Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
715 changes: 669 additions & 46 deletions Plugins/WindowSwitcher/Sources/WindowSwitcherAppCatalog.swift

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) })
}

Expand Down
2 changes: 2 additions & 0 deletions Plugins/WindowSwitcher/Sources/WindowSwitcherPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -829,6 +829,7 @@ final class WindowSwitcherPlugin: MacToolsPlugin, AccessibilityPermissionRefresh
}

private func cancelSession() {
let wasWaitingForDiscovery = pendingInvocation != nil
shortcutTap.setSessionActive(false)
shortcutTap.setEditing(false)
sessionGeneration += 1
Expand All @@ -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 {
Expand Down
36 changes: 25 additions & 11 deletions Plugins/WindowSwitcher/Sources/WindowSwitcherProcessWorker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<CGWindowID> = []
var focusReadStartedAt: ContinuousClock.Instant?
}

struct WindowSwitcherAXIdentity: Hashable {
Expand Down Expand Up @@ -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<String>()
var excluded = Set<WindowSwitcherAXIdentity>()
var excludedWindowNumbers = Set<CGWindowID>()
var didRead = 0
var metadataFailed = false
let count = windows.count
Expand All @@ -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,
Expand All @@ -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),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ struct WindowSwitcherPublishedWindows {
private var confirmedAXWindowNumbers: [pid_t: Set<CGWindowID>] = [:]
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)
Expand Down
28 changes: 20 additions & 8 deletions Plugins/WindowSwitcher/Sources/WindowSwitcherSession.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>) {
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
Expand Down
109 changes: 41 additions & 68 deletions Plugins/WindowSwitcher/Sources/WindowSwitcherWindowRecords.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void, Never>
var waiters: [UUID: CheckedContinuation<WindowSwitcherWindowRecordSnapshot, Never>] = [:]
}

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<Void, Never>?
private var waiters: [UUID: CheckedContinuation<WindowSwitcherWindowRecordSnapshot, Never>] = [:]

init(windowRecordRefreshTimeout: TimeInterval = 0.75,
windowRecordProvider: @escaping @Sendable () -> [WindowSwitcherWindowRecord]? = {
Expand All @@ -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] {
Expand Down Expand Up @@ -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
Expand All @@ -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) }
}
}

Expand Down
Loading
Loading