import Foundation import ApplicationServices import CoreGraphics import Observation // WindowStore holds the windows per application and the frontmost PID. // The store is the single source of truth for the tab bar. The store is // main-actor isolated. The store publishes changes with the Observation // framework (@Observable). See spec section 7.2. // // The store keeps the stable order (decision D5). The store sorts windows by // firstSeen. When a window closes and opens again, the window gets a new // firstSeen value. @MainActor @Observable final class WindowStore { // byPID holds the windows for each application PID. private var byPID: [pid_t: [WindowInfo]] = [:] // frontmostPID is the PID of the frontmost application. private(set) var frontmostPID: pid_t? // frontmostWindows returns the windows of the frontmost application in the // stable order. var frontmostWindows: [WindowInfo] { guard let pid = frontmostPID else { return [] } return windows(for: pid) } // windows returns the windows for one PID in the stable order. func windows(for pid: pid_t) -> [WindowInfo] { let list = byPID[pid] ?? [] return list.sorted { lhs, rhs in if lhs.firstSeen == rhs.firstSeen { return lhs.id < rhs.id } return lhs.firstSeen < rhs.firstSeen } } // setFrontmost sets the frontmost PID. func setFrontmost(_ pid: pid_t?) { frontmostPID = pid } // replaceWindows replaces the windows for one PID. The function keeps the // firstSeen value of a window that is already known. A new window gets the // firstSeen value "now". This keeps the stable order (decision D5). func replaceWindows(_ incoming: [WindowInfo], for pid: pid_t, now: Date = Date()) { let existing = byPID[pid] ?? [] var firstSeenByID: [CGWindowID: Date] = [:] for window in existing { firstSeenByID[window.id] = window.firstSeen } var merged: [WindowInfo] = [] merged.reserveCapacity(incoming.count) for var window in incoming { window.firstSeen = firstSeenByID[window.id] ?? now merged.append(window) } byPID[pid] = merged } // removeApp removes all windows of one application. func removeApp(_ pid: pid_t) { byPID[pid] = nil } // allPIDs returns the PIDs that the store knows. func allPIDs() -> [pid_t] { return Array(byPID.keys) } } // AXElementCache holds the AXUIElement for each window. The cache is separate // from WindowInfo. The spec forbids the AXUIElement inside the value type // (section 7.2). The cache is main-actor isolated. @MainActor final class AXElementCache { private var elements: [CGWindowID: AXUIElement] = [:] func element(for id: CGWindowID) -> AXUIElement? { return elements[id] } func set(_ element: AXUIElement?, for id: CGWindowID) { elements[id] = element } func remove(_ id: CGWindowID) { elements[id] = nil } func removeAll() { elements.removeAll() } }