import AppKit import ApplicationServices import ParcelCore import ParcelPlatform struct NativeApplicationInfo: Sendable { let id: AppID var isHidden: Bool = false var launchedAt: Double? var name: String = "" var launchIdentity: Date? var isRegular: Bool = true } struct NativeWindowSnapshot: Sendable { let window: ManagedWindow var frame: Rect var excluded: Bool = false var validity: AppThreadOperationValidity? = nil } struct NativeVisibleWindows: Sendable { let frames: [WindowID: Rect] let owners: [WindowID: Int32] let catalogFrames: [WindowID: Rect] let catalogOwners: [WindowID: Int32] let discoveryCandidates: Set init( frames: [WindowID: Rect], owners: [WindowID: Int32], catalogFrames: [WindowID: Rect]? = nil, catalogOwners: [WindowID: Int32]? = nil, discoveryCandidates: Set? = nil ) { self.frames = frames self.owners = owners self.catalogFrames = catalogFrames ?? frames self.catalogOwners = catalogOwners ?? owners self.discoveryCandidates = discoveryCandidates ?? Set(frames.keys) } } struct NativeWindowFrameReadbackFailure: Error, Sendable { let app: AppID let window: WindowID let cause: any Error var platformFailure: EnginePlatformFailure { if case AppThreadFailure.windowNotFound = cause { return .vanished(window) } return .unexpected(EngineUnexpectedFailure(cause: self)) } } struct NativeSpaceState: Sendable { let spaces: [DisplayID: SpaceID] let suspended: Set var snapshot: [NativeDisplaySpaces]? = nil } private actor NativeServerFacts { private var windows: [WindowServer.Window] = [] func update(_ windows: [WindowServer.Window]) { self.windows = windows } func forApp(_ pid: Int32) -> [WindowID: WindowServer.Window] { Dictionary(uniqueKeysWithValues: windows.filter { $0.pid == pid }.map { (WindowID(rawValue: $0.number), $0) }) } } enum NativeEngineEvent: Sendable { case launched(NativeApplicationInfo) case terminated(AppID) case activated(NativeApplicationInfo) case hidden(NativeApplicationInfo) case unhidden(NativeApplicationInfo) case spaceChanged case woke case displaysChanged([ParcelCore.Display]) case pointerButton(isDown: Bool) case preferencesChanged(SystemWindowPreferencesSnapshot) case failure(any Error) } @MainActor protocol NativeEngineApplication: AnyObject { var events: AsyncStream { get } func windows() async throws -> [NativeWindowSnapshot] func frame(_ window: WindowID) async throws -> Rect func acknowledgeMotion(_ window: UInt32) func focusedWindow() async throws -> WindowID? func probeResponsiveness() async throws func menuShortcuts() async throws -> [MenuShortcut] func write(_ frame: Rect, to window: WindowID) async throws -> Rect func writeFrames(_ frames: [EngineFrameWrite]) async throws -> EngineWriteReceipt func cancelFrameWrites(_ window: WindowID, throughGeneration: UInt64) async throws func finishShutdown() async throws func focus(_ window: WindowID) async throws func raise(_ window: WindowID) async throws func edited(_ window: WindowID) async throws -> Bool? func close(_ window: WindowID) async throws func restore(_ window: WindowID, validity: AppThreadOperationValidity) async throws func toggleFullscreen(_ window: WindowID) async throws func shutdown() func spaceDragWindow(_ window: WindowID) async throws -> SpaceDragWindow } extension NativeEngineApplication { func acknowledgeMotion(_ window: UInt32) {} func probeResponsiveness() async throws { _ = try await focusedWindow() } func spaceDragWindow(_ window: WindowID) async throws -> SpaceDragWindow { throw SpaceCommandError.titleBarUnavailable } } extension NativeEngineApplication { func edited(_ window: WindowID) async throws -> Bool? { nil } func close(_ window: WindowID) async throws { throw AXPlatformError.unavailable("AXCloseButton") } func restore(_ window: WindowID, validity: AppThreadOperationValidity) async throws { throw AXPlatformError.unavailable("AXMinimized") } func menuShortcuts() async throws -> [MenuShortcut] { throw EngineMenuShortcutError.unavailable } } @MainActor protocol NativeEngineBackend: AnyObject { var accessibilityPermissionGranted: Bool? { get } func start(receive: @escaping @MainActor (NativeEngineEvent) -> Void) throws func setDetectionTracing(_ source: (any DetectionTraceSource)?) func stop() func currentDisplays() throws -> [ParcelCore.Display] func focusedApplication() -> AppID? func runningApplications() -> [NativeApplicationInfo] func application(_ app: AppID) throws -> any NativeEngineApplication func visibleWindows() async throws -> NativeVisibleWindows func windowSpaces(for windows: Set) async throws -> [WindowID: Set] func currentSpaces(for displays: [DisplayID]) async throws -> NativeSpaceState func setNewWindowTarget(_ target: @escaping @Sendable (AppThreadCreatedWindow) -> CGRect?) } extension NativeEngineBackend { var accessibilityPermissionGranted: Bool? { nil } func windowSpaces(for windows: Set) async throws -> [WindowID: Set] { [:] } func setNewWindowTarget(_ target: @escaping @Sendable (AppThreadCreatedWindow) -> CGRect?) {} func setDetectionTracing(_ source: (any DetectionTraceSource)?) {} } @MainActor final class SystemNativeEngineBackend: NativeEngineBackend { var accessibilityPermissionGranted: Bool? { Permissions.accessibilityStatus() == .granted } private var displays: Displays? private let pointer = EnginePointerMonitor() private let serverFacts = NativeServerFacts() private var detectionSource: (any DetectionTraceSource)? private var newWindowTarget: (@Sendable (AppThreadCreatedWindow) -> CGRect?)? private let observationCandidates: @MainActor () -> [NativeObservationCandidate] private let readWindows: @Sendable () throws -> [WindowServer.Window] private var observationInventory = NativeObservationInventory() private var observationTask: Task? private var observationRefreshPending = false private var receive: (@MainActor (NativeEngineEvent) -> Void)? private let workspaceObserver = WorkspaceObserver() private var displayTask: Task? private var preferences: SystemWindowPreferences? private var preferenceTask: Task? private var lifetime: UInt64 = 0 private var e2eWakeObserver: (any NSObjectProtocol)? convenience init(applicationFilter: @escaping @MainActor (NSRunningApplication) -> Bool) { self.init(observationCandidates: { NSWorkspace.shared.runningApplications.compactMap { application in Self.candidate(application, applicationFilter: applicationFilter) } }) } init( observationCandidates: @escaping @MainActor () -> [NativeObservationCandidate], readWindows: @escaping @Sendable () throws -> [WindowServer.Window] = { try WindowServer().windows() } ) { self.observationCandidates = observationCandidates self.readWindows = readWindows } func start(receive: @escaping @MainActor (NativeEngineEvent) -> Void) throws { guard Permissions.accessibilityStatus() == .granted else { throw EnginePlatformFailure.permissionLost } lifetime += 1 let generation = lifetime _ = observationInventory.update( candidates: observationCandidates(), windowOwners: WindowServer.windowOwners(try readWindows())) let preferences = try SystemWindowPreferences() self.preferences = preferences self.receive = receive receive(.preferencesChanged(preferences.snapshot())) let changes = preferences.changes() preferenceTask = Task { @MainActor [weak self] in for await update in changes { guard let self, self.lifetime == generation, !Task.isCancelled else { return } self.receive?(.preferencesChanged(update)) } } try pointer.start { [weak self] isDown in receive(.pointerButton(isDown: isDown)) if !isDown { self?.requestObservationRefresh() } } workspaceObserver.start { [weak self] name, application in self?.workspaceNotification(name, application: application) } let displays = Displays() self.displays = displays let displayChanges = displays.changes() displayTask = Task { @MainActor [weak self] in do { for try await update in displayChanges { guard !Task.isCancelled else { return } self?.receive?(.displaysChanged(Self.coreDisplays(update))) } } catch { guard !Task.isCancelled else { return } self?.receive?(.failure(error)) } } #if DEBUG installE2EWakeBridgeIfNeeded(generation: generation) #endif } func stop() { lifetime += 1 observationTask?.cancel() observationTask = nil observationRefreshPending = false observationInventory.reset() do { try displays?.stop() } catch { receive?(.failure(error)) } displays = nil receive = nil pointer.stop() workspaceObserver.stop() if let e2eWakeObserver { DistributedNotificationCenter.default().removeObserver(e2eWakeObserver) } e2eWakeObserver = nil displayTask?.cancel() displayTask = nil preferenceTask?.cancel() preferenceTask = nil preferences?.stop() preferences = nil } #if DEBUG // Workspace notifications are process-local, so the e2e harness relays them with a session token. private func installE2EWakeBridgeIfNeeded(generation: UInt64) { let environment = ProcessInfo.processInfo.environment guard environment["PARCEL_E2E"] == "1", let token = environment["PARCEL_E2E_TOKEN"], !token.isEmpty else { return } e2eWakeObserver = DistributedNotificationCenter.default().addObserver( forName: Self.e2eWakeNotificationName(token: token), object: nil, queue: .main ) { [weak self] _ in DispatchQueue.main.async { guard let self, self.lifetime == generation else { return } let center = NSWorkspace.shared.notificationCenter center.post(name: NSWorkspace.willSleepNotification, object: nil) center.post(name: NSWorkspace.didWakeNotification, object: nil) NotificationCenter.default.post( name: NSApplication.didChangeScreenParametersNotification, object: nil) if let path = environment["PARCEL_E2E_WAKE_RECEIPT"] { do { try JSONEncoder().encode(["token": token, "event": "wake"]).write( to: URL(fileURLWithPath: path), options: .atomic) } catch { self.receive?(.failure(error)) } } } } } static func e2eWakeNotificationName(token: String) -> Notification.Name { Notification.Name("dev.vinnymac.parcel.e2e.\(token).wake") } #endif func currentDisplays() throws -> [ParcelCore.Display] { guard let displays else { throw DisplayObservationError.stopped } return Self.coreDisplays(try displays.current()) } func focusedApplication() -> AppID? { NSWorkspace.shared.frontmostApplication.flatMap { info($0)?.id } } func runningApplications() -> [NativeApplicationInfo] { observationCandidates().compactMap { candidate in let info = candidate.info guard candidate.canObserve, observationInventory.applications[info.id].map({ $0.launchIdentity == info.launchIdentity }) == true else { return nil } return info }.sorted { $0.id.pid < $1.id.pid } } func setDetectionTracing(_ source: (any DetectionTraceSource)?) { detectionSource = source } func setNewWindowTarget(_ target: @escaping @Sendable (AppThreadCreatedWindow) -> CGRect?) { newWindowTarget = target } func application(_ app: AppID) throws -> any NativeEngineApplication { guard runningApplications().contains(where: { $0.id == app }) else { throw EnginePlatformFailure.appUnavailable(app) } let running = NSRunningApplication(processIdentifier: app.pid) let activation: AppActivationPolicy? switch running?.activationPolicy { case .regular: activation = .regular case .accessory: activation = .accessory case .prohibited: activation = .prohibited default: activation = nil } let context = WindowFactsContext( bundleID: app.bundleID, appName: running?.localizedName ?? "", activationPolicy: activation, isHelper: running?.activationPolicy == .prohibited ? true : nil) return SystemNativeEngineApplication( app: app, context: context, serverFacts: serverFacts, thread: try AppThread( pid: app.pid, detectionSource: detectionSource, factsContext: context, newWindowTarget: newWindowTarget)) } func visibleWindows() async throws -> NativeVisibleWindows { let generation = lifetime let readWindows = readWindows let windows = try await Self.windowSnapshot(readWindows) try Task.checkCancellation() guard lifetime == generation else { throw CancellationError() } await serverFacts.update(windows) try Task.checkCancellation() guard lifetime == generation else { throw CancellationError() } updateObservationInventory(windows) let visible = windows.filter(\.isOnscreen) return NativeVisibleWindows( frames: Dictionary(uniqueKeysWithValues: visible.map { (WindowID(rawValue: $0.number), Rect($0.bounds)) }), owners: Dictionary(uniqueKeysWithValues: visible.map { (WindowID(rawValue: $0.number), $0.pid) }), catalogFrames: Dictionary( uniqueKeysWithValues: windows.map { (WindowID(rawValue: $0.number), Rect($0.bounds)) }), catalogOwners: Dictionary(uniqueKeysWithValues: windows.map { (WindowID(rawValue: $0.number), $0.pid) }), discoveryCandidates: Set(visible.filter { $0.layer == 0 }.map { WindowID(rawValue: $0.number) })) } func currentSpaces(for displays: [DisplayID]) async throws -> NativeSpaceState { let native = try await NativeSpaceReader().snapshot() let spaces = try NativeSpaceMapping.currentSpaces(native, displays: displays) var suspended: Set = [] for (display, current) in spaces { let matches = native.flatMap(\.spaces).filter { $0.id == current.rawValue } guard let kind = matches.first?.kind, matches.allSatisfy({ $0.kind == kind }) else { throw WindowServer.ReadError.currentSpaceUnavailable(displayID: display.rawValue) } if kind != .desktop { suspended.insert(display) } } return NativeSpaceState(spaces: spaces, suspended: suspended, snapshot: native) } func windowSpaces(for windows: Set) async throws -> [WindowID: Set] { var result: [WindowID: Set] = [:] let reader = NativeSpaceReader() for window in windows.sorted() { result[window] = Set(try await reader.spaces(for: window.rawValue).map { SpaceID(rawValue: $0) }) } return result } @concurrent private static func windowSnapshot( _ read: @Sendable () throws -> [WindowServer.Window] ) async throws -> [WindowServer.Window] { try Task.checkCancellation() return try read() } private func updateObservationInventory(_ windows: [WindowServer.Window]) { let arrivals = observationInventory.update( candidates: observationCandidates(), windowOwners: WindowServer.windowOwners(windows)) for info in arrivals { receive?(.launched(info)) if focusedApplication() == info.id { receive?(.activated(info)) } } } private func requestObservationRefresh() { guard receive != nil, observationCandidates().contains(where: { candidate in candidate.canObserve && observationInventory.applications[candidate.info.id].map({ $0.launchIdentity == candidate.info.launchIdentity }) != true }) else { return } guard observationTask == nil else { observationRefreshPending = true return } let generation = lifetime observationTask = Task { @MainActor [weak self] in guard let self else { return } repeat { self.observationRefreshPending = false do { _ = try await self.visibleWindows() } catch { guard self.lifetime == generation, !Task.isCancelled else { return } self.receive?(.failure(error)) } guard self.lifetime == generation, !Task.isCancelled else { return } } while self.observationRefreshPending self.observationTask = nil } } private func workspaceNotification(_ name: Notification.Name, application: NSRunningApplication?) { if name == NSWorkspace.didLaunchApplicationNotification, let application { let id = AppID(pid: application.processIdentifier, bundleID: application.bundleIdentifier ?? "") _ = admitLaunchedApplication(id, launchIdentity: application.launchDate) } requestObservationRefresh() switch name { case NSWorkspace.activeSpaceDidChangeNotification: receive?(.spaceChanged) case NSWorkspace.didWakeNotification: if let preferences { preferences.refresh() receive?(.preferencesChanged(preferences.snapshot())) } receive?(.woke) case NSWorkspace.didTerminateApplicationNotification: guard let application else { receive?(.failure(EngineOperationFailure.missingApplicationNotification)) return } let app = AppID(pid: application.processIdentifier, bundleID: application.bundleIdentifier ?? "") if observationInventory.applications[app]?.launchIdentity == application.launchDate { observationInventory.remove(app) } receive?(.terminated(app)) default: guard let application else { receive?(.failure(EngineOperationFailure.missingApplicationNotification)) return } guard let info = info(application) else { return } switch name { case NSWorkspace.didLaunchApplicationNotification: receive?(.launched(info)) case NSWorkspace.didActivateApplicationNotification: receive?(.activated(info)) case NSWorkspace.didHideApplicationNotification: receive?(.hidden(info)) case NSWorkspace.didUnhideApplicationNotification: receive?(.unhidden(info)) default: preconditionFailure("Unexpected workspace notification") } } } static func isExternalProcess(_ pid: Int32, ownPID: Int32 = ProcessInfo.processInfo.processIdentifier) -> Bool { pid != ownPID } func admitLaunchedApplication(_ id: AppID, launchIdentity: Date?) -> NativeApplicationInfo? { guard let candidate = observationCandidates().first(where: { $0.info.id == id && $0.info.launchIdentity == launchIdentity }) else { return nil } return observationInventory.admitLaunch(candidate) } private func info(_ application: NSRunningApplication) -> NativeApplicationInfo? { let id = AppID(pid: application.processIdentifier, bundleID: application.bundleIdentifier ?? "") guard let retained = observationInventory.applications[id], retained.launchIdentity == application.launchDate, !application.isTerminated else { return nil } var info = retained info.isHidden = application.isHidden return info } private static func candidate( _ application: NSRunningApplication, applicationFilter: @MainActor (NSRunningApplication) -> Bool ) -> NativeObservationCandidate? { guard Self.isExternalProcess(application.processIdentifier), !application.isTerminated, applicationFilter(application) else { return nil } let policy: AppActivationPolicy? = switch application.activationPolicy { case .regular: .regular case .accessory: .accessory case .prohibited: .prohibited @unknown default: nil } let launchedAt = application.launchDate.flatMap { date -> Double? in let age = Date().timeIntervalSince(date) return age < 1.5 ? ProcessInfo.processInfo.systemUptime - age : nil } return NativeObservationCandidate( info: NativeApplicationInfo( id: AppID(pid: application.processIdentifier, bundleID: application.bundleIdentifier ?? ""), isHidden: application.isHidden, launchedAt: launchedAt, name: application.localizedName ?? "", launchIdentity: application.launchDate, isRegular: application.activationPolicy == .regular), activationPolicy: policy, bundleURL: application.bundleURL) } static func coreDisplays(_ updated: [ParcelPlatform.Display]) -> [ParcelCore.Display] { let height = CGDisplayBounds(CGMainDisplayID()).height return updated.map { ParcelCore.Display( id: DisplayID(rawValue: $0.id.uuidString), frame: Rect( x: $0.visibleFrame.minX, y: height - $0.visibleFrame.maxY, width: $0.visibleFrame.width, height: $0.visibleFrame.height), fullFrame: Rect( x: $0.frame.minX, y: height - $0.frame.maxY, width: $0.frame.width, height: $0.frame.height)) } } } @MainActor enum NativeRestoreVerification { static func restore( _ window: WindowID, timeout: Duration = .seconds(3), interval: Duration = .milliseconds(25), now: () -> ContinuousClock.Instant = { .now }, write: () async throws -> Bool, read: () async throws -> Bool ) async throws { try Task.checkCancellation() if try await write() { return } let deadline = now().advanced(by: timeout) repeat { try Task.checkCancellation() try await Task.sleep(for: interval) if try await read() { return } } while now() < deadline throw MinimizedWindowRestoreError.unconfirmed(window) } } @MainActor private final class SystemNativeEngineApplication: NativeEngineApplication { private let app: AppID private let context: WindowFactsContext private let serverFacts: NativeServerFacts private let thread: AppThread var events: AsyncStream { thread.events } init(app: AppID, context: WindowFactsContext, serverFacts: NativeServerFacts, thread: AppThread) { self.app = app self.context = context self.serverFacts = serverFacts self.thread = thread } func windows() async throws -> [NativeWindowSnapshot] { let app = app let context = context let observed = try await thread.performWithWindows { windows in try windows.map { var snapshot = try Self.read($0.element, windowID: $0.windowID, app: app, context: context) snapshot.validity = $0.validity return snapshot } } let server = await serverFacts.forApp(app.pid) return observed.map { observation in var window = observation.window if let record = server[window.id] { window.facts?.layer = Int(record.layer) window.facts?.serverSize = Size(width: record.bounds.width, height: record.bounds.height) } let frame = window.facts?.hasNativeTabs == true ? server[window.id].map { Rect($0.bounds) } ?? observation.frame : observation.frame return NativeWindowSnapshot( window: window, frame: frame, excluded: observation.excluded, validity: observation.validity) } } func frame(_ window: WindowID) async throws -> Rect { let pid = app.pid return try await thread.performWindow(windowID: window.rawValue) { _ in try Rect( AppThreadWindowFrameReadback.read(windowID: window.rawValue, pid: pid) { options, id in try WindowServer().windows(options: options, relativeTo: id) }) } } func acknowledgeMotion(_ window: UInt32) { thread.acknowledgeMotion(windowID: window) } func writeFrames(_ frames: [EngineFrameWrite]) async throws -> EngineWriteReceipt { var initialFrames: [WindowFrame] = [] for request in frames where request.capturesInitialFrame { initialFrames.append(WindowFrame(window: request.window, frame: try await frame(request.window))) } let receipt = try await thread.writeFrames( frames.map { AppThreadFrameWrite( windowID: $0.window.rawValue, target: $0.frame.cgRect, generation: $0.generation, phase: $0.isFinal ? .final : .ongoing, resetsSizeFit: $0.resetsSizeFit) }) let requests = frames.map { AppThreadFrameWrite( windowID: $0.window.rawValue, target: $0.frame.cgRect, generation: $0.generation, phase: .final) } let readback = try await AppThreadWindowFrameReadback.verified( writes: requests, receipts: receipt.windows, pid: app.pid ) { _, id in try await WindowServer().frameReadbackWindows(windowID: id) } var verified = readback.frames var frameWriteDiagnostics: [WindowID: AppThreadFrameWriteDiagnostics] = [:] for window in receipt.windows { if let diagnostics = window.diagnostics { frameWriteDiagnostics[WindowID(rawValue: window.windowID)] = diagnostics } } var duration = receipt.duration var failures = readback.failures.sorted { $0.key < $1.key }.map { id, error in NativeWindowFrameReadbackFailure(app: app, window: WindowID(rawValue: id), cause: error).platformFailure } var eligible = Set(verified.keys) for _ in 0..<2 { try Task.checkCancellation() var corrections: [AppThreadFrameWrite] = [] for request in requests where eligible.contains(request.windowID) { guard let accepted = verified[request.windowID], accepted.origin != request.target.origin, accepted.width <= request.target.width, accepted.height <= request.target.height else { continue } let spent = frameWriteDiagnostics[WindowID(rawValue: request.windowID)]?.setterCount ?? 0 let remaining = AppThreadFrameWriteDiagnostics.maximumSetters - spent guard remaining > 0 else { continue } do { let adjusted = try await thread.performWindow(windowID: request.windowID) { window in try AppThreadWindowFrameReadback.positionOnlyTarget( desired: request.target, accepted: accepted, accessibility: window.frame) } if let adjusted { // Keep ownership: a position repair must never restart a resize from stale AX dimensions. var correction = AppThreadFrameWrite( windowID: request.windowID, target: adjusted, generation: request.generation, phase: .final) correction.preservesSize = true correction.setterLimit = remaining corrections.append(correction) } } catch is CancellationError { throw CancellationError() } catch { eligible.remove(request.windowID) verified.removeValue(forKey: request.windowID) failures.append( NativeEngineWorld.failure(error, app: app, window: WindowID(rawValue: request.windowID))) } } guard !corrections.isEmpty else { break } let corrected = try await thread.writeFrames(corrections) duration += corrected.duration for window in corrected.windows { let id = WindowID(rawValue: window.windowID) if let diagnostics = window.diagnostics { frameWriteDiagnostics[id] = frameWriteDiagnostics[id]?.adding(diagnostics) ?? diagnostics } if let error = window.error { eligible.remove(window.windowID) verified.removeValue(forKey: window.windowID) if case AppThreadFrameWriteError.staleGeneration = error { continue } failures.append( NativeEngineWorld.failure(error, app: app, window: WindowID(rawValue: window.windowID))) } } failures += corrected.cleanupErrors.map { NativeEngineWorld.failure($0, app: app) } let ids = Set(corrections.map(\.windowID)).intersection(eligible) guard !ids.isEmpty else { break } let repaired = try await AppThreadWindowFrameReadback.settled( writes: requests.filter { ids.contains($0.windowID) }, pid: app.pid ) { _, id in try await WindowServer().frameReadbackWindows(windowID: id) } for (id, error) in repaired.failures.sorted(by: { $0.key < $1.key }) { eligible.remove(id) verified.removeValue(forKey: id) failures.append( NativeWindowFrameReadbackFailure(app: app, window: WindowID(rawValue: id), cause: error) .platformFailure) } verified.merge(repaired.frames) { _, current in current } } var actual: [WindowFrame] = [] for window in receipt.windows { let id = WindowID(rawValue: window.windowID) if let frame = verified[window.windowID] { actual.append(WindowFrame(window: id, frame: Rect(frame))) } if let error = window.error { if case AppThreadFrameWriteError.staleGeneration = error { continue } failures.append(NativeEngineWorld.failure(error, app: app, window: id)) } } failures += receipt.cleanupErrors.map { NativeEngineWorld.failure($0, app: app) } return EngineWriteReceipt( frames: actual, failures: failures, duration: duration, writtenWindowCount: receipt.windows.isEmpty ? nil : receipt.windows.count, initialFrames: initialFrames, frameWriteDiagnostics: frameWriteDiagnostics) } func cancelFrameWrites(_ window: WindowID, throughGeneration: UInt64) async throws { try await thread.cancelFrameWrites(windowIDs: [window.rawValue], throughGeneration: throughGeneration) } func finishShutdown() async throws { try await thread.shutdownRestoringFrameWrites() } func edited(_ window: WindowID) async throws -> Bool? { try await thread.perform { application in do { return try Self.find(window, in: application).edited } catch AXPlatformError.attributeUnsupported { return nil } catch AXPlatformError.noValue { return nil } } } func close(_ window: WindowID) async throws { try await thread.perform { application in try Self.find(window, in: application).closeWindow() } } func restore(_ window: WindowID, validity: AppThreadOperationValidity) async throws { do { try await NativeRestoreVerification.restore(window) { try await thread.performWindow(windowID: window.rawValue, validity: validity) { element in try element.setMinimized(false) return try !element.minimized } } read: { try await thread.performWindow(windowID: window.rawValue, validity: validity) { element in try !element.minimized } } } catch is AppThreadOperationInvalidated { throw MinimizedWindowRestoreError.staleWindow(window) } } func toggleFullscreen(_ window: WindowID) async throws { // AXWindows can omit a live fullscreen window during its native Space transition. try await performNativeFullscreenTransition( window: window, retain: { try await self.thread.retainWindow(windowID: window.rawValue) }, change: { request, cancellation in try await self.thread.performWindow(request: request) { element in try cancellation.check() let target = try !element.fullscreen try cancellation.check() try element.setFullscreen(target) return target } }, read: { request in try await self.thread.performWindow(request: request) { try $0.fullscreen } }, release: { request in await self.thread.releaseWindow(request) }) } func menuShortcuts() async throws -> [MenuShortcut] { try await MenuShortcutReader.read(on: thread) } func probeResponsiveness() async throws { try await thread.perform { application in _ = try application.role } } func focusedWindow() async throws -> WindowID? { try await thread.perform { application in try Self.optional { WindowID(rawValue: try application.focusedWindow.windowID()) } } } func write(_ frame: Rect, to window: WindowID) async throws -> Rect { Rect(try await thread.writeFrame(windowID: window.rawValue, target: frame.cgRect)) } func focus(_ window: WindowID) async throws { guard let running = NSRunningApplication(processIdentifier: app.pid) else { throw EnginePlatformFailure.appUnavailable(app) } guard running.activate(options: []) else { throw EngineOperationFailure.activationRefused(app) } try await thread.perform { application in let target = try Self.find(window, in: application) try target.setMain(true) try application.setFocusedWindow(target) guard try application.focusedWindow.windowID() == window.rawValue else { throw EngineOperationFailure.focusUnchanged(window) } } } func raise(_ window: WindowID) async throws { try await NativeRaiseVerification.perform( window: window, app: app, read: { let foreground = NSWorkspace.shared.frontmostApplication?.processIdentifier guard foreground == self.app.pid else { return NativeRaiseReadback(foregroundPID: foreground, focusedWindow: nil, frontWindow: nil) } let focused = try await self.focusedWindow() guard focused == window else { return NativeRaiseReadback(foregroundPID: foreground, focusedWindow: focused, frontWindow: nil) } let front = try await Self.frontmostWindow() return NativeRaiseReadback( foregroundPID: NSWorkspace.shared.frontmostApplication?.processIdentifier, focusedWindow: focused, frontWindow: front) }, raise: { try await self.thread.perform { application in try Self.find(window, in: application).raise() } }) } @concurrent private static func frontmostWindow() async throws -> WindowID? { try Task.checkCancellation() return try WindowServer().windows(options: .optionOnScreenOnly) .first { $0.isOnscreen && $0.layer == 0 && $0.bounds.width > 0 && $0.bounds.height > 0 } .map { WindowID(rawValue: $0.number) } } func spaceDragWindow(_ window: WindowID) async throws -> SpaceDragWindow { try await thread.perform { application in let element = try Self.find(window, in: application) guard try application.focusedWindow.windowID() == window.rawValue else { throw SpaceCommandError.windowUnavailable } guard try !element.fullscreen else { throw SpaceCommandError.fullscreen } do { return SpaceDragWindow(id: window.rawValue, titleBar: try element.titleBarFrame, isFullscreen: false) } catch AXPlatformError.attributeUnsupported, AXPlatformError.noValue { throw SpaceCommandError.titleBarUnavailable } } } func shutdown() { thread.shutdown() } nonisolated private static func find(_ window: WindowID, in application: AXElement) throws -> AXElement { for candidate in try application.windows where try candidate.windowID() == window.rawValue { return candidate } throw EnginePlatformFailure.vanished(window) } nonisolated private static func optional(_ read: () throws -> Value) throws -> Value? { do { return try read() } catch AXPlatformError.attributeUnsupported, AXPlatformError.noValue { return nil } } nonisolated private static func read( _ element: AXElement, windowID: CGWindowID, app: AppID, context: WindowFactsContext ) throws -> NativeWindowSnapshot { let id = WindowID(rawValue: windowID) let facts = try WindowFactsReader.gather(window: element, context: context) let window = ManagedWindow( id: id, app: app, title: facts.title ?? "", role: facts.role ?? "", subrole: facts.subrole, facts: facts) return NativeWindowSnapshot( window: window, frame: Rect(try element.frame), excluded: facts.isMinimized == true || facts.isFullScreen == true) } } extension Rect { var cgRect: CGRect { CGRect(x: minX, y: minY, width: size.width, height: size.height) } init(_ frame: CGRect) { self.init(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height) } }