Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SnapShotAccessibility.ts

223 lines7.2 KB

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 accessibleText =
61 progress.accessibleText ??
62 (richTree
63 ? accessibleWindowText(richTree.root, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS)
64 : undefined);
65 const accessibility: SnapShotAccessibility | undefined =
66 progress.richComplete && richTree
67 ? {
68 format: "element-tree",
69 coordinateSpace: "captured-image",
70 imageSize,
71 truncated: progress.richTruncated || richTree.truncated,
72 root: richTree.root,
73 }
74 : progress.flatComplete && accessibleText
75 ? {
76 format: "flat-text",
77 text: accessibleText,
78 truncated: accessibleText.length >= SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS,
79 }
80 : richTree
81 ? {
82 format: "element-tree",
83 coordinateSpace: "captured-image",
84 imageSize,
85 truncated: true,
86 root: richTree.root,
87 }
88 : undefined;
89 if (!accessibleText && !accessibility) return undefined;
90 return JSON.parse(
91 JSON.stringify({
92 ...(accessibleText ? { accessibleText } : {}),
93 ...(accessibility ? { accessibility } : {}),
94 }),
95 ) as CapturedWindowAccessibilityContext;
97​
98async function readCapturedWindowAccessibility(
99 App: AccessibilityApp,
100 request: SnapShotAccessibilityRequest,
101 progress: AccessibilityReadProgress,
102 onStarted: () => void,
103): Promise<CapturedWindowAccessibilityContext | undefined> {
104 const { active, platform, sourceTitle, imageSize } = request;
105 const foreground = platform === "win32" ? await App.foreground({ timeout: 0 }) : undefined;
106 const windows =
107 foreground !== undefined
108 ? foreground.pid === active.owner.processId
109 ? [foreground.asElement()]
110 : []
111 : await (await App.byPid(active.owner.processId, { timeout: 0 })).children();
112 const matchMode = isWaylandSession(platform, process.env) ? "wayland" : "screen-bounds";
113 const window = findAccessibleWindow(
114 windows,
115 { title: active.title, sourceTitle, bounds: active.bounds, clientBounds: active.clientBounds },
116 matchMode,
117 );
118 if (!window) {
119 onStarted();
120 return undefined;
121 }
122 const accessibleBounds = window.bounds;
123 const matchingBounds =
124 matchMode === "wayland" &&
125 active.clientBounds &&
126 accessibleBounds &&
127 Math.abs(accessibleBounds.width - active.clientBounds.width) <= 2 &&
128 Math.abs(accessibleBounds.height - active.clientBounds.height) <= 2
129 ? active.clientBounds
130 : active.bounds;
131 const locationsReliable =
132 active.accessibilityBoundsReliable !== false &&
133 (matchMode === "screen-bounds" ||
134 (accessibleBounds !== null &&
135 Math.abs(accessibleBounds.x - matchingBounds.x) <= 2 &&
136 Math.abs(accessibleBounds.y - matchingBounds.y) <= 2));
137 const flatRead = window
138 .tree()
139 .then((tree) => {
140 progress.accessibleText =
141 accessibleWindowText(tree, SNAP_SHOT_ACCESSIBLE_TEXT_MAX_CHARS) || undefined;
142 progress.flatComplete = true;
143 })
144 .catch(() => {
145 progress.flatComplete = true;
146 });
147 // A decorated screenshot contains more than the accessibility client area. Keep its
148 // frame origin/scale so element coordinates include the actual decoration offset.
149 const sourceBounds =
150 matchMode === "wayland" && active.clientBounds
151 ? active.bounds
152 : (accessibleBounds ?? active.bounds);
153 const richRead = accessibleWindowElementTree(window, sourceBounds, imageSize, {
154 locationsReliable,
155 onProgress: (root, truncated, descendantLocationsReliable) => {
156 progress.richLocationsReliable = descendantLocationsReliable;
157 progress.richRoot = root;
158 progress.richTruncated = truncated;
159 },
160 shouldContinue: () => !progress.timedOut,
161 verifyDescendantLocations: matchMode === "wayland",
162 })
163 .then((rich) => {
164 progress.richComplete = true;
165 if (rich) {
166 progress.richRoot = rich.root;
167 progress.richTruncated = rich.truncated;
168 }
169 })
170 .catch(() => {
171 progress.richComplete = true;
172 });
173 onStarted();
174 await Promise.all([flatRead, richRead]);
175 return accessibilityReadSnapshot(progress, imageSize);
177​
178let activeAccessibilityRead: Promise<unknown> | undefined;
179​
180async function raceAccessibleRead<T>(
181 run: () => Promise<T>,
182 timeoutValue: () => T | undefined,
183): Promise<T | undefined> {
184 if (activeAccessibilityRead) return undefined;
185 const read = run().catch(() => undefined);
186 activeAccessibilityRead = read;
187 void read.finally(() => {
188 if (activeAccessibilityRead === read) activeAccessibilityRead = undefined;
189 });
190 let timeout: ReturnType<typeof setTimeout> | undefined;
191 try {
192 return await Promise.race([
193 read,
194 new Promise<T | undefined>((resolve) => {
195 timeout = setTimeout(() => resolve(timeoutValue()), ACCESSIBILITY_TIMEOUT_MS);
196 }),
197 ]);
198 } finally {
199 if (timeout) clearTimeout(timeout);
200 }
202​
203export function readAccessibleWindowContextWithApp(
204 App: AccessibilityApp,
205 request: SnapShotAccessibilityRequest,
206 onStarted: () => void = () => undefined,
207): Promise<CapturedWindowAccessibilityContext | undefined> {
208 const progress: AccessibilityReadProgress = {
209 accessibleText: undefined,
210 flatComplete: false,
211 richComplete: false,
212 richLocationsReliable: false,
213 richTruncated: false,
214 timedOut: false,
215 };
216 return raceAccessibleRead(
217 () => readCapturedWindowAccessibility(App, request, progress, onStarted),
218 () => {
219 progress.timedOut = true;
220 return accessibilityReadSnapshot(progress, request.imageSize);
221 },
222 );