EPOD Window Bar: a window strip above the macOS Dock
EPOD Window Bar is a macOS agent app. It shows a thin strip above the Dock with one tab per window of the frontmost application. One click raises the window. Build from source with XcodeGen and Xcode. Signing uses Config.xcconfig (ad-hoc by default; a local Local.xcconfig can set a team ID). The app needs Accessibility and Screen Recording permissions, and runs in a reduced mode without Screen Recording. See README.md and docs/ for details.
This commit is contained in:
136
Sources/Tracking/AppObserverRegistry.swift
Normal file
136
Sources/Tracking/AppObserverRegistry.swift
Normal file
@@ -0,0 +1,136 @@
|
||||
import Foundation
|
||||
import AppKit
|
||||
import ApplicationServices
|
||||
|
||||
// ObserverContext carries the data for one AX observer. The C callback reads
|
||||
// the context from the refcon pointer. The registry keeps the context alive.
|
||||
final class ObserverContext {
|
||||
let pid: pid_t
|
||||
let handler: (pid_t, String, AXUIElement) -> Void
|
||||
|
||||
init(pid: pid_t, handler: @escaping (pid_t, String, AXUIElement) -> Void) {
|
||||
self.pid = pid
|
||||
self.handler = handler
|
||||
}
|
||||
}
|
||||
|
||||
// observerCallback is the C callback for every AX observer. The callback has
|
||||
// no captured state. The callback reads the context from the refcon pointer.
|
||||
// The callback hops to the main actor and calls the handler.
|
||||
private let observerCallback: AXObserverCallback = { _, element, notification, refcon in
|
||||
guard let refcon = refcon else { return }
|
||||
let context = Unmanaged<ObserverContext>.fromOpaque(refcon).takeUnretainedValue()
|
||||
let name = notification as String
|
||||
let pid = context.pid
|
||||
let handler = context.handler
|
||||
DispatchQueue.main.async {
|
||||
handler(pid, name, element)
|
||||
}
|
||||
}
|
||||
|
||||
// AppObserverRegistry holds one AXObserver per regular application. The
|
||||
// registry registers the notifications of spec section 7.4. The registry
|
||||
// removes the observer when the application terminates. The registry is
|
||||
// main-actor isolated.
|
||||
@MainActor
|
||||
final class AppObserverRegistry {
|
||||
|
||||
// Entry holds the state of one application observer.
|
||||
private final class Entry {
|
||||
let observer: AXObserver
|
||||
let appElement: AXUIElement
|
||||
let context: ObserverContext
|
||||
var windowElements: [AXUIElement] = []
|
||||
|
||||
init(observer: AXObserver, appElement: AXUIElement, context: ObserverContext) {
|
||||
self.observer = observer
|
||||
self.appElement = appElement
|
||||
self.context = context
|
||||
}
|
||||
}
|
||||
|
||||
private var entries: [pid_t: Entry] = [:]
|
||||
|
||||
// The application element gets these notifications.
|
||||
private let appNotifications = [
|
||||
kAXWindowCreatedNotification,
|
||||
kAXFocusedWindowChangedNotification,
|
||||
kAXMainWindowChangedNotification,
|
||||
kAXWindowMiniaturizedNotification,
|
||||
kAXWindowDeminiaturizedNotification
|
||||
]
|
||||
|
||||
// Each window element gets these notifications.
|
||||
private let windowNotifications = [
|
||||
kAXUIElementDestroyedNotification,
|
||||
kAXTitleChangedNotification,
|
||||
kAXMovedNotification,
|
||||
kAXResizedNotification
|
||||
]
|
||||
|
||||
// addApp creates the observer for one application. The handler runs on the
|
||||
// main actor. The function registers the application notifications.
|
||||
func addApp(pid: pid_t, handler: @escaping (pid_t, String, AXUIElement) -> Void) {
|
||||
guard entries[pid] == nil else { return }
|
||||
|
||||
var observer: AXObserver?
|
||||
let error = AXObserverCreate(pid, observerCallback, &observer)
|
||||
guard error == .success, let observer = observer else {
|
||||
Log.tracking.error("AXObserverCreate failed for pid \(pid): \(error.rawValue)")
|
||||
return
|
||||
}
|
||||
|
||||
let appElement = AXUIElementCreateApplication(pid)
|
||||
let context = ObserverContext(pid: pid, handler: handler)
|
||||
let entry = Entry(observer: observer, appElement: appElement, context: context)
|
||||
let refcon = Unmanaged.passUnretained(context).toOpaque()
|
||||
|
||||
for name in appNotifications {
|
||||
AXObserverAddNotification(observer, appElement, name as CFString, refcon)
|
||||
}
|
||||
|
||||
CFRunLoopAddSource(CFRunLoopGetMain(),
|
||||
AXObserverGetRunLoopSource(observer),
|
||||
.defaultMode)
|
||||
|
||||
entries[pid] = entry
|
||||
}
|
||||
|
||||
// setWindowElements registers the per-window notifications. The function
|
||||
// removes the notifications of the old window elements first. The caller
|
||||
// passes the current window elements after each enumeration.
|
||||
func setWindowElements(pid: pid_t, windows: [AXUIElement]) {
|
||||
guard let entry = entries[pid] else { return }
|
||||
let refcon = Unmanaged.passUnretained(entry.context).toOpaque()
|
||||
|
||||
for element in entry.windowElements {
|
||||
for name in windowNotifications {
|
||||
AXObserverRemoveNotification(entry.observer, element, name as CFString)
|
||||
}
|
||||
}
|
||||
for element in windows {
|
||||
for name in windowNotifications {
|
||||
AXObserverAddNotification(entry.observer, element, name as CFString, refcon)
|
||||
}
|
||||
}
|
||||
entry.windowElements = windows
|
||||
}
|
||||
|
||||
// removeApp removes the observer of one application. The function runs when
|
||||
// the application terminates.
|
||||
func removeApp(pid: pid_t) {
|
||||
guard let entry = entries[pid] else { return }
|
||||
CFRunLoopRemoveSource(CFRunLoopGetMain(),
|
||||
AXObserverGetRunLoopSource(entry.observer),
|
||||
.defaultMode)
|
||||
entries[pid] = nil
|
||||
}
|
||||
|
||||
// removeAll removes all observers. The function runs on stop and on an
|
||||
// Accessibility loss.
|
||||
func removeAll() {
|
||||
for pid in Array(entries.keys) {
|
||||
removeApp(pid: pid)
|
||||
}
|
||||
}
|
||||
}
|
||||
378
Sources/Tracking/TrackingController.swift
Normal file
378
Sources/Tracking/TrackingController.swift
Normal file
@@ -0,0 +1,378 @@
|
||||
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<pid_t> = []
|
||||
|
||||
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..<apps.count {
|
||||
if let lines = sections[index] {
|
||||
all.append(contentsOf: lines)
|
||||
}
|
||||
}
|
||||
completion(all)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Event handlers
|
||||
|
||||
private func handleFrontmostChanged(_ pid: pid_t) {
|
||||
store.setFrontmost(pid)
|
||||
registerObserver(for: pid)
|
||||
performRefreshNow(pid)
|
||||
checkFullScreen(pid)
|
||||
checkFocusedWindow(pid)
|
||||
}
|
||||
|
||||
private func handleAppTerminated(_ pid: pid_t) {
|
||||
observers.removeApp(pid: pid)
|
||||
store.removeApp(pid)
|
||||
}
|
||||
|
||||
private func handleActiveSpaceChanged() {
|
||||
guard let pid = store.frontmostPID else { return }
|
||||
scheduleRefresh(pid)
|
||||
checkFullScreen(pid)
|
||||
checkFocusedWindow(pid)
|
||||
}
|
||||
|
||||
private func registerObserver(for pid: pid_t) {
|
||||
observers.addApp(pid: pid) { [weak self] pid, name, element in
|
||||
self?.handleAXNotification(pid: pid, name: name, element: element)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleAXNotification(pid: pid_t, name: String, element: AXUIElement) {
|
||||
if name == kAXMovedNotification || name == kAXResizedNotification || name == kAXWindowCreatedNotification {
|
||||
// Resolve the CGWindowID on the serial AX queue (spec section 7.4).
|
||||
serialQueue.async { [weak self] in
|
||||
let id = PrivateAPI.shared.windowID(for: element)
|
||||
DispatchQueue.main.async {
|
||||
guard let self = self, let id = id else { return }
|
||||
self.onWindowGeometryEvent?(pid, name, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if name == kAXFocusedWindowChangedNotification || name == kAXMainWindowChangedNotification {
|
||||
checkFullScreen(pid)
|
||||
checkFocusedWindow(pid)
|
||||
}
|
||||
if pid == store.frontmostPID {
|
||||
scheduleRefresh(pid)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Refresh
|
||||
|
||||
// reconcile runs every 2 s. The reconcile covers applications that do not
|
||||
// send all AX notifications (spec section 7.4).
|
||||
private func reconcile() {
|
||||
guard let pid = store.frontmostPID else { return }
|
||||
performRefreshNow(pid)
|
||||
}
|
||||
|
||||
// scheduleRefresh coalesces the refresh. The controller runs at most one
|
||||
// refresh per 50 ms per application.
|
||||
private func scheduleRefresh(_ pid: pid_t) {
|
||||
let now = Date()
|
||||
let last = lastRefreshAt[pid] ?? .distantPast
|
||||
let elapsed = now.timeIntervalSince(last)
|
||||
if elapsed >= 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<CGWindowID>()
|
||||
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)
|
||||
}
|
||||
}
|
||||
325
Sources/Tracking/WindowEnumerator.swift
Normal file
325
Sources/Tracking/WindowEnumerator.swift
Normal file
@@ -0,0 +1,325 @@
|
||||
import Foundation
|
||||
import AppKit
|
||||
import ApplicationServices
|
||||
import CoreGraphics
|
||||
|
||||
// WindowEnumerator reads the windows of one application. The enumerator uses
|
||||
// two sources and merges them by CGWindowID (spec section 7.3).
|
||||
// - AX source: the current Space and the minimized windows.
|
||||
// - CGWindowList source: all Spaces.
|
||||
//
|
||||
// The enumerator does the blocking AX attribute reads on a background queue. A
|
||||
// frozen application must not freeze the caller (spec section 7.15). The caller
|
||||
// runs readAXWindows and readCGWindows on a serial queue.
|
||||
//
|
||||
// The enumerator does NOT map an AX element to a CGWindowID. The private
|
||||
// function for that map lives in PrivateAPI, and PrivateAPI is main-actor
|
||||
// isolated in the foundation. The caller resolves the window IDs on the main
|
||||
// actor and passes them to buildWindows. See the phase report for the reason.
|
||||
struct WindowEnumerator {
|
||||
|
||||
// AXRawWindow holds the raw AX data of one window.
|
||||
struct AXRawWindow {
|
||||
let element: AXUIElement
|
||||
let title: String?
|
||||
let isMinimized: Bool
|
||||
let subrole: String?
|
||||
let isFullScreen: Bool
|
||||
}
|
||||
|
||||
// CGRawWindow holds the raw CGWindowList data of one window.
|
||||
struct CGRawWindow {
|
||||
let windowID: CGWindowID
|
||||
let title: String?
|
||||
let layer: Int
|
||||
let bounds: CGRect
|
||||
}
|
||||
|
||||
// WindowDebugRecord holds one line for the debug dump (spec section 7.14).
|
||||
struct WindowDebugRecord {
|
||||
let windowID: CGWindowID
|
||||
let title: String
|
||||
let subrole: String?
|
||||
let layer: Int
|
||||
let bounds: CGRect
|
||||
let spaceIDs: [UInt64]
|
||||
let isMinimized: Bool
|
||||
let isFullScreen: Bool
|
||||
let shown: Bool
|
||||
let reason: String
|
||||
}
|
||||
|
||||
// EnumerationResult holds the result of buildWindows.
|
||||
struct EnumerationResult {
|
||||
let windows: [WindowInfo]
|
||||
let elements: [(CGWindowID, AXUIElement)]
|
||||
let debug: [WindowDebugRecord]
|
||||
}
|
||||
|
||||
private let standardSubrole = kAXStandardWindowSubrole as String
|
||||
|
||||
// readAXWindows reads the AX windows of the application. The function sets
|
||||
// the AX messaging timeout to 0.25 s. Run this function on a serial queue.
|
||||
func readAXWindows(pid: pid_t) -> [AXRawWindow] {
|
||||
let app = AXUIElementCreateApplication(pid)
|
||||
AXUIElementSetMessagingTimeout(app, 0.25)
|
||||
|
||||
let elements = Self.copyElements(app, kAXWindowsAttribute as String)
|
||||
var result: [AXRawWindow] = []
|
||||
result.reserveCapacity(elements.count)
|
||||
for element in elements {
|
||||
let title = Self.copyString(element, kAXTitleAttribute as String)
|
||||
let minimized = Self.copyBool(element, kAXMinimizedAttribute as String)
|
||||
let subrole = Self.copyString(element, kAXSubroleAttribute as String)
|
||||
let fullScreen = Self.copyBool(element, "AXFullScreen")
|
||||
result.append(AXRawWindow(element: element,
|
||||
title: title,
|
||||
isMinimized: minimized,
|
||||
subrole: subrole,
|
||||
isFullScreen: fullScreen))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// readFocusedFullScreen returns true if the focused window of the
|
||||
// application is full screen. Run this function on a serial queue.
|
||||
func readFocusedFullScreen(pid: pid_t) -> Bool {
|
||||
let app = AXUIElementCreateApplication(pid)
|
||||
AXUIElementSetMessagingTimeout(app, 0.25)
|
||||
var value: CFTypeRef?
|
||||
let error = AXUIElementCopyAttributeValue(app, kAXFocusedWindowAttribute as CFString, &value)
|
||||
guard error == .success, let value = value else { return false }
|
||||
let focused = value as! AXUIElement
|
||||
return Self.copyBool(focused, "AXFullScreen")
|
||||
}
|
||||
|
||||
// readFocusedWindowElement returns the focused window element of the
|
||||
// application. The caller resolves the CGWindowID on the main actor. Run
|
||||
// this function on a serial queue.
|
||||
func readFocusedWindowElement(pid: pid_t) -> AXUIElement? {
|
||||
let app = AXUIElementCreateApplication(pid)
|
||||
AXUIElementSetMessagingTimeout(app, 0.25)
|
||||
var value: CFTypeRef?
|
||||
let error = AXUIElementCopyAttributeValue(app, kAXFocusedWindowAttribute as CFString, &value)
|
||||
guard error == .success, let value = value else { return nil }
|
||||
return (value as! AXUIElement)
|
||||
}
|
||||
|
||||
// readCGWindows reads the CGWindowList windows of the application. The
|
||||
// function keeps only the windows of the given PID. Run this function on a
|
||||
// serial queue.
|
||||
func readCGWindows(pid: pid_t) -> [CGRawWindow] {
|
||||
let options: CGWindowListOption = [.optionAll, .excludeDesktopElements]
|
||||
guard let list = CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]] else {
|
||||
return []
|
||||
}
|
||||
var result: [CGRawWindow] = []
|
||||
for info in list {
|
||||
guard let owner = (info[kCGWindowOwnerPID as String] as? NSNumber)?.int32Value,
|
||||
owner == pid else { continue }
|
||||
let layer = (info[kCGWindowLayer as String] as? NSNumber)?.intValue ?? -1
|
||||
let windowID = (info[kCGWindowNumber as String] as? NSNumber)?.uint32Value ?? 0
|
||||
let title = info[kCGWindowName as String] as? String
|
||||
var bounds = CGRect.zero
|
||||
if let boundsValue = info[kCGWindowBounds as String] {
|
||||
let dict = boundsValue as! CFDictionary
|
||||
var rect = CGRect.zero
|
||||
if CGRectMakeWithDictionaryRepresentation(dict, &rect) {
|
||||
bounds = rect
|
||||
}
|
||||
}
|
||||
result.append(CGRawWindow(windowID: windowID,
|
||||
title: title,
|
||||
layer: layer,
|
||||
bounds: bounds))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// buildWindows merges the AX source and the CGWindowList source. The
|
||||
// function applies the filter rules (spec section 7.3). The function is
|
||||
// pure. The caller resolves axWindowIDs on the main actor. axWindowIDs is
|
||||
// parallel to ax.
|
||||
func buildWindows(pid: pid_t,
|
||||
bundleID: String?,
|
||||
appName: String,
|
||||
ax: [AXRawWindow],
|
||||
axWindowIDs: [CGWindowID?],
|
||||
cg: [CGRawWindow],
|
||||
spaceIDsByWindow: [CGWindowID: [UInt64]],
|
||||
currentSpaceIDs: [UInt64],
|
||||
ownPID: pid_t,
|
||||
screenBoundsCG: CGRect = .null,
|
||||
now: Date = Date()) -> EnumerationResult {
|
||||
|
||||
// Index the AX windows by CGWindowID.
|
||||
var axByID: [CGWindowID: AXRawWindow] = [:]
|
||||
for (index, window) in ax.enumerated() {
|
||||
guard index < axWindowIDs.count, let id = axWindowIDs[index], id != 0 else { continue }
|
||||
axByID[id] = window
|
||||
}
|
||||
var cgByID: [CGWindowID: CGRawWindow] = [:]
|
||||
for window in cg where window.windowID != 0 {
|
||||
cgByID[window.windowID] = window
|
||||
}
|
||||
|
||||
var ids = Set<CGWindowID>()
|
||||
ids.formUnion(axByID.keys)
|
||||
ids.formUnion(cgByID.keys)
|
||||
|
||||
var windows: [WindowInfo] = []
|
||||
var elements: [(CGWindowID, AXUIElement)] = []
|
||||
var debug: [WindowDebugRecord] = []
|
||||
|
||||
for id in ids {
|
||||
let axWindow = axByID[id]
|
||||
let cgWindow = cgByID[id]
|
||||
|
||||
let spaceIDs = spaceIDsByWindow[id] ?? []
|
||||
let onCurrentSpace = isOnCurrentSpace(windowSpaceIDs: spaceIDs,
|
||||
currentSpaceIDs: currentSpaceIDs)
|
||||
|
||||
var title = appName
|
||||
if let axTitle = axWindow?.title, axTitle.isEmpty == false {
|
||||
title = axTitle
|
||||
} else if let cgTitle = cgWindow?.title, cgTitle.isEmpty == false {
|
||||
title = cgTitle
|
||||
}
|
||||
|
||||
let subrole = axWindow?.subrole
|
||||
let layer = cgWindow?.layer ?? 0
|
||||
let bounds = cgWindow?.bounds ?? .zero
|
||||
let isMinimized = axWindow?.isMinimized ?? false
|
||||
let isFullScreen = axWindow?.isFullScreen ?? false
|
||||
let hasAX = axWindow != nil
|
||||
|
||||
let decision = shouldShow(ownerPID: pid,
|
||||
ownPID: ownPID,
|
||||
layer: layer,
|
||||
subrole: subrole,
|
||||
hasAX: hasAX,
|
||||
bounds: bounds,
|
||||
title: title,
|
||||
appName: appName,
|
||||
isMinimized: isMinimized,
|
||||
screenBoundsCG: screenBoundsCG,
|
||||
hasCG: cgWindow != nil)
|
||||
|
||||
debug.append(WindowDebugRecord(windowID: id,
|
||||
title: title,
|
||||
subrole: subrole,
|
||||
layer: layer,
|
||||
bounds: bounds,
|
||||
spaceIDs: spaceIDs,
|
||||
isMinimized: isMinimized,
|
||||
isFullScreen: isFullScreen,
|
||||
shown: decision.show,
|
||||
reason: decision.reason))
|
||||
|
||||
guard decision.show else { continue }
|
||||
|
||||
let info = WindowInfo(id: id,
|
||||
pid: pid,
|
||||
bundleID: bundleID,
|
||||
title: title,
|
||||
spaceIDs: spaceIDs,
|
||||
isOnCurrentSpace: onCurrentSpace,
|
||||
isMinimized: isMinimized,
|
||||
isFullScreen: isFullScreen,
|
||||
firstSeen: now)
|
||||
windows.append(info)
|
||||
|
||||
if let element = axWindow?.element {
|
||||
elements.append((id, element))
|
||||
}
|
||||
}
|
||||
|
||||
return EnumerationResult(windows: windows, elements: elements, debug: debug)
|
||||
}
|
||||
|
||||
// shouldShow applies the filter rules of spec section 7.3. A window is
|
||||
// shown only if all rules are true.
|
||||
private func shouldShow(ownerPID: pid_t,
|
||||
ownPID: pid_t,
|
||||
layer: Int,
|
||||
subrole: String?,
|
||||
hasAX: Bool,
|
||||
bounds: CGRect,
|
||||
title: String,
|
||||
appName: String,
|
||||
isMinimized: Bool,
|
||||
screenBoundsCG: CGRect,
|
||||
hasCG: Bool) -> (show: Bool, reason: String) {
|
||||
if ownerPID == ownPID {
|
||||
return (false, "owned by EPOD Window Bar")
|
||||
}
|
||||
if hasCG, layer != 0 {
|
||||
return (false, "layer != 0 (\(layer))")
|
||||
}
|
||||
// Off-screen check: hide a window that lies entirely outside all
|
||||
// screens (for example the Eclipse "limbo" shell at y=10000). A
|
||||
// minimized window keeps its tab. The user restores it with a click.
|
||||
if isMinimized == false,
|
||||
screenBoundsCG.isNull == false, screenBoundsCG.isEmpty == false,
|
||||
bounds.isEmpty == false, bounds.intersects(screenBoundsCG) == false {
|
||||
return (false, "off-screen")
|
||||
}
|
||||
if hasAX {
|
||||
if subrole != standardSubrole {
|
||||
return (false, "subrole \(subrole ?? "nil") is not standard")
|
||||
}
|
||||
} else {
|
||||
// The window has no AX element. The window is on another Space, or
|
||||
// the window is a hidden placeholder. A genuine window has a
|
||||
// distinct title. A placeholder has the application name as the
|
||||
// title. The title is the application name because the real title
|
||||
// is empty, or because kCGWindowName is set to the application name.
|
||||
if title == appName {
|
||||
return (false, "no AX and title is the app name")
|
||||
}
|
||||
if bounds.width < 50 || bounds.height < 50 {
|
||||
return (false, "no AX and bounds < 50 x 50")
|
||||
}
|
||||
}
|
||||
return (true, "shown")
|
||||
}
|
||||
|
||||
// isOnCurrentSpace returns true if the window shares a Space with a current
|
||||
// Space. If the Space data is empty, the function returns true.
|
||||
private func isOnCurrentSpace(windowSpaceIDs: [UInt64], currentSpaceIDs: [UInt64]) -> Bool {
|
||||
if windowSpaceIDs.isEmpty || currentSpaceIDs.isEmpty { return true }
|
||||
for id in windowSpaceIDs where currentSpaceIDs.contains(id) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MARK: - AX attribute helpers
|
||||
|
||||
private static func copyString(_ element: AXUIElement, _ attribute: String) -> String? {
|
||||
var value: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success,
|
||||
let value = value else { return nil }
|
||||
return value as? String
|
||||
}
|
||||
|
||||
private static func copyBool(_ element: AXUIElement, _ attribute: String) -> Bool {
|
||||
var value: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success,
|
||||
let value = value else { return false }
|
||||
if CFGetTypeID(value) == CFBooleanGetTypeID() {
|
||||
return CFBooleanGetValue((value as! CFBoolean))
|
||||
}
|
||||
if let number = value as? NSNumber {
|
||||
return number.boolValue
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private static func copyElements(_ element: AXUIElement, _ attribute: String) -> [AXUIElement] {
|
||||
var value: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success,
|
||||
let value = value else { return [] }
|
||||
return value as? [AXUIElement] ?? []
|
||||
}
|
||||
}
|
||||
80
Sources/Tracking/WorkspaceEvents.swift
Normal file
80
Sources/Tracking/WorkspaceEvents.swift
Normal file
@@ -0,0 +1,80 @@
|
||||
import Foundation
|
||||
import AppKit
|
||||
|
||||
// WorkspaceEvents subscribes to the NSWorkspace notifications and the screen
|
||||
// parameter notification (spec section 7.4). The type turns each notification
|
||||
// into a callback. The type is main-actor isolated.
|
||||
@MainActor
|
||||
final class WorkspaceEvents {
|
||||
|
||||
var onFrontmostChanged: ((pid_t) -> Void)?
|
||||
var onAppLaunched: ((NSRunningApplication) -> Void)?
|
||||
var onAppTerminated: ((pid_t) -> Void)?
|
||||
var onActiveSpaceChanged: (() -> Void)?
|
||||
var onScreenParametersChanged: (() -> Void)?
|
||||
|
||||
private var tokens: [NSObjectProtocol] = []
|
||||
|
||||
// start subscribes to the notifications.
|
||||
func start() {
|
||||
let workspaceCenter = NSWorkspace.shared.notificationCenter
|
||||
|
||||
tokens.append(workspaceCenter.addObserver(
|
||||
forName: NSWorkspace.didActivateApplicationNotification,
|
||||
object: nil, queue: .main) { [weak self] note in
|
||||
MainActor.assumeIsolated {
|
||||
guard let app = Self.app(from: note) else { return }
|
||||
self?.onFrontmostChanged?(app.processIdentifier)
|
||||
}
|
||||
})
|
||||
|
||||
tokens.append(workspaceCenter.addObserver(
|
||||
forName: NSWorkspace.didLaunchApplicationNotification,
|
||||
object: nil, queue: .main) { [weak self] note in
|
||||
MainActor.assumeIsolated {
|
||||
guard let app = Self.app(from: note) else { return }
|
||||
self?.onAppLaunched?(app)
|
||||
}
|
||||
})
|
||||
|
||||
tokens.append(workspaceCenter.addObserver(
|
||||
forName: NSWorkspace.didTerminateApplicationNotification,
|
||||
object: nil, queue: .main) { [weak self] note in
|
||||
MainActor.assumeIsolated {
|
||||
guard let app = Self.app(from: note) else { return }
|
||||
self?.onAppTerminated?(app.processIdentifier)
|
||||
}
|
||||
})
|
||||
|
||||
tokens.append(workspaceCenter.addObserver(
|
||||
forName: NSWorkspace.activeSpaceDidChangeNotification,
|
||||
object: nil, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated {
|
||||
self?.onActiveSpaceChanged?()
|
||||
}
|
||||
})
|
||||
|
||||
tokens.append(NotificationCenter.default.addObserver(
|
||||
forName: NSApplication.didChangeScreenParametersNotification,
|
||||
object: nil, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated {
|
||||
self?.onScreenParametersChanged?()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// stop removes the subscriptions.
|
||||
func stop() {
|
||||
let workspaceCenter = NSWorkspace.shared.notificationCenter
|
||||
for token in tokens {
|
||||
workspaceCenter.removeObserver(token)
|
||||
NotificationCenter.default.removeObserver(token)
|
||||
}
|
||||
tokens.removeAll()
|
||||
}
|
||||
|
||||
// app reads the NSRunningApplication from the notification user info.
|
||||
private static func app(from note: Notification) -> NSRunningApplication? {
|
||||
return note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user