Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

18.3 KB
Raw Blame
import AppKit
import Quartz
import QuickLookThumbnailing

/// The grid view's Tiles style, sized as on Windows at its default size (folder_view.rs
/// `GRID_SIZES[2]`): tiles 124 wide in rows 150 high with 4 between them, the picture asked
/// for at 128 and drawn at 96, the label `text_xs`, centred, at most two lines.
enum TileMetrics {
    /// folder_view.rs `GRID_SIZES`: (tile width, row height, picture asked for), smallest first.
    static let sizes: [(CGFloat, CGFloat, CGFloat)] = [(76, 94, 64), (92, 112, 80), (124, 150, 128), (172, 204, 192), (236, 276, 272)]
    /// The size chosen in the Layout flyout (0…4, 2 by default).
    static var size: Int {
        let v = UserDefaults.standard.object(forKey: "tileSize") as? Int ?? 2
        return min(max(v, 0), sizes.count - 1)
    }
    static var width: CGFloat { sizes[size].0 }
    /// Lines of a name under a tile (2 to 4; Windows' tile_name_lines, issue 452): the row grows
    /// by a line for each one past two.
    static var nameLines: Int { min(max(UserDefaults.standard.object(forKey: "tileNameLines") as? Int ?? 2, 2), 4) }
    static var rowHeight: CGFloat { sizes[size].1 + CGFloat(nameLines - 2) * lineHeight }
    /// One line of `text_xs` (12 pt).
    static let lineHeight: CGFloat = 15
    static let gap: CGFloat = 4
    /// The picture drawn: three quarters of the one asked for.
    static var visual: CGFloat { sizes[size].2 * 0.75 }
    /// The grid's own padding (`py_2`, `px 6`).
    static let padX: CGFloat = 6
    static let padY: CGFloat = 8
}

/// Thumbnails from Quick Look, made off the main thread. They are kept up to 256 MB, the
/// least recently made going first (issue 324: kept for the whole session, a long one of
/// picture folders ran into tens of GB). A file Quick Look can't picture keeps its icon.
@MainActor
final class ThumbnailCache {
    static let shared = ThumbnailCache()
    private let images: NSCache<NSString, NSImage> = {
        let c = NSCache<NSString, NSImage>()
        c.totalCostLimit = 256 << 20
        return c
    }()
    private var failed: Set<String> = []
    private var pending: [String: [(NSImage) -> Void]] = [:]

    func cached(_ path: String) -> NSImage? { images.object(forKey: path as NSString) }

    /// Calls `done` with the thumbnail when there is one (not at all when there is none).
    func request(_ path: String, scale: CGFloat, done: @escaping (NSImage) -> Void) {
        if let image = cached(path) { return done(image) }
        guard !failed.contains(path) else { return }
        if pending[path] != nil {
            pending[path]?.append(done)
            return
        }
        pending[path] = [done]
        let side = TileMetrics.visual
        let request = QLThumbnailGenerator.Request(
            fileAt: URL(fileURLWithPath: path), size: CGSize(width: side, height: side), scale: scale, representationTypes: .thumbnail)
        QLThumbnailGenerator.shared.generateBestRepresentation(for: request) { rep, _ in
            let cg = rep?.cgImage
            Task { @MainActor in
                let waiting = ThumbnailCache.shared.pending.removeValue(forKey: path) ?? []
                guard let cg else {
                    ThumbnailCache.shared.failed.insert(path)
                    return
                }
                let image = NSImage(cgImage: cg, size: NSSize(width: CGFloat(cg.width) / scale, height: CGFloat(cg.height) / scale))
                ThumbnailCache.shared.images.setObject(image, forKey: path as NSString, cost: cg.bytesPerRow * cg.height)
                waiting.forEach { $0(image) }
            }
        }
    }

    /// Forgets every thumbnail (Advanced › Cache › Clear).
    func clear() {
        images.removeAllObjects()
        failed = []
    }

    /// Forgets a folder's thumbnails (its files changed).
    func forget(under dir: String) {
        let prefix = dir.hasSuffix("/") ? dir : dir + "/"
        // (NSCache can't be walked: the folder's own pictures are dropped by name)
        for name in (try? FileManager.default.contentsOfDirectory(atPath: dir)) ?? [] { images.removeObject(forKey: (prefix + name) as NSString) }
        failed = failed.filter { !$0.hasPrefix(prefix) }
    }
}

/// One tile (folder_view.rs, grid): radius 8, `p_1`, the picture in a box 4 larger than it,
/// the name under it. Selected: selection fill and a 1 px `selection_border`; hover: hover fill.
final class TileView: HoverView, NSViewToolTipOwner {
    /// Settings › Files › Show details on hover: the text, asked for only when the tip shows.
    var detailTip: (() -> String?)? { didSet { needsLayout = true } }

    nonisolated func view(_ view: NSView, stringForToolTip tag: NSView.ToolTipTag, point: NSPoint, userData data: UnsafeMutableRawPointer?) -> String {
        MainActor.assumeIsolated { detailTip?() ?? "" }
    }

    let picture = NSImageView()
    let label = NSTextField(wrappingLabelWithString: "")
    /// Cards: the type, size and date beside the picture.
    let facts = NSTextField(wrappingLabelWithString: "")
    /// Tiles, Cards or List (folder_view.rs `GridStyle`).
    var style: ViewMode = .tiles {
        didSet {
            guard style != oldValue else { return }
            applyStyle()
            needsLayout = true
        }
    }
    var isSelected = false { didSet { needsDisplay = true } }
    /// Appearance › Alternating row colors, in List: whether the tile stands on a shaded line.
    /// Asked when the tile draws, since the line a tile is on changes with the layout.
    var onStripedLine: (() -> Bool)?
    /// (a tile moved by the layout may now be on the other kind of line)
    override var frame: NSRect { didSet { if style == .list && frame.origin != oldValue.origin { needsDisplay = true } } }
    var isThumbnail = false { didSet { picture.layer?.cornerRadius = isThumbnail ? 4 : 0 } }
    /// A small play mark on a video's picture, so it is told from a photo (Windows' video_badge).
    let badge = NSImageView()
    var isVideo = false { didSet { if isVideo != oldValue { applyStyle(); needsLayout = true } } }

    override init(frame: NSRect) {
        super.init(frame: frame)
        picture.imageScaling = .scaleProportionallyUpOrDown
        picture.wantsLayer = true
        picture.layer?.masksToBounds = true
        label.font = Metrics.textXs
        label.alignment = .center
        // two lines at most (Settings › Name lines in the grid), the last ending in "…"
        label.maximumNumberOfLines = TileMetrics.nameLines
        label.lineBreakMode = .byWordWrapping
        label.cell?.truncatesLastVisibleLine = true
        label.cell?.lineBreakMode = .byWordWrapping
        facts.font = Metrics.textXs
        facts.maximumNumberOfLines = 3
        facts.isHidden = true
        addSubview(picture)
        addSubview(label)
        addSubview(facts)
        badge.image = NSImage(systemSymbolName: "play.circle.fill", accessibilityDescription: nil)?
            .withSymbolConfiguration(.init(paletteColors: [.white, NSColor.black.withAlphaComponent(0.55)]))
        badge.imageScaling = .scaleProportionallyUpOrDown
        badge.isHidden = true
        addSubview(badge)
    }

    private func applyStyle() {
        switch style {
        case .cards:
            label.font = Metrics.textSmMedium
            label.alignment = .left
            label.maximumNumberOfLines = 1
            label.cell?.lineBreakMode = .byTruncatingTail
            facts.isHidden = false
        case .list:
            label.font = Metrics.textSm
            label.alignment = .left
            label.maximumNumberOfLines = 1
            label.cell?.lineBreakMode = .byTruncatingTail
            facts.isHidden = true
        default:
            label.font = Metrics.textXs
            label.alignment = .center
            label.maximumNumberOfLines = TileMetrics.nameLines
            label.cell?.lineBreakMode = .byWordWrapping
            facts.isHidden = true
        }
        badge.isHidden = !(isVideo && style == .tiles && AppSettings.videoBadge)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) { fatalError() }

    override func layout() {
        super.layout()
        removeAllToolTips()
        if detailTip != nil { addToolTip(bounds, owner: self, userData: nil) }
        switch style {
        case .cards:
            // px_2 gap_3: the picture 60 (in a box of 64), the name and the facts beside it
            let side: CGFloat = 60
            picture.frame = NSRect(x: 8 + 2, y: (bounds.height - side) / 2, width: side, height: side)
            let x = 8 + side + 4 + 12, w = bounds.width - x - 8
            let lh = ceil(Metrics.textSmMedium.ascender - Metrics.textSmMedium.descender) + 2
            let fh = min(facts.sizeThatFits(NSSize(width: w, height: 100)).height, 3 * 16)
            let top = (bounds.height - lh - 2 - fh) / 2
            label.frame = NSRect(x: x, y: top, width: w, height: lh)
            facts.frame = NSRect(x: x, y: top + lh + 2, width: w, height: fh)
            return
        case .list:
            // px_2 gap_2: a 20 icon and the name
            picture.frame = NSRect(x: 8, y: (bounds.height - 20) / 2, width: 20, height: 20)
            let lh = ceil(Metrics.textSm.ascender - Metrics.textSm.descender) + 2
            label.frame = NSRect(x: 8 + 20 + 8, y: (bounds.height - lh) / 2, width: bounds.width - 44, height: lh)
            return
        default: break
        }
        let box = TileMetrics.visual + 4
        let boxX = (bounds.width - box) / 2
        picture.frame = NSRect(x: boxX + 2, y: 4 + 2, width: TileMetrics.visual, height: TileMetrics.visual)
        let b = max(16, min(28, TileMetrics.visual / 4))
        badge.frame = NSRect(x: picture.frame.minX + 4, y: picture.frame.maxY - b - 4, width: b, height: b)
        label.frame = NSRect(x: 4, y: 4 + box + 4, width: bounds.width - 8, height: bounds.height - (4 + box + 4) - 4)
    }

    override func draw(_ dirtyRect: NSRect) {
        let p = Palette.of(self)
        let r = bounds.insetBy(dx: 0.5, dy: 0.5)
        let path = NSBezierPath(roundedRect: r, xRadius: Metrics.radius, yRadius: Metrics.radius)
        if isSelected {
            p.selection.setFill()
            path.fill()
            p.selectionBorder.setStroke()
            path.lineWidth = 1
            path.stroke()
        } else if hovered {
            (style == .list && AppSettings.alternatingRows ? p.stripeHover : p.hover).setFill()
            path.fill()
        } else if onStripedLine?() == true {
            p.stripe.setFill()
            path.fill()
        }
    }
}

final class TileItem: NSCollectionViewItem {
    static let id = NSUserInterfaceItemIdentifier("tile")
    var path = ""

    var tile: TileView { view as! TileView }

    override func loadView() {
        view = TileView(frame: NSRect(origin: .zero, size: ViewMode.tiles.cellSize))
        textField = tile.label
        imageView = tile.picture
    }

    override func prepareForReuse() {
        super.prepareForReuse()
        tile.hoverPoint = nil
        tile.hovered = false
    }

    override var isSelected: Bool { didSet { tile.isSelected = isSelected } }
}

/// The grid itself, with the same keys as the list.
@MainActor
final class TileCollectionView: NSCollectionView, NSServicesMenuRequestor {
    weak var list: FileListController?

    override func magnify(with event: NSEvent) { list?.pinched(event) }
    override func otherMouseUp(with event: NSEvent) {
        guard event.buttonNumber == 2, let list, let at = indexPathForItem(at: convert(event.locationInWindow, from: nil)) else { return super.otherMouseUp(with: event) }
        list.middleClicked(row: list.gridRow(at))
    }

    // Settings › Select on hover, in the grid too: resting on a tile for half a second selects it
    private var hoverTimer: Timer?
    private var hoverPath: IndexPath?

    override func updateTrackingAreas() {
        super.updateTrackingAreas()
        trackingAreas.filter { $0.owner === self }.forEach(removeTrackingArea)
        addTrackingArea(NSTrackingArea(rect: .zero, options: [.mouseMoved, .activeInKeyWindow, .inVisibleRect], owner: self))
    }

    override func mouseMoved(with event: NSEvent) {
        super.mouseMoved(with: event)
        guard AppSettings.selectOnHover else { return }
        let at = indexPathForItem(at: convert(event.locationInWindow, from: nil))
        guard at != hoverPath else { return }
        hoverPath = at
        hoverTimer?.invalidate()
        guard let at else { return }
        hoverTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { [weak self] _ in
            MainActor.assumeIsolated {
                guard let self, self.hoverPath == at, NSEvent.pressedMouseButtons == 0, let list = self.list else { return }
                list.hoverSelect(list.gridRow(at))
            }
        }
    }
    override func scrollWheel(with event: NSEvent) {
        if list?.commandScrolled(event) != true { super.scrollWheel(with: event) }
    }

    override func becomeFirstResponder() -> Bool {
        let ok = super.becomeFirstResponder()
        if ok { list?.onFocus?() }
        return ok
    }

    override func keyDown(with event: NSEvent) {
        if list?.handleKey(event) == true { return }
        super.keyDown(with: event)
    }

    override func mouseDown(with event: NSEvent) {
        let point = convert(event.locationInWindow, from: nil)
        if event.clickCount == 1, isSelectable, allowsMultipleSelection,
           indexPathForItem(at: point) == nil,
           !event.modifierFlags.contains(.control) {
            let initial = selectionIndexPaths
            let toggle = event.modifierFlags.contains(.command)
            let extend = event.modifierFlags.contains(.shift)
            let dragged = SelectionMarquee.track(from: event, in: self) { rect in
                let hits = Set((collectionViewLayout?.layoutAttributesForElements(in: rect) ?? [])
                    .filter { $0.representedElementCategory == .item && $0.frame.intersects(rect) }
                    .compactMap(\.indexPath))
                let selection = toggle ? initial.symmetricDifference(hits) : extend ? initial.union(hits) : hits
                updateMarqueeSelection(selection)
            }
            if !dragged {
                window?.makeFirstResponder(self)
                if !toggle && !extend { updateMarqueeSelection([]) }
            }
            if initial != selectionIndexPaths {
                delegate?.collectionView?(self, didSelectItemsAt: selectionIndexPaths)
            }
            return
        }
        super.mouseDown(with: event)
        guard event.clickCount == 2 else { return }
        if indexPathForItem(at: convert(event.locationInWindow, from: nil)) != nil {
            list?.openSelected()
        } else {
            // Files › Double-click empty space to go up (issue 439)
            list?.emptySpaceDoubleClicked()
        }
    }

    private func updateMarqueeSelection(_ selection: Set<IndexPath>) {
        guard selectionIndexPaths != selection else { return }
        selectionIndexPaths = selection
    }

    /// Right button on a tile: a drag with it asks Move / Copy / Alias on the drop (RightDrag).
    override func rightMouseDown(with event: NSEvent) {
        guard let at = indexPathForItem(at: convert(event.locationInWindow, from: nil)), let list, list.archiveIsNil else {
            return super.rightMouseDown(with: event)
        }
        if !selectionIndexPaths.contains(at) {
            selectionIndexPaths = [at]
            delegate?.collectionView?(self, didSelectItemsAt: [at])
        }
        if RightDrag.track(event, in: self, urls: { list.selectedURLs }) { return }
        super.rightMouseDown(with: event)
    }

    override func menu(for event: NSEvent) -> NSMenu? {
        let at = indexPathForItem(at: convert(event.locationInWindow, from: nil))
        if let at, !selectionIndexPaths.contains(at) {
            selectionIndexPaths = [at]
            delegate?.collectionView?(self, didSelectItemsAt: [at])
        }
        if at == nil {
            let old = selectionIndexPaths
            selectionIndexPaths = []
            delegate?.collectionView?(self, didDeselectItemsAt: old)
        }
        return list?.contextMenu()
    }

    // macOS's Services and Quick Actions (the Windows app's "Show more options") work on the
    // selected files: the menu shows the ones that take file URLs.
    override func validRequestor(forSendType sendType: NSPasteboard.PasteboardType?, returnType: NSPasteboard.PasteboardType?) -> Any? {
        if sendType == .fileURL, returnType == nil, let list, !list.selectedURLs.isEmpty, list.archiveIsNil { return self }
        return super.validRequestor(forSendType: sendType, returnType: returnType)
    }

    func writeSelection(to pboard: NSPasteboard, types: [NSPasteboard.PasteboardType]) -> Bool {
        guard let urls = list?.selectedURLs, !urls.isEmpty else { return false }
        pboard.clearContents()
        return pboard.writeObjects(urls as [NSURL])
    }

    override func acceptsPreviewPanelControl(_ panel: QLPreviewPanel!) -> Bool { true }
    override func beginPreviewPanelControl(_ panel: QLPreviewPanel!) { list?.beginQuickLook(panel) }
    override func endPreviewPanelControl(_ panel: QLPreviewPanel!) { list?.endQuickLook(panel) }

    override func viewDidChangeEffectiveAppearance() {
        super.viewDidChangeEffectiveAppearance()
        let p = Palette.of(self)
        for item in visibleItems() {
            guard let t = item as? TileItem else { continue }
            t.tile.label.textColor = p.text
            t.tile.facts.textColor = p.textSecondary
            t.tile.needsDisplay = true
        }
    }
}

/// A group's header in the grid: the title in the accent, medium, then a line (the list's
/// group header, folder_view.rs).
@MainActor
final class GridGroupHeader: NSView, NSCollectionViewElement {
    static let id = NSUserInterfaceItemIdentifier("gridGroup")
    var title = "" { didSet { needsDisplay = true } }
    var count: Int? { didSet { needsDisplay = true } }
    var folded = false { didSet { needsDisplay = true } }
    var onClick: (() -> Void)?

    override var isFlipped: Bool { true }

    override func draw(_ dirtyRect: NSRect) {
        GroupMetrics.draw(title, count: count, folded: folded, hot: false, in: NSRect(x: 6, y: 10, width: bounds.width - 12, height: 18), palette: Palette.of(self))
    }

    override func mouseDown(with event: NSEvent) {}
    override func mouseUp(with event: NSEvent) {
        if bounds.contains(convert(event.locationInWindow, from: nil)) { onClick?() }
    }
}