PM-Einstellungen komplett importieren (Vorlagen, Code-Dateien, Trennzeichen, Feld-Listen, Ingest), ▾-Wertelisten, Info-Fenster ⌘B/⌘N + Pfeiltasten, Keyword-Limit pro Eintrag

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
This commit is contained in:
Lichtkasten DevandClaude Opus 5.5 committed 2026-11-04 00:52:42 +00:00
1 parent 12f61b5d66
commit 2bf0d851aa
11 files changed
+516 -15

No files matched your search

@@ -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<String>()
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.templates.count { scan.templates[i].origin = f.lastPathComponent }
case "txt":
// PM field lists are plain text, one value per line, named after the field
let base = f.deletingPathExtension().lastPathComponent
if let field = fieldFor(name: base), let text = try? CodeLibrary.readText(f), !text.contains("\t") {
let values = text.components(separatedBy: .newlines).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
if !values.isEmpty { scan.fieldLists[field.id, default: []].append(contentsOf: values); scan.scannedFiles.append(f.path) }
}
default: break
}
}
// dedupe
scan.templates = scan.templates.filter { ft in
let t = ft.template
let key = t.name + "|" + t.values.text.sorted { $0.key < $1.key }.map { $0.value }.joined()
return seenTemplates.insert(key).inserted
}
for (k, v) in scan.fieldLists { scan.fieldLists[k] = NSOrderedSet(array: v).array as? [String] ?? v }
var seenCode = Set<String>()
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("<x:xmpmeta") || s.contains("<IPTCSettings") {
if var t = try? XMPTemplateIO.parseAny(data: Data(s.utf8)) {
t.name = path.last(where: { Int($0) == nil && $0.count > 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
}
}