// NOTE: the cocoa platform layer, compiled on its own as objective-c++ with ARC by // build_macos.sh. see platform_macos.h for the contract. #import #import #include #include #include #include #define PLATFORM_APPLE 1 #define PLATFORM_LINUX 0 #define PLATFORM_WINDOWS 0 #ifndef DEBUG #define DEBUG 0 #endif // NOTE: base_core defines Nil (objc has its own) and internal; the objc headers are already in #pragma push_macro("Nil") #undef Nil #include "base_core.h" #undef Nil #pragma pop_macro("Nil") #include "platform.h" #include "platform_keysyms.h" #define PLATFORM_MACOS_IMPLEMENTATION #include "platform_macos.h" internal u64 mac_now_ns(void) { struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return (u64)now.tv_sec * 1000000000ull + (u64)now.tv_nsec; } internal void mac_button_update(PlatformButton *button, b32 down) { if(button->ended_down != down) { button->ended_down = down; ++button->half_transition_count; } } // NOTE: files from finder / the dock can arrive before the window exists (launch by "open with") global_variable char mac_pending_paths[PLATFORM_MAX_DROPS][PLATFORM_DROP_PATH_SIZE]; global_variable u32 mac_pending_count; global_variable MacWindowState *mac_state; internal void mac_queue_path(const char *path) { if(!path || !path[0]) return; if(mac_state) { PlatformInput *input = &mac_state->input; if(input->drop_count < PLATFORM_MAX_DROPS) { snprintf(input->drop_paths[input->drop_count++], PLATFORM_DROP_PATH_SIZE, "%s", path); input->changed = true; } } else if(mac_pending_count < PLATFORM_MAX_DROPS) { snprintf(mac_pending_paths[mac_pending_count++], PLATFORM_DROP_PATH_SIZE, "%s", path); } } internal u32 mac_mods(NSEventModifierFlags flags) { u32 mods = 0; if(flags & NSEventModifierFlagShift) mods |= PLATFORM_MOD_SHIFT; if(flags & (NSEventModifierFlagCommand | NSEventModifierFlagControl)) mods |= PLATFORM_MOD_CTRL; if(flags & NSEventModifierFlagOption) mods |= PLATFORM_MOD_ALT; return mods; } // NOTE: kVK_* virtual key codes (Carbon's Events.h) for everything that isn't a character internal u32 mac_special_keysym(u16 code, b32 shift) { switch(code) { case 0x24: return XKB_KEY_Return; case 0x30: return shift ? XKB_KEY_ISO_Left_Tab : XKB_KEY_Tab; case 0x31: return XKB_KEY_space; case 0x33: return XKB_KEY_BackSpace; case 0x35: return XKB_KEY_Escape; case 0x75: return XKB_KEY_Delete; case 0x72: return XKB_KEY_Insert; // help key, where pc keyboards have insert case 0x73: return XKB_KEY_Home; case 0x77: return XKB_KEY_End; case 0x74: return XKB_KEY_Page_Up; case 0x79: return XKB_KEY_Page_Down; case 0x7B: return XKB_KEY_Left; case 0x7C: return XKB_KEY_Right; case 0x7D: return XKB_KEY_Down; case 0x7E: return XKB_KEY_Up; case 0x7A: return XKB_KEY_F1; case 0x78: return XKB_KEY_F2; case 0x63: return XKB_KEY_F3; case 0x76: return XKB_KEY_F4; case 0x60: return XKB_KEY_F5; case 0x61: return XKB_KEY_F6; case 0x62: return XKB_KEY_F7; case 0x64: return XKB_KEY_F8; case 0x65: return XKB_KEY_F9; case 0x6D: return XKB_KEY_F10; case 0x67: return XKB_KEY_F11; case 0x6F: return XKB_KEY_F12; case 0x4C: return XKB_KEY_KP_Enter; case 0x45: return XKB_KEY_KP_Add; case 0x4E: return XKB_KEY_KP_Subtract; case 0x43: return XKB_KEY_KP_Multiply; case 0x4B: return XKB_KEY_KP_Divide; case 0x41: return XKB_KEY_KP_Decimal; case 0x52: return XKB_KEY_KP_0; case 0x53: return XKB_KEY_KP_1; case 0x54: return XKB_KEY_KP_2; case 0x55: return XKB_KEY_KP_3; case 0x56: return XKB_KEY_KP_4; case 0x57: return XKB_KEY_KP_5; case 0x58: return XKB_KEY_KP_6; case 0x59: return XKB_KEY_KP_7; case 0x5B: return XKB_KEY_KP_8; case 0x5C: return XKB_KEY_KP_9; case 0x38: return XKB_KEY_Shift_L; case 0x3C: return XKB_KEY_Shift_R; case 0x3B: return XKB_KEY_Control_L; case 0x3E: return XKB_KEY_Control_R; case 0x3A: return XKB_KEY_Alt_L; case 0x3D: return XKB_KEY_Alt_R; case 0x37: return XKB_KEY_Super_L; case 0x36: return XKB_KEY_Super_R; case 0x39: return XKB_KEY_Caps_Lock; } return 0; } internal void mac_append_utf8(PlatformInput *input, NSString *text) { const char *utf8 = [text UTF8String]; if(!utf8) return; for(const u8 *at = (const u8 *)utf8; *at; ) { // NOTE: skip control characters and cocoa's private use function key range (U+F700..) u32 length = (*at < 0x80) ? 1 : ((*at >> 5) == 0x6) ? 2 : ((*at >> 4) == 0xE) ? 3 : 4; b32 control = (*at < 0x20 || *at == 0x7f); b32 private_use = (length == 3 && at[0] == 0xEF && at[1] >= 0x9C && at[1] <= 0xA3); if(!control && !private_use && input->text_size + length <= sizeof(input->text)) { MemCpy(input->text + input->text_size, at, length); input->text_size += length; } for(u32 index = 0; index < length && *at; ++index) ++at; } } //- the view: input, drops, the metal layer @interface DesignView : NSView @property(nonatomic, strong) NSEvent *lastMouseDown; @end @implementation DesignView - (BOOL)isFlipped { return YES; } - (BOOL)acceptsFirstResponder { return YES; } - (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; } - (BOOL)wantsUpdateLayer { return YES; } - (CALayer *)makeBackingLayer { return [CAMetalLayer layer]; } - (void)updateTrackingAreas { for(NSTrackingArea *area in [self.trackingAreas copy]) [self removeTrackingArea:area]; NSTrackingAreaOptions options = NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways | NSTrackingInVisibleRect | NSTrackingCursorUpdate; [self addTrackingArea:[[NSTrackingArea alloc] initWithRect:self.bounds options:options owner:self userInfo:nil]]; [super updateTrackingAreas]; } - (void)mousePosition:(NSEvent *)event { if(!mac_state) return; NSPoint point = [self convertPoint:event.locationInWindow fromView:nil]; mac_state->input.mouse_x = (f32)point.x; mac_state->input.mouse_y = (f32)point.y; mac_state->input.mods = mac_mods(event.modifierFlags); mac_state->input.changed = true; } - (void)button:(u32)index event:(NSEvent *)event down:(b32)down { [self mousePosition:event]; if(mac_state) mac_button_update(&mac_state->input.mouse[index], down); if(down && index == 0) self.lastMouseDown = event; } - (void)mouseDown:(NSEvent *)event { [self button:0 event:event down:true]; } - (void)mouseUp:(NSEvent *)event { [self button:0 event:event down:false]; } - (void)rightMouseDown:(NSEvent *)event { [self button:1 event:event down:true]; } - (void)rightMouseUp:(NSEvent *)event { [self button:1 event:event down:false]; } - (void)otherMouseDown:(NSEvent *)event { if(event.buttonNumber == 2) [self button:2 event:event down:true]; } - (void)otherMouseUp:(NSEvent *)event { if(event.buttonNumber == 2) [self button:2 event:event down:false]; } - (void)mouseMoved:(NSEvent *)event { [self mousePosition:event]; } - (void)mouseDragged:(NSEvent *)event { [self mousePosition:event]; } - (void)rightMouseDragged:(NSEvent *)event { [self mousePosition:event]; } - (void)otherMouseDragged:(NSEvent *)event { [self mousePosition:event]; } - (void)mouseEntered:(NSEvent *)event { if(!mac_state) return; mac_state->input.mouse_in_window = true; [self mousePosition:event]; } - (void)mouseExited:(NSEvent *)event { if(!mac_state) return; mac_state->input.mouse_in_window = false; mac_state->input.changed = true; if(!([NSEvent pressedMouseButtons] & 7)) { for(u32 index = 0; index < 3; ++index) mac_button_update(&mac_state->input.mouse[index], false); } } - (void)cursorUpdate:(NSEvent *)event { if(mac_state) macos_window_set_cursor(NULL, UINT32_MAX); } - (void)scrollWheel:(NSEvent *)event { if(!mac_state) return; // NOTE: trackpads report pixels, wheels report lines. ours is notches, positive = down f32 divisor = event.hasPreciseScrollingDeltas ? 10.0f : 1.0f; mac_state->input.scroll_y -= (f32)event.scrollingDeltaY / divisor; mac_state->input.scroll_x -= (f32)event.scrollingDeltaX / divisor; mac_state->input.changed = true; } - (void)keyDown:(NSEvent *)event { if(!mac_state) return; PlatformInput *input = &mac_state->input; u32 mods = mac_mods(event.modifierFlags); input->mods = mods; input->changed = true; // NOTE: like xkb_state_key_get_one_sym: shift applies, cmd / ctrl / option don't u32 keysym = mac_special_keysym(event.keyCode, (mods & PLATFORM_MOD_SHIFT) != 0); if(!keysym) { NSString *base = event.charactersIgnoringModifiers; if(base.length > 0) { u32 codepoint = [base characterAtIndex:0]; if(base.length > 1 && codepoint >= 0xD800 && codepoint < 0xDC00) { codepoint = 0x10000 + ((codepoint - 0xD800) << 10) + ([base characterAtIndex:1] - 0xDC00); } if(codepoint >= 0x20 && codepoint != 0x7f && !(codepoint >= 0xF700 && codepoint <= 0xF8FF)) { keysym = (codepoint < 0x100) ? codepoint : (0x01000000u | codepoint); } } } if(keysym && input->key_count < PLATFORM_MAX_KEY_EVENTS) { PlatformKeyEvent *key = &input->keys[input->key_count++]; key->keysym = keysym; key->mods = mods; key->repeat = event.isARepeat; } // NOTE: cmd / ctrl chords are commands. option still types (layout dependent @, [, ~, ...) if(!(event.modifierFlags & (NSEventModifierFlagCommand | NSEventModifierFlagControl))) { mac_append_utf8(input, event.characters); } } - (void)keyUp:(NSEvent *)event { if(!mac_state) return; mac_state->input.mods = mac_mods(event.modifierFlags); mac_state->input.changed = true; } - (void)flagsChanged:(NSEvent *)event { if(!mac_state) return; mac_state->input.mods = mac_mods(event.modifierFlags); mac_state->input.changed = true; } // NOTE: let cmd+key reach keyDown unless the menu (cmd+q, cmd+h, cmd+m) claims it - (BOOL)performKeyEquivalent:(NSEvent *)event { if(event.type != NSEventTypeKeyDown || !(event.modifierFlags & (NSEventModifierFlagCommand | NSEventModifierFlagControl))) return NO; if([[NSApp mainMenu] performKeyEquivalent:event]) return YES; [self keyDown:event]; return YES; } //- drag and drop - (NSDragOperation)draggingEntered:(id)sender { NSDictionary *options = @{NSPasteboardURLReadingFileURLsOnlyKey : @YES}; BOOL files = [sender.draggingPasteboard canReadObjectForClasses:@[ [NSURL class] ] options:options]; return files ? NSDragOperationCopy : NSDragOperationNone; } - (BOOL)performDragOperation:(id)sender { NSDictionary *options = @{NSPasteboardURLReadingFileURLsOnlyKey : @YES}; NSArray *urls = [sender.draggingPasteboard readObjectsForClasses:@[ [NSURL class] ] options:options]; if(!mac_state || urls.count == 0) return NO; NSPoint point = [self convertPoint:sender.draggingLocation fromView:nil]; mac_state->input.drop_x = (f32)point.x; mac_state->input.drop_y = (f32)point.y; for(NSURL *url in urls) mac_queue_path(url.fileSystemRepresentation); [self.window makeKeyAndOrderFront:nil]; [NSApp activateIgnoringOtherApps:YES]; return YES; } @end //- window delegate: size, scale, close, focus, live resize @interface DesignWindowDelegate : NSObject @property(nonatomic, weak) DesignView *view; @end internal void mac_update_size(DesignView *view) { if(!mac_state || !view) return; NSRect bounds = view.bounds; u32 scale = (u32)(view.window.backingScaleFactor + 0.5); if(scale == 0) scale = 1; u32 width = (u32)bounds.size.width; u32 height = (u32)bounds.size.height; CAMetalLayer *layer = (CAMetalLayer *)view.layer; layer.contentsScale = (CGFloat)scale; layer.drawableSize = CGSizeMake((CGFloat)(width * scale), (CGFloat)(height * scale)); if(width != mac_state->width || height != mac_state->height || scale != mac_state->scale) { mac_state->width = width; mac_state->height = height; mac_state->scale = scale; mac_state->resized = true; } mac_state->input.changed = true; } @implementation DesignWindowDelegate - (BOOL)windowShouldClose:(NSWindow *)sender { if(mac_state) { mac_state->should_close = true; mac_state->input.changed = true; } return NO; } - (void)windowDidResize:(NSNotification *)notification { mac_update_size(self.view); if(mac_state) mac_state->maximized = [(NSWindow *)notification.object isZoomed]; // NOTE: inside the live resize loop app_run is blocked in the pump, draw from here if(mac_state && mac_state->refresh && self.view.inLiveResize) mac_state->refresh(mac_state->refresh_user); } - (void)windowDidChangeBackingProperties:(NSNotification *)notification { mac_update_size(self.view); } - (void)windowDidMiniaturize:(NSNotification *)notification { if(mac_state) mac_state->suspended = true; } - (void)windowDidDeminiaturize:(NSNotification *)notification { if(mac_state) { mac_state->suspended = false; mac_state->input.changed = true; } } - (void)windowDidChangeOcclusionState:(NSNotification *)notification { if(!mac_state) return; mac_state->suspended = !([(NSWindow *)notification.object occlusionState] & NSWindowOcclusionStateVisible); mac_state->input.changed = true; } - (void)windowDidBecomeKey:(NSNotification *)notification { if(!mac_state) return; mac_state->input.focused = true; mac_state->input.changed = true; } - (void)windowDidResignKey:(NSNotification *)notification { if(!mac_state) return; mac_state->input.focused = false; mac_state->input.mods = 0; mac_state->input.changed = true; } @end //- application delegate: finder / dock opens, quit @interface DesignAppDelegate : NSObject @end @implementation DesignAppDelegate - (void)application:(NSApplication *)application openURLs:(NSArray *)urls { for(NSURL *url in urls) if(url.isFileURL) mac_queue_path(url.fileSystemRepresentation); } - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender { // NOTE: cmd+q / dock quit: let the main loop save state and exit on its own if(mac_state) { mac_state->should_close = true; mac_state->input.changed = true; return NSTerminateCancel; } return NSTerminateNow; } - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender { return NO; } @end //- globals global_variable NSWindow *mac_window; global_variable DesignView *mac_view; global_variable DesignWindowDelegate *mac_window_delegate; global_variable DesignAppDelegate *mac_app_delegate; global_variable NSCursor *mac_cursors[8]; // NOTE: wake fd / hot reload fd: dispatch sources on the main queue post an empty event so // nextEventMatchingMask returns. suspended after firing, resumed on the next pump, so a readable // fd that nobody drained yet doesn't spin. typedef struct MacFdWatch MacFdWatch; struct MacFdWatch { int fd; dispatch_source_t source; b32 suspended; b32 fired; }; global_variable MacFdWatch mac_fd_watches[4]; internal void mac_post_wakeup(void) { NSEvent *event = [NSEvent otherEventWithType:NSEventTypeApplicationDefined location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 context:nil subtype:0 data1:0 data2:0]; [NSApp postEvent:event atStart:NO]; } internal MacFdWatch *mac_watch_fd(int fd) { for(u32 index = 0; index < ArrayCount(mac_fd_watches); ++index) { if(mac_fd_watches[index].source && mac_fd_watches[index].fd == fd) return &mac_fd_watches[index]; } for(u32 index = 0; index < ArrayCount(mac_fd_watches); ++index) { MacFdWatch *watch = &mac_fd_watches[index]; if(watch->source) continue; watch->fd = fd; watch->source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, (uintptr_t)fd, 0, dispatch_get_main_queue()); dispatch_source_set_event_handler(watch->source, ^{ watch->fired = true; if(!watch->suspended) { watch->suspended = true; dispatch_suspend(watch->source); } mac_post_wakeup(); }); dispatch_resume(watch->source); return watch; } return NULL; } internal void mac_build_menu(const char *name) { NSMenu *bar = [[NSMenu alloc] init]; NSMenuItem *app_item = [[NSMenuItem alloc] init]; [bar addItem:app_item]; NSMenu *app_menu = [[NSMenu alloc] init]; NSString *title = [NSString stringWithUTF8String:name]; [app_menu addItemWithTitle:[@"Hide " stringByAppendingString:title] action:@selector(hide:) keyEquivalent:@"h"]; [app_menu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@"m"]; [app_menu addItem:[NSMenuItem separatorItem]]; [app_menu addItemWithTitle:[@"Quit " stringByAppendingString:title] action:@selector(terminate:) keyEquivalent:@"q"]; app_item.submenu = app_menu; NSApp.mainMenu = bar; } //- public api extern "C" void macos_show_error(const char *title, const char *message) { fprintf(stderr, "%s: %s\n", title, message); @autoreleasepool { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; [NSApp activateIgnoringOtherApps:YES]; NSAlert *alert = [[NSAlert alloc] init]; alert.alertStyle = NSAlertStyleCritical; alert.messageText = [NSString stringWithUTF8String:title]; alert.informativeText = [NSString stringWithUTF8String:message]; [alert runModal]; } } extern "C" b32 macos_window_open(PlatformWindow *window, WindowParams params) { MacWindowState *state = &window->mac; @autoreleasepool { [NSApplication sharedApplication]; // NOTE: a bare executable (no .app) is a background process until it says otherwise [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; mac_app_delegate = [[DesignAppDelegate alloc] init]; NSApp.delegate = mac_app_delegate; mac_build_menu(params.title ? params.title : params.name); [NSApp finishLaunching]; state->width = params.width ? params.width : 960; state->height = params.height ? params.height : 600; state->scale = 1; state->is_layer = params.layer; NSScreen *screen = [NSScreen mainScreen]; NSRect visible = screen ? screen.visibleFrame : NSMakeRect(0, 0, 1440, 900); NSRect frame = NSMakeRect(0, 0, state->width, state->height); NSWindowStyleMask style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable; if(state->is_layer) { // NOTE: overlay: borderless, floating, anchored to the visible frame (cocoa is y up) style = NSWindowStyleMaskBorderless | NSWindowStyleMaskResizable; CGFloat m = (CGFloat)params.margin; b32 left = (params.anchor & PLATFORM_ANCHOR_LEFT) != 0, right = (params.anchor & PLATFORM_ANCHOR_RIGHT) != 0; b32 top = (params.anchor & PLATFORM_ANCHOR_TOP) != 0, bottom = (params.anchor & PLATFORM_ANCHOR_BOTTOM) != 0; if(left && right) { frame.origin.x = visible.origin.x + m; frame.size.width = visible.size.width - 2 * m; } else if(left) { frame.origin.x = visible.origin.x + m; } else if(right) { frame.origin.x = NSMaxX(visible) - m - frame.size.width; } else { frame.origin.x = NSMidX(visible) - frame.size.width / 2; } if(top && bottom) { frame.origin.y = visible.origin.y + m; frame.size.height = visible.size.height - 2 * m; } else if(top) { frame.origin.y = NSMaxY(visible) - m - frame.size.height; } else if(bottom) { frame.origin.y = visible.origin.y + m; } else { frame.origin.y = NSMidY(visible) - frame.size.height / 2; } } mac_window = [[NSWindow alloc] initWithContentRect:frame styleMask:style backing:NSBackingStoreBuffered defer:NO]; if(!mac_window) return false; mac_window.releasedWhenClosed = NO; mac_window.title = [NSString stringWithUTF8String:params.title ? params.title : params.name]; mac_window.acceptsMouseMovedEvents = YES; if(params.min_width && params.min_height) mac_window.contentMinSize = NSMakeSize(params.min_width, params.min_height); if(state->is_layer) { mac_window.level = NSFloatingWindowLevel; mac_window.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces; } else { [mac_window center]; mac_window.tabbingMode = NSWindowTabbingModeDisallowed; } // NOTE: dark title bar, matches the default scheme mac_window.appearance = [NSAppearance appearanceNamed:NSAppearanceNameDarkAqua]; mac_view = [[DesignView alloc] initWithFrame:NSMakeRect(0, 0, frame.size.width, frame.size.height)]; mac_view.wantsLayer = YES; mac_view.layerContentsRedrawPolicy = NSViewLayerContentsRedrawDuringViewResize; [mac_view registerForDraggedTypes:@[ NSPasteboardTypeFileURL ]]; mac_window.contentView = mac_view; mac_window_delegate = [[DesignWindowDelegate alloc] init]; mac_window_delegate.view = mac_view; mac_window.delegate = mac_window_delegate; state->metal_layer = (__bridge void *)mac_view.layer; mac_cursors[PLATFORM_CURSOR_DEFAULT] = [NSCursor arrowCursor]; mac_cursors[PLATFORM_CURSOR_POINTER] = [NSCursor pointingHandCursor]; mac_cursors[PLATFORM_CURSOR_GRABBING] = [NSCursor closedHandCursor]; mac_cursors[PLATFORM_CURSOR_RESIZE_X] = [NSCursor resizeLeftRightCursor]; mac_cursors[PLATFORM_CURSOR_RESIZE_Y] = [NSCursor resizeUpDownCursor]; mac_cursors[PLATFORM_CURSOR_CROSSHAIR] = [NSCursor crosshairCursor]; mac_cursors[PLATFORM_CURSOR_MOVE] = [NSCursor openHandCursor]; // NOTE: no public diagonal resize cursor before macos 15, the private one exists since 10.x SEL diagonal = NSSelectorFromString(@"_windowResizeNorthWestSouthEastCursor"); mac_cursors[PLATFORM_CURSOR_RESIZE_NWSE] = [NSCursor respondsToSelector:diagonal] ? ((NSCursor * (*)(id, SEL))[NSCursor methodForSelector:diagonal])([NSCursor class], diagonal) : [NSCursor crosshairCursor]; mac_state = state; for(u32 index = 0; index < mac_pending_count; ++index) mac_queue_path(mac_pending_paths[index]); mac_pending_count = 0; [mac_window makeKeyAndOrderFront:nil]; [mac_window makeFirstResponder:mac_view]; [NSApp activateIgnoringOtherApps:YES]; mac_update_size(mac_view); state->resized = false; state->input.focused = mac_window.isKeyWindow; state->input.changed = true; } return true; } extern "C" b32 macos_window_pump(PlatformWindow *window, PlatformInput *input, s64 timeout_ns, int *extra_fds, u32 extra_count, u32 *ready_mask) { MacWindowState *state = &window->mac; if(ready_mask) *ready_mask = 0; @autoreleasepool { u32 watched[4] = {}; for(u32 index = 0; index < extra_count && index < ArrayCount(watched); ++index) { if(extra_fds[index] < 0) continue; MacFdWatch *watch = mac_watch_fd(extra_fds[index]); if(!watch) continue; watch->fired = false; if(watch->suspended) { watch->suspended = false; dispatch_resume(watch->source); } watched[index] = (u32)(watch - mac_fd_watches) + 1; } NSDate *until = (timeout_ns < 0) ? [NSDate distantFuture] : (timeout_ns == 0) ? [NSDate distantPast] : [NSDate dateWithTimeIntervalSinceNow:(f64)timeout_ns / 1e9]; NSEvent *event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:until inMode:NSDefaultRunLoopMode dequeue:YES]; while(event) { if(event.type != NSEventTypeApplicationDefined) [NSApp sendEvent:event]; event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES]; } if(ready_mask) { for(u32 index = 0; index < ArrayCount(watched); ++index) { if(watched[index] && mac_fd_watches[watched[index] - 1].fired) *ready_mask |= 1u << index; } } } *input = state->input; for(u32 index = 0; index < 3; ++index) state->input.mouse[index].half_transition_count = 0; state->input.key_count = 0; state->input.text_size = 0; state->input.scroll_x = 0; state->input.scroll_y = 0; state->input.drop_count = 0; state->input.changed = false; return !state->should_close; } extern "C" void macos_window_begin_move(PlatformWindow *window) { if(!mac_window || window->mac.is_layer || !mac_view.lastMouseDown) return; // NOTE: runs the window server drag until the button comes up, which then never reaches us [mac_window performWindowDragWithEvent:mac_view.lastMouseDown]; mac_button_update(&window->mac.input.mouse[0], false); } extern "C" void macos_window_toggle_maximized(PlatformWindow *window) { if(mac_window && !window->mac.is_layer) [mac_window zoom:nil]; } // NOTE: window == NULL re-applies the current cursor (cursorUpdate) extern "C" void macos_window_set_cursor(PlatformWindow *window, u32 cursor) { if(!mac_state) return; if(window) { if(mac_state->cursor == cursor || cursor >= ArrayCount(mac_cursors)) return; mac_state->cursor = cursor; } NSCursor *shape = mac_cursors[mac_state->cursor < ArrayCount(mac_cursors) ? mac_state->cursor : 0]; if(shape && mac_state->input.mouse_in_window) [shape set]; } extern "C" void macos_window_close(PlatformWindow *window) { @autoreleasepool { mac_state = NULL; for(u32 index = 0; index < ArrayCount(mac_fd_watches); ++index) { MacFdWatch *watch = &mac_fd_watches[index]; if(!watch->source) continue; if(watch->suspended) dispatch_resume(watch->source); dispatch_source_cancel(watch->source); watch->source = nil; } if(mac_window) { mac_window.delegate = nil; [mac_window close]; } mac_window = nil; mac_view = nil; } }