Repository Public License
1// ORIX Convert — App/Sources/Features/Flow/FlowDocument.swift2// Description: The editable form of a core Workflow: the same nodes with stable identifiers (selection, drag, undo),3// tree editing by identifier, the condition builder's flat form, plain descriptions of nodes and4// conditions, and the built-in example workflows.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import ConvertCore7import Foundation89struct FlowNode: Identifiable, Hashable {10 enum Kind: Hashable {11 case convert(destination: FormatID, operation: String?, options: ConversionOptions)12 case rename(String)13 case filter(WorkflowCondition)14 case branch(WorkflowCondition, then: [FlowNode], otherwise: [FlowNode])15 case export(URL, ConflictPolicy)16 }1718 enum Category: String, CaseIterable, Identifiable {19 case convert, rename, filter, branch, export20 var id: String { rawValue }21 var title: String {22 switch self {23 case .convert: L("Convert")24 case .rename: L("Rename")25 case .filter: L("Filter")26 case .branch: L("Branch")27 case .export: L("Export")28 }29 }30 var symbol: String {31 switch self {32 case .convert: "arrow.triangle.2.circlepath"33 case .rename: "character.cursor.ibeam"34 case .filter: "line.3.horizontal.decrease.circle"35 case .branch: "arrow.triangle.branch"36 case .export: "square.and.arrow.down"37 }38 }39 var help: String {40 switch self {41 case .convert: L("Converts the file; the following steps receive the result.")42 case .rename: L("Sets the name used by the exports that follow.")43 case .filter: L("Stops the files that do not match.")44 case .branch: L("Runs one of two lanes depending on a condition, then continues.")45 case .export: L("Copies the current file into a folder.")46 }47 }48 }4950 var id = UUID()51 var kind: Kind5253 var category: Category {54 switch kind {55 case .convert: .convert56 case .rename: .rename57 case .filter: .filter58 case .branch: .branch59 case .export: .export60 }61 }6263 init(id: UUID = UUID(), kind: Kind) { self.id = id; self.kind = kind }6465 init(_ node: WorkflowNode) {66 switch node {67 case .convert(let destination, let operation, let options): kind = .convert(destination: destination, operation: operation, options: options)68 case .rename(let template): kind = .rename(template)69 case .filter(let condition): kind = .filter(condition)70 case .branch(let condition, let then, let otherwise): kind = .branch(condition, then: then.map(FlowNode.init), otherwise: otherwise.map(FlowNode.init))71 case .export(let folder, let policy): kind = .export(folder, policy)72 }73 }7475 var workflowNode: WorkflowNode {76 switch kind {77 case .convert(let destination, let operation, let options): .convert(destination: destination, operation: operation, options: options)78 case .rename(let template): .rename(template: template)79 case .filter(let condition): .filter(condition)80 case .branch(let condition, let then, let otherwise): .branch(condition: condition, then: then.map(\.workflowNode), otherwise: otherwise.map(\.workflowNode))81 case .export(let folder, let policy): .export(folder: folder, conflictPolicy: policy)82 }83 }8485 /// A copy with new identifiers everywhere.86 func duplicated() -> FlowNode {87 var copy = FlowNode(kind: kind)88 if case .branch(let condition, let then, let otherwise) = kind {89 copy.kind = .branch(condition, then: then.map { $0.duplicated() }, otherwise: otherwise.map { $0.duplicated() })90 }91 return copy92 }9394 /// A new node of a category, with harmless defaults.95 static func make(_ category: Category, defaultDestination: FormatID) -> FlowNode {96 switch category {97 case .convert: FlowNode(kind: .convert(destination: defaultDestination, operation: nil, options: ConversionOptions()))98 case .rename: FlowNode(kind: .rename("{name}"))99 case .filter: FlowNode(kind: .filter(.categoryIs(.image)))100 case .branch: FlowNode(kind: .branch(.categoryIs(.image), then: [], otherwise: []))101 case .export: FlowNode(kind: .export(FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first ?? URL(fileURLWithPath: NSHomeDirectory()), .rename))102 }103 }104}105106/// Where a node can be inserted: an index in the main lane or in one side of a branch.107struct FlowSlot: Hashable {108 enum Lane: String, Hashable { case main, then, otherwise }109 var parent: UUID?110 var lane: Lane111 var index: Int112}113114/// A node with its position in the workflow, in reading order.115struct FlowEntry: Identifiable {116 let node: FlowNode117 /// The core's path of the node: `2`, `3.then.1`.118 let path: String119 let slot: FlowSlot120 let depth: Int121 var id: UUID { node.id }122}123124struct FlowDocument: Hashable {125 var id: UUID126 var name: String127 var summary: String128 var nodes: [FlowNode]129 var errorPolicy: WorkflowErrorPolicy130131 init(_ workflow: Workflow) {132 id = workflow.id; name = workflow.name; summary = workflow.summary133 nodes = workflow.nodes.map(FlowNode.init); errorPolicy = workflow.errorPolicy134 }135136 var workflow: Workflow { Workflow(id: id, name: name, summary: summary, nodes: nodes.map(\.workflowNode), errorPolicy: errorPolicy) }137138 // MARK: Reading139140 var entries: [FlowEntry] {141 var list: [FlowEntry] = []142 func walk(_ nodes: [FlowNode], prefix: String, parent: UUID?, lane: FlowSlot.Lane, depth: Int) {143 for (index, node) in nodes.enumerated() {144 let path = prefix + String(index + 1)145 list.append(FlowEntry(node: node, path: path, slot: FlowSlot(parent: parent, lane: lane, index: index), depth: depth))146 if case .branch(_, let then, let otherwise) = node.kind {147 walk(then, prefix: path + ".then.", parent: node.id, lane: .then, depth: depth + 1)148 walk(otherwise, prefix: path + ".otherwise.", parent: node.id, lane: .otherwise, depth: depth + 1)149 }150 }151 }152 walk(nodes, prefix: "", parent: nil, lane: .main, depth: 0)153 return list154 }155156 func entry(_ id: UUID) -> FlowEntry? { entries.first { $0.id == id } }157 func node(_ id: UUID) -> FlowNode? { entry(id)?.node }158159 // MARK: Editing160161 private static func edit(_ nodes: inout [FlowNode], parent: UUID?, lane: FlowSlot.Lane, _ body: (inout [FlowNode]) -> Void) -> Bool {162 if parent == nil { body(&nodes); return true }163 for index in nodes.indices {164 guard case .branch(let condition, var then, var otherwise) = nodes[index].kind else { continue }165 if nodes[index].id == parent {166 if lane == .otherwise { body(&otherwise) } else { body(&then) }167 nodes[index].kind = .branch(condition, then: then, otherwise: otherwise)168 return true169 }170 if edit(&then, parent: parent, lane: lane, body) || edit(&otherwise, parent: parent, lane: lane, body) {171 nodes[index].kind = .branch(condition, then: then, otherwise: otherwise)172 return true173 }174 }175 return false176 }177178 mutating func insert(_ node: FlowNode, at slot: FlowSlot) {179 _ = Self.edit(&nodes, parent: slot.parent, lane: slot.lane) { list in list.insert(node, at: min(max(0, slot.index), list.count)) }180 }181182 @discardableResult183 mutating func remove(_ id: UUID) -> FlowNode? {184 guard let entry = entry(id) else { return nil }185 _ = Self.edit(&nodes, parent: entry.slot.parent, lane: entry.slot.lane) { list in list.removeAll { $0.id == id } }186 return entry.node187 }188189 mutating func update(_ id: UUID, _ body: (inout FlowNode) -> Void) {190 guard let entry = entry(id) else { return }191 _ = Self.edit(&nodes, parent: entry.slot.parent, lane: entry.slot.lane) { list in192 if let index = list.firstIndex(where: { $0.id == id }) { body(&list[index]) }193 }194 }195196 /// Moves a node to a slot. A branch cannot be moved inside itself.197 mutating func move(_ id: UUID, to slot: FlowSlot) -> Bool {198 guard let entry = entry(id) else { return false }199 if let parent = slot.parent {200 if parent == id { return false }201 // The target lane must not belong to the moved node.202 var inside = false203 func search(_ nodes: [FlowNode]) { for node in nodes { if node.id == parent { inside = true }; if case .branch(_, let a, let b) = node.kind { search(a); search(b) } } }204 if case .branch(_, let a, let b) = entry.node.kind { search(a); search(b) }205 if inside { return false }206 }207 var target = slot208 if entry.slot.parent == slot.parent, entry.slot.lane == slot.lane, entry.slot.index < slot.index { target.index -= 1 }209 if entry.slot == target { return false }210 guard let node = remove(id) else { return false }211 insert(node, at: target)212 return true213 }214}215216// MARK: - Conditions217218/// One line of the condition builder.219struct ConditionClause: Identifiable, Hashable {220 enum Kind: String, CaseIterable, Identifiable {221 case format, category, sizeAbove, sizeBelow, name, width, height, duration222 var id: String { rawValue }223 var title: String {224 switch self {225 case .format: L("Format is")226 case .category: L("Category is")227 case .sizeAbove: L("Size above")228 case .sizeBelow: L("Size below")229 case .name: L("Name matches")230 case .width: L("Width")231 case .height: L("Height")232 case .duration: L("Duration")233 }234 }235 }236237 var id = UUID()238 var kind: Kind = .category239 var negated = false240 var format: FormatID = .jpeg241 var category: FormatCategory = .image242 /// Megabytes (decimal), for the two size tests.243 var megabytes = 1.0244 var glob = "*.jpg"245 var comparison: Comparison = .greaterThan246 /// Pixels (width, height) or seconds (duration).247 var number = 2000.0248249 init() {}250251 init?(_ condition: WorkflowCondition) {252 var inner = condition253 if case .not(let wrapped) = condition { negated = true; inner = wrapped }254 switch inner {255 case .formatIs(let value): kind = .format; format = value256 case .categoryIs(let value): kind = .category; category = value257 case .sizeAbove(let bytes): kind = .sizeAbove; megabytes = Double(bytes) / 1_000_000258 case .sizeBelow(let bytes): kind = .sizeBelow; megabytes = Double(bytes) / 1_000_000259 case .nameMatches(let pattern): kind = .name; glob = pattern260 case .width(let c, let value): kind = .width; comparison = c; number = Double(value)261 case .height(let c, let value): kind = .height; comparison = c; number = Double(value)262 case .duration(let c, let value): kind = .duration; comparison = c; number = value263 case .not, .all, .any: return nil264 }265 }266267 var condition: WorkflowCondition {268 let base: WorkflowCondition = switch kind {269 case .format: .formatIs(format)270 case .category: .categoryIs(category)271 case .sizeAbove: .sizeAbove(Int64((megabytes * 1_000_000).rounded()))272 case .sizeBelow: .sizeBelow(Int64((megabytes * 1_000_000).rounded()))273 case .name: .nameMatches(glob)274 case .width: .width(comparison, Int(number.rounded()))275 case .height: .height(comparison, Int(number.rounded()))276 case .duration: .duration(comparison, number)277 }278 return negated ? .not(base) : base279 }280}281282/// The form the builder edits: clauses joined by "all" or "any". Conditions nested deeper (imported JSON) have no283/// draft and are shown as text until they are replaced.284struct ConditionDraft: Hashable {285 var matchAll = true286 var clauses: [ConditionClause] = [ConditionClause()]287288 init() {}289290 init?(_ condition: WorkflowCondition) {291 switch condition {292 case .all(let list):293 let parsed = list.compactMap(ConditionClause.init)294 guard parsed.count == list.count, !parsed.isEmpty else { return nil }295 matchAll = true; clauses = parsed296 case .any(let list):297 let parsed = list.compactMap(ConditionClause.init)298 guard parsed.count == list.count, !parsed.isEmpty else { return nil }299 matchAll = false; clauses = parsed300 default:301 guard let clause = ConditionClause(condition) else { return nil }302 clauses = [clause]303 }304 }305306 var condition: WorkflowCondition {307 if clauses.count == 1 { return clauses[0].condition }308 return matchAll ? .all(clauses.map(\.condition)) : .any(clauses.map(\.condition))309 }310}311312extension Comparison {313 var symbol: String {314 switch self {315 case .lessThan: "<"316 case .lessOrEqual: "≤"317 case .equal: "="318 case .greaterOrEqual: "≥"319 case .greaterThan: ">"320 }321 }322}323324extension WorkflowCondition {325 /// The condition in plain words ("Images and wider than 2,000 px").326 var summary: String {327 switch self {328 case .formatIs(let format): return L("format is %@", format.displayName)329 case .categoryIs(let category): return L("category is %@", category.title)330 case .sizeAbove(let bytes): return L("larger than %@", Fmt.bytes(bytes))331 case .sizeBelow(let bytes): return L("smaller than %@", Fmt.bytes(bytes))332 case .nameMatches(let pattern): return L("name matches %@", pattern)333 case .width(let c, let value): return L("width %@ %@ px", c.symbol, Fmt.count(value))334 case .height(let c, let value): return L("height %@ %@ px", c.symbol, Fmt.count(value))335 case .duration(let c, let value): return L("duration %@ %@", c.symbol, Fmt.duration(value))336 case .not(let inner): return L("not (%@)", inner.summary)337 case .all(let list): return list.isEmpty ? L("always") : list.map(\.summary).joined(separator: " " + L("and") + " ")338 case .any(let list): return list.isEmpty ? L("never") : list.map(\.summary).joined(separator: " " + L("or") + " ")339 }340 }341}342343extension FlowNode {344 /// Title of the card.345 func title(registry: FormatRegistry) -> String {346 switch kind {347 case .convert(let destination, let operation, _):348 if let operation, let title = registry.paths(to: destination, operation: .some(operation)).first?.title { return LE(title) }349 return L("Convert to %@", destination.displayName)350 case .rename: return L("Rename")351 case .filter: return L("Keep only")352 case .branch: return L("If")353 case .export: return L("Export to folder")354 }355 }356357 /// Second line of the card.358 var detail: String {359 switch kind {360 case .convert(_, _, let options):361 let count = options.redactingSecrets().values.count362 return count == 0 ? L("Default settings") : (count == 1 ? L("1 setting changed") : L("%lld settings changed", count))363 case .rename(let template): return template364 case .filter(let condition), .branch(let condition, _, _): return condition.summary365 case .export(let folder, let policy): return (folder.path as NSString).abbreviatingWithTildeInPath + " · " + policy.title366 }367 }368}369370// MARK: - Built-in examples371372struct BuiltInWorkflow: Identifiable {373 let key: String374 let workflow: Workflow375 /// Formats the example is checked against at launch: every one of them must really go through.376 let checkedInputs: Set<FormatID>377 var id: UUID { workflow.id }378}379380enum BuiltInWorkflows {381 private static func uuid(_ n: Int) -> UUID { UUID(uuidString: String(format: "0A1B2C3D-0000-4000-8000-%012d", n)) ?? UUID() }382383 /// Examples built with the same model as any workflow. Only those that validate against the registry, for the384 /// formats they are meant for, are offered.385 static func all(registry: FormatRegistry) -> [BuiltInWorkflow] {386 let candidates: [BuiltInWorkflow] = [387 BuiltInWorkflow(key: "images-webp", workflow: Workflow(388 id: uuid(1), name: L("Images → WebP, 2000 px, no location"),389 summary: L("Every image becomes a WebP of at most 2000 pixels on its long edge, without its GPS position."),390 nodes: [.filter(.categoryIs(.image)),391 .convert(destination: .webp, operation: nil, options: ConversionOptions(["resize.mode": .string("long-edge"), "resize.long-edge": .int(2000),392 "metadata": .string("strip-location"), "quality": .int(82)])),393 .rename(template: "{name}-web")]), checkedInputs: [.jpeg, .png, .heic, .tiff]),394 BuiltInWorkflow(key: "pdf-ocr", workflow: Workflow(395 id: uuid(2), name: L("PDF → searchable PDF (OCR)"),396 summary: L("Scanned PDFs get a text layer recognised on this Mac; other files are left out."),397 nodes: [.filter(.formatIs(.pdf)), .convert(destination: .pdf, operation: "pdf.ocr", options: ConversionOptions()), .rename(template: "{name}-searchable")]),398 checkedInputs: [.pdf]),399 BuiltInWorkflow(key: "media-branch", workflow: Workflow(400 id: uuid(3), name: L("Video → MP4, audio → M4A"),401 summary: L("A branch: videos are converted to MP4, everything else that carries sound to M4A."),402 nodes: [.filter(.any([.categoryIs(.video), .categoryIs(.audio)])),403 .branch(condition: .categoryIs(.video), then: [.convert(destination: .mp4, operation: nil, options: ConversionOptions())],404 otherwise: [.convert(destination: .m4a, operation: nil, options: ConversionOptions())])]), checkedInputs: [.mov, .wav, .mp3]),405 BuiltInWorkflow(key: "scans-pdf", workflow: Workflow(406 id: uuid(4), name: L("Scans → PDF, one per image"),407 summary: L("Each scanned image becomes its own PDF, named with the date. (A workflow handles files one by one: to combine several images into one PDF, use Convert.)"),408 nodes: [.filter(.any([.formatIs(.tiff), .formatIs(.png), .formatIs(.jpeg)])), .convert(destination: .pdf, operation: nil, options: ConversionOptions()),409 .rename(template: "{name}-{date}")]), checkedInputs: [.tiff, .png, .jpeg]),410 BuiltInWorkflow(key: "large-photos", workflow: Workflow(411 id: uuid(5), name: L("Large photos → JPEG, small ones untouched"),412 summary: L("Images wider than 3000 pixels are reduced and saved as JPEG; smaller ones are only converted."),413 nodes: [.filter(.categoryIs(.image)),414 .branch(condition: .width(.greaterThan, 3000),415 then: [.convert(destination: .jpeg, operation: nil, options: ConversionOptions(["resize.mode": .string("long-edge"), "resize.long-edge": .int(3000), "quality": .int(85)]))],416 otherwise: [.convert(destination: .jpeg, operation: nil, options: ConversionOptions(["quality": .int(90)]))])]), checkedInputs: [.png, .heic, .tiff]),417 ]418 return candidates.filter { WorkflowValidator.validate($0.workflow, registry: registry, inputFormats: $0.checkedInputs).isValid }419 }420}421422// MARK: - Messages423424enum FlowMessages {425 /// The validator's messages in the user's language. Patterns the app knows are rebuilt from their parts; the426 /// rest goes through the engines' catalog, then stays as the core wrote it.427 static func text(_ issue: WorkflowIssue) -> String {428 let message = issue.message429 if let match = message.firstMatch(of: /^No conversion to ([A-Z0-9-]+)(?: \((.+)\))? exists for: (.+)\.$/) {430 let destination = FormatID(String(match.1).lowercased()).displayName431 let sources = String(match.3).replacingOccurrences(of: "…", with: "").split(separator: ",").map { FormatID($0.trimmingCharacters(in: .whitespaces).lowercased()).displayName }432 let list = sources.prefix(4).joined(separator: ", ") + (sources.count > 4 || String(match.3).hasSuffix("…") ? "…" : "")433 if let operation = match.2 { return L("%@ cannot go through “%@” to %@.", list, String(operation), destination) }434 return L("%@ cannot be converted to %@.", list, destination)435 }436 if let match = message.firstMatch(of: /^No file can reach this conversion to ([A-Z0-9-]+)\.$/) {437 return L("No file can reach this conversion to %@: an earlier step leaves nothing for it.", FormatID(String(match.1).lowercased()).displayName)438 }439 switch message {440 case "The name template is empty.": return L("The name template is empty.")441 case "The export folder is not set.": return L("The export folder is not set.")442 case "The workflow has no step.": return L("The workflow has no step.")443 case let text where text.hasPrefix("A workflow cannot ask"): return L("A workflow cannot ask: with this policy an existing file is reported as an error for that item.")444 case let text where text.hasPrefix("Some paths have no export step"): return L("Some paths have no export step: their results go to the folder chosen for the run (next to each source by default).")445 default: return LE(message)446 }447 }448}449