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"] 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 enum CodingKeys: String, CodingKey { case delimiter, table, caseSensitive } 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 } 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) } /// 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) } 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[..= 1, column <= row.count else { return nil } return row[column - 1] } 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).. 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[.. 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"), ] }