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 MAX_ACCESSIBILITY_TREE_DEPTH,
16} from "./snapShot.ts";
17
18const ACCESSIBILITY_TIMEOUT_MS = 3_000;
19
20export type AccessibleWindowIdentity = {
21 readonly title: string;
22 readonly bounds: Electron.Rectangle;
23 readonly clientBounds?: Electron.Rectangle;
24 readonly owner: { readonly processId: number; readonly bundleId?: string };
25 readonly accessibilityBoundsReliable?: boolean;
26};
27
28export type CapturedWindowAccessibilityContext = {
29 readonly accessibleText?: string;
30 readonly accessibility?: SnapShotAccessibility;
31};
32
33export type SnapShotAccessibilityRequest = {
34 readonly active: AccessibleWindowIdentity;
35 readonly platform: NodeJS.Platform;
36 readonly sourceTitle: string;
37 readonly imageSize: Electron.Size;
38};
39
40type AccessibilityApp = (typeof import("@crowecawcaw/xa11y"))["App"];
41
42type AccessibilityReadProgress = {
43 accessibleText: string | undefined;
44 flatComplete: boolean;
45 richComplete: boolean;
46 richLocationsReliable: boolean;
47 richRoot?: Extract<SnapShotAccessibility, { format: "element-tree" }>["root"];
48 richTruncated: boolean;
49 timedOut: boolean;
50};
51
52function accessibilityReadSnapshot(
53 progress: AccessibilityReadProgress,
54 imageSize: Electron.Size,
55): CapturedWindowAccessibilityContext | undefined {
56 const richTree = progress.richRoot
57 ? compactAccessibilityTree(progress.richRoot, {
58 descendantLocationsReliable: progress.richLocationsReliable,
59 })
60 : undefined;
61 const richText = richTree
62 ? accessibleWindowText(richTree.root, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS)
63 : undefined;
64 const accessibleText = progress.accessibleText ?? richText;
65 const richTruncated = progress.richTruncated || richTree?.truncated === true;
66 const accessibility: SnapShotAccessibility | undefined =
67 progress.richComplete &&
68 richTree &&
69 (!richTruncated || !progress.accessibleText || progress.accessibleText === richText)
70 ? {
71 format: "element-tree",
72 coordinateSpace: "captured-image",
73 imageSize,
74 truncated: richTruncated,
75 root: richTree.root,
76 }
77 : progress.flatComplete && progress.accessibleText
78 ? {
79 format: "flat-text",
80 text: progress.accessibleText,
81 truncated: progress.accessibleText.length >= SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS,
82 }
83 : richTree
84 ? {
85 format: "element-tree",
86 coordinateSpace: "captured-image",
87 imageSize,
88 truncated: true,
89 root: richTree.root,
90 }
91 : undefined;
92 if (!accessibleText && !accessibility) return undefined;
93 return JSON.parse(
94 JSON.stringify({
95 ...(accessibleText ? { accessibleText } : {}),
96 ...(accessibility ? { accessibility } : {}),
97 }),
98 ) as CapturedWindowAccessibilityContext;
99}
100
101type AccessibilityElement = Awaited<ReturnType<InstanceType<AccessibilityApp>["children"]>>[number];
102
103async function windowsForPid(
104 App: AccessibilityApp,
105 processId: number,
106): Promise<readonly AccessibilityElement[]> {
107 return await App.byPid(processId, { timeout: 0 })
108 .then((app) => app.children())
109 .catch(() => []);
110}
111
112/** Flatpak apps reach AT-SPI through xdg-dbus-proxy, so the compositor PID misses. */
113async function windowsFromAppList(App: AccessibilityApp): Promise<readonly AccessibilityElement[]> {
114 const apps = await App.list().catch(() => []);
115 return (await Promise.all(apps.map((app) => app.children().catch(() => [])))).flat();
116}
117
118async function readCapturedWindowAccessibility(
119 App: AccessibilityApp,
120 request: SnapShotAccessibilityRequest,
121 progress: AccessibilityReadProgress,
122 onStarted: () => void,
123): Promise<CapturedWindowAccessibilityContext | undefined> {
124 const { active, platform, sourceTitle, imageSize } = request;
125 const foreground = platform === "win32" ? await App.foreground({ timeout: 0 }) : undefined;
126 const pidWindows =
127 foreground !== undefined
128 ? foreground.pid === active.owner.processId
129 ? await foreground.children().catch(() => [])
130 : []
131 : await windowsForPid(App, active.owner.processId);
132 const matchMode = isWaylandSession(platform, process.env) ? "wayland" : "screen-bounds";
133 const captured = {
134 title: active.title,
135 sourceTitle,
136 bounds: active.bounds,
137 clientBounds: active.clientBounds,
138 platform,
139 bundleId: pidWindows.length > 0 ? active.owner.bundleId : undefined,
140 };
141 const window = findAccessibleWindow(
142 pidWindows.length > 0 || foreground !== undefined ? pidWindows : await windowsFromAppList(App),
143 captured,
144 matchMode,
145 { allowUntitledUniqueBounds: foreground === undefined && pidWindows.length > 0 },
146 );
147 if (!window) {
148 onStarted();
149 return undefined;
150 }
151 const accessibleBounds = window.bounds;
152 const matchingBounds =
153 matchMode === "wayland" &&
154 active.clientBounds &&
155 accessibleBounds &&
156 Math.abs(accessibleBounds.width - active.clientBounds.width) <= 2 &&
157 Math.abs(accessibleBounds.height - active.clientBounds.height) <= 2
158 ? active.clientBounds
159 : active.bounds;
160 const locationsReliable =
161 active.accessibilityBoundsReliable !== false &&
162 (matchMode === "screen-bounds" ||
163 (accessibleBounds !== null &&
164 Math.abs(accessibleBounds.x - matchingBounds.x) <= 2 &&
165 Math.abs(accessibleBounds.y - matchingBounds.y) <= 2));
166 const flatRead = window
167 .tree(MAX_ACCESSIBILITY_TREE_DEPTH)
168 .then((tree) => {
169 progress.accessibleText =
170 accessibleWindowText(tree, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS) || undefined;
171 progress.flatComplete = true;
172 })
173 .catch(() => {
174 progress.flatComplete = true;
175 });
176 // Preserve the screenshot frame origin and scale so accessibility coordinates include decorations.
177 const sourceBounds =
178 matchMode === "wayland" && active.clientBounds
179 ? active.bounds
180 : (accessibleBounds ?? active.bounds);
181 const richRead = accessibleWindowElementTree(window, sourceBounds, imageSize, {
182 locationsReliable,
183 onProgress: (root, truncated, descendantLocationsReliable) => {
184 progress.richLocationsReliable = descendantLocationsReliable;
185 progress.richRoot = root;
186 progress.richTruncated = truncated;
187 },
188 shouldContinue: () => !progress.timedOut,
189 verifyDescendantLocations: matchMode === "wayland",
190 })
191 .then((rich) => {
192 progress.richComplete = true;
193 if (rich) {
194 progress.richRoot = rich.root;
195 progress.richTruncated = rich.truncated;
196 }
197 })
198 .catch(() => {
199 progress.richComplete = true;
200 });
201 onStarted();
202 await Promise.all([flatRead, richRead]);
203 return accessibilityReadSnapshot(progress, imageSize);
204}
205
206let activeAccessibilityRead: Promise<unknown> | undefined;
207
208async function raceAccessibleRead<T>(
209 run: () => Promise<T>,
210 timeoutValue: () => T | undefined,
211): Promise<T | undefined> {
212 if (activeAccessibilityRead) return undefined;
213 const read = run().catch(() => undefined);
214 activeAccessibilityRead = read;
215 void read.finally(() => {
216 if (activeAccessibilityRead === read) activeAccessibilityRead = undefined;
217 });
218 let timeout: ReturnType<typeof setTimeout> | undefined;
219 try {
220 return await Promise.race([
221 read,
222 new Promise<T | undefined>((resolve) => {
223 timeout = setTimeout(() => resolve(timeoutValue()), ACCESSIBILITY_TIMEOUT_MS);
224 }),
225 ]);
226 } finally {
227 if (timeout) clearTimeout(timeout);
228 }
229}
230
231export function readAccessibleWindowContextWithApp(
232 App: AccessibilityApp,
233 request: SnapShotAccessibilityRequest,
234 onStarted: () => void = () => undefined,
235): Promise<CapturedWindowAccessibilityContext | undefined> {
236 const progress: AccessibilityReadProgress = {
237 accessibleText: undefined,
238 flatComplete: false,
239 richComplete: false,
240 richLocationsReliable: false,
241 richTruncated: false,
242 timedOut: false,
243 };
244 return raceAccessibleRead(
245 () => readCapturedWindowAccessibility(App, request, progress, onStarted),
246 () => {
247 progress.timedOut = true;
248 return accessibilityReadSnapshot(progress, request.imageSize);
249 },
250 );
251}