- 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
1973 lines
95 KiB
Swift
1973 lines
95 KiB
Swift
import AppKit
|
||
import SwiftUI
|
||
import LichtkastenCore
|
||
|
||
/// PM toolbar filters: Tag popup, star toggles, color class toggles.
|
||
enum TagFilter: String, CaseIterable { case all = "Alle", tagged = "Getaggt", untagged = "Nicht getaggt" }
|
||
|
||
/// "Gesendet"-Filter
|
||
enum SentFilter: String, CaseIterable {
|
||
case all = "Alle", sent = "Gesendet", notSent = "Nicht gesendet"
|
||
case ftp = "Per FTP gesendet", notFTP = "Nicht per FTP gesendet"
|
||
case immich = "An Immich gesendet", notImmich = "Nicht an Immich gesendet"
|
||
}
|
||
|
||
struct PMFilter: Equatable {
|
||
var tag: TagFilter = .all
|
||
var ratingOn = false
|
||
var ratings: Set<Int> = [] // 0…5
|
||
var colorOn = false
|
||
var colors: Set<Int> = [] // 0 = keine Farbklasse, 1…8
|
||
|
||
/// only images with open jersey suggestions
|
||
var suggestionsOnly = false
|
||
/// Matchday filters
|
||
var team: UUID?
|
||
var person: String?
|
||
var withoutPlayer = false
|
||
/// upload status
|
||
var sent: SentFilter = .all
|
||
|
||
var isActive: Bool {
|
||
tag != .all || (ratingOn && !ratings.isEmpty) || (colorOn && !colors.isEmpty) || suggestionsOnly
|
||
|| team != nil || person != nil || withoutPlayer || sent != .all
|
||
}
|
||
|
||
func matches(_ item: PhotoItem) -> Bool {
|
||
switch tag {
|
||
case .all: break
|
||
case .tagged: if !item.tagged { return false }
|
||
case .untagged: if item.tagged { return false }
|
||
}
|
||
if ratingOn && !ratings.isEmpty && !ratings.contains(item.rating) { return false }
|
||
if colorOn && !colors.isEmpty && !colors.contains(item.label?.pmColorClass ?? 0) { return false }
|
||
return true
|
||
}
|
||
}
|
||
|
||
enum SortOrder: String, CaseIterable {
|
||
case captureTime = "Aufnahmezeit"
|
||
case filename = "Dateiname"
|
||
case fileDate = "Dateidatum"
|
||
case colorClass = "Farbklasse"
|
||
case rating = "Bewertung"
|
||
case tagged = "Tag"
|
||
}
|
||
|
||
/// Request to open a separate window (handled in ContentView, which has `openWindow`).
|
||
struct WindowRequest: Equatable {
|
||
let id: String
|
||
let token = UUID()
|
||
}
|
||
|
||
/// One step on the undo stack: the affected photos before and after the change.
|
||
struct UndoEntry {
|
||
enum Kind { case flags, iptc([IPTCField]) }
|
||
let title: String
|
||
let kind: Kind
|
||
let before: [PhotoItem]
|
||
let after: [PhotoItem]
|
||
}
|
||
|
||
/// Upload waiting for the Agentur-Check / double-send decision.
|
||
struct PendingUpload: Identifiable {
|
||
let id = UUID()
|
||
let target: String
|
||
let targetName: String
|
||
var variant: UploadVariant
|
||
let skipAlreadySent: Bool
|
||
var items: [PhotoItem]
|
||
/// item id → issues
|
||
var issues: [String: [PreflightIssue]]
|
||
/// item ids already sent to this target
|
||
var alreadySent: Set<String>
|
||
|
||
func hasError(_ id: String) -> Bool { issues[id]?.contains { $0.severity == .error } ?? false }
|
||
var errorItems: Int { items.filter { hasError($0.id) }.count }
|
||
var warningItems: Int { items.filter { !hasError($0.id) && !(issues[$0.id] ?? []).isEmpty }.count }
|
||
}
|
||
|
||
struct AppAlert: Identifiable {
|
||
let id = UUID()
|
||
let title: String
|
||
let message: String
|
||
}
|
||
|
||
@MainActor
|
||
final class AppState: ObservableObject {
|
||
@Published private(set) var items: [PhotoItem] = []
|
||
@Published var folder: URL?
|
||
@Published var selection: Set<String> = []
|
||
@Published var cursorID: String?
|
||
@Published var filter = PMFilter() { didSet { if filter != oldValue { rebuildVisible() } } }
|
||
@Published var sortOrder: SortOrder = .captureTime { didSet { rebuildVisible() } }
|
||
@Published var reverseSort = false { didSet { rebuildVisible() } }
|
||
/// Open folders as tabs (like PM's contact sheet tabs).
|
||
@Published var tabs: [URL] = []
|
||
@Published var searchText = "" { didSet { rebuildVisible() } }
|
||
@Published private(set) var visible: [PhotoItem] = []
|
||
@Published var previewMode = false
|
||
/// Focus view while going through the photos: no toolbar, tabs, Matchday header or filter bar –
|
||
/// only the photo, the filmstrip below and the panel on the right (F). Remembered.
|
||
@Published var focusMode = UserDefaults.standard.bool(forKey: "focusMode") {
|
||
didSet { UserDefaults.standard.set(focusMode, forKey: "focusMode") }
|
||
}
|
||
/// focus applies to the loupe only – the contact sheet keeps its bars
|
||
var focusActive: Bool { focusMode && previewMode }
|
||
@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 = ""
|
||
@Published var alert: AppAlert?
|
||
@Published var templates: [IPTCTemplate] = [] { didSet { Storage.save(templates, to: Storage.templatesURL) } }
|
||
@Published var settings: AppSettings {
|
||
didSet {
|
||
scheduleSettingsSave()
|
||
if settings.jersey.teams != oldValue.jersey.teams { syncKitsToProfiles() }
|
||
}
|
||
}
|
||
/// Spieltag assistant: teams, competitions, patterns, created matches
|
||
@Published var spieltag: SpieltagLibrary { didSet { scheduleSettingsSave() } }
|
||
private var settingsSaveTask: Task<Void, Never>?
|
||
|
||
/// Text fields are bound directly to the settings – write the files once typing pauses, not per key.
|
||
private func scheduleSettingsSave() {
|
||
settingsSaveTask?.cancel()
|
||
settingsSaveTask = Task { [weak self] in
|
||
try? await Task.sleep(nanoseconds: 600_000_000)
|
||
guard !Task.isCancelled else { return }
|
||
self?.flushSettings()
|
||
}
|
||
}
|
||
|
||
func flushSettings() {
|
||
Storage.save(settings, to: Storage.settingsURL)
|
||
Storage.save(spieltag, to: Storage.spieltagURL)
|
||
}
|
||
@Published var showSpieltag = false
|
||
/// Teams with player codes (PM: list of code replacement files).
|
||
@Published var codeLibrary: CodeLibrary {
|
||
didSet {
|
||
Storage.save(codeLibrary, to: Storage.codeLibraryURL)
|
||
codes = codeLibrary.replacements
|
||
}
|
||
}
|
||
/// Flat lookup of all enabled teams (used for expansion).
|
||
@Published private(set) var codes: CodeReplacements { didSet { rebuildPersonIndex() } }
|
||
/// person name ("Svenja Huth") → code ("w10") – for Matchday cards
|
||
private(set) var personIndex: [String: String] = [:]
|
||
|
||
private func rebuildPersonIndex() {
|
||
var idx: [String: String] = [:]
|
||
// enabled teams first, then the others (the SENT folder holds photos of many games)
|
||
for set in codeLibrary.sets.filter(\.enabled) + codeLibrary.sets.filter({ !$0.enabled }) {
|
||
for e in set.entries {
|
||
guard let rep = e.columns.first else { continue }
|
||
let name = JerseyLogic.personName(replacement: rep, columns: e.columns)
|
||
if idx[name] == nil { idx[name] = e.code.lowercased() }
|
||
}
|
||
}
|
||
personIndex = idx
|
||
}
|
||
@Published var gridColumns = 5
|
||
|
||
// Sheets
|
||
@Published var showTemplatePicker = false
|
||
@Published var showTemplateManager = false
|
||
@Published var showIngest = false
|
||
@Published var showPMImport = false
|
||
@Published var showJerseySetup = false
|
||
|
||
// MARK: Jersey numbers
|
||
/// Suggestions per image id (primary path)
|
||
@Published private(set) var jerseySuggestions: [String: [JerseySuggestion]] = [:]
|
||
/// Dismissed / accepted suggestion ids per image (not shown again)
|
||
@Published private(set) var jerseyDone: [String: Set<String>] = [:]
|
||
private var jerseyTask: Task<Void, Never>?
|
||
var jerseyRunning: Bool { jerseyTask != nil }
|
||
@Published var windowRequest: WindowRequest?
|
||
/// Card(s) that triggered the ingest window.
|
||
@Published var pendingIngestSources: [URL] = []
|
||
/// PM "Copy/Paste" in the IPTC window.
|
||
@Published var iptcClipboard: IPTCValues?
|
||
|
||
let tasks = TaskCenter()
|
||
weak var browserWindow: NSWindow?
|
||
private var visibleIndex: [String: Int] = [:]
|
||
private lazy var folderWatcher = FolderWatcher { [weak self] in self?.refreshFolder() }
|
||
private let cardMonitor = CardMonitor()
|
||
private var ingestTask: Task<Void, Never>?
|
||
|
||
let uploads = UploadQueue()
|
||
private var indexByID: [String: Int] = [:]
|
||
private var exiftoolInstance: ExifTool?
|
||
private var lrPollTimer: Timer?
|
||
private var codeReloadTimer: Timer?
|
||
private var pendingLRJobs: [String: LightroomJob] = [:]
|
||
/// source photos of each job (with their IPTC) – the folder may have changed when the result arrives
|
||
private var pendingLRSources: [String: [PhotoItem]] = [:]
|
||
@Published var lrPendingCount = 0
|
||
|
||
/// Upload history ("Gesendet"-Status)
|
||
@Published private(set) var sentLog = SentLog()
|
||
private var sentLogSaveTask: Task<Void, Never>?
|
||
/// Agentur-Check / double-send question waiting for the user (window "check")
|
||
@Published private var pendingUploads: [PendingUpload] = []
|
||
var pendingUpload: PendingUpload? { pendingUploads.first }
|
||
/// Undo / redo of ratings, labels, tags and IPTC changes
|
||
@Published private(set) var undoStack: [UndoEntry] = []
|
||
@Published private(set) var redoStack: [UndoEntry] = []
|
||
/// metadata writes run one after another (fast key presses, undo right after a change)
|
||
private var writeTail: Task<Void, Never>?
|
||
|
||
init() {
|
||
settings = Storage.load(AppSettings.self, from: Storage.settingsURL) ?? AppSettings()
|
||
spieltag = Storage.load(SpieltagLibrary.self, from: Storage.spieltagURL) ?? SpieltagLibrary()
|
||
templates = Storage.load([IPTCTemplate].self, from: Storage.templatesURL) ?? []
|
||
let library = Storage.load(CodeLibrary.self, from: Storage.codeLibraryURL)
|
||
?? CodeLibrary.migrate(Storage.load(CodeReplacements.self, from: Storage.codesURL) ?? CodeReplacements())
|
||
codeLibrary = library
|
||
codes = library.replacements
|
||
rebuildPersonIndex()
|
||
sentLog = Storage.load(SentLog.self, from: Storage.sentLogURL) ?? SentLog()
|
||
uploads.state = self
|
||
_ = NotificationCenter.default.addObserver(forName: NSApplication.willTerminateNotification, object: nil, queue: .main) { [weak self] _ in
|
||
MainActor.assumeIsolated { self?.flushSentLog(); self?.flushSettings() }
|
||
}
|
||
seedDefaultsIfNeeded()
|
||
startLightroomPolling()
|
||
updateLightroomPluginIfNeeded()
|
||
// PM "Automatically reload code replacement files when they change"
|
||
codeReloadTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
|
||
Task { @MainActor in
|
||
guard let self, self.codeLibrary.autoReload else { return }
|
||
var lib = self.codeLibrary
|
||
let n = lib.reloadAll(onlyChanged: true)
|
||
if n > 0 { self.codeLibrary = lib; self.statusText = "Codes: \(n) neue Einträge nachgeladen" }
|
||
}
|
||
}
|
||
cardMonitor.start { [weak self] dcim in
|
||
guard let self, self.settings.autoIngestOnCardMount, self.ingestTask == nil else { return }
|
||
self.pendingIngestSources = [dcim]
|
||
self.showIngest = true
|
||
NSApp.activate(ignoringOtherApps: true)
|
||
}
|
||
}
|
||
|
||
func openWindow(_ id: String) { windowRequest = WindowRequest(id: id) }
|
||
var showUploads: Bool {
|
||
get { false }
|
||
set { if newValue { openWindow("tasks") } }
|
||
}
|
||
|
||
/// First launch: agency FTP profiles (host/user are placeholders – adjust in Settings → FTP).
|
||
private func seedDefaultsIfNeeded() {
|
||
// Leon's folder layout: ~/Desktop/BILDER/INPUT (ingest) and ~/Desktop/BILDER/SENT (JPEG export)
|
||
if !UserDefaults.standard.bool(forKey: "seededImmichAlbum") {
|
||
UserDefaults.standard.set(true, forKey: "seededImmichAlbum")
|
||
if settings.immich.albumName.isEmpty { settings.immich.albumName = "{event}" }
|
||
}
|
||
if !UserDefaults.standard.bool(forKey: "seededBILDER") {
|
||
UserDefaults.standard.set(true, forKey: "seededBILDER")
|
||
let bilder = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Desktop/BILDER")
|
||
let input = bilder.appendingPathComponent("INPUT").path, sent = bilder.appendingPathComponent("SENT").path
|
||
for p in [input, sent] where !settings.favoriteFolders.contains(p) { settings.favoriteFolders.append(p) }
|
||
if settings.ingest.primaryDestination.isEmpty { settings.ingest.primaryDestination = input }
|
||
settings.lightroom.exportTarget = .fixed
|
||
if settings.lightroom.exportFolder.isEmpty { settings.lightroom.exportFolder = sent }
|
||
}
|
||
guard settings.ftpDestinations.isEmpty, !UserDefaults.standard.bool(forKey: "seededFTP") else { return }
|
||
UserDefaults.standard.set(true, forKey: "seededFTP")
|
||
let host = "beautifulsports.ftp.xxx.com"
|
||
settings.ftpDestinations = [
|
||
FTPDestination(name: "Beautiful Sports – Sport", proto: .ftp, host: host, port: 21,
|
||
remoteDirectory: "/Tonhäuser_Sport", passive: true, variant: .jpeg),
|
||
FTPDestination(name: "Beautiful Sports – Stock", proto: .ftp, host: host, port: 21,
|
||
remoteDirectory: "/Tonhäuser_Stock", passive: true, variant: .jpeg),
|
||
]
|
||
}
|
||
|
||
// MARK: exiftool
|
||
|
||
var exiftool: ExifTool? {
|
||
if let e = exiftoolInstance { return e }
|
||
guard let url = ExifTool.locate(custom: settings.exiftoolPath) else { return nil }
|
||
let e = ExifTool(executable: url)
|
||
exiftoolInstance = e
|
||
return e
|
||
}
|
||
|
||
func requireExifTool() -> ExifTool? {
|
||
if let e = exiftool { return e }
|
||
alert = AppAlert(title: "exiftool fehlt", message: ExifToolError.notInstalled.localizedDescription)
|
||
return nil
|
||
}
|
||
|
||
var writer: MetadataWriter? { requireExifTool().map { MetadataWriter(exiftool: $0) } }
|
||
|
||
func resetExifTool() {
|
||
exiftoolInstance?.shutdown()
|
||
exiftoolInstance = nil
|
||
readPool?.shutdown()
|
||
readPool = nil
|
||
}
|
||
|
||
// MARK: Folder loading
|
||
|
||
func chooseFolder() {
|
||
let panel = NSOpenPanel()
|
||
panel.canChooseDirectories = true
|
||
panel.canChooseFiles = false
|
||
panel.allowsMultipleSelection = false
|
||
panel.prompt = "Öffnen"
|
||
if panel.runModal() == .OK, let url = panel.url { open(folder: url) }
|
||
}
|
||
|
||
/// Photos to select when a folder is opened next (the last ingest into it)
|
||
private var pendingSelection: [URL: Set<String>] = [:]
|
||
|
||
private func selectIngested(_ ids: Set<String>) {
|
||
let present = visible.filter { ids.contains($0.primary.standardizedFileURL.path) }.map(\.id)
|
||
guard !present.isEmpty else { return }
|
||
selection = Set(present)
|
||
cursorID = present.first
|
||
statusText = "\(present.count) neu importierte Bilder ausgewählt"
|
||
}
|
||
|
||
private struct TabSnapshot { var items: [PhotoItem]; var selection: Set<String>; var cursor: String? }
|
||
private var tabSnapshots: [URL: TabSnapshot] = [:]
|
||
|
||
/// Opens a folder in the current tab (or switches to its tab if it is already open).
|
||
func open(folder url: URL, newTab: Bool = false) {
|
||
if let current = folder {
|
||
tabSnapshots[current] = TabSnapshot(items: items, selection: selection, cursor: cursorID)
|
||
}
|
||
if !tabs.contains(url) {
|
||
if newTab || tabs.isEmpty { tabs.append(url) }
|
||
else if let cur = folder, let i = tabs.firstIndex(of: cur) { tabs[i] = url; tabSnapshots[cur] = nil }
|
||
else { tabs.append(url) }
|
||
}
|
||
if let snap = tabSnapshots[url] {
|
||
folder = url
|
||
setItems(snap.items)
|
||
selection = snap.selection
|
||
cursorID = snap.cursor
|
||
folderWatcher.watch(url)
|
||
loadJerseyCache()
|
||
refreshFolder()
|
||
statusText = "\(items.count) Bilder"
|
||
if let ids = pendingSelection.removeValue(forKey: url) { selectIngested(ids) }
|
||
return
|
||
}
|
||
folder = url
|
||
settings.recentFolders.removeAll { $0 == url.path }
|
||
settings.recentFolders.insert(url.path, at: 0)
|
||
settings.recentFolders = Array(settings.recentFolders.prefix(15))
|
||
do {
|
||
let scanned = try FolderScanner.scan(folder: url)
|
||
setItems(scanned)
|
||
selection = []
|
||
cursorID = visible.first?.id
|
||
if let c = cursorID { selection = [c] }
|
||
if let ids = pendingSelection.removeValue(forKey: url) { selectIngested(ids) }
|
||
statusText = "\(scanned.count) Bilder"
|
||
folderWatcher.watch(url)
|
||
loadJerseyCache()
|
||
Task { await loadMetadata(for: scanned) }
|
||
} catch {
|
||
alert = AppAlert(title: "Ordner konnte nicht gelesen werden", message: error.localizedDescription)
|
||
}
|
||
}
|
||
|
||
func reload() {
|
||
guard let f = folder else { return }
|
||
tabSnapshots[f] = nil
|
||
metadataCache = nil
|
||
let keep = (selection, cursorID)
|
||
folder = nil
|
||
open(folder: f)
|
||
selection = keep.0.filter { indexByID[$0] != nil }
|
||
cursorID = keep.1
|
||
}
|
||
|
||
func closeTab(_ url: URL) {
|
||
guard let i = tabs.firstIndex(of: url) else { return }
|
||
tabs.remove(at: i)
|
||
tabSnapshots[url] = nil
|
||
if folder == url {
|
||
folder = nil
|
||
folderWatcher.watch(nil)
|
||
if let next = tabs.isEmpty ? nil : tabs[min(i, tabs.count - 1)] {
|
||
open(folder: next)
|
||
} else {
|
||
setItems([]); selection = []; cursorID = nil
|
||
}
|
||
}
|
||
}
|
||
|
||
func newTab() {
|
||
let panel = NSOpenPanel()
|
||
panel.canChooseDirectories = true
|
||
panel.canChooseFiles = false
|
||
if panel.runModal() == .OK, let url = panel.url { open(folder: url, newTab: true) }
|
||
}
|
||
|
||
/// Selected files total size (status bar).
|
||
var selectedBytes: Int64 { selectedItems.reduce(0) { $0 + $1.fileSize } }
|
||
|
||
/// Re-scans the open folder, keeps loaded metadata/selection and reads only new files.
|
||
func refreshFolder() {
|
||
guard let f = folder, let scanned = try? FolderScanner.scan(folder: f) else { return }
|
||
var existing: [String: PhotoItem] = [:]
|
||
for i in items { existing[i.id] = i }
|
||
var merged: [PhotoItem] = []
|
||
var newOnes: [PhotoItem] = []
|
||
var changed: [PhotoItem] = []
|
||
let now = Date()
|
||
for var item in scanned {
|
||
if let old = existing[item.id] {
|
||
// File changed on disk by someone else (Lightroom still writing the JPEG, our IPTC rewrite after
|
||
// the export, PM …) → read its metadata again; otherwise the first, incomplete read stays forever.
|
||
let fileChanged = old.fileSize != item.fileSize || old.modified != item.modified
|
||
let ours = ownWrites[item.id].map { now.timeIntervalSince($0) < 5 } ?? false
|
||
if fileChanged && !ours { changed.append(item) }
|
||
let companions = item.companions, size = item.fileSize, modified = item.modified
|
||
item = old
|
||
item.companions = companions
|
||
item.fileSize = size
|
||
item.modified = modified
|
||
} else {
|
||
newOnes.append(item)
|
||
}
|
||
merged.append(item)
|
||
}
|
||
let sameIDs = merged.map(\.id) == items.map(\.id)
|
||
if sameIDs && newOnes.isEmpty && changed.isEmpty && merged.map(\.companions) == items.map(\.companions) { return }
|
||
setItems(merged)
|
||
selection = selection.filter { indexByID[$0] != nil }
|
||
if let c = cursorID, indexByID[c] == nil { cursorID = visible.first?.id }
|
||
if !newOnes.isEmpty || !changed.isEmpty { Task { await loadMetadata(for: newOnes + changed) } }
|
||
}
|
||
|
||
/// Files Lichtkasten itself just wrote (stars, IPTC …) – not re-read when the folder watcher fires.
|
||
private var ownWrites: [String: Date] = [:]
|
||
private func noteOwnWrite(_ targets: [PhotoItem]) {
|
||
let now = Date()
|
||
for t in targets { ownWrites[t.id] = now }
|
||
if ownWrites.count > 5000 { ownWrites = ownWrites.filter { now.timeIntervalSince($0.value) < 60 } }
|
||
}
|
||
|
||
// MARK: RAW ⇄ SENT
|
||
|
||
var sentFolderName: String {
|
||
let n = settings.lightroom.sentFolderName.trimmingCharacters(in: .whitespaces)
|
||
return n.isEmpty ? "SENT" : n
|
||
}
|
||
|
||
var isInSentFolder: Bool { folder?.lastPathComponent.caseInsensitiveCompare(sentFolderName) == .orderedSame }
|
||
|
||
/// SENT folder that belongs to `base` (the RAW/shooting folder).
|
||
func sentFolder(for base: URL) -> URL {
|
||
if base.lastPathComponent.caseInsensitiveCompare(sentFolderName) == .orderedSame { return base }
|
||
switch settings.lightroom.exportTarget {
|
||
case .sentInside: return base.appendingPathComponent(sentFolderName, isDirectory: true)
|
||
case .sentSibling: return base.deletingLastPathComponent().appendingPathComponent(sentFolderName, isDirectory: true)
|
||
case .fixed:
|
||
let p = settings.lightroom.exportFolder
|
||
return p.isEmpty ? base.appendingPathComponent(sentFolderName, isDirectory: true) : URL(fileURLWithPath: p)
|
||
}
|
||
}
|
||
|
||
/// The RAW folder a SENT folder belongs to.
|
||
func rawFolder(forSent sent: URL) -> URL {
|
||
let parent = sent.deletingLastPathComponent()
|
||
switch settings.lightroom.exportTarget {
|
||
case .sentInside: return parent
|
||
case .fixed:
|
||
let input = settings.ingest.primaryDestination
|
||
return input.isEmpty ? parent : URL(fileURLWithPath: input)
|
||
case .sentSibling:
|
||
// pick the sibling that contains RAW files (e.g. "RAW"), else the parent
|
||
let siblings = (try? FileManager.default.contentsOfDirectory(at: parent, includingPropertiesForKeys: [.isDirectoryKey])) ?? []
|
||
return siblings.first { $0.lastPathComponent.caseInsensitiveCompare("RAW") == .orderedSame } ?? parent
|
||
}
|
||
}
|
||
|
||
private var lastRawFolder: URL?
|
||
|
||
/// ⌘⌥S – jump between the RAW folder and its SENT folder.
|
||
func toggleRawSent() {
|
||
guard let f = folder else { return }
|
||
if isInSentFolder {
|
||
open(folder: lastRawFolder ?? rawFolder(forSent: f))
|
||
} else {
|
||
lastRawFolder = f
|
||
let sent = sentFolder(for: f)
|
||
try? FileManager.default.createDirectory(at: sent, withIntermediateDirectories: true)
|
||
open(folder: sent)
|
||
}
|
||
}
|
||
|
||
// MARK: Ingest (background)
|
||
|
||
/// Closes everything of ours that could keep the card busy (open tab on the card, folder watcher).
|
||
private func ejectReleaseCardHandles(_ volumes: [URL]) {
|
||
for v in volumes {
|
||
func onVolume(_ u: URL) -> Bool { u.path == v.path || u.path.hasPrefix(v.path + "/") }
|
||
for tab in tabs where onVolume(tab) { closeTab(tab) }
|
||
if let f = folder, onVolume(f) { folderWatcher.watch(nil) }
|
||
}
|
||
}
|
||
|
||
var ingestRunning: Bool { ingestTask != nil }
|
||
|
||
func startIngest(sources: [URL], fromCards: Bool = true) {
|
||
guard let et = requireExifTool(), ingestTask == nil else { return }
|
||
let settings = self.settings.ingest
|
||
let template = settings.applyTemplate ? templates.first { $0.id == settings.templateID } : nil
|
||
// Only real memory cards are ejected – never the system disk or a drive you ingested a folder from.
|
||
// (Some built-in SD readers don't report "ejectable" – any non-system volume under /Volumes counts.)
|
||
let volumes: [URL] = fromCards ? Array(Set(sources.compactMap { src -> URL? in
|
||
let keys: Set<URLResourceKey> = [.volumeURLKey, .volumeIsRootFileSystemKey]
|
||
guard let v = try? src.resourceValues(forKeys: keys), let vol = v.volume,
|
||
v.volumeIsRootFileSystem != true, vol.path.hasPrefix("/Volumes/") else { return nil }
|
||
return vol
|
||
})) : []
|
||
let taskID = tasks.start(.ingest, title: "Ingest von \(sources.map { $0.deletingLastPathComponent().lastPathComponent }.joined(separator: ", "))") { [weak self] in
|
||
self?.ingestTask?.cancel()
|
||
}
|
||
openWindow("tasks")
|
||
ingestTask = Task { [weak self] in
|
||
guard let self else { return }
|
||
defer { self.ingestTask = nil }
|
||
do {
|
||
let result = try await IngestService.run(
|
||
sources: sources, settings: settings, exiftool: et,
|
||
onFolder: { [weak self] url in
|
||
Task { @MainActor [weak self] in
|
||
guard let self else { return }
|
||
self.tasks.update(taskID, 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)
|
||
}
|
||
}
|
||
},
|
||
onSequence: { [weak self] next in
|
||
// runs on success, cancel and error – the numbering never starts over
|
||
Task { @MainActor [weak self] in self?.settings.ingest.startSequence = next }
|
||
},
|
||
progress: { [weak self] p in
|
||
Task { @MainActor [weak self] in
|
||
self?.tasks.update(taskID, done: p.done, total: p.total, detail: p.currentFile)
|
||
}
|
||
})
|
||
// PM: the sequence continues with the next number next time.
|
||
if settings.sequenceEnabled { self.settings.ingest.startSequence = max(self.settings.ingest.startSequence, result.nextSequence) }
|
||
|
||
// Eject right after copying – everything after this works on the copies only.
|
||
var ejectNote = ""
|
||
if settings.unmountAfter && !volumes.isEmpty {
|
||
self.tasks.update(taskID, detail: "Werfe Karte aus …")
|
||
self.ejectReleaseCardHandles(volumes)
|
||
var failed: [String] = []
|
||
for v in volumes {
|
||
if let err = await IngestService.eject(volume: v) { failed.append("\(v.lastPathComponent): \(err)") }
|
||
}
|
||
if failed.isEmpty {
|
||
ejectNote = " · Karte ausgeworfen"
|
||
} else {
|
||
ejectNote = " · Auswerfen fehlgeschlagen"
|
||
self.alert = AppAlert(title: "Karte konnte nicht ausgeworfen werden",
|
||
message: failed.joined(separator: "\n") + "\n\nDie Fotos sind vollständig kopiert. Bitte im Finder auswerfen.")
|
||
}
|
||
}
|
||
|
||
// 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 {
|
||
// only the tag – stars / color class set in the camera stay
|
||
try? await w.writeTag(true, to: PhotoItem(primary: url))
|
||
}
|
||
}
|
||
if let template {
|
||
self.tasks.update(taskID, detail: "Wende Vorlage „\(template.name)“ an …")
|
||
let copied = Set(result.copied.map(\.standardizedFileURL.path))
|
||
for f in result.folders {
|
||
// only the photos of this ingest – older (captioned) photos in the folder stay untouched
|
||
let found = try FolderScanner.scan(folder: f).filter { item in
|
||
([item.primary] + item.companions).contains { copied.contains($0.standardizedFileURL.path) }
|
||
}
|
||
guard !found.isEmpty else { continue }
|
||
let meta = try await et.readMetadata(files: found.map(\.primary))
|
||
let loaded = found.map { item -> PhotoItem in
|
||
var i = item
|
||
i.apply(fileMeta: meta[item.primary.path] ?? [:], sidecarMeta: nil)
|
||
return i
|
||
}
|
||
await self.applyTemplateAndWait(template, to: loaded, recordUndo: false)
|
||
}
|
||
}
|
||
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" : "") }
|
||
self.tasks.finish(taskID, detail: detail + ejectNote)
|
||
// the photos of this ingest are selected (e.g. straight into Lightroom with ⌘E / ⌘⇧L)
|
||
let newIDs = Set(result.copied.map(\.standardizedFileURL.path))
|
||
for f in result.folders where f != self.folder { self.pendingSelection[f] = newIDs }
|
||
if let current = self.folder, result.folders.contains(current) {
|
||
self.metadataCache = nil
|
||
self.refreshFolder()
|
||
self.selectIngested(newIDs)
|
||
await self.loadMetadata(for: self.items)
|
||
// after the refresh, so the new photos are part of it
|
||
if self.settings.jersey.autoAfterIngest, !self.settings.jersey.teams.isEmpty {
|
||
self.recognizeJerseys()
|
||
}
|
||
}
|
||
} catch is CancellationError {
|
||
self.tasks.cancel(taskID)
|
||
} catch {
|
||
self.tasks.finish(taskID, error: error.localizedDescription)
|
||
// e.g. disk full: say it loudly – the card stays in (no eject), what was copied is complete
|
||
self.alert = AppAlert(title: "Ingest abgebrochen", message: error.localizedDescription)
|
||
}
|
||
}
|
||
}
|
||
|
||
private func setItems(_ new: [PhotoItem]) {
|
||
items = new
|
||
indexByID = Dictionary(uniqueKeysWithValues: items.enumerated().map { ($1.id, $0) })
|
||
rebuildVisible()
|
||
}
|
||
|
||
private func rebuildVisible() {
|
||
var list = items.filter { filter.matches($0) }
|
||
if filter.suggestionsOnly { list = list.filter { !(openSuggestions(for: $0.id).isEmpty) } }
|
||
switch filter.sent {
|
||
case .all: break
|
||
case .sent: list = list.filter { sentLog.wasSent($0) }
|
||
case .notSent: list = list.filter { !sentLog.wasSent($0) }
|
||
case .ftp: list = list.filter { sentLog.wasSentByFTP($0) }
|
||
case .notFTP: list = list.filter { !sentLog.wasSentByFTP($0) }
|
||
case .immich: list = list.filter { sentLog.wasSentToImmich($0) }
|
||
case .notImmich: list = list.filter { !sentLog.wasSentToImmich($0) }
|
||
}
|
||
if filter.team != nil || filter.person != nil || filter.withoutPlayer {
|
||
list = list.filter { item in
|
||
let p = playerInfo(for: item)
|
||
if filter.withoutPlayer { return p == nil }
|
||
if let t = filter.team, p?.team?.id != t { return false }
|
||
if let n = filter.person, p?.name != n { return false }
|
||
return true
|
||
}
|
||
}
|
||
let q = searchText.trimmingCharacters(in: .whitespaces).lowercased()
|
||
if !q.isEmpty {
|
||
list = list.filter { item in
|
||
item.filename.lowercased().contains(q)
|
||
|| item.iptc.text.values.contains { $0.lowercased().contains(q) }
|
||
|| item.iptc.lists.values.contains { $0.contains { $0.lowercased().contains(q) } }
|
||
}
|
||
}
|
||
switch sortOrder {
|
||
case .filename:
|
||
list.sort { $0.filename.localizedStandardCompare($1.filename) == .orderedAscending }
|
||
case .captureTime:
|
||
list.sort { ($0.captureDate ?? $0.modified, $0.filename) < ($1.captureDate ?? $1.modified, $1.filename) }
|
||
case .fileDate:
|
||
list.sort { ($0.modified, $0.filename) < ($1.modified, $1.filename) }
|
||
case .colorClass:
|
||
list.sort { ($0.label?.pmColorClass ?? 99, $0.filename) < ($1.label?.pmColorClass ?? 99, $1.filename) }
|
||
case .rating:
|
||
list.sort { (-$0.rating, $0.filename) < (-$1.rating, $1.filename) }
|
||
case .tagged:
|
||
list.sort { ($0.tagged ? 0 : 1, $0.filename) < ($1.tagged ? 0 : 1, $1.filename) }
|
||
}
|
||
if reverseSort { list.reverse() }
|
||
visible = list
|
||
visibleIndex = Dictionary(uniqueKeysWithValues: list.enumerated().map { ($1.id, $0) })
|
||
}
|
||
|
||
private var readPool: ExifToolPool?
|
||
private var metadataCache: MetadataCache?
|
||
private var metadataGeneration = 0
|
||
private var activeMetadataLoads = 0
|
||
|
||
/// Cache first (instant), then the remaining files with several exiftool processes in parallel.
|
||
func loadMetadata(for snapshot: [PhotoItem]) async {
|
||
guard !snapshot.isEmpty, let folder else { return }
|
||
guard let exe = ExifTool.locate(custom: settings.exiftoolPath) else { _ = requireExifTool(); return }
|
||
if readPool == nil { readPool = ExifToolPool(executable: exe) }
|
||
if metadataCache == nil || metadataCacheFolder != folder {
|
||
metadataCache?.save()
|
||
metadataCache = MetadataCache(folder: folder)
|
||
metadataCacheFolder = folder
|
||
// only a new folder (or reload) makes running loads obsolete – new files arriving do not
|
||
metadataGeneration += 1
|
||
}
|
||
guard let pool = readPool, let cache = metadataCache else { return }
|
||
let generation = metadataGeneration
|
||
activeMetadataLoads += 1
|
||
defer { activeMetadataLoads -= 1 }
|
||
loadingMetadata = true
|
||
|
||
// 1. cache hits
|
||
var missing: [PhotoItem] = []
|
||
for item in snapshot {
|
||
if let e = cache.lookup(item), let idx = indexByID[item.id] {
|
||
items[idx].apply(fileMeta: e.file, sidecarMeta: e.sidecar)
|
||
} else {
|
||
missing.append(item)
|
||
}
|
||
}
|
||
rebuildVisible()
|
||
statusText = missing.isEmpty ? "\(items.count) Bilder" : "Metadaten: \(snapshot.count - missing.count)/\(snapshot.count)"
|
||
|
||
// 2. read the rest in parallel
|
||
if !missing.isEmpty {
|
||
var groups: [[URL]] = []
|
||
var byPrimary: [String: PhotoItem] = [:]
|
||
for item in missing {
|
||
var g = [item.primary]
|
||
byPrimary[item.primary.path] = item
|
||
if item.kind.usesSidecar, FileManager.default.fileExists(atPath: item.sidecarURL.path) { g.append(item.sidecarURL) }
|
||
groups.append(g)
|
||
}
|
||
final class Counter: @unchecked Sendable { var n = 0 }
|
||
let done = Counter()
|
||
done.n = snapshot.count - missing.count
|
||
let total = snapshot.count
|
||
await pool.readMetadata(groups: groups) { [weak self] meta in
|
||
await MainActor.run { [weak self] in
|
||
guard let self, self.metadataGeneration == generation else { return }
|
||
for (path, fileMeta) in meta {
|
||
guard let item = byPrimary[path], let idx = self.indexByID[item.id] else { continue }
|
||
let sidecar = item.kind.usesSidecar ? meta[item.sidecarURL.path] : nil
|
||
self.items[idx].apply(fileMeta: fileMeta, sidecarMeta: sidecar)
|
||
cache.store(item, file: fileMeta, sidecar: sidecar)
|
||
done.n += 1
|
||
}
|
||
self.rebuildVisible()
|
||
self.statusText = "Metadaten: \(done.n)/\(total)"
|
||
}
|
||
}
|
||
cache.save()
|
||
}
|
||
if metadataGeneration == generation && activeMetadataLoads == 1 {
|
||
loadingMetadata = false
|
||
statusText = "\(items.count) Bilder"
|
||
}
|
||
}
|
||
|
||
private var metadataCacheFolder: URL?
|
||
|
||
// MARK: Selection
|
||
|
||
func item(_ id: String) -> PhotoItem? { indexByID[id].map { items[$0] } }
|
||
|
||
var selectedItems: [PhotoItem] {
|
||
let ids = selection.isEmpty ? Set([cursorID].compactMap { $0 }) : selection
|
||
return ids.compactMap { visibleIndex[$0] }.sorted().map { visible[$0] }
|
||
}
|
||
|
||
func visiblePosition(_ id: String?) -> Int? { id.flatMap { visibleIndex[$0] } }
|
||
|
||
var cursorItem: PhotoItem? { cursorID.flatMap { item($0) } }
|
||
|
||
func click(_ id: String, modifiers: NSEvent.ModifierFlags) {
|
||
// Leave any text field so number keys rate instead of typing.
|
||
browserWindow?.makeFirstResponder(nil)
|
||
if modifiers.contains(.command) {
|
||
if selection.contains(id) { selection.remove(id) } else { selection.insert(id) }
|
||
cursorID = id
|
||
} else if modifiers.contains(.shift), let anchor = cursorID,
|
||
let a = visibleIndex[anchor], let b = visibleIndex[id] {
|
||
let range = min(a, b)...max(a, b)
|
||
selection.formUnion(visible[range].map(\.id))
|
||
} else {
|
||
selection = [id]
|
||
cursorID = id
|
||
}
|
||
}
|
||
|
||
func moveCursor(by delta: Int, extend: Bool = false) {
|
||
guard !visible.isEmpty else { return }
|
||
let current = visiblePosition(cursorID) ?? -1
|
||
let next = max(0, min(visible.count - 1, current + delta))
|
||
let id = visible[next].id
|
||
cursorID = id
|
||
if extend { selection.insert(id) } else { selection = [id] }
|
||
if previewMode {
|
||
let around = [next + 1, next + 2, next - 1].filter { $0 >= 0 && $0 < visible.count }
|
||
ImageLoader.shared.prefetchPreviews(around.map { previewURL(for: visible[$0]) })
|
||
}
|
||
}
|
||
|
||
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
|
||
guard !targets.isEmpty else { return }
|
||
let alert = NSAlert()
|
||
alert.messageText = targets.count == 1 ? "„\(targets[0].filename)“ in den Papierkorb legen?"
|
||
: "\(targets.count) Bilder in den Papierkorb legen?"
|
||
alert.informativeText = "RAW, JPEG und XMP-Datei werden zusammen verschoben. Im Finder lassen sie sich mit „Zurücklegen“ wiederherstellen."
|
||
alert.addButton(withTitle: "In den Papierkorb")
|
||
alert.addButton(withTitle: "Abbrechen")
|
||
alert.alertStyle = .warning
|
||
guard alert.runModal() == .alertFirstButtonReturn else { return }
|
||
let fm = FileManager.default
|
||
var trashed = Set<String>()
|
||
var failed: [String] = []
|
||
for item in targets {
|
||
var files = [item.primary] + item.companions
|
||
if item.kind.usesSidecar, fm.fileExists(atPath: item.sidecarURL.path) { files.append(item.sidecarURL) }
|
||
do {
|
||
for f in files where fm.fileExists(atPath: f.path) { try fm.trashItem(at: f, resultingItemURL: nil) }
|
||
trashed.insert(item.id)
|
||
} catch { failed.append("\(item.filename): \(error.localizedDescription)") }
|
||
}
|
||
// cursor to the photo after the deleted ones (like PM)
|
||
let after = visible.drop { !trashed.contains($0.id) }.first { !trashed.contains($0.id) }?.id
|
||
?? visible.last { !trashed.contains($0.id) }?.id
|
||
setItems(items.filter { !trashed.contains($0.id) })
|
||
cursorID = after
|
||
selection = after.map { [$0] } ?? []
|
||
statusText = "\(trashed.count) Bild(er) in den Papierkorb gelegt"
|
||
if !failed.isEmpty { self.alert = AppAlert(title: "Nicht alles gelöscht", message: failed.joined(separator: "\n")) }
|
||
}
|
||
func deselectAll() { selection = cursorID.map { [$0] } ?? [] }
|
||
func selectTagged() { selection = Set(visible.filter(\.tagged).map(\.id)) }
|
||
|
||
func previewURL(for item: PhotoItem) -> URL { item.jpegForUpload ?? item.primary }
|
||
|
||
// MARK: Rating / labels / tags
|
||
|
||
private func mutate(_ targets: [PhotoItem], rebuild: Bool = true, _ change: (inout PhotoItem) -> Void) {
|
||
for t in targets { if let i = indexByID[t.id] { change(&items[i]) } }
|
||
if rebuild { rebuildVisible() }
|
||
}
|
||
|
||
private var actionTargets: [PhotoItem] {
|
||
if previewMode, let c = cursorItem { return [c] }
|
||
return selectedItems
|
||
}
|
||
|
||
private func advanceIfSingle(_ count: Int, _ allowed: Bool = true) {
|
||
if allowed && settings.autoAdvance && count == 1 { moveCursor(by: 1) }
|
||
}
|
||
|
||
func setRating(_ n: Int, advance: Bool = true, only: PhotoItem? = nil) {
|
||
let targets = only.map { [$0] } ?? actionTargets
|
||
guard !targets.isEmpty, let w = writer else { return }
|
||
let before = current(targets)
|
||
mutate(targets) { $0.rating = n }
|
||
pushUndo(UndoEntry(title: (n == 0 ? "Sterne entfernt" : "\(n) ★") + countSuffix(targets.count),
|
||
kind: .flags, before: before, after: current(targets)))
|
||
writeState(targets, w)
|
||
advanceIfSingle(targets.count, advance)
|
||
}
|
||
|
||
func setLabel(_ l: ColorLabel?, advance: Bool = true, only: PhotoItem? = nil) {
|
||
let targets = only.map { [$0] } ?? actionTargets
|
||
guard !targets.isEmpty, let w = writer else { return }
|
||
// Same label again toggles it off (LR behaviour).
|
||
let newLabel: ColorLabel? = targets.allSatisfy({ $0.label == l }) ? nil : l
|
||
let before = current(targets)
|
||
mutate(targets) { $0.label = newLabel }
|
||
pushUndo(UndoEntry(title: (newLabel.map { "Farbklasse \($0.germanName)" } ?? "Farbklasse entfernt") + countSuffix(targets.count),
|
||
kind: .flags, before: before, after: current(targets)))
|
||
writeState(targets, w)
|
||
advanceIfSingle(targets.count, advance)
|
||
}
|
||
|
||
func toggleTag() {
|
||
let targets = actionTargets
|
||
guard !targets.isEmpty, let w = writer else { return }
|
||
let newValue = !targets.allSatisfy(\.tagged)
|
||
let before = current(targets)
|
||
mutate(targets) { $0.tagged = newValue }
|
||
pushUndo(UndoEntry(title: (newValue ? "Tag gesetzt" : "Tag entfernt") + countSuffix(targets.count),
|
||
kind: .flags, before: before, after: current(targets)))
|
||
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) }
|
||
serialWrite { [weak self] in
|
||
self?.noteOwnWrite(updated)
|
||
for t in updated { do { try await w.writeState(of: t) } catch { self?.report(error) } }
|
||
self?.noteOwnWrite(updated)
|
||
}
|
||
}
|
||
|
||
/// Runs metadata writes strictly one after another.
|
||
func serialWrite(_ op: @escaping @MainActor () async -> Void) {
|
||
let previous = writeTail
|
||
writeTail = Task { @MainActor in
|
||
await previous?.value
|
||
await op()
|
||
}
|
||
}
|
||
|
||
/// Current in-memory state of these photos (falls back to the passed copy, e.g. other folder).
|
||
private func current(_ targets: [PhotoItem]) -> [PhotoItem] { targets.map { item($0.id) ?? $0 } }
|
||
|
||
private func countSuffix(_ n: Int) -> String { n == 1 ? "" : " (\(n) Bilder)" }
|
||
|
||
func report(_ error: Error) {
|
||
alert = AppAlert(title: "Fehler", message: error.localizedDescription)
|
||
}
|
||
|
||
// MARK: IPTC
|
||
|
||
/// Writes edited fields to all selected images, expanding variables/codes per image.
|
||
func applyIPTC(_ draft: IPTCValues, fields: [IPTCField]) {
|
||
let targets = selectedItems
|
||
Task { await applyIPTCAndWait(draft, fields: fields, to: targets) }
|
||
}
|
||
|
||
/// Remembers used values for the ▾ list of each field (most recent first, like PM's recent values).
|
||
func rememberFieldValues(_ values: IPTCValues, fields: [IPTCField]) {
|
||
for f in fields where f.kind != .list && f.kind != .multiline {
|
||
guard let v = values.text[f.id]?.trimmingCharacters(in: .whitespaces), !v.isEmpty, !v.contains("{") else { continue }
|
||
var list = settings.fieldLists[f.id] ?? []
|
||
list.removeAll { $0 == v }
|
||
list.insert(v, at: 0)
|
||
settings.fieldLists[f.id] = Array(list.prefix(60))
|
||
}
|
||
}
|
||
|
||
@discardableResult
|
||
func applyIPTCAndWait(_ draft: IPTCValues, fields: [IPTCField], to targets: [PhotoItem], recordUndo: Bool = true) async -> Bool {
|
||
guard !targets.isEmpty, !fields.isEmpty, let w = writer else { return false }
|
||
rememberFieldValues(draft, fields: fields)
|
||
statusText = "Schreibe IPTC in \(targets.count) Bild(er) …"
|
||
await writeTail?.value // pending flag writes first
|
||
var count = 0
|
||
var before: [PhotoItem] = []
|
||
var after: [PhotoItem] = []
|
||
defer {
|
||
rebuildVisible() // once for all images instead of once per image
|
||
if recordUndo && !after.isEmpty {
|
||
let title = (fields.count == 1 ? "IPTC: \(fields[0].label)" : "IPTC: \(fields.count) Felder") + countSuffix(after.count)
|
||
pushUndo(UndoEntry(title: title, kind: .iptc(fields), before: before, after: after))
|
||
}
|
||
}
|
||
for t in targets {
|
||
var merged = item(t.id)?.iptc ?? t.iptc
|
||
for f in fields {
|
||
if f.kind == .list { merged.lists[f.id] = draft.lists[f.id] } else { merged.text[f.id] = draft.text[f.id] }
|
||
}
|
||
let ctx = VariableContext.make(fileURL: t.primary, exif: t.exif, iptc: merged, dateFormat: settings.dateFormat)
|
||
let expanded = VariableExpander.expand(merged, context: ctx, codes: codes)
|
||
do {
|
||
let old = item(t.id) ?? t
|
||
noteOwnWrite([t])
|
||
try await w.write(values: expanded, fields: fields, to: t)
|
||
noteOwnWrite([t])
|
||
mutate([t], rebuild: false) { $0.iptc = expanded }
|
||
if count % 50 == 49 { rebuildVisible() } // visible progress on big selections
|
||
before.append(old)
|
||
after.append(item(t.id) ?? { var n = t; n.iptc = expanded; return n }())
|
||
count += 1
|
||
} catch { report(error); return false }
|
||
}
|
||
statusText = "IPTC in \(count) Bild(er) geschrieben"
|
||
return true
|
||
}
|
||
|
||
/// Navigation inside the IPTC window: within the selection if several are selected, else all visible.
|
||
func iptcNavigate(_ delta: Int) {
|
||
let pool = selection.count > 1 ? selectedItems : visible
|
||
guard !pool.isEmpty else { return }
|
||
let cur = pool.firstIndex { $0.id == cursorID } ?? 0
|
||
let next = max(0, min(pool.count - 1, cur + delta))
|
||
cursorID = pool[next].id
|
||
if selection.count <= 1 { selection = [pool[next].id] }
|
||
}
|
||
|
||
/// FTP/Immich upload of one item (IPTC window "Speichern, Hochladen & →").
|
||
func upload(item: PhotoItem, to target: String) {
|
||
requestUpload([self.item(item.id) ?? item], to: target)
|
||
}
|
||
|
||
func applyTemplate(_ template: IPTCTemplate, to targets: [PhotoItem]? = nil) {
|
||
let targets = targets ?? selectedItems
|
||
Task { await applyTemplateAndWait(template, to: targets) }
|
||
}
|
||
|
||
func applyTemplateAndWait(_ template: IPTCTemplate, to targets: [PhotoItem], recordUndo: Bool = true) async {
|
||
guard !targets.isEmpty, let w = writer else { return }
|
||
if templates.contains(where: { $0.id == template.id }) { settings.lastTemplateID = template.id }
|
||
statusText = "Wende Vorlage „\(template.name)“ an …"
|
||
await writeTail?.value
|
||
let before = current(targets)
|
||
do {
|
||
noteOwnWrite(targets)
|
||
let result = try await w.apply(template: template, to: targets, codes: codes, dateFormat: settings.dateFormat)
|
||
noteOwnWrite(targets)
|
||
for t in targets { if let v = result[t.id] { mutate([t], rebuild: false) { $0.iptc = v } } }
|
||
rebuildVisible()
|
||
if recordUndo {
|
||
let after = targets.map { t -> PhotoItem in
|
||
if let cur = item(t.id) { return cur }
|
||
var n = t; n.iptc = result[t.id] ?? t.iptc; return n
|
||
}
|
||
pushUndo(UndoEntry(title: "Vorlage „\(template.name)“" + countSuffix(targets.count),
|
||
kind: .iptc(template.fieldsToWrite), before: before, after: after))
|
||
}
|
||
statusText = "Vorlage auf \(targets.count) Bild(er) angewendet"
|
||
} catch { report(error) }
|
||
}
|
||
|
||
func importPMTemplate() {
|
||
let panel = NSOpenPanel()
|
||
panel.allowedContentTypes = []
|
||
panel.allowsOtherFileTypes = true
|
||
panel.allowsMultipleSelection = true
|
||
panel.message = "Photo-Mechanic-Vorlage(n) (.snap / .xmp) oder Bilder mit IPTC wählen"
|
||
guard panel.runModal() == .OK else { return }
|
||
for url in panel.urls {
|
||
do {
|
||
if ["xmp", "xml", "snap"].contains(url.pathExtension.lowercased()) {
|
||
templates.append(try XMPTemplateIO.importTemplate(from: url))
|
||
} else {
|
||
try templateFromImage(url)
|
||
}
|
||
} catch { report(error) }
|
||
}
|
||
}
|
||
|
||
/// Creates a template from the IPTC of an existing image (e.g. a JPEG captioned in PM).
|
||
func templateFromImage(_ url: URL) throws {
|
||
guard let et = requireExifTool() else { return }
|
||
Task {
|
||
do {
|
||
let meta = try await et.readMetadata(files: [url])
|
||
var item = PhotoItem(primary: url)
|
||
item.apply(fileMeta: meta[url.path] ?? [:], sidecarMeta: nil)
|
||
templates.append(IPTCTemplate(name: url.deletingPathExtension().lastPathComponent, values: item.iptc))
|
||
} catch { report(error) }
|
||
}
|
||
}
|
||
|
||
func exportTemplate(_ t: IPTCTemplate) {
|
||
let panel = NSSavePanel()
|
||
panel.nameFieldStringValue = t.name + ".xmp"
|
||
guard panel.runModal() == .OK, let url = panel.url else { return }
|
||
do { try XMPTemplateIO.export(t).write(to: url, atomically: true, encoding: .utf8) } catch { report(error) }
|
||
}
|
||
|
||
/// PM "Add…": each TXT becomes a team – or, if the team exists already, only new players are added.
|
||
/// Folders can be chosen too: every TXT inside becomes a team, sorted under the league = its folder
|
||
/// ("Codes/1. Bundesliga/…", "Codes/2. Bundesliga/…").
|
||
func importCodeFiles(into setID: UUID? = nil, league: String? = nil) {
|
||
let panel = NSOpenPanel()
|
||
panel.allowsMultipleSelection = setID == nil
|
||
panel.canChooseDirectories = setID == nil
|
||
panel.message = setID == nil ? "TXT-Dateien oder Liga-Ordner wählen – jede TXT wird ein Team, der Ordner ist die Liga"
|
||
: "TXT mit neuen Spielern – vorhandene Codes bleiben unverändert"
|
||
guard panel.runModal() == .OK else { return }
|
||
var lib = codeLibrary
|
||
var results: [(team: String, added: Int, existing: Int)] = []
|
||
for url in panel.urls {
|
||
do {
|
||
if (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true {
|
||
results += try lib.importFolder(url)
|
||
} else {
|
||
results.append(try lib.importFile(url, into: setID, league: league))
|
||
}
|
||
} catch { report(error) }
|
||
}
|
||
codeLibrary = lib // one save / rebuild for the whole import
|
||
let added = results.reduce(0) { $0 + $1.added }
|
||
statusText = results.count > 3
|
||
? "\(results.count) Teams importiert, \(added) neue Codes"
|
||
: results.map { "\($0.team): \($0.added) neu" + ($0.existing > 0 ? ", \($0.existing) schon vorhanden" : "") }
|
||
.joined(separator: " · ")
|
||
}
|
||
|
||
func reloadAllCodes() {
|
||
let n = codeLibrary.reloadAll()
|
||
statusText = n == 0 ? "Codes: keine neuen Einträge" : "Codes: \(n) neue Einträge"
|
||
}
|
||
|
||
func importCodeReplacements() { importCodeFiles() }
|
||
|
||
// MARK: Lightroom
|
||
|
||
var lightroomAppURL: URL? {
|
||
for id in LightroomBridge.lightroomBundleIDs {
|
||
if let u = NSWorkspace.shared.urlForApplication(withBundleIdentifier: id) { return u }
|
||
}
|
||
let guess = URL(fileURLWithPath: "/Applications/Adobe Lightroom Classic/Adobe Lightroom Classic.app")
|
||
return FileManager.default.fileExists(atPath: guess.path) ? guess : nil
|
||
}
|
||
|
||
private func rawOrPrimary(_ items: [PhotoItem]) -> [URL] { items.map { $0.rawFile ?? $0.primary } }
|
||
|
||
private var lrTaskIDs: [String: UUID] = [:]
|
||
|
||
/// ⌘⇧L import · ⌘E import + Develop module · ⌘⌥L import + preset + JPEG export into SENT.
|
||
func sendToLightroom(export: Bool, develop: Bool = false) {
|
||
let targets = selectedItems
|
||
guard !targets.isEmpty else { return }
|
||
let lr = settings.lightroom
|
||
if LightroomBridge.pluginIsAlive {
|
||
let base = folder ?? targets[0].primary.deletingLastPathComponent()
|
||
let exportFolder = sentFolder(for: isInSentFolder ? rawFolder(forSent: base) : base)
|
||
let applyPreset = export || !develop || lr.presetOnEdit
|
||
var job = LightroomJob(files: rawOrPrimary(targets), developPreset: applyPreset ? lr.developPreset : "",
|
||
collection: lr.collection, export: export, exportFolder: export ? exportFolder : nil,
|
||
jpegQuality: lr.jpegQuality, longEdge: lr.longEdge, sharpening: lr.sharpening,
|
||
colorSpace: lr.colorSpace, rewriteIPTCAfterExport: lr.rewriteIPTCAfterExport,
|
||
uploadTargets: export ? lr.autoUploadTargets : [])
|
||
job.openDevelop = develop
|
||
do {
|
||
try LightroomBridge.submit(job)
|
||
pendingLRJobs[job.id] = job
|
||
pendingLRSources[job.id] = targets
|
||
lrPendingCount = pendingLRJobs.count
|
||
let what = export ? "Import + JPEG-Export nach \(exportFolder.lastPathComponent)" : develop ? "Bearbeiten" : "Import"
|
||
lrTaskIDs[job.id] = tasks.start(.lightroom, title: "Lightroom: \(what) (\(targets.count) Bild(er))", total: targets.count)
|
||
statusText = "\(targets.count) Bild(er) an Lightroom übergeben"
|
||
if let app = lightroomAppURL { NSWorkspace.shared.openApplication(at: app, configuration: .init()) }
|
||
} catch { report(error) }
|
||
} else {
|
||
guard let app = lightroomAppURL else {
|
||
alert = AppAlert(title: "Lightroom Classic nicht gefunden", message: "Bitte Lightroom Classic installieren.")
|
||
return
|
||
}
|
||
if export {
|
||
alert = AppAlert(title: "Lichtkasten Bridge läuft nicht",
|
||
message: "Für Import mit Vorgabe und automatischem JPEG-Export muss Lightroom Classic mit dem Plugin laufen. Einstellungen → Lightroom → Plugin installieren, dann Lightroom (neu) starten.")
|
||
return
|
||
}
|
||
NSWorkspace.shared.open(rawOrPrimary(targets), withApplicationAt: app, configuration: NSWorkspace.OpenConfiguration())
|
||
statusText = "Lightroom-Importdialog geöffnet (Bridge-Plugin nicht aktiv)"
|
||
}
|
||
}
|
||
|
||
/// A newer Lichtkasten brings a newer Lightroom plugin (e.g. source paths for the export) – an old one in
|
||
/// Lightroom's Modules folder is replaced automatically, so the export mapping works without manual steps.
|
||
private func updateLightroomPluginIfNeeded() {
|
||
guard LightroomBridge.pluginInstalled,
|
||
let bundled = Bundle.main.url(forResource: "LichtkastenBridge", withExtension: "lrplugin") else { return }
|
||
let installed = LightroomBridge.lightroomModulesFolder.appendingPathComponent("LichtkastenBridge.lrplugin")
|
||
let files = (try? FileManager.default.contentsOfDirectory(atPath: bundled.path)) ?? []
|
||
let differs = files.contains { name in
|
||
(try? Data(contentsOf: bundled.appendingPathComponent(name))) != (try? Data(contentsOf: installed.appendingPathComponent(name)))
|
||
}
|
||
guard differs else { return }
|
||
do {
|
||
try LightroomBridge.installPlugin(from: bundled)
|
||
alert = AppAlert(title: "Lightroom-Plugin aktualisiert",
|
||
message: "Die Lichtkasten Bridge in Lightroom Classic wurde auf die neue Version gebracht. Bitte Lightroom Classic einmal neu starten.")
|
||
} catch { report(error) }
|
||
}
|
||
|
||
private func startLightroomPolling() {
|
||
lrPollTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] _ in
|
||
Task { @MainActor in self?.pollLightroom() }
|
||
}
|
||
}
|
||
|
||
private func pollLightroom() {
|
||
guard !pendingLRJobs.isEmpty else { return }
|
||
// no answer from the plugin for 30 min (LR closed, plugin error) → give up instead of "running" forever
|
||
for (id, job) in pendingLRJobs where Date().timeIntervalSince(job.created) > 30 * 60 {
|
||
pendingLRJobs[id] = nil
|
||
pendingLRSources[id] = nil
|
||
if let tid = lrTaskIDs.removeValue(forKey: id) {
|
||
tasks.finish(tid, error: "Keine Antwort von Lightroom – läuft Lightroom Classic mit dem Lichtkasten-Plugin?")
|
||
}
|
||
}
|
||
lrPendingCount = pendingLRJobs.count
|
||
for result in LightroomBridge.collectResults() {
|
||
let job = pendingLRJobs.removeValue(forKey: result.id)
|
||
let jobSources = pendingLRSources.removeValue(forKey: result.id) ?? []
|
||
lrPendingCount = pendingLRJobs.count
|
||
if let tid = lrTaskIDs.removeValue(forKey: result.id) {
|
||
let detail = "\(result.imported) importiert" + (result.exported.isEmpty ? "" : ", \(result.exported.count) JPEG(s) exportiert")
|
||
tasks.finish(tid, error: result.errors.isEmpty ? nil : result.errors.joined(separator: " · "), detail: detail)
|
||
}
|
||
if !result.errors.isEmpty {
|
||
alert = AppAlert(title: "Lightroom meldet Probleme", message: result.errors.joined(separator: "\n"))
|
||
}
|
||
statusText = "Lightroom: \(result.imported) importiert, \(result.exported.count) JPEG(s) exportiert"
|
||
guard let job, !result.exported.isEmpty else { continue }
|
||
Task { await handleExported(result, job: job, sources: jobSources) }
|
||
}
|
||
}
|
||
|
||
/// Path key for matching LR's source paths: symlinks resolved, Unicode precomposed (LR may report
|
||
/// "Köln" decomposed), case-insensitive like APFS.
|
||
static func exportKey(_ url: URL) -> String {
|
||
url.resolvingSymlinksInPath().standardizedFileURL.path.precomposedStringWithCanonicalMapping.lowercased()
|
||
}
|
||
|
||
/// After LR export: re-apply the original IPTC (PM-identical structure) and upload.
|
||
private func handleExported(_ result: LightroomJobResult, job: LightroomJob, sources jobSources: [PhotoItem]) async {
|
||
let sources = Dictionary(jobSources.map { original in
|
||
return (Self.exportKey(original.rawFile ?? original.primary), item(original.id) ?? original)
|
||
}, uniquingKeysWith: { first, _ in first })
|
||
let writer = job.rewriteIPTCAfterExport ? self.writer : nil
|
||
var exportedItems: [PhotoItem] = []
|
||
var missingSources = 0
|
||
for file in result.exported {
|
||
// plugin ≥ 0.2 reports the source path; older plugins (not reinstalled in LR) only the JPEG →
|
||
// fall back to the file name (LR keeps it, may append "-2")
|
||
let base = file.deletingPathExtension().lastPathComponent
|
||
let byPath = result.exportSources[file].flatMap { sources[Self.exportKey($0)] }
|
||
guard let source = byPath ?? sources.values.first(where: {
|
||
base == $0.baseName || base.hasPrefix($0.baseName + "-")
|
||
}) else {
|
||
missingSources += 1
|
||
continue
|
||
}
|
||
var exported = PhotoItem(primary: file)
|
||
// Never write an empty block over the JPEG: if the source's metadata was not read (yet), the
|
||
// IPTC Lightroom wrote stays – otherwise the photo would lose everything.
|
||
let sourceHasIPTC = source.metadataLoaded && !source.iptc.isCompletelyEmpty
|
||
if job.rewriteIPTCAfterExport && sourceHasIPTC {
|
||
guard let writer else { continue }
|
||
do {
|
||
try await writer.write(values: source.iptc, fields: IPTCField.all, to: exported)
|
||
} catch {
|
||
report(error)
|
||
continue
|
||
}
|
||
}
|
||
if sourceHasIPTC {
|
||
exported.iptc = source.iptc
|
||
exported.exif = source.exif
|
||
exported.captureDate = source.captureDate
|
||
} else if let et = exiftool, let meta = try? await et.readMetadata(files: [file]) {
|
||
exported.apply(fileMeta: meta[file.path] ?? [:], sidecarMeta: nil) // what Lightroom wrote
|
||
}
|
||
exportedItems.append(exported)
|
||
}
|
||
if missingSources > 0 && (job.rewriteIPTCAfterExport || !job.uploadTargets.isEmpty) {
|
||
alert = AppAlert(title: "Lightroom-Export ohne Originalzuordnung",
|
||
message: "Für \(missingSources) JPEG(s) wurden IPTC-Nachbearbeitung und automatischer Versand ausgesetzt. Bitte die Lichtkasten Bridge aktualisieren und Lightroom neu starten.")
|
||
}
|
||
for target in job.uploadTargets {
|
||
requestUpload(exportedItems, to: target, skipAlreadySent: true)
|
||
}
|
||
if !job.uploadTargets.isEmpty && pendingUpload == nil { openWindow("tasks") }
|
||
// SENT workflow: show the exported JPEGs for captioning.
|
||
if settings.lightroom.openSentAfterExport, let dir = job.exportFolder {
|
||
if folder != dir { lastRawFolder = folder; open(folder: dir) } else { refreshFolder() }
|
||
}
|
||
}
|
||
|
||
// MARK: Upload
|
||
|
||
/// Immich album name for an image: the album pattern with variables from its IPTC/EXIF,
|
||
/// e.g. "{event}" → "DFB-Pokal Frauen: VfL Wolfsburg - TSG 1899 Hoffenheim".
|
||
/// Unresolved variables are dropped; if nothing is left the fallback pattern is used.
|
||
func immichAlbum(for item: PhotoItem) -> String {
|
||
func resolve(_ pattern: String) -> String {
|
||
guard !pattern.isEmpty else { return "" }
|
||
var ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, iptc: item.iptc, dateFormat: settings.dateFormat)
|
||
ctx.values.merge(matchVariables(for: item)) { iptc, _ in iptc } // IPTC values win (city, …)
|
||
var s = VariableExpander.expand(pattern, context: ctx, codes: nil)
|
||
// drop variables that had no value, tidy separators
|
||
while let open = s.firstIndex(of: "{"), let close = s[open...].firstIndex(of: "}") { s.removeSubrange(open...close) }
|
||
return s.trimmingCharacters(in: CharacterSet(charactersIn: " -–|·,").union(.whitespaces))
|
||
}
|
||
let main = resolve(settings.immich.albumName)
|
||
return main.isEmpty ? resolve(settings.immich.albumFallback) : main
|
||
}
|
||
|
||
/// {home}/{away} (= {vereina}/{vereinb}) … of a photo: from its Spieltag, else read from the IPTC event.
|
||
func matchVariables(for item: PhotoItem) -> [String: String] {
|
||
SpieltagGenerator.matchVariables(event: (self.item(item.id) ?? item).iptc.text["event"] ?? "", library: spieltag)
|
||
}
|
||
|
||
/// Files to upload for an item, depending on the destination's variant.
|
||
func uploadFiles(for item: PhotoItem, variant: UploadVariant) -> [URL] {
|
||
switch variant {
|
||
case .jpeg: return [item.jpegForUpload].compactMap { $0 }
|
||
case .original: return [item.primary]
|
||
case .both: return Array(Set([item.primary] + [item.jpegForUpload].compactMap { $0 })).sorted { $0.path < $1.path }
|
||
}
|
||
}
|
||
|
||
func upload(to target: String) {
|
||
requestUpload(selectedItems, to: target)
|
||
}
|
||
|
||
func uploadVariant(_ target: String) -> UploadVariant? {
|
||
if target == "immich" { return settings.immich.variant }
|
||
return settings.ftpDestinations.first { $0.id.uuidString == target }?.variant
|
||
}
|
||
|
||
func uploadTargetName(_ target: String) -> String? {
|
||
if target == "immich" { return "Immich" }
|
||
return settings.ftpDestinations.first { $0.id.uuidString == target }?.name
|
||
}
|
||
|
||
/// Every upload goes through here: photos without a suitable file, double sending, Agentur-Check –
|
||
/// only then the queue. Problems open the "Agentur-Check" window.
|
||
/// `skipAlreadySent`: nil = ask if some were sent before, true/false = decided (e.g. ⌘U window).
|
||
func requestUpload(_ targets: [PhotoItem], to target: String, skipAlreadySent: Bool? = nil, force: Bool = false) {
|
||
guard !targets.isEmpty, let variant = uploadVariant(target), let name = uploadTargetName(target) else { return }
|
||
let withFiles = targets.filter { !uploadFiles(for: $0, variant: variant).isEmpty }
|
||
let missing = targets.count - withFiles.count
|
||
if missing > 0 {
|
||
alert = AppAlert(title: "\(missing) Bild(er) ohne JPEG",
|
||
message: "Für reine RAW-Dateien zuerst „Lightroom → JPEG exportieren“ (⌘⌥L) nutzen; mit automatischem Upload in den Lightroom-Einstellungen geht das in einem Schritt.")
|
||
}
|
||
guard !withFiles.isEmpty else { return }
|
||
let sentBefore = Set(withFiles.filter { sentLog.wasSent($0, to: target) }.map(\.id))
|
||
let destination = settings.ftpDestinations.first { $0.id.uuidString == target }
|
||
let runCheck = !force && target != "immich" && (destination?.preflight ?? true)
|
||
var issues: [String: [PreflightIssue]] = [:]
|
||
if runCheck {
|
||
for t in withFiles {
|
||
let i = preflightIssues(for: t, variant: variant)
|
||
if !i.isEmpty { issues[t.id] = i }
|
||
}
|
||
}
|
||
let decided = skipAlreadySent != nil || sentBefore.isEmpty || force
|
||
if issues.isEmpty && decided {
|
||
let send = skipAlreadySent == true ? withFiles.filter { !sentBefore.contains($0.id) } : withFiles
|
||
if send.isEmpty { statusText = "Alle ausgewählten Bilder wurden schon an \(name) gesendet"; return }
|
||
enqueueUpload(send, target: target, variant: variant)
|
||
return
|
||
}
|
||
pendingUploads.append(PendingUpload(target: target, targetName: name, variant: variant, skipAlreadySent: skipAlreadySent ?? true,
|
||
items: withFiles, issues: issues, alreadySent: sentBefore))
|
||
openWindow("check")
|
||
}
|
||
|
||
/// Agentur-Check of one photo (current metadata).
|
||
func preflightIssues(for item: PhotoItem, variant: UploadVariant) -> [PreflightIssue] {
|
||
let cur = self.item(item.id) ?? item
|
||
let open = openSuggestions(for: cur.id).map { s -> String in
|
||
let name = s.replacement.map { JerseyLogic.personName(replacement: $0, columns: []) } ?? ""
|
||
return [s.code ?? "#\(s.number)", name].filter { !$0.isEmpty }.joined(separator: " ")
|
||
}
|
||
return Preflight.check(iptc: cur.iptc, exif: cur.exif, captureDate: cur.captureDate, codes: codes,
|
||
options: settings.preflight, openSuggestions: open,
|
||
uploadFiles: uploadFiles(for: cur, variant: variant))
|
||
}
|
||
|
||
/// Check window: run the check again (after fixing captions in the IPTC window).
|
||
func recheckPendingUpload() {
|
||
guard var p = pendingUpload, let variant = uploadVariant(p.target) else { return }
|
||
p.variant = variant
|
||
p.items = p.items.map { item($0.id) ?? $0 }
|
||
var issues: [String: [PreflightIssue]] = [:]
|
||
let destination = settings.ftpDestinations.first { $0.id.uuidString == p.target }
|
||
if p.target != "immich" && (destination?.preflight ?? true) {
|
||
for t in p.items { let i = preflightIssues(for: t, variant: variant); if !i.isEmpty { issues[t.id] = i } }
|
||
}
|
||
p.issues = issues
|
||
p.alreadySent = Set(p.items.filter { sentLog.wasSent($0, to: p.target) }.map(\.id))
|
||
pendingUploads[0] = p
|
||
}
|
||
|
||
/// Check window: send these photos.
|
||
func confirmPendingUpload(_ send: [PhotoItem]) {
|
||
guard let p = pendingUpload else { return }
|
||
guard let variant = uploadVariant(p.target) else { discardPendingUpload(); return }
|
||
guard p.variant == variant else { recheckPendingUpload(); return }
|
||
discardPendingUpload()
|
||
guard !send.isEmpty else { return }
|
||
// current metadata (captions may have been fixed after the check) for rename patterns / albums
|
||
enqueueUpload(send.map { item($0.id) ?? $0 }, target: p.target, variant: variant)
|
||
}
|
||
|
||
func discardPendingUpload() {
|
||
guard !pendingUploads.isEmpty else { return }
|
||
pendingUploads.removeFirst()
|
||
recheckPendingUpload()
|
||
}
|
||
|
||
private func enqueueUpload(_ items: [PhotoItem], target: String, variant: UploadVariant) {
|
||
let files = items.flatMap { uploadFiles(for: $0, variant: variant) }
|
||
uploads.enqueue(files: files, target: target, sourceItems: items)
|
||
}
|
||
|
||
// MARK: - Gesendet-Status
|
||
|
||
func recordSent(file: URL, destination: String, destinationName: String, remoteName: String, size: Int64) {
|
||
sentLog.record(file, SentRecord(destination: destination, destinationName: destinationName, remoteName: remoteName, size: size))
|
||
scheduleSentLogSave()
|
||
if filter.sent != .all { rebuildVisible() }
|
||
}
|
||
|
||
func sentSummary(for item: PhotoItem) -> SentSummary? { sentLog.summary(for: item) }
|
||
|
||
var sentCountInFolder: Int { items.filter { sentLog.wasSent($0) }.count }
|
||
|
||
/// "Als nicht gesendet markieren"
|
||
func markNotSent(_ targets: [PhotoItem]) {
|
||
sentLog.clear(targets.flatMap { [$0.primary] + $0.companions })
|
||
scheduleSentLogSave()
|
||
rebuildVisible()
|
||
statusText = "\(targets.count) Bild(er) als nicht gesendet markiert"
|
||
}
|
||
|
||
private func scheduleSentLogSave() {
|
||
sentLogSaveTask?.cancel()
|
||
sentLogSaveTask = Task { [weak self] in
|
||
try? await Task.sleep(nanoseconds: 1_000_000_000)
|
||
guard !Task.isCancelled else { return }
|
||
self?.flushSentLog()
|
||
}
|
||
}
|
||
|
||
func flushSentLog() {
|
||
Storage.save(sentLog, to: Storage.sentLogURL)
|
||
}
|
||
|
||
// MARK: - Rückgängig / Wiederholen
|
||
|
||
var undoTitle: String? { undoStack.last?.title }
|
||
var redoTitle: String? { redoStack.last?.title }
|
||
|
||
private func pushUndo(_ e: UndoEntry) {
|
||
undoStack.append(e)
|
||
if undoStack.count > 100 { undoStack.removeFirst(undoStack.count - 100) }
|
||
redoStack.removeAll()
|
||
}
|
||
|
||
/// ⌘Z: while typing in a text field the text is undone, otherwise the last metadata change.
|
||
func performUndo() {
|
||
if NSApp.keyWindow?.firstResponder is NSText {
|
||
_ = NSApp.sendAction(Selector(("undo:")), to: nil, from: nil)
|
||
} else {
|
||
undo()
|
||
}
|
||
}
|
||
|
||
func performRedo() {
|
||
if NSApp.keyWindow?.firstResponder is NSText {
|
||
_ = NSApp.sendAction(Selector(("redo:")), to: nil, from: nil)
|
||
} else {
|
||
redo()
|
||
}
|
||
}
|
||
|
||
func undo() {
|
||
guard let e = undoStack.popLast() else { statusText = "Nichts zum Rückgängigmachen"; return }
|
||
restore(e.before, kind: e.kind)
|
||
redoStack.append(e)
|
||
statusText = "Rückgängig: \(e.title)"
|
||
}
|
||
|
||
func redo() {
|
||
guard let e = redoStack.popLast() else { statusText = "Nichts zum Wiederholen"; return }
|
||
restore(e.after, kind: e.kind)
|
||
undoStack.append(e)
|
||
statusText = "Wiederholt: \(e.title)"
|
||
}
|
||
|
||
/// Puts photos back into a recorded state – in memory and on disk.
|
||
private func restore(_ snapshots: [PhotoItem], kind: UndoEntry.Kind) {
|
||
guard let w = writer else { return }
|
||
switch kind {
|
||
case .flags:
|
||
for s in snapshots {
|
||
if let i = indexByID[s.id] { items[i].rating = s.rating; items[i].label = s.label; items[i].tagged = s.tagged }
|
||
}
|
||
rebuildVisible()
|
||
let toWrite = snapshots.map { s -> PhotoItem in
|
||
guard var cur = item(s.id) else { return s }
|
||
cur.rating = s.rating; cur.label = s.label; cur.tagged = s.tagged
|
||
return cur
|
||
}
|
||
serialWrite { [weak self] in
|
||
self?.noteOwnWrite(toWrite)
|
||
for t in toWrite { do { try await w.writeState(of: t) } catch { self?.report(error) } }
|
||
self?.noteOwnWrite(toWrite)
|
||
}
|
||
case .iptc(let fields):
|
||
for s in snapshots {
|
||
guard let i = indexByID[s.id] else { continue }
|
||
for f in fields {
|
||
if f.kind == .list { items[i].iptc.lists[f.id] = s.iptc.lists[f.id] } else { items[i].iptc.text[f.id] = s.iptc.text[f.id] }
|
||
}
|
||
}
|
||
rebuildVisible()
|
||
serialWrite { [weak self] in
|
||
self?.noteOwnWrite(snapshots)
|
||
for s in snapshots { do { try await w.write(values: s.iptc, fields: fields, to: s) } catch { self?.report(error) } }
|
||
self?.noteOwnWrite(snapshots)
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - Jersey number recognition
|
||
|
||
/// Everything that was read for an image, including numbers without team/code (IPTC window).
|
||
func allOpenSuggestions(for id: String) -> [JerseySuggestion] {
|
||
let done = jerseyDone[id] ?? []
|
||
return (jerseySuggestions[id] ?? []).filter { !done.contains($0.id) }
|
||
}
|
||
|
||
func openSuggestions(for id: String) -> [JerseySuggestion] {
|
||
let done = jerseyDone[id] ?? []
|
||
return (jerseySuggestions[id] ?? []).filter { !done.contains($0.id) && $0.replacement != nil }
|
||
}
|
||
|
||
/// Short label for the thumbnail badge ("#10 #7").
|
||
func suggestionBadge(for id: String) -> String? {
|
||
let s = openSuggestions(for: id)
|
||
guard !s.isEmpty else { return nil }
|
||
return s.prefix(3).map { "#\($0.number)" }.joined(separator: " ")
|
||
}
|
||
|
||
private var jerseyCacheURL: URL? { folder.map(jerseyCacheURL(for:)) }
|
||
|
||
private func jerseyCacheURL(for f: URL) -> URL {
|
||
var h: UInt64 = 0xcbf29ce484222325
|
||
for b in f.standardizedFileURL.path.utf8 { h = (h ^ UInt64(b)) &* 0x100000001b3 }
|
||
// "jersey2": results of the improved recognizer (older caches are ignored → recognized again)
|
||
return MetadataCache.directory.appendingPathComponent("jersey2-" + String(h, radix: 16) + ".json")
|
||
}
|
||
|
||
private struct JerseyCache: Codable { var suggestions: [String: [JerseySuggestion]]; var done: [String: Set<String>] }
|
||
|
||
func loadJerseyCache() {
|
||
guard let u = jerseyCacheURL, let d = try? Data(contentsOf: u),
|
||
let c = try? JSONDecoder().decode(JerseyCache.self, from: d) else { jerseySuggestions = [:]; jerseyDone = [:]; return }
|
||
jerseySuggestions = c.suggestions
|
||
jerseyDone = c.done
|
||
}
|
||
|
||
private func saveJerseyCache() {
|
||
guard let u = jerseyCacheURL else { return }
|
||
if let d = try? JSONEncoder().encode(JerseyCache(suggestions: jerseySuggestions, done: jerseyDone)) { try? d.write(to: u, options: .atomic) }
|
||
}
|
||
|
||
/// Results of a recognition run belong to the folder it was started in – even if another folder is open now.
|
||
private func storeJerseyResults(_ results: [String: [JerseySuggestion]], folder f: URL?) {
|
||
guard let f else { return }
|
||
if folder == f { saveJerseyCache(); return }
|
||
let u = jerseyCacheURL(for: f)
|
||
var c = (try? Data(contentsOf: u)).flatMap { try? JSONDecoder().decode(JerseyCache.self, from: $0) }
|
||
?? JerseyCache(suggestions: [:], done: [:])
|
||
c.suggestions.merge(results) { _, new in new }
|
||
if let d = try? JSONEncoder().encode(c) { try? d.write(to: u, options: .atomic) }
|
||
}
|
||
|
||
/// Runs the recognition in the background (task window shows progress, cancellable).
|
||
func recognizeJerseys(_ targets: [PhotoItem]? = nil, onlyNew: Bool = true) {
|
||
guard jerseyTask == nil else { return }
|
||
guard !settings.jersey.teams.isEmpty else { showJerseySetup = true; return }
|
||
var list = targets ?? visible
|
||
if onlyNew { list = list.filter { jerseySuggestions[$0.id] == nil } }
|
||
guard !list.isEmpty else { statusText = "Trikotnummern: alle Bilder schon erkannt"; return }
|
||
let codes = self.codes
|
||
let recognizer = JerseyRecognizer(teams: settings.jersey.teams, codes: codes, columns: codes.table,
|
||
useShirt: settings.jersey.useShirt, useShorts: settings.jersey.useShorts,
|
||
minConfidence: settings.jersey.minConfidence)
|
||
let jobs = list.map { (id: $0.id, url: previewURL(for: $0)) }
|
||
let taskID = tasks.start(.metadata, title: "Trikotnummern erkennen (\(jobs.count) Bilder)", total: jobs.count) { [weak self] in
|
||
self?.jerseyTask?.cancel()
|
||
}
|
||
let startFolder = folder
|
||
jerseyTask = Task { [weak self] in
|
||
var done = 0
|
||
var found = 0
|
||
var collected: [String: [JerseySuggestion]] = [:]
|
||
await withTaskGroup(of: (String, [JerseySuggestion]).self) { group in
|
||
var next = 0
|
||
let parallel = 4
|
||
func add() {
|
||
guard next < jobs.count else { return }
|
||
let job = jobs[next]; next += 1
|
||
group.addTask { (job.id, Task.isCancelled ? [] : recognizer.recognize(url: job.url)) }
|
||
}
|
||
for _ in 0..<parallel { add() }
|
||
while let (id, result) = await group.next() {
|
||
guard let self else { return }
|
||
if Task.isCancelled { group.cancelAll(); break }
|
||
collected[id] = result
|
||
if self.folder == startFolder { self.jerseySuggestions[id] = result }
|
||
done += 1
|
||
if result.contains(where: { $0.replacement != nil }) { found += 1 }
|
||
self.tasks.update(taskID, done: done, detail: "\(found) Bilder mit Spieler-Vorschlag")
|
||
if done % 20 == 0 { self.storeJerseyResults(collected, folder: startFolder) }
|
||
add()
|
||
}
|
||
}
|
||
guard let self else { return }
|
||
self.storeJerseyResults(collected, folder: startFolder)
|
||
self.jerseyTask = nil
|
||
if Task.isCancelled { self.tasks.cancel(taskID) } else {
|
||
self.tasks.finish(taskID, detail: "\(found) von \(done) Bildern mit Vorschlag")
|
||
}
|
||
self.rebuildVisible()
|
||
}
|
||
}
|
||
|
||
func dismissSuggestion(_ s: JerseySuggestion, for id: String) {
|
||
jerseyDone[id, default: []].insert(s.id)
|
||
saveJerseyCache()
|
||
if filter.suggestionsOnly { rebuildVisible() }
|
||
}
|
||
|
||
/// Caption + Persons shown with the accepted player(s) – used by the IPTC window (fills the form)
|
||
/// and by direct accept (writes immediately).
|
||
func applying(_ suggestions: [JerseySuggestion], to values: IPTCValues) -> IPTCValues {
|
||
var v = values
|
||
let reps = suggestions.compactMap(\.replacement)
|
||
v.text["caption"] = JerseyLogic.insertIntoCaption(v.text["caption"] ?? "", names: reps, separator: settings.jersey.separator)
|
||
// "Persons shown" only if switched on – by default the player goes into the caption only
|
||
guard settings.jersey.writePersonsShown else { return v }
|
||
var persons = v.lists["personInImage"] ?? []
|
||
for s in suggestions {
|
||
guard let rep = s.replacement, let code = s.code else { continue }
|
||
let name = JerseyLogic.personName(replacement: rep, columns: codes.table[code.lowercased()] ?? [])
|
||
if !persons.contains(name) { persons.append(name) }
|
||
}
|
||
v.lists["personInImage"] = persons.isEmpty ? nil : persons
|
||
return v
|
||
}
|
||
|
||
/// Accept directly (contact sheet / context menu): writes caption + persons and marks as done.
|
||
func acceptSuggestions(_ s: [JerseySuggestion], for item: PhotoItem) {
|
||
guard !s.isEmpty else { return }
|
||
let fields = (settings.jersey.writePersonsShown ? ["caption", "personInImage"] : ["caption"]).compactMap { IPTCField.byID[$0] }
|
||
let values = applying(s, to: item.iptc)
|
||
Task {
|
||
if await applyIPTCAndWait(values, fields: fields, to: [item]) {
|
||
for x in s { jerseyDone[item.id, default: []].insert(x.id) }
|
||
saveJerseyCache()
|
||
if filter.suggestionsOnly { rebuildVisible() }
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Forgets the recognition results (and dismissed/accepted marks) – of the given photos or the whole folder.
|
||
/// Useful after the teams changed: old suggestions of another game disappear from the player list.
|
||
/// Players already written into the caption / "Persons shown" stay.
|
||
func resetJerseySuggestions(_ targets: [PhotoItem]? = nil) {
|
||
guard jerseyTask == nil else { statusText = "Erkennung läuft noch – erst abbrechen"; return }
|
||
if let targets {
|
||
for t in targets { jerseySuggestions[t.id] = nil; jerseyDone[t.id] = nil }
|
||
} else {
|
||
jerseySuggestions = [:]; jerseyDone = [:]
|
||
}
|
||
saveJerseyCache()
|
||
if filter.suggestionsOnly || filter.person != nil || filter.team != nil || filter.withoutPlayer { setTeamFilter(nil) }
|
||
rebuildVisible()
|
||
statusText = targets.map { "Vorschläge für \($0.count) Bild(er) zurückgesetzt" } ?? "Alle Trikot-Vorschläge im Ordner zurückgesetzt"
|
||
}
|
||
|
||
func markSuggestionsDone(_ s: [JerseySuggestion], for id: String) {
|
||
for x in s { jerseyDone[id, default: []].insert(x.id) }
|
||
saveJerseyCache()
|
||
}
|
||
|
||
|
||
// MARK: - Matchday
|
||
|
||
struct PlayerInfo: Equatable {
|
||
var name: String
|
||
var number: Int?
|
||
var team: JerseyTeam?
|
||
var confirmed: Bool
|
||
}
|
||
|
||
var matchdayActive: Bool { settings.jersey.matchday && settings.jersey.teams.count >= 2 }
|
||
|
||
func team(forCode code: String, in teams: [JerseyTeam]? = nil) -> JerseyTeam? {
|
||
let c = code.lowercased()
|
||
return (teams ?? settings.jersey.teams).first { t in
|
||
let p = t.prefix.lowercased()
|
||
return !p.isEmpty && c.hasPrefix(p) && c.dropFirst(p.count).allSatisfy(\.isNumber)
|
||
}
|
||
}
|
||
|
||
/// Main player of an image: accepted suggestion / "Persons shown" first, else the top open suggestion.
|
||
func playerInfo(for item: PhotoItem) -> PlayerInfo? {
|
||
let teamsOfPhoto = teams(for: item)
|
||
if let name = item.iptc.lists["personInImage"]?.first {
|
||
let code = personIndex[name]
|
||
let number = code.flatMap { c in Int(c.drop { !$0.isNumber }) }
|
||
return PlayerInfo(name: name, number: number, team: code.flatMap { team(forCode: $0, in: teamsOfPhoto) }, confirmed: true)
|
||
}
|
||
// accepted players now only live in the first caption line → find a known player name there
|
||
let firstLine = (item.iptc.text["caption"] ?? "").components(separatedBy: "\n").first ?? ""
|
||
if !firstLine.trimmingCharacters(in: .whitespaces).isEmpty {
|
||
for t in teamsOfPhoto {
|
||
guard let set = t.codeSetID.flatMap({ id in codeLibrary.sets.first { $0.id == id } }) else { continue }
|
||
for e in set.entries {
|
||
guard let rep = e.columns.first else { continue }
|
||
let name = JerseyLogic.personName(replacement: rep, columns: e.columns)
|
||
if name.count > 3, firstLine.contains(name) {
|
||
let number = Int(e.code.drop { !$0.isNumber })
|
||
return PlayerInfo(name: name, number: number, team: t, confirmed: true)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if let s = openSuggestions(for: item.id).first, let rep = s.replacement {
|
||
let name = JerseyLogic.personName(replacement: rep, columns: codes.table[(s.code ?? "").lowercased()] ?? [])
|
||
let team = (teamsOfPhoto + settings.jersey.teams).first { $0.id == s.teamID }
|
||
return PlayerInfo(name: name, number: s.number, team: team, confirmed: false)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
struct PlayerCount: Identifiable { var id: String { name }; var name: String; var number: Int?; var team: JerseyTeam?; var count: Int }
|
||
|
||
/// Players in this folder with number of images (Matchday rail).
|
||
var playerCounts: [PlayerCount] {
|
||
var map: [String: PlayerCount] = [:]
|
||
for item in items {
|
||
guard let p = playerInfo(for: item) else { continue }
|
||
map[p.name, default: PlayerCount(name: p.name, number: p.number, team: p.team, count: 0)].count += 1
|
||
}
|
||
return map.values.sorted { ($0.count, $1.name) > ($1.count, $0.name) }
|
||
}
|
||
|
||
/// Event and date for the Matchday header: those of the current image (SENT holds several games),
|
||
/// else the most common event in the folder.
|
||
var matchdayEvent: (event: String, date: String) {
|
||
let f = DateFormatter(); f.dateFormat = "dd.MM.yyyy"
|
||
if let c = cursorItem, let e = c.iptc.text["event"], !e.isEmpty {
|
||
return (e, c.captureDate.map { f.string(from: $0) } ?? "")
|
||
}
|
||
var counts: [String: Int] = [:]
|
||
for i in items { if let e = i.iptc.text["event"], !e.isEmpty { counts[e, default: 0] += 1 } }
|
||
let event = counts.max { $0.value < $1.value }?.key ?? (folder?.lastPathComponent ?? "")
|
||
let date = (cursorItem?.captureDate ?? items.compactMap(\.captureDate).min()).map { f.string(from: $0) } ?? ""
|
||
return (event, date)
|
||
}
|
||
|
||
func setTeamFilter(_ id: UUID?) {
|
||
filter.team = id; filter.person = nil; filter.withoutPlayer = false
|
||
}
|
||
|
||
|
||
// MARK: - Spieltag
|
||
|
||
struct SpieltagOptions {
|
||
var setIngest = true
|
||
var setJersey = true
|
||
var onlyTheseCodes = true
|
||
var matchday = true
|
||
var applyToSelection = false
|
||
}
|
||
|
||
/// Jersey recognition teams of a match (kit colors from the team profiles; id = profile id, so
|
||
/// suggestions stay valid when the teams are set up again later).
|
||
func jerseyTeams(for m: MatchPlan) -> [JerseyTeam] {
|
||
var out: [JerseyTeam] = []
|
||
for (pid, home) in [(m.homeID, true), (m.awayID, false)] {
|
||
guard let p = spieltag.team(pid) else { continue }
|
||
let kit = home ? (p.homeKit ?? p.awayKit) : (p.awayKit ?? p.homeKit)
|
||
let fallback = home ? KitColor(r: 0.1, g: 0.45, b: 0.25) : KitColor(r: 0.95, g: 0.95, b: 0.95)
|
||
var t = JerseyTeam(id: p.id, name: p.name, codeSetID: p.codeSetID, prefix: p.codePrefix,
|
||
shirtColor: kit?.shirt ?? fallback, shortsColor: kit?.shorts)
|
||
t.profileID = p.id
|
||
t.isHome = home
|
||
out.append(t)
|
||
}
|
||
return out
|
||
}
|
||
|
||
/// Teams of the match a photo belongs to (IPTC "Event" of a created Spieltag), else the current teams.
|
||
func teams(for item: PhotoItem?) -> [JerseyTeam] {
|
||
if let e = item?.iptc.text["event"], let m = spieltag.match(forEvent: e) {
|
||
let t = jerseyTeams(for: m)
|
||
if t.count == 2 { return t }
|
||
}
|
||
return settings.jersey.teams
|
||
}
|
||
|
||
/// Kit colors picked in the jersey setup are remembered in the team profile (home or away kit).
|
||
private func syncKitsToProfiles() {
|
||
var lib = spieltag
|
||
var changed = false
|
||
for t in settings.jersey.teams {
|
||
guard let pid = t.profileID, let i = lib.teams.firstIndex(where: { $0.id == pid }) else { continue }
|
||
let kit = Kit(shirt: t.shirtColor, shorts: t.shortsColor)
|
||
if t.isHome == false {
|
||
if lib.teams[i].awayKit != kit { lib.teams[i].awayKit = kit; changed = true }
|
||
} else if lib.teams[i].homeKit != kit {
|
||
lib.teams[i].homeKit = kit; changed = true
|
||
}
|
||
}
|
||
if changed { spieltag = lib }
|
||
}
|
||
|
||
/// Creates (or updates) the match: IPTC template from the base template + patterns, ingest folder name,
|
||
/// jersey teams, active code teams.
|
||
@discardableResult
|
||
func createSpieltag(_ plan: MatchPlan, options: SpieltagOptions) -> IPTCTemplate? {
|
||
guard let home = spieltag.team(plan.homeID), let away = spieltag.team(plan.awayID) else { return nil }
|
||
let comp = spieltag.competition(plan.competitionID)
|
||
let base = templates.first { $0.id == plan.baseTemplateID }
|
||
var m = plan
|
||
// same match again (same teams, same day) → update it instead of adding a second template
|
||
if let old = spieltag.matches.first(where: { $0.homeID == m.homeID && $0.awayID == m.awayID
|
||
&& Calendar.current.isDate($0.date, inSameDayAs: m.date) }) {
|
||
m.id = old.id
|
||
m.templateID = old.templateID
|
||
m.created = old.created
|
||
}
|
||
let ctx = SpieltagGenerator.context(match: m, home: home, away: away, competition: comp, patterns: spieltag.patterns)
|
||
let template = SpieltagGenerator.makeTemplate(match: m, home: home, away: away, competition: comp,
|
||
patterns: spieltag.patterns, base: base)
|
||
m.templateID = template.id
|
||
m.event = template.values.text["event"] ?? ""
|
||
m.folderName = SpieltagGenerator.folderName(patterns: spieltag.patterns, ctx: ctx)
|
||
|
||
if let i = templates.firstIndex(where: { $0.id == template.id }) { templates[i] = template } else { templates.append(template) }
|
||
settings.lastTemplateID = template.id
|
||
|
||
var lib = spieltag
|
||
if let i = lib.matches.firstIndex(where: { $0.id == m.id }) { lib.matches[i] = m } else { lib.matches.append(m) }
|
||
lib.lastBaseTemplateID = plan.baseTemplateID
|
||
lib.lastCompetitionID = plan.competitionID
|
||
spieltag = lib
|
||
|
||
if options.setIngest {
|
||
settings.ingest.folderPattern = m.folderName
|
||
settings.ingest.templateID = template.id
|
||
settings.ingest.applyTemplate = true
|
||
}
|
||
if options.setJersey {
|
||
settings.jersey.teams = jerseyTeams(for: m)
|
||
if options.matchday { settings.jersey.matchday = true }
|
||
}
|
||
if options.onlyTheseCodes {
|
||
let ids = Set([home.codeSetID, away.codeSetID].compactMap { $0 })
|
||
if !ids.isEmpty {
|
||
var cl = codeLibrary
|
||
for i in cl.sets.indices { cl.sets[i].enabled = ids.contains(cl.sets[i].id) }
|
||
codeLibrary = cl
|
||
}
|
||
}
|
||
if options.applyToSelection, !selectedItems.isEmpty { applyTemplate(template, to: selectedItems) }
|
||
statusText = "Spieltag angelegt: \(home.name) – \(away.name) · Vorlage „\(template.name)“"
|
||
return template
|
||
}
|
||
|
||
}
|