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