Skip to content

Visual Studio Code, rebuilt in Rust

Rust
21.2 KB
Raw Blame
#!/usr/bin/env bun
// Drives the reference and the port through the same steps with cua-driver and saves window screenshots of both,
// for states a still pixel-check frame cannot reach (inline editors, dialogs, drags). Run on the Studio.
// Usage: port/tools/ui-pair <out-dir> <steps.json> [dark|light|hc|hclight]   (env REF = reference checkout,
// default ~/Developer/vscode-ref-1.148.0; env FOLDER = folder to open, default a copy of port/fixtures/workspace, empty for an empty window;
// env FILE = file to open, relative to the folder; env ONLY = "reference" or "port" to run one of them; env ARGS = more arguments for both, space separated;
// env SETTINGS = a JSON object of user settings for both; env USER_TASKS = a tasks.json file both get as their user tasks)
// Steps, in window points (both windows are 1024x768):
//   {"click": [x, y]}  {"click": [x, y], "modifier": ["cmd"]}  {"click": [x, y], "foreground": true}  {"doubleClick": [x, y]}  {"rightClick": [x, y], "foreground": true}  {"key": "return"}  {"key": "escape", "foreground": true} (the window brought to front and left there; also on hotkey)
//   {"scroll": [x, y], "amount": notches} (real wheel notches down, the pointer left there)  {"hover": [x, y]} (the real pointer, for hovers)  {"hotkey": ["cmd", "c"]}  {"type": "text"}  {"type": "Text", "foreground": true} (capitals as shift plus the letter)  {"wait": ms}  {"shot": "name"}  {"clipboard": "name"} (the pasteboard text, the folder path as <folder>)
//   {"dragShot": [x1, y1, x2, y2], "shot": "name", "modifier": ["option"], "button": "middle"}: a slow drag, captured while held
//   {"windows": "name"}: the titles, sizes and visibility of the app's windows, as <app>-<name>.json
//   {"window": "auxiliary", ...}: the step acts on (or shoots) the app's other on-screen window, the first one that is not the main window
//   {"frame": [x, y, width, height], "window": "auxiliary"}: moves and sizes that window, in points from the main window's top left
//   {"dragShot": [...]} without "shot": the drag alone; with "window" and "shotMain": true, a drag from that window captured in the main one
//   {"restart": true}: after the app quit (a Cmd+Q step), start it again on the same user data and folder
//   {"launch": ["docs/guide.md"]}: start the app a second time with these paths (relative to the folder), as a command line would
// Shots land in <out-dir>/<reference|port>-<name>.png at 2x; a sheet on the window is captured as its own window.
import { cpSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { dlopen, FFIType } from 'bun:ffi';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { referenceArgs, referenceUserData } from './ref-user-data.ts';
import { referenceCacheKey, restoreReference, storeReference } from './ui-pair-ref-cache.ts';

type Step = { window?: string; frame?: number[]; shotMain?: boolean; click?: number[]; scroll?: number[]; amount?: number; hover?: number[]; doubleClick?: number[]; rightClick?: number[]; modifier?: string[]; key?: string; hotkey?: string[]; type?: string; wait?: number; shot?: string; dragShot?: number[]; foreground?: boolean; clipboard?: string; windows?: string; button?: string; restart?: boolean; launch?: string[]; refCache?: boolean };

// Index = virtual key code (HIToolbox Events.h, kVK_ANSI_*); '' where the code is no character key.
const usKeyCodes = ['a', 's', 'd', 'f', 'h', 'g', 'z', 'x', 'c', 'v', '', 'b', 'q', 'w', 'e', 'r', 'y', 't', '1', '2', '3', '4', '6', '5', '=', '9', '7', '-', '8', '0', ']', 'o', 'u', '[', 'i', 'p', '\n', 'l', 'j', "'", 'k', ';', '\\', ',', '/', 'n', 'm', '.', '\t', ' ', '`'];
// cua-driver's key names (kVK_Return, kVK_Escape, ...).
const namedKeyCodes: Record<string, number> = { return: 36, tab: 48, space: 49, backspace: 51, escape: 53, f5: 96, f6: 97, f9: 101, f10: 109, left: 123, right: 124, down: 125, up: 126 };
const modifierFlags: Record<string, number> = { shift: 0x20000, ctrl: 0x40000, option: 0x80000, alt: 0x80000, cmd: 0x100000 };
const shiftedKeys: Record<string, string> = { '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0', '_': '-', '+': '=', '{': '[', '}': ']', '|': '\\', ':': ';', '"': "'", '<': ',', '>': '.', '?': '/', '~': '`' };
const coreGraphics = dlopen('/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics', {
	CGEventCreateKeyboardEvent: { args: [FFIType.ptr, FFIType.u16, FFIType.bool], returns: FFIType.ptr },
	CGEventSetFlags: { args: [FFIType.ptr, FFIType.u64], returns: FFIType.void },
	CGEventPostToPid: { args: [FFIType.i32, FFIType.ptr], returns: FFIType.void },
});
const coreFoundation = dlopen('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation', {
	CFRelease: { args: [FFIType.ptr], returns: FFIType.void },
});

const [outDir, stepsFile, themeName = 'dark'] = process.argv.slice(2);
const steps: Step[] = JSON.parse(readFileSync(stepsFile, 'utf8'));
/** Windows `otherWindow` found: never taken for a sheet. */
const otherWindowIds = new Set<number>();
const ref = process.env.REF ?? join(process.env.HOME!, 'Developer/vscode-ref-1.148.0');
const themes: Record<string, [string, string]> = {
	dark: ['Default Dark Modern', 'Dark Modern'],
	light: ['Default Light Modern', 'Light Modern'],
	hc: ['Default High Contrast', 'Default High Contrast'],
	hclight: ['Default High Contrast Light', 'Default High Contrast Light'],
};
const [referenceTheme, portTheme] = themes[themeName];
const extraArgs = process.env.ARGS?.split(' ') ?? [];
const settings: Record<string, unknown> = JSON.parse(process.env.SETTINGS ?? '{}');
mkdirSync(outDir, { recursive: true });
// The reference never changes: its outputs come from ~/Library/Caches/vsrustium-ui-pair-ref unless REF_FRESH=1 or a
// {"refCache": false} step (time-dependent fixtures) says otherwise.
const referenceKey = steps.some(step => step.refCache === false) ? undefined : referenceCacheKey('.', stepsFile, themeName, process.env, ref);
const referenceCached = referenceKey !== undefined && !process.env.REF_FRESH && restoreReference(referenceKey, outDir);
await takeGuiLock();
const lockedAt = Date.now();

const scratch = mkdtempSync(join(tmpdir(), 'ui-pair-'));
for (const app of (process.env.ONLY ?? 'reference port').split(' ')) {
	if (app === 'reference' && referenceCached) {
		console.log(`reference: cached ${referenceKey}`);
		continue;
	}
	const startedAt = Date.now();
	const folder = process.env.FOLDER ?? join(scratch, app, 'workspace');
	if (process.env.FOLDER === undefined) {
		cpSync('port/fixtures/workspace', folder, { recursive: true });
	}
	const paths = process.env.FOLDER === '' ? [] : process.env.FILE ? [folder, join(folder, process.env.FILE)] : [folder];
	const userData = app === 'reference' ? referenceUserDataDir() : portUserDataDir();
	const start = (openPaths = paths) => app === 'reference' ? startReference(openPaths, userData) : startPort(openPaths, userData);
	let child = start();
	// A `restart` step: the app quit by the steps before it (Cmd+Q) starts again on the same user data.
	const restart = async () => {
		await Promise.race([child.exited, Bun.sleep(30000)]);
		child.kill('SIGKILL');
		child = start();
		return child.pid;
	};
	try {
		// A `launch` step: a second start on the same user data, which hands its paths to the running app and exits.
		const launch = async (relative: string[]) => {
			const second = start(relative.map(path => join(folder, path)));
			await Promise.race([second.exited, Bun.sleep(30000)]);
			second.kill('SIGKILL');
		};
		await run(app, child.pid, folder, restart, launch);
	} finally {
		child.kill('SIGKILL');
		await child.exited;
	}
	if (app === 'reference' && referenceKey) {
		storeReference(referenceKey, outDir, startedAt);
	}
}
rmSync(scratch, { recursive: true, force: true });
console.log(`ui-pair: GUI lock held ${((Date.now() - lockedAt) / 1000).toFixed(1)} s`);
process.exit(0);

function referenceUserDataDir() {
	const userData = fixedUserDataDir();
	renameSync(referenceUserData(referenceTheme, settings), userData);
	// Accessibility support off unless SETTINGS sets it, as in the port's user data.
	const settingsFile = join(userData, 'User/settings.json');
	writeFileSync(settingsFile, JSON.stringify({ 'editor.accessibilitySupport': 'off', ...JSON.parse(readFileSync(settingsFile, 'utf8')) }));
	// windowsStateHandler.ts: the first window takes the last active window's size (WindowMode.Normal is 1).
	writeFileSync(join(userData, 'User/globalStorage/storage.json'), JSON.stringify({ windowsState: { lastActiveWindow: { uiState: { mode: 1, x: 100, y: 100, width: 1024, height: 768 } } } }));
	copyUserTasks(userData);
	return userData;
}

function startReference(paths: string[], userData: string) {
	const electron = join(ref, '.build/electron/Code - OSS.app/Contents/MacOS/Code - OSS');
	return Bun.spawn([electron, ref, ...paths, ...referenceArgs, ...extraArgs, '--user-data-dir', userData, '--shared-data-dir', join(userData, 'shared')], {
		env: { ...process.env, VSCODE_DEV: '1', NODE_ENV: 'development' },
		stdout: 'ignore',
		stderr: 'ignore',
	});
}

function portUserDataDir() {
	const userData = fixedUserDataDir();
	mkdirSync(join(userData, 'User'), { recursive: true });
	// Trust is off in referenceUserData; SETTINGS turns it on for both. cua-driver reads the accessibility tree, which
	// the port takes for a screen reader as the reference does, so both run with accessibility support off. Reduced
	// motion and the solid cursor as in referenceUserData.
	writeFileSync(join(userData, 'User/settings.json'), JSON.stringify({ 'security.workspace.trust.enabled': false, 'workbench.startupEditor': 'none', 'editor.accessibilitySupport': 'off', 'workbench.reduceMotion': 'on', 'editor.cursorBlinking': 'solid', ...settings }));
	copyUserTasks(userData);
	return userData;
}

/** One path for both apps, emptied: breadcrumbs of User/settings.json show it, so a random name would differ per shot. */
function fixedUserDataDir() {
	const userData = join(tmpdir(), 'ui-pair-user-data');
	rmSync(userData, { recursive: true, force: true });
	return userData;
}

function copyUserTasks(userData: string) {
	if (process.env.USER_TASKS) {
		cpSync(process.env.USER_TASKS, join(userData, 'User/tasks.json'));
	}
}

function startPort(paths: string[], userData: string) {
	return Bun.spawn(['native/target/release/vsrustium', ...paths, ...extraArgs, '--user-data-dir', userData, '--shared-data-dir', join(userData, 'shared'), '--theme', portTheme], {
		env: { ...process.env, VSCODE_GPUI_EXTENSIONS: join(ref, 'extensions') },
		stdout: 'ignore',
		stderr: Bun.file(join(outDir, 'port.log')),
	});
}

async function run(app: string, firstPid: number, folder: string, restart: () => Promise<number>, launch: (paths: string[]) => Promise<void>) {
	let { window, target: main, scale } = await attach(app, firstPid);
	const at = (point: number[]) => ({ x: point[0] * scale, y: point[1] * scale });
	for (const step of steps) {
		const target = step.window ? await otherWindow(main) : main;
		if (step.frame) {
			const [x, y, width, height] = step.frame;
			await cua('set_window_frame', { ...target, x: window.bounds.x + x, y: window.bounds.y + y, width, height });
		} else if (step.click) {
			await cua('click', { ...target, ...at(step.click), modifier: step.modifier, delivery_mode: step.foreground ? 'foreground' : undefined });
		} else if (step.scroll) {
			// Electron drops background wheel events; both get the real pointer's.
			await cua('scroll', { ...target, ...at(step.scroll), direction: 'down', amount: step.amount ?? 3, delivery_mode: 'foreground' });
		} else if (step.hover) {
			// Editor hovers follow mouse moves, which only the real pointer sends; desktop coordinates are pixels.
			await cua('move_cursor', { scope: 'desktop', delivery_mode: 'foreground', x: (window.bounds.x + step.hover[0]) * scale, y: (window.bounds.y + step.hover[1]) * scale });
		} else if (step.doubleClick) {
			await cua('double_click', { ...target, ...at(step.doubleClick) });
		} else if (step.rightClick) {
			await cua('right_click', { ...target, ...at(step.rightClick), delivery_mode: step.foreground ? 'foreground' : undefined });
		} else if (step.key || step.hotkey) {
			if (step.foreground) {
				// The window stays in front between the keys of a chord: an inactive one leaves chord mode
				// (keybindingResolver `_scheduleLeaveChordMode`).
				await bringToFront(target);
				const keys = step.key ? [step.key] : step.hotkey!;
				pressKey(target.pid, keys.at(-1)!, keys.slice(0, -1));
			} else {
				// Background keys stay on cua-driver: unlike a posted key, its escape moves the port's traffic lights
				// 1 pt right in m11/split-settings-edit, which the shots show.
				await (step.key ? cua('press_key', { ...target, key: step.key }) : cua('hotkey', { ...target, keys: step.hotkey }));
			}
		} else if (step.type) {
			if (step.foreground) {
				await bringToFront(target);
			}
			await typeText(target.pid, step.type);
		} else if (step.wait) {
			await Bun.sleep(step.wait);
		} else if (step.launch) {
			await launch(step.launch);
		} else if (step.restart) {
			({ window, target: main, scale } = await attach(app, await restart()));
		} else if (step.dragShot) {
			const [x1, y1, x2, y2] = step.dragShot;
			// A background drag reaches only Electron's own drag and drop; GPUI needs the real pointer.
			// `foreground: true` sends the reference's drag through the real pointer too (a sash, not a drag and drop).
			const delivery_mode = app === 'port' || step.foreground ? 'foreground' : 'background';
			const drag = cua('drag', { ...target, from_x: x1 * scale, from_y: y1 * scale, to_x: x2 * scale, to_y: y2 * scale, duration_ms: 4000, steps: 40, modifier: step.modifier, button: step.button, delivery_mode });
			if (step.shot) {
				await Bun.sleep(3500);
				const shotTarget = step.shotMain ? main : target;
				await shot(app, shotTarget.pid, shotTarget.window_id, step.shot);
			}
			await drag;
		} else if (step.shot) {
			await shot(app, target.pid, target.window_id, step.shot);
		} else if (step.windows) {
			type Listed = { title: string; is_on_screen: boolean; bounds: { width: number; height: number } };
			const { windows } = await cua('list_windows', { pid: target.pid });
			const listed = windows.filter((w: Listed) => w.bounds.width > 100).map((w: Listed) => ({ title: w.title, on_screen: w.is_on_screen, width: w.bounds.width, height: w.bounds.height }));
			writeFileSync(resolve(outDir, `${app}-${step.windows}.json`), JSON.stringify(listed, null, '\t'));
			console.log(`${app}-${step.windows}.json: ${JSON.stringify(listed)}`);
		} else if (step.clipboard) {
			const text = (await Bun.$`pbpaste`.text()).replaceAll(folder, '<folder>');
			writeFileSync(resolve(outDir, `${app}-${step.clipboard}.txt`), text);
			console.log(`${app}-${step.clipboard}.txt: ${JSON.stringify(text)}`);
			const html = await Bun.$`osascript -l JavaScript -e ${"ObjC.import('AppKit'); const h = $.NSPasteboard.generalPasteboard.stringForType('public.html'); h.isNil() ? '' : h.js"}`.text();
			if (html.trim()) {
				writeFileSync(resolve(outDir, `${app}-${step.clipboard}.html`), html.trimEnd());
				console.log(`${app}-${step.clipboard}.html: ${html.trimEnd()}`);
			}
		}
		// A shot, windows or clipboard step only reads: nothing to settle after it.
		if ((step.shot && !step.dragShot) || step.windows || step.clipboard || step.refCache === false) {
			continue;
		}
		await Bun.sleep(400);
	}
}

/** The app's 1024px window once the workbench settled. */
async function attach(app: string, pid: number) {
	const window = await until(async () => {
		const { windows } = await cua('list_windows', { pid });
		return windows.find((w: { bounds: { width: number }; is_on_screen: boolean }) => w.is_on_screen && w.bounds.width === 1024);
	}, 120000);
	const target = { pid, window_id: window.window_id };
	// The workbench and its extensions settle after the window appears: wait until three captures 500 ms apart
	// match, at most as long as the fixed 10 s (reference) and 6 s (port) waits that came before.
	// The captures also set the screenshot pixel space the pixel actions use: 2x on a Retina display, 1x on a
	// headless or 1x one. The PNG's width (bytes 16 to 19 of its header) gives the scale.
	const probe = join(outDir, `.${app}-scale.png`);
	const deadline = Date.now() + (app === 'reference' ? 10000 : 6000);
	let previous: number | bigint = -1;
	let matches = 0;
	while (matches < 2 && Date.now() < deadline) {
		await Bun.sleep(500);
		await cua('get_window_state', { ...target, include_accessibility_tree: false, max_image_dimension: 2048, screenshot_out_file: probe });
		const hash = Bun.hash(readFileSync(probe));
		matches = hash === previous ? matches + 1 : 0;
		previous = hash;
	}
	const scale = readFileSync(probe).readUInt32BE(16) / window.bounds.width;
	rmSync(probe);
	return { window, target, scale };
}

/** The app's on-screen window other than `main` (an auxiliary window), at least 400 points wide. */
async function otherWindow(main: { pid: number; window_id: number }) {
	type Listed = { window_id: number; is_on_screen: boolean; bounds: { width: number } };
	const other = await until(async () => {
		const { windows } = await cua('list_windows', { pid: main.pid });
		return windows.find((w: Listed) => w.is_on_screen && w.window_id !== main.window_id && w.bounds.width >= 400);
	}, 10000);
	otherWindowIds.add(other.window_id);
	return { pid: main.pid, window_id: other.window_id };
}

/** The window, or the sheet over it when one is open. */
async function shot(app: string, pid: number, windowId: number, name: string) {
	type Listed = { window_id: number; is_on_screen: boolean; bounds: { width: number } };
	const { windows } = await cua('list_windows', { pid });
	const main = windowId;
	const sheet = windows.find((w: Listed) => w.is_on_screen && w.window_id !== main && w.bounds.width < 1024 && !otherWindowIds.has(w.window_id) && !otherWindowIds.has(main));
	const file = resolve(outDir, `${app}-${name}.png`);
	await cua('get_window_state', { pid, window_id: sheet?.window_id ?? main, include_accessibility_tree: false, max_image_dimension: 2048, screenshot_out_file: file });
	console.log(`${app}-${name}.png${sheet ? ' (sheet)' : ''}`);
}

async function bringToFront(target: object) {
	// A sheet (the delete confirmation) keeps the window from turning key: the app is in front all the same.
	await cua('bring_to_front', target).catch(error => {
		if (!String(error).includes('"front_process_matches_target": true')) {
			throw error;
		}
	});
}

/**
 * Types the text as US layout key events, capitals and shifted symbols as shift plus the base key.
 * type_text refuses windows without an accessible text field, as GPUI's.
 */
async function typeText(pid: number, text: string) {
	for (const char of text) {
		const lower = char.toLowerCase();
		pressKey(pid, shiftedKeys[char] ?? lower, shiftedKeys[char] || char !== lower ? ['shift'] : []);
		await Bun.sleep(20);
	}
}

/**
 * A key down and up with the modifiers' flags, posted to the app's pid, in front or not: an m12/pinned-tabs run lost
 * its foreground keys posted to the HID tap. cua-driver's press_key and hotkey spend 0.4 s (reference) to 1.4 s
 * (port) per key reading the focused element back over AX.
 */
function pressKey(pid: number, key: string, modifiers: string[]) {
	const keyCode = namedKeyCodes[key] ?? usKeyCodes.indexOf(key);
	if (keyCode < 0) {
		throw new Error(`ui-pair: no US key for ${JSON.stringify(key)}`);
	}
	let flags = 0;
	for (const modifier of modifiers) {
		if (!modifierFlags[modifier]) {
			throw new Error(`ui-pair: no modifier ${JSON.stringify(modifier)}`);
		}
		flags |= modifierFlags[modifier];
	}
	for (const down of [true, false]) {
		const event = coreGraphics.symbols.CGEventCreateKeyboardEvent(null, keyCode, down);
		coreGraphics.symbols.CGEventSetFlags(event, flags);
		coreGraphics.symbols.CGEventPostToPid(pid, event);
		coreFoundation.symbols.CFRelease(event);
	}
}

async function cua(tool: string, args: object) {
	// One session for every call: the pixel actions use the screenshot space of the session's last read.
	const child = Bun.spawn(['cua-driver', 'call', tool, JSON.stringify({ session: `ui-pair-${process.pid}`, ...args })], { stderr: 'pipe' });
	const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
	if (code !== 0) {
		throw new Error(`cua-driver ${tool}: ${stderr}${stdout}`);
	}
	return JSON.parse(stdout);
}

/** gui-lock.sh's lock: windows of parallel sessions take turns. */
async function takeGuiLock() {
	// port/tools/gui-lane holds it for this run.
	if (process.env.PORT_GUI_LOCK_HELD) {
		return;
	}
	const lock = '/tmp/port-gui.lock';
	while (true) {
		try {
			mkdirSync(lock);
			writeFileSync(join(lock, 'pid'), String(process.pid));
			process.on('exit', () => rmSync(lock, { recursive: true, force: true }));
			return;
		} catch {
			const owner = Number(await Bun.file(join(lock, 'pid')).text().catch(() => '0'));
			if (owner && !isAlive(owner)) {
				rmSync(lock, { recursive: true, force: true });
				continue;
			}
			await Bun.sleep(5000);
		}
	}
}

function isAlive(pid: number) {
	try {
		process.kill(pid, 0);
		return true;
	} catch {
		return false;
	}
}

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');
}