Repository Public License
1// ORIX Convert — App/Sources/Features/Studio/StudioSupport.swift2// Description: What the studios share: the list of real destinations for a format (or for the whole registry), a3// destination picker that is not tied to the Convert workspace, the private queue that runs trial4// conversions and direct exports through the normal engine path, and bounded picture loading.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import AppKit7import ConvertCore8import EngineImage9import EngineMedia10import EnginePDF11import EngineVector12import SwiftUI1314// MARK: - Destinations1516struct TargetEntry: Identifiable, Hashable, Sendable {17 let destination: FormatID18 let operation: String?19 let title: String20 let fidelity: Fidelity21 let experimental: Bool22 let chainedVia: [FormatID]23 var id: String { destination.rawValue + (operation.map { "#" + $0 } ?? "") }24}2526enum TargetCatalog {27 /// Destinations a single file of `source` can really reach: named operations first, then formats (direct, then28 /// two-step plans the planner finds). Multi-source-only operations (merge…) are left out when asked.29 static func entries(for source: FormatID, manager: ConversionJobManager, singleFileOnly: Bool = true) -> [TargetEntry] {30 let capabilities = manager.resolver.capabilities(for: source)31 var list: [TargetEntry] = []32 for target in capabilities.operations where !(singleFileOnly && target.best.acceptsMultipleSources) {33 list.append(TargetEntry(destination: target.destination, operation: target.operation, title: LE(target.title), fidelity: target.best.fidelity,34 experimental: target.best.status == .experimental, chainedVia: []))35 }36 for target in capabilities.targets {37 list.append(TargetEntry(destination: target.destination, operation: nil, title: target.destination.displayName, fidelity: target.best.fidelity,38 experimental: target.best.status == .experimental, chainedVia: []))39 }40 for destination in capabilities.chainedDestinations {41 guard let plan = try? manager.planner.plan(from: source, to: destination) else { continue }42 list.append(TargetEntry(destination: destination, operation: nil, title: destination.displayName, fidelity: plan.fidelity,43 experimental: plan.status == .experimental, chainedVia: plan.intermediates))44 }45 return list46 }4748 /// Every destination and single-file operation that exists in the registry, whatever the source (workflow nodes49 /// and watch rules are validated afterwards against what can actually reach them).50 static func everyEntry(registry: FormatRegistry) -> [TargetEntry] {51 var best: [String: ConversionPath] = [:]52 var order: [String] = []53 for path in registry.paths where path.source != .folder && path.destination != .folder && !(path.operation != nil && path.acceptsMultipleSources) {54 let key = path.destination.rawValue + (path.operation.map { "#" + $0 } ?? "")55 if let current = best[key] {56 if ConversionCapabilityResolver.prefers(path, over: current) { best[key] = path }57 } else {58 best[key] = path59 order.append(key)60 }61 }62 return order.compactMap { best[$0] }.map { path in63 TargetEntry(destination: path.destination, operation: path.operation, title: path.title.map { LE($0) } ?? path.destination.displayName,64 fidelity: path.fidelity, experimental: path.status == .experimental, chainedVia: [])65 }66 .sorted { ($0.operation == nil ? 1 : 0, $0.title.lowercased()) < ($1.operation == nil ? 1 : 0, $1.title.lowercased()) }67 }6869 /// The real plan behind a choice, or `nil` when none exists.70 static func choice(from source: FormatID, to destination: FormatID, operation: String?, manager: ConversionJobManager) -> TargetChoice? {71 guard let plan = try? manager.planner.plan(from: source, to: destination, operation: operation) else { return nil }72 return TargetChoice(destination: destination, operation: operation, plan: plan)73 }7475 static func descriptors(for choice: TargetChoice, registry: FormatRegistry) -> [OptionDescriptor] {76 choice.plan.steps.last.flatMap { step in registry.engine(id: step.engine)?.options(for: step) } ?? []77 }7879 /// Engines able to produce `destination` (with `operation`), each with the options it declares. A workflow node80 /// does not know its input format in advance, so its form shows the options of one of these.81 static func optionSets(to destination: FormatID, operation: String?, registry: FormatRegistry) -> [(engine: String, name: String, descriptors: [OptionDescriptor])] {82 var seen = Set<String>()83 var sets: [(String, String, [OptionDescriptor])] = []84 for path in registry.paths(to: destination, operation: .some(operation)) where path.source != .folder {85 guard seen.insert(path.engine).inserted, let engine = registry.engine(id: path.engine) else { continue }86 sets.append((path.engine, LE(engine.displayName), engine.options(for: path)))87 }88 return sets.map { (engine: $0.0, name: $0.1, descriptors: $0.2) }89 }90}9192/// Searchable list of destinations: operations, then formats by category.93struct TargetPicker: View {94 let entries: [TargetEntry]95 let selectedID: String?96 let onSelect: (TargetEntry) -> Void97 @State private var search = ""98 @FocusState private var searchFocused: Bool99100 private func matches(_ entry: TargetEntry) -> Bool {101 let needle = search.trimmingCharacters(in: .whitespaces).lowercased()102 if needle.isEmpty { return true }103 let extensions = entry.destination.catalogEntry?.extensions ?? []104 return entry.title.lowercased().contains(needle) || entry.destination.rawValue.contains(needle) || extensions.contains { $0.contains(needle) }105 }106107 var body: some View {108 let shown = entries.filter(matches)109 let operations = shown.filter { $0.operation != nil }110 let grouped = Dictionary(grouping: shown.filter { $0.operation == nil }) { $0.destination.category }111 let formats = FormatCategory.allCases.compactMap { category in grouped[category].map { (category, $0) } }112 VStack(spacing: 0) {113 SearchField(text: $search, prompt: L("Search formats"), focus: $searchFocused).padding(ORIX.Space.m)114 ORIX.Palette.hairline.frame(height: 1)115 ScrollView {116 LazyVStack(alignment: .leading, spacing: 2) {117 if shown.isEmpty {118 Text(L("No destination matches “%@”.", search)).font(.callout).foregroundStyle(ORIX.Palette.textSecondary).padding(ORIX.Space.l)119 }120 if !operations.isEmpty {121 SectionLabel(L("Operations")).padding(.horizontal, ORIX.Space.s).padding(.top, ORIX.Space.s)122 ForEach(operations) { row($0) }123 }124 ForEach(formats, id: \.0) { category, list in125 SectionLabel(category.title).padding(.horizontal, ORIX.Space.s).padding(.top, ORIX.Space.m)126 ForEach(list) { row($0) }127 }128 }129 .padding(ORIX.Space.s)130 }131 }132 .frame(width: 380, height: 440)133 .background(ORIX.Palette.surface)134 .onAppear { searchFocused = true }135 }136137 private func row(_ entry: TargetEntry) -> some View {138 let selected = entry.id == selectedID139 return Button { onSelect(entry) } label: {140 HStack(spacing: ORIX.Space.s) {141 FormatBadge(format: entry.destination, size: .small, selected: selected)142 VStack(alignment: .leading, spacing: 1) {143 Text(entry.title).font(.callout.weight(selected ? .semibold : .regular)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)144 if !entry.chainedVia.isEmpty {145 Text(L("In two steps, through %@", entry.chainedVia.map(\.displayName).joined(separator: ", "))).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary)146 }147 }148 Spacer(minLength: 4)149 if entry.experimental { ExperimentalBadge() }150 FidelityBadge(fidelity: entry.fidelity)151 if selected { Image(systemName: "checkmark").font(.caption.weight(.bold)).foregroundStyle(ORIX.Palette.accent) }152 }153 .padding(.horizontal, ORIX.Space.s).padding(.vertical, 5)154 .background(selected ? ORIX.Palette.accentSoft : .clear, in: RoundedRectangle(cornerRadius: ORIX.Radius.s, style: .continuous))155 .contentShape(Rectangle())156 }157 .buttonStyle(.plain)158 .accessibilityLabel(entry.title)159 .accessibilityValue(entry.fidelity.title + (entry.experimental ? ", " + L("Experimental") : ""))160 .accessibilityAddTraits(selected ? [.isSelected] : [])161 }162}163164/// Button that shows the current destination and opens the picker.165struct TargetButton: View {166 let entries: [TargetEntry]167 let current: TargetEntry?168 var placeholder = L("Choose a destination")169 let onSelect: (TargetEntry) -> Void170 @State private var showPicker = false171172 var body: some View {173 Button { showPicker = true } label: {174 HStack(spacing: ORIX.Space.s) {175 if let current { FormatBadge(format: current.destination, size: .small, selected: true) }176 Text(current?.title ?? placeholder).font(.callout.weight(.medium)).foregroundStyle(current == nil ? ORIX.Palette.textSecondary : ORIX.Palette.textPrimary).lineLimit(1)177 Spacer(minLength: 4)178 Image(systemName: "chevron.up.chevron.down").font(.system(size: 10, weight: .semibold)).foregroundStyle(ORIX.Palette.textTertiary)179 }180 .padding(.horizontal, 9).padding(.vertical, 6)181 .frame(maxWidth: .infinity, alignment: .leading)182 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous))183 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m, style: .continuous).strokeBorder(ORIX.Palette.hairlineStrong, lineWidth: 1))184 .contentShape(Rectangle())185 }186 .buttonStyle(.plain)187 .disabled(entries.isEmpty)188 .popover(isPresented: $showPicker, arrowEdge: .bottom) {189 TargetPicker(entries: entries, selectedID: current?.id) { entry in190 showPicker = false191 onSelect(entry)192 }193 }194 .accessibilityLabel(L("Destination"))195 .accessibilityValue(current?.title ?? L("None"))196 }197}198199// MARK: - Private queue200201/// A second conversion queue, used only by the studios: Quality Lab trial conversions and Vector Studio exports run202/// through the same planner, engines, validation and safe writer as any job, without appearing in the Convert queue203/// or in the history.204final class StudioRunner {205 let queue: ConversionQueue206 /// Trial results live here until the next trial or until the app quits.207 let scratch: URL208209 init(registry: FormatRegistry, workDirectories: WorkDirectoryManager) {210 queue = ConversionQueue(registry: registry, configuration: QueueConfiguration(maxConcurrentJobs: 2, maxHeavyJobs: 1, heavyEngineIDs: EngineCatalog.heavyEngineIDs),211 history: nil, workDirectories: workDirectories)212 // Outside the work-directory root, which the queue sweeps and the self-test inspects.213 scratch = FileManager.default.temporaryDirectory.appendingPathComponent("ai.spboucher.orix.convert.studio-\(ProcessInfo.processInfo.processIdentifier)", isDirectory: true)214 }215216 func scratchDirectory(_ name: String) -> URL {217 let url = scratch.appendingPathComponent(name, isDirectory: true)218 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])219 return url220 }221222 /// Runs one job to its end. Cancelling the calling task cancels the job. `onProgress` receives measured values.223 func run(_ request: ConversionJobRequest, onProgress: (@MainActor (JobProgress) -> Void)? = nil) async -> ConversionJob? {224 var request = request225 request.recordInHistory = false226 let queue = queue227 let id = await queue.enqueue(request)228 let ticker = Task {229 while !Task.isCancelled {230 try? await Task.sleep(for: .milliseconds(120))231 if let progress = await queue.job(id)?.progress { onProgress?(progress) }232 }233 }234 defer { ticker.cancel() }235 return await withTaskCancellationHandler {236 await queue.waitForJob(id)237 } onCancel: {238 Task { await queue.cancel(id) }239 }240 }241242 func shutDown() async {243 await queue.cancelAll()244 await queue.waitUntilIdle()245 try? FileManager.default.removeItem(at: scratch)246 }247}248249// MARK: - Pictures250251/// How a file can be shown as a picture, if it can.252nonisolated enum PictureSource: Sendable, Equatable {253 case image(URL)254 case pdf(URL, pages: Int)255 case svg(URL, width: Int, height: Int)256 case video(URL, duration: Double)257258 /// The real limit of the bitmaps drawn in the canvas: longest side of the "detail" decode.259 static let detailLimit = 8192260 static let previewLimit = 2048261262 static func make(for file: InspectedFile) -> PictureSource? {263 guard let format = file.detection.format else { return nil }264 let inspection = file.inspection265 switch FormatCatalog.format(format)?.category ?? .other {266 case .image: return .image(file.url)267 case .pdf:268 let pages = inspection.pageCount ?? ((try? PDFPreview.pageCount(of: file.url)) ?? 0)269 return pages > 0 ? .pdf(file.url, pages: pages) : nil270 case .vector where format == .svg:271 guard let w = inspection.pixelWidth, let h = inspection.pixelHeight, w > 0, h > 0 else { return nil }272 return .svg(file.url, width: w, height: h)273 case .video:274 guard let duration = inspection.durationSeconds, duration > 0, inspection.pixelWidth != nil else { return nil }275 return .video(file.url, duration: duration)276 default: return nil277 }278 }279280 var pageCount: Int { if case .pdf(_, let pages) = self { return pages }; return 1 }281 var duration: Double? { if case .video(_, let duration) = self { return duration }; return nil }282283 /// Decodes a picture whose longest side is at most `limit` pixels.284 func render(limit: Int, page: Int = 0, time: Double = 0) async throws -> CGImage {285 switch self {286 case .image(let url): return try ImagePreview.decode(url: url, maxPixelSize: limit)287 case .pdf(let url, let pages): return try PDFPreview.thumbnail(of: url, pageIndex: min(max(0, page), pages - 1), maxPixelSize: min(4096, limit))288 case .svg(let url, let width, let height):289 let factor = min(1, Double(min(limit, 8192)) / Double(max(width, height)))290 let data = try Data(contentsOf: url)291 return try await SVGWebRenderer.bitmap(svg: data, pixelWidth: max(1, Int(Double(width) * factor)), pixelHeight: max(1, Int(Double(height) * factor)), background: nil)292 case .video(let url, let duration): return try await MediaQualityLab.videoFrame(of: url, atSeconds: min(max(0, time), duration), maxDimension: min(1920, limit))293 }294 }295}296297nonisolated enum PixelMath {298 /// Draws `image` into an 8-bit sRGB buffer of the given size (premultiplied alpha).299 static func buffer(_ image: CGImage, width: Int, height: Int) -> [UInt8]? {300 guard width > 0, height > 0, let space = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }301 var data = [UInt8](repeating: 0, count: width * height * 4)302 let ok: Bool = data.withUnsafeMutableBytes { raw in303 guard let context = CGContext(data: raw.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: space,304 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return false }305 context.interpolationQuality = .high306 context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))307 return true308 }309 return ok ? data : nil310 }311312 /// Absolute per-channel difference of two pictures, multiplied by `gain` and clamped, on an opaque black313 /// background. `b` is resampled to the size of `a` when they differ.314 static func difference(_ a: CGImage, _ b: CGImage, gain: Int) -> CGImage? {315 let width = a.width, height = a.height316 guard let first = buffer(a, width: width, height: height), let second = buffer(b, width: width, height: height),317 let space = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }318 var out = [UInt8](repeating: 255, count: width * height * 4)319 first.withUnsafeBufferPointer { pa in320 second.withUnsafeBufferPointer { pb in321 out.withUnsafeMutableBufferPointer { po in322 for index in stride(from: 0, to: width * height * 4, by: 4) {323 // Alpha differences show as grey added to every channel.324 let alpha = abs(Int(pa[index + 3]) - Int(pb[index + 3]))325 for channel in 0..<3 {326 let delta = abs(Int(pa[index + channel]) - Int(pb[index + channel]))327 po[index + channel] = UInt8(min(255, max(delta, alpha) * gain))328 }329 }330 }331 }332 }333 guard let provider = CGDataProvider(data: Data(out) as CFData) else { return nil }334 return CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4, space: space,335 bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue), provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)336 }337}338339/// Lets a `CGImage` cross isolation boundaries (it is immutable).340nonisolated struct SendableImage: @unchecked Sendable {341 let image: CGImage342 init(_ image: CGImage) { self.image = image }343}344