diff --git a/README.md b/README.md index 148801b..c5a3c8a 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ Zum Entwickeln `Package.swift` in Xcode öffnen und das Scheme **Lichtkasten** s | Leertaste | Vorschau · Z = Einpassen/100 % · +/− oder Trackpad = Zoom (max. einstellbar) | | F (in der Vorschau) | Fokus: Werkzeugleiste, Tabs, Matchday-Kopf, Filter und Seitenleiste aus – nur Bild, Filmstreifen und IPTC-Panel | | ⌘A / ⌘⌫ | Alle Bilder auswählen / Auswahl in den Papierkorb | +| Ziehen auf Ordner | Bilder (RAW + JPEG + XMP) in einen Ordner der Seitenleiste verschieben; aus dem Finder gezogene Dateien werden kopiert. Rechtsklick auf Ordner oder 📁+ bei Favoriten = neuer Ordner (in INPUT) | Unter Einstellungen → Allgemein lässt sich auf die Lightroom-Belegung umstellen (0–5 = Sterne, 6–9 = Farben). diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index 6cccecc..a6dc521 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -814,6 +814,110 @@ final class AppState: ObservableObject { func selectAll() { selection = Set(visible.map(\.id)) } + // MARK: - Moving photos / folders + + /// Prefix of the drag payload for photos dragged out of the contact sheet (one path per line). + static let dragPrefix = "lichtkasten-photos\n" + + /// Drag payload: the whole selection if the dragged photo is part of it, else just that photo. + func dragPayload(for item: PhotoItem) -> String { + let ids = selection.contains(item.id) ? selectedItems.map(\.id) : [item.id] + return Self.dragPrefix + ids.joined(separator: "\n") + } + + /// Drop on a folder in the sidebar. Photos from the contact sheet are moved (RAW + JPEG + XMP together, + /// sent status and selection follow); files dragged in from the Finder are copied. + @discardableResult + func handleDrop(_ strings: [String], urls: [URL], on folder: URL) -> Bool { + if let payload = strings.first(where: { $0.hasPrefix(Self.dragPrefix) }) { + let ids = payload.dropFirst(Self.dragPrefix.count).split(separator: "\n").map(String.init) + let photos = ids.compactMap { item($0) } + guard !photos.isEmpty else { return false } + movePhotos(photos, to: folder) + return true + } + let files = urls.filter { $0.isFileURL && (FileKind(url: $0).isImage || $0.pathExtension.lowercased() == "xmp") } + guard !files.isEmpty else { return false } + copyFiles(files, to: folder) + return true + } + + func movePhotos(_ photos: [PhotoItem], to folder: URL) { + let fm = FileManager.default + guard photos.contains(where: { $0.primary.deletingLastPathComponent().standardizedFileURL != folder.standardizedFileURL }) else { return } + var moved = 0 + var failed: [String] = [] + for p in photos where p.primary.deletingLastPathComponent().standardizedFileURL != folder.standardizedFileURL { + var files = [p.primary] + p.companions + if p.kind.usesSidecar, fm.fileExists(atPath: p.sidecarURL.path) { files.append(p.sidecarURL) } + let name = IngestService.uniqueName(p.baseName, files: files, in: folder, skipDuplicates: false).name + var done: [(URL, URL)] = [] + do { + for f in files { + let dest = folder.appendingPathComponent(name).appendingPathExtension(f.pathExtension) + try fm.moveItem(at: f, to: dest) + done.append((f, dest)) + } + for (from, to) in done { sentLog.move(from: from, to: to) } + moved += 1 + } catch { + for (from, to) in done.reversed() { try? fm.moveItem(at: to, to: from) } // all or nothing per photo + failed.append("\(p.filename): \(error.localizedDescription)") + } + } + scheduleSentLogSave() + refreshFolder() + statusText = "\(moved) Bild(er) nach „\(folder.lastPathComponent)“ verschoben" + if !failed.isEmpty { alert = AppAlert(title: "Nicht alles verschoben", message: failed.joined(separator: "\n")) } + } + + private func copyFiles(_ files: [URL], to folder: URL) { + let fm = FileManager.default + var copied = 0 + for f in files { + let base = f.deletingPathExtension().lastPathComponent + let name = IngestService.uniqueName(base, files: [f], in: folder, skipDuplicates: true) + if name.skip { continue } + do { + try fm.copyItem(at: f, to: folder.appendingPathComponent(name.name).appendingPathExtension(f.pathExtension)) + copied += 1 + } catch { report(error) } + } + if folder == self.folder { refreshFolder() } + statusText = "\(copied) Datei(en) nach „\(folder.lastPathComponent)“ kopiert" + } + + /// "Neuer Ordner …" – asks for a name (preset with today's date like the game folders) and opens it. + @discardableResult + func createFolder(in parent: URL) -> URL? { + let alert = NSAlert() + alert.messageText = "Neuer Ordner in „\(parent.lastPathComponent)“" + let f = DateFormatter(); f.dateFormat = "dd.MM.yyyy" + let field = NSTextField(string: f.string(from: Date()) + " - ") + field.frame = NSRect(x: 0, y: 0, width: 320, height: 24) + alert.accessoryView = field + alert.addButton(withTitle: "Anlegen") + alert.addButton(withTitle: "Abbrechen") + alert.window.initialFirstResponder = field + guard alert.runModal() == .alertFirstButtonReturn else { return nil } + let name = field.stringValue.trimmingCharacters(in: .whitespaces) + .replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: "-") + guard !name.isEmpty else { return nil } + let url = parent.appendingPathComponent(name, isDirectory: true) + if FileManager.default.fileExists(atPath: url.path) { + self.alert = AppAlert(title: "Ordner existiert schon", message: url.path) + return nil + } + do { + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false) + folderTreeVersion += 1 + return url + } catch { report(error); return nil } + } + + /// Bumped when folders are created → the sidebar tree re-reads its sub folders. + @Published var folderTreeVersion = 0 + /// ⌘⌫ – moves the selected photos (RAW, JPEG, XMP sidecar) to the Trash (Finder: "Put Back" restores them). func trashSelected() { let targets = selectedItems diff --git a/Sources/Lichtkasten/Views/ContactSheetView.swift b/Sources/Lichtkasten/Views/ContactSheetView.swift index eb4aa1f..3ab962a 100644 --- a/Sources/Lichtkasten/Views/ContactSheetView.swift +++ b/Sources/Lichtkasten/Views/ContactSheetView.swift @@ -26,6 +26,11 @@ struct ContactSheetView: View { .contentShape(Rectangle()) // Single tap reacts immediately; a double click (clickCount 2) opens the preview. .onTapGesture { click(item) } + // drag onto a folder in the sidebar = move (the whole selection) + .draggable(state.dragPayload(for: item)) { + DragPreview(count: state.selection.contains(item.id) ? max(1, state.selection.count) : 1, + url: state.previewURL(for: item)) + } .contextMenu { ItemContextMenu(item: item) } } } @@ -309,3 +314,30 @@ extension ColorLabel { } } } + + +/// What hangs under the pointer while photos are dragged: thumbnail + count. +struct DragPreview: View { + let count: Int + let url: URL + + var body: some View { + ZStack(alignment: .topTrailing) { + Group { + if let img = ImageLoader.shared.cachedThumbnail(url) { + Image(nsImage: img).resizable().scaledToFill() + } else { + RoundedRectangle(cornerRadius: 6).fill(LK.raised) + } + } + .frame(width: 96, height: 64) + .clipShape(RoundedRectangle(cornerRadius: 6)) + if count > 1 { + Text("\(count)").font(.system(size: 11, weight: .bold)).foregroundStyle(LK.onAmber) + .padding(.horizontal, 6).frame(height: 18) + .background(Capsule().fill(LK.amber)) + .offset(x: 6, y: -6) + } + } + } +} diff --git a/Sources/Lichtkasten/Views/ContentView.swift b/Sources/Lichtkasten/Views/ContentView.swift index e3d1aca..baa3453 100644 --- a/Sources/Lichtkasten/Views/ContentView.swift +++ b/Sources/Lichtkasten/Views/ContentView.swift @@ -1,4 +1,5 @@ import SwiftUI +import UniformTypeIdentifiers import LichtkastenCore /// Main browser window in Photo Mechanic's layout: @@ -342,6 +343,14 @@ struct PMSidebar: View { .padding(.vertical, 4) } } accessory: { + if !state.settings.ingest.primaryDestination.isEmpty { + Button { + let input = URL(fileURLWithPath: state.settings.ingest.primaryDestination, isDirectory: true) + if let new = state.createFolder(in: input) { state.open(folder: new) } + } label: { Image(systemName: "folder.badge.plus") } + .buttonStyle(.borderless) + .help("Neuer Ordner in \(URL(fileURLWithPath: state.settings.ingest.primaryDestination).lastPathComponent)") + } if let f = state.folder, !state.settings.favoriteFolders.contains(f.path) { Button { state.settings.favoriteFolders.append(f.path) } label: { Image(systemName: "plus") } .buttonStyle(.borderless).help("Aktuellen Ordner zu Favoriten") @@ -474,6 +483,7 @@ struct FolderTreeRow: View { var newestFirst = false @State private var expanded = false @State private var children: [URL]? + @State private var dropTarget = false var body: some View { VStack(alignment: .leading, spacing: 0) { @@ -499,8 +509,14 @@ struct FolderTreeRow: View { .padding(.vertical, 5) .foregroundStyle(state.folder == url ? LK.amber : LK.text) .background(RoundedRectangle(cornerRadius: 7).fill(state.folder == url ? LK.selected : Color.clear)) + .overlay(RoundedRectangle(cornerRadius: 7).stroke(LK.amber, lineWidth: dropTarget ? 2 : 0)) .padding(.horizontal, 8) .contentShape(Rectangle()) + // photos from the contact sheet are moved here, files from the Finder copied + .onDrop(of: [UTType.plainText, UTType.fileURL], isTargeted: $dropTarget) { providers in + receive(providers) + return true + } .onTapGesture(count: 1) { state.open(folder: url) // A folder without photos but with sub folders (e.g. INPUT) opens its list right away. @@ -510,6 +526,14 @@ struct FolderTreeRow: View { } } .contextMenu { + Button("Neuer Ordner …") { + if let new = state.createFolder(in: url) { + children = Self.subfolders(of: url, newestFirst: newestFirst) + expanded = true + state.open(folder: new) + } + } + Divider() Button("In neuem Tab öffnen") { state.open(folder: url, newTab: true) } Button("Zu Favoriten") { if !state.settings.favoriteFolders.contains(url.path) { state.settings.favoriteFolders.append(url.path) } } Button("Im Finder zeigen") { NSWorkspace.shared.activateFileViewerSelecting([url]) } @@ -522,6 +546,38 @@ struct FolderTreeRow: View { ForEach(children, id: \.self) { FolderTreeRow(url: $0, depth: depth + 1, newestFirst: newestFirst) } } } + .onChange(of: state.folderTreeVersion) { _, _ in + if expanded { children = Self.subfolders(of: url, newestFirst: newestFirst) } + } + } + + /// Collects the dragged strings (our photo payload) and file URLs (Finder), then hands them to the state. + private func receive(_ providers: [NSItemProvider]) { + let group = DispatchGroup() + final class Box: @unchecked Sendable { var strings: [String] = []; var urls: [URL] = []; let lock = NSLock() } + let box = Box() + for p in providers { + if p.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { + group.enter() + _ = p.loadObject(ofClass: URL.self) { u, _ in + if let u { box.lock.lock(); box.urls.append(u); box.lock.unlock() } + group.leave() + } + } else if p.canLoadObject(ofClass: String.self) { + group.enter() + _ = p.loadObject(ofClass: String.self) { s, _ in + if let s { box.lock.lock(); box.strings.append(s); box.lock.unlock() } + group.leave() + } + } + } + let target = url + group.notify(queue: .main) { + MainActor.assumeIsolated { + state.handleDrop(box.strings, urls: box.urls, on: target) + if expanded { children = Self.subfolders(of: target, newestFirst: newestFirst) } + } + } } private var displayName: String { diff --git a/Sources/LichtkastenCore/Ingest/IngestService.swift b/Sources/LichtkastenCore/Ingest/IngestService.swift index 824dcba..5afcbb6 100644 --- a/Sources/LichtkastenCore/Ingest/IngestService.swift +++ b/Sources/LichtkastenCore/Ingest/IngestService.swift @@ -427,7 +427,7 @@ public enum IngestService { } /// A shared name across destinations that either has no collision or can resume a partial copy. - static func uniqueName(_ base: String, files: [URL], in folder: URL, skipDuplicates: Bool) -> (name: String, skip: Bool) { + public static func uniqueName(_ base: String, files: [URL], in folder: URL, skipDuplicates: Bool) -> (name: String, skip: Bool) { uniqueName(base, files: files, in: [folder], skipDuplicates: skipDuplicates) } diff --git a/Sources/LichtkastenCore/Upload/SentLog.swift b/Sources/LichtkastenCore/Upload/SentLog.swift index 992aadd..f91b413 100644 --- a/Sources/LichtkastenCore/Upload/SentLog.swift +++ b/Sources/LichtkastenCore/Upload/SentLog.swift @@ -30,6 +30,12 @@ public struct SentLog: Codable, Sendable { records[SentLog.key(url), default: []].append(r) } + /// A file was moved (drag & drop into another folder) – its history moves with it. + public mutating func move(from old: URL, to new: URL) { + guard let r = records.removeValue(forKey: SentLog.key(old)) else { return } + records[SentLog.key(new), default: []].append(contentsOf: r) + } + /// Forget the history of these files ("Als nicht gesendet markieren"). public mutating func clear(_ urls: [URL]) { for u in urls { records[SentLog.key(u)] = nil } diff --git a/Tests/LichtkastenCoreTests/CoreTests.swift b/Tests/LichtkastenCoreTests/CoreTests.swift index 42596d5..5dba124 100644 --- a/Tests/LichtkastenCoreTests/CoreTests.swift +++ b/Tests/LichtkastenCoreTests/CoreTests.swift @@ -488,3 +488,14 @@ final class MatchVariableTests: XCTestCase { XCTAssertNil(SpieltagGenerator.teams(fromEvent: "Training")) } } + +final class SentLogMoveTests: XCTestCase { + func testSentStatusFollowsMovedFile() { + var log = SentLog() + let old = URL(fileURLWithPath: "/INPUT/a/x.JPG"), new = URL(fileURLWithPath: "/INPUT/b/x.JPG") + log.record(old, SentRecord(destination: "d1", destinationName: "Sport", remoteName: "x.jpg")) + log.move(from: old, to: new) + XCTAssertTrue(log.wasSent(PhotoItem(primary: new))) + XCTAssertFalse(log.wasSent(PhotoItem(primary: old))) + } +}