PM-Prefs (Tag/Farbe/Sterne) lesen+schreiben, Datum Capture Time, Zoom bis einstellbarem Maximum, Ingest im PM-Aufbau (gesperrt/RAW-Filter, Sequenz, inkrementell, Auswerfen), App-Icon

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:05:21 +00:00
1 parent c0ee93995f
commit 8effd1af0c
25 files changed
+885 -131

No files matched your search

@@ -1,20 +1,78 @@
import Foundation
/// Ingest settings (PM: "Ingest"): copy from card to primary + optional backup destination.
/// PM Ingest "Filter Files": in-camera protected (locked) photos.
public enum LockedFilter: String, Codable, CaseIterable, Sendable {
case all = "Gesperrte und nicht gesperrte Fotos kopieren"
case lockedOnly = "Nur gesperrte (geschützte) Fotos kopieren"
case unlockedOnly = "Nur nicht gesperrte Fotos kopieren"
}
public enum RawFilter: String, Codable, CaseIterable, Sendable {
case all = "RAW und nicht-RAW kopieren"
case rawOnly = "Nur RAW kopieren"
case nonRawOnly = "Nur nicht-RAW (JPEG …) kopieren"
}
/// Ingest settings in Photo Mechanic's structure.
public struct IngestSettings: Codable, Hashable, Sendable {
public var primaryDestination: String = ""
public var secondaryEnabled = false
public var backupDestination: String = ""
/// Sub folder pattern, e.g. "{year4}/{isodate}_{event}". Empty = directly into destination.
public var folderPattern: String = "{isodate}"
/// Rename pattern without extension, e.g. "{isodate}_{seqn4}". Empty = keep original name.
public var renamePattern: String = ""
/// "Copy photos into folder with name", e.g. "{day0}.{month0}.{year4} - Wolfsburg (F) - Hoffenheim (F)".
public var folderPattern: String = "{day0}.{month0}.{year4} - "
/// Keep the card's folder structure (DCIM/100NZ8 …) below the destination folder.
public var preserveStructure = false
public var renameEnabled = true
/// Rename pattern without extension, e.g. "@leon.tonhaeuser-{seqn}".
public var renamePattern: String = "{filenamebase}"
public var sequenceEnabled = true
public var startSequence: Int = 1
public var skipDuplicates = true
public var incremental = true
public var lockedFilter: LockedFilter = .all
public var rawFilter: RawFilter = .all
/// Write the PM tag for photos that were protected in the camera.
public var tagLockedPhotos = true
public var applyTemplate = false
public var templateID: UUID?
public var openAfterIngest = true
public var onlyNewSinceLastIngest = false
/// PM "Open Contact Sheets in background": add the tab without switching to it.
public var openInBackground = false
public var unmountAfter = true
public var skipDuplicates = true
public init() {}
enum CodingKeys: String, CodingKey {
case primaryDestination, secondaryEnabled, backupDestination, folderPattern, preserveStructure, renameEnabled,
renamePattern, sequenceEnabled, startSequence, incremental, lockedFilter, rawFilter, tagLockedPhotos,
applyTemplate, templateID, openAfterIngest, openInBackground, unmountAfter, skipDuplicates
}
/// Tolerant decoding: new options never reset existing settings.
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = IngestSettings()
func v<T: Decodable>(_ k: CodingKeys, _ def: T) -> T { (try? c.decode(T.self, forKey: k)) ?? def }
primaryDestination = v(.primaryDestination, d.primaryDestination)
backupDestination = v(.backupDestination, d.backupDestination)
secondaryEnabled = v(.secondaryEnabled, !backupDestination.isEmpty)
folderPattern = v(.folderPattern, d.folderPattern)
preserveStructure = v(.preserveStructure, d.preserveStructure)
renamePattern = v(.renamePattern, d.renamePattern)
renameEnabled = v(.renameEnabled, !renamePattern.isEmpty)
sequenceEnabled = v(.sequenceEnabled, d.sequenceEnabled)
startSequence = v(.startSequence, d.startSequence)
incremental = v(.incremental, d.incremental)
lockedFilter = v(.lockedFilter, d.lockedFilter)
rawFilter = v(.rawFilter, d.rawFilter)
tagLockedPhotos = v(.tagLockedPhotos, d.tagLockedPhotos)
templateID = try? c.decode(UUID.self, forKey: .templateID)
applyTemplate = v(.applyTemplate, templateID != nil)
openAfterIngest = v(.openAfterIngest, d.openAfterIngest)
openInBackground = v(.openInBackground, d.openInBackground)
unmountAfter = v(.unmountAfter, d.unmountAfter)
skipDuplicates = v(.skipDuplicates, d.skipDuplicates)
}
}
public struct IngestProgress: Sendable {
@@ -23,61 +81,177 @@ public struct IngestProgress: Sendable {
public var currentFile: String
}
public struct IngestResult: Sendable {
public var folders: [URL]
/// Copied primary files (in the primary destination).
public var copied: [URL]
/// Copied files that were locked (protected) on the card.
public var lockedCopies: [URL]
public var nextSequence: Int
public var skipped: Int
}
public enum IngestService {
/// Copies all images (and their XMP sidecars) from `sources`. Returns the destination folders used.
// MARK: Locked / incremental helpers
/// A photo protected in the camera shows up as read-only / locked (FAT read-only attribute).
public static func isLocked(_ url: URL, volumeReadOnly: Bool) -> Bool {
let fm = FileManager.default
if let attrs = try? fm.attributesOfItem(atPath: url.path), (attrs[.immutable] as? Bool) == true { return true }
if volumeReadOnly { return false } // SD write-protect switch: everything looks read-only
return !fm.isWritableFile(atPath: url.path)
}
static func volumeIsReadOnly(_ url: URL) -> Bool {
(try? url.resourceValues(forKeys: [.volumeIsReadOnlyKey]).volumeIsReadOnly) == true
}
static var historyURL: URL {
let d = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("Lichtkasten", isDirectory: true)
try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)
return d.appendingPathComponent("ingest-history.json")
}
/// Incremental ingest key: original name + size + capture/mod date (survives card re-insert).
static func historyKey(_ url: URL) -> String {
let a = try? FileManager.default.attributesOfItem(atPath: url.path)
let size = (a?[.size] as? NSNumber)?.int64Value ?? 0
let m = Int((a?[.modificationDate] as? Date)?.timeIntervalSince1970 ?? 0)
return "\(url.lastPathComponent)|\(size)|\(m)"
}
static func loadHistory() -> Set<String> {
guard let d = try? Data(contentsOf: historyURL), let s = try? JSONDecoder().decode(Set<String>.self, from: d) else { return [] }
return s
}
static func saveHistory(_ s: Set<String>) {
if let d = try? JSONEncoder().encode(s) { try? d.write(to: historyURL, options: .atomic) }
}
/// Copy + make the copy writable again (otherwise locked files stay locked and metadata can't be written).
static func copy(_ src: URL, to dest: URL) throws {
let fm = FileManager.default
try fm.copyItem(at: src, to: dest)
try? fm.setAttributes([.immutable: false, .posixPermissions: 0o644], ofItemAtPath: dest.path)
}
// MARK: Run
/// Copies the photos (and their XMP sidecars) from `sources` like PM's Ingest.
public static func run(sources: [URL], settings: IngestSettings, exiftool: ExifTool,
onFolder: (@Sendable (URL) -> Void)? = nil,
progress: @escaping @Sendable (IngestProgress) -> Void) async throws -> [URL] {
progress: @escaping @Sendable (IngestProgress) -> Void) async throws -> IngestResult {
let fm = FileManager.default
var items: [PhotoItem] = []
for s in sources { items += try FolderScanner.scan(folder: s, recursive: true) }
progress(IngestProgress(done: 0, total: items.count, currentFile: "Lese Aufnahmedaten …"))
guard !settings.primaryDestination.isEmpty else { throw UploadError.failed("Kein Ziel für den Ingest gewählt.") }
// Read capture dates for folder/rename patterns in one go.
let meta = try await exiftool.readMetadata(files: items.map(\.primary))
for i in items.indices {
items[i].apply(fileMeta: meta[items[i].primary.path] ?? [:], sidecarMeta: nil)
// 1. scan + filters
var entries: [(item: PhotoItem, root: URL, locked: Bool)] = []
for s in sources {
let ro = volumeIsReadOnly(s)
for item in try FolderScanner.scan(folder: s, recursive: true) {
entries.append((item, s, isLocked(item.primary, volumeReadOnly: ro)))
}
}
items.sort { ($0.captureDate ?? $0.modified) < ($1.captureDate ?? $1.modified) }
entries = entries.filter { e in
switch settings.lockedFilter {
case .all: break
case .lockedOnly: if !e.locked { return false }
case .unlockedOnly: if e.locked { return false }
}
return true
}
var history = settings.incremental ? loadHistory() : []
var skipped = 0
if settings.incremental {
let before = entries.count
entries = entries.filter { !history.contains(historyKey($0.item.primary)) }
skipped = before - entries.count
}
progress(IngestProgress(done: 0, total: entries.count, currentFile: "Lese Aufnahmezeiten …"))
// 2. capture dates (for folder/rename variables and the order of {seqn})
for chunkStart in stride(from: 0, to: entries.count, by: 200) {
try Task.checkCancellation()
let range = chunkStart..<min(chunkStart + 200, entries.count)
let meta = try await exiftool.readMetadata(files: entries[range].map { $0.item.primary })
for i in range { entries[i].item.apply(fileMeta: meta[entries[i].item.primary.path] ?? [:], sidecarMeta: nil) }
}
entries.sort { ($0.item.captureDate ?? $0.item.modified, $0.item.filename) < ($1.item.captureDate ?? $1.item.modified, $1.item.filename) }
// 3. copy
var usedFolders = Set<URL>()
var copied: [URL] = []
var lockedCopies: [URL] = []
var seq = settings.startSequence
let total = items.reduce(0) { $0 + 1 + $1.companions.count }
let total = entries.reduce(0) { total, e in
let n = 1 + e.item.companions.count
return total + n
}
var done = 0
let destRoots = [settings.primaryDestination] + (settings.secondaryEnabled && !settings.backupDestination.isEmpty ? [settings.backupDestination] : [])
progress(IngestProgress(done: 0, total: total, currentFile: "Starte …"))
for item in items {
for e in entries {
try Task.checkCancellation()
let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, sequence: seq, iptc: item.iptc)
let item = e.item
let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, sequence: settings.sequenceEnabled ? seq : nil, iptc: item.iptc)
let sub = VariableExpander.expand(settings.folderPattern, context: ctx)
.replacingOccurrences(of: ":", with: "-")
let baseName = settings.renamePattern.isEmpty
? item.baseName
: VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-")
seq += 1
.trimmingCharacters(in: .whitespaces)
var baseName = item.baseName
if settings.renameEnabled, !settings.renamePattern.isEmpty {
baseName = VariableExpander.expand(settings.renamePattern, context: ctx).replacingOccurrences(of: "/", with: "-")
}
if settings.sequenceEnabled { seq += 1 }
// Card structure (DCIM/100NZ8_1) below the destination if requested
let rel = settings.preserveStructure
? item.primary.deletingLastPathComponent().path.replacingOccurrences(of: e.root.path, with: "")
.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
: ""
for destRoot in [settings.primaryDestination, settings.backupDestination] where !destRoot.isEmpty {
let folder = sub.isEmpty ? URL(fileURLWithPath: destRoot) : URL(fileURLWithPath: destRoot).appendingPathComponent(sub)
var rawFiles = [item.primary] + item.companions
switch settings.rawFilter {
case .all: break
case .rawOnly: rawFiles = rawFiles.filter { FileKind(url: $0).isRawLike }
case .nonRawOnly: rawFiles = rawFiles.filter { !FileKind(url: $0).isRawLike }
}
guard !rawFiles.isEmpty else { continue }
var files = rawFiles
if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path), rawFiles.contains(item.primary) { files.append(item.sidecarURL) }
for destRoot in destRoots {
var folder = URL(fileURLWithPath: destRoot)
if !sub.isEmpty { folder.appendPathComponent(sub, isDirectory: true) }
if !rel.isEmpty { folder.appendPathComponent(rel, isDirectory: true) }
try fm.createDirectory(at: folder, withIntermediateDirectories: true)
if destRoot == settings.primaryDestination, usedFolders.insert(folder).inserted { onFolder?(folder) }
var files = [item.primary] + item.companions
if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path) { files.append(item.sidecarURL) }
for src in files {
let isPrimary = destRoot == settings.primaryDestination
if isPrimary, usedFolders.insert(folder).inserted { onFolder?(folder) }
for (n, src) in files.enumerated() {
let dest = folder.appendingPathComponent(baseName).appendingPathExtension(src.pathExtension)
if fm.fileExists(atPath: dest.path) {
if settings.skipDuplicates, sameSize(src, dest) { continue }
try fm.removeItem(at: dest)
}
try fm.copyItem(at: src, to: dest)
if destRoot == settings.primaryDestination {
done += 1
progress(IngestProgress(done: done, total: total, currentFile: src.lastPathComponent))
try copy(src, to: dest)
if isPrimary {
if n == 0 {
copied.append(dest)
if e.locked { lockedCopies.append(dest) }
}
if src.pathExtension.lowercased() != "xmp" {
done += 1
progress(IngestProgress(done: done, total: total, currentFile: src.lastPathComponent))
}
}
}
}
if settings.incremental { history.insert(historyKey(item.primary)) }
}
return Array(usedFolders).sorted { $0.path < $1.path }
if settings.incremental { saveHistory(history) }
return IngestResult(folders: Array(usedFolders).sorted { $0.path < $1.path }, copied: copied,
lockedCopies: lockedCopies, nextSequence: seq, skipped: skipped)
}
static func sameSize(_ a: URL, _ b: URL) -> Bool {
@@ -27,7 +27,8 @@ public final class MetadataCache: @unchecked Sendable {
// FNV-1a hash of the path as file name
var h: UInt64 = 0xcbf29ce484222325
for b in folder.standardizedFileURL.path.utf8 { h = (h ^ UInt64(b)) &* 0x100000001b3 }
url = MetadataCache.directory.appendingPathComponent(String(h, radix: 16) + ".json")
// "v2": cache format includes PM Prefs (tag/color class) – older caches are ignored.
url = MetadataCache.directory.appendingPathComponent("v2-" + String(h, radix: 16) + ".json")
if let d = try? Data(contentsOf: url), let e = try? JSONDecoder().decode([String: Entry].self, from: d) {
entries = e
}
@@ -88,6 +88,8 @@ public struct PhotoItem: Identifiable, Hashable, Sendable {
public var exif: [String: String] = [:]
public var captureDate: Date?
public var metadataLoaded = false
/// Frame number part of PM's Prefs ("Tagged:ColorClass:Rating:Frame"), kept when we rewrite it.
public var pmFrame = "-00001"
public init(primary: URL, companions: [URL] = [], fileSize: Int64 = 0, modified: Date = Date()) {
self.primary = primary
@@ -128,6 +130,26 @@ public struct PhotoItem: Identifiable, Hashable, Sendable {
public var rawFile: URL? { kind.isRawLike ? primary : companions.first { FileKind(url: $0).isRawLike } }
public struct PMPrefs: Equatable, Sendable {
public var tagged: Bool; public var colorClass: Int; public var rating: Int; public var frame: String
}
/// Parses PM's Prefs value, raw ("1:3:0:-00001") or exiftool-printed ("Tagged:1, ColorClass:3, …").
public static func parsePMPrefs(_ raw: String) -> PMPrefs? {
var s = raw
if s.contains("Tagged") {
s = s.replacingOccurrences(of: "Tagged:", with: "").replacingOccurrences(of: "ColorClass:", with: "")
.replacingOccurrences(of: "Rating:", with: "").replacingOccurrences(of: "FrameNum:", with: "")
.replacingOccurrences(of: ", ", with: ":").replacingOccurrences(of: " ", with: "")
}
let parts = s.split(separator: ":", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
guard parts.count >= 3, let t = Int(parts[0]), let c = Int(parts[1]), let r = Int(parts[2]) else { return nil }
return PMPrefs(tagged: t != 0, colorClass: c, rating: r, frame: parts.count > 3 ? parts[3] : "-00001")
}
/// PM Prefs string for the current state.
public var pmPrefsString: String { "\(tagged ? 1 : 0):\(label?.pmColorClass ?? 0):\(rating):\(pmFrame)" }
/// Applies exiftool output (primary file + optional sidecar) to the item.
public mutating func apply(fileMeta: [String: MetadataValue], sidecarMeta: [String: MetadataValue]?) {
// EXIF from the image itself
@@ -140,11 +162,17 @@ public struct PhotoItem: Identifiable, Hashable, Sendable {
let xmpSource = sidecarMeta ?? [:]
func xmp(_ tag: String) -> MetadataValue? { xmpSource[tag] ?? fileMeta[tag] }
rating = xmp("XMP-xmp:Rating")?.int ?? 0
// Photo Mechanic keeps tag/color/rating in "Prefs" (IPTC 2:221 and photomechanic:Prefs):
// "1:3:0:-00001" = tagged, color class 3, no stars, frame. Many PM files only have this.
let prefs = (xmp("XMP-photomech:Prefs") ?? fileMeta["IPTC:Prefs"]).flatMap { PhotoItem.parsePMPrefs($0.string) }
if let p = prefs { pmFrame = p.frame }
rating = xmp("XMP-xmp:Rating")?.int ?? prefs?.rating ?? 0
// PM color class first (it knows all 8 classes), then Lightroom's label.
label = xmp("XMP-photomech:ColorClass")?.int.flatMap { ColorLabel(pmColorClass: $0) }
?? prefs.flatMap { ColorLabel(pmColorClass: $0.colorClass) }
?? xmp("XMP-xmp:Label").flatMap { ColorLabel(xmp: $0.string) }
tagged = xmp("XMP-photomech:Tagged")?.bool ?? false
tagged = xmp("XMP-photomech:Tagged")?.bool ?? prefs?.tagged ?? false
var values = IPTCValues()
for field in IPTCField.all {
@@ -121,6 +121,7 @@ public final class ExifTool: @unchecked Sendable {
guard !files.isEmpty else { return [:] }
var args = ["-json", "-G1", "-fast2", "-a",
"-XMP-xmp:Rating#", "-XMP-xmp:Label", "-XMP-photomech:Tagged#", "-XMP-photomech:ColorClass#",
"-IPTC:Prefs#", "-XMP-photomech:Prefs#",
"-Make", "-Model", "-LensModel", "-Lens", "-SerialNumber", "-ISO", "-ExposureTime", "-FNumber",
"-FocalLength", "-DateTimeOriginal", "-CreateDate", "-SubSecTimeOriginal", "-OffsetTimeOriginal", "-ImageWidth", "-ImageHeight",
"-Orientation#", "-Artist", "-GPSLatitude#", "-GPSLongitude#"]
@@ -36,6 +36,26 @@ public struct MetadataWriter: Sendable {
try await writeFlags(["-XMP-photomech:Tagged=\(tagged ? "Yes" : "No")"], item: item)
}
/// Writes tag, color class and stars in one go – in every place PM and Lightroom look:
/// xmp:Rating, xmp:Label, photomechanic:Tagged/ColorClass/Prefs and (JPEG/TIFF) IPTC 2:221 Prefs.
public func writeState(of item: PhotoItem) async throws {
let prefs = item.pmPrefsString
for target in item.metadataTargets {
var args = ["-overwrite_original", "-m",
"-XMP-xmp:Rating=\(max(0, min(5, item.rating)))",
"-XMP-photomech:Tagged=\(item.tagged ? "Yes" : "No")",
"-XMP-photomech:Prefs=\(prefs)"]
if let l = item.label {
args += ["-XMP-xmp:Label=\(l.xmpValue)", "-XMP-photomech:ColorClass=\(l.pmColorClass)"]
} else {
args += ["-XMP-xmp:Label=", "-XMP-photomech:ColorClass=0"]
}
if target.kind.supportsIIM { args += ["-IPTC:Prefs=\(prefs)"] }
let (_, err) = try await exiftool.execute(args + [target.url.path])
if err.contains("Error:") { throw ExifToolError.failed(err) }
}
}
private func writeFlags(_ args: [String], item: PhotoItem) async throws {
for target in item.metadataTargets {
let (_, err) = try await exiftool.execute(["-overwrite_original", "-m"] + args + [target.url.path])
@@ -24,6 +24,12 @@ public struct VariableContext: Sendable {
v["shutter"] = exif["ExposureTime"]
v["focallength"] = exif["FocalLength"]
v["artist"] = exif["Artist"]
// Date field popup (PM "Capture Time" / "Today")
v["capturetime"] = MetadataWriter.captureDateValue(exif: exif)
let today = DateFormatter()
today.locale = Locale(identifier: "en_US_POSIX")
today.dateFormat = "yyyy-MM-dd"
v["today"] = today.string(from: Date())
if let seq = sequence {
v["seqn"] = String(seq)
v["seqn3"] = String(format: "%03d", seq)
@@ -77,7 +77,7 @@ public enum XMPTemplateIO {
}
}
// Keep only the date part of a fixed Date Created ("2026-02-15T00:00:00+01:00").
if let d = values.text["dateCreated"], d.count > 10 { values.text["dateCreated"] = String(d.prefix(10)) }
if let d = values.text["dateCreated"], d.count > 10, d.first?.isNumber == true { values.text["dateCreated"] = String(d.prefix(10)) }
guard found > 0 || !extras.isEmpty else { throw TemplateImportError.noFieldsFound }
var t = IPTCTemplate(name: "Importiert", values: values, extras: extras)
@@ -97,6 +97,7 @@ public enum XMPTemplateIO {
t.listMergeMode = merge.contains(where: { $0.lowercased() == "0x219" }) ? .append : .replace
}
if let dt = pm["ApplyDateType"]?.first { t.dateFromCapture = (dt == "2") }
if t.dateFromCapture { t.values.text["dateCreated"] = "{capturetime}" }
return t
}
@@ -107,6 +108,7 @@ public enum XMPTemplateIO {
static func applySnapSettings(_ snap: PMSnapFile, to t: inout IPTCTemplate) {
if let style = snap.applyDateStyle { t.dateFromCapture = (style == "2") }
if t.dateFromCapture { t.values.text["dateCreated"] = "{capturetime}" }
}
// MARK: Export