Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Scripts/window-shot.swift3// Description: Captures the frontmost window (or every window with --all) of one process to PNG, by process id or by application name. Used for visual checks of the Debug build.4//5// Usage: swift Scripts/window-shot.swift --pid <pid> <out.png> [--all] (or: <AppName> <out.png>)6import AppKit7import CoreGraphics89var args = Array(CommandLine.arguments.dropFirst())10let all = args.contains("--all"); args.removeAll { $0 == "--all" }11var pid: Int?12if args.first == "--pid", args.count >= 2 { pid = Int(args[1]); args.removeFirst(2) }13guard (pid != nil && args.count == 1) || (pid == nil && args.count == 2) else { print("usage: window-shot (--pid <pid> | <AppName>) <out.png> [--all]"); exit(2) }14let out = args.last!15let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []16let wins = list.filter { w in17 guard (w["kCGWindowLayer"] as? Int) == 0 else { return false }18 if let pid { return (w["kCGWindowOwnerPID"] as? Int) == pid }19 return (w["kCGWindowOwnerName"] as? String) == args[0]20}21guard !wins.isEmpty else { print("no window"); exit(1) }22func capture(_ win: [String: Any], _ path: String) {23 guard let id = win["kCGWindowNumber"] as? Int else { return }24 let p = Process(); p.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture"); p.arguments = ["-l", String(id), "-o", "-x", path]25 try! p.run(); p.waitUntilExit()26 print("saved \(path) title=\(win["kCGWindowName"] ?? "")")27}28if all {29 for (i, w) in wins.enumerated() { capture(w, i == 0 ? out : out.replacingOccurrences(of: ".png", with: "-\(i + 1).png")) }30} else { capture(wins[0], out) }31