diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift index 6b09b100f..4e7cee227 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift @@ -13,6 +13,7 @@ protocol WindowSwitcherCatalog: AnyObject { func stop() func refresh() func prepareForInvocation() + func cancelInvocation() func entries(sortMode: WindowSwitcherSortMode) -> [WindowSwitcherAppEntry] func activate(_ entry: WindowSwitcherAppEntry, intent: WindowSwitcherActivationIntent) async -> WindowSwitcherActionResult func closeWindow(_ entry: WindowSwitcherAppEntry) async -> WindowSwitcherActionResult @@ -22,6 +23,7 @@ protocol WindowSwitcherCatalog: AnyObject { extension WindowSwitcherCatalog { var isInvocationReady: Bool { isInitialDiscoveryComplete } func prepareForInvocation() { refresh() } + func cancelInvocation() {} var listingPolicy: WindowSwitcherListingPolicy { get { .default } @@ -47,6 +49,7 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { var launchDate: Date? = nil var lifetime: UUID? = nil var isRegular = true + var isFinishedLaunching = true var isHidden = false var isActive = false var loadPresentation: (() -> Presentation)? = nil @@ -66,10 +69,97 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { struct DiscoveryEnvironment { var applications: (() -> [Application])? = nil + var foregroundProcessIdentifier: () -> pid_t? = { NSWorkspace.shared.frontmostApplication?.processIdentifier } var isAccessibilityTrusted: () -> Bool = { AXIsProcessTrusted() } var isDragging: () -> Bool = { CGEventSource.buttonState(.combinedSessionState, button: .left) } } + private struct ForegroundTarget: Equatable { + let hostPID: pid_t + let workerPID: pid_t + } + + private struct ForegroundCheck { + enum Phase: Equatable { + case initialCapture, initialScan + case retryDelay, retryCapture, retryQueued(pid_t), retryScan + + var needsCapture: Bool { self == .initialCapture || self == .retryCapture } + var canFinish: Bool { self == .initialScan || self == .retryScan } + + var queuedHost: pid_t? { + if case let .retryQueued(pid) = self { return pid } + return nil + } + } + + var pid: pid_t? + var phase = Phase.initialCapture + var focusRead: (target: ForegroundTarget, startedAt: ContinuousClock.Instant)? + var conflict: FocusConflict? + var deferredRefreshes: Set = [] + } + + private enum FocusIssue: Equatable { + case unmatchedAXFocus, incompleteAX, offscreenAX, excludedAXFocus + + var requiresAXConfirmation: Bool { self == .unmatchedAXFocus || self == .incompleteAX } + } + + private enum FocusVisibility { + case onscreen, offscreen + } + + private enum LaunchVisibilityCheck { + case none, initial, retry + } + + private struct FocusObservation { + let workerPID: pid_t + let id: String? + let windowNumber: CGWindowID? + let unavailable: Bool + let reportedFocusedWindow: Bool + let reportedFocusWasExcluded: Bool + let readStartedAt: ContinuousClock.Instant? + var canInfer: Bool { !unavailable && !reportedFocusedWindow } + + init(workerPID: pid_t, scan: WindowSwitcherScan) { + self.workerPID = workerPID + id = scan.focusedID + windowNumber = scan.focusedID.flatMap { id in scan.windows.first { $0.id == id }?.windowNumber } + unavailable = scan.unavailable + reportedFocusedWindow = scan.reportedFocusedWindow + reportedFocusWasExcluded = scan.reportedFocusWasExcluded + readStartedAt = scan.focusReadStartedAt + } + } + + private struct FocusChange { + let receivedAt: ContinuousClock.Instant + let capture: Int + } + + private struct FocusConflict { + let id: String + let capture: Int + } + + private struct InvocationVisibility { + let generation: UUID + let foregroundPID: pid_t? + let capture: Int + let records: [WindowSwitcherWindowRecord]? + } + + private struct PendingFocus { + let target: ForegroundTarget + let foregroundAtScanStart: ForegroundTarget? + let observations: [pid_t: FocusObservation] + let focusChangeAfterCapture: Int? + var confirmedOnly = false + } + var onChange: (() -> Void)? private(set) var isInitialDiscoveryComplete = false private(set) var isInvocationReady = false @@ -90,11 +180,14 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var observers: [NSObjectProtocol] = [] private var workers: [pid_t: WindowSwitcherProcessWorker] = [:] private var snapshots: [pid_t: [WindowSwitcherAppEntry]] = [:] + private var scannedHelperPIDs: [pid_t: Set] = [:] + private var excludedWindowNumbersByHost: [pid_t: Set] = [:] private var inFlight: Set = [] // Kept across stop/start until the actual worker returns. private var activeScanCount = 0 private var dirtyHosts: Set = [] private var pendingInvalidations: Set = [] + private var focusChanges: [pid_t: FocusChange] = [:] private var pendingRecordsInvalidation = false private var applicationsByPID: [pid_t: Application] = [:] private var mappingCandidates: [WindowSwitcherProcessMapping.Candidate] = [] @@ -107,14 +200,17 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var publicationTask: Task? private var publicationDirty = false private var removedProcesses: Set = [] - private var pendingFocus: [pid_t: (id: String?, unavailable: Bool)] = [:] + private var pendingFocus: [pid_t: PendingFocus] = [:] + private var inferredFocusWorkerLifetime: UUID? private var windowRecordsPending = false private var sleeping = false private var sessionInactive = false private var suspended: Bool { sleeping || sessionInactive } private var invocationGeneration = UUID() - private var invocationRequiredHosts: Set = [] - private var invocationRequiresRecords = false + private var foregroundCheck: ForegroundCheck? + private var foregroundRetryDelay: Task? + private var cancelledFocus: (generation: UUID, target: ForegroundTarget, conflict: FocusConflict?)? + private var requiredCatalogScans: Set = [] private let allSpacesCatalog: WindowSwitcherWindowRecords private let discovery: DiscoveryEnvironment private var publication = WindowSwitcherPublishedWindows() @@ -122,6 +218,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { private var allSpacesRecordsAreFresh = false private var allSpacesRecords: [WindowSwitcherWindowRecord] = [] private var allSpacesRefreshTask: Task? + private var pendingVisibilityInvocation: UUID? + private var captureSequence = 0 + private var lastPublishedCapture = 0 + private var invocationVisibility: InvocationVisibility? private var allSpacesGeneration = UUID() private var didReadAllSpaces = false @@ -204,14 +304,15 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { publicationDirty = false removedProcesses.removeAll() pendingFocus.removeAll() + inferredFocusWorkerLifetime = nil applicationInventory?.stop() allSpacesGeneration = UUID() - invocationGeneration = UUID() - invocationRequiredHosts.removeAll() - invocationRequiresRecords = false + resetInvocation() isInvocationReady = false windowRecordsPending = false allSpacesRefreshTask?.cancel(); allSpacesRefreshTask = nil + pendingVisibilityInvocation = nil + invocationVisibility = nil allSpacesCatalog.stop() allSpacesRecords.removeAll() publication = WindowSwitcherPublishedWindows() @@ -226,19 +327,29 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { helperPIDsByHost.removeAll() dirtyHosts.removeAll() pendingInvalidations.removeAll() + focusChanges.removeAll() pendingRecordsInvalidation = false timer?.invalidate(); timer = nil observers.forEach(notificationCenter.removeObserver); observers.removeAll() workers.values.forEach { $0.stop() }; workers.removeAll() snapshots.removeAll(); inFlight.removeAll(); unavailable.removeAll() + scannedHelperPIDs.removeAll() + excludedWindowNumbersByHost.removeAll() unavailableApplicationCount = 0 } /// Coalesces events by owner. A dirty host remains queued when a scan is in /// flight, so changes arriving during that scan get one follow-up read. - func invalidate(processIdentifiers: Set, windowRecords: Bool) { + func invalidate(processIdentifiers: Set, windowRecords: Bool, focusChanged: Bool = false) { guard running else { return } - pendingInvalidations.formUnion(processIdentifiers.map { processMapping.host(for: $0) }.filter { expectedHostPIDs.contains($0) }) + let hosts = Set(processIdentifiers.map { processMapping.host(for: $0) }).intersection(expectedHostPIDs) + pendingInvalidations.formUnion(hosts) + if focusChanged { + let change = FocusChange(receivedAt: .now, capture: captureSequence) + for pid in processIdentifiers where hosts.contains(processMapping.host(for: pid)) { + focusChanges[pid] = change + } + } pendingRecordsInvalidation = pendingRecordsInvalidation || windowRecords if processIdentifiers.contains(ProcessInfo.processInfo.processIdentifier) { markPublicationDirty() } scheduleRefresh() @@ -275,19 +386,67 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { func prepareForInvocation() { guard running else { return } - invocationGeneration = UUID() + resetInvocation() + // Release any older background waiter. The new invocation can use the + // second reader slot while that physical query finishes. + allSpacesRefreshTask?.cancel() + allSpacesRefreshTask = nil + pendingVisibilityInvocation = nil + invocationVisibility = nil + let foregroundPID = discovery.foregroundProcessIdentifier() + foregroundCheck = ForegroundCheck(pid: foregroundPID) isInvocationReady = false - applicationInventory?.reconcile(notify: false) - reloadApplications() + pendingFocus.removeAll() + inferredFocusWorkerLifetime = nil + publication.recency.clearInference() + reloadForegroundApplication(foregroundPID) applyInvalidations() - invocationRequiredHosts = expectedHostPIDs - invocationRequiresRecords = true + requiredCatalogScans = expectedHostPIDs dirtyHosts.formUnion(expectedHostPIDs) windowRecordsPending = true markPublicationDirty() drainRefreshes() } + func cancelInvocation() { + guard let check = foregroundCheck else { return } + let target = foregroundTarget() + let capturedFocus = target.flatMap { pendingFocus[$0.hostPID] } + let generation = invocationGeneration + let canPreserveFocus = target?.workerPID == check.pid + resetInvocation() + pendingFocus.removeAll() + publication.recency.clearInference() + inferredFocusWorkerLifetime = nil + // Cancelling the chooser still allows a genuine foreground observation + // to enter history if the app and its focus scan have not changed. + if let target, canPreserveFocus { + cancelledFocus = (generation, target, check.conflict) + if var capturedFocus, capturedFocus.target == target, capturedFocus.foregroundAtScanStart == target { + capturedFocus.confirmedOnly = true + pendingFocus[target.hostPID] = capturedFocus + } + } + applyInvalidations() + drainRefreshes() + } + + private func resetInvocation() { + if let check = foregroundCheck { pendingInvalidations.formUnion(check.deferredRefreshes) } + foregroundCheck = nil + foregroundRetryDelay?.cancel() + foregroundRetryDelay = nil + invocationGeneration = UUID() + cancelledFocus = nil + requiredCatalogScans.removeAll() + } + + private func reloadForegroundApplication(_ pid: pid_t?) { + applicationInventory?.reconcile(notify: false) + if let pid { applicationInventory?.reload(processIdentifier: pid, notify: false) } + reloadApplications() + } + private func reloadApplications() { let oldMapping = processMapping let ownPID = ProcessInfo.processInfo.processIdentifier @@ -316,7 +475,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { inFlight.remove(pid) unavailable.remove(pid) snapshots.removeValue(forKey: pid) - pendingFocus.removeValue(forKey: pid) + scannedHelperPIDs.removeValue(forKey: oldMapping.host(for: pid)) + excludedWindowNumbersByHost.removeValue(forKey: pid) + pendingFocus.removeValue(forKey: oldMapping.host(for: pid)) + focusChanges.removeValue(forKey: pid) removedProcesses.insert(pid) dirtyHosts.insert(oldMapping.host(for: pid)) markPublicationDirty() @@ -325,11 +487,17 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } for pid in Array(snapshots.keys) where !expectedHostPIDs.contains(pid) { snapshots.removeValue(forKey: pid) + scannedHelperPIDs.removeValue(forKey: pid) + excludedWindowNumbersByHost.removeValue(forKey: pid) removedProcesses.insert(pid) markPublicationDirty() } dirtyHosts.formIntersection(expectedHostPIDs) - invocationRequiredHosts.formIntersection(expectedHostPIDs) + requiredCatalogScans.formIntersection(expectedHostPIDs) + foregroundCheck?.deferredRefreshes.formIntersection(expectedHostPIDs) + if let host = foregroundCheck?.phase.queuedHost, !expectedHostPIDs.contains(host) { + foregroundCheck?.phase = .retryScan + } dirtyHosts.formUnion(expectedHostPIDs.filter { snapshots[$0] == nil }) } @@ -342,17 +510,35 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { // Preserve pending work during tracking; the short retry exists only // while a user drag prevents a requested refresh from proceeding. guard !discovery.isDragging() else { scheduleRefresh(); return } - if windowRecordsPending { refreshAllSpaces() } + // Finish publishing the invocation's visibility snapshot before + // servicing any refreshes queued behind it. + if windowRecordsPending, foregroundCheck?.phase.needsCapture != false { + refreshAllSpaces() + } + let foregroundAtScanStart = foregroundTarget() + let foregroundHostPID = foregroundAtScanStart?.hostPID + let hostAwaitingVisibility: pid_t? + if let check = foregroundCheck, check.phase == .retryDelay || check.phase == .retryCapture { + hostAwaitingVisibility = check.pid.flatMap { foregroundTarget(for: $0)?.hostPID } + } else { + hostAwaitingVisibility = nil + } let pids = dirtyHosts.sorted { - let lhsActive = activeWorkerPID(for: $0) != nil - let rhsActive = activeWorkerPID(for: $1) != nil + let lhsActive = $0 == foregroundHostPID + let rhsActive = $1 == foregroundHostPID return lhsActive == rhsActive ? $0 < $1 : lhsActive } for pid in pids { guard activeScanCount < Self.maximumConcurrentScans else { break } - guard !inFlight.contains(pid), let application = applicationsByPID[pid] else { continue } + guard pid != hostAwaitingVisibility, !inFlight.contains(pid), + let application = applicationsByPID[pid] else { continue } let worker = ensureWorker(pid: pid, launchDate: application.launchDate, applicationLifetime: application.lifetime) dirtyHosts.remove(pid) + foregroundCheck?.deferredRefreshes.remove(pid) + if foregroundCheck?.phase.queuedHost == pid { + foregroundCheck?.phase = .retryScan + pendingInvalidations.remove(pid) + } inFlight.insert(pid) activeScanCount += 1 let app = application.withPresentation() @@ -367,8 +553,9 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { let result = await worker.scan() guard let self, running, workers[pid] === worker else { return } var entries = windowEntries(from: result, app: app, ownerPID: pid) + var excludedWindowNumbers = result.excludedWindowNumbers var helperUnavailable = false - var helperFocusIDs: [pid_t: String] = [:] + var focusObservations = [pid: FocusObservation(workerPID: pid, scan: result)] for helperPID in (helperPIDsByHost[pid] ?? []).sorted() { guard let helperApp = applicationsByPID[helperPID] else { continue } let helperWorker = ensureWorker(pid: helperPID, launchDate: helperApp.launchDate, @@ -377,7 +564,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { guard running, workers[pid] === worker else { return } guard workers[helperPID] === helperWorker else { continue } if helperScan.unavailable { helperUnavailable = true } - helperFocusIDs[helperPID] = helperScan.focusedID + focusObservations[helperPID] = FocusObservation(workerPID: helperPID, scan: helperScan) + excludedWindowNumbers.formUnion(helperScan.excludedWindowNumbers) entries = WindowSwitcherListing.preferringUniqueWindowNumbers( entries + windowEntries(from: helperScan, app: app, ownerPID: helperPID)) } @@ -397,13 +585,29 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { entries = previous.map { var entry = $0; entry.metadataUnavailable = true; return entry } } snapshots[pid] = entries + scannedHelperPIDs[pid] = Set(focusObservations.keys).subtracting([pid]) + excludedWindowNumbersByHost[pid] = excludedWindowNumbers if previous != entries { markPublicationDirty() } - if let activePID = activeWorkerPID(for: pid) { - pendingFocus[pid] = (activePID == pid ? result.focusedID : helperFocusIDs[activePID], unavailableScan) - markPublicationDirty() - } - if invocation == invocationGeneration { - invocationRequiredHosts.remove(pid) + let isCurrentScan = invocation == invocationGeneration && foregroundCheck?.phase.queuedHost != pid + if isCurrentScan { requiredCatalogScans.remove(pid) } + if let target = foregroundTarget(), target.hostPID == pid { + let wasCancelled = cancelledFocus?.generation == invocation && cancelledFocus?.target == target + && foregroundAtScanStart == target + if isCurrentScan || wasCancelled { + let focusChange = focusChanges[target.workerPID] + let focusRead = focusObservations[target.workerPID]?.readStartedAt + // Compare the event with the focus read, including events + // delivered while window enumeration was in progress. + let focusChangeAfterCapture: Int? + if let focusChange, let focusRead, focusChange.receivedAt <= focusRead { + focusChangeAfterCapture = focusChange.capture + } else { + focusChangeAfterCapture = nil + } + pendingFocus[pid] = PendingFocus(target: target, foregroundAtScanStart: foregroundAtScanStart, + observations: focusObservations, focusChangeAfterCapture: focusChangeAfterCapture, + confirmedOnly: wasCancelled) + } } schedulePublication() } @@ -411,13 +615,16 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { schedulePublication() } - private func activeWorkerPID(for hostPID: pid_t) -> pid_t? { - if let helperPID = (helperPIDsByHost[hostPID] ?? []).sorted().first(where: { - applicationsByPID[$0]?.isActive == true - }) { - return helperPID - } - return applicationsByPID[hostPID]?.isActive == true ? hostPID : nil + private func foregroundTarget() -> ForegroundTarget? { + guard let foregroundPID = discovery.foregroundProcessIdentifier() else { return nil } + return foregroundTarget(for: foregroundPID) + } + + private func foregroundTarget(for foregroundPID: pid_t) -> ForegroundTarget? { + let hostPID = processMapping.host(for: foregroundPID) + guard expectedHostPIDs.contains(hostPID), + foregroundPID == hostPID || helperPIDsByHost[hostPID]?.contains(foregroundPID) == true else { return nil } + return ForegroundTarget(hostPID: hostPID, workerPID: foregroundPID) } func entries(sortMode: WindowSwitcherSortMode) -> [WindowSwitcherAppEntry] { @@ -447,7 +654,8 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { applicationLifetime: applicationLifetime, access: accessFactory(pid)) { [weak self] event in Task { @MainActor [weak self] in guard let self, workers[event.processIdentifier]?.lifetime == event.lifetime else { return } - invalidate(processIdentifiers: [event.processIdentifier], windowRecords: event.kind.requiresWindowRecords) + invalidate(processIdentifiers: [event.processIdentifier], windowRecords: event.kind.requiresWindowRecords, + focusChanged: event.kind == .focus) } } workers[pid] = created @@ -486,6 +694,10 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { publication.update(snapshots: snapshots, records: allSpacesRecords, recordsAreFresh: allSpacesRecordsAreFresh, localEntries: hostWindows.entries(), helperProcessIdentifiers: helperPIDsByHost, displayContext: { self.displayContext(for: $0) }) + recordLocalFocus() + } + + private func recordLocalFocus() { if NSApp.isActive, let focusedID = hostWindows.focusedID { publication.recency.observeForeground(entries: publication.entries.filter { $0.processIdentifier == ProcessInfo.processInfo.processIdentifier @@ -493,6 +705,398 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { } } + private func inferredForegroundWindowID(in entries: [WindowSwitcherAppEntry], + target: ForegroundTarget, requiresOnscreen: Bool) -> String? { + guard allSpacesRecordsAreFresh, !entries.isEmpty else { return nil } + let onscreenWindowNumbers = foregroundOnscreenWindowNumbers(target: target) + guard !hasUnresolvedOnscreenWindow(onscreenWindowNumbers, in: entries) else { return nil } + // A fresh WindowServer snapshot can distinguish a visible window from + // windows that are still restoring or live on other Spaces. + let excluded = excludedWindowNumbersByHost[target.hostPID] ?? [] + let ownerPIDs = foregroundOwnerPIDs(target: target) + let candidates = entries.compactMap { entry -> (id: String, onscreen: Bool, belongsToForeground: Bool)? in + guard ownerPIDs.contains(entry.owningProcessIdentifier) + || entry.axWorkerPID.map(ownerPIDs.contains) == true, + isUsableWindow(entry), !publication.lostAXConfirmation(entry), + entry.windowElement != nil || entry.windowNumber.map(excluded.contains) != true else { return nil } + let record = visibilityRecord(for: entry, among: entries) + guard record?.isOnScreen != false, record?.isOnActiveSpace != false else { return nil } + return (entry.id, record?.isOnScreen == true, + entry.axWorkerPID == target.workerPID || entry.owningProcessIdentifier == target.workerPID) + } + let likely = candidates.count == 1 ? candidates : candidates.filter(\.onscreen) + // A helper can make the host ambiguous without being inferred as the + // focused window when Workspace identifies the host. + guard likely.count == 1, let candidate = likely.first, candidate.belongsToForeground, + !requiresOnscreen || candidate.onscreen else { return nil } + return candidate.id + } + + private func isUsableWindow(_ entry: WindowSwitcherAppEntry) -> Bool { + entry.isWindowEntry && !entry.isHidden && !entry.isMinimized + && !entry.isOnOtherDesktop && !entry.metadataUnavailable + } + + private func foregroundOwnerPIDs(target: ForegroundTarget) -> Set { + target.workerPID == target.hostPID + ? (helperPIDsByHost[target.hostPID] ?? []).union([target.workerPID]) + : [target.workerPID] + } + + private func foregroundOnscreenWindowNumbers(target: ForegroundTarget, + records: [WindowSwitcherWindowRecord]? = nil) -> Set { + let ownerPIDs = foregroundOwnerPIDs(target: target) + return Set((records ?? allSpacesRecords).lazy.filter { + $0.isOnScreen == true && $0.isOnActiveSpace != false && ownerPIDs.contains($0.processIdentifier) + }.map(\.windowNumber)).subtracting(excludedWindowNumbersByHost[target.hostPID] ?? []) + } + + private func hasUnresolvedOnscreenWindow(_ onscreen: Set, in entries: [WindowSwitcherAppEntry], + requiresAXConfirmation: Bool = false) -> Bool { + let usable = entries.filter { entry in + isUsableWindow(entry) && (entry.windowElement != nil + || (!requiresAXConfirmation && !publication.lostAXConfirmation(entry))) + } + let represented = Set(usable.compactMap { + $0.windowNumber ?? visibilityRecord(for: $0, among: entries)?.windowNumber + }) + return !onscreen.isSubset(of: represented) + } + + private func visibilityRecord(for entry: WindowSwitcherAppEntry, + among entries: [WindowSwitcherAppEntry], + records: [WindowSwitcherWindowRecord]? = nil) -> WindowSwitcherWindowRecord? { + let records = records ?? allSpacesRecords + if let number = entry.windowNumber { + return records.first { $0.windowNumber == number && $0.processIdentifier == entry.owningProcessIdentifier } + } + guard entry.windowElement != nil else { return nil } + // Unique geometry can inform visibility only. Preserve exact IDs for + // listing and actions. Check all Spaces for competing matches. + let excluded = excludedWindowNumbersByHost[entry.processIdentifier] ?? [] + let matches = records.lazy.filter { + $0.processIdentifier == entry.owningProcessIdentifier + && !excluded.contains($0.windowNumber) && Self.sameBounds($0.bounds, entry.bounds) + }.prefix(2) + guard matches.count == 1, let record = matches.first else { return nil } + let competingEntry = entries.contains { + $0.id != entry.id && ($0.windowNumber == record.windowNumber + || ($0.windowNumber == nil && $0.windowElement != nil + && $0.owningProcessIdentifier == record.processIdentifier + && Self.sameBounds($0.bounds, record.bounds))) + } + return competingEntry ? nil : record + } + + private func exactWindowID(for focus: FocusObservation, in entries: [WindowSwitcherAppEntry]) -> String? { + // Deduplication can keep the host's AX row for a helper-owned window. + entries.first { entry in + (entry.workerWindowID ?? entry.id) == focus.id + || (entry.owningProcessIdentifier == focus.workerPID + && focus.windowNumber != nil && entry.windowNumber == focus.windowNumber) + }?.id + } + + private func activeHelperFocusIDs(in entries: [WindowSwitcherAppEntry], pending: PendingFocus) -> [String] { + let target = pending.target + guard target.workerPID == target.hostPID else { return [] } + return (helperPIDsByHost[target.hostPID] ?? []).sorted().compactMap { pid in + guard applicationsByPID[pid]?.isActive == true, let focus = pending.observations[pid] else { return nil } + return exactWindowID(for: focus, in: entries) + } + } + + private func focusVisibility(of entry: WindowSwitcherAppEntry, in entries: [WindowSwitcherAppEntry], + target: ForegroundTarget, records: [WindowSwitcherWindowRecord], + launchCheck: LaunchVisibilityCheck) -> FocusVisibility? { + let record = visibilityRecord(for: entry, among: entries, records: records) + if record?.isOnScreen == true && record?.isOnActiveSpace != false { return .onscreen } + if launchCheck != .none, record?.isOnActiveSpace == false, !entry.isMinimized { return .offscreen } + let missingLaunchWindow = launchCheck == .initial && record == nil && !entry.isMinimized + guard record?.isOnScreen == false || record?.isOnActiveSpace == false || missingLaunchWindow else { return nil } + let onscreen = foregroundOnscreenWindowNumbers(target: target, records: records) + guard !onscreen.isEmpty else { return nil } + if missingLaunchWindow, entry.windowNumber == nil { + // With no window number, a different AX-backed visible row + // provides the evidence needed to question the launch focus. + guard entries.contains(where: { other in + other.id != entry.id && other.windowElement != nil && isUsableWindow(other) + && other.windowNumber.map(onscreen.contains) == true + && !Self.sameBounds(entry.bounds, other.bounds) + }) else { return nil } + } + return .offscreen + } + + private func publishForegroundFocus(for foregroundPID: pid_t?) -> FocusIssue? { + let check = foregroundCheck + if let check, foregroundPID != check.pid { return nil } + guard inferredFocusWorkerLifetime != nil || !pendingFocus.isEmpty else { return nil } + let target = foregroundPID.flatMap { foregroundTarget(for: $0) } + let workerLifetime = target.flatMap { workers[$0.workerPID]?.lifetime } + if let inferredFocusWorkerLifetime, inferredFocusWorkerLifetime != workerLifetime { + self.inferredFocusWorkerLifetime = nil + publication.recency.clearInference() + } + guard !pendingFocus.isEmpty else { return nil } + let pending = target.flatMap { pendingFocus[$0.hostPID] } + pendingFocus.removeAll() + guard let target, let pending, pending.target == target, let focus = pending.observations[target.workerPID] else { + publication.recency.clearInference() + inferredFocusWorkerLifetime = nil + return nil + } + let entries = publication.entries.filter { $0.processIdentifier == target.hostPID } + var exactID = exactWindowID(for: focus, in: entries) + // Workspace can report the host for a focused helper. A cached active + // flag permits checking a helper's exact AX focus, but cannot infer it. + if exactID == nil, !focus.reportedFocusedWindow, target.workerPID == target.hostPID { + exactID = activeHelperFocusIDs(in: entries, pending: pending).first + } + // AX can finish before the current WindowServer read. Keep the focus + // observation for publication when the matching visibility is available. + let pairedInvocation = pending.confirmedOnly ? cancelledFocus?.generation + : check != nil ? invocationGeneration : nil + let awaitingInvocationVisibility = check?.phase.needsCapture == true + || (pairedInvocation != nil && pairedInvocation == pendingVisibilityInvocation) + let visibilityPending = check != nil + ? awaitingInvocationVisibility || !requiredCatalogScans.isEmpty + : windowRecordsPending || allSpacesRefreshTask != nil + var issue: FocusIssue? + if exactID == nil { + if focus.reportedFocusWasExcluded { + issue = .excludedAXFocus + } else if focus.reportedFocusedWindow { + issue = .unmatchedAXFocus + } else if check != nil, focus.unavailable { + issue = .incompleteAX + } + } + if awaitingInvocationVisibility + || (!pending.confirmedOnly && visibilityPending && exactID == nil + && (focus.canInfer || issue?.requiresAXConfirmation == true)) { + pendingFocus[target.hostPID] = pending + publication.recency.clearInference() + inferredFocusWorkerLifetime = nil + return nil + } + // A focus event can use a capture started after the event, including + // when another invalidation requests that capture in the same refresh. + let pairedCapture = invocationVisibility.flatMap { capture in + capture.generation == pairedInvocation && capture.foregroundPID == target.workerPID ? capture : nil + } + let latestCaptureFollowsFocusChange = pending.focusChangeAfterCapture.map { lastPublishedCapture > $0 } != false + let backgroundFocusCanUseCapture = pairedInvocation == nil && !visibilityPending && latestCaptureFollowsFocusChange + let cancelledFocusHasNewerCapture = pending.confirmedOnly && latestCaptureFollowsFocusChange + && pairedCapture.map { lastPublishedCapture > $0.capture } == true + let latestRecords = allSpacesRecordsAreFresh && (backgroundFocusCanUseCapture || cancelledFocusHasNewerCapture) + ? allSpacesRecords : nil + let pairedRecords = pairedCapture.flatMap { capture in + pending.focusChangeAfterCapture.map { capture.capture > $0 } != false ? capture.records : nil + } + var helperVerificationRecords = pairedRecords + let launching = applicationsByPID[target.workerPID].map(isLaunching) == true + if let exactID, let entry = entries.first(where: { $0.id == exactID }) { + // When cancelled, prefer a newer decisive observation and fall + // back to the paired capture if the new snapshot is inconclusive. + let launchCheck: LaunchVisibilityCheck + if !launching || pairedInvocation == nil { + launchCheck = .none + } else { + launchCheck = check?.phase == .initialScan || pending.confirmedOnly ? .initial : .retry + } + let latestVisibility = latestRecords.flatMap { + focusVisibility(of: entry, in: entries, target: target, records: $0, launchCheck: launchCheck) + } + let visibility = latestVisibility ?? pairedRecords.flatMap { + focusVisibility(of: entry, in: entries, target: target, records: $0, launchCheck: launchCheck) + } + if latestVisibility != nil { helperVerificationRecords = latestRecords } + let conflict = pending.confirmedOnly ? cancelledFocus?.conflict : check?.conflict + let repeatsUnverifiedFocus = pairedInvocation != nil && conflict.map { conflict in + exactID == conflict.id && pending.focusChangeAfterCapture.map { conflict.capture > $0 } != false + } == true && visibility != .onscreen + if visibility == .offscreen || repeatsUnverifiedFocus { + issue = .offscreenAX + if visibility == .offscreen, let pairedCapture { + foregroundCheck?.conflict = FocusConflict(id: exactID, capture: pairedCapture.capture) + } + } + } + if issue == .offscreenAX { + if let helperVerificationRecords { + let onscreen = foregroundOnscreenWindowNumbers(target: target, records: helperVerificationRecords) + let helperIDs = Set(activeHelperFocusIDs(in: entries, pending: pending)) + let verifiedHelpers = entries.filter { + $0.id != exactID && helperIDs.contains($0.id) && $0.windowElement != nil && isUsableWindow($0) + && visibilityRecord(for: $0, among: entries, records: helperVerificationRecords) + .map { onscreen.contains($0.windowNumber) } == true + } + if verifiedHelpers.count == 1 { + exactID = verifiedHelpers.first?.id + issue = nil + } + } + if issue == .offscreenAX, check != nil, !requiredCatalogScans.isEmpty { + pendingFocus[target.hostPID] = pending + return nil + } + } + if pending.confirmedOnly { + if issue != .offscreenAX, let exactID { + publication.recency.observeForeground(entries: entries, focusedWindowID: exactID, unavailable: focus.unavailable) + } + return nil + } + foregroundCheck?.focusRead = focus.readStartedAt.map { (target, $0) } + let canInferFromVisibility = check != nil ? pairedRecords != nil : latestCaptureFollowsFocusChange + let inferredID = exactID == nil && focus.canInfer && canInferFromVisibility + ? inferredForegroundWindowID(in: entries, target: target, requiresOnscreen: check != nil && launching) : nil + inferredFocusWorkerLifetime = inferredID == nil ? nil : workerLifetime + publication.recency.observeForeground(entries: entries, focusedWindowID: issue == .offscreenAX ? nil : exactID, + inferredWindowID: inferredID, unavailable: focus.unavailable) + return issue + } + + @discardableResult + private func updateForegroundTarget(_ current: pid_t?) -> Bool { + guard let check = foregroundCheck, current != check.pid else { return false } + foregroundCheck?.pid = current + foregroundCheck?.focusRead = nil + foregroundCheck?.conflict = nil + publication.recency.clearFocus() + inferredFocusWorkerLifetime = nil + let observedFocus = current.flatMap { foregroundTarget(for: $0) }.flatMap { target in + pendingFocus[target.hostPID].flatMap { pending in + pending.target == target && pending.foregroundAtScanStart == target ? pending : nil + } + } + pendingFocus.removeAll() + if current == ProcessInfo.processInfo.processIdentifier { + recordLocalFocus() + return false + } + if let observedFocus { + pendingFocus[observedFocus.target.hostPID] = observedFocus + } + // An observation started in the background can report the app's + // previous key window. A handoff needs a read started in foreground. + return current != nil + && observedFocus.flatMap { $0.observations[$0.target.workerPID]?.id } == nil + } + + private func needsForegroundRetry(for foregroundPID: pid_t, focusIssue: FocusIssue?) -> Bool { + guard let target = foregroundTarget(for: foregroundPID) else { + guard foregroundPID != ProcessInfo.processInfo.processIdentifier else { return false } + let replacesPreviousFocus = publication.recency.focusedID != nil + publication.recency.clearFocus() + let visible = allSpacesRecordsAreFresh && allSpacesRecords.contains { + $0.processIdentifier == foregroundPID && $0.isOnScreen == true && $0.isOnActiveSpace != false + } + let app = applicationsByPID[foregroundPID] + // A newly foreground accessory can become regular during launch. + // After its first attempt the old app no longer owns the anchor. + return visible || app.map(isLaunching) != false || (replacesPreviousFocus && app?.isRegular == false) + } + // A focus event can arrive after the foreground read while discovery + // is still waiting on another app. Resolve it before opening the chooser. + if let read = foregroundCheck?.focusRead, read.target == target, + let change = focusChanges[target.workerPID], change.receivedAt > read.startedAt { return true } + let entries = publication.entries.filter { $0.processIdentifier == target.hostPID } + let launching = applicationsByPID[target.workerPID].map(isLaunching) == true + let hasUsableFocus = entries.contains { $0.id == publication.recency.focusedID && isUsableWindow($0) } + // A launch may have no confirmed focus even after both reads finish. + // Give it the same one retry, unless AX identified an excluded window. + if launching, focusIssue?.requiresAXConfirmation == true + || (focusIssue != .excludedAXFocus && !hasUsableFocus) { + return true + } + guard allSpacesRecordsAreFresh else { return false } + let onscreen = foregroundOnscreenWindowNumbers(target: target) + let hasConfirmedOnscreenFocus = entries.contains { entry in + entry.id == publication.recency.confirmedFocusID + && visibilityRecord(for: entry, among: entries).map { onscreen.contains($0.windowNumber) } == true + } + let missingAX = !hasConfirmedOnscreenFocus + && hasUnresolvedOnscreenWindow(onscreen, in: entries, + requiresAXConfirmation: focusIssue?.requiresAXConfirmation == true) + let missingHelper = !(helperPIDsByHost[target.hostPID] ?? []) + .isSubset(of: scannedHelperPIDs[target.hostPID] ?? []) + return missingAX || focusIssue == .offscreenAX || missingHelper + } + + private func isLaunching(_ app: Application) -> Bool { + !app.isFinishedLaunching || app.launchDate.map { Date().timeIntervalSince($0) < 2 } == true + } + + private func startForegroundRetry() { + foregroundCheck?.phase = .retryDelay + foregroundRetryDelay = Task { [weak self] in + do { try await Task.sleep(for: .milliseconds(100)) } catch { return } + guard !Task.isCancelled, let self else { return } + foregroundRetryDelay = nil + let current = discovery.foregroundProcessIdentifier() + updateForegroundTarget(current) + guard let current, current != ProcessInfo.processInfo.processIdentifier else { + foregroundCheck?.phase = .retryScan + schedulePublication() + return + } + reloadForegroundApplication(current) + foregroundCheck?.phase = .retryCapture + windowRecordsPending = true + drainRefreshes() + } + } + + private func finishedForegroundCapture() { + guard let check = foregroundCheck else { return } + if check.phase == .initialCapture { + foregroundCheck?.phase = .initialScan + return + } + + foregroundCheck?.phase = .retryScan + let current = discovery.foregroundProcessIdentifier() + if current != check.pid { + reloadForegroundApplication(current) + updateForegroundTarget(current) + } + guard let current, let target = foregroundTarget(for: current), + current == check.pid || pendingFocus[target.hostPID]?.observations[target.workerPID]?.id == nil else { return } + foregroundCheck?.phase = .retryQueued(target.hostPID) + requiredCatalogScans.insert(target.hostPID) + dirtyHosts.insert(target.hostPID) + pendingFocus.removeValue(forKey: target.hostPID) + } + + /// Owns the chooser's readiness and the transition that spends its one retry. + /// Background scans can still publish windows and confirmed focus while it waits. + private func advanceForegroundCheck() -> Bool { + let current = discovery.foregroundProcessIdentifier() + let scansAreReady = isInitialDiscoveryComplete && requiredCatalogScans.isEmpty + && foregroundCheck?.phase.canFinish != false + let needsHandoffScan = scansAreReady && updateForegroundTarget(current) + let focusIssue = publishForegroundFocus(for: current) + guard scansAreReady, requiredCatalogScans.isEmpty else { + isInvocationReady = false + return false + } + if foregroundCheck?.phase == .initialScan, let current, + needsHandoffScan || needsForegroundRetry(for: current, focusIssue: focusIssue) { + startForegroundRetry() + isInvocationReady = false + return false + } + isInvocationReady = pendingFocus.isEmpty + guard isInvocationReady, let check = foregroundCheck else { return false } + foregroundCheck = nil + if !check.deferredRefreshes.isEmpty { + invalidate(processIdentifiers: check.deferredRefreshes, windowRecords: false) + } + return true + } + private func markPublicationDirty() { publicationDirty = true schedulePublication() @@ -514,18 +1118,13 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { removedProcesses.removeAll() rebuildPublication() } - for (pid, focus) in pendingFocus where activeWorkerPID(for: pid) != nil { - let entries = publication.entries.filter { $0.processIdentifier == pid } - let id = entries.first { ($0.workerWindowID ?? $0.id) == focus.id }?.id - publication.recency.observeForeground(entries: entries, focusedWindowID: id, unavailable: focus.unavailable) - } - pendingFocus.removeAll() isInitialDiscoveryComplete = didReadAllSpaces && expectedHostPIDs.allSatisfy { snapshots[$0] != nil } - isInvocationReady = isInitialDiscoveryComplete && !invocationRequiresRecords && invocationRequiredHosts.isEmpty + let completedInvocation = advanceForegroundCheck() if oldEntries != publication.entries || oldFocus != publication.recency.focusedID || wasComplete != isInitialDiscoveryComplete || wasReady != isInvocationReady { onChange?() } + if completedInvocation, windowRecordsPending { drainRefreshes() } } } @@ -534,11 +1133,18 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { windowRecordsPending = false let generation = allSpacesGeneration let invocation = invocationGeneration + let isInvocationCapture = foregroundCheck?.phase.needsCapture == true + let foregroundPIDAtCapture = isInvocationCapture ? discovery.foregroundProcessIdentifier() : nil + let foregroundAtCapture = foregroundPIDAtCapture.flatMap { foregroundTarget(for: $0)?.hostPID } + captureSequence += 1 + let capture = captureSequence + pendingVisibilityInvocation = isInvocationCapture ? invocation : nil allSpacesRefreshTask = Task { [weak self] in guard let self else { return } - let result = await allSpacesCatalog.freshWindowRecordSnapshot() + let result = await allSpacesCatalog.freshWindowRecordSnapshot(requiresNewCapture: isInvocationCapture) guard !Task.isCancelled, running, allSpacesGeneration == generation else { return } allSpacesRefreshTask = nil + pendingVisibilityInvocation = nil let oldRecords = Dictionary(grouping: allSpacesRecords, by: \.processIdentifier) let newRecords = Dictionary(grouping: result.records, by: \.processIdentifier) let changedOwners = Set(oldRecords.keys).union(newRecords.keys).filter { @@ -550,18 +1156,35 @@ final class WindowSwitcherAppCatalog: WindowSwitcherCatalog { allSpacesRecords = result.records helperPIDsByHost = processMapping.helpersByHost(owningWindowsIn: allSpacesRecords) allSpacesRecordsAreFresh = result.isFresh + lastPublishedCapture = capture + if isInvocationCapture { + invocationVisibility = InvocationVisibility(generation: invocation, foregroundPID: foregroundPIDAtCapture, + capture: capture, records: result.isFresh ? result.records : nil) + } if oldHelpers != helperPIDsByHost { reloadApplications() } + let foregroundRetryHost = isInvocationCapture && invocation == invocationGeneration + ? foregroundTarget()?.hostPID : nil // New helper ownership and missing AX events must schedule a scoped // scan, including when another read of that host is already active. for pid in expectedHostPIDs { let changed = changedOwners.contains { processMapping.host(for: $0) == pid } - if oldHelpers[pid] != helperPIDsByHost[pid] || (changed && snapshots[pid] != nil) { + let readingForeground = (pid == foregroundAtCapture || pid == foregroundRetryHost) + && inFlight.contains(pid) + guard oldHelpers[pid] != helperPIDsByHost[pid] + || (changed && (snapshots[pid] != nil || readingForeground)) else { continue } + // A required retry covers this change. Otherwise let the + // foreground host refresh after the chooser opens. + if pid == foregroundRetryHost { + foregroundCheck?.deferredRefreshes.insert(pid) + } else { dirtyHosts.insert(pid) } } didReadAllSpaces = true - if invocation == invocationGeneration { invocationRequiresRecords = false } - if !isInvocationReady { invocationRequiredHosts.formUnion(dirtyHosts) } + if invocation == invocationGeneration { + if isInvocationCapture { finishedForegroundCapture() } + if foregroundCheck == nil, !isInvocationReady { requiredCatalogScans.formUnion(dirtyHosts) } + } schedulePublication() drainRefreshes() } diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift index b677938df..7ca7a5d16 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherApplicationInventory.swift @@ -101,26 +101,26 @@ final class WindowSwitcherApplicationInventory { if notify, !changed.isEmpty { onChange?(changed) } } - func reload(processIdentifier: pid_t) { + func reload(processIdentifier: pid_t, notify: Bool = true) { for identity in entries.keys where entries[identity]?.application.processIdentifier == processIdentifier { - reload(identity) + reload(identity, notify: notify) break } } - private func reload(_ identity: AnyHashable) { + private func reload(_ identity: AnyHashable, notify: Bool = true) { guard running, var entry = entries[identity] else { return } let old = entry.application guard var application = entry.source.load(), application.processIdentifier > 0 else { entries.removeValue(forKey: identity) - onChange?([old.processIdentifier]) + if notify { onChange?([old.processIdentifier]) } return } application.lifetime = application.processIdentifier == old.processIdentifier ? old.lifetime : UUID() entry.application = application entries[identity] = entry - onChange?([old.processIdentifier, application.processIdentifier]) + if notify { onChange?([old.processIdentifier, application.processIdentifier]) } } private static func source(_ app: NSRunningApplication) -> Source { @@ -182,7 +182,8 @@ final class WindowSwitcherApplicationInventory { let active = application.isActive return Application(processIdentifier: pid, bundleIdentifier: metadata.bundleIdentifier, bundlePath: metadata.bundlePath, localizedName: nil, launchDate: metadata.launchDate, - isRegular: application.activationPolicy == .regular, isHidden: hidden, isActive: active, + isRegular: application.activationPolicy == .regular, isFinishedLaunching: application.isFinishedLaunching, + isHidden: hidden, isActive: active, loadPresentation: { self.value(isHidden: hidden, isActive: active) }) } diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift index be0f85946..8885769a2 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift @@ -829,6 +829,7 @@ final class WindowSwitcherPlugin: MacToolsPlugin, AccessibilityPermissionRefresh } private func cancelSession() { + let wasWaitingForDiscovery = pendingInvocation != nil shortcutTap.setSessionActive(false) shortcutTap.setEditing(false) sessionGeneration += 1 @@ -837,6 +838,7 @@ final class WindowSwitcherPlugin: MacToolsPlugin, AccessibilityPermissionRefresh pendingInvocation = nil; pendingRelease = false; pendingSteps = 0 overlayController.hide() session = nil + if wasWaitingForDiscovery { appCatalog.cancelInvocation() } } private func ensureAccessibilityForInvocation() -> Bool { diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift index ae8731327..1c1444ee7 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift @@ -20,6 +20,10 @@ struct WindowSwitcherScan: Sendable { var focusedID: String? var unavailable: Bool var windowListReadSucceeded = true + var reportedFocusedWindow = false + var reportedFocusWasExcluded = false + var excludedWindowNumbers: Set = [] + var focusReadStartedAt: ContinuousClock.Instant? } struct WindowSwitcherAXIdentity: Hashable { @@ -156,7 +160,8 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { windowSubscriptions.removeValue(forKey: old) } var indexes = Dictionary(uniqueKeysWithValues: records.enumerated().map { (WindowSwitcherAXIdentity(element: $0.element.element), $0.offset) }) - var excluded = Set() + var excluded = Set() + var excludedWindowNumbers = Set() var didRead = 0 var metadataFailed = false let count = windows.count @@ -172,39 +177,48 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { if let oldIndex { records[oldIndex] = snapshot } else { indexes[key] = records.count; records.append(snapshot) } if uptime() < deadline { observe(window) } - case .excluded: - if let oldIndex { excluded.insert(records[oldIndex].id) } + case let .excluded(number): + excluded.insert(key) + if let number { excludedWindowNumbers.insert(number) } case .unavailable: metadataFailed = true if let oldIndex { records[oldIndex].unavailable = true } } didRead += 1 } - records.removeAll { excluded.contains($0.id) } + records.removeAll { excluded.contains(WindowSwitcherAXIdentity(element: $0.element)) } cursor = count == 0 ? 0 : (cursor + didRead) % count - let focused = uptime() < deadline ? copyElement(app, kAXFocusedWindowAttribute) : nil + let focusReadStartedAt: ContinuousClock.Instant? = uptime() < deadline ? .now : nil + let focused = focusReadStartedAt != nil ? copyElement(app, kAXFocusedWindowAttribute) : nil let focusedID = focused.flatMap { element in records.first { CFEqual($0.element, element) }?.id } - return WindowSwitcherScan(windows: records, focusedID: focusedID, unavailable: metadataFailed || didRead < count) + return WindowSwitcherScan(windows: records, focusedID: focusedID, + unavailable: metadataFailed || didRead < count, reportedFocusedWindow: focused != nil, + reportedFocusWasExcluded: focused.map { excluded.contains(WindowSwitcherAXIdentity(element: $0)) } == true, + excludedWindowNumbers: excludedWindowNumbers, focusReadStartedAt: focusReadStartedAt) } - private enum Admission { case eligible(WindowSwitcherWindowSnapshot), excluded, unavailable } + private enum Admission { + case eligible(WindowSwitcherWindowSnapshot) + case excluded(CGWindowID? = nil) + case unavailable + } private func snapshot(_ window: AXUIElement, id: String) -> Admission { guard let values = access.windowAttributes(window), values.count == 6, let role = values[0] as? String else { return .unavailable } // A process root masquerading as a window is invalid AX data, not // evidence that the app has no user windows. if role == kAXApplicationRole as String { return .unavailable } - guard role == kAXWindowRole as String else { return .excluded } + guard role == kAXWindowRole as String else { return .excluded() } if let subrole = values[1] as? String, ![kAXStandardWindowSubrole as String, kAXDialogSubrole as String, "AXFullScreenWindow"].contains(subrole) { - return .excluded + return .excluded(access.windowNumber(window)) } guard let minimized = values[3] as? Bool, let point = decodePoint(values[4]), let size = decodeSize(values[5]) else { return .unavailable } guard point.x.isFinite, point.y.isFinite, size.width.isFinite, size.height.isFinite, size.width >= 0, size.height >= 0 else { return .unavailable } - guard minimized || (size.width >= 80 && size.height >= 60) else { return .excluded } + guard minimized || (size.width >= 80 && size.height >= 60) else { return .excluded() } let title = values[2] as? String ?? "" if !minimized, values[1] as? String == kAXDialogSubrole as String, @@ -215,7 +229,7 @@ final class WindowSwitcherProcessWorker: @unchecked Sendable { // Some apps expose empty, unfocused compositor surfaces as AX // dialogs even while WindowServer marks them visible. A dialog // with content or foreground status remains a selectable window. - return .excluded + return .excluded(access.windowNumber(window)) } let snapshot = WindowSwitcherWindowSnapshot(id: id, element: window, title: title, minimized: minimized, bounds: CGRect(origin: point, size: size), diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherPublishedWindows.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherPublishedWindows.swift index 17dd7c516..bac69898b 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherPublishedWindows.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherPublishedWindows.swift @@ -10,6 +10,11 @@ struct WindowSwitcherPublishedWindows { private var confirmedAXWindowNumbers: [pid_t: Set] = [:] private var axAliases: [pid_t: [String: String]] = [:] + func lostAXConfirmation(_ entry: WindowSwitcherAppEntry) -> Bool { + guard entry.windowElement == nil, let number = entry.windowNumber else { return false } + return confirmedAXWindowNumbers[entry.processIdentifier]?.contains(number) == true + } + mutating func removeProcess(_ pid: pid_t) { knownWindowIDs.removeValue(forKey: pid) axAliases.removeValue(forKey: pid) diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift index b47c3a243..24dddfc36 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift @@ -133,30 +133,42 @@ struct WindowSwitcherSession { struct WindowSwitcherRecency { private(set) var ids: [String] = [] - private(set) var focusedID: String? + private(set) var confirmedFocusID: String? + private var inferredFocusID: String? + var focusedID: String? { inferredFocusID ?? confirmedFocusID } - mutating func observeForeground(entries: [WindowSwitcherAppEntry], focusedWindowID: String?, unavailable: Bool) { + mutating func observeForeground(entries: [WindowSwitcherAppEntry], focusedWindowID: String?, + inferredWindowID: String? = nil, unavailable: Bool) { if let focusedWindowID, entries.contains(where: { $0.id == focusedWindowID }) { record(focusedWindowID) } else if !unavailable, entries.count == 1, let fallback = entries.first, !fallback.isWindowEntry { record(fallback.id) } else { - // An unknown foreground target must not keep another app's window - // marked current. Keep its recency position, but clear the anchor. - focusedID = nil + // Inferred focus can lead the current order without changing history. + confirmedFocusID = nil + inferredFocusID = inferredWindowID } } + mutating func clearInference() { inferredFocusID = nil } + mutating func clearFocus() { + confirmedFocusID = nil + clearInference() + } + mutating func record(_ id: String) { - focusedID = id + clearInference() + confirmedFocusID = id ids.removeAll { $0 == id } ids.insert(id, at: 0) } mutating func retain(_ live: Set) { ids.removeAll { !live.contains($0) } - if let focusedID, !live.contains(focusedID) { self.focusedID = nil } + if let confirmedFocusID, !live.contains(confirmedFocusID) { self.confirmedFocusID = nil } + if let inferredFocusID, !live.contains(inferredFocusID) { clearInference() } } func sort(_ entries: [WindowSwitcherAppEntry]) -> [WindowSwitcherAppEntry] { - let ranks = Dictionary(uniqueKeysWithValues: ids.enumerated().map { ($0.element, $0.offset) }) + var ranks = Dictionary(uniqueKeysWithValues: ids.enumerated().map { ($0.element, $0.offset) }) + if let inferredFocusID { ranks[inferredFocusID] = -1 } return entries.enumerated().sorted { let lhs = ranks[$0.element.id] ?? Int.max let rhs = ranks[$1.element.id] ?? Int.max diff --git a/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift b/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift index ddec1f790..5fd8116ff 100644 --- a/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift +++ b/Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift @@ -137,15 +137,19 @@ struct WindowSwitcherWindowRecordSnapshot: Sendable { /// Slow system reads are bounded and stale data can never authorize an action. @MainActor final class WindowSwitcherWindowRecords { + private struct Capture { + let task: Task<[WindowSwitcherWindowRecord]?, Never> + let timeout: Task + var waiters: [UUID: CheckedContinuation] = [:] + } + private static let maxWindowRecordRefreshesInFlight = 2 private let windowRecordProvider: @Sendable () -> [WindowSwitcherWindowRecord]? private let windowRecordRefreshTimeout: TimeInterval private var windowRecords: [WindowSwitcherWindowRecord] = [] - private var windowRecordRefreshTask: Task<[WindowSwitcherWindowRecord]?, Never>? + private var captures: [UInt64: Capture] = [:] private var windowRecordRefreshGeneration: UInt64 = 0 private var windowRecordRefreshInFlightCount = 0 - private var timeoutTask: Task? - private var waiters: [UUID: CheckedContinuation] = [:] init(windowRecordRefreshTimeout: TimeInterval = 0.75, windowRecordProvider: @escaping @Sendable () -> [WindowSwitcherWindowRecord]? = { @@ -158,13 +162,10 @@ final class WindowSwitcherWindowRecords { } func stop() { - windowRecordRefreshGeneration &+= 1 - windowRecordRefreshTask?.cancel() - windowRecordRefreshTask = nil - timeoutTask?.cancel() - timeoutTask = nil windowRecords.removeAll() - finishWaiters(isFresh: false) + for generation in Array(captures.keys) { + finishCapture(generation, records: nil) + } } func windowRecordsSnapshot() async -> [WindowSwitcherWindowRecord] { @@ -213,12 +214,8 @@ final class WindowSwitcherWindowRecords { return record } - private func refreshWindowRecords() { - guard windowRecordRefreshTask == nil, - windowRecordRefreshInFlightCount < Self.maxWindowRecordRefreshesInFlight - else { - return - } + private func startCapture() -> UInt64? { + guard windowRecordRefreshInFlightCount < Self.maxWindowRecordRefreshesInFlight else { return nil } windowRecordRefreshGeneration &+= 1 let generation = windowRecordRefreshGeneration @@ -227,87 +224,63 @@ final class WindowSwitcherWindowRecords { let task = Task.detached(priority: .userInitiated) { provider() } - windowRecordRefreshTask = task - let timeout = windowRecordRefreshTimeout - timeoutTask = Task { [weak self] in - do { try await Task.sleep(for: .seconds(timeout)) } catch { return } - self?.abandonWindowRecordRefresh(generation: generation) + let timeout = Task { [weak self, windowRecordRefreshTimeout] in + do { try await Task.sleep(for: .seconds(windowRecordRefreshTimeout)) } catch { return } + self?.finishCapture(generation, records: nil) } + captures[generation] = Capture(task: task, timeout: timeout) Task { @MainActor [weak self] in let records = await task.value - guard let self, - self.windowRecordRefreshInFlightCount > 0 - else { - return - } - self.windowRecordRefreshInFlightCount -= 1 - - guard self.windowRecordRefreshGeneration == generation else { - return - } - - guard self.windowRecordRefreshTask != nil else { - return - } - - self.windowRecordRefreshTask = nil - self.timeoutTask?.cancel() - self.timeoutTask = nil - // Failure is not a successful empty scan. Retain the last snapshot - // for presentation, but never mark it fresh enough for an action. - if let records { - self.windowRecords = records - } - self.finishWaiters(isFresh: records != nil) + guard let self else { return } + windowRecordRefreshInFlightCount -= 1 + finishCapture(generation, records: records) } + return generation } private func freshWindowRecords() async -> [WindowSwitcherWindowRecord] { await freshWindowRecordSnapshot().records } - func freshWindowRecordSnapshot() async -> WindowSwitcherWindowRecordSnapshot { + func freshWindowRecordSnapshot(requiresNewCapture: Bool = false) async -> WindowSwitcherWindowRecordSnapshot { guard !Task.isCancelled else { return .init(records: windowRecords, isFresh: false) } - refreshWindowRecords() - guard windowRecordRefreshTask != nil else { + // An older read can still be physically running after a newer one + // completes. Joining it cannot provide fresh validation. + let latest = windowRecordRefreshGeneration + let joinable = captures[latest] == nil ? nil : latest + let generation = requiresNewCapture ? startCapture() : joinable ?? startCapture() + guard let generation else { return WindowSwitcherWindowRecordSnapshot(records: windowRecords, isFresh: false) } let id = UUID() return await withTaskCancellationHandler { await withCheckedContinuation { continuation in - guard !Task.isCancelled else { + guard !Task.isCancelled, captures[generation] != nil else { continuation.resume(returning: .init(records: windowRecords, isFresh: false)) return } - waiters[id] = continuation + captures[generation]?.waiters[id] = continuation } } onCancel: { Task { @MainActor [weak self] in guard let self else { return } - waiters.removeValue(forKey: id)?.resume(returning: .init(records: windowRecords, isFresh: false)) + captures[generation]?.waiters.removeValue(forKey: id)? + .resume(returning: .init(records: windowRecords, isFresh: false)) } } } - private func abandonWindowRecordRefresh(generation: UInt64) { - guard windowRecordRefreshGeneration == generation else { - return - } - - windowRecordRefreshTask?.cancel() - windowRecordRefreshTask = nil - windowRecordRefreshGeneration &+= 1 - timeoutTask?.cancel() - timeoutTask = nil - finishWaiters(isFresh: false) - } - - private func finishWaiters(isFresh: Bool) { - let pending = waiters - waiters.removeAll() - let snapshot = WindowSwitcherWindowRecordSnapshot(records: windowRecords, isFresh: isFresh) - for continuation in pending.values { continuation.resume(returning: snapshot) } + private func finishCapture(_ generation: UInt64, records: [WindowSwitcherWindowRecord]?) { + guard let capture = captures.removeValue(forKey: generation) else { return } + capture.timeout.cancel() + if records == nil { capture.task.cancel() } + // A newer attempt supersedes an older capture even if it fails. + let isFresh = records != nil && generation == windowRecordRefreshGeneration + if isFresh, let records { windowRecords = records } + let snapshot = WindowSwitcherWindowRecordSnapshot(records: windowRecords, + isFresh: isFresh) + for continuation in capture.waiters.values { continuation.resume(returning: snapshot) } } } diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift index 3c98f089b..cbc8a0602 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherAppCatalogTests.swift @@ -7,6 +7,14 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable struct State { var number: CGWindowID? var focused = false + var exposesWindowNumber = true + var exposesSecondaryWindowNumber = true + var includesSecondaryWindow = true + var focusesSecondaryWindow = false + var secondaryWindowIsSmall = false + var secondaryWindowIsFloating = false + var secondaryMetadataUnavailable = false + var windowListUnavailable = false var beforeRead: (() -> Void)? var reads = 0 var actions: [String] = [] @@ -14,30 +22,71 @@ private final class CatalogAXAccess: WindowSwitcherAXAccess, @unchecked Sendable private let lock = NSLock() private var state: State private let window: AXUIElement + private let replacement: AXUIElement? + private let replacementNumber: CGWindowID? + private let emptyDialog: AXUIElement? + private let emptyDialogNumber: CGWindowID? + private let secondaryWindow: AXUIElement? + private let secondaryWindowNumber: CGWindowID? let observesSystemNotifications = false - init(number: CGWindowID?, elementPID: pid_t) { + init(number: CGWindowID?, elementPID: pid_t, replacementNumber: CGWindowID? = nil, + emptyDialogNumber: CGWindowID? = nil, secondaryWindowNumber: CGWindowID? = nil) { state = State(number: number) window = AXUIElementCreateApplication(elementPID) + self.replacementNumber = replacementNumber + replacement = replacementNumber.map { _ in AXUIElementCreateApplication(elementPID + 100) } + self.emptyDialogNumber = emptyDialogNumber + emptyDialog = emptyDialogNumber.map { _ in AXUIElementCreateApplication(elementPID + 200) } + self.secondaryWindowNumber = secondaryWindowNumber + secondaryWindow = secondaryWindowNumber.map { _ in AXUIElementCreateApplication(elementPID + 300) } } func update(_ body: (inout State) -> Void) { lock.lock(); defer { lock.unlock() }; body(&state) } func read(_ body: (State) -> T) -> T { lock.lock(); defer { lock.unlock() }; return body(state) } func windows(of application: AXUIElement) -> [AXUIElement]? { update { $0.reads += 1 } read { $0.beforeRead }?() - return read { $0.number == nil ? [] : [window] } + return read { state in + guard !state.windowListUnavailable else { return nil } + let main = state.number.map { $0 == replacementNumber ? replacement ?? window : window } + let other = state.includesSecondaryWindow && state.number != secondaryWindowNumber ? secondaryWindow : nil + return [main, emptyDialog, other].compactMap { $0 } + } } func element(_ owner: AXUIElement, attribute: String) -> AXUIElement? { - if attribute == kAXFocusedWindowAttribute, read({ $0.focused }) { return window } + if attribute == kAXFocusedWindowAttribute { + return read { state in + if state.focusesSecondaryWindow { return secondaryWindow } + return state.focused ? window : nil + } + } return attribute == kAXCloseButtonAttribute ? owner : nil } func windowAttributes(_ window: AXUIElement) -> [Any]? { + let isDialog = emptyDialog.map { CFEqual($0, window) } == true + let isSecondary = secondaryWindow.map { CFEqual($0, window) } == true + if isSecondary, read({ $0.secondaryMetadataUnavailable }) { return nil } var point = CGPoint(x: 20, y: 20) - var size = CGSize(width: 800, height: 600) - return [kAXWindowRole, kAXStandardWindowSubrole, "Fixture", false, + if isDialog { point = CGPoint(x: 30, y: 30) } + if isSecondary { point = CGPoint(x: 60, y: 60) } + var size = isDialog ? CGSize(width: 400, height: 300) : CGSize(width: 800, height: 600) + if isSecondary, read({ $0.secondaryWindowIsSmall }) { size = CGSize(width: 40, height: 30) } + let subrole = isDialog ? kAXDialogSubrole + : isSecondary && read({ $0.secondaryWindowIsFloating }) ? "AXFloatingWindow" : kAXStandardWindowSubrole + return [kAXWindowRole, subrole, isDialog ? "" : "Fixture", false, AXValueCreate(.cgPoint, &point)!, AXValueCreate(.cgSize, &size)!] } - func windowNumber(_ window: AXUIElement) -> CGWindowID? { read { $0.number } } + func windowNumber(_ window: AXUIElement) -> CGWindowID? { + if emptyDialog.map({ CFEqual($0, window) }) == true { return emptyDialogNumber } + if secondaryWindow.map({ CFEqual($0, window) }) == true { + return read { $0.exposesSecondaryWindowNumber ? secondaryWindowNumber : nil } + } + return read { $0.exposesWindowNumber ? $0.number : nil } + } + func boolValue(_ window: AXUIElement, attribute: String) -> Bool? { + emptyDialog.map { CFEqual($0, window) } == true ? false : nil + } + func childCount(_ window: AXUIElement) -> Int? { emptyDialog.map { CFEqual($0, window) } == true ? 0 : nil } func minimized(_ window: AXUIElement) -> Bool? { false } func set(_ element: AXUIElement, attribute: String, value: Bool) -> AXError { .success } func perform(_ element: AXUIElement, action: String) -> AXError { @@ -152,6 +201,1479 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(numbers(catalog), [9]) } + func testNewlyLaunchedForegroundWindowRanksFirstBeforeAccessibilityReportsFocus() async throws { + let first = CatalogAXAccess(number: 7, elementPID: 201) + first.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + var launchedExists = false + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? first : launched }, + allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + let first = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "first", localizedName: "First", isActive: true) + let launched = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched") + return launchedExists ? [first, launched] : [first] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + launchedExists = true + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + + foregroundPID = 42 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7, 8]) + } + + func testInvocationRetriesForegroundDiscoveryOnceWhenWindowServerSeesAWindow() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + launched.update { + $0.beforeRead = { [weak launched] in + launched?.update { state in + guard state.reads == 2 else { return } + state.number = 8 + state.focused = true + } + } + } + var launchedExists = false + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Launched", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600))] + }), + discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let launched = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched") + return launchedExists ? [previous, launched] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + launchedExists = true + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [8, 7]) + + launched.update { + $0.number = nil + $0.focused = false + $0.beforeRead = nil + } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 4) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7]) + } + + func testColdLaunchRecapturesWindowServerWhenNeitherSourceHasAWindowYet() async throws { + try await verifyRetryUsesNewVisibility(initialRecords: []) + } + + func testRetryReplacesSplashVisibilityBeforeInferringFocus() async throws { + let splash = WindowSwitcherWindowRecord(windowNumber: 9, processIdentifier: 43, title: "", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600), titleIsAvailable: false) + try await verifyRetryUsesNewVisibility(initialRecords: [splash]) + } + + private func verifyRetryUsesNewVisibility(initialRecords: [WindowSwitcherWindowRecord]) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + let emptyCaptures = DispatchSemaphore(value: 2) + defer { emptyCaptures.signal(); emptyCaptures.signal() } + let record = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Launched", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + let retryCaptureStarted = DispatchSemaphore(value: 0) + let finishRetryCapture = DispatchSemaphore(value: 0) + defer { finishRetryCapture.signal() } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + if emptyCaptures.wait(timeout: .now()) == .success { return initialRecords } + retryCaptureStarted.signal() + _ = finishRetryCapture.wait(timeout: .now() + 1) + launched.update { $0.number = 8; $0.focused = initialRecords.isEmpty } + return [record] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched", + isFinishedLaunching: false) + return foregroundPID == 43 ? [prior, new] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { retryCaptureStarted.wait(timeout: .now()) == .success } + XCTAssertEqual(launched.read { $0.reads }, 1) + finishRetryCapture.signal() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 2) + } + + func testSingleForegroundAXWindowWithoutNumberDoesNotNeedAnExtraScan() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + launched.update { $0.exposesWindowNumber = false } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Foreground", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600))] + }), discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground") + return foregroundPID == 43 ? [previous, new] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + for reportedFocus in [false, true] { + let readsBeforeInvocation = launched.read { $0.reads } + launched.update { $0.focused = reportedFocus } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.map(\.processIdentifier), [43, 42]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertNil(entries.first?.windowNumber) + XCTAssertEqual(launched.read { $0.reads }, readsBeforeInvocation + 1) + } + } + + func testVisibilityCountsNumberedAndUnnumberedOnscreenRowsAsSeparateCandidates() async throws { + try await verifyTwoAXWindows(secondaryOnscreen: true, secondaryNumbered: true) + } + + func testVisibilityCanIdentifyTheOnlyOnscreenUnnumberedAXWindow() async throws { + try await verifyTwoAXWindows(secondaryOnscreen: false, secondaryNumbered: false) + } + + private func verifyTwoAXWindows(secondaryOnscreen: Bool, secondaryNumbered: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + launched.update { + $0.exposesWindowNumber = false + $0.exposesSecondaryWindowNumber = secondaryNumbered + } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + [ + .init(windowNumber: 8, processIdentifier: 43, title: "First", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 9, processIdentifier: 43, title: "Second", isOnScreen: secondaryOnscreen, + bounds: CGRect(x: 60, y: 60, width: 800, height: 600), hasSpace: true, + isOnActiveSpace: secondaryOnscreen), + ] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + return foregroundPID == 43 + ? [prior, .init(processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground")] + : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + if secondaryOnscreen { + XCTAssertNil(catalog.focusedWindowID) + XCTAssertEqual(entries.first?.windowNumber, 7) + } else { + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(entries.first?.processIdentifier, 43) + XCTAssertEqual(entries.first?.bounds.origin, CGPoint(x: 20, y: 20)) + XCTAssertNil(entries.first?.windowNumber) + } + } + + func testInvocationReconcilesForegroundAppThatJoinsInventoryAfterPreparation() async throws { + try await verifyLateForegroundEligibility(startsAsAccessory: false) + } + + func testInvocationReconcilesAccessoryAppThatBecomesRegularDuringLaunch() async throws { + try await verifyLateForegroundEligibility(startsAsAccessory: true) + } + + private func verifyLateForegroundEligibility(startsAsAccessory: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + launched.update { $0.focused = true } + var foregroundPID: pid_t = 42 + var isRegular = false + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched", isRegular: isRegular) + return isRegular || startsAsAccessory ? [previous, new] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + XCTAssertNotNil(catalog.focusedWindowID) + + foregroundPID = 43 + catalog.prepareForInvocation() + isRegular = true + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 1) + } + + func testUnnumberedAXWindowWithAmbiguousBoundsCannotBecomeAnchor() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let restoring = CatalogAXAccess(number: 8, elementPID: 202) + restoring.update { $0.exposesWindowNumber = false } + let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : restoring }, + allSpacesCatalog: .init(windowRecordProvider: { + [ + .init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, + bounds: bounds, hasSpace: true, isOnActiveSpace: false), + .init(windowNumber: 9, processIdentifier: 43, title: "Foreground", isOnScreen: true, + bounds: bounds, hasSpace: true, isOnActiveSpace: true), + ] + }), discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground") + return foregroundPID == 43 ? [previous, new] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 7) + XCTAssertNil(catalog.focusedWindowID) + XCTAssertEqual(restoring.read { $0.reads }, 2) + } + + func testBackgroundExactFocusIgnoresVisibilityAwaitingReplacement() async throws { + try await verifyBackgroundExactFocus(refreshesVisibility: true) + } + + func testBackgroundFocusOnlyEventIgnoresStaleVisibility() async throws { + try await verifyBackgroundExactFocus(refreshesVisibility: false) + } + + func testFollowupAXRefreshKeepsFocusNewerThanVisibility() async throws { + try await verifyBackgroundExactFocus(refreshesVisibility: false, followsUpWithoutVisibility: true) + } + + private func verifyBackgroundExactFocus(refreshesVisibility: Bool, followsUpWithoutVisibility: Bool = false) async throws { + let foreground = CatalogAXAccess(number: 9, elementPID: 201, + secondaryWindowNumber: followsUpWithoutVisibility ? 10 : nil) + foreground.update { + $0.focused = true + $0.includesSecondaryWindow = false + } + let initialCapture = DispatchSemaphore(value: 1) + let releaseCapture = DispatchSemaphore(value: 0) + let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { _ in foreground }, + allSpacesCatalog: .init(windowRecordProvider: { + let initial = initialCapture.wait(timeout: .now()) == .success + if !initial { _ = releaseCapture.wait(timeout: .now() + 2) } + let current: CGWindowID = initial ? 9 : 8 + return [8, 9].map { number in + .init(windowNumber: number, processIdentifier: 42, title: "Window", isOnScreen: number == current, + bounds: bounds, hasSpace: true, isOnActiveSpace: number == current) + } + }), discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "foreground", localizedName: "Foreground")] + }, foregroundProcessIdentifier: { 42 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { initialCapture.signal(); releaseCapture.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foreground.update { $0.number = 8 } + if refreshesVisibility { + catalog.refresh() + } else { + catalog.invalidate(processIdentifiers: [42], windowRecords: false, focusChanged: true) + } + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 && $0.windowElement != nil } + } + let focused = catalog.entries(sortMode: .recentUse).first { $0.id == catalog.focusedWindowID } + XCTAssertEqual(focused?.windowNumber, 8) + + if followsUpWithoutVisibility { + foreground.update { $0.includesSecondaryWindow = true } + catalog.invalidate(processIdentifiers: [42], windowRecords: false) + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 10 && $0.windowElement != nil } + } + XCTAssertEqual(catalog.focusedWindowID, focused?.id) + } + } + + func testExcludedOnscreenDialogDoesNotPreventInferringTheForegroundWindow() async throws { + try await verifyExcludedOnscreenSurface(floating: false) + } + + func testExcludedFloatingPanelCannotBecomeInferredFocus() async throws { + try await verifyExcludedOnscreenSurface(floating: true) + } + + private func verifyExcludedOnscreenSurface(floating: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let foreground = CatalogAXAccess(number: 8, elementPID: 202, emptyDialogNumber: floating ? nil : 9, + secondaryWindowNumber: floating ? 9 : nil) + foreground.update { $0.secondaryWindowIsFloating = floating } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : foreground }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Foreground", isOnScreen: !floating, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true, isOnActiveSpace: !floating), + .init(windowNumber: 9, processIdentifier: 43, title: floating ? "Tools" : "", isOnScreen: true, + bounds: floating ? CGRect(x: 60, y: 60, width: 800, height: 600) + : CGRect(x: 30, y: 30, width: 400, height: 300))] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground") + return foregroundPID == 43 ? [prior, new] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + if floating { + XCTAssertEqual(entries.first?.windowNumber, 7) + XCTAssertNil(catalog.focusedWindowID) + } else { + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + XCTAssertEqual(foreground.read { $0.reads }, 1) + } + + func testMissingSplashInFreshVisibilityRetriesBeforeRecordingRecentUse() async throws { + try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: false, omitsSplash: true) + } + + func testForeignWindowServerOwnerCannotConfirmLaunchFocus() async throws { + try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: false, splashHasForeignOwner: true) + } + + func testOffscreenReportedFocusRetriesBeforeRecordingRecentUse() async throws { + try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: false) + } + + func testPartiallyReadableForegroundAXRetriesBeforeRelyingOnCGFallback() async throws { + try await verifyLaunchFocusRecovery(partialAX: true, failsRetryCapture: false) + } + + func testFailedRetryCaptureDoesNotConfirmRepeatedOffscreenAXFocus() async throws { + try await verifyLaunchFocusRecovery(partialAX: false, failsRetryCapture: true) + } + + func testReportedLaunchFocusRetriesWhenVisibilityOnlyShowsAnOlderListedWindow() async throws { + let splash = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Splash", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + try await verifyLaunchWindowRetry(records: [splash]) + } + + func testIncompleteLaunchAXRetriesWhenVisibilityOnlyShowsAnOlderListedWindow() async throws { + let splash = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Splash", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + try await verifyLaunchWindowRetry(records: [splash], partialInitialAXRead: true) + } + + func testReportedLaunchFocusRetriesWhenVisibilityCaptureFails() async throws { + try await verifyLaunchWindowRetry(records: nil) + } + + func testLaunchRetriesWhenBothInitialWindowSourcesFail() async throws { + try await verifyLaunchWindowRetry(records: nil, failsInitialAXRead: true) + } + + func testLaunchRetriesWhenAccessibilityListsTwoWindowsWithoutFocus() async throws { + let records: [WindowSwitcherWindowRecord] = [ + .init(windowNumber: 8, processIdentifier: 43, title: "Primary", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 9, processIdentifier: 43, title: "Document", + isOnScreen: true, bounds: CGRect(x: 60, y: 60, width: 800, height: 600)), + ] + try await verifyLaunchWindowRetry(records: records, waitsForFocus: true) + } + + func testLaunchRetriesWhenVisibilityFailsAndAccessibilityReturnsAnEmptyList() async throws { + try await verifyLaunchWindowRetry(records: nil, initiallyEmpty: true) + } + + func testLaunchFocusOnAnAlreadyExcludedWindowDoesNotRetry() async throws { + let primary = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Primary", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + try await verifyLaunchWindowRetry(records: [primary], secondaryWindowIsSmall: true) + } + + func testUncorroboratedLaunchSplashStillAllowsTheRetry() async throws { + try await verifyLaunchFocusAppearingAfterRetryCapture(.inferredSplash) + } + + func testOffSpaceLaunchFocusDoesNotEnterHistoryBeforeRetry() async throws { + try await verifyLaunchFocusAppearingAfterRetryCapture(.offSpaceRestoration) + } + + func testOffSpaceFocusReportedOnRetryDoesNotEnterLaunchHistory() async throws { + try await verifyLaunchFocusAppearingAfterRetryCapture(.offSpaceFocusOnRetry) + } + + func testUnnumberedSplashDoesNotDisplaceAnAXBackedLaunchDocument() async throws { + try await verifyLaunchFocusAppearingAfterRetryCapture(.unnumberedSplash) + } + + private enum LaunchFocusFixture { + case inferredSplash, offSpaceRestoration, offSpaceFocusOnRetry, unnumberedSplash + } + + private func verifyLaunchFocusAppearingAfterRetryCapture(_ fixture: LaunchFocusFixture) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, replacementNumber: 9, secondaryWindowNumber: 9) + launched.update { + $0.focused = fixture == .offSpaceRestoration || fixture == .unnumberedSplash + $0.exposesWindowNumber = fixture != .unnumberedSplash + $0.includesSecondaryWindow = fixture == .unnumberedSplash + } + let initialCaptures = DispatchSemaphore(value: 2) + defer { initialCaptures.signal(); initialCaptures.signal() } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + let restored = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 43, title: "Restored elsewhere", + isOnScreen: false, bounds: CGRect(x: 20, y: 20, width: 800, height: 600), + hasSpace: true, isOnActiveSpace: false) + let origin = fixture == .inferredSplash ? CGPoint(x: 20, y: 20) : CGPoint(x: 60, y: 60) + let document = WindowSwitcherWindowRecord(windowNumber: 9, processIdentifier: 43, title: "Actual window", + isOnScreen: true, bounds: CGRect(origin: origin, size: CGSize(width: 800, height: 600))) + let restoredWindows = fixture == .offSpaceRestoration || fixture == .offSpaceFocusOnRetry ? [restored] : [] + if initialCaptures.wait(timeout: .now()) == .success { + return fixture == .unnumberedSplash ? [document] : restoredWindows + } + if fixture == .offSpaceFocusOnRetry { + launched.update { $0.focused = true } + return restoredWindows + } + launched.update { + if fixture == .inferredSplash { + $0.number = 9 + } else { + $0.includesSecondaryWindow = true + $0.focusesSecondaryWindow = true + } + } + return restoredWindows + [document] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application(processIdentifier: 42, localizedName: "Previous") + guard foregroundPID == 43 else { return [prior] } + return [prior, .init(processIdentifier: 43, localizedName: "Launched", isFinishedLaunching: false)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + if fixture == .offSpaceFocusOnRetry { + XCTAssertEqual(entries.compactMap(\.windowNumber), [7, 8]) + XCTAssertNil(catalog.focusedWindowID) + } else { + XCTAssertEqual(entries.compactMap(\.windowNumber), fixture == .offSpaceRestoration ? [9, 7, 8] : [9, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + XCTAssertEqual(launched.read { $0.reads }, 2) + } + + private func verifyLaunchWindowRetry(records: [WindowSwitcherWindowRecord]?, + secondaryWindowIsSmall: Bool = false, + failsInitialAXRead: Bool = false, + partialInitialAXRead: Bool = false, waitsForFocus: Bool = false, + initiallyEmpty: Bool = false) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: initiallyEmpty ? nil : 8, elementPID: 202, secondaryWindowNumber: 9) + launched.update { + $0.includesSecondaryWindow = secondaryWindowIsSmall || partialInitialAXRead || waitsForFocus + $0.focusesSecondaryWindow = !partialInitialAXRead && !waitsForFocus && !initiallyEmpty + $0.secondaryWindowIsSmall = secondaryWindowIsSmall + $0.secondaryMetadataUnavailable = partialInitialAXRead + $0.windowListUnavailable = failsInitialAXRead + $0.beforeRead = { [weak launched] in + launched?.update { state in + if state.reads == 2 { + state.number = 8 + state.windowListUnavailable = false + state.includesSecondaryWindow = true + state.secondaryMetadataUnavailable = false + state.focusesSecondaryWindow = true + } + } + } + } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { records }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched", + isFinishedLaunching: false) + return foregroundPID == 43 ? [prior, new] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + if secondaryWindowIsSmall { + XCTAssertEqual(entries.compactMap(\.windowNumber), [7, 8]) + XCTAssertNil(catalog.focusedWindowID) + XCTAssertEqual(launched.read { $0.reads }, 1) + } else { + XCTAssertEqual(entries.compactMap(\.windowNumber), [9, 7, 8]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 2) + } + } + + private func verifyLaunchFocusRecovery(partialAX: Bool, failsRetryCapture: Bool, omitsSplash: Bool = false, + splashHasForeignOwner: Bool = false) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: partialAX ? 9 : nil) + let initialCaptures = DispatchSemaphore(value: 2) + defer { initialCaptures.signal(); initialCaptures.signal() } + launched.update { + $0.focused = !partialAX + $0.secondaryMetadataUnavailable = partialAX + $0.beforeRead = { [weak launched] in + launched?.update { state in + guard state.reads == 2, !failsRetryCapture else { return } + state.number = 9 + state.focused = true + } + } + } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + if initialCaptures.wait(timeout: .now()) != .success, failsRetryCapture { return nil } + let splash = WindowSwitcherWindowRecord(windowNumber: 8, + processIdentifier: splashHasForeignOwner ? 44 : 43, title: "Restoring", + isOnScreen: splashHasForeignOwner, bounds: CGRect(x: 20, y: 20, width: 800, height: 600), + hasSpace: true, isOnActiveSpace: splashHasForeignOwner) + let document = WindowSwitcherWindowRecord(windowNumber: 9, processIdentifier: 43, title: "Launched", + isOnScreen: true, bounds: CGRect(x: 40, y: 40, width: 800, height: 600)) + return omitsSplash ? [document] : [splash, document] + }), + discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let new = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched", + isFinishedLaunching: !omitsSplash && !splashHasForeignOwner) + return foregroundPID == 43 ? [prior, new] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 2) + let entries = catalog.entries(sortMode: .recentUse) + if failsRetryCapture { + XCTAssertEqual(entries.first?.windowNumber, 7) + XCTAssertNil(catalog.focusedWindowID) + } else { + XCTAssertEqual(entries.compactMap(\.windowNumber), omitsSplash || splashHasForeignOwner ? [9, 7] : [9, 7, 8]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + } + + func testInvocationPublishesBeforeQueuedBackgroundVisibilityReadCompletes() async throws { + let access = CatalogAXAccess(number: 7, elementPID: 201) + let blockRead = DispatchSemaphore(value: 0) + let readStarted = DispatchSemaphore(value: 0) + let releaseRead = DispatchSemaphore(value: 0) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { _ in access }, + allSpacesCatalog: .init(windowRecordRefreshTimeout: 5, windowRecordProvider: { + if blockRead.wait(timeout: .now()) == .success { + readStarted.signal() + _ = releaseRead.wait(timeout: .now() + 5) + } + return [] + }), + discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "fixture", localizedName: "Fixture")] + }, foregroundProcessIdentifier: { 42 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseRead.signal(); releaseRead.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + blockRead.signal() + blockRead.signal() + catalog.prepareForInvocation() + try await waitUntil { readStarted.wait(timeout: .now()) == .success } + XCTAssertFalse(catalog.isInvocationReady) + catalog.refresh() + releaseRead.signal() + + try await waitUntil { readStarted.wait(timeout: .now()) == .success } + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.first?.windowNumber, 7) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + + func testVisibilityChangeWithConfirmedFocusRefreshesOtherWindowAfterReadiness() async throws { + try await verifyVisibilityChangeRefreshesAfterReadiness(hasPriorSnapshot: true) + } + + func testVisibilityChangeDuringFirstAXReadRefreshesOtherWindowAfterReadiness() async throws { + try await verifyVisibilityChangeRefreshesAfterReadiness(hasPriorSnapshot: false) + } + + func testVisibilityChangeDuringCancelledFirstAXReadStillRefreshesOtherWindow() async throws { + try await verifyVisibilityChangeRefreshesAfterReadiness(hasPriorSnapshot: false, cancelsInvocation: true) + } + + private func verifyVisibilityChangeRefreshesAfterReadiness(hasPriorSnapshot: Bool, + cancelsInvocation: Bool = false) async throws { + let previous = CatalogAXAccess(number: 6, elementPID: 200) + previous.update { $0.focused = true } + let app = CatalogAXAccess(number: 7, elementPID: 201, secondaryWindowNumber: 8) + let firstAXStarted = DispatchSemaphore(value: 0) + let releaseFirstAX = DispatchSemaphore(value: 0) + app.update { + $0.focused = true + $0.includesSecondaryWindow = false + } + let initialCapture = DispatchSemaphore(value: 1) + let captureStarted = DispatchSemaphore(value: 0) + let releaseCapture = DispatchSemaphore(value: 0) + let primary = WindowSwitcherWindowRecord(windowNumber: 7, processIdentifier: 42, title: "Document", + isOnScreen: true, bounds: CGRect(x: 20, y: 20, width: 800, height: 600)) + let secondary = WindowSwitcherWindowRecord(windowNumber: 8, processIdentifier: 42, title: "", isOnScreen: true, + bounds: CGRect(x: 60, y: 60, width: 800, height: 600), titleIsAvailable: false) + let priorBounds = CGRect(x: 100, y: 100, width: 800, height: 600) + let priorVisible = WindowSwitcherWindowRecord(windowNumber: 6, processIdentifier: 41, title: "Prior", + isOnScreen: true, bounds: priorBounds) + let priorOffscreen = WindowSwitcherWindowRecord(windowNumber: 6, processIdentifier: 41, title: "Prior", + isOnScreen: false, bounds: priorBounds, hasSpace: true, isOnActiveSpace: false) + var foregroundPID: pid_t = hasPriorSnapshot ? 42 : 41 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? app : previous }, + allSpacesCatalog: .init(windowRecordProvider: { + if initialCapture.wait(timeout: .now()) == .success { + return hasPriorSnapshot ? [primary] : [priorVisible] + } + captureStarted.signal() + _ = releaseCapture.wait(timeout: .now() + 1) + return hasPriorSnapshot ? [primary, secondary] : [priorOffscreen, primary, secondary] + }), discovery: .init(applications: { + let host = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "fixture", localizedName: "Fixture") + if hasPriorSnapshot { return [host] } + let prior = WindowSwitcherAppCatalog.Application( + processIdentifier: 41, bundleIdentifier: "prior", localizedName: "Prior") + return foregroundPID == 42 ? [prior, host] : [prior] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { initialCapture.signal(); releaseCapture.signal(); releaseFirstAX.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + // Startup can already have reconciled an AX read with WindowServer. + let discoveryRead = app.read { $0.reads } + 1 + app.update { + $0.beforeRead = { [weak app] in + if !hasPriorSnapshot, app?.read({ $0.reads }) == discoveryRead { + firstAXStarted.signal() + _ = releaseFirstAX.wait(timeout: .now() + 1) + } + app?.update { state in + if state.reads > discoveryRead { state.includesSecondaryWindow = true } + } + } + } + + var windowsAtReadiness: [CGWindowID]? + catalog.onChange = { [weak catalog] in + guard let catalog, catalog.isInvocationReady, windowsAtReadiness == nil else { return } + windowsAtReadiness = catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber) + } + foregroundPID = 42 + catalog.prepareForInvocation() + try await waitUntil { captureStarted.wait(timeout: .now()) == .success } + if hasPriorSnapshot { + try await waitUntil { app.read { $0.reads } == discoveryRead } + } else { + try await waitUntil { firstAXStarted.wait(timeout: .now()) == .success } + } + if cancelsInvocation { catalog.cancelInvocation() } + releaseCapture.signal() + if !hasPriorSnapshot { + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 6 && $0.isOnOtherDesktop } + } + releaseFirstAX.signal() + } + + let expectedAtReadiness: [CGWindowID] = hasPriorSnapshot ? [7] : [7, 6] + try await waitUntil { + catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber) == expectedAtReadiness + [8] + } + if !cancelsInvocation { XCTAssertEqual(windowsAtReadiness, expectedAtReadiness) } + XCTAssertEqual(app.read { $0.reads }, discoveryRead + 1) + } + + func testCancellingInvocationLetsAQueuedVisibilityRefreshRunWhileAXIsPending() async throws { + let access = CatalogAXAccess(number: 7, elementPID: 201) + let axStarted = DispatchSemaphore(value: 0) + let releaseAX = DispatchSemaphore(value: 0) + let recordsStarted = DispatchSemaphore(value: 0) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { _ in access }, allSpacesCatalog: .init(windowRecordProvider: { + recordsStarted.signal() + return [] + }), discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "fixture", localizedName: "Fixture")] + }, foregroundProcessIdentifier: { 42 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseAX.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + try await waitUntil { recordsStarted.wait(timeout: .now()) == .success } + + access.update { + $0.beforeRead = { + axStarted.signal() + _ = releaseAX.wait(timeout: .now() + 5) + } + } + catalog.prepareForInvocation() + try await waitUntil { axStarted.wait(timeout: .now()) == .success } + try await waitUntil { recordsStarted.wait(timeout: .now()) == .success } + XCTAssertFalse(catalog.isInvocationReady) + catalog.refresh() + catalog.cancelInvocation() + + try await waitUntil { recordsStarted.wait(timeout: .now()) == .success } + access.update { $0.beforeRead = nil } + } + + func testInvocationStartsFreshCaptureAndUsesOnlyOneVisibilityDrivenRetry() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + let holdOlderCapture = DispatchSemaphore(value: 0) + let olderCaptureStarted = DispatchSemaphore(value: 0) + let releaseOlderCapture = DispatchSemaphore(value: 0) + let holdInvocationCapture = DispatchSemaphore(value: 0) + let invocationCaptureStarted = DispatchSemaphore(value: 0) + let releaseInvocationCapture = DispatchSemaphore(value: 0) + let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 5, windowRecordProvider: { + if holdOlderCapture.wait(timeout: .now()) == .success { + olderCaptureStarted.signal() + _ = releaseOlderCapture.wait(timeout: .now() + 5) + return [] + } + if holdInvocationCapture.wait(timeout: .now()) == .success { + invocationCaptureStarted.signal() + _ = releaseInvocationCapture.wait(timeout: .now() + 5) + } else if launched.read({ $0.reads }) == 0 { + return [] + } + return [.init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: false, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 9, processIdentifier: 43, title: "", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600), titleIsAvailable: false)] + }) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, allSpacesCatalog: reader, + discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + let launched = WindowSwitcherAppCatalog.Application( + processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched") + return foregroundPID == 43 ? [previous, launched] : [previous] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { + releaseOlderCapture.signal() + releaseInvocationCapture.signal() + catalog.stop() + } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + holdOlderCapture.signal() + catalog.refresh() + try await waitUntil { olderCaptureStarted.wait(timeout: .now()) == .success } + + holdInvocationCapture.signal() + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { invocationCaptureStarted.wait(timeout: .now()) == .success } + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 } } + XCTAssertEqual(launched.read { $0.reads }, 1) + XCTAssertFalse(catalog.isInvocationReady) + releaseInvocationCapture.signal() + + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7, 8]) + XCTAssertNil(catalog.focusedWindowID) + } + + func testForegroundChangeUsesNewFocusBeforeInvocationBecomesReady() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let first = CatalogAXAccess(number: 8, elementPID: 202) + let second = CatalogAXAccess(number: 9, elementPID: 203) + let slow = CatalogAXAccess(number: 11, elementPID: 204) + let release = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 41 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 41: previous + case 42: first + case 43: second + default: slow + } + }, allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + (41...44).map { pid in + .init(processIdentifier: pid_t(pid), bundleIdentifier: "fixture.\(pid)", localizedName: "Fixture \(pid)") + } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { release.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + slow.update { $0.beforeRead = { _ = release.wait(timeout: .now() + 2) } } + second.update { + $0.number = 10 + $0.focused = true + } + foregroundPID = 42 + catalog.prepareForInvocation() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 10 } } + XCTAssertFalse(catalog.isInvocationReady) + + foregroundPID = 43 + catalog.invalidate(processIdentifiers: [43], windowRecords: true) + release.signal() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.first?.windowNumber, 10) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + var session = WindowSwitcherSession(entries: entries, selectedID: catalog.focusedWindowID, + isPersistent: false, originalWindowID: catalog.focusedWindowID) + session.advance(1) + XCTAssertEqual(session.selected?.windowNumber, 7) + } + + func testFocusChangeAfterInitialReadUsesRetryBeforeInvocationBecomesReady() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + launched.update { $0.focused = true } + let slow = CatalogAXAccess(number: 10, elementPID: 203) + let releaseScan = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: slow + } + }, allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "First", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true, isOnActiveSpace: true), + .init(windowNumber: 9, processIdentifier: 43, title: "Second", isOnScreen: true, + bounds: CGRect(x: 60, y: 60, width: 800, height: 600), hasSpace: true, isOnActiveSpace: true)] + }), discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application(processIdentifier: 42, localizedName: "Previous") + let other = WindowSwitcherAppCatalog.Application(processIdentifier: 44, localizedName: "Other") + guard foregroundPID == 43 else { return [previous, other] } + return [previous, other, + .init(processIdentifier: 43, localizedName: "Launched", isFinishedLaunching: false)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseScan.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + slow.update { $0.beforeRead = { _ = releaseScan.wait(timeout: .now() + 2) } } + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { + catalog.entries(sortMode: .recentUse).first { $0.id == catalog.focusedWindowID }?.windowNumber == 8 + } + XCTAssertFalse(catalog.isInvocationReady) + + launched.update { $0.focusesSecondaryWindow = true } + catalog.invalidate(processIdentifiers: [43], windowRecords: false, focusChanged: true) + slow.update { $0.beforeRead = nil } + releaseScan.signal() + try await waitUntil { catalog.isInvocationReady } + + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [9, 8, 7, 10]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 2) + } + + func testCancelledInvocationKeepsConfirmedForegroundHistory() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202) + launched.update { $0.focused = true } + let next = CatalogAXAccess(number: 9, elementPID: 203) + next.update { $0.focused = true } + let scanStarted = DispatchSemaphore(value: 0) + let releaseScan = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + var didLaunch = false + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: next + } + }, allSpacesCatalog: .init(windowRecordProvider: { [] }), + discovery: .init(applications: { + let pids: [pid_t] = didLaunch ? [42, 43, 44] : [42, 44] + return pids.map { .init(processIdentifier: $0, localizedName: "Fixture \($0)") } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseScan.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + launched.update { + $0.beforeRead = { + scanStarted.signal() + _ = releaseScan.wait(timeout: .now() + 2) + } + } + didLaunch = true + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { scanStarted.wait(timeout: .now()) == .success } + catalog.cancelInvocation() + launched.update { $0.beforeRead = nil } + releaseScan.signal() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 } } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 8) + + foregroundPID = 44 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [9, 8, 7]) + var session = WindowSwitcherSession(entries: entries, selectedID: catalog.focusedWindowID, + isPersistent: false, originalWindowID: catalog.focusedWindowID) + session.advance(1) + XCTAssertEqual(session.selected?.windowNumber, 8) + } + + func testRoutineRefreshDoesNotRestoreOffscreenFocus() async throws { + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: false) + } + + func testCancelledFocusStillUsesItsVisibilityAfterQueuedRefresh() async throws { + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: true) + } + + func testCoalescedFocusEventUsesFreshVisibilityFromRoutineRefresh() async throws { + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: false, coalescesFocusChange: true) + } + + func testNewVisibilityCanRejectFocusFromCancelledInvocation() async throws { + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: true, wasOnscreenAtInvocation: true) + } + + func testCancelledFocusUsesNewerAXEventWhenQueuedVisibilityPredatesIt() async throws { + try await verifyFocusAfterQueuedRefresh(cancelsInvocation: true, focusChangesAfterQueuedCapture: true) + } + + private func verifyFocusAfterQueuedRefresh(cancelsInvocation: Bool, coalescesFocusChange: Bool = false, + wasOnscreenAtInvocation: Bool = false, + focusChangesAfterQueuedCapture: Bool = false) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + launched.update { + $0.focused = true + $0.includesSecondaryWindow = false + } + let holdCapture = DispatchSemaphore(value: 0) + let invocationCaptureStarted = DispatchSemaphore(value: 0) + let releaseCapture = DispatchSemaphore(value: 0) + let showBackgroundCapture = DispatchSemaphore(value: 0) + let axStarted = DispatchSemaphore(value: 0) + let holdFirstAX = DispatchSemaphore(value: 1) + let releaseAX = DispatchSemaphore(value: 0) + let releaseFollowupAX = DispatchSemaphore(value: 0) + let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + let background = showBackgroundCapture.wait(timeout: .now()) == .success + if holdCapture.wait(timeout: .now()) == .success { + invocationCaptureStarted.signal() + _ = releaseCapture.wait(timeout: .now() + 2) + } + let reportedWindowIsOnscreen = focusChangesAfterQueuedCapture || (wasOnscreenAtInvocation && !background) + return [.init(windowNumber: 7, processIdentifier: 42, title: "Previous", isOnScreen: !background, + bounds: bounds, hasSpace: true, isOnActiveSpace: !background), + .init(windowNumber: 8, processIdentifier: 43, title: "Restoring", isOnScreen: reportedWindowIsOnscreen, + bounds: bounds, hasSpace: true, isOnActiveSpace: reportedWindowIsOnscreen), + .init(windowNumber: 9, processIdentifier: 43, title: "Launched", isOnScreen: !reportedWindowIsOnscreen, + bounds: bounds, hasSpace: true, isOnActiveSpace: !reportedWindowIsOnscreen)] + }), discovery: .init(applications: { + let pids: [pid_t] = foregroundPID == 43 ? [42, 43] : [42] + return pids.map { .init(processIdentifier: $0, localizedName: "Fixture \($0)") } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { + catalog.stop() + releaseCapture.signal() + releaseAX.signal() + releaseFollowupAX.signal() + holdFirstAX.signal() + } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + let holdFocusScan = { + launched.update { + $0.beforeRead = { + if holdFirstAX.wait(timeout: .now()) == .success { + axStarted.signal() + _ = releaseAX.wait(timeout: .now() + 2) + } else { + _ = releaseFollowupAX.wait(timeout: .now() + 2) + } + } + } + } + foregroundPID = 43 + if cancelsInvocation { + holdCapture.signal() + holdFocusScan() + } + catalog.prepareForInvocation() + if cancelsInvocation { + try await waitUntil { invocationCaptureStarted.wait(timeout: .now()) == .success } + try await waitUntil { axStarted.wait(timeout: .now()) == .success } + showBackgroundCapture.signal() + catalog.invalidate(processIdentifiers: [], windowRecords: true) + catalog.cancelInvocation() + releaseCapture.signal() + } else { + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 7) + holdFocusScan() + showBackgroundCapture.signal() + if coalescesFocusChange { + catalog.invalidate(processIdentifiers: [43], windowRecords: false, focusChanged: true) + } + catalog.refresh() + try await waitUntil { axStarted.wait(timeout: .now()) == .success } + } + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 7 && $0.isOnOtherDesktop } + } + launched.update { + $0.includesSecondaryWindow = true + $0.focusesSecondaryWindow = focusChangesAfterQueuedCapture + } + if focusChangesAfterQueuedCapture { + catalog.invalidate(processIdentifiers: [43], windowRecords: false, focusChanged: true) + } + releaseAX.signal() + try await waitUntil { + catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 9 && $0.windowElement != nil } + } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, focusChangesAfterQueuedCapture ? 9 : 7) + } + + func testForegroundHandoffWhileWaitingForRetryUsesNewForeground() async throws { + try await verifyForegroundHandoff(duringRetryCapture: false) + } + + func testForegroundHandoffDuringRetryCaptureUsesNewForeground() async throws { + try await verifyForegroundHandoff(duringRetryCapture: true) + } + + private func verifyForegroundHandoff(duringRetryCapture: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 11) + launched.update { + $0.focusesSecondaryWindow = true + $0.includesSecondaryWindow = false + } + let next = CatalogAXAccess(number: 9, elementPID: 203) + let releaseLaunchScan = DispatchSemaphore(value: 0) + let initialCaptures = DispatchSemaphore(value: 2) + let retryCaptureStarted = DispatchSemaphore(value: 0) + let releaseCapture = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + var didLaunch = false + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: next + } + }, allSpacesCatalog: .init(windowRecordProvider: { + if duringRetryCapture, initialCaptures.wait(timeout: .now()) != .success { + retryCaptureStarted.signal() + _ = releaseCapture.wait(timeout: .now() + 2) + } + return [] + }), + discovery: .init(applications: { + let pids: [pid_t] = didLaunch ? [42, 43, 44] : [42, 44] + return pids.map { + .init(processIdentifier: $0, localizedName: "Fixture \($0)", isFinishedLaunching: $0 != 43) + } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { + catalog.stop() + releaseLaunchScan.signal() + initialCaptures.signal() + initialCaptures.signal() + releaseCapture.signal() + } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + let initialReads = next.read { $0.reads } + + launched.update { $0.beforeRead = { _ = releaseLaunchScan.wait(timeout: .now() + 2) } } + next.update { $0.number = 10 } + catalog.onChange = { [weak catalog] in + guard let catalog else { return } + let numbers = catalog.entries(sortMode: .fixed).compactMap(\.windowNumber) + if numbers.contains(10) { releaseLaunchScan.signal() } + if !duringRetryCapture, foregroundPID == 43, numbers.contains(8), !catalog.isInvocationReady { + foregroundPID = 44 + next.update { $0.focused = true } + } + } + didLaunch = true + foregroundPID = 43 + catalog.prepareForInvocation() + if duringRetryCapture { + try await waitUntil { retryCaptureStarted.wait(timeout: .now()) == .success } + foregroundPID = 44 + next.update { $0.focused = true } + releaseCapture.signal() + } + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(foregroundPID, 44) + XCTAssertEqual(entries.first?.windowNumber, 10) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(next.read { $0.reads }, initialReads + 2) + XCTAssertEqual(launched.read { $0.reads }, 1) + } + + func testConfirmedHandoffDuringRetryAXSurvivesPublication() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + let next = CatalogAXAccess(number: 10, elementPID: 203) + let retryStarted = DispatchSemaphore(value: 0) + let releaseRetry = DispatchSemaphore(value: 0) + launched.update { + $0.beforeRead = { [weak launched] in + guard launched?.read({ $0.reads }) == 2 else { return } + retryStarted.signal() + _ = releaseRetry.wait(timeout: .now() + 2) + } + } + var foregroundPID: pid_t = 42 + var didLaunch = false + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: next + } + }, allSpacesCatalog: .init(windowRecordProvider: { [] }), discovery: .init(applications: { + let pids: [pid_t] = didLaunch ? [42, 43, 44] : [42, 44] + return pids.map { .init(processIdentifier: $0, localizedName: "Fixture \($0)", isFinishedLaunching: $0 != 43) } + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseRetry.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + didLaunch = true + catalog.prepareForInvocation() + try await waitUntil { retryStarted.wait(timeout: .now()) == .success } + foregroundPID = 44 + next.update { $0.number = 11; $0.focused = true } + catalog.refresh() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 11 } } + XCTAssertFalse(catalog.isInvocationReady) + releaseRetry.signal() + try await waitUntil { catalog.isInvocationReady } + + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [11, 7]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + + func testRetryCaptureCannotContradictAnExactFocusEventFromTheNextSpace() async throws { + try await verifyRetryFocusEvent(duringAccessibility: false) + } + + func testRetryAXReadUsesAFocusChangeThatArrivesDuringEnumeration() async throws { + try await verifyRetryFocusEvent(duringAccessibility: true) + } + + private func verifyRetryFocusEvent(duringAccessibility: Bool) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: 8, elementPID: 202, secondaryWindowNumber: 9) + let initialCaptures = DispatchSemaphore(value: 2) + let retryStarted = DispatchSemaphore(value: 0) + let releaseRetry = DispatchSemaphore(value: 0) + launched.update { + $0.windowListUnavailable = true + if duringAccessibility { + $0.beforeRead = { [weak launched] in + guard launched?.read({ $0.reads }) == 2 else { return } + retryStarted.signal() + _ = releaseRetry.wait(timeout: .now() + 2) + } + } + } + let changedSpace = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + let onNextSpace = changedSpace.wait(timeout: .now()) == .success + if !duringAccessibility, initialCaptures.wait(timeout: .now()) != .success, !onNextSpace { + retryStarted.signal() + _ = releaseRetry.wait(timeout: .now() + 2) + } + return [ + .init(windowNumber: 8, processIdentifier: 43, title: "Previous Space", isOnScreen: !onNextSpace, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true, isOnActiveSpace: !onNextSpace), + .init(windowNumber: 9, processIdentifier: 43, title: "Next Space", isOnScreen: onNextSpace, + bounds: CGRect(x: 60, y: 60, width: 800, height: 600), hasSpace: true, isOnActiveSpace: onNextSpace), + ] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application(processIdentifier: 42, localizedName: "Previous") + guard foregroundPID == 43 else { return [prior] } + return [prior, .init(processIdentifier: 43, localizedName: "Launched", isFinishedLaunching: false)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { + catalog.stop() + initialCaptures.signal() + initialCaptures.signal() + releaseRetry.signal() + } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { retryStarted.wait(timeout: .now()) == .success } + launched.update { + $0.windowListUnavailable = false + $0.focusesSecondaryWindow = true + } + changedSpace.signal() + catalog.invalidate(processIdentifiers: [43], windowRecords: true, focusChanged: true) + releaseRetry.signal() + + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.first?.windowNumber, 9) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(launched.read { $0.reads }, 2) + } + + func testForegroundHandoffAndIncompleteAXShareOneRetry() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + let holdInvocationCapture = DispatchSemaphore(value: 0) + let invocationCaptureStarted = DispatchSemaphore(value: 0) + let releaseCapture = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordProvider: { + if holdInvocationCapture.wait(timeout: .now()) == .success { + invocationCaptureStarted.signal() + _ = releaseCapture.wait(timeout: .now() + 2) + } + return [.init(windowNumber: 8, processIdentifier: 43, title: "Launched", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600))] + }), discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous"), + .init(processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched")] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseCapture.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + let initialReads = launched.read { $0.reads } + + holdInvocationCapture.signal() + catalog.prepareForInvocation() + try await waitUntil { invocationCaptureStarted.wait(timeout: .now()) == .success } + try await waitUntil { launched.read { $0.reads } == initialReads + 1 } + foregroundPID = 43 + releaseCapture.signal() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, initialReads + 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7]) + XCTAssertNil(catalog.focusedWindowID) + } + + func testRecentUseWaitsForVisibilityAndKeepsInferenceOutOfHistory() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + let failNextRead = DispatchSemaphore(value: 0) + let delayNextRead = DispatchSemaphore(value: 0) + let releaseRead = DispatchSemaphore(value: 0) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : launched }, + allSpacesCatalog: .init(windowRecordRefreshTimeout: 2, windowRecordProvider: { + if failNextRead.wait(timeout: .now()) == .success { return nil } + if delayNextRead.wait(timeout: .now()) == .success { + _ = releaseRead.wait(timeout: .now() + 2) + } + return [.init(windowNumber: 9, processIdentifier: 43, title: "Onscreen", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600))] + }), + discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous"), + .init(processIdentifier: 43, bundleIdentifier: "launched", localizedName: "Launched")] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { releaseRead.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + failNextRead.signal() + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).last?.metadataUnavailable, true) + + foregroundPID = 43 + launched.update { $0.number = 8 } + delayNextRead.signal() + catalog.prepareForInvocation() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 } } + XCTAssertFalse(catalog.isInvocationReady) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 7) + releaseRead.signal() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [9, 7, 8]) + + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.windowNumber, 9) + + launched.update { $0.focused = true } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [8, 7, 9]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + var session = WindowSwitcherSession(entries: entries, selectedID: catalog.focusedWindowID, + isPersistent: false, originalWindowID: catalog.focusedWindowID) + session.advance(1) + XCTAssertEqual(session.selected?.windowNumber, 7) + } + func testWakeAndSpaceChangesDoNotResumeAnInactiveSession() async throws { let first = CatalogAXAccess(number: 7, elementPID: 201) let second = CatalogAXAccess(number: 8, elementPID: 202) @@ -181,7 +1703,7 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { discovery: .init(applications: { [.init(processIdentifier: 42, bundleIdentifier: "first", bundlePath: "/First.app", localizedName: "First"), .init(processIdentifier: 43, bundleIdentifier: "second", bundlePath: "/Second.app", localizedName: "Second")] - }, isAccessibilityTrusted: { true }, isDragging: isDragging)) + }, foregroundProcessIdentifier: { nil }, isAccessibilityTrusted: { true }, isDragging: isDragging)) } private func makeCatalog(host: CatalogAXAccess, helper: CatalogAXAccess, @@ -198,15 +1720,19 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { [.init(processIdentifier: 42, bundleIdentifier: "fixture.host", bundlePath: "/Fixture.app", localizedName: "Fixture"), .init(processIdentifier: 43, bundleIdentifier: "fixture.host.helper", bundlePath: "/Fixture.app/Helper.app", localizedName: "Helper", isRegular: false, isActive: helperIsActive)] - }, isAccessibilityTrusted: { true }, isDragging: { false })) + }, foregroundProcessIdentifier: { helperIsActive ? 42 : nil }, + isAccessibilityTrusted: { true }, isDragging: { false })) } private func waitUntil(_ condition: () -> Bool, file: StaticString = #filePath, line: UInt = #line) async throws { let deadline = ContinuousClock.now + .seconds(2) - while !condition(), ContinuousClock.now < deadline { + while !condition() { + guard ContinuousClock.now < deadline else { + XCTFail("Condition was not met before the deadline", file: file, line: line) + return + } try await Task.sleep(for: .milliseconds(5)) } - XCTAssertTrue(condition(), file: file, line: line) } private func numbers(_ catalog: WindowSwitcherAppCatalog) -> Set { @@ -284,4 +1810,260 @@ final class WindowSwitcherAppCatalogTests: XCTestCase { XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.id, focused) XCTAssertEqual(catalog.entries(sortMode: .recentUse).first?.axWorkerPID, 43) } + + func testCachedHelperActivationDoesNotOverrideExactForegroundHostFocus() async throws { + let host = CatalogAXAccess(number: 7, elementPID: 201) + host.update { $0.focused = true } + let helper = CatalogAXAccess(number: 8, elementPID: 202) + let catalog = makeCatalog(host: host, helper: helper, helperIsActive: true) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [7, 8]) + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + } + + func testActiveHelperExactFocusWinsAfterHostFocusIsContradicted() async throws { + try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: true) + } + + func testBackgroundRefreshRecordsExactHelperFocusAfterHostFocusIsContradicted() async throws { + try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: true, refreshesInBackground: true) + } + + func testUnnumberedHelperExactFocusCanUseItsUniqueVisibilityMatch() async throws { + try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: true, exposesHelperNumber: false) + } + + func testVisibleHelperPreventsInferringHostFocus() async throws { + try await verifyForegroundHostWithActiveHelper(hostIsOffscreen: false) + } + + private func verifyForegroundHostWithActiveHelper(hostIsOffscreen: Bool, refreshesInBackground: Bool = false, + exposesHelperNumber: Bool = true) async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let host = CatalogAXAccess(number: 8, elementPID: 202) + host.update { $0.focused = hostIsOffscreen } + let helper = CatalogAXAccess(number: 9, elementPID: 203) + helper.update { + $0.focused = hostIsOffscreen + $0.exposesWindowNumber = exposesHelperNumber + } + var foregroundPID: pid_t = 42 + let bounds = CGRect(x: 20, y: 20, width: 800, height: 600) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: host + default: helper + } + }, allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Host", isOnScreen: !hostIsOffscreen, + bounds: bounds, hasSpace: true, isOnActiveSpace: !hostIsOffscreen), + .init(windowNumber: 9, processIdentifier: 44, title: "Helper", isOnScreen: true, + bounds: bounds, hasSpace: true, isOnActiveSpace: true)] + }), discovery: .init(applications: { + let prior = WindowSwitcherAppCatalog.Application(processIdentifier: 42, localizedName: "Previous") + guard foregroundPID == 43 else { return [prior] } + return [prior, + .init(processIdentifier: 43, bundleIdentifier: "host", bundlePath: "/Host.app", localizedName: "Host"), + .init(processIdentifier: 44, bundleIdentifier: "host.helper", bundlePath: "/Host.app/Helper.app", + localizedName: "Helper", isRegular: false, isActive: true)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + if refreshesInBackground { + catalog.refresh() + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.axWorkerPID == 44 } } + } else { + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(Set(entries.compactMap(\.windowNumber)), exposesHelperNumber ? [7, 8, 9] : [7, 8]) + XCTAssertEqual(entries.first?.windowNumber, hostIsOffscreen ? (exposesHelperNumber ? 9 : nil) : 7) + if hostIsOffscreen { + XCTAssertEqual(catalog.focusedWindowID, entries.first?.id) + XCTAssertEqual(entries.first?.axWorkerPID, 44) + } else { + XCTAssertNil(catalog.focusedWindowID) + } + } + + func testUnlistedHostFocusRetriesBeforeConsideringCachedHelperFocus() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let launched = CatalogAXAccess(number: nil, elementPID: 202) + launched.update { + $0.focused = true + $0.beforeRead = { [weak launched] in + launched?.update { state in + if state.reads == 2 { state.number = 9 } + } + } + } + let helper = CatalogAXAccess(number: 8, elementPID: 203) + helper.update { $0.focused = true } + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { pid in + switch pid { + case 42: previous + case 43: launched + default: helper + } + }, allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 9, processIdentifier: 43, title: "New foreground window", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600)), + .init(windowNumber: 8, processIdentifier: 44, title: "Helper", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600))] + }), discovery: .init(applications: { + let previous = WindowSwitcherAppCatalog.Application( + processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous") + guard foregroundPID == 43 else { return [previous] } + return [previous, + .init(processIdentifier: 43, bundleIdentifier: "launched", bundlePath: "/Launched.app", + localizedName: "Launched"), + .init(processIdentifier: 44, bundleIdentifier: "launched.helper", + bundlePath: "/Launched.app/Helper.app", localizedName: "Helper", isRegular: false, isActive: true)] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(launched.read { $0.reads }, 2) + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [9, 7, 8]) + } + + func testHelperDiscoveredDuringHostReadDoesNotCauseARedundantRetry() async throws { + let host = CatalogAXAccess(number: 7, elementPID: 201) + host.update { $0.focused = true } + let helper = CatalogAXAccess(number: 8, elementPID: 202) + let initialCapture = DispatchSemaphore(value: 1) + let hostReadStarted = DispatchSemaphore(value: 0) + let releaseHostRead = DispatchSemaphore(value: 0) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? host : helper }, + allSpacesCatalog: .init(windowRecordProvider: { + if initialCapture.wait(timeout: .now()) == .success { return [] } + return [ + .init(windowNumber: 7, processIdentifier: 42, title: "Host", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600)), + .init(windowNumber: 8, processIdentifier: 43, title: "Helper", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600)), + ] + }), discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "fixture.host", bundlePath: "/Fixture.app", + localizedName: "Fixture"), + .init(processIdentifier: 43, bundleIdentifier: "fixture.host.helper", + bundlePath: "/Fixture.app/Helper.app", localizedName: "Helper", isRegular: false)] + }, foregroundProcessIdentifier: { 42 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { initialCapture.signal(); releaseHostRead.signal(); catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + let initialHostReads = host.read { $0.reads } + host.update { + $0.beforeRead = { + hostReadStarted.signal() + _ = releaseHostRead.wait(timeout: .now() + 1) + } + } + + catalog.prepareForInvocation() + try await waitUntil { hostReadStarted.wait(timeout: .now()) == .success } + try await waitUntil { catalog.entries(sortMode: .fixed).contains { $0.windowNumber == 8 } } + host.update { $0.beforeRead = nil } + releaseHostRead.signal() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + XCTAssertEqual(entries.compactMap(\.windowNumber), [7, 8]) + XCTAssertEqual(entries.first { $0.windowNumber == 8 }?.axWorkerPID, 43) + XCTAssertEqual(host.read { $0.reads }, initialHostReads + 1) + XCTAssertEqual(helper.read { $0.reads }, 1) + } + + func testPreviouslyAXListedWindowCannotBecomeAnchorAfterItsAXRowDisappears() async throws { + let previous = CatalogAXAccess(number: 7, elementPID: 201) + previous.update { $0.focused = true } + let foreground = CatalogAXAccess(number: 9, elementPID: 202, replacementNumber: 8) + var foregroundPID: pid_t = 42 + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? previous : foreground }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "Offscreen", isOnScreen: false, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), hasSpace: true), + .init(windowNumber: 9, processIdentifier: 43, title: "Previously listed window", isOnScreen: true, + bounds: CGRect(x: 40, y: 40, width: 800, height: 600), hasSpace: true)] + }), + discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "previous", localizedName: "Previous"), + .init(processIdentifier: 43, bundleIdentifier: "foreground", localizedName: "Foreground")] + }, foregroundProcessIdentifier: { foregroundPID }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + XCTAssertNotNil(catalog.entries(sortMode: .fixed).first { $0.windowNumber == 9 }?.windowElement) + + foreground.update { $0.number = 8 } + foregroundPID = 43 + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entries = catalog.entries(sortMode: .recentUse) + let fallback = try XCTUnwrap(entries.first { $0.windowNumber == 9 }) + XCTAssertNil(fallback.windowElement) + XCTAssertNil(catalog.focusedWindowID) + XCTAssertEqual(entries.first?.windowNumber, 7) + } + + func testForegroundHelperUsesOnlyWindowsTiedToItsProcess() async throws { + let host = CatalogAXAccess(number: 7, elementPID: 201) + let helper = CatalogAXAccess(number: nil, elementPID: 202) + let catalog = WindowSwitcherAppCatalog(notificationCenter: NotificationCenter(), + accessFactory: { $0 == 42 ? host : helper }, + allSpacesCatalog: .init(windowRecordProvider: { + [.init(windowNumber: 8, processIdentifier: 43, title: "", isOnScreen: true, + bounds: CGRect(x: 20, y: 20, width: 800, height: 600), titleIsAvailable: false)] + }), + discovery: .init(applications: { + [.init(processIdentifier: 42, bundleIdentifier: "fixture.host", bundlePath: "/Fixture.app", + localizedName: "Fixture"), + .init(processIdentifier: 43, bundleIdentifier: "fixture.host.helper", bundlePath: "/Fixture.app/Helper.app", + localizedName: "Helper", isRegular: false)] + }, foregroundProcessIdentifier: { 43 }, isAccessibilityTrusted: { true }, isDragging: { false })) + defer { catalog.stop() } + catalog.start() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.entries(sortMode: .recentUse).compactMap(\.windowNumber), [7]) + XCTAssertNil(catalog.focusedWindowID) + + host.update { $0.number = 8 } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + let entry = try XCTUnwrap(catalog.entries(sortMode: .recentUse).first) + XCTAssertEqual(entry.owningProcessIdentifier, 43) + XCTAssertEqual(entry.axWorkerPID, 42) + XCTAssertEqual(catalog.focusedWindowID, entry.id) + + helper.update { $0.focused = true } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertNil(catalog.focusedWindowID) + + helper.update { $0.number = 8 } + catalog.prepareForInvocation() + try await waitUntil { catalog.isInvocationReady } + XCTAssertEqual(catalog.focusedWindowID, entry.id) + } } diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherLifecycleTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherLifecycleTests.swift index ad857fa62..d5d516442 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherLifecycleTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherLifecycleTests.swift @@ -30,6 +30,8 @@ private final class ControlledSwitcherCatalog: WindowSwitcherCatalog { var isInvocationReady: Bool { invocationReady ?? isInitialDiscoveryComplete } var prepareInvocation: (() -> Void)? func prepareForInvocation() { prepareInvocation?() } + var cancelledInvocations = 0 + func cancelInvocation() { cancelledInvocations += 1 } var windows: [WindowSwitcherAppEntry] = [] var activated: [String] = [] var activationResult: WindowSwitcherActionResult = .succeeded @@ -338,6 +340,7 @@ final class WindowSwitcherLifecycleTests: XCTestCase { XCTAssertNil(plugin.session) XCTAssertNil(plugin.pendingInvocation) XCTAssertTrue(catalog.activated.isEmpty) + XCTAssertEqual(catalog.cancelledInvocations, 1) } func testModifierReleaseAfterEnteringSearchDoesNotCommit() async throws { diff --git a/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift b/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift index 9ec000a0e..4452c3894 100644 --- a/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift +++ b/Plugins/WindowSwitcher/Tests/WindowSwitcherWindowRecordsTests.swift @@ -15,8 +15,11 @@ private final class BlockingWindowRecords: @unchecked Sendable { private var calls = 0 private var completions = 0 private var blocked = true + private let failingCall: Int? let release = DispatchSemaphore(value: 0) + init(failingCall: Int? = nil) { self.failingCall = failingCall } + var counts: (started: Int, completed: Int) { lock.lock(); defer { lock.unlock() } return (calls, completions) @@ -32,6 +35,7 @@ private final class BlockingWindowRecords: @unchecked Sendable { lock.unlock() if shouldWait { _ = release.wait(timeout: .now() + 3) } lock.lock(); completions += 1; lock.unlock() + if number == failingCall { return nil } return [.init(windowNumber: UInt32(number), processIdentifier: 42, title: "Fixture", isOnScreen: true, bounds: CGRect(x: 0, y: 30, width: 800, height: 600))] } @@ -56,6 +60,32 @@ final class WindowSwitcherWindowRecordsTests: XCTestCase { XCTAssertEqual(snapshot.records.map(\.windowNumber), [1]) } + func testNewCaptureSupersedesAnOlderCaptureThatFinishesLater() async throws { + let provider = BlockingWindowRecords() + let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 2, windowRecordProvider: { provider.read() }) + defer { provider.release.signal(); reader.stop() } + let older = Task { await reader.freshWindowRecordSnapshot() } + try await waitUntil { provider.counts.started == 1 } + + provider.unblock() + let current = await reader.freshWindowRecordSnapshot(requiresNewCapture: true) + XCTAssertTrue(current.isFresh) + XCTAssertEqual(current.records.map(\.windowNumber), [2]) + XCTAssertEqual(provider.counts.completed, 1) + + let entry = WindowSwitcherAppEntry(id: "latest", processIdentifier: 42, bundleIdentifier: "fixture", + appName: "Fixture", windowTitle: "Fixture", icon: nil, windowElement: nil, isMinimized: false, + windowNumber: 3, windowBounds: CGRect(x: 0, y: 30, width: 800, height: 600), shortcutToken: nil) + let validated = await reader.isCurrentFallback(entry) + XCTAssertTrue(validated) + XCTAssertEqual(provider.counts.completed, 2) + + provider.release.signal() + let superseded = await older.value + XCTAssertFalse(superseded.isFresh) + XCTAssertEqual(superseded.records.map(\.windowNumber), [3]) + } + func testTimeoutKeepsPhysicalQueriesBoundedAndIgnoresTheirLateResults() async throws { let provider = BlockingWindowRecords() let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 0.03, windowRecordProvider: { provider.read() }) @@ -78,6 +108,29 @@ final class WindowSwitcherWindowRecordsTests: XCTestCase { XCTAssertEqual(current.records.map(\.windowNumber), [3]) } + func testFailedNewCaptureDoesNotMakeOlderRecordsFreshForAnAction() async throws { + let provider = BlockingWindowRecords(failingCall: 2) + let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 2, windowRecordProvider: { provider.read() }) + defer { provider.release.signal(); reader.stop() } + let older = Task { await reader.freshWindowRecordSnapshot() } + try await waitUntil { provider.counts.started == 1 } + + provider.unblock() + let failed = await reader.freshWindowRecordSnapshot(requiresNewCapture: true) + XCTAssertFalse(failed.isFresh) + let entry = WindowSwitcherAppEntry(id: "latest", processIdentifier: 42, bundleIdentifier: "fixture", + appName: "Fixture", windowTitle: "Fixture", icon: nil, windowElement: nil, isMinimized: false, + windowNumber: 3, windowBounds: CGRect(x: 0, y: 30, width: 800, height: 600), shortcutToken: nil) + let validated = await reader.isCurrentFallback(entry) + XCTAssertTrue(validated) + XCTAssertEqual(provider.counts.completed, 2) + + provider.release.signal() + let superseded = await older.value + XCTAssertFalse(superseded.isFresh) + XCTAssertEqual(superseded.records.map(\.windowNumber), [3]) + } + func testStopResumesWaitersWithoutWaitingForSystemQuery() async throws { let provider = BlockingWindowRecords() let reader = WindowSwitcherWindowRecords(windowRecordRefreshTimeout: 2, windowRecordProvider: { provider.read() }) diff --git a/changes/unreleased/window-switcher-launch-recency.md b/changes/unreleased/window-switcher-launch-recency.md new file mode 100644 index 000000000..7cb9496eb --- /dev/null +++ b/changes/unreleased/window-switcher-launch-recency.md @@ -0,0 +1,6 @@ +--- +release: plugin +type: fixed +--- + +Window Switcher puts a newly launched foreground window first in Recent Use when the window can be identified while Accessibility is still catching up.