Skip to content

Commit 95bf390

Browse files
committed
Share kWindowIdKey and improve window retrieval on macOS
Moves kWindowIdKey to global scope for use across window_macos.mm and window_manager_macos.mm. Enhances WindowManager::GetCurrent to check for existing window IDs via associated objects and registry before creating new Window wrappers, reducing duplicate instances.
1 parent 09ca5f5 commit 95bf390

File tree

2 files changed

+20
-11
lines changed

2 files changed

+20
-11
lines changed

src/platform/macos/window_macos.mm

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
#import <Cocoa/Cocoa.h>
1010
#import <objc/runtime.h>
1111

12-
// Static key for associated objects
13-
static const void* kWindowIdKey = &kWindowIdKey;
12+
// Key for associated objects (used by both window_macos.mm and window_manager_macos.mm)
13+
const void* kWindowIdKey = &kWindowIdKey;
1414

1515
namespace nativeapi {
1616

@@ -323,9 +323,6 @@
323323
}
324324

325325
void Window::Center() {
326-
if (!pimpl_->ns_window_)
327-
return;
328-
329326
// Use NSWindow's center method which automatically centers on the main screen
330327
[pimpl_->ns_window_ center];
331328
}

src/platform/macos/window_manager_macos.mm

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
// Forward declaration for the delegate
1212
@class NativeAPIWindowManagerDelegate;
1313

14+
// External declaration of kWindowIdKey (defined in window_macos.mm)
15+
extern const void* kWindowIdKey;
16+
1417
namespace nativeapi {
1518

1619
// Private implementation to hide Objective-C details
@@ -301,15 +304,24 @@ - (void)windowWillClose:(NSNotification*)notification {
301304
ns_window = [ns_windows objectAtIndex:0];
302305
}
303306
if (ns_window != nil) {
304-
// Create or get Window wrapper - this will handle ID retrieval via associated object
307+
// First, try to get the window ID from the associated object
308+
NSNumber* existingIdNumber = objc_getAssociatedObject(ns_window, kWindowIdKey);
309+
if (existingIdNumber) {
310+
WindowId window_id = [existingIdNumber unsignedLongLongValue];
311+
312+
// Try to get the existing Window from registry
313+
auto existing_window = WindowRegistry::GetInstance().Get(window_id);
314+
if (existing_window) {
315+
return existing_window;
316+
}
317+
}
318+
319+
// If not found in registry, create a new Window wrapper
305320
auto window = std::make_shared<Window>((__bridge void*)ns_window);
306321
WindowId window_id = window->GetId();
307322

308-
// Ensure it's in the registry
309-
if (!WindowRegistry::GetInstance().Get(window_id)) {
310-
WindowRegistry::GetInstance().Add(window_id, window);
311-
}
312-
323+
// Add to registry (temporary solution)
324+
WindowRegistry::GetInstance().Add(window_id, window);
313325
return window;
314326
}
315327
return nullptr;

0 commit comments

Comments
 (0)