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