Sources/FaceMaker/FaceViewer.swift

Swift source for Making faces, 311 lines. Raw file

import AppKit
import SwiftUI
import UniformTypeIdentifiers

/// A face opened for full-size viewing, with the full recipe needed to
/// re-render it: seed + model + every setting.
struct ViewerFace: Identifiable, Hashable, Codable {
    let id: Int
    let pngPath: String
    let seed: UInt64
    /// The exact state that produced this face (for "Use Image").
    let modelID: String
    let sliderValues: [String: Double]
    let enabledGroups: [String: Bool]
    /// The exact 512-d latent (z) that produced this face.
    let vector: [Float]
    /// Labelled recipe rows (Model, changed sliders, enabled groups) for
    /// display.
    let details: [Detail]

    struct Detail: Hashable, Codable {
        let label: String
        let value: String
    }
}

/// Non-modal window: the full face image with wheel + pinch zoom, drag pan,
/// and Reset View / Save As… buttons.
struct FaceViewerView: View {
    let face: ViewerFace
    @Environment(AppModel.self) private var model
    @Environment(\.openWindow) private var openWindow
    @Environment(\.colorScheme) private var colorScheme
    @State private var zoom: CGFloat = 1
    @State private var offset: CGSize = .zero
    @State private var resetToken = 0

    /// White canvas in light mode, black in dark mode (matches the main
    /// window's tile area).
    private var canvasColor: Color { colorScheme == .dark ? .black : .white }

    private var image: NSImage? { NSImage(contentsOfFile: face.pngPath) }

    var body: some View {
        VStack(spacing: 0) {
            // Native split: image on top, scrollable recipe details below.
            VSplitView {
                imageArea
                    .frame(minHeight: 180)
                detailsArea
                    .frame(minHeight: 80)
            }
            .persistSplitPosition("facemaker.viewerSplit")

            Divider()
            toolbar
        }
        .frame(minWidth: 420, minHeight: 480)
        .navigationTitle("Seed \(String(face.seed))")
    }

    @ViewBuilder
    private var imageArea: some View {
        if let image {
            ZoomableImageView(
                image: image, zoom: $zoom, offset: $offset,
                resetToken: resetToken, canvas: canvasColor)
        } else {
            ContentUnavailableView("Image unavailable", systemImage: "photo")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(canvasColor)
        }
    }

    /// Everything needed to re-render this face: seed + model + settings.
    private var detailsArea: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 6) {
                detailRow("Seed", String(face.seed))
                ForEach(face.details, id: \.self) { detail in
                    detailRow(detail.label, detail.value)
                }
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(12)
        }
        // Standard window background, like the main window's controls.
        .background(Color(nsColor: .windowBackgroundColor))
    }

    private func detailRow(_ label: String, _ value: String) -> some View {
        HStack(alignment: .firstTextBaseline, spacing: 8) {
            Text(label)
                .font(.callout)
                .foregroundStyle(.secondary)
                .frame(width: 110, alignment: .leading)
            Text(value)
                .font(.callout.monospacedDigit())
            Spacer(minLength: 0)
        }
        .textSelection(.enabled)
    }

    private var toolbar: some View {
        HStack(spacing: 10) {
            Button("Use Image") {
                model.applyRecipe(
                    modelID: face.modelID, seed: face.seed,
                    sliders: face.sliderValues, groups: face.enabledGroups)
                openWindow(id: "main")
            }
            .help("Load this face's model, seed, and settings into the main window")
            if !face.vector.isEmpty {
                Button("View Vector") {
                    openWindow(id: "vector-viewer", value: VectorPayload(
                        id: face.id, title: "Face \(face.id) vector", values: face.vector))
                }
                .help("Show the 512-d latent that produced this face")
            }
            Text("\(Int(zoom * 100))%")
                .font(.callout.monospacedDigit())
                .foregroundStyle(.secondary)
            Spacer()
            Button("Copy Seed") {
                NSPasteboard.general.clearContents()
                NSPasteboard.general.setString(String(face.seed), forType: .string)
            }
            Button("Reset View") {
                zoom = 1
                offset = .zero
                resetToken += 1
            }
            Button("Save As…") {
                if let image { FaceExport.saveAs(image: image, suggestedName: "Face-\(face.seed)") }
            }
            .keyboardShortcut("s")
        }
        .padding(.horizontal, 14)
        .padding(.vertical, 8)
        .frame(maxWidth: .infinity)
        .background(.bar)
    }
}

/// AppKit surface handling scroll-wheel zoom, trackpad pinch (`magnify`), and
/// drag-to-pan. SwiftUI gestures don't cover wheel + pinch cleanly, so this
/// owns the interaction and reports state back through bindings.
private struct ZoomableImageView: NSViewRepresentable {
    let image: NSImage
    @Binding var zoom: CGFloat
    @Binding var offset: CGSize
    let resetToken: Int
    let canvas: Color

    func makeNSView(context: Context) -> ZoomImageNSView {
        let view = ZoomImageNSView()
        view.image = image
        view.canvasColor = NSColor(canvas)
        view.onStateChange = { z, o in
            // Avoid feeding SwiftUI updates back into a layout pass.
            DispatchQueue.main.async {
                zoom = z
                offset = o
            }
        }
        return view
    }

    func updateNSView(_ view: ZoomImageNSView, context: Context) {
        if view.image !== image { view.image = image }
        let nsCanvas = NSColor(canvas)
        if view.canvasColor != nsCanvas { view.canvasColor = nsCanvas }
        if view.lastResetToken != resetToken {
            view.lastResetToken = resetToken
            view.resetView()
        }
    }
}

final class ZoomImageNSView: NSView {
    var image: NSImage? { didSet { needsDisplay = true } }
    var canvasColor: NSColor = .windowBackgroundColor {
        didSet {
            layer?.backgroundColor = canvasColor.cgColor
            needsDisplay = true
        }
    }
    var onStateChange: ((CGFloat, CGSize) -> Void)?
    var lastResetToken = 0

    private var scale: CGFloat = 1
    private var translation = CGSize.zero
    private let minScale: CGFloat = 0.1
    private let maxScale: CGFloat = 20

    override var isFlipped: Bool { false }
    override var acceptsFirstResponder: Bool { true }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        wantsLayer = true
        layer?.backgroundColor = canvasColor.cgColor
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }

    func resetView() {
        scale = 1
        translation = .zero
        needsDisplay = true
        report()
    }

    // MARK: Interaction

    override func scrollWheel(with event: NSEvent) {
        // Pixel-precise trackpad scroll and notched mouse wheel both zoom
        // about the cursor.
        let factor = 1 + event.scrollingDeltaY * (event.hasPreciseScrollingDeltas ? 0.005 : 0.03)
        zoom(by: factor, around: convert(event.locationInWindow, from: nil))
    }

    override func magnify(with event: NSEvent) {
        zoom(by: 1 + event.magnification, around: convert(event.locationInWindow, from: nil))
    }

    override func mouseDragged(with event: NSEvent) {
        translation.width += event.deltaX
        translation.height -= event.deltaY
        needsDisplay = true
        report()
    }

    private func zoom(by factor: CGFloat, around point: CGPoint) {
        let newScale = min(max(scale * factor, minScale), maxScale)
        let applied = newScale / scale
        // Keep the point under the cursor fixed while scaling.
        let center = CGPoint(x: bounds.midX + translation.width,
                             y: bounds.midY + translation.height)
        translation.width += (center.x - point.x) * (applied - 1) * -1
        translation.height += (center.y - point.y) * (applied - 1) * -1
        scale = newScale
        needsDisplay = true
        report()
    }

    private func report() { onStateChange?(scale, translation) }

    // MARK: Drawing

    override func draw(_ dirtyRect: NSRect) {
        canvasColor.setFill()
        dirtyRect.fill()
        guard let image else { return }
        let imageSize = image.size
        guard imageSize.width > 0, imageSize.height > 0 else { return }

        // Aspect-fit at scale 1, then apply zoom + pan about the center.
        let fit = min(bounds.width / imageSize.width, bounds.height / imageSize.height)
        let drawScale = fit * scale
        let drawSize = CGSize(width: imageSize.width * drawScale,
                              height: imageSize.height * drawScale)
        let origin = CGPoint(
            x: bounds.midX - drawSize.width / 2 + translation.width,
            y: bounds.midY - drawSize.height / 2 + translation.height)
        image.draw(in: CGRect(origin: origin, size: drawSize),
                   from: .zero, operation: .sourceOver, fraction: 1)
    }
}

/// Shared Save As… panel writing a PNG.
enum FaceExport {
    @MainActor
    static func saveAs(image: NSImage, suggestedName: String) {
        let panel = NSSavePanel()
        panel.allowedContentTypes = [.png]
        panel.canCreateDirectories = true
        panel.nameFieldStringValue = "\(suggestedName).png"
        guard panel.runModal() == .OK, let url = panel.url else { return }
        guard
            let tiff = image.tiffRepresentation,
            let rep = NSBitmapImageRep(data: tiff),
            let png = rep.representation(using: .png, properties: [:])
        else { return }
        try? png.write(to: url)
    }

    @MainActor
    static func saveAs(pngData: Data, suggestedName: String) {
        let panel = NSSavePanel()
        panel.allowedContentTypes = [.png]
        panel.canCreateDirectories = true
        panel.nameFieldStringValue = "\(suggestedName).png"
        guard panel.runModal() == .OK, let url = panel.url else { return }
        try? pngData.write(to: url)
    }

    /// Saves a latent as JSON, `{"model": ..., "data": [512 or 9216 numbers]}`,
    /// the same format Import… reads back.
    @MainActor
    static func saveVector(_ values: [Float], model: String, suggestedName: String) {
        let panel = NSSavePanel()
        panel.allowedContentTypes = [.json]
        panel.canCreateDirectories = true
        panel.nameFieldStringValue = "\(suggestedName).json"
        guard panel.runModal() == .OK, let url = panel.url else { return }
        let object: [String: Any] = ["model": model, "data": values.map { Double($0) }]
        guard let data = try? JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) else { return }
        try? data.write(to: url)
    }
}