import Foundation /// Builds exiftool commands that write IPTC exactly like Photo Mechanic does: /// IIM (UTF-8, CodedCharacterSet set) + XMP in sync for JPEG/TIFF/DNG, XMP sidecar for RAW. public struct MetadataWriter: Sendable { public let exiftool: ExifTool public init(exiftool: ExifTool) { self.exiftool = exiftool } /// Writes the given fields (only those – other fields stay untouched) to all targets of the item. @discardableResult public func write(values: IPTCValues, fields: [IPTCField], to item: PhotoItem) async throws -> [String] { var warnings: [String] = [] for target in item.metadataTargets { let args = try arguments(values: values, fields: fields, targetKind: target.kind) + [target.url.path] let (_, err) = try await exiftool.execute(["-overwrite_original", "-m"] + args) if !err.isEmpty { warnings.append(contentsOf: Self.relevantMessages(err, file: target.url)) } if err.contains("Error:") { throw ExifToolError.failed(err) } } return warnings } public func writeRating(_ rating: Int, to item: PhotoItem) async throws { try await writeFlags(["-XMP-xmp:Rating=\(max(0, min(5, rating)))"], item: item) } public func writeLabel(_ label: ColorLabel?, to item: PhotoItem) async throws { if let label { try await writeFlags(["-XMP-xmp:Label=\(label.xmpValue)", "-XMP-photomech:ColorClass=\(label.pmColorClass)"], item: item) } else { try await writeFlags(["-XMP-xmp:Label=", "-XMP-photomech:ColorClass="], item: item) } } public func writeTag(_ tagged: Bool, to item: PhotoItem) async throws { try await writeFlags(["-XMP-photomech:Tagged=\(tagged ? "Yes" : "No")"], item: item) } private func writeFlags(_ args: [String], item: PhotoItem) async throws { for target in item.metadataTargets { let (_, err) = try await exiftool.execute(["-overwrite_original", "-m"] + args + [target.url.path]) if err.contains("Error:") { throw ExifToolError.failed(err) } } } /// Argument list for one target file (without the file path). public func arguments(values: IPTCValues, fields: [IPTCField], targetKind: FileKind) throws -> [String] { let writeIIM = targetKind.supportsIIM var args: [String] = [] if writeIIM { args.append("-IPTC:CodedCharacterSet=UTF8") } for field in fields { var tags = [field.xmpTag] if writeIIM, let iim = field.iimTag { tags.append(iim) } if field.kind == .list { let list = values.list(field) for tag in tags { if list.isEmpty { args.append("-\(tag)=") } for item in list { args.append("-\(tag)=\(item)") } } } else { var value = values.text[field.id] ?? "" if field.id == "dateCreated" { value = value.replacingOccurrences(of: "-", with: ":") if !value.isEmpty, value.count != 10 { continue } // ignore incomplete dates } for tag in tags { if value.isEmpty { args.append("-\(tag)=") } else if value.contains("\n") || value.contains("\r") { let file = try exiftool.writeValueFile(value) args.append("-\(tag)<=\(file.path)") } else { args.append("-\(tag)=\(value)") } } } } if writeIIM && targetKind != .dng { args.append("-IPTCDigest=new") } return args } static func relevantMessages(_ stderr: String, file: URL) -> [String] { stderr.components(separatedBy: .newlines) .filter { !$0.isEmpty && !$0.contains("image files updated") } .map { "\(file.lastPathComponent): \($0)" } } } public extension MetadataWriter { /// Applies a template to the items, expanding variables & codes per image. /// Returns the new values per item id (so the UI can update without re-reading). func apply(template: IPTCTemplate, to items: [PhotoItem], codes: CodeReplacements?, dateFormat: String, progress: (@Sendable (Int) -> Void)? = nil) async throws -> [String: IPTCValues] { var result: [String: IPTCValues] = [:] // Fields touched by the template (non-empty, or all if clearEmptyFields). let fields = IPTCField.all.filter { template.clearEmptyFields || !template.values.isEmpty($0) } for (i, item) in items.enumerated() { let merged = template.apply(to: item.iptc) let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, iptc: merged, dateFormat: dateFormat) let expanded = VariableExpander.expand(merged, context: ctx, codes: codes) try await write(values: expanded, fields: fields, to: item) result[item.id] = expanded progress?(i + 1) } return result } }