Re: a mouse event problem on macOS


James Walker
 

On 9/20/2017 5:17 PM, Graham Cox wrote:

      
On 21 Sep 2017, at 3:53 am, James Walker <list2@...> wrote:

Thank you very much.  Your code didn't work for me at first, perhaps because of a complication that I did not mention in my original message:  The original mouse down happens in a Carbon window.  Anyway, the mouse events returned by -[NSWindow nextEventMatchingMask:untilDate:inMode:dequeue:] are for the wrong window and hence have the wrong mouse coordinates, so I had to convert the coordinates and create a new NSEvent for the right window before forwarding it on to my view's mouseDragged: method.  But it's working now.
OK, sounds a bit smelly, but whatever works, I guess.

The red flag here is the need to “create an event”. I don’t believe there’s ever any reason to do that in mainstream (i.e. app level) code.

NSView has a reference to its window, and the events for that window should have the -locationInWindow coordinate correct for the window. From that you need to convert to the view’s local coordinates using -convertPoint:fromView:, but other than that there’s nothing special to do. I’m not sure why Carbon windows make a difference (surprised they’re still a thing), and since you are creating the overlay window, then everything should be local to that. The original mouse down in the Carbon window is irrelevant in this case - you can simply discard it.

NSView’s trio of mouse methods - mouseDown: -mouseDragged: and -mouseUp: are conveniences - NSView internally implements a loop just like the one I showed which calls out to those methods, but you are not obliged to use them.

The docs on -[NSWindow nextEventMatchingMask:untilDate:inMode:dequeue:] says it forwards the message to -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:].  So, how does NSApplication know what window to send the event to?  It could check what's under the location of the mouse, but as Quincey Morris said elsewhere in this thread, maybe it just sends mouse dragged and mouse up events to the same target as the mouse down.

Join cocoa@apple-dev.groups.io to automatically receive all group messages.