Multitouch and the Teleporting Mouse

Working on a tool called Multitouch, a MacOS app for binding shortcuts to trackpad gestures, we ran into an issue where a user’s mouse would teleport to a seemingly random location when the user executed a click via one of Multitouch’s gestures.

The odd part was that it only occurred when the user had an external monitor connected.

It turns out we were translating the coordinates of an NSEvent to a CGEvent (they have different coordinate origins) and using only the main screen height for calculating the translation.

So, previously we had the following function:

func getCgMouseLoc() -> CGPoint {
  let mouseLoc = NSEvent.mouseLocation
  let scrn: NSScreen = NSScreen.main!
  let height = scrn.frame.size.height
  return CGPoint(x: mouseLoc.x, y: abs(mouseLoc.y - height))

While this translates coordinates correctly for a single screen, it’s obvious that NSScreen.Main! is not the only possible screen when there’s an external monitor connected.

To fix this, we ended up avoiding the translation entirely:

func getCgMouseLoc() -> CGPoint? {
  let mouseLocEvent = CGEvent.init(source: nil)
  return mouseLocEvent?.location

This was rather unintuitive to me, as it seemed undocumented that creating a new CGEvent can give the location of the cursor.

However, it worked like a charm and looks simple enough. I’m new to Swift though, so if there’s a better way you should let me know!