콘텐츠로 이동
한국어

창 따라가기

Pixling은 Mac App Store 출시를 준비하고 있어요. 출시 알림은 pixling.app 대기자 명단에서 신청할 수 있어요.

주민은 Chrome의 위쪽 가장자리에 서서 창을 옮길 때마다 함께 움직일 수 있어요. Pixling은 다른 앱의 창을 직접 지켜보지 않아요. 대신 직접 만든 감시 스크립트가 대상 창의 틀을 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는 아래로 커져요) 한 번 움직이고, stdin이 닫히면 마지막으로 보인 자리에 머물러요.

출력
follow ended: callerEnded (2 lines, 2 applied)

아래 스크립트를 chrome-follow.swift로 저장한 뒤, 출력을 Pixling으로 파이프해요.

터미널
swift chrome-follow.swift | pixling resident follow --to 'No.1#1'

스크립트는 손쉬운 사용 알림을 구독해 Chrome의 앞쪽 창이 옮겨지거나, 크기가 바뀌거나, 최소화되거나, 닫히거나, 포커스가 바뀔 때마다 macOS가 깨우도록 하고, 폴링 없이 변화가 생길 때마다 JSON 한 줄을 출력해요.

  • 창 겹침 순서("window"): 각 줄에 창의 kCGWindowNumber가 들어가서, 주민이 모든 앱 위에 떠 있지 않고 Chrome 창 바로 위에 앉아요. 다른 창이 Chrome을 가리면 주민도 함께 가려져요.
  • 포커스와 데스크탑 전환: Chrome이 다시 앞으로 오거나 데스크탑을 바꾸면 스크립트가 마지막 줄을 한 번 더 보내서, Pixling이 주민을 Chrome 위로 다시 겹치거나 Chrome이 다른 Space에 있는 동안 숨길 수 있게 해요.
전체 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과 함께 다른 앱 뒤로 가요.
floating 화면의 모든 창 앞에 머물러요.
window Chrome의 겹침 순서를 따르지 않고 일반 창들 사이에 머물러요.
  • 화면 표시 확인: Pixling은 줄이 도착할 때만 지정된 창을 확인해요. 그 순간 창이 화면에 없으면, 창이 화면에 있는 줄이 도착할 때까지 주민을 숨겨요.
  • 메뉴 막대 겹침: 주민이 메뉴 막대와 겹칠 때(예: 전체 화면 크기의 창 위)는 메뉴 막대가 가리지 않도록 자기 층을 유지해요.
  • 가리기, 최소화, 닫기: Chrome이 가려지거나, 최소화되거나, 닫히거나, 종료되면 스크립트가 {"hidden":true}를 보내요. 주민은 다음 보이는 틀이 올 때 다시 나타나요.
  • Space 전환: 손쉬운 사용 API는 창이 어느 Space에 있는지 알려 주지 않아요. 데스크탑을 바꿀 때 마지막 줄을 한 번 더 보내면, Chrome 창이 다른 데스크탑에 있는 동안 Pixling이 주민을 숨길 수 있어요.
  • 클릭: 그냥 클릭하면 주민은 창에 붙은 채로 남아요. 클릭을 들으려면 pixling resident events를 쓰세요.
  • 드래그: 주민을 드래그해 떼어 내면 userGrabbed로 따라가기가 끝나고 놓은 자리에 머물러요. Pixling이 종료되고 감시 스크립트는 다음 쓰기에서 멈춰요. 파이프라인을 다시 실행하면 다시 붙어요.