# Follow a window

> Keep a resident on top of a Chrome window (or any app's window) with a small watcher script and `pixling resident follow`.

A resident can stand on Chrome's top edge and move whenever you move that window. Pixling never watches other apps' windows itself. Instead, your own watcher script streams the target window's frame as JSON lines into [`pixling resident follow`](/docs/reference/residents/#resident-follow-cli-only).

```text title="How window following works"
  Watcher script (Accessibility API) ──(JSON lines)──▶ pixling resident follow ──▶ Resident tracks window
```

> [!NOTE]
> **Prerequisites**
> Turn on **CLI connection** in **Settings** › **Connect**, and keep a resident on the desk. Run `pixling residents` to find its selector (for example, `No.1#1`).

## Try it by hand

Test the pipeline without writing a watcher by piping two sample frames into `pixling resident follow`:

```sh title="Terminal"
printf '%s\n' '{"x":300,"y":200,"width":900,"height":600}' \
               '{"x":420,"y":260,"width":900,"height":600}' |
  pixling resident follow --to 'No.1#1'
```

The resident stands on the top edge of a 900×600 frame (`x` and `y` start at the main display's top-left corner, with `y` increasing downward). It moves once and stays at its last shown spot when stdin closes:

```text title="Output"
follow ended: callerEnded (2 lines, 2 applied)
```

## Ride on a browser window

Save the script below as `chrome-follow.swift`, then pipe its output into Pixling:

```sh title="Terminal"
swift chrome-follow.swift | pixling resident follow --to 'No.1#1'
```

The script subscribes to Accessibility notifications so macOS wakes it whenever Chrome's front window moves, resizes, minimizes, closes, or changes focus, printing one JSON line per change without polling:

- **Window stacking (`"window"`)**: Each line includes the window's `kCGWindowNumber` so the resident sits directly above Chrome's window instead of floating over every app. When another window covers Chrome, it covers the resident too.
- **Focus and desktop switches**: When Chrome returns to the front or you switch desktops, the script repeats the last line so Pixling re-stacks the resident above Chrome or hides it while Chrome is on another Space.

> [!TIP]
> **First run and other apps**
> - On the first run, macOS prompts for Accessibility access for your terminal app (**System Settings** › **Privacy & Security** › **Accessibility**). Allow it, then run the command again.
> - To follow another app instead of Chrome, pass its bundle ID as the first argument: `swift chrome-follow.swift com.apple.Safari | …`. Look up any macOS app's bundle ID in Terminal with `osascript -e 'id of app "Safari"'` (or `"Google Chrome"`).

<details>
<summary>Full chrome-follow.swift script (147 lines)</summary>

```swift title="chrome-follow.swift"
// chrome-follow.swift — print the front Chrome window's frame as JSON lines, one per change.
// swift chrome-follow.swift | pixling resident follow --to 'No.1#1'
// Optional argument: another app's bundle ID (default com.google.Chrome).
import AppKit
import ApplicationServices

let bundleID = CommandLine.arguments.dropFirst().first ?? "com.google.Chrome"
setvbuf(stdout, nil, _IOLBF, 0) // one line out per change, even through a pipe

let prompt = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
guard AXIsProcessTrustedWithOptions(prompt) else {
    FileHandle.standardError.write(Data("Allow your terminal in System Settings > Privacy & Security > Accessibility, then run this again.\n".utf8))
    exit(1)
}

final class Watcher {
    private var pid: pid_t = 0
    private var app: AXUIElement?
    private var window: AXUIElement?
    private var observer: AXObserver?
    private var last = ""
    private var number: Int? // the followed window's kCGWindowNumber, looked up once per window

    private let appNotifications = [kAXFocusedWindowChangedNotification, kAXMainWindowChangedNotification,
                                    kAXWindowCreatedNotification, kAXApplicationHiddenNotification,
                                    kAXApplicationShownNotification]
    private let windowNotifications = [kAXMovedNotification, kAXResizedNotification, kAXWindowMiniaturizedNotification,
                                       kAXWindowDeminiaturizedNotification, kAXUIElementDestroyedNotification]

    var watchedPID: pid_t { pid }

    func attach(_ running: NSRunningApplication) {
        detach(quietly: true) // the next frame follows at once; no blink in between
        pid = running.processIdentifier
        let app = AXUIElementCreateApplication(pid)
        var created: AXObserver?
        let callback: AXObserverCallback = { _, _, _, refcon in
            Unmanaged<Watcher>.fromOpaque(refcon!).takeUnretainedValue().changed()
        }
        guard AXObserverCreate(pid, callback, &created) == .success, let observer = created else {
            return emit(#"{"hidden":true}"#)
        }
        self.app = app
        self.observer = observer
        let refcon = Unmanaged.passUnretained(self).toOpaque()
        for name in appNotifications { AXObserverAddNotification(observer, app, name as CFString, refcon) }
        CFRunLoopAddSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .defaultMode)
        changed()
    }

    func detach(quietly: Bool = false) {
        if let observer { CFRunLoopRemoveSource(CFRunLoopGetMain(), AXObserverGetRunLoopSource(observer), .defaultMode) }
        observer = nil; app = nil; window = nil; pid = 0
        if !quietly { emit(#"{"hidden":true}"#) }
    }

    /// Every notification lands here: follow the app's focused window and print its frame.
    func changed() {
        guard let app, let observer else { return emit(#"{"hidden":true}"#) }
        let focused: AXUIElement? = value(app, kAXFocusedWindowAttribute)
        let same = switch (focused, window) {
        case (nil, nil): true
        case let (focused?, window?): CFEqual(focused, window)
        default: false
        }
        if !same {
            let refcon = Unmanaged.passUnretained(self).toOpaque()
            if let window { for name in windowNotifications { AXObserverRemoveNotification(observer, window, name as CFString) } }
            window = focused
            number = nil
            if let focused { for name in windowNotifications { AXObserverAddNotification(observer, focused, name as CFString, refcon) } }
        }
        let hidden: Bool = value(app, kAXHiddenAttribute) ?? false
        let minimized: Bool = window.flatMap { value($0, kAXMinimizedAttribute) } ?? false
        guard !hidden, !minimized, let window,
              let position: AXValue = value(window, kAXPositionAttribute),
              let size: AXValue = value(window, kAXSizeAttribute) else { return emit(#"{"hidden":true}"#) }
        var origin = CGPoint.zero, extent = CGSize.zero
        AXValueGetValue(position, .cgPoint, &origin)
        AXValueGetValue(size, .cgSize, &extent)
        if number == nil { number = windowNumber(origin: origin, extent: extent) }
        let named = number.map { #","window":\#($0)"# } ?? ""
        emit(#"{"x":\#(origin.x),"y":\#(origin.y),"width":\#(extent.width),"height":\#(extent.height)\#(named)}"#)
    }

    /// Chrome came to the front, or you switched desktops: send the same line again. Pixling puts the resident
    /// back on top of Chrome's window, or hides it while that window is not on this desktop.
    func resend() {
        guard !last.isEmpty, last != #"{"hidden":true}"# else { return }
        print(last)
    }

    /// The number of the app's on-screen window with this frame (kCGWindowNumber), so Pixling can stand the
    /// resident just above it. Reading bounds and numbers needs no extra permission. Looked up when the
    /// followed window changes (not on every move, when the two APIs can briefly disagree mid-drag).
    private func windowNumber(origin: CGPoint, extent: CGSize) -> Int? {
        let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID)
            as? [[String: Any]] ?? []
        return windows.first { info in
            guard (info[kCGWindowOwnerPID as String] as? Int).map(pid_t.init) == pid,
                  (info[kCGWindowLayer as String] as? Int) == 0,
                  let bounds = info[kCGWindowBounds as String] as? NSDictionary,
                  let frame = CGRect(dictionaryRepresentation: bounds as CFDictionary) else { return false }
            return abs(frame.minX - origin.x) < 1 && abs(frame.minY - origin.y) < 1
                && abs(frame.width - extent.width) < 1 && abs(frame.height - extent.height) < 1
        }?[kCGWindowNumber as String] as? Int
    }

    private func value<T>(_ element: AXUIElement, _ attribute: String) -> T? {
        var raw: CFTypeRef?
        guard AXUIElementCopyAttributeValue(element, attribute as CFString, &raw) == .success else { return nil }
        return raw as? T
    }

    private func emit(_ line: String) {
        guard line != last else { return }
        last = line
        print(line)
    }
}

let watcher = Watcher()
let workspace = NSWorkspace.shared.notificationCenter
workspace.addObserver(forName: NSWorkspace.didLaunchApplicationNotification, object: nil, queue: .main) { note in
    guard let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
          app.bundleIdentifier == bundleID else { return }
    watcher.attach(app)
}
workspace.addObserver(forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { note in
    guard let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
          app.processIdentifier == watcher.watchedPID else { return }
    watcher.resend()
}
workspace.addObserver(forName: NSWorkspace.activeSpaceDidChangeNotification, object: nil, queue: .main) { _ in
    watcher.resend()
}
workspace.addObserver(forName: NSWorkspace.didTerminateApplicationNotification, object: nil, queue: .main) { note in
    guard let app = note.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication,
          app.bundleIdentifier == bundleID else { return }
    watcher.detach()
}
if let running = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).first {
    watcher.attach(running)
} else {
    watcher.detach()
}
RunLoop.main.run()
```

</details>

### Positioning and layering

Move the resident to another edge with `--edge` and `--at`, such as `--edge right --at 0.1` to sit beside the window's top-right corner. Choose how it stacks with `--layer`; layer choices while following are not saved.

| `--layer` value | Stacking behavior |
| --- | --- |
| `above-target` *(default)* | Sits directly above the window in `"window"`, going behind other apps together with Chrome. |
| `floating` | Stays in front of every window on screen. |
| `window` | Stays among ordinary windows without tracking Chrome's stacking order. |

- **On-screen check**: Pixling checks the named window only when a line arrives. If that window is not on screen at that moment, the resident hides until a line arrives whose window is on screen.
- **Menu bar overlap**: When the resident overlaps the menu bar (such as on a full-screen-sized window), it keeps its own layer so the menu bar does not cover it.

### Behavior while following

- **Hidden, minimized, or closed**: When Chrome is hidden, minimized, closed, or quits, the script emits `{"hidden":true}`. The resident reappears on the next visible frame.
- **Switching Spaces**: The Accessibility API does not report which Space a window belongs to. Repeating the last line on a desktop switch lets Pixling hide the resident while Chrome's window is on another desktop.
- **Clicking**: A plain click leaves the resident attached to the window. Listen for clicks with [`pixling resident events`](/docs/connect/hear-clicks/).
- **Dragging**: Dragging the resident away ends the follow session with `userGrabbed` and leaves it where you dropped it. Pixling exits, the watcher stops on its next write, and running the pipeline again reattaches it.

> [!NOTE]
> **What gets saved**
> Nothing is saved while the resident follows. The last position shown is saved once when the pipeline ends.

## Next steps

- [Hear clicks](/docs/connect/hear-clicks/): Stream click events from a resident to your script with pixling resident events.
- [Resident follow reference](/docs/reference/residents/#resident-follow-cli-only): All flags, JSON line fields, and exit reasons for pixling resident follow.
