244 lines
12 KiB
Swift
244 lines
12 KiB
Swift
import Foundation
|
||
|
||
public enum FileKind: String, Sendable, Codable {
|
||
case raw, dng, jpeg, heic, tiff, png, other
|
||
|
||
public static let rawExtensions: Set<String> = [
|
||
"cr2", "cr3", "crw", "nef", "nrw", "arw", "srf", "sr2", "raf", "orf", "rw2", "pef",
|
||
"3fr", "iiq", "erf", "mos", "mrw", "x3f", "srw", "gpr", "rwl", "fff",
|
||
]
|
||
|
||
public init(url: URL) {
|
||
let ext = url.pathExtension.lowercased()
|
||
switch ext {
|
||
case _ where FileKind.rawExtensions.contains(ext): self = .raw
|
||
case "dng": self = .dng
|
||
case "jpg", "jpeg", "jpe": self = .jpeg
|
||
case "heic", "heif", "hif": self = .heic
|
||
case "tif", "tiff": self = .tiff
|
||
case "png": self = .png
|
||
default: self = .other
|
||
}
|
||
}
|
||
|
||
public var isImage: Bool { self != .other }
|
||
public var isRawLike: Bool { self == .raw || self == .dng }
|
||
/// Proprietary RAWs get an XMP sidecar (like PM & Lightroom). Everything else is written in place.
|
||
public var usesSidecar: Bool { self == .raw }
|
||
/// IPTC-IIM can be embedded (JPEG/TIFF/DNG/PSD). PNG/HEIC get XMP only.
|
||
public var supportsIIM: Bool { self == .jpeg || self == .tiff || self == .dng }
|
||
}
|
||
|
||
/// Photo Mechanic color classes 1–8 (keys 1–8). Classes 1–5 map to Lightroom's label colors.
|
||
public enum ColorLabel: String, CaseIterable, Codable, Sendable {
|
||
case red = "Red", yellow = "Yellow", green = "Green", blue = "Blue", purple = "Purple"
|
||
case cyan = "Cyan", orange = "Orange", gray = "Gray"
|
||
|
||
/// Value written to xmp:Label (Lightroom default label set understands Red…Purple).
|
||
public var xmpValue: String { rawValue }
|
||
/// Photo Mechanic color class number.
|
||
public var pmColorClass: Int { (ColorLabel.allCases.firstIndex(of: self) ?? 0) + 1 }
|
||
/// PM's default class names.
|
||
public var pmName: String {
|
||
["Winner", "Winner alt", "Superior", "Superior alt", "Typical", "Typical alt", "Extras", "Trash"][pmColorClass - 1]
|
||
}
|
||
public var germanName: String {
|
||
switch self {
|
||
case .red: return "Rot"
|
||
case .yellow: return "Gelb"
|
||
case .green: return "Grün"
|
||
case .blue: return "Blau"
|
||
case .purple: return "Magenta"
|
||
case .cyan: return "Cyan"
|
||
case .orange: return "Orange"
|
||
case .gray: return "Grau"
|
||
}
|
||
}
|
||
|
||
public init?(xmp: String) {
|
||
let l = xmp.lowercased()
|
||
let map: [String: ColorLabel] = ["red": .red, "rot": .red, "yellow": .yellow, "gelb": .yellow,
|
||
"green": .green, "grün": .green, "blue": .blue, "blau": .blue,
|
||
"purple": .purple, "lila": .purple, "violett": .purple, "magenta": .purple,
|
||
"cyan": .cyan, "orange": .orange, "gray": .gray, "grey": .gray, "grau": .gray]
|
||
guard let c = map[l] else { return nil }
|
||
self = c
|
||
}
|
||
|
||
public init?(pmColorClass n: Int) {
|
||
guard n >= 1, n <= ColorLabel.allCases.count else { return nil }
|
||
self = ColorLabel.allCases[n - 1]
|
||
}
|
||
}
|
||
|
||
/// One entry in the contact sheet. A RAW+JPEG pair is shown as a single item (like PM).
|
||
public struct PhotoItem: Identifiable, Hashable, Sendable {
|
||
public var id: String { primary.path }
|
||
public var primary: URL
|
||
/// Other files with the same base name (e.g. the JPEG next to a RAW).
|
||
public var companions: [URL]
|
||
public var kind: FileKind
|
||
public var fileSize: Int64
|
||
public var modified: Date
|
||
|
||
public var rating: Int = 0
|
||
public var label: ColorLabel?
|
||
public var tagged = false
|
||
public var iptc = IPTCValues()
|
||
public var exif: [String: String] = [:]
|
||
public var captureDate: Date?
|
||
public var metadataLoaded = false
|
||
/// Frame number part of PM's Prefs ("Tagged:ColorClass:Rating:Frame"), kept when we rewrite it.
|
||
public var pmFrame = "-00001"
|
||
|
||
public init(primary: URL, companions: [URL] = [], fileSize: Int64 = 0, modified: Date = Date()) {
|
||
self.primary = primary
|
||
self.companions = companions
|
||
self.kind = FileKind(url: primary)
|
||
self.fileSize = fileSize
|
||
self.modified = modified
|
||
}
|
||
|
||
public static func == (a: PhotoItem, b: PhotoItem) -> Bool {
|
||
a.id == b.id && a.rating == b.rating && a.label == b.label && a.tagged == b.tagged && a.iptc == b.iptc
|
||
&& a.metadataLoaded == b.metadataLoaded
|
||
}
|
||
|
||
public func hash(into h: inout Hasher) { h.combine(id) }
|
||
|
||
public var filename: String { primary.lastPathComponent }
|
||
public var baseName: String { primary.deletingPathExtension().lastPathComponent }
|
||
|
||
public var sidecarURL: URL { primary.deletingPathExtension().appendingPathExtension("xmp") }
|
||
|
||
/// All files that should receive metadata (RAW → sidecar, plus embedded JPEG companions).
|
||
public var metadataTargets: [(url: URL, kind: FileKind)] {
|
||
var t: [(url: URL, kind: FileKind)] = []
|
||
t.append(kind.usesSidecar ? (url: sidecarURL, kind: FileKind.raw) : (url: primary, kind: kind))
|
||
for c in companions {
|
||
let k = FileKind(url: c)
|
||
if k.isImage, !k.usesSidecar { t.append((url: c, kind: k)) }
|
||
}
|
||
return t
|
||
}
|
||
|
||
/// The JPEG that represents this item for upload (companion JPEG or primary JPEG).
|
||
public var jpegForUpload: URL? {
|
||
if kind == .jpeg { return primary }
|
||
return companions.first { FileKind(url: $0) == .jpeg }
|
||
}
|
||
|
||
public var rawFile: URL? { kind.isRawLike ? primary : companions.first { FileKind(url: $0).isRawLike } }
|
||
|
||
public struct PMPrefs: Equatable, Sendable {
|
||
public var tagged: Bool; public var colorClass: Int; public var rating: Int; public var frame: String
|
||
}
|
||
|
||
/// Parses PM's Prefs value, raw ("1:3:0:-00001") or exiftool-printed ("Tagged:1, ColorClass:3, …").
|
||
public static func parsePMPrefs(_ raw: String) -> PMPrefs? {
|
||
var s = raw
|
||
if s.contains("Tagged") {
|
||
s = s.replacingOccurrences(of: "Tagged:", with: "").replacingOccurrences(of: "ColorClass:", with: "")
|
||
.replacingOccurrences(of: "Rating:", with: "").replacingOccurrences(of: "FrameNum:", with: "")
|
||
.replacingOccurrences(of: ", ", with: ":").replacingOccurrences(of: " ", with: "")
|
||
}
|
||
let parts = s.split(separator: ":", omittingEmptySubsequences: false).map { $0.trimmingCharacters(in: .whitespaces) }
|
||
guard parts.count >= 3, let t = Int(parts[0]), let c = Int(parts[1]), let r = Int(parts[2]) else { return nil }
|
||
return PMPrefs(tagged: t != 0, colorClass: c, rating: r, frame: parts.count > 3 ? parts[3] : "-00001")
|
||
}
|
||
|
||
/// PM Prefs string for the current state.
|
||
public var pmPrefsString: String { "\(tagged ? 1 : 0):\(label?.pmColorClass ?? 0):\(max(0, rating)):\(pmFrame)" }
|
||
|
||
/// Applies exiftool output (primary file + optional sidecar) to the item.
|
||
public mutating func apply(fileMeta: [String: MetadataValue], sidecarMeta: [String: MetadataValue]?) {
|
||
// EXIF from the image itself
|
||
var exif: [String: String] = [:]
|
||
for (k, v) in fileMeta where !k.hasPrefix("IPTC:") && !k.hasPrefix("XMP-") { exif[k] = v.string }
|
||
self.exif = exif
|
||
if let d = exif["DateTimeOriginal"] ?? exif["CreateDate"] { captureDate = ExifDate.parse(d) }
|
||
|
||
// Sidecar wins for XMP (that is what LR and PM do), embedded values are the fallback.
|
||
let xmpSource = sidecarMeta ?? [:]
|
||
func xmp(_ tag: String) -> MetadataValue? { xmpSource[tag] ?? fileMeta[tag] }
|
||
|
||
// Photo Mechanic keeps tag/color/rating in "Prefs" (IPTC 2:221 and photomechanic:Prefs):
|
||
// "1:3:0:-00001" = tagged, color class 3, no stars, frame. Many PM files only have this.
|
||
let prefs = (xmp("XMP-photomech:Prefs") ?? fileMeta["IPTC:Prefs"]).flatMap { PhotoItem.parsePMPrefs($0.string) }
|
||
if let p = prefs { pmFrame = p.frame }
|
||
|
||
rating = xmp("XMP-xmp:Rating")?.int ?? prefs?.rating ?? 0
|
||
// PM color class first (it knows all 8 classes), then Lightroom's label.
|
||
label = xmp("XMP-photomech:ColorClass")?.int.flatMap { ColorLabel(pmColorClass: $0) }
|
||
?? prefs.flatMap { ColorLabel(pmColorClass: $0.colorClass) }
|
||
?? xmp("XMP-xmp:Label").flatMap { ColorLabel(xmp: $0.string) }
|
||
tagged = xmp("XMP-photomech:Tagged")?.bool ?? prefs?.tagged ?? false
|
||
|
||
var values = IPTCValues()
|
||
for field in IPTCField.all {
|
||
let v = xmp(field.xmpReadKey) ?? field.iimTag.flatMap { fileMeta[$0] }
|
||
guard let v else { continue }
|
||
if field.kind == .list {
|
||
let l = v.list.filter { !$0.isEmpty }
|
||
if !l.isEmpty { values.lists[field.id] = l }
|
||
} else {
|
||
var s = v.string
|
||
if field.id == "dateCreated" {
|
||
// "2026:11:02 18:31:05+01:00" → "2026-11-02 18:31:05+01:00" – keep the time of day,
|
||
// otherwise every save of the field would cut it from XMP DateCreated
|
||
s = String(s.prefix(10)).replacingOccurrences(of: ":", with: "-") + String(s.dropFirst(10))
|
||
}
|
||
if !s.isEmpty { values.text[field.id] = s }
|
||
}
|
||
}
|
||
iptc = values
|
||
metadataLoaded = true
|
||
}
|
||
}
|
||
|
||
public enum FolderScanner {
|
||
/// Lists images in a folder and pairs RAW+JPEG by base name.
|
||
public static func scan(folder: URL, recursive: Bool = false) throws -> [PhotoItem] {
|
||
let fm = FileManager.default
|
||
let keys: [URLResourceKey] = [.isRegularFileKey, .fileSizeKey, .contentModificationDateKey, .isHiddenKey]
|
||
var urls: [URL] = []
|
||
if recursive {
|
||
var scanError: Error?
|
||
guard let enumerator = fm.enumerator(at: folder, includingPropertiesForKeys: keys,
|
||
options: [.skipsHiddenFiles, .skipsPackageDescendants],
|
||
errorHandler: { _, error in
|
||
scanError = error
|
||
return false
|
||
}) else {
|
||
throw CocoaError(.fileReadUnknown, userInfo: [NSURLErrorKey: folder])
|
||
}
|
||
for case let url as URL in enumerator { urls.append(url) }
|
||
if let scanError { throw scanError }
|
||
} else {
|
||
urls = try fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles])
|
||
}
|
||
urls = try urls.filter { url in
|
||
guard !url.lastPathComponent.hasPrefix("._"), FileKind(url: url).isImage else { return false }
|
||
return try url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true
|
||
}
|
||
|
||
// Group by directory + lowercase base name
|
||
var groups: [String: [URL]] = [:]
|
||
for u in urls {
|
||
let key = u.deletingLastPathComponent().path + "/" + u.deletingPathExtension().lastPathComponent.lowercased()
|
||
groups[key, default: []].append(u)
|
||
}
|
||
var items: [PhotoItem] = []
|
||
for (_, files) in groups {
|
||
// Primary: RAW > DNG > TIFF > HEIC > JPEG > PNG
|
||
let order: [FileKind] = [.raw, .dng, .tiff, .heic, .jpeg, .png]
|
||
let sorted = files.sorted { (order.firstIndex(of: FileKind(url: $0)) ?? 9) < (order.firstIndex(of: FileKind(url: $1)) ?? 9) }
|
||
guard let primary = sorted.first else { continue }
|
||
let rv = try? primary.resourceValues(forKeys: Set(keys))
|
||
items.append(PhotoItem(primary: primary, companions: Array(sorted.dropFirst()),
|
||
fileSize: Int64(rv?.fileSize ?? 0), modified: rv?.contentModificationDate ?? Date()))
|
||
}
|
||
return items.sorted { $0.filename.localizedStandardCompare($1.filename) == .orderedAscending }
|
||
}
|
||
}
|