diff --git a/alt-tab-macos/api-wrappers/AXUIElement.swift b/alt-tab-macos/api-wrappers/AXUIElement.swift index e27bc07c..13c1f696 100644 --- a/alt-tab-macos/api-wrappers/AXUIElement.swift +++ b/alt-tab-macos/api-wrappers/AXUIElement.swift @@ -50,6 +50,15 @@ extension AXUIElement { return attribute(kAXSubroleAttribute, String.self) } + func subscribeWithRetry(_ axObserver: AXObserver, _ notification: String, _ pointer: UnsafeMutableRawPointer?) { + let result = AXObserverAddNotification(axObserver, self, notification as CFString, pointer) + if result != .success && result != .notificationUnsupported && result != .notificationAlreadyRegistered { + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(10), execute: { + self.subscribeWithRetry(axObserver, notification, pointer) + }) + } + } + private func attribute(_ key: String, _ type: T.Type) -> T? { var value: AnyObject? let result = AXUIElementCopyAttributeValue(self, key as CFString, &value) diff --git a/alt-tab-macos/logic/Application.swift b/alt-tab-macos/logic/Application.swift index 06e108d5..5f06dca1 100644 --- a/alt-tab-macos/logic/Application.swift +++ b/alt-tab-macos/logic/Application.swift @@ -30,7 +30,7 @@ class Application: NSObject { let windows = getActualWindows() debugPrint("Adding app: " + (runningApplication.bundleIdentifier ?? "nil"), windows.map { $0.title() }) addWindows(windows) - observeEvents(windows) + observeEvents() } func observeNewWindows() { @@ -56,7 +56,7 @@ class Application: NSObject { Windows.list.insert(contentsOf: windows.map { Window($0, self) }, at: 0) } - private func observeEvents(_ windows: [AXUIElement]) { + private func observeEvents() { guard let axObserver = axObserver else { return } let selfPointer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) for notification in [ @@ -66,7 +66,7 @@ class Application: NSObject { kAXApplicationHiddenNotification, kAXApplicationShownNotification, ] { - AXObserverAddNotification(axObserver, axUiElement!, notification as CFString, selfPointer) + axUiElement!.subscribeWithRetry(axObserver, notification, selfPointer) } CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(axObserver), .defaultMode) } diff --git a/alt-tab-macos/logic/Window.swift b/alt-tab-macos/logic/Window.swift index 2ab76b14..e6d4edd4 100644 --- a/alt-tab-macos/logic/Window.swift +++ b/alt-tab-macos/logic/Window.swift @@ -40,7 +40,7 @@ class Window { kAXWindowMiniaturizedNotification, kAXWindowDeminiaturizedNotification, ] { - AXObserverAddNotification(axObserver, axUiElement, notification as CFString, nil) + axUiElement.subscribeWithRetry(axObserver, notification, nil) } CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(axObserver), .defaultMode) }