ウインドウに乗せる
Pixling は Mac App Store 公開準備中です。リリース通知は pixling.app のウェイトリストから登録できます。
住人は Chrome の上のふちに立ち、ウインドウを動かすたびに一緒に移動できます。Pixling 自身はほかのアプリのウインドウを監視しません。代わりに、あなた自身の監視スクリプトが対象ウインドウの枠を JSON 行として pixling resident follow へ流し続けます。
監視スクリプト(Accessibility API)──(JSON 行)──▶ pixling resident follow ──▶ 住人がウインドウに追従監視スクリプトを書く前に、サンプルの枠を 2 行そのまま 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)ブラウザのウインドウに乗る
Section titled “ブラウザのウインドウに乗る”下のスクリプトを chrome-follow.swift として保存し、出力をパイプで Pixling に渡します。
swift chrome-follow.swift | pixling resident follow --to 'No.1#1'このスクリプトは Accessibility 通知を購読しているため、Chrome の最前面ウインドウが動いたとき、大きさが変わったとき、最小化・閉じられたとき、フォーカスが変わったときにだけ macOS から起こされ、ポーリングなしで変化ごとに 1 行ずつ JSON を出力します。
- ウインドウの重なり順(
"window"):各行にウインドウのkCGWindowNumberが含まれるため、住人はすべてのアプリの上に浮くのではなく、Chrome のウインドウのすぐ上に立ちます。別のウインドウが Chrome を覆えば、住人も一緒に隠れます。 - フォーカスとデスクトップの切り替え:Chrome が再び最前面に来たときやデスクトップを切り替えたときは、スクリプトが最後の行をもう一度送り、Pixling が住人を Chrome の上へ戻したり、Chrome が別の操作スペースにあるあいだ隠したりします。
chrome-follow.swift 全文(147 行)
// 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 AppKitimport 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 CFDictionaryguard 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.notificationCenterworkspace.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()位置と重なり方
Section titled “位置と重なり方”住人を別のふちに置きたいときは --edge と --at を使います(たとえば --edge right --at 0.1 で、ウインドウの右上の角のそばに立ちます)。重なり方は --layer で選びます(追従中のレイヤー指定は保存されません)。
--layer の値 |
重なり方 |
|---|---|
above-target (既定) |
"window" で指定されたウインドウのすぐ上に立ち、Chrome と一緒にほかのアプリのうしろへ回る。 |
floating |
画面上のすべてのウインドウの前に出し続ける。 |
window |
Chrome の重なり順には従わず、ふつうのウインドウと同じ階層にとどまる。 |
- 画面上にあるかの確認:Pixling は行が届いたときだけ指定のウインドウを確認します。その瞬間にウインドウが画面にない場合、そのウインドウが画面上にある行が届くまで住人は隠れます。
- メニューバーとの重なり:画面いっぱいのウインドウなど、住人がメニューバーに重なる位置にあるときは、メニューバーに隠れないよう住人自身の階層を保ちます。
乗っているあいだの振る舞い
Section titled “乗っているあいだの振る舞い”- 非表示・最小化・閉じたとき:Chrome が隠れたり、最小化・閉じられたり、終了したりすると、スクリプトが
{"hidden":true}を送ります。次の表示枠が届くと住人が再び現れます。 - 操作スペースの切り替え:Accessibility API はウインドウがどの操作スペースに属しているかを報告しません。デスクトップ切り替え時にスクリプトが最後の行をもう一度送ることで、Chrome のウインドウが別のデスクトップにあるあいだ Pixling が住人を隠せます。
- クリック:ふつうにクリックしても住人はウインドウに乗ったままです。クリックは
pixling resident eventsで受け取れます。 - ドラッグ:住人をドラッグして引き離すと追従が
userGrabbedで終わり、離した場所にとどまります。Pixling は終了し、監視スクリプトも次の書き込みで止まります。再び乗せるにはパイプラインを実行し直してください。
次のステップ
Section titled “次のステップ”クリックを聞くpixling resident events で住人へのクリックをスクリプトへ流す。
resident follow リファレンスpixling resident follow の全フラグ、JSON 行のフィールド、終了理由。