import Foundation import AppKit @preconcurrency import ApplicationServices import CoreGraphics // TrackingController ties the enumerator, the observer registry, and the // workspace events together. The controller writes the WindowStore and the // AXElementCache. The controller keeps the AX reads off the main thread // (spec sections 7.3, 7.4, 7.15). The controller is main-actor isolated. @MainActor final class TrackingController { private let store: WindowStore private let cache: AXElementCache private let spaceService: SpaceService private let settings: Settings private let enumerator = WindowEnumerator() private let observers = AppObserverRegistry() private let workspace = WorkspaceEvents() // serialQueue runs all AX reads. One serial queue keeps the order. A frozen // application blocks only this queue, not the main thread. private let serialQueue = DispatchQueue(label: "com.epod.windowbar.tracking.ax", qos: .userInitiated) private let ownPID = NSRunningApplication.current.processIdentifier // Coalesce state: at most one refresh per 50 ms per application. private var lastRefreshAt: [pid_t: Date] = [:] private var refreshScheduled: Set = [] private var reconcileTimer: Timer? private var lastFullScreen = false private var running = false // onFrontmostFocusedFullScreenChanged reports the full-screen state of the // focused window of the frontmost application (spec section 7.11). var onFrontmostFocusedFullScreenChanged: ((Bool) -> Void)? // onWindowGeometryEvent forwards a move or a resize event. The controller // resolves the CGWindowID on the serial AX queue (spec section 7.4). The // constraint service uses this hook (spec section 7.10). var onWindowGeometryEvent: ((pid_t, String, CGWindowID) -> Void)? // onFocusedWindowChanged reports the CGWindowID of the focused window of // the frontmost application. The strip uses this ID for the active tab // (spec section 7.9). The value is nil if no focused window exists. var onFocusedWindowChanged: ((CGWindowID?) -> Void)? init(store: WindowStore, cache: AXElementCache, spaceService: SpaceService, settings: Settings) { self.store = store self.cache = cache self.spaceService = spaceService self.settings = settings } // start subscribes to the events and registers the observers. func start() { guard running == false else { return } running = true workspace.onFrontmostChanged = { [weak self] pid in self?.handleFrontmostChanged(pid) } workspace.onAppLaunched = { [weak self] app in self?.registerObserver(for: app.processIdentifier) } workspace.onAppTerminated = { [weak self] pid in self?.handleAppTerminated(pid) } workspace.onActiveSpaceChanged = { [weak self] in self?.handleActiveSpaceChanged() } workspace.start() for app in regularApps() { registerObserver(for: app.processIdentifier) } if let frontmost = NSWorkspace.shared.frontmostApplication { handleFrontmostChanged(frontmost.processIdentifier) } reconcileTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in MainActor.assumeIsolated { self?.reconcile() } } } // stop ends all tracking work. func stop() { running = false reconcileTimer?.invalidate() reconcileTimer = nil observers.removeAll() workspace.stop() } // onAccessibilityLost stops all AX work. The app shows the onboarding // window again (spec section 6.1). The controller does not crash. func onAccessibilityLost() { stop() } // dumpWindowsToLog writes the window dump to the log at notice level. The // notice level is persisted. "log show" reads it (spec section 7.14). func dumpWindowsToLog() { collectDump { lines in for line in lines { Log.tracking.notice("\(line, privacy: .public)") } } } // dumpWindowsToPasteboard puts the window dump on the clipboard. The user // reads the dump without a log tool. func dumpWindowsToPasteboard() { collectDump { lines in let text = lines.joined(separator: "\n") NSPasteboard.general.clearContents() NSPasteboard.general.setString(text, forType: .string) Log.tracking.notice("Window dump copied to the clipboard. \(lines.count, privacy: .public) lines.") } } // collectDump enumerates every regular application and builds the dump // text. The enumeration runs on the serial AX queue. The completion runs on // the main actor with the lines in application order. Every field is a // plain string, so no field is redacted (spec section 7.14). private func collectDump(completion: @escaping ([String]) -> Void) { let apps = regularApps() let enumerator = self.enumerator let ownPID = self.ownPID let group = DispatchGroup() var sections: [Int: [String]] = [:] for (index, app) in apps.enumerated() { let pid = app.processIdentifier let bundleID = app.bundleIdentifier let appName = app.localizedName ?? "" group.enter() serialQueue.async { [weak self] in let ax = enumerator.readAXWindows(pid: pid) let cg = enumerator.readCGWindows(pid: pid) let axWindowIDs = ax.map { PrivateAPI.shared.windowID(for: $0.element) } DispatchQueue.main.async { defer { group.leave() } guard let self = self else { return } let ids = Self.allIDs(axWindowIDs: axWindowIDs, cg: cg) let spaceMap = self.spaceService.spaces(for: ids) let currentSpaces = self.spaceService.currentSpaceIDs() let result = enumerator.buildWindows(pid: pid, bundleID: bundleID, appName: appName, ax: ax, axWindowIDs: axWindowIDs, cg: cg, spaceIDsByWindow: spaceMap, currentSpaceIDs: currentSpaces, ownPID: ownPID, screenBoundsCG: Self.screenBoundsCG()) var lines: [String] = [] lines.append("DUMP app pid=\(pid) bundle=\(bundleID ?? "nil") name=\(appName)") for r in result.debug { let b = r.bounds let boundsText = "(\(b.origin.x), \(b.origin.y), \(b.width), \(b.height))" lines.append("DUMP id=\(r.windowID) title=\(r.title) subrole=\(r.subrole ?? "nil") layer=\(r.layer) bounds=\(boundsText) spaces=\(r.spaceIDs) min=\(r.isMinimized) full=\(r.isFullScreen) shown=\(r.shown) reason=\(r.reason)") } sections[index] = lines } } } group.notify(queue: .main) { var all: [String] = [] for index in 0..= 0.05 { performRefreshNow(pid) } else if refreshScheduled.contains(pid) == false { refreshScheduled.insert(pid) let delay = 0.05 - elapsed DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in guard let self = self else { return } self.refreshScheduled.remove(pid) self.performRefreshNow(pid) } } } private func performRefreshNow(_ pid: pid_t) { lastRefreshAt[pid] = Date() let enumerator = self.enumerator serialQueue.async { [weak self] in let ax = enumerator.readAXWindows(pid: pid) let cg = enumerator.readCGWindows(pid: pid) // Map each AX element to a CGWindowID on the serial AX queue // (spec sections 7.4, 7.15). let axWindowIDs = ax.map { PrivateAPI.shared.windowID(for: $0.element) } DispatchQueue.main.async { guard let self = self else { return } self.applyEnumeration(pid: pid, ax: ax, cg: cg, axWindowIDs: axWindowIDs) } } } private func applyEnumeration(pid: pid_t, ax: [WindowEnumerator.AXRawWindow], cg: [WindowEnumerator.CGRawWindow], axWindowIDs: [CGWindowID?]) { let app = NSRunningApplication(processIdentifier: pid) let bundleID = app?.bundleIdentifier let appName = app?.localizedName ?? "" let ids = Self.allIDs(axWindowIDs: axWindowIDs, cg: cg) let spaceMap = spaceService.spaces(for: ids) let currentSpaces = spaceService.currentSpaceIDs() let result = enumerator.buildWindows(pid: pid, bundleID: bundleID, appName: appName, ax: ax, axWindowIDs: axWindowIDs, cg: cg, spaceIDsByWindow: spaceMap, currentSpaceIDs: currentSpaces, ownPID: ownPID, screenBoundsCG: Self.screenBoundsCG()) store.replaceWindows(result.windows, for: pid) for (id, element) in result.elements { cache.set(element, for: id) } observers.setWindowElements(pid: pid, windows: ax.map { $0.element }) } // checkFullScreen reads the full-screen state of the focused window. The // controller reports a change (spec section 7.11). private func checkFullScreen(_ pid: pid_t) { guard pid == store.frontmostPID else { return } let enumerator = self.enumerator serialQueue.async { [weak self] in let isFullScreen = enumerator.readFocusedFullScreen(pid: pid) DispatchQueue.main.async { guard let self = self else { return } if isFullScreen != self.lastFullScreen { self.lastFullScreen = isFullScreen self.onFrontmostFocusedFullScreenChanged?(isFullScreen) } } } } // checkFocusedWindow reads the focused window of the frontmost application. // The controller resolves the CGWindowID on the main actor. The controller // reports the ID for the active tab (spec section 7.9). private func checkFocusedWindow(_ pid: pid_t) { guard pid == store.frontmostPID else { return } let enumerator = self.enumerator serialQueue.async { [weak self] in let element = enumerator.readFocusedWindowElement(pid: pid) // Map the focused element to a CGWindowID on the serial AX queue. let id = element.flatMap { PrivateAPI.shared.windowID(for: $0) } DispatchQueue.main.async { guard let self = self else { return } guard pid == self.store.frontmostPID else { return } self.onFocusedWindowChanged?(id) } } } // MARK: - Helpers private func regularApps() -> [NSRunningApplication] { return NSWorkspace.shared.runningApplications.filter { $0.activationPolicy == .regular } } // screenBoundsCG returns the union of all screens in CG coordinates (the // top-left origin of the primary screen). The filter uses this rect to hide // a window that lies entirely off-screen. private static func screenBoundsCG() -> CGRect { let screens = NSScreen.screens guard let primary = screens.first else { return .null } let primaryHeight = primary.frame.height var union = CGRect.null for screen in screens { union = union.union(Geometry.cocoaToAX(screen.frame, primaryHeight: primaryHeight)) } return union } private static func allIDs(axWindowIDs: [CGWindowID?], cg: [WindowEnumerator.CGRawWindow]) -> [CGWindowID] { var set = Set() for id in axWindowIDs { if let id = id, id != 0 { set.insert(id) } } for window in cg where window.windowID != 0 { set.insert(window.windowID) } return Array(set) } }