import ApplicationServices import Foundation import ParcelCore import ParcelPlatform struct NativeRaiseReadback: Sendable { let foregroundPID: Int32? let focusedWindow: WindowID? let frontWindow: WindowID? func alreadyPresented(_ window: WindowID, in app: AppID) -> Bool { foregroundPID == app.pid && focusedWindow == window && frontWindow == window } } @MainActor enum NativeRaiseVerification { static func perform( window: WindowID, app: AppID, timeout: Double = 0.25, read: () async throws -> NativeRaiseReadback, raise: () async throws -> Void, now: () -> Double = { ProcessInfo.processInfo.systemUptime }, wait: () async throws -> Void = { try await Task.sleep(for: .milliseconds(10)) } ) async throws { try Task.checkCancellation() if try await read().alreadyPresented(window, in: app) { return } do { try await raise() } catch let failure as AXPlatformError where failure == .attributeUnsupported || failure == .other(AXError.actionUnsupported.rawValue) { // A focus effect can finish while an app rejects the redundant raise action. let deadline = now() + timeout repeat { try Task.checkCancellation() if try await read().alreadyPresented(window, in: app) { return } guard now() < deadline else { throw failure } try await wait() } while true } } }