import AppKit import CommanderCore /// Ctrl+Shift+M: date dei file (creazione, modifica, accesso) come in BulkFileChanger. /// In alto i file selezionati con le loro date (in blu quelle che cambieranno), sotto "Modifica ora / attributi". final class FileDatesWindow: NSObject, NSWindowDelegate, NSTableViewDataSource, NSTableViewDelegate, NSTextFieldDelegate { private struct Row { let url: URL let isDirectory: Bool var old: FileDates var new: FileDates var error: String? } private let window: NSWindow private var rows: [Row] private let table = NSTableView() private let status = NSTextField(labelWithString: "") private var exifLoaded = false private struct FieldControls { let setDate = NSButton(checkboxWithTitle: "", target: nil, action: nil) let date = NSDatePicker() let setTime = NSButton(checkboxWithTitle: "", target: nil, action: nil) let time = NSDatePicker() let add = NSButton(checkboxWithTitle: "Aggiungi", target: nil, action: nil) let amount = NSTextField(string: "0") let step = NSPopUpButton() } private var controls: [FileDateKind: FieldControls] = [:] private let gmt = NSButton(checkboxWithTitle: "Ora specificata in GMT", target: nil, action: nil) private let sequence = NSButton(checkboxWithTitle: "Modalità sequenza data/ora", target: nil, action: nil) private let copyFrom = NSButton(checkboxWithTitle: "Copia orario da…", target: nil, action: nil) private let copySource = NSPopUpButton() private var copyTo: [FileDateKind: NSButton] = [:] private let hidden = NSPopUpButton() private let locked = NSPopUpButton() private static let longDate: DateFormatter = { let f = DateFormatter() f.dateFormat = "dd/MM/yyyy HH:mm:ss" return f }() static func run(items: [FileItem]) { let w = FileDatesWindow(items: items) w.show() } private init(items: [FileItem]) { rows = items.map { Row(url: $0.url, isDirectory: $0.showsAsFolder, old: FileDates.read($0.url), new: FileDates.read($0.url)) } window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1250, height: 720), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false) window.title = "Modifica data e ora dei file" window.isReleasedWhenClosed = false window.minSize = NSSize(width: 1000, height: 520) super.init() window.delegate = self build() loadExif() recompute() } private func show() { _ = window.setFrameUsingName("DateFile") window.centerInApp() window.setFrameAutosaveName("DateFile") let previous = Dialogs.modalKeyHandler Dialogs.modalKeyHandler = { [weak self] e in self?.handleKey(e) ?? false } defer { Dialogs.modalKeyHandler = previous } window.makeKeyAndOrderFront(nil) NSApp.runModal(for: window) window.orderOut(nil) } func windowWillClose(_ notification: Notification) { NSApp.stopModal() } private func handleKey(_ e: NSEvent) -> Bool { guard NSApp.keyWindow === window else { return false } let mods = e.modifierFlags.intersection([.control, .option, .command, .shift]) if e.keyCode == KeyCode.escape && mods.isEmpty { window.close(); return true } return false } // MARK: - Costruzione private func build() { for (id, title, width) in [("name", "Nome del file", 200.0), ("path", "Percorso completo", 170.0), ("exif", "Data scatto (EXIF)", 140.0), ("modified", "Data modifica", 140.0), ("created", "Data creazione", 140.0), ("accessed", "Data ultimo accesso", 140.0), ("diff", "Differenza modifica-creazione", 190.0)] { let c = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(id)) c.title = title c.width = width table.addTableColumn(c) } table.dataSource = self table.delegate = self table.rowHeight = 18 table.usesAlternatingRowBackgroundColors = true table.columnAutoresizingStyle = .lastColumnOnlyAutoresizingStyle let scroll = NSScrollView() scroll.documentView = table scroll.hasVerticalScroller = true scroll.hasHorizontalScroller = true scroll.borderType = .bezelBorder // Giorno / ora del file let initial = rows.first?.old.modified ?? Date() var gridRows: [[NSView]] = [] for kind in FileDateKind.allCases { let c = FieldControls() c.date.datePickerStyle = .textFieldAndStepper c.date.datePickerElements = .yearMonthDay c.time.datePickerStyle = .textFieldAndStepper c.time.datePickerElements = .hourMinuteSecond for p in [c.date, c.time] { p.locale = Locale(identifier: "it_IT") p.dateValue = initial p.target = self p.action = #selector(changed) } for b in [c.setDate, c.setTime, c.add] { b.target = self b.action = #selector(changed) } c.amount.delegate = self c.amount.widthAnchor.constraint(equalToConstant: 70).isActive = true for s in TimeStep.allCases { c.step.addItem(withTitle: s.title) } c.step.selectItem(at: TimeStep.hours.rawValue) c.step.target = self c.step.action = #selector(changed) controls[kind] = c gridRows.append([NSTextField(labelWithString: kind.title + ":"), c.setDate, c.date, c.setTime, c.time, c.add, c.amount, c.step]) } let grid = NSGridView(views: gridRows) grid.rowSpacing = 8 grid.columnSpacing = 8 grid.column(at: 0).width = 90 grid.setContentHuggingPriority(.required, for: .horizontal) for b in [gmt, sequence, copyFrom] { b.target = self b.action = #selector(changed) } gmt.toolTip = "Giorno e ora scritti sopra sono in GMT invece che nell'ora italiana" sequence.toolTip = "Il primo file riceve la data indicata, ognuno dei successivi \"Aggiungi\" in più (utile per mettere in ordine le foto)" for s in DateSource.allCases { copySource.addItem(withTitle: s.title) } copySource.selectItem(at: DateSource.modified.rawValue) copySource.target = self copySource.action = #selector(changed) var targets: [NSView] = [copyFrom, copySource, NSTextField(labelWithString: "A:")] for kind in FileDateKind.allCases { let b = NSButton(checkboxWithTitle: kind.title, target: self, action: #selector(changed)) b.state = kind == .modified ? .off : .on copyTo[kind] = b targets.append(b) } let options = NSStackView(views: [gmt, sequence]) options.spacing = 30 let copyRow = NSStackView(views: targets) copyRow.spacing = 10 for p in [hidden, locked] { p.addItems(withTitles: ["Non modificare", "Sì", "No"]) p.target = self p.action = #selector(changed) } let attrs = NSStackView(views: [NSTextField(labelWithString: "Nascosto:"), hidden, NSTextField(labelWithString: "Bloccato:"), locked]) attrs.spacing = 10 locked.toolTip = "Il lucchetto del Finder: il file non si può modificare né cancellare" let dateGroup = box("Giorno / ora del file", [grid, options, copyRow]) let attrGroup = box("Attributi del file", [attrs]) let run = ActionButton("Esegui") { [weak self] in self?.execute() } run.keyEquivalent = "\r" let close = ActionButton("Chiudi") { [weak self] in self?.window.close() } status.lineBreakMode = .byTruncatingTail status.setContentCompressionResistancePriority(.init(1), for: .horizontal) let bottom = NSStackView(views: [status, run, close]) for b in [run, close] { b.widthAnchor.constraint(equalToConstant: 110).isActive = true } let root = NSStackView(views: [scroll, dateGroup, attrGroup, bottom]) root.orientation = .vertical root.alignment = .leading root.spacing = 10 root.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) for v in [scroll, dateGroup, attrGroup, bottom] { v.widthAnchor.constraint(equalTo: root.widthAnchor, constant: -20).isActive = true } scroll.setContentHuggingPriority(.init(1), for: .vertical) window.contentView = root } private func box(_ title: String, _ views: [NSView]) -> NSView { let label = NSTextField(labelWithString: title) label.font = NSFont.boldSystemFont(ofSize: 12) let inner = NSStackView(views: views) inner.orientation = .vertical inner.alignment = .leading inner.spacing = 10 inner.edgeInsets = NSEdgeInsets(top: 8, left: 10, bottom: 8, right: 10) inner.wantsLayer = true inner.layer?.borderWidth = 1 inner.layer?.cornerRadius = 6 inner.layer?.borderColor = NSColor.separatorColor.cgColor let s = NSStackView(views: [label, inner]) s.orientation = .vertical s.alignment = .leading s.spacing = 4 inner.widthAnchor.constraint(equalTo: s.widthAnchor).isActive = true return s } // MARK: - Anteprima private var settings: DateChangeSettings { var s = DateChangeSettings() let utc = TimeZone(identifier: "UTC")! for (kind, c) in controls { var f = DateChangeSettings.Field() f.setDate = c.setDate.state == .on f.date = c.date.dateValue f.setTime = c.setTime.state == .on f.time = c.time.dateValue f.add = c.add.state == .on f.amount = Int(c.amount.stringValue.trimmingCharacters(in: .whitespaces)) ?? 0 f.step = TimeStep(rawValue: c.step.indexOfSelectedItem) ?? .hours s.fields[kind] = f c.date.isEnabled = f.setDate c.time.isEnabled = f.setTime c.amount.isEnabled = f.add c.step.isEnabled = f.add c.date.timeZone = gmt.state == .on ? utc : .current c.time.timeZone = gmt.state == .on ? utc : .current } s.gmt = gmt.state == .on s.sequence = sequence.state == .on s.copyFrom = copyFrom.state == .on ? DateSource(rawValue: copySource.indexOfSelectedItem) : nil s.copyTo = Set(copyTo.filter { $0.value.state == .on }.map(\.key)) copySource.isEnabled = copyFrom.state == .on copyTo.values.forEach { $0.isEnabled = copyFrom.state == .on } s.hidden = TriState(rawValue: hidden.indexOfSelectedItem) ?? .unchanged s.locked = TriState(rawValue: locked.indexOfSelectedItem) ?? .unchanged return s } @objc private func changed() { recompute() } func controlTextDidChange(_ obj: Notification) { recompute() } private func recompute() { let s = settings for i in rows.indices { rows[i].new = DateChanger.newDates(rows[i].old, index: i, settings: s) } table.reloadData() let changing = rows.filter { $0.new != $0.old }.count status.stringValue = s.changesDates ? "\(changing) di \(rows.count) file cambiano data (in blu le date nuove)." : "\(rows.count) file." } private func loadExif() { let urls = rows.map(\.url) DispatchQueue.global(qos: .userInitiated).async { [weak self] in let dates = urls.map { MultiRenameWindow.captureDate($0) } DispatchQueue.main.async { guard let self else { return } for (i, d) in dates.enumerated() where self.rows.indices.contains(i) { self.rows[i].old.exif = d } self.exifLoaded = true self.recompute() } } } // MARK: - Esegui private func execute() { let s = settings var done = 0, errors: [String] = [] for i in rows.indices { let r = rows[i] guard r.new != r.old || s.hidden != .unchanged || s.locked != .unchanged else { continue } do { try DateChanger.apply(r.url, from: r.old, to: r.new, hidden: s.hidden, locked: s.locked) done += 1 } catch { errors.append("\(r.url.lastPathComponent): \(error.localizedDescription)") } let exif = rows[i].old.exif rows[i].old = FileDates.read(r.url) rows[i].old.exif = exif } // Dopo l'esecuzione si riparte da zero: un secondo "Esegui" non sposta ancora le ore. for c in controls.values { c.setDate.state = .off; c.setTime.state = .off; c.add.state = .off } copyFrom.state = .off hidden.selectItem(at: 0) locked.selectItem(at: 0) recompute() status.stringValue = "\(done) file modificati." + (errors.isEmpty ? "" : " \(errors.count) errori.") if !errors.isEmpty { Dialogs.message("Alcuni file non sono stati modificati", info: errors.prefix(6).joined(separator: "\n"), style: .warning) } } // MARK: - Tabella func numberOfRows(in tableView: NSTableView) -> Int { rows.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { guard let id = tableColumn?.identifier.rawValue else { return nil } let tf = (tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(id), owner: self) as? NSTextField) ?? { let t = NSTextField(labelWithString: "") t.identifier = NSUserInterfaceItemIdentifier(id) t.lineBreakMode = .byTruncatingMiddle t.font = id == "name" || id == "path" ? NSFont.systemFont(ofSize: 12) : NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .regular) return t }() let r = rows[row] tf.textColor = .labelColor func show(_ kind: FileDateKind) { let n = r.new[kind], o = r.old[kind] tf.stringValue = n.map { Self.longDate.string(from: $0) } ?? "" if n != o { tf.textColor = .systemBlue } tf.toolTip = n != o ? "Ora: \(o.map { Self.longDate.string(from: $0) } ?? "")" : nil } switch id { case "name": tf.stringValue = r.url.lastPathComponent case "path": tf.stringValue = Format.path(r.url.deletingLastPathComponent()) case "modified": show(.modified) case "created": show(.created) case "accessed": show(.accessed) case "exif": // Arancione se lo scatto non coincide con la data di modifica: è il caso da sistemare. if let e = r.old.exif { tf.stringValue = Self.longDate.string(from: e) if let m = r.new.modified, abs(m.timeIntervalSince(e)) >= 1 { tf.textColor = .systemOrange } tf.toolTip = "Data di scatto della foto o di registrazione del video" } else { tf.stringValue = exifLoaded ? "—" : "…" tf.textColor = .secondaryLabelColor tf.toolTip = exifLoaded ? "Il file non ha una data di scatto" : "Sto leggendo le date di scatto" } default: guard let m = r.new.modified, let c = r.new.created else { tf.stringValue = ""; break } let diff = m.timeIntervalSince(c) let a = Int(abs(diff)) tf.stringValue = diff == 0 ? "0" : String(format: "%@ %d:%02d:%02d", diff < 0 ? "-" : "+", a / 3600, (a / 60) % 60, a % 60) tf.textColor = abs(diff) >= 1 ? .systemOrange : .labelColor } return tf } }