【Mac】Detecting File Dragging in Cocoa

// properties for preventing consistently calling
var mouseDidDragged = false
var shouldCallForMouseDrag = true
// a system-wide AXUIElement
let systemWideElement = AXUIElementCreateSystemWide()

// MARK: Listen for fileDrag event

NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDragged) { event in
    if self.shouldCallForMouseDrag {
        self.shouldCallForMouseDrag = false
        self.mouseDidDragged = true

        // getting mouse position
        let (x, y) = NSEvent.mouseLocation.verticalFlippedInScreen().sepratedFloatValue

        // getting accessibility object under the pointer
        var element: AXUIElement?
        guard AXUIElementCopyElementAtPosition(self.systemWideElement, x, y, &element) == .success  else {
            return
        }

        // ask accessibility API for filename attribute
        var value: CFTypeRef?
        guard AXUIElementCopyAttributeValue(element!, kAXFilenameAttribute as CFString, &value) == .success else {
            return
        }

        // check whether there's a filename exist
        guard let _ = value else {
            return
        }

        print("we are dragging a file!")
        // do your thing here
    }
}

NSEvent.addGlobalMonitorForEvents(matching: .leftMouseUp) { event in
    if self.mouseDidDragged {
        self.shouldCallForMouseDrag = true
        self.mouseDidDragged = false

        // undo your thing here
    }
}

// MARK: Helpful NSPoint Extensions

extension NSPoint {
    func verticalFlippedInScreen() -> NSPoint {
        guard let screen = (NSScreen.screens.first { NSPointInRect(self, $0.frame) }) else { return .zero }
        let screenHeight = screen.frame.height
        return NSPoint(x: x, y: screenHeight - y - 1)
    }

    var separatedFloatValue: (Float, Float) {
        return (Float(x), Float(y))
    }
}

Note: This works only when dragging a file in finder. If you want this apply to like when dragging an image inside an application, fell free to add other attribute name to examine, or even combine it with the result of pasteboard’s propertyList.

There you have it, this is how to detecting a file dragging. One thing to remember: If your app is sandboxed, you may found this not working. In this case, you may want to send a email to Apple, tell them what you want to do with this API, and ask them to send you a slightly different .entitlements file.

https://isaacxen.github.io/2018/03/03/detecting-file-dragging-in-cocoa/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章