From 3851a6e0b01585feea9ad0ea58b1bf1fae8ed1fa Mon Sep 17 00:00:00 2001 From: Peter Li Date: Sun, 27 Sep 2026 17:43:27 -0700 Subject: [PATCH] macos argv --- README.md | 9 +++ build.zig | 1 + src/macos/native.m | 152 +++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 158 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 1c523e5..fdc950d 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,10 @@ and handles presentation at the frame boundary. All services accept that same session handle. Additional native windows can be created synchronously between iterations for external rendering; they do not have independent UHDK GL contexts. +On macOS, UHDK disables AppKit's conversion of command-line arguments into +`UHDK_EVENT_OPEN_FILES` by default. Applications handle their own arguments; +document-open requests from Finder and the Dock still arrive as events. + ## Tray icons Create a session-owned `uhdk_tray` with `uhdk_tray_create`, replace its complete @@ -242,6 +246,11 @@ The first iteration never waits. Session GL calls are valid before, during and after iterations until close; drawing to the window is conditional on `drawable`. A fatal native/driver error may prevent further GL work, including cleanup. +On macOS, vsync waits for a per-window CoreVideo display link before presenting, +with the native OpenGL swap interval disabled. The link follows the window's +display. Each wait is bounded to 100 ms so a sleeping display cannot indefinitely +block the frame loop; disabling vsync bypasses the wait. + Accept close/quit requests with `uhdk_quit`. Keep iterating to drain request completions and `STOPPED`; then `next_frame` returns false and `get_status` returns OK. Failures also end the loop, with a non-OK status. An early `close` abandons diff --git a/build.zig b/build.zig index 5b0e3da..d643169 100644 --- a/build.zig +++ b/build.zig @@ -98,6 +98,7 @@ fn createLibraryNamed(b: *std.Build, target: std.Build.ResolvedTarget, optimize: module.linkFramework("Cocoa", .{}); module.linkFramework("OpenGL", .{}); module.linkFramework("CoreServices", .{}); + module.linkFramework("CoreVideo", .{}); } else if (target.result.os.tag == .linux) { @import("src/linux/build.zig").configure(b, module, target, optimize); } else { diff --git a/src/macos/native.m b/src/macos/native.m index 7f81d19..2a78088 100644 --- a/src/macos/native.m +++ b/src/macos/native.m @@ -1,5 +1,6 @@ #import #import +#import #import #include #include @@ -7,6 +8,7 @@ #include #include #include +#include #include "native.h" static NSString *str(uhdk_text t) { @@ -53,9 +55,23 @@ static uhdk_modifier_flags mods(NSEventModifierFlags f) { - (void)invoke:(id)sender; - (void)refreshMenu; @end -@interface ZGL : NSObject +typedef struct ZDisplayPacer { + pthread_mutex_t mutex; + pthread_cond_t condition; + uint64_t tick; +} ZDisplayPacer; +@interface ZGL : NSObject { + ZDisplayPacer *_pacer; + uhdk_status _displayLinkStatus; +} @property(nonatomic, strong) NSOpenGLContext *context; @property(nonatomic, weak) ZWindow *owner; +@property(nonatomic) CVDisplayLinkRef displayLink; +@property(nonatomic) GLint swapInterval; +- (uhdk_status)startDisplayLink; +- (void)updateDisplayLink; +- (void)stopDisplayLink; +- (uhdk_status)waitForRefresh; @end @interface ZWindow : NSObject @property(nonatomic) uhdk_window *handle; @@ -190,7 +206,113 @@ static uhdk_key logical(NSEvent *e) { return CFStringGetLongCharacterForSurrogatePair(hi, [s characterAtIndex:1]); return hi; } +static CVReturn displayLinkTick( + CVDisplayLinkRef link, + const CVTimeStamp *now, + const CVTimeStamp *output, + CVOptionFlags flags, + CVOptionFlags *outFlags, + void *user +) { + (void)link; + (void)now; + (void)output; + (void)flags; + (void)outFlags; + // No AppKit, GL calls, or Objective-C ownership on the display-link thread. + ZDisplayPacer *pacer = user; + pthread_mutex_lock(&pacer->mutex); + ++pacer->tick; + pthread_cond_signal(&pacer->condition); + pthread_mutex_unlock(&pacer->mutex); + return kCVReturnSuccess; +} @implementation ZGL +- (uhdk_status)startDisplayLink { + ZDisplayPacer *pacer = calloc(1, sizeof(*pacer)); + if (!pacer) + return UHDK_STATUS_OUT_OF_MEMORY; + if (pthread_mutex_init(&pacer->mutex, NULL) != 0) { + free(pacer); + return UHDK_STATUS_OS_ERROR; + } + if (pthread_cond_init(&pacer->condition, NULL) != 0) { + pthread_mutex_destroy(&pacer->mutex); + free(pacer); + return UHDK_STATUS_OS_ERROR; + } + _pacer = pacer; + // A main-run-loop display link would require pumping events inside a frame. + if (CVDisplayLinkCreateWithActiveCGDisplays(&_displayLink) != kCVReturnSuccess || + CVDisplayLinkSetOutputCallback(_displayLink, displayLinkTick, _pacer) != kCVReturnSuccess) + return UHDK_STATUS_OS_ERROR; + [self updateDisplayLink]; + if (_displayLinkStatus != UHDK_STATUS_OK || + CVDisplayLinkStart(_displayLink) != kCVReturnSuccess) + return UHDK_STATUS_OS_ERROR; + return UHDK_STATUS_OK; +} +- (void)updateDisplayLink { + if (!_displayLink) + return; + NSScreen *screen = self.owner.window.screen; + CGDirectDisplayID display = + screen ? [screen.deviceDescription[@"NSScreenNumber"] unsignedIntValue] : CGMainDisplayID(); + if (display == CVDisplayLinkGetCurrentCGDisplay(_displayLink)) { + _displayLinkStatus = UHDK_STATUS_OK; + return; + } + _displayLinkStatus = CVDisplayLinkSetCurrentCGDisplay(_displayLink, display) == kCVReturnSuccess + ? UHDK_STATUS_OK + : UHDK_STATUS_OS_ERROR; +} +- (uhdk_status)waitForRefresh { + if (!self.swapInterval) + return UHDK_STATUS_OK; + if (_displayLinkStatus != UHDK_STATUS_OK) + return _displayLinkStatus; + // Use one monotonic deadline so spurious wakeups cannot extend the timeout. + // A sleeping/disconnected display must not leave the main thread blocked. + int64_t deadline = z_io_now(1) + INT64_C(100000000); + pthread_mutex_lock(&_pacer->mutex); + uint64_t tick = _pacer->tick; + uhdk_status status = UHDK_STATUS_OK; + while (_pacer->tick == tick) { + int64_t remaining = deadline - z_io_now(1); + if (remaining <= 0) + break; + struct timespec timeout = { + remaining / INT64_C(1000000000), remaining % INT64_C(1000000000) + }; + int error = + pthread_cond_timedwait_relative_np(&_pacer->condition, &_pacer->mutex, &timeout); + if (error == ETIMEDOUT) + break; + if (error != 0) { + status = UHDK_STATUS_OS_ERROR; + break; + } + } + pthread_mutex_unlock(&_pacer->mutex); + return status; +} +- (void)stopDisplayLink { + // Stop without holding the callback's mutex, before freeing its userdata. + if (_displayLink) { + CVDisplayLinkStop(_displayLink); + CVDisplayLinkRelease(_displayLink); + _displayLink = NULL; + } + if (_pacer) { + pthread_cond_destroy(&_pacer->condition); + pthread_mutex_destroy(&_pacer->mutex); + free(_pacer); + _pacer = NULL; + } +} +- (void)dealloc { + [self stopDisplayLink]; +} @end @implementation ZView - (instancetype)initWithFrame:(NSRect)frame { @@ -763,6 +885,7 @@ static uhdk_key logical(NSEvent *e) { CGLLockContext(gl); [self.gl.context update]; CGLUnlockContext(gl); + [self.gl updateDisplayLink]; } NSRect bounds = self.view.bounds, pixels = [self.view convertRectToBacking:bounds]; uhdk_window_metrics m = { @@ -804,6 +927,10 @@ static uhdk_key logical(NSEvent *e) { (void)n; [self metrics]; } +- (void)windowDidChangeScreen:(NSNotification *)n { + (void)n; + [self metrics]; +} - (void)windowDidBecomeKey:(NSNotification *)n { (void)n; [host refreshMenus]; @@ -1356,6 +1483,10 @@ uhdk_status z_native_start(uhdk_session *app, uhdk_text name) { }]]; [NSApp addObserver:host forKeyPath:@"effectiveAppearance" options:0 context:NULL]; [host preferences]; + // Prevent AppKit from interpreting process arguments as document-open requests. + [NSUserDefaults.standardUserDefaults registerDefaults:@{ + @"NSTreatUnknownArgumentsAsOpen" : @NO + }]; [NSApp finishLaunching]; return UHDK_STATUS_OK; } @@ -1477,6 +1608,7 @@ void z_native_destroy(uint32_t kind, void *native) { ZGL *gl = w.gl; if (!gl) return; + [gl stopDisplayLink]; CGLLockContext(gl.context.CGLContextObj); [gl.context clearDrawable]; CGLUnlockContext(gl.context.CGLContextObj); @@ -1604,6 +1736,8 @@ uhdk_status z_native_execute( if (!format) return UHDK_STATUS_UNSUPPORTED; ZGL *gl = [ZGL new]; + if (!gl) + return UHDK_STATUS_OUT_OF_MEMORY; gl.context = [[NSOpenGLContext alloc] initWithFormat:format shareContext:nil]; if (!gl.context) return UHDK_STATUS_OS_ERROR; @@ -1622,6 +1756,13 @@ uhdk_status z_native_execute( if (major < 3 || (major == 3 && minor < 3) || !(profile & GL_CONTEXT_CORE_PROFILE_BIT)) return UHDK_STATUS_UNSUPPORTED; + // Layer-backed windows do not reliably block in flushBuffer. + // Pace with the display link only; never combine two vsync waits. + GLint interval = 0; + [gl.context setValues:&interval forParameter:NSOpenGLContextParameterSwapInterval]; + uhdk_status status = [gl startDisplayLink]; + if (status != UHDK_STATUS_OK) + return status; w.gl = gl; [w metrics]; break; @@ -1860,10 +2001,13 @@ uhdk_status z_native_gl(void *native, uint32_t op, void *out) { } if (NSOpenGLContext.currentContext != gl.context) return UHDK_STATUS_UNAVAILABLE; - if (op == 6) + if (op == 6) { + uhdk_status status = [gl waitForRefresh]; + if (status != UHDK_STATUS_OK) + return status; [gl.context flushBuffer]; - else if (op == 7) - [gl.context setValues:out forParameter:NSOpenGLContextParameterSwapInterval]; + } else if (op == 7) + gl.swapInterval = *(GLint *)out; else return UHDK_STATUS_INVALID_ARGUMENT; return UHDK_STATUS_OK;