Open History to see the last commit
1// @effect-diagnostics globalTimers:off -- Accessibility timeouts run outside Effect fibers.
2
3import {
4 SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS,
5 type SnapShotAccessibility,
6} from "@t3tools/contracts";
7import type * as Electron from "electron";
8
9import {
10 accessibleWindowElementTree,
11 accessibleWindowText,
12 compactAccessibilityTree,
13 findAccessibleWindow,
14 isWaylandSession,
15} from "./snapShot.ts";
16
17const ACCESSIBILITY_TIMEOUT_MS = 3_000;
18
19export type AccessibleWindowIdentity = {
20 readonly title: string;
21 readonly bounds: Electron.Rectangle;
22 readonly clientBounds?: Electron.Rectangle;
23 readonly owner: { readonly processId: number };
24 readonly accessibilityBoundsReliable?: boolean;
25};
26
27export type CapturedWindowAccessibilityContext = {
28 readonly accessibleText?: string;
29 readonly accessibility?: SnapShotAccessibility;
30};
31
32export type SnapShotAccessibilityRequest = {
33 readonly active: AccessibleWindowIdentity;
34 readonly platform: NodeJS.Platform;
35 readonly sourceTitle: string;
36 readonly imageSize: Electron.Size;
37};
38
39type AccessibilityApp = (typeof import("@crowecawcaw/xa11y"))["App"];
40
41type AccessibilityReadProgress = {
42 accessibleText: string | undefined;
43 flatComplete: boolean;
44 richComplete: boolean;
45 richLocationsReliable: boolean;
46 richRoot?: Extract<SnapShotAccessibility, { format: "element-tree" }>["root"];
47 richTruncated: boolean;
48 timedOut: boolean;
49};
50
51function accessibilityReadSnapshot(
52 progress: AccessibilityReadProgress,
53 imageSize: Electron.Size,
54): CapturedWindowAccessibilityContext | undefined {
55 const richTree = progress.richRoot
56 ? compactAccessibilityTree(progress.richRoot, {
57 descendantLocationsReliable: progress.richLocationsReliable,
58 })
59 : undefined;
60 const richText = richTree
61 ? accessibleWindowText(richTree.root, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS)
62 : undefined;
63 const accessibleText = progress.accessibleText ?? richText;
64 const richTruncated = progress.richTruncated || richTree?.truncated === true;
65 const accessibility: SnapShotAccessibility | undefined =
66 progress.richComplete &&
67 richTree &&
68 (!richTruncated || !progress.accessibleText || progress.accessibleText === richText)
69 ? {
70 format: "element-tree",
71 coordinateSpace: "captured-image",
72 imageSize,
73 truncated: richTruncated,
74 root: richTree.root,
75 }
76 : progress.flatComplete && progress.accessibleText
77 ? {
78 format: "flat-text",
79 text: progress.accessibleText,
80 truncated: progress.accessibleText.length >= SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS,
81 }
82 : richTree
83 ? {
84 format: "element-tree",
85 coordinateSpace: "captured-image",
86 imageSize,
87 truncated: true,
88 root: richTree.root,
89 }
90 : undefined;
91 if (!accessibleText && !accessibility) return undefined;
92 return JSON.parse(
93 JSON.stringify({
94 ...(accessibleText ? { accessibleText } : {}),
95 ...(accessibility ? { accessibility } : {}),
96 }),
97 ) as CapturedWindowAccessibilityContext;
98}
99
100async function readCapturedWindowAccessibility(
101 App: AccessibilityApp,
102 request: SnapShotAccessibilityRequest,
103 progress: AccessibilityReadProgress,
104 onStarted: () => void,
105): Promise<CapturedWindowAccessibilityContext | undefined> {
106 const { active, platform, sourceTitle, imageSize } = request;
107 const foreground = platform === "win32" ? await App.foreground({ timeout: 0 }) : undefined;
108 const windows =
109 foreground !== undefined
110 ? foreground.pid === active.owner.processId
111 ? [foreground.asElement()]
112 : []
113 : await (await App.byPid(active.owner.processId, { timeout: 0 })).children();
114 const matchMode = isWaylandSession(platform, process.env) ? "wayland" : "screen-bounds";
115 const window = findAccessibleWindow(
116 windows,
117 { title: active.title, sourceTitle, bounds: active.bounds, clientBounds: active.clientBounds },
118 matchMode,
119 );
120 if (!window) {
121 onStarted();
122 return undefined;
123 }
124 const accessibleBounds = window.bounds;
125 const matchingBounds =
126 matchMode === "wayland" &&
127 active.clientBounds &&
128 accessibleBounds &&
129 Math.abs(accessibleBounds.width - active.clientBounds.width) <= 2 &&
130 Math.abs(accessibleBounds.height - active.clientBounds.height) <= 2
131 ? active.clientBounds
132 : active.bounds;
133 const locationsReliable =
134 active.accessibilityBoundsReliable !== false &&
135 (matchMode === "screen-bounds" ||
136 (accessibleBounds !== null &&
137 Math.abs(accessibleBounds.x - matchingBounds.x) <= 2 &&
138 Math.abs(accessibleBounds.y - matchingBounds.y) <= 2));
139 const flatRead = window
140 .tree()
141 .then((tree) => {
142 progress.accessibleText =
143 accessibleWindowText(tree, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS) || undefined;
144 progress.flatComplete = true;
145 })
146 .catch(() => {
147 progress.flatComplete = true;
148 });
149 // A decorated screenshot contains more than the accessibility client area. Keep its
150 // frame origin/scale so element coordinates include the actual decoration offset.
151 const sourceBounds =
152 matchMode === "wayland" && active.clientBounds
153 ? active.bounds
154 : (accessibleBounds ?? active.bounds);
155 const richRead = accessibleWindowElementTree(window, sourceBounds, imageSize, {
156 locationsReliable,
157 onProgress: (root, truncated, descendantLocationsReliable) => {
158 progress.richLocationsReliable = descendantLocationsReliable;
159 progress.richRoot = root;
160 progress.richTruncated = truncated;
161 },
162 shouldContinue: () => !progress.timedOut,
163 verifyDescendantLocations: matchMode === "wayland",
164 })
165 .then((rich) => {
166 progress.richComplete = true;
167 if (rich) {
168 progress.richRoot = rich.root;
169 progress.richTruncated = rich.truncated;
170 }
171 })
172 .catch(() => {
173 progress.richComplete = true;
174 });
175 onStarted();
176 await Promise.all([flatRead, richRead]);
177 return accessibilityReadSnapshot(progress, imageSize);
178}
179
180let activeAccessibilityRead: Promise<unknown> | undefined;
181
182async function raceAccessibleRead<T>(
183 run: () => Promise<T>,
184 timeoutValue: () => T | undefined,
185): Promise<T | undefined> {
186 if (activeAccessibilityRead) return undefined;
187 const read = run().catch(() => undefined);
188 activeAccessibilityRead = read;
189 void read.finally(() => {
190 if (activeAccessibilityRead === read) activeAccessibilityRead = undefined;
191 });
192 let timeout: ReturnType<typeof setTimeout> | undefined;
193 try {
194 return await Promise.race([
195 read,
196 new Promise<T | undefined>((resolve) => {
197 timeout = setTimeout(() => resolve(timeoutValue()), ACCESSIBILITY_TIMEOUT_MS);
198 }),
199 ]);
200 } finally {
201 if (timeout) clearTimeout(timeout);
202 }
203}
204
205export function readAccessibleWindowContextWithApp(
206 App: AccessibilityApp,
207 request: SnapShotAccessibilityRequest,
208 onStarted: () => void = () => undefined,
209): Promise<CapturedWindowAccessibilityContext | undefined> {
210 const progress: AccessibilityReadProgress = {
211 accessibleText: undefined,
212 flatComplete: false,
213 richComplete: false,
214 richLocationsReliable: false,
215 richTruncated: false,
216 timedOut: false,
217 };
218 return raceAccessibleRead(
219 () => readCapturedWindowAccessibility(App, request, progress, onStarted),
220 () => {
221 progress.timedOut = true;
222 return accessibilityReadSnapshot(progress, request.imageSize);
223 },
224 );
225}