SPB Git

Repository Public License

Engine.swift 18.7 KB 394 lines swift

1// ORIX Convert — Packages/ORIXConvertCore/Sources/ConvertCore/Engine.swift2// Description: The engine contract. Every conversion engine declares real conversion paths (decoder → transform →3//              encoder) and implements inspect / convert / validate against this file. The app and the CLI only ever4//              talk to engines through these types.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation78// MARK: - Conversion paths910public enum SupportStatus: String, Codable, Sendable {11    /// Implemented and covered by passing tests.12    case supported13    /// Implemented, tested on a narrow corpus; results can vary.14    case experimental15}1617public enum Fidelity: String, Codable, Sendable {18    /// Decoding the output gives back the source content exactly (pixels, samples, rows, bytes).19    case lossless20    /// Perceptual or numeric loss is expected (lossy codecs, quantization, resampling).21    case lossy22    /// Content is kept but re-expressed: layout, styling or structure is rebuilt and may differ.23    case structural24    /// Only part of the source is carried over (text extraction, single sheet, geometry without materials…).25    case partial26}2728/// Aspects of a source file a path is able to carry to the destination.29public enum Preserved: String, Codable, Sendable, CaseIterable {30    case metadata, transparency, animation, colorProfile, hdr, layers, vectorGeometry31    case textStyles, tables, images, links, formulas, multipleSheets, chapters32    case audioTracks, subtitleTracks, timing, materials, textures, attributes, coordinateSystem, dimensions33}3435/// One real conversion capability of an engine: a decoder for `source`, a transformation, an encoder for `destination`.36public struct ConversionPath: Sendable, Hashable, Codable, Identifiable {37    public let source: FormatID38    public let destination: FormatID39    /// Identifier of the engine that implements the path.40    public let engine: String41    /// `nil` for a plain format conversion; otherwise a named operation such as `pdf.merge`, `pdf.split`,42    /// `archive.extract`, `image.vectorize`, `video.extract-audio`.43    public let operation: String?44    /// Short English title, shown in the UI for operations ("Merge PDFs").45    public let title: String?46    public let status: SupportStatus47    public let fidelity: Fidelity48    public let preserves: Set<Preserved>49    /// Plain-English statements of what is lost or not handled. Shown to the user before converting.50    public let limitations: [String]51    /// The path consumes several sources at once (merge, images → PDF, archive creation).52    public let acceptsMultipleSources: Bool53    /// One source can yield several files or a folder (a page per image, a slide per image…). Such a path is never54    /// the first step of a chained plan: the second step needs exactly one file.55    public let producesMultipleOutputs: Bool56    /// The path does not look at what its source is: it applies to **any regular file**, whatever its format57    /// (stream compression). Declared once from the `.folder` pseudo-source; the core offers it for every file and58    /// enqueues the job with `sourceFormat: .folder`.59    public let appliesToAnyFile: Bool6061    public init(_ source: FormatID, _ destination: FormatID, engine: String, operation: String? = nil, title: String? = nil,62                status: SupportStatus = .supported, fidelity: Fidelity, preserves: Set<Preserved> = [],63                limitations: [String] = [], acceptsMultipleSources: Bool = false, producesMultipleOutputs: Bool = false,64                appliesToAnyFile: Bool = false) {65        self.source = source; self.destination = destination; self.engine = engine; self.operation = operation66        self.title = title; self.status = status; self.fidelity = fidelity; self.preserves = preserves67        self.limitations = limitations; self.acceptsMultipleSources = acceptsMultipleSources68        self.producesMultipleOutputs = producesMultipleOutputs; self.appliesToAnyFile = appliesToAnyFile69    }7071    private enum CodingKeys: String, CodingKey {72        case source, destination, engine, operation, title, status, fidelity, preserves, limitations, acceptsMultipleSources, producesMultipleOutputs, appliesToAnyFile73    }7475    /// Values stored before `producesMultipleOutputs` / `appliesToAnyFile` existed decode with `false`.76    public init(from decoder: any Decoder) throws {77        let c = try decoder.container(keyedBy: CodingKeys.self)78        source = try c.decode(FormatID.self, forKey: .source)79        destination = try c.decode(FormatID.self, forKey: .destination)80        engine = try c.decode(String.self, forKey: .engine)81        operation = try c.decodeIfPresent(String.self, forKey: .operation)82        title = try c.decodeIfPresent(String.self, forKey: .title)83        status = try c.decode(SupportStatus.self, forKey: .status)84        fidelity = try c.decode(Fidelity.self, forKey: .fidelity)85        preserves = try c.decode(Set<Preserved>.self, forKey: .preserves)86        limitations = try c.decode([String].self, forKey: .limitations)87        acceptsMultipleSources = try c.decode(Bool.self, forKey: .acceptsMultipleSources)88        producesMultipleOutputs = try c.decodeIfPresent(Bool.self, forKey: .producesMultipleOutputs) ?? false89        appliesToAnyFile = try c.decodeIfPresent(Bool.self, forKey: .appliesToAnyFile) ?? false90    }9192    public var id: String { "\(engine):\(source.rawValue)>\(destination.rawValue)\(operation.map { "#\($0)" } ?? "")" }93}9495// MARK: - Options9697public enum OptionValue: Sendable, Hashable, Codable {98    case bool(Bool), int(Int), double(Double), string(String)99}100101/// Describes one user-adjustable setting of a path. The app builds its settings panels from these.102public struct OptionDescriptor: Sendable, Hashable, Identifiable {103    public struct Choice: Sendable, Hashable {104        public let value: String105        public let label: String106        public init(_ value: String, _ label: String) { self.value = value; self.label = label }107    }108109    public enum Kind: Sendable, Hashable {110        case toggle(default: Bool)111        case integer(default: Int, range: ClosedRange<Int>, unit: String?)112        case number(default: Double, range: ClosedRange<Double>, step: Double, unit: String?)113        case choice(default: String, choices: [Choice])114        case text(default: String, placeholder: String)115    }116117    /// Key used in `ConversionOptions`.118    public let id: String119    /// English label (localized by the app).120    public let label: String121    public let help: String?122    public let kind: Kind123    /// English group title ("Quality", "Size", "Metadata"…).124    public let group: String125    public let advanced: Bool126127    public init(_ id: String, label: String, help: String? = nil, kind: Kind, group: String = "General", advanced: Bool = false) {128        self.id = id; self.label = label; self.help = help; self.kind = kind; self.group = group; self.advanced = advanced129    }130131    public var defaultValue: OptionValue {132        switch kind {133        case .toggle(let d): .bool(d)134        case .integer(let d, _, _): .int(d)135        case .number(let d, _, _, _): .double(d)136        case .choice(let d, _): .string(d)137        case .text(let d, _): .string(d)138        }139    }140}141142public struct ConversionOptions: Sendable, Hashable, Codable {143    public var values: [String: OptionValue]144    public init(_ values: [String: OptionValue] = [:]) { self.values = values }145146    public subscript(key: String) -> OptionValue? {147        get { values[key] }148        set { values[key] = newValue }149    }150151    public func bool(_ key: String, default d: Bool = false) -> Bool {152        if case .bool(let v)? = values[key] { return v }153        return d154    }155156    public func int(_ key: String, default d: Int = 0) -> Int {157        switch values[key] {158        case .int(let v)?: return v159        case .double(let v)?: return Int(v.rounded())160        default: return d161        }162    }163164    public func double(_ key: String, default d: Double = 0) -> Double {165        switch values[key] {166        case .double(let v)?: return v167        case .int(let v)?: return Double(v)168        default: return d169        }170    }171172    public func string(_ key: String, default d: String = "") -> String {173        if case .string(let v)? = values[key] { return v }174        return d175    }176177    /// `true` when the user (or a preset) set the key explicitly.178    public func has(_ key: String) -> Bool { values[key] != nil }179}180181// MARK: - Requests, context, results182183public struct ConversionRequest: Sendable {184    public let source: URL185    public let sourceFormat: FormatID186    public let destinationFormat: FormatID187    public let operation: String?188    public var options: ConversionOptions189    /// Further inputs for paths with `acceptsMultipleSources` (in order, after `source`).190    public var additionalSources: [URL]191    /// File name (without extension) the engine should give its output inside the work directory.192    public var outputBaseName: String193194    public init(source: URL, sourceFormat: FormatID, destinationFormat: FormatID, operation: String? = nil,195                options: ConversionOptions = .init(), additionalSources: [URL] = [], outputBaseName: String? = nil) {196        self.source = source; self.sourceFormat = sourceFormat; self.destinationFormat = destinationFormat197        self.operation = operation; self.options = options; self.additionalSources = additionalSources198        self.outputBaseName = outputBaseName ?? source.deletingPathExtension().lastPathComponent199    }200201    public var allSources: [URL] { [source] + additionalSources }202}203204public struct ProgressUpdate: Sendable {205    /// Measured completion in 0…1, or `nil` when the engine cannot measure it (the UI then shows an206    /// indeterminate indicator; a fraction is never invented).207    public let fraction: Double?208    public let message: String?209    public init(fraction: Double?, message: String? = nil) { self.fraction = fraction; self.message = message }210}211212public enum LogLevel: String, Sendable, Codable { case debug, info, warning, error }213214public struct ConversionWarning: Sendable, Hashable, Codable {215    public enum Severity: String, Sendable, Codable { case info, caution, dataLoss }216    public let severity: Severity217    /// Stable code, e.g. `alpha-flattened`, `formulas-dropped`, `animation-first-frame`.218    public let code: String219    public let message: String220    public init(_ severity: Severity, code: String, _ message: String) { self.severity = severity; self.code = code; self.message = message }221}222223/// Everything an engine needs while converting. Engines write only inside `workDirectory`; the core validates the224/// output and moves it to the destination atomically.225public struct ConversionContext: Sendable {226    public let workDirectory: URL227    public let progress: @Sendable (ProgressUpdate) -> Void228    public let log: @Sendable (LogLevel, String) -> Void229    public let warn: @Sendable (ConversionWarning) -> Void230231    public init(workDirectory: URL,232                progress: @escaping @Sendable (ProgressUpdate) -> Void = { _ in },233                log: @escaping @Sendable (LogLevel, String) -> Void = { _, _ in },234                warn: @escaping @Sendable (ConversionWarning) -> Void = { _ in }) {235        self.workDirectory = workDirectory; self.progress = progress; self.log = log; self.warn = warn236    }237238    /// Throws `CancellationError` when the job was cancelled. Engines call it inside their loops.239    public func checkCancellation() throws { try Task.checkCancellation() }240241    /// Path inside the work directory for an output named after the request.242    public func outputURL(for request: ConversionRequest, extension ext: String? = nil, suffix: String = "") -> URL {243        let format = FormatCatalog.format(request.destinationFormat)244        let e = ext ?? (format?.traits.contains(.directory) == true ? "" : format?.preferredExtension ?? request.destinationFormat.rawValue)245        let name = request.outputBaseName + suffix246        return e.isEmpty ? workDirectory.appendingPathComponent(name, isDirectory: true) : workDirectory.appendingPathComponent(name).appendingPathExtension(e)247    }248}249250public struct ConversionOutput: Sendable {251    /// Output items inside the work directory. One file for most paths; several files (pages, slides) or a single252    /// directory for extraction paths.253    public let files: [URL]254    /// Measured facts about the output (e.g. "width": "1920", "pages": "12"), shown in the job details.255    public let facts: [String: String]256    public init(files: [URL], facts: [String: String] = [:]) { self.files = files; self.facts = facts }257    public init(file: URL, facts: [String: String] = [:]) { self.files = [file]; self.facts = facts }258}259260// MARK: - Inspection (Smart Drop, Metadata Studio, Quality Lab)261262public struct InspectionField: Sendable, Hashable, Codable, Identifiable {263    /// English group ("General", "EXIF", "Color", "Video", "Audio", "Document"…).264    public let group: String265    public let key: String266    public let value: String267    public init(_ group: String, _ key: String, _ value: String) { self.group = group; self.key = key; self.value = value }268    public var id: String { group + "/" + key }269}270271/// What an engine actually read from a file. Every member is optional: a field that could not be read stays `nil`272/// and is shown as unavailable, never guessed.273public struct FileInspection: Sendable, Codable {274    public var format: FormatID275    public var fields: [InspectionField] = []276    public var pixelWidth: Int?277    public var pixelHeight: Int?278    public var durationSeconds: Double?279    public var pageCount: Int?280    public var frameCount: Int?281    public var hasAlpha: Bool?282    public var isAnimated: Bool?283    public var colorSpace: String?284    public var bitDepth: Int?285    public var videoCodec: String?286    public var audioCodec: String?287    public var frameRate: Double?288    public var bitRate: Int?289    public var sampleRate: Double?290    public var channels: Int?291    public var rowCount: Int?292    public var columnCount: Int?293    public var sheetNames: [String]?294    public var entryCount: Int?295    public var uncompressedSize: Int64?296    public var isEncrypted: Bool?297    public var hasMetadata: Bool?298    public var vertexCount: Int?299    public var faceCount: Int?300    public var notes: [String] = []301    public init(format: FormatID) { self.format = format }302}303304// MARK: - Validation305306public struct ValidationCheck: Sendable, Hashable, Codable {307    public let name: String308    public let passed: Bool309    public let detail: String310    public init(_ name: String, passed: Bool, _ detail: String = "") { self.name = name; self.passed = passed; self.detail = detail }311}312313// MARK: - Errors314315public enum ConversionError: Error, Sendable, LocalizedError, Equatable {316    case unsupportedPath(source: FormatID, destination: FormatID)317    case unreadableInput(String)318    case malformedInput(String)319    case encryptedInput(String)320    case engineUnavailable(String)321    case invalidOption(String)322    case limitExceeded(String)323    case toolFailed(tool: String, status: Int32, message: String)324    case outputInvalid(String)325    case writeFailed(String)326    case destinationExists(String)327    case internalError(String)328329    public var errorDescription: String? {330        switch self {331        case .unsupportedPath(let s, let d): "Converting \(s.rawValue.uppercased()) to \(d.rawValue.uppercased()) is not supported."332        case .unreadableInput(let m): "The file could not be read. \(m)"333        case .malformedInput(let m): "The file is damaged or not what its name says. \(m)"334        case .encryptedInput(let m): "The file is protected. \(m)"335        case .engineUnavailable(let m): "A conversion component is missing. \(m)"336        case .invalidOption(let m): "A setting is not valid. \(m)"337        case .limitExceeded(let m): "A safety limit was reached. \(m)"338        case .toolFailed(let t, let s, let m): "\(t) stopped with status \(s). \(m)"339        case .outputInvalid(let m): "The converted file failed verification. \(m)"340        case .writeFailed(let m): "The result could not be written. \(m)"341        case .destinationExists(let m): "A file already exists at the destination. \(m)"342        case .internalError(let m): m343        }344    }345}346347// MARK: - Engine protocol348349public enum EngineAvailability: Sendable, Equatable {350    case available351    /// A bundled component is missing; `reason` says which one.352    case unavailable(reason: String)353}354355/// A conversion engine. Implementations are stateless value types or actors; every method may be called356/// concurrently for different files.357public protocol ConversionEngine: Sendable {358    /// Stable identifier, e.g. `image`, `vector`, `media`, `documents`, `pdf`, `data`, `archive`.359    var id: String { get }360    /// English display name.361    var displayName: String { get }362    /// The real conversion paths of the engine. A path must be listed only if `convert` implements it and a test363    /// in the engine's test target exercises it.364    var paths: [ConversionPath] { get }365    /// Formats the engine can `inspect` even when it offers no conversion for them.366    var inspectableFormats: Set<FormatID> { get }367    /// Whether the engine's bundled components are present.368    func availability() -> EngineAvailability369    /// Settings offered for a path.370    func options(for path: ConversionPath) -> [OptionDescriptor]371    /// Reads real properties and metadata of a file.372    func inspect(_ url: URL, format: FormatID) async throws -> FileInspection373    /// Warnings specific to this file and these options (beyond `path.limitations`), computed before converting.374    func preflight(_ request: ConversionRequest, inspection: FileInspection?) -> [ConversionWarning]375    /// Performs the conversion, writing inside `context.workDirectory`. Must honour cancellation.376    func convert(_ request: ConversionRequest, context: ConversionContext) async throws -> ConversionOutput377    /// Re-opens the output and checks it (decodable, expected dimensions / duration / rows…). The core adds the378    /// generic checks (exists, not empty, detected format).379    func validate(_ output: ConversionOutput, request: ConversionRequest, source: FileInspection?) async throws -> [ValidationCheck]380}381382public extension ConversionEngine {383    var inspectableFormats: Set<FormatID> { Set(paths.map(\.source)) }384    func availability() -> EngineAvailability { .available }385    func options(for path: ConversionPath) -> [OptionDescriptor] { [] }386    func preflight(_ request: ConversionRequest, inspection: FileInspection?) -> [ConversionWarning] { [] }387    func validate(_ output: ConversionOutput, request: ConversionRequest, source: FileInspection?) async throws -> [ValidationCheck] { [] }388389    /// The declared path matching a request, if any.390    func path(for request: ConversionRequest) -> ConversionPath? {391        paths.first { $0.source == request.sourceFormat && $0.destination == request.destinationFormat && $0.operation == request.operation }392    }393}394
Files main
Menu

Theme