From 1e6fdbf815842d71fd6520fa327cb24e3f6dc8b7 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Mon, 7 Apr 2025 04:18:18 +0300 Subject: [PATCH] gg: fix screen_size() on macos with multiple displays --- vlib/gg/gg_darwin.m | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/vlib/gg/gg_darwin.m b/vlib/gg/gg_darwin.m index 9ad725daf0..7ac401c8bc 100644 --- a/vlib/gg/gg_darwin.m +++ b/vlib/gg/gg_darwin.m @@ -15,11 +15,43 @@ NSString* nsstring(string s) { } gg__Size gg_get_screen_size() { - NSScreen* screen = [NSScreen mainScreen]; - NSDictionary* description = [screen deviceDescription]; + NSScreen *currentScreen = nil; + NSWindow *mainWindow = [NSApp mainWindow]; + // 1. Try screen containing the main window + if (mainWindow) { + currentScreen = [mainWindow screen]; + } + // 2. If no main window, try the key window (might be different, e.g., a panel) + if (!currentScreen) { + NSWindow *keyWindow = [NSApp keyWindow]; + if (keyWindow) { + currentScreen = [keyWindow screen]; + } + } + // 3. If no relevant window, find the screen containing the mouse cursor + if (!currentScreen) { + // Get mouse location in global screen coordinates (bottom-left origin) + NSPoint mouseLocation = [NSEvent mouseLocation]; + NSArray *screens = [NSScreen screens]; + for (NSScreen *screen in screens) { + // Check if the mouse location is within the screen's frame + // Note: Both mouseLocation and screen.frame use bottom-left origin coordinates + if (NSMouseInRect(mouseLocation, [screen frame], NO)) { + currentScreen = screen; + break; // Found the screen with the mouse + } + } + } + // 4. As a last resort, fall back to the main screen + if (!currentScreen) { + NSLog(@"Warning: Could not determine current screen based on window or mouse. Falling back to mainScreen."); + currentScreen = [NSScreen mainScreen]; + } + // Now get the size of the determined screen + NSDictionary *description = [currentScreen deviceDescription]; + // Use NSDeviceSize to get pixel dimensions NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue]; - CGSize displayPhysicalSize = - CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]); + // Create the V gg.Size object gg__Size res; res.width = displayPixelSize.width; res.height = displayPixelSize.height;