Skip to content

Visual Studio Code, rebuilt in Rust

Rust
1.4 KB
Raw Blame
// Used by port/tools/bench: swiftc -O port/tools/bench-window.swift -o <bin>
//   <bin> wait <pid> <timeout s>: prints the epoch time (s) at which <pid> first owns an on-screen window, exit 1 on timeout.
//   <bin> quit <pid>: sends <pid> the quit Apple event, as Cmd+Q from the Dock does.
import AppKit

let args = CommandLine.arguments
guard args.count >= 3, let pid = pid_t(args[2]) else {
	FileHandle.standardError.write("usage: bench-window wait <pid> <timeout s> | quit <pid>\n".data(using: .utf8)!)
	exit(2)
}

switch args[1] {
case "wait":
	let deadline = Date().addingTimeInterval(Double(args[3])!)
	while Date() < deadline {
		let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as! [[String: Any]]
		// Layer 0 and wider than 400 pt: the workbench window, not a menu bar extra or a splash.
		let shown = windows.contains { window in
			let bounds = window[kCGWindowBounds as String] as! [String: CGFloat]
			return window[kCGWindowOwnerPID as String] as! pid_t == pid && window[kCGWindowLayer as String] as! Int == 0 && bounds["Width"]! > 400
		}
		if shown {
			print(String(format: "%.3f", Date().timeIntervalSince1970))
			exit(0)
		}
		usleep(10_000)
	}
	exit(1)
case "quit":
	guard let app = NSRunningApplication(processIdentifier: pid), app.terminate() else {
		FileHandle.standardError.write("bench-window: no app with pid \(pid) took the quit event\n".data(using: .utf8)!)
		exit(1)
	}
default:
	exit(2)
}