@namzu/computer-use 4.1.1 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +18 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +28 -2
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y-script.d.ts +47 -0
  7. package/dist/a11y/a11y-script.d.ts.map +1 -0
  8. package/dist/a11y/a11y-script.js +738 -0
  9. package/dist/a11y/a11y-script.js.map +1 -0
  10. package/dist/a11y/a11y.d.ts +60 -0
  11. package/dist/a11y/a11y.d.ts.map +1 -0
  12. package/dist/a11y/a11y.js +400 -0
  13. package/dist/a11y/a11y.js.map +1 -0
  14. package/dist/a11y/index.d.ts +8 -0
  15. package/dist/a11y/index.d.ts.map +1 -0
  16. package/dist/a11y/index.js +5 -0
  17. package/dist/a11y/index.js.map +1 -0
  18. package/dist/a11y/interface.d.ts +198 -0
  19. package/dist/a11y/interface.d.ts.map +1 -0
  20. package/dist/a11y/interface.js +22 -0
  21. package/dist/a11y/interface.js.map +1 -0
  22. package/dist/a11y/windows.d.ts +20 -0
  23. package/dist/a11y/windows.d.ts.map +1 -0
  24. package/dist/a11y/windows.js +40 -0
  25. package/dist/a11y/windows.js.map +1 -0
  26. package/dist/adapters/cua-driver/adapter.d.ts +47 -0
  27. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  28. package/dist/adapters/cua-driver/adapter.js +138 -3
  29. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  30. package/dist/adapters/types.d.ts +11 -0
  31. package/dist/adapters/types.d.ts.map +1 -1
  32. package/dist/adapters/types.js.map +1 -1
  33. package/dist/adapters/win32.d.ts +3 -0
  34. package/dist/adapters/win32.d.ts.map +1 -1
  35. package/dist/adapters/win32.js +1 -0
  36. package/dist/adapters/win32.js.map +1 -1
  37. package/dist/foreground/guard.d.ts.map +1 -1
  38. package/dist/foreground/guard.js +1 -0
  39. package/dist/foreground/guard.js.map +1 -1
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +1 -0
  43. package/dist/index.js.map +1 -1
  44. package/package.json +2 -2
  45. package/src/SubprocessComputerUseHost.ts +48 -1
  46. package/src/a11y/a11y-script.ts +740 -0
  47. package/src/a11y/a11y.ts +499 -0
  48. package/src/a11y/index.ts +24 -0
  49. package/src/a11y/interface.ts +226 -0
  50. package/src/a11y/windows.ts +56 -0
  51. package/src/adapters/cua-driver/adapter.ts +151 -6
  52. package/src/adapters/types.ts +8 -0
  53. package/src/adapters/win32.ts +4 -0
  54. package/src/foreground/guard.ts +1 -0
  55. package/src/index.ts +19 -0
@@ -0,0 +1,740 @@
1
+ /**
2
+ * The Windows side of the accessibility host: one long-lived PowerShell
3
+ * process that compiles a small C# library and answers JSON lines.
4
+ *
5
+ * It exists because every cheaper way of asking Windows "what windows are
6
+ * there, what is in this one, did it change" costs a process start (seconds
7
+ * under WSL) or an uncached accessibility walk (over a second). Resident, the
8
+ * same questions take a fraction of a millisecond to a few milliseconds:
9
+ *
10
+ * - `windows` enumerates the top-level windows with plain Win32 calls (no
11
+ * accessibility call at all), keeping the visible, un-cloaked, non-tool
12
+ * ones and, unless asked otherwise, only those without an owner;
13
+ * - `displays` lists the monitors with their work area and scale;
14
+ * - `snapshot` reads one window's accessibility tree with a single cached
15
+ * subtree request (the controls a person would see, not the raw tree) and
16
+ * keeps the elements so `identity` and `resolve` can name one and find it
17
+ * again after the window changed;
18
+ * - `seq` returns a counter of observed changes and, given a window, makes
19
+ * sure that window is being watched; `wait_change` resolves from events,
20
+ * not from sleeping: once a change has been seen and the window has been
21
+ * quiet for `quietMs`, or after `timeoutMs` with none. A window is watched
22
+ * by accessibility events (structure and property changes of its subtree)
23
+ * and by system window events scoped to its process (so a new top-level
24
+ * window of the same program counts). Events are queued on the thread
25
+ * that received them and never call back into accessibility.
26
+ *
27
+ * Chromium and Electron windows are not read: asking one for its tree turns
28
+ * its accessibility on for the rest of the session, which costs the user
29
+ * speed in an application they did not hand over. `snapshot` refuses with
30
+ * `chromium_not_activated` unless the request sets `allowChromium`, and a
31
+ * wait on one listens to system window events only.
32
+ *
33
+ * Like the presence helper it is handed to PowerShell as a bootstrap that
34
+ * reads this script from its first line of input; the line protocol follows
35
+ * on the same stream, and the process ends when its input closes.
36
+ */
37
+ export const A11Y_HELPER_SCRIPT = String.raw`
38
+ $ErrorActionPreference = 'Stop'
39
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
40
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
41
+ Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes, WindowsBase, System.Web.Extensions
42
+ $refs = @(
43
+ [System.Windows.Automation.AutomationElement].Assembly.Location,
44
+ [System.Windows.Automation.TreeScope].Assembly.Location,
45
+ [System.Windows.Rect].Assembly.Location,
46
+ [System.Web.Script.Serialization.JavaScriptSerializer].Assembly.Location
47
+ )
48
+ Add-Type -ReferencedAssemblies $refs -TypeDefinition @'
49
+ using System;
50
+ using System.Collections.Generic;
51
+ using System.Diagnostics;
52
+ using System.Globalization;
53
+ using System.Runtime.InteropServices;
54
+ using System.Text;
55
+ using System.Threading;
56
+ using System.Web.Script.Serialization;
57
+ using System.Windows.Automation;
58
+
59
+ public static class NzA {
60
+ const int Version = 1;
61
+ const int RingN = 8192;
62
+ const int MaxSubs = 32;
63
+
64
+ // ---- Native ----
65
+ [StructLayout(LayoutKind.Sequential)] struct RC { public int l; public int t; public int r; public int b; }
66
+ [StructLayout(LayoutKind.Sequential)] struct PT { public int x; public int y; }
67
+ [StructLayout(LayoutKind.Sequential)] struct MSG { public IntPtr h; public uint m; public IntPtr w; public IntPtr l; public uint t; public PT p; }
68
+ [StructLayout(LayoutKind.Sequential)] struct WPL { public int length; public int flags; public int showCmd; public PT minPos; public PT maxPos; public RC normal; }
69
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct MI { public int size; public RC mon; public RC work; public int flags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string dev; }
70
+ delegate bool EnumProc(IntPtr h, IntPtr lp);
71
+ delegate bool MonProc(IntPtr mon, IntPtr dc, ref RC r, IntPtr lp);
72
+ delegate void HookProc(IntPtr hook, uint ev, IntPtr hwnd, int obj, int child, uint thread, uint time);
73
+ [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc p, IntPtr lp);
74
+ [DllImport("user32.dll")] static extern bool EnumChildWindows(IntPtr h, EnumProc p, IntPtr lp);
75
+ [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
76
+ [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h);
77
+ [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h);
78
+ [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint c);
79
+ [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint f);
80
+ [DllImport("user32.dll")] static extern IntPtr GetDesktopWindow();
81
+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
82
+ [DllImport("user32.dll", EntryPoint="GetWindowLongW")] static extern int GetWindowLong(IntPtr h, int i);
83
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
84
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int GetClassNameW(IntPtr h, StringBuilder s, int n);
85
+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
86
+ [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RC r);
87
+ [DllImport("user32.dll")] static extern bool GetWindowPlacement(IntPtr h, ref WPL p);
88
+ [DllImport("user32.dll")] static extern bool EnumDisplayMonitors(IntPtr dc, IntPtr clip, MonProc p, IntPtr lp);
89
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool GetMonitorInfoW(IntPtr mon, ref MI mi);
90
+ [DllImport("user32.dll")] static extern IntPtr SetWinEventHook(uint min, uint max, IntPtr mod, HookProc p, uint pid, uint thread, uint flags);
91
+ [DllImport("user32.dll")] static extern bool UnhookWinEvent(IntPtr hook);
92
+ [DllImport("user32.dll")] static extern int GetMessage(out MSG m, IntPtr h, uint a, uint b);
93
+ [DllImport("user32.dll")] static extern bool PeekMessage(out MSG m, IntPtr h, uint a, uint b, uint remove);
94
+ [DllImport("user32.dll")] static extern bool TranslateMessage(ref MSG m);
95
+ [DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref MSG m);
96
+ [DllImport("user32.dll")] static extern bool PostThreadMessage(uint thread, uint msg, IntPtr w, IntPtr l);
97
+ [DllImport("user32.dll")] static extern bool SetProcessDpiAwarenessContext(IntPtr c);
98
+ [DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr c);
99
+ [DllImport("dwmapi.dll", EntryPoint="DwmGetWindowAttribute")] static extern int DwmGetInt(IntPtr h, int a, out int v, int n);
100
+ [DllImport("dwmapi.dll", EntryPoint="DwmGetWindowAttribute")] static extern int DwmGetRect(IntPtr h, int a, out RC v, int n);
101
+ [DllImport("shcore.dll")] static extern int GetDpiForMonitor(IntPtr mon, int type, out uint dx, out uint dy);
102
+ [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
103
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
104
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] static extern bool QueryFullProcessImageNameW(IntPtr p, int flags, StringBuilder s, ref int n);
105
+ [DllImport("kernel32.dll")] static extern bool GetProcessTimes(IntPtr p, out long create, out long exit, out long kernel, out long user);
106
+ [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
107
+ [DllImport("winmm.dll")] static extern uint timeBeginPeriod(uint ms);
108
+
109
+ sealed class Cmd : Exception { public string Code; public Cmd(string code, string msg) : base(msg) { Code = code; } }
110
+
111
+ // ---- Time, output ----
112
+ static double NowMs() { return Stopwatch.GetTimestamp() * 1000.0 / Stopwatch.Frequency; }
113
+ static readonly object outLock = new object();
114
+ static void Send(string json) { lock (outLock) { Console.Out.Write(json); Console.Out.Write("\n"); Console.Out.Flush(); } }
115
+ static string D(double v) { return v.ToString("0.#", CultureInfo.InvariantCulture); }
116
+ static string Q(string s) {
117
+ if (s == null) return "\"\"";
118
+ StringBuilder b = new StringBuilder(s.Length + 2); b.Append('"');
119
+ foreach (char c in s) {
120
+ if (c == '"') b.Append("\\\""); else if (c == '\\') b.Append("\\\\");
121
+ else if (c == '\n') b.Append("\\n"); else if (c == '\r') b.Append("\\r"); else if (c == '\t') b.Append("\\t");
122
+ else if (c < 0x20 || c == 0x2028 || c == 0x2029) b.Append("\\u").Append(((int)c).ToString("x4"));
123
+ else b.Append(c);
124
+ }
125
+ return b.Append('"').ToString();
126
+ }
127
+ static string IdJson(object id) {
128
+ if (id == null) return "null";
129
+ if (id is string) return Q((string)id);
130
+ try { return Convert.ToInt64(id).ToString(CultureInfo.InvariantCulture); } catch { return "null"; }
131
+ }
132
+ static long seqCtr;
133
+ static string Head(object id, bool ok) { return "{\"id\":" + IdJson(id) + ",\"ok\":" + (ok ? "true" : "false") + ",\"seq\":" + Interlocked.Read(ref seqCtr) + ",\"t\":" + Stopwatch.GetTimestamp(); }
134
+ static void Ok(object id, string body) { Send(Head(id, true) + (string.IsNullOrEmpty(body) ? "" : "," + body) + "}"); }
135
+ static void Fail(object id, string code, string msg) { Send(Head(id, false) + ",\"code\":" + Q(code) + ",\"message\":" + Q(msg) + "}"); }
136
+ static string Describe(Exception e) { return e.GetType().Name + " 0x" + e.HResult.ToString("x8"); }
137
+
138
+ // ---- Request helpers ----
139
+ static object Get(Dictionary<string, object> d, string k) { object v; return d != null && d.TryGetValue(k, out v) ? v : null; }
140
+ static long GetL(Dictionary<string, object> d, string k, long def) { object v = Get(d, k); if (v == null) return def; try { return Convert.ToInt64(v); } catch { return def; } }
141
+ static bool GetB(Dictionary<string, object> d, string k, bool def) { object v = Get(d, k); return v is bool ? (bool)v : def; }
142
+ static string GetS(Dictionary<string, object> d, string k) { object v = Get(d, k); return v as string; }
143
+ static long Clamp(long v, long lo, long hi) { return v < lo ? lo : (v > hi ? hi : v); }
144
+ static IntPtr Hw(long h) { return new IntPtr(h); }
145
+ static long HwL(IntPtr h) { return h.ToInt64() & 0xFFFFFFFFL; }
146
+ static IntPtr NeedWindow(Dictionary<string, object> req) {
147
+ long h = GetL(req, "hwnd", 0);
148
+ if (h == 0) throw new Cmd("bad_request", "hwnd is required");
149
+ IntPtr p = Hw(h);
150
+ if (!IsWindow(p)) throw new Cmd("window_gone", "no such window");
151
+ return p;
152
+ }
153
+
154
+ // ---- Window facts ----
155
+ static string ClassOf(IntPtr h) { StringBuilder s = new StringBuilder(256); int n = GetClassNameW(h, s, 256); return n > 0 ? s.ToString(0, n) : ""; }
156
+ static string TitleOf(IntPtr h) { StringBuilder s = new StringBuilder(512); int n = GetWindowTextW(h, s, 512); return n > 0 ? s.ToString(0, n) : ""; }
157
+ static bool ChromiumClass(string c) { return c.StartsWith("Chrome_", StringComparison.Ordinal) || c == "MozillaWindowClass" || c == "CefBrowserWindow"; }
158
+ static bool HasChromiumChild(IntPtr h) {
159
+ bool found = false; int seen = 0;
160
+ EnumChildWindows(h, delegate(IntPtr c, IntPtr lp) { seen++; if (ChromiumClass(ClassOf(c))) { found = true; return false; } return seen < 2000; }, IntPtr.Zero);
161
+ return found;
162
+ }
163
+ static uint PidOf(IntPtr h) { uint pid; GetWindowThreadProcessId(h, out pid); return pid; }
164
+ static string ProcName(uint pid) {
165
+ IntPtr p = OpenProcess(0x1000, false, pid);
166
+ if (p == IntPtr.Zero) return "";
167
+ try {
168
+ StringBuilder sb = new StringBuilder(520); int n = sb.Capacity;
169
+ if (!QueryFullProcessImageNameW(p, 0, sb, ref n)) return "";
170
+ string s = sb.ToString(0, n); int i = s.LastIndexOf('\\');
171
+ return i >= 0 ? s.Substring(i + 1) : s;
172
+ } finally { CloseHandle(p); }
173
+ }
174
+ static long ProcStart(uint pid) {
175
+ IntPtr p = OpenProcess(0x1000, false, pid);
176
+ if (p == IntPtr.Zero) return 0;
177
+ try { long c, e, k, u; return GetProcessTimes(p, out c, out e, out k, out u) ? c / 10000 : 0; } finally { CloseHandle(p); }
178
+ }
179
+ static bool Cloaked(IntPtr h) { int v; return DwmGetInt(h, 14, out v, 4) == 0 && v != 0; }
180
+ // The windows a person sees as windows: visible, not cloaked (other virtual desktops, suspended apps), not a tool window; without an owner unless asked.
181
+ static bool Listable(IntPtr h, bool includeOwned) {
182
+ if (!IsWindowVisible(h)) return false;
183
+ int ex = GetWindowLong(h, -20);
184
+ if ((ex & 0x80) != 0 && (ex & 0x40000) == 0) return false;
185
+ if (!includeOwned && GetWindow(h, 4) != IntPtr.Zero) return false;
186
+ if (Cloaked(h)) return false;
187
+ return true;
188
+ }
189
+ static RC FrameRect(IntPtr h, bool iconic) {
190
+ RC r;
191
+ if (iconic) { WPL p = new WPL(); p.length = Marshal.SizeOf(typeof(WPL)); if (GetWindowPlacement(h, ref p)) return p.normal; }
192
+ if (DwmGetRect(h, 9, out r, Marshal.SizeOf(typeof(RC))) == 0) return r;
193
+ GetWindowRect(h, out r);
194
+ return r;
195
+ }
196
+ static IntPtr RootOf(IntPtr h) { IntPtr r = GetAncestor(h, 2); return r == IntPtr.Zero ? h : r; }
197
+
198
+ static string Windows(Dictionary<string, object> req) {
199
+ bool includeOwned = GetB(req, "includeOwned", false);
200
+ List<IntPtr> found = new List<IntPtr>(); int total = 0;
201
+ EnumWindows(delegate(IntPtr h, IntPtr lp) { total++; if (Listable(h, includeOwned)) found.Add(h); return true; }, IntPtr.Zero);
202
+ IntPtr fg = GetForegroundWindow(); if (fg != IntPtr.Zero) fg = RootOf(fg);
203
+ StringBuilder sb = new StringBuilder("\"windows\":[");
204
+ for (int i = 0; i < found.Count; i++) {
205
+ IntPtr h = found[i]; uint pid = PidOf(h); bool ic = IsIconic(h); RC r = FrameRect(h, ic);
206
+ if (i > 0) sb.Append(',');
207
+ sb.Append("{\"hwnd\":").Append(HwL(h)).Append(",\"pid\":").Append(pid).Append(",\"process\":").Append(Q(ProcName(pid)))
208
+ .Append(",\"title\":").Append(Q(TitleOf(h))).Append(",\"x\":").Append(r.l).Append(",\"y\":").Append(r.t)
209
+ .Append(",\"width\":").Append(r.r - r.l).Append(",\"height\":").Append(r.b - r.t)
210
+ .Append(",\"minimized\":").Append(ic ? "true" : "false").Append(",\"focused\":").Append(h == fg ? "true" : "false")
211
+ .Append(",\"z\":").Append(i).Append('}');
212
+ }
213
+ return sb.Append("],\"total\":").Append(total).ToString();
214
+ }
215
+
216
+ static string Displays() {
217
+ StringBuilder sb = new StringBuilder("\"displays\":["); int n = 0;
218
+ EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, delegate(IntPtr mon, IntPtr dc, ref RC rc, IntPtr lp) {
219
+ MI mi = new MI(); mi.size = Marshal.SizeOf(typeof(MI));
220
+ if (!GetMonitorInfoW(mon, ref mi)) return true;
221
+ uint dx = 96, dy = 96;
222
+ try { GetDpiForMonitor(mon, 0, out dx, out dy); } catch { }
223
+ if (dx == 0) dx = 96;
224
+ if (n > 0) sb.Append(',');
225
+ sb.Append("{\"id\":").Append(Q(mi.dev)).Append(",\"index\":").Append(n)
226
+ .Append(",\"x\":").Append(mi.mon.l).Append(",\"y\":").Append(mi.mon.t).Append(",\"width\":").Append(mi.mon.r - mi.mon.l).Append(",\"height\":").Append(mi.mon.b - mi.mon.t)
227
+ .Append(",\"workX\":").Append(mi.work.l).Append(",\"workY\":").Append(mi.work.t).Append(",\"workWidth\":").Append(mi.work.r - mi.work.l).Append(",\"workHeight\":").Append(mi.work.b - mi.work.t)
228
+ .Append(",\"scale\":").Append(D(dx / 96.0)).Append(",\"dpi\":").Append(dx).Append(",\"primary\":").Append((mi.flags & 1) != 0 ? "true" : "false").Append('}');
229
+ n++; return true;
230
+ }, IntPtr.Zero);
231
+ return sb.Append(']').ToString();
232
+ }
233
+
234
+ // ---- Events: one counter, one ring, written by the hook thread and the UIA threads, read by the scheduler ----
235
+ // Source: 1 = accessibility event, 2 = system window event. Kind: 1 structure, 2 property, 3 created, 4 destroyed, 5 shown, 6 hidden, 7 name, 8 value, 9 location.
236
+ struct Ev { public long Seq; public double Ms; public int Src; public int Kind; public long Hwnd; public long Root; public uint Pid; public bool Top; }
237
+ static readonly object evLock = new object();
238
+ static readonly Ev[] ring = new Ev[RingN];
239
+ static bool dirty;
240
+ static int KindBit(int kind) { return (kind == 1 || (kind >= 3 && kind <= 6)) ? 1 : (kind == 9 ? 4 : 2); }
241
+ static void AddEv(int src, int kind, long hwnd, long root, uint pid, bool top) {
242
+ lock (evLock) {
243
+ long s = Interlocked.Increment(ref seqCtr);
244
+ Ev e = new Ev(); e.Seq = s; e.Ms = NowMs(); e.Src = src; e.Kind = kind; e.Hwnd = hwnd; e.Root = root; e.Pid = pid; e.Top = top;
245
+ ring[(int)(s % RingN)] = e; dirty = true; Monitor.PulseAll(evLock);
246
+ }
247
+ }
248
+
249
+ // ---- System window events: a hook per watched process, on one thread that pumps messages ----
250
+ sealed class HookCmd { public bool Install; public uint Pid; public IntPtr Handle; public ManualResetEvent Done = new ManualResetEvent(false); }
251
+ static readonly Queue<HookCmd> hookQ = new Queue<HookCmd>();
252
+ static readonly Dictionary<uint, IntPtr> hooks = new Dictionary<uint, IntPtr>();
253
+ static readonly Dictionary<IntPtr, uint> hookPid = new Dictionary<IntPtr, uint>();
254
+ static readonly ManualResetEvent hookReady = new ManualResetEvent(false);
255
+ static uint hookThreadId;
256
+ static readonly HookProc hookDelegate = new HookProc(OnWinEvent);
257
+ static void OnWinEvent(IntPtr hook, uint ev, IntPtr hwnd, int obj, int child, uint thread, uint time) {
258
+ try {
259
+ int kind;
260
+ switch (ev) {
261
+ case 0x8000: kind = 3; break; case 0x8001: kind = 4; break; case 0x8002: kind = 5; break; case 0x8003: kind = 6; break;
262
+ case 0x800B: kind = 9; break; case 0x800C: kind = 7; break; case 0x800E: kind = 8; break;
263
+ default: return;
264
+ }
265
+ if (hwnd == IntPtr.Zero || obj == -9 || obj == -8) return;
266
+ uint pid = 0; lock (hookQ) { if (!hookPid.TryGetValue(hook, out pid)) pid = 0; }
267
+ if (pid == 0) pid = PidOf(hwnd);
268
+ IntPtr root = GetAncestor(hwnd, 2);
269
+ bool gone = root == IntPtr.Zero;
270
+ if (gone) root = hwnd;
271
+ bool top = obj == 0 && !gone && root == hwnd && GetAncestor(hwnd, 1) == GetDesktopWindow();
272
+ AddEv(2, kind, HwL(hwnd), HwL(root), pid, top);
273
+ } catch { }
274
+ }
275
+ static void HookMain() {
276
+ MSG m; PeekMessage(out m, IntPtr.Zero, 0, 0, 0);
277
+ hookThreadId = GetCurrentThreadId(); hookReady.Set();
278
+ while (GetMessage(out m, IntPtr.Zero, 0, 0) > 0) {
279
+ if (m.m == 0x8001) {
280
+ while (true) {
281
+ HookCmd c; lock (hookQ) { if (hookQ.Count == 0) break; c = hookQ.Dequeue(); }
282
+ try {
283
+ if (c.Install) { c.Handle = SetWinEventHook(0x8000, 0x800E, IntPtr.Zero, hookDelegate, c.Pid, 0, 2); if (c.Handle != IntPtr.Zero) lock (hookQ) hookPid[c.Handle] = c.Pid; }
284
+ else if (c.Handle != IntPtr.Zero) { UnhookWinEvent(c.Handle); lock (hookQ) hookPid.Remove(c.Handle); }
285
+ } catch { }
286
+ c.Done.Set();
287
+ }
288
+ } else { TranslateMessage(ref m); DispatchMessage(ref m); }
289
+ }
290
+ }
291
+ static void HookCall(HookCmd c) {
292
+ lock (hookQ) hookQ.Enqueue(c);
293
+ PostThreadMessage(hookThreadId, 0x8001, IntPtr.Zero, IntPtr.Zero);
294
+ c.Done.WaitOne(3000);
295
+ }
296
+ static void EnsureHook(uint pid) {
297
+ lock (hookQ) { if (hooks.ContainsKey(pid)) return; }
298
+ HookCmd c = new HookCmd(); c.Install = true; c.Pid = pid; HookCall(c);
299
+ if (c.Handle == IntPtr.Zero) throw new Cmd("hook_failed", "could not watch the process");
300
+ lock (hookQ) hooks[pid] = c.Handle;
301
+ }
302
+ static void DropHook(uint pid) {
303
+ IntPtr h; lock (hookQ) { if (!hooks.TryGetValue(pid, out h)) return; hooks.Remove(pid); }
304
+ HookCmd c = new HookCmd(); c.Install = false; c.Handle = h; HookCall(c);
305
+ }
306
+
307
+ // ---- Accessibility events: registered once per window, on the worker thread; the handlers only record ----
308
+ sealed class Sub { public long Hwnd; public uint Pid; public bool Uia; public AutomationElement El; public StructureChangedEventHandler Sh; public AutomationPropertyChangedEventHandler Ph; public long Used; }
309
+ static readonly Dictionary<long, Sub> subs = new Dictionary<long, Sub>();
310
+ static readonly object subLock = new object();
311
+ static long useCtr;
312
+ static Sub Armed(long hwnd) { lock (subLock) { Sub s; if (subs.TryGetValue(hwnd, out s)) { s.Used = ++useCtr; return s; } } return null; }
313
+ static void Unsub(Sub s) {
314
+ if (s.Uia) {
315
+ try { Automation.RemoveStructureChangedEventHandler(s.El, s.Sh); } catch { }
316
+ try { Automation.RemoveAutomationPropertyChangedEventHandler(s.El, s.Ph); } catch { }
317
+ }
318
+ }
319
+ // Worker thread only.
320
+ static Sub Arm(long hwnd) {
321
+ Sub have = Armed(hwnd); if (have != null) return have;
322
+ IntPtr h = Hw(hwnd);
323
+ if (!IsWindow(h)) throw new Cmd("window_gone", "no such window");
324
+ uint pid = PidOf(h);
325
+ EnsureHook(pid);
326
+ Sub n = new Sub(); n.Hwnd = hwnd; n.Pid = pid; n.Used = ++useCtr;
327
+ if (!ChromiumClass(ClassOf(h))) {
328
+ n.El = AutomationElement.FromHandle(h);
329
+ long hw = hwnd;
330
+ n.Sh = delegate(object sender, StructureChangedEventArgs a) { AddEv(1, 1, hw, hw, pid, false); };
331
+ n.Ph = delegate(object sender, AutomationPropertyChangedEventArgs a) { AddEv(1, 2, hw, hw, pid, false); };
332
+ Automation.AddStructureChangedEventHandler(n.El, TreeScope.Subtree, n.Sh);
333
+ Automation.AddAutomationPropertyChangedEventHandler(n.El, TreeScope.Subtree, n.Ph,
334
+ new AutomationProperty[] { AutomationElement.NameProperty, AutomationElement.IsEnabledProperty, AutomationElement.IsOffscreenProperty,
335
+ TogglePattern.ToggleStateProperty, ExpandCollapsePattern.ExpandCollapseStateProperty, ValuePattern.ValueProperty, SelectionItemPattern.IsSelectedProperty });
336
+ n.Uia = true;
337
+ }
338
+ List<Sub> drop = new List<Sub>();
339
+ lock (subLock) {
340
+ subs[hwnd] = n;
341
+ foreach (KeyValuePair<long, Sub> kv in subs) if (kv.Key != hwnd && !IsWindow(Hw(kv.Key))) drop.Add(kv.Value);
342
+ while (subs.Count - drop.Count > MaxSubs) {
343
+ Sub oldest = null;
344
+ foreach (KeyValuePair<long, Sub> kv in subs) if (kv.Key != hwnd && !drop.Contains(kv.Value) && (oldest == null || kv.Value.Used < oldest.Used)) oldest = kv.Value;
345
+ if (oldest == null) break; drop.Add(oldest);
346
+ }
347
+ foreach (Sub d in drop) subs.Remove(d.Hwnd);
348
+ }
349
+ foreach (Sub d in drop) {
350
+ Unsub(d);
351
+ bool still = false; lock (subLock) { foreach (Sub o in subs.Values) if (o.Pid == d.Pid) still = true; }
352
+ if (!still) DropHook(d.Pid);
353
+ }
354
+ return n;
355
+ }
356
+
357
+ // ---- Waiting for a change ----
358
+ sealed class Waiter {
359
+ public object Id; public long Hwnd; public uint Pid; public long Since; public long ScanSeq; public double StartMs; public double FirstMs = -1; public double LastMs = -1;
360
+ public double QuietMs; public double TimeoutMs; public int Kinds; public int Count; public List<long> NewWins = new List<long>();
361
+ }
362
+ static readonly List<Waiter> waiters = new List<Waiter>();
363
+ static bool Match(Ev e, Waiter w) {
364
+ if ((KindBit(e.Kind) & w.Kinds) == 0) return false;
365
+ if (e.Src == 1) return e.Hwnd == w.Hwnd;
366
+ if (e.Root == w.Hwnd) return true;
367
+ return e.Pid == w.Pid && e.Top && (e.Kind >= 3 && e.Kind <= 6);
368
+ }
369
+ // Under evLock.
370
+ static void Scan(Waiter w, double now) {
371
+ long cur = Interlocked.Read(ref seqCtr);
372
+ long from = w.ScanSeq + 1;
373
+ if (cur - from >= RingN) { w.Count++; if (w.FirstMs < 0) w.FirstMs = now; w.LastMs = now; from = cur - RingN + 1; }
374
+ for (long s = from; s <= cur; s++) {
375
+ Ev e = ring[(int)(s % RingN)];
376
+ if (e.Seq != s || !Match(e, w)) continue;
377
+ w.Count++; if (w.FirstMs < 0 || e.Ms < w.FirstMs) w.FirstMs = e.Ms; if (e.Ms > w.LastMs) w.LastMs = e.Ms;
378
+ if (e.Root != w.Hwnd && e.Top && (e.Kind == 3 || e.Kind == 5) && !w.NewWins.Contains(e.Root)) w.NewWins.Add(e.Root);
379
+ }
380
+ w.ScanSeq = cur;
381
+ }
382
+ static string ChangedBody(Waiter w, double now, bool settled) {
383
+ StringBuilder sb = new StringBuilder("\"changed\":true,\"settled\":" + (settled ? "true" : "false") + ",\"firstEventMs\":" + D(w.FirstMs - w.StartMs) + ",\"settledMs\":" + D(now - w.StartMs) + ",\"events\":" + w.Count + ",\"newWindows\":[");
384
+ bool first = true;
385
+ foreach (long id in w.NewWins) { IntPtr h = Hw(id); if (!IsWindow(h) || !Listable(h, true)) continue; if (!first) sb.Append(','); first = false; sb.Append(id); }
386
+ return sb.Append(']').ToString();
387
+ }
388
+ static void StartWait(object id, Dictionary<string, object> req) {
389
+ IntPtr h = NeedWindow(req);
390
+ Waiter w = new Waiter(); w.Id = id; w.Hwnd = HwL(h); w.Pid = PidOf(h);
391
+ w.QuietMs = Clamp(GetL(req, "quietMs", 120), 5, 5000);
392
+ w.TimeoutMs = Clamp(GetL(req, "timeoutMs", 2000), 20, 10000);
393
+ int kinds = 0; object ks = Get(req, "kinds");
394
+ System.Collections.IEnumerable list = ks as System.Collections.IEnumerable;
395
+ if (list != null && !(ks is string)) foreach (object k in list) { string s = k as string; if (s == "structure") kinds |= 1; else if (s == "property") kinds |= 2; else if (s == "location") kinds |= 4; }
396
+ w.Kinds = kinds == 0 ? 7 : kinds;
397
+ w.StartMs = NowMs();
398
+ w.Since = GetL(req, "since", -1);
399
+ bool armed = Armed(w.Hwnd) != null;
400
+ lock (evLock) {
401
+ long cur = Interlocked.Read(ref seqCtr);
402
+ if (w.Since < 0 || w.Since > cur) w.Since = cur;
403
+ w.ScanSeq = w.Since; waiters.Add(w); dirty = true; Monitor.PulseAll(evLock);
404
+ }
405
+ // A window that was not yet watched is armed now, behind the wait; the wait still ends on time.
406
+ if (!armed) Enqueue(null, delegate() { Arm(w.Hwnd); return null; }, 8000, delegate(Exception e) {
407
+ Cmd c = e as Cmd; lock (evLock) { waiters.Remove(w); }
408
+ Fail(w.Id, c != null ? c.Code : "error", c != null ? c.Message : Describe(e));
409
+ });
410
+ }
411
+
412
+ // ---- Worker: every accessibility call runs on one MTA thread; one that hangs is abandoned and replaced ----
413
+ sealed class Job { public object Id; public Func<string> Fn; public int TimeoutMs; public double StartMs; public int Replied; public Action<Exception> OnError; }
414
+ static readonly Queue<Job> jobs = new Queue<Job>();
415
+ static readonly object qLock = new object();
416
+ static Job current;
417
+ static int workerGen;
418
+ static void Enqueue(object id, Func<string> fn, int timeoutMs, Action<Exception> onError) {
419
+ Job j = new Job(); j.Id = id; j.Fn = fn; j.TimeoutMs = timeoutMs; j.OnError = onError;
420
+ lock (qLock) { jobs.Enqueue(j); Monitor.PulseAll(qLock); }
421
+ }
422
+ static void StartWorker() {
423
+ int gen; lock (qLock) { gen = ++workerGen; }
424
+ Thread t = new Thread(delegate() { WorkerMain(gen); });
425
+ t.SetApartmentState(ApartmentState.MTA); t.IsBackground = true; t.Name = "nz-a11y-worker"; t.Start();
426
+ }
427
+ static void WorkerMain(int gen) {
428
+ try { SetThreadDpiAwarenessContext(new IntPtr(-4)); } catch { }
429
+ while (true) {
430
+ Job j;
431
+ lock (qLock) {
432
+ while (jobs.Count == 0 && gen == workerGen) Monitor.Wait(qLock);
433
+ if (gen != workerGen) return;
434
+ j = jobs.Dequeue(); current = j; j.StartMs = NowMs();
435
+ }
436
+ string body = null; Exception err = null;
437
+ try { body = j.Fn(); } catch (Exception e) { err = e; }
438
+ lock (qLock) { if (current == j) current = null; }
439
+ if (Interlocked.Exchange(ref j.Replied, 1) == 0) {
440
+ if (err != null) {
441
+ if (j.OnError != null) j.OnError(err);
442
+ else { Cmd c = err as Cmd; Fail(j.Id, c != null ? c.Code : "uia_error", c != null ? c.Message : Describe(err)); }
443
+ } else if (body != null) Ok(j.Id, body);
444
+ }
445
+ if (gen != workerGen) return;
446
+ }
447
+ }
448
+ static void Watchdog(double now) {
449
+ Job stuck = null;
450
+ lock (qLock) {
451
+ if (current != null && now - current.StartMs > current.TimeoutMs) { stuck = current; current = null; }
452
+ }
453
+ if (stuck == null) return;
454
+ // The stuck thread is left to finish on its own; a fresh worker takes over the queue.
455
+ StartWorker();
456
+ lock (qLock) { Monitor.PulseAll(qLock); }
457
+ if (Interlocked.Exchange(ref stuck.Replied, 1) == 0) {
458
+ if (stuck.OnError != null) stuck.OnError(new Cmd("timeout", "the window did not answer in time"));
459
+ else Fail(stuck.Id, "timeout", "the window did not answer in time");
460
+ }
461
+ }
462
+ static void SchedMain() {
463
+ while (true) {
464
+ List<KeyValuePair<object, string>> out2 = new List<KeyValuePair<object, string>>();
465
+ double sleep = 50;
466
+ lock (evLock) {
467
+ double now = NowMs();
468
+ for (int i = waiters.Count - 1; i >= 0; i--) {
469
+ Waiter w = waiters[i];
470
+ Scan(w, now);
471
+ string body = null;
472
+ if (w.Count > 0 && now - w.LastMs >= w.QuietMs) body = ChangedBody(w, now, true);
473
+ else if (now - w.StartMs >= w.TimeoutMs) body = w.Count > 0 ? ChangedBody(w, now, false) : "\"changed\":false,\"timedOut\":true,\"settledMs\":" + D(now - w.StartMs);
474
+ if (body != null) { waiters.RemoveAt(i); out2.Add(new KeyValuePair<object, string>(w.Id, body)); }
475
+ else {
476
+ double due = w.StartMs + w.TimeoutMs;
477
+ if (w.Count > 0) due = Math.Min(due, w.LastMs + w.QuietMs);
478
+ sleep = Math.Min(sleep, Math.Max(0.5, due - now));
479
+ }
480
+ }
481
+ }
482
+ foreach (KeyValuePair<object, string> r in out2) Ok(r.Key, r.Value);
483
+ Watchdog(NowMs());
484
+ lock (evLock) { if (!dirty) Monitor.Wait(evLock, (int)Math.Ceiling(sleep)); dirty = false; }
485
+ Thread.Sleep(1);
486
+ }
487
+ }
488
+
489
+ // ---- Snapshot ----
490
+ sealed class Nd {
491
+ public AutomationElement El; public int Index; public int Parent; public int Depth; public string Role; public string Name; public string Aid; public string Cls;
492
+ public int X; public int Y; public int W; public int H; public bool En; public bool Off; public bool Foc; public List<string> Act = new List<string>();
493
+ public string Val; public string Tog; public string Exp; public int Sel = -1; public int ChildCount = -1; public int[] Rid; public string Tag; public string Path; public int Ord;
494
+ }
495
+ sealed class Snap { public long Rev; public long Hwnd; public uint Pid; public List<Nd> Nodes; }
496
+ static readonly Dictionary<long, Snap> snaps = new Dictionary<long, Snap>();
497
+ static long revCtr;
498
+ static string Fnv(string s) { uint h = 2166136261; foreach (char c in s) { h ^= c; h *= 16777619; } return h.ToString("x8"); }
499
+ static string RidStr(int[] r) { if (r == null) return ""; StringBuilder b = new StringBuilder(); for (int i = 0; i < r.Length; i++) { if (i > 0) b.Append('.'); b.Append(r[i]); } return b.ToString(); }
500
+ static CacheRequest NewCache(TreeScope scope) {
501
+ CacheRequest cr = new CacheRequest();
502
+ cr.TreeFilter = Automation.ControlViewCondition; cr.TreeScope = scope;
503
+ cr.Add(AutomationElement.NameProperty); cr.Add(AutomationElement.ControlTypeProperty); cr.Add(AutomationElement.AutomationIdProperty); cr.Add(AutomationElement.ClassNameProperty);
504
+ cr.Add(AutomationElement.BoundingRectangleProperty); cr.Add(AutomationElement.IsEnabledProperty); cr.Add(AutomationElement.IsOffscreenProperty);
505
+ cr.Add(AutomationElement.HasKeyboardFocusProperty); cr.Add(AutomationElement.RuntimeIdProperty); cr.Add(AutomationElement.IsPasswordProperty);
506
+ cr.Add(AutomationElement.IsInvokePatternAvailableProperty); cr.Add(AutomationElement.IsValuePatternAvailableProperty); cr.Add(AutomationElement.IsTogglePatternAvailableProperty);
507
+ cr.Add(AutomationElement.IsExpandCollapsePatternAvailableProperty); cr.Add(AutomationElement.IsSelectionItemPatternAvailableProperty); cr.Add(AutomationElement.IsScrollPatternAvailableProperty);
508
+ cr.Add(ValuePattern.Pattern); cr.Add(ValuePattern.ValueProperty); cr.Add(ValuePattern.IsReadOnlyProperty);
509
+ cr.Add(TogglePattern.Pattern); cr.Add(TogglePattern.ToggleStateProperty);
510
+ cr.Add(ExpandCollapsePattern.Pattern); cr.Add(ExpandCollapsePattern.ExpandCollapseStateProperty);
511
+ cr.Add(SelectionItemPattern.Pattern); cr.Add(SelectionItemPattern.IsSelectedProperty);
512
+ return cr;
513
+ }
514
+ static bool Avail(AutomationElement e, AutomationProperty p) { object v = e.GetCachedPropertyValue(p); return v is bool && (bool)v; }
515
+ static Nd Make(AutomationElement e, int parent, int depth) {
516
+ Nd n = new Nd(); n.El = e; n.Parent = parent; n.Depth = depth;
517
+ AutomationElement.AutomationElementInformation c = e.Cached;
518
+ string role = c.ControlType.ProgrammaticName; n.Role = role.StartsWith("ControlType.", StringComparison.Ordinal) ? role.Substring(12) : role;
519
+ string name = c.Name ?? ""; n.Name = name.Length > 120 ? name.Substring(0, 120) : name;
520
+ n.Aid = c.AutomationId ?? ""; n.Cls = c.ClassName ?? "";
521
+ System.Windows.Rect r = c.BoundingRectangle;
522
+ if (r.IsEmpty || double.IsInfinity(r.X) || double.IsInfinity(r.Width)) { n.X = 0; n.Y = 0; n.W = 0; n.H = 0; }
523
+ else { n.X = (int)Math.Round(r.X); n.Y = (int)Math.Round(r.Y); n.W = (int)Math.Round(r.Width); n.H = (int)Math.Round(r.Height); }
524
+ n.En = c.IsEnabled; n.Off = c.IsOffscreen; n.Foc = c.HasKeyboardFocus;
525
+ try { n.Rid = (int[])e.GetCachedPropertyValue(AutomationElement.RuntimeIdProperty); } catch { }
526
+ object po;
527
+ if (Avail(e, AutomationElement.IsInvokePatternAvailableProperty)) n.Act.Add("invoke");
528
+ if (Avail(e, AutomationElement.IsValuePatternAvailableProperty)) {
529
+ n.Act.Add("value");
530
+ bool pw = false; try { object v = e.GetCachedPropertyValue(AutomationElement.IsPasswordProperty); pw = v is bool && (bool)v; } catch { }
531
+ if (!pw && e.TryGetCachedPattern(ValuePattern.Pattern, out po)) { string val = ((ValuePattern)po).Cached.Value ?? ""; n.Val = val.Length > 120 ? val.Substring(0, 120) : val; }
532
+ }
533
+ if (Avail(e, AutomationElement.IsTogglePatternAvailableProperty)) {
534
+ n.Act.Add("toggle");
535
+ if (e.TryGetCachedPattern(TogglePattern.Pattern, out po)) { ToggleState ts = ((TogglePattern)po).Cached.ToggleState; n.Tog = ts == ToggleState.On ? "on" : (ts == ToggleState.Off ? "off" : "mixed"); }
536
+ }
537
+ if (Avail(e, AutomationElement.IsExpandCollapsePatternAvailableProperty)) {
538
+ n.Act.Add("expandCollapse");
539
+ if (e.TryGetCachedPattern(ExpandCollapsePattern.Pattern, out po)) { ExpandCollapseState xs = ((ExpandCollapsePattern)po).Cached.ExpandCollapseState; n.Exp = xs == ExpandCollapseState.Expanded ? "expanded" : (xs == ExpandCollapseState.Collapsed ? "collapsed" : (xs == ExpandCollapseState.PartiallyExpanded ? "partial" : "leaf")); }
540
+ }
541
+ if (Avail(e, AutomationElement.IsSelectionItemPatternAvailableProperty)) {
542
+ n.Act.Add("selectionItem");
543
+ if (e.TryGetCachedPattern(SelectionItemPattern.Pattern, out po)) n.Sel = ((SelectionItemPattern)po).Cached.IsSelected ? 1 : 0;
544
+ }
545
+ if (Avail(e, AutomationElement.IsScrollPatternAvailableProperty)) n.Act.Add("scroll");
546
+ n.Tag = n.Role + ":" + Fnv(name);
547
+ return n;
548
+ }
549
+ static int ChildrenOf(AutomationElement e, out AutomationElementCollection kids) {
550
+ try { kids = e.CachedChildren; return kids.Count; } catch (InvalidOperationException) { kids = null; return -1; }
551
+ }
552
+ sealed class WalkCtx { public List<Nd> Nodes = new List<Nd>(); public int Max; public int MaxDepth; public int Total; public bool Truncated; public Dictionary<int, Dictionary<string, int>> Ords = new Dictionary<int, Dictionary<string, int>>(); }
553
+ static void Walk(AutomationElement e, int parent, int depth, WalkCtx x) {
554
+ x.Total++;
555
+ if (x.Nodes.Count >= x.Max || depth > x.MaxDepth) { x.Truncated = true; AutomationElementCollection skip; int cnt = ChildrenOf(e, out skip); if (cnt > 0) foreach (AutomationElement k in skip) WalkCount(k, x); return; }
556
+ Nd n = Make(e, parent, depth); n.Index = x.Nodes.Count; x.Nodes.Add(n);
557
+ if (parent >= 0) {
558
+ Nd p = x.Nodes[parent]; n.Path = p.Path.Length == 0 ? p.Tag : p.Path + "/" + p.Tag;
559
+ Dictionary<string, int> oc; if (!x.Ords.TryGetValue(parent, out oc)) { oc = new Dictionary<string, int>(); x.Ords[parent] = oc; }
560
+ int o; oc.TryGetValue(n.Tag, out o); n.Ord = o; oc[n.Tag] = o + 1;
561
+ } else n.Path = "";
562
+ AutomationElementCollection kids; int count = ChildrenOf(e, out kids);
563
+ if (count < 0) return;
564
+ int before = x.Nodes.Count;
565
+ foreach (AutomationElement k in kids) Walk(k, n.Index, depth + 1, x);
566
+ if (x.Nodes.Count - before < count || depth + 1 > x.MaxDepth) n.ChildCount = count;
567
+ }
568
+ static void WalkCount(AutomationElement e, WalkCtx x) {
569
+ x.Total++; AutomationElementCollection kids; int c = ChildrenOf(e, out kids);
570
+ if (c > 0) foreach (AutomationElement k in kids) WalkCount(k, x);
571
+ }
572
+ // The shallow read: the window, its children and theirs, one request per second-level container.
573
+ static WalkCtx Skeleton(AutomationElement root, int max) {
574
+ WalkCtx x = new WalkCtx(); x.Max = max; x.MaxDepth = 2;
575
+ CacheRequest cr = NewCache(TreeScope.Element | TreeScope.Children);
576
+ AutomationElement top = root.GetUpdatedCache(cr);
577
+ x.Total = 1; Nd rn = Make(top, -1, 0); rn.Index = 0; rn.Path = ""; x.Nodes.Add(rn);
578
+ AutomationElementCollection kids; int count = ChildrenOf(top, out kids);
579
+ rn.ChildCount = count > 0 ? count : -1;
580
+ if (count > 0) foreach (AutomationElement k in kids) {
581
+ if (x.Nodes.Count >= x.Max) { x.Truncated = true; x.Total++; continue; }
582
+ AutomationElement kc = k.GetUpdatedCache(cr); x.Total++;
583
+ Nd kn = Make(kc, 0, 1); kn.Index = x.Nodes.Count; kn.Path = rn.Tag; x.Nodes.Add(kn);
584
+ AutomationElementCollection gk; int gc = ChildrenOf(kc, out gk);
585
+ if (gc > 0) { kn.ChildCount = gc; foreach (AutomationElement g in gk) {
586
+ x.Total++;
587
+ if (x.Nodes.Count >= x.Max) { x.Truncated = true; continue; }
588
+ Nd gn = Make(g, kn.Index, 2); gn.Index = x.Nodes.Count; gn.Path = rn.Tag + "/" + kn.Tag; x.Nodes.Add(gn);
589
+ } }
590
+ }
591
+ return x;
592
+ }
593
+ static void NodeJson(StringBuilder sb, Nd n) {
594
+ sb.Append("{\"index\":").Append(n.Index).Append(",\"parent\":").Append(n.Parent).Append(",\"depth\":").Append(n.Depth).Append(",\"role\":").Append(Q(n.Role));
595
+ if (n.Name.Length > 0) sb.Append(",\"name\":").Append(Q(n.Name));
596
+ if (n.Aid.Length > 0) sb.Append(",\"automationId\":").Append(Q(n.Aid));
597
+ if (n.Cls.Length > 0) sb.Append(",\"className\":").Append(Q(n.Cls));
598
+ sb.Append(",\"rect\":[").Append(n.X).Append(',').Append(n.Y).Append(',').Append(n.W).Append(',').Append(n.H).Append(']');
599
+ sb.Append(",\"enabled\":").Append(n.En ? "true" : "false");
600
+ if (n.Off) sb.Append(",\"offscreen\":true");
601
+ if (n.Foc) sb.Append(",\"focused\":true");
602
+ if (n.Act.Count > 0) { sb.Append(",\"actions\":["); for (int i = 0; i < n.Act.Count; i++) { if (i > 0) sb.Append(','); sb.Append(Q(n.Act[i])); } sb.Append(']'); }
603
+ if (n.Val != null) sb.Append(",\"value\":").Append(Q(n.Val));
604
+ if (n.Tog != null) sb.Append(",\"toggle\":").Append(Q(n.Tog));
605
+ if (n.Exp != null) sb.Append(",\"expand\":").Append(Q(n.Exp));
606
+ if (n.Sel >= 0) sb.Append(",\"selected\":").Append(n.Sel == 1 ? "true" : "false");
607
+ if (n.ChildCount >= 0) sb.Append(",\"childCount\":").Append(n.ChildCount);
608
+ sb.Append('}');
609
+ }
610
+ static void RefuseChromium(IntPtr h, Dictionary<string, object> req) {
611
+ if (GetB(req, "allowChromium", false)) return;
612
+ if (ChromiumClass(ClassOf(h)) || HasChromiumChild(h)) throw new Cmd("chromium_not_activated", "this window is a Chromium or Electron one; reading it would turn its accessibility on");
613
+ }
614
+ static Snap ReadSnap(IntPtr h, int max, int maxDepth, bool skeleton, out WalkCtx ctx, out double readMs) {
615
+ double t0 = NowMs();
616
+ AutomationElement root = AutomationElement.FromHandle(h);
617
+ if (skeleton) ctx = Skeleton(root, max);
618
+ else {
619
+ AutomationElement top = root.GetUpdatedCache(NewCache(TreeScope.Subtree));
620
+ ctx = new WalkCtx(); ctx.Max = max; ctx.MaxDepth = maxDepth;
621
+ Walk(top, -1, 0, ctx);
622
+ }
623
+ readMs = NowMs() - t0;
624
+ Snap s = new Snap(); s.Rev = Interlocked.Increment(ref revCtr); s.Hwnd = HwL(h); s.Pid = PidOf(h); s.Nodes = ctx.Nodes;
625
+ lock (subLock) {
626
+ snaps[s.Hwnd] = s;
627
+ while (snaps.Count > 6) { long oldest = -1; foreach (KeyValuePair<long, Snap> kv in snaps) if (oldest < 0 || kv.Value.Rev < snaps[oldest].Rev) oldest = kv.Key; if (oldest == s.Hwnd) break; snaps.Remove(oldest); }
628
+ }
629
+ return s;
630
+ }
631
+ static string Snapshot(Dictionary<string, object> req) {
632
+ IntPtr h = NeedWindow(req);
633
+ RefuseChromium(h, req);
634
+ bool skeleton = GetB(req, "skeleton", false);
635
+ int max = (int)Clamp(GetL(req, "maxNodes", 400), 1, 5000), depth = (int)Clamp(GetL(req, "maxDepth", 12), 0, 64);
636
+ WalkCtx x; double readMs;
637
+ Snap s = ReadSnap(h, max, depth, skeleton, out x, out readMs);
638
+ double e0 = NowMs();
639
+ StringBuilder sb = new StringBuilder("\"hwnd\":" + HwL(h) + ",\"rev\":" + s.Rev + ",\"skeleton\":" + (skeleton ? "true" : "false") + ",\"total\":" + x.Total + ",\"truncated\":" + (x.Truncated ? "true" : "false") + ",\"readMs\":" + D(readMs) + ",\"nodes\":[");
640
+ for (int i = 0; i < s.Nodes.Count; i++) { if (i > 0) sb.Append(','); NodeJson(sb, s.Nodes[i]); }
641
+ return sb.Append("],\"emitMs\":").Append(D(NowMs() - e0)).ToString();
642
+ }
643
+ static Snap Latest(long hwnd) { lock (subLock) { Snap s; if (snaps.TryGetValue(hwnd, out s)) return s; } return null; }
644
+ static string Identity(Dictionary<string, object> req) {
645
+ IntPtr h = NeedWindow(req);
646
+ Snap s = Latest(HwL(h));
647
+ if (s == null) throw new Cmd("no_snapshot", "take a snapshot of the window first");
648
+ long rev = GetL(req, "rev", -1);
649
+ if (rev >= 0 && rev != s.Rev) throw new Cmd("stale_snapshot", "the window was read again since");
650
+ long idx = GetL(req, "index", -1);
651
+ if (idx < 0 || idx >= s.Nodes.Count) throw new Cmd("bad_index", "no such node");
652
+ Nd n = s.Nodes[(int)idx];
653
+ return "\"fingerprint\":{\"runtimeId\":" + Q(RidStr(n.Rid)) + ",\"automationId\":" + Q(n.Aid) + ",\"role\":" + Q(n.Role) + ",\"nameHash\":" + Q(n.Tag.Substring(n.Tag.IndexOf(':') + 1)) + ",\"parentPath\":" + Q(n.Path) + ",\"ordinal\":" + n.Ord + ",\"processStart\":" + ProcStart(s.Pid) + "}";
654
+ }
655
+ static string Resolve(Dictionary<string, object> req) {
656
+ IntPtr h = NeedWindow(req);
657
+ Dictionary<string, object> f = Get(req, "fingerprint") as Dictionary<string, object>;
658
+ if (f == null) throw new Cmd("bad_request", "fingerprint is required");
659
+ string rid = GetS(f, "runtimeId") ?? "", aid = GetS(f, "automationId") ?? "", role = GetS(f, "role") ?? "", nh = GetS(f, "nameHash") ?? "", path = GetS(f, "parentPath") ?? "";
660
+ long ord = GetL(f, "ordinal", -1), pstart = GetL(f, "processStart", 0);
661
+ if (pstart != 0) { long now = ProcStart(PidOf(h)); if (now != 0 && now != pstart) return "\"found\":false,\"code\":\"not_found\""; }
662
+ WalkCtx x; double readMs;
663
+ Snap s = ReadSnap(h, 5000, 64, false, out x, out readMs);
664
+ List<Nd> hits = new List<Nd>(); string via = "";
665
+ if (rid.Length > 0) { foreach (Nd n in s.Nodes) if (RidStr(n.Rid) == rid) hits.Add(n); if (hits.Count == 1) via = "runtimeId"; else if (hits.Count > 1) return "\"found\":false,\"code\":\"ambiguous\",\"candidates\":" + hits.Count; }
666
+ if (via.Length == 0 && aid.Length > 0) {
667
+ hits.Clear(); foreach (Nd n in s.Nodes) if (n.Aid == aid && n.Role == role) hits.Add(n);
668
+ if (hits.Count > 1) { List<Nd> by = hits.FindAll(delegate(Nd n) { return n.Path == path; }); if (by.Count > 0) hits = by; }
669
+ if (hits.Count > 1 && ord >= 0) { List<Nd> by = hits.FindAll(delegate(Nd n) { return n.Ord == ord; }); if (by.Count > 0) hits = by; }
670
+ if (hits.Count == 1) via = "automationId"; else if (hits.Count > 1) return "\"found\":false,\"code\":\"ambiguous\",\"candidates\":" + hits.Count;
671
+ }
672
+ if (via.Length == 0) {
673
+ hits.Clear(); foreach (Nd n in s.Nodes) if (n.Role == role && n.Tag.EndsWith(":" + nh, StringComparison.Ordinal) && n.Path == path) hits.Add(n);
674
+ if (hits.Count > 1 && ord >= 0) { List<Nd> by = hits.FindAll(delegate(Nd n) { return n.Ord == ord; }); if (by.Count > 0) hits = by; }
675
+ if (hits.Count == 1) via = "name"; else if (hits.Count > 1) return "\"found\":false,\"code\":\"ambiguous\",\"candidates\":" + hits.Count;
676
+ }
677
+ if (via.Length == 0) return "\"found\":false,\"code\":\"not_found\"";
678
+ return "\"found\":true,\"index\":" + hits[0].Index + ",\"via\":" + Q(via) + ",\"rev\":" + s.Rev + ",\"total\":" + x.Total + ",\"readMs\":" + D(readMs);
679
+ }
680
+
681
+ // ---- The loop ----
682
+ static string Hello() { return "\"hello\":true,\"version\":" + Version + ",\"pid\":" + Process.GetCurrentProcess().Id + ",\"freq\":" + Stopwatch.Frequency + ",\"capabilities\":[\"windows\",\"displays\",\"snapshot\",\"seq\",\"wait_change\",\"identity\",\"resolve\"]"; }
683
+ static void Handle(string line) {
684
+ object id = null;
685
+ try {
686
+ Dictionary<string, object> req = new JavaScriptSerializer().DeserializeObject(line) as Dictionary<string, object>;
687
+ if (req == null) throw new Cmd("bad_request", "not an object");
688
+ id = Get(req, "id");
689
+ int to = (int)Clamp(GetL(req, "timeoutMs", 8000), 500, 30000);
690
+ switch (GetS(req, "cmd")) {
691
+ case "hello": Ok(id, Hello()); break;
692
+ case "windows": Ok(id, Windows(req)); break;
693
+ case "displays": Ok(id, Displays()); break;
694
+ case "seq": {
695
+ long hw = GetL(req, "hwnd", 0);
696
+ if (hw == 0 || Armed(hw) != null) { Ok(id, "\"armed\":" + (hw != 0 ? "true" : "false")); break; }
697
+ NeedWindow(req);
698
+ Enqueue(id, delegate() { Arm(hw); return "\"armed\":true"; }, 8000, null);
699
+ break;
700
+ }
701
+ case "snapshot": Enqueue(id, delegate() { return Snapshot(req); }, to, null); break;
702
+ case "identity": Enqueue(id, delegate() { return Identity(req); }, to, null); break;
703
+ case "resolve": Enqueue(id, delegate() { return Resolve(req); }, to, null); break;
704
+ case "wait_change": StartWait(id, req); break;
705
+ case "quit": Ok(id, ""); Environment.Exit(0); break;
706
+ default: Fail(id, "unknown_command", "unknown command"); break;
707
+ }
708
+ } catch (Cmd c) { Fail(id, c.Code, c.Message); }
709
+ catch (Exception e) { Fail(id, "error", Describe(e)); }
710
+ }
711
+ public static void Run() {
712
+ timeBeginPeriod(1);
713
+ try { SetProcessDpiAwarenessContext(new IntPtr(-4)); } catch { }
714
+ Thread hk = new Thread(HookMain); hk.IsBackground = true; hk.Name = "nz-a11y-hook"; hk.Start();
715
+ hookReady.WaitOne(3000);
716
+ StartWorker();
717
+ Thread sc = new Thread(SchedMain); sc.IsBackground = true; sc.Name = "nz-a11y-sched"; sc.Start();
718
+ Send(Head(null, true) + "," + Hello() + "}");
719
+ string line;
720
+ while ((line = Console.In.ReadLine()) != null) { if (line.Length > 0) Handle(line); }
721
+ Environment.Exit(0);
722
+ }
723
+ }
724
+ '@
725
+ [NzA]::Run()
726
+ `
727
+
728
+ /**
729
+ * The script is longer than a Windows command line allows once encoded, so
730
+ * PowerShell is started with this short bootstrap, which reads the script as
731
+ * its first line of input (UTF-8, base64) and runs it; the line protocol
732
+ * follows on the same stream.
733
+ */
734
+ export const A11Y_BOOTSTRAP =
735
+ '$s=[Console]::In.ReadLine();Invoke-Expression ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s)))'
736
+
737
+ /** The first line to write to a helper started with {@link A11Y_BOOTSTRAP}. */
738
+ export function a11yScriptLine(script: string = A11Y_HELPER_SCRIPT): string {
739
+ return Buffer.from(script, 'utf8').toString('base64')
740
+ }