Bilder per Drag & Drop verschieben, neue Ordner anlegen

- Bilder aus dem Kontaktabzug auf einen Ordner in der Seitenleiste ziehen = verschieben (ganze Auswahl,
  RAW + JPEG + XMP zusammen, Namenskollision → -1, Gesendet-Status zieht mit, alles-oder-nichts pro Bild)
- aus dem Finder gezogene Bilder werden in den Ordner kopiert
- Ordner hebt sich beim Darüberziehen hervor, Vorschau mit Anzahl unter dem Zeiger
- „Neuer Ordner …“ per Rechtsklick auf jeden Ordner, Knopf bei Favoriten legt ihn in INPUT an
  (Name mit heutigem Datum vorbelegt), danach wird er geöffnet

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-08 17:47:22 +00:00
1 parent 244734c59f
commit 223d8b0610
7 files changed
+211 -1

No files matched your search

+104
View File
@@ -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
@@ -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)
}
}
}
}
@@ -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 {