SPB Git

Repository Public License

MetadataModel.swift 11.4 KB 212 lines swift

1// ORIX Convert — App/Sources/Features/Metadata/MetadataModel.swift2// Description: Metadata Studio state: the inspected file, its fields grouped and searchable, export as text / JSON,3//              and the metadata actions discovered from the engines' real paths and options (nothing hard-coded).4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import AppKit6import ConvertCore7import Observation89/// A metadata operation an engine really offers for the inspected format.10struct MetadataAction: Identifiable, Sendable {11    enum Kind: Sendable { case remove, edit }12    let kind: Kind13    let path: ConversionPath14    /// Options shown in the sheet (the metadata ones; a source password when the path has one).15    let descriptors: [OptionDescriptor]16    /// Values applied without asking (the "strip" toggles for a removal).17    let presetValues: [String: OptionValue]18    var id: String { path.id + (kind == .remove ? "|remove" : "|edit") }19    var title: String { kind == .remove ? L("Remove metadata…") : L("Edit metadata…") }20}2122/// Fields of an inspection, grouped in the engine's order.23struct FieldGroup: Identifiable, Sendable {24    let name: String25    var fields: [InspectionField]26    var id: String { name }27}2829enum FieldGrouping {30    static func groups(_ fields: [InspectionField], matching search: String = "") -> [FieldGroup] {31        let needle = search.trimmingCharacters(in: .whitespaces).lowercased()32        var order: [String] = []33        var map: [String: [InspectionField]] = [:]34        for field in fields {35            if !needle.isEmpty, !LE(field.key).lowercased().contains(needle), !field.key.lowercased().contains(needle),36               !field.value.lowercased().contains(needle), !field.group.lowercased().contains(needle) { continue }37            if map[field.group] == nil { order.append(field.group) }38            map[field.group, default: []].append(field)39        }40        return order.map { FieldGroup(name: $0, fields: map[$0] ?? []) }41    }4243    /// Typed facts of an inspection as rows; a fact the engine did not read is `nil` (shown as "—").44    static func typedFacts(_ i: FileInspection) -> [(key: String, value: String?)] {45        func yesNo(_ value: Bool?) -> String? { value.map { $0 ? L("Yes") : L("No") } }46        var rows: [(String, String?)] = []47        let category = i.format.category48        let visual: Set<FormatCategory> = [.image, .vector, .video]49        if visual.contains(category) {50            rows.append((L("Dimensions"), i.pixelWidth.flatMap { w in i.pixelHeight.map { "\(Fmt.count(w)) × \(Fmt.count($0)) px" } }))51        }52        if [.image, .vector].contains(category) {53            rows.append((L("Transparency"), yesNo(i.hasAlpha)))54            rows.append((L("Animated"), yesNo(i.isAnimated)))55            rows.append((L("Colour space"), i.colorSpace))56            rows.append((L("Bit depth"), i.bitDepth.map { Fmt.count($0) }))57        }58        if [.video, .audio].contains(category) {59            rows.append((L("Duration"), i.durationSeconds.map { Fmt.duration($0) }))60            rows.append((L("Bit rate"), i.bitRate.map { L("%@ kbit/s", Fmt.count($0 / 1000)) }))61            rows.append((L("Audio codec"), i.audioCodec))62            rows.append((L("Sample rate"), i.sampleRate.map { L("%@ Hz", Fmt.count(Int($0))) }))63            rows.append((L("Channels"), i.channels.map { Fmt.count($0) }))64        }65        if category == .video {66            rows.append((L("Video codec"), i.videoCodec))67            rows.append((L("Frame rate"), i.frameRate.map { $0.formatted(.number.precision(.fractionLength(0...3))) + " fps" }))68        }69        if [.pdf, .document, .presentation, .ebook].contains(category) { rows.append((L("Pages"), i.pageCount.map { Fmt.count($0) })) }70        if [.spreadsheet, .data].contains(category) {71            rows.append((L("Rows"), i.rowCount.map { Fmt.count($0) }))72            rows.append((L("Columns"), i.columnCount.map { Fmt.count($0) }))73            rows.append((L("Sheets"), i.sheetNames.map { $0.joined(separator: ", ") }))74        }75        if category == .archive {76            rows.append((L("Entries"), i.entryCount.map { Fmt.count($0) }))77            rows.append((L("Uncompressed size"), i.uncompressedSize.map { Fmt.bytes($0) }))78        }79        if category == .model3D {80            rows.append((L("Vertices"), i.vertexCount.map { Fmt.count($0) }))81            rows.append((L("Faces"), i.faceCount.map { Fmt.count($0) }))82        }83        rows.append((L("Protected"), yesNo(i.isEncrypted)))84        rows.append((L("Has metadata"), yesNo(i.hasMetadata)))85        return rows.map { (key: $0.0, value: $0.1) }86    }8788    /// The generic "File" group, from the typed file-system facts, formatted for the user's locale.89    static func fileRows(_ file: InspectedFile) -> [(key: String, value: String?)] {90        let facts = file.facts, detection = file.detection91        var rows: [(String, String?)] = [92            (L("Format"), detection.format?.displayName ?? L("Unknown format")),93            (L("Detection"), detection.confidence.title + " — " + detection.evidence),94        ]95        if let encoding = detection.textEncoding { rows.append((L("Text encoding"), encoding.rawValue)) }96        rows.append((L("Size"), facts.size.map { "\(Fmt.bytes($0)) (\(L("%@ bytes", Fmt.count(Int($0)))))" }))97        rows.append((L("Created"), facts.created.map { Fmt.date($0) }))98        rows.append((L("Modified"), facts.modified.map { Fmt.date($0) }))99        rows.append((L("Permissions"), facts.posixPermissions.map { String($0, radix: 8) }))100        rows.append((L("Type identifier"), facts.uti))101        rows.append((L("Quarantine attribute"), facts.isQuarantined ? L("Present") : L("Absent")))102        rows.append((L("Download origin attribute"), facts.hasWhereFroms ? L("Present") : L("Absent")))103        return rows.map { (key: $0.0, value: $0.1) }104    }105106    static func text(for file: InspectedFile) -> String {107        var lines = [file.url.path, ""]108        for row in typedFacts(file.inspection) { lines.append("\(row.key): \(row.value ?? "—")") }109        for group in groups(file.inspection.fields) {110            lines.append("")111            lines.append("[\(LE(group.name))]")112            for field in group.fields { lines.append("\(LE(field.key)): \(LEValue(field.value))") }113        }114        for note in file.inspection.notes { lines.append("• \(LE(note))") }115        return lines.joined(separator: "\n")116    }117118    static func json(for file: InspectedFile) -> String {119        struct Export: Encodable { let path: String; let detectedFormat: String?; let confidence: String; let evidence: String; let inspection: FileInspection }120        let encoder = JSONEncoder()121        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]122        let export = Export(path: file.url.path, detectedFormat: file.detection.format?.rawValue, confidence: file.detection.confidence.rawValue,123                            evidence: file.detection.evidence, inspection: file.inspection)124        return (try? encoder.encode(export)).map { String(decoding: $0, as: UTF8.self) } ?? "{}"125    }126}127128@Observable final class MetadataModel {129    @ObservationIgnored unowned let app: AppModel130    var file: InspectedFile?131    var isLoading = false132    var search = ""133    var actions: [MetadataAction] = []134    var activeAction: MetadataAction?135    var notice: String?136    /// Preview of the inspected file (loaded after the inspection, bounded, cancellable).137    let preview = FilePreviewModel()138139    init(app: AppModel) { self.app = app }140141    func load(_ url: URL) async {142        isLoading = true143        notice = nil144        let inspector = app.manager.inspector145        let inspected = await Task.detached(priority: .userInitiated) { await inspector.inspect(url) }.value146        file = inspected147        actions = Self.actions(for: inspected.detection.format, registry: app.registry)148        isLoading = false149        preview.load(url, format: inspected.detection.format, inspection: inspected.inspection)150    }151152    func choose() {153        let panel = NSOpenPanel()154        panel.canChooseFiles = true155        panel.canChooseDirectories = false156        panel.allowsMultipleSelection = false157        panel.prompt = L("Inspect")158        if panel.runModal() == .OK, let url = panel.url { Task { await load(url) } }159    }160161    func clear() { file = nil; actions = []; search = ""; notice = nil; preview.clear() }162163    /// Finds metadata operations among the real paths of the format: an option group named "Metadata", option keys164    /// starting with `metadata.` or containing `strip`, or an operation whose identifier mentions metadata.165    nonisolated static func actions(for format: FormatID?, registry: FormatRegistry) -> [MetadataAction] {166        guard let format else { return [] }167        func isMetadataOption(_ o: OptionDescriptor) -> Bool {168            o.id.hasPrefix("metadata.") || o.id.contains("strip") || o.id.contains("gps") || o.id.contains("exif") || o.id.hasPrefix("tag.") || o.id.hasPrefix("tags.") || o.group.lowercased() == "metadata" || o.group.lowercased() == "tags"169        }170        func isStrip(_ o: OptionDescriptor) -> Bool {171            if case .toggle = o.kind { return o.id.contains("strip") || o.id.contains("remove") }172            return false173        }174        // Same-format paths only: the file keeps its format, only its metadata changes.175        let candidates = registry.paths(from: format, to: format).sorted { a, b in176            let am = a.operation?.contains("metadata") == true, bm = b.operation?.contains("metadata") == true177            return am != bm ? am : ConversionCapabilityResolver.prefers(a, over: b)178        }179        var remove: MetadataAction?180        var edit: MetadataAction?181        for path in candidates {182            guard let engine = registry.engine(id: path.engine) else { continue }183            let options = engine.options(for: path)184            let metadataOptions = options.filter(isMetadataOption)185            guard !metadataOptions.isEmpty else { continue }186            let secrets = options.filter { ConversionOptions.isSecretKey($0.id) && !$0.id.contains("output") }187            let strips = metadataOptions.filter(isStrip)188            if remove == nil, !strips.isEmpty {189                remove = MetadataAction(kind: .remove, path: path, descriptors: strips + secrets,190                                        presetValues: Dictionary(uniqueKeysWithValues: strips.map { ($0.id, OptionValue.bool(true)) }))191            }192            let editable = metadataOptions.filter { !isStrip($0) }193            if edit == nil, !editable.isEmpty {194                edit = MetadataAction(kind: .edit, path: path, descriptors: metadataOptions + secrets, presetValues: [:])195            }196        }197        return [remove, edit].compactMap { $0 }198    }199200    func run(_ action: MetadataAction, values: [String: OptionValue]) {201        guard let file else { return }202        var options = action.presetValues203        for (key, value) in values { options[key] = value }204        var destination = app.defaultDestination205        // Never touches the original: the result is written next to it under a new name.206        destination.conflictPolicy = .rename207        app.enqueue(ConversionJobRequest(sources: [file.url], sourceFormat: action.path.source, destinationFormat: action.path.destination,208                                         operation: action.path.operation, options: ConversionOptions(options), engineID: action.path.engine,209                                         destination: destination))210    }211}212
Files main
Menu

Theme