Repository Public License
1// ORIX Convert — App/Sources/Features/Flow/FlowModel.swift2// Description: Conversion Flow state: the workflow library (user workflows and validated built-in examples), the3// document being edited with undo / redo, live validation against the registry, and runs through the4// core's WorkflowRunner with per-item progress, cancellation and the run history.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import AppKit7import ConvertCore8import Observation9import UniformTypeIdentifiers1011/// One input of the run panel.12@Observable final class FlowRunItem: Identifiable {13 let url: URL14 var result: WorkflowItemResult?15 var progress: JobProgress?16 var isActive = false17 var id: URL { url }18 init(url: URL) { self.url = url }19}2021enum FlowPanelTab: Int { case step, run, history }2223@Observable final class FlowModel {24 @ObservationIgnored unowned let app: AppModel25 @ObservationIgnored let library: WorkflowLibrary26 @ObservationIgnored let undoManager = UndoManager()2728 private(set) var builtIns: [BuiltInWorkflow] = []29 private(set) var saved: [Workflow] = []30 private(set) var loadError: String?31 private(set) var document: FlowDocument?32 private(set) var validation: WorkflowValidation?33 var selection: UUID?34 var tab: FlowPanelTab = .run35 private(set) var notice: String?36 /// Bumped at every undo / redo registration so the menu items follow.37 private(set) var undoRevision = 03839 // Run40 private(set) var runItems: [FlowRunItem] = []41 private(set) var isRunning = false42 private(set) var lastRun: WorkflowRunResult?43 private(set) var runError: String?44 /// Where paths without an export step write; `nil` = next to each source.45 var exportFolder: URL?46 private(set) var history: [WorkflowRunRecord] = []47 @ObservationIgnored private var runTask: Task<Void, Never>?48 @ObservationIgnored private var progressTask: Task<Void, Never>?49 @ObservationIgnored private var saveTask: Task<Void, Never>?50 @ObservationIgnored private var loaded = false5152 init(app: AppModel) {53 self.app = app54 library = app.workflows55 undoManager.levelsOfUndo = 20056 }5758 var isBuiltIn: Bool { document.map { id in builtIns.contains { $0.id == id.id } } ?? false }59 var canEdit: Bool { document != nil && !isBuiltIn }60 var issues: [WorkflowIssue] { validation?.issues ?? [] }61 var isValid: Bool { validation?.isValid ?? false }62 var canRun: Bool { document != nil && isValid && !runItems.isEmpty && !isRunning }63 var canUndo: Bool { _ = undoRevision; return canEdit && undoManager.canUndo }64 var canRedo: Bool { _ = undoRevision; return canEdit && undoManager.canRedo }65 var selectedEntry: FlowEntry? { selection.flatMap { document?.entry($0) } }6667 func issues(for path: String) -> [WorkflowIssue] { issues.filter { $0.nodePath == path } }68 var workflowIssues: [WorkflowIssue] { issues.filter(\.nodePath.isEmpty) }6970 // MARK: Library7172 /// Loads the library once; opens the workflow asked at launch, or the first one.73 func start() async {74 guard !loaded else { return }75 loaded = true76 builtIns = BuiltInWorkflows.all(registry: app.registry)77 await reloadLibrary()78 if let wanted = app.launch.workflow, let workflow = find(wanted) { open(workflow) }79 else if document == nil, let first = saved.first ?? builtIns.first?.workflow { open(first) }80 }8182 /// Demonstration workflows for screenshots (`-ORIXSeedDemo YES`): one valid, one with an impossible step.83 func seedDemo(in root: URL) async {84 guard saved.isEmpty else { return }85 let shop = root.appendingPathComponent("Shop images", isDirectory: true)86 try? FileManager.default.createDirectory(at: shop, withIntermediateDirectories: true)87 let resize = ConversionOptions(["resize.mode": .string("long-edge"), "resize.long-edge": .int(2000), "quality": .int(80)])88 let valid = Workflow(name: L("Product photos"), summary: L("Web copies of product photos, exported to the shop folder."), nodes: [89 .filter(.all([.categoryIs(.image), .not(.nameMatches("draft-*"))])),90 .branch(condition: .width(.greaterThan, 2000), then: [.convert(destination: .webp, operation: nil, options: resize)],91 otherwise: [.convert(destination: .webp, operation: nil, options: ConversionOptions(["quality": .int(88)]))]),92 .rename(template: "{name}-{width}w"),93 .export(folder: shop, conflictPolicy: .rename),94 ])95 let broken = Workflow(name: L("Photos to subtitles (broken)"), nodes: [96 .filter(.categoryIs(.image)),97 .convert(destination: .jpeg, operation: nil, options: ConversionOptions()),98 .convert(destination: .srt, operation: nil, options: ConversionOptions()),99 ])100 try? await library.save(valid)101 try? await library.save(broken)102 await reloadLibrary()103 if let wanted = app.launch.workflow, let workflow = find(wanted) { open(workflow) } else { open(valid) }104 }105106 func reloadLibrary() async {107 saved = await library.all108 loadError = await library.loadError109 }110111 /// A workflow by identifier, built-in key or name.112 func find(_ text: String) -> Workflow? {113 let key = text.lowercased()114 if let builtIn = builtIns.first(where: { $0.key == key || $0.workflow.id.uuidString.lowercased() == key }) { return builtIn.workflow }115 return saved.first { $0.id.uuidString.lowercased() == key || $0.name.lowercased() == key } ?? builtIns.first { $0.workflow.name.lowercased() == key }?.workflow116 }117118 func open(_ workflow: Workflow) {119 guard !isRunning else { return }120 flushSave()121 document = FlowDocument(workflow)122 selection = nil123 undoManager.removeAllActions()124 undoRevision += 1125 lastRun = nil; runError = nil; notice = nil126 for item in runItems { item.result = nil; item.progress = nil; item.isActive = false }127 validate()128 Task { await reloadHistory() }129 }130131 func newWorkflow() {132 var index = 1133 var name = L("New workflow")134 while saved.contains(where: { $0.name == name }) { index += 1; name = L("New workflow %lld", index) }135 let destination = FormatID.pdf136 let workflow = Workflow(name: name, nodes: [.convert(destination: destination, operation: nil, options: ConversionOptions())])137 persist(workflow) { self.open(workflow); self.tab = .step; self.selection = self.document?.nodes.first?.id }138 }139140 /// Copies a workflow (built-in or not) into the user's library and opens the copy.141 func duplicate(_ workflow: Workflow) {142 var copy = workflow143 copy.id = UUID()144 let base = workflow.name145 var name = L("%@ copy", base), index = 1146 while saved.contains(where: { $0.name == name }) { index += 1; name = L("%@ copy %lld", base, index) }147 copy.name = name148 persist(copy) { self.open(copy) }149 }150151 func delete(_ workflow: Workflow) {152 let library = library153 Task {154 try? await library.delete(id: workflow.id)155 await reloadLibrary()156 if document?.id == workflow.id {157 document = nil158 if let next = saved.first ?? builtIns.first?.workflow { open(next) }159 }160 }161 }162163 func rename(_ workflow: Workflow, to name: String) {164 let trimmed = name.trimmingCharacters(in: .whitespaces)165 guard !trimmed.isEmpty else { return }166 if document?.id == workflow.id {167 edit(L("Rename Workflow")) { $0.name = trimmed }168 } else {169 var copy = workflow170 copy.name = trimmed171 persist(copy) {}172 }173 }174175 private func persist(_ workflow: Workflow, then: @escaping () -> Void) {176 let library = library177 Task {178 do { try await library.save(workflow) } catch { notice = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription }179 await reloadLibrary()180 then()181 }182 }183184 func exportJSON(_ workflow: Workflow) {185 let panel = NSSavePanel()186 panel.nameFieldStringValue = workflow.name + ".json"187 panel.allowedContentTypes = [.json]188 panel.prompt = L("Export")189 guard panel.runModal() == .OK, let url = panel.url else { return }190 let library = library191 let isSaved = saved.contains { $0.id == workflow.id }192 Task {193 do {194 // Built-in examples are not in the library file: they are written with the same encoder.195 let data: Data196 if isSaved { data = try await library.exportData(ids: [workflow.id]) } else { data = try Self.encode([workflow.redactingSecrets()]) }197 try data.write(to: url, options: .atomic)198 notice = L("“%@” was exported.", url.lastPathComponent)199 } catch { notice = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription }200 }201 }202203 private nonisolated static func encode(_ workflows: [Workflow]) throws -> Data {204 struct File: Encodable { var version = 1; var workflows: [Workflow] }205 let encoder = JSONEncoder()206 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]207 return try encoder.encode(File(workflows: workflows))208 }209210 func importJSON() {211 let panel = NSOpenPanel()212 panel.allowedContentTypes = [.json]213 panel.allowsMultipleSelection = false214 panel.prompt = L("Import")215 guard panel.runModal() == .OK, let url = panel.url else { return }216 Task { await importJSON(from: url) }217 }218219 func importJSON(from url: URL) async {220 do {221 let data = try Data(contentsOf: url)222 let imported = try await library.importData(data)223 await reloadLibrary()224 notice = imported.count == 1 ? L("1 workflow imported.") : L("%lld workflows imported.", imported.count)225 if let first = imported.first { open(first) }226 } catch { notice = LE((error as? LocalizedError)?.errorDescription ?? error.localizedDescription) }227 }228229 func dismissNotice() { notice = nil }230231 // MARK: Editing (undoable)232233 /// Applies a change to the document, registers its undo, validates and saves.234 func edit(_ actionName: String, _ body: (inout FlowDocument) -> Void) {235 guard canEdit, var next = document else { return }236 body(&next)237 guard next != document else { return }238 replaceDocument(with: next, actionName: actionName)239 }240241 private func replaceDocument(with next: FlowDocument, actionName: String) {242 guard let previous = document else { return }243 let previousSelection = selection244 undoManager.registerUndo(withTarget: self) { model in245 MainActor.assumeIsolated {246 model.replaceDocument(with: previous, actionName: actionName)247 model.selection = previousSelection.flatMap { previous.entry($0) != nil ? $0 : nil }248 }249 }250 undoManager.setActionName(actionName)251 document = next252 if let selection, next.entry(selection) == nil { self.selection = nil }253 undoRevision += 1254 validate()255 scheduleSave()256 }257258 func undo() { if canUndo { undoManager.undo(); undoRevision += 1 } }259 func redo() { if canRedo { undoManager.redo(); undoRevision += 1 } }260 var undoTitle: String { _ = undoRevision; return undoManager.undoMenuItemTitle }261 var redoTitle: String { _ = undoRevision; return undoManager.redoMenuItemTitle }262263 private func validate() {264 guard let document else { validation = nil; return }265 validation = WorkflowValidator.validate(document.workflow, registry: app.registry)266 }267268 private func scheduleSave() {269 saveTask?.cancel()270 guard canEdit, let workflow = document?.workflow else { return }271 let library = library272 saveTask = Task { [weak self] in273 try? await Task.sleep(for: .milliseconds(250))274 if Task.isCancelled { return }275 try? await library.save(workflow)276 await self?.reloadLibrary()277 }278 }279280 /// Writes pending edits now (before opening another workflow, running, or quitting).281 func flushSave() {282 guard saveTask != nil, canEdit, let workflow = document?.workflow else { return }283 saveTask?.cancel()284 saveTask = nil285 let library = library286 Task { try? await library.save(workflow); await reloadLibrary() }287 }288289 /// Saves the current document and waits (self-test).290 func saveNow() async {291 saveTask?.cancel()292 saveTask = nil293 guard canEdit, let workflow = document?.workflow else { return }294 try? await library.save(workflow)295 await reloadLibrary()296 }297298 private var defaultDestination: FormatID { app.registry.destinationFormats.contains(.pdf) ? .pdf : (app.registry.destinationFormats.first ?? .pdf) }299300 /// Adds a node after the selection (in its lane), or at the end.301 func add(_ category: FlowNode.Category) {302 guard let document else { return }303 var slot = FlowSlot(parent: nil, lane: .main, index: document.nodes.count)304 if let entry = selectedEntry { slot = entry.slot; slot.index += 1 }305 insert(category, at: slot)306 }307308 func insert(_ category: FlowNode.Category, at slot: FlowSlot) {309 let node = FlowNode.make(category, defaultDestination: defaultDestination)310 edit(L("Add Step")) { $0.insert(node, at: slot) }311 if document?.entry(node.id) != nil { selection = node.id; tab = .step }312 }313314 func move(_ id: UUID, to slot: FlowSlot) {315 edit(L("Move Step")) { _ = $0.move(id, to: slot) }316 }317318 /// Moves the selected node one place up or down in its lane.319 func moveSelection(by offset: Int) {320 guard let entry = selectedEntry else { return }321 var slot = entry.slot322 slot.index += offset < 0 ? -1 : 2323 guard slot.index >= 0 else { return }324 move(entry.id, to: slot)325 }326327 func deleteSelection() {328 guard let entry = selectedEntry, let document else { return }329 let entries = document.entries330 let index = entries.firstIndex { $0.id == entry.id } ?? 0331 edit(L("Delete Step")) { $0.remove(entry.id) }332 // Select the neighbour, like a list would.333 let remaining = self.document?.entries ?? []334 selection = remaining.isEmpty ? nil : remaining[min(index, remaining.count - 1)].id335 }336337 func duplicateSelection() {338 guard let entry = selectedEntry else { return }339 let copy = entry.node.duplicated()340 var slot = entry.slot341 slot.index += 1342 edit(L("Duplicate Step")) { $0.insert(copy, at: slot) }343 selection = copy.id344 }345346 func update(_ id: UUID, actionName: String = L("Change Step"), _ body: (inout FlowNode) -> Void) {347 edit(actionName) { $0.update(id, body) }348 }349350 /// Arrow keys: next / previous node in reading order.351 func selectNeighbour(_ offset: Int) {352 guard let entries = document?.entries, !entries.isEmpty else { return }353 guard let selection, let index = entries.firstIndex(where: { $0.id == selection }) else {354 self.selection = offset > 0 ? entries.first?.id : entries.last?.id355 return356 }357 self.selection = entries[min(entries.count - 1, max(0, index + offset))].id358 }359360 // MARK: Running361362 func chooseInputs() {363 let panel = NSOpenPanel()364 panel.canChooseFiles = true365 panel.canChooseDirectories = false366 panel.allowsMultipleSelection = true367 panel.prompt = L("Add")368 panel.message = L("Choose the files to send through this workflow")369 if panel.runModal() == .OK { addInputs(panel.urls) }370 }371372 func addInputs(_ urls: [URL]) {373 guard !isRunning else { return }374 var isDirectory: ObjCBool = false375 let known = Set(runItems.map(\.url.standardizedFileURL))376 for url in urls where url.isFileURL && !known.contains(url.standardizedFileURL) {377 guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), !isDirectory.boolValue else { continue }378 runItems.append(FlowRunItem(url: url))379 }380 tab = .run381 }382383 func removeInput(_ item: FlowRunItem) { if !isRunning { runItems.removeAll { $0.id == item.id } } }384 func clearInputs() { if !isRunning { runItems = []; lastRun = nil; runError = nil } }385386 func chooseExportFolder() {387 let panel = NSOpenPanel()388 panel.canChooseFiles = false389 panel.canChooseDirectories = true390 panel.canCreateDirectories = true391 panel.prompt = L("Choose")392 panel.message = L("Results of paths without an export step go to this folder")393 if panel.runModal() == .OK { exportFolder = panel.url }394 }395396 func run() {397 guard canRun else { return }398 runTask = Task { await runNow() }399 }400401 func cancelRun() { runTask?.cancel() }402403 /// Runs the document over the inputs and waits for the end.404 @discardableResult405 func runNow() async -> WorkflowRunResult? {406 guard let document, !isRunning, !runItems.isEmpty else { return nil }407 // The in-memory workflow runs (its passwords included); the library only ever holds the redacted copy.408 let workflow = document.workflow409 await saveNow()410 isRunning = true411 runError = nil412 lastRun = nil413 let items = runItems414 for item in items { item.result = nil; item.progress = nil; item.isActive = true }415 let started = Date()416 let queue = app.manager.queue417 // Measured progress of each item: its conversion jobs carry the run's counter (input position + 1).418 progressTask = Task { [weak self] in419 while !Task.isCancelled {420 try? await Task.sleep(for: .milliseconds(150))421 let jobs = await queue.snapshot().jobs.filter { $0.request.workflowRunID != nil && $0.createdAt >= started && $0.state.isActive }422 guard self != nil, !Task.isCancelled else { return }423 for (index, item) in items.enumerated() where item.result == nil {424 item.progress = jobs.first { $0.request.counter == index + 1 }?.progress425 }426 }427 }428 defer { progressTask?.cancel(); isRunning = false }429 let options = WorkflowRunOptions(defaultExportFolder: exportFolder, defaultConflictPolicy: .rename, recordRun: app.settings.stored.historyEnabled)430 let runner = app.manager.workflowRunner431 let urls = items.map(\.url)432 do {433 let result = try await runner.run(workflow, inputs: urls, options: options) { [weak self] finished in434 Task { @MainActor in435 guard self != nil, let item = items.first(where: { $0.url == finished.source }) else { return }436 item.result = finished437 item.isActive = false438 item.progress = nil439 }440 }441 for (index, item) in items.enumerated() where index < result.items.count {442 item.result = result.items[index]443 item.isActive = false444 item.progress = nil445 }446 lastRun = result447 await reloadHistory()448 return result449 } catch {450 for item in items { item.isActive = false }451 runError = (error as? WorkflowError).map(Self.describe) ?? (error as? LocalizedError)?.errorDescription ?? error.localizedDescription452 return nil453 }454 }455456 private static func describe(_ error: WorkflowError) -> String {457 switch error {458 case .invalid(let validation): L("The workflow cannot run.") + " " + validation.errors.map { FlowMessages.text($0) }.joined(separator: " ")459 case .notFound: L("The workflow no longer exists.")460 case .storage(let message): LE(message)461 }462 }463464 func reloadHistory() async {465 guard let id = document?.id, let store = app.manager.history else { history = []; return }466 history = (try? await store.workflowRuns(workflowID: id, limit: 50)) ?? []467 }468}469470extension WorkflowItemResult.Status {471 var title: String {472 switch self {473 case .succeeded: L("Done")474 case .succeededWithErrors: L("Done, with a skipped step")475 case .filtered: L("Filtered out")476 case .failed: L("Failed")477 case .cancelled: L("Cancelled")478 }479 }480 var symbol: String {481 switch self {482 case .succeeded: "checkmark.circle.fill"483 case .succeededWithErrors: "exclamationmark.circle.fill"484 case .filtered: "line.3.horizontal.decrease.circle"485 case .failed: "xmark.octagon.fill"486 case .cancelled: "slash.circle"487 }488 }489}490