import AppKit import AVFoundation import CommanderCore import ImageIO /// Ctrl+M: lo "Strumento multi rinomina" di TC, con la stessa disposizione. final class MultiRenameWindow: NSObject, NSWindowDelegate, NSComboBoxDelegate, NSTextFieldDelegate, NSTableViewDataSource, NSTableViewDelegate { private struct Row { var source: RenameSource let original: URL // percorso vero sul disco var newName: String = "" var error: String? } private let window: NSWindow private var rows: [Row] = [] private var settings = MultiRenameSettings() private let openedAt = Date() private var changedAt = Date() private var lastResult: [RenameOperation] = [] // Maschere private let nameMask = NSComboBox() private let extMask = NSComboBox() private weak var lastMaskField: NSComboBox? // Cerca e sostituisci private let find = NSComboBox() private let replace = NSComboBox() private let caseSensitive = NSButton(checkboxWithTitle: "^", target: nil, action: nil) private let firstOnly = NSButton(checkboxWithTitle: "1x", target: nil, action: nil) private let inExt = NSButton(checkboxWithTitle: "[E]", target: nil, action: nil) private let regex = NSButton(checkboxWithTitle: "RegEx", target: nil, action: nil) private let substitute = NSButton(checkboxWithTitle: "Sostituisci", target: nil, action: nil) private let casePopup = NSPopUpButton() // Contatore private let counterStart = NSTextField(string: "1") private let counterStep = NSTextField(string: "1") private let counterDigits = NSPopUpButton() private let presets = NSPopUpButton(frame: .zero, pullsDown: true) // Elenco e fondo private let table = NSTableView() private let status = NSTextField(labelWithString: "Seleziona 'Inizia!' per effettuare la rinomina!") private var undoButton: NSButton! private var resultsButton: NSButton! private static let undoFile = HotlistStore.defaultURL.deletingLastPathComponent().appendingPathComponent("ultima-rinomina.json") private static let masksKey = "mrt.maschere", findKey = "mrt.trova", replaceKey = "mrt.sostituisci", presetsKey = "mrt.impostazioni" /// Apre la finestra sui file indicati e aspetta che venga chiusa. static func run(items: [FileItem]) { let w = MultiRenameWindow(items: items) w.show() } private init(items: [FileItem]) { window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1300, height: 760), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false) window.title = "Strumento multi rinomina" // Swift tiene già il riferimento: senza questo, chiudere la finestra la rilascia due volte (crash). window.isReleasedWhenClosed = false window.minSize = NSSize(width: 1000, height: 400) super.init() window.delegate = self rows = items.map { Row(source: RenameSource(url: $0.url, isDirectory: $0.showsAsFolder, size: $0.size, modified: $0.modified), original: $0.url) } build() loadExifIfNeeded() recompute() } private func show() { _ = window.setFrameUsingName("MultiRinomina") window.centerInApp() window.setFrameAutosaveName("MultiRinomina") let previous = Dialogs.modalKeyHandler Dialogs.modalKeyHandler = { [weak self] e in self?.handleKey(e) ?? false } defer { Dialogs.modalKeyHandler = previous } window.makeKeyAndOrderFront(nil) window.makeFirstResponder(nameMask) NSApp.runModal(for: window) window.orderOut(nil) } func windowWillClose(_ notification: Notification) { NSApp.stopModal() } private func close() { window.close() } // MARK: - Costruzione private func group(_ title: String, _ content: NSView) -> NSView { let label = NSTextField(labelWithString: title) label.font = NSFont.systemFont(ofSize: 12) let s = NSStackView(views: [label, content]) s.orientation = .vertical s.alignment = .leading s.spacing = 4 content.widthAnchor.constraint(equalTo: s.widthAnchor).isActive = true return s } private func insertButton(_ title: String, insert: String, into field: @escaping () -> NSComboBox) -> NSButton { ActionButton(title) { [weak self] in self?.insert(insert, into: field()) }.styled() } private func build() { // Maschera nome for c in [nameMask, extMask, find, replace] { c.delegate = self c.completes = false c.numberOfVisibleItems = 20 c.font = NSFont.systemFont(ofSize: 13) } nameMask.stringValue = "[N]" extMask.stringValue = "[E]" nameMask.addItems(withObjectValues: UserDefaults.standard.stringArray(forKey: Self.masksKey) ?? []) find.addItems(withObjectValues: UserDefaults.standard.stringArray(forKey: Self.findKey) ?? []) replace.addItems(withObjectValues: UserDefaults.standard.stringArray(forKey: Self.replaceKey) ?? []) lastMaskField = nameMask let name = { [unowned self] in self.nameMask } let ext = { [unowned self] in self.extMask } let plusMenu = ActionButton("±") { [weak self] in self?.showPlaceholderMenu(extra: true) }.styled() let hashMenu = ActionButton("#") { [weak self] in self?.showPlaceholderMenu(extra: false) }.styled() plusMenu.toolTip = "Altri segnaposto: cartella, dimensione, data EXIF, maiuscole…" hashMenu.toolTip = "Parti del nome e contatori speciali" let nameGrid = NSGridView(views: [ [insertButton("[N] Nome", insert: "[N]", into: name), plusMenu, insertButton("[YMD] Data", insert: "[YMD]", into: name)], [ActionButton("[N#-#] Intervallo") { [weak self] in self?.chooseRange(ext: false) }.styled(), hashMenu, insertButton("[hms] Ora", insert: "[hms]", into: name)], [insertButton("[C] Contatore", insert: "[C]", into: name), NSGridCell.emptyContentView, ActionButton("[=?] Plugin") { [weak self] in self?.showPluginMenu() }.styled()], ]) nameGrid.rowSpacing = 4 nameGrid.columnSpacing = 4 nameGrid.column(at: 1).width = 26 let nameBox = NSStackView(views: [nameMask, nameGrid]) nameBox.orientation = .vertical nameBox.alignment = .leading nameMask.widthAnchor.constraint(equalTo: nameBox.widthAnchor).isActive = true nameGrid.widthAnchor.constraint(equalTo: nameBox.widthAnchor).isActive = true // Estensione let extButtons = NSStackView(views: [ insertButton("[E] Est.", insert: "[E]", into: ext), ActionButton("[E#-#] Intervallo") { [weak self] in self?.chooseRange(ext: true) }.styled(), insertButton("[C] Contatore", insert: "[C]", into: ext), ]) extButtons.orientation = .vertical extButtons.alignment = .leading extButtons.spacing = 4 let extBox = NSStackView(views: [extMask, extButtons]) extBox.orientation = .vertical extBox.alignment = .leading extMask.widthAnchor.constraint(equalTo: extBox.widthAnchor).isActive = true for b in extButtons.arrangedSubviews { b.widthAnchor.constraint(equalTo: extBox.widthAnchor).isActive = true } // Trova & sostituisci inExt.state = .on for b in [caseSensitive, firstOnly, inExt, regex, substitute] { b.target = self b.action = #selector(optionsChanged) } caseSensitive.toolTip = "Rispetta maiuscole/minuscole" firstOnly.toolTip = "Solo la prima occorrenza" inExt.toolTip = "Cerca anche nell'estensione" substitute.toolTip = "Con RegEx: il nome intero diventa il testo di \"Sostituisci con\"" substitute.isEnabled = false for c in RenameCase.allCases { casePopup.addItem(withTitle: c.title) } casePopup.target = self casePopup.action = #selector(optionsChanged) let help = ActionButton("?") { [weak self] in self?.showHelp() }.styled() let findGrid = NSGridView(views: [ [NSTextField(labelWithString: "Trova:"), find], [NSTextField(labelWithString: "Sostituisci con:"), replace], ]) findGrid.rowSpacing = 4 let checks = NSStackView(views: [caseSensitive, firstOnly, inExt, regex, substitute]) checks.spacing = 10 let caseRow = NSStackView(views: [casePopup, help]) let findBox = NSStackView(views: [findGrid, checks, NSTextField(labelWithString: "Maiuscolo/minuscolo"), caseRow]) findBox.orientation = .vertical findBox.alignment = .leading findBox.spacing = 4 findGrid.widthAnchor.constraint(equalTo: findBox.widthAnchor).isActive = true caseRow.widthAnchor.constraint(equalTo: findBox.widthAnchor).isActive = true // Contatore for f in [counterStart, counterStep] { f.delegate = self f.widthAnchor.constraint(equalToConstant: 70).isActive = true } counterDigits.addItem(withTitle: "a") for i in 1...10 { counterDigits.addItem(withTitle: "\(i)") } counterDigits.selectItem(at: 1) counterDigits.target = self counterDigits.action = #selector(optionsChanged) presets.addItem(withTitle: "Carica/salva impostazioni") rebuildPresets() let counterGrid = NSGridView(views: [ [NSTextField(labelWithString: "Inizia a:"), counterStart], [NSTextField(labelWithString: "Incremento:"), counterStep], [NSTextField(labelWithString: "Cifre:"), counterDigits], ]) counterGrid.rowSpacing = 6 let counterBox = NSStackView(views: [counterGrid, presets]) counterBox.orientation = .vertical counterBox.alignment = .leading counterBox.spacing = 6 let top = NSStackView(views: [ group("Maschera rinomina: nome file", nameBox), group("Estensione", extBox), group("Trova & sostituisci", findBox), group("Definisci contatore [C]", counterBox), ]) top.orientation = .horizontal top.alignment = .top top.spacing = 14 top.arrangedSubviews[0].widthAnchor.constraint(equalTo: top.widthAnchor, multiplier: 0.33).isActive = true top.arrangedSubviews[1].widthAnchor.constraint(equalTo: top.widthAnchor, multiplier: 0.16).isActive = true top.arrangedSubviews[3].widthAnchor.constraint(equalToConstant: 200).isActive = true // Elenco for (id, title, width) in [("old", "Vecchio nome", 360.0), ("ext", "Estensione", 90.0), ("new", "Nuovo nome", 420.0), ("size", "Dimensioni", 110.0), ("date", "Data", 150.0)] { let c = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(id)) c.title = title c.width = width c.sortDescriptorPrototype = NSSortDescriptor(key: id, ascending: true) table.addTableColumn(c) } table.dataSource = self table.delegate = self table.rowHeight = 18 table.usesAlternatingRowBackgroundColors = true table.allowsMultipleSelection = true table.columnAutoresizingStyle = .lastColumnOnlyAutoresizingStyle let scroll = NSScrollView() scroll.documentView = table scroll.hasVerticalScroller = true scroll.borderType = .bezelBorder // Fondo let next = ActionButton("↻") { [weak self] in self?.nextStep() }.styled() next.toolTip = "Passo successivo: applica un'altra regola agli stessi file (F5)" let start = ActionButton("Inizia!") { [weak self] in self?.start() }.styled() start.keyEquivalent = "\r" undoButton = ActionButton("Annulla") { [weak self] in self?.undo() }.styled() undoButton.isEnabled = FileManager.default.fileExists(atPath: Self.undoFile.path) resultsButton = ActionButton("Elenco risultati") { [weak self] in self?.showResults() }.styled() resultsButton.isEnabled = false let closeButton = ActionButton("Chiudi") { [weak self] in self?.close() }.styled() closeButton.keyEquivalent = "\u{1b}" status.lineBreakMode = .byTruncatingTail status.setContentCompressionResistancePriority(.init(1), for: .horizontal) let bottom = NSStackView(views: [status, next, start, undoButton, resultsButton, closeButton]) bottom.spacing = 8 for b in [start, undoButton!, resultsButton!, closeButton] { b.widthAnchor.constraint(greaterThanOrEqualToConstant: 110).isActive = true } let root = NSStackView(views: [top, scroll, bottom]) root.orientation = .vertical root.alignment = .leading root.spacing = 10 root.edgeInsets = NSEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) for v in [top, scroll, bottom] { v.widthAnchor.constraint(equalTo: root.widthAnchor, constant: -20).isActive = true } scroll.setContentHuggingPriority(.init(1), for: .vertical) window.contentView = root } // MARK: - Anteprima private func readSettings() { settings.nameMask = nameMask.stringValue settings.extMask = extMask.stringValue settings.search = find.stringValue settings.replace = replace.stringValue settings.caseSensitive = caseSensitive.state == .on settings.firstOnly = firstOnly.state == .on settings.includeExtension = inExt.state == .on settings.regex = regex.state == .on settings.substitute = substitute.state == .on settings.caseMode = RenameCase(rawValue: casePopup.indexOfSelectedItem) ?? .unchanged settings.counterStart = Int(counterStart.stringValue) ?? 1 settings.counterStep = Int(counterStep.stringValue) ?? 1 settings.counterDigits = counterDigits.indexOfSelectedItem // 0 = "a" substitute.isEnabled = regex.state == .on } private func writeSettings() { nameMask.stringValue = settings.nameMask extMask.stringValue = settings.extMask find.stringValue = settings.search replace.stringValue = settings.replace caseSensitive.state = settings.caseSensitive ? .on : .off firstOnly.state = settings.firstOnly ? .on : .off inExt.state = settings.includeExtension ? .on : .off regex.state = settings.regex ? .on : .off substitute.state = settings.substitute ? .on : .off casePopup.selectItem(at: settings.caseMode.rawValue) counterStart.stringValue = "\(settings.counterStart)" counterStep.stringValue = "\(settings.counterStep)" counterDigits.selectItem(at: min(settings.counterDigits, 10)) } private func recompute() { readSettings() changedAt = Date() let ctx = MultiRenameContext(total: rows.count, openedAt: openedAt, changedAt: changedAt, clipboard: NSPasteboard.general.string(forType: .string)) for i in rows.indices { switch MultiRename.newName(for: rows[i].source, index: i, settings: settings, context: ctx) { case .success(let n): rows[i].newName = n rows[i].error = n.contains(":") ? "Il carattere \":\" non è ammesso" : nil case .failure(let e): rows[i].newName = "" rows[i].error = e.description } } table.reloadData() if let e = rows.first(where: { $0.error != nil })?.error { status.stringValue = e status.textColor = .systemRed } else { status.stringValue = "Seleziona 'Inizia!' per effettuare la rinomina!" status.textColor = .labelColor } } func controlTextDidChange(_ obj: Notification) { if let c = obj.object as? NSComboBox, c === nameMask || c === extMask { lastMaskField = c } recompute() } func controlTextDidBeginEditing(_ obj: Notification) { if let c = obj.object as? NSComboBox, c === nameMask || c === extMask { lastMaskField = c } } func comboBoxSelectionDidChange(_ notification: Notification) { DispatchQueue.main.async { self.recompute() } } @objc private func optionsChanged() { recompute() } private func insert(_ text: String, into field: NSComboBox) { window.makeFirstResponder(field) if let ed = field.currentEditor() { ed.insertText(text) } else { field.stringValue += text } lastMaskField = field recompute() } // MARK: - Segnaposto private func showPlaceholderMenu(extra: Bool) { let items: [(String, String)] = extra ? [ ("[A] Nome completo con estensione", "[A]"), ("[P] Cartella che contiene il file", "[P]"), ("[G] Cartella sopra ancora", "[G]"), ("[S] Dimensione in byte", "[S]"), ("[d] Data (gg-mm-aaaa)", "[d]"), ("[t] Ora (hh.mm.ss)", "[t]"), ("[Y] Anno [M] Mese [D] Giorno", "[Y]-[M]-[D]"), ("[h] Ore [m] Minuti [s] Secondi", "[h].[m].[s]"), ("[T4] Usa la data di scatto (EXIF) / del video", "[T4]"), ("[T2] Usa la data e ora di adesso", "[T2]"), ("[U] Da qui tutto maiuscolo", "[U]"), ("[L] Da qui tutto minuscolo", "[L]"), ("[F] Da qui iniziali maiuscole", "[F]"), ("[n] Da qui come l'originale", "[n]"), ("[X] Testo negli appunti", "[X]"), ] : [ ("[N1-3] I primi 3 caratteri", "[N1-3]"), ("[N-3-] Gli ultimi 3 caratteri", "[N-3-]"), ("[N2-] Dal secondo carattere in poi", "[N2-]"), ("[N2--2] Senza il primo e l'ultimo carattere", "[N2--2]"), ("[C:a] Contatore con cifre automatiche", "[C:a]"), ("[C+1/10] Contatore che cresce ogni 10 file", "[C+1/10]"), ("[c] Numero di file", "[c]"), ("[[] Parentesi quadra aperta", "[[]"), ("[]] Parentesi quadra chiusa", "[]]"), ] let menu = NSMenu() for (title, text) in items { menu.addItem(ActionMenuItem(title) { [weak self] in guard let self else { return } self.insert(text, into: self.lastMaskField ?? self.nameMask) }) } menu.popUp(positioning: nil, at: NSEvent.mouseLocation, in: nil) } private func showPluginMenu() { let menu = NSMenu() menu.addItem(ActionMenuItem("Data di scatto della foto/video: [T4][YMD] [hms]") { [weak self] in guard let self else { return } self.insert("[T4][YMD] [hms]", into: self.nameMask) self.loadExifIfNeeded() }) menu.addItem(ActionMenuItem("Data di scatto con trattini: [T4][Y]-[M]-[D] [hms]") { [weak self] in guard let self else { return } self.insert("[T4][Y]-[M]-[D] [hms]", into: self.nameMask) self.loadExifIfNeeded() }) menu.popUp(positioning: nil, at: NSEvent.mouseLocation, in: nil) } /// [N#-#] / [E#-#]: si selezionano le lettere sul nome del primo file. private func chooseRange(ext: Bool) { guard let first = rows.first else { return } let full = first.source.name let dot = full.lastIndex(of: ".") let text = ext ? (dot.map { String(full[full.index(after: $0)...]) } ?? "") : (dot.map { String(full[..<$0]) } ?? full) let a = NSAlert() a.messageText = ext ? "Seleziona le lettere dell'estensione" : "Seleziona le lettere del nome" a.informativeText = "Trascina il mouse (o Shift+frecce) sulla parte da tenere." // Un NSTextView tiene la selezione anche dopo la chiusura della finestra. let tf = NSTextView(frame: NSRect(x: 0, y: 0, width: 520, height: 24)) tf.string = text tf.isEditable = false tf.isSelectable = true tf.font = NSFont.monospacedSystemFont(ofSize: 14, weight: .regular) a.accessoryView = tf a.addButton(withTitle: "OK") a.addButton(withTitle: "Annulla").keyEquivalent = "\u{1b}" a.window.initialFirstResponder = tf let previous = Dialogs.modalKeyHandler Dialogs.modalKeyHandler = nil defer { Dialogs.modalKeyHandler = previous } guard a.runCentered() == .alertFirstButtonReturn else { return } let r = tf.selectedRange() guard r.length > 0 else { return } let ns = text as NSString let startChars = (ns.substring(to: r.location) as String).count + 1 let len = (ns.substring(with: r) as String).count let token = "[\(ext ? "E" : "N")\(startChars)-\(startChars + len - 1)]" insert(token, into: ext ? extMask : nameMask) } private func showHelp() { let text = """ Segnaposto (maiuscole e minuscole contano): [N] nome senza estensione [N1] primo carattere [N2-5] caratteri 2-5 [N2,5] 5 caratteri dal 2° [N2-] dal 2° alla fine [N-5-] dal 5° dalla fine [N02-9] riempie con zeri [E] estensione [A] nome completo [P] cartella superiore [G] quella sopra [B0]..[B9] cartelle dal fondo [B+1] dall'inizio [C] contatore [C10+5:3] parte da 10, passo 5, 3 cifre [C:a] cifre automatiche [C+1/100] cresce ogni 100 file [Y] anno [y] anno a 2 cifre [M] mese [D] giorno [h] ore [m] minuti [s] secondi [YMD] [hms] [d] data [t] ora [T1] data del file (normale) [T2] adesso [T4] data EXIF/video (salta i file senza) [U] maiuscolo [L] minuscolo [F] iniziali maiuscole [n] come l'originale [S] dimensione [X] appunti [[] e []] parentesi quadre. Con "/" nel nome il file si sposta in una sottocartella. Trova & sostituisci: * e ? come jolly, più ricerche separate da | (es. à|è → a|e). ^ = rispetta maiuscole, 1x = solo la prima, [E] = anche nell'estensione, RegEx con $1 $2. Tasti: Invio = Inizia!, Esc = Chiudi, F5 = passo successivo, F2 = carica/salva impostazioni, Shift+↑/↓ = sposta il file nell'elenco (per il contatore), Canc = toglie il file dall'elenco. """ let a = NSAlert() a.messageText = "Rinomina multipla: aiuto" a.informativeText = text a.runCentered() } // MARK: - Data EXIF private func loadExifIfNeeded() { let need = (nameMask.stringValue + extMask.stringValue).contains("[T4") guard need, rows.contains(where: { $0.source.exifDate == nil }) else { return } let urls = rows.map(\.original) DispatchQueue.global(qos: .userInitiated).async { [weak self] in let dates = urls.map(Self.captureDate) DispatchQueue.main.async { guard let self else { return } for (i, d) in dates.enumerated() where self.rows.indices.contains(i) && self.rows[i].original == urls[i] { self.rows[i].source.exifDate = d } self.recompute() } } } static func captureDate(_ url: URL) -> Date? { if let src = CGImageSourceCreateWithURL(url as CFURL, nil), let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as? [CFString: Any], let exif = props[kCGImagePropertyExifDictionary] as? [CFString: Any], let s = exif[kCGImagePropertyExifDateTimeOriginal] as? String { let f = DateFormatter() f.dateFormat = "yyyy:MM:dd HH:mm:ss" return f.date(from: s) } // Video: data di registrazione. let sem = DispatchSemaphore(value: 0) var result: Date? Task.detached { let asset = AVURLAsset(url: url) if let item = try? await asset.load(.creationDate) { result = try? await item.load(.dateValue) } sem.signal() } sem.wait() return result } // MARK: - Azioni private func operations() -> [RenameOperation] { rows.map { r in RenameOperation(from: r.original, to: r.original.deletingLastPathComponent().appendingPathComponent(r.newName)) } } private func start() { recompute() if let e = rows.first(where: { $0.error != nil })?.error { Dialogs.message("La maschera ha un errore", info: e, style: .warning) return } var ops = operations().filter { $0.from.path != $0.to.path } guard !ops.isEmpty else { NSSound.beep(); return } let clashes = RenameExecutor.conflicts(ops) if !clashes.isEmpty { let names = clashes.prefix(5).map { $0.to.lastPathComponent }.joined(separator: "\n") guard Dialogs.confirm("\(clashes.count) nomi esistono già o si ripetono", info: "\(names)\n\nLi rinomino in \"nome (2)\", \"nome (3)\"…?", ok: "Rinomina così") else { return } ops = RenameExecutor.autoResolve(ops) } let result = RenameExecutor.execute(ops) lastResult = result.done saveUndo(result.done) rememberHistory() // L'elenco ora mostra i nomi nuovi: un secondo "Inizia!" non fa nulla. for op in result.done { if let i = rows.firstIndex(where: { $0.original == op.from }) { rows[i] = Row(source: RenameSource(url: op.to, isDirectory: rows[i].source.isDirectory, size: rows[i].source.size, modified: rows[i].source.modified, exifDate: rows[i].source.exifDate), original: op.to) } } undoButton.isEnabled = !result.done.isEmpty resultsButton.isEnabled = !result.done.isEmpty settings = MultiRenameSettings() writeSettings() recompute() if result.errors.isEmpty { status.stringValue = "\(result.done.count) file rinominati." } else { let list = result.errors.prefix(5).map { "\($0.0.from.lastPathComponent): \($0.1)" }.joined(separator: "\n") Dialogs.message("\(result.errors.count) file non rinominati", info: list, style: .warning) status.stringValue = "\(result.done.count) file rinominati, \(result.errors.count) errori." } } /// "Annulla": rimette i nomi di prima, anche dopo aver chiuso e riaperto la finestra. private func undo() { guard let data = try? Data(contentsOf: Self.undoFile), let ops = try? JSONDecoder().decode([RenameOperation].self, from: data), !ops.isEmpty else { return } guard Dialogs.confirm("Annullare l'ultima rinomina?", info: "\(ops.count) file tornano al nome di prima.", ok: "Annulla rinomina") else { return } let back = ops.reversed().map { RenameOperation(from: $0.to, to: $0.from) } let result = RenameExecutor.execute(back) for op in result.done { if let i = rows.firstIndex(where: { $0.original == op.from }) { rows[i] = Row(source: RenameSource(url: op.to, isDirectory: rows[i].source.isDirectory, size: rows[i].source.size, modified: rows[i].source.modified), original: op.to) } } try? FileManager.default.removeItem(at: Self.undoFile) undoButton.isEnabled = false recompute() status.stringValue = result.errors.isEmpty ? "Rinomina annullata." : "Annullata in parte: \(result.errors.count) errori." } private func saveUndo(_ ops: [RenameOperation]) { guard !ops.isEmpty, let data = try? JSONEncoder().encode(ops) else { return } try? FileManager.default.createDirectory(at: Self.undoFile.deletingLastPathComponent(), withIntermediateDirectories: true) try? data.write(to: Self.undoFile) } private func showResults() { let text = lastResult.map { "\($0.from.lastPathComponent) → \($0.to.lastPathComponent)" }.joined(separator: "\n") let a = NSAlert() a.messageText = "Elenco risultati" let scroll = NSTextView.scrollableTextView() scroll.frame = NSRect(x: 0, y: 0, width: 700, height: 300) let tv = scroll.documentView as! NSTextView tv.string = text tv.isEditable = false tv.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular) a.accessoryView = scroll a.addButton(withTitle: "OK") a.addButton(withTitle: "Copia") if a.runCentered() == .alertSecondButtonReturn { NSPasteboard.general.clearContents() NSPasteboard.general.setString(text, forType: .string) } } /// F5 / ↻: i nuovi nomi diventano il punto di partenza per un'altra regola (i file non si toccano ancora). private func nextStep() { recompute() guard !rows.contains(where: { $0.error != nil }) else { NSSound.beep(); return } for i in rows.indices { rows[i].source.name = rows[i].newName } rememberHistory() settings = MultiRenameSettings() writeSettings() recompute() status.stringValue = "Passo successivo: i nomi nuovi sono il punto di partenza." } private func rememberHistory() { func push(_ value: String, _ key: String, _ defaultValue: String) { guard !value.isEmpty, value != defaultValue else { return } var list = UserDefaults.standard.stringArray(forKey: key) ?? [] list.removeAll { $0 == value } list.insert(value, at: 0) UserDefaults.standard.set(Array(list.prefix(30)), forKey: key) } push(nameMask.stringValue, Self.masksKey, "[N]") push(find.stringValue, Self.findKey, "") push(replace.stringValue, Self.replaceKey, "") } // MARK: - Impostazioni salvate (F2) private var savedPresets: [String: MultiRenameSettings] { guard let data = UserDefaults.standard.data(forKey: Self.presetsKey), let d = try? JSONDecoder().decode([String: MultiRenameSettings].self, from: data) else { return [:] } return d } private func storePresets(_ p: [String: MultiRenameSettings]) { if let data = try? JSONEncoder().encode(p) { UserDefaults.standard.set(data, forKey: Self.presetsKey) } } private func rebuildPresets() { let menu = presets.menu! while menu.items.count > 1 { menu.removeItem(at: 1) } menu.addItem(ActionMenuItem("") { [weak self] in self?.settings = MultiRenameSettings() self?.writeSettings() self?.recompute() }) menu.addItem(ActionMenuItem("Salva impostazioni…") { [weak self] in self?.savePreset() }) let saved = savedPresets if !saved.isEmpty { let del = NSMenuItem(title: "Elimina voce", action: nil, keyEquivalent: "") let sub = NSMenu() for name in saved.keys.sorted() { sub.addItem(ActionMenuItem(name) { [weak self] in guard let self else { return } var p = self.savedPresets p[name] = nil self.storePresets(p) self.rebuildPresets() }) } del.submenu = sub menu.addItem(del) menu.addItem(.separator()) for name in saved.keys.sorted() { menu.addItem(ActionMenuItem(name) { [weak self] in guard let self, let s = self.savedPresets[name] else { return } self.settings = s self.writeSettings() self.recompute() self.loadExifIfNeeded() }) } } } private func savePreset() { recompute() guard case .ok(let name) = Dialogs.prompt("Nome per queste impostazioni:", value: ""), !name.isEmpty else { return } var p = savedPresets p[name] = settings storePresets(p) rebuildPresets() } // MARK: - Tasti private func handleKey(_ e: NSEvent) -> Bool { guard NSApp.keyWindow === window else { return false } let mods = e.modifierFlags.intersection([.control, .option, .command, .shift]) switch e.keyCode { case KeyCode.escape where mods.isEmpty: close() return true case KeyCode.returnKey, KeyCode.keypadEnter: guard mods.isEmpty, window.firstResponder !== table else { return false } start() return true case KeyCode.f5 where mods.isEmpty: nextStep() return true case KeyCode.f2 where mods.isEmpty: presets.performClick(nil) return true case KeyCode.up, KeyCode.down: guard mods == .shift, window.firstResponder === table else { return false } moveSelected(e.keyCode == KeyCode.up ? -1 : 1) return true case KeyCode.forwardDelete, KeyCode.backspace: guard window.firstResponder === table, mods.isEmpty else { return false } removeSelected() return true default: return false } } private func moveSelected(_ delta: Int) { let r = table.selectedRow let t = r + delta guard rows.indices.contains(r), rows.indices.contains(t) else { return } rows.swapAt(r, t) recompute() table.selectRowIndexes(IndexSet(integer: t), byExtendingSelection: false) table.scrollRowToVisible(t) } private func removeSelected() { let sel = table.selectedRowIndexes guard !sel.isEmpty else { return } rows = rows.enumerated().filter { !sel.contains($0.offset) }.map(\.element) recompute() } // 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 == "size" ? NSFont.monospacedDigitSystemFont(ofSize: 12, weight: .regular) : NSFont.systemFont(ofSize: 12) t.alignment = id == "size" ? .right : .left return t }() let r = rows[row] let name = r.source.name let dot = name.lastIndex(of: ".").flatMap { $0 == name.startIndex ? nil : $0 } switch id { case "old": tf.stringValue = r.source.isDirectory ? name : (dot.map { String(name[..<$0]) } ?? name) case "ext": tf.stringValue = r.source.isDirectory ? "" : (dot.map { String(name[name.index(after: $0)...]) } ?? "") case "new": tf.stringValue = r.newName tf.textColor = r.error != nil ? .systemRed : (r.newName != name ? .systemBlue : .labelColor) tf.toolTip = r.error return tf case "size": tf.stringValue = r.source.isDirectory ? "" : Format.bytes(r.source.size) default: let f = DateFormatter() f.dateFormat = "dd/MM/yyyy HH:mm:ss" tf.stringValue = r.source.modified.map { f.string(from: $0) } ?? "" } tf.textColor = .labelColor return tf } func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { guard let d = tableView.sortDescriptors.first, let key = d.key else { return } rows.sort { a, b in let r: Bool switch key { case "size": r = a.source.size < b.source.size case "date": r = (a.source.modified ?? .distantPast) < (b.source.modified ?? .distantPast) case "ext": r = (a.source.name as NSString).pathExtension.localizedStandardCompare((b.source.name as NSString).pathExtension) == .orderedAscending case "new": r = a.newName.localizedStandardCompare(b.newName) == .orderedAscending default: r = a.source.name.localizedStandardCompare(b.source.name) == .orderedAscending } return d.ascending ? r : !r } recompute() } } private extension NSButton { func styled() -> Self { bezelStyle = .push controlSize = .regular alignment = .left return self } }