From 70d7ca5efe8c441a4c4541ea57251595fa1ba4d5 Mon Sep 17 00:00:00 2001 From: Erhan Keseli Date: Sat, 21 Nov 2026 21:41:06 +0100 Subject: [PATCH] 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. --- .github/workflows/ci.yml | 40 ++ .gitignore | 23 + Config.xcconfig | 19 + LICENSE | 21 + Local.xcconfig.example | 13 + README.md | 139 ++++++ Sources/Actions/WindowActivator.swift | 138 ++++++ Sources/App/AppControl.swift | 17 + Sources/App/AppDelegate.swift | 254 ++++++++++ Sources/App/LaunchAtLogin.swift | 31 ++ Sources/App/MenuBarController.swift | 160 +++++++ Sources/App/main.swift | 14 + Sources/Constraint/ConstraintMath.swift | 25 + .../Constraint/WindowConstraintService.swift | 193 ++++++++ Sources/Model/WindowInfo.swift | 17 + Sources/Model/WindowStore.swift | 99 ++++ Sources/Permissions/OnboardingWindow.swift | 152 ++++++ Sources/Permissions/PermissionManager.swift | 81 ++++ Sources/Private/PrivateAPI.swift | 145 ++++++ Sources/Private/SpaceService.swift | 68 +++ Sources/Settings/Settings.swift | 67 +++ Sources/Settings/SettingsWindow.swift | 134 ++++++ Sources/Strip/StripController.swift | 116 +++++ Sources/Strip/StripPanel.swift | 43 ++ Sources/Strip/StripPositioner.swift | 52 ++ Sources/Strip/TabBarView.swift | 143 ++++++ Sources/Strip/TabLayout.swift | 127 +++++ Sources/Tracking/AppObserverRegistry.swift | 136 ++++++ Sources/Tracking/TrackingController.swift | 378 +++++++++++++++ Sources/Tracking/WindowEnumerator.swift | 325 +++++++++++++ Sources/Tracking/WorkspaceEvents.swift | 80 ++++ Sources/Util/Geometry.swift | 36 ++ Sources/Util/Log.swift | 15 + Tests/ConstraintMathTests.swift | 53 +++ Tests/GeometryTests.swift | 55 +++ Tests/TabLayoutTests.swift | 76 +++ Tests/WindowFilterTests.swift | 101 ++++ Tests/WindowOrderTests.swift | 81 ++++ docs/architecture.md | 96 ++++ docs/spec.md | 449 ++++++++++++++++++ project.yml | 63 +++ scripts/reset-permissions.sh | 14 + scripts/run.sh | 43 ++ 43 files changed, 4332 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Config.xcconfig create mode 100644 LICENSE create mode 100644 Local.xcconfig.example create mode 100644 README.md create mode 100644 Sources/Actions/WindowActivator.swift create mode 100644 Sources/App/AppControl.swift create mode 100644 Sources/App/AppDelegate.swift create mode 100644 Sources/App/LaunchAtLogin.swift create mode 100644 Sources/App/MenuBarController.swift create mode 100644 Sources/App/main.swift create mode 100644 Sources/Constraint/ConstraintMath.swift create mode 100644 Sources/Constraint/WindowConstraintService.swift create mode 100644 Sources/Model/WindowInfo.swift create mode 100644 Sources/Model/WindowStore.swift create mode 100644 Sources/Permissions/OnboardingWindow.swift create mode 100644 Sources/Permissions/PermissionManager.swift create mode 100644 Sources/Private/PrivateAPI.swift create mode 100644 Sources/Private/SpaceService.swift create mode 100644 Sources/Settings/Settings.swift create mode 100644 Sources/Settings/SettingsWindow.swift create mode 100644 Sources/Strip/StripController.swift create mode 100644 Sources/Strip/StripPanel.swift create mode 100644 Sources/Strip/StripPositioner.swift create mode 100644 Sources/Strip/TabBarView.swift create mode 100644 Sources/Strip/TabLayout.swift create mode 100644 Sources/Tracking/AppObserverRegistry.swift create mode 100644 Sources/Tracking/TrackingController.swift create mode 100644 Sources/Tracking/WindowEnumerator.swift create mode 100644 Sources/Tracking/WorkspaceEvents.swift create mode 100644 Sources/Util/Geometry.swift create mode 100644 Sources/Util/Log.swift create mode 100644 Tests/ConstraintMathTests.swift create mode 100644 Tests/GeometryTests.swift create mode 100644 Tests/TabLayoutTests.swift create mode 100644 Tests/WindowFilterTests.swift create mode 100644 Tests/WindowOrderTests.swift create mode 100644 docs/architecture.md create mode 100644 docs/spec.md create mode 100644 project.yml create mode 100755 scripts/reset-permissions.sh create mode 100755 scripts/run.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ed1236a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,40 @@ +# CI builds and tests EPOD Window Bar on macOS. +# The workflow uses ad-hoc signing only. The workflow needs no secrets and no +# Apple signing identity. XcodeGen generates the Xcode project first, because +# the project repository does not contain the .xcodeproj. +name: CI + +on: + push: + pull_request: + +jobs: + test: + name: Build and test (ad-hoc signing) + runs-on: macos-latest + + steps: + - name: Check out the repository + uses: actions/checkout@v4 + + - name: Print the tool versions + run: | + xcodebuild -version + swift --version + + - name: Install XcodeGen + run: brew install xcodegen + + - name: Generate the Xcode project + run: xcodegen generate + + - name: Run the tests + run: | + xcodebuild test \ + -project EPODWindowBar.xcodeproj \ + -scheme EPODWindowBar \ + -destination 'platform=macOS' \ + CODE_SIGNING_ALLOWED=NO \ + CODE_SIGNING_REQUIRED=NO \ + CODE_SIGN_IDENTITY="" \ + DEVELOPMENT_TEAM="" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d9ed6e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# Xcode +*.xcodeproj +xcuserdata/ +*.xcuserstate +DerivedData/ +build/ +*.xcarchive + +# XcodeGen generates the Info.plist. +Sources/App/Info.plist + +# Build output of the local scripts. +.build/ + +# macOS +.DS_Store + +# Debug output. +dump.txt +*.log + +# Local signing config. Config.xcconfig includes this file if it exists. +Local.xcconfig diff --git a/Config.xcconfig b/Config.xcconfig new file mode 100644 index 0000000..e7b8c7d --- /dev/null +++ b/Config.xcconfig @@ -0,0 +1,19 @@ +// Config.xcconfig +// This file holds the signing settings for EPOD Window Bar. +// +// The default is ad-hoc signing. The default build needs no Apple account. +// WARNING: ad-hoc signing changes the signature on each build. macOS stores +// the Accessibility permission and the Screen Recording permission per +// signature. So macOS resets both permissions after each build. +// +// To keep the permissions between builds, sign with a stable Apple Development +// certificate. Copy Local.xcconfig.example to Local.xcconfig and set +// DEVELOPMENT_TEAM. Local.xcconfig is in .gitignore. See README.md. + +CODE_SIGN_STYLE = Manual +CODE_SIGN_IDENTITY = - +DEVELOPMENT_TEAM = + +// The optional include brings in the local certificate settings if the file +// exists. The build works without Local.xcconfig (ad-hoc signing). +#include? "Local.xcconfig" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..986a797 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Erhan Keseli + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Local.xcconfig.example b/Local.xcconfig.example new file mode 100644 index 0000000..387263e --- /dev/null +++ b/Local.xcconfig.example @@ -0,0 +1,13 @@ +// Local.xcconfig.example +// Copy this file to Local.xcconfig and set your team ID. Local.xcconfig is in +// .gitignore, so the file stays on your machine. Config.xcconfig includes +// Local.xcconfig if the file exists. +// +// Find your team ID in the OU field of the Apple Development certificate. The +// value in parentheses in the CN field is the personal ID, not the team ID. +// Read the subject with: +// security find-certificate -c "Apple Development" -p | openssl x509 -noout -subject + +CODE_SIGN_STYLE = Automatic +CODE_SIGN_IDENTITY = Apple Development +DEVELOPMENT_TEAM = YOURTEAMID diff --git a/README.md b/README.md new file mode 100644 index 0000000..81ec1dd --- /dev/null +++ b/README.md @@ -0,0 +1,139 @@ +# EPOD Window Bar + +EPOD Window Bar is a macOS agent application. It shows a thin strip directly +above the Dock. The strip shows the windows of the frontmost application as +tabs. One click on a tab raises that window. + +macOS shows applications in the Dock. macOS does not show the individual +windows. When one application has many windows, it is slow to find the correct +window. EPOD Window Bar fills this gap. The strip shows every window of the +frontmost application, so one click reaches the correct window. + +The Dock does not change. EPOD Window Bar adds to the Dock. It does not replace +the Dock. + +## Requirements + +- macOS 14 (Sonoma) or later. +- Full Xcode. The build tool `xcodebuild` needs full Xcode. The Command Line + Tools alone are not enough. +- XcodeGen. Install it with `brew install xcodegen`. + +## Build from source + +There is no prebuilt release. You build the application from source. + +The repository does not contain the Xcode project. XcodeGen generates the +project from `project.yml` and the source folders. + +### 1. Signing + +The file `Config.xcconfig` holds the signing settings. The default is ad-hoc +signing. The default build needs no Apple account. + +> **Note.** With ad-hoc signing, macOS resets the Accessibility permission and +> the Screen Recording permission after each build. The signature changes on +> each build, and macOS stores the permissions per signature. + +To keep the permissions between builds, sign with a stable Apple Development +certificate: + +1. Copy the example file: `cp Local.xcconfig.example Local.xcconfig`. +2. Set your team ID in `Local.xcconfig`: + + ``` + DEVELOPMENT_TEAM = YOURTEAMID + CODE_SIGN_STYLE = Automatic + ``` + +3. Find your team ID in the `OU` field of the Apple Development certificate. + The value in parentheses in the `CN` field is the personal ID, not the team + ID. Read the subject with: + + ```sh + security find-certificate -c "Apple Development" -p | openssl x509 -noout -subject + ``` + + Read the `OU` field of the output. That value is the team ID. + +`Local.xcconfig` is in `.gitignore`. The file stays on your machine. + +### 2. Build and run + +```sh +./scripts/run.sh +``` + +The script generates the project, builds the application, copies it to +`~/Applications/EPOD Window Bar.app`, and starts it. Always run the application +from `~/Applications`. + +### 3. Run the tests + +```sh +xcodebuild test -scheme EPODWindowBar +``` + +## Permissions + +EPOD Window Bar needs two permissions. + +- **Accessibility.** The application reads, raises, minimizes, closes, and + resizes windows. +- **Screen Recording.** The application reads the window titles of windows on + other desktops through `CGWindowListCopyWindowInfo`. Without this permission, + the title of a window on another desktop is empty. + +The application works in a reduced mode without Screen Recording. In reduced +mode, the strip shows only the windows on the current desktop. The menu bar +item shows a warning icon. + +At the first start, the application shows an onboarding window. The window has +a button for each permission. Each button opens the correct System Settings +pane. + +## Recommended system setting + +Turn on this setting: **System Settings → Desktop & Dock → "When switching to +an application, switch to a Space with open windows for the application"**. + +With this setting on, a click on a tab of a window on another desktop switches +to that desktop and raises the window. + +## Known limits + +- The application uses private macOS APIs. A macOS update can change or remove + these functions. The application loads each symbol at runtime. If a symbol is + missing, the application disables the feature and does not crash. The private + symbols are: + - `_AXUIElementGetWindow` + - `CGSMainConnectionID` + - `CGSCopyManagedDisplaySpaces` + - `CGSCopySpacesForWindows` + - `_AXUIElementCreateWithRemoteToken` +- The strip does not show the native tabs inside one window. Examples are the + tabs of Finder, Terminal, Safari, and a web browser. +- The strip is on the Dock screen only. The application does not add a strip to + a second monitor. +- With Stage Manager on, the strip shows, but the application does not constrain + the windows. + +## Debugging + +The menu bar item has two debug actions. + +- **Copy window dump.** The action puts the window dump on the clipboard. You + read the dump without a log tool. +- **Dump windows to log.** The action writes the window dump to the log. + +Read the log with one of these commands: + +```sh +log stream --predicate 'subsystem == "com.epod.windowbar"' --level debug +log show --last 5m --predicate 'subsystem == "com.epod.windowbar"' --info +``` + +## Trademarks + +EPOD Window Bar is not affiliated with Apple Inc. "macOS", "Dock", "Finder", +"Terminal", "Safari", and "Xcode" are trademarks of Apple Inc. diff --git a/Sources/Actions/WindowActivator.swift b/Sources/Actions/WindowActivator.swift new file mode 100644 index 0000000..cb4792a --- /dev/null +++ b/Sources/Actions/WindowActivator.swift @@ -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) + } +} diff --git a/Sources/App/AppControl.swift b/Sources/App/AppControl.swift new file mode 100644 index 0000000..1275124 --- /dev/null +++ b/Sources/App/AppControl.swift @@ -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() +} diff --git a/Sources/App/AppDelegate.swift b/Sources/App/AppDelegate.swift new file mode 100644 index 0000000..3b16f95 --- /dev/null +++ b/Sources/App/AppDelegate.swift @@ -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() + } +} diff --git a/Sources/App/LaunchAtLogin.swift b/Sources/App/LaunchAtLogin.swift new file mode 100644 index 0000000..013bdf8 --- /dev/null +++ b/Sources/App/LaunchAtLogin.swift @@ -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)") + } + } +} diff --git a/Sources/App/MenuBarController.swift b/Sources/App/MenuBarController.swift new file mode 100644 index 0000000..2f86520 --- /dev/null +++ b/Sources/App/MenuBarController.swift @@ -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) + } +} diff --git a/Sources/App/main.swift b/Sources/App/main.swift new file mode 100644 index 0000000..7b5a482 --- /dev/null +++ b/Sources/App/main.swift @@ -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() +} diff --git a/Sources/Constraint/ConstraintMath.swift b/Sources/Constraint/ConstraintMath.swift new file mode 100644 index 0000000..86d41f2 --- /dev/null +++ b/Sources/Constraint/ConstraintMath.swift @@ -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) + } +} diff --git a/Sources/Constraint/WindowConstraintService.swift b/Sources/Constraint/WindowConstraintService.swift new file mode 100644 index 0000000..710f507 --- /dev/null +++ b/Sources/Constraint/WindowConstraintService.swift @@ -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 = [] + + 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") + } +} diff --git a/Sources/Model/WindowInfo.swift b/Sources/Model/WindowInfo.swift new file mode 100644 index 0000000..4325902 --- /dev/null +++ b/Sources/Model/WindowInfo.swift @@ -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) +} diff --git a/Sources/Model/WindowStore.swift b/Sources/Model/WindowStore.swift new file mode 100644 index 0000000..5a2bf7b --- /dev/null +++ b/Sources/Model/WindowStore.swift @@ -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() + } +} diff --git a/Sources/Permissions/OnboardingWindow.swift b/Sources/Permissions/OnboardingWindow.swift new file mode 100644 index 0000000..c305073 --- /dev/null +++ b/Sources/Permissions/OnboardingWindow.swift @@ -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 + } +} diff --git a/Sources/Permissions/PermissionManager.swift b/Sources/Permissions/PermissionManager.swift new file mode 100644 index 0000000..2db455a --- /dev/null +++ b/Sources/Permissions/PermissionManager.swift @@ -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) + } +} diff --git a/Sources/Private/PrivateAPI.swift b/Sources/Private/PrivateAPI.swift new file mode 100644 index 0000000..91d4cee --- /dev/null +++ b/Sources/Private/PrivateAPI.swift @@ -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) -> AXError + private typealias MainConnFn = + @convention(c) () -> Int32 + private typealias CopyManagedDisplaySpacesFn = + @convention(c) (Int32) -> Unmanaged? + private typealias CopySpacesForWindowsFn = + @convention(c) (Int32, Int32, CFArray) -> Unmanaged? + private typealias CreateWithRemoteTokenFn = + @convention(c) (CFData) -> Unmanaged? + + 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(_ 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 + } +} diff --git a/Sources/Private/SpaceService.swift b/Sources/Private/SpaceService.swift new file mode 100644 index 0000000..c704963 --- /dev/null +++ b/Sources/Private/SpaceService.swift @@ -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 + } +} diff --git a/Sources/Settings/Settings.swift b/Sources/Settings/Settings.swift new file mode 100644 index 0000000..fd8d049 --- /dev/null +++ b/Sources/Settings/Settings.swift @@ -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 } + } +} diff --git a/Sources/Settings/SettingsWindow.swift b/Sources/Settings/SettingsWindow.swift new file mode 100644 index 0000000..bf9b6df --- /dev/null +++ b/Sources/Settings/SettingsWindow.swift @@ -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() + 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 + } +} diff --git a/Sources/Strip/StripController.swift b/Sources/Strip/StripController.swift new file mode 100644 index 0000000..bf21f05 --- /dev/null +++ b/Sources/Strip/StripController.swift @@ -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 + + 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) + } + } +} diff --git a/Sources/Strip/StripPanel.swift b/Sources/Strip/StripPanel.swift new file mode 100644 index 0000000..5a006d5 --- /dev/null +++ b/Sources/Strip/StripPanel.swift @@ -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 } +} diff --git a/Sources/Strip/StripPositioner.swift b/Sources/Strip/StripPositioner.swift new file mode 100644 index 0000000..e35e278 --- /dev/null +++ b/Sources/Strip/StripPositioner.swift @@ -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) + } +} diff --git a/Sources/Strip/TabBarView.swift b/Sources/Strip/TabBarView.swift new file mode 100644 index 0000000..8d798ab --- /dev/null +++ b/Sources/Strip/TabBarView.swift @@ -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 + } + } +} diff --git a/Sources/Strip/TabLayout.swift b/Sources/Strip/TabLayout.swift new file mode 100644 index 0000000..51fa296 --- /dev/null +++ b/Sources/Strip/TabLayout.swift @@ -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.. 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.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) + } + } +} diff --git a/Sources/Tracking/TrackingController.swift b/Sources/Tracking/TrackingController.swift new file mode 100644 index 0000000..d55bcbf --- /dev/null +++ b/Sources/Tracking/TrackingController.swift @@ -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 = [] + + private var reconcileTimer: Timer? + private var lastFullScreen = false + private var running = false + + // onFrontmostFocusedFullScreenChanged reports the full-screen state of the + // focused window of the frontmost application (spec section 7.11). + var onFrontmostFocusedFullScreenChanged: ((Bool) -> Void)? + + // onWindowGeometryEvent forwards a move or a resize event. The controller + // resolves the CGWindowID on the serial AX queue (spec section 7.4). The + // constraint service uses this hook (spec section 7.10). + var onWindowGeometryEvent: ((pid_t, String, CGWindowID) -> Void)? + + // onFocusedWindowChanged reports the CGWindowID of the focused window of + // the frontmost application. The strip uses this ID for the active tab + // (spec section 7.9). The value is nil if no focused window exists. + var onFocusedWindowChanged: ((CGWindowID?) -> Void)? + + init(store: WindowStore, + cache: AXElementCache, + spaceService: SpaceService, + settings: Settings) { + self.store = store + self.cache = cache + self.spaceService = spaceService + self.settings = settings + } + + // start subscribes to the events and registers the observers. + func start() { + guard running == false else { return } + running = true + + workspace.onFrontmostChanged = { [weak self] pid in + self?.handleFrontmostChanged(pid) + } + workspace.onAppLaunched = { [weak self] app in + self?.registerObserver(for: app.processIdentifier) + } + workspace.onAppTerminated = { [weak self] pid in + self?.handleAppTerminated(pid) + } + workspace.onActiveSpaceChanged = { [weak self] in + self?.handleActiveSpaceChanged() + } + workspace.start() + + for app in regularApps() { + registerObserver(for: app.processIdentifier) + } + + if let frontmost = NSWorkspace.shared.frontmostApplication { + handleFrontmostChanged(frontmost.processIdentifier) + } + + reconcileTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { + self?.reconcile() + } + } + } + + // stop ends all tracking work. + func stop() { + running = false + reconcileTimer?.invalidate() + reconcileTimer = nil + observers.removeAll() + workspace.stop() + } + + // onAccessibilityLost stops all AX work. The app shows the onboarding + // window again (spec section 6.1). The controller does not crash. + func onAccessibilityLost() { + stop() + } + + // dumpWindowsToLog writes the window dump to the log at notice level. The + // notice level is persisted. "log show" reads it (spec section 7.14). + func dumpWindowsToLog() { + collectDump { lines in + for line in lines { + Log.tracking.notice("\(line, privacy: .public)") + } + } + } + + // dumpWindowsToPasteboard puts the window dump on the clipboard. The user + // reads the dump without a log tool. + func dumpWindowsToPasteboard() { + collectDump { lines in + let text = lines.joined(separator: "\n") + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(text, forType: .string) + Log.tracking.notice("Window dump copied to the clipboard. \(lines.count, privacy: .public) lines.") + } + } + + // collectDump enumerates every regular application and builds the dump + // text. The enumeration runs on the serial AX queue. The completion runs on + // the main actor with the lines in application order. Every field is a + // plain string, so no field is redacted (spec section 7.14). + private func collectDump(completion: @escaping ([String]) -> Void) { + let apps = regularApps() + let enumerator = self.enumerator + let ownPID = self.ownPID + let group = DispatchGroup() + var sections: [Int: [String]] = [:] + + for (index, app) in apps.enumerated() { + let pid = app.processIdentifier + let bundleID = app.bundleIdentifier + let appName = app.localizedName ?? "" + group.enter() + serialQueue.async { [weak self] in + let ax = enumerator.readAXWindows(pid: pid) + let cg = enumerator.readCGWindows(pid: pid) + let axWindowIDs = ax.map { PrivateAPI.shared.windowID(for: $0.element) } + DispatchQueue.main.async { + defer { group.leave() } + guard let self = self else { return } + let ids = Self.allIDs(axWindowIDs: axWindowIDs, cg: cg) + let spaceMap = self.spaceService.spaces(for: ids) + let currentSpaces = self.spaceService.currentSpaceIDs() + let result = enumerator.buildWindows(pid: pid, + bundleID: bundleID, + appName: appName, + ax: ax, + axWindowIDs: axWindowIDs, + cg: cg, + spaceIDsByWindow: spaceMap, + currentSpaceIDs: currentSpaces, + ownPID: ownPID, + screenBoundsCG: Self.screenBoundsCG()) + var lines: [String] = [] + lines.append("DUMP app pid=\(pid) bundle=\(bundleID ?? "nil") name=\(appName)") + for r in result.debug { + let b = r.bounds + let boundsText = "(\(b.origin.x), \(b.origin.y), \(b.width), \(b.height))" + lines.append("DUMP id=\(r.windowID) title=\(r.title) subrole=\(r.subrole ?? "nil") layer=\(r.layer) bounds=\(boundsText) spaces=\(r.spaceIDs) min=\(r.isMinimized) full=\(r.isFullScreen) shown=\(r.shown) reason=\(r.reason)") + } + sections[index] = lines + } + } + } + + group.notify(queue: .main) { + var all: [String] = [] + for index in 0..= 0.05 { + performRefreshNow(pid) + } else if refreshScheduled.contains(pid) == false { + refreshScheduled.insert(pid) + let delay = 0.05 - elapsed + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in + guard let self = self else { return } + self.refreshScheduled.remove(pid) + self.performRefreshNow(pid) + } + } + } + + private func performRefreshNow(_ pid: pid_t) { + lastRefreshAt[pid] = Date() + let enumerator = self.enumerator + serialQueue.async { [weak self] in + let ax = enumerator.readAXWindows(pid: pid) + let cg = enumerator.readCGWindows(pid: pid) + // Map each AX element to a CGWindowID on the serial AX queue + // (spec sections 7.4, 7.15). + let axWindowIDs = ax.map { PrivateAPI.shared.windowID(for: $0.element) } + DispatchQueue.main.async { + guard let self = self else { return } + self.applyEnumeration(pid: pid, ax: ax, cg: cg, axWindowIDs: axWindowIDs) + } + } + } + + private func applyEnumeration(pid: pid_t, + ax: [WindowEnumerator.AXRawWindow], + cg: [WindowEnumerator.CGRawWindow], + axWindowIDs: [CGWindowID?]) { + let app = NSRunningApplication(processIdentifier: pid) + let bundleID = app?.bundleIdentifier + let appName = app?.localizedName ?? "" + + let ids = Self.allIDs(axWindowIDs: axWindowIDs, cg: cg) + let spaceMap = spaceService.spaces(for: ids) + let currentSpaces = spaceService.currentSpaceIDs() + + let result = enumerator.buildWindows(pid: pid, + bundleID: bundleID, + appName: appName, + ax: ax, + axWindowIDs: axWindowIDs, + cg: cg, + spaceIDsByWindow: spaceMap, + currentSpaceIDs: currentSpaces, + ownPID: ownPID, + screenBoundsCG: Self.screenBoundsCG()) + + store.replaceWindows(result.windows, for: pid) + for (id, element) in result.elements { + cache.set(element, for: id) + } + observers.setWindowElements(pid: pid, windows: ax.map { $0.element }) + } + + // checkFullScreen reads the full-screen state of the focused window. The + // controller reports a change (spec section 7.11). + private func checkFullScreen(_ pid: pid_t) { + guard pid == store.frontmostPID else { return } + let enumerator = self.enumerator + serialQueue.async { [weak self] in + let isFullScreen = enumerator.readFocusedFullScreen(pid: pid) + DispatchQueue.main.async { + guard let self = self else { return } + if isFullScreen != self.lastFullScreen { + self.lastFullScreen = isFullScreen + self.onFrontmostFocusedFullScreenChanged?(isFullScreen) + } + } + } + } + + // checkFocusedWindow reads the focused window of the frontmost application. + // The controller resolves the CGWindowID on the main actor. The controller + // reports the ID for the active tab (spec section 7.9). + private func checkFocusedWindow(_ pid: pid_t) { + guard pid == store.frontmostPID else { return } + let enumerator = self.enumerator + serialQueue.async { [weak self] in + let element = enumerator.readFocusedWindowElement(pid: pid) + // Map the focused element to a CGWindowID on the serial AX queue. + let id = element.flatMap { PrivateAPI.shared.windowID(for: $0) } + DispatchQueue.main.async { + guard let self = self else { return } + guard pid == self.store.frontmostPID else { return } + self.onFocusedWindowChanged?(id) + } + } + } + + // MARK: - Helpers + + private func regularApps() -> [NSRunningApplication] { + return NSWorkspace.shared.runningApplications.filter { $0.activationPolicy == .regular } + } + + // screenBoundsCG returns the union of all screens in CG coordinates (the + // top-left origin of the primary screen). The filter uses this rect to hide + // a window that lies entirely off-screen. + private static func screenBoundsCG() -> CGRect { + let screens = NSScreen.screens + guard let primary = screens.first else { return .null } + let primaryHeight = primary.frame.height + var union = CGRect.null + for screen in screens { + union = union.union(Geometry.cocoaToAX(screen.frame, primaryHeight: primaryHeight)) + } + return union + } + + private static func allIDs(axWindowIDs: [CGWindowID?], + cg: [WindowEnumerator.CGRawWindow]) -> [CGWindowID] { + var set = Set() + for id in axWindowIDs { + if let id = id, id != 0 { set.insert(id) } + } + for window in cg where window.windowID != 0 { + set.insert(window.windowID) + } + return Array(set) + } +} diff --git a/Sources/Tracking/WindowEnumerator.swift b/Sources/Tracking/WindowEnumerator.swift new file mode 100644 index 0000000..e383f8c --- /dev/null +++ b/Sources/Tracking/WindowEnumerator.swift @@ -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() + 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] ?? [] + } +} diff --git a/Sources/Tracking/WorkspaceEvents.swift b/Sources/Tracking/WorkspaceEvents.swift new file mode 100644 index 0000000..370681e --- /dev/null +++ b/Sources/Tracking/WorkspaceEvents.swift @@ -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 + } +} diff --git a/Sources/Util/Geometry.swift b/Sources/Util/Geometry.swift new file mode 100644 index 0000000..553537d --- /dev/null +++ b/Sources/Util/Geometry.swift @@ -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 + } +} diff --git a/Sources/Util/Log.swift b/Sources/Util/Log.swift new file mode 100644 index 0000000..a317233 --- /dev/null +++ b/Sources/Util/Log.swift @@ -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") +} diff --git a/Tests/ConstraintMathTests.swift b/Tests/ConstraintMathTests.swift new file mode 100644 index 0000000..8c3e4ce --- /dev/null +++ b/Tests/ConstraintMathTests.swift @@ -0,0 +1,53 @@ +import XCTest +import CoreGraphics +@testable import EPODWindowBar + +// ConstraintMathTests checks the pure constraint math (spec 7.10). +// All rects use Cocoa coordinates. The origin is bottom-left. The Y axis +// points up. limitY is the strip top edge. +final class ConstraintMathTests: XCTestCase { + + // A window fully above the limit needs no change. + func testWindowAboveLimitReturnsNil() { + let window = CGRect(x: 0, y: 200, width: 800, height: 400) + XCTAssertNil(ConstraintMath.newHeight(windowCocoa: window, limitY: 30)) + } + + // A window with the bottom below the limit gets a new height. The top stays + // fixed. The top is maxY = 20 + 600 = 620. The new height is 620 - 30 = 590. + func testWindowBottomBelowLimitReturnsNewHeight() { + let window = CGRect(x: 0, y: 20, width: 800, height: 600) + let height = ConstraintMath.newHeight(windowCocoa: window, limitY: 30) + XCTAssertEqual(height, 590, accuracy: 0.001) + } + + // The boundary case: the window bottom is exactly at the limit. No change. + func testWindowBottomExactlyAtLimitReturnsNil() { + let window = CGRect(x: 0, y: 30, width: 800, height: 400) + XCTAssertNil(ConstraintMath.newHeight(windowCocoa: window, limitY: 30)) + } + + // The user moved the window down on purpose. The top is also below + // (limitY - 100). The service skips the window. + func testIntentionalMoveDownIsTrue() { + // limitY = 30. limitY - 100 = -70. A top at -80 is below -70. + XCTAssertTrue(ConstraintMath.isIntentionalMoveDown(windowTopCocoa: -80, limitY: 30)) + } + + // A normal window with a high top is not an intentional move-down. + func testIntentionalMoveDownIsFalse() { + XCTAssertFalse(ConstraintMath.isIntentionalMoveDown(windowTopCocoa: 500, limitY: 30)) + } + + // A window on a second screen below the primary screen. The second screen + // has negative Cocoa Y. The strip is on that screen. limitY = -770. + // The window bottom (-900) is below the limit. The top is -300. + // The top is not below (limitY - 100 = -870), so the service corrects the + // window. The new height is top - limitY = -300 - (-770) = 470. + func testWindowOnSecondScreenGetsNewHeight() { + let window = CGRect(x: 0, y: -900, width: 800, height: 600) // top = -300 + XCTAssertFalse(ConstraintMath.isIntentionalMoveDown(windowTopCocoa: window.maxY, limitY: -770)) + let height = ConstraintMath.newHeight(windowCocoa: window, limitY: -770) + XCTAssertEqual(height, 470, accuracy: 0.001) + } +} diff --git a/Tests/GeometryTests.swift b/Tests/GeometryTests.swift new file mode 100644 index 0000000..205ac4a --- /dev/null +++ b/Tests/GeometryTests.swift @@ -0,0 +1,55 @@ +import XCTest +@testable import EPODWindowBar + +// GeometryTests checks the coordinate conversion between the Cocoa system and +// the AX system. The tests use a primary screen height of 1000. The tests +// cover the primary screen and a second screen above, below, and left of the +// primary screen (spec section 7.10). +final class GeometryTests: XCTestCase { + + private let primaryHeight: CGFloat = 1000 + + func testPrimaryScreenRect() { + // A window sits at the bottom-left of the primary screen. + let cocoa = CGRect(x: 0, y: 0, width: 100, height: 100) + let ax = Geometry.cocoaToAX(cocoa, primaryHeight: primaryHeight) + XCTAssertEqual(ax.origin.x, 0) + XCTAssertEqual(ax.origin.y, 900) // 1000 - 100 + XCTAssertEqual(ax.width, 100) + XCTAssertEqual(ax.height, 100) + } + + func testRoundTripPrimary() { + let cocoa = CGRect(x: 10, y: 20, width: 300, height: 200) + let ax = Geometry.cocoaToAX(cocoa, primaryHeight: primaryHeight) + let back = Geometry.axToCocoa(ax, primaryHeight: primaryHeight) + XCTAssertEqual(back, cocoa) + } + + func testScreenAbovePrimary() { + // A window above the primary top has a negative AX Y value. + let cocoa = CGRect(x: 0, y: 1000, width: 100, height: 100) + let ax = Geometry.cocoaToAX(cocoa, primaryHeight: primaryHeight) + XCTAssertEqual(ax.origin.y, -100) // 1000 - 1100 + } + + func testScreenBelowPrimary() { + // A window below the primary bottom has an AX Y value past the height. + let cocoa = CGRect(x: 0, y: -200, width: 100, height: 100) + let ax = Geometry.cocoaToAX(cocoa, primaryHeight: primaryHeight) + XCTAssertEqual(ax.origin.y, 1100) // 1000 - (-100) + } + + func testScreenLeftKeepsX() { + // A screen left of the primary has a negative X. The X value does not + // change in the conversion. + let cocoa = CGRect(x: -1440, y: 0, width: 100, height: 100) + let ax = Geometry.cocoaToAX(cocoa, primaryHeight: primaryHeight) + XCTAssertEqual(ax.origin.x, -1440) + } + + func testCocoaYToAXTop() { + let top = Geometry.cocoaYToAXTop(100, primaryHeight: primaryHeight) + XCTAssertEqual(top, 900) + } +} diff --git a/Tests/TabLayoutTests.swift b/Tests/TabLayoutTests.swift new file mode 100644 index 0000000..4c47f47 --- /dev/null +++ b/Tests/TabLayoutTests.swift @@ -0,0 +1,76 @@ +import XCTest +@testable import EPODWindowBar + +// TabLayoutTests check the pure layout function. See spec section 7.9. +final class TabLayoutTests: XCTestCase { + + // All tabs fit. There is no overflow. The tabs have equal width. + func testAllTabsFitNoOverflow() { + let result = TabLayout.compute(availableWidth: 1000, windowCount: 4, activeIndex: 0) + XCTAssertEqual(result.visibleCount, 4) + XCTAssertFalse(result.showsOverflow) + XCTAssertEqual(result.overflowCount, 0) + XCTAssertEqual(result.visibleIndices, [0, 1, 2, 3]) + XCTAssertTrue(result.overflowIndices.isEmpty) + } + + // The tab width is equal for all tabs and inside the bounds. + func testTabWidthInsideBounds() { + let result = TabLayout.compute(availableWidth: 1000, windowCount: 4, activeIndex: 0) + XCTAssertGreaterThanOrEqual(result.tabWidth, 90) + XCTAssertLessThanOrEqual(result.tabWidth, 220) + } + + // The tab width reaches the maximum when few tabs share a wide strip. + func testTabWidthReachesMaximum() { + let result = TabLayout.compute(availableWidth: 2000, windowCount: 2, activeIndex: 0) + XCTAssertEqual(result.tabWidth, 220, accuracy: 0.001) + } + + // Too many tabs do not fit. The +N button appears. + func testOverflowAppears() { + let result = TabLayout.compute(availableWidth: 500, windowCount: 15, activeIndex: 0) + XCTAssertTrue(result.showsOverflow) + XCTAssertGreaterThan(result.overflowCount, 0) + XCTAssertEqual(result.visibleCount + result.overflowCount, 15) + } + + // The visible tabs keep the minimum width in the overflow case. + func testOverflowTabsKeepMinimumWidth() { + let result = TabLayout.compute(availableWidth: 500, windowCount: 15, activeIndex: 0) + XCTAssertGreaterThanOrEqual(result.tabWidth, 90) + } + + // The active window is always visible. The active window is in the overflow + // range before the swap. The swap puts the active window into the last + // visible slot. + func testActiveWindowAlwaysVisible() { + let result = TabLayout.compute(availableWidth: 500, windowCount: 15, activeIndex: 14) + XCTAssertTrue(result.visibleIndices.contains(14)) + XCTAssertFalse(result.overflowIndices.contains(14)) + XCTAssertEqual(result.visibleIndices.last, 14) + } + + // The swap helper keeps the count correct. + func testSwapKeepsCounts() { + let split = TabLayout.visibleIndices(windowCount: 10, visibleCount: 3, activeIndex: 9) + XCTAssertEqual(split.visible.count, 3) + XCTAssertEqual(split.overflow.count, 7) + XCTAssertTrue(split.visible.contains(9)) + XCTAssertFalse(Set(split.visible).intersection(Set(split.overflow)).isEmpty == false) + } + + // Zero windows give an empty layout. + func testZeroWindows() { + let result = TabLayout.compute(availableWidth: 1000, windowCount: 0, activeIndex: nil) + XCTAssertEqual(result.visibleCount, 0) + XCTAssertFalse(result.showsOverflow) + XCTAssertTrue(result.visibleIndices.isEmpty) + } + + // A nil active index does not swap. The first tabs stay visible. + func testNilActiveIndexNoSwap() { + let split = TabLayout.visibleIndices(windowCount: 10, visibleCount: 3, activeIndex: nil) + XCTAssertEqual(split.visible, [0, 1, 2]) + } +} diff --git a/Tests/WindowFilterTests.swift b/Tests/WindowFilterTests.swift new file mode 100644 index 0000000..7cb73db --- /dev/null +++ b/Tests/WindowFilterTests.swift @@ -0,0 +1,101 @@ +import XCTest +import ApplicationServices +import CoreGraphics +@testable import EPODWindowBar + +// WindowFilterTests checks the window filter of WindowEnumerator.buildWindows +// (spec section 7.3). The test uses the Teams case from the dump: a real window +// shows, and a ghost placeholder with the application name as the title hides. +// A window on another Space with a distinct title also shows. +final class WindowFilterTests: XCTestCase { + + private let enumerator = WindowEnumerator() + private let pid: pid_t = 1234 + private let appName = "Microsoft Teams" + + private func axWindow(title: String) -> WindowEnumerator.AXRawWindow { + // The element is a placeholder. buildWindows does not read the element. + let element = AXUIElementCreateApplication(ProcessInfo.processInfo.processIdentifier) + return WindowEnumerator.AXRawWindow(element: element, + title: title, + isMinimized: false, + subrole: kAXStandardWindowSubrole as String, + isFullScreen: false) + } + + private func cgWindow(id: CGWindowID, title: String?, bounds: CGRect) -> WindowEnumerator.CGRawWindow { + return WindowEnumerator.CGRawWindow(windowID: id, title: title, layer: 0, bounds: bounds) + } + + private func shownIDs(ax: [WindowEnumerator.AXRawWindow], + axIDs: [CGWindowID?], + cg: [WindowEnumerator.CGRawWindow], + screenBoundsCG: CGRect = CGRect(x: 0, y: 0, width: 2560, height: 1440)) -> Set { + let result = enumerator.buildWindows(pid: pid, + bundleID: "com.microsoft.teams2", + appName: appName, + ax: ax, + axWindowIDs: axIDs, + cg: cg, + spaceIDsByWindow: [:], + currentSpaceIDs: [], + ownPID: 9999, + screenBoundsCG: screenBoundsCG, + now: Date()) + return Set(result.windows.map { $0.id }) + } + + func testShowsRealAXWindow() { + let real = axWindow(title: "Chat | Team") + let cg = [cgWindow(id: 7476, title: "Chat | Team", + bounds: CGRect(x: 215, y: 249, width: 1307, height: 865))] + let shown = shownIDs(ax: [real], axIDs: [7476], cg: cg) + XCTAssertTrue(shown.contains(7476)) + } + + func testHidesGhostWithAppNameTitle() { + // Ghost: no AX element, title equals the application name. + let cg = [cgWindow(id: 8274, title: "Microsoft Teams", + bounds: CGRect(x: 0, y: 0, width: 800, height: 600))] + let shown = shownIDs(ax: [], axIDs: [], cg: cg) + XCTAssertFalse(shown.contains(8274)) + } + + func testHidesEmptyTitleGhost() { + // No AX element, empty CG title. The title falls back to the app name. + let cg = [cgWindow(id: 7475, title: nil, + bounds: CGRect(x: 0, y: 0, width: 2560, height: 300))] + let shown = shownIDs(ax: [], axIDs: [], cg: cg) + XCTAssertFalse(shown.contains(7475)) + } + + func testShowsOtherSpaceWindowWithDistinctTitle() { + // No AX element, distinct title: a real window on another Space. + let cg = [cgWindow(id: 999, title: "Terminal — ~/project", + bounds: CGRect(x: 0, y: 0, width: 1268, height: 1319))] + let shown = shownIDs(ax: [], axIDs: [], cg: cg) + XCTAssertTrue(shown.contains(999)) + } + + func testHidesOffScreenLimboWindow() { + // The Eclipse limbo shell sits at y=10000, off every screen. + let cg = [cgWindow(id: 9231, title: "PartRenderingEngine's limbo", + bounds: CGRect(x: 0, y: 10000, width: 1600, height: 900))] + let shown = shownIDs(ax: [], axIDs: [], cg: cg) + XCTAssertFalse(shown.contains(9231)) + } + + func testKeepsMinimizedOffScreenWindow() { + // A minimized window keeps its tab, even with off-screen bounds. + let element = AXUIElementCreateApplication(ProcessInfo.processInfo.processIdentifier) + let ax = [WindowEnumerator.AXRawWindow(element: element, + title: "Minimized Chat", + isMinimized: true, + subrole: kAXStandardWindowSubrole as String, + isFullScreen: false)] + let cg = [cgWindow(id: 555, title: "Minimized Chat", + bounds: CGRect(x: 0, y: 10000, width: 1200, height: 800))] + let shown = shownIDs(ax: ax, axIDs: [555], cg: cg) + XCTAssertTrue(shown.contains(555)) + } +} diff --git a/Tests/WindowOrderTests.swift b/Tests/WindowOrderTests.swift new file mode 100644 index 0000000..6bc59d6 --- /dev/null +++ b/Tests/WindowOrderTests.swift @@ -0,0 +1,81 @@ +import XCTest +@testable import EPODWindowBar + +// WindowOrderTests checks the stable order of the WindowStore (decision D5). +// The store sorts windows by firstSeen. A known window keeps its firstSeen +// value on a refresh. A new window gets the firstSeen value "now". A window +// that closes and opens again gets a new firstSeen value. +@MainActor +final class WindowOrderTests: XCTestCase { + + private let pid: pid_t = 42 + + private func makeWindow(id: CGWindowID, title: String) -> WindowInfo { + return WindowInfo( + id: id, + pid: pid, + bundleID: "com.test.app", + title: title, + spaceIDs: [], + isOnCurrentSpace: true, + isMinimized: false, + isFullScreen: false, + firstSeen: Date(timeIntervalSince1970: 0)) + } + + func testEqualFirstSeenSortsByID() { + let store = WindowStore() + let t0 = Date(timeIntervalSince1970: 100) + store.replaceWindows([makeWindow(id: 2, title: "B"), + makeWindow(id: 1, title: "A")], + for: pid, now: t0) + let order = store.windows(for: pid).map { $0.id } + XCTAssertEqual(order, [1, 2]) + } + + func testNewWindowKeepsStableOrder() { + let store = WindowStore() + let t0 = Date(timeIntervalSince1970: 100) + store.replaceWindows([makeWindow(id: 1, title: "A"), + makeWindow(id: 2, title: "B")], + for: pid, now: t0) + + // A later refresh adds window 3. The order of 1 and 2 does not change. + let t1 = Date(timeIntervalSince1970: 200) + store.replaceWindows([makeWindow(id: 2, title: "B"), + makeWindow(id: 1, title: "A"), + makeWindow(id: 3, title: "C")], + for: pid, now: t1) + let order = store.windows(for: pid).map { $0.id } + XCTAssertEqual(order, [1, 2, 3]) + } + + func testReopenGetsNewFirstSeen() { + let store = WindowStore() + let t0 = Date(timeIntervalSince1970: 100) + store.replaceWindows([makeWindow(id: 1, title: "A"), + makeWindow(id: 2, title: "B")], + for: pid, now: t0) + + // Window 1 closes. + let t1 = Date(timeIntervalSince1970: 200) + store.replaceWindows([makeWindow(id: 2, title: "B")], for: pid, now: t1) + + // Window 1 opens again. Window 1 gets a new firstSeen value. Window 1 + // moves after window 2. + let t2 = Date(timeIntervalSince1970: 300) + store.replaceWindows([makeWindow(id: 2, title: "B"), + makeWindow(id: 1, title: "A")], + for: pid, now: t2) + let order = store.windows(for: pid).map { $0.id } + XCTAssertEqual(order, [2, 1]) + } + + func testFrontmostWindows() { + let store = WindowStore() + store.replaceWindows([makeWindow(id: 1, title: "A")], for: pid, + now: Date(timeIntervalSince1970: 100)) + store.setFrontmost(pid) + XCTAssertEqual(store.frontmostWindows.map { $0.id }, [1]) + } +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..4b6b930 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,96 @@ +# Architecture + +EPOD Window Bar is a macOS agent application. It shows a strip of window tabs +above the Dock. This document gives a short overview of the module groups and +the data flow. + +## Data flow + +The tracking group reads the windows and writes the `WindowStore`. The strip +observes the `WindowStore` and shows the tabs of the frontmost application. A +click on a tab calls the activation group. A window move or resize event drives +the constraint group. The `AppDelegate` creates every group and connects them. + +``` +WorkspaceEvents + AppObserverRegistry + │ (events) + ▼ +TrackingController ──► WindowEnumerator ──► WindowStore (@Observable) + │ │ + │ focused window / full screen │ observe + ▼ ▼ + StripController ◄──────────────────────── TabBarView + │ onActivate / onMinimize / onClose + ▼ + WindowActivator WindowConstraintService ◄── geometry events +``` + +## Module groups + +### App + +The `main.swift` file starts the application on the main actor. `AppDelegate` +creates every service and connects the closures between them. `AppDelegate` +implements `AppControl`, the interface that the menu and the settings window +use. `MenuBarController` owns the status item and the menu. `LaunchAtLogin` +wraps `SMAppService.mainApp`. + +### Permissions + +`PermissionManager` reads the Accessibility state and the Screen Recording +state. The manager polls every 2 s and reports a change. `OnboardingWindow` +explains each permission and opens the correct System Settings pane. + +### Model + +`WindowInfo` is the value type for one window. `WindowStore` holds the windows +per application and the frontmost PID. The store is `@MainActor` and +`@Observable`. `AXElementCache` holds the AX element for each window in a +separate cache. The value type does not hold the AX element. + +### Tracking + +`WindowEnumerator` reads the windows from the AX source and the CGWindowList +source and merges them. The enumerator applies the filter rules. +`AppObserverRegistry` keeps one `AXObserver` per regular application. +`WorkspaceEvents` subscribes to the `NSWorkspace` notifications. +`TrackingController` ties the three together. The controller runs every AX call +on one serial queue and writes the `WindowStore` on the main actor. + +### Private + +`PrivateAPI` loads the private symbols with `dlsym`. If a symbol is missing, +the feature is disabled and the application does not crash. `PrivateAPI` is +nonisolated, so the serial AX queue can call the wrappers. `SpaceService` +reports the Space of each window through `PrivateAPI`. + +### Actions + +`WindowActivator` raises a window, restores a minimized window, and activates a +window on another Space. The activator minimizes and closes a window for the +context menu. + +### Constraint + +`ConstraintMath` holds the pure math for the window limit line. The math is +unit-tested. `WindowConstraintService` keeps a window above the strip. The +service debounces the events, protects against a loop, and keeps a runtime +blacklist. + +### Strip + +`StripPanel` is the borderless, non-activating `NSPanel`. `StripPositioner` +computes the frame above the Dock. `TabLayout` is the pure layout math for the +tabs and is unit-tested. `TabBarView` is the SwiftUI view in an +`NSHostingView`. `StripController` owns the panel and the view and forwards the +tab actions through closures. + +### Settings + +`Settings` wraps `UserDefaults` with the `ws.` keys. `SettingsWindow` shows the +excluded applications list with Add and Remove. + +### Util + +`Geometry` converts between the Cocoa coordinate system and the AX coordinate +system. The conversion is unit-tested. `Log` holds the `os.Logger` instances. diff --git a/docs/spec.md b/docs/spec.md new file mode 100644 index 0000000..9bf37eb --- /dev/null +++ b/docs/spec.md @@ -0,0 +1,449 @@ +# EPOD Window Bar — Specification + +> Product name: **EPOD Window Bar**. Xcode target and module name: `EPODWindowBar`. Bundle display name: `EPOD Window Bar`. + +This document describes the design. The document matches the current code. The +window filter rules, the signing setup, the threading, and the logging reflect +the implementation. + +--- + +## 1. Problem + +macOS shows applications in the Dock. It does not show windows. +When one application has many windows (for example, a terminal with many +windows, or a browser with many windows), it is slow to find the correct window. +`Cmd + \`` and Mission Control are too slow for 100+ switches each day. + +## 2. Goal + +Make a thin, always-visible strip directly above the Dock. +The strip shows all windows of the **frontmost application** as tabs. +One click on a tab brings that window to the front. + +``` +[ Document 1 ][ Terminal — zsh ][ Project – main.swift ][ Downloads ][ +3 ] +──────────────────────────── Dock ──────────────────────────── +``` + +The Dock does not change. EPOD Window Bar adds to the Dock. It does not replace it. + +## 3. Design decisions (fixed — do not change without approval) + +| # | Decision | Reason | +|---|----------|--------| +| D1 | The strip is always visible. No hover-to-show. | Hover delay costs time 100+ times each day. | +| D2 | The strip is horizontal, directly above the Dock, full screen width. | The owner chose this layout. Side panels were rejected. | +| D3 | The strip shows the windows of the frontmost application only. | The Dock already shows applications. | +| D4 | The strip shows windows from **all** Spaces (desktops). | Windows on other desktops are also lost windows. | +| D5 | Tabs keep a **stable order** (order of first detection). Do not sort by z-order. | Tabs must not jump when focus changes. Muscle memory. | +| D6 | EPOD Window Bar prevents windows from covering the strip (Accessibility resize). | macOS reserves space for the Dock only. | +| D7 | The strip is hidden when the frontmost window is full screen. | The Dock is also hidden in full screen. | +| D8 | Height: 30 pt. | Thin, but tab titles stay readable. | + +## 4. Scope + +### 4.1 In scope (v1) + +- Strip panel above the Dock on the Dock's screen. +- Tabs for all windows of the frontmost application, on all Spaces. +- Tab states: active, inactive, minimized, on other Space. +- Left click: activate window (also on other Space, also when minimized). +- Right click: context menu with **Minimize** and **Close**. +- Overflow: tabs shrink to a minimum width. Then a `+N` button opens a menu with the remaining windows. +- Window constraint: windows cannot extend below the strip top. +- Full-screen detection: hide the strip. +- Menu bar item with settings. +- Launch at login. +- Excluded applications list (no constraint for these applications). +- Debug: "Dump windows to log" and "Copy window dump" menu items. + +### 4.2 Out of scope (v1) — do not implement + +- Pinning applications. +- Side panel, hover panel, search popup. +- Window thumbnails / previews. +- One strip per monitor. (v1: Dock screen only.) +- Native tabs inside one window (Finder, Terminal, Safari, a browser). +- Stage Manager support. (When Stage Manager is on, show the strip but do not constrain windows.) +- App Store distribution. + +## 5. Platform and tooling + +- macOS 14 (Sonoma) and later. +- Swift 5 language mode. The project sets `SWIFT_VERSION = 5.0`. +- AppKit for the panel and window logic. SwiftUI is allowed inside `NSHostingView` for the tab bar and the settings window. +- **No App Sandbox.** Accessibility APIs do not work in the sandbox. +- Agent application: `LSUIElement = YES` (no Dock icon, no main menu). +- Project generation: **XcodeGen** (`project.yml`). Build from the command line with `xcodebuild`. Do not commit the `.xcodeproj`. +- No third-party dependencies in v1. + +## 6. Permissions and code signing + +### 6.1 Permissions + +| Permission | Why | API | +|------------|-----|-----| +| Accessibility | Read windows, raise, minimize, close, resize. | `AXIsProcessTrustedWithOptions` | +| Screen Recording | Read window titles of windows on other Spaces through `CGWindowListCopyWindowInfo` (`kCGWindowName` is empty without it). | `CGPreflightScreenCaptureAccess`, `CGRequestScreenCaptureAccess` | + +- At start, check both permissions. +- If a permission is missing, show a small onboarding window. The window explains each permission in one sentence and has a button that opens the correct System Settings pane. +- Poll the permission state every 2 s. Continue automatically when access is granted. +- The application must work in a reduced mode without Screen Recording: show only windows that AX can find (current Space). Show a warning icon in the menu bar item. +- If Accessibility is revoked at runtime, stop all AX work and show the onboarding window again. Do not crash. + +### 6.2 Code signing + +macOS stores the permissions per code signature. An ad-hoc signature changes each build, so macOS resets the permissions after each build. + +- The committed file `Config.xcconfig` sets ad-hoc signing by default. The default build needs no Apple account. The file ends with `#include? "Local.xcconfig"`. +- To keep the permissions between builds, sign with a stable **Apple Development** certificate. Copy `Local.xcconfig.example` to `Local.xcconfig`. Set `DEVELOPMENT_TEAM` in `Local.xcconfig`. +- Find the team ID in the `OU` field of the Apple Development certificate. The value in parentheses in the `CN` field is the personal ID, not the team ID. +- `Local.xcconfig` is in `.gitignore`. The team ID stays on the local machine. `project.yml` holds no team ID. +- Use a fixed bundle ID: `com.epod.windowbar`. +- Build output: copy the `.app` to `~/Applications/EPOD Window Bar.app` with a script. Always run from this path. +- `scripts/run.sh`: generate, build, kill the running instance, copy, start. +- `scripts/reset-permissions.sh`: `tccutil reset Accessibility com.epod.windowbar` and `tccutil reset ScreenCapture com.epod.windowbar`. + +## 7. Architecture + +### 7.1 Modules + +``` +epod-window-bar/ // repository root +├── project.yml +├── Config.xcconfig // ad-hoc default, includes Local.xcconfig +├── Local.xcconfig.example // team ID placeholder +├── .github/workflows/ci.yml +├── docs/ +│ ├── spec.md +│ └── architecture.md +├── scripts/ +│ ├── run.sh +│ └── reset-permissions.sh +├── Sources/ +│ ├── App/ +│ │ ├── main.swift +│ │ ├── AppDelegate.swift // wires every module; implements AppControl +│ │ ├── AppControl.swift // interface for the menu and the settings +│ │ ├── MenuBarController.swift +│ │ └── LaunchAtLogin.swift // SMAppService.mainApp +│ ├── Permissions/ +│ │ ├── PermissionManager.swift +│ │ └── OnboardingWindow.swift +│ ├── Model/ +│ │ ├── WindowInfo.swift +│ │ └── WindowStore.swift // WindowStore and AXElementCache +│ ├── Tracking/ +│ │ ├── AppObserverRegistry.swift +│ │ ├── WindowEnumerator.swift +│ │ ├── WorkspaceEvents.swift +│ │ └── TrackingController.swift +│ ├── Private/ +│ │ ├── PrivateAPI.swift // ALL private symbols, loaded with dlsym +│ │ └── SpaceService.swift +│ ├── Actions/ +│ │ └── WindowActivator.swift +│ ├── Constraint/ +│ │ ├── ConstraintMath.swift // pure math, unit-tested +│ │ └── WindowConstraintService.swift +│ ├── Strip/ +│ │ ├── StripPanel.swift +│ │ ├── StripPositioner.swift +│ │ ├── TabBarView.swift +│ │ ├── TabLayout.swift // pure layout math, unit-tested +│ │ └── StripController.swift +│ ├── Settings/ +│ │ ├── Settings.swift +│ │ └── SettingsWindow.swift +│ └── Util/ +│ ├── Geometry.swift // coordinate conversion, unit-tested +│ └── Log.swift +└── Tests/ + ├── TabLayoutTests.swift + ├── GeometryTests.swift + ├── ConstraintMathTests.swift + ├── WindowOrderTests.swift + └── WindowFilterTests.swift +``` + +### 7.2 Data model + +```swift +struct WindowInfo: Identifiable, Equatable { + let id: CGWindowID // primary key + let pid: pid_t + let bundleID: String? + var title: String // fallback: application name + var spaceIDs: [UInt64] // from SpaceService; empty if unknown + var isOnCurrentSpace: Bool + var isMinimized: Bool + var isFullScreen: Bool + var firstSeen: Date // used for stable order (D5) +} +``` + +- `WindowStore` holds `[pid_t: [WindowInfo]]` and the frontmost `pid`. +- `WindowStore` is `@MainActor` and publishes changes with `@Observable`. +- `AXElementCache` holds the AX element for each window: `[CGWindowID: AXUIElement]`. The cache is separate. The value type does not hold `AXUIElement`. +- Stable order: sort by `firstSeen`. When a window closes and opens again, it gets a new `firstSeen`. + +### 7.3 Window enumeration + +Use two sources and merge them by `CGWindowID`. + +1. **AX source** (current Space and minimized windows): + - `AXUIElementCreateApplication(pid)` → `kAXWindowsAttribute`. + - Map each AX window to `CGWindowID` with the private `_AXUIElementGetWindow`. + - Read `kAXTitleAttribute`, `kAXMinimizedAttribute`, `kAXSubroleAttribute`, `"AXFullScreen"`. +2. **CGWindowList source** (all Spaces): + - `CGWindowListCopyWindowInfo([.optionAll, .excludeDesktopElements], kCGNullWindowID)`. + - Filter: `kCGWindowOwnerPID == pid`, `kCGWindowLayer == 0`. + - Title from `kCGWindowName` (needs Screen Recording). +3. **Space source**: `SpaceService.spaces(for: [CGWindowID])` (private, see 7.5). + +Filter rules (a window is shown only if all rules are true). The code is in +`Sources/Tracking/WindowEnumerator.swift`: + +- The window is not owned by EPOD Window Bar. +- The CG layer is 0. +- The window is not entirely off all screens, **or** the window is minimized. The off-screen rule hides a placeholder shell such as the Eclipse "limbo" shell at `y = 10000`. A minimized window keeps its tab. +- If the window has an AX element: the AX subrole is `kAXStandardWindowSubrole`. +- If the window has no AX element (a window on another Space): the title must not equal the application name, and the CG bounds are at least 50 × 50. A ghost placeholder has the application name as the title (an empty real title, or `kCGWindowName` set to the application name), so the filter hides it. + +> **Note on the Space data.** The per-window Space query (`CGSCopySpacesForWindows`) can return an empty result for a real window on another Space. So the filter does **not** use the Space data to decide visibility. The filter uses the title and the position. The Space data only sets the "on other Space" tab state. + +### 7.4 Live updates + +- `NSWorkspace` notifications: `didActivateApplication`, `didLaunchApplication`, `didTerminateApplication`, `activeSpaceDidChangeNotification`. +- `NSApplication.didChangeScreenParametersNotification` → reposition the strip. +- One `AXObserver` per running regular application (`activationPolicy == .regular`). Notifications: + - `kAXWindowCreatedNotification` + - `kAXUIElementDestroyedNotification` (register on each window) + - `kAXTitleChangedNotification` (register on each window — some applications change titles often) + - `kAXFocusedWindowChangedNotification`, `kAXMainWindowChangedNotification` + - `kAXWindowMiniaturizedNotification`, `kAXWindowDeminiaturizedNotification` + - `kAXWindowMovedNotification`, `kAXWindowResizedNotification` (for the constraint service) +- Coalesce updates: max one store refresh each 50 ms per application. +- Fallback reconcile: a full refresh of the frontmost application each 2 s. Some applications (Java, Electron) do not send all notifications. +- Remove observers when an application terminates. +- Do all AX calls off the main thread on one serial queue. Set `AXUIElementSetMessagingTimeout` to 0.25 s. A frozen application must not freeze the strip. `PrivateAPI` is nonisolated, so the serial queue can call the private AX wrappers. + +### 7.5 Private APIs + +Put all private symbols in `Private/PrivateAPI.swift`. Load each symbol with `dlsym` at runtime. If a symbol is missing, log it and disable the feature. **Never crash because of a missing private symbol.** + +Mark each use with the comment `// PRIVATE API`. + +| Symbol | Use | Fallback if missing | +|--------|-----|---------------------| +| `_AXUIElementGetWindow` | AX element → `CGWindowID` | Match by PID + frame + title | +| `CGSMainConnectionID` | Connection for CGS calls | Disable Space features | +| `CGSCopyManagedDisplaySpaces` | List of Spaces per display, current Space | Treat all windows as current Space | +| `CGSCopySpacesForWindows` | Spaces of a window | Same as above | +| `_AXUIElementCreateWithRemoteToken` | AX element for windows on other Spaces | Activate the application only (see 7.6) | + +> The signatures of these functions are not documented. The code uses the signatures from open-source projects (AltTab, yabai, Hammerspoon). The remote-token layout is the most uncertain part. The code marks it UNCERTAIN. + +### 7.6 Window activation + +`WindowActivator.activate(windowID:)`: + +1. If minimized: set `kAXMinimizedAttribute` to `false`. +2. If on current Space: `AXUIElementPerformAction(window, kAXRaiseAction)`, then `NSRunningApplication.activate()`. Then set `kAXMainAttribute` to `true`. +3. If on other Space: + - **Method A (default):** get the AX element (remote token method), raise it, activate the application. macOS switches to the Space if the system setting *"When switching to an application, switch to a Space with open windows for the application"* is on. + - **Method B (fallback):** if no AX element is available, activate the application only, and log a warning. + - Do not use `CGSManagedDisplaySetCurrentSpace` in v1. It is known to cause an inconsistent state. +4. Check after 300 ms if the target window is the focused window. If not, log it with the debug details. + +Context menu actions: +- **Minimize:** set `kAXMinimizedAttribute` to `true`. +- **Close:** get `kAXCloseButtonAttribute`, then `kAXPressAction`. (The application can show a "save changes?" dialog. This is correct behavior.) + +### 7.7 Strip panel + +- `NSPanel` with `styleMask: [.borderless, .nonactivatingPanel]`. +- `becomesKeyOnlyIfNeeded = true`, `canBecomeKey = false`, `canBecomeMain = false`. A click on the strip must not take focus from the frontmost application. +- `collectionBehavior = [.canJoinAllSpaces, .stationary, .ignoresCycle]`. +- `level = NSWindow.Level(rawValue: Int(CGWindowLevelForKey(.dockWindow)) - 1)`. The strip is above normal windows but **below** the Dock, so Dock magnification can cover the strip. +- `hasShadow = false`, background: `NSVisualEffectView` with material `.hudWindow`. +- `hidesOnDeactivate = false`. + +### 7.8 Strip position + +`StripPositioner` calculates the frame: + +- Find the Dock screen: the screen where `visibleFrame.minY > frame.minY` (Dock at bottom). If the Dock is hidden (auto-hide) or on the left/right side, use the main screen. +- Frame: `x = screen.visibleFrame.minX`, `y = screen.visibleFrame.minY`, `width = screen.visibleFrame.width`, `height` = the setting value. +- Dock auto-hide: the strip is at the bottom of the screen. The Dock covers it when the Dock appears. This is accepted. +- Recalculate on: screen parameter change, a 2 s poll of `NSScreen.main.visibleFrame` (there is no public Dock-preference notification), wake from sleep. + +### 7.9 Tab bar + +Layout (`TabLayout`, pure function, unit-tested): +- Input: available width, window count, active index, max tab width 220 pt, min tab width 90 pt, spacing 3 pt, `+N` button width 36 pt, application icon area 26 pt. +- Output: visible tabs with widths, and overflow windows. +- Rule: all tabs have equal width. If `count × minWidth` does not fit, show as many tabs as fit, plus `+N`. +- The active window must always be visible. If the active window is in the overflow, swap it with the last visible tab. + +Tab content: +- Left of all tabs: the icon of the frontmost application (16 pt). +- Tab: title, one line, truncated with `…` in the **middle** (`.truncationMode(.middle)`). Some titles have the important part at the end. +- Tooltip: full title. + +Tab states: + +| State | Look | +|-------|------| +| Active (focused window) | Accent background tint, accent text | +| Normal | Secondary text, no background | +| Hover | Light background tint | +| Minimized | Text in italic, 60 % contrast | +| On other Space | Small "desktop" icon before the title, muted text | + +- `+N` button: opens a menu with the overflow windows. +- Empty state (frontmost application has no windows): show only the application icon and the application name in muted text. +- Support light and dark mode. Use system colors only. + +### 7.10 Window constraint service + +Goal: no window extends below the top edge of the strip. + +- Limit line (Cocoa coordinates): `limitY = stripFrame.maxY`. +- AX uses the top-left origin of the **primary** screen. Convert with `Geometry.swift`. The pure math is in `ConstraintMath.swift` and is unit-tested. +- On `kAXWindowMovedNotification` / `kAXWindowResizedNotification` and on window creation: + 1. Skip if: setting is off, application is excluded, window is full screen, subrole is not standard, Stage Manager is on, `kAXSizeAttribute` is not settable (`AXUIElementIsAttributeSettable`). + 2. Skip if the window is not on the strip screen. + 3. If the window bottom is below `limitY`: + - If the window top is also below `limitY - 100`: the user moves the window down intentionally. Do nothing. + - Else: set new height so that the bottom is at `limitY`. +- Debounce: wait 150 ms after the last move/resize event of a window. Do not resize during a drag. (Check `NSEvent.pressedMouseButtons == 0` before resizing.) +- Loop protection: after own resize, ignore events for this window for 300 ms. +- If an application does not accept the new size, add it to a runtime blacklist for this session and log it. + +### 7.11 Full-screen handling + +- After each activation and Space change, read `"AXFullScreen"` of the focused window of the frontmost application. +- If true: `orderOut` the strip. Else: `orderFrontRegardless`. + +### 7.12 Menu bar item + +`NSStatusItem` with an SF Symbol (`rectangle.split.3x1`). Menu: + +- Pause EPOD Window Bar (hides strip, stops constraint) +- ✓ Keep windows above strip +- Excluded apps… (opens settings window) +- ✓ Launch at login (`SMAppService.mainApp`) +- Dump windows to log +- Copy window dump +- Permissions status (text, with a warning icon if a permission is missing) +- Quit + +### 7.13 Settings + +`UserDefaults`, keys with prefix `ws.`: + +| Key | Type | Default | +|-----|------|---------| +| `ws.paused` | Bool | false | +| `ws.constrainWindows` | Bool | true | +| `ws.excludedBundleIDs` | [String] | [] | +| `ws.stripHeight` | Double | 30 | + +The settings window shows the excluded applications list with **Add** (choose from running applications) and **Remove**. + +### 7.14 Logging and debugging + +- `os.Logger`, subsystem `com.epod.windowbar`, categories: `app`, `tracking`, `private`, `activation`, `constraint`, `strip`. +- **Dump windows to log** writes for each running regular application: PID, bundle ID, and for each window: CGWindowID, title, AX subrole, layer, bounds, Space IDs, minimized, full screen, shown/filtered (with filter reason). The dump writes at **notice** level, so `log show` persists it. Every dump field is public (not redacted). +- **Copy window dump** puts the same dump text on the clipboard. The user reads the dump without a log tool. +- Read the log with: `log stream --predicate 'subsystem == "com.epod.windowbar"' --level debug` or `log show --last 5m --predicate 'subsystem == "com.epod.windowbar"' --info`. + +### 7.15 Performance targets + +- Idle CPU: < 1 % average. +- Memory: < 60 MB. +- Click on tab → window in front: < 150 ms on the current Space. +- No AX call on the main thread. All AX calls run on one serial queue. + +## 8. Phases + +The project was built in phases. Each phase has a manual test checklist. The +owner tests each phase on a real machine. + +### Phase 0 — Skeleton +- XcodeGen project, agent app, menu bar item with Quit. +- `run.sh`, `reset-permissions.sh`, README with signing setup. +- PermissionManager + onboarding window. + +**Test:** App starts from `~/Applications`. No Dock icon. Menu bar item is visible. Onboarding opens the correct settings panes. After a rebuild, permissions stay granted. + +### Phase 1 — Strip panel +- Panel, positioner, static fake tabs. + +**Test:** Strip is directly above the Dock. Change Dock size, Dock magnification, auto-hide, Dock position left/right, connect/disconnect a second monitor. Strip stays in the correct position. Click on the strip does not take focus from the frontmost application. Strip is visible on all Spaces. + +### Phase 2 — Windows on current Space +- AX enumeration, `_AXUIElementGetWindow`, WindowStore, observers, stable order, tab bar with real data, title updates. + +**Test:** Open 5 Finder windows. Switch applications: tabs change immediately. Open/close windows: tabs update. Change a document in an application: the tab title updates. Tab order does not change when focus changes. + +### Phase 3 — Actions +- Activation (current Space, minimized), context menu, overflow `+N`, active tab always visible. + +**Test:** Click on each tab activates the correct window. Minimized window is restored. Close/Minimize from the context menu work. Open 15 windows: `+N` appears and its menu works. + +### Phase 4 — All Spaces +- CGWindowList `optionAll`, SpaceService, remote-token AX elements, other-Space tab state, activation across Spaces, debug dump. + +**Test:** Windows on Desktop 2 and 3 appear with the desktop icon. Click switches to the correct Space and window. Dump output shows no wrong helper windows. Without Screen Recording permission, the app still runs (reduced mode). + +### Phase 5 — Window constraint +- WindowConstraintService, coordinate conversion, loop protection, blacklist. + +**Test:** Green button zoom: window ends at the strip. Drag a window down: no resize during drag; after drop, bottom is corrected unless the window was moved down intentionally. Test Finder, Terminal, a web browser, and Xcode: report which ones work. Excluded application is not resized. + +### Phase 6 — Full screen, settings, login +- Full-screen hide, settings window, excluded apps, launch at login, pause. + +**Test:** Full-screen application: strip disappears; exit: strip comes back. Pause works. Settings persist after restart. Launch at login works after logout/login. + +### Phase 7 — Hardening +- Performance check (Activity Monitor), sleep/wake, frozen application test (`kill -STOP `), permission revoked at runtime, Stage Manager on. + +**Test:** CPU and memory inside targets. A stopped application does not freeze the strip. Revoke Accessibility: onboarding appears, no crash. + +## 9. Known edge cases + +| Case | Expected behavior | +|------|-------------------| +| Limited AX support (for example a Java application) | If AX titles are empty, use CG titles. | +| Application with 0 windows | Empty state. | +| Application terminates | Remove observers and tabs immediately. | +| Window title changes often | Update the tab. Do not change the order. | +| Two windows with the same title | Show both. | +| Electron applications | May not send all AX notifications. The 2 s reconcile covers this. | +| Sheets and dialogs | Not shown as tabs (subrole filter). | +| Finder desktop | Not shown (filter `excludeDesktopElements`). | +| Off-screen placeholder shell | Hidden (off-screen filter rule). | +| Multiple monitors | v1: strip on the Dock screen only. The constraint service only acts on windows on this screen. | +| Sleep / wake | Reposition the strip, full refresh. | +| Display resolution change | Reposition the strip. | + +## 10. Working rules + +1. Put all private API code in `Private/`. Mark it with `// PRIVATE API`. Load symbols with `dlsym`. +2. Write unit tests for pure logic: tab layout, coordinate conversion, constraint math, stable order, and the window filter. +3. Keep the build green. Run `xcodebuild test`. +4. Do not change design decisions D1–D8 without approval. + +## 11. Later (v2 ideas, not now) + +- Pin applications. +- Search popup with hotkey (filter windows by title). +- Window thumbnails on hover. +- One strip per monitor. +- Color tags per title pattern. +- Keyboard shortcuts: `Ctrl + 1…9` for tab 1…9. diff --git a/project.yml b/project.yml new file mode 100644 index 0000000..87379a0 --- /dev/null +++ b/project.yml @@ -0,0 +1,63 @@ +name: EPODWindowBar + +options: + bundleIdPrefix: com.epod + createIntermediateGroups: true + deploymentTarget: + macOS: "14.0" + +settings: + base: + # SWIFT_VERSION is the language version, not the compiler version. + # 5.0 selects Swift 5 language mode. The spec allows this mode. + SWIFT_VERSION: "5.0" + MACOSX_DEPLOYMENT_TARGET: "14.0" + MARKETING_VERSION: "1.0" + CURRENT_PROJECT_VERSION: "1" + # The signing settings live in Config.xcconfig. The default is ad-hoc + # signing. Config.xcconfig includes the optional Local.xcconfig for a + # stable Apple Development certificate. See README.md. + +targets: + EPODWindowBar: + type: application + platform: macOS + # The product file is EPODWindowBar.app. + # The run script copies it to "~/Applications/EPOD Window Bar.app". + configFiles: + Debug: Config.xcconfig + Release: Config.xcconfig + sources: + - path: Sources + settings: + base: + PRODUCT_NAME: EPODWindowBar + PRODUCT_MODULE_NAME: EPODWindowBar + PRODUCT_BUNDLE_IDENTIFIER: com.epod.windowbar + info: + path: Sources/App/Info.plist + properties: + CFBundleName: EPODWindowBar + CFBundleDisplayName: EPOD Window Bar + CFBundleShortVersionString: "1.0" + CFBundleVersion: "1" + # LSUIElement makes the app an agent: no Dock icon, no main menu. + LSUIElement: true + LSMinimumSystemVersion: "14.0" + NSHumanReadableCopyright: "" + # The scheme runs the unit tests with: xcodebuild test -scheme EPODWindowBar + scheme: + testTargets: + - EPODWindowBarTests + + EPODWindowBarTests: + type: bundle.unit-test + platform: macOS + sources: + - path: Tests + dependencies: + - target: EPODWindowBar + settings: + base: + PRODUCT_BUNDLE_IDENTIFIER: com.epod.windowbar.tests + GENERATE_INFOPLIST_FILE: YES diff --git a/scripts/reset-permissions.sh b/scripts/reset-permissions.sh new file mode 100755 index 0000000..e662ef2 --- /dev/null +++ b/scripts/reset-permissions.sh @@ -0,0 +1,14 @@ +#!/bin/bash +# reset-permissions.sh clears the macOS permissions for EPOD Window Bar. +# Use this script to test the onboarding flow again. +set -euo pipefail + +BUNDLE_ID="com.epod.windowbar" + +echo "==> Reset Accessibility for $BUNDLE_ID" +tccutil reset Accessibility "$BUNDLE_ID" || true + +echo "==> Reset Screen Recording for $BUNDLE_ID" +tccutil reset ScreenCapture "$BUNDLE_ID" || true + +echo "==> Done. Start the app again to see the onboarding window." diff --git a/scripts/run.sh b/scripts/run.sh new file mode 100755 index 0000000..4418f32 --- /dev/null +++ b/scripts/run.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# run.sh builds EPOD Window Bar, kills the running instance, copies the app +# to ~/Applications, and starts it. Always run the app from ~/Applications. +# A stable path and a stable signature keep the macOS permissions. +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +APP_DISPLAY_NAME="EPOD Window Bar" +PRODUCT_NAME="EPODWindowBar" +SCHEME="EPODWindowBar" +CONFIG="Debug" + +DERIVED="$ROOT/.build/derived" +BUILT_APP="$DERIVED/Build/Products/$CONFIG/$PRODUCT_NAME.app" +DEST_APP="$HOME/Applications/$APP_DISPLAY_NAME.app" + +echo "==> Generate the Xcode project with XcodeGen" +xcodegen generate + +echo "==> Build with xcodebuild" +# The signing comes from Config.xcconfig. The default is ad-hoc signing. +# Copy Local.xcconfig.example to Local.xcconfig to sign with your team ID. +xcodebuild \ + -project "EPODWindowBar.xcodeproj" \ + -scheme "$SCHEME" \ + -configuration "$CONFIG" \ + -derivedDataPath "$DERIVED" \ + build + +echo "==> Kill the running instance" +killall "$PRODUCT_NAME" 2>/dev/null || true + +echo "==> Copy the app to ~/Applications" +mkdir -p "$HOME/Applications" +rm -rf "$DEST_APP" +cp -R "$BUILT_APP" "$DEST_APP" + +echo "==> Start the app" +open "$DEST_APP" + +echo "==> Done. App is at: $DEST_APP"