Skip to content

Commit 1e6fdbf

Browse files
committed
gg: fix screen_size() on macos with multiple displays
1 parent 071ab6c commit 1e6fdbf

1 file changed

Lines changed: 36 additions & 4 deletions

File tree

‎vlib/gg/gg_darwin.m‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,43 @@
1515
}
1616

1717
gg__Size gg_get_screen_size() {
18-
NSScreen* screen = [NSScreen mainScreen];
19-
NSDictionary* description = [screen deviceDescription];
18+
NSScreen *currentScreen = nil;
19+
NSWindow *mainWindow = [NSApp mainWindow];
20+
// 1. Try screen containing the main window
21+
if (mainWindow) {
22+
currentScreen = [mainWindow screen];
23+
}
24+
// 2. If no main window, try the key window (might be different, e.g., a panel)
25+
if (!currentScreen) {
26+
NSWindow *keyWindow = [NSApp keyWindow];
27+
if (keyWindow) {
28+
currentScreen = [keyWindow screen];
29+
}
30+
}
31+
// 3. If no relevant window, find the screen containing the mouse cursor
32+
if (!currentScreen) {
33+
// Get mouse location in global screen coordinates (bottom-left origin)
34+
NSPoint mouseLocation = [NSEvent mouseLocation];
35+
NSArray<NSScreen *> *screens = [NSScreen screens];
36+
for (NSScreen *screen in screens) {
37+
// Check if the mouse location is within the screen's frame
38+
// Note: Both mouseLocation and screen.frame use bottom-left origin coordinates
39+
if (NSMouseInRect(mouseLocation, [screen frame], NO)) {
40+
currentScreen = screen;
41+
break; // Found the screen with the mouse
42+
}
43+
}
44+
}
45+
// 4. As a last resort, fall back to the main screen
46+
if (!currentScreen) {
47+
NSLog(@"Warning: Could not determine current screen based on window or mouse. Falling back to mainScreen.");
48+
currentScreen = [NSScreen mainScreen];
49+
}
50+
// Now get the size of the determined screen
51+
NSDictionary *description = [currentScreen deviceDescription];
52+
// Use NSDeviceSize to get pixel dimensions
2053
NSSize displayPixelSize = [[description objectForKey:NSDeviceSize] sizeValue];
21-
CGSize displayPhysicalSize =
22-
CGDisplayScreenSize([[description objectForKey:@"NSScreenNumber"] unsignedIntValue]);
54+
// Create the V gg.Size object
2355
gg__Size res;
2456
res.width = displayPixelSize.width;
2557
res.height = displayPixelSize.height;

0 commit comments

Comments
 (0)