Repository Public License
1// ORIX Convert — Packages/ORIXConvertCore/Sources/ConvertCore/Presets.swift2// Description: Conversion presets: named (source scope, destination, operation, options) tuples. Built-in presets3// are registered by the engines' owners at start-up (none ship in the core); user presets are persisted4// as JSON in Application Support and can be imported and exported.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation78public struct ConversionPreset: Sendable, Hashable, Codable, Identifiable {9 /// What a preset applies to.10 public enum Scope: Sendable, Hashable, Codable {11 case any12 case category(FormatCategory)13 case format(FormatID)1415 public func matches(_ format: FormatID) -> Bool {16 switch self {17 case .any: true18 case .category(let category): FormatCatalog.format(format)?.category == category19 case .format(let id): id == format20 }21 }22 }2324 public var id: UUID25 public var name: String26 public var summary: String27 public var source: Scope28 public var destinationFormat: FormatID29 public var operation: String?30 public var options: ConversionOptions31 /// Registered by the app, not editable by the user.32 public var isBuiltIn: Bool3334 public init(id: UUID = UUID(), name: String, summary: String = "", source: Scope, destinationFormat: FormatID, operation: String? = nil,35 options: ConversionOptions = .init(), isBuiltIn: Bool = false) {36 self.id = id; self.name = name; self.summary = summary; self.source = source; self.destinationFormat = destinationFormat37 self.operation = operation; self.options = options; self.isBuiltIn = isBuiltIn38 }39}4041public enum PresetError: Error, Sendable, LocalizedError, Equatable {42 case notFound43 case builtInIsReadOnly44 case invalidFile(String)45 case storage(String)4647 public var errorDescription: String? {48 switch self {49 case .notFound: "The preset no longer exists."50 case .builtInIsReadOnly: "Built-in presets cannot be changed. Duplicate it first."51 case .invalidFile(let m): "The preset file could not be read. \(m)"52 case .storage(let m): "Presets could not be saved. \(m)"53 }54 }55}5657/// On-disk and exchange format of presets.58struct PresetFile: Codable {59 var version = 160 var presets: [ConversionPreset]61}6263/// Stores user presets (JSON, written atomically) and holds the built-in presets registered for this run.64public actor PresetStore {65 public nonisolated let fileURL: URL66 private var builtIns: [ConversionPreset] = []67 private var user: [ConversionPreset] = []68 /// Why the stored file could not be loaded, if it could not (the file is left untouched until the next save).69 public private(set) var loadError: String?7071 public init(fileURL: URL = AppPaths.presetsFile) {72 self.fileURL = fileURL73 if let data = try? Data(contentsOf: fileURL) {74 do {75 user = try JSONDecoder().decode(PresetFile.self, from: data).presets.map { var p = $0; p.isBuiltIn = false; p.options = p.options.redactingSecrets(); return p }76 } catch {77 loadError = error.localizedDescription78 }79 }80 }8182 /// Registers built-in presets (the core ships none). Presets with an identifier already registered are replaced.83 public func registerBuiltIns(_ presets: [ConversionPreset]) {84 for var preset in presets {85 preset.isBuiltIn = true86 if let index = builtIns.firstIndex(where: { $0.id == preset.id }) { builtIns[index] = preset } else { builtIns.append(preset) }87 }88 }8990 public var builtInPresets: [ConversionPreset] { builtIns }91 public var userPresets: [ConversionPreset] { user }92 /// Built-in presets, then user presets.93 public var all: [ConversionPreset] { builtIns + user }9495 public func preset(id: UUID) -> ConversionPreset? { all.first { $0.id == id } }9697 /// Presets whose scope covers `format`.98 public func presets(for format: FormatID) -> [ConversionPreset] { all.filter { $0.source.matches(format) } }99100 /// Adds a user preset (a fresh identifier is given when the identifier is already taken).101 @discardableResult102 public func add(_ preset: ConversionPreset) throws -> ConversionPreset {103 var preset = preset104 preset.isBuiltIn = false105 preset.options = preset.options.redactingSecrets()106 if all.contains(where: { $0.id == preset.id }) { preset.id = UUID() }107 user.append(preset)108 try save()109 return preset110 }111112 public func update(_ preset: ConversionPreset) throws {113 if builtIns.contains(where: { $0.id == preset.id }) { throw PresetError.builtInIsReadOnly }114 guard let index = user.firstIndex(where: { $0.id == preset.id }) else { throw PresetError.notFound }115 var preset = preset116 preset.isBuiltIn = false117 preset.options = preset.options.redactingSecrets()118 user[index] = preset119 try save()120 }121122 public func delete(id: UUID) throws {123 if builtIns.contains(where: { $0.id == id }) { throw PresetError.builtInIsReadOnly }124 guard let index = user.firstIndex(where: { $0.id == id }) else { throw PresetError.notFound }125 user.remove(at: index)126 try save()127 }128129 /// Copies any preset (built-in included) into an editable user preset.130 @discardableResult131 public func duplicate(id: UUID, name: String? = nil) throws -> ConversionPreset {132 guard var copy = preset(id: id) else { throw PresetError.notFound }133 copy.id = UUID()134 copy.name = name ?? copy.name + " copy"135 return try add(copy)136 }137138 /// JSON for the given presets (all user presets when `ids` is `nil`).139 public func exportData(ids: [UUID]? = nil) throws -> Data {140 let selected = ids.map { wanted in all.filter { wanted.contains($0.id) } } ?? user141 let encoder = JSONEncoder()142 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]143 do { return try encoder.encode(PresetFile(presets: selected)) } catch { throw PresetError.storage(error.localizedDescription) }144 }145146 /// Imports presets from exported JSON as user presets, with new identifiers. Returns the imported presets.147 @discardableResult148 public func importData(_ data: Data) throws -> [ConversionPreset] {149 let file: PresetFile150 do { file = try JSONDecoder().decode(PresetFile.self, from: data) } catch { throw PresetError.invalidFile(error.localizedDescription) }151 var imported: [ConversionPreset] = []152 for var preset in file.presets.prefix(10_000) {153 preset.id = UUID()154 preset.isBuiltIn = false155 preset.options = preset.options.redactingSecrets()156 user.append(preset)157 imported.append(preset)158 }159 try save()160 return imported161 }162163 private func save() throws {164 do {165 try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)166 let encoder = JSONEncoder()167 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]168 try encoder.encode(PresetFile(presets: user)).write(to: fileURL, options: .atomic)169 loadError = nil170 } catch {171 throw PresetError.storage(error.localizedDescription)172 }173 }174}175