Repository Public License
1// ORIX Convert — Packages/ORIXConvertCore/Sources/ConvertCore/Planner.swift2// Description: Capability resolution (what can this format become, and what is recommended) and conversion planning3// (direct path, or a chain of at most two real paths through an intermediate format). Every ranking and4// cost rule is written out in this file; nothing is tuned by hidden weights.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation78extension Fidelity {9 /// Order from best to worst: lossless < structural < lossy < partial.10 public var lossRank: Int {11 switch self {12 case .lossless: 013 case .structural: 114 case .lossy: 215 case .partial: 316 }17 }1819 /// The worse of two fidelities.20 public static func worst(_ a: Fidelity, _ b: Fidelity) -> Fidelity { a.lossRank >= b.lossRank ? a : b }21}2223/// A destination (or named operation) offered for a source format, with the engine alternatives.24public struct ConversionTarget: Sendable, Hashable, Identifiable {25 public let destination: FormatID26 public let operation: String?27 /// The path the planner would use (best status, then best fidelity).28 public let best: ConversionPath29 /// Every available path for this pair, best first.30 public let alternatives: [ConversionPath]31 /// Recommendation score (see `ConversionCapabilityResolver.score`).32 public let score: Int33 public var id: String { destination.rawValue + (operation.map { "#" + $0 } ?? "") }34 public var title: String { best.title ?? FormatCatalog.format(destination)?.name ?? destination.rawValue.uppercased() }35}3637/// What can be done with one source format.38public struct ConversionCapabilities: Sendable {39 public let source: FormatID40 /// Plain conversions, best score first.41 public let targets: [ConversionTarget]42 /// Named operations (merge, split, extract…), best score first.43 public let operations: [ConversionTarget]44 /// The first few targets by score — what the UI proposes by default.45 public let recommended: [ConversionTarget]46 /// Destinations reachable only through a two-step chain (no direct path), sorted.47 public let chainedDestinations: [FormatID]48 public var isSupported: Bool { !targets.isEmpty || !operations.isEmpty }49}5051public struct ConversionCapabilityResolver: Sendable {52 public let registry: FormatRegistry53 public init(registry: FormatRegistry) { self.registry = registry }5455 /// The destinations most people want, per source category, in order of preference. Only used for ranking:56 /// a format appears as a target only when a real path exists.57 public static let commonTargets: [FormatCategory: [FormatID]] = [58 .image: [.png, .jpeg, .heic, .webp, .tiff, .pdf, .avif, .gif],59 .vector: [.png, .pdf, .svg, .jpeg],60 .pdf: [.png, .jpeg, .docx, .txt, .pdf],61 .video: [.mp4, .mov, .webm, .gif, .mp3, .m4a, .mkv],62 .audio: [.mp3, .m4a, .wav, .flac, .aiff, .ogg, .opus],63 .document: [.pdf, .docx, .markdown, .html, .txt, .rtf, .odt, .epub],64 .ebook: [.pdf, .epub, .html, .txt, .docx],65 .spreadsheet: [.xlsx, .csv, .pdf, .ods, .json],66 .data: [.csv, .json, .xlsx, .parquet, .jsonl, .yaml, .xml, .sqlite],67 .presentation: [.pdf, .pptx, .png, .odp],68 .archive: [.folder, .zip, .tgz, .sevenZip],69 .model3D: [.usdz, .glb, .obj, .stl, .gltf, .ply],70 .font: [.woff2, .ttf, .otf, .woff],71 .subtitle: [.srt, .vtt, .ass],72 .geospatial: [.geojson, .kml, .gpx, .csv, .geopackage],73 .scientific: [.csv, .parquet, .json],74 .other: [.zip],75 ]7677 /// Number of targets returned as `recommended`.78 public static let recommendedCount = 47980 /// Transparent recommendation score of a path for a source format (higher is better). The rule is additive:81 ///82 /// - **+100** when the destination is in the same category as the source (an image stays an image);83 /// - **+60 − 5 × position** when the destination is in `commonTargets` for the source category84 /// (position 0 is the most common target), never below +10;85 /// - **+10** when the path is `supported` (0 when `experimental`);86 /// - **+4 / +3 / +2 / +1** for `lossless` / `structural` / `lossy` / `partial` fidelity.87 ///88 /// Ties are broken alphabetically by destination identifier, so the order is deterministic.89 public static func score(_ path: ConversionPath, sourceCategory: FormatCategory?) -> Int {90 var score = 091 let destinationCategory = FormatCatalog.format(path.destination)?.category92 if let sourceCategory, destinationCategory == sourceCategory { score += 100 }93 if let sourceCategory, let position = commonTargets[sourceCategory]?.firstIndex(of: path.destination) {94 score += max(10, 60 - 5 * position)95 }96 if path.status == .supported { score += 10 }97 score += 4 - path.fidelity.lossRank98 return score99 }100101 /// Engine preference among paths for the same pair: `supported` before `experimental`, then better fidelity,102 /// then engine identifier (alphabetical) for determinism.103 public static func prefers(_ a: ConversionPath, over b: ConversionPath) -> Bool {104 if a.status != b.status { return a.status == .supported }105 if a.fidelity != b.fidelity { return a.fidelity.lossRank < b.fidelity.lossRank }106 return a.engine < b.engine107 }108109 public func capabilities(for source: FormatID) -> ConversionCapabilities {110 let category = FormatCatalog.format(source)?.category111 let all = registry.paths(from: source)112 func group(_ paths: [ConversionPath]) -> [ConversionTarget] {113 Dictionary(grouping: paths) { $0.destination.rawValue + "#" + ($0.operation ?? "") }.values.compactMap { alternatives in114 let sorted = alternatives.sorted { Self.prefers($0, over: $1) }115 guard let best = sorted.first else { return nil }116 return ConversionTarget(destination: best.destination, operation: best.operation, best: best, alternatives: sorted,117 score: Self.score(best, sourceCategory: category))118 }.sorted { ($1.score, $0.id) < ($0.score, $1.id) }119 }120 let targets = group(all.filter { $0.operation == nil })121 let direct = Set(targets.map(\.destination))122 // Two-step reachability: source → M → D, plain conversions only.123 var chained = Set<FormatID>()124 let planner = ConversionPlanner(registry: registry)125 var candidates = Set<FormatID>()126 for middle in direct where middle != .folder {127 for path in registry.paths(from: middle, operation: .some(nil)) where path.destination != source && !direct.contains(path.destination) && !path.acceptsMultipleSources {128 candidates.insert(path.destination)129 }130 }131 // Only destinations the planner would really accept (see `ConversionPlanner.canChain`).132 for destination in candidates where !planner.chains(from: source, to: destination).isEmpty { chained.insert(destination) }133 return ConversionCapabilities(source: source, targets: targets, operations: group(all.filter { $0.operation != nil }),134 recommended: Array(targets.prefix(Self.recommendedCount)), chainedDestinations: chained.sorted())135 }136}137138extension ConversionCapabilityResolver {139 /// Operations that do not look at what a file is, declared by engines from the `.folder` pseudo-source with a140 /// name ("Create ZIP archive", "Compress to gzip"). They are offered for **any** selection:141 ///142 /// - `forSelection`: `.folder` paths that accept several sources — any mix of regular files and folders becomes143 /// one output;144 /// - `forEachFile`: `.folder` paths marked `appliesToAnyFile` — applied to one regular file at a time (stream145 /// compression); never offered for a folder.146 ///147 /// A job that uses one of them is enqueued with `sourceFormat: .folder`, whatever the files are (see148 /// `ConversionJobManager.enqueueGeneric`). This keeps the registry honest: one declared path per destination149 /// instead of one per catalog format.150 public func genericOperations() -> (forSelection: [ConversionTarget], forEachFile: [ConversionTarget]) {151 let all = capabilities(for: .folder).operations152 return (all.filter { $0.best.acceptsMultipleSources && !$0.best.appliesToAnyFile }, all.filter { $0.best.appliesToAnyFile })153 }154}155156/// An ordered list of real conversion paths taking a source format to a destination format.157public struct ConversionPlan: Sendable, Hashable, Codable {158 /// One step for a direct conversion, two for a chained one.159 public let steps: [ConversionPath]160161 public init(steps: [ConversionPath]) { self.steps = steps }162163 public var source: FormatID { steps.first?.source ?? "unknown" }164 public var destination: FormatID { steps.last?.destination ?? "unknown" }165 public var operation: String? { steps.last?.operation }166 /// The plan goes through an intermediate format.167 public var isChained: Bool { steps.count > 1 }168 /// Intermediate formats, in order (empty for a direct plan).169 public var intermediates: [FormatID] { steps.dropLast().map(\.destination) }170 /// Union of the limitations of every step, in order, without duplicates.171 public var limitations: [String] {172 var seen = Set<String>()173 return steps.flatMap(\.limitations).filter { seen.insert($0).inserted }174 }175 /// The worst fidelity among the steps.176 public var fidelity: Fidelity { steps.map(\.fidelity).reduce(.lossless, Fidelity.worst) }177 /// `experimental` as soon as one step is.178 public var status: SupportStatus { steps.contains { $0.status == .experimental } ? .experimental : .supported }179 /// Aspects carried by every step (intersection).180 public var preserves: Set<Preserved> {181 guard let first = steps.first else { return [] }182 return steps.dropFirst().reduce(first.preserves) { $0.intersection($1.preserves) }183 }184 public var engines: [String] { steps.map(\.engine) }185 public var acceptsMultipleSources: Bool { steps.count == 1 && steps[0].acceptsMultipleSources }186}187188public struct ConversionPlanner: Sendable {189 public let registry: FormatRegistry190 public init(registry: FormatRegistry) { self.registry = registry }191192 /// Cost of one step of a chain: 0 lossless, 1 structural, 4 lossy, 8 partial, +2 when the path is experimental.193 public static func stepCost(_ path: ConversionPath) -> Int {194 [0, 1, 4, 8][path.fidelity.lossRank] + (path.status == .experimental ? 2 : 0)195 }196197 /// `true` when going through this first step keeps the content intact enough to convert again: the step is198 /// lossless or structural and the intermediate format is not a lossy format.199 public static func isLosslessIntermediate(_ first: ConversionPath) -> Bool {200 let lossyFormat = FormatCatalog.format(first.destination)?.traits.contains(.lossy) ?? false201 return !lossyFormat && first.fidelity.lossRank <= Fidelity.structural.lossRank202 }203204 /// `true` when `path` may give several files or a folder for one source, so that nothing can be chained after205 /// it: the engine says so (`producesMultipleOutputs`), the destination is a folder, or — for engines that have206 /// not set the flag — the source is a multi-page / multi-sheet format and the destination is a still image or207 /// drawing that holds one page (a PDF or a presentation becomes one PNG per page).208 public static func mayProduceSeveralFiles(_ path: ConversionPath) -> Bool {209 if path.producesMultipleOutputs || path.destination == .folder { return true }210 guard let source = FormatCatalog.format(path.source), let destination = FormatCatalog.format(path.destination) else { return false }211 let paged = source.traits.contains(.multiPage) || source.traits.contains(.multiSheet)212 let still = (destination.category == .image || destination.category == .vector) && !destination.traits.contains(.multiPage)213 return paged && still214 }215216 /// The rule for two paths to form a chain `first` then `second`:217 ///218 /// - both are plain single-source conversions;219 /// - `first` cannot yield several files (`mayProduceSeveralFiles`);220 /// - they belong to **different engines**. An engine that reads the source and writes the destination but221 /// declares no direct path between them has chosen not to convert that pair (the font engine reads OTF and222 /// writes TTF, and never converts outlines): two hops through the same engine would do it behind its back.223 public static func canChain(_ first: ConversionPath, _ second: ConversionPath) -> Bool {224 first.operation == nil && second.operation == nil && !first.acceptsMultipleSources && !second.acceptsMultipleSources225 && !first.appliesToAnyFile && !second.appliesToAnyFile226 && first.destination == second.source && !mayProduceSeveralFiles(first) && first.engine != second.engine227 }228229 /// Plans a conversion.230 ///231 /// 1. **Direct path** when one exists for (source, destination, operation). Among several engines the choice is232 /// `ConversionCapabilityResolver.prefers`: status, then fidelity. `engine` forces one engine's direct path.233 /// 2. Otherwise, for plain conversions only (`operation == nil`; chains never cross or include a named234 /// operation) and unless `allowChaining` is false, a **chain of exactly two paths** `source → M → destination`.235 /// Only pairs accepted by `canChain` are candidates (never after a step that can yield several files, never236 /// two steps of the same engine). Candidates through a lossy intermediate (see `isLosslessIntermediate`) are discarded whenever at least one237 /// lossless candidate exists. The remaining candidates are ranked by `stepCost(first) + stepCost(second)`,238 /// then by the intermediate identifier (alphabetical) for determinism.239 ///240 /// - Throws: `ConversionError.unsupportedPath` when no plan exists, `ConversionError.engineUnavailable` when the241 /// only paths belong to engines whose component is missing.242 public func plan(from source: FormatID, to destination: FormatID, operation: String? = nil, engine: String? = nil,243 allowChaining: Bool = true) throws -> ConversionPlan {244 let direct = registry.paths(from: source, to: destination, operation: .some(operation), engine: engine)245 .sorted { ConversionCapabilityResolver.prefers($0, over: $1) }246 if let best = direct.first { return ConversionPlan(steps: [best]) }247 if engine == nil, operation == nil, allowChaining, let chain = chains(from: source, to: destination).first { return chain }248 if let missing = registry.unavailablePaths(from: source, to: destination).first(where: { $0.path.operation == operation && (engine == nil || $0.path.engine == engine) }) {249 throw ConversionError.engineUnavailable(missing.reason)250 }251 throw ConversionError.unsupportedPath(source: source, destination: destination)252 }253254 /// Every admissible two-step chain for a plain conversion, best first (see `plan`). Empty when a chain is not255 /// possible; does not look at direct paths.256 public func chains(from source: FormatID, to destination: FormatID) -> [ConversionPlan] {257 guard source != destination else { return [] }258 var candidates: [(first: ConversionPath, second: ConversionPath)] = []259 let firsts = Dictionary(grouping: registry.paths(from: source, operation: .some(nil)), by: \.destination)260 for (middle, options) in firsts where middle != destination && middle != source && middle != .folder {261 let seconds = registry.paths(from: middle, to: destination, operation: .some(nil))262 // Best admissible pair through this intermediate: the preferred first step, then the preferred second.263 let pairs = options.sorted { ConversionCapabilityResolver.prefers($0, over: $1) }.flatMap { first in264 seconds.sorted { ConversionCapabilityResolver.prefers($0, over: $1) }.filter { Self.canChain(first, $0) }.map { (first, $0) }265 }266 guard let best = pairs.first else { continue }267 candidates.append(best)268 }269 if candidates.contains(where: { Self.isLosslessIntermediate($0.first) }) {270 candidates.removeAll { !Self.isLosslessIntermediate($0.first) }271 }272 return candidates.sorted {273 (Self.stepCost($0.first) + Self.stepCost($0.second), $0.first.destination.rawValue) < (Self.stepCost($1.first) + Self.stepCost($1.second), $1.first.destination.rawValue)274 }.map { ConversionPlan(steps: [$0.first, $0.second]) }275 }276}277