Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
306 lines
15 KiB
Swift
306 lines
15 KiB
Swift
import Foundation
|
||
#if canImport(FoundationXML)
|
||
import FoundationXML
|
||
#endif
|
||
|
||
public enum TemplateImportError: LocalizedError {
|
||
case unreadable(String)
|
||
case noFieldsFound
|
||
|
||
public var errorDescription: String? {
|
||
switch self {
|
||
case .unreadable(let m): return "Vorlage konnte nicht gelesen werden: \(m)"
|
||
case .noFieldsFound: return "In der Datei wurden keine IPTC-Felder gefunden."
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Reads and writes metadata templates as XMP – the format Photo Mechanic uses for
|
||
/// saved IPTC Stationery Pad / IPTC templates (also readable by Lightroom & Bridge).
|
||
public enum XMPTemplateIO {
|
||
|
||
// MARK: Import
|
||
|
||
public static func importTemplate(from url: URL) throws -> IPTCTemplate {
|
||
let data = try Data(contentsOf: url)
|
||
var t = try parseAny(data: data)
|
||
// PM saves "<id>-<Name>.snap" – drop the numeric prefix for display.
|
||
var name = url.deletingPathExtension().lastPathComponent
|
||
if let dash = name.firstIndex(of: "-"), name[..<dash].allSatisfy(\.isNumber), name.distance(from: name.startIndex, to: dash) >= 4 {
|
||
name = String(name[name.index(after: dash)...])
|
||
}
|
||
t.name = name.replacingOccurrences(of: "_", with: " ")
|
||
return t
|
||
}
|
||
|
||
/// Accepts both a Photo Mechanic `.snap` (IPTCSettings wrapper) and plain XMP.
|
||
public static func parseAny(data: Data) throws -> IPTCTemplate {
|
||
if let snap = try? PMSnapFile.parse(data: data), let xmp = snap.xmpRecord {
|
||
var t = try parse(data: Data(xmp.utf8))
|
||
applySnapSettings(snap, to: &t)
|
||
return t
|
||
}
|
||
return try parse(data: data)
|
||
}
|
||
|
||
/// PM bookkeeping properties inside the XMP record (not image metadata).
|
||
static let pmControlProperties: Set<String> = [
|
||
"FieldsToApply", "FieldsToMerge", "ColorClass", "Tagged", "PMVersion", "ColorClassEval", "ColorClassApply",
|
||
"RatingEval", "RatingApply", "TagEval", "TagApply", "CaptionMergeStyle", "ApplyDateType", "Prefs",
|
||
]
|
||
|
||
public static func parse(data: Data) throws -> IPTCTemplate {
|
||
let props = try XMPPropertyCollector.collect(data: data)
|
||
var values = IPTCValues()
|
||
var extras: [String: String] = [:]
|
||
var pm: [String: [String]] = [:]
|
||
var found = 0
|
||
for p in props {
|
||
if p.namespace == XMPNamespace.photomechanic && pmControlProperties.contains(p.localName) {
|
||
pm[p.localName] = p.values
|
||
continue
|
||
}
|
||
if let field = IPTCField.forXMP(namespace: p.namespace, localName: p.localName) {
|
||
found += 1
|
||
if field.kind == .list {
|
||
var list = values.lists[field.id] ?? []
|
||
list.append(contentsOf: p.values.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty })
|
||
values.lists[field.id] = list.isEmpty ? nil : list
|
||
} else {
|
||
let v = p.values.joined(separator: field.xmpContainer == .seq ? "; " : "\n")
|
||
if !v.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { values.text[field.id] = v }
|
||
}
|
||
} else if p.namespace != XMPNamespace.rdf,
|
||
p.values.contains(where: { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }),
|
||
!(p.namespace == XMPNamespace.iptcCore && p.localName == "CreatorContactInfo") {
|
||
extras["\(p.namespace)|\(p.localName)"] = p.values.joined(separator: "\u{1F}")
|
||
}
|
||
}
|
||
// Keep only the date part of a fixed Date Created ("2026-02-15T00:00:00+01:00").
|
||
if let d = values.text["dateCreated"], d.count > 10 { values.text["dateCreated"] = String(d.prefix(10)) }
|
||
guard found > 0 || !extras.isEmpty else { throw TemplateImportError.noFieldsFound }
|
||
|
||
var t = IPTCTemplate(name: "Importiert", values: values, extras: extras)
|
||
// PM checkboxes: FieldsToApply holds 0x200 + IIM dataset (0x8000+ = PM extended fields).
|
||
if let apply = pm["FieldsToApply"] {
|
||
let codes = Set(apply.compactMap { Int($0.replacingOccurrences(of: "0x", with: ""), radix: 16) })
|
||
var applied = Set<String>()
|
||
for (fieldID, ds) in IPTCField.iimDataset where codes.contains(0x200 + ds) { applied.insert(fieldID) }
|
||
// Extended (XMP-only) fields use PM-internal codes ≥ 0x8000.
|
||
for c in codes where c >= 0x8000 {
|
||
if let id = pmExtendedCodes[c] { applied.insert(id) } else { t.unmappedPMCodes.append("0x" + String(c, radix: 16)) }
|
||
}
|
||
t.appliedFields = applied
|
||
}
|
||
// FieldsToMerge: keywords (0x219) listed → append, else replace (PM default for a template).
|
||
if let merge = pm["FieldsToMerge"] {
|
||
t.listMergeMode = merge.contains(where: { $0.lowercased() == "0x219" }) ? .append : .replace
|
||
}
|
||
if let dt = pm["ApplyDateType"]?.first { t.dateFromCapture = (dt == "2") }
|
||
return t
|
||
}
|
||
|
||
/// Known PM extended field codes (derived from real .snap files; extend when new ones show up).
|
||
static let pmExtendedCodes: [Int: String] = [
|
||
0x8013: "event",
|
||
]
|
||
|
||
static func applySnapSettings(_ snap: PMSnapFile, to t: inout IPTCTemplate) {
|
||
if let style = snap.applyDateStyle { t.dateFromCapture = (style == "2") }
|
||
}
|
||
|
||
// MARK: Export
|
||
|
||
public static func export(_ t: IPTCTemplate) -> String {
|
||
var simpleAttrs: [String] = []
|
||
var elements: [String] = []
|
||
var contact: [String] = []
|
||
var locationCreated: [String] = []
|
||
|
||
func esc(_ s: String) -> String {
|
||
s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")
|
||
.replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)
|
||
}
|
||
func qname(_ ns: String, _ local: String) -> String {
|
||
"\(XMPNamespace.preferredPrefix[ns] ?? "ns"):\(local)"
|
||
}
|
||
|
||
for field in IPTCField.all where !t.values.isEmpty(field) {
|
||
let q = qname(field.xmpNamespace, field.xmpLocalName)
|
||
let vals = field.kind == .list ? t.values.list(field) : [t.values[field]]
|
||
if field.section == .contact {
|
||
contact.append(" <\(q)>\(esc(vals[0]))</\(q)>")
|
||
continue
|
||
}
|
||
if field.section == .locationCreated {
|
||
locationCreated.append(" <\(q)>\(esc(vals[0]))</\(q)>")
|
||
continue
|
||
}
|
||
switch field.xmpContainer {
|
||
case .simple:
|
||
simpleAttrs.append(" \(q)=\"\(esc(vals[0]))\"")
|
||
case .alt:
|
||
elements.append(" <\(q)>\n <rdf:Alt>\n <rdf:li xml:lang=\"x-default\">\(esc(vals[0]))</rdf:li>\n </rdf:Alt>\n </\(q)>")
|
||
case .seq, .bag:
|
||
let tag = field.xmpContainer == .seq ? "rdf:Seq" : "rdf:Bag"
|
||
let lis = vals.map { " <rdf:li>\(esc($0))</rdf:li>" }.joined(separator: "\n")
|
||
elements.append(" <\(q)>\n <\(tag)>\n\(lis)\n </\(tag)>\n </\(q)>")
|
||
}
|
||
}
|
||
if !locationCreated.isEmpty {
|
||
elements.append(" <Iptc4xmpExt:LocationCreated>\n <rdf:Bag>\n <rdf:li rdf:parseType=\"Resource\">\n\(locationCreated.joined(separator: "\n"))\n </rdf:li>\n </rdf:Bag>\n </Iptc4xmpExt:LocationCreated>")
|
||
}
|
||
if !contact.isEmpty {
|
||
elements.append(" <Iptc4xmpCore:CreatorContactInfo rdf:parseType=\"Resource\">\n\(contact.joined(separator: "\n"))\n </Iptc4xmpCore:CreatorContactInfo>")
|
||
}
|
||
// Unknown properties from imported PM templates (simple values only).
|
||
var extraNS: [String: String] = [:]
|
||
for (key, value) in t.extras.sorted(by: { $0.key < $1.key }) {
|
||
let parts = key.components(separatedBy: "|")
|
||
guard parts.count == 2 else { continue }
|
||
let prefix: String
|
||
if let known = XMPNamespace.preferredPrefix[parts[0]] {
|
||
prefix = known
|
||
} else if let seen = extraNS[parts[0]] {
|
||
prefix = seen
|
||
} else {
|
||
prefix = "ns\(extraNS.count + 1)"
|
||
extraNS[parts[0]] = prefix
|
||
}
|
||
let items = value.components(separatedBy: "\u{1F}")
|
||
if items.count == 1 {
|
||
simpleAttrs.append(" \(prefix):\(parts[1])=\"\(esc(items[0]))\"")
|
||
} else {
|
||
let lis = items.map { " <rdf:li>\(esc($0))</rdf:li>" }.joined(separator: "\n")
|
||
elements.append(" <\(prefix):\(parts[1])>\n <rdf:Bag>\n\(lis)\n </rdf:Bag>\n </\(prefix):\(parts[1])>")
|
||
}
|
||
}
|
||
var nsDecl = XMPNamespace.preferredPrefix.sorted(by: { $0.value < $1.value })
|
||
.map { " xmlns:\($0.value)=\"\($0.key)\"" }
|
||
nsDecl += extraNS.map { " xmlns:\($0.value)=\"\($0.key)\"" }
|
||
|
||
return """
|
||
<?xpacket begin="\u{FEFF}" id="W5M0MpCehiHzreSzNTczkc9d"?>
|
||
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Lichtkasten">
|
||
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||
<rdf:Description rdf:about=""
|
||
\(nsDecl.joined(separator: "\n"))\(simpleAttrs.isEmpty ? "" : "\n" + simpleAttrs.joined(separator: "\n"))>
|
||
\(elements.joined(separator: "\n"))
|
||
</rdf:Description>
|
||
</rdf:RDF>
|
||
</x:xmpmeta>
|
||
<?xpacket end="w"?>
|
||
"""
|
||
}
|
||
}
|
||
|
||
/// Flattens all XMP properties (attributes + elements, including structs like
|
||
/// CreatorContactInfo) into (namespace, localName, values) triples.
|
||
final class XMPPropertyCollector: NSObject, XMLParserDelegate {
|
||
struct Property { var namespace: String; var localName: String; var values: [String] }
|
||
|
||
private var prefixes: [String: String] = ["xml": "http://www.w3.org/XML/1998/namespace"]
|
||
private var props: [Property] = []
|
||
private struct Frame { var ns: String; var local: String; var text = ""; var liValues: [String] = []; var hasChildElements = false }
|
||
private var stack: [Frame] = []
|
||
private var error: Error?
|
||
|
||
static func collect(data: Data) throws -> [Property] {
|
||
let c = XMPPropertyCollector()
|
||
let p = XMLParser(data: data)
|
||
p.shouldProcessNamespaces = true
|
||
p.shouldReportNamespacePrefixes = true
|
||
p.delegate = c
|
||
if !p.parse() {
|
||
throw TemplateImportError.unreadable(p.parserError?.localizedDescription ?? "ungültiges XML")
|
||
}
|
||
return c.props
|
||
}
|
||
|
||
func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) {
|
||
prefixes[prefix] = namespaceURI
|
||
}
|
||
|
||
private func isContainer(_ ns: String, _ local: String) -> Bool {
|
||
ns == XMPNamespace.rdf || ns == "adobe:ns:meta/"
|
||
}
|
||
|
||
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?,
|
||
qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {
|
||
let ns = namespaceURI ?? ""
|
||
if !stack.isEmpty { stack[stack.count - 1].hasChildElements = true }
|
||
// Attributes on rdf:Description or on struct property elements are simple properties.
|
||
for (qn, value) in attributeDict {
|
||
let parts = qn.split(separator: ":", maxSplits: 1).map(String.init)
|
||
guard parts.count == 2, let uri = prefixes[parts[0]] else { continue }
|
||
if uri == XMPNamespace.rdf || parts[0] == "xml" || parts[0] == "xmlns" || uri == "adobe:ns:meta/" { continue }
|
||
props.append(Property(namespace: uri, localName: parts[1], values: [value]))
|
||
}
|
||
stack.append(Frame(ns: ns, local: elementName))
|
||
}
|
||
|
||
func parser(_ parser: XMLParser, foundCharacters string: String) {
|
||
guard !stack.isEmpty else { return }
|
||
stack[stack.count - 1].text += string
|
||
}
|
||
|
||
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
|
||
guard let frame = stack.popLast() else { return }
|
||
// Keep text exactly (captions may start with blank lines), but treat pure formatting whitespace as empty.
|
||
let text = frame.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "" : frame.text
|
||
if frame.ns == XMPNamespace.rdf && frame.local == "li" {
|
||
// Hand the li value up to the nearest real property.
|
||
if let idx = stack.lastIndex(where: { !isContainer($0.ns, $0.local) }) {
|
||
stack[idx].liValues.append(text)
|
||
}
|
||
return
|
||
}
|
||
if isContainer(frame.ns, frame.local) { return }
|
||
if frame.ns == XMPNamespace.photomechanic && frame.liValues.isEmpty && frame.hasChildElements { return }
|
||
if !frame.liValues.isEmpty {
|
||
props.append(Property(namespace: frame.ns, localName: frame.local, values: frame.liValues))
|
||
} else if !frame.hasChildElements {
|
||
props.append(Property(namespace: frame.ns, localName: frame.local, values: [text]))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Photo Mechanic `.snap` file: `<IPTCSettings><XMPRecord>…escaped XMP…</XMPRecord><ApplyFlags/>…`
|
||
struct PMSnapFile {
|
||
var xmpRecord: String?
|
||
var applyFlags: String?
|
||
var mergeFlags: String?
|
||
var applyDateStyle: String?
|
||
|
||
static func parse(data: Data) throws -> PMSnapFile {
|
||
final class Delegate: NSObject, XMLParserDelegate {
|
||
var root: String?
|
||
var current: String?
|
||
var buffer = ""
|
||
var result = PMSnapFile()
|
||
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?,
|
||
qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]) {
|
||
if root == nil { root = elementName }
|
||
current = elementName
|
||
buffer = ""
|
||
}
|
||
func parser(_ parser: XMLParser, foundCharacters string: String) { buffer += string }
|
||
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
|
||
switch elementName {
|
||
case "XMPRecord": result.xmpRecord = buffer
|
||
case "ApplyFlags": result.applyFlags = buffer
|
||
case "MergeFlags": result.mergeFlags = buffer
|
||
case "ApplyDateStyle": result.applyDateStyle = buffer.trimmingCharacters(in: .whitespacesAndNewlines)
|
||
default: break
|
||
}
|
||
buffer = ""
|
||
}
|
||
}
|
||
let d = Delegate()
|
||
let p = XMLParser(data: data)
|
||
p.delegate = d
|
||
guard p.parse(), d.root == "IPTCSettings" else { throw TemplateImportError.unreadable("keine .snap-Datei") }
|
||
return d.result
|
||
}
|
||
}
|