Repository Public
1// Captures the frontmost window of a named app to a PNG (evidence for acceptance tests).2// Usage: swift Scripts/window-shot.swift <AppName|pid> <output.png>3import CoreGraphics4import Foundation5let args = CommandLine.arguments6guard args.count == 3 else { print("usage: window-shot <AppName> <out.png>"); exit(2) }7let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []8// A numeric first argument selects the windows of one process id (several instances of an app).9let pid = Int(args[1])10let wins = list.filter { info in11 let owner = pid.map { (info["kCGWindowOwnerPID"] as? Int) == $0 } ?? ((info["kCGWindowOwnerName"] as? String) == args[1])12 return owner && (info["kCGWindowLayer"] as? Int) == 013}14guard let win = wins.first, let id = win["kCGWindowNumber"] as? Int else { print("no window for \(args[1])"); exit(1) }15print("window \(id) \(win["kCGWindowBounds"] ?? "") title=\(win["kCGWindowName"] ?? "")")16let p = Process(); p.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture"); p.arguments = ["-l", String(id), "-o", "-x", args[2]]17try! p.run(); p.waitUntilExit(); print("saved \(args[2])")18