diff --git a/Sources/Lichtkasten/LichtkastenApp.swift b/Sources/Lichtkasten/LichtkastenApp.swift index be1616e..ded942b 100644 --- a/Sources/Lichtkasten/LichtkastenApp.swift +++ b/Sources/Lichtkasten/LichtkastenApp.swift @@ -77,7 +77,8 @@ struct AppCommands: Commands { @ObservedObject var state: AppState var body: some Commands { - CommandGroup(after: .newItem) { + // Replaces "New Window" (⌘N) – ⌘N is "Save & previous" in the IPTC window like in PM. + CommandGroup(replacing: .newItem) { Button("Ordner öffnen …") { state.chooseFolder() }.keyboardShortcut("o") Button("Neuer Tab …") { state.newTab() }.keyboardShortcut("t") Button("Ingest (von Karte kopieren) …") { state.showIngest = true }.keyboardShortcut("g") @@ -125,6 +126,7 @@ struct AppCommands: Commands { Button("Vorlagen verwalten …") { state.showTemplateManager = true }.keyboardShortcut("t", modifiers: [.command, .shift]) Divider() Button("Code-Ersetzungen …") { state.openWindow("codes") }.keyboardShortcut("k", modifiers: [.command, .shift]) + Button("Photo-Mechanic-Einstellungen importieren (alle) …") { state.showPMImport = true } Button("Photo-Mechanic-Vorlage importieren …") { state.importPMTemplate() } } CommandMenu("Ausgabe") { diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index f5ab5b2..0984249 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -87,6 +87,7 @@ final class AppState: ObservableObject { @Published var showTemplatePicker = false @Published var showTemplateManager = false @Published var showIngest = false + @Published var showPMImport = false @Published var windowRequest: WindowRequest? /// Card(s) that triggered the ingest window. @Published var pendingIngestSources: [URL] = [] @@ -682,9 +683,21 @@ final class AppState: ObservableObject { Task { await applyIPTCAndWait(draft, fields: fields, to: targets) } } + /// Remembers used values for the ▾ list of each field (most recent first, like PM's recent values). + func rememberFieldValues(_ values: IPTCValues, fields: [IPTCField]) { + for f in fields where f.kind != .list && f.kind != .multiline { + guard let v = values.text[f.id]?.trimmingCharacters(in: .whitespaces), !v.isEmpty, !v.contains("{") else { continue } + var list = settings.fieldLists[f.id] ?? [] + list.removeAll { $0 == v } + list.insert(v, at: 0) + settings.fieldLists[f.id] = Array(list.prefix(60)) + } + } + @discardableResult func applyIPTCAndWait(_ draft: IPTCValues, fields: [IPTCField], to targets: [PhotoItem]) async -> Bool { guard !targets.isEmpty, !fields.isEmpty, let w = writer else { return false } + rememberFieldValues(draft, fields: fields) statusText = "Schreibe IPTC in \(targets.count) Bild(er) …" var count = 0 for t in targets { diff --git a/Sources/Lichtkasten/Services/Persistence.swift b/Sources/Lichtkasten/Services/Persistence.swift index 3190e2c..401cba2 100644 --- a/Sources/Lichtkasten/Services/Persistence.swift +++ b/Sources/Lichtkasten/Services/Persistence.swift @@ -83,6 +83,8 @@ struct AppSettings: Codable { var recentFolders: [String] = [] var favoriteFolders: [String] = [] var lastTemplateID: UUID? + /// PM ▾ drop-down lists per IPTC field (imported from PM + recently used values) + var fieldLists: [String: [String]] = [:] init() {} @@ -105,6 +107,7 @@ struct AppSettings: Codable { recentFolders = (try? c.decode([String].self, forKey: .recentFolders)) ?? d.recentFolders favoriteFolders = (try? c.decode([String].self, forKey: .favoriteFolders)) ?? d.favoriteFolders lastTemplateID = try? c.decode(UUID.self, forKey: .lastTemplateID) + fieldLists = (try? c.decode([String: [String]].self, forKey: .fieldLists)) ?? [:] } } diff --git a/Sources/Lichtkasten/Views/BatchEditWindow.swift b/Sources/Lichtkasten/Views/BatchEditWindow.swift index d1eb84e..0126595 100644 --- a/Sources/Lichtkasten/Views/BatchEditWindow.swift +++ b/Sources/Lichtkasten/Views/BatchEditWindow.swift @@ -30,7 +30,7 @@ struct BatchEditWindow: View { .padding(12) Divider() ScrollView { - PMMetadataForm(texts: $texts, columns: 2, mixed: mixed, applied: $applied, codes: state.codes) + PMMetadataForm(texts: $texts, columns: 2, mixed: mixed, applied: $applied, codes: state.codes, fieldLists: state.settings.fieldLists) .padding(14) } Divider() diff --git a/Sources/Lichtkasten/Views/ContentView.swift b/Sources/Lichtkasten/Views/ContentView.swift index 587691d..e292cc1 100644 --- a/Sources/Lichtkasten/Views/ContentView.swift +++ b/Sources/Lichtkasten/Views/ContentView.swift @@ -41,6 +41,7 @@ struct ContentView: View { .sheet(isPresented: $state.showTemplatePicker) { TemplatePickerSheet() } .sheet(isPresented: $state.showTemplateManager) { TemplateManagerView().frame(minWidth: 1280, minHeight: 760) } .sheet(isPresented: $state.showIngest) { IngestView() } + .sheet(isPresented: $state.showPMImport) { PMImportSheet() } .alert(item: $state.alert) { a in Alert(title: Text(a.title), message: Text(a.message), dismissButton: .default(Text("OK"))) } diff --git a/Sources/Lichtkasten/Views/IPTCForm.swift b/Sources/Lichtkasten/Views/IPTCForm.swift index 42be2c2..7664a2e 100644 --- a/Sources/Lichtkasten/Views/IPTCForm.swift +++ b/Sources/Lichtkasten/Views/IPTCForm.swift @@ -43,6 +43,8 @@ struct PMMetadataForm: View { /// PM checkboxes; nil = no checkboxes (info window). var applied: Binding>? = nil var codes: CodeReplacements? = nil + /// ▾ lists (PM drop-down values) + var fieldLists: [String: [String]] = [:] var onEdit: (String) -> Void = { _ in } /// Extra rows (e.g. "Image Preferences → Label") inserted after Image Content. var extraAfterContent: AnyView? = nil @@ -72,7 +74,7 @@ struct PMMetadataForm: View { VStack(alignment: .leading, spacing: 6) { PMSectionHeader(title: section.rawValue) ForEach(IPTCField.all.filter { $0.section == section }) { field in - PMFieldRow(field: field, text: binding(field), codes: codes, + PMFieldRow(field: field, text: binding(field), codes: codes, listValues: fieldLists[field.id] ?? [], isMixed: mixed.contains(field.id) && !dirty.contains(field.id), isDirty: dirty.contains(field.id), applied: appliedBinding(field)) @@ -103,6 +105,7 @@ struct PMFieldRow: View { let field: IPTCField @Binding var text: String var codes: CodeReplacements? + var listValues: [String] = [] let isMixed: Bool let isDirty: Bool let applied: Binding? @@ -126,9 +129,18 @@ struct PMFieldRow: View { .font(.system(size: 12)) .foregroundStyle(isDirty ? Color.accentColor : .primary) .help(field.label) - if let max = field.iimMaxBytes, text.utf8.count > max, !text.contains("{") { - Text("\(text.utf8.count)/\(max)").font(.caption2.monospacedDigit()).foregroundStyle(.red) - .help("IPTC-IIM-Limit in Bytes – Agenturen kürzen längere Werte.") + // IIM limit: for keywords etc. it applies to each entry, not to the whole field. + if let max = field.iimMaxBytes, !text.contains("{") { + if field.kind == .list { + let long = IPTCValues.splitList(text).filter { $0.utf8.count > max } + if !long.isEmpty { + Text("\(long.count)× > \(max)").font(.caption2.monospacedDigit()).foregroundStyle(.red) + .help("Diese Einträge sind länger als \(max) Bytes (IIM-Limit pro Eintrag): " + long.joined(separator: ", ")) + } + } else if text.utf8.count > max { + Text("\(text.utf8.count)/\(max)").font(.caption2.monospacedDigit()).foregroundStyle(.red) + .help("IPTC-IIM-Limit in Bytes – Agenturen kürzen längere Werte.") + } } } .frame(width: 150, alignment: .leading) @@ -153,6 +165,20 @@ struct PMFieldRow: View { .frame(maxWidth: .infinity) Menu { + if !listValues.isEmpty { + Section("Werte") { + ForEach(listValues.prefix(40), id: \.self) { v in + Button(v) { + if field.kind == .list { + let items = IPTCValues.splitList(text) + if !items.contains(v) { text = (items + [v]).joined(separator: ", ") } + } else { + text = v + } + } + } + } + } Section("Variablen") { ForEach(VariableExpander.documented, id: \.0) { v in Button("\(v.0) – \(v.1)") { text += v.0 } diff --git a/Sources/Lichtkasten/Views/IPTCInfoWindow.swift b/Sources/Lichtkasten/Views/IPTCInfoWindow.swift index d38ef20..29cda2e 100644 --- a/Sources/Lichtkasten/Views/IPTCInfoWindow.swift +++ b/Sources/Lichtkasten/Views/IPTCInfoWindow.swift @@ -11,6 +11,8 @@ struct IPTCInfoWindow: View { @State private var image: NSImage? @State private var saving = false @AppStorage("iptcWindowUploadTarget") private var uploadTarget = "" + @State private var window: NSWindow? + @State private var arrowMonitor: Any? private var item: PhotoItem? { state.cursorItem } @@ -18,7 +20,7 @@ struct IPTCInfoWindow: View { HSplitView { VStack(spacing: 0) { ScrollView { - PMMetadataForm(texts: $texts, columns: 1, dirty: dirty, codes: state.codes, + PMMetadataForm(texts: $texts, columns: 1, dirty: dirty, codes: state.codes, fieldLists: state.settings.fieldLists, onEdit: { dirty.insert($0) }, extraAfterContent: AnyView(labelSection)) .padding(14) } @@ -42,7 +44,14 @@ struct IPTCInfoWindow: View { sidePanel.frame(minWidth: 380, idealWidth: 520) } .navigationTitle(item.map { "IPTC-Info – \($0.filename)" } ?? "IPTC-Info") - .onAppear { load(force: true) } + .background(WindowAccessor { window = $0 }) + .onAppear { + load(force: true) + installArrowKeys() + } + .onDisappear { + if let m = arrowMonitor { NSEvent.removeMonitor(m); arrowMonitor = nil } + } .onChange(of: state.cursorID) { _, _ in load(force: true) } .onReceive(state.$items) { _ in if dirty.isEmpty { DispatchQueue.main.async { load(force: false) } } } .task(id: item.map { state.previewURL(for: $0) }) { await loadImage() } @@ -101,14 +110,14 @@ struct IPTCInfoWindow: View { Grid(horizontalSpacing: 8, verticalSpacing: 8) { GridRow { - Button("Speichern & ←") { saveAndMove(-1) } - .keyboardShortcut(.leftArrow, modifiers: [.command, .option]) - Button("Speichern & →") { saveAndMove(1) } - .keyboardShortcut(.rightArrow, modifiers: [.command, .option]) + Button("Speichern & ← (⌘N)") { saveAndMove(-1) } + .keyboardShortcut("n", modifiers: .command) + Button("Speichern & → (⌘B)") { saveAndMove(1) } + .keyboardShortcut("b", modifiers: .command) } GridRow { - Button("←") { move(-1) } - Button("→") { move(1) } + Button("←") { move(-1) }.help("Ohne Speichern zurück (Pfeil links)") + Button("→") { move(1) }.help("Ohne Speichern weiter (Pfeil rechts)") } GridRow { Button("Speichern, Hochladen & →") { saveUploadAndMove() } @@ -180,6 +189,23 @@ struct IPTCInfoWindow: View { return ok } + /// ←/→ = previous/next image WITHOUT saving (when no text field is being edited); + /// ⌃←/⌃→ work even while typing. + private func installArrowKeys() { + guard arrowMonitor == nil else { return } + arrowMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in + guard let w = window, event.window === w, w.attachedSheet == nil else { return event } + let mods = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + guard event.keyCode == 123 || event.keyCode == 124 else { return event } + let typing = w.firstResponder is NSText + let ctrlOnly = mods == [.control] || mods == [.control, .function] || mods == [.function, .control] + let plain = mods.subtracting([.function, .numericPad]).isEmpty + guard ctrlOnly || (plain && !typing) else { return event } + move(event.keyCode == 123 ? -1 : 1) + return nil + } + } + private func move(_ delta: Int) { dirty = [] state.iptcNavigate(delta) diff --git a/Sources/Lichtkasten/Views/PMImportSheet.swift b/Sources/Lichtkasten/Views/PMImportSheet.swift new file mode 100644 index 0000000..5154f1c --- /dev/null +++ b/Sources/Lichtkasten/Views/PMImportSheet.swift @@ -0,0 +1,176 @@ +import SwiftUI +import LichtkastenCore + +/// IPTC → "Photo-Mechanic-Einstellungen importieren …": scans PM's folders and imports everything at once. +struct PMImportSheet: View { + @EnvironmentObject var state: AppState + @Environment(\.dismiss) private var dismiss + @State private var scan: PMSettingsScan? + @State private var scanning = false + @State private var roots: [URL] = PMSettingsImporter.defaultRoots + @State private var pickTemplates: Set = [] + @State private var pickCodes: Set = [] + @State private var importLists = true + @State private var importIngest = true + @State private var importDelimiter = true + @State private var result = "" + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Photo-Mechanic-Einstellungen importieren").font(.title3.bold()) + Text("Durchsucht: " + (roots.isEmpty ? "– keine PM-Ordner gefunden –" : roots.map(\.path).joined(separator: ", "))) + .font(.caption).foregroundStyle(.secondary).lineLimit(3) + HStack { + Button("Ordner oder Datei hinzufügen …") { addRoot() } + .help("z. B. exportierte PM-Einstellungen, einen Ordner mit .snap-Vorlagen oder Code-TXT-Dateien") + Button("Erneut suchen") { runScan() } + if scanning { ProgressView().controlSize(.small) } + } + + if let scan { + if scan.isEmpty { + Text("Nichts gefunden. Wähle den Ordner mit deinen PM-Vorlagen (.snap) bzw. die exportierten Einstellungen über „Ordner oder Datei hinzufügen …“.") + .foregroundStyle(.orange) + } + List { + if !scan.templates.isEmpty { + Section("IPTC-Vorlagen (\(scan.templates.count))") { + ForEach(scan.templates) { t in + Toggle(isOn: bind(t.id, in: $pickTemplates)) { + VStack(alignment: .leading) { + Text(t.template.name) + Text(t.origin).font(.caption2).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) + } + } + } + } + } + if !scan.codeFiles.isEmpty { + Section("Code-Ersetzungsdateien (\(scan.codeFiles.count)) → werden Teams") { + ForEach(scan.codeFiles) { c in + Toggle(isOn: bind(c.id, in: $pickCodes)) { + HStack { + Text(c.url.lastPathComponent) + if !c.exists { Text("Datei fehlt").font(.caption).foregroundStyle(.red) } + if !c.enabled { Text("in PM deaktiviert").font(.caption).foregroundStyle(.secondary) } + } + } + .disabled(!c.exists) + } + } + } + if scan.codeDelimiter != nil || scan.codeDefaultReplacement != nil { + Section("Code-Optionen") { + Toggle("Trennzeichen „\(scan.codeDelimiter ?? "–")“, Standard-Ersetzung „\(scan.codeDefaultReplacement ?? "")“", isOn: $importDelimiter) + } + } + if !scan.fieldLists.isEmpty { + Section("Feld-Listen (▾)") { + Toggle(scan.fieldLists.map { "\(IPTCField.byID[$0.key]?.pmLabel ?? $0.key): \($0.value.count)" }.sorted().joined(separator: " · "), + isOn: $importLists) + } + } + if scan.renamePattern != nil || scan.sequence != nil || scan.ingestFolderPattern != nil { + Section("Ingest") { + Toggle("Umbenennen „\(scan.renamePattern ?? "–")“, Sequenz \(scan.sequence.map(String.init) ?? "–"), Ordner „\(scan.ingestFolderPattern ?? "–")“", + isOn: $importIngest) + } + } + } + .frame(minHeight: 300) + DisclosureGroup("Gefundene Einstellungs-Schlüssel (\(scan.keyReport.count)) – zum Verfeinern an Claude schicken") { + HStack { + Text("\(scan.scannedFiles.count) Dateien gelesen. Nur Schlüsselnamen, keine Werte/Passwörter.").font(.caption) + Spacer() + Button("In Zwischenablage kopieren") { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString((scan.scannedFiles + [""] + scan.keyReport).joined(separator: "\n"), forType: .string) + } + } + } + } else if scanning { + Text("Suche PM-Einstellungen …").foregroundStyle(.secondary) + } + + if !result.isEmpty { Text(result).font(.callout).foregroundStyle(.green) } + HStack { + Spacer() + Button("Schließen") { dismiss() }.keyboardShortcut(.cancelAction) + Button("Importieren") { doImport() } + .keyboardShortcut(.defaultAction) + .buttonStyle(.borderedProminent) + .disabled(scan == nil || scan?.isEmpty == true) + } + } + .padding(18) + .frame(width: 760, height: 640) + .onAppear(perform: runScan) + } + + private func bind(_ id: UUID, in set: Binding>) -> Binding { + Binding(get: { set.wrappedValue.contains(id) }, + set: { on in if on { set.wrappedValue.insert(id) } else { set.wrappedValue.remove(id) } }) + } + + private func addRoot() { + let p = NSOpenPanel() + p.canChooseDirectories = true; p.canChooseFiles = true; p.allowsMultipleSelection = true + p.showsHiddenFiles = true + p.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library") + if p.runModal() == .OK { roots += p.urls; runScan() } + } + + private func runScan() { + scanning = true + let r = roots + Task { + let s = await Task.detached(priority: .userInitiated) { PMSettingsImporter.scan(roots: r) }.value + scan = s + pickTemplates = Set(s.templates.map(\.id)) + pickCodes = Set(s.codeFiles.filter(\.exists).map(\.id)) + scanning = false + } + } + + private func doImport() { + guard let scan else { return } + var notes: [String] = [] + // templates (same name → replaced) + var tCount = 0 + for t in scan.templates where pickTemplates.contains(t.id) { + state.templates.removeAll { $0.name == t.template.name } + state.templates.append(t.template) + tCount += 1 + } + if tCount > 0 { notes.append("\(tCount) Vorlagen") } + // code files → teams + var lib = state.codeLibrary + var teams = 0, players = 0 + for c in scan.codeFiles where pickCodes.contains(c.id) { + if let r = try? lib.importFile(c.url) { + teams += 1; players += r.added + if let i = lib.sets.firstIndex(where: { $0.sourcePath == c.url.path }) { lib.sets[i].enabled = c.enabled } + } + } + if importDelimiter { + if let d = scan.codeDelimiter { lib.delimiter = d } + if let d = scan.codeDefaultReplacement { lib.defaultReplacement = d } + } + state.codeLibrary = lib + if teams > 0 { notes.append("\(teams) Teams mit \(players) Codes") } + if importLists { + for (k, v) in scan.fieldLists { + var list = state.settings.fieldLists[k] ?? [] + for x in v where !list.contains(x) { list.append(x) } + state.settings.fieldLists[k] = list + } + if !scan.fieldLists.isEmpty { notes.append("\(scan.fieldLists.count) Feld-Listen") } + } + if importIngest { + if let r = scan.renamePattern { state.settings.ingest.renamePattern = r; state.settings.ingest.renameEnabled = true } + if let n = scan.sequence { state.settings.ingest.startSequence = n } + if let f = scan.ingestFolderPattern { state.settings.ingest.folderPattern = f } + } + result = notes.isEmpty ? "Nichts ausgewählt." : "Importiert: " + notes.joined(separator: ", ") + } +} diff --git a/Sources/Lichtkasten/Views/TemplateViews.swift b/Sources/Lichtkasten/Views/TemplateViews.swift index 7372e62..ec40873 100644 --- a/Sources/Lichtkasten/Views/TemplateViews.swift +++ b/Sources/Lichtkasten/Views/TemplateViews.swift @@ -129,7 +129,7 @@ struct TemplateManagerView: View { applied: state.templates[i].appliedFields == nil ? nil : Binding( get: { state.templates[i].appliedFields ?? [] }, set: { state.templates[i].appliedFields = $0 }), - codes: state.codes, onEdit: { _ in save() }) + codes: state.codes, fieldLists: state.settings.fieldLists, onEdit: { _ in save() }) .padding(.trailing, 8) } } diff --git a/Sources/LichtkastenCore/Metadata/PMSettingsImporter.swift b/Sources/LichtkastenCore/Metadata/PMSettingsImporter.swift new file mode 100644 index 0000000..8c6a587 --- /dev/null +++ b/Sources/LichtkastenCore/Metadata/PMSettingsImporter.swift @@ -0,0 +1,221 @@ +import Foundation + +/// Finds Photo Mechanic's IPTC-related settings on this Mac (or in a folder / exported preferences the user picks): +/// templates (.snap / .xmp and XMP stored inside the preferences), code replacement files + delimiter, +/// IPTC field drop-down lists and ingest rename/sequence settings. +/// +/// PM's storage layout is not documented publicly, so this works heuristically: it scans the usual +/// Camera Bits folders, reads every property list it finds and looks for the values by shape and key name. +/// `keyReport` lists the key names it saw (no values) so the mapping can be refined. +public struct PMSettingsScan: Sendable { + public struct FoundTemplate: Identifiable, Sendable { + public let id = UUID() + public var template: IPTCTemplate + public var origin: String + } + public struct FoundCodeFile: Identifiable, Sendable { + public let id = UUID() + public var url: URL + public var enabled: Bool + public var exists: Bool + } + + public var templates: [FoundTemplate] = [] + public var codeFiles: [FoundCodeFile] = [] + public var codeDelimiter: String? + public var codeDefaultReplacement: String? + /// field id → values for the ▾ menu + public var fieldLists: [String: [String]] = [:] + public var renamePattern: String? + public var sequence: Int? + public var ingestFolderPattern: String? + public var scannedFiles: [String] = [] + public var keyReport: [String] = [] + + public var isEmpty: Bool { + templates.isEmpty && codeFiles.isEmpty && fieldLists.isEmpty && renamePattern == nil && sequence == nil && codeDelimiter == nil + } +} + +public enum PMSettingsImporter { + /// Default places Photo Mechanic (6 / Plus) uses on macOS. + public static var defaultRoots: [URL] { + let home = FileManager.default.homeDirectoryForCurrentUser + var roots: [URL] = [] + let lib = home.appendingPathComponent("Library") + for sub in ["Application Support", "Preferences", "Containers", "Group Containers"] { + let dir = lib.appendingPathComponent(sub) + guard let list = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) else { continue } + for u in list { + let n = u.lastPathComponent.lowercased() + if n.contains("camerabits") || n.contains("camera bits") || n.contains("photo mechanic") || n.contains("photomechanic") { + roots.append(u) + } + } + } + for doc in ["Documents/Photo Mechanic", "Documents/Photo Mechanic Plus", "Documents/Camera Bits"] { + let u = home.appendingPathComponent(doc) + if FileManager.default.fileExists(atPath: u.path) { roots.append(u) } + } + return roots + } + + public static func scan(roots: [URL]) -> PMSettingsScan { + var scan = PMSettingsScan() + var seenTemplates = Set() + let fm = FileManager.default + + + var files: [URL] = [] + for root in roots { + var isDir: ObjCBool = false + guard fm.fileExists(atPath: root.path, isDirectory: &isDir) else { continue } + if !isDir.boolValue { files.append(root); continue } + if let e = fm.enumerator(at: root, includingPropertiesForKeys: [.fileSizeKey], options: [.skipsPackageDescendants]) { + for case let u as URL in e { + // skip previews/caches – only settings are interesting + let lower = u.path.lowercased() + if lower.contains("/cache") || lower.contains("proxies") || lower.contains("previews") { e.skipDescendants(); continue } + if let size = try? u.resourceValues(forKeys: [.fileSizeKey]).fileSize, size > 20_000_000 { continue } + files.append(u) + if files.count > 20_000 { break } + } + } + } + + for f in files { + let ext = f.pathExtension.lowercased() + switch ext { + case "snap", "xmp": + if var t = try? XMPTemplateIO.importTemplate(from: f) { + if t.name.isEmpty { t.name = f.deletingPathExtension().lastPathComponent } + scan.templates.append(.init(template: t, origin: f.path)) + scan.scannedFiles.append(f.path) + } + case "plist", "pmprefs", "prefs", "": + guard let data = try? Data(contentsOf: f), + let plist = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) else { continue } + scan.scannedFiles.append(f.path) + let before = scan.templates.count + walk(plist, path: [], scan: &scan) + for i in before..() + scan.codeFiles = scan.codeFiles.filter { seenCode.insert($0.url.path).inserted } + scan.keyReport = Array(Set(scan.keyReport)).sorted() + return scan + } + + /// Matches a PM field label / IIM name / our id to a field ("City", "Headline", "Caption-Abstract", "Keywords" …). + static func fieldFor(name raw: String) -> IPTCField? { + let n = raw.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "_", with: "") + .replacingOccurrences(of: "-", with: "").replacingOccurrences(of: "/", with: "") + guard !n.isEmpty else { return nil } + let aliases: [String: String] = ["captionabstract": "caption", "description": "caption", "caption": "caption", + "byline": "creator", "photographer": "creator", "sublocation": "sublocation", + "location": "sublocation", "provincestate": "state", "stateprovince": "state", + "countryprimarylocationname": "country", "objectname": "objectname", + "specialinstructions": "instructions", "writereditor": "captionWriter", + "captionwriter": "captionWriter", "persons": "personInImage", "personshown": "personInImage"] + if let id = aliases[n], let f = IPTCField.byID[id] ?? IPTCField.all.first(where: { $0.id.lowercased() == id }) { return f } + return IPTCField.all.first { f in + let pm = f.pmLabel.lowercased().replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "/", with: "") + .replacingOccurrences(of: "'", with: "").replacingOccurrences(of: ".", with: "") + return f.id.lowercased() == n || pm == n || (f.iimTag?.lowercased().replacingOccurrences(of: "iptc:", with: "") + .replacingOccurrences(of: "-", with: "") == n) + } + } + + private static func walk(_ node: Any, path: [String], scan: inout PMSettingsScan) { + let keyPath = path.joined(separator: ".") + let lowerPath = keyPath.lowercased() + switch node { + case let d as [String: Any]: + // A dictionary describing a code replacement file: {path/file/url: …, enabled: Bool} + if lowerPath.contains("code") { + let pathValue = d.first { ["path", "file", "filepath", "url", "filename"].contains($0.key.lowercased()) }?.value as? String + if let p = pathValue.map(normalizePath), p.lowercased().hasSuffix(".txt") { + let enabled = (d.first { $0.key.lowercased().contains("enable") }?.value as? Bool) ?? true + scan.codeFiles.append(.init(url: URL(fileURLWithPath: p), enabled: enabled, exists: FileManager.default.fileExists(atPath: p))) + } + } + for (k, v) in d { + scan.keyReport.append((path + [k]).joined(separator: ".")) + walk(v, path: path + [k], scan: &scan) + } + case let a as [Any]: + // Arrays of strings under a field-like key = drop-down list + if let strings = a as? [String], !strings.isEmpty, let last = path.last { + let fieldName = last.replacingOccurrences(of: "List", with: "").replacingOccurrences(of: "Recent", with: "") + .replacingOccurrences(of: "Values", with: "") + if !lowerPath.contains("code"), let field = fieldFor(name: fieldName), + strings.allSatisfy({ !$0.hasPrefix("/") && $0.count < 2000 }) { + scan.fieldLists[field.id, default: []].append(contentsOf: strings) + } + } + for (i, v) in a.enumerated() { walk(v, path: path + ["\(i)"], scan: &scan) } + case let s as String: + handleString(s, path: path, lowerPath: lowerPath, scan: &scan) + case let data as Data: + if let s = String(data: data, encoding: .utf8) { + handleString(s, path: path, lowerPath: lowerPath, scan: &scan) + } else if let nested = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) { + walk(nested, path: path, scan: &scan) + } + case let n as NSNumber: + if lowerPath.contains("seq") && (lowerPath.contains("ingest") || lowerPath.contains("rename") || lowerPath.hasSuffix("seqn")) { + if n.intValue > 0 { scan.sequence = max(scan.sequence ?? 0, n.intValue) } + } + default: + break + } + } + + private static func handleString(_ s: String, path: [String], lowerPath: String, scan: inout PMSettingsScan) { + let last = path.last?.lowercased() ?? "" + if s.contains(" 2 }) ?? "PM-Vorlage" + scan.templates.append(.init(template: t, origin: "")) + } + return + } + if lowerPath.contains("code") { + let p = normalizePath(s) + if p.lowercased().hasSuffix(".txt") { + scan.codeFiles.append(.init(url: URL(fileURLWithPath: p), enabled: true, exists: FileManager.default.fileExists(atPath: p))) + } else if last.contains("delim"), let c = s.first, s.count == 1 { + scan.codeDelimiter = String(c) + } else if last.contains("default") && s.count < 200 { + scan.codeDefaultReplacement = s + } + return + } + if (lowerPath.contains("rename") || lowerPath.contains("ingest")) && s.contains("{") && !s.contains("/") { + if lowerPath.contains("folder") { scan.ingestFolderPattern = s } else { scan.renamePattern = s } + } + if lowerPath.contains("seq"), let n = Int(s), n > 0 { scan.sequence = max(scan.sequence ?? 0, n) } + } + + /// file:// URLs, "~" and HFS-style paths → POSIX path + static func normalizePath(_ s: String) -> String { + if s.hasPrefix("file://"), let u = URL(string: s) { return u.path } + return (s as NSString).expandingTildeInPath + } +} diff --git a/Tests/LichtkastenCoreTests/CoreTests.swift b/Tests/LichtkastenCoreTests/CoreTests.swift index 54e5c59..941d95a 100644 --- a/Tests/LichtkastenCoreTests/CoreTests.swift +++ b/Tests/LichtkastenCoreTests/CoreTests.swift @@ -196,3 +196,36 @@ final class CodeLibraryTests: XCTestCase { XCTAssertNotNil(l.replacements.lookup("W10")) } } + +final class PMSettingsImporterTests: XCTestCase { + func testScanFindsSnapCodeFilesAndLists() throws { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("pmscan-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + // template + let snap = try XCTUnwrap(Bundle.module.url(forResource: "Fixtures", withExtension: nil)) + .appendingPathComponent("42061495-VFL_Frauen_-_Hoffenheim.snap") + try FileManager.default.copyItem(at: snap, to: dir.appendingPathComponent("42061495-VFL_Frauen_-_Hoffenheim.snap")) + // code file + prefs plist referencing it + let codes = dir.appendingPathComponent("vfl_kader.txt") + try "w10\tSvenja Huth (VfL Wolfsburg, 10)\n".write(to: codes, atomically: true, encoding: .utf8) + let plist: [String: Any] = [ + "CodeReplacementFiles": [["Path": codes.path, "Enabled": false]], + "CodeReplacementDelimiter": ".", + "IngestRenameAs": "@leon.tonhaeuser-{seqn}", + "IngestSequence": 382623, + "CityList": ["Wolfsburg", "Hoffenheim"], + ] + let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .binary, options: 0) + try data.write(to: dir.appendingPathComponent("com.camerabits.PhotoMechanic.plist")) + + let scan = PMSettingsImporter.scan(roots: [dir]) + XCTAssertEqual(scan.templates.count, 1) + XCTAssertEqual(scan.codeFiles.first?.url.lastPathComponent, "vfl_kader.txt") + XCTAssertEqual(scan.codeFiles.first?.enabled, false) + XCTAssertEqual(scan.codeDelimiter, ".") + XCTAssertEqual(scan.renamePattern, "@leon.tonhaeuser-{seqn}") + XCTAssertEqual(scan.sequence, 382623) + XCTAssertEqual(scan.fieldLists["city"], ["Wolfsburg", "Hoffenheim"]) + } +}