Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

snapShot.ts

648 lines20.8 KB

1// @effect-diagnostics globalTimers:off -- The Electron window-blur handshake uses a native timeout outside any Effect fiber.
2// @effect-diagnostics nodeBuiltinImport:off -- This desktop-only platform check reads procfs and resolves Wayland socket paths with Node.
3​
4import * as NodeFS from "node:fs";
5import * as NodePath from "node:path";
6​
7import {
8 SNAP_SHOT_ACCESSIBILITY_MAX_NODES,
9 SNAP_SHOT_ACCESSIBILITY_MAX_SERIALIZED_CHARS,
10 isModifierPairShortcut,
11 snapShotModifierPairLabel,
12 snapShotShortcutModifierPair,
13 type SnapShotAccessibilityNode,
14 type SnapShotKeyChord,
15 type SnapShotModifier,
16 type SnapShotShortcut,
17} from "@t3tools/contracts";
18​
19interface AccessibilityTreeNode {
20 readonly name?: string;
21 readonly value?: string;
22 readonly children: ReadonlyArray<AccessibilityTreeNode>;
24​
25const MAX_ACCESSIBILITY_TREE_NODES = 10_000;
26const WINDOW_BLUR_TIMEOUT_MS = 1_000;
27​
28export const WINDOWS_MODIFIER_PAIR_VIRTUAL_KEYS: Record<
29 SnapShotModifier,
30 readonly [number, number]
31> = {
32 shift: [0xa0, 0xa1],
33 control: [0xa2, 0xa3],
34 alt: [0xa4, 0xa5],
35 meta: [0x5b, 0x5c],
36};
37​
38export function snapShotShortcutRegistrationFailureMessage(
39 shortcut: SnapShotShortcut,
40 platform: NodeJS.Platform,
41): string {
42 return isModifierPairShortcut(shortcut)
43 ? `${snapShotModifierPairLabel(
44 snapShotShortcutModifierPair(shortcut),
45 platform === "darwin",
46 )} is not available on this system.`
47 : "This shortcut is already used by the system or another app.";
49​
50const COMMON_MOD_ACTIONS: Readonly<Record<string, string>> = {
51 a: "Select All",
52 c: "Copy",
53 f: "Find",
54 n: "New",
55 o: "Open",
56 p: "Print",
57 q: "Quit",
58 s: "Save",
59 t: "New Tab",
60 v: "Paste",
61 w: "Close Window",
62 x: "Cut",
63 z: "Undo",
64};
65​
66export function snapShotShortcutSystemConflict(shortcut: SnapShotKeyChord): string | null {
67 const modifierCount = [
68 shortcut.modKey,
69 shortcut.metaKey,
70 shortcut.ctrlKey,
71 shortcut.altKey,
72 shortcut.shiftKey,
73 ].filter(Boolean).length;
74 if (modifierCount !== 1) return null;
75 if (shortcut.shiftKey) {
76 return "Shift combinations are used for typing and text selection. Add another modifier.";
77 }
78 const key = shortcut.key.toLowerCase();
79 if (shortcut.modKey) {
80 const action = COMMON_MOD_ACTIONS[key];
81 return action ? `This shortcut is ${action} in most apps.` : null;
82 }
83 if (shortcut.ctrlKey && ["c", "d", "z"].includes(key)) {
84 return "This shortcut controls running commands in terminals.";
85 }
86 if (shortcut.altKey && key === "tab") return "The system uses Alt+Tab to switch apps.";
87 if (shortcut.metaKey && ["l", " "].includes(key)) {
88 return "The system already uses this shortcut.";
89 }
90 return null;
92​
93export function accessibleWindowText(root: AccessibilityTreeNode, maxChars: number): string {
94 const seen = new Set<string>();
95 const stack = [root];
96 let text = "";
97 let visited = 0;
98 while (stack.length > 0 && text.length < maxChars && visited < MAX_ACCESSIBILITY_TREE_NODES) {
99 const node = stack.pop()!;
100 visited += 1;
101 for (const value of [node.name, node.value]) {
102 const candidate = value?.replaceAll("\0", "").trim();
103 if (!candidate || seen.has(candidate)) continue;
104​
105 const separator = text ? "\n" : "";
106 const remaining = maxChars - text.length - separator.length;
107 if (remaining <= 0) return text;
108 const candidateEnd =
109 candidate.length <= remaining
110 ? candidate.length
111 : /[\uD800-\uDBFF]/.test(candidate[remaining - 1] ?? "")
112 ? remaining - 1
113 : remaining;
114 if (candidateEnd === 0) return text;
115 text += separator + candidate.slice(0, candidateEnd);
116 if (candidateEnd < candidate.length) return text;
117 seen.add(candidate);
118 }
119 stack.push(...node.children.toReversed());
120 }
121 return text;
123​
124type AccessibilityElement = {
125 readonly role?: string;
126 readonly name?: string | null;
127 readonly value?: string | null;
128 readonly description?: string | null;
129 readonly bounds?: WindowBounds | null;
130 readonly actions?: ReadonlyArray<string>;
131 readonly active?: boolean;
132 readonly busy?: boolean;
133 readonly checked?: "on" | "off" | "mixed" | null;
134 readonly editable?: boolean;
135 readonly enabled?: boolean;
136 readonly expanded?: boolean | null;
137 readonly focused?: boolean;
138 readonly selected?: boolean;
139 readonly visible?: boolean;
140 readonly children?: () => Promise<ReadonlyArray<AccessibilityElement>>;
141};
142​
143type MutableAccessibilityNode = Omit<SnapShotAccessibilityNode, "children"> & {
144 children: Array<MutableAccessibilityNode>;
145};
146​
147type CapturedImageSize = { readonly width: number; readonly height: number };
148​
149function safeProperty<T>(read: () => T): T | undefined {
150 try {
151 return read();
152 } catch {
153 return undefined;
154 }
156​
157export function boundedSnapShotString(
158 value: unknown,
159 maxChars: number,
160 onTruncated?: () => void,
161): string | undefined {
162 if (typeof value !== "string") return undefined;
163 const candidate = value.replaceAll("\0", "").trim();
164 if (!candidate) return undefined;
165 if (candidate.length <= maxChars) return candidate;
166 onTruncated?.();
167 const end = /[\uD800-\uDBFF]/.test(candidate[maxChars - 1] ?? "") ? maxChars - 1 : maxChars;
168 return candidate.slice(0, end).trimEnd();
170​
171function capturedImageBounds(
172 bounds: WindowBounds | null | undefined,
173 sourceBounds: WindowBounds,
174 imageSize: CapturedImageSize,
175): SnapShotAccessibilityNode["bounds"] {
176 if (
177 bounds === null ||
178 bounds === undefined ||
179 sourceBounds.width <= 0 ||
180 sourceBounds.height <= 0 ||
181 imageSize.width <= 0 ||
182 imageSize.height <= 0 ||
183 ![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)
184 ) {
185 return null;
186 }
187 const scaleX = imageSize.width / sourceBounds.width;
188 const scaleY = imageSize.height / sourceBounds.height;
189 const left = Math.max(0, Math.round((bounds.x - sourceBounds.x) * scaleX));
190 const top = Math.max(0, Math.round((bounds.y - sourceBounds.y) * scaleY));
191 const right = Math.min(
192 imageSize.width,
193 Math.round((bounds.x + bounds.width - sourceBounds.x) * scaleX),
194 );
195 const bottom = Math.min(
196 imageSize.height,
197 Math.round((bounds.y + bounds.height - sourceBounds.y) * scaleY),
198 );
199 return right > left && bottom > top
200 ? { x: left, y: top, width: right - left, height: bottom - top }
201 : null;
203​
204function accessibilityNode(
205 element: AccessibilityElement,
206 elementBounds: WindowBounds | null | undefined,
207 sourceBounds: WindowBounds,
208 imageSize: CapturedImageSize,
209 isRoot: boolean,
210 locationsReliable: boolean,
211 onTruncated: () => void,
212): MutableAccessibilityNode {
213 const name = boundedSnapShotString(
214 safeProperty(() => element.name),
215 1_000,
216 onTruncated,
217 );
218 const value = boundedSnapShotString(
219 safeProperty(() => element.value),
220 8_000,
221 onTruncated,
222 );
223 const description = boundedSnapShotString(
224 safeProperty(() => element.description),
225 2_000,
226 onTruncated,
227 );
228 const checked = safeProperty(() => element.checked);
229 const expanded = safeProperty(() => element.expanded);
230 const state = {
231 ...(safeProperty(() => element.active) === true ? { active: true } : {}),
232 ...(safeProperty(() => element.busy) === true ? { busy: true } : {}),
233 ...(checked === "on" || checked === "off" || checked === "mixed" ? { checked } : {}),
234 ...(safeProperty(() => element.editable) === true ? { editable: true } : {}),
235 ...(safeProperty(() => element.enabled) === false ? { enabled: false } : {}),
236 ...(typeof expanded === "boolean" ? { expanded } : {}),
237 ...(safeProperty(() => element.focused) === true ? { focused: true } : {}),
238 ...(safeProperty(() => element.selected) === true ? { selected: true } : {}),
239 ...(safeProperty(() => element.visible) === false ? { visible: false } : {}),
240 };
241 const actions = Array.from(
242 new Set(
243 (safeProperty(() => element.actions) ?? [])
244 .map((action) => boundedSnapShotString(action, 100))
245 .filter((action): action is string => action !== undefined),
246 ),
247 ).slice(0, 32);
248 return {
249 role:
250 boundedSnapShotString(
251 safeProperty(() => element.role),
252 100,
253 ) ?? "unknown",
254 ...(name ? { name } : {}),
255 ...(value && value !== name ? { value } : {}),
256 ...(description && description !== name && description !== value ? { description } : {}),
257 bounds: isRoot
258 ? { x: 0, y: 0, width: imageSize.width, height: imageSize.height }
259 : locationsReliable
260 ? capturedImageBounds(elementBounds, sourceBounds, imageSize)
261 : null,
262 ...(Object.keys(state).length > 0 ? { state } : {}),
263 ...(actions.length > 0 ? { actions } : {}),
264 children: [],
265 };
267​
268function isAnonymousGroup(node: SnapShotAccessibilityNode): boolean {
269 return (
270 node.role === "group" &&
271 node.name === undefined &&
272 node.value === undefined &&
273 node.description === undefined &&
274 node.state === undefined &&
275 node.actions === undefined
276 );
278​
279function compactAccessibilityNodes(
280 node: SnapShotAccessibilityNode,
281 isRoot: boolean,
282 descendantLocationsReliable: boolean,
283): Array<MutableAccessibilityNode> {
284 const children = node.children.flatMap((child) =>
285 compactAccessibilityNodes(child, false, descendantLocationsReliable),
286 );
287 const compacted: MutableAccessibilityNode = {
288 ...node,
289 ...(!isRoot && !descendantLocationsReliable ? { bounds: null } : {}),
290 children,
291 };
292 if (!isRoot && isAnonymousGroup(compacted)) {
293 if (children.length === 0) return [];
294 if (children.length === 1) return children;
295 }
296 return [compacted];
298​
299export function compactAccessibilityTree(
300 root: SnapShotAccessibilityNode,
301 options: { readonly descendantLocationsReliable?: boolean } = {},
302): {
303 readonly root: SnapShotAccessibilityNode;
304 readonly truncated: boolean;
305} {
306 const compactedRoot = compactAccessibilityNodes(
307 root,
308 true,
309 options.descendantLocationsReliable !== false,
310 )[0]!;
311 let nodes = 0;
312 let serializedChars = 256;
313 let truncated = false;
314​
315 const visit = (
316 node: SnapShotAccessibilityNode,
317 required: boolean,
318 ): MutableAccessibilityNode | undefined => {
319 const copy: MutableAccessibilityNode = { ...node, children: [] };
320 const nodeChars = JSON.stringify(copy).length + 1;
321 if (
322 !required &&
323 (nodes >= SNAP_SHOT_ACCESSIBILITY_MAX_NODES ||
324 serializedChars + nodeChars > SNAP_SHOT_ACCESSIBILITY_MAX_SERIALIZED_CHARS)
325 ) {
326 truncated = true;
327 return undefined;
328 }
329 nodes += 1;
330 serializedChars += nodeChars;
331 for (const child of node.children) {
332 const childCopy = visit(child, false);
333 if (!childCopy) break;
334 copy.children.push(childCopy);
335 }
336 return copy;
337 };
338​
339 return { root: visit(compactedRoot, true)!, truncated };
341​
342type AccessibleWindowElementTreeOptions = {
343 readonly locationsReliable?: boolean;
344 readonly onProgress?: (
345 root: SnapShotAccessibilityNode,
346 truncated: boolean,
347 descendantLocationsReliable: boolean,
348 ) => void;
349 readonly shouldContinue?: () => boolean;
350 readonly verifyDescendantLocations?: boolean;
351};
352​
353export async function accessibleWindowElementTree(
354 element: AccessibilityElement,
355 sourceBounds: WindowBounds,
356 imageSize: CapturedImageSize,
357 options: AccessibleWindowElementTreeOptions = {},
358): Promise<{ readonly root: SnapShotAccessibilityNode; readonly truncated: boolean } | undefined> {
359 if (typeof element.children !== "function") return undefined;
360 let nodes = 0;
361 let truncated = false;
362 let root: MutableAccessibilityNode | undefined;
363 const shouldContinue = options.shouldContinue ?? (() => true);
364 let descendantLocationVaries = false;
365 let rootBounds = sourceBounds;
366​
367 const descendantLocationsReliable = () =>
368 options.locationsReliable !== false &&
369 (options.verifyDescendantLocations !== true || descendantLocationVaries);
370​
371 const visit = async (
372 current: AccessibilityElement,
373 required: boolean,
374 ): Promise<MutableAccessibilityNode | undefined> => {
375 if (!shouldContinue()) {
376 truncated = true;
377 return undefined;
378 }
379 if (nodes >= SNAP_SHOT_ACCESSIBILITY_MAX_NODES) {
380 truncated = true;
381 return undefined;
382 }
383 const elementBounds = safeProperty(() => current.bounds);
384 if (required && elementBounds) rootBounds = elementBounds;
385 if (
386 !required &&
387 elementBounds !== null &&
388 elementBounds !== undefined &&
389 (Math.abs(elementBounds.x - rootBounds.x) > 2 || Math.abs(elementBounds.y - rootBounds.y) > 2)
390 ) {
391 descendantLocationVaries = true;
392 }
393 const node = accessibilityNode(
394 current,
395 elementBounds,
396 sourceBounds,
397 imageSize,
398 required,
399 options.locationsReliable !== false,
400 () => {
401 truncated = true;
402 },
403 );
404 nodes += 1;
405 root ??= node;
406 options.onProgress?.(root, true, descendantLocationsReliable());
407​
408 const readChildren = safeProperty(() => current.children);
409 if (typeof readChildren !== "function") return node;
410 let children: ReadonlyArray<AccessibilityElement>;
411 try {
412 children = await readChildren.call(current);
413 } catch {
414 truncated = true;
415 return node;
416 }
417 if (!shouldContinue()) {
418 truncated = true;
419 return node;
420 }
421 for (const child of children) {
422 const childNode = await visit(child, false);
423 if (!childNode) break;
424 node.children.push(childNode);
425 options.onProgress?.(root, true, descendantLocationsReliable());
426 }
427 return node;
428 };
429​
430 const completedRoot = await visit(element, true);
431 if (!completedRoot) return undefined;
432 const locationsReliable = descendantLocationsReliable();
433 const compacted = compactAccessibilityTree(completedRoot, {
434 descendantLocationsReliable: locationsReliable,
435 });
436 const completedTruncated = truncated || compacted.truncated;
437 options.onProgress?.(compacted.root, completedTruncated, locationsReliable);
438 return { root: compacted.root, truncated: completedTruncated };
440​
441export function hideAndWaitForBlur(window: {
442 readonly hide: () => void;
443 readonly once: (event: "blur", listener: () => void) => unknown;
444 readonly removeListener: (event: "blur", listener: () => void) => unknown;
445}): Promise<void> {
446 return new Promise((resolve, reject) => {
447 const timeout = setTimeout(() => {
448 window.removeListener("blur", onBlur);
449 reject(new Error("Timed out waiting for T3 Code to lose focus."));
450 }, WINDOW_BLUR_TIMEOUT_MS);
451 const onBlur = () => {
452 clearTimeout(timeout);
453 resolve();
454 };
455 window.once("blur", onBlur);
456 window.hide();
457 });
459​
460type WindowBounds = {
461 readonly x: number;
462 readonly y: number;
463 readonly width: number;
464 readonly height: number;
465};
466​
467export function findAccessibleWindow<
468 T extends {
469 readonly name: string | null;
470 readonly bounds: WindowBounds | null;
471 readonly active?: boolean;
472 },
473>(
474 windows: readonly T[],
475 captured: {
476 readonly title: string;
477 readonly sourceTitle?: string;
478 readonly bounds: WindowBounds;
479 readonly clientBounds?: WindowBounds | undefined;
480 readonly platform?: NodeJS.Platform;
481 readonly bundleId?: string | undefined;
482 },
483 matchMode: "screen-bounds" | "wayland" = "screen-bounds",
484 options: { readonly allowUntitledUniqueBounds?: boolean } = {},
485): T | undefined {
486 const normalizeTitle = (value: string) => {
487 const title = value.trim();
488 // Terminal apps can animate a leading CLI spinner between capture and AT-SPI lookup.
489 return matchMode === "wayland" ? title.replace(/^[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏](?:\s+|$)/u, "") : title;
490 };
491 const titles = new Set(
492 [captured.title, captured.sourceTitle ?? ""].map(normalizeTitle).filter(Boolean),
493 );
494 // Wayland accessibility providers can expose window size without a screen position.
495 const boundsKeys =
496 matchMode === "wayland"
497 ? (["width", "height"] as const)
498 : (["x", "y", "width", "height"] as const);
499 const candidateBounds =
500 matchMode === "wayland" && captured.clientBounds
501 ? [captured.bounds, captured.clientBounds]
502 : [captured.bounds];
503 const matchesBounds = (window: T) => {
504 const bounds = window.bounds;
505 return (
506 bounds !== null &&
507 candidateBounds.some((candidate) =>
508 boundsKeys.every((key) => Math.abs(bounds[key] - candidate[key]) <= 2),
509 )
510 );
511 };
512 if (titles.size > 0) {
513 const matches = windows.filter(
514 (window) => titles.has(normalizeTitle(window.name ?? "")) && matchesBounds(window),
515 );
516 if (matches.length === 1) return matches[0];
517 const activeMatches = matches.filter((window) => safeProperty(() => window.active) === true);
518 if (activeMatches.length === 1) return activeMatches[0];
519 if (matches.length > 1) return undefined;
520 const browserMatch = findBrowserTitleMatch(windows, titles, captured, matchMode, matchesBounds);
521 if (browserMatch) return browserMatch;
522 }
523 // GTK4/libadwaita often exposes the frame as an unnamed group. A PID-scoped
524 // lookup can accept the one window whose bounds match; size-only guesses cannot.
525 if (!options.allowUntitledUniqueBounds) return undefined;
526 const boundsMatches = windows.filter(
527 (window) => normalizeTitle(window.name ?? "") === "" && matchesBounds(window),
528 );
529 return boundsMatches.length === 1 ? boundsMatches[0] : undefined;
531​
532// Chrome's macOS AX title can append the browser and profile to the captured page title.
533function findBrowserTitleMatch<T extends { readonly name?: string | null }>(
534 windows: readonly T[],
535 titles: ReadonlySet<string>,
536 captured: { readonly platform?: NodeJS.Platform; readonly bundleId?: string | undefined },
537 matchMode: "screen-bounds" | "wayland",
538 matchesBounds: (window: T) => boolean,
539): T | undefined {
540 if (captured.platform !== "darwin" || matchMode !== "screen-bounds") return undefined;
541 const browserName = /^com\.google\.Chrome(?:\.(?:beta|dev|canary))?$/.test(
542 captured.bundleId ?? "",
543 )
544 ? "Google Chrome"
545 : captured.bundleId === "org.chromium.Chromium"
546 ? "Chromium"
547 : undefined;
548 if (!browserName) return undefined;
549 const browserMatches = windows.filter((window) => {
550 if (!matchesBounds(window)) return false;
551 const name = window.name?.trim() ?? "";
552 return [...titles].some((title) => {
553 const prefix = `${title} - ${browserName}`;
554 return (
555 name === prefix ||
556 (name.startsWith(prefix) && /^ [–—-] \S.*$/u.test(name.slice(prefix.length)))
557 );
558 });
559 });
560 return browserMatches.length === 1 ? browserMatches[0] : undefined;
562​
563const ELECTRON_KEY_NAMES: Readonly<Record<string, string>> = {
564 " ": "Space",
565 "+": "Plus",
566 ArrowDown: "Down",
567 ArrowLeft: "Left",
568 ArrowRight: "Right",
569 ArrowUp: "Up",
570 Escape: "Esc",
571};
572​
573export function sameSnapShotShortcut(left: SnapShotShortcut, right: SnapShotShortcut): boolean {
574 if (isModifierPairShortcut(left) || isModifierPairShortcut(right)) {
575 return (
576 isModifierPairShortcut(left) &&
577 isModifierPairShortcut(right) &&
578 snapShotShortcutModifierPair(left) === snapShotShortcutModifierPair(right)
579 );
580 }
581 return toElectronAccelerator(left) === toElectronAccelerator(right);
583​
584export function toElectronAccelerator(shortcut: SnapShotKeyChord): string {
585 const parts: string[] = [];
586 if (shortcut.modKey) parts.push("CommandOrControl");
587 if (shortcut.metaKey) parts.push("Super");
588 if (shortcut.ctrlKey) parts.push("Control");
589 if (shortcut.altKey) parts.push("Alt");
590 if (shortcut.shiftKey) parts.push("Shift");
591 parts.push(ELECTRON_KEY_NAMES[shortcut.key] ?? shortcut.key.toUpperCase());
592 return parts.join("+");
594​
595interface CaptureSourceLike {
596 readonly id: string;
597 readonly name: string;
599​
600interface ActiveWindowLike {
601 readonly id: number;
602 readonly title: string;
604​
605export function findCaptureSource<T extends CaptureSourceLike>(
606 sources: readonly T[],
607 activeWindow: ActiveWindowLike,
608): T | undefined {
609 const idPrefix = `window:${activeWindow.id}:`;
610 const idMatch = sources.find((source) => source.id.startsWith(idPrefix));
611 if (idMatch) return idMatch;
612​
613 const title = activeWindow.title.trim();
614 if (!title) return undefined;
615 const titleMatches = sources.filter((source) => source.name.trim() === title);
616 return titleMatches.length === 1 ? titleMatches[0] : undefined;
618​
619export function isWaylandSession(
620 platform: NodeJS.Platform,
621 environment: NodeJS.ProcessEnv,
622): boolean {
623 if (platform !== "linux") return false;
624 if (
625 environment.XDG_SESSION_TYPE?.toLowerCase() === "wayland" ||
626 Boolean(environment.WAYLAND_DISPLAY)
627 ) {
628 return true;
629 }
630 if (environment.XDG_SESSION_TYPE?.toLowerCase() === "x11") return false;
631 const runtimeDirectory = environment.XDG_RUNTIME_DIR;
632 if (!runtimeDirectory) return false;
633 try {
634 const liveSockets = new Set(
635 NodeFS.readFileSync("/proc/net/unix", "utf8")
636 .split("\n")
637 .flatMap((line) => line.match(/\s(\/.*)$/)?.[1] ?? []),
638 );
639 return NodeFS.readdirSync(runtimeDirectory, { withFileTypes: true }).some(
640 (entry) =>
641 /^wayland-\d+$/.test(entry.name) &&
642 entry.isSocket() &&
643 liveSockets.has(NodePath.join(runtimeDirectory, entry.name)),
644 );
645 } catch {
646 return false;
647 }