跳到內容
繁體中文

跟著視窗走

Pixling 正在準備於 Mac App Store 上架。歡迎到 pixling.app 加入候補名單,上架時會通知你。

居民可以站在 Chrome 的上緣,並在你移動那個視窗時跟著移動。Pixling 本身從不監看其他 App 的視窗;而是由你自己的監看腳本把目標視窗的外框以一行行 JSON 串流進 pixling resident follow。

視窗跟隨的運作方式
監看腳本(輔助使用 API) ──(JSON 行)──▶ pixling resident follow ──▶ 居民跟著視窗移動

不用先寫監看腳本,把兩個範例的外框直接管線送進 pixling resident follow 就能測試這條流程:

終端機
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'

居民會站在一個 900×600 外框的上緣(x 和 y 從主螢幕的左上角算起,y 往下遞增)。它會移動一次,並在標準輸入關閉時留在最後顯示的位置:

輸出
follow ended: callerEnded (2 lines, 2 applied)

搭在瀏覽器視窗上

「搭在瀏覽器視窗上」一節

把下面的腳本存成 chrome-follow.swift,再把它的輸出管線接到 Pixling:

終端機
swift chrome-follow.swift | pixling resident follow --to 'No.1#1'

腳本會訂閱「輔助使用」通知,讓 macOS 在 Chrome 最前面的視窗移動、改變大小、縮到最小、關閉或焦點改變時喚醒它,每次改變印出一行 JSON,完全不需要輪詢:

  • 視窗堆疊("window"):每一行包含視窗的 kCGWindowNumber,讓居民正好待在 Chrome 視窗的正上方,而不是浮在所有 App 前面。當其他視窗蓋住 Chrome 時,也會一併蓋住居民。
  • 焦點與桌面切換:當 Chrome 回到最前面或你切換桌面時,腳本會重複送出最後一行,讓 Pixling 把居民重新排到 Chrome 上面,或在 Chrome 位於其他空間時把它藏起來。
完整的 chrome-follow.swift 腳本(147 行)
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()

用 --edge 和 --at 把居民移到別的邊緣,例如 --edge right --at 0.1 會讓它待在視窗右上角旁邊。用 --layer 決定堆疊方式;跟隨期間的圖層選擇不會儲存。

--layer 值 堆疊行為
above-target (預設) 待在 "window" 指名的視窗正上方,會和 Chrome 一起退到其他 App 後面。
floating 一直待在畫面上所有視窗的前面。
window 待在一般視窗之間,不跟著 Chrome 的堆疊順序。
  • 畫面內檢查:Pixling 只在收到一行時才檢查指名的視窗。如果當下該視窗不在畫面上,居民就會藏起來,直到有一行的視窗在畫面上為止。
  • 選單列重疊:居民和選單列重疊時(例如視窗佔滿整個螢幕),它會保持自己的圖層,讓選單列不會蓋住它。
  • 隱藏、縮到最小或關閉:當 Chrome 被隱藏、縮到最小、關閉或結束時,腳本會送出 {"hidden":true}。居民會在下一個可見外框送到時重新出現。
  • 切換空間:「輔助使用」API 不會回報視窗屬於哪個空間。切換桌面時重複送出最後一行,就能讓 Pixling 在 Chrome 視窗位於其他桌面時把居民藏起來。
  • 點按:單純點一下會讓居民繼續待在視窗上。你可以用 pixling resident events 聽見點按。
  • 拖移:把居民拖移開來會以 userGrabbed 結束跟隨工作階段,並把居民留在你放開的位置。Pixling 會結束,監看腳本會在下一次寫入時停止,再執行一次管線就能重新接上。