import AppKit import ImageIO import ImagePlayground import SwiftUI import UniformTypeIdentifiers struct StudioImagePreview: Sendable { let name: String let width: Int let height: Int let png: Data init(data: Data, name: String, maxDimension: Int = 2048) throws { guard let source = CGImageSourceCreateWithData(data as CFData, nil), let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], let width = properties[kCGImagePropertyPixelWidth] as? Int, let height = properties[kCGImagePropertyPixelHeight] as? Int, let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: max(1, maxDimension) ] as CFDictionary) else { throw StudioError("This file could not be opened as an image.") } let output = NSMutableData() guard let destination = CGImageDestinationCreateWithData(output, UTType.png.identifier as CFString, 1, nil) else { throw StudioError("Could not create the PNG preview.") } CGImageDestinationAddImage(destination, image, nil) guard CGImageDestinationFinalize(destination) else { throw StudioError("Could not encode the PNG preview.") } self.name = name self.width = width self.height = height self.png = output as Data } } struct CreativeWorkspace: View { private enum Area: String, CaseIterable, Identifiable { case training = "Training" case images = "Images" var id: Self { self } var icon: String { self == .training ? "cpu" : "photo" } } @State private var area: Area = .training @AppStorage("mlxRegisteredPaths") private var registered = Data() var body: some View { HStack(spacing: 0) { VStack(alignment: .leading, spacing: 5) { ForEach(Area.allCases) { item in Button { area = item } label: { Label(item.rawValue, systemImage: item.icon) .font(.headline) .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 12) .padding(.vertical, 9) .background(area == item ? Color.accentColor.opacity(0.15) : .clear, in: RoundedRectangle(cornerRadius: 8)) } .buttonStyle(.plain) .accessibilityAddTraits(area == item ? .isSelected : []) } Spacer() } .padding(12) .frame(width: 158) .background(.regularMaterial) Divider() ZStack { ModelWorkshopView(workshop: ModelWorkshop(base: nil), embedded: true, register: register) .opacity(area == .training ? 1 : 0) .allowsHitTesting(area == .training) .accessibilityHidden(area != .training) ImageWorkspace() .opacity(area == .images ? 1 : 0) .allowsHitTesting(area == .images) .accessibilityHidden(area != .images) } } .frame(minWidth: 835, minHeight: 560) } private func register(_ url: URL) { let paths = (try? JSONDecoder().decode([String].self, from: registered)) ?? [] let updated = Set(paths + [url.resolvingSymlinksInPath().path]).sorted() if let data = try? JSONEncoder().encode(updated) { registered = data } } } private struct ImageWorkspace: View { @State private var prompt = "" @State private var preview: StudioImagePreview? @State private var importing = false @State private var status = "" var body: some View { HStack(spacing: 0) { VStack(alignment: .leading, spacing: 14) { Text("Images").font(.largeTitle.weight(.semibold)) Text("Image description").font(.headline) TextField("Describe the image to generate", text: $prompt, axis: .vertical) .textFieldStyle(.roundedBorder) .lineLimit(3...6) if #available(macOS 15.1, *) { PlaygroundAction(prompt: prompt) { receive($0) } } else { Label("Image generation requires Image Playground.", systemImage: "info.circle") .font(.caption).foregroundStyle(.secondary) } Divider() Button("Open Image…", systemImage: "folder") { importing = true } Button("Export Preview PNG…", systemImage: "square.and.arrow.up", action: export) .disabled(preview == nil) if !status.isEmpty { Text(status).font(.callout).foregroundStyle(.secondary).textSelection(.enabled) } Spacer() } .padding(24) .frame(width: 280) Divider() VStack(alignment: .leading, spacing: 12) { HStack { Text("Preview").font(.headline) Spacer() if let preview { Text("\(preview.width) × \(preview.height) px") .monospacedDigit().foregroundStyle(.secondary) } } if let preview, let image = NSImage(data: preview.png) { Image(nsImage: image).resizable().scaledToFit() .frame(maxWidth: .infinity, maxHeight: .infinity) .accessibilityLabel(preview.name) } else { ContentUnavailableView("No image selected", systemImage: "photo.on.rectangle", description: Text("Generate an image or open one to preview.")) .frame(maxWidth: .infinity, maxHeight: .infinity) } } .padding(24) .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(nsColor: .controlBackgroundColor)) } .fileImporter(isPresented: $importing, allowedContentTypes: [.image]) { switch $0 { case .success(let url): receive(url) case .failure(let error): status = error.localizedDescription } } } private func receive(_ url: URL) { let access = url.startAccessingSecurityScopedResource() defer { if access { url.stopAccessingSecurityScopedResource() } } do { preview = try StudioImagePreview(data: Data(contentsOf: url, options: .mappedIfSafe), name: url.deletingPathExtension().lastPathComponent) status = "" } catch { status = error.localizedDescription } } private func export() { guard let preview else { return } let panel = NSSavePanel() panel.allowedContentTypes = [.png] panel.nameFieldStringValue = preview.name + "-preview.png" guard panel.runModal() == .OK, let url = panel.url else { return } do { try preview.png.write(to: url, options: .atomic) status = "Saved \(url.lastPathComponent)" } catch { status = error.localizedDescription } } } @available(macOS 15.1, *) private struct PlaygroundAction: View { let prompt: String let completion: (URL) -> Void @Environment(\.supportsImagePlayground) private var supported @State private var showing = false var body: some View { let description = prompt.trimmingCharacters(in: .whitespacesAndNewlines) if supported { Button("Generate Image", systemImage: "sparkles") { showing = true } .buttonStyle(.borderedProminent) .disabled(description.isEmpty) .imagePlaygroundSheet(isPresented: $showing, concepts: [.text(description)], onCompletion: completion) } else { Label("Image Playground is unavailable on this Mac.", systemImage: "info.circle") .font(.caption).foregroundStyle(.secondary) } } }