Files
ai_studio/Sources/CreativeWorkspace.swift
2026-11-19 09:18:49 +00:00

253 lines
11 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import AppKit
import CoreImage
import Metal
import ImageIO
import ImagePlayground
import SwiftUI
import UniformTypeIdentifiers
struct StudioImagePreview: Sendable {
let name: String
let width: Int
let height: Int
let png: Data
private static let renderer: CIContext = {
if let device = MTLCreateSystemDefaultDevice() { return CIContext(mtlDevice: device) }
return CIContext(options: [.useSoftwareRenderer: true])
}()
func adjusted(exposure: Double) throws -> Self {
guard exposure.isFinite, let input = CIImage(data: png) else { throw StudioError("Could not read the preview.") }
let output = input.applyingFilter("CIExposureAdjust", parameters: [kCIInputEVKey: min(3, max(-3, exposure))])
guard let image = Self.renderer.createCGImage(output, from: input.extent) else {
throw StudioError("Could not render the adjusted preview.")
}
let encoded = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(encoded, 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.") }
return Self(name: name, width: width, height: height, png: encoded as Data)
}
private init(name: String, width: Int, height: Int, png: Data) {
self.name = name
self.width = width
self.height = height
self.png = png
}
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 original: StudioImagePreview?
@State private var exposureStep = 0
@State private var adjustment: Task<Void, Never>?
@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 }
Stepper("Exposure \(Double(exposureStep) / 2, specifier: "%+.1f") EV", value: $exposureStep, in: -6...6)
.disabled(original == nil)
.onChange(of: exposureStep) { applyExposure() }
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 {
let image = try StudioImagePreview(data: Data(contentsOf: url, options: .mappedIfSafe),
name: url.deletingPathExtension().lastPathComponent)
adjustment?.cancel()
exposureStep = 0
original = image
preview = image
status = ""
} catch { status = error.localizedDescription }
}
private func applyExposure() {
adjustment?.cancel()
guard let original else { return }
let exposure = Double(exposureStep) / 2
if exposure == 0 { preview = original; return }
adjustment = Task {
do {
let image = try await Task.detached(priority: .userInitiated) { try original.adjusted(exposure: exposure) }.value
guard !Task.isCancelled else { return }
preview = image
} catch {
if !Task.isCancelled { 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)
}
}
}