Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.2 KB
Raw Blame
#!/usr/bin/env bun
// Captures the reference VS Code workbench through CDP (Page.captureScreenshot), so no Screen Recording permission is needed.
// Usage: port/tools/ref-screenshot <out-dir> [dark|light|hc|hclight|abyss|... (the keys of `themes`)]   (env REF = reference checkout, default ~/Developer/vscode-ref-1.148.0;
// env FOLDER = folder to open, default none; env FILE = file to open in that window, default none;
// env KEYS = keystrokes to type into it first, GPUI style: "cmd-down up alt-cmd-["; env SETTINGS = a JSON object of
// extra user settings)
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { referenceArgs, referenceUserData } from './ref-user-data.ts';

const outDir = process.argv[2] ?? 'port/results/screenshots/reference';
const ref = process.env.REF ?? join(process.env.HOME!, 'Developer/vscode-ref-1.148.0');
const electron = join(ref, '.build/electron/Code - OSS.app/Contents/MacOS/Code - OSS');
const themes: Record<string, string> = {
	dark: 'Default Dark Modern', light: 'Default Light Modern', hc: 'Default High Contrast', hclight: 'Default High Contrast Light',
	abyss: 'Abyss', kimbie: 'Kimbie Dark', monokai: 'Monokai', dimmed: 'Monokai Dimmed', quiet: 'Quiet Light', red: 'Red',
	sdark: 'Solarized Dark', slight: 'Solarized Light', tnb: 'Tomorrow Night Blue',
};
const selected = process.argv.length > 3 ? process.argv.slice(3) : ['dark', 'light', 'hc', 'hclight'];
const width = 1024;
const height = 768;
const port = 9333;

mkdirSync(outDir, { recursive: true });
for (const name of selected) {
	// Another app taking the key window midway dims the title bar and drops the editor's word highlight: capture again.
	let png = await capture(themes[name]);
	for (let retry = 0; !png && retry < 2; retry++) {
		png = await capture(themes[name]);
	}
	if (!png) {
		throw new Error(`${name}: the reference window lost the focus in three captures`);
	}
	writeFileSync(join(outDir, `${name}.png`), png);
	console.log(`${name}: ${png.length} bytes`);
}
// The CDP sockets of killed apps keep Bun's event loop alive.
process.exit(0);

async function capture(theme: string) {
	const userData = referenceUserData(theme, JSON.parse(process.env.SETTINGS || '{}'));
	const paths = [process.env.FOLDER, process.env.FILE].filter(path => path);
	const app = Bun.spawn([electron, ref, ...paths, ...referenceArgs, '--user-data-dir', userData, '--remote-debugging-port=' + port], {
		env: { ...process.env, VSCODE_DEV: '1', NODE_ENV: 'development' },
		stdout: 'ignore',
		stderr: 'ignore',
	});
	try {
		const cdp = await connect();
		await cdp('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 2, mobile: false });
		await until(async () => (await cdp('Runtime.evaluate', { expression: `!!document.querySelector('.monaco-workbench .part.statusbar')`, returnByValue: true })).result.value === true);
		// Extensions settle their status bar items after the workbench appears.
		await Bun.sleep(5000);
		// The title bar dims when the window is not key. Page.bringToFront does not activate the app over
		// another frontmost one (Spotify); `open -a` on the running bundle does, without Accessibility permission.
		Bun.spawnSync(['open', '-a', join(ref, '.build/electron/Code - OSS.app')]);
		await cdp('Page.bringToFront');
		await until(async () => (await cdp('Runtime.evaluate', { expression: `!document.querySelector('.part.titlebar.inactive')`, returnByValue: true })).result.value === true, 10000);
		// The editor's scrollbars show at open; park the pointer on the empty status bar and let them fade.
		// Only with a file: with the move and wait the side bar sash shows grip dots the other windows' references lack.
		for (const keystroke of (process.env.KEYS ?? '').split(' ').filter(key => key)) {
			await press(cdp, keystroke);
		}
		if (process.env.FILE) {
			await cdp('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 500, y: 754 });
			await Bun.sleep(1500);
		}
		// Inputs blink their caret from the last key; hidden here and in the port's --screenshot, so the phase drops out.
		await cdp('Runtime.evaluate', { expression: `document.head.append(Object.assign(document.createElement('style'), { textContent: '* { caret-color: transparent !important; }' }))` });
		const { data } = await cdp('Page.captureScreenshot', { format: 'png' });
		const active = (await cdp('Runtime.evaluate', { expression: `!document.querySelector('.part.titlebar.inactive')`, returnByValue: true })).result.value === true;
		return active ? Buffer.from(data, 'base64') : undefined;
	} finally {
		app.kill('SIGKILL');
		await app.exited;
		rmSync(userData, { recursive: true, force: true });
	}
}

// CDP key events for a GPUI keystroke: modifiers bits alt 1, ctrl 2, meta 4, shift 8.
async function press(cdp: (method: string, params?: object) => Promise<any>, keystroke: string) {
	const parts = keystroke.split('-');
	const key = parts.pop()!;
	const bits: Record<string, number> = { alt: 1, ctrl: 2, cmd: 4, shift: 8 };
	const modifiers = parts.reduce((sum, part) => sum + bits[part], 0);
	const keys: Record<string, [string, string, number]> = {
		up: ['ArrowUp', 'ArrowUp', 38], down: ['ArrowDown', 'ArrowDown', 40], left: ['ArrowLeft', 'ArrowLeft', 37], right: ['ArrowRight', 'ArrowRight', 39],
		'[': ['[', 'BracketLeft', 219], ']': [']', 'BracketRight', 221], '\\': ['\\', 'Backslash', 220], k: ['k', 'KeyK', 75],
	};
	const letter = /^[a-z]$/.test(key);
	// A letter without modifiers types its text; key events only run keybindings.
	if (letter && modifiers === 0) {
		await cdp('Input.insertText', { text: key });
		await Bun.sleep(100);
		return;
	}
	if (letter) {
		keys[key] = [key, `Key${key.toUpperCase()}`, key.toUpperCase().charCodeAt(0)];
	}
	const [name, code, windowsVirtualKeyCode] = keys[key];
	await cdp('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers, key: name, code, windowsVirtualKeyCode });
	await cdp('Input.dispatchKeyEvent', { type: 'keyUp', modifiers, key: name, code, windowsVirtualKeyCode });
	await Bun.sleep(100);
}

async function connect() {
	const target = await until(async () => {
		const targets: { type: string; url: string; webSocketDebuggerUrl: string }[] = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
		return targets.find(t => t.type === 'page' && t.url.includes('workbench'));
	});
	const socket = new WebSocket(target.webSocketDebuggerUrl);
	await new Promise(resolve => socket.addEventListener('open', resolve, { once: true }));
	let nextId = 1;
	const pending = new Map<number, (message: any) => void>();
	socket.addEventListener('message', event => {
		const message = JSON.parse(String(event.data));
		pending.get(message.id)?.(message);
		pending.delete(message.id);
	});
	return (method: string, params: object = {}) => new Promise<any>((resolve, reject) => {
		const id = nextId++;
		pending.set(id, message => message.error ? reject(new Error(`${method}: ${message.error.message}`)) : resolve(message.result));
		socket.send(JSON.stringify({ id, method, params }));
	});
}

async function until<T>(probe: () => Promise<T>, timeoutMs = 60000): Promise<NonNullable<T>> {
	const deadline = Date.now() + timeoutMs;
	while (Date.now() < deadline) {
		const value = await probe().catch(() => undefined);
		if (value) {
			return value;
		}
		await Bun.sleep(250);
	}
	throw new Error('timed out');
}