Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
191 lines
8.3 KiB
Swift
191 lines
8.3 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 }
|
|
}
|
|
|
|
public enum ColorLabel: String, CaseIterable, Codable, Sendable {
|
|
case red = "Red", yellow = "Yellow", green = "Green", blue = "Blue", purple = "Purple"
|
|
|
|
/// Value written to Lightroom's xmp:Label (LR default label set, German UI uses the same English keys
|
|
/// only if the label set is "Lightroom-Standard"; see README).
|
|
public var xmpValue: String { rawValue }
|
|
/// Photo Mechanic color class number for compatibility.
|
|
public var pmColorClass: Int { (ColorLabel.allCases.firstIndex(of: self) ?? 0) + 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 "Lila"
|
|
}
|
|
}
|
|
|
|
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]
|
|
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
|
|
|
|
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 } }
|
|
|
|
/// 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] }
|
|
|
|
rating = xmp("XMP-xmp:Rating")?.int ?? 0
|
|
label = xmp("XMP-xmp:Label").flatMap { ColorLabel(xmp: $0.string) }
|
|
?? xmp("XMP-photomech:ColorClass")?.int.flatMap { ColorLabel(pmColorClass: $0) }
|
|
tagged = xmp("XMP-photomech:Tagged")?.bool ?? 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" { s = String(s.prefix(10)).replacingOccurrences(of: ":", with: "-") }
|
|
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 {
|
|
if let e = fm.enumerator(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles, .skipsPackageDescendants]) {
|
|
for case let u as URL in e { urls.append(u) }
|
|
}
|
|
} else {
|
|
urls = try fm.contentsOfDirectory(at: folder, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles])
|
|
}
|
|
urls = urls.filter { !$0.lastPathComponent.hasPrefix("._") && FileKind(url: $0).isImage }
|
|
|
|
// 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 }
|
|
}
|
|
}
|