import AppKit import CommanderCore /// Percorso in cima al pannello, come la barra degli indirizzi di Windows e di TC: /// ogni cartella si clicca per tornarci; un clic sullo spazio libero (o sull'ultima cartella) /// lo rende modificabile, Invio va al percorso scritto, Esc annulla. final class PathBar: NSView, NSTextFieldDelegate { var onNavigate: ((URL) -> Void)? /// Testo scritto e confermato con Invio. var onSubmit: ((String) -> Void)? /// Prima di ogni clic (il pannello diventa attivo). var onClick: (() -> Void)? var textColor: NSColor = .white { didSet { needsDisplay = true } } let font = NSFont.boldSystemFont(ofSize: 12) private struct Crumb { let title: String; let url: URL; var rect: NSRect = .zero } private var crumbs: [Crumb] = [] private var hovered: Int? private var field: NSTextField? private var editText = "" override var isFlipped: Bool { true } override var intrinsicContentSize: NSSize { NSSize(width: NSView.noIntrinsicMetric, height: 17) } /// Le cartelle del percorso: "~" per la cartella Inizio, "nome:" per i server FTP. func show(_ url: URL) { var list: [Crumb] = [] if let s = FtpRegistry.session(for: url), let id = url.host { list.append(Crumb(title: s.connection.name + ":", url: FtpRegistry.url(id: id, path: "/"))) var p = "" for c in url.path.split(separator: "/") { p += "/" + c list.append(Crumb(title: String(c), url: FtpRegistry.url(id: id, path: p))) } } else { let path = url.standardizedFileURL.path let home = FileManager.default.homeDirectoryForCurrentUser.standardizedFileURL.path var base: URL var rest: Substring if path == home || path.hasPrefix(home + "/") { list.append(Crumb(title: "~", url: URL(fileURLWithPath: home))) base = URL(fileURLWithPath: home) rest = path.dropFirst(home.count) } else { list.append(Crumb(title: "/", url: URL(fileURLWithPath: "/"))) base = URL(fileURLWithPath: "/") rest = Substring(path) } for c in rest.split(separator: "/") { base.appendPathComponent(String(c)) list.append(Crumb(title: String(c), url: base)) } } crumbs = list editText = Format.path(url) hovered = nil needsDisplay = true } // MARK: - Disegno private func separator(after i: Int) -> String { // "/" tra le cartelle; dopo "/" e "nome:" non serve. let t = crumbs[i].title return (t == "/" || t.hasSuffix(":")) ? "" : "/" } override func draw(_ dirtyRect: NSRect) { guard field == nil, !crumbs.isEmpty else { return } let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: textColor] let widths = crumbs.indices.map { (crumbs[$0].title as NSString).size(withAttributes: attrs).width } let sepWidths = crumbs.indices.map { (separator(after: $0) as NSString).size(withAttributes: attrs).width } // Se non ci sta, si tolgono le prime cartelle e si mette "…/" (come TC accorcia a sinistra). let ellipsis = ("…/" as NSString).size(withAttributes: attrs).width var first = 0 func total(from f: Int) -> CGFloat { (f...(crumbs.count - 1)).reduce(f > 0 ? ellipsis : 0) { $0 + widths[$1] + ($1 < crumbs.count - 1 ? sepWidths[$1] : 0) } } while first < crumbs.count - 1 && total(from: first) > bounds.width { first += 1 } var x: CGFloat = 0 let y = (bounds.height - font.boundingRectForFont.height) / 2 if first > 0 { ("…/" as NSString).draw(at: NSPoint(x: x, y: y), withAttributes: attrs) x += ellipsis } for i in crumbs.indices { guard i >= first else { crumbs[i].rect = .zero; continue } var a = attrs if i == hovered { a[.underlineStyle] = NSUnderlineStyle.single.rawValue } (crumbs[i].title as NSString).draw(at: NSPoint(x: x, y: y), withAttributes: a) crumbs[i].rect = NSRect(x: x, y: 0, width: widths[i], height: bounds.height) x += widths[i] if i < crumbs.count - 1 { (separator(after: i) as NSString).draw(at: NSPoint(x: x, y: y), withAttributes: attrs) x += sepWidths[i] } } } // MARK: - Mouse override func updateTrackingAreas() { super.updateTrackingAreas() trackingAreas.forEach(removeTrackingArea) addTrackingArea(NSTrackingArea(rect: bounds, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self, userInfo: nil)) } private func crumb(at e: NSEvent) -> Int? { let p = convert(e.locationInWindow, from: nil) return crumbs.indices.first { crumbs[$0].rect.contains(p) } } override func mouseMoved(with e: NSEvent) { let h = crumb(at: e) if h != hovered { hovered = h; needsDisplay = true } if h != nil { NSCursor.pointingHand.set() } else { NSCursor.iBeam.set() } } override func mouseExited(with e: NSEvent) { hovered = nil needsDisplay = true NSCursor.arrow.set() } override func mouseDown(with e: NSEvent) { onClick?() // L'ultima cartella è quella in cui si è: cliccarla apre la modifica, come lo spazio vuoto. if let i = crumb(at: e), i < crumbs.count - 1 { onNavigate?(crumbs[i].url) } else { beginEditing() } } // MARK: - Modifica var isEditing: Bool { field != nil } func beginEditing() { guard field == nil else { return } let f = NSTextField(frame: bounds.insetBy(dx: -2, dy: -1)) f.stringValue = editText f.font = NSFont.systemFont(ofSize: 12) f.isBordered = true f.focusRingType = .none f.cell?.isScrollable = true f.cell?.wraps = false f.delegate = self f.autoresizingMask = [.width] addSubview(f) field = f needsDisplay = true window?.makeFirstResponder(f) f.currentEditor()?.selectAll(nil) } func endEditing() { guard let f = field else { return } field = nil f.delegate = nil f.removeFromSuperview() needsDisplay = true } func control(_ control: NSControl, textView: NSTextView, doCommandBy sel: Selector) -> Bool { if sel == #selector(NSResponder.insertNewline(_:)) { let text = field?.stringValue ?? "" endEditing() onSubmit?(text) return true } if sel == #selector(NSResponder.cancelOperation(_:)) { endEditing() onSubmit?("") return true } return false } func controlTextDidEndEditing(_ obj: Notification) { // Clic altrove: si torna alle cartelle senza cambiare percorso. DispatchQueue.main.async { [weak self] in self?.endEditing() } } }