import AppKit import CommanderCore /// Option+F5 come in TC: comprime i file selezionati in un archivio, di solito nell'altro pannello. final class PackDialog: ModalPanel { struct Options { var archive: URL var format: ArchiveFormat var deleteSources: Bool var separate: Bool } private let target = NSComboBox() private let format = NSPopUpButton() private let move = NSButton(checkboxWithTitle: "Sposta nell'archivio (cancella gli originali)", target: nil, action: nil) private let separate = NSButton(checkboxWithTitle: "Crea archivi separati, uno per ogni file/cartella", target: nil, action: nil) private static let formatKey = "comprimi.formato", recentKey = "comprimi.destinazioni" static func run(items: [FileItem], targetDir: URL, currentDir: URL) -> Options? { PackDialog(items: items, targetDir: targetDir, currentDir: currentDir).show() } private init(items: [FileItem], targetDir: URL, currentDir: URL) { super.init(width: 620) panel.title = "Comprimi" let title = NSTextField(labelWithString: "Comprimi \(items.count == 1 ? "\"\(items[0].name)\"" : "\(items.count) file/cartelle") nell'archivio:") for f in ArchiveFormat.allCases { format.addItem(withTitle: f.title) } let saved = ArchiveFormat(rawValue: UserDefaults.standard.string(forKey: Self.formatKey) ?? "") ?? .zip format.selectItem(at: ArchiveFormat.allCases.firstIndex(of: saved) ?? 0) format.target = self format.action = #selector(formatChanged) // Il nome come in TC: quello dell'elemento, o della cartella se sono tanti. let name = items.count == 1 ? (items[0].showsAsFolder ? items[0].name : items[0].baseName) : currentDir.lastPathComponent target.stringValue = Format.path(targetDir.appendingPathComponent(name + "." + saved.rawValue)) target.font = Theme.font target.completes = false target.addItems(withObjectValues: UserDefaults.standard.stringArray(forKey: Self.recentKey) ?? []) target.setContentCompressionResistancePriority(.init(1), for: .horizontal) separate.isEnabled = items.count > 1 separate.target = self separate.action = #selector(formatChanged) let formatRow = NSStackView(views: [NSTextField(labelWithString: "Formato:"), format]) let ok = button("OK", key: "\r") { [weak self] in self?.finish(.OK) } let cancel = button("Annulla", key: "\u{1b}") { [weak self] in self?.finish(.cancel) } let buttons = NSStackView(views: [ok, cancel]) buttons.distribution = .fillEqually panel.contentView = column([title, target, formatRow, move, separate, buttons], width: 640) panel.initialFirstResponder = target } private var selectedFormat: ArchiveFormat { ArchiveFormat.allCases[max(format.indexOfSelectedItem, 0)] } /// Cambiando formato cambia l'estensione del nome. @objc private func formatChanged() { var t = target.stringValue for f in ArchiveFormat.allCases.sorted(by: { $0.rawValue.count > $1.rawValue.count }) where t.lowercased().hasSuffix("." + f.rawValue) { t = String(t.dropLast(f.rawValue.count + 1)) break } target.stringValue = t + "." + selectedFormat.rawValue } private func show() -> Options? { let r = runModal { [weak self] e in guard let self, e.keyCode == KeyCode.returnKey || e.keyCode == KeyCode.keypadEnter else { return false } self.finish(.OK) return true } guard r == .OK else { return nil } let text = target.stringValue.trimmingCharacters(in: .whitespaces) guard !text.isEmpty else { return nil } var recent = UserDefaults.standard.stringArray(forKey: Self.recentKey) ?? [] recent.removeAll { $0 == text } recent.insert(text, at: 0) UserDefaults.standard.set(Array(recent.prefix(20)), forKey: Self.recentKey) UserDefaults.standard.set(selectedFormat.rawValue, forKey: Self.formatKey) let url = URL(fileURLWithPath: (text as NSString).expandingTildeInPath) return Options(archive: url, format: ArchiveFormat.from(url) ?? selectedFormat, deleteSources: move.state == .on, separate: separate.isEnabled && separate.state == .on) } } /// Option+F9 (o Option+F6) come in TC: estrae l'archivio sotto il cursore, o quelli selezionati. final class UnpackDialog: ModalPanel { struct Options { var destination: URL var mask: String var withPaths: Bool var subfolders: Bool var overwrite: Bool } private let target = NSComboBox() private let mask = NSComboBox() private let paths = NSButton(checkboxWithTitle: "Con i percorsi salvati nell'archivio", target: nil, action: nil) private let subfolders = NSButton(checkboxWithTitle: "Ogni archivio in una cartella con il suo nome", target: nil, action: nil) private let overwrite = NSButton(checkboxWithTitle: "Sovrascrivi i file esistenti senza chiedere", target: nil, action: nil) static func run(archives: [URL], targetDir: URL) -> Options? { UnpackDialog(archives: archives, targetDir: targetDir).show() } private init(archives: [URL], targetDir: URL) { super.init(width: 620) panel.title = "Estrai" let what = archives.count == 1 ? "\"\(archives[0].lastPathComponent)\"" : "\(archives.count) archivi" target.stringValue = Format.path(targetDir) target.font = Theme.font target.completes = false target.addItems(withObjectValues: UserDefaults.standard.stringArray(forKey: "estrai.destinazioni") ?? []) target.setContentCompressionResistancePriority(.init(1), for: .horizontal) mask.stringValue = "*.*" mask.font = Theme.font mask.completes = false mask.addItems(withObjectValues: UserDefaults.standard.stringArray(forKey: "copia.maschere") ?? []) paths.state = .on subfolders.state = UserDefaults.standard.bool(forKey: "estrai.cartelle") ? .on : .off let ok = button("OK", key: "\r") { [weak self] in self?.finish(.OK) } let cancel = button("Annulla", key: "\u{1b}") { [weak self] in self?.finish(.cancel) } let buttons = NSStackView(views: [ok, cancel]) buttons.distribution = .fillEqually panel.contentView = column([NSTextField(labelWithString: "Estrai i file da \(what) in:"), target, NSTextField(labelWithString: "Solo i file di questo tipo:"), mask, paths, subfolders, overwrite, buttons], width: 640) panel.initialFirstResponder = target } private func show() -> Options? { let r = runModal { [weak self] e in guard let self, e.keyCode == KeyCode.returnKey || e.keyCode == KeyCode.keypadEnter else { return false } self.finish(.OK) return true } guard r == .OK else { return nil } let text = target.stringValue.trimmingCharacters(in: .whitespaces) guard !text.isEmpty else { return nil } var recent = UserDefaults.standard.stringArray(forKey: "estrai.destinazioni") ?? [] recent.removeAll { $0 == text } recent.insert(text, at: 0) UserDefaults.standard.set(Array(recent.prefix(20)), forKey: "estrai.destinazioni") UserDefaults.standard.set(subfolders.state == .on, forKey: "estrai.cartelle") return Options(destination: URL(fileURLWithPath: (text as NSString).expandingTildeInPath, isDirectory: true), mask: mask.stringValue, withPaths: paths.state == .on, subfolders: subfolders.state == .on, overwrite: overwrite.state == .on) } } extension Dialogs { /// Password di un archivio protetto. Si può chiamare da qualsiasi thread. static func archivePassword(_ archive: URL) -> String? { let ask: () -> String? = { bringForward() let a = NSAlert() a.messageText = "\"\(archive.lastPathComponent)\" è protetto da password" a.informativeText = "Scrivi la password per aprirlo." a.addButton(withTitle: "OK") let c = a.addButton(withTitle: "Annulla") c.keyEquivalent = "\u{1b}" let tf = NSSecureTextField(frame: NSRect(x: 0, y: 0, width: 320, height: 24)) a.accessoryView = tf a.layout() a.window.initialFirstResponder = tf let previous = modalKeyHandler modalKeyHandler = nil defer { modalKeyHandler = previous } return a.runCentered() == .alertFirstButtonReturn ? tf.stringValue : nil } return Thread.isMainThread ? ask() : DispatchQueue.main.sync(execute: ask) } }