How a Mac Menu Bar App Detects File Drags
Summary
Pixel shares a technical look at how Convrt, an open-source macOS menu bar app, detects file drags and Shift presses using global event monitors and the system drag pasteboard. The approach lets users convert files through a cursor wheel while leaving the original drag-and-drop interaction untouched.
DEV Community
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)
}
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()
}
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?()
}
}
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
}
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, .fullScreenAux...

Powered by Readybot.io