DEV Community

Cover image for Noticing "Shift held during a file drag" from a macOS menu bar app
Usukhbayar
Usukhbayar

Posted on AI-assisted

Noticing "Shift held during a file drag" from a macOS menu bar app

Convrt is a small open-source menu bar app: you start dragging files from Finder or the desktop, hold Shift, and a wheel opens under the cursor. Drop on a slice and the file is converted (HEIC to JPG, MOV to MP4, images to PDF and so on).

The interesting part isn't the conversion. It's how a background app with no window finds out that some other app is dragging files and that Shift is down, without breaking the drag. Here is how it works in the shipped code.

1. Watch mouse and modifier events globally

A menu bar app never gets these events directly, so it uses a global monitor:

let mask: NSEvent.EventTypeMask = [.leftMouseDown, .leftMouseDragged, .leftMouseUp,
                                   .flagsChanged, .scrollWheel, .keyDown]
monitor = NSEvent.addGlobalMonitorForEvents(matching: mask) { [weak self] event in
    self?.handle(event)
}
Enter fullscreen mode Exit fullscreen mode

Global monitors only work with the Accessibility permission (and Input Monitoring for keys), and they only observe: you can't consume or change the events. That's fine here, because the drag should carry on untouched.

2. Find out whether the drag is carrying files

A global leftMouseDragged event says nothing about what is being dragged. Selecting text and dragging a window look the same as dragging a file.

The trick is the system drag pasteboard. Every drag session writes to NSPasteboard(name: .drag), which bumps its changeCount. So remember the count when the mouse goes down, and during the drag check whether it changed and holds file URLs:

case .leftMouseDown:
    countAtMouseDown = NSPasteboard(name: .drag).changeCount

// on .leftMouseDragged, until files are found:
private func detectFileDrag() {
    let pb = NSPasteboard(name: .drag)
    guard pb.changeCount != countAtMouseDown, pb.changeCount != lastCheckedCount else { return }
    lastCheckedCount = pb.changeCount

    let urls = pb.readObjects(forClasses: [NSURL.self],
                              options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
    guard !urls.isEmpty else { return }
    activeURLs = urls
    startWatchdog()
}
Enter fullscreen mode Exit fullscreen mode

lastCheckedCount stops the app from re-reading the pasteboard on every mouse move.

3. Check the trigger key from both directions

People press Shift before they start dragging, or halfway through. So the same check runs on drag moves and on flagsChanged:

private func evaluateTrigger() {
    let held = NSEvent.modifierFlags.contains(triggerModifier)   // .shift by default
    let shouldBeActive = !activeURLs.isEmpty && held

    if shouldBeActive && !triggerActive {
        triggerActive = true
        onTriggerBegan?(activeURLs, NSEvent.mouseLocation)
    } else if !shouldBeActive && triggerActive {
        triggerActive = false
        onTriggerEnded?()
    }
}
Enter fullscreen mode Exit fullscreen mode

Reading NSEvent.modifierFlags (the current state) rather than the event's own flags avoids getting out of sync when a flagsChanged event is missed.

4. Don't trust the mouse-up

While another app is running its drag session, a global monitor often doesn't see the mouse-up that ends it. The wheel would stay open after the drop.

The fix is a small watchdog that only runs while a file drag is active and polls the real button state:

// Global monitors don't reliably see the mouse-up that ends a drag session,
// so poll the real button state while a file drag is active.
private func startWatchdog() {
    let timer = Timer(timeInterval: 0.1, repeats: true) { [weak self] _ in
        if NSEvent.pressedMouseButtons & 1 == 0 { self?.endSession() }
    }
    RunLoop.main.add(timer, forMode: .common)
    watchdog = timer
}
Enter fullscreen mode Exit fullscreen mode

The timer goes in .common run loop modes so it keeps firing even while the run loop is in a tracking mode, not only in the default mode.

5. Let the wheel accept the drop without stealing focus

The wheel is a borderless NSPanel:

styleMask: [.borderless, .nonactivatingPanel]
level = .popUpMenu
ignoresMouseEvents = false        // must be false so the wedges can receive drops
collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]
Enter fullscreen mode Exit fullscreen mode

.nonactivatingPanel is the key: showing it doesn't activate Convrt, so Finder stays frontmost and the drag session continues. The view inside calls registerForDraggedTypes([.fileURL]) and works out which slice is under the cursor in draggingUpdated, so the drop goes straight to the slice. From there it's an ordinary performDragOperation.

The no-permission fallback

Some people won't grant Accessibility to a converter, which is fair. Convrt also has a Drop Zone window: drag files onto it and the same wheels appear, with no permissions needed, because then it's a normal drop target.

Try it or read the code

Convrt is free and MIT-licensed: https://github.com/atuuuuuuu/Convrt (the code above is from Convrt/Wheel/DragMonitor.swift and WheelPanel.swift).

brew install --cask atuuuuuuu/tap/convrt
Enter fullscreen mode Exit fullscreen mode

If you know a cleaner way to spot a file drag from outside the source app than watching the drag pasteboard, I'd like to hear it.

Top comments (0)