Repository Public
1// Captures the frontmost window of an app to a PNG (evidence for acceptance tests).2// Usage: swift scripts/window-shot.swift <AppName> <output.png>3// swift scripts/window-shot.swift --pid <pid> <output.png> (one precise process, when several copies run)4import CoreGraphics5import Foundation6let args = CommandLine.arguments7let byPID = args.count == 4 && args[1] == "--pid"8guard args.count == 3 || byPID else { print("usage: window-shot <AppName>|--pid <pid> <out.png>"); exit(2) }9let out = args[args.count - 1]10let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []11let wins = list.filter { info in12 guard (info["kCGWindowLayer"] as? Int) == 0 else { return false }13 return byPID ? (info["kCGWindowOwnerPID"] as? Int) == Int(args[2]) : (info["kCGWindowOwnerName"] as? String) == args[1]14}15guard let win = wins.first, let id = win["kCGWindowNumber"] as? Int else { print("no window for \(args[byPID ? 2 : 1])"); exit(1) }16print("window \(id) \(win["kCGWindowBounds"] ?? "") title=\(win["kCGWindowName"] ?? "")")17let p = Process(); p.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture"); p.arguments = ["-l", String(id), "-o", "-x", out]18try! p.run(); p.waitUntilExit(); print("saved \(out)")19