SPB Git

Repository Public

window-shot.swift 2.0 KB 23 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Scripts/window-shot.swift3// Description: Captures the largest on-screen window of a named app to a PNG (evidence for visual checks). Never the whole screen.4// Usage: swift Scripts/window-shot.swift <AppName> <output.png> [smallest | title]5//   smallest: the smallest window instead of the largest (Settings, a message window)6//   title: capture the window whose title contains this text (needs Screen Recording permission to read titles); default = the largest window.7import CoreGraphics8import Foundation9let args = CommandLine.arguments10guard args.count == 3 || args.count == 4 else { print("usage: window-shot <AppName> <out.png> [smallest | title]"); exit(2) }11let list = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []12let wins = list.filter { ($0["kCGWindowOwnerName"] as? String) == args[1] && ($0["kCGWindowLayer"] as? Int) == 0 }13func area(_ w: [String: Any]) -> Double { let b = w["kCGWindowBounds"] as? [String: Double] ?? [:]; return (b["Width"] ?? 0) * (b["Height"] ?? 0) }14let pick: [String: Any]?15if args.count == 4 && args[3] == "smallest" { pick = wins.filter { area($0) > 40_000 }.min(by: { area($0) < area($1) }) }16else if args.count == 4 { pick = wins.filter { ($0["kCGWindowName"] as? String)?.localizedCaseInsensitiveContains(args[3]) == true }.max(by: { area($0) < area($1) }) }17else { pick = wins.max(by: { area($0) < area($1) }) }18guard let win = pick, let id = win["kCGWindowNumber"] as? Int else { print("no window for \(args[1])"); exit(1) }19if let b = win["kCGWindowBounds"] as? [String: Double] { print("bounds \(Int(b["X"] ?? 0)) \(Int(b["Y"] ?? 0)) \(Int(b["Width"] ?? 0)) \(Int(b["Height"] ?? 0))") }20let p = Process(); p.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture"); p.arguments = ["-l", String(id), "-o", "-x", args[2]]21do { try p.run() } catch { print("screencapture failed: \(error)"); exit(1) }22p.waitUntilExit(); print("saved \(args[2])")23
Files main
Menu

Theme