Files
lichtkasten/Sources/Lichtkasten/Views/IPTCInfoWindow.swift
T
Lichtkasten DevandClaude Opus 5.5 bfaea219c6 Trikot-Vorschlag nur in die Beschreibung; LR-Plugin automatisch aktualisieren
- Annehmen trägt den Spieler nur in die erste Zeile der Beschreibung ein, nicht mehr in
  „Persons shown“ (zuschaltbar in der Trikot-Erkennung)
- Matchday-Spielerliste erkennt angenommene Spieler:innen auch aus der ersten Beschreibungszeile
- veraltetes Lichtkasten-Bridge-Plugin in Lightroom wird beim Start ersetzt (Hinweis: LR neu starten) –
  ohne die neue Version fehlte die Zuordnung der Exporte, IPTC wurde nicht zurückgeschrieben und die
  Leerzeilen (Platzhalter für die Personen) oben in der Beschreibung fehlten

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
2026-11-06 23:57:31 +00:00

358 lines
16 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SwiftUI
import LichtkastenCore
/// PM "Metadata (IPTC) Info" as a separate window: edit one image, step through the selection.
struct IPTCInfoWindow: View {
@EnvironmentObject var state: AppState
@Environment(\.dismissWindow) private var dismissWindow
@State private var texts: FieldTexts = [:]
@State private var dirty: Set<String> = []
@State private var loadedID: String?
@State private var image: NSImage?
@State private var saving = false
@AppStorage("iptcWindowUploadTarget") private var uploadTarget = ""
@State private var window: NSWindow?
@State private var arrowMonitor: Any?
private var item: PhotoItem? { state.cursorItem }
var body: some View {
HSplitView {
VStack(spacing: 0) {
suggestionBar
ScrollView {
PMMetadataForm(texts: $texts, columns: 1, dirty: dirty, codes: state.codes, fieldLists: state.settings.fieldLists,
onEdit: { dirty.insert($0) }, extraAfterContent: AnyView(labelSection))
.padding(14)
}
Divider()
HStack {
Menu("Vorlage anwenden") {
ForEach(state.templates) { t in Button(t.name) { applyTemplateToForm(t) } }
if state.templates.isEmpty { Text("Noch keine Vorlagen") }
}
.fixedSize()
Button("Leeren") {
for f in IPTCField.all where !(texts[f.id] ?? "").isEmpty { texts[f.id] = ""; dirty.insert(f.id) }
}
Spacer()
if !dirty.isEmpty { Text("\(dirty.count) geändert").font(.caption).foregroundStyle(.secondary) }
}
.padding(10)
}
.frame(minWidth: 560, idealWidth: 640)
sidePanel.frame(minWidth: 380, idealWidth: 520)
}
.navigationTitle(item.map { "IPTC-Info – \($0.filename)" } ?? "IPTC-Info")
.background(WindowAccessor { window = $0 })
.onAppear {
load(force: true)
installArrowKeys()
}
.onDisappear {
if let m = arrowMonitor { NSEvent.removeMonitor(m); arrowMonitor = nil }
}
.onChange(of: state.cursorID) { _, _ in
// cursor moved from outside (click in the contact sheet …) while edits are open → keep them:
// they are saved to the image they were typed for instead of being thrown away
if !dirty.isEmpty, let id = loadedID, id != state.cursorID, let previous = state.item(id) {
let fields = IPTCField.all.filter { dirty.contains($0.id) }
let values = IPTCValues(texts: texts)
Task {
if await state.applyIPTCAndWait(values, fields: fields, to: [previous]) {
state.statusText = "Änderungen an \(previous.filename) gespeichert"
}
}
}
load(force: true)
}
.onReceive(state.$items) { _ in if dirty.isEmpty { DispatchQueue.main.async { load(force: false) } } }
.task(id: item.map { state.previewURL(for: $0) }) { await loadImage() }
}
/// PM "Image Preferences": color class label + stars of the current image.
private var labelSection: some View {
VStack(alignment: .leading, spacing: 6) {
PMSectionHeader(title: "Image Preferences")
HStack {
Text("Label:").frame(width: 150, alignment: .leading)
Picker("", selection: Binding(
get: { item?.label?.pmColorClass ?? 0 },
set: { n in if let item { state.setLabel(n == 0 ? nil : ColorLabel(pmColorClass: n), advance: false, only: item) } })) {
Text("Keine").tag(0)
ForEach(ColorLabel.allCases, id: \.self) { l in
Text("\(l.pmColorClass) – \(l.germanName) (\(l.pmName))").tag(l.pmColorClass)
}
}
.labelsHidden()
}
HStack {
Text("Rating:").frame(width: 150, alignment: .leading)
Picker("", selection: Binding(get: { item?.rating ?? 0 }, set: { n in if let item { state.setRating(n, advance: false, only: item) } })) {
ForEach(0...5, id: \.self) { n in Text(n == 0 ? "Keine" : String(repeating: "★", count: n)).tag(n) }
}
.labelsHidden()
.pickerStyle(.segmented)
}
}
}
// MARK: Jersey suggestions
private var openSuggestions: [JerseySuggestion] { item.map { state.allOpenSuggestions(for: $0.id) } ?? [] }
private var acceptable: [JerseySuggestion] { openSuggestions.filter { $0.replacement != nil } }
@ViewBuilder
private var suggestionBar: some View {
let open = openSuggestions
if !open.isEmpty, let item {
VStack(alignment: .leading, spacing: 6) {
HStack {
Image(systemName: "person.text.rectangle").foregroundStyle(LK.amber)
Text("Erkannt:").bold()
Spacer()
if acceptable.count > 1 {
Button("Alle annehmen") { accept(acceptable) }
}
Button("Neu erkennen") { state.recognizeJerseys([item], onlyNew: false) }
.controlSize(.small)
}
ForEach(Array(open.enumerated()), id: \.element.id) { idx, s in
HStack(spacing: 8) {
if let c = s.measuredColor {
RoundedRectangle(cornerRadius: 3)
.fill(Color(red: c.r, green: c.g, blue: c.b))
.frame(width: 14, height: 14)
.overlay(RoundedRectangle(cornerRadius: 3).stroke(Color.secondary))
.help("Gemessene Trikotfarbe um die Nummer – passt sie nicht zum Team, Farbe in „Trikot-Erkennung einrichten“ anpassen")
}
Text(s.code ?? "#\(s.number)").font(.system(.body, design: .monospaced)).bold()
Text(s.replacement ?? "Nummer erkannt – kein Team/Code gefunden").lineLimit(1)
.foregroundStyle(s.replacement == nil ? .secondary : .primary)
Text(s.regions.map(\.rawValue).joined(separator: "+") + " · \(Int(s.confidence * 100)) %"
+ (s.teamCertain == false ? " · Team unsicher" : ""))
.font(.caption).foregroundStyle(.secondary)
Spacer()
if s.replacement == nil {
EmptyView()
} else if s.id == acceptable.first?.id {
Button("Annehmen (⌘J)") { accept([s]) }
.keyboardShortcut("j", modifiers: .command)
.buttonStyle(.borderedProminent)
} else {
Button("Annehmen") { accept([s]) }
}
Button { state.dismissSuggestion(s, for: item.id) } label: { Image(systemName: "xmark") }
.help("Falsch – verwerfen")
}
.padding(.vertical, 2)
}
}
.padding(10)
.background(LK.amber.opacity(0.10))
Divider()
}
}
/// Fills the first caption line (and "Persons shown" if switched on) in the form – saved with ⌘B / OK as usual.
private func accept(_ s: [JerseySuggestion]) {
guard let item else { return }
let updated = state.applying(s, to: IPTCValues(texts: texts))
let newTexts = updated.texts()
for id in ["caption", "personInImage"] where (texts[id] ?? "") != (newTexts[id] ?? "") {
texts[id] = newTexts[id] ?? ""
dirty.insert(id)
}
state.markSuggestionsDone(s, for: item.id)
}
/// Boxes around the recognized numbers on the preview.
private func numberBoxes(in size: CGSize) -> some View {
ZStack(alignment: .topLeading) {
ForEach(openSuggestions) { s in
if s.box.count == 4 {
let r = CGRect(x: s.box[0] * size.width, y: s.box[1] * size.height,
width: max(14, s.box[2] * size.width), height: max(14, s.box[3] * size.height))
Rectangle().stroke(Color.yellow, lineWidth: 2)
.frame(width: r.width, height: r.height)
.overlay(alignment: .topLeading) {
Text(s.code ?? "#\(s.number)").font(.caption2.bold()).foregroundStyle(.black)
.padding(.horizontal, 3).background(Color.yellow).offset(y: -14)
}
.offset(x: r.minX, y: r.minY)
}
}
}
.frame(width: size.width, height: size.height, alignment: .topLeading)
.allowsHitTesting(false)
}
// MARK: Right side (preview + PM buttons)
private var sidePanel: some View {
VStack(spacing: 12) {
ZStack {
Color.black
if let image {
Image(nsImage: image).resizable().scaledToFit()
.overlay { GeometryReader { geo in numberBoxes(in: geo.size) } }
} else { ProgressView() }
}
.frame(minHeight: 280)
if let item {
HStack(spacing: 10) {
Image(systemName: item.tagged ? "checkmark.square.fill" : "square")
Text(item.filename).bold().lineLimit(1)
HStack(spacing: 1) {
ForEach(1...5, id: \.self) { n in Image(systemName: n <= item.rating ? "star.fill" : "star") }
}.foregroundStyle(.yellow)
if let l = item.label { Circle().fill(l.color).frame(width: 10, height: 10) }
Spacer()
Text(positionText).foregroundStyle(.secondary).font(.caption)
}
.font(.callout)
SentStatusLine(summary: state.sentSummary(for: item))
}
Grid(horizontalSpacing: 8, verticalSpacing: 8) {
GridRow {
Button("Speichern & ← (⌘N)") { saveAndMove(-1) }
.keyboardShortcut("n", modifiers: .command)
Button("Speichern & → (⌘B)") { saveAndMove(1) }
.keyboardShortcut("b", modifiers: .command)
}
GridRow {
Button("←") { move(-1) }.help("Ohne Speichern zurück (Pfeil links)")
Button("→") { move(1) }.help("Ohne Speichern weiter (Pfeil rechts)")
}
GridRow {
Button("Speichern, Hochladen & →") { saveUploadAndMove() }
.disabled(uploadTarget.isEmpty)
.gridCellColumns(2)
}
GridRow {
Picker("Ziel", selection: $uploadTarget) {
Text("– Upload-Ziel –").tag("")
ForEach(state.settings.ftpDestinations) { d in Text("FTP: \(d.name)").tag(d.id.uuidString) }
if state.settings.immich.enabled { Text("Immich").tag("immich") }
}
.labelsHidden()
.gridCellColumns(2)
}
GridRow {
Button("Kopieren") { state.iptcClipboard = IPTCValues(texts: texts) }
Button("Einfügen") { paste() }.disabled(state.iptcClipboard == nil)
}
}
.controlSize(.large)
.disabled(item == nil || saving)
Spacer()
HStack {
if saving { ProgressView().controlSize(.small) }
Spacer()
Button("Abbrechen") { dirty = []; dismissWindow(id: "iptc") }
.keyboardShortcut(.cancelAction)
Button("OK") { Task { if await save() { dismissWindow(id: "iptc") } } }
.keyboardShortcut(.return, modifiers: .command)
.buttonStyle(.borderedProminent)
}
}
.padding(14)
}
private var positionText: String {
let pool = state.selection.count > 1 ? state.selectedItems : state.visible
guard let i = pool.firstIndex(where: { $0.id == state.cursorID }) else { return "" }
return "\(i + 1) von \(pool.count)" + (state.selection.count > 1 ? " (Auswahl)" : "")
}
// MARK: Actions
private func load(force: Bool) {
guard let item else { texts = [:]; dirty = []; loadedID = nil; return }
if !force && loadedID == item.id && !dirty.isEmpty { return }
texts = item.iptc.texts()
dirty = []
loadedID = item.id
}
private func loadImage() async {
guard let item else { image = nil; return }
let url = state.previewURL(for: item)
image = ImageLoader.shared.cachedPreview(url) ?? ImageLoader.shared.cachedThumbnail(url)
if let big = await ImageLoader.shared.preview(for: url, maxPixel: 2000), state.cursorID == item.id { image = big }
}
@discardableResult
private func save() async -> Bool {
// the image the form was loaded for (not whatever the cursor points at right now)
guard let item = loadedID.flatMap({ state.item($0) }) ?? item, !dirty.isEmpty else { return true }
saving = true
defer { saving = false }
let fields = IPTCField.all.filter { dirty.contains($0.id) }
let ok = await state.applyIPTCAndWait(IPTCValues(texts: texts), fields: fields, to: [item])
if ok { dirty = [] }
return ok
}
/// ←/→ = previous/next image WITHOUT saving (when no text field is being edited);
/// ⌃←/⌃→ work even while typing.
private func installArrowKeys() {
guard arrowMonitor == nil else { return }
arrowMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
guard let w = window, event.window === w, w.attachedSheet == nil else { return event }
let mods = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
guard event.keyCode == 123 || event.keyCode == 124 else { return event }
let typing = w.firstResponder is NSText
let ctrlOnly = mods == [.control] || mods == [.control, .function] || mods == [.function, .control]
let plain = mods.subtracting([.function, .numericPad]).isEmpty
guard ctrlOnly || (plain && !typing) else { return event }
move(event.keyCode == 123 ? -1 : 1)
return nil
}
}
private func move(_ delta: Int) {
dirty = []
state.iptcNavigate(delta)
}
private func saveAndMove(_ delta: Int) {
Task { if await save() { state.iptcNavigate(delta) } }
}
private func saveUploadAndMove() {
Task {
guard await save(), let id = loadedID, let fresh = state.item(id) else { return }
state.upload(item: fresh, to: uploadTarget)
state.iptcNavigate(1)
}
}
private func paste() {
guard let clip = state.iptcClipboard else { return }
let t = clip.texts()
for f in IPTCField.all where (texts[f.id] ?? "") != (t[f.id] ?? "") {
texts[f.id] = t[f.id] ?? ""
dirty.insert(f.id)
}
}
/// Fills the form from a template (PM: "Apply Metadata Template" in the info window) – saved with OK/Speichern.
private func applyTemplateToForm(_ t: IPTCTemplate) {
let current = IPTCValues(texts: texts)
var merged = t.apply(to: current)
if t.dateFromCapture, t.fieldsToWrite.contains(where: { $0.id == "dateCreated" }), let item {
merged.text["dateCreated"] = MetadataWriter.captureDateValue(exif: item.exif) ?? merged.text["dateCreated"]
}
let newTexts = merged.texts()
for f in IPTCField.all where (texts[f.id] ?? "") != (newTexts[f.id] ?? "") {
texts[f.id] = newTexts[f.id] ?? ""
dirty.insert(f.id)
}
}
}