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
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.";
48}
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;
91}
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;
122}
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 }
155}
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();
169}
170
171export function 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;
202}
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 };
266}
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 );
277}
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];
297}
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 };
340}
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 };
439}
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 });
458}
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 },
481 matchMode: "screen-bounds" | "wayland" = "screen-bounds",
482 options: { readonly allowUntitledUniqueBounds?: boolean } = {},
483): T | undefined {
484 const normalizeTitle = (value: string) => {
485 const title = value.trim();
486 // Terminal apps can animate a leading CLI spinner between capture and AT-SPI lookup.
487 return matchMode === "wayland" ? title.replace(/^[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏](?:\s+|$)/u, "") : title;
488 };
489 const titles = new Set(
490 [captured.title, captured.sourceTitle ?? ""].map(normalizeTitle).filter(Boolean),
491 );
492 // Wayland accessibility providers can expose window size without a screen position.
493 const boundsKeys =
494 matchMode === "wayland"
495 ? (["width", "height"] as const)
496 : (["x", "y", "width", "height"] as const);
497 const candidateBounds =
498 matchMode === "wayland" && captured.clientBounds
499 ? [captured.bounds, captured.clientBounds]
500 : [captured.bounds];
501 const matchesBounds = (window: T) => {
502 const bounds = window.bounds;
503 return (
504 bounds !== null &&
505 candidateBounds.some((candidate) =>
506 boundsKeys.every((key) => Math.abs(bounds[key] - candidate[key]) <= 2),
507 )
508 );
509 };
510 if (titles.size > 0) {
511 const matches = windows.filter(
512 (window) => titles.has(normalizeTitle(window.name ?? "")) && matchesBounds(window),
513 );
514 if (matches.length === 1) return matches[0];
515 const activeMatches = matches.filter((window) => safeProperty(() => window.active) === true);
516 if (activeMatches.length === 1) return activeMatches[0];
517 if (matches.length > 1) return undefined;
518 }
519 // GTK4/libadwaita often exposes the frame as an unnamed group. A PID-scoped
520 // lookup can accept the one window whose bounds match; size-only guesses cannot.
521 if (!options.allowUntitledUniqueBounds) return undefined;
522 const boundsMatches = windows.filter(
523 (window) => normalizeTitle(window.name ?? "") === "" && matchesBounds(window),
524 );
525 return boundsMatches.length === 1 ? boundsMatches[0] : undefined;
526}
527
528const ELECTRON_KEY_NAMES: Readonly<Record<string, string>> = {
529 " ": "Space",
530 "+": "Plus",
531 ArrowDown: "Down",
532 ArrowLeft: "Left",
533 ArrowRight: "Right",
534 ArrowUp: "Up",
535 Escape: "Esc",
536};
537
538export function sameSnapShotShortcut(left: SnapShotShortcut, right: SnapShotShortcut): boolean {
539 if (isModifierPairShortcut(left) || isModifierPairShortcut(right)) {
540 return (
541 isModifierPairShortcut(left) &&
542 isModifierPairShortcut(right) &&
543 snapShotShortcutModifierPair(left) === snapShotShortcutModifierPair(right)
544 );
545 }
546 return toElectronAccelerator(left) === toElectronAccelerator(right);
547}
548
549export function toElectronAccelerator(shortcut: SnapShotKeyChord): string {
550 const parts: string[] = [];
551 if (shortcut.modKey) parts.push("CommandOrControl");
552 if (shortcut.metaKey) parts.push("Super");
553 if (shortcut.ctrlKey) parts.push("Control");
554 if (shortcut.altKey) parts.push("Alt");
555 if (shortcut.shiftKey) parts.push("Shift");
556 parts.push(ELECTRON_KEY_NAMES[shortcut.key] ?? shortcut.key.toUpperCase());
557 return parts.join("+");
558}
559
560interface CaptureSourceLike {
561 readonly id: string;
562 readonly name: string;
563}
564
565interface ActiveWindowLike {
566 readonly id: number;
567 readonly title: string;
568}
569
570export function findCaptureSource<T extends CaptureSourceLike>(
571 sources: readonly T[],
572 activeWindow: ActiveWindowLike,
573): T | undefined {
574 const idPrefix = `window:${activeWindow.id}:`;
575 const idMatch = sources.find((source) => source.id.startsWith(idPrefix));
576 if (idMatch) return idMatch;
577
578 const title = activeWindow.title.trim();
579 if (!title) return undefined;
580 const titleMatches = sources.filter((source) => source.name.trim() === title);
581 return titleMatches.length === 1 ? titleMatches[0] : undefined;
582}
583
584export function isWaylandSession(
585 platform: NodeJS.Platform,
586 environment: NodeJS.ProcessEnv,
587): boolean {
588 if (platform !== "linux") return false;
589 if (
590 environment.XDG_SESSION_TYPE?.toLowerCase() === "wayland" ||
591 Boolean(environment.WAYLAND_DISPLAY)
592 ) {
593 return true;
594 }
595 if (environment.XDG_SESSION_TYPE?.toLowerCase() === "x11") return false;
596 const runtimeDirectory = environment.XDG_RUNTIME_DIR;
597 if (!runtimeDirectory) return false;
598 try {
599 const liveSockets = new Set(
600 NodeFS.readFileSync("/proc/net/unix", "utf8")
601 .split("\n")
602 .flatMap((line) => line.match(/\s(\/.*)$/)?.[1] ?? []),
603 );
604 return NodeFS.readdirSync(runtimeDirectory, { withFileTypes: true }).some(
605 (entry) =>
606 /^wayland-\d+$/.test(entry.name) &&
607 entry.isSocket() &&
608 liveSockets.has(NodePath.join(runtimeDirectory, entry.name)),
609 );
610 } catch {
611 return false;
612 }
613}