SPB Git

Repository Public License

VectorStudioView.swift 18.3 KB 313 lines swift

1// ORIX Convert — App/Sources/Features/VectorStudio/VectorStudioView.swift2// Description: Vector Studio: a raster image traced live into vector shapes. The drawing is painted from the3//              engine's CGPath layers, so it stays sharp at any zoom; controls are built from the engine's option4//              descriptors; every statistic is measured by the engine.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import EngineVector8import SwiftUI910struct VectorStudioView: View {11    @Environment(AppModel.self) private var model1213    var body: some View {14        let studio = model.vectorStudio15        VStack(spacing: 0) {16            HeaderBar(title: L("Vector Studio"), subtitle: subtitle(studio)) {17                if studio.raster != nil {18                    SegmentedPicker(selection: Binding(get: { studio.viewMode }, set: { studio.viewMode = $0 }),19                                    options: VectorViewMode.allCases.map { ($0, $0.title, 0) })20                    ZoomControls(viewport: studio.viewport)21                }22                Button { studio.choose() } label: { Label(studio.source == nil ? L("Choose Image…") : L("Change Image…"), systemImage: "photo.badge.plus") }23                    .buttonStyle(SecondaryButtonStyle())24            }25            if studio.source == nil {26                EmptyState(symbol: "pencil.and.outline", title: L("Turn pixels into shapes"),27                           message: L("Drop an image here or choose one. Logos, icons, line art and flat illustrations trace well; photographs become posterised drawings. The preview is the real result, drawn from the traced paths."),28                           actionTitle: L("Choose Image…")) { studio.choose() }29            } else if let error = studio.loadError {30                EmptyState(symbol: "exclamationmark.triangle", title: L("This image cannot be traced"), message: error, actionTitle: L("Choose Image…")) { studio.choose() }31            } else {32                GeometryReader { geo in33                    let panelWidth: CGFloat = geo.size.width < 980 ? 300 : ORIX.Metric.sidePanelWidth34                    HStack(spacing: 0) {35                        VStack(spacing: 0) {36                            if let warning = studio.photographicWarning {37                                Banner(kind: .caution, text: L("This looks like a photograph"), detail: LE(warning.message))38                                    .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.s)39                                    .background(ORIX.Palette.canvas)40                            }41                            VectorStage(studio: studio)42                            VectorStatsBar(studio: studio, narrow: geo.size.width - panelWidth < 640)43                        }44                        ORIX.Palette.hairline.frame(width: 1)45                        VectorPanel(studio: studio).frame(width: panelWidth)46                    }47                }48            }49        }50    }5152    private func subtitle(_ studio: VectorStudioModel) -> String? {53        guard let source = studio.source else { return L("Raster to SVG, traced live") }54        guard let raster = studio.raster else { return source.lastPathComponent }55        return "\(source.lastPathComponent) · \(Fmt.count(raster.sourceWidth)) × \(Fmt.count(raster.sourceHeight)) px"56    }57}5859private struct VectorStage: View {60    let studio: VectorStudioModel6162    var body: some View {63        ZStack {64            ORIX.Palette.surfaceSunken65            if let raster = studio.raster {66                let original = CanvasLayer.image(preview: raster.image, detail: nil)67                let drawing: CanvasLayer? = studio.result == nil ? nil : (studio.viewMode == .outline68                    ? .outline(layers: studio.layers, nodes: studio.showNodes ? studio.nodes : nil)69                    : .vector(layers: studio.layers, background: studio.result?.document.background.map { CGColor(srgbRed: CGFloat($0.red) / 255, green: CGFloat($0.green) / 255, blue: CGFloat($0.blue) / 255, alpha: 1) }))70                let mode: CanvasMode = switch studio.viewMode {71                case .original: .original72                case .vector, .outline: .result73                case .split: .split74                }75                CompareCanvas(left: original, right: drawing, leftLabel: L("Original"), rightLabel: studio.viewMode == .outline ? L("Outline") : L("Vector"), mode: mode,76                              imageSize: studio.imageSize, viewport: studio.viewport)77                    .accessibilityElement(children: .ignore)78                    .accessibilityLabel(L("Traced drawing compared with the original image"))79                    .accessibilityValue(canvasValue)80                    .accessibilityAdjustableAction { direction in81                        guard studio.viewMode == .split else { return }82                        studio.viewport.split = min(1, max(0, studio.viewport.split + (direction == .increment ? 0.05 : -0.05)))83                    }84                if studio.viewMode == .outline {85                    VStack {86                        Spacer()87                        Toggle(isOn: Binding(get: { studio.showNodes }, set: { studio.showNodes = $0 })) { Text(L("Show nodes")).font(.caption.weight(.medium)) }88                            .toggleStyle(.checkbox).controlSize(.small)89                            .padding(.horizontal, 12).padding(.vertical, 6)90                            .background(ORIX.Palette.surfaceRaised, in: Capsule())91                            .overlay(Capsule().strokeBorder(ORIX.Palette.hairlineStrong, lineWidth: 1))92                            .padding(.bottom, ORIX.Space.m)93                    }94                }95                if let error = studio.traceError {96                    VStack { Spacer(); Banner(kind: .danger, text: L("Tracing failed"), detail: error).frame(maxWidth: 520).padding(ORIX.Space.l) }97                }98            } else {99                VStack(spacing: ORIX.Space.m) {100                    ORIXProgressRing(fraction: nil, size: 28, lineWidth: 3, label: L("Decoding"))101                    Text(L("Reading the image…")).font(.callout).foregroundStyle(ORIX.Palette.textSecondary)102                }103            }104        }105        .frame(maxWidth: .infinity, maxHeight: .infinity)106    }107108    private var canvasValue: String {109        var parts = [studio.viewMode.title, L("zoom %@", studio.viewport.percentText)]110        if studio.viewMode == .split { parts.append(L("split at %@", Fmt.percent(studio.viewport.split))) }111        if let statistics = studio.result?.statistics { parts.append(L("%lld paths, %lld nodes", statistics.pathCount, statistics.nodeCount)) }112        return parts.joined(separator: ", ")113    }114}115116/// Measured statistics of the visible drawing, under the canvas.117private struct VectorStatsBar: View {118    let studio: VectorStudioModel119    let narrow: Bool120121    var body: some View {122        HStack(spacing: narrow ? ORIX.Space.m : ORIX.Space.xl) {123            if let statistics = studio.result?.statistics {124                stat(L("Paths"), Fmt.count(statistics.pathCount))125                stat(L("Nodes"), Fmt.count(statistics.nodeCount))126                stat(L("SVG"), Fmt.bytes(Int64(statistics.svgByteCount)) + (Fmt.change(before: studio.sourceBytes, after: Int64(statistics.svgByteCount)).map { "  \($0)" } ?? ""))127                if !narrow { stat(L("Traced in"), Fmt.duration(statistics.totalSeconds)) }128            } else {129                Text(L("Tracing…")).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)130            }131            Spacer(minLength: ORIX.Space.s)132            passState133        }134        .padding(.horizontal, ORIX.Space.l)135        .frame(height: 46)136        .background(ORIX.Palette.canvas)137        .overlay(alignment: .top) { ORIX.Palette.hairline.frame(height: 1) }138    }139140    private func stat(_ label: String, _ value: String) -> some View {141        VStack(alignment: .leading, spacing: 0) {142            Text(label.uppercased(with: .current)).font(.system(size: 9, weight: .semibold)).kerning(0.4).foregroundStyle(ORIX.Palette.textTertiary)143            Text(value).font(.callout.weight(.medium).monospacedDigit()).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)144        }145        .fixedSize()146        .accessibilityElement(children: .ignore)147        .accessibilityLabel(label)148        .accessibilityValue(value)149    }150151    @ViewBuilder private var passState: some View {152        if studio.isTracing {153            HStack(spacing: 6) {154                ORIXProgressRing(fraction: studio.traceFraction, size: 14, lineWidth: 2, label: L("Tracing"))155                Text(studio.pass == .preview ? L("Fast preview · refining…") : L("Tracing…")).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)156            }157        } else if studio.pass == .full {158            Pill(text: L("Full quality"), symbol: "checkmark.seal", color: ORIX.Palette.success)159        } else if studio.pass == .preview {160            Pill(text: L("Fast preview"), symbol: "hare", color: ORIX.Palette.caution)161        }162    }163}164165// MARK: - Side panel166167private struct VectorPanel: View {168    let studio: VectorStudioModel169170    var body: some View {171        VStack(spacing: 0) {172            ScrollView {173                VStack(alignment: .leading, spacing: ORIX.Space.xl) {174                    modes175                    if !studio.palette.isEmpty { paletteStrip }176                    OptionsForm(descriptors: studio.formDescriptors, values: studio.optionValues) { key, value in studio.setOption(key, value) }177                    measurements178                    guidance179                }180                .padding(ORIX.Space.l)181            }182            ORIX.Palette.hairline.frame(height: 1)183            exportBar184        }185        .background(ORIX.Palette.surface)186        .accessibilityElement(children: .contain)187        .accessibilityLabel(L("Tracing settings"))188    }189190    private var modes: some View {191        VStack(alignment: .leading, spacing: ORIX.Space.s) {192            SectionLabel(L("Mode"))193            FlowLayout(spacing: 6, lineSpacing: 6) {194                ForEach(VectorMode.allCases, id: \.self) { mode in195                    let selected = studio.mode == mode196                    Button { studio.apply(mode: mode) } label: {197                        Text(LE(mode.displayName)).font(.callout.weight(selected ? .semibold : .regular)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)198                            .padding(.horizontal, 10).padding(.vertical, 5)199                            .background(selected ? ORIX.Palette.accentSoft : ORIX.Palette.canvas, in: Capsule())200                            .overlay(Capsule().strokeBorder(selected ? AnyShapeStyle(ORIX.Palette.transformation) : AnyShapeStyle(ORIX.Palette.hairlineStrong), lineWidth: selected ? 1.5 : 1))201                            .contentShape(Capsule())202                    }203                    .buttonStyle(.plain)204                    .accessibilityLabel(L("%@ mode", LE(mode.displayName)))205                    .accessibilityAddTraits(selected ? [.isSelected] : [])206                }207            }208            Text(L("A mode fills the controls below with the engine's preset; adjust them afterwards.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)209                .fixedSize(horizontal: false, vertical: true)210        }211    }212213    private var paletteStrip: some View {214        VStack(alignment: .leading, spacing: ORIX.Space.s) {215            HStack {216                SectionLabel(L("Traced colours"))217                Spacer()218                Text(Fmt.count(studio.palette.count)).font(.orixCaptionNumber).foregroundStyle(ORIX.Palette.textTertiary)219            }220            FlowLayout(spacing: 4, lineSpacing: 4) {221                ForEach(studio.palette.prefix(64)) { entry in222                    RoundedRectangle(cornerRadius: 5, style: .continuous)223                        .fill(Color(.sRGB, red: Double(entry.color.red) / 255, green: Double(entry.color.green) / 255, blue: Double(entry.color.blue) / 255, opacity: 1))224                        .frame(width: 22, height: 22)225                        .overlay(RoundedRectangle(cornerRadius: 5, style: .continuous).strokeBorder(ORIX.Palette.hairlineStrong, lineWidth: 1))226                        .help("\(entry.color.hex) · " + (entry.shapes == 1 ? L("1 shape") : L("%lld shapes", entry.shapes)))227                        .accessibilityLabel(L("Colour %@", entry.color.hex))228                        .accessibilityValue(entry.shapes == 1 ? L("1 shape") : L("%lld shapes", entry.shapes))229                }230            }231            Text(L("The colours of the drawing. Change the colour count to merge or split them.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)232                .fixedSize(horizontal: false, vertical: true)233        }234    }235236    @ViewBuilder private var measurements: some View {237        if let result = studio.result {238            let statistics = result.statistics239            VStack(alignment: .leading, spacing: ORIX.Space.s) {240                SectionLabel(L("Measured by the tracer"))241                KeyValueRow(key: L("Paths"), value: Fmt.count(statistics.pathCount))242                KeyValueRow(key: L("Closed outlines"), value: Fmt.count(statistics.subpathCount))243                KeyValueRow(key: L("Nodes"), value: "\(Fmt.count(statistics.nodeCount)) (\(L("%lld lines, %lld curves", statistics.lineSegmentCount, statistics.curveSegmentCount)))")244                KeyValueRow(key: L("Traced at"), value: "\(Fmt.count(statistics.tracedWidth)) × \(Fmt.count(statistics.tracedHeight)) px")245                KeyValueRow(key: L("SVG size"), value: Fmt.bytes(Int64(statistics.svgByteCount)))246                KeyValueRow(key: L("Source size"), value: Fmt.bytes(studio.sourceBytes))247                KeyValueRow(key: L("Tracing time"), value: Fmt.duration(statistics.totalSeconds))248                if let threshold = statistics.thresholdUsed { KeyValueRow(key: L("Threshold used"), value: Fmt.percent(threshold)) }249                if let similarity = result.similarity {250                    SectionLabel(L("Similarity to the source")).padding(.top, ORIX.Space.s)251                    KeyValueRow(key: L("Mean colour difference (OKLab × 100)"), value: similarity.meanDeltaE.formatted(.number.precision(.fractionLength(2))))252                    KeyValueRow(key: L("Mean absolute error (0–255)"), value: similarity.meanAbsoluteError.formatted(.number.precision(.fractionLength(2))))253                    KeyValueRow(key: L("Pixels within 2.5 of the source"), value: similarity.matchingPixelFraction.formatted(.percent.precision(.fractionLength(1))))254                    KeyValueRow(key: L("Edge recall"), value: similarity.edgeRecall.formatted(.percent.precision(.fractionLength(1))))255                    KeyValueRow(key: L("Edge precision"), value: similarity.edgePrecision.formatted(.percent.precision(.fractionLength(1))))256                    Text(L("Measured by rasterising the drawing at %@ pixels and comparing it with the source.", "\(Fmt.count(similarity.width)) × \(Fmt.count(similarity.height))"))257                        .font(.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)258                } else if studio.pass == .preview {259                    Text(L("Similarity is measured on the full-quality pass.")).font(.caption).foregroundStyle(ORIX.Palette.textTertiary)260                }261            }262        }263    }264265    @ViewBuilder private var guidance: some View {266        let warnings = (studio.result?.warnings ?? []).filter { $0.code != "photographic-content" }267        if !warnings.isEmpty {268            VStack(alignment: .leading, spacing: ORIX.Space.s) {269                SectionLabel(L("What the tracer reports"))270                ForEach(warnings, id: \.self) { warning in Banner(kind: warning.isDataLoss ? .danger : .info, text: LE(warning.message)) }271            }272        }273    }274275    private var exportBar: some View {276        VStack(alignment: .leading, spacing: ORIX.Space.s) {277            if let notice = studio.notice {278                HStack(spacing: 6) {279                    Text(notice).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2)280                    Spacer(minLength: 0)281                    if let url = studio.noticeURL { IconButton(symbol: "magnifyingglass", label: L("Reveal in Finder")) { FileActions.reveal([url]) } }282                }283            }284            HStack(spacing: ORIX.Space.s) {285                Button { studio.exportWithPanel(.svg) } label: { Text(L("Export SVG…")).frame(maxWidth: .infinity) }286                    .buttonStyle(PrimaryButtonStyle()).disabled(studio.raster == nil || studio.isExporting)287                Menu {288                    Button(L("Export Vector PDF…")) { studio.exportWithPanel(.pdf) }289                    Button(L("Copy SVG")) { studio.copySVG() }.disabled(!studio.hasFullResult)290                    Divider()291                    if !studio.batch.isEmpty {292                        Button(L("Apply to the %lld Other Dropped Files", studio.batch.count)) { studio.applyToFiles(studio.batch) }293                    }294                    Button(L("Apply to Files…")) { studio.chooseBatch() }295                } label: { Image(systemName: "ellipsis").font(.system(size: 13, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary).frame(width: 30, height: 30) }296                .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()297                .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))298                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairlineStrong, lineWidth: 1))299                .accessibilityLabel(L("More export actions"))300                Image(systemName: "square.and.arrow.up.on.square").font(.system(size: 13)).foregroundStyle(studio.hasFullResult ? ORIX.Palette.accent : ORIX.Palette.textTertiary)301                    .frame(width: 30, height: 30)302                    .background(ORIX.Palette.accentSoft, in: RoundedRectangle(cornerRadius: ORIX.Radius.s, style: .continuous))303                    .onDrag { studio.dragProvider() }304                    .help(L("Drag the SVG to the Finder or another app"))305                    .accessibilityLabel(L("Traced SVG file"))306                    .accessibilityHint(L("Drag to the Finder or another app"))307            }308            if studio.isExporting { ORIXProgressBar(fraction: nil, height: 3, label: L("Exporting")) }309        }310        .padding(ORIX.Space.m)311    }312}313
Files main
Menu

Theme