diff --git a/README.md b/README.md index cebc551..7393d82 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Zum Entwickeln `Package.swift` in Xcode öffnen und das Scheme **Lichtkasten** s | ⌘⌥L | Lightroom: Vorgabe + JPEG-Export nach SENT | | ⌘⌥S | INPUT ⇄ SENT | | ⌘T | Neuer Tab · ⌘G Ingest · ⌘⌥U Aufgaben · ⌘⇧K Code-Ersetzungen | -| Leertaste | Vorschau, Z = 100 % | +| Leertaste | Vorschau · Z = Einpassen/100 % · +/− oder Trackpad = Zoom (max. einstellbar) | Unter Einstellungen → Allgemein lässt sich auf die Lightroom-Belegung umstellen (0–5 = Sterne, 6–9 = Farben). @@ -98,3 +98,14 @@ PM speichert Vorlagen als `.snap`: ein XMP-Block plus Steuerdaten. Lichtkasten - **ApplyDateType/ApplyDateStyle = 2**: Datum und Uhrzeit (IIM 2:55/2:60, `photoshop:DateCreated`) kommen aus der Aufnahmezeit. Alle Häkchen lassen sich im Vorlagen-Editor (⌘⇧T) pro Feld ändern. + +## Photo-Mechanic-Kompatibilität + +- Tag, Farbklasse und Sterne werden dort gelesen und geschrieben, wo PM sie ablegt: in `photomechanic:Prefs`, + in IPTC 2:221 „Prefs“ (`Tagged:ColorClass:Rating:Frame`), in `photomechanic:Tagged/ColorClass` und für + Lightroom zusätzlich in `xmp:Rating/Label`. +- Datum in Vorlagen: „Capture Time“ (`{capturetime}`), „Heute“ (`{today}`) oder ein festes Datum. +- Ingest wie in PM: Karten-Liste, inkrementell, gesperrte/RAW-Filter, Umbenennen mit fortlaufender Sequenz, + Vorlage, Kontaktabzug während des Ingests, Karte auswerfen. In der Kamera gesperrte Fotos werden auf Wunsch getaggt. + +App-Icon: `scripts/make-icon.py` erzeugt `Resources/AppIcon.icns`. diff --git a/Resources/AppIcon.icns b/Resources/AppIcon.icns new file mode 100644 index 0000000..0b17acf Binary files /dev/null and b/Resources/AppIcon.icns differ diff --git a/Resources/Icon/AppIcon-1024.png b/Resources/Icon/AppIcon-1024.png new file mode 100644 index 0000000..bf5beb9 Binary files /dev/null and b/Resources/Icon/AppIcon-1024.png differ diff --git a/Resources/Icon/AppIcon-256.png b/Resources/Icon/AppIcon-256.png new file mode 100644 index 0000000..c775426 Binary files /dev/null and b/Resources/Icon/AppIcon-256.png differ diff --git a/Resources/Info.plist b/Resources/Info.plist index 3110b3b..49518c4 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -6,6 +6,7 @@ CFBundleDisplayNameLichtkasten CFBundleIdentifierde.lichtkasten.app CFBundleExecutableLichtkasten + CFBundleIconFileAppIcon CFBundlePackageTypeAPPL CFBundleShortVersionString0.1.0 CFBundleVersion1 diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index eb0b341..35ed745 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -61,7 +61,11 @@ final class AppState: ObservableObject { @Published var searchText = "" { didSet { rebuildVisible() } } @Published private(set) var visible: [PhotoItem] = [] @Published var previewMode = false - @Published var zoom100 = false + @Published var zoom100 = false // true = not fitted (zoomed in) + @Published var zoomRequest: ZoomRequest? + @Published var zoomPercent = 0 + + func zoom(_ a: ZoomAction) { zoomRequest = ZoomRequest(action: a) } @Published var showInspector = false @Published var loadingMetadata = false @Published var statusText = "" @@ -335,7 +339,8 @@ final class AppState: ObservableObject { func startIngest(sources: [URL]) { guard let et = requireExifTool(), ingestTask == nil else { return } let settings = self.settings.ingest - let templates = self.templates + let template = settings.applyTemplate ? templates.first { $0.id == settings.templateID } : nil + let volumes = sources.compactMap { try? $0.resourceValues(forKeys: [.volumeURLKey]).volume } let taskID = tasks.start(.ingest, title: "Ingest von \(sources.map { $0.deletingLastPathComponent().lastPathComponent }.joined(separator: ", "))") { [weak self] in self?.ingestTask?.cancel() } @@ -344,15 +349,19 @@ final class AppState: ObservableObject { guard let self else { return } defer { self.ingestTask = nil } do { - let folders = try await IngestService.run( + let result = try await IngestService.run( sources: sources, settings: settings, exiftool: et, onFolder: { url in Task { @MainActor [weak self] in guard let self else { return } self.tasks.update(taskID, folder: url) - // Live view: show the destination while files arrive – but never pull the - // user out of a folder they are working in (the task row has "Öffnen"). - if settings.openAfterIngest && self.folder == nil { self.open(folder: url) } + // PM "Open Contact Sheets during Ingest" (optionally in the background tab) + guard settings.openAfterIngest else { return } + if settings.openInBackground { + if !self.tabs.contains(url) { self.tabs.append(url) } + } else { + self.open(folder: url, newTab: true) + } } }, progress: { p in @@ -360,9 +369,21 @@ final class AppState: ObservableObject { self?.tasks.update(taskID, done: p.done, total: p.total, detail: p.currentFile) } }) - if let tid = settings.templateID, let template = templates.first(where: { $0.id == tid }) { + // PM: the sequence continues with the next number next time. + if settings.sequenceEnabled { self.settings.ingest.startSequence = result.nextSequence } + + // Protected-in-camera photos → PM tag + if settings.tagLockedPhotos, !result.lockedCopies.isEmpty, let w = self.writer { + self.tasks.update(taskID, detail: "Tagge \(result.lockedCopies.count) gesperrte Fotos …") + for url in result.lockedCopies { + var item = PhotoItem(primary: url) + item.tagged = true + try? await w.writeState(of: item) + } + } + if let template { self.tasks.update(taskID, detail: "Wende Vorlage „\(template.name)“ an …") - for f in folders { + for f in result.folders { let found = try FolderScanner.scan(folder: f) let meta = try await et.readMetadata(files: found.map(\.primary)) let loaded = found.map { item -> PhotoItem in @@ -373,8 +394,16 @@ final class AppState: ObservableObject { await self.applyTemplateAndWait(template, to: loaded) } } - self.tasks.finish(taskID, detail: "Fertig – \(folders.count) Ordner") - if let current = self.folder, folders.contains(current) { + var detail = "\(result.copied.count) Fotos kopiert" + if result.skipped > 0 { detail += ", \(result.skipped) bereits importiert übersprungen" } + if !result.lockedCopies.isEmpty { detail += ", \(result.lockedCopies.count) gesperrt" + (settings.tagLockedPhotos ? " → getaggt" : "") } + if settings.unmountAfter { + for v in volumes { try? NSWorkspace.shared.unmountAndEjectDevice(at: v) } + detail += " · Karte ausgeworfen" + } + self.tasks.finish(taskID, detail: detail) + if let current = self.folder, result.folders.contains(current) { + self.metadataCache = nil self.refreshFolder() await self.loadMetadata(for: self.items) } @@ -558,7 +587,7 @@ final class AppState: ObservableObject { let targets = only.map { [$0] } ?? actionTargets guard !targets.isEmpty, let w = writer else { return } mutate(targets) { $0.rating = n } - Task { for t in targets { do { try await w.writeRating(n, to: t) } catch { report(error) } } } + writeState(targets, w) advanceIfSingle(targets.count, advance) } @@ -568,7 +597,7 @@ final class AppState: ObservableObject { // Same label again toggles it off (LR behaviour). let newLabel: ColorLabel? = targets.allSatisfy({ $0.label == l }) ? nil : l mutate(targets) { $0.label = newLabel } - Task { for t in targets { do { try await w.writeLabel(newLabel, to: t) } catch { report(error) } } } + writeState(targets, w) advanceIfSingle(targets.count, advance) } @@ -577,10 +606,16 @@ final class AppState: ObservableObject { guard !targets.isEmpty, let w = writer else { return } let newValue = !targets.allSatisfy(\.tagged) mutate(targets) { $0.tagged = newValue } - Task { for t in targets { do { try await w.writeTag(newValue, to: t) } catch { report(error) } } } + writeState(targets, w) advanceIfSingle(targets.count) } + /// Writes tag/color/stars of the (already updated) items to disk. + private func writeState(_ targets: [PhotoItem], _ w: MetadataWriter) { + let updated = targets.compactMap { item($0.id) } + Task { for t in updated { do { try await w.writeState(of: t) } catch { report(error) } } } + } + func report(_ error: Error) { alert = AppAlert(title: "Fehler", message: error.localizedDescription) } diff --git a/Sources/Lichtkasten/Services/KeyboardMonitor.swift b/Sources/Lichtkasten/Services/KeyboardMonitor.swift index 38acdee..35293bc 100644 --- a/Sources/Lichtkasten/Services/KeyboardMonitor.swift +++ b/Sources/Lichtkasten/Services/KeyboardMonitor.swift @@ -44,7 +44,14 @@ final class KeyboardMonitor { guard let ch = event.charactersIgnoringModifiers?.lowercased(), let c = ch.first else { return false } if c == "t" { state.toggleTag(); return true } if c == "i" { state.openWindow("iptc"); return true } - if c == "z", state.previewMode { state.zoom100.toggle(); return true } + if state.previewMode { + switch c { + case "z": state.zoom(state.zoom100 ? .fit : .actual); return true + case "+", "=": state.zoom(.zoomIn); return true + case "-": state.zoom(.zoomOut); return true + default: break + } + } guard let digit = c.wholeNumberValue else { return false } switch state.settings.keyScheme { diff --git a/Sources/Lichtkasten/Services/Persistence.swift b/Sources/Lichtkasten/Services/Persistence.swift index 9512ebe..83d9b00 100644 --- a/Sources/Lichtkasten/Services/Persistence.swift +++ b/Sources/Lichtkasten/Services/Persistence.swift @@ -70,7 +70,11 @@ struct AppSettings: Codable { var dateFormat = "dd.MM.yyyy" var keyScheme: KeyScheme = .photoMechanic var autoIngestOnCardMount = true - var thumbnailSize: Double = 200 + var thumbnailSize: Double = 240 + /// Loupe: maximum zoom (1 = 100 %, 4 = 400 %) + var maxZoom: Double = 4 + /// Largest contact sheet thumbnail size (slider maximum) + var maxThumbnailSize: Double = 700 var autoAdvance = true // after rating/tagging jump to next image (PM: "Auto-advance") var ftpDestinations: [FTPDestination] = [] var immich = ImmichSettings() @@ -91,6 +95,8 @@ struct AppSettings: Codable { keyScheme = (try? c.decode(KeyScheme.self, forKey: .keyScheme)) ?? d.keyScheme autoIngestOnCardMount = (try? c.decode(Bool.self, forKey: .autoIngestOnCardMount)) ?? d.autoIngestOnCardMount thumbnailSize = (try? c.decode(Double.self, forKey: .thumbnailSize)) ?? d.thumbnailSize + maxZoom = (try? c.decode(Double.self, forKey: .maxZoom)) ?? d.maxZoom + maxThumbnailSize = (try? c.decode(Double.self, forKey: .maxThumbnailSize)) ?? d.maxThumbnailSize autoAdvance = (try? c.decode(Bool.self, forKey: .autoAdvance)) ?? d.autoAdvance ftpDestinations = (try? c.decode([FTPDestination].self, forKey: .ftpDestinations)) ?? d.ftpDestinations immich = (try? c.decode(ImmichSettings.self, forKey: .immich)) ?? d.immich diff --git a/Sources/Lichtkasten/Views/BatchEditWindow.swift b/Sources/Lichtkasten/Views/BatchEditWindow.swift index 0eda53f..d1eb84e 100644 --- a/Sources/Lichtkasten/Views/BatchEditWindow.swift +++ b/Sources/Lichtkasten/Views/BatchEditWindow.swift @@ -26,7 +26,6 @@ struct BatchEditWindow: View { ForEach(ListMergeMode.allCases, id: \.self) { Text($0.rawValue).tag($0) } } .fixedSize() - Toggle("Datum = Aufnahmezeit", isOn: $dateFromCapture) } .padding(12) Divider() diff --git a/Sources/Lichtkasten/Views/ContentView.swift b/Sources/Lichtkasten/Views/ContentView.swift index 8a2d332..df58c9d 100644 --- a/Sources/Lichtkasten/Views/ContentView.swift +++ b/Sources/Lichtkasten/Views/ContentView.swift @@ -151,7 +151,7 @@ struct ContactSheetHeader: View { var body: some View { HStack(spacing: 12) { - Slider(value: $state.settings.thumbnailSize, in: 140...460) + Slider(value: $state.settings.thumbnailSize, in: 120...max(200, state.settings.maxThumbnailSize)) .frame(width: 140) .help("Vorschaugröße") diff --git a/Sources/Lichtkasten/Views/IPTCForm.swift b/Sources/Lichtkasten/Views/IPTCForm.swift index 429cd74..076248c 100644 --- a/Sources/Lichtkasten/Views/IPTCForm.swift +++ b/Sources/Lichtkasten/Views/IPTCForm.swift @@ -138,7 +138,9 @@ struct PMFieldRow: View { .padding(.top, 3) Group { - if let h = height { + if field.id == "dateCreated" { + DateFieldEditor(text: $text) + } else if let h = height { TextEditor(text: $text) .font(.system(size: 13)) .scrollContentBackground(.hidden) @@ -173,3 +175,41 @@ struct PMFieldRow: View { } } } + +/// PM's Date row: popup "Capture Time" / "Today" / own date. +struct DateFieldEditor: View { + @Binding var text: String + + enum Mode: String, CaseIterable { case capture = "Capture Time", today = "Heute", custom = "Datum eingeben", none = "Kein Datum" } + + private var mode: Mode { + switch text { + case "{capturetime}": return .capture + case "{today}": return .today + case "": return .none + default: return .custom + } + } + + var body: some View { + HStack { + Picker("", selection: Binding(get: { mode }, set: { m in + switch m { + case .capture: text = "{capturetime}" + case .today: text = "{today}" + case .none: text = "" + case .custom: if mode != .custom { text = ISO8601DateFormatter.string(from: Date(), timeZone: .current, formatOptions: [.withFullDate]) } + } + })) { + ForEach(Mode.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + .labelsHidden() + .frame(width: 170) + if mode == .custom { + TextField("JJJJ-MM-TT [HH:MM:SS]", text: $text).textFieldStyle(.roundedBorder) + } else { + Spacer() + } + } + } +} diff --git a/Sources/Lichtkasten/Views/IngestView.swift b/Sources/Lichtkasten/Views/IngestView.swift index 26ff956..ef48b2f 100644 --- a/Sources/Lichtkasten/Views/IngestView.swift +++ b/Sources/Lichtkasten/Views/IngestView.swift @@ -1,87 +1,252 @@ import SwiftUI import LichtkastenCore +/// Ingest dialog in Photo Mechanic's layout (Source Paths | Destination, Filter, Rename, Options). struct IngestView: View { @EnvironmentObject var state: AppState @Environment(\.dismiss) private var dismiss - @State private var sources: [URL] = [] + + enum SourceMode: String, CaseIterable { case disks = "Karten", folders = "Ordner", selection = "Aus Auswahl" } + + struct Card: Identifiable, Hashable { + var id: URL { dcim } + let volume: URL + let dcim: URL + let name: String + let used: String + } + + @State private var mode: SourceMode = .disks + @State private var cards: [Card] = [] + @State private var selectedCards: Set = [] + @State private var folders: [URL] = [] + + private var ingest: Binding { $state.settings.ingest } + + private var sources: [URL] { + switch mode { + case .disks: return cards.filter { selectedCards.contains($0.dcim) }.map(\.dcim) + case .folders: return folders + case .selection: + return Array(Set(state.selectedItems.map { $0.primary.deletingLastPathComponent() })) + } + } var body: some View { - VStack(alignment: .leading, spacing: 12) { - Text("Ingest – von Karte kopieren").font(.headline) - Form { - Section("Quelle") { - ForEach(sources, id: \.self) { Text($0.path) } - HStack { - Button("Quelle hinzufügen …") { pickSource() } - Button("Karten automatisch finden") { sources = detectCards() } - if !sources.isEmpty { Button("Leeren") { sources = [] } } - } - } - Section("Ziel") { - folderRow("Hauptziel", path: $state.settings.ingest.primaryDestination) - folderRow("Backup (optional)", path: $state.settings.ingest.backupDestination) - TextField("Unterordner", text: $state.settings.ingest.folderPattern, prompt: Text("{year4}/{isodate}")) - TextField("Umbenennen (leer = Original)", text: $state.settings.ingest.renamePattern, prompt: Text("{isodate}_{seqn4}")) - HStack { - Text("Startnummer {seqn}") - Spacer() - TextField("", value: $state.settings.ingest.startSequence, format: .number.grouping(.never)) - .multilineTextAlignment(.trailing) - .frame(width: 90) - Stepper("", value: $state.settings.ingest.startSequence, in: 0...9_999_999).labelsHidden() - } - Toggle("Duplikate überspringen", isOn: $state.settings.ingest.skipDuplicates) - } - Section("Metadaten") { - Picker("IPTC-Vorlage", selection: $state.settings.ingest.templateID) { - Text("Keine").tag(UUID?.none) - ForEach(state.templates) { Text($0.name).tag(UUID?.some($0.id)) } - } - Toggle("Zielordner live anzeigen, wenn gerade kein Ordner offen ist", isOn: $state.settings.ingest.openAfterIngest) - Toggle("Ingest-Fenster automatisch öffnen, wenn eine Karte erkannt wird", isOn: $state.settings.autoIngestOnCardMount) - } + VStack(spacing: 12) { + HStack(alignment: .top, spacing: 16) { + leftColumn.frame(maxWidth: .infinity) + rightColumn.frame(maxWidth: .infinity) } - .formStyle(.grouped) - Text("Der Ingest läuft im Hintergrund. Den Fortschritt siehst du im Aufgaben-Fenster (⌘⌥U).") - .font(.caption).foregroundStyle(.secondary) + pathPreview HStack { + Button("Variablen …") { state.openWindow("codes") } Spacer() Button("Abbrechen") { state.pendingIngestSources = []; dismiss() }.keyboardShortcut(.cancelAction) - Button("Ingest starten") { + Button("Ingest") { state.startIngest(sources: sources) state.pendingIngestSources = [] dismiss() } .keyboardShortcut(.defaultAction) + .buttonStyle(.borderedProminent) .disabled(sources.isEmpty || state.settings.ingest.primaryDestination.isEmpty || state.ingestRunning) } } - .padding(16) - .frame(width: 620, height: 660) - .onAppear { - if !state.pendingIngestSources.isEmpty { sources = state.pendingIngestSources } - else if sources.isEmpty { sources = detectCards() } - } + .padding(18) + .frame(width: 980) + .onAppear(perform: setup) } - private func folderRow(_ title: String, path: Binding) -> some View { - HStack { - TextField(title, text: path) - Button("Wählen …") { - let p = NSOpenPanel(); p.canChooseDirectories = true; p.canChooseFiles = false; p.canCreateDirectories = true - if p.runModal() == .OK, let u = p.url { path.wrappedValue = u.path } + // MARK: Left + + private var leftColumn: some View { + VStack(alignment: .leading, spacing: 12) { + GroupBox("Quelle") { + VStack(alignment: .leading, spacing: 8) { + Picker("Ingest:", selection: $mode) { + ForEach(SourceMode.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + .pickerStyle(.radioGroup) + .horizontalRadioGroupLayout() + + switch mode { + case .disks: + List(cards, selection: $selectedCards) { c in + HStack { + Image(systemName: "sdcard") + Text(c.name) + Spacer() + Text(c.used).foregroundStyle(.secondary) + } + .tag(c.dcim) + } + .frame(height: 150) + HStack { + Button("Neu suchen") { rescan() } + Button("Auswerfen") { + for c in cards where selectedCards.contains(c.dcim) { try? NSWorkspace.shared.unmountAndEjectDevice(at: c.volume) } + rescan() + } + .disabled(selectedCards.isEmpty) + } + case .folders: + List(folders, id: \.self) { Text($0.path).lineLimit(1).truncationMode(.middle) }.frame(height: 150) + HStack { + Button("Ordner hinzufügen …") { pickFolders() } + Button("Leeren") { folders = [] }.disabled(folders.isEmpty) + } + case .selection: + Text("\(state.selectedItems.count) ausgewählte Bilder aus \(sources.count) Ordner(n)") + .foregroundStyle(.secondary) + .frame(height: 150, alignment: .center) + } + Toggle("Inkrementell: nur neue Fotos kopieren", isOn: ingest.incremental) + Toggle("Ingest-Fenster öffnen, wenn eine Karte erkannt wird", isOn: $state.settings.autoIngestOnCardMount) + } + .padding(6) + } + + GroupBox { + VStack(alignment: .leading, spacing: 8) { + Picker("Ordnerstruktur der Quelle:", selection: ingest.preserveStructure) { + Text("ignorieren – alle Fotos in dasselbe Ziel").tag(false) + Text("beibehalten (DCIM/100…)").tag(true) + } + HStack { + Text("In Ordner mit Namen:") + TextField("{day0}.{month0}.{year4} - Ereignis", text: ingest.folderPattern) + .textFieldStyle(.roundedBorder) + } + } + .padding(6) } } } - private func pickSource() { - let p = NSOpenPanel(); p.canChooseDirectories = true; p.canChooseFiles = false; p.allowsMultipleSelection = true - if p.runModal() == .OK { sources += p.urls } + // MARK: Right + + private var rightColumn: some View { + VStack(alignment: .leading, spacing: 12) { + GroupBox("Zielordner") { + VStack(alignment: .leading, spacing: 6) { + HStack { + Text("Primär:").frame(width: 80, alignment: .leading) + Button("Primäres Ziel …") { pick(ingest.primaryDestination) } + } + Text(state.settings.ingest.primaryDestination.isEmpty ? "–" : state.settings.ingest.primaryDestination) + .font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) + HStack { + Toggle("Sekundär:", isOn: ingest.secondaryEnabled).frame(width: 80, alignment: .leading) + Button("Sekundäres Ziel …") { pick(ingest.backupDestination) } + .disabled(!state.settings.ingest.secondaryEnabled) + } + if state.settings.ingest.secondaryEnabled { + Text(state.settings.ingest.backupDestination.isEmpty ? "–" : state.settings.ingest.backupDestination) + .font(.caption).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle) + } + } + .padding(6) + } + + GroupBox("Dateien filtern") { + VStack(alignment: .leading, spacing: 6) { + Picker("", selection: ingest.lockedFilter) { + ForEach(LockedFilter.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + .labelsHidden() + Picker("", selection: ingest.rawFilter) { + ForEach(RawFilter.allCases, id: \.self) { Text($0.rawValue).tag($0) } + } + .labelsHidden() + Toggle("In der Kamera gesperrte Fotos taggen", isOn: ingest.tagLockedPhotos) + .help("Geschützte Fotos (Schlüssel-Symbol in der Kamera) bekommen den PM-Tag") + Divider() + Toggle("Metadaten-Vorlage anwenden", isOn: ingest.applyTemplate) + Picker("Vorlage", selection: ingest.templateID) { + Text("–").tag(UUID?.none) + ForEach(state.templates) { Text($0.name).tag(UUID?.some($0.id)) } + } + .disabled(!state.settings.ingest.applyTemplate) + } + .padding(6) + } + + GroupBox { + VStack(alignment: .leading, spacing: 6) { + Toggle("Fotos umbenennen in:", isOn: ingest.renameEnabled) + TextField("@leon.tonhaeuser-{seqn}", text: ingest.renamePattern) + .textFieldStyle(.roundedBorder) + .disabled(!state.settings.ingest.renameEnabled) + HStack { + Toggle("Sequenz {seqn} =", isOn: ingest.sequenceEnabled) + TextField("", value: ingest.startSequence, format: .number.grouping(.never)) + .textFieldStyle(.roundedBorder) + .frame(width: 110) + .disabled(!state.settings.ingest.sequenceEnabled) + } + } + .padding(6) + } + + GroupBox { + VStack(alignment: .leading, spacing: 6) { + Toggle("Kontaktabzug während des Ingests öffnen", isOn: ingest.openAfterIngest) + Toggle("Kontaktabzug im Hintergrund öffnen", isOn: ingest.openInBackground) + .disabled(!state.settings.ingest.openAfterIngest) + Toggle("Karte(n) nach dem Ingest auswerfen", isOn: ingest.unmountAfter) + } + .padding(6) + } + } } - private func detectCards() -> [URL] { - let vols = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil, options: [.skipHiddenVolumes]) ?? [] - return vols.map { $0.appendingPathComponent("DCIM") }.filter { FileManager.default.fileExists(atPath: $0.path) } + private var pathPreview: some View { + let s = state.settings.ingest + let name = s.renameEnabled ? s.renamePattern : "{filenamebase}" + let ctx = VariableContext(values: ["seqn": String(s.startSequence)]) + return HStack { + Text("Ziel:").foregroundStyle(.secondary) + Text("\(s.primaryDestination)/\(s.folderPattern)/\(VariableExpander.expand(name, context: ctx)).NEF") + .lineLimit(1).truncationMode(.middle).textSelection(.enabled) + Spacer() + } + .font(.caption) + } + + // MARK: Helpers + + private func setup() { + rescan() + if !state.pendingIngestSources.isEmpty { + mode = .disks + selectedCards = Set(state.pendingIngestSources) + } else if selectedCards.isEmpty, let first = cards.first { + selectedCards = [first.dcim] + } + } + + private func rescan() { + let keys: [URLResourceKey] = [.volumeLocalizedNameKey, .volumeTotalCapacityKey, .volumeAvailableCapacityKey] + let vols = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: keys, options: [.skipHiddenVolumes]) ?? [] + cards = vols.compactMap { v in + let dcim = v.appendingPathComponent("DCIM") + guard FileManager.default.fileExists(atPath: dcim.path) else { return nil } + let r = try? v.resourceValues(forKeys: Set(keys)) + let used = Int64((r?.volumeTotalCapacity ?? 0) - (r?.volumeAvailableCapacity ?? 0)) + return Card(volume: v, dcim: dcim, name: r?.volumeLocalizedName ?? v.lastPathComponent, + used: ByteCountFormatter.string(fromByteCount: used, countStyle: .file) + " belegt") + } + selectedCards = selectedCards.filter { id in cards.contains { $0.dcim == id } } + } + + private func pickFolders() { + let p = NSOpenPanel(); p.canChooseDirectories = true; p.canChooseFiles = false; p.allowsMultipleSelection = true + if p.runModal() == .OK { folders += p.urls } + } + + private func pick(_ path: Binding) { + let p = NSOpenPanel(); p.canChooseDirectories = true; p.canChooseFiles = false; p.canCreateDirectories = true + if p.runModal() == .OK, let u = p.url { path.wrappedValue = u.path } } } diff --git a/Sources/Lichtkasten/Views/PreviewView.swift b/Sources/Lichtkasten/Views/PreviewView.swift index 2afce68..0348e25 100644 --- a/Sources/Lichtkasten/Views/PreviewView.swift +++ b/Sources/Lichtkasten/Views/PreviewView.swift @@ -4,37 +4,43 @@ import LichtkastenCore struct PreviewView: View { @EnvironmentObject var state: AppState @State private var image: NSImage? + @State private var fullResLoadedFor: String? var body: some View { ZStack(alignment: .bottom) { Color.black if let image { - if state.zoom100 { - ScrollView([.horizontal, .vertical]) { - Image(nsImage: image) - .frame(width: image.size.width / (NSScreen.main?.backingScaleFactor ?? 2), - height: image.size.height / (NSScreen.main?.backingScaleFactor ?? 2)) - } - } else { - Image(nsImage: image).resizable().scaledToFit().padding(8) + ZoomableImageView(image: image, maxZoom: CGFloat(state.settings.maxZoom), request: state.zoomRequest) { mag, fit in + state.zoom100 = !fit + state.zoomPercent = Int((mag * 100).rounded()) + if !fit { Task { await loadFullRes() } } } } else { ProgressView() } if let item = state.cursorItem { infoBar(item) } } - .onTapGesture(count: 2) { state.previewMode = false } - .task(id: "\(state.cursorID ?? "")|\(state.zoom100)") { await load() } + .task(id: state.cursorID) { await load() } } private func load() async { guard let item = state.cursorItem else { image = nil; return } let url = state.previewURL(for: item) - // Show the thumbnail immediately, then the big preview. image = ImageLoader.shared.cachedPreview(url) ?? ImageLoader.shared.cachedThumbnail(url) - let maxPixel = state.zoom100 ? 8000 : 3200 - if let big = await ImageLoader.shared.preview(for: url, maxPixel: maxPixel), state.cursorID == item.id { + if let big = await ImageLoader.shared.preview(for: url, maxPixel: state.zoom100 ? 9000 : 3200), state.cursorID == item.id { image = big + fullResLoadedFor = state.zoom100 ? item.id : nil + } + } + + /// Zooming in needs the full-resolution image (fit view uses a 3200 px preview). + private func loadFullRes() async { + guard let item = state.cursorItem, fullResLoadedFor != item.id else { return } + fullResLoadedFor = item.id + let url = state.previewURL(for: item) + if let full = await Task.detached(priority: .userInitiated, operation: { ImageLoader.makeImage(url, maxPixel: 9000, minAcceptable: 4000) }).value, + state.cursorID == item.id { + image = full } } @@ -52,7 +58,14 @@ struct PreviewView: View { item.exif["ExposureTime"].map { "\($0) s" }, item.exif["FNumber"].map { "f/\($0)" }, item.exif["ISO"].map { "ISO \($0)" }].compactMap { $0 }.joined(separator: " · ")) .foregroundStyle(.secondary) - Text(state.zoom100 ? "100 % (Z)" : "Einpassen (Z)").foregroundStyle(.secondary) + HStack(spacing: 4) { + Button { state.zoom(.zoomOut) } label: { Image(systemName: "minus.magnifyingglass") } + Button { state.zoom(.fit) } label: { Text(state.zoom100 ? "\(state.zoomPercent) %" : "Einpassen").monospacedDigit().frame(minWidth: 70) } + .help("Einpassen (Z)") + Button { state.zoom(.actual) } label: { Text("100 %") } + Button { state.zoom(.zoomIn) } label: { Image(systemName: "plus.magnifyingglass") } + } + .buttonStyle(.borderless) } .font(.callout) .padding(.horizontal, 14) diff --git a/Sources/Lichtkasten/Views/SettingsView.swift b/Sources/Lichtkasten/Views/SettingsView.swift index 8d71cf6..1b7c4a7 100644 --- a/Sources/Lichtkasten/Views/SettingsView.swift +++ b/Sources/Lichtkasten/Views/SettingsView.swift @@ -27,6 +27,15 @@ struct GeneralSettings: View { Text("1–8 = Farbklasse · 0 = keine · ⌥1–5 = Sterne · T = Tag · I = IPTC-Info · ⌘I = IPTC für Auswahl · ⌘U = Hochladen · ⌘E = Lightroom · ⌘⌥S = INPUT ⇄ SENT") .font(.caption).foregroundStyle(.secondary) } + Section("Zoom") { + Picker("Maximaler Zoom in der Vorschau", selection: $state.settings.maxZoom) { + Text("100 %").tag(1.0); Text("200 %").tag(2.0); Text("400 %").tag(4.0); Text("800 %").tag(8.0); Text("1600 %").tag(16.0) + } + Slider(value: $state.settings.maxThumbnailSize, in: 300...1200, step: 50) { + Text("Größte Vorschaubilder: \(Int(state.settings.maxThumbnailSize)) px") + } + Text("Vorschau: Z = Einpassen/100 %, + / − oder Trackpad zum Zoomen.").font(.caption).foregroundStyle(.secondary) + } Section("Ingest") { Toggle("Ingest-Fenster öffnen, wenn eine Speicherkarte erkannt wird", isOn: $state.settings.autoIngestOnCardMount) } diff --git a/Sources/Lichtkasten/Views/TemplateViews.swift b/Sources/Lichtkasten/Views/TemplateViews.swift index b4178b6..7372e62 100644 --- a/Sources/Lichtkasten/Views/TemplateViews.swift +++ b/Sources/Lichtkasten/Views/TemplateViews.swift @@ -113,8 +113,6 @@ struct TemplateManagerView: View { if state.templates[i].appliedFields == nil { Toggle("Leere Felder löschen", isOn: $state.templates[i].clearEmptyFields) } - Toggle("Datum = Aufnahmezeit", isOn: $state.templates[i].dateFromCapture) - .help("Erstellungsdatum/-zeit aus der EXIF-Aufnahmezeit jedes Bildes (PM: Apply Date → Capture Date)") } .font(.callout) if !state.templates[i].unmappedPMCodes.isEmpty { diff --git a/Sources/Lichtkasten/Views/ZoomableImageView.swift b/Sources/Lichtkasten/Views/ZoomableImageView.swift new file mode 100644 index 0000000..c8c714d --- /dev/null +++ b/Sources/Lichtkasten/Views/ZoomableImageView.swift @@ -0,0 +1,120 @@ +import AppKit +import SwiftUI + +enum ZoomAction: Equatable { case fit, actual, zoomIn, zoomOut } + +struct ZoomRequest: Equatable { + let action: ZoomAction + let token = UUID() +} + +/// Scroll view that keeps the image fitted while in "fit" mode (also on window resize). +final class FitScrollView: NSScrollView { + var fitMode = true + var onMagnification: ((CGFloat, Bool) -> Void)? + + var fitMagnification: CGFloat { + guard let doc = documentView, doc.frame.width > 0, doc.frame.height > 0 else { return 1 } + let size = contentView.bounds.size.applying(CGAffineTransform(scaleX: magnification, y: magnification)) + return min(size.width / doc.frame.width, size.height / doc.frame.height) + } + + override func layout() { + super.layout() + if fitMode { applyFit() } + } + + func applyFit() { + let m = fitMagnification + minMagnification = min(m, 0.05) + magnification = m + centerDocument() + } + + func centerDocument() { + guard let doc = documentView else { return } + let clip = contentView.bounds.size + let x = max(0, (doc.frame.width - clip.width) / 2) + let y = max(0, (doc.frame.height - clip.height) / 2) + contentView.scroll(to: NSPoint(x: x, y: y)) + reflectScrolledClipView(contentView) + } + + override func magnify(with event: NSEvent) { + super.magnify(with: event) + fitMode = false + onMagnification?(magnification, false) + } +} + +/// PM-style loupe: fit, 100 % (Z), pinch / +/- up to `maxZoom`. +struct ZoomableImageView: NSViewRepresentable { + let image: NSImage + let maxZoom: CGFloat + let request: ZoomRequest? + let onZoomChange: (CGFloat, Bool) -> Void // magnification, isFit + + final class Coordinator { var lastToken: UUID?; var lastImage: NSImage? } + func makeCoordinator() -> Coordinator { Coordinator() } + + func makeNSView(context: Context) -> FitScrollView { + let sv = FitScrollView() + sv.hasHorizontalScroller = true + sv.hasVerticalScroller = true + sv.autohidesScrollers = true + sv.allowsMagnification = true + sv.drawsBackground = true + sv.backgroundColor = .black + sv.contentView = CenteringClipView() + let iv = NSImageView() + iv.imageScaling = .scaleAxesIndependently + sv.documentView = iv + sv.onMagnification = { m, fit in onZoomChange(m, fit) } + return sv + } + + func updateNSView(_ sv: FitScrollView, context: Context) { + sv.maxMagnification = maxZoom + guard let iv = sv.documentView as? NSImageView else { return } + if context.coordinator.lastImage !== image { + context.coordinator.lastImage = image + // Document size in points = pixel size / backing scale → magnification 1 == 100 % pixels. + let scale = sv.window?.backingScaleFactor ?? 2 + let px = image.representations.first.map { CGSize(width: $0.pixelsWide, height: $0.pixelsHigh) } ?? image.size + let oldFit = sv.fitMode + let oldMag = sv.magnification + iv.image = image + iv.frame = NSRect(origin: .zero, size: CGSize(width: px.width / scale, height: px.height / scale)) + if oldFit { sv.applyFit() } else { sv.magnification = min(oldMag, maxZoom) } + } + if let req = request, req.token != context.coordinator.lastToken { + context.coordinator.lastToken = req.token + switch req.action { + case .fit: + sv.fitMode = true + sv.applyFit() + case .actual: + sv.fitMode = false + sv.setMagnification(1, centeredAt: NSPoint(x: iv.frame.midX, y: iv.frame.midY)) + case .zoomIn: + sv.fitMode = false + sv.animator().magnification = min(maxZoom, sv.magnification * 1.5) + case .zoomOut: + let next = sv.magnification / 1.5 + if next <= sv.fitMagnification { sv.fitMode = true; sv.applyFit() } else { sv.animator().magnification = next } + } + DispatchQueue.main.async { onZoomChange(sv.magnification, sv.fitMode) } + } + } +} + +/// Keeps a smaller-than-viewport image centered. +final class CenteringClipView: NSClipView { + override func constrainBoundsRect(_ proposedBounds: NSRect) -> NSRect { + var rect = super.constrainBoundsRect(proposedBounds) + guard let doc = documentView else { return rect } + if rect.width > doc.frame.width { rect.origin.x = (doc.frame.width - rect.width) / 2 } + if rect.height > doc.frame.height { rect.origin.y = (doc.frame.height - rect.height) / 2 } + return rect + } +} diff --git a/Sources/LichtkastenCore/Ingest/IngestService.swift b/Sources/LichtkastenCore/Ingest/IngestService.swift index 3400e9e..afa11c4 100644 --- a/Sources/LichtkastenCore/Ingest/IngestService.swift +++ b/Sources/LichtkastenCore/Ingest/IngestService.swift @@ -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(_ 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 { + guard let d = try? Data(contentsOf: historyURL), let s = try? JSONDecoder().decode(Set.self, from: d) else { return [] } + return s + } + + static func saveHistory(_ s: Set) { + 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..() + 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 { diff --git a/Sources/LichtkastenCore/Library/MetadataCache.swift b/Sources/LichtkastenCore/Library/MetadataCache.swift index dc4bec4..4f1660d 100644 --- a/Sources/LichtkastenCore/Library/MetadataCache.swift +++ b/Sources/LichtkastenCore/Library/MetadataCache.swift @@ -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 } diff --git a/Sources/LichtkastenCore/Library/PhotoItem.swift b/Sources/LichtkastenCore/Library/PhotoItem.swift index 381cf71..6e3b550 100644 --- a/Sources/LichtkastenCore/Library/PhotoItem.swift +++ b/Sources/LichtkastenCore/Library/PhotoItem.swift @@ -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 { diff --git a/Sources/LichtkastenCore/Metadata/ExifTool.swift b/Sources/LichtkastenCore/Metadata/ExifTool.swift index 4fdac9f..5517e08 100644 --- a/Sources/LichtkastenCore/Metadata/ExifTool.swift +++ b/Sources/LichtkastenCore/Metadata/ExifTool.swift @@ -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#"] diff --git a/Sources/LichtkastenCore/Metadata/MetadataWriter.swift b/Sources/LichtkastenCore/Metadata/MetadataWriter.swift index eaededf..ab81ca7 100644 --- a/Sources/LichtkastenCore/Metadata/MetadataWriter.swift +++ b/Sources/LichtkastenCore/Metadata/MetadataWriter.swift @@ -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]) diff --git a/Sources/LichtkastenCore/Metadata/Variables.swift b/Sources/LichtkastenCore/Metadata/Variables.swift index 6025f61..303719d 100644 --- a/Sources/LichtkastenCore/Metadata/Variables.swift +++ b/Sources/LichtkastenCore/Metadata/Variables.swift @@ -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) diff --git a/Sources/LichtkastenCore/Metadata/XMPTemplateIO.swift b/Sources/LichtkastenCore/Metadata/XMPTemplateIO.swift index 19a43f6..c172fd3 100644 --- a/Sources/LichtkastenCore/Metadata/XMPTemplateIO.swift +++ b/Sources/LichtkastenCore/Metadata/XMPTemplateIO.swift @@ -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 diff --git a/Tests/LichtkastenCoreTests/CoreTests.swift b/Tests/LichtkastenCoreTests/CoreTests.swift index 42d7fee..d8c6237 100644 --- a/Tests/LichtkastenCoreTests/CoreTests.swift +++ b/Tests/LichtkastenCoreTests/CoreTests.swift @@ -119,6 +119,7 @@ final class PMSnapTests: XCTestCase { "creator", "caption", "headline", "copyright", "sublocation", "event"]) XCTAssertEqual(t.listMergeMode, .replace) XCTAssertTrue(t.dateFromCapture) + XCTAssertEqual(t.values.text["dateCreated"], "{capturetime}") XCTAssertTrue(t.unmappedPMCodes.isEmpty) // PM bookkeeping does not leak into extras XCTAssertNil(t.extras["\(XMPNamespace.photomechanic)|FieldsToApply"]) @@ -137,3 +138,19 @@ final class PMSnapTests: XCTestCase { ["-XMP-photoshop:DateCreated=2026:11:02 14:22:01+01:00", "-IPTC:DateCreated=2026:11:02", "-IPTC:TimeCreated=14:22:01+01:00"]) } } + +final class PMPrefsTests: XCTestCase { + func testParsesRawAndPrintedPrefs() { + XCTAssertEqual(PhotoItem.parsePMPrefs("1:3:4:-00001"), .init(tagged: true, colorClass: 3, rating: 4, frame: "-00001")) + XCTAssertEqual(PhotoItem.parsePMPrefs("Tagged:0, ColorClass:1, Rating:0, FrameNum:-00001")?.colorClass, 1) + XCTAssertNil(PhotoItem.parsePMPrefs("garbage")) + } + + func testTagFromIPTCPrefsOnly() { + var item = PhotoItem(primary: URL(fileURLWithPath: "/x/a.jpg")) + item.apply(fileMeta: ["IPTC:Prefs": .string("1:1:0:-00001")], sidecarMeta: nil) + XCTAssertTrue(item.tagged) + XCTAssertEqual(item.label, .red) + XCTAssertEqual(item.pmPrefsString, "1:1:0:-00001") + } +} diff --git a/scripts/make-icon.py b/scripts/make-icon.py new file mode 100644 index 0000000..c7d2832 --- /dev/null +++ b/scripts/make-icon.py @@ -0,0 +1,101 @@ +from PIL import Image, ImageDraw, ImageFilter, ImageChops +import math +S=2048 # supersampled +def lerp(a,b,t): return tuple(int(a[i]+(b[i]-a[i])*t) for i in range(len(a))) +def vgrad(w,h,top,bot): + g=Image.new('RGBA',(w,h)) + d=ImageDraw.Draw(g) + for y in range(h): + d.line([(0,y),(w,y)],fill=lerp(top,bot,y/(h-1))) + return g +def squircle_mask(size, box, n=5.0): + m=Image.new('L',(size,size),0); d=ImageDraw.Draw(m) + x0,y0,x1,y1=box; cx=(x0+x1)/2; cy=(y0+y1)/2; a=(x1-x0)/2; b=(y1-y0)/2 + pts=[] + for i in range(720): + t=2*math.pi*i/720; c=math.cos(t); s=math.sin(t) + pts.append((cx+a*math.copysign(abs(c)**(2/n),c), cy+b*math.copysign(abs(s)**(2/n),s))) + d.polygon(pts,fill=255); return m +def rrect_mask(size,box,r): + m=Image.new('L',size,0); ImageDraw.Draw(m).rounded_rectangle(box,radius=r,fill=255); return m + +img=Image.new('RGBA',(S,S),(0,0,0,0)) +pad=int(S*0.098); box=(pad,pad,S-pad,S-pad) +# drop shadow of body +sh=Image.new('RGBA',(S,S),(0,0,0,0)); shm=squircle_mask(S,(box[0],box[1]+30,box[2],box[3]+30)) +sh.putalpha(shm.point(lambda v:int(v*0.45))); sh=sh.filter(ImageFilter.GaussianBlur(40)); img=Image.alpha_composite(img,sh) +# body: deep graphite → midnight blue +body=vgrad(S,S,(52,58,72,255),(16,19,28,255)); bm=squircle_mask(S,box) +layer=Image.new('RGBA',(S,S),(0,0,0,0)); layer.paste(body,(0,0),bm); img=Image.alpha_composite(img,layer) + +# light table panel (glowing) +pw,ph=int(S*0.60),int(S*0.46); px=(S-pw)//2; py=int(S*0.30) +glow=Image.new('RGBA',(S,S),(0,0,0,0)); gd=ImageDraw.Draw(glow) +gd.rounded_rectangle((px-60,py-60,px+pw+60,py+ph+60),radius=120,fill=(255,214,140,170)) +glow=glow.filter(ImageFilter.GaussianBlur(90)); glow.putalpha(ImageChops.multiply(glow.getchannel('A'),bm)) +img=Image.alpha_composite(img,glow) +panel=vgrad(pw,ph,(255,250,236,255),(255,226,170,255)) +pm=rrect_mask((pw,ph),(0,0,pw-1,ph-1),70) +img.paste(panel,(px,py),pm) +# subtle grid lines on the light table +grid=Image.new('RGBA',(S,S),(0,0,0,0)); gdd=ImageDraw.Draw(grid) +for i in range(1,6): + x=px+pw*i//6; gdd.line([(x,py+20),(x,py+ph-20)],fill=(210,160,90,60),width=4) +for j in range(1,4): + y=py+ph*j//4; gdd.line([(px+20,y),(px+pw-20,y)],fill=(210,160,90,60),width=4) +img=Image.alpha_composite(img,grid) + +def slide(cx,cy,w,angle,photo): + s=Image.new('RGBA',(w,w),(0,0,0,0)); d=ImageDraw.Draw(s) + d.rounded_rectangle((0,0,w-1,w-1),radius=int(w*0.09),fill=(250,250,246,255)) + iw,ih=int(w*0.66),int(w*0.46); ix=(w-iw)//2; iy=int(w*0.20) + ph=photo(iw,ih); s.paste(ph,(ix,iy),rrect_mask((iw,ih),(0,0,iw-1,ih-1),10)) + # label strip + d.rounded_rectangle((ix,iy+ih+int(w*0.07),ix+int(iw*0.55),iy+ih+int(w*0.11)),radius=8,fill=(200,200,195,255)) + s=s.rotate(angle,resample=Image.BICUBIC,expand=True) + shadow=Image.new('RGBA',s.size,(0,0,0,0)); shadow.putalpha(s.getchannel('A').point(lambda v:int(v*0.35))) + shadow=shadow.filter(ImageFilter.GaussianBlur(22)) + return s,shadow +def photo_stadium(w,h): + p=vgrad(w,h,(24,70,140,255),(255,150,70,255)); d=ImageDraw.Draw(p) + d.rectangle((0,int(h*0.68),w,h),fill=(28,120,70,255)) # pitch + for k in range(5): d.line([(int(w*k/4),int(h*0.68)),(int(w*(k/4-0.1)),h)],fill=(40,140,85,255),width=5) + d.ellipse((int(w*0.62),int(h*0.15),int(w*0.80),int(h*0.15)+int(w*0.18)),fill=(255,236,190,255)) # floodlight/sun + return p +def photo_mountain(w,h): + p=vgrad(w,h,(120,170,220,255),(230,235,240,255)); d=ImageDraw.Draw(p) + d.polygon([(0,h),(int(w*0.35),int(h*0.35)),(int(w*0.6),int(h*0.75)),(int(w*0.78),int(h*0.45)),(w,h)],fill=(52,70,95,255)) + return p + +for (cx,cy,w,ang,ph) in [(int(S*0.40),int(S*0.53),int(S*0.30),8,photo_mountain),(int(S*0.60),int(S*0.52),int(S*0.33),-6,photo_stadium)]: + s,shadow=slide(cx,cy,w,ang,ph) + ox,oy=cx-s.size[0]//2,cy-s.size[1]//2 + img.alpha_composite(shadow,(ox+14,oy+26)); img.alpha_composite(s,(ox,oy)) + +# loupe +L=Image.new('RGBA',(S,S),(0,0,0,0)); ld=ImageDraw.Draw(L) +lcx,lcy,lr=int(S*0.64),int(S*0.62),int(S*0.105) +ld.line([(lcx+int(lr*0.72),lcy+int(lr*0.72)),(lcx+int(lr*1.32),lcy+int(lr*1.32))],fill=(30,32,40,255),width=int(S*0.045)) +ld.ellipse((lcx-lr,lcy-lr,lcx+lr,lcy+lr),outline=(30,32,40,255),width=int(S*0.028)) +ld.ellipse((lcx-lr+30,lcy-lr+30,lcx+lr-30,lcy+lr-30),fill=(200,225,255,70)) +ld.arc((lcx-lr+70,lcy-lr+70,lcx+lr-70,lcy+lr-70),200,250,fill=(255,255,255,200),width=18) +lsh=Image.new('RGBA',(S,S),(0,0,0,0)); lsh.putalpha(L.getchannel('A').point(lambda v:int(v*0.4))); lsh=lsh.filter(ImageFilter.GaussianBlur(20)) +img.alpha_composite(lsh,(10,22)); img=Image.alpha_composite(img,L) + +# PM-style tag check (accent) bottom-left of panel +T=Image.new('RGBA',(S,S),(0,0,0,0)); td=ImageDraw.Draw(T) +tx,ty,ts=int(S*0.235),int(S*0.645),int(S*0.12) +td.rounded_rectangle((tx,ty,tx+ts,ty+ts),radius=int(ts*0.22),fill=(232,64,52,255)) +td.line([(tx+ts*0.24,ty+ts*0.53),(tx+ts*0.43,ty+ts*0.72),(tx+ts*0.78,ty+ts*0.30)],fill=(255,255,255,255),width=int(ts*0.13),joint='curve') +tsh=Image.new('RGBA',(S,S),(0,0,0,0)); tsh.putalpha(T.getchannel('A').point(lambda v:int(v*0.35))); tsh=tsh.filter(ImageFilter.GaussianBlur(16)) +img.alpha_composite(tsh,(8,18)); img=Image.alpha_composite(img,T) + +# soft top sheen +shm2=Image.new('L',(S,S),0); ImageDraw.Draw(shm2).ellipse((-S*0.3,-S*0.75,S*1.3,S*0.42),fill=70) +shm2=ImageChops.multiply(shm2.filter(ImageFilter.GaussianBlur(120)),squircle_mask(S,box)) +sl=Image.new('RGBA',(S,S),(255,255,255,0)); sl.putalpha(shm2); img=Image.alpha_composite(img,sl) +out=img.resize((1024,1024),Image.LANCZOS) +out.save('/home/user/Lichtkasten/Resources/Icon/AppIcon-1024.png') +out.save('/home/user/Lichtkasten/Resources/AppIcon.icns', sizes=[(16,16),(32,32),(64,64),(128,128),(256,256),(512,512),(1024,1024)]) +out.resize((256,256),Image.LANCZOS).save('/home/user/Lichtkasten/Resources/Icon/AppIcon-256.png') +print('ok')