Files
lichtkasten/Sources/Lichtkasten/Views/IPTCInfoWindow.swift
T

223 lines
9.3 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 = ""
private var item: PhotoItem? { state.cursorItem }
var body: some View {
HSplitView {
VStack(spacing: 0) {
ScrollView {
PMMetadataForm(texts: $texts, columns: 1, dirty: dirty, codes: state.codes,
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")
.onAppear { load(force: true) }
.onChange(of: state.cursorID) { _, _ in 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: Right side (preview + PM buttons)
private var sidePanel: some View {
VStack(spacing: 12) {
ZStack {
Color.black
if let image { Image(nsImage: image).resizable().scaledToFit() } 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)
}
Grid(horizontalSpacing: 8, verticalSpacing: 8) {
GridRow {
Button("Speichern & ←") { saveAndMove(-1) }
.keyboardShortcut(.leftArrow, modifiers: [.command, .option])
Button("Speichern & →") { saveAndMove(1) }
.keyboardShortcut(.rightArrow, modifiers: [.command, .option])
}
GridRow {
Button("←") { move(-1) }
Button("→") { move(1) }
}
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 {
guard let 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
}
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)
}
}
}