Event Loop with Cocoa on MacOS

References

We already had a basic event loop just to make the window show up, but now we'll handle all the events you're likely to need for your game/app. The setup code is mostly the same; the delegate and event loop have extra code this time.

Build with:

clang main.m -fobjc-arc -framework Cocoa
#import

We really only need one header file from this framework - HiToolblox/Events.h, which can be found at: [macOS SDK]/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Headers/Events.h. You could use the full system path of that file and #import it, but I'd rather conform to OBJC's intended methods and just #import the "umbrella" framework, Carbon.h, which then goes on to import this header. It contains all the kVK key codes we need.

Most events are self-explanatory, but I'll explore a few.

case NSEventTypeScrollWheel: { if ([e hasPreciseScrollingDeltas]) { const NSTimeInterval time = [e timestamp]; const float dy = [e scrollingDeltaY]; printf ("Precise scroll %f @ %f\n", dy, time); } else { const float dy = [e deltaY]; printf ("Simple scroll %f\n", dy); } } break;

Scrolling on MacOS for games is a disaster. Mac uses "precise scrolling," which is great if you want to smoothly change a continuous value with the scroll wheel/ball or touchpad (like moving around a map, say), but horrible for switching weapons with the scroll wheel in a shooter. You may just need to ask the user what kind of scrolling device they're using.

You'll either receive "simple" scrolls, or "precise" scrolls. Precise scrolls give you pixel values, intended for smooth scrolling around a page and stuff. Simple scrolls are filtered, accelerated values that macOS generates based on how quickly the scroll wheel was moved - so the wheel may be moved the same number of notches, but generate higher or lower numbers based on how quickly that was done! We'll explore a solution for filtering scrolls into discrete steps in a later step on the Path.

-(void)windowDidBecomeKey:(NSNotification *)notification { NSEvent *event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:(NSPoint){0,0} modifierFlags:0 timestamp:[[NSProcessInfo processInfo] systemUptime] windowNumber:[window windowNumber] context:nil subtype:OSXUserEvent_GainedFocus data1:0 data2:0]; [app postEvent:event atStart:false]; } int8_t kVKToModkey (uint8_t keycode) { switch (keycode) { case kVK_Shift: return 0; break; case kVK_RightShift: return 1; break; case kVK_Control: return 2; break; case kVK_RightControl: return 3; break; case kVK_Option: return 4; break; case kVK_RightOption: return 5; break; case kVK_Command: return 6; break; case kVK_RightCommand: return 7; break; case kVK_Function: return 8; break; default: return -1; } } static const uint8_t modkeys_kvk[] = { kVK_Shift, kVK_RightShift, kVK_Control, kVK_RightControl, kVK_Option, kVK_RightOption, kVK_Command, kVK_RightCommand, kVK_Function }; static uint8_t modkeys[sizeof (modkeys_kvk) / sizeof(modkeys_kvk[0])]; case NSEventTypeFlagsChanged: { const uint8_t key_code = (uint8_t)[e keyCode]; const int8_t modkeyi = kVKToModkey(key_code); if (modkeyi == -1) { puts ("Unsupported modifier key"); break; } modkeys[modkeyi] = !modkeys[modkeyi]; const NSEventModifierFlags flags = [e modifierFlags]; static const int modkey_flagbit[sizeof (modkeys_kvk) / sizeof(modkeys_kvk[0])] = { NSEventModifierFlagShift, NSEventModifierFlagShift, NSEventModifierFlagControl, NSEventModifierFlagControl, NSEventModifierFlagOption, NSEventModifierFlagOption, NSEventModifierFlagCommand, NSEventModifierFlagCommand, NSEventModifierFlagFunction }; if (!(flags & modkey_flagbit[modkeyi])) modkeys[modkeyi] = false; printf ("Key %s %s\n", KeycodeStr(key_code), modkeys[modkeyi] ? "pressed" : "released"); } break; case OSXUserEvent_GainedFocus: { puts ("Focus in"); for (int i = 0; i < sizeof (modkeys) / sizeof (modkeys[0]); ++i) { modkeys[i] = CGEventSourceKeyState (kCGEventSourceStateCombinedSessionState, (CGKeyCode)modkeys_kvk[i]); } } break;

Annoyingly, Cocoa handles keys such as ALT, CTRL, Command, and such, separately to regular keys, with the NSEventTypeFlagsChanged event. It contains the keycode, [e keyCode], of the key that has been pressed or released, but it does not say whether the key was pressed or released. It does contain a set of flags, obtainable with [e modifierFlags], but each flag relates to multiple keys - a single control flag for both control keys, for example. A reasonable way to handle these is by checking the current state of the relevant key whenever this event is received, with CGEventSourceKeyState. However, this has the issue that, if a key is pressed and released before the press event is handled, the press event will be treated as a release event.

My solution is to keep track of the state of these keys in an array, modkeys, and swap the state of the given key every time we receive an NSEventTypeFlagsChanged event of that key. If the user tabs out of the window while holding one of these keys, then releases the key while in a different window, our program will still think the key is held. To solve that, we check the state of all modifier keys whenever the window regains focus.

It is still theoretically possible for the keys to become out of sync, so we check the flag state whenever we receive the NSEventTypeFlagsChanged event, and reset the given key to released if the flag is clear. With this, it's only possible for the key state to be out of sync if the user has pressed both keys, keeps one held, and the program hits a random lag spike when tabbing in, during which the user releases one of the keys. It's not perfect, but it's close enough. Let me know if you discover a truly 100% robust way to handle these keys!

CAPSLOCK NOTE: Since CapsLock is a toggle, we only receive an NSEventTypeFlagsChanged whenever the key is pressed, but not when it is released. We also don't receive this event at all if the key is tapped very briefly, since macOS filters this out to prevent accidental toggling. It may or may not be appropriate for your game to support using the CapsLock key - if you use it, you could either treat it as a toggle, or as a key that can only be tapped, not held (by treating each capslock event as an instantaneous press+release).

case NSEventTypeApplicationDefined: { switch ([e subtype]) { case OSXUserEvent_WindowClose: { printf ("Window close\n"); quit = true; } break; case OSXUserEvent_WindowResize: printf ("Resize %d, %d\n", (int)[e data1], (int)[e data2]); break; case OSXUserEvent_LostFocus: puts ("Focus Out"); break; default: puts ("Unknown user event?"); break; } } break;

Ah, the user events! Finally, something that just works exactly as you'd expect.

enum { OSXUserEvent_WindowClose, OSXUserEvent_WindowResize, OSXUserEvent_LostFocus, };

These are user event values. You can set them to anything - they're entirely created and used by your own code. I like to just put them in an enum to give them all a unique value.

NSView *content_view = [window contentView]; NSTrackingArea *tracking_area = [[NSTrackingArea alloc] initWithRect:content_view.bounds options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect | NSTrackingEnabledDuringMouseDrag owner:[window delegate] userInfo:nil]; [content_view addTrackingArea:tracking_area];

Adding a tracking area to your window allows you to detect whenever the mouse enters or exits the content area of your window. This is important for discarding mouse movement events when the mouse is outside of your window, or showing/hiding the cursor as it enters/leaves.

-(void)mouseEntered:(NSEvent *)event { printf("Mouse entered content view tracking area\n"); } -(void)mouseExited:(NSEvent *)event { printf("Mouse exited content view tracking area\n"); } -(void)mouseMoved:(NSEvent *)event { NSPoint p = [[window contentView] convertPointToBacking:[event locationInWindow]]; printf("Mouse moved inside content view tracking area: %.1f %.1f\n", p.x, p.y); }

Since we set the NSTrackingMouseEnteredAndExited and NSTrackingMouseMoved options, we must implement the associated functions to be called.

case NSEventTypeMouseMoved: case NSEventTypeLeftMouseDragged: case NSEventTypeRightMouseDragged: case NSEventTypeOtherMouseDragged: { if (e.window == nil) { NSRect frame = [window frame]; NSPoint p = [e locationInWindow]; p.x -= frame.origin.x; p.y -= frame.origin.y; p = [[window contentView] convertPointToBacking:p]; printf ("Mouse moved outside window: %.1f %.1f\n", p.x, p.y); } else { NSPoint p = [[window contentView] convertPointToBacking:[e locationInWindow]]; printf("Mouse moved: %.1f %.1f\n", p.x, p.y); } } break;

We need to detect mouse movements with all 4 of these event types. You'd think you could just use [e locationInWindow] to get the position. But that coordinate is highly inconsistent. If the mouse is in our window, it's relative to the bottom-left corner of our window. If not, it's relative to the global desktop bottom-left corner. And the coordinates are scaled depending on the system HiDPI resolution scaling setting, so even when it's relative to our window, it's scaled differently than our pixels! So, we use convertPointToBacking to convert it to the coordinate space of the content view. We also manually map it relative to the bottom-left corner of our window when it's outside our window.

-(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender { NSEvent *event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:(NSPoint){0,0} modifierFlags:0 timestamp:[[NSProcessInfo processInfo] systemUptime] windowNumber:[window windowNumber] context:nil subtype:OSXUserEvent_WindowClose data1:0 data2:0]; [app postEvent:event atStart:true]; return NSTerminateCancel; }

We create an event with [NSEvent otherEventWithType:NSEventTypeApplicationDefined ...]. subtype is where we use our custom OSXUserEvent enum. In [app postEvent ...] you have the choice of posting it to the start of the event queue, so that it's the next event to be processed. I only use this for quit events, since there's no point processing remaining events.

-(void)windowDidResignKey:(NSNotification*)notification { NSEvent *event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:(NSPoint){0,0} modifierFlags:0 timestamp:[[NSProcessInfo processInfo] systemUptime] windowNumber:[window windowNumber] context:nil subtype:OSXUserEvent_LostFocus data1:0 data2:0]; [app postEvent:event atStart:false]; }

windowDidResignKey means your window is no longer the "key window" - Apple's term for the window with focus.

@implementation Delegate { bool live_resizing; } -(void)windowDidResize:(NSNotification *)notification { if (live_resizing) return; [self SendResizeEvent]; } -(void)windowWillStartLiveResize:(NSNotification *)notification { live_resizing = true; } -(void)windowDidEndLiveResize:(NSNotification *)notification { live_resizing = false; [self SendResizeEvent]; } -(void)SendResizeEvent { NSSize size = [[window contentView] convertRectToBacking:[[window contentView] bounds]].size; NSEvent *event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:(NSPoint){0,0} modifierFlags:0 timestamp:[[NSProcessInfo processInfo] systemUptime] windowNumber:[window windowNumber] context:nil subtype:OSXUserEvent_WindowResize data1:size.width data2:size.height]; [app postEvent:event atStart:false]; }

The window can either be instantaneously resized, or "live resized" when the user drags the edges/corners. Whenever the window is finished resizing, we call our own SendResizeEvent function to send a user event with the new size. If we're live resizing, we avoid sending thousands of resize events by using this live_resizing member variable.

if (pass_event_along) [app sendEvent:e];

By default, events should be passed along to AppKit with sendEvent. The only events we don't send are key down/up, which produce beep sounds when sent to AppKit.