import Foundation /// Una riga di un pannello. public struct FileItem: Hashable { public let url: URL public let name: String public let isDirectory: Bool public let isPackage: Bool public let isParent: Bool public let isHidden: Bool public let isSymlink: Bool public let size: Int64 public let modified: Date? /// Colore del tag del Finder (0 = nessuno, 1 grigio, 2 verde, 3 viola, 4 blu, 5 giallo, 6 rosso, 7 arancione). public let label: Int /// Simbolo o emoji scelti nel Finder per la cartella ("Personalizza cartella"). public let folderSymbol: FolderSymbol? public init(url: URL, name: String, isDirectory: Bool, isPackage: Bool = false, isParent: Bool = false, isHidden: Bool = false, isSymlink: Bool = false, size: Int64 = 0, modified: Date? = nil, label: Int = 0, folderSymbol: FolderSymbol? = nil) { self.url = url self.name = name self.isDirectory = isDirectory self.isPackage = isPackage self.isParent = isParent self.isHidden = isHidden self.isSymlink = isSymlink self.size = size self.modified = modified self.label = label self.folderSymbol = folderSymbol } /// Cartella in cui si entra con Invio (i pacchetti come .app si aprono, come nel Finder). public var showsAsFolder: Bool { isParent || (isDirectory && !isPackage) } public var ext: String { if showsAsFolder { return "" } let e = (name as NSString).pathExtension if e.isEmpty || e.count + 1 >= name.count { return "" } // ".bashrc" non ha estensione return e } public var baseName: String { let e = ext return e.isEmpty ? name : String(name.dropLast(e.count + 1)) } public static func parent(of dir: URL) -> FileItem? { let path = dir.isFileURL ? dir.standardizedFileURL.path : dir.path guard path != "/" else { return nil } return FileItem(url: dir.deletingLastPathComponent(), name: "..", isDirectory: true, isParent: true) } } /// Simbolo della cartella personalizzata dal Finder, salvato nell'attributo `com.apple.icon.folder#S`. public enum FolderSymbol: Hashable { case symbol(String) case emoji(String) static let attribute = "com.apple.icon.folder#S" /// `{"sym":"camera.fill"}` oppure `{"emoji":"🎸"}`. public static func parse(_ data: Data) -> FolderSymbol? { guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } if let s = obj["sym"] as? String, !s.isEmpty { return .symbol(s) } if let e = obj["emoji"] as? String, !e.isEmpty { return .emoji(e) } return nil } static func read(_ url: URL) -> FolderSymbol? { url.withUnsafeFileSystemRepresentation { path -> FolderSymbol? in guard let path else { return nil } let n = getxattr(path, attribute, nil, 0, 0, XATTR_NOFOLLOW) guard n > 0, n < 4096 else { return nil } var buf = [UInt8](repeating: 0, count: n) guard getxattr(path, attribute, &buf, n, 0, XATTR_NOFOLLOW) == n else { return nil } return parse(Data(buf)) } } } public enum SortKey: String, Codable { case name, ext, size, date } public struct FileSort: Codable, Equatable { public var key: SortKey public var ascending: Bool public init(key: SortKey = .name, ascending: Bool = true) { self.key = key self.ascending = ascending } } public enum DirectoryLister { static let keys: [URLResourceKey] = [.isDirectoryKey, .isPackageKey, .isHiddenKey, .isSymbolicLinkKey, .fileSizeKey, .contentModificationDateKey, .labelNumberKey] public static func list(_ dir: URL) throws -> [FileItem] { // Dentro un archivio (zip, rar, 7z…): si legge l'archivio come una cartella. if let a = ArchivePath.split(dir) { return try ArchiveReader.list(a.archive, inner: a.inner) } let fm = FileManager() // Una cartella che è un collegamento (es. ~/Google Drive): contentsOfDirectory(at:) non lo segue // ("Not a directory"). Si legge la cartella vera, ma i file restano sotto il percorso del collegamento. let real = dir.resolvingSymlinksInPath() let urls = try fm.contentsOfDirectory(at: real, includingPropertiesForKeys: keys, options: []) return urls.map { realURL in item(real: realURL, shownAs: real == dir ? realURL : dir.appendingPathComponent(realURL.lastPathComponent), fm: fm) } } /// Una riga per il file `real`, mostrata col percorso `u` (diverso se si passa da un collegamento). static func item(real realURL: URL, shownAs u: URL, fm: FileManager) -> FileItem { let v = try? realURL.resourceValues(forKeys: Set(keys)) var isDir = v?.isDirectory ?? false let isLink = v?.isSymbolicLink ?? false if isLink { var d: ObjCBool = false if fm.fileExists(atPath: u.path, isDirectory: &d) { isDir = d.boolValue } } let name = u.lastPathComponent return FileItem(url: u, name: name, isDirectory: isDir, isPackage: isDir && (v?.isPackage ?? false), isHidden: (v?.isHidden ?? false) || name.hasPrefix("."), isSymlink: isLink, size: Int64(v?.fileSize ?? 0), modified: v?.contentModificationDate, label: v?.labelNumber ?? 0, folderSymbol: isDir && !isLink ? FolderSymbol.read(u) : nil) } /// Rilegge un file già noto (per aggiornare l'elenco della ricerca). nil se non c'è più. public static func item(at url: URL) -> FileItem? { guard FileManager.default.fileExists(atPath: url.path) else { return nil } return item(real: url, shownAs: url, fm: FileManager()) } /// Ctrl+B come in TC: tutti i file della cartella e delle sottocartelle in un solo elenco /// (le cartelle no). I pacchetti (.app) contano come file. Con `roots` di più cartelle /// (Ctrl+Shift+B) si uniscono quelle selezionate. public static func listBranch(_ roots: [URL], includeHidden: Bool, isCancelled: () -> Bool = { false }) throws -> [FileItem] { var out: [FileItem] = [] let fm = FileManager() for root in roots { for (real, shown) in try walk(root, maxDepth: nil, includeHidden: includeHidden, fm: fm) { if isCancelled() { return out } let i = item(real: real, shownAs: shown, fm: fm) if !i.showsAsFolder { out.append(i) } } } return out } /// Tutto quello che c'è sotto `root`, senza entrare nei pacchetti né seguire i collegamenti. /// `maxDepth`: 0 = solo la cartella, 1 = anche le sottocartelle dirette, nil = tutte. /// Restituisce il percorso vero e quello da mostrare (sotto `root` anche se `root` è un collegamento). static func walk(_ root: URL, maxDepth: Int?, includeHidden: Bool, fm: FileManager) throws -> AnySequence<(URL, URL)> { let real = root.resolvingSymlinksInPath() // Senza permesso o cartella sparita: l'errore deve arrivare a chi ha chiesto, come per una cartella normale. _ = try fm.contentsOfDirectory(atPath: real.path) var opts: FileManager.DirectoryEnumerationOptions = [.skipsPackageDescendants] if !includeHidden { opts.insert(.skipsHiddenFiles) } guard let en = fm.enumerator(at: real, includingPropertiesForKeys: keys, options: opts, errorHandler: { _, _ in true }) else { return AnySequence([]) } return AnySequence(AnyIterator { while let u = en.nextObject() as? URL { let level = en.level if let maxDepth, level > maxDepth { en.skipDescendants() if level > maxDepth + 1 { continue } } // Il percorso relativo sono gli ultimi `level` pezzi (l'enumeratore può dare /var al posto di /private/var). let rel = u.pathComponents.suffix(level) let realURL = rel.reduce(real) { $0.appendingPathComponent($1) } let shown = rel.reduce(root) { $0.appendingPathComponent($1) } return (realURL, shown) } return nil }) } /// Cartelle prima, poi i file. ".." resta fuori: lo aggiunge il pannello. /// Le cartelle stanno sempre sopra i file. Per dimensione, le cartelle già calcolate /// (`folderSize`) si ordinano per dimensione, le altre per nome. public static func sorted(_ items: [FileItem], by order: FileSort, folderSize: @escaping (URL) -> Int64? = { _ in nil }) -> [FileItem] { func byName(_ a: FileItem, _ b: FileItem) -> Bool { a.name.localizedStandardCompare(b.name) == .orderedAscending } func less(_ a: FileItem, _ b: FileItem) -> Bool { switch order.key { case .name: return byName(a, b) case .ext: let c = a.ext.localizedStandardCompare(b.ext) return c == .orderedSame ? byName(a, b) : c == .orderedAscending case .size: if a.showsAsFolder { return byName(a, b) } return a.size == b.size ? byName(a, b) : a.size < b.size case .date: let da = a.modified ?? .distantPast, db = b.modified ?? .distantPast return da == db ? byName(a, b) : da < db } } let cmp: (FileItem, FileItem) -> Bool = order.ascending ? less : { less($1, $0) } let folders = items.filter { $0.showsAsFolder } let files = items.filter { !$0.showsAsFolder } let folderCmp: (FileItem, FileItem) -> Bool switch order.key { case .ext: folderCmp = byName case .size: folderCmp = { a, b in let sa = folderSize(a.url) ?? -1, sb = folderSize(b.url) ?? -1 if sa == sb { return byName(a, b) } return order.ascending ? sa < sb : sa > sb } default: folderCmp = cmp } return folders.sorted(by: folderCmp) + files.sorted(by: cmp) } /// Dimensione totale (file e sottocartelle, senza seguire i link). public static func totalSize(of url: URL, isCancelled: () -> Bool = { false }) -> (bytes: Int64, files: Int, folders: Int) { var st = stat() guard lstat(url.path, &st) == 0 else { return (0, 0, 0) } if (st.st_mode & S_IFMT) != S_IFDIR { return (Int64(st.st_size), 1, 0) } var bytes: Int64 = 0, files = 0, folders = 0 let keys: [URLResourceKey] = [.fileSizeKey, .isDirectoryKey, .isSymbolicLinkKey] guard let en = FileManager().enumerator(at: url, includingPropertiesForKeys: keys, options: [], errorHandler: { _, _ in true }) else { return (0, 0, 0) } for case let u as URL in en { if isCancelled() { break } let v = try? u.resourceValues(forKeys: Set(keys)) if v?.isDirectory == true && v?.isSymbolicLink != true { folders += 1 } else { files += 1 bytes += Int64(v?.fileSize ?? 0) } } return (bytes, files, folders) } } public enum Matcher { /// Maschere come in TC: "*.jpg *.png", "*.jpg;*.png", "*.*" = tutto. public static func matches(_ name: String, mask: String) -> Bool { let parts = mask.split(whereSeparator: { $0 == ";" || $0 == " " }).map(String.init) if parts.isEmpty { return false } return parts.contains { part in let p = part == "*.*" ? "*" : part return fnmatch(p, name, FNM_CASEFOLD) == 0 } } /// Ricerca rapida: inizio del nome, senza badare a maiuscole e accenti. /// Con * o ? diventa una maschera. public static func quickFilter(_ name: String, filter: String) -> Bool { if filter.isEmpty { return true } if filter.contains("*") || filter.contains("?") { return fnmatch(filter + "*", name, FNM_CASEFOLD) == 0 } return name.range(of: filter, options: [.caseInsensitive, .diacriticInsensitive, .anchored]) != nil } } public enum Format { private static let grouping: NumberFormatter = { let f = NumberFormatter() f.numberStyle = .decimal f.locale = Locale(identifier: "it_IT") return f }() private static let dateFormatter: DateFormatter = { let f = DateFormatter() f.dateFormat = "dd/MM/yyyy HH:mm" return f }() /// "1.234.567" public static func bytes(_ n: Int64) -> String { grouping.string(from: NSNumber(value: n)) ?? "\(n)" } /// "1,2 GB" public static func short(_ n: Int64) -> String { shortFormatter.string(fromByteCount: n) } private static let shortFormatter: ByteCountFormatter = { let f = ByteCountFormatter() f.countStyle = .file f.allowsNonnumericFormatting = false // "0 byte", non "Zero KB" return f }() public static func date(_ d: Date?) -> String { d.map { dateFormatter.string(from: $0) } ?? "" } /// "/Users/paolo/Downloads" -> "~/Downloads" public static func path(_ url: URL) -> String { if let s = FtpRegistry.session(for: url) { return "\(s.connection.name):\(url.path)" } return (url.path as NSString).abbreviatingWithTildeInPath } }