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.

2.6 KB
Raw Blame
import AppKit

/// Dragging with the right button, as on Windows: pressing it on an item and moving starts a
/// drag of the selection; letting go over a folder asks Move here / Copy here / Make alias here
/// (FileListController.askDrop). A right click that doesn't move opens the menu as before.
@MainActor
enum RightDrag {
    /// A right-button drag is under way (the drop shows the menu).
    static var active = false

    /// Called from a list's rightMouseDown with the item under the pointer selected. Waits for
    /// the button to move or come up: true when a drag started, false for a plain right click.
    static func track(_ event: NSEvent, in view: NSView, urls: () -> [URL]) -> Bool {
        guard AppSettings.rightDrag, let window = view.window else { return false }
        let start = event.locationInWindow
        while let e = window.nextEvent(matching: [.rightMouseDragged, .rightMouseUp], until: .distantFuture, inMode: .eventTracking, dequeue: true) {
            if e.type == .rightMouseUp { return false }
            let p = e.locationInWindow
            guard hypot(p.x - start.x, p.y - start.y) > 5 else { continue }
            let files = urls()
            guard !files.isEmpty else { return false }
            let at = view.convert(start, from: nil)
            let items = files.enumerated().map { i, u -> NSDraggingItem in
                let item = NSDraggingItem(pasteboardWriter: u as NSURL)
                let icon = NSWorkspace.shared.icon(forFile: u.path)
                let size: CGFloat = 32
                item.setDraggingFrame(NSRect(x: at.x - size / 2 + CGFloat(i) * 3, y: at.y - size / 2 - CGFloat(i) * 3, width: size, height: size), contents: icon)
                return item
            }
            active = true
            let session = view.beginDraggingSession(with: items, event: e, source: Source.shared)
            session.animatesToStartingPositionsOnCancelOrFail = true
            return true
        }
        return false
    }

    final class Source: NSObject, NSDraggingSource {
        static let shared = Source()
        func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
            context == .withinApplication ? [.move, .copy, .link, .generic] : [.copy, .link, .generic]
        }
        func draggingSession(_ session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
            // the drop's menu (if any) was already put up asynchronously; it reads nothing from here
            DispatchQueue.main.async { MainActor.assumeIsolated { RightDrag.active = false } }
        }
    }
}