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:
Erhan Keseli
2026-11-21 21:41:06 +01:00
commit 70d7ca5efe
43 changed files with 4332 additions and 0 deletions

View File

@@ -0,0 +1,138 @@
import AppKit
import ApplicationServices
import CoreGraphics
// WindowActivator runs the window actions: activate, minimize, and close.
// The class follows spec section 7.6. The class is main-actor isolated.
//
// NOTE: These AX calls run on the main actor. A user click starts each action,
// so the call is short. The spec wants AX calls off the main thread. A later
// change can move these reads to the serial AX queue.
@MainActor
final class WindowActivator {
private let store: WindowStore
private let cache: AXElementCache
init(store: WindowStore, cache: AXElementCache) {
self.store = store
self.cache = cache
}
// activate brings the window to the front. The method handles the current
// Space, a minimized window, and a window on another Space.
func activate(windowID: CGWindowID) {
guard let info = findWindow(windowID) else {
Log.activation.error("activate: no window info for \(windowID)")
return
}
let app = NSRunningApplication(processIdentifier: info.pid)
let element = resolveElement(for: info)
// Step 1: restore a minimized window.
if info.isMinimized, let element = element {
setBool(element, kAXMinimizedAttribute, false)
}
if info.isOnCurrentSpace {
// Step 2: the window is on the current Space.
if let element = element {
AXUIElementPerformAction(element, kAXRaiseAction as CFString)
}
app?.activate()
if let element = element {
setBool(element, kAXMainAttribute, true)
}
} else {
// Step 3: the window is on another Space.
if let element = element {
// Method A: raise the remote element, then activate the app.
AXUIElementPerformAction(element, kAXRaiseAction as CFString)
app?.activate()
} else {
// Method B: activate the app only.
Log.activation.warning("activate: no AX element for other-Space window \(windowID); app activate only")
app?.activate()
}
}
// Step 4: check the focused window after 300 ms.
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in
self?.verifyFocused(info)
}
}
// minimize minimizes the window.
func minimize(windowID: CGWindowID) {
guard let info = findWindow(windowID), let element = resolveElement(for: info) else {
Log.activation.error("minimize: no AX element for \(windowID)")
return
}
setBool(element, kAXMinimizedAttribute, true)
}
// close presses the close button of the window. The application can show a
// "save changes?" dialog. This is correct behavior.
func close(windowID: CGWindowID) {
guard let info = findWindow(windowID), let element = resolveElement(for: info) else {
Log.activation.error("close: no AX element for \(windowID)")
return
}
var button: CFTypeRef?
let error = AXUIElementCopyAttributeValue(element, kAXCloseButtonAttribute as CFString, &button)
guard error == .success, let button = button,
CFGetTypeID(button) == AXUIElementGetTypeID() else {
Log.activation.error("close: no close button for \(windowID)")
return
}
let buttonElement = button as! AXUIElement
AXUIElementPerformAction(buttonElement, kAXPressAction as CFString)
}
// resolveElement returns the AX element for a window. The method reads the
// cache first. For a window on another Space the method uses the private
// remote token.
private func resolveElement(for info: WindowInfo) -> AXUIElement? {
if let cached = cache.element(for: info.id) {
return cached
}
if info.isOnCurrentSpace == false {
return PrivateAPI.shared.remoteElement(pid: info.pid, windowID: info.id)
}
return nil
}
// verifyFocused reads the focused window of the application. The method
// logs a warning if the focused window is not the target window.
private func verifyFocused(_ info: WindowInfo) {
let appElement = AXUIElementCreateApplication(info.pid)
var focused: CFTypeRef?
let error = AXUIElementCopyAttributeValue(appElement, kAXFocusedWindowAttribute as CFString, &focused)
guard error == .success, let focused = focused,
CFGetTypeID(focused) == AXUIElementGetTypeID() else {
Log.activation.debug("verify: cannot read focused window for pid \(info.pid)")
return
}
let focusedElement = focused as! AXUIElement
let focusedID = PrivateAPI.shared.windowID(for: focusedElement)
if focusedID != info.id {
let text = focusedID.map { String($0) } ?? "nil"
Log.activation.debug("verify: focused window \(text, privacy: .public) is not target \(info.id)")
}
}
private func findWindow(_ id: CGWindowID) -> WindowInfo? {
for pid in store.allPIDs() {
if let window = store.windows(for: pid).first(where: { $0.id == id }) {
return window
}
}
return nil
}
private func setBool(_ element: AXUIElement, _ attribute: String, _ value: Bool) {
let cfValue: CFTypeRef = value ? kCFBooleanTrue : kCFBooleanFalse
AXUIElementSetAttributeValue(element, attribute as CFString, cfValue)
}
}

View File

@@ -0,0 +1,17 @@
import Foundation
// AppControl is the interface for the menu bar item and the settings window.
// AppDelegate implements AppControl. The protocol keeps the UI modules
// independent from the concrete controllers.
@MainActor
protocol AppControl: AnyObject {
var isPaused: Bool { get }
func togglePause()
var constrainWindows: Bool { get }
func setConstrainWindows(_ on: Bool)
func dumpWindowsToLog()
func copyWindowDump()
func openSettings()
}

View File

@@ -0,0 +1,254 @@
import AppKit
import ApplicationServices
import CoreGraphics
// AppDelegate wires every module of EPOD Window Bar together. The delegate
// starts the tracking, the strip, the activation, and the constraint services
// after Accessibility is granted. The delegate implements AppControl for the
// menu bar item and the settings window.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate, AppControl {
private let permissions = PermissionManager()
private let settings = Settings.shared
private let store = WindowStore()
private let cache = AXElementCache()
private let spaceService = SpaceService()
private var menuBar: MenuBarController?
private var onboarding: OnboardingWindow?
private var settingsWindow: SettingsWindow?
private var tracking: TrackingController?
private var strip: StripController?
private var activator: WindowActivator?
private var constraint: WindowConstraintService?
private var servicesStarted = false
private var userContinuedReduced = false
private var isFullScreenNow = false
private var screenPollTimer: Timer?
private var lastVisibleFrame: CGRect = .zero
func applicationDidFinishLaunching(_ notification: Notification) {
Log.app.info("EPOD Window Bar starts.")
menuBar = MenuBarController(permissions: permissions, control: self, settings: settings)
permissions.onChange = { [weak self] state in
self?.handle(state)
}
permissions.start()
handle(permissions.current)
}
// handle reacts to a new permission state. The app starts the services if
// Accessibility is granted. The app shows the onboarding window if
// Accessibility is missing (spec section 6.1).
private func handle(_ state: PermissionState) {
menuBar?.updatePermissionState(state)
onboarding?.update(state: state)
if state.accessibility {
startServicesIfNeeded()
updateStripVisibility()
if state.allGranted {
onboarding?.close()
} else if userContinuedReduced == false {
showOnboarding()
}
} else {
userContinuedReduced = false
stopServices()
showOnboarding()
}
}
// MARK: - Services
private func startServicesIfNeeded() {
guard servicesStarted == false else { return }
servicesStarted = true
let tracking = TrackingController(store: store,
cache: cache,
spaceService: spaceService,
settings: settings)
let strip = StripController(store: store, settings: settings)
let activator = WindowActivator(store: store, cache: cache)
let constraint = WindowConstraintService(store: store, cache: cache, settings: settings)
// The strip forwards the tab actions to the activator.
strip.onActivate = { [weak self] id in self?.activator?.activate(windowID: id) }
strip.onMinimize = { [weak self] id in self?.activator?.minimize(windowID: id) }
strip.onClose = { [weak self] id in self?.activator?.close(windowID: id) }
// The tracking controller reports the focused window for the active tab.
tracking.onFocusedWindowChanged = { [weak self] id in
self?.strip?.activeWindowID = id
}
// The tracking controller reports the full-screen state. The strip
// hides in full screen (decision D7).
tracking.onFrontmostFocusedFullScreenChanged = { [weak self] full in
self?.isFullScreenNow = full
self?.updateStripVisibility()
}
// The tracking controller forwards the geometry events to the
// constraint service (spec section 7.10). The controller resolves the
// CGWindowID on the serial AX queue.
tracking.onWindowGeometryEvent = { [weak self] _, name, id in
guard let self = self, self.settings.paused == false else { return }
if name == kAXWindowCreatedNotification {
self.constraint?.constrainOnCreate(windowID: id)
} else {
self.constraint?.handleMovedOrResized(windowID: id)
}
}
self.tracking = tracking
self.strip = strip
self.activator = activator
self.constraint = constraint
strip.start()
tracking.start()
constraint.stripFrame = strip.stripFrame
startScreenObservers()
updateStripVisibility()
}
// stopServices stops all AX work. The app calls this function when
// Accessibility is revoked at runtime (spec section 6.1). The app does not
// crash.
private func stopServices() {
guard servicesStarted else { return }
servicesStarted = false
tracking?.onAccessibilityLost()
strip?.setVisible(false)
stopScreenObservers()
tracking = nil
strip = nil
activator = nil
constraint = nil
cache.removeAll()
}
// updateStripVisibility shows the strip only if the app is active, the app
// is not paused, and the frontmost window is not full screen.
private func updateStripVisibility() {
let visible = settings.paused == false
&& isFullScreenNow == false
&& permissions.current.accessibility
strip?.setVisible(visible)
}
// MARK: - Screen and Dock changes
private func startScreenObservers() {
NotificationCenter.default.addObserver(
self,
selector: #selector(screenParametersChanged),
name: NSApplication.didChangeScreenParametersNotification,
object: nil)
NSWorkspace.shared.notificationCenter.addObserver(
self,
selector: #selector(didWake),
name: NSWorkspace.didWakeNotification,
object: nil)
lastVisibleFrame = NSScreen.main?.visibleFrame ?? .zero
// The Dock preference change has no public notification. The app polls
// the visible frame every 2 s (spec section 7.8).
screenPollTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in
MainActor.assumeIsolated {
self?.pollVisibleFrame()
}
}
}
private func stopScreenObservers() {
NotificationCenter.default.removeObserver(
self, name: NSApplication.didChangeScreenParametersNotification, object: nil)
NSWorkspace.shared.notificationCenter.removeObserver(
self, name: NSWorkspace.didWakeNotification, object: nil)
screenPollTimer?.invalidate()
screenPollTimer = nil
}
@objc private func screenParametersChanged() {
repositionStrip()
}
@objc private func didWake() {
repositionStrip()
}
private func pollVisibleFrame() {
let current = NSScreen.main?.visibleFrame ?? .zero
if current != lastVisibleFrame {
lastVisibleFrame = current
repositionStrip()
}
}
private func repositionStrip() {
strip?.reposition()
if let strip = strip {
constraint?.stripFrame = strip.stripFrame
}
}
// MARK: - Onboarding
private func showOnboarding() {
if onboarding == nil {
let window = OnboardingWindow(permissions: permissions)
window.onContinue = { [weak self] in
self?.userContinuedReduced = true
self?.onboarding?.close()
}
onboarding = window
}
onboarding?.show()
}
// MARK: - AppControl
var isPaused: Bool {
return settings.paused
}
func togglePause() {
settings.paused.toggle()
updateStripVisibility()
Log.app.info("Pause is now \(self.settings.paused, privacy: .public).")
}
var constrainWindows: Bool {
return settings.constrainWindows
}
func setConstrainWindows(_ on: Bool) {
settings.constrainWindows = on
Log.app.info("Constrain windows is now \(on, privacy: .public).")
}
func dumpWindowsToLog() {
tracking?.dumpWindowsToLog()
}
func copyWindowDump() {
tracking?.dumpWindowsToPasteboard()
}
func openSettings() {
if settingsWindow == nil {
settingsWindow = SettingsWindow(settings: settings)
}
settingsWindow?.show()
}
}

View File

@@ -0,0 +1,31 @@
import Foundation
import ServiceManagement
// LaunchAtLogin controls the login item of EPOD Window Bar. The helper uses
// SMAppService.mainApp. The helper logs an error and does not crash if the
// register call or the unregister call fails.
@MainActor
enum LaunchAtLogin {
// isEnabled is true if the app starts at login.
static var isEnabled: Bool {
return SMAppService.mainApp.status == .enabled
}
// setEnabled turns the login item on or off.
static func setEnabled(_ on: Bool) {
do {
if on {
if SMAppService.mainApp.status != .enabled {
try SMAppService.mainApp.register()
}
} else {
if SMAppService.mainApp.status == .enabled {
try SMAppService.mainApp.unregister()
}
}
} catch {
Log.app.error("Launch at login change failed: \(error.localizedDescription, privacy: .public)")
}
}
}

View File

@@ -0,0 +1,160 @@
import AppKit
// MenuBarController owns the NSStatusItem and the menu (spec section 7.12).
// The menu refreshes its checkmarks each time the user opens the menu. The
// button shows a warning symbol if a permission is missing.
@MainActor
final class MenuBarController: NSObject, NSMenuDelegate {
private let statusItem: NSStatusItem
private let permissions: PermissionManager
private weak var control: AppControl?
private let settings: Settings
private let menu = NSMenu()
private let pauseItem = NSMenuItem()
private let constrainItem = NSMenuItem()
private let launchItem = NSMenuItem()
private let permissionsItem = NSMenuItem()
private var lastState: PermissionState
init(permissions: PermissionManager, control: AppControl, settings: Settings) {
self.permissions = permissions
self.control = control
self.settings = settings
self.lastState = permissions.current
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
super.init()
configureButton()
buildMenu()
updatePermissionState(permissions.current)
}
private func configureButton() {
guard let button = statusItem.button else { return }
button.image = NSImage(systemSymbolName: "rectangle.split.3x1",
accessibilityDescription: "EPOD Window Bar")
button.image?.isTemplate = true
}
private func buildMenu() {
menu.delegate = self
pauseItem.title = "Pause EPOD Window Bar"
pauseItem.action = #selector(togglePause)
pauseItem.target = self
menu.addItem(pauseItem)
constrainItem.title = "Keep windows above strip"
constrainItem.action = #selector(toggleConstrain)
constrainItem.target = self
menu.addItem(constrainItem)
menu.addItem(.separator())
let excluded = NSMenuItem(title: "Excluded apps…",
action: #selector(openSettings),
keyEquivalent: "")
excluded.target = self
menu.addItem(excluded)
launchItem.title = "Launch at login"
launchItem.action = #selector(toggleLaunchAtLogin)
launchItem.target = self
menu.addItem(launchItem)
let dump = NSMenuItem(title: "Dump windows to log",
action: #selector(dumpWindows),
keyEquivalent: "")
dump.target = self
menu.addItem(dump)
let copyDump = NSMenuItem(title: "Copy window dump",
action: #selector(copyWindowDump),
keyEquivalent: "")
copyDump.target = self
menu.addItem(copyDump)
menu.addItem(.separator())
permissionsItem.title = "Permissions: unknown"
permissionsItem.isEnabled = false
menu.addItem(permissionsItem)
menu.addItem(.separator())
let quit = NSMenuItem(title: "Quit EPOD Window Bar",
action: #selector(quit),
keyEquivalent: "q")
quit.target = self
menu.addItem(quit)
statusItem.menu = menu
}
// updatePermissionState sets the status text and the button symbol.
// The button shows a warning symbol if a permission is missing.
func updatePermissionState(_ state: PermissionState) {
lastState = state
let text: String
if state.allGranted {
text = "Permissions: all granted"
} else if state.accessibility {
text = "Permissions: Screen Recording missing (reduced mode)"
} else {
text = "Permissions: Accessibility missing"
}
permissionsItem.title = text
guard let button = statusItem.button else { return }
let symbol = state.allGranted ? "rectangle.split.3x1" : "exclamationmark.triangle"
button.image = NSImage(systemSymbolName: symbol,
accessibilityDescription: "EPOD Window Bar")
button.image?.isTemplate = true
}
// refreshState sets the checkmarks from the current app state. The menu
// calls this function each time the user opens the menu.
private func refreshState() {
pauseItem.state = (control?.isPaused ?? false) ? .on : .off
constrainItem.state = (control?.constrainWindows ?? true) ? .on : .off
launchItem.state = LaunchAtLogin.isEnabled ? .on : .off
updatePermissionState(permissions.current)
}
// menuNeedsUpdate refreshes the menu state before macOS shows the menu.
func menuNeedsUpdate(_ menu: NSMenu) {
refreshState()
}
@objc private func togglePause() {
control?.togglePause()
}
@objc private func toggleConstrain() {
let now = control?.constrainWindows ?? true
control?.setConstrainWindows(!now)
}
@objc private func openSettings() {
control?.openSettings()
}
@objc private func toggleLaunchAtLogin() {
LaunchAtLogin.setEnabled(!LaunchAtLogin.isEnabled)
}
@objc private func dumpWindows() {
control?.dumpWindowsToLog()
}
@objc private func copyWindowDump() {
control?.copyWindowDump()
}
@objc private func quit() {
NSApp.terminate(nil)
}
}

14
Sources/App/main.swift Normal file
View File

@@ -0,0 +1,14 @@
import AppKit
// EPOD Window Bar entry point.
// The app is an agent (LSUIElement). It has no Dock icon and no main menu.
// The program starts on the main thread. The app and the delegate are
// main-actor isolated. MainActor.assumeIsolated makes the main-actor context
// available at the entry point.
MainActor.assumeIsolated {
let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.setActivationPolicy(.accessory)
app.run()
}

View File

@@ -0,0 +1,25 @@
import CoreGraphics
// ConstraintMath holds the pure math for the window constraint (spec 7.10).
// The functions have no AppKit dependency. The unit tests cover the functions.
//
// Coordinate convention: Cocoa. The origin is bottom-left. The Y axis points
// up. The window bottom is rect.minY. The window top is rect.maxY. limitY is
// the strip top edge in Cocoa Y. This convention matches Sources/Util/Geometry.swift.
enum ConstraintMath {
// newHeight returns the new window height so the window bottom sits at
// limitY. The function keeps the window top fixed. The function returns nil
// if the window bottom is at limitY or above limitY.
static func newHeight(windowCocoa: CGRect, limitY: CGFloat) -> CGFloat? {
guard windowCocoa.minY < limitY else { return nil }
return windowCocoa.maxY - limitY
}
// isIntentionalMoveDown returns true if the window top is also below
// (limitY - 100). In this case the user moved the window down on purpose.
// The service does nothing (spec 7.10, step 3).
static func isIntentionalMoveDown(windowTopCocoa: CGFloat, limitY: CGFloat) -> Bool {
return windowTopCocoa < (limitY - 100)
}
}

View File

@@ -0,0 +1,193 @@
import AppKit
import ApplicationServices
import CoreGraphics
// WindowConstraintService keeps windows above the strip (decision D6, spec
// 7.10). The service reacts to move and resize events. The service resizes a
// window so the window bottom sits at the strip top edge.
//
// NOTE: These AX reads and writes run on the main actor. The spec wants AX
// calls off the main thread. A later change can move the AX work to the serial
// AX queue. The debounce and the loop protection stay the same.
@MainActor
final class WindowConstraintService {
private let store: WindowStore
private let cache: AXElementCache
private let settings: Settings
// stripFrame is the strip frame in Cocoa global coordinates. The
// integration sets this value. limitY is the strip top edge.
var stripFrame: CGRect = .zero
private var limitY: CGFloat { stripFrame.maxY }
// debounceWork holds the pending resize work per window.
private var debounceWork: [CGWindowID: DispatchWorkItem] = [:]
// ignoreUntil holds the loop-protection deadline per window.
private var ignoreUntil: [CGWindowID: Date] = [:]
// blacklist holds the applications that do not accept the new size.
private var blacklist: Set<pid_t> = []
init(store: WindowStore, cache: AXElementCache, settings: Settings) {
self.store = store
self.cache = cache
self.settings = settings
}
// handleMovedOrResized schedules a constraint check after a move or a
// resize event.
func handleMovedOrResized(windowID: CGWindowID) {
schedule(windowID)
}
// constrainOnCreate schedules a constraint check for a new window.
func constrainOnCreate(windowID: CGWindowID) {
schedule(windowID)
}
// schedule debounces the check. The service waits 150 ms after the last
// event of a window.
private func schedule(_ id: CGWindowID) {
debounceWork[id]?.cancel()
let work = DispatchWorkItem { [weak self] in
self?.constrainNow(id)
}
debounceWork[id] = work
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: work)
}
// constrainNow runs the constraint check for one window.
private func constrainNow(_ id: CGWindowID) {
debounceWork[id] = nil
// Loop protection: ignore the window after an own resize.
if let until = ignoreUntil[id], until > Date() {
return
}
// Do not resize during a drag. Check the window again after the drag.
if NSEvent.pressedMouseButtons != 0 {
schedule(id)
return
}
// Skip rules (spec 7.10, step 1).
guard settings.constrainWindows else { return }
guard let info = findWindow(id) else { return }
if settings.isExcluded(info.bundleID) { return }
if info.isFullScreen { return }
if blacklist.contains(info.pid) { return }
if StageManagerState.isOn { return }
guard let element = cache.element(for: id) else { return }
guard subrole(element) == (kAXStandardWindowSubrole as String) else { return }
guard isSizeSettable(element) else { return }
guard let currentFrame = axFrame(element) else { return }
let primaryHeight = NSScreen.screens.first?.frame.height ?? 0
let cocoa = Geometry.axToCocoa(currentFrame, primaryHeight: primaryHeight)
// Skip if the window is not on the strip screen (spec 7.10, step 2).
guard isOnStripScreen(cocoa) else { return }
// The window bottom must be below the limit (spec 7.10, step 3).
guard cocoa.minY < limitY else { return }
// The user moved the window down on purpose. Do nothing.
if ConstraintMath.isIntentionalMoveDown(windowTopCocoa: cocoa.maxY, limitY: limitY) {
return
}
guard let newHeight = ConstraintMath.newHeight(windowCocoa: cocoa, limitY: limitY),
newHeight > 0 else {
return
}
let requested = CGSize(width: cocoa.width, height: newHeight)
// Set the loop-protection deadline before the resize.
ignoreUntil[id] = Date().addingTimeInterval(0.3)
setSize(element, requested)
// Check the size after the set. Blacklist the application if the size
// is wrong.
if let after = axFrame(element), abs(after.height - requested.height) > 2 {
blacklist.insert(info.pid)
Log.constraint.warning("app \(info.pid) did not accept the new size; blacklist for this session")
}
}
// isOnStripScreen returns true if the window is on the strip screen.
private func isOnStripScreen(_ cocoa: CGRect) -> Bool {
guard let stripScreen = NSScreen.screens.first(where: { $0.frame.intersects(stripFrame) }) else {
return true
}
return stripScreen.frame.intersects(cocoa)
}
private func findWindow(_ id: CGWindowID) -> WindowInfo? {
for pid in store.allPIDs() {
if let window = store.windows(for: pid).first(where: { $0.id == id }) {
return window
}
}
return nil
}
private func subrole(_ element: AXUIElement) -> String? {
var value: CFTypeRef?
guard AXUIElementCopyAttributeValue(element, kAXSubroleAttribute as CFString, &value) == .success else {
return nil
}
return value as? String
}
private func isSizeSettable(_ element: AXUIElement) -> Bool {
var settable: DarwinBoolean = false
let error = AXUIElementIsAttributeSettable(element, kAXSizeAttribute as CFString, &settable)
return error == .success && settable.boolValue
}
// axFrame returns the window frame in AX coordinates (top-left origin).
private func axFrame(_ element: AXUIElement) -> CGRect? {
var positionValue: CFTypeRef?
var sizeValue: CFTypeRef?
guard AXUIElementCopyAttributeValue(element, kAXPositionAttribute as CFString, &positionValue) == .success,
AXUIElementCopyAttributeValue(element, kAXSizeAttribute as CFString, &sizeValue) == .success,
let positionValue = positionValue, let sizeValue = sizeValue,
CFGetTypeID(positionValue) == AXValueGetTypeID(),
CFGetTypeID(sizeValue) == AXValueGetTypeID() else {
return nil
}
var point = CGPoint.zero
var size = CGSize.zero
AXValueGetValue(positionValue as! AXValue, .cgPoint, &point)
AXValueGetValue(sizeValue as! AXValue, .cgSize, &size)
return CGRect(origin: point, size: size)
}
private func setSize(_ element: AXUIElement, _ size: CGSize) {
var value = size
if let axValue = AXValueCreate(.cgSize, &value) {
AXUIElementSetAttributeValue(element, kAXSizeAttribute as CFString, axValue)
}
}
}
// StageManagerState reads the Stage Manager state.
//
// UNCERTAIN: macOS has no public API for the Stage Manager state. The key
// "GloballyEnabled" in the domain "com.apple.WindowManager" reports if Stage
// Manager is on. This key reports the global setting, not the per-Space state.
// The constraint service skips the window if this key is true.
private enum StageManagerState {
static var isOn: Bool {
guard let defaults = UserDefaults(suiteName: "com.apple.WindowManager") else {
return false
}
return defaults.bool(forKey: "GloballyEnabled")
}
}

View File

@@ -0,0 +1,17 @@
import Foundation
import CoreGraphics
// WindowInfo is the value type for one window. The primary key is the
// CGWindowID. The type does not hold the AXUIElement. The AX element lives in
// a separate cache (AXElementCache). See spec section 7.2.
struct WindowInfo: Identifiable, Equatable {
let id: CGWindowID
let pid: pid_t
let bundleID: String?
var title: String // fallback: the application name
var spaceIDs: [UInt64] // from SpaceService; empty if unknown
var isOnCurrentSpace: Bool
var isMinimized: Bool
var isFullScreen: Bool
var firstSeen: Date // used for the stable order (decision D5)
}

View File

@@ -0,0 +1,99 @@
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()
}
}

View File

@@ -0,0 +1,152 @@
import AppKit
// OnboardingWindow explains the two permissions. Each row has a button that
// opens the correct System Settings pane. The window updates the status of
// each permission when the state changes. The Continue button is active only
// when Accessibility is granted. Screen Recording is optional (reduced mode).
@MainActor
final class OnboardingWindow: NSObject, NSWindowDelegate {
private let permissions: PermissionManager
var onContinue: (() -> Void)?
private var window: NSWindow?
private var accessibilityStatus: NSTextField?
private var screenStatus: NSTextField?
private var continueButton: NSButton?
init(permissions: PermissionManager) {
self.permissions = permissions
super.init()
}
func show() {
if window == nil {
build()
}
window?.center()
window?.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
}
func close() {
window?.orderOut(nil)
}
// update sets the status text of each permission.
// The function enables the Continue button if Accessibility is granted.
func update(state: PermissionState) {
accessibilityStatus?.stringValue = state.accessibility ? "Granted" : "Not granted"
accessibilityStatus?.textColor = state.accessibility ? .systemGreen : .systemRed
screenStatus?.stringValue = state.screenRecording ? "Granted" : "Not granted — reduced mode"
screenStatus?.textColor = state.screenRecording ? .systemGreen : .systemOrange
continueButton?.isEnabled = state.accessibility
}
private func build() {
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 480, height: 320),
styleMask: [.titled, .closable],
backing: .buffered,
defer: false)
window.title = "EPOD Window Bar — Permissions"
window.isReleasedWhenClosed = false
window.delegate = self
let title = label(text: "EPOD Window Bar needs two permissions.",
font: .boldSystemFont(ofSize: 15))
let accessibilityRow = permissionRow(
name: "Accessibility",
detail: "EPOD Window Bar reads, raises, and resizes windows.",
buttonTitle: "Open Accessibility Settings",
action: #selector(openAccessibility),
statusOut: &accessibilityStatus)
let screenRow = permissionRow(
name: "Screen Recording",
detail: "EPOD Window Bar reads window titles on other desktops.",
buttonTitle: "Open Screen Recording Settings",
action: #selector(openScreen),
statusOut: &screenStatus)
let continueButton = NSButton(title: "Continue",
target: self,
action: #selector(continueTapped))
continueButton.bezelStyle = .rounded
continueButton.keyEquivalent = "\r"
continueButton.isEnabled = false
self.continueButton = continueButton
let stack = NSStackView(views: [title, accessibilityRow, screenRow, continueButton])
stack.orientation = .vertical
stack.alignment = .leading
stack.spacing = 18
stack.edgeInsets = NSEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
stack.translatesAutoresizingMaskIntoConstraints = false
let content = NSView()
content.addSubview(stack)
NSLayoutConstraint.activate([
stack.topAnchor.constraint(equalTo: content.topAnchor),
stack.leadingAnchor.constraint(equalTo: content.leadingAnchor),
stack.trailingAnchor.constraint(equalTo: content.trailingAnchor),
stack.bottomAnchor.constraint(equalTo: content.bottomAnchor)
])
window.contentView = content
self.window = window
update(state: permissions.current)
}
// permissionRow builds one row: a name, a detail line, a status line, and
// a button that opens the correct settings pane.
private func permissionRow(name: String,
detail: String,
buttonTitle: String,
action: Selector,
statusOut: inout NSTextField?) -> NSView {
let nameLabel = label(text: name, font: .boldSystemFont(ofSize: 13))
let detailLabel = label(text: detail, font: .systemFont(ofSize: 12))
detailLabel.textColor = .secondaryLabelColor
let status = label(text: "—", font: .systemFont(ofSize: 12))
statusOut = status
let button = NSButton(title: buttonTitle, target: self, action: action)
button.bezelStyle = .rounded
let stack = NSStackView(views: [nameLabel, detailLabel, status, button])
stack.orientation = .vertical
stack.alignment = .leading
stack.spacing = 4
return stack
}
private func label(text: String, font: NSFont) -> NSTextField {
let field = NSTextField(labelWithString: text)
field.font = font
return field
}
@objc private func openAccessibility() {
permissions.openAccessibilitySettings()
}
@objc private func openScreen() {
permissions.requestScreenRecording()
permissions.openScreenRecordingSettings()
}
@objc private func continueTapped() {
onContinue?()
}
// windowShouldClose hides the window. The window stays in memory.
// The app opens the window again if a permission is revoked.
func windowShouldClose(_ sender: NSWindow) -> Bool {
window?.orderOut(nil)
return false
}
}

View File

@@ -0,0 +1,81 @@
import AppKit
import ApplicationServices
import CoreGraphics
// PermissionState holds the two permissions that EPOD Window Bar needs.
struct PermissionState: Equatable {
var accessibility: Bool
var screenRecording: Bool
// allGranted is true if both permissions are present.
var allGranted: Bool { accessibility && screenRecording }
// reducedMode is true if Accessibility is present but Screen Recording
// is not. In reduced mode the app shows only windows on the current Space.
var reducedMode: Bool { accessibility && !screenRecording }
}
// PermissionManager reads the permission state and polls for changes.
// The manager polls every 2 s. The poll catches a grant while the onboarding
// window is open. The poll also catches a revoke at runtime.
@MainActor
final class PermissionManager {
private(set) var current: PermissionState
var onChange: ((PermissionState) -> Void)?
private var timer: Timer?
init() {
current = PermissionManager.read(prompt: false)
}
func start() {
timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in
MainActor.assumeIsolated {
self?.refresh()
}
}
refresh()
}
// refresh reads the state again. The manager calls onChange only if the
// state changed.
func refresh() {
let new = PermissionManager.read(prompt: false)
if new != current {
current = new
Log.app.info("Permission state changed. ax=\(new.accessibility) sr=\(new.screenRecording)")
onChange?(new)
}
}
// requestScreenRecording asks macOS for Screen Recording.
// macOS shows the system prompt one time.
func requestScreenRecording() {
CGRequestScreenCaptureAccess()
}
func openAccessibilitySettings() {
open("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")
}
func openScreenRecordingSettings() {
open("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")
}
// read returns the current permission state.
// prompt shows the system Accessibility prompt if the value is true.
static func read(prompt: Bool) -> PermissionState {
let key = kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String
let options = [key: prompt] as CFDictionary
let ax = AXIsProcessTrustedWithOptions(options)
let sr = CGPreflightScreenCaptureAccess()
return PermissionState(accessibility: ax, screenRecording: sr)
}
private func open(_ value: String) {
guard let url = URL(string: value) else { return }
NSWorkspace.shared.open(url)
}
}

View File

@@ -0,0 +1,145 @@
import Foundation
import ApplicationServices
import CoreGraphics
// PrivateAPI loads all private symbols at runtime with dlsym. If a symbol is
// missing, the loader logs the problem and the feature is disabled. The app
// never crashes because of a missing private symbol (spec section 7.5).
//
// Signature sources:
// - _AXUIElementGetWindow: AltTab (PrivateApis.swift), yabai.
// - CGSMainConnectionID: common CGS use (yabai, Hammerspoon).
// - CGSCopyManagedDisplaySpaces: yabai, AltTab.
// - CGSCopySpacesForWindows: AltTab, yabai.
// - _AXUIElementCreateWithRemoteToken: AltTab.
//
// UNCERTAIN: The remote-token layout for _AXUIElementCreateWithRemoteToken is
// not documented. The layout below follows AltTab. The constraint and the
// cross-Space activation have a fallback if this call returns nil.
//
// PrivateAPI is nonisolated. The stored function pointers are immutable (let).
// The caller runs the AX wrappers on the serial AX queue (spec sections 7.4,
// 7.15). The CGS wrappers are also safe off the main thread.
final class PrivateAPI {
static let shared = PrivateAPI()
// Function pointer typealiases (C calling convention).
private typealias GetWindowFn =
@convention(c) (AXUIElement, UnsafeMutablePointer<CGWindowID>) -> AXError
private typealias MainConnFn =
@convention(c) () -> Int32
private typealias CopyManagedDisplaySpacesFn =
@convention(c) (Int32) -> Unmanaged<CFArray>?
private typealias CopySpacesForWindowsFn =
@convention(c) (Int32, Int32, CFArray) -> Unmanaged<CFArray>?
private typealias CreateWithRemoteTokenFn =
@convention(c) (CFData) -> Unmanaged<AXUIElement>?
private let getWindowFn: GetWindowFn?
private let mainConnFn: MainConnFn?
private let copyManagedDisplaySpacesFn: CopyManagedDisplaySpacesFn?
private let copySpacesForWindowsFn: CopySpacesForWindowsFn?
private let createWithRemoteTokenFn: CreateWithRemoteTokenFn?
// spacesAvailable is true if the Space symbols loaded.
let spacesAvailable: Bool
private init() {
// SkyLight holds the CGS symbols on current macOS. The AX symbols live
// in ApplicationServices (already loaded). RTLD_DEFAULT finds a symbol
// in any loaded image. The loader opens SkyLight as a fallback.
let skyLight = dlopen(
"/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight",
RTLD_NOW)
func load<T>(_ name: String, _ type: T.Type) -> T? {
// PRIVATE API
var pointer = dlsym(UnsafeMutableRawPointer(bitPattern: -2), name) // RTLD_DEFAULT
if pointer == nil, let skyLight = skyLight {
pointer = dlsym(skyLight, name)
}
guard let pointer = pointer else {
Log.privateAPI.error("Private symbol missing: \(name, privacy: .public)")
return nil
}
return unsafeBitCast(pointer, to: T.self)
}
getWindowFn = load("_AXUIElementGetWindow", GetWindowFn.self)
mainConnFn = load("CGSMainConnectionID", MainConnFn.self)
copyManagedDisplaySpacesFn = load("CGSCopyManagedDisplaySpaces", CopyManagedDisplaySpacesFn.self)
copySpacesForWindowsFn = load("CGSCopySpacesForWindows", CopySpacesForWindowsFn.self)
createWithRemoteTokenFn = load("_AXUIElementCreateWithRemoteToken", CreateWithRemoteTokenFn.self)
spacesAvailable = mainConnFn != nil && copySpacesForWindowsFn != nil
}
// windowID returns the CGWindowID of an AX window element.
// Fallback if missing: the caller matches by PID, frame, and title.
func windowID(for element: AXUIElement) -> CGWindowID? {
guard let getWindowFn = getWindowFn else { return nil }
var id: CGWindowID = 0
let error = getWindowFn(element, &id) // PRIVATE API
if error != .success { return nil }
return id
}
// mainConnectionID returns the CGS connection ID for this process.
func mainConnectionID() -> Int32? {
guard let mainConnFn = mainConnFn else { return nil }
return mainConnFn() // PRIVATE API
}
// managedDisplaySpaces returns the raw Space list per display. The caller
// parses the dictionaries. Fallback if missing: nil (treat all windows as
// current Space).
func managedDisplaySpaces() -> [[String: Any]]? {
guard let copyFn = copyManagedDisplaySpacesFn, let cid = mainConnectionID() else {
return nil
}
guard let array = copyFn(cid)?.takeRetainedValue() as? [[String: Any]] else { // PRIVATE API
return nil
}
return array
}
// spaces returns the Space IDs for the given window IDs. The mask 7 selects
// all Space types. Fallback if missing: nil.
func spaces(forWindows windowIDs: [CGWindowID]) -> [UInt64]? {
guard let copyFn = copySpacesForWindowsFn, let cid = mainConnectionID() else {
return nil
}
let numbers = windowIDs.map { NSNumber(value: $0) } as CFArray
let mask: Int32 = 7 // kCGSAllSpacesMask (all Space types)
guard let result = copyFn(cid, mask, numbers)?.takeRetainedValue() as? [NSNumber] else { // PRIVATE API
return nil
}
return result.map { $0.uint64Value }
}
// remoteElement returns an AX element for a window on another Space. The
// function builds the remote token from the PID and the window ID. The
// layout follows AltTab. Fallback if missing or nil: activate the
// application only (spec section 7.6, Method B).
func remoteElement(pid: pid_t, windowID: CGWindowID) -> AXUIElement? {
guard let createFn = createWithRemoteTokenFn else { return nil }
// UNCERTAIN LAYOUT (source: AltTab). The token is 20 bytes:
// - bytes 0..<4: pid (little endian Int32)
// - bytes 4..<8: 0
// - bytes 8..<12: magic 'coco' (0x636f636f)
// - bytes 12..<20: window ID (UInt64 little endian)
var token = Data(count: 20)
token.withUnsafeMutableBytes { raw in
let base = raw.baseAddress!
base.storeBytes(of: Int32(pid).littleEndian, toByteOffset: 0, as: Int32.self)
base.storeBytes(of: Int32(0).littleEndian, toByteOffset: 4, as: Int32.self)
base.storeBytes(of: UInt32(0x636f636f).littleEndian, toByteOffset: 8, as: UInt32.self)
base.storeBytes(of: UInt64(windowID).littleEndian, toByteOffset: 12, as: UInt64.self)
}
guard let element = createFn(token as CFData)?.takeRetainedValue() else { // PRIVATE API
return nil
}
return element
}
}

View File

@@ -0,0 +1,68 @@
import Foundation
import CoreGraphics
// SpaceService reports the Space (desktop) of each window. The service uses
// the private CGS API (PrivateAPI). If the private API is missing, the service
// reports no Spaces. The caller then treats all windows as the current Space
// (spec section 7.5). The service is main-actor isolated.
@MainActor
final class SpaceService {
private let api: PrivateAPI
init(api: PrivateAPI? = nil) {
self.api = api ?? .shared
}
// isAvailable is true if the Space API loaded.
var isAvailable: Bool {
return api.spacesAvailable
}
// spaces returns a map from window ID to its Space IDs. If the API is
// missing, the function returns an empty map.
func spaces(for windowIDs: [CGWindowID]) -> [CGWindowID: [UInt64]] {
guard isAvailable, windowIDs.isEmpty == false else { return [:] }
var result: [CGWindowID: [UInt64]] = [:]
// CGSCopySpacesForWindows returns the union of Spaces for the whole
// list. The service queries one window at a time to map each window to
// its own Space IDs.
for id in windowIDs {
if let spaces = api.spaces(forWindows: [id]) {
result[id] = spaces
}
}
return result
}
// currentSpaceIDs returns the current Space ID of each display. The service
// reads the managed display Space list. If the API is missing, the function
// returns an empty array.
func currentSpaceIDs() -> [UInt64] {
guard let displays = api.managedDisplaySpaces() else { return [] }
var ids: [UInt64] = []
for display in displays {
// Each display dictionary has a "Current Space" dictionary with the
// key "ManagedSpaceID" (UInt64). Source: yabai, AltTab.
if let current = display["Current Space"] as? [String: Any],
let id = current["ManagedSpaceID"] as? UInt64 {
ids.append(id)
} else if let current = display["Current Space"] as? [String: Any],
let number = current["ManagedSpaceID"] as? NSNumber {
ids.append(number.uint64Value)
}
}
return ids
}
// isOnCurrentSpace returns true if any Space ID of the window is a current
// Space ID. If the service has no data, the function returns true. The app
// then treats the window as a window on the current Space.
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
}
}

View File

@@ -0,0 +1,67 @@
import Foundation
import Observation
// Settings holds the user settings. The settings use UserDefaults. The keys
// have the prefix "ws." (spec section 7.13). The type is main-actor isolated
// and publishes changes with the Observation framework.
@MainActor
@Observable
final class Settings {
static let shared = Settings()
private enum Key {
static let paused = "ws.paused"
static let constrainWindows = "ws.constrainWindows"
static let excludedBundleIDs = "ws.excludedBundleIDs"
static let stripHeight = "ws.stripHeight"
}
@ObservationIgnored
private let defaults: UserDefaults
var paused: Bool {
didSet { defaults.set(paused, forKey: Key.paused) }
}
var constrainWindows: Bool {
didSet { defaults.set(constrainWindows, forKey: Key.constrainWindows) }
}
var excludedBundleIDs: [String] {
didSet { defaults.set(excludedBundleIDs, forKey: Key.excludedBundleIDs) }
}
var stripHeight: Double {
didSet { defaults.set(stripHeight, forKey: Key.stripHeight) }
}
init(defaults: UserDefaults = .standard) {
self.defaults = defaults
defaults.register(defaults: [
Key.paused: false,
Key.constrainWindows: true,
Key.excludedBundleIDs: [String](),
Key.stripHeight: 30.0
])
paused = defaults.bool(forKey: Key.paused)
constrainWindows = defaults.bool(forKey: Key.constrainWindows)
excludedBundleIDs = defaults.stringArray(forKey: Key.excludedBundleIDs) ?? []
stripHeight = defaults.double(forKey: Key.stripHeight)
}
// isExcluded returns true if the application is on the excluded list.
func isExcluded(_ bundleID: String?) -> Bool {
guard let bundleID = bundleID else { return false }
return excludedBundleIDs.contains(bundleID)
}
func addExcluded(_ bundleID: String) {
guard excludedBundleIDs.contains(bundleID) == false else { return }
excludedBundleIDs.append(bundleID)
}
func removeExcluded(_ bundleID: String) {
excludedBundleIDs.removeAll { $0 == bundleID }
}
}

View File

@@ -0,0 +1,134 @@
import AppKit
import SwiftUI
// SettingsWindow shows the settings of EPOD Window Bar. In v1 the window shows
// the excluded applications list (spec section 7.13). The user adds an
// application from the running applications. The user removes an application
// from the list. EPOD Window Bar does not resize the windows of an excluded
// application.
@MainActor
final class SettingsWindow: NSObject, NSWindowDelegate {
private let settings: Settings
private var window: NSWindow?
init(settings: Settings) {
self.settings = settings
super.init()
}
func show() {
if window == nil {
build()
}
window?.center()
window?.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
}
private func build() {
let root = ExcludedAppsView(settings: settings)
let hosting = NSHostingView(rootView: root)
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 440, height: 380),
styleMask: [.titled, .closable],
backing: .buffered,
defer: false)
window.title = "EPOD Window Bar — Settings"
window.isReleasedWhenClosed = false
window.contentView = hosting
window.delegate = self
self.window = window
}
// windowShouldClose hides the window. The window stays in memory.
func windowShouldClose(_ sender: NSWindow) -> Bool {
window?.orderOut(nil)
return false
}
}
// AppEntry is one running application in the Add menu.
private struct AppEntry: Identifiable {
let name: String
let bundleID: String
var id: String { bundleID }
}
// ExcludedAppsView is the SwiftUI content of the settings window.
private struct ExcludedAppsView: View {
@Bindable var settings: Settings
@State private var selection: String?
var body: some View {
VStack(alignment: .leading, spacing: 10) {
Text("Excluded applications")
.font(.headline)
Text("EPOD Window Bar does not resize the windows of an excluded application.")
.font(.caption)
.foregroundStyle(.secondary)
List(selection: $selection) {
ForEach(settings.excludedBundleIDs, id: \.self) { bundleID in
Text(displayName(for: bundleID))
.tag(bundleID)
}
}
.frame(minHeight: 220)
HStack {
Menu("Add") {
let apps = runningApps()
if apps.isEmpty {
Text("No application is available.")
} else {
ForEach(apps) { app in
Button(app.name) {
settings.addExcluded(app.bundleID)
}
}
}
}
.frame(width: 90)
Button("Remove") {
if let selection = selection {
settings.removeExcluded(selection)
self.selection = nil
}
}
.disabled(selection == nil)
Spacer()
}
}
.padding()
}
// runningApps returns the regular running applications that are not on the
// excluded list. The function sorts the applications by name.
private func runningApps() -> [AppEntry] {
var seen = Set<String>()
var result: [AppEntry] = []
for app in NSWorkspace.shared.runningApplications {
guard app.activationPolicy == .regular else { continue }
guard let bundleID = app.bundleIdentifier else { continue }
guard settings.excludedBundleIDs.contains(bundleID) == false else { continue }
guard seen.contains(bundleID) == false else { continue }
seen.insert(bundleID)
result.append(AppEntry(name: app.localizedName ?? bundleID, bundleID: bundleID))
}
return result.sorted { $0.name.lowercased() < $1.name.lowercased() }
}
// displayName returns the application name for a bundle ID. The function
// falls back to the bundle ID if no running application has this ID.
private func displayName(for bundleID: String) -> String {
for app in NSWorkspace.shared.runningApplications
where app.bundleIdentifier == bundleID {
return app.localizedName ?? bundleID
}
return bundleID
}
}

View File

@@ -0,0 +1,116 @@
import AppKit
import SwiftUI
// StripViewModel holds the state for the tab bar view. The view model is
// observable. The strip controller sets the active window and the action
// closures. The view reads the window store through the view model.
@MainActor
@Observable
final class StripViewModel {
let store: WindowStore
var activeWindowID: CGWindowID?
var availableWidth: CGFloat = 800
@ObservationIgnored var onActivate: ((CGWindowID) -> Void)?
@ObservationIgnored var onMinimize: ((CGWindowID) -> Void)?
@ObservationIgnored var onClose: ((CGWindowID) -> Void)?
init(store: WindowStore) {
self.store = store
}
// appIcon returns the icon of the frontmost application.
func appIcon() -> NSImage? {
guard let pid = store.frontmostPID,
let app = NSRunningApplication(processIdentifier: pid) else { return nil }
return app.icon
}
// appName returns the name of the frontmost application.
func appName() -> String {
guard let pid = store.frontmostPID,
let app = NSRunningApplication(processIdentifier: pid) else { return "" }
return app.localizedName ?? ""
}
}
// StripController owns the strip panel and the tab bar view. The controller
// positions the strip and shows or hides the strip. The controller forwards
// the tab actions through the closures. See spec sections 7.7, 7.8, 7.9.
// The controller does not read AX and does not detect full screen. The
// integration layer calls setVisible for the full-screen case (decision D7).
@MainActor
final class StripController {
private let panel: StripPanel
private let model: StripViewModel
private let settings: Settings
private let hostingView: NSHostingView<TabBarView>
var onActivate: ((CGWindowID) -> Void)? {
get { model.onActivate }
set { model.onActivate = newValue }
}
var onMinimize: ((CGWindowID) -> Void)? {
get { model.onMinimize }
set { model.onMinimize = newValue }
}
var onClose: ((CGWindowID) -> Void)? {
get { model.onClose }
set { model.onClose = newValue }
}
// activeWindowID is the focused window of the frontmost application. The
// integration layer sets this value. The tab bar marks this tab as active.
var activeWindowID: CGWindowID? {
get { model.activeWindowID }
set { model.activeWindowID = newValue }
}
// stripFrame is the current frame of the strip panel. The constraint
// service reads this frame for the limit line (spec section 7.10).
var stripFrame: CGRect {
return panel.frame
}
init(store: WindowStore, settings: Settings) {
self.settings = settings
self.model = StripViewModel(store: store)
let screen = StripPositioner.dockScreen(NSScreen.screens, main: NSScreen.main) ?? NSScreen.main
let frame = screen.map { StripPositioner.stripFrame(for: $0, height: CGFloat(settings.stripHeight)) }
?? NSRect(x: 0, y: 0, width: 800, height: CGFloat(settings.stripHeight))
panel = StripPanel(contentRect: frame)
hostingView = NSHostingView(rootView: TabBarView(model: model))
hostingView.frame = NSRect(origin: .zero, size: frame.size)
hostingView.autoresizingMask = [.width, .height]
panel.contentView?.addSubview(hostingView)
model.availableWidth = frame.width
}
func start() {
reposition()
setVisible(true)
}
// reposition recomputes the strip frame. The integration layer calls this
// function on a screen change, a Dock change, and after wake from sleep.
func reposition() {
guard let screen = StripPositioner.dockScreen(NSScreen.screens, main: NSScreen.main) else { return }
let frame = StripPositioner.stripFrame(for: screen, height: CGFloat(settings.stripHeight))
panel.setFrame(frame, display: true)
model.availableWidth = frame.width
Log.strip.debug("Strip repositioned to \(String(describing: frame), privacy: .public)")
}
// setVisible shows or hides the strip.
func setVisible(_ visible: Bool) {
if visible {
panel.orderFrontRegardless()
} else {
panel.orderOut(nil)
}
}
}

View File

@@ -0,0 +1,43 @@
import AppKit
// StripPanel is the always-visible strip above the Dock. The panel does not
// take focus from the frontmost application. See spec section 7.7.
final class StripPanel: NSPanel {
init(contentRect: NSRect) {
super.init(contentRect: contentRect,
styleMask: [.borderless, .nonactivatingPanel],
backing: .buffered,
defer: false)
becomesKeyOnlyIfNeeded = true
hasShadow = false
hidesOnDeactivate = false
isReleasedWhenClosed = false
isFloatingPanel = true
isOpaque = false
backgroundColor = .clear
// The strip joins all Spaces. The strip does not move. The strip does
// not take part in the window cycle.
collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]
// The strip is above normal windows but below the Dock. The Dock
// magnification can then cover the strip.
level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.dockWindow)) - 1)
// The background uses a visual effect view. The material is close to
// the Dock.
let effect = NSVisualEffectView(frame: NSRect(origin: .zero, size: contentRect.size))
effect.material = .hudWindow
effect.blendingMode = .behindWindow
effect.state = .active
effect.autoresizingMask = [.width, .height]
contentView = effect
}
// The panel must not become the key window. A click on the strip must not
// take focus from the frontmost application.
override var canBecomeKey: Bool { false }
override var canBecomeMain: Bool { false }
}

View File

@@ -0,0 +1,52 @@
import AppKit
// StripPositioner finds the Dock screen and computes the strip frame.
// See spec section 7.8. The core math takes plain values so a unit test can
// check the logic without a real screen.
enum StripPositioner {
// ScreenFrames holds the two frames of one screen.
struct ScreenFrames: Equatable {
let frame: CGRect
let visibleFrame: CGRect
}
// dockScreenIndex returns the index of the Dock screen. The Dock screen has
// a visibleFrame.minY above the frame.minY. macOS reserves this space for
// the Dock at the bottom. If no screen matches, the function returns the
// main index.
static func dockScreenIndex(screens: [ScreenFrames], mainIndex: Int) -> Int {
for (index, screen) in screens.enumerated() {
if screen.visibleFrame.minY > screen.frame.minY {
return index
}
}
return mainIndex
}
// stripFrame returns the strip frame for a visible frame and a height.
// The strip sits at the bottom of the visible frame, full width.
static func stripFrame(visibleFrame: CGRect, height: CGFloat) -> CGRect {
return CGRect(x: visibleFrame.minX,
y: visibleFrame.minY,
width: visibleFrame.width,
height: height)
}
// dockScreen returns the Dock NSScreen. The function uses the same rule as
// dockScreenIndex. If no screen matches, the function returns the main
// screen, or the first screen.
static func dockScreen(_ screens: [NSScreen], main: NSScreen?) -> NSScreen? {
for screen in screens {
if screen.visibleFrame.minY > screen.frame.minY {
return screen
}
}
return main ?? screens.first
}
// stripFrame returns the strip frame for an NSScreen and a height.
static func stripFrame(for screen: NSScreen, height: CGFloat) -> NSRect {
return stripFrame(visibleFrame: screen.visibleFrame, height: height)
}
}

View File

@@ -0,0 +1,143 @@
import SwiftUI
import AppKit
// TabBarView draws the tab bar. The view is a SwiftUI view. The strip hosts
// the view in an NSHostingView. The view observes the StripViewModel. See
// spec section 7.9. The view uses system colors only. The view supports light
// mode and dark mode.
struct TabBarView: View {
let model: StripViewModel
@State private var hoveredID: CGWindowID?
var body: some View {
let windows = model.store.frontmostWindows
let appIcon = model.appIcon()
let appName = model.appName()
HStack(spacing: 0) {
// The app icon is on the left of all tabs.
iconView(appIcon)
.frame(width: 26)
if windows.isEmpty {
// Empty state: the app name in muted text.
Text(appName)
.font(.system(size: 12))
.foregroundStyle(.secondary)
.padding(.leading, 4)
Spacer(minLength: 0)
} else {
tabRow(windows)
}
}
.padding(.horizontal, 4)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
@ViewBuilder
private func iconView(_ icon: NSImage?) -> some View {
if let icon = icon {
Image(nsImage: icon)
.resizable()
.frame(width: 16, height: 16)
} else {
Image(systemName: "app")
.frame(width: 16, height: 16)
}
}
@ViewBuilder
private func tabRow(_ windows: [WindowInfo]) -> some View {
let activeIndex = windows.firstIndex { $0.id == model.activeWindowID }
let layout = TabLayout.compute(availableWidth: model.availableWidth,
windowCount: windows.count,
activeIndex: activeIndex)
HStack(spacing: 3) {
ForEach(layout.visibleIndices, id: \.self) { index in
tabView(windows[index], width: layout.tabWidth)
}
if layout.showsOverflow {
overflowMenu(windows, indices: layout.overflowIndices)
}
Spacer(minLength: 0)
}
.padding(.leading, 4)
}
private func tabView(_ window: WindowInfo, width: CGFloat) -> some View {
let isActive = window.id == model.activeWindowID
let isHovered = window.id == hoveredID
return HStack(spacing: 3) {
if window.isOnCurrentSpace == false {
Image(systemName: "desktopcomputer")
.font(.system(size: 9))
.foregroundStyle(.secondary)
}
Text(window.title)
.font(.system(size: 11))
.italic(window.isMinimized)
.lineLimit(1)
.truncationMode(.middle)
.foregroundStyle(textStyle(active: isActive, minimized: window.isMinimized))
}
.padding(.horizontal, 6)
.frame(width: width, height: 22)
.background(background(active: isActive, hovered: isHovered))
.clipShape(RoundedRectangle(cornerRadius: 5))
.help(window.title)
.contentShape(Rectangle())
.onTapGesture {
model.onActivate?(window.id)
}
.onHover { inside in
hoveredID = inside ? window.id : (hoveredID == window.id ? nil : hoveredID)
}
.contextMenu {
Button("Minimize") { model.onMinimize?(window.id) }
Button("Close") { model.onClose?(window.id) }
}
}
private func overflowMenu(_ windows: [WindowInfo], indices: [Int]) -> some View {
Menu("+\(indices.count)") {
ForEach(indices, id: \.self) { index in
let window = windows[index]
Button(action: { model.onActivate?(window.id) }) {
Text(prefix(window) + window.title)
}
}
}
.menuStyle(.borderlessButton)
.frame(width: 36, height: 22)
.fixedSize()
}
// prefix returns a text marker for the overflow menu. The marker shows the
// state of the window.
private func prefix(_ window: WindowInfo) -> String {
if window.isMinimized { return "— " }
if window.isOnCurrentSpace == false { return "□ " }
return ""
}
private func textStyle(active: Bool, minimized: Bool) -> HierarchicalShapeStyle {
if active { return .primary }
if minimized { return .tertiary }
return .secondary
}
@ViewBuilder
private func background(active: Bool, hovered: Bool) -> some View {
if active {
Color.accentColor.opacity(0.25)
} else if hovered {
Color.primary.opacity(0.08)
} else {
Color.clear
}
}
}

View File

@@ -0,0 +1,127 @@
import CoreGraphics
// TabLayout is a pure layout function. The function has no AppKit dependency.
// The unit tests check this function. See spec section 7.9.
enum TabLayout {
// Constants holds the layout sizes. The default values come from the spec.
struct Constants: Equatable {
var maxTabWidth: CGFloat = 220
var minTabWidth: CGFloat = 90
var spacing: CGFloat = 3
var overflowButtonWidth: CGFloat = 36
var appIconArea: CGFloat = 26
init() {}
}
// Result holds the output of the layout.
struct Result: Equatable {
let visibleCount: Int
let tabWidth: CGFloat
let showsOverflow: Bool
let overflowCount: Int
let visibleIndices: [Int]
let overflowIndices: [Int]
}
// compute returns the layout for the tab bar.
// availableWidth is the full width of the strip.
// windowCount is the number of windows.
// activeIndex is the index of the active window, or nil.
static func compute(availableWidth: CGFloat,
windowCount: Int,
activeIndex: Int?,
constants: Constants = Constants()) -> Result {
if windowCount <= 0 {
return Result(visibleCount: 0, tabWidth: 0, showsOverflow: false,
overflowCount: 0, visibleIndices: [], overflowIndices: [])
}
// The app icon area is on the left of all tabs. The tabs use the rest.
let tabsWidth = max(0, availableWidth - constants.appIconArea)
// fits returns true if n tabs fit at the minimum width. overflow adds
// the +N button width.
func fits(_ n: Int, overflow: Bool) -> Bool {
guard n > 0 else { return overflow ? constants.overflowButtonWidth <= tabsWidth : true }
var need = CGFloat(n) * constants.minTabWidth + CGFloat(n - 1) * constants.spacing
if overflow {
need += constants.overflowButtonWidth + constants.spacing
}
return need <= tabsWidth
}
var showsOverflow = false
var visibleCount = windowCount
if fits(windowCount, overflow: false) {
visibleCount = windowCount
showsOverflow = false
} else {
// The tabs do not all fit. Show as many as fit plus the +N button.
showsOverflow = true
var n = windowCount - 1
while n > 0 && fits(n, overflow: true) == false {
n -= 1
}
visibleCount = max(0, n)
}
// All visible tabs have the same width. The width fills the free space.
// The width stays inside the minimum and the maximum.
let tabWidth: CGFloat
if visibleCount > 0 {
let reserved = showsOverflow ? (constants.overflowButtonWidth + constants.spacing) : 0
let spacingTotal = CGFloat(visibleCount - 1) * constants.spacing
let free = tabsWidth - reserved - spacingTotal
var width = free / CGFloat(visibleCount)
width = min(constants.maxTabWidth, max(constants.minTabWidth, width))
tabWidth = width
} else {
tabWidth = 0
}
let split = visibleIndices(windowCount: windowCount,
visibleCount: visibleCount,
activeIndex: activeIndex)
return Result(visibleCount: visibleCount,
tabWidth: tabWidth,
showsOverflow: showsOverflow,
overflowCount: windowCount - visibleCount,
visibleIndices: split.visible,
overflowIndices: split.overflow)
}
// visibleIndices returns the visible window indices and the overflow window
// indices. The function keeps the natural order. The active window must
// always be visible. If the active window is in the overflow, the function
// swaps the active window with the last visible tab (spec 7.9, decision D5
// keeps the order otherwise).
static func visibleIndices(windowCount: Int,
visibleCount: Int,
activeIndex: Int?) -> (visible: [Int], overflow: [Int]) {
guard windowCount > 0 else { return ([], []) }
guard visibleCount > 0 else {
return ([], Array(0..<windowCount))
}
guard visibleCount < windowCount else {
return (Array(0..<windowCount), [])
}
var visible = Array(0..<visibleCount)
var overflow = Array(visibleCount..<windowCount)
if let active = activeIndex, overflow.contains(active) {
let lastPos = visible.count - 1
let moved = visible[lastPos]
visible[lastPos] = active
if let activePos = overflow.firstIndex(of: active) {
overflow[activePos] = moved
}
overflow.sort()
}
return (visible, overflow)
}
}

View 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)
}
}
}

View 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)
}
}

View 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] ?? []
}
}

View 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
}
}

View File

@@ -0,0 +1,36 @@
import CoreGraphics
// Geometry converts between two coordinate systems.
//
// Cocoa (AppKit) uses a bottom-left origin on the primary screen. The Y axis
// points up. NSScreen.frame uses this system.
//
// Accessibility (AX) and CGWindowList use a top-left origin on the primary
// screen. The Y axis points down.
//
// The primary screen is NSScreen.screens[0]. Its height is the pivot for the
// conversion. All functions are pure. The unit tests cover a primary screen
// and a second screen above, below, and left of the primary screen.
enum Geometry {
// cocoaToAX converts a rect with a Cocoa origin to a rect with an AX origin.
// primaryHeight is the height of the primary screen.
static func cocoaToAX(_ rect: CGRect, primaryHeight: CGFloat) -> CGRect {
let y = primaryHeight - rect.maxY
return CGRect(x: rect.minX, y: y, width: rect.width, height: rect.height)
}
// axToCocoa converts a rect with an AX origin to a rect with a Cocoa origin.
// The conversion is symmetric to cocoaToAX.
static func axToCocoa(_ rect: CGRect, primaryHeight: CGFloat) -> CGRect {
let y = primaryHeight - (rect.origin.y + rect.height)
return CGRect(x: rect.minX, y: y, width: rect.width, height: rect.height)
}
// cocoaYToAXTop returns the AX top-left Y for a Cocoa rect top edge.
// The Cocoa top edge is rect.maxY. The AX value is the distance from the
// primary screen top.
static func cocoaYToAXTop(_ cocoaMaxY: CGFloat, primaryHeight: CGFloat) -> CGFloat {
return primaryHeight - cocoaMaxY
}
}

15
Sources/Util/Log.swift Normal file
View File

@@ -0,0 +1,15 @@
import os
// Log holds the os.Logger instances for EPOD Window Bar.
// The subsystem is com.epod.windowbar. The spec (section 7.14) defines the
// categories. Phase 0 uses the "app" category only. Later phases add more.
enum Log {
static let subsystem = "com.epod.windowbar"
static let app = Logger(subsystem: subsystem, category: "app")
static let tracking = Logger(subsystem: subsystem, category: "tracking")
static let privateAPI = Logger(subsystem: subsystem, category: "private")
static let activation = Logger(subsystem: subsystem, category: "activation")
static let constraint = Logger(subsystem: subsystem, category: "constraint")
static let strip = Logger(subsystem: subsystem, category: "strip")
}