Files
lichtkasten/Sources/LichtkastenCore/Metadata/Variables.swift
T

253 lines
12 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 Foundation
/// Per-image values used for `{variable}` expansion (PM compatible names where possible).
public struct VariableContext: Sendable {
public var values: [String: String]
public init(values: [String: String] = [:]) { self.values = values }
/// Builds the context from file info + EXIF as read by exiftool.
public static func make(fileURL: URL, exif: [String: String], sequence: Int? = nil,
iptc: IPTCValues = IPTCValues(), dateFormat: String = "dd.MM.yyyy") -> VariableContext {
var v: [String: String] = [:]
v["filename"] = fileURL.lastPathComponent
v["filenamebase"] = fileURL.deletingPathExtension().lastPathComponent
v["fileext"] = fileURL.pathExtension
v["folder"] = fileURL.deletingLastPathComponent().lastPathComponent
v["make"] = exif["Make"]
v["model"] = exif["Model"]
v["lens"] = exif["LensModel"] ?? exif["Lens"] ?? exif["LensID"]
v["serial"] = exif["SerialNumber"]
v["serialnum"] = exif["SerialNumber"]
v["iso"] = exif["ISO"]
v["aperture"] = exif["FNumber"].map { "f/\($0)" }
v["shutter"] = exif["ExposureTime"]
v["focallength"] = exif["FocalLength"]
v["artist"] = exif["Artist"]
// Date field popup (PM "Capture Time" / "Today")
v["capturetime"] = MetadataWriter.captureDateValue(exif: exif)
let today = DateFormatter()
today.locale = Locale(identifier: "en_US_POSIX")
today.dateFormat = "yyyy-MM-dd"
v["today"] = today.string(from: Date())
if let seq = sequence {
v["seqn"] = String(seq)
v["seqn3"] = String(format: "%03d", seq)
v["seqn4"] = String(format: "%04d", seq)
}
if let raw = exif["DateTimeOriginal"] ?? exif["CreateDate"], let date = ExifDate.parse(raw) {
let cal = Calendar(identifier: .gregorian)
let c = cal.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let df = DateFormatter()
df.locale = Locale(identifier: "de_DE")
df.dateFormat = dateFormat
v["date"] = df.string(from: date)
df.dateFormat = "HH:mm:ss"
v["time"] = df.string(from: date)
df.dateFormat = "MMMM"
v["monthname"] = df.string(from: date)
df.dateFormat = "EEEE"
v["weekday"] = df.string(from: date)
v["isodate"] = String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)
v["year4"] = String(format: "%04d", c.year ?? 0)
v["year2"] = String(format: "%02d", (c.year ?? 0) % 100)
v["month0"] = String(format: "%02d", c.month ?? 0)
v["month"] = String(c.month ?? 0)
v["day0"] = String(format: "%02d", c.day ?? 0)
v["day"] = String(c.day ?? 0)
v["hour"] = String(format: "%02d", c.hour ?? 0)
v["minute"] = String(format: "%02d", c.minute ?? 0)
v["second"] = String(format: "%02d", c.second ?? 0)
}
// IPTC fields can be referenced too, e.g. "{city}" inside the caption.
for field in IPTCField.all {
let value = iptc[field]
if !value.isEmpty { v[field.id.lowercased()] = value }
}
return VariableContext(values: v.compactMapValues { $0 })
}
}
public enum ExifDate {
/// Parses exiftool dates like "2026:11:03 14:22:01" (optionally with sub-seconds / timezone).
public static func parse(_ s: String) -> Date? {
let core = String(s.prefix(19))
let f = DateFormatter()
f.locale = Locale(identifier: "en_US_POSIX")
f.timeZone = TimeZone.current
f.dateFormat = "yyyy:MM:dd HH:mm:ss"
if let d = f.date(from: core) { return d }
f.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return f.date(from: core)
}
}
/// PM-style code replacement: `\bvb\` → "Borussia Dortmund", `\bvb#2\` → second column.
/// Codes file format (as exported from PM): tab separated, first column = code.
public struct CodeReplacements: Codable, Sendable {
public var delimiter: Character = "\\"
public var table: [String: [String]] = [:]
public var caseSensitive = false
/// PM "Default replacement": used when a \code\ is not found (empty = leave the code as typed).
public var defaultReplacement = ""
/// Codes without delimiter: "w10" + space/comma/… expands (only while typing).
public var bareCodes = true
enum CodingKeys: String, CodingKey { case delimiter, table, caseSensitive, defaultReplacement, bareCodes }
public init(table: [String: [String]] = [:]) { self.table = table }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = try c.decodeIfPresent(String.self, forKey: .delimiter) ?? "\\"
delimiter = d.first ?? "\\"
table = try c.decodeIfPresent([String: [String]].self, forKey: .table) ?? [:]
caseSensitive = try c.decodeIfPresent(Bool.self, forKey: .caseSensitive) ?? false
defaultReplacement = try c.decodeIfPresent(String.self, forKey: .defaultReplacement) ?? ""
bareCodes = try c.decodeIfPresent(Bool.self, forKey: .bareCodes) ?? true
}
public func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
try c.encode(String(delimiter), forKey: .delimiter)
try c.encode(table, forKey: .table)
try c.encode(caseSensitive, forKey: .caseSensitive)
try c.encode(defaultReplacement, forKey: .defaultReplacement)
try c.encode(bareCodes, forKey: .bareCodes)
}
/// Loads a tab-delimited PM code replacement file. Lines starting with '#' are ignored.
public static func load(tabDelimited text: String) -> CodeReplacements {
var table: [String: [String]] = [:]
for line in text.components(separatedBy: .newlines) {
let trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.isEmpty || trimmed.hasPrefix("#") { continue }
let cols = line.components(separatedBy: "\t")
guard cols.count >= 2 else { continue }
let code = cols[0].trimmingCharacters(in: .whitespaces)
guard !code.isEmpty else { continue }
table[code.lowercased()] = Array(cols.dropFirst()).map { $0.trimmingCharacters(in: .whitespaces) }
}
return CodeReplacements(table: table)
}
public func lookup(_ code: String) -> String? {
var name = code
var column = 1
if let hash = code.lastIndex(of: "#"), let n = Int(code[code.index(after: hash)...]) {
name = String(code[..<hash])
column = n
}
let key = caseSensitive ? name : name.lowercased()
let row = caseSensitive ? table.first(where: { $0.key == key })?.value : table[key]
guard let row, column >= 1, column <= row.count else { return nil }
return row[column - 1]
}
static let terminators: Set<Character> = [" ", "\t", "\n", "\r", ",", ";", ":", ")", "!", "?", ".", "/"]
static func isTokenChar(_ c: Character) -> Bool { c.isLetter || c.isNumber || c == "_" || c == "-" || c == "#" }
/// Live expansion while typing (PM behaviour): looks at the text just before the cursor and returns the
/// range (UTF-16, for NSTextView) to replace plus the replacement, or nil.
/// – "\\w10\\" (delimiter mode, as soon as the closing delimiter is typed)
/// – "w10" followed by space/comma/… (bare codes, the terminator itself is kept)
public func pendingExpansion(in text: String, cursor: Int) -> (range: NSRange, replacement: String)? {
guard !table.isEmpty else { return nil }
let ns = text as NSString
guard cursor > 0, cursor <= ns.length else { return nil }
let before = ns.substring(to: cursor)
guard let last = before.last else { return nil }
if last == delimiter {
let body = before.dropLast()
if let open = body.lastIndex(of: delimiter) {
let code = String(body[body.index(after: open)...])
if !code.isEmpty, !code.contains(where: { $0.isWhitespace }) {
let rep = lookup(code) ?? (defaultReplacement.isEmpty ? nil : defaultReplacement)
if let rep {
let start = (String(body[..<open]) as NSString).length
return (NSRange(location: start, length: cursor - start), rep)
}
}
}
}
if bareCodes, CodeReplacements.terminators.contains(last) {
let body = before.dropLast()
var start = body.endIndex
while start > body.startIndex, CodeReplacements.isTokenChar(body[body.index(before: start)]) {
start = body.index(before: start)
}
let token = String(body[start...])
guard !token.isEmpty, let rep = lookup(token) else { return nil }
let loc = (String(body[..<start]) as NSString).length
return (NSRange(location: loc, length: (token as NSString).length), rep)
}
return nil
}
public func expand(_ text: String) -> String {
guard !table.isEmpty, text.contains(delimiter) else { return text }
var out = ""
var i = text.startIndex
while i < text.endIndex {
let ch = text[i]
if ch == delimiter, let close = text[text.index(after: i)...].firstIndex(of: delimiter) {
let code = String(text[text.index(after: i)..<close])
if !code.isEmpty, !code.contains(" "), let rep = lookup(code) {
out += rep
i = text.index(after: close)
continue
}
}
out.append(ch)
i = text.index(after: i)
}
return out
}
}
public enum VariableExpander {
/// Expands `{variable}` tokens. Unknown variables are left untouched so the user notices them.
public static func expand(_ text: String, context: VariableContext, codes: CodeReplacements? = nil) -> String {
var s = codes?.expand(text) ?? text
guard s.contains("{") else { return s }
var out = ""
var rest = s[...]
while let open = rest.firstIndex(of: "{") {
out += rest[..<open]
guard let close = rest[open...].firstIndex(of: "}") else { break }
let name = rest[rest.index(after: open)..<close].lowercased()
if let v = context.values[name] {
out += v
} else {
out += rest[open...close]
}
rest = rest[rest.index(after: close)...]
}
out += rest
s = out
return s
}
public static func expand(_ values: IPTCValues, context: VariableContext, codes: CodeReplacements?) -> IPTCValues {
var r = values
for (k, v) in values.text { r.text[k] = expand(v, context: context, codes: codes) }
for (k, list) in values.lists { r.lists[k] = list.map { expand($0, context: context, codes: codes) } }
return r
}
/// Variables offered in the editor's insert menu.
public static let documented: [(String, String)] = [
("{filename}", "Dateiname"), ("{filenamebase}", "Dateiname ohne Endung"),
("{date}", "Aufnahmedatum (Format in Einstellungen)"), ("{isodate}", "Datum JJJJ-MM-TT"),
("{time}", "Uhrzeit"), ("{weekday}", "Wochentag"), ("{year4}", "Jahr"), ("{month0}", "Monat 01–12"),
("{monthname}", "Monatsname"), ("{day0}", "Tag 01–31"),
("{city}", "Stadt (IPTC)"), ("{country}", "Land (IPTC)"), ("{event}", "Ereignis (IPTC)"),
("{creator}", "Fotograf (IPTC)"), ("{credit}", "Credit (IPTC)"),
("{model}", "Kameramodell"), ("{serial}", "Seriennummer"), ("{lens}", "Objektiv"),
("{iso}", "ISO"), ("{aperture}", "Blende"), ("{shutter}", "Belichtungszeit"),
("{focallength}", "Brennweite"), ("{seqn}", "Laufnummer (Ingest)"), ("{seqn4}", "Laufnummer 4-stellig"),
]
}