dsh-native-uia 0.0.0-stage → 0.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.
- package/LICENSE +21 -0
- package/README.md +431 -2
- package/client/client.js +81 -0
- package/cordis.patch.yml +11 -0
- package/icon.svg +11 -0
- package/locale/desktop/en.json +6 -0
- package/locale/desktop/zh.json +6 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +80 -4
- package/scripts/bench-live.mjs +157 -0
- package/scripts/check-lease.mjs +308 -0
- package/scripts/install.mjs +154 -0
- package/scripts/lib/load-tools-source.mjs +24 -0
- package/scripts/measure-parse.mjs +77 -0
- package/scripts/regression-halt-latch.mjs +100 -0
- package/scripts/regression-quality.mjs +207 -0
- package/scripts/regression-tools.mjs +88 -0
- package/scripts/regression-worker.ps1 +1042 -0
- package/scripts/smoke.mjs +158 -0
- package/scripts/verify-capture-scale.mjs +37 -0
- package/scripts/verify-live-clipboard.mjs +108 -0
- package/scripts/verify-live.mjs +110 -0
- package/scripts/verify-locator.mjs +52 -0
- package/scripts/verify.mjs +1459 -0
- package/src/activity-window.js +212 -0
- package/src/dashboard.js +145 -0
- package/src/guard.js +191 -0
- package/src/index.js +377 -0
- package/src/native-uia-remote.js +80 -0
- package/src/panel-face.js +14 -0
- package/src/state.js +177 -0
- package/src/tools.js +1482 -0
- package/src/worker-client.js +246 -0
- package/web/control.html +1413 -0
- package/worker/bin/build-ocr.ps1 +41 -0
- package/worker/bin/ocr.cs +69 -0
- package/worker/bin/ocr.exe +0 -0
- package/worker/indicator-server.ps1 +1928 -0
- package/worker/ps-stdio.ps1 +168 -0
- package/worker/uia-worker.ps1 +4220 -0
|
@@ -0,0 +1,4220 @@
|
|
|
1
|
+
# uia-worker.ps1 -- resident UI Automation RPC server for the DSH native-uia plugin.
|
|
2
|
+
#
|
|
3
|
+
# Transport: stdio, one JSON object per request line, one JSON object per response line.
|
|
4
|
+
# All responses are escaped to pure ASCII (\uXXXX for anything > 0x7E) because the pipe
|
|
5
|
+
# encoding between Node and powershell.exe is not guaranteed on Windows/Git-Bash.
|
|
6
|
+
# Diagnostics go to stderr ONLY; stdout carries nothing but response JSON.
|
|
7
|
+
#
|
|
8
|
+
# Run: powershell.exe -NoProfile -ExecutionPolicy Bypass -File uia-worker.ps1
|
|
9
|
+
# Requires: Windows PowerShell 5.1 (System.Windows.Automation managed UIA client).
|
|
10
|
+
#
|
|
11
|
+
# Safety model:
|
|
12
|
+
# * every snapshot mints a fresh ref table and bumps a per-window revision
|
|
13
|
+
# * refs whose revision is not the current revision of their window are refused
|
|
14
|
+
# * commit_batch refuses everything when the supplied revision does not match
|
|
15
|
+
# * background delivery only: no cursor motion, no SetForegroundWindow unless asked
|
|
16
|
+
# * the pointer_* commands are the one opt-in physical channel: absolute SendInput only, and a
|
|
17
|
+
# click or drag re-reads the window under the point and refuses unless `expect` matches it
|
|
18
|
+
$ErrorActionPreference = 'Stop'
|
|
19
|
+
Set-StrictMode -Off
|
|
20
|
+
|
|
21
|
+
$script:W = @{
|
|
22
|
+
startTick = [Diagnostics.Stopwatch]::GetTimestamp()
|
|
23
|
+
windows = @{} # windowId -> window entry
|
|
24
|
+
winByHwnd = @{} # hwnd(int) -> windowId
|
|
25
|
+
refs = @{} # ref key -> ref entry
|
|
26
|
+
refOrder = New-Object System.Collections.Generic.List[string]
|
|
27
|
+
winSeq = 0
|
|
28
|
+
refSeq = 0
|
|
29
|
+
snapSeq = 0
|
|
30
|
+
totalRefs = 0
|
|
31
|
+
maxRefs = 4000
|
|
32
|
+
dl = [Int64]::MaxValue # deadline tick for the request in flight
|
|
33
|
+
lastPrepare = $null
|
|
34
|
+
# Side channel for descriptor matching: Find-ByDescriptor still returns the element (every caller
|
|
35
|
+
# relies on that), and records here WHY it returned it. descriptor_match reads it back.
|
|
36
|
+
lastMatch = $null
|
|
37
|
+
stats = @{ commands = 0; snapshots = 0; actionsPerformed = 0; refused = 0; evictions = 0 }
|
|
38
|
+
procNames = @{}
|
|
39
|
+
errors = New-Object System.Collections.Generic.List[string]
|
|
40
|
+
# How element actions (act / commit_batch) reach the desktop: background = UIA patterns only (safe
|
|
41
|
+
# default, no cursor motion); auto = UIA first, pixel fallback when the element has no usable
|
|
42
|
+
# pattern; foreground = always drive the physical pointer at the element's rect. Explicit
|
|
43
|
+
# computer_click/type/key/scroll are always physical and ignore this.
|
|
44
|
+
pointerMode = 'background'
|
|
45
|
+
# The verbs Do-Action / Invoke-UiaAction actually implement. prepare_batch validates against
|
|
46
|
+
# this set so a typo is caught in the dry run instead of after a committed batch.
|
|
47
|
+
actionNames = @{
|
|
48
|
+
invoke = $true; set_value = $true; text_append = $true; toggle = $true; select = $true
|
|
49
|
+
expand = $true; collapse = $true; scroll_up = $true; scroll_down = $true; focus = $true
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
# The ref ceiling is 4000 by default. DSH_UIA_MAX_REFS only exists so the test harness can
|
|
54
|
+
# prove the eviction path without having to mint 4000 refs; the Node side never sets it.
|
|
55
|
+
if ($env:DSH_UIA_MAX_REFS -match '^\d+$' -and [int]$env:DSH_UIA_MAX_REFS -ge 8) {
|
|
56
|
+
$script:W.maxRefs = [int]$env:DSH_UIA_MAX_REFS
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
# stderr logging helper (defined before anything can use it; stdout is reserved for responses)
|
|
60
|
+
$script:stdErr = [Console]::Error
|
|
61
|
+
function Log($msg) {
|
|
62
|
+
try { $script:stdErr.WriteLine('[uia-worker] ' + $msg) } catch { }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
# ---------------------------------------------------------------- assemblies
|
|
66
|
+
$script:asmMs = 0
|
|
67
|
+
$t0 = [Diagnostics.Stopwatch]::GetTimestamp()
|
|
68
|
+
Add-Type -AssemblyName UIAutomationClient
|
|
69
|
+
Add-Type -AssemblyName UIAutomationTypes
|
|
70
|
+
Add-Type -AssemblyName System.Drawing
|
|
71
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
72
|
+
$script:asmMs = [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $t0) / 10000.0, 1)
|
|
73
|
+
|
|
74
|
+
$AE = [System.Windows.Automation.AutomationElement]
|
|
75
|
+
$TW = [System.Windows.Automation.TreeWalker]
|
|
76
|
+
|
|
77
|
+
# ---------------------------------------------------------------- native helper
|
|
78
|
+
$script:nativeSrc = @'
|
|
79
|
+
using System;
|
|
80
|
+
using System.Collections.Generic;
|
|
81
|
+
using System.Diagnostics;
|
|
82
|
+
using System.Runtime.InteropServices;
|
|
83
|
+
using System.Drawing;
|
|
84
|
+
using System.Drawing.Imaging;
|
|
85
|
+
using System.IO;
|
|
86
|
+
|
|
87
|
+
public static class Native {
|
|
88
|
+
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
|
|
89
|
+
[DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
|
|
90
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
91
|
+
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
|
92
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
|
|
93
|
+
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
|
|
94
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
|
|
95
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
|
96
|
+
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);
|
|
97
|
+
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
|
|
98
|
+
[DllImport("user32.dll")] public static extern IntPtr PostMessageW(IntPtr h, uint msg, IntPtr w, IntPtr l);
|
|
99
|
+
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr h, uint cmd);
|
|
100
|
+
[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags);
|
|
101
|
+
[DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr h);
|
|
102
|
+
[DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr h, IntPtr dc);
|
|
103
|
+
[DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDest, int xDest, int yDest, int w, int h, IntPtr hdcSrc, int xSrc, int ySrc, uint rop);
|
|
104
|
+
// Whole-desktop capture: StretchBlt so one call serves both native 1:1 and a token-bounded
|
|
105
|
+
// preview, with HALFTONE so downscaled text stays legible.
|
|
106
|
+
[DllImport("gdi32.dll")] public static extern bool StretchBlt(IntPtr hdcDest, int xDest, int yDest, int wDest, int hDest, IntPtr hdcSrc, int xSrc, int ySrc, int wSrc, int hSrc, uint rop);
|
|
107
|
+
[DllImport("gdi32.dll")] public static extern int SetStretchBltMode(IntPtr hdc, int mode);
|
|
108
|
+
[DllImport("gdi32.dll")] public static extern bool SetBrushOrgEx(IntPtr hdc, int x, int y, IntPtr prev);
|
|
109
|
+
|
|
110
|
+
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
|
|
111
|
+
|
|
112
|
+
public class CapResult {
|
|
113
|
+
public string method = "none";
|
|
114
|
+
public bool blank = true;
|
|
115
|
+
public int width = 0;
|
|
116
|
+
public int height = 0;
|
|
117
|
+
public int distinct = 0;
|
|
118
|
+
public byte[] png = null;
|
|
119
|
+
public string error = "";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
static int Distinct(Bitmap bmp, out bool allTransparent) {
|
|
123
|
+
HashSet<int> seen = new HashSet<int>();
|
|
124
|
+
allTransparent = true;
|
|
125
|
+
int w = bmp.Width, h = bmp.Height;
|
|
126
|
+
if (w <= 0 || h <= 0) return 0;
|
|
127
|
+
int stepX = Math.Max(1, (int)(w / 90));
|
|
128
|
+
int stepY = Math.Max(1, (int)(h / 90));
|
|
129
|
+
BitmapData bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
|
|
130
|
+
try {
|
|
131
|
+
int[] row = new int[w];
|
|
132
|
+
for (int y = 0; y < h; y += stepY) {
|
|
133
|
+
IntPtr ptr = IntPtr.Add(bd.Scan0, y * bd.Stride);
|
|
134
|
+
Marshal.Copy(ptr, row, 0, w);
|
|
135
|
+
for (int x = 0; x < w; x += stepX) {
|
|
136
|
+
int c = row[x];
|
|
137
|
+
if (((c >> 24) & 0xFF) != 0) allTransparent = false;
|
|
138
|
+
if (!seen.Contains(c)) { seen.Add(c); if (seen.Count > 40) return seen.Count; }
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
} finally { bmp.UnlockBits(bd); }
|
|
142
|
+
return seen.Count;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// Whole-desktop capture across the virtual screen (all monitors, negative origins included).
|
|
146
|
+
/// computer_capture could only ever see ONE window, so anything the model needed from the rest
|
|
147
|
+
/// of the screen — a second app, a dialog belonging to another process, the taskbar, a
|
|
148
|
+
/// multi-monitor desktop — was simply absent ("设备屏幕截不全"). This captures the composed
|
|
149
|
+
/// desktop as the user sees it, which is also the honest picture for a self-drawn app that
|
|
150
|
+
/// PrintWindow cannot render.
|
|
151
|
+
public static CapResult CaptureScreen(int maxDim) {
|
|
152
|
+
CapResult res = new CapResult();
|
|
153
|
+
// SM_XVIRTUALSCREEN=76 SM_YVIRTUALSCREEN=77 SM_CXVIRTUALSCREEN=78 SM_CYVIRTUALSCREEN=79.
|
|
154
|
+
// The origin is NOT always 0:0 — a monitor placed left of the primary has a negative X.
|
|
155
|
+
// This inline copy exists because C# cannot call the PowerShell Get-VirtScreen function, which
|
|
156
|
+
// is the AUTHORITATIVE station-size measurement (measured fallback chain, screen_unknown on
|
|
157
|
+
// failure); if the two ever disagree, fix Get-VirtScreen and mirror it here.
|
|
158
|
+
int vx = GetSystemMetrics(76), vy = GetSystemMetrics(77);
|
|
159
|
+
int vw = GetSystemMetrics(78), vh = GetSystemMetrics(79);
|
|
160
|
+
if (vw <= 0 || vh <= 0) { res.error = "virtual screen reports no area (" + vw + "x" + vh + ")"; return res; }
|
|
161
|
+
int w = vw, h = vh;
|
|
162
|
+
if (maxDim > 0) {
|
|
163
|
+
if (w > maxDim) { h = (int)((long)h * maxDim / w); w = maxDim; }
|
|
164
|
+
if (h > maxDim) { w = (int)((long)w * maxDim / h); h = maxDim; }
|
|
165
|
+
}
|
|
166
|
+
if (w < 2) w = 2;
|
|
167
|
+
if (h < 2) h = 2;
|
|
168
|
+
res.width = w; res.height = h;
|
|
169
|
+
using (Bitmap bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb)) {
|
|
170
|
+
using (Graphics g = Graphics.FromImage(bmp)) {
|
|
171
|
+
// Copy from the virtual-screen origin, then let GDI+ scale to the requested bitmap size so
|
|
172
|
+
// one capture serves both "native 1:1" (maxDim=0) and a token-bounded preview.
|
|
173
|
+
IntPtr screen = GetDC(IntPtr.Zero);
|
|
174
|
+
try {
|
|
175
|
+
IntPtr hdc = g.GetHdc();
|
|
176
|
+
try {
|
|
177
|
+
// SetStretchBltMode + HALFTONE keeps downscaled text legible instead of aliasing it.
|
|
178
|
+
SetStretchBltMode(hdc, 4); // HALFTONE
|
|
179
|
+
SetBrushOrgEx(hdc, 0, 0, IntPtr.Zero);
|
|
180
|
+
bool ok = StretchBlt(hdc, 0, 0, w, h, screen, vx, vy, vw, vh, 0x00CC0020u); // SRCCOPY
|
|
181
|
+
if (!ok) res.error = "StretchBlt from the desktop returned false; ";
|
|
182
|
+
} finally { g.ReleaseHdc(hdc); }
|
|
183
|
+
} finally { ReleaseDC(IntPtr.Zero, screen); }
|
|
184
|
+
}
|
|
185
|
+
bool transparent;
|
|
186
|
+
int d = Distinct(bmp, out transparent);
|
|
187
|
+
res.method = "desktop-gdi";
|
|
188
|
+
res.distinct = d;
|
|
189
|
+
res.blank = (d <= 1 || transparent);
|
|
190
|
+
res.png = ToPng(bmp);
|
|
191
|
+
return res;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/// Scale a whole native-size rendering down to the requested token budget.
|
|
196
|
+
/// PrintWindow and BitBlt both paint at the WINDOW's real pixel size: drawing them into a
|
|
197
|
+
/// pre-shrunk bitmap silently kept only the top-left corner of the frame, so every downscaled
|
|
198
|
+
/// window capture was cropped at the right and bottom and every OCR coordinate taken from it
|
|
199
|
+
/// was displaced. Capture at native size, then scale the complete frame.
|
|
200
|
+
static Bitmap Fit(Bitmap src, int w, int h) {
|
|
201
|
+
Bitmap dst = new Bitmap(w, h, PixelFormat.Format32bppArgb);
|
|
202
|
+
using (Graphics g = Graphics.FromImage(dst)) {
|
|
203
|
+
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
|
|
204
|
+
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
|
|
205
|
+
g.DrawImage(src, new Rectangle(0, 0, w, h));
|
|
206
|
+
}
|
|
207
|
+
return dst;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
public static CapResult Capture(IntPtr hwnd, int maxDim) {
|
|
211
|
+
CapResult res = new CapResult();
|
|
212
|
+
RECT r;
|
|
213
|
+
if (!GetWindowRect(hwnd, out r)) { res.error = "GetWindowRect failed"; return res; }
|
|
214
|
+
// Native size is what the window paints at; the target size is only the token budget.
|
|
215
|
+
int nw = r.Right - r.Left, nh = r.Bottom - r.Top;
|
|
216
|
+
if (nw <= 1 || nh <= 1) { res.error = "window has no area (" + nw + "x" + nh + ")"; return res; }
|
|
217
|
+
int w = nw, h = nh;
|
|
218
|
+
// maxDim caps the longer edge to keep the PNG (and its tokens) bounded. maxDim <= 0 means
|
|
219
|
+
// "native": capture at the window's real physical size, 1 image px = 1 screen px (scale = 1).
|
|
220
|
+
if (maxDim > 0) {
|
|
221
|
+
if (w > maxDim) { h = (int)((long)h * maxDim / w); w = maxDim; }
|
|
222
|
+
if (h > maxDim) { w = (int)((long)w * maxDim / h); h = maxDim; }
|
|
223
|
+
}
|
|
224
|
+
if (w < 2) w = 2;
|
|
225
|
+
if (h < 2) h = 2;
|
|
226
|
+
res.width = w; res.height = h;
|
|
227
|
+
|
|
228
|
+
bool transparent;
|
|
229
|
+
// attempt 1: PrintWindow with PW_RENDERFULLCONTENT (2), painted at native size
|
|
230
|
+
using (Bitmap full = new Bitmap(nw, nh, PixelFormat.Format32bppArgb)) {
|
|
231
|
+
using (Graphics g = Graphics.FromImage(full)) {
|
|
232
|
+
IntPtr hdc = g.GetHdc();
|
|
233
|
+
bool ok = PrintWindow(hwnd, hdc, 2);
|
|
234
|
+
g.ReleaseHdc();
|
|
235
|
+
if (!ok) res.error = "PrintWindow(2) returned false; ";
|
|
236
|
+
}
|
|
237
|
+
int d = Distinct(full, out transparent);
|
|
238
|
+
res.method = "printwindow-full"; res.distinct = d;
|
|
239
|
+
res.blank = (d <= 1 || transparent);
|
|
240
|
+
if (!res.blank) {
|
|
241
|
+
using (Bitmap bmp = Fit(full, w, h)) { res.png = ToPng(bmp); }
|
|
242
|
+
return res;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
// attempt 2: plain PrintWindow (0), also at native size
|
|
246
|
+
using (Bitmap full2 = new Bitmap(nw, nh, PixelFormat.Format32bppArgb)) {
|
|
247
|
+
using (Graphics g = Graphics.FromImage(full2)) {
|
|
248
|
+
IntPtr hdc = g.GetHdc();
|
|
249
|
+
PrintWindow(hwnd, hdc, 0);
|
|
250
|
+
g.ReleaseHdc();
|
|
251
|
+
}
|
|
252
|
+
int d = Distinct(full2, out transparent);
|
|
253
|
+
if (d > res.distinct) { res.distinct = d; }
|
|
254
|
+
res.method = "printwindow";
|
|
255
|
+
res.blank = (d <= 1 || transparent);
|
|
256
|
+
if (!res.blank) {
|
|
257
|
+
using (Bitmap bmp = Fit(full2, w, h)) { res.png = ToPng(bmp); }
|
|
258
|
+
return res;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// attempt 3: BitBlt from screen (only what is actually visible), native region then scaled
|
|
262
|
+
using (Bitmap full3 = new Bitmap(nw, nh, PixelFormat.Format32bppArgb)) {
|
|
263
|
+
IntPtr screen = GetDC(IntPtr.Zero);
|
|
264
|
+
using (Graphics g = Graphics.FromImage(full3)) {
|
|
265
|
+
IntPtr hdc = g.GetHdc();
|
|
266
|
+
BitBlt(hdc, 0, 0, nw, nh, screen, r.Left, r.Top, 0x00CC0020u);
|
|
267
|
+
g.ReleaseHdc();
|
|
268
|
+
}
|
|
269
|
+
ReleaseDC(IntPtr.Zero, screen);
|
|
270
|
+
int d = Distinct(full3, out transparent);
|
|
271
|
+
res.method = "bitblt"; res.distinct = d;
|
|
272
|
+
res.blank = (d <= 1 || transparent);
|
|
273
|
+
using (Bitmap bmp = Fit(full3, w, h)) { res.png = ToPng(bmp); }
|
|
274
|
+
return res;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
static byte[] ToPng(Bitmap bmp) {
|
|
279
|
+
using (MemoryStream ms = new MemoryStream()) {
|
|
280
|
+
bmp.Save(ms, ImageFormat.Png);
|
|
281
|
+
return ms.ToArray();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
public static string ProcName(int pid) {
|
|
286
|
+
try { return Process.GetProcessById(pid).ProcessName; } catch { return ""; }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
[DllImport("user32.dll")] static extern IntPtr SetProcessDpiAwarenessContext(IntPtr ctx);
|
|
290
|
+
static int g_aware = 0;
|
|
291
|
+
// 0 = not applied, 1 = SetProcessDPIAware (system aware), 2 = per-monitor v2 context
|
|
292
|
+
public static int MakeAware() {
|
|
293
|
+
if (g_aware != 0) return g_aware;
|
|
294
|
+
try {
|
|
295
|
+
IntPtr r = SetProcessDpiAwarenessContext(new IntPtr(-4)); // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
|
|
296
|
+
if (r != IntPtr.Zero) { g_aware = 2; return g_aware; }
|
|
297
|
+
} catch { }
|
|
298
|
+
try { if (SetProcessDPIAware()) { g_aware = 1; return g_aware; } } catch { }
|
|
299
|
+
return 0;
|
|
300
|
+
}
|
|
301
|
+
public static int Awareness { get { return g_aware; } }
|
|
302
|
+
public static int PhysWidth { get { return GetSystemMetrics(0); } }
|
|
303
|
+
public static int PhysHeight { get { return GetSystemMetrics(1); } }
|
|
304
|
+
|
|
305
|
+
// ---- physical pointer channel ---------------------------------------------------------
|
|
306
|
+
// Motion is SendInput with MOUSEEVENTF_ABSOLUTE only. SetCursorPos is deliberately NOT
|
|
307
|
+
// declared anywhere in this file: a pointer that is placed instead of moved produces one
|
|
308
|
+
// observable position instead of a trajectory, and the whole point of this channel is that
|
|
309
|
+
// the trajectory can be measured by an independent sampler.
|
|
310
|
+
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; }
|
|
311
|
+
|
|
312
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
313
|
+
public struct MOUSEINPUT {
|
|
314
|
+
public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo;
|
|
315
|
+
}
|
|
316
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
317
|
+
public struct KEYBDINPUT {
|
|
318
|
+
public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo;
|
|
319
|
+
}
|
|
320
|
+
// Both arms share offset 0 in an explicit union so Marshal.SizeOf(INPUT) stays the native
|
|
321
|
+
// 40 bytes (x64) for mouse AND keyboard events -- SendInput rejects a cbSize that disagrees with
|
|
322
|
+
// sizeof(INPUT), so the keyboard path must reuse the same union, not a smaller struct.
|
|
323
|
+
[StructLayout(LayoutKind.Explicit)]
|
|
324
|
+
public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
|
|
325
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
326
|
+
public struct INPUT { public uint type; public INPUTUNION u; }
|
|
327
|
+
|
|
328
|
+
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
|
|
329
|
+
[DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vKey);
|
|
330
|
+
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
|
|
331
|
+
[DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
|
|
332
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowTextW(IntPtr h, System.Text.StringBuilder buf, int max);
|
|
333
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassNameW(IntPtr h, System.Text.StringBuilder buf, int max);
|
|
334
|
+
[DllImport("winmm.dll")] public static extern uint timeBeginPeriod(uint ms);
|
|
335
|
+
[DllImport("winmm.dll")] public static extern uint timeEndPeriod(uint ms);
|
|
336
|
+
|
|
337
|
+
const uint MF_MOVE = 0x0001u;
|
|
338
|
+
const uint MF_LDOWN = 0x0002u, MF_LUP = 0x0004u;
|
|
339
|
+
const uint MF_RDOWN = 0x0008u, MF_RUP = 0x0010u;
|
|
340
|
+
const uint MF_MDOWN = 0x0020u, MF_MUP = 0x0040u;
|
|
341
|
+
const uint MF_ABSOLUTE = 0x8000u;
|
|
342
|
+
const uint MF_VIRTUALDESK = 0x4000u;
|
|
343
|
+
const uint KF_UNICODE = 0x0004u, KF_KEYUP = 0x0002u;
|
|
344
|
+
|
|
345
|
+
public static int InputByteSize { get { return Marshal.SizeOf(typeof(INPUT)); } }
|
|
346
|
+
|
|
347
|
+
static INPUT MkMouse(int dx, int dy, uint flags, uint data) {
|
|
348
|
+
INPUT i = new INPUT();
|
|
349
|
+
i.type = 0u; // INPUT_MOUSE
|
|
350
|
+
i.u.mi.dx = dx; i.u.mi.dy = dy;
|
|
351
|
+
i.u.mi.mouseData = data; i.u.mi.dwFlags = flags;
|
|
352
|
+
i.u.mi.time = 0u; i.u.mi.dwExtraInfo = IntPtr.Zero;
|
|
353
|
+
return i;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
static INPUT MkKey(ushort vk, ushort scan, uint flags) {
|
|
357
|
+
INPUT i = new INPUT();
|
|
358
|
+
i.type = 1u; // INPUT_KEYBOARD
|
|
359
|
+
i.u.ki.wVk = vk; i.u.ki.wScan = scan; i.u.ki.dwFlags = flags;
|
|
360
|
+
i.u.ki.time = 0u; i.u.ki.dwExtraInfo = IntPtr.Zero;
|
|
361
|
+
return i;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Type a string into the focused control via KEYEVENTF_UNICODE: each UTF-16 code unit is sent as a
|
|
365
|
+
// down+up pair. This is the only SendInput path that types CJK reliably (VK/SendKeys cannot), which
|
|
366
|
+
// is what "type 你好 into WeChat's box" needs. Returns the number of INPUT events the OS accepted.
|
|
367
|
+
public static int SendUnicode(string s) {
|
|
368
|
+
if (string.IsNullOrEmpty(s)) return 0;
|
|
369
|
+
System.Collections.Generic.List<INPUT> list = new System.Collections.Generic.List<INPUT>();
|
|
370
|
+
foreach (char c in s) {
|
|
371
|
+
list.Add(MkKey(0, c, KF_UNICODE));
|
|
372
|
+
list.Add(MkKey(0, c, KF_UNICODE | KF_KEYUP));
|
|
373
|
+
}
|
|
374
|
+
INPUT[] arr = list.ToArray();
|
|
375
|
+
return (int)SendInput((uint)arr.Length, arr, Marshal.SizeOf(typeof(INPUT)));
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// Every event on this path carries ABSOLUTE|VIRTUALDESK|MOVE plus the button bit, so the
|
|
379
|
+
// pointer position is asserted by the same event that presses or releases: a button event
|
|
380
|
+
// can never land somewhere other than the point the caller asked for.
|
|
381
|
+
static uint AbsEvent(int nx, int ny, uint buttonFlags) {
|
|
382
|
+
INPUT[] a = new INPUT[] { MkMouse(nx, ny, MF_ABSOLUTE | MF_VIRTUALDESK | MF_MOVE | buttonFlags, 0u) };
|
|
383
|
+
return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT)));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
public static uint AbsMove(int nx, int ny) { return AbsEvent(nx, ny, 0u); }
|
|
387
|
+
|
|
388
|
+
public static int DownFlag(string button) {
|
|
389
|
+
if (button == "right") return (int)MF_RDOWN;
|
|
390
|
+
if (button == "middle") return (int)MF_MDOWN;
|
|
391
|
+
return (int)MF_LDOWN;
|
|
392
|
+
}
|
|
393
|
+
public static int UpFlag(string button) {
|
|
394
|
+
if (button == "right") return (int)MF_RUP;
|
|
395
|
+
if (button == "middle") return (int)MF_MUP;
|
|
396
|
+
return (int)MF_LUP;
|
|
397
|
+
}
|
|
398
|
+
public static uint AbsButtonDown(int nx, int ny, string button) { return AbsEvent(nx, ny, (uint)DownFlag(button)); }
|
|
399
|
+
public static uint AbsButtonUp(int nx, int ny, string button) { return AbsEvent(nx, ny, (uint)UpFlag(button)); }
|
|
400
|
+
|
|
401
|
+
const uint MF_WHEEL = 0x0800u, MF_HWHEEL = 0x1000u;
|
|
402
|
+
// Wheel events also carry ABSOLUTE|VIRTUALDESK|MOVE so the scroll happens at the asserted point,
|
|
403
|
+
// same guarantee as the button events. delta is in WHEEL_DELTA units (120/notch), negative = down/left.
|
|
404
|
+
public static uint AbsWheel(int nx, int ny, int delta) {
|
|
405
|
+
INPUT[] a = new INPUT[] { MkMouse(nx, ny, MF_ABSOLUTE | MF_VIRTUALDESK | MF_MOVE | MF_WHEEL, (uint)delta) };
|
|
406
|
+
return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT)));
|
|
407
|
+
}
|
|
408
|
+
public static uint AbsHWheel(int nx, int ny, int delta) {
|
|
409
|
+
INPUT[] a = new INPUT[] { MkMouse(nx, ny, MF_ABSOLUTE | MF_VIRTUALDESK | MF_MOVE | MF_HWHEEL, (uint)delta) };
|
|
410
|
+
return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT)));
|
|
411
|
+
}
|
|
412
|
+
// VK key down/up for control keys and hotkeys (Enter/Tab/arrows/Ctrl+C...). KEYEVENTF_KEYUP = 0x2.
|
|
413
|
+
public static uint KeyDownVk(int vk) { INPUT[] a = new INPUT[] { MkKey((ushort)vk, 0, 0u) }; return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT))); }
|
|
414
|
+
public static uint KeyUpVk(int vk) { INPUT[] a = new INPUT[] { MkKey((ushort)vk, 0, KF_KEYUP) }; return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT))); }
|
|
415
|
+
|
|
416
|
+
// one GetCursorPos call, both axes: [0]=x [1]=y, physical pixels for a DPI-aware worker
|
|
417
|
+
public static int[] CursorXY() {
|
|
418
|
+
POINT p = new POINT();
|
|
419
|
+
try { if (!GetCursorPos(out p)) return new int[] { -1, -1 }; } catch { return new int[] { -1, -1 }; }
|
|
420
|
+
return new int[] { p.x, p.y };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
public class HitInfo {
|
|
424
|
+
public long hit = 0; public long root = 0; public long pid = 0;
|
|
425
|
+
public string hitClass = ""; public string rootClass = ""; public string title = "";
|
|
426
|
+
}
|
|
427
|
+
// What is actually under a screen point right now. The overlay windows this plugin draws are
|
|
428
|
+
// WS_EX_TRANSPARENT, so WindowFromPoint skips them and the answer is the real target window.
|
|
429
|
+
public static HitInfo HitTest(int x, int y) {
|
|
430
|
+
HitInfo r = new HitInfo();
|
|
431
|
+
POINT p = new POINT(); p.x = x; p.y = y;
|
|
432
|
+
IntPtr h = IntPtr.Zero;
|
|
433
|
+
try { h = WindowFromPoint(p); } catch { h = IntPtr.Zero; }
|
|
434
|
+
r.hit = (h == IntPtr.Zero ? 0 : h.ToInt64());
|
|
435
|
+
IntPtr root = RootOf(h);
|
|
436
|
+
r.root = (root == IntPtr.Zero ? 0 : root.ToInt64());
|
|
437
|
+
r.hitClass = ClassOf(h);
|
|
438
|
+
r.rootClass = ClassOf(root);
|
|
439
|
+
r.title = TitleOf(root);
|
|
440
|
+
uint pid = 0;
|
|
441
|
+
try { GetWindowThreadProcessId(root, out pid); } catch { pid = 0; }
|
|
442
|
+
r.pid = pid;
|
|
443
|
+
return r;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
public static IntPtr WindowUnder(int x, int y) {
|
|
447
|
+
POINT p = new POINT(); p.x = x; p.y = y;
|
|
448
|
+
try { return WindowFromPoint(p); } catch { return IntPtr.Zero; }
|
|
449
|
+
}
|
|
450
|
+
public static IntPtr RootOf(IntPtr h) {
|
|
451
|
+
if (h == IntPtr.Zero) return IntPtr.Zero;
|
|
452
|
+
try { IntPtr r = GetAncestor(h, 2u); return (r == IntPtr.Zero) ? h : r; } catch { return h; }
|
|
453
|
+
}
|
|
454
|
+
// self-or-descendant: is `node` the ancestor itself or living inside it (GA_PARENT walk)?
|
|
455
|
+
public static bool IsSelfOrDescendant(IntPtr node, IntPtr ancestor) {
|
|
456
|
+
if (node == IntPtr.Zero || ancestor == IntPtr.Zero) return false;
|
|
457
|
+
IntPtr cur = node;
|
|
458
|
+
for (int i = 0; i < 40 && cur != IntPtr.Zero; i++) {
|
|
459
|
+
if (cur == ancestor) return true;
|
|
460
|
+
IntPtr par;
|
|
461
|
+
try { par = GetAncestor(cur, 1u); } catch { break; } // GA_PARENT
|
|
462
|
+
if (par == IntPtr.Zero || par == cur) break;
|
|
463
|
+
cur = par;
|
|
464
|
+
}
|
|
465
|
+
return false;
|
|
466
|
+
}
|
|
467
|
+
public static string TitleOf(IntPtr h) {
|
|
468
|
+
if (h == IntPtr.Zero) return "";
|
|
469
|
+
System.Text.StringBuilder sb = new System.Text.StringBuilder(512);
|
|
470
|
+
try { GetWindowTextW(h, sb, sb.Capacity); } catch { return ""; }
|
|
471
|
+
return sb.ToString();
|
|
472
|
+
}
|
|
473
|
+
public static string ClassOf(IntPtr h) {
|
|
474
|
+
if (h == IntPtr.Zero) return "";
|
|
475
|
+
System.Text.StringBuilder sb = new System.Text.StringBuilder(256);
|
|
476
|
+
try { GetClassNameW(h, sb, sb.Capacity); } catch { return ""; }
|
|
477
|
+
return sb.ToString();
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// win32 truth about where the input focus and the caret actually are. Used to prove that a
|
|
481
|
+
// physical click landed in a document, rather than only proving that an event was queued.
|
|
482
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
483
|
+
public struct GUITHREADINFO {
|
|
484
|
+
public int cbSize; public int flags;
|
|
485
|
+
public IntPtr hwndActive; public IntPtr hwndFocus; public IntPtr hwndCapture;
|
|
486
|
+
public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize; public IntPtr hwndCaret;
|
|
487
|
+
public RECT rcCaret;
|
|
488
|
+
}
|
|
489
|
+
[DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint idThread, out GUITHREADINFO r);
|
|
490
|
+
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h, ref POINT p);
|
|
491
|
+
// rcCaret is client-relative for some providers (Win11 Notepad's RichEditD2DPT is one) and
|
|
492
|
+
// screen-absolute for others, so both readings are returned and the caller can tell which one
|
|
493
|
+
// lines up with the element it is looking at.
|
|
494
|
+
public static int[] ClientToScreenPt(long hwnd, int x, int y) {
|
|
495
|
+
POINT p = new POINT(); p.x = x; p.y = y;
|
|
496
|
+
try { if (hwnd != 0 && ClientToScreen(new IntPtr(hwnd), ref p)) return new int[] { p.x, p.y }; } catch { }
|
|
497
|
+
return new int[] { x, y };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
public class CaretInfo {
|
|
501
|
+
public long hwndFocus = 0; public long hwndCaret = 0; public long tid = 0;
|
|
502
|
+
public int x = 0; public int y = 0; public int w = 0; public int h = 0;
|
|
503
|
+
public int sx = 0; public int sy = 0;
|
|
504
|
+
public bool hasCaret = false;
|
|
505
|
+
}
|
|
506
|
+
// The second instrument for "the click landed": UIA reports which element has focus,
|
|
507
|
+
// GetGUIThreadInfo reports which window owns the caret and where the system put it.
|
|
508
|
+
public static CaretInfo FindCaret(int pid) {
|
|
509
|
+
CaretInfo r = new CaretInfo();
|
|
510
|
+
try {
|
|
511
|
+
Process p = Process.GetProcessById(pid);
|
|
512
|
+
foreach (ProcessThread pt in p.Threads) {
|
|
513
|
+
GUITHREADINFO g = new GUITHREADINFO();
|
|
514
|
+
g.cbSize = Marshal.SizeOf(typeof(GUITHREADINFO));
|
|
515
|
+
bool got = false;
|
|
516
|
+
try { got = GetGUIThreadInfo((uint)pt.Id, out g); } catch { got = false; }
|
|
517
|
+
if (!got) continue;
|
|
518
|
+
if (g.hwndFocus == IntPtr.Zero && g.hwndCaret == IntPtr.Zero) continue;
|
|
519
|
+
r.hwndFocus = g.hwndFocus.ToInt64();
|
|
520
|
+
r.hwndCaret = g.hwndCaret.ToInt64();
|
|
521
|
+
r.x = g.rcCaret.Left; r.y = g.rcCaret.Top;
|
|
522
|
+
r.w = g.rcCaret.Right - g.rcCaret.Left; r.h = g.rcCaret.Bottom - g.rcCaret.Top;
|
|
523
|
+
int[] sc = ClientToScreenPt(r.hwndCaret, r.x, r.y);
|
|
524
|
+
r.sx = sc[0]; r.sy = sc[1];
|
|
525
|
+
r.tid = pt.Id;
|
|
526
|
+
r.hasCaret = (g.hwndCaret != IntPtr.Zero);
|
|
527
|
+
if (g.hwndCaret != IntPtr.Zero) break; // prefer the thread that actually owns a caret
|
|
528
|
+
}
|
|
529
|
+
} catch { }
|
|
530
|
+
return r;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
'@
|
|
534
|
+
$script:nativeMs = 0
|
|
535
|
+
$t0 = [Diagnostics.Stopwatch]::GetTimestamp()
|
|
536
|
+
$script:nativeLoaded = $false
|
|
537
|
+
$script:dpiMode = 0
|
|
538
|
+
try {
|
|
539
|
+
Add-Type -TypeDefinition $script:nativeSrc -ReferencedAssemblies @('System.Drawing', 'System.Core') -ErrorAction Stop
|
|
540
|
+
$script:nativeLoaded = $true
|
|
541
|
+
} catch {
|
|
542
|
+
Log ('Add-Type native helper failed: ' + $_.Exception.Message)
|
|
543
|
+
}
|
|
544
|
+
if ($script:nativeLoaded) {
|
|
545
|
+
try { $script:dpiMode = [Native]::MakeAware() } catch { Log ('MakeAware threw: ' + $_.Exception.Message) }
|
|
546
|
+
}
|
|
547
|
+
$script:nativeMs = [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $t0) / 10000.0, 1)
|
|
548
|
+
|
|
549
|
+
# ---------------------------------------------------------------- framing / io
|
|
550
|
+
$script:utf8NoBom = New-Object System.Text.UTF8Encoding($false)
|
|
551
|
+
try {
|
|
552
|
+
[Console]::InputEncoding = $script:utf8NoBom
|
|
553
|
+
[Console]::OutputEncoding = $script:utf8NoBom
|
|
554
|
+
} catch { }
|
|
555
|
+
|
|
556
|
+
# The stdio JSON helpers (Esc/JsonOf/OneLine/Err/ArgOf/IntArg/StrArg/BoolArg/Dict/
|
|
557
|
+
# Split-Err) are shared verbatim with indicator-server.ps1 via ps-stdio.ps1; the
|
|
558
|
+
# escaping contract ("absent vs null" fields, 7-bit clean pipe) is documented there.
|
|
559
|
+
# Send-Ok/Send-Err stay here: they write $script:W.stats, which is worker-owned.
|
|
560
|
+
. (Join-Path $PSScriptRoot 'ps-stdio.ps1')
|
|
561
|
+
|
|
562
|
+
function Send-Ok($id, $result) {
|
|
563
|
+
$script:W.stats.commands += 1
|
|
564
|
+
$r = [ordered]@{ id = $id; ok = $true }
|
|
565
|
+
if ($null -ne $result) { $r['result'] = $result }
|
|
566
|
+
$r['stats'] = $script:W.stats
|
|
567
|
+
[Console]::Out.Write((JsonOf $r))
|
|
568
|
+
[Console]::Out.Write("`n")
|
|
569
|
+
[Console]::Out.Flush()
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function Send-Err($id, $code, $message) {
|
|
573
|
+
$script:W.stats.commands += 1
|
|
574
|
+
$script:W.stats.refused += 1
|
|
575
|
+
$r = [ordered]@{ id = $id; ok = $false; code = [string]$code; error = (OneLine $message) }
|
|
576
|
+
$r['stats'] = $script:W.stats
|
|
577
|
+
[Console]::Out.Write((JsonOf $r))
|
|
578
|
+
[Console]::Out.Write("`n")
|
|
579
|
+
[Console]::Out.Flush()
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function ListOf($o) {
|
|
583
|
+
if ($null -eq $o) { return @() }
|
|
584
|
+
if ($o -is [System.Collections.IEnumerable] -and -not ($o -is [string])) { return @($o) }
|
|
585
|
+
return @($o)
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
# deadline helpers -------------------------------------------------------------
|
|
589
|
+
function TickNow { return [Diagnostics.Stopwatch]::GetTimestamp() }
|
|
590
|
+
function MsFrom($startTick) { return [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $startTick) / 10000.0, 1) }
|
|
591
|
+
function Set-Deadline($ms) {
|
|
592
|
+
if ($ms -le 0) { $script:W.dl = [Int64]::MaxValue } else { $script:W.dl = (TickNow) + ([Int64]$ms * 10000) }
|
|
593
|
+
}
|
|
594
|
+
function Test-Deadline($what) {
|
|
595
|
+
if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) {
|
|
596
|
+
Err 'deadline_exceeded' ("budget exhausted during " + $what)
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function BudgetLeftMs {
|
|
600
|
+
if ($script:W.dl -eq [Int64]::MaxValue) { return 9.0E+14 }
|
|
601
|
+
$left = ($script:W.dl - (TickNow)) / 10000.0
|
|
602
|
+
if ($left -lt 0) { return 0 }
|
|
603
|
+
return [Math]::Round($left, 1)
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
Log ("ready ps=" + $PSVersionTable.PSVersion.ToString() + " assemblies=" + $script:asmMs + 'ms native=' + $script:nativeMs + 'ms pid=' + $PID)
|
|
607
|
+
|
|
608
|
+
# ---------------------------------------------------------------- uiA plumbing
|
|
609
|
+
$script:ctCache = @{}
|
|
610
|
+
function ControlTypeName($ct) {
|
|
611
|
+
if ($null -eq $ct) { return 'Unknown' }
|
|
612
|
+
$key = $null
|
|
613
|
+
try { $key = $ct.Id } catch { }
|
|
614
|
+
# Some providers return a partial ControlType with no Id. Hashtable.Item(null) throws,
|
|
615
|
+
# and unknown types must not poison the shared cache for later, healthy nodes.
|
|
616
|
+
if ($null -ne $key -and $script:ctCache.ContainsKey($key)) { return $script:ctCache[$key] }
|
|
617
|
+
$n = ''
|
|
618
|
+
try { $n = [string]$ct.ProgrammaticName } catch { }
|
|
619
|
+
if ($n -ne '') { $n = ($n -split '\.')[-1] }
|
|
620
|
+
if ([string]::IsNullOrEmpty($n)) { return 'Unknown' }
|
|
621
|
+
if ($null -ne $key) { $script:ctCache[$key] = $n }
|
|
622
|
+
return $n
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
$script:patCache = @{}
|
|
626
|
+
# GetSupportedPatterns() returns AutomationPattern objects (NOT AutomationPatternInfo): the
|
|
627
|
+
# usable name is $q.ProgrammaticName, shaped "ValuePatternIdentifiers.Pattern"; $q.Id is a bare
|
|
628
|
+
# int (10002) and has no ProgrammaticName, so reading $q.Id.ProgrammaticName yields '' and every
|
|
629
|
+
# node used to report an empty pattern list.
|
|
630
|
+
#
|
|
631
|
+
# The COM call itself cannot be avoided (78% of nodes in a real tree are interactive, so filtering
|
|
632
|
+
# by type saves nothing), but the string work after it can: the same control type yields the same
|
|
633
|
+
# pattern set, and a 300-node tree is mostly repeats of a handful of types. Caching by the pattern
|
|
634
|
+
# signature keeps the per-node cost at the one round-trip instead of round-trip + regex + dedupe.
|
|
635
|
+
$script:patSetCache = @{}
|
|
636
|
+
function PatternsOf($el) {
|
|
637
|
+
# Cached elements (snapshot subtree / find_text scan) build the list from the cached
|
|
638
|
+
# availability with no cross-process round-trip; anything without a usable cache keeps the
|
|
639
|
+
# live GetSupportedPatterns path below (the fallback is reserved for cache-read failures, and
|
|
640
|
+
# the mock/test harnesses stub this whole function out).
|
|
641
|
+
try {
|
|
642
|
+
$cached = Cached-PatternsOf $el
|
|
643
|
+
if ($null -ne $cached) { return ,$cached }
|
|
644
|
+
} catch { }
|
|
645
|
+
$names = @()
|
|
646
|
+
try {
|
|
647
|
+
$sp = $el.GetSupportedPatterns()
|
|
648
|
+
if ($null -ne $sp) {
|
|
649
|
+
# Build the signature cheaply, then look the friendly list up once per distinct signature.
|
|
650
|
+
# Every value that reaches a Hashtable key or a List[string] is normalised to a non-empty
|
|
651
|
+
# string first: a provider that reports a pattern with no ProgrammaticName and no Id used to
|
|
652
|
+
# put $null into both, and Hashtable indexing with $null throws "Key cannot be null" — which
|
|
653
|
+
# surfaced as a whole snapshot failing with internal_error.
|
|
654
|
+
$sigParts = New-Object System.Collections.Generic.List[string]
|
|
655
|
+
foreach ($q in $sp) {
|
|
656
|
+
$pk = ''
|
|
657
|
+
try { $pk = [string]$q.ProgrammaticName } catch { $pk = '' }
|
|
658
|
+
if ([string]::IsNullOrEmpty($pk)) {
|
|
659
|
+
$qid = -1
|
|
660
|
+
try { $qid = [int]$q.Id } catch { $qid = -1 }
|
|
661
|
+
$pk = 'id:' + $qid
|
|
662
|
+
}
|
|
663
|
+
$sigParts.Add($pk) | Out-Null
|
|
664
|
+
}
|
|
665
|
+
$sig = ($sigParts | Sort-Object) -join '|'
|
|
666
|
+
if ($sig -ne '') {
|
|
667
|
+
$hit = $script:patSetCache[$sig]
|
|
668
|
+
if ($null -ne $hit) { return ,$hit }
|
|
669
|
+
}
|
|
670
|
+
foreach ($pk in $sigParts) {
|
|
671
|
+
if ([string]::IsNullOrEmpty($pk)) { continue }
|
|
672
|
+
$friendly = $null
|
|
673
|
+
if ($script:patCache.ContainsKey($pk)) { $friendly = $script:patCache[$pk] }
|
|
674
|
+
if ($null -eq $friendly) {
|
|
675
|
+
if ($pk -match '^(.*?)PatternIdentifiers\.Pattern$') {
|
|
676
|
+
$friendly = $matches[1]
|
|
677
|
+
} else {
|
|
678
|
+
$n = ($pk -split '\.')[-1]
|
|
679
|
+
$n = $n -replace 'Pattern$', ''
|
|
680
|
+
$n = $n -replace 'Identifiers$', ''
|
|
681
|
+
$friendly = $n
|
|
682
|
+
}
|
|
683
|
+
if ([string]::IsNullOrEmpty($friendly)) { continue }
|
|
684
|
+
$script:patCache[$pk] = $friendly
|
|
685
|
+
}
|
|
686
|
+
if ($friendly -ne '' -and ($names -notcontains $friendly)) { $names += $friendly }
|
|
687
|
+
}
|
|
688
|
+
# Remember this exact pattern set for the next node that has the same one. Bounded: a
|
|
689
|
+
# long-lived worker walking many windows must not grow this without limit.
|
|
690
|
+
if ($sig -ne '' -and $script:patSetCache.Count -lt 512) { $script:patSetCache[$sig] = $names }
|
|
691
|
+
}
|
|
692
|
+
} catch { }
|
|
693
|
+
return ,$names
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
# The pattern list of a CACHED element (one that came back from GetUpdatedCache or from a walker
|
|
697
|
+
# request overload): built from the cached Is*PatternAvailable properties — zero cross-process
|
|
698
|
+
# calls. Returns $null when the element carries no usable cache (a live element throws on
|
|
699
|
+
# GetCachedPropertyValue), which is the caller's signal to fall back to the live
|
|
700
|
+
# GetSupportedPatterns path. Every Is*PatternAvailableProperty the managed client has IS cached
|
|
701
|
+
# (probe-verified: all exist; IsLegacyIAccessiblePatternAvailableProperty does not — there is no
|
|
702
|
+
# managed wrapper type for that pattern, so it can neither be requested nor reported here, and
|
|
703
|
+
# LegacyIAccessible is deliberately absent from a cached pattern list: the capability table
|
|
704
|
+
# computer_act checks (tools.js NEEDED) never names it and the rendered tree filters patterns
|
|
705
|
+
# through ACTIONABLE, which never showed it either).
|
|
706
|
+
$script:cachedPatProps = @(
|
|
707
|
+
'IsDockPatternAvailableProperty', 'IsExpandCollapsePatternAvailableProperty', 'IsGridItemPatternAvailableProperty',
|
|
708
|
+
'IsGridPatternAvailableProperty', 'IsInvokePatternAvailableProperty', 'IsItemContainerPatternAvailableProperty',
|
|
709
|
+
'IsMultipleViewPatternAvailableProperty', 'IsRangeValuePatternAvailableProperty', 'IsScrollItemPatternAvailableProperty',
|
|
710
|
+
'IsScrollPatternAvailableProperty', 'IsSelectionItemPatternAvailableProperty', 'IsSelectionPatternAvailableProperty',
|
|
711
|
+
'IsTableItemPatternAvailableProperty', 'IsTablePatternAvailableProperty', 'IsTextPatternAvailableProperty',
|
|
712
|
+
'IsTogglePatternAvailableProperty', 'IsTransformPatternAvailableProperty', 'IsValuePatternAvailableProperty',
|
|
713
|
+
'IsWindowPatternAvailableProperty'
|
|
714
|
+
)
|
|
715
|
+
function Cached-PatternsOf($el) {
|
|
716
|
+
if ($null -eq $el) { return $null }
|
|
717
|
+
$names = @()
|
|
718
|
+
$any = $false
|
|
719
|
+
foreach ($p in $script:cachedPatProps) {
|
|
720
|
+
$v = $null
|
|
721
|
+
try { $v = $el.GetCachedPropertyValue([System.Windows.Automation.AutomationElement]::$p) } catch { return $null }
|
|
722
|
+
$any = $true
|
|
723
|
+
if ($v -is [bool] -and $v) {
|
|
724
|
+
$n = ([string]$p) -replace '^Is', '' -replace 'PatternAvailableProperty$', ''
|
|
725
|
+
if ($n -ne '' -and ($names -notcontains $n)) { $names += $n }
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
if (-not $any) { return $null }
|
|
729
|
+
return $names
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
$patternTypes = @{
|
|
733
|
+
Invoke = [System.Windows.Automation.InvokePattern]
|
|
734
|
+
Value = [System.Windows.Automation.ValuePattern]
|
|
735
|
+
Toggle = [System.Windows.Automation.TogglePattern]
|
|
736
|
+
SelectionItem = [System.Windows.Automation.SelectionItemPattern]
|
|
737
|
+
ExpandCollapse = [System.Windows.Automation.ExpandCollapsePattern]
|
|
738
|
+
Scroll = [System.Windows.Automation.ScrollPattern]
|
|
739
|
+
RangeValue = [System.Windows.Automation.RangeValuePattern]
|
|
740
|
+
Window = [System.Windows.Automation.WindowPattern]
|
|
741
|
+
Transform = [System.Windows.Automation.TransformPattern]
|
|
742
|
+
Text = [System.Windows.Automation.TextPattern]
|
|
743
|
+
GridItem = [System.Windows.Automation.GridItemPattern]
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
function GetPattern($el, $name) {
|
|
747
|
+
if (-not $patternTypes.ContainsKey($name)) { return $null }
|
|
748
|
+
try {
|
|
749
|
+
$p = $el.GetCurrentPattern($patternTypes[$name]::Pattern)
|
|
750
|
+
if ($null -eq $p) { return $null }
|
|
751
|
+
return $p
|
|
752
|
+
} catch { return $null }
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
# Same lookup as GetPattern, but the pattern OBJECT is kept on the ref record. The act sequence
|
|
756
|
+
# before → action → after used to call GetCurrentPattern for the SAME pattern three times (three
|
|
757
|
+
# cross-process round-trips for one set_value). Invalidated by Resolve-Ref on rebind, because the
|
|
758
|
+
# cached object is bound to the element it was fetched from.
|
|
759
|
+
function Get-RefPattern($re, $name) {
|
|
760
|
+
if ($null -eq $re) { return $null }
|
|
761
|
+
if ($null -eq $re.patCache) { $re.patCache = @{} }
|
|
762
|
+
if ($re.patCache.ContainsKey($name)) { return $re.patCache[$name] }
|
|
763
|
+
$p = GetPattern $re.ae $name
|
|
764
|
+
$re.patCache[$name] = $p
|
|
765
|
+
return $p
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function RectOf($cp) {
|
|
769
|
+
try {
|
|
770
|
+
$r = $cp.BoundingRectangle
|
|
771
|
+
if ($null -eq $r -or [double]::IsNaN($r.X) -or [double]::IsNaN($r.Width)) { return @{ x = 0; y = 0; w = 0; h = 0 } }
|
|
772
|
+
# an empty WPF-style Rect comes back as X=Infinity / Width=-Infinity; [int] on that throws
|
|
773
|
+
if ([double]::IsInfinity($r.X) -or [double]::IsInfinity($r.Width) -or [double]::IsInfinity($r.Height) -or [double]::IsInfinity($r.Y)) {
|
|
774
|
+
return @{ x = 0; y = 0; w = 0; h = 0 }
|
|
775
|
+
}
|
|
776
|
+
if ($r.Width -le 0 -or $r.Height -le 0) { return @{ x = [int]$r.X; y = [int]$r.Y; w = 0; h = 0 } }
|
|
777
|
+
return @{ x = [int]$r.X; y = [int]$r.Y; w = [int]$r.Width; h = [int]$r.Height }
|
|
778
|
+
} catch { return @{ x = 0; y = 0; w = 0; h = 0 } }
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function RuntimeIdKey($el) {
|
|
782
|
+
# Cached elements (snapshot subtree / find_text scan) read the runtime id from the cache —
|
|
783
|
+
# probe-verified bit-identical to GetRuntimeId() on real trees (the old comment here claimed the
|
|
784
|
+
# managed cache returns an empty array for RuntimeIdProperty; that was a probe artifact and did
|
|
785
|
+
# not reproduce on Chromium or Explorer windows, live request or GetUpdatedCache). A live element
|
|
786
|
+
# (or a provider that never cached it) keeps the live call below; both shapes land in the same
|
|
787
|
+
# comma-joined string, so the rebind identity check does not change meaning.
|
|
788
|
+
try {
|
|
789
|
+
$rid = $el.GetCachedPropertyValue([System.Windows.Automation.AutomationElement]::RuntimeIdProperty)
|
|
790
|
+
if ($null -ne $rid) { return (($rid | ForEach-Object { [string]$_ }) -join ',') }
|
|
791
|
+
} catch { }
|
|
792
|
+
try {
|
|
793
|
+
$rid = $el.GetRuntimeId()
|
|
794
|
+
if ($null -eq $rid) { return '' }
|
|
795
|
+
return (($rid | ForEach-Object { [string]$_ }) -join ',')
|
|
796
|
+
} catch { return '' }
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
function RootWindows {
|
|
800
|
+
$root = [System.Windows.Automation.AutomationElement]::RootElement
|
|
801
|
+
return @($root.FindAll([System.Windows.Automation.TreeScope]::Children, [System.Windows.Automation.Condition]::TrueCondition))
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function TruncStr([string]$s, $max) {
|
|
805
|
+
if ($null -eq $s) { return '' }
|
|
806
|
+
if ($s.Length -le $max) { return $s }
|
|
807
|
+
return $s.Substring(0, $max) + '~'
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
function ProcNameOf($procId) {
|
|
811
|
+
$k = [string]$procId
|
|
812
|
+
if ($script:W.procNames.ContainsKey($k)) { return $script:W.procNames[$k] }
|
|
813
|
+
$n = ''
|
|
814
|
+
try { $n = [Native]::ProcName([int]$procId) } catch { }
|
|
815
|
+
if ($n -eq '') {
|
|
816
|
+
try { $p = Get-Process -Id ([int]$procId) -ErrorAction SilentlyContinue; if ($null -ne $p) { $n = [string]$p.ProcessName } } catch { }
|
|
817
|
+
}
|
|
818
|
+
$script:W.procNames[$k] = $n
|
|
819
|
+
return $n
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
# ---------------------------------------------------------------- window registry
|
|
823
|
+
function Ensure-Window($hwnd, $aeHint) {
|
|
824
|
+
$hk = [string]$hwnd
|
|
825
|
+
$existing = $script:W.winByHwnd.Item($hk)
|
|
826
|
+
if ($null -ne $existing) {
|
|
827
|
+
$e = $script:W.windows.Item($existing)
|
|
828
|
+
if ($null -ne $e) { return $e }
|
|
829
|
+
}
|
|
830
|
+
$ae = $aeHint
|
|
831
|
+
if ($null -eq $ae) {
|
|
832
|
+
try { $ae = [System.Windows.Automation.AutomationElement]::FromHandle([IntPtr]$hwnd) } catch { $ae = $null }
|
|
833
|
+
}
|
|
834
|
+
if ($null -eq $ae) { return $null }
|
|
835
|
+
try { $cp = $ae.Current } catch { return $null }
|
|
836
|
+
$script:W.winSeq += 1
|
|
837
|
+
$id = 'w' + $script:W.winSeq
|
|
838
|
+
$entry = @{
|
|
839
|
+
id = $id
|
|
840
|
+
hwnd = [int]$hwnd
|
|
841
|
+
pid = [int]$cp.ProcessId
|
|
842
|
+
class = [string]$cp.ClassName
|
|
843
|
+
revision = 0
|
|
844
|
+
snapshots = New-Object System.Collections.Generic.List[object]
|
|
845
|
+
lastSeen = (TickNow)
|
|
846
|
+
}
|
|
847
|
+
$script:W.windows[$id] = $entry
|
|
848
|
+
$script:W.winByHwnd[$hk] = $id
|
|
849
|
+
return $entry
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function Window-Ae($entry) {
|
|
853
|
+
try {
|
|
854
|
+
$ae = [System.Windows.Automation.AutomationElement]::FromHandle([IntPtr]$entry.hwnd)
|
|
855
|
+
if ($null -eq $ae) { return $null }
|
|
856
|
+
$null = $ae.Current.Name
|
|
857
|
+
return $ae
|
|
858
|
+
} catch { return $null }
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
function Window-Entry($windowId) {
|
|
863
|
+
if ($null -eq $windowId -or [string]$windowId -eq '') { Err 'missing_arg' 'windowId is required' }
|
|
864
|
+
$e = $script:W.windows.Item([string]$windowId)
|
|
865
|
+
if ($null -eq $e) { Err 'unknown_window' ("no such windowId: " + $windowId + '; call list_windows or resolve_window first') }
|
|
866
|
+
return $e
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
function WindowInfo($entry, $cp) {
|
|
870
|
+
$rc = RectOf $cp
|
|
871
|
+
$fg = $false
|
|
872
|
+
try { $fg = ([Native]::GetForegroundWindow() -eq [IntPtr]$entry.hwnd) } catch { }
|
|
873
|
+
# Minimized matters to the caller: a minimized window has no usable screen rect, so stale
|
|
874
|
+
# snapshot coordinates point at nothing and pixel actions must not fire before a restore.
|
|
875
|
+
$iconic = $false
|
|
876
|
+
try { $iconic = [Native]::IsIconic([IntPtr]$entry.hwnd) } catch { }
|
|
877
|
+
return @{
|
|
878
|
+
windowId = $entry.id
|
|
879
|
+
pid = $entry.pid
|
|
880
|
+
appName = (ProcNameOf $entry.pid)
|
|
881
|
+
title = (TruncStr ([string]$cp.Name) 200)
|
|
882
|
+
class = [string]$cp.ClassName
|
|
883
|
+
hwnd = $entry.hwnd
|
|
884
|
+
rect = $rc
|
|
885
|
+
isForeground = $fg
|
|
886
|
+
isMinimized = $iconic
|
|
887
|
+
revision = $entry.revision
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
# Read-only position metadata for an observation result (snapshot / find_text): which window is
|
|
892
|
+
# foreground RIGHT NOW, where the UIA focus sits, and whether that focus lives inside the observed
|
|
893
|
+
# window (pid comparison — advisory only; a multi-process host can misreport "not in this window").
|
|
894
|
+
# The next observation after a click/type then carries free proof of whether the action took
|
|
895
|
+
# effect: the focus moved into (or out of) the target window. Every probe is try/catch-guarded —
|
|
896
|
+
# a failure just omits the field and must never fail the observation it decorates. FocusedElement
|
|
897
|
+
# can also be slow against elevated/UAC windows, so the focus probe is bounded by the request
|
|
898
|
+
# budget as well: a soft skip (no field), never a throw inside an observation.
|
|
899
|
+
function Window-ObservationHeader($entry) {
|
|
900
|
+
$obs = @{}
|
|
901
|
+
$fgHwnd = [IntPtr]::Zero
|
|
902
|
+
try { $fgHwnd = [Native]::GetForegroundWindow() } catch { }
|
|
903
|
+
if ($fgHwnd -ne [IntPtr]::Zero) {
|
|
904
|
+
try {
|
|
905
|
+
$fgPid = 0
|
|
906
|
+
try { [void][Native]::GetWindowThreadProcessId($fgHwnd, [ref]$fgPid) } catch { }
|
|
907
|
+
$fg = [ordered]@{
|
|
908
|
+
title = (TruncStr ([Native]::TitleOf($fgHwnd)) 200)
|
|
909
|
+
class = (TruncStr ([Native]::ClassOf($fgHwnd)) 120)
|
|
910
|
+
pid = [int]$fgPid
|
|
911
|
+
app = $(if ($fgPid -gt 0) { ProcNameOf ([int]$fgPid) } else { '' })
|
|
912
|
+
isTarget = $false
|
|
913
|
+
}
|
|
914
|
+
try { $fg['isTarget'] = ($fgHwnd -eq [IntPtr]$entry.hwnd) } catch { }
|
|
915
|
+
$obs['foreground'] = $fg
|
|
916
|
+
} catch { }
|
|
917
|
+
}
|
|
918
|
+
try {
|
|
919
|
+
if ((BudgetLeftMs) -gt 150) {
|
|
920
|
+
$fe = $null
|
|
921
|
+
try { $fe = [System.Windows.Automation.AutomationElement]::FocusedElement } catch { $fe = $null }
|
|
922
|
+
if ($null -ne $fe) {
|
|
923
|
+
$fcp = $fe.Current
|
|
924
|
+
$obs['focus'] = [ordered]@{
|
|
925
|
+
controlType = (ControlTypeName $fcp.ControlType)
|
|
926
|
+
name = (TruncStr ([string]$fcp.Name) 120)
|
|
927
|
+
pid = [int]$fcp.ProcessId
|
|
928
|
+
app = (ProcNameOf ([int]$fcp.ProcessId))
|
|
929
|
+
}
|
|
930
|
+
try { $obs['focusInWindow'] = ([int]$fcp.ProcessId -eq [int]$entry.pid) } catch { }
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
} catch { }
|
|
934
|
+
return $obs
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
# ---------------------------------------------------------------- ref table
|
|
938
|
+
function New-Ref($entry, $ae, $cp, $node) {
|
|
939
|
+
$script:W.refSeq += 1
|
|
940
|
+
$ref = 'e' + $script:W.refSeq
|
|
941
|
+
$re = @{
|
|
942
|
+
ref = $ref
|
|
943
|
+
windowId = $entry.id
|
|
944
|
+
hwnd = $entry.hwnd
|
|
945
|
+
revision = $entry.revision
|
|
946
|
+
ae = $ae
|
|
947
|
+
runtimeId = (RuntimeIdKey $ae)
|
|
948
|
+
controlType = $node.controlType
|
|
949
|
+
name = $node.name
|
|
950
|
+
className = $node.className
|
|
951
|
+
fullName = $node.fullName
|
|
952
|
+
automationId = $node.automationId
|
|
953
|
+
patterns = $node.patterns
|
|
954
|
+
enabled = $node.enabled
|
|
955
|
+
isOffscreen = $node.isOffscreen
|
|
956
|
+
rect = $node.rect
|
|
957
|
+
depth = $node.depth
|
|
958
|
+
rebound = $false
|
|
959
|
+
patCache = @{}
|
|
960
|
+
}
|
|
961
|
+
$script:W.refs[$ref] = $re
|
|
962
|
+
$script:W.refOrder.Add($ref)
|
|
963
|
+
$script:W.totalRefs += 1
|
|
964
|
+
if ($entry.snapshots.Count -gt 0) {
|
|
965
|
+
$entry.snapshots[$entry.snapshots.Count - 1].refs.Add($ref)
|
|
966
|
+
}
|
|
967
|
+
return $re
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
function Evict-ForReservation($needed) {
|
|
971
|
+
$evicted = @()
|
|
972
|
+
$guard = 0
|
|
973
|
+
while ($script:W.totalRefs + $needed -gt $script:W.maxRefs -and $guard -lt 400) {
|
|
974
|
+
$guard += 1
|
|
975
|
+
$victim = $null; $victimWin = $null
|
|
976
|
+
foreach ($wid in @($script:W.windows.Keys)) {
|
|
977
|
+
$e = $script:W.windows[$wid]
|
|
978
|
+
if ($null -eq $e.snapshots -or $e.snapshots.Count -le 1) { continue }
|
|
979
|
+
$cand = $e.snapshots[0]
|
|
980
|
+
if ($null -eq $victim -or $cand.createdTick -lt $victim.createdTick) { $victim = $cand; $victimWin = $e }
|
|
981
|
+
}
|
|
982
|
+
if ($null -eq $victim) { break }
|
|
983
|
+
$count = $victim.refs.Count
|
|
984
|
+
foreach ($rk in $victim.refs) {
|
|
985
|
+
# .Item($null) throws "Key cannot be null" and used to abort the whole snapshot with
|
|
986
|
+
# internal_error, because a ref list can hold an entry that never became a string key.
|
|
987
|
+
if ([string]::IsNullOrEmpty([string]$rk)) { continue }
|
|
988
|
+
$r = $null
|
|
989
|
+
if ($script:W.refs.ContainsKey($rk)) { $r = $script:W.refs[$rk] }
|
|
990
|
+
if ($null -ne $r) {
|
|
991
|
+
# Managed UIA elements are plain .NET objects (IsComObject(AutomationElement::RootElement)
|
|
992
|
+
# is False), so Marshal.ReleaseComObject always threw here and the empty catch swallowed
|
|
993
|
+
# it — a guaranteed-failing call that misled readers into seeing resource release. The
|
|
994
|
+
# wrappers are reclaimed by GC; dropping the last reference is the cleanup.
|
|
995
|
+
$r.ae = $null
|
|
996
|
+
$script:W.refs.Remove($rk) | Out-Null
|
|
997
|
+
}
|
|
998
|
+
$i = $script:W.refOrder.IndexOf($rk)
|
|
999
|
+
if ($i -ge 0) { $script:W.refOrder.RemoveAt($i) }
|
|
1000
|
+
}
|
|
1001
|
+
$victimWin.snapshots.RemoveAt(0)
|
|
1002
|
+
$script:W.totalRefs -= $count
|
|
1003
|
+
$script:W.stats.evictions += 1
|
|
1004
|
+
$evicted += @{ windowId = $victimWin.id; revision = $victim.revision; refs = $count }
|
|
1005
|
+
}
|
|
1006
|
+
return ,$evicted
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
# ---------------------------------------------------------------- descriptor matching
|
|
1010
|
+
# Match ladder, strictly ordered and never silently fuzzy:
|
|
1011
|
+
# 1. strict the caller's AND of exact UIA conditions (unchanged legacy behaviour)
|
|
1012
|
+
# 2. id automationId (+controlType/className) only; the name is allowed to churn
|
|
1013
|
+
# 3. normalizedName the name's dynamic tail normalised away, then compared exactly
|
|
1014
|
+
# 4. prefix literal substring, ONLY for an explicit nameExact:false
|
|
1015
|
+
# A level either resolves to exactly ONE element or records why it could not. Lower levels only
|
|
1016
|
+
# run when every level above produced no decision, and none of them loosens a condition the caller
|
|
1017
|
+
# did not loosen himself: nameExact:false is the only opt-in, and it selects the prefix level alone.
|
|
1018
|
+
# The outcome of the last lookup is left in $script:W.lastMatch for the descriptor_match command.
|
|
1019
|
+
|
|
1020
|
+
# Normalisation rules. Deliberately narrow: only the TAIL is rewritten, and only shapes that are
|
|
1021
|
+
# known to churn between two runs of the same recipe.
|
|
1022
|
+
# 1. trim, then collapse every whitespace run to a single space (\s already covers U+3000 / NBSP)
|
|
1023
|
+
# 2. drop a trailing relative-time token that is separated from the title by whitespace:
|
|
1024
|
+
# 刚刚 刚才 今天 昨天 前天 / N秒[前] N分钟[前] N小时[前] N天[前] N周[前] N个月[前] / H:MM[:SS]
|
|
1025
|
+
# 3. drop a trailing pure-count parenthetical: (3) (12)
|
|
1026
|
+
# steps 2-3 repeat at most 3 times so "会话 A 刚刚 (2)" needs one call
|
|
1027
|
+
# A tail glued to the title ("倒计时3分钟") is NOT touched: without a separator there is no way to
|
|
1028
|
+
# tell a churning suffix from part of the title, and this level must not guess.
|
|
1029
|
+
# Idempotent: Normalize(Normalize(x)) -eq Normalize(x).
|
|
1030
|
+
#
|
|
1031
|
+
# The tokens below are written as \uXXXX escapes ON PURPOSE. This file is UTF-8 without a BOM and
|
|
1032
|
+
# Windows PowerShell 5.1 parses source as the ANSI code page (936 here), so a literal 刚刚 in a regex
|
|
1033
|
+
# would arrive as mojibake and never match. \u521A etc. are interpreted by the regex engine, not by
|
|
1034
|
+
# the parser, so they survive any code page.
|
|
1035
|
+
function Normalize-NameText([string]$s) {
|
|
1036
|
+
if ($null -eq $s) { return '' }
|
|
1037
|
+
$t = [regex]::Replace($s, '\s+', ' ').Trim()
|
|
1038
|
+
for ($i = 0; $i -lt 3; $i++) {
|
|
1039
|
+
$before = $t
|
|
1040
|
+
$t = [regex]::Replace($t, '(?<=\s|^)\d{1,2}:\d{2}(:\d{2})?\s*$', '')
|
|
1041
|
+
$t = [regex]::Replace($t, '(?<=\s|^)(\u521A\u521A|\u521A\u624D|\u4ECA\u5929|\u6628\u5929|\u524D\u5929)\s*$', '')
|
|
1042
|
+
$t = [regex]::Replace($t, '(?<=\s|^)\d{1,3}\s*(\u79D2\u524D|\u79D2|\u5206\u949F\u524D|\u5206\u949F|\u5206\u524D|\u5206|\u5C0F\u65F6\u524D|\u5C0F\u65F6|\u65F6|\u5929\u524D|\u5929|\u5468\u524D|\u5468|\u4E2A\u6708\u524D|\u4E2A\u6708|\u6708)\s*$', '')
|
|
1043
|
+
$t = [regex]::Replace($t, '\s*[\(\uFF08]\s*\d{1,4}\s*[\)\uFF09]\s*$', '')
|
|
1044
|
+
$t = $t.Trim()
|
|
1045
|
+
if ($t -eq $before) { break }
|
|
1046
|
+
}
|
|
1047
|
+
return $t
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
# Deterministic 0..1 similarity, used ONLY to order the near-miss diagnostics of a failed lookup.
|
|
1051
|
+
# It never decides whether something matches: that is always an exact (or explicitly substring)
|
|
1052
|
+
# test. Length of the common prefix over the longer string, so it is cheap and stable.
|
|
1053
|
+
function Get-NameSimilarity([string]$a, [string]$b) {
|
|
1054
|
+
$x = [string]$a
|
|
1055
|
+
$y = [string]$b
|
|
1056
|
+
$max = [Math]::Max($x.Length, $y.Length)
|
|
1057
|
+
if ($max -eq 0) { return 1.0 }
|
|
1058
|
+
$n = [Math]::Min($x.Length, $y.Length)
|
|
1059
|
+
$i = 0
|
|
1060
|
+
while ($i -lt $n -and $x[$i] -eq $y[$i]) { $i += 1 }
|
|
1061
|
+
return [Math]::Round(([double]$i / [double]$max), 3)
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
# A caller opts into substring matching with nameExact:false. JSON booleans arrive as [bool]; the
|
|
1065
|
+
# string/number spellings are accepted too, because a hand-written recipe may quote the value and
|
|
1066
|
+
# treating "false" as truthy would silently turn the prefix level into an exact one.
|
|
1067
|
+
function Test-ExplicitFalse($dict, [string]$key) {
|
|
1068
|
+
if ($null -eq $dict) { return $false }
|
|
1069
|
+
if (-not $dict.Contains($key)) { return $false }
|
|
1070
|
+
$v = $dict.Item($key)
|
|
1071
|
+
if ($null -eq $v) { return $false }
|
|
1072
|
+
if ($v -is [bool]) { return (-not $v) }
|
|
1073
|
+
$s = ([string]$v).Trim().ToLowerInvariant()
|
|
1074
|
+
return ($s -eq 'false' -or $s -eq '0' -or $s -eq 'no')
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
function Join-UiaCondition($conds) {
|
|
1078
|
+
if ($null -eq $conds -or $conds.Count -eq 0) { return [System.Windows.Automation.Condition]::TrueCondition }
|
|
1079
|
+
if ($conds.Count -eq 1) { return $conds[0] }
|
|
1080
|
+
return New-Object System.Windows.Automation.AndCondition(($conds.ToArray()))
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
# Deterministic score for a successful resolution. The table is the whole rule:
|
|
1084
|
+
# strict 1.00 | id 0.80 | normalizedName 0.70 | prefix 0.55
|
|
1085
|
+
# chosen by nth -0.05 | chosen by nearPoint -0.03
|
|
1086
|
+
# so a caller can tell "this is the element I described" from "this is a fallback that happened to
|
|
1087
|
+
# be unique". Pinned by the regression script.
|
|
1088
|
+
function Get-MatchScore([string]$ladder, [string]$selectedBy) {
|
|
1089
|
+
$base = 0.0
|
|
1090
|
+
switch ($ladder) {
|
|
1091
|
+
'strict' { $base = 1.00; break }
|
|
1092
|
+
'id' { $base = 0.80; break }
|
|
1093
|
+
'normalizedName' { $base = 0.70; break }
|
|
1094
|
+
'prefix' { $base = 0.55; break }
|
|
1095
|
+
}
|
|
1096
|
+
if ($selectedBy -eq 'nth') { $base = $base - 0.05 }
|
|
1097
|
+
elseif ($selectedBy -eq 'nearPoint') { $base = $base - 0.03 }
|
|
1098
|
+
if ($base -lt 0.0) { $base = 0.0 }
|
|
1099
|
+
if ($base -gt 1.0) { $base = 1.0 }
|
|
1100
|
+
return [Math]::Round($base, 3)
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
# Locator confidence as it goes onto a step descriptor (prepare_batch) and a step result
|
|
1104
|
+
# (commit_batch). Returns $null when the record carries no decision — a ref step, or a lookup that
|
|
1105
|
+
# never ran the ladder — so callers add the fields ONLY when they exist. An invented
|
|
1106
|
+
# degraded=false / score=0 would be a claim about a lookup that never happened.
|
|
1107
|
+
function Get-LocatorFields($lm) {
|
|
1108
|
+
if ($null -eq $lm) { return $null }
|
|
1109
|
+
if ([string]$lm.matchedBy -eq '') { return $null }
|
|
1110
|
+
return [ordered]@{
|
|
1111
|
+
matchedBy = [string]$lm.matchedBy
|
|
1112
|
+
ladder = [string]$lm.ladder
|
|
1113
|
+
score = [double]$lm.score
|
|
1114
|
+
degraded = [bool]$lm.degraded
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
# One "closest candidate" record for a failed lookup: what it is, and why it is not the answer.
|
|
1119
|
+
function New-MatchCandidate($cp, $wantName, $wantNorm, $wantCt, $wantCn, $wantAi, $reason) {
|
|
1120
|
+
$candName = ''
|
|
1121
|
+
$candCt = ''
|
|
1122
|
+
$candCn = ''
|
|
1123
|
+
$candAi = ''
|
|
1124
|
+
try { $candName = [string]$cp.Name } catch { }
|
|
1125
|
+
try { $candCt = ControlTypeName $cp.ControlType } catch { }
|
|
1126
|
+
try { $candCn = [string]$cp.ClassName } catch { }
|
|
1127
|
+
try { $candAi = [string]$cp.AutomationId } catch { }
|
|
1128
|
+
$why = New-Object System.Collections.Generic.List[string]
|
|
1129
|
+
if ($reason -ne '') { $why.Add($reason) | Out-Null }
|
|
1130
|
+
if ($wantName -ne '' -and $candName -ne $wantName) {
|
|
1131
|
+
if ($wantNorm -ne '' -and (Normalize-NameText $candName) -eq $wantNorm) { $why.Add('name-normalized-only') | Out-Null }
|
|
1132
|
+
elseif ($candName.IndexOf($wantName, [StringComparison]::OrdinalIgnoreCase) -ge 0) { $why.Add('name-contains-only') | Out-Null }
|
|
1133
|
+
else { $why.Add('name-differs') | Out-Null }
|
|
1134
|
+
}
|
|
1135
|
+
if ($wantCt -ne '' -and $candCt -ne $wantCt) { $why.Add('controlType-differs') | Out-Null }
|
|
1136
|
+
if ($wantCn -ne '' -and $candCn -ne $wantCn) { $why.Add('className-differs') | Out-Null }
|
|
1137
|
+
if ($wantAi -ne '' -and $candAi -ne $wantAi) { $why.Add('automationId-differs') | Out-Null }
|
|
1138
|
+
return [ordered]@{
|
|
1139
|
+
name = (TruncStr $candName 120)
|
|
1140
|
+
automationId = $candAi
|
|
1141
|
+
controlType = $candCt
|
|
1142
|
+
className = (TruncStr $candCn 80)
|
|
1143
|
+
reason = ([string]::Join(',', $why))
|
|
1144
|
+
score = (Get-NameSimilarity $wantName $candName)
|
|
1145
|
+
rect = (RectOf $cp)
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
# At most three candidates, in tree order, each tagged with the nth it would take to reach it —
|
|
1150
|
+
# so a failure tells the model exactly how to fix the descriptor on the next attempt.
|
|
1151
|
+
function New-MatchCandidateList($hits, $wantName, $wantNorm, $wantCt, $wantCn, $wantAi, $reason) {
|
|
1152
|
+
$out = New-Object System.Collections.Generic.List[object]
|
|
1153
|
+
$i = 0
|
|
1154
|
+
foreach ($h in $hits) {
|
|
1155
|
+
if ($i -ge 3) { break }
|
|
1156
|
+
$i += 1
|
|
1157
|
+
$c = New-MatchCandidate $h.cp $wantName $wantNorm $wantCt $wantCn $wantAi $reason
|
|
1158
|
+
$c['nth'] = $i
|
|
1159
|
+
$out.Add($c) | Out-Null
|
|
1160
|
+
}
|
|
1161
|
+
return ,$out
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
# Enumerate the descendants that satisfy $cond, keep the ones $keep accepts, then pick exactly one.
|
|
1165
|
+
# $keep is $null for a pure condition lookup. $fallbackFirst preserves the historical "first match
|
|
1166
|
+
# wins" behaviour of the strict and prefix levels; the newer levels pass $false so that a multiple
|
|
1167
|
+
# hit is reported as ambiguity instead of being resolved by enumeration order.
|
|
1168
|
+
function Select-DescriptorHit($ae, $cond, $keep, $keepArg, $nth, $near, $fallbackFirst) {
|
|
1169
|
+
$hits = New-Object System.Collections.Generic.List[object]
|
|
1170
|
+
$all = @()
|
|
1171
|
+
try { $all = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, $cond)) } catch { return @{ hits = $hits; chosen = $null; selectedBy = ''; error = 'scan_failed' } }
|
|
1172
|
+
foreach ($c in $all) {
|
|
1173
|
+
if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) { break }
|
|
1174
|
+
$cp = $null
|
|
1175
|
+
try { $cp = $c.Current } catch { continue }
|
|
1176
|
+
if ($null -eq $cp) { continue }
|
|
1177
|
+
if ($null -ne $keep) {
|
|
1178
|
+
$ok = $false
|
|
1179
|
+
try { $ok = [bool](& $keep $cp $keepArg) } catch { $ok = $false }
|
|
1180
|
+
if (-not $ok) { continue }
|
|
1181
|
+
}
|
|
1182
|
+
$hits.Add(@{ el = $c; cp = $cp }) | Out-Null
|
|
1183
|
+
}
|
|
1184
|
+
if ($hits.Count -eq 0) { return @{ hits = $hits; chosen = $null; selectedBy = ''; error = 'no_match' } }
|
|
1185
|
+
# nearPoint wins over nth: a coordinate is the caller's strongest statement of intent.
|
|
1186
|
+
if ($null -ne $near) {
|
|
1187
|
+
$nx = 0.0; $ny = 0.0
|
|
1188
|
+
try { $nx = [double](ArgOf $near 'x'); $ny = [double](ArgOf $near 'y') } catch { }
|
|
1189
|
+
$best = $null; $bestD = [double]::MaxValue
|
|
1190
|
+
foreach ($h in $hits) {
|
|
1191
|
+
$r = RectOf $h.cp
|
|
1192
|
+
if ($r.w -le 0 -or $r.h -le 0) { continue }
|
|
1193
|
+
$cx = [double]$r.x + [double]$r.w / 2.0; $cy = [double]$r.y + [double]$r.h / 2.0
|
|
1194
|
+
$d = [Math]::Sqrt(($cx - $nx) * ($cx - $nx) + ($cy - $ny) * ($cy - $ny))
|
|
1195
|
+
if ($d -lt $bestD) { $bestD = $d; $best = $h }
|
|
1196
|
+
}
|
|
1197
|
+
if ($null -ne $best) { return @{ hits = $hits; chosen = $best.el; selectedBy = 'nearPoint'; error = '' } }
|
|
1198
|
+
}
|
|
1199
|
+
if ($nth -gt 0) {
|
|
1200
|
+
if ($nth -gt $hits.Count) { return @{ hits = $hits; chosen = $null; selectedBy = ''; error = 'nth_out_of_range' } }
|
|
1201
|
+
return @{ hits = $hits; chosen = $hits[$nth - 1].el; selectedBy = 'nth'; error = '' }
|
|
1202
|
+
}
|
|
1203
|
+
if ($hits.Count -eq 1) { return @{ hits = $hits; chosen = $hits[0].el; selectedBy = ''; error = '' } }
|
|
1204
|
+
if ($fallbackFirst) { return @{ hits = $hits; chosen = $hits[0].el; selectedBy = ''; error = '' } }
|
|
1205
|
+
return @{ hits = $hits; chosen = $null; selectedBy = ''; error = 'ambiguous' }
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
function Find-ByDescriptor($entry, $by) {
|
|
1209
|
+
# Returns the element (unchanged contract: Resolve-Ref / Wait-Condition / prepare+commit all rely
|
|
1210
|
+
# on getting the UIA element itself) or $null, and always leaves the explanation in lastMatch.
|
|
1211
|
+
$script:W.lastMatch = @{
|
|
1212
|
+
found = $false; matchedBy = ''; ladder = ''; score = 0.0; degraded = $false
|
|
1213
|
+
candidateCount = 0; scanned = 'all'; nameExact = $true; reason = ''
|
|
1214
|
+
tried = @(); candidates = @(); ambiguityAt = ''; diagnosticTruncated = $false
|
|
1215
|
+
# candidateCountKnown=false marks the one record that cannot know the real count (the strict
|
|
1216
|
+
# FindFirst fast path below); every other record is written from a full enumeration.
|
|
1217
|
+
candidateCountKnown = $true
|
|
1218
|
+
# The exact condition the fast path ran, kept so the read-only descriptor_match diagnostic can
|
|
1219
|
+
# re-enumerate it and recover the true same-name count. Reset on every lookup.
|
|
1220
|
+
fastCond = $null
|
|
1221
|
+
}
|
|
1222
|
+
$lm = $script:W.lastMatch
|
|
1223
|
+
$ae = Window-Ae $entry
|
|
1224
|
+
if ($null -eq $ae) { $lm.reason = 'window_gone'; return $null }
|
|
1225
|
+
$by = Dict $by
|
|
1226
|
+
if ($null -eq $by) { $lm.reason = 'empty_descriptor'; return $null }
|
|
1227
|
+
$wantName = [string]$by.Item('name')
|
|
1228
|
+
$wantCt = [string]$by.Item('controlType')
|
|
1229
|
+
$wantCn = [string]$by.Item('className')
|
|
1230
|
+
$wantAi = [string]$by.Item('automationId')
|
|
1231
|
+
$exact = -not (Test-ExplicitFalse $by 'nameExact')
|
|
1232
|
+
$lm.nameExact = $exact
|
|
1233
|
+
# Disambiguators for a descriptor that matches several elements. Without them the provider's
|
|
1234
|
+
# enumeration order decides, so a window with three "复制" buttons can only ever reach the first
|
|
1235
|
+
# one — the model asks for the third, gets the first, and reports "点不准" while every coordinate
|
|
1236
|
+
# was correct.
|
|
1237
|
+
# nth : 1-based index among the matches (in tree order)
|
|
1238
|
+
# nearPoint : pick the match whose centre is closest to this {x,y}
|
|
1239
|
+
$nth = 0
|
|
1240
|
+
$near = $null
|
|
1241
|
+
try {
|
|
1242
|
+
$nthRaw = $by.Item('nth')
|
|
1243
|
+
if ($null -ne $nthRaw) { $nth = [int]$nthRaw }
|
|
1244
|
+
$near = $by.Item('nearPoint')
|
|
1245
|
+
} catch { }
|
|
1246
|
+
# The structural half of the descriptor. Every level starts from exactly this and may only ADD
|
|
1247
|
+
# constraints, never drop one that the caller supplied.
|
|
1248
|
+
$baseConds = New-Object System.Collections.Generic.List[object]
|
|
1249
|
+
if ($wantCt -ne '') {
|
|
1250
|
+
try {
|
|
1251
|
+
$field = [System.Windows.Automation.ControlType].GetField($wantCt)
|
|
1252
|
+
if ($null -ne $field) {
|
|
1253
|
+
$ctObj = $field.GetValue($null)
|
|
1254
|
+
$baseConds.Add((New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ControlTypeProperty, $ctObj))) | Out-Null
|
|
1255
|
+
}
|
|
1256
|
+
} catch { }
|
|
1257
|
+
}
|
|
1258
|
+
if ($wantCn -ne '') { $baseConds.Add((New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::ClassNameProperty, $wantCn))) | Out-Null }
|
|
1259
|
+
if ($wantAi -ne '') { $baseConds.Add((New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::AutomationIdProperty, $wantAi))) | Out-Null }
|
|
1260
|
+
if ($baseConds.Count -eq 0 -and $wantName -eq '') { $lm.reason = 'empty_descriptor'; return $null }
|
|
1261
|
+
|
|
1262
|
+
$wantNorm = Normalize-NameText $wantName
|
|
1263
|
+
$tiers = New-Object System.Collections.Generic.List[string]
|
|
1264
|
+
if (-not $exact -and $wantName -ne '') {
|
|
1265
|
+
# nameExact:false is an explicit request for substring matching. It selects that level alone:
|
|
1266
|
+
# running the exact levels first could resolve a *different*, exactly-named element.
|
|
1267
|
+
$tiers.Add('prefix') | Out-Null
|
|
1268
|
+
} else {
|
|
1269
|
+
$tiers.Add('strict') | Out-Null
|
|
1270
|
+
# id: only worth trying when the strict level had a name to lose (a name-less strict lookup
|
|
1271
|
+
# already used every structural condition, so a second pass could not find anything new).
|
|
1272
|
+
if ($wantName -ne '' -and $wantAi -ne '') { $tiers.Add('id') | Out-Null }
|
|
1273
|
+
if ($wantName -ne '' -and $wantNorm -ne '') { $tiers.Add('normalizedName') | Out-Null }
|
|
1274
|
+
}
|
|
1275
|
+
$nameCond = $null
|
|
1276
|
+
if ($exact -and $wantName -ne '') {
|
|
1277
|
+
$nameCond = New-Object System.Windows.Automation.PropertyCondition([System.Windows.Automation.AutomationElement]::NameProperty, $wantName)
|
|
1278
|
+
}
|
|
1279
|
+
$tried = New-Object System.Collections.Generic.List[string]
|
|
1280
|
+
$blockers = New-Object System.Collections.Generic.List[object]
|
|
1281
|
+
foreach ($tier in $tiers) {
|
|
1282
|
+
$tried.Add($tier) | Out-Null
|
|
1283
|
+
$conds = New-Object System.Collections.Generic.List[object]
|
|
1284
|
+
foreach ($c in $baseConds) { $conds.Add($c) | Out-Null }
|
|
1285
|
+
$keep = $null
|
|
1286
|
+
$keepArg = $null
|
|
1287
|
+
$fallbackFirst = $true
|
|
1288
|
+
if ($tier -eq 'strict') {
|
|
1289
|
+
if ($null -ne $nameCond) { $conds.Add($nameCond) | Out-Null }
|
|
1290
|
+
} elseif ($tier -eq 'id') {
|
|
1291
|
+
$fallbackFirst = $false
|
|
1292
|
+
} elseif ($tier -eq 'normalizedName') {
|
|
1293
|
+
$fallbackFirst = $false
|
|
1294
|
+
$keep = { param($cp, $w) return ((Normalize-NameText ([string]$cp.Name)) -eq $w) }
|
|
1295
|
+
$keepArg = $wantNorm
|
|
1296
|
+
} elseif ($tier -eq 'prefix') {
|
|
1297
|
+
$keep = { param($cp, $w) return (([string]$cp.Name).IndexOf($w, [StringComparison]::OrdinalIgnoreCase) -ge 0) }
|
|
1298
|
+
$keepArg = $wantName
|
|
1299
|
+
}
|
|
1300
|
+
$cond = Join-UiaCondition $conds
|
|
1301
|
+
# Fast path: the legacy code used FindFirst whenever nothing had to be disambiguated and the
|
|
1302
|
+
# name stayed exact. Keeping that identical shape means a recipe that resolved before resolves
|
|
1303
|
+
# the same way, and the common case does not pay for a full descendant enumeration.
|
|
1304
|
+
if ($tier -eq 'strict' -and $null -eq $keep -and $nth -le 1 -and $null -eq $near) {
|
|
1305
|
+
$hit = $null
|
|
1306
|
+
try { $hit = $ae.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $cond) } catch { $hit = $null }
|
|
1307
|
+
if ($null -ne $hit) {
|
|
1308
|
+
$lm.found = $true
|
|
1309
|
+
$lm.ladder = 'strict'; $lm.matchedBy = 'strict'
|
|
1310
|
+
$lm.score = (Get-MatchScore 'strict' '')
|
|
1311
|
+
$lm.degraded = $false
|
|
1312
|
+
# FindFirst stops at the first hit, so the REAL number of same-named candidates is unknown
|
|
1313
|
+
# here. Writing 1 used to fake a uniqueness this scan never established (descriptor_match
|
|
1314
|
+
# read exactly that lie, and a same-name ambiguity was invisible in every report). Say what
|
|
1315
|
+
# is true instead: the count is unknown, and the condition is kept so the read-only
|
|
1316
|
+
# descriptor_match diagnostic can re-enumerate it and recover the real number.
|
|
1317
|
+
$lm.candidateCountKnown = $false
|
|
1318
|
+
$lm.fastCond = $cond
|
|
1319
|
+
$lm.scanned = 'first'
|
|
1320
|
+
$lm.tried = $tried
|
|
1321
|
+
return $hit
|
|
1322
|
+
}
|
|
1323
|
+
$blockers.Add(@{ ladder = 'strict'; reason = 'no_match'; count = 0; hits = @() }) | Out-Null
|
|
1324
|
+
continue
|
|
1325
|
+
}
|
|
1326
|
+
$r = Select-DescriptorHit $ae $cond $keep $keepArg $nth $near $fallbackFirst
|
|
1327
|
+
if ($null -ne $r.chosen) {
|
|
1328
|
+
$lm.found = $true
|
|
1329
|
+
$lm.ladder = $tier
|
|
1330
|
+
$lm.matchedBy = $tier
|
|
1331
|
+
if ($r.selectedBy -ne '') { $lm.matchedBy = $r.selectedBy }
|
|
1332
|
+
$lm.score = (Get-MatchScore $tier $r.selectedBy)
|
|
1333
|
+
$lm.degraded = ($tier -ne 'strict')
|
|
1334
|
+
$lm.candidateCount = $r.hits.Count
|
|
1335
|
+
$lm.scanned = 'all'
|
|
1336
|
+
$lm.tried = $tried
|
|
1337
|
+
return $r.chosen
|
|
1338
|
+
}
|
|
1339
|
+
if ($r.error -eq 'nth_out_of_range' -or $r.error -eq 'scan_failed') {
|
|
1340
|
+
# The descriptor DID match elements; the caller's own disambiguator is what failed. Falling
|
|
1341
|
+
# through to a looser level here would silently pick a different element than the recipe
|
|
1342
|
+
# asked for, so this is terminal.
|
|
1343
|
+
$lm.reason = $r.error
|
|
1344
|
+
$lm.candidateCount = $r.hits.Count
|
|
1345
|
+
$lm.tried = $tried
|
|
1346
|
+
$lm.candidates = (New-MatchCandidateList $r.hits $wantName $wantNorm $wantCt $wantCn $wantAi $r.error)
|
|
1347
|
+
return $null
|
|
1348
|
+
}
|
|
1349
|
+
if ($r.error -eq 'ambiguous' -and $lm.ambiguityAt -eq '') { $lm.ambiguityAt = $tier }
|
|
1350
|
+
$blockers.Add(@{ ladder = $tier; reason = $r.error; count = $r.hits.Count; hits = $r.hits }) | Out-Null
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
$lm.tried = $tried
|
|
1354
|
+
$best = $null
|
|
1355
|
+
foreach ($b in $blockers) { if ($b.count -ge 1) { $best = $b; break } }
|
|
1356
|
+
if ($null -ne $best) {
|
|
1357
|
+
$lm.reason = $best.reason
|
|
1358
|
+
if ($lm.reason -eq '') { $lm.reason = 'ambiguous' }
|
|
1359
|
+
$lm.candidateCount = $best.count
|
|
1360
|
+
$lm.candidates = (New-MatchCandidateList $best.hits $wantName $wantNorm $wantCt $wantCn $wantAi $best.reason)
|
|
1361
|
+
return $null
|
|
1362
|
+
}
|
|
1363
|
+
$lm.reason = 'no_match'
|
|
1364
|
+
if ($wantName -eq '') { return $null }
|
|
1365
|
+
# Not even one level matched structurally: report the closest NAMES instead of only $null. Bounded
|
|
1366
|
+
# so a pathological tree cannot turn a miss into a long scan, and only within the request budget.
|
|
1367
|
+
if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) { return $null }
|
|
1368
|
+
$scan = @()
|
|
1369
|
+
try { $scan = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, (Join-UiaCondition $baseConds))) } catch { $scan = @() }
|
|
1370
|
+
$ranked = New-Object System.Collections.Generic.List[object]
|
|
1371
|
+
$i = 0
|
|
1372
|
+
foreach ($c in $scan) {
|
|
1373
|
+
$i += 1
|
|
1374
|
+
if ($i -gt 400) { $lm.diagnosticTruncated = $true; break }
|
|
1375
|
+
$cp = $null
|
|
1376
|
+
try { $cp = $c.Current } catch { continue }
|
|
1377
|
+
if ($null -eq $cp) { continue }
|
|
1378
|
+
$cn = ''
|
|
1379
|
+
try { $cn = [string]$cp.Name } catch { $cn = '' }
|
|
1380
|
+
if ($cn -eq '') { continue }
|
|
1381
|
+
$sim = Get-NameSimilarity $wantName $cn
|
|
1382
|
+
if ($sim -le 0) { continue }
|
|
1383
|
+
$ranked.Add(@{ cp = $cp; name = $cn; sim = $sim }) | Out-Null
|
|
1384
|
+
}
|
|
1385
|
+
$sorted = @($ranked | Sort-Object -Property @{ Expression = { $_.sim }; Descending = $true }, @{ Expression = { $_.name }; Descending = $false })
|
|
1386
|
+
$cands = New-Object System.Collections.Generic.List[object]
|
|
1387
|
+
$k = 0
|
|
1388
|
+
foreach ($s in $sorted) {
|
|
1389
|
+
if ($k -ge 3) { break }
|
|
1390
|
+
$k += 1
|
|
1391
|
+
$cands.Add((New-MatchCandidate $s.cp $wantName $wantNorm $wantCt $wantCn $wantAi '')) | Out-Null
|
|
1392
|
+
}
|
|
1393
|
+
$lm.candidates = $cands
|
|
1394
|
+
return $null
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
function Resolve-Ref($ref, $opts) {
|
|
1398
|
+
if ($null -eq $ref -or [string]$ref -eq '') { Err 'missing_ref' 'a ref is required' }
|
|
1399
|
+
$re = $script:W.refs.Item([string]$ref)
|
|
1400
|
+
if ($null -eq $re) { Err 'unknown_ref' ("ref " + $ref + " is not in the ref table (evicted, never issued, or its window was closed)") }
|
|
1401
|
+
$entry = $script:W.windows.Item($re.windowId)
|
|
1402
|
+
if ($null -eq $entry) { Err 'unknown_window' ("window " + $re.windowId + " is gone") }
|
|
1403
|
+
if ($re.revision -ne $entry.revision) {
|
|
1404
|
+
$script:W.stats.refused += 1
|
|
1405
|
+
Err 'stale_revision' ("ref " + $ref + " belongs to revision " + $re.revision + " of " + $re.windowId + " but the current revision is " + $entry.revision + '; take a fresh snapshot')
|
|
1406
|
+
}
|
|
1407
|
+
if ($null -ne $opts) {
|
|
1408
|
+
$o = Dict $opts
|
|
1409
|
+
if ($null -ne $o) {
|
|
1410
|
+
$want = $o.Item('revision')
|
|
1411
|
+
if ($null -ne $want -and [int]$want -ne $entry.revision) {
|
|
1412
|
+
$script:W.stats.refused += 1
|
|
1413
|
+
Err 'revision_mismatch' ("caller supplied revision " + $want + " but " + $re.windowId + ' is at ' + $entry.revision)
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
$live = $null
|
|
1418
|
+
try { $null = $re.ae.Current.Name; $live = $re.ae } catch { $live = $null }
|
|
1419
|
+
if ($null -eq $live) {
|
|
1420
|
+
$reb = Find-ByDescriptor $entry @{ automationId = $re.automationId; className = $re.className; name = $re.name; controlType = $re.controlType }
|
|
1421
|
+
if ($null -eq $reb) { Err 'element_gone' ("ref " + $ref + ' no longer resolves in the tree of ' + $entry.id) }
|
|
1422
|
+
$cpb = $null
|
|
1423
|
+
try { $cpb = $reb.Current } catch { Err 'element_gone' ("ref " + $ref + ' cannot be read anymore') }
|
|
1424
|
+
$ridNew = RuntimeIdKey $reb
|
|
1425
|
+
if ($re.runtimeId -ne '' -and $ridNew -ne '' -and $ridNew -ne $re.runtimeId) {
|
|
1426
|
+
Err 'element_gone' ("ref " + $ref + " would resolve to a different element (runtimeId " + $re.runtimeId + ' -> ' + $ridNew + ')')
|
|
1427
|
+
}
|
|
1428
|
+
$re.ae = $reb
|
|
1429
|
+
$re.rebound = $true
|
|
1430
|
+
# Cached pattern objects belong to the OLD element; after a rebind they would read the dead
|
|
1431
|
+
# element (or nothing) forever. Drop them so the next read re-fetches on the new element.
|
|
1432
|
+
$re.patCache = @{}
|
|
1433
|
+
}
|
|
1434
|
+
return $re
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
# ---------------------------------------------------------------- values
|
|
1438
|
+
# Reads one value-bearing property from the element's CACHE (GetCachedPattern + pattern.Cached).
|
|
1439
|
+
# Returns $null when the pattern is not usable (not in the cache, provider refused) so the caller
|
|
1440
|
+
# falls back to the live pattern lookup. Only Read-Value's SNAPSHOT path calls this: the whole
|
|
1441
|
+
# subtree's pattern objects were already materialised by the cache request, so the reading costs
|
|
1442
|
+
# no cross-process round-trip. The act/wait/verify path never calls it — a verify must read the
|
|
1443
|
+
# value as it is NOW, not as it was when the tree was materialised.
|
|
1444
|
+
function Cached-ValueOf($el, $name) {
|
|
1445
|
+
if ($null -eq $el) { return $null }
|
|
1446
|
+
if (-not $patternTypes.ContainsKey($name)) { return $null }
|
|
1447
|
+
try {
|
|
1448
|
+
$p = $el.GetCachedPattern($patternTypes[$name]::Pattern)
|
|
1449
|
+
if ($null -eq $p) { return $null }
|
|
1450
|
+
switch ($name) {
|
|
1451
|
+
'Value' { return [string]$p.Cached.Value }
|
|
1452
|
+
'RangeValue' { return [string]$p.Cached.Value }
|
|
1453
|
+
'Toggle' { return [string]$p.Cached.ToggleState }
|
|
1454
|
+
'ExpandCollapse' { return [string]$p.Cached.ExpandCollapseState }
|
|
1455
|
+
}
|
|
1456
|
+
} catch { }
|
|
1457
|
+
return $null
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
function Read-Value($el, $patterns, $refRec, $useCached) {
|
|
1461
|
+
# $refRec, when given, routes the pattern fetch through the ref's pattern cache (Get-RefPattern):
|
|
1462
|
+
# the act before→action→after sequence then fetches each pattern ONCE instead of three times.
|
|
1463
|
+
# Callers without a ref record keep the plain lookup. $useCached marks the SNAPSHOT path: the
|
|
1464
|
+
# value then comes from the element's cache (Cached-ValueOf) and only a failed cached read falls
|
|
1465
|
+
# back to the live pattern for that one node.
|
|
1466
|
+
if ($null -ne $patterns -and $patterns -contains 'Value') {
|
|
1467
|
+
$v = $null
|
|
1468
|
+
if ($useCached) { $v = Cached-ValueOf $el 'Value' }
|
|
1469
|
+
if ($null -ne $v) { return $v }
|
|
1470
|
+
$vp = if ($null -ne $refRec) { Get-RefPattern $refRec 'Value' } else { GetPattern $el 'Value' }
|
|
1471
|
+
if ($null -ne $vp) { try { return [string]$vp.Current.Value } catch { } }
|
|
1472
|
+
}
|
|
1473
|
+
if ($null -ne $patterns -and $patterns -contains 'RangeValue') {
|
|
1474
|
+
$v = $null
|
|
1475
|
+
if ($useCached) { $v = Cached-ValueOf $el 'RangeValue' }
|
|
1476
|
+
if ($null -ne $v) { return $v }
|
|
1477
|
+
$rp = if ($null -ne $refRec) { Get-RefPattern $refRec 'RangeValue' } else { GetPattern $el 'RangeValue' }
|
|
1478
|
+
if ($null -ne $rp) { try { return [string]$rp.Current.Value } catch { } }
|
|
1479
|
+
}
|
|
1480
|
+
if ($null -ne $patterns -and $patterns -contains 'Toggle') {
|
|
1481
|
+
$v = $null
|
|
1482
|
+
if ($useCached) { $v = Cached-ValueOf $el 'Toggle' }
|
|
1483
|
+
if ($null -ne $v) { return $v }
|
|
1484
|
+
$tp = if ($null -ne $refRec) { Get-RefPattern $refRec 'Toggle' } else { GetPattern $el 'Toggle' }
|
|
1485
|
+
if ($null -ne $tp) { try { return [string]$tp.Current.ToggleState } catch { } }
|
|
1486
|
+
}
|
|
1487
|
+
if ($null -ne $patterns -and $patterns -contains 'ExpandCollapse') {
|
|
1488
|
+
$v = $null
|
|
1489
|
+
if ($useCached) { $v = Cached-ValueOf $el 'ExpandCollapse' }
|
|
1490
|
+
if ($null -ne $v) { return $v }
|
|
1491
|
+
$ep = if ($null -ne $refRec) { Get-RefPattern $refRec 'ExpandCollapse' } else { GetPattern $el 'ExpandCollapse' }
|
|
1492
|
+
if ($null -ne $ep) { try { return [string]$ep.Current.ExpandCollapseState } catch { } }
|
|
1493
|
+
}
|
|
1494
|
+
# No LegacyIAccessible branch here: the managed UIAutomationClient has no
|
|
1495
|
+
# System.Windows.Automation.LegacyIAccessiblePattern type, so GetPattern could never return one
|
|
1496
|
+
# and this read was unreachable (the pattern name only appears in PatternsOf's report of what the
|
|
1497
|
+
# PROVIDER exposes, never in what this client can obtain).
|
|
1498
|
+
if ($null -ne $patterns -and $patterns -contains 'Text') {
|
|
1499
|
+
$tx = GetPattern $el 'Text'
|
|
1500
|
+
if ($null -ne $tx) { try { return [string]$tx.DocumentRange.GetText(200) } catch { } }
|
|
1501
|
+
}
|
|
1502
|
+
return ''
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
function SupportedActionOf($patterns) {
|
|
1506
|
+
if ($null -eq $patterns) { return 'focus' }
|
|
1507
|
+
if ($patterns -contains 'Invoke') { return 'invoke' }
|
|
1508
|
+
if ($patterns -contains 'Toggle') { return 'toggle' }
|
|
1509
|
+
if ($patterns -contains 'SelectionItem') { return 'select' }
|
|
1510
|
+
if ($patterns -contains 'ExpandCollapse') { return 'expand' }
|
|
1511
|
+
if ($patterns -contains 'Value') { return 'set_value' }
|
|
1512
|
+
if ($patterns -contains 'Scroll') { return 'scroll_down' }
|
|
1513
|
+
# LegacyIAccessible is NOT actionable from the managed UIA client (there is no
|
|
1514
|
+
# System.Windows.Automation.LegacyIAccessiblePattern type in UIAutomationClient), so it is
|
|
1515
|
+
# reported but never advertised as an action.
|
|
1516
|
+
return 'focus'
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
function DescriptorOf($re, $live) {
|
|
1520
|
+
$cp = $null
|
|
1521
|
+
$patterns = $re.patterns
|
|
1522
|
+
$name = $re.name
|
|
1523
|
+
# The UNtruncated name, when the snapshot recorded one: a saved recipe needs it because a
|
|
1524
|
+
# 160-cut name with '~' can never satisfy a strict re-match (F: recipe save quality).
|
|
1525
|
+
$full = ''
|
|
1526
|
+
if ($re.ContainsKey('fullName')) { $full = [string]$re.fullName }
|
|
1527
|
+
$enabled = $re.enabled
|
|
1528
|
+
$off = $re.isOffscreen
|
|
1529
|
+
$rect = $re.rect
|
|
1530
|
+
if ($live) {
|
|
1531
|
+
try { $cp = $re.ae.Current } catch { $cp = $null }
|
|
1532
|
+
if ($null -ne $cp) {
|
|
1533
|
+
$name = [string]$cp.Name
|
|
1534
|
+
$full = $name
|
|
1535
|
+
$enabled = [bool]$cp.IsEnabled
|
|
1536
|
+
$off = [bool]$cp.IsOffscreen
|
|
1537
|
+
$rect = RectOf $cp
|
|
1538
|
+
$p2 = PatternsOf $re.ae
|
|
1539
|
+
if ($null -ne $p2 -and $p2.Count -gt 0) { $patterns = $p2 }
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
$d = [ordered]@{
|
|
1543
|
+
ref = $re.ref
|
|
1544
|
+
windowId = $re.windowId
|
|
1545
|
+
revision = $re.revision
|
|
1546
|
+
name = (TruncStr ([string]$name) 160)
|
|
1547
|
+
controlType = $re.controlType
|
|
1548
|
+
className = $re.className
|
|
1549
|
+
automationId = $re.automationId
|
|
1550
|
+
availablePatterns = @($patterns)
|
|
1551
|
+
supportedAction = (SupportedActionOf $patterns)
|
|
1552
|
+
enabled = $enabled
|
|
1553
|
+
isOffscreen = $off
|
|
1554
|
+
rect = $rect
|
|
1555
|
+
depth = $re.depth
|
|
1556
|
+
runtimeId = $re.runtimeId
|
|
1557
|
+
}
|
|
1558
|
+
# Attach only when truncation actually happened, so the common short-name descriptor keeps the
|
|
1559
|
+
# old wire shape and no caller can mistake fullName for an always-present field.
|
|
1560
|
+
if ($full -ne '' -and $full -ne [string]$d['name']) { $d['fullName'] = $full }
|
|
1561
|
+
if ($live -and $null -ne $cp) {
|
|
1562
|
+
$v = Read-Value $re.ae $patterns
|
|
1563
|
+
if ($v -ne '') {
|
|
1564
|
+
$d['value'] = (TruncStr $v 200)
|
|
1565
|
+
if ($v.Length -gt 200) { $d['valueTruncated'] = $true }
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
# Attach the owning window so a saved recipe can rebind to it later. tools.js reads
|
|
1569
|
+
# descriptors[0].ownerWindow to populate recipe.window; without it the recipe falls back to
|
|
1570
|
+
# the store's window list, which is empty for a batch taken before any computer_windows call,
|
|
1571
|
+
# and the recipe then replays with no windowId.
|
|
1572
|
+
$we = $script:W.windows.Item([string]$re.windowId)
|
|
1573
|
+
if ($null -ne $we) {
|
|
1574
|
+
$d['ownerWindow'] = [ordered]@{ windowId = $re.windowId; hwnd = $we.hwnd; pid = $we.pid; revision = $we.revision }
|
|
1575
|
+
}
|
|
1576
|
+
return $d
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
# ---------------------------------------------------------------- snapshot
|
|
1580
|
+
# One CacheRequest shared by every snapshot walk, handed to the walker's cached overloads
|
|
1581
|
+
# (GetFirstChild/GetNextSibling with a request — reflection-confirmed overloads) and, at Subtree
|
|
1582
|
+
# scope, to the one-shot GetUpdatedCache path. The request carries the seven properties the node
|
|
1583
|
+
# builder reads, PLUS RuntimeIdProperty (probe-verified bit-identical to GetRuntimeId() on real
|
|
1584
|
+
# trees — the old "cache returns an empty array" note was a probe artifact and did not reproduce),
|
|
1585
|
+
# PLUS every Is*PatternAvailableProperty the managed client has (19 exist; there is no managed
|
|
1586
|
+
# LegacyIAccessible availability property, so a cached pattern list never names it — accepted
|
|
1587
|
+
# shrink, see Cached-PatternsOf), PLUS the four value-bearing pattern objects Read-Value's
|
|
1588
|
+
# snapshot path reads from the cache. AutomationElementMode stays Full so refs minted from cached
|
|
1589
|
+
# elements remain usable for live pattern calls later (invoke/set_value read patterns through the
|
|
1590
|
+
# same element).
|
|
1591
|
+
$script:snapReq = $null
|
|
1592
|
+
$script:subTreeReq = $null
|
|
1593
|
+
$script:findReq = $null
|
|
1594
|
+
$script:snapProps = @(
|
|
1595
|
+
'NameProperty', 'ClassNameProperty', 'ControlTypeProperty', 'AutomationIdProperty',
|
|
1596
|
+
'IsEnabledProperty', 'IsOffscreenProperty', 'BoundingRectangleProperty', 'RuntimeIdProperty',
|
|
1597
|
+
'IsDockPatternAvailableProperty', 'IsExpandCollapsePatternAvailableProperty', 'IsGridItemPatternAvailableProperty',
|
|
1598
|
+
'IsGridPatternAvailableProperty', 'IsInvokePatternAvailableProperty', 'IsItemContainerPatternAvailableProperty',
|
|
1599
|
+
'IsMultipleViewPatternAvailableProperty', 'IsRangeValuePatternAvailableProperty', 'IsScrollItemPatternAvailableProperty',
|
|
1600
|
+
'IsScrollPatternAvailableProperty', 'IsSelectionItemPatternAvailableProperty', 'IsSelectionPatternAvailableProperty',
|
|
1601
|
+
'IsTableItemPatternAvailableProperty', 'IsTablePatternAvailableProperty', 'IsTextPatternAvailableProperty',
|
|
1602
|
+
'IsTogglePatternAvailableProperty', 'IsTransformPatternAvailableProperty', 'IsValuePatternAvailableProperty',
|
|
1603
|
+
'IsWindowPatternAvailableProperty'
|
|
1604
|
+
)
|
|
1605
|
+
$script:snapPatterns = @(
|
|
1606
|
+
[System.Windows.Automation.ValuePattern]::Pattern,
|
|
1607
|
+
[System.Windows.Automation.TogglePattern]::Pattern,
|
|
1608
|
+
[System.Windows.Automation.RangeValuePattern]::Pattern,
|
|
1609
|
+
[System.Windows.Automation.ExpandCollapsePattern]::Pattern
|
|
1610
|
+
)
|
|
1611
|
+
function New-SnapshotCacheRequest($scope) {
|
|
1612
|
+
$req = New-Object System.Windows.Automation.CacheRequest
|
|
1613
|
+
$req.TreeScope = $scope
|
|
1614
|
+
$req.AutomationElementMode = [System.Windows.Automation.AutomationElementMode]::Full
|
|
1615
|
+
foreach ($p in $script:snapProps) {
|
|
1616
|
+
$req.Add([System.Windows.Automation.AutomationElement]::$p)
|
|
1617
|
+
}
|
|
1618
|
+
foreach ($pat in $script:snapPatterns) {
|
|
1619
|
+
$req.Add($pat)
|
|
1620
|
+
}
|
|
1621
|
+
return $req
|
|
1622
|
+
}
|
|
1623
|
+
function Snapshot-CacheRequest {
|
|
1624
|
+
if ($null -eq $script:snapReq) {
|
|
1625
|
+
try {
|
|
1626
|
+
$script:snapReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Element)
|
|
1627
|
+
} catch {
|
|
1628
|
+
Log ('CacheRequest build failed, snapshot falls back to live reads: ' + $_.Exception.Message)
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
return $script:snapReq
|
|
1632
|
+
}
|
|
1633
|
+
function Subtree-CacheRequest {
|
|
1634
|
+
# One-shot path: the same property list at TreeScope=Subtree. GetUpdatedCache(Subtree)
|
|
1635
|
+
# materialises the WHOLE subtree in one cross-process call (measured 0.10-0.16 ms/node vs
|
|
1636
|
+
# ~1.5 ms/node for the Activate+FindAll shape and ~4.4 ms/node for the per-child walker).
|
|
1637
|
+
# Kept as its own request object so the walker fallback never changes scope under it.
|
|
1638
|
+
if ($null -eq $script:subTreeReq) {
|
|
1639
|
+
try {
|
|
1640
|
+
$script:subTreeReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Subtree)
|
|
1641
|
+
} catch {
|
|
1642
|
+
Log ('subtree CacheRequest build failed, snapshot falls back to the walker: ' + $_.Exception.Message)
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
return $script:subTreeReq
|
|
1646
|
+
}
|
|
1647
|
+
function Find-CacheRequest {
|
|
1648
|
+
# find_text's own request object — deliberately NOT the shared $script:snapReq: the two callers
|
|
1649
|
+
# must not fight over one request (find_text activates and pops within one command, and a
|
|
1650
|
+
# snapshot in flight on the same thread would see its scope changed under it).
|
|
1651
|
+
if ($null -eq $script:findReq) {
|
|
1652
|
+
try {
|
|
1653
|
+
$script:findReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Element)
|
|
1654
|
+
} catch {
|
|
1655
|
+
Log ('find_text CacheRequest build failed, find_text falls back to live reads: ' + $_.Exception.Message)
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
return $script:findReq
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
# The walker used by the snapshot fallback path. One indirection so the test harness can walk a
|
|
1662
|
+
# mock tree through the SAME code path (regression-worker.ps1 redefines this and feeds a mock
|
|
1663
|
+
# walker); production always gets the ControlViewWalker.
|
|
1664
|
+
function Get-SnapshotWalker {
|
|
1665
|
+
return [System.Windows.Automation.TreeWalker]::ControlViewWalker
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
# Builds ONE snapshot node (shared by the one-shot subtree path and the walker fallback): the emit
|
|
1669
|
+
# filter, the node fields, the ref minting and the value read all live here, so the two paths
|
|
1670
|
+
# cannot drift. $ctx is the shared mutable state hashtable (a script-scope function cannot see
|
|
1671
|
+
# Build-Snapshot's locals). A per-node provider failure records nodeProviderError and lets the
|
|
1672
|
+
# walk continue — the per-node fault-tolerance contract is unchanged.
|
|
1673
|
+
function Build-SnapshotNode($el, $depth, $cp, $ctx) {
|
|
1674
|
+
try {
|
|
1675
|
+
$ctx.visited += 1
|
|
1676
|
+
# Hoist each cross-process property read once; Current/Cached does not cache these reads.
|
|
1677
|
+
$ctRaw = $cp.ControlType
|
|
1678
|
+
$nm = [string]$cp.Name
|
|
1679
|
+
$cls = [string]$cp.ClassName
|
|
1680
|
+
$off = [bool]$cp.IsOffscreen
|
|
1681
|
+
$ctn = ControlTypeName $ctRaw
|
|
1682
|
+
$emit = $true
|
|
1683
|
+
if ($ctx.fCtSet.Count -gt 0 -and -not $ctx.fCtSet.ContainsKey($ctn)) { $emit = $false }
|
|
1684
|
+
# Literal, case-insensitive containment: -like treats * ? [ ] in a caller's text as
|
|
1685
|
+
# wildcards, so a control whose name really contains brackets matched the wrong things.
|
|
1686
|
+
if ($ctx.fClass -ne '' -and $cls.IndexOf($ctx.fClass, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $emit = $false }
|
|
1687
|
+
if ($ctx.fName -ne '' -and $nm.IndexOf($ctx.fName, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $emit = $false }
|
|
1688
|
+
if (-not $ctx.incOff -and $off -and $depth -gt 0) { $emit = $false }
|
|
1689
|
+
$patterns = @()
|
|
1690
|
+
if ($emit) {
|
|
1691
|
+
if ($ctx.wantPatterns) { $patterns = PatternsOf $el }
|
|
1692
|
+
$aid = [string]$cp.AutomationId
|
|
1693
|
+
$enabled = [bool]$cp.IsEnabled
|
|
1694
|
+
$rc = RectOf $cp
|
|
1695
|
+
$node = [ordered]@{
|
|
1696
|
+
ref = ('e' + ($script:W.refSeq + 1))
|
|
1697
|
+
controlType = $ctn
|
|
1698
|
+
name = (TruncStr $nm 160)
|
|
1699
|
+
className = $cls
|
|
1700
|
+
automationId = $aid
|
|
1701
|
+
depth = $depth
|
|
1702
|
+
patterns = @($patterns)
|
|
1703
|
+
enabled = $enabled
|
|
1704
|
+
isOffscreen = $off
|
|
1705
|
+
rect = $rc
|
|
1706
|
+
}
|
|
1707
|
+
# Only when truncation happened: the untruncated name a saved recipe needs to re-resolve
|
|
1708
|
+
# later (a 160-cut name with '~' can never satisfy a strict match). Short names carry no
|
|
1709
|
+
# extra field, so the wire shape stays unchanged for the 99% case.
|
|
1710
|
+
if ($nm.Length -gt 160) { $node['fullName'] = $nm }
|
|
1711
|
+
if ($ctx.wantValues -and -not $off) {
|
|
1712
|
+
$v = Read-Value $el $patterns $null $true
|
|
1713
|
+
if ($v -ne '') {
|
|
1714
|
+
$node['value'] = (TruncStr $v 200)
|
|
1715
|
+
if ($v.Length -gt 200) { $node['valueTruncated'] = $true }
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
$null = New-Ref $ctx.entry $el $cp $node
|
|
1719
|
+
$ctx.nodes.Add($node) | Out-Null
|
|
1720
|
+
}
|
|
1721
|
+
return $true
|
|
1722
|
+
} catch {
|
|
1723
|
+
$ctx.truncated = $true
|
|
1724
|
+
$ctx.partialReasons['nodeProviderError'] = $true
|
|
1725
|
+
$ctx.providerErrors += 1
|
|
1726
|
+
return $true
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
function Build-Snapshot($entry, $A) {
|
|
1731
|
+
$ae = Window-Ae $entry
|
|
1732
|
+
if ($null -eq $ae) { Err 'window_not_found' ("window " + $entry.id + " (hwnd " + $entry.hwnd + ") is gone") }
|
|
1733
|
+
$maxNodes = IntArg $A 'maxNodes' 300
|
|
1734
|
+
if ($maxNodes -lt 1) { $maxNodes = 1 }
|
|
1735
|
+
if ($maxNodes -gt $script:W.maxRefs) { $maxNodes = $script:W.maxRefs }
|
|
1736
|
+
$wantPatterns = BoolArg $A 'patterns' $true
|
|
1737
|
+
$wantValues = BoolArg $A 'values' $true
|
|
1738
|
+
$maxDepth = IntArg $A 'maxDepth' 30
|
|
1739
|
+
$filter = Dict (ArgOf $A 'filter')
|
|
1740
|
+
$fCt = ''; $fCtSet = @{}; $fName = ''; $fClass = ''; $incOff = $true
|
|
1741
|
+
if ($null -ne $filter) {
|
|
1742
|
+
$fCt = [string](ArgOf $filter 'controlType')
|
|
1743
|
+
# The tool contract advertises controlType as a comma-separated set ("Button,Edit"). Comparing
|
|
1744
|
+
# the whole string against one node's type silently matched nothing, so a documented filter
|
|
1745
|
+
# returned an empty tree. Split once and test membership.
|
|
1746
|
+
foreach ($t in ($fCt -split ',')) {
|
|
1747
|
+
$tt = $t.Trim()
|
|
1748
|
+
if ($tt -ne '') { $fCtSet[$tt] = $true }
|
|
1749
|
+
}
|
|
1750
|
+
$fName = [string](ArgOf $filter 'nameContains')
|
|
1751
|
+
$fClass = [string](ArgOf $filter 'className')
|
|
1752
|
+
$io = ArgOf $filter 'includeOffscreen'
|
|
1753
|
+
if ($null -eq $io) { $incOff = $false } else { $incOff = BoolArg $filter 'includeOffscreen' $false }
|
|
1754
|
+
} else {
|
|
1755
|
+
$incOff = BoolArg $A 'includeOffscreen' $true
|
|
1756
|
+
}
|
|
1757
|
+
$reserve = [Math]::Min($maxNodes, 900)
|
|
1758
|
+
$evicted = Evict-ForReservation $reserve
|
|
1759
|
+
|
|
1760
|
+
$entry.revision += 1
|
|
1761
|
+
$snap = @{ revision = $entry.revision; windowId = $entry.id; createdTick = TickNow; refs = (New-Object System.Collections.Generic.List[string]); started = (TickNow) }
|
|
1762
|
+
$entry.snapshots.Add($snap)
|
|
1763
|
+
$entry.lastSeen = (TickNow)
|
|
1764
|
+
$script:W.stats.snapshots += 1
|
|
1765
|
+
|
|
1766
|
+
$walker = Get-SnapshotWalker
|
|
1767
|
+
$req = Snapshot-CacheRequest
|
|
1768
|
+
$nodes = New-Object System.Collections.Generic.List[object]
|
|
1769
|
+
$siblingLimit = 512
|
|
1770
|
+
$stack = New-Object System.Collections.Generic.Stack[object]
|
|
1771
|
+
$stack.Push(@($ae, 0))
|
|
1772
|
+
# Shared mutable walk state: one hashtable, because the node builder is a script-scope function
|
|
1773
|
+
# and cannot see this function's locals. Same fields the old loop locals carried.
|
|
1774
|
+
$ctx = @{
|
|
1775
|
+
entry = $entry
|
|
1776
|
+
nodes = $nodes
|
|
1777
|
+
visited = 0
|
|
1778
|
+
truncated = $false
|
|
1779
|
+
partialReasons = @{}
|
|
1780
|
+
providerErrors = 0
|
|
1781
|
+
fCtSet = $fCtSet
|
|
1782
|
+
fClass = $fClass
|
|
1783
|
+
fName = $fName
|
|
1784
|
+
incOff = $incOff
|
|
1785
|
+
wantPatterns = $wantPatterns
|
|
1786
|
+
wantValues = $wantValues
|
|
1787
|
+
}
|
|
1788
|
+
|
|
1789
|
+
# ---- one-shot subtree path ---------------------------------------------------------------
|
|
1790
|
+
# ONE cross-process call (GetUpdatedCache at TreeScope=Subtree) materialises the whole subtree
|
|
1791
|
+
# with every property, pattern availability and RuntimeId already cached; everything after it
|
|
1792
|
+
# is in-memory (measured 0.10-0.16 ms/node vs ~1.5 ms/node for an Activate+FindAll shape and
|
|
1793
|
+
# ~4.4 ms/node for the per-child walker). This is NOT a cost cap: the whole-tree materialisation
|
|
1794
|
+
# is paid BEFORE any node cap is checked (a Chromium window materialises its full a11y tree in
|
|
1795
|
+
# that one call and it cannot be interrupted) — the cap below only stops the in-memory walk from
|
|
1796
|
+
# continuing on a pathological tree, and the walker fallback after it is loss control, not fee
|
|
1797
|
+
# control. A provider that refuses the bulk cache (or any failure here) falls back to the
|
|
1798
|
+
# per-child walker below, which carries the same emit contract.
|
|
1799
|
+
$oneShot = $null
|
|
1800
|
+
$subReq = Subtree-CacheRequest
|
|
1801
|
+
if ($null -ne $subReq) {
|
|
1802
|
+
try {
|
|
1803
|
+
$rootC = $ae.GetUpdatedCache($subReq)
|
|
1804
|
+
if ($null -ne $rootC) {
|
|
1805
|
+
$oneShot = New-Object System.Collections.Generic.List[object]
|
|
1806
|
+
$nav = New-Object System.Collections.Generic.Stack[object]
|
|
1807
|
+
$nav.Push(@($rootC, 0))
|
|
1808
|
+
$hardCap = 3000
|
|
1809
|
+
$tooBig = $false
|
|
1810
|
+
while ($nav.Count -gt 0) {
|
|
1811
|
+
$pair = $nav.Pop()
|
|
1812
|
+
$oneShot.Add($pair) | Out-Null
|
|
1813
|
+
if ($oneShot.Count -gt $hardCap) { $tooBig = $true; break }
|
|
1814
|
+
$d = [int]$pair[1]
|
|
1815
|
+
if ($d -ge $maxDepth) { $ctx.truncated = $true; $ctx.partialReasons['maxDepth'] = $true; continue }
|
|
1816
|
+
try { $kids = $pair[0].CachedChildren } catch {
|
|
1817
|
+
$ctx.truncated = $true; $ctx.partialReasons['childProviderError'] = $true; $ctx.providerErrors += 1
|
|
1818
|
+
continue
|
|
1819
|
+
}
|
|
1820
|
+
for ($j = $kids.Count - 1; $j -ge 0; $j--) { $nav.Push(@($kids[$j], ($d + 1))) }
|
|
1821
|
+
}
|
|
1822
|
+
if ($tooBig) {
|
|
1823
|
+
Log ('one-shot subtree exceeded ' + $hardCap + ' nodes; falling back to the walker path')
|
|
1824
|
+
$oneShot = $null
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
} catch {
|
|
1828
|
+
Log ('one-shot subtree cache failed, falling back to the walker: ' + $_.Exception.Message)
|
|
1829
|
+
$oneShot = $null
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
if ($null -ne $oneShot) {
|
|
1834
|
+
foreach ($pair in $oneShot) {
|
|
1835
|
+
if ($nodes.Count -ge $maxNodes) { $ctx.truncated = $true; $ctx.partialReasons['maxNodes'] = $true; break }
|
|
1836
|
+
Test-Deadline 'snapshot'
|
|
1837
|
+
$el = $pair[0]; $depth = [int]$pair[1]
|
|
1838
|
+
try {
|
|
1839
|
+
# TreeScope=Subtree includes Element, so even the root carries its cache here — unlike the
|
|
1840
|
+
# walker path below, where the depth-0 root is still read live.
|
|
1841
|
+
$cp = $el.Cached
|
|
1842
|
+
if ($null -eq $cp) { throw 'provider returned no Cached properties' }
|
|
1843
|
+
} catch {
|
|
1844
|
+
$ctx.truncated = $true; $ctx.partialReasons['nodeProviderError'] = $true; $ctx.providerErrors += 1
|
|
1845
|
+
continue
|
|
1846
|
+
}
|
|
1847
|
+
[void](Build-SnapshotNode $el $depth $cp $ctx)
|
|
1848
|
+
}
|
|
1849
|
+
} else {
|
|
1850
|
+
while ($stack.Count -gt 0) {
|
|
1851
|
+
if ($nodes.Count -ge $maxNodes) { $ctx.truncated = $true; $ctx.partialReasons['maxNodes'] = $true; break }
|
|
1852
|
+
Test-Deadline 'snapshot'
|
|
1853
|
+
$pair = $stack.Pop()
|
|
1854
|
+
$el = $pair[0]; $depth = [int]$pair[1]
|
|
1855
|
+
# A single provider/property failure must not discard the rest of the snapshot. Keep
|
|
1856
|
+
# walking this node's children as well: Current can fail while navigation still works.
|
|
1857
|
+
try {
|
|
1858
|
+
# Depth 0 is the live window element: the walker's cached overloads apply the request to the
|
|
1859
|
+
# element they RETURN, so the root has no cached blob and one node's live reads are noise.
|
|
1860
|
+
# Every node below it came back from GetFirstChild/GetNextSibling(el, request) and reads its
|
|
1861
|
+
# seven properties from the cached blob with no cross-process round-trip. Same struct shape
|
|
1862
|
+
# as Current, so the builder below is unchanged.
|
|
1863
|
+
$cp = if ($null -ne $req -and $depth -gt 0) { $el.Cached } else { $el.Current }
|
|
1864
|
+
if ($null -eq $cp) { throw 'provider returned no Current properties' }
|
|
1865
|
+
[void](Build-SnapshotNode $el $depth $cp $ctx)
|
|
1866
|
+
} catch {
|
|
1867
|
+
$ctx.truncated = $true; $ctx.partialReasons['nodeProviderError'] = $true; $ctx.providerErrors += 1
|
|
1868
|
+
}
|
|
1869
|
+
if ($depth -ge $maxDepth) { $ctx.truncated = $true; $ctx.partialReasons['maxDepth'] = $true; continue }
|
|
1870
|
+
$kids = New-Object System.Collections.Generic.List[object]
|
|
1871
|
+
$c = $null
|
|
1872
|
+
# The request overload returns the child WITH its properties already cached — one round-trip
|
|
1873
|
+
# instead of one navigation call plus seven property reads (see Snapshot-CacheRequest).
|
|
1874
|
+
try { $c = if ($null -ne $req) { $walker.GetFirstChild($el, $req) } else { $walker.GetFirstChild($el) } } catch {
|
|
1875
|
+
$ctx.truncated = $true; $ctx.partialReasons['childProviderError'] = $true; $ctx.providerErrors += 1
|
|
1876
|
+
}
|
|
1877
|
+
while ($null -ne $c) {
|
|
1878
|
+
if ($kids.Count -ge $siblingLimit) { $ctx.truncated = $true; $ctx.partialReasons['siblingLimit'] = $true; break }
|
|
1879
|
+
$kids.Add($c) | Out-Null
|
|
1880
|
+
try { $c = if ($null -ne $req) { $walker.GetNextSibling($c, $req) } else { $walker.GetNextSibling($c) } } catch {
|
|
1881
|
+
$c = $null; $ctx.truncated = $true; $ctx.partialReasons['siblingProviderError'] = $true; $ctx.providerErrors += 1
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
for ($j = $kids.Count - 1; $j -ge 0; $j--) { $stack.Push(@($kids[$j], ($depth + 1))) }
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
$ms = MsFrom $snap.started
|
|
1888
|
+
$result = [ordered]@{
|
|
1889
|
+
revision = $entry.revision
|
|
1890
|
+
windowId = $entry.id
|
|
1891
|
+
nodeCount = $nodes.Count
|
|
1892
|
+
visited = $ctx.visited
|
|
1893
|
+
truncated = [bool]$ctx.truncated
|
|
1894
|
+
maxNodesApplied = $maxNodes
|
|
1895
|
+
ceiling = [int]$script:W.maxRefs
|
|
1896
|
+
totalRefs = $script:W.totalRefs
|
|
1897
|
+
evictions = $evicted.Count
|
|
1898
|
+
ms = $ms
|
|
1899
|
+
msPerNode = if ($nodes.Count -gt 0) { [Math]::Round($ms / $nodes.Count, 3) } else { 0 }
|
|
1900
|
+
nodes = $nodes
|
|
1901
|
+
}
|
|
1902
|
+
if ($ctx.partialReasons.Count -gt 0) { $result['partialReason'] = (($ctx.partialReasons.Keys | Sort-Object) -join ',') }
|
|
1903
|
+
if ($ctx.providerErrors -gt 0) { $result['providerErrors'] = $ctx.providerErrors }
|
|
1904
|
+
if ($evicted.Count -gt 0) { $result['evicted'] = $evicted }
|
|
1905
|
+
if ($nodes.Count -eq 0) { $result['detail'] = 'no nodes matched; check filter or take an unfiltered snapshot' }
|
|
1906
|
+
# Position metadata: what is foreground and where the focus sits right now. Advisory,
|
|
1907
|
+
# try/catch-guarded — a probe failure just omits the fields, it never fails the snapshot.
|
|
1908
|
+
try {
|
|
1909
|
+
$obsHeader = Window-ObservationHeader $entry
|
|
1910
|
+
if ($null -ne $obsHeader) {
|
|
1911
|
+
foreach ($k in @($obsHeader.Keys)) { $result[$k] = $obsHeader[$k] }
|
|
1912
|
+
}
|
|
1913
|
+
} catch { }
|
|
1914
|
+
return $result
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
# ---------------------------------------------------------------- actions
|
|
1918
|
+
function Is-ForegroundHwnd($hwnd) {
|
|
1919
|
+
try { return ([Native]::GetForegroundWindow() -eq [IntPtr]$hwnd) } catch { return $false }
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
function Foreground-Hwnd {
|
|
1923
|
+
try { return [Native]::GetForegroundWindow() } catch { return [IntPtr]::Zero }
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
function Cursor-Pos {
|
|
1927
|
+
try { $p = [System.Windows.Forms.Cursor]::Position; return @{ x = [int]$p.X; y = [int]$p.Y } } catch { return @{ x = -1; y = -1 } }
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
function Test-Escape {
|
|
1931
|
+
# VK_ESCAPE high bit = physically held right now. Checked between batch steps and inside the
|
|
1932
|
+
# pointer glide so a user pressing ESC stops the run promptly instead of only at the next command.
|
|
1933
|
+
try { return (([int][Native]::GetAsyncKeyState(0x1B)) -band 0x8000) -ne 0 } catch { return $false }
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
function Invoke-PixelAction($re, $action, $value) {
|
|
1937
|
+
# Drive the physical pointer at the element's own BoundingRectangle. Only used when the mode is
|
|
1938
|
+
# foreground, or auto and the UIA path could not act on this element.
|
|
1939
|
+
$rc = $re.rect
|
|
1940
|
+
if ($null -eq $rc -or [int]$rc.w -le 0 -or [int]$rc.h -le 0) {
|
|
1941
|
+
Err 'no_rect' ("pixel path needs a non-empty bounding rect for " + $re.controlType + " '" + (TruncStr $re.name 40) + "'")
|
|
1942
|
+
}
|
|
1943
|
+
$cx = [int]($rc.x + [Math]::Round($rc.w / 2)); $cy = [int]($rc.y + [Math]::Round($rc.h / 2))
|
|
1944
|
+
$exp = @{ windowId = [string]$re.windowId }
|
|
1945
|
+
switch ($action) {
|
|
1946
|
+
{ $_ -in @('invoke', 'select', 'toggle', 'expand', 'collapse', 'focus') } {
|
|
1947
|
+
[void](Cmd-PointerClick @{ x = $cx; y = $cy; button = 'left'; expect = $exp }); return 'pixel-click'
|
|
1948
|
+
}
|
|
1949
|
+
'set_value' {
|
|
1950
|
+
[void](Cmd-PointerClick @{ x = $cx; y = $cy; button = 'left'; expect = $exp })
|
|
1951
|
+
[void](Cmd-Key @{ keys = 'ctrl+a' })
|
|
1952
|
+
# An empty value means "clear the field". Typing '' over the ctrl+a selection leaves it
|
|
1953
|
+
# untouched, so delete the selection explicitly instead.
|
|
1954
|
+
if ([string]$value -eq '') { [void](Cmd-Key @{ keys = 'del' }) }
|
|
1955
|
+
else { [void](Cmd-TypeText @{ text = [string]$value }) }
|
|
1956
|
+
return 'pixel-type'
|
|
1957
|
+
}
|
|
1958
|
+
'text_append' {
|
|
1959
|
+
[void](Cmd-PointerClick @{ x = $cx; y = $cy; button = 'left'; expect = $exp })
|
|
1960
|
+
[void](Cmd-TypeText @{ text = [string]$value }); return 'pixel-type'
|
|
1961
|
+
}
|
|
1962
|
+
'scroll_up' { [void](Cmd-PointerScroll @{ x = $cx; y = $cy; direction = 'up'; clicks = 3; expect = $exp }); return 'pixel-scroll' }
|
|
1963
|
+
'scroll_down' { [void](Cmd-PointerScroll @{ x = $cx; y = $cy; direction = 'down'; clicks = 3; expect = $exp }); return 'pixel-scroll' }
|
|
1964
|
+
default { Err 'unknown_action' ("no pixel path for action '" + $action + "'") }
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
|
|
1968
|
+
function Do-Action($re, $action, $value, $step) {
|
|
1969
|
+
$mode = [string]$script:W.pointerMode
|
|
1970
|
+
$s = Dict $step
|
|
1971
|
+
if ($null -ne $s -and (BoolArg $s 'foreground' $false)) { $mode = 'foreground' }
|
|
1972
|
+
if ($mode -eq 'foreground') { return Invoke-PixelAction $re $action $value }
|
|
1973
|
+
if ($mode -eq 'auto') {
|
|
1974
|
+
try { return Invoke-UiaAction $re $action $value $step }
|
|
1975
|
+
catch {
|
|
1976
|
+
$msg = $_.Exception.Message
|
|
1977
|
+
if ($msg -like 'ERR|pattern_unsupported|*' -or $msg -like 'ERR|read_only|*' -or $msg -like 'ERR|action_failed|*') {
|
|
1978
|
+
return Invoke-PixelAction $re $action $value
|
|
1979
|
+
}
|
|
1980
|
+
throw
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
return Invoke-UiaAction $re $action $value $step
|
|
1984
|
+
}
|
|
1985
|
+
|
|
1986
|
+
function Invoke-UiaAction($re, $action, $value, $step) {
|
|
1987
|
+
$el = $re.ae
|
|
1988
|
+
$patterns = $re.patterns
|
|
1989
|
+
$s = Dict $step
|
|
1990
|
+
$forceFg = $false
|
|
1991
|
+
if ($null -ne $s) { $forceFg = BoolArg $s 'foreground' $false }
|
|
1992
|
+
$via = 'uia'
|
|
1993
|
+
switch ($action) {
|
|
1994
|
+
'invoke' {
|
|
1995
|
+
# No LegacyIAccessible fallback: the managed client has no LegacyIAccessiblePattern type, so
|
|
1996
|
+
# GetPattern($el, 'LegacyIAccessible') always returned $null and this branch was unreachable.
|
|
1997
|
+
# Patterns come from the ref's cache (Get-RefPattern): a set_value/focus reads the same
|
|
1998
|
+
# pattern in before→action→after, which used to be three GetCurrentPattern round-trips.
|
|
1999
|
+
$p = Get-RefPattern $re 'Invoke'
|
|
2000
|
+
if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " '" + (TruncStr $re.name 40) + "' does not support Invoke") }
|
|
2001
|
+
$p.Invoke(); return $via
|
|
2002
|
+
}
|
|
2003
|
+
'set_value' {
|
|
2004
|
+
$p = Get-RefPattern $re 'Value'
|
|
2005
|
+
if ($null -eq $p) {
|
|
2006
|
+
Err 'pattern_unsupported' ("element " + $re.controlType + " '" + (TruncStr $re.name 40) + "' does not support Value")
|
|
2007
|
+
}
|
|
2008
|
+
try { if ($p.Current.IsReadOnly) { Err 'read_only' ("element " + $re.controlType + " '" + (TruncStr $re.name 40) + "' is read only") } } catch { }
|
|
2009
|
+
$p.SetValue([string]$value); return $via
|
|
2010
|
+
}
|
|
2011
|
+
'text_append' {
|
|
2012
|
+
$p = Get-RefPattern $re 'Value'
|
|
2013
|
+
if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " '" + (TruncStr $re.name 40) + "' does not support Value, cannot append") }
|
|
2014
|
+
try { if ($p.Current.IsReadOnly) { Err 'read_only' 'element is read only' } } catch { }
|
|
2015
|
+
$cur = ''
|
|
2016
|
+
try { $cur = [string]$p.Current.Value } catch { $cur = '' }
|
|
2017
|
+
$p.SetValue($cur + [string]$value); return $via
|
|
2018
|
+
}
|
|
2019
|
+
'toggle' {
|
|
2020
|
+
$p = Get-RefPattern $re 'Toggle'
|
|
2021
|
+
if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support Toggle") }
|
|
2022
|
+
$p.Toggle(); return $via
|
|
2023
|
+
}
|
|
2024
|
+
'select' {
|
|
2025
|
+
$p = Get-RefPattern $re 'SelectionItem'
|
|
2026
|
+
if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support SelectionItem") }
|
|
2027
|
+
$p.Select(); return $via
|
|
2028
|
+
}
|
|
2029
|
+
'expand' {
|
|
2030
|
+
$p = Get-RefPattern $re 'ExpandCollapse'
|
|
2031
|
+
if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support ExpandCollapse") }
|
|
2032
|
+
$p.Expand(); return $via
|
|
2033
|
+
}
|
|
2034
|
+
'collapse' {
|
|
2035
|
+
$p = Get-RefPattern $re 'ExpandCollapse'
|
|
2036
|
+
if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support ExpandCollapse") }
|
|
2037
|
+
$p.Collapse(); return $via
|
|
2038
|
+
}
|
|
2039
|
+
'scroll_up' {
|
|
2040
|
+
$p = Get-RefPattern $re 'Scroll'
|
|
2041
|
+
if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support Scroll") }
|
|
2042
|
+
try { if (-not [bool]$p.Current.VerticallyScrollable) { Err 'action_failed' ("element " + $re.controlType + " is not vertically scrollable") } } catch { }
|
|
2043
|
+
try { $p.ScrollVertical([System.Windows.Automation.ScrollAmount]::SmallDecrement) } catch { Err 'action_failed' ('ScrollVertical threw: ' + $_.Exception.Message) }
|
|
2044
|
+
return $via
|
|
2045
|
+
}
|
|
2046
|
+
'scroll_down' {
|
|
2047
|
+
$p = Get-RefPattern $re 'Scroll'
|
|
2048
|
+
if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support Scroll") }
|
|
2049
|
+
try { if (-not [bool]$p.Current.VerticallyScrollable) { Err 'action_failed' ("element " + $re.controlType + " is not vertically scrollable") } } catch { }
|
|
2050
|
+
try { $p.ScrollVertical([System.Windows.Automation.ScrollAmount]::SmallIncrement) } catch { Err 'action_failed' ('ScrollVertical threw: ' + $_.Exception.Message) }
|
|
2051
|
+
return $via
|
|
2052
|
+
}
|
|
2053
|
+
'focus' {
|
|
2054
|
+
if (-not $forceFg -and -not (Is-ForegroundHwnd $re.hwnd)) {
|
|
2055
|
+
$script:W.stats.refused += 1
|
|
2056
|
+
Err 'needs_foreground' ('action focus on window ' + $re.windowId + ' would raise it; pass {"foreground":true} on the step to allow it')
|
|
2057
|
+
}
|
|
2058
|
+
if ($forceFg) { try { [void][Native]::SetForegroundWindow([IntPtr]$re.hwnd) } catch { } }
|
|
2059
|
+
try { $el.SetFocus() } catch { Err 'action_failed' ('SetFocus threw: ' + $_.Exception.Message) }
|
|
2060
|
+
return $via
|
|
2061
|
+
}
|
|
2062
|
+
default {
|
|
2063
|
+
Err 'unknown_action' ("unsupported action '" + $action + "' (invoke|set_value|toggle|select|expand|collapse|scroll_up|scroll_down|focus|text_append)")
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
function Raise-Foreground($entry) {
|
|
2069
|
+
$h = [IntPtr]$entry.hwnd
|
|
2070
|
+
# A minimized window has no usable screen rect, so pixel coordinates taken from the last
|
|
2071
|
+
# snapshot point at nothing. Restore it before raising so the raise is actually clickable.
|
|
2072
|
+
try { if ([Native]::IsIconic($h)) { [void][Native]::ShowWindow($h, 9); Start-Sleep -Milliseconds 80 } } catch { }
|
|
2073
|
+
try { [void][Native]::SetForegroundWindow($h) } catch { }
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
# ---------------------------------------------------------------- conditions
|
|
2077
|
+
function Target-Element($entry, $cond, $refMap) {
|
|
2078
|
+
$c = Dict $cond
|
|
2079
|
+
$ref = $c.Item('ref')
|
|
2080
|
+
if ($null -ne $ref -and [string]$ref -ne '') {
|
|
2081
|
+
$re = Resolve-Ref $ref $refMap
|
|
2082
|
+
return $re
|
|
2083
|
+
}
|
|
2084
|
+
$by = Dict $c.Item('by')
|
|
2085
|
+
if ($null -eq $by) { $by = @{} }
|
|
2086
|
+
if ($c.ContainsKey('windowId')) { $entry = Window-Entry ([string]$c.Item('windowId')) }
|
|
2087
|
+
$el = Find-ByDescriptor $entry $by
|
|
2088
|
+
if ($null -eq $el) { return $null }
|
|
2089
|
+
return @{ synthetic = $true; ae = $el; windowId = $entry.id; hwnd = $entry.hwnd; patterns = (PatternsOf $el); name = [string]$el.Current.Name; controlType = (ControlTypeName $el.Current.ControlType); className = [string]$el.Current.ClassName; automationId = [string]$el.Current.AutomationId; ref = $null }
|
|
2090
|
+
}
|
|
2091
|
+
|
|
2092
|
+
# Vertical scroll percent for the scroll_percent_changed verify. $null means "no usable Scroll
|
|
2093
|
+
# reading" (pattern unsupported, element unreadable, or not scrollable - UIA reports -1 for the
|
|
2094
|
+
# percent then), so the caller can tell that apart from a genuine 0%. Routes through the ref's
|
|
2095
|
+
# pattern cache (Get-RefPattern) like every other before→action→after read.
|
|
2096
|
+
function Read-ScrollPercent($re) {
|
|
2097
|
+
if ($null -eq $re) { return $null }
|
|
2098
|
+
$sp = Get-RefPattern $re 'Scroll'
|
|
2099
|
+
if ($null -eq $sp) { return $null }
|
|
2100
|
+
try {
|
|
2101
|
+
$pct = [double]$sp.Current.VerticalScrollPercent
|
|
2102
|
+
if ($pct -lt 0) { return $null }
|
|
2103
|
+
return $pct
|
|
2104
|
+
} catch { return $null }
|
|
2105
|
+
}
|
|
2106
|
+
|
|
2107
|
+
function Eval-Once($type, $entry, $cond, $before, $refMap, $scrollBefore) {
|
|
2108
|
+
$c = Dict $cond
|
|
2109
|
+
$expect = $c.Item('expect')
|
|
2110
|
+
switch ($type) {
|
|
2111
|
+
'element_appears' {
|
|
2112
|
+
$t = Target-Element $entry $cond $refMap
|
|
2113
|
+
$obs = 'absent'
|
|
2114
|
+
if ($null -ne $t) { $obs = 'present' }
|
|
2115
|
+
return @{ matched = ($null -ne $t); observed = $obs }
|
|
2116
|
+
}
|
|
2117
|
+
'element_gone' {
|
|
2118
|
+
$t = Target-Element $entry $cond $refMap
|
|
2119
|
+
$obs = 'absent'
|
|
2120
|
+
if ($null -ne $t) { $obs = 'present' }
|
|
2121
|
+
return @{ matched = ($null -eq $t); observed = $obs }
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
$t = Target-Element $entry $cond $refMap
|
|
2125
|
+
if ($null -eq $t) { return @{ matched = $false; observed = 'target missing'; error = 'element_gone' } }
|
|
2126
|
+
$cp = $null
|
|
2127
|
+
try { $cp = $t.ae.Current } catch { }
|
|
2128
|
+
if ($null -eq $cp) { return @{ matched = $false; observed = 'unreadable'; error = 'element_gone' } }
|
|
2129
|
+
$pats = $t.patterns
|
|
2130
|
+
if ($null -eq $pats -or $pats.Count -eq 0) { $pats = PatternsOf $t.ae }
|
|
2131
|
+
switch ($type) {
|
|
2132
|
+
'value_equals' {
|
|
2133
|
+
$v = Read-Value $t.ae $pats
|
|
2134
|
+
return @{ matched = ($v -eq [string]$expect); observed = (TruncStr $v 200) }
|
|
2135
|
+
}
|
|
2136
|
+
'value_changed' {
|
|
2137
|
+
$v = Read-Value $t.ae $pats
|
|
2138
|
+
return @{ matched = ($v -ne [string]$before); observed = (TruncStr $v 200); before = (TruncStr ([string]$before) 200) }
|
|
2139
|
+
}
|
|
2140
|
+
'no_change' {
|
|
2141
|
+
$v = Read-Value $t.ae $pats
|
|
2142
|
+
$n = [string]$cp.Name
|
|
2143
|
+
return @{ matched = ($v -eq [string]$before); observed = (TruncStr $v 200); name = (TruncStr $n 80) }
|
|
2144
|
+
}
|
|
2145
|
+
'name_contains' {
|
|
2146
|
+
$n = [string]$cp.Name
|
|
2147
|
+
return @{ matched = ($n.IndexOf([string]$expect, [StringComparison]::OrdinalIgnoreCase) -ge 0); observed = (TruncStr $n 120) }
|
|
2148
|
+
}
|
|
2149
|
+
'enabled_is' {
|
|
2150
|
+
$want = BoolArg (@{ v = $expect }) 'v' $true
|
|
2151
|
+
$e = [bool]$cp.IsEnabled
|
|
2152
|
+
return @{ matched = ($e -eq $want); observed = $e }
|
|
2153
|
+
}
|
|
2154
|
+
'scroll_percent_changed' {
|
|
2155
|
+
# 防循环的确定性判据:"滚了但列表没动"(动作缓存不记结果的无限滚动)在这里有读数可依:
|
|
2156
|
+
# ScrollPattern.VerticalScrollPercent 与动作前读数($scrollBefore,动作步开始时读一次)
|
|
2157
|
+
# 的差值 ≥ expect(默认 1)才命中。轮询复用上面的同一 Target-Element 管道。
|
|
2158
|
+
$sp = Get-RefPattern $t 'Scroll'
|
|
2159
|
+
if ($null -eq $sp) { return @{ matched = $false; observed = 'no Scroll pattern'; error = 'pattern_unsupported' } }
|
|
2160
|
+
$pct = $null
|
|
2161
|
+
try { $pct = [double]$sp.Current.VerticalScrollPercent } catch { $pct = $null }
|
|
2162
|
+
if ($null -eq $pct -or $pct -lt 0) { return @{ matched = $false; observed = 'not scrollable'; error = 'pattern_unsupported' } }
|
|
2163
|
+
$base = $scrollBefore
|
|
2164
|
+
if ($null -eq $base) { $base = $pct } # 无动作前基线(独立 wait):首轮读数即基线
|
|
2165
|
+
$want = 1.0
|
|
2166
|
+
if ($null -ne $expect -and [string]$expect -ne '') { try { $want = [Math]::Abs([double]$expect) } catch { $want = 1.0 } }
|
|
2167
|
+
$delta = [Math]::Abs($pct - [double]$base)
|
|
2168
|
+
return @{ matched = ($delta -ge $want); observed = ('percent=' + $pct); before = ('percent=' + $base) }
|
|
2169
|
+
}
|
|
2170
|
+
default {
|
|
2171
|
+
Err 'unknown_condition' ("unsupported condition type '" + $type + "'")
|
|
2172
|
+
}
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
function Wait-Condition($entry, $cond, $timeoutMs, $before, $refMap, $scrollBefore) {
|
|
2177
|
+
$c = Dict $cond
|
|
2178
|
+
$type = [string]$c.Item('type')
|
|
2179
|
+
if ($type -eq '') { Err 'missing_arg' 'condition needs a type' }
|
|
2180
|
+
if ($null -eq $timeoutMs -or $timeoutMs -le 0) { $timeoutMs = 750 }
|
|
2181
|
+
$budget = $timeoutMs
|
|
2182
|
+
$left = BudgetLeftMs
|
|
2183
|
+
if ($left -lt $budget) { $budget = [int]$left }
|
|
2184
|
+
if ($budget -lt 0) { $budget = 0 }
|
|
2185
|
+
$st = TickNow
|
|
2186
|
+
$deadline = $st + ([Int64]$budget * 10000)
|
|
2187
|
+
$last = $null
|
|
2188
|
+
while ($true) {
|
|
2189
|
+
$last = Eval-Once $type $entry $cond $before $refMap $scrollBefore
|
|
2190
|
+
if ($last.matched) { break }
|
|
2191
|
+
if ((TickNow) -ge $deadline) { break }
|
|
2192
|
+
Start-Sleep -Milliseconds 80
|
|
2193
|
+
}
|
|
2194
|
+
$r = [ordered]@{ type = $type; matched = [bool]$last.matched; ms = (MsFrom $st) }
|
|
2195
|
+
if ($last.ContainsKey('observed')) { $r['observed'] = $last.observed }
|
|
2196
|
+
if ($last.ContainsKey('before')) { $r['beforeObserved'] = $last.before }
|
|
2197
|
+
if ($last.ContainsKey('name')) { $r['observedName'] = $last.name }
|
|
2198
|
+
if ($last.ContainsKey('error')) { $r['error'] = $last.error }
|
|
2199
|
+
return $r
|
|
2200
|
+
}
|
|
2201
|
+
# ---------------------------------------------------------------- commands
|
|
2202
|
+
function Cmd-Ping($A) {
|
|
2203
|
+
if ($script:dpiMode -eq 0 -and $script:nativeLoaded) {
|
|
2204
|
+
try { $script:dpiMode = [Native]::MakeAware() } catch { }
|
|
2205
|
+
}
|
|
2206
|
+
# The station size comes from the ONE authoritative measurement (Get-VirtScreen: the virtual
|
|
2207
|
+
# screen with its measured fallback chain). Ping used to re-derive it from its own SM_CXSCREEN
|
|
2208
|
+
# read plus the WinForms primary-screen bounds, and also reported a dead "logical" pair no
|
|
2209
|
+
# consumer ever read — a second opinion that disagreed with the pointer channel's answer on
|
|
2210
|
+
# multi-monitor boxes, exactly the silent drift the "measure, never hardcode" rule exists for.
|
|
2211
|
+
# MakeAware has already run at startup (and above), so the metrics are physical.
|
|
2212
|
+
$v = Get-VirtScreen
|
|
2213
|
+
$w = [int]$v.w; $h = [int]$v.h
|
|
2214
|
+
return [ordered]@{
|
|
2215
|
+
psVersion = $PSVersionTable.PSVersion.ToString()
|
|
2216
|
+
station = @{ width = $w; height = $h }
|
|
2217
|
+
workerPid = [int]$PID
|
|
2218
|
+
maxRefs = [int]$script:W.maxRefs
|
|
2219
|
+
windowCount = $script:W.windows.Count
|
|
2220
|
+
totalRefs = $script:W.totalRefs
|
|
2221
|
+
startupMs = [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $script:W.startTick) / 10000.0, 1)
|
|
2222
|
+
nativeLoaded = [bool]$script:nativeLoaded
|
|
2223
|
+
dpiAware = [int]$script:dpiMode
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
|
|
2227
|
+
function Match-RootWindow($w, $wantPid, $wantTitle, $wantClass, $titleExact, $wantRegex) {
|
|
2228
|
+
$cp = $null
|
|
2229
|
+
try { $cp = $w.Current } catch { return $false }
|
|
2230
|
+
$hwnd = [int]$cp.NativeWindowHandle
|
|
2231
|
+
if ($hwnd -eq 0) { return $false }
|
|
2232
|
+
$rc = RectOf $cp
|
|
2233
|
+
$iconic = $false
|
|
2234
|
+
try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
|
|
2235
|
+
if (($rc.w -le 0 -or $rc.h -le 0) -and -not $iconic) { return $false }
|
|
2236
|
+
if ($wantPid -gt 0 -and [int]$cp.ProcessId -ne $wantPid) { return $false }
|
|
2237
|
+
if ($wantClass -ne '' -and ([string]$cp.ClassName).IndexOf($wantClass, [StringComparison]::OrdinalIgnoreCase) -lt 0) { return $false }
|
|
2238
|
+
$t = [string]$cp.Name
|
|
2239
|
+
if ($wantTitle -ne '') {
|
|
2240
|
+
if ($titleExact) { if (-not $t.Equals($wantTitle, [StringComparison]::OrdinalIgnoreCase)) { return $false } }
|
|
2241
|
+
elseif ($t.IndexOf($wantTitle, [StringComparison]::OrdinalIgnoreCase) -lt 0) { return $false }
|
|
2242
|
+
}
|
|
2243
|
+
if ($wantRegex -ne '') {
|
|
2244
|
+
try { if ($t -notmatch $wantRegex) { return $false } } catch { return $false }
|
|
2245
|
+
}
|
|
2246
|
+
return $true
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2249
|
+
function Cmd-ResolveWindow($A) {
|
|
2250
|
+
$windowId = StrArg $A 'windowId' ''
|
|
2251
|
+
if ($windowId -ne '') {
|
|
2252
|
+
$e = Window-Entry $windowId
|
|
2253
|
+
$ae = Window-Ae $e
|
|
2254
|
+
if ($null -eq $ae) { Err 'window_not_found' ("windowId " + $windowId + " is gone") }
|
|
2255
|
+
$info = WindowInfo $e ($ae.Current)
|
|
2256
|
+
$info['appearedMs'] = 0
|
|
2257
|
+
return $info
|
|
2258
|
+
}
|
|
2259
|
+
$wantPid = IntArg $A 'pid' 0
|
|
2260
|
+
$wantTitle = StrArg $A 'title' ''
|
|
2261
|
+
$wantClass = StrArg $A 'class' ''
|
|
2262
|
+
$wantRegex = StrArg $A 'titleRegex' ''
|
|
2263
|
+
$titleExact = BoolArg $A 'titleExact' $false
|
|
2264
|
+
$timeoutMs = IntArg $A 'timeoutMs' 4000
|
|
2265
|
+
if ($wantPid -eq 0 -and $wantTitle -eq '' -and $wantClass -eq '' -and $wantRegex -eq '') { Err 'missing_arg' 'resolve_window needs windowId, pid, title, class or titleRegex' }
|
|
2266
|
+
$st = TickNow
|
|
2267
|
+
$left = BudgetLeftMs
|
|
2268
|
+
if ($timeoutMs -gt $left) { $timeoutMs = [int]$left }
|
|
2269
|
+
if ($timeoutMs -lt 0) { $timeoutMs = 0 }
|
|
2270
|
+
$deadline = $st + ([Int64]$timeoutMs * 10000)
|
|
2271
|
+
while ($true) {
|
|
2272
|
+
foreach ($w in (RootWindows)) {
|
|
2273
|
+
if (Match-RootWindow $w $wantPid $wantTitle $wantClass $titleExact $wantRegex) {
|
|
2274
|
+
$hwnd = 0
|
|
2275
|
+
try { $hwnd = [int]$w.Current.NativeWindowHandle } catch { continue }
|
|
2276
|
+
$e = Ensure-Window $hwnd $w
|
|
2277
|
+
if ($null -eq $e) { continue }
|
|
2278
|
+
$info = WindowInfo $e ($w.Current)
|
|
2279
|
+
$info['appearedMs'] = [Math]::Round((MsFrom $st), 1)
|
|
2280
|
+
return $info
|
|
2281
|
+
}
|
|
2282
|
+
}
|
|
2283
|
+
if ((TickNow) -ge $deadline) { break }
|
|
2284
|
+
Start-Sleep -Milliseconds 150
|
|
2285
|
+
}
|
|
2286
|
+
$script:W.stats.refused += 1
|
|
2287
|
+
Err 'window_not_found' ("no window matching pid=" + $wantPid + " title='" + $wantTitle + "' class='" + $wantClass + "' after " + $timeoutMs + 'ms of polling')
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
function Cmd-ListWindows($A) {
|
|
2291
|
+
$onlyVisible = BoolArg $A 'onlyVisible' $true
|
|
2292
|
+
$out = New-Object System.Collections.Generic.List[object]
|
|
2293
|
+
foreach ($w in (RootWindows)) {
|
|
2294
|
+
$cp = $null
|
|
2295
|
+
try { $cp = $w.Current } catch { continue }
|
|
2296
|
+
$hwnd = [int]$cp.NativeWindowHandle
|
|
2297
|
+
if ($hwnd -eq 0) { continue }
|
|
2298
|
+
$rc = RectOf $cp
|
|
2299
|
+
$iconic = $false
|
|
2300
|
+
try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
|
|
2301
|
+
$vis = $false
|
|
2302
|
+
try { $vis = [Native]::IsWindowVisible([IntPtr]$hwnd) } catch { }
|
|
2303
|
+
if ($onlyVisible -and (($rc.w -le 0 -or $rc.h -le 0) -or (-not $vis -and -not $iconic))) { continue }
|
|
2304
|
+
$e = Ensure-Window $hwnd $w
|
|
2305
|
+
if ($null -eq $e) { continue }
|
|
2306
|
+
$info = WindowInfo $e $cp
|
|
2307
|
+
$info['isMinimized'] = $iconic
|
|
2308
|
+
$out.Add($info) | Out-Null
|
|
2309
|
+
}
|
|
2310
|
+
return [ordered]@{ windows = $out; count = $out.Count; totalRefs = $script:W.totalRefs }
|
|
2311
|
+
}
|
|
2312
|
+
|
|
2313
|
+
function Cmd-Snapshot($A) {
|
|
2314
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
2315
|
+
return Build-Snapshot $entry $A
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
function Cmd-Describe($A) {
|
|
2319
|
+
$ref = StrArg $A 'ref' ''
|
|
2320
|
+
$re = Resolve-Ref $ref $A
|
|
2321
|
+
# The descriptor rides the ref record: New-Ref already cached controlType/name/className/
|
|
2322
|
+
# automationId/patterns/enabled/isOffscreen/rect at snapshot time, and the only caller
|
|
2323
|
+
# (computer_act's Node-side policy precheck) needs exactly those fields — the same
|
|
2324
|
+
# cached-descriptor semantics Cmd-PrepareBatch has always judged policy on. The live COM re-read
|
|
2325
|
+
# is confined to the cache-miss branch: a rebound ref's cached fields belong to the OLD element
|
|
2326
|
+
# (Resolve-Ref swaps $re.ae without refreshing them), so only there is a re-read honest.
|
|
2327
|
+
if ($re.rebound) {
|
|
2328
|
+
$d = DescriptorOf $re $true
|
|
2329
|
+
$d['rebound'] = $true
|
|
2330
|
+
return $d
|
|
2331
|
+
}
|
|
2332
|
+
return DescriptorOf $re $false
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
function Cmd-DescriptorMatch($A) {
|
|
2336
|
+
# Read-only: resolves a by-descriptor exactly the way act / commit_batch / wait would, and reports
|
|
2337
|
+
# WHY (which rung of the ladder, how confident, whether it degraded) or what it nearly matched.
|
|
2338
|
+
# It sends no input, moves no pointer and mints no ref, so it is safe to call before a batch.
|
|
2339
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
2340
|
+
$by = Dict (ArgOf $A 'by')
|
|
2341
|
+
if ($null -eq $by) { Err 'missing_arg' 'descriptor_match needs a by descriptor' }
|
|
2342
|
+
$el = Find-ByDescriptor $entry $by
|
|
2343
|
+
$lm = $script:W.lastMatch
|
|
2344
|
+
if ($null -eq $lm) {
|
|
2345
|
+
$lm = @{
|
|
2346
|
+
matchedBy = ''; ladder = ''; score = 0.0; degraded = $false; candidateCount = 0
|
|
2347
|
+
scanned = 'all'; nameExact = $true; reason = 'no_match'; tried = @(); candidates = @()
|
|
2348
|
+
ambiguityAt = ''; diagnosticTruncated = $false
|
|
2349
|
+
candidateCountKnown = $true; fastCond = $null
|
|
2350
|
+
}
|
|
2351
|
+
}
|
|
2352
|
+
# The strict fast path resolved through FindFirst, which stops at the first hit and leaves the
|
|
2353
|
+
# real same-name count unknown (candidateCountKnown=false). This command is the read-only
|
|
2354
|
+
# diagnostic, so it re-runs the EXACT condition the resolver used as a full enumeration: a
|
|
2355
|
+
# same-name ambiguity surfaces here with its true candidate count instead of hiding behind a
|
|
2356
|
+
# fabricated one. Reads only — no input, no refs.
|
|
2357
|
+
if ($null -ne $el -and -not [bool]$lm.candidateCountKnown -and $null -ne $lm.fastCond) {
|
|
2358
|
+
$aeD = Window-Ae $entry
|
|
2359
|
+
if ($null -ne $aeD) {
|
|
2360
|
+
$recount = @()
|
|
2361
|
+
try { $recount = @($aeD.FindAll([System.Windows.Automation.TreeScope]::Descendants, $lm.fastCond)) } catch { $recount = @() }
|
|
2362
|
+
if ($recount.Count -ge 1) {
|
|
2363
|
+
$lm.candidateCount = $recount.Count
|
|
2364
|
+
$lm.candidateCountKnown = $true
|
|
2365
|
+
if ($recount.Count -gt 1 -and [string]$lm.ambiguityAt -eq '') { $lm.ambiguityAt = [string]$lm.ladder }
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
}
|
|
2369
|
+
$r = [ordered]@{
|
|
2370
|
+
found = [bool]($null -ne $el)
|
|
2371
|
+
windowId = $entry.id
|
|
2372
|
+
matchedBy = [string]$lm.matchedBy
|
|
2373
|
+
ladder = [string]$lm.ladder
|
|
2374
|
+
score = [double]$lm.score
|
|
2375
|
+
degraded = [bool]$lm.degraded
|
|
2376
|
+
candidateCount = [int]$lm.candidateCount
|
|
2377
|
+
# true = counted from a full enumeration (or the recount above); false = the resolver only
|
|
2378
|
+
# ran FindFirst, so the count is "at least one" and a same-name ambiguity may still hide.
|
|
2379
|
+
candidateCountKnown = [bool]$lm.candidateCountKnown
|
|
2380
|
+
scanned = [string]$lm.scanned
|
|
2381
|
+
nameExact = [bool]$lm.nameExact
|
|
2382
|
+
# NOT @($lm.tried)/@($lm.candidates): Windows PowerShell 5.1 throws "Argument types do not
|
|
2383
|
+
# match" for @() around a List[object] made by New-Object (verified on 5.1.26100). JsonOf walks
|
|
2384
|
+
# IEnumerable, so the raw collections serialise as arrays without the cast.
|
|
2385
|
+
tried = $lm.tried
|
|
2386
|
+
candidates = $lm.candidates
|
|
2387
|
+
}
|
|
2388
|
+
if ([string]$lm.reason -ne '') { $r['reason'] = [string]$lm.reason }
|
|
2389
|
+
if ([string]$lm.ambiguityAt -ne '') { $r['ambiguityAt'] = [string]$lm.ambiguityAt }
|
|
2390
|
+
if ([bool]$lm.diagnosticTruncated) { $r['diagnosticTruncated'] = $true }
|
|
2391
|
+
if ($null -ne $el) {
|
|
2392
|
+
$cp = $null
|
|
2393
|
+
try { $cp = $el.Current } catch { $cp = $null }
|
|
2394
|
+
if ($null -ne $cp) {
|
|
2395
|
+
$r['element'] = [ordered]@{
|
|
2396
|
+
name = (TruncStr ([string]$cp.Name) 160)
|
|
2397
|
+
automationId = [string]$cp.AutomationId
|
|
2398
|
+
controlType = (ControlTypeName $cp.ControlType)
|
|
2399
|
+
className = [string]$cp.ClassName
|
|
2400
|
+
enabled = [bool]$cp.IsEnabled
|
|
2401
|
+
isOffscreen = [bool]$cp.IsOffscreen
|
|
2402
|
+
rect = (RectOf $cp)
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
if ([string]$r['matchedBy'] -eq '' -and $r.Contains('matchedBy')) {
|
|
2407
|
+
$r.Remove('matchedBy')
|
|
2408
|
+
if ($r.Contains('ladder')) { $r.Remove('ladder') }
|
|
2409
|
+
}
|
|
2410
|
+
return $r
|
|
2411
|
+
}
|
|
2412
|
+
|
|
2413
|
+
function Apply-ModeArg($A) {
|
|
2414
|
+
# The Node side sends the user's chosen delivery mode on every act/commit_batch, so a fresh worker
|
|
2415
|
+
# (respawned lazily) picks it up on the next action instead of resetting to the default.
|
|
2416
|
+
$m = (StrArg $A 'mode' '').ToLowerInvariant()
|
|
2417
|
+
if (@('background', 'auto', 'foreground') -contains $m) { $script:W.pointerMode = $m }
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
function Cmd-SetPointerMode($A) {
|
|
2421
|
+
$m = (StrArg $A 'mode' '').ToLowerInvariant()
|
|
2422
|
+
if (@('background', 'auto', 'foreground') -notcontains $m) { Err 'bad_arg' ("pointer mode '" + $m + "' is not background|auto|foreground") }
|
|
2423
|
+
$script:W.pointerMode = $m
|
|
2424
|
+
return [ordered]@{ mode = $m }
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
function Cmd-EscapePressed($A) {
|
|
2428
|
+
# Fallback probe for the Node host's global-ESC watcher (the indicator is the primary channel).
|
|
2429
|
+
# Same latch as the indicator: the low bit reports "pressed since the previous call", so a tap
|
|
2430
|
+
# shorter than the poll interval still counts once. Test-Escape stays the plain held-read for
|
|
2431
|
+
# aborting a batch mid-step, where "is it down right now" is the correct question.
|
|
2432
|
+
try {
|
|
2433
|
+
$state = [int][Native]::GetAsyncKeyState(0x1B)
|
|
2434
|
+
return [ordered]@{ pressed = [bool](($state -band 0x8000) -ne 0 -or ($state -band 0x0001) -ne 0) }
|
|
2435
|
+
} catch {
|
|
2436
|
+
return [ordered]@{ pressed = $false }
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
|
|
2440
|
+
function Cmd-Act($A) {
|
|
2441
|
+
Apply-ModeArg $A
|
|
2442
|
+
$ref = StrArg $A 'ref' ''
|
|
2443
|
+
$action = StrArg $A 'action' ''
|
|
2444
|
+
if ($action -eq '') { Err 'missing_arg' 'act needs an action' }
|
|
2445
|
+
$value = ArgOf $A 'value'
|
|
2446
|
+
$re = Resolve-Ref $ref $A
|
|
2447
|
+
# Third arg = the ref record: before/action/after then share ONE cached pattern object each
|
|
2448
|
+
# instead of re-running GetCurrentPattern for the same pattern three times.
|
|
2449
|
+
$before = Read-Value $re.ae $re.patterns $re
|
|
2450
|
+
# scroll_percent_changed 的动作前基线:只有滚动动作或 verify 明确要它才多读一次(否则每个
|
|
2451
|
+
# act 都白付一次跨进程 pattern 读)。
|
|
2452
|
+
$scrollBefore = $null
|
|
2453
|
+
$vpre = Dict (ArgOf $A 'verify')
|
|
2454
|
+
$vpreType = if ($null -ne $vpre) { [string]$vpre.Item('type') } else { '' }
|
|
2455
|
+
if ($action -eq 'scroll_up' -or $action -eq 'scroll_down' -or $vpreType -eq 'scroll_percent_changed') {
|
|
2456
|
+
$scrollBefore = Read-ScrollPercent $re
|
|
2457
|
+
}
|
|
2458
|
+
$cur0 = Cursor-Pos
|
|
2459
|
+
$fg0 = Foreground-Hwnd
|
|
2460
|
+
$st = TickNow
|
|
2461
|
+
$via = Do-Action $re $action $value $A
|
|
2462
|
+
$script:W.stats.actionsPerformed += 1
|
|
2463
|
+
$ms = MsFrom $st
|
|
2464
|
+
$re2 = Resolve-Ref $ref $A
|
|
2465
|
+
$after = Read-Value $re2.ae $re2.patterns $re2
|
|
2466
|
+
$cur1 = Cursor-Pos
|
|
2467
|
+
$fg1 = Foreground-Hwnd
|
|
2468
|
+
$r = [ordered]@{
|
|
2469
|
+
applied = $true
|
|
2470
|
+
before = (TruncStr ([string]$before) 200)
|
|
2471
|
+
after = (TruncStr ([string]$after) 200)
|
|
2472
|
+
ms = $ms
|
|
2473
|
+
via = $via
|
|
2474
|
+
ref = $ref
|
|
2475
|
+
action = $action
|
|
2476
|
+
cursorMoved = -not ($cur0.x -eq $cur1.x -and $cur0.y -eq $cur1.y)
|
|
2477
|
+
foregroundChanged = ($fg0 -ne $fg1)
|
|
2478
|
+
revision = $re.revision
|
|
2479
|
+
}
|
|
2480
|
+
$v = Dict (ArgOf $A 'verify')
|
|
2481
|
+
if ($null -ne $v) {
|
|
2482
|
+
$entry = $script:W.windows.Item($re.windowId)
|
|
2483
|
+
# A verify that does not name its own target is a claim about the element this very action
|
|
2484
|
+
# just touched, so default it to that ref. Without this, value_equals resolves nothing and
|
|
2485
|
+
# every post-action check reads "target missing" no matter how correct the action was.
|
|
2486
|
+
if (-not $v.ContainsKey('ref') -and $null -eq $v.Item('by')) { $v['ref'] = $ref }
|
|
2487
|
+
$vm = IntArg $v 'timeoutMs' 900
|
|
2488
|
+
$vv = Wait-Condition $entry $v $vm $before $null $scrollBefore
|
|
2489
|
+
$r['verify'] = $vv
|
|
2490
|
+
$verdict = if ([bool]$vv.matched) { 'matched' } else { 'unmatched' }
|
|
2491
|
+
$r['detail'] = ('verify=' + [string]$vv.type + ':' + $verdict)
|
|
2492
|
+
}
|
|
2493
|
+
return $r
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
function Cmd-PrepareBatch($A) {
|
|
2497
|
+
$steps = ListOf (ArgOf $A 'steps')
|
|
2498
|
+
if ($steps.Count -eq 0) { Err 'missing_arg' 'prepare_batch needs steps' }
|
|
2499
|
+
if ($steps.Count -gt 64) { Err 'too_many_steps' ('prepare_batch supports at most 64 steps, got ' + $steps.Count) }
|
|
2500
|
+
$descs = New-Object System.Collections.Generic.List[object]
|
|
2501
|
+
$allOk = $true
|
|
2502
|
+
$revSeen = @{}
|
|
2503
|
+
$batchWid = StrArg $A 'windowId' ''
|
|
2504
|
+
$i = -1
|
|
2505
|
+
foreach ($raw in $steps) {
|
|
2506
|
+
$i += 1
|
|
2507
|
+
$s = Dict $raw
|
|
2508
|
+
$ref = [string]$s.Item('ref')
|
|
2509
|
+
$by = Dict $s.Item('by')
|
|
2510
|
+
$re = $null
|
|
2511
|
+
try {
|
|
2512
|
+
if ($ref -ne '') {
|
|
2513
|
+
$re = Resolve-Ref $ref $null
|
|
2514
|
+
$d = DescriptorOf $re $false
|
|
2515
|
+
$d['index'] = $i
|
|
2516
|
+
$e = $script:W.windows.Item($re.windowId)
|
|
2517
|
+
$revSeen[$re.windowId] = $e.revision
|
|
2518
|
+
} elseif ($null -ne $by) {
|
|
2519
|
+
$wid = [string]$s.Item('windowId')
|
|
2520
|
+
# A replayed recipe step carries only a `by` descriptor; the window it belongs to comes
|
|
2521
|
+
# from the batch-level windowId, not from the step. Fall back to it before refusing.
|
|
2522
|
+
if ($wid -eq '') { $wid = $batchWid }
|
|
2523
|
+
if ($wid -eq '') { Err 'missing_arg' ("step " + $i + " has a by-descriptor but no windowId") }
|
|
2524
|
+
$entry = Window-Entry $wid
|
|
2525
|
+
$el = Find-ByDescriptor $entry $by
|
|
2526
|
+
if ($null -eq $el) { Err 'descriptor_unresolved' ("step " + $i + " descriptor matched nothing in " + $wid) }
|
|
2527
|
+
# A by-descriptor is a guess (a name can churn, an id can be ambiguous), so the dry run has
|
|
2528
|
+
# to say HOW the guess was reached. These fields come from the ladder record the call above
|
|
2529
|
+
# just left behind, and only the by branch gets them: a ref is an exact identity, not a
|
|
2530
|
+
# locator decision, so attaching a score to it would describe a match that never happened.
|
|
2531
|
+
$loc = Get-LocatorFields $script:W.lastMatch
|
|
2532
|
+
$cp = $el.Current
|
|
2533
|
+
$pats = PatternsOf $el
|
|
2534
|
+
$d = [ordered]@{
|
|
2535
|
+
index = $i
|
|
2536
|
+
windowId = $wid
|
|
2537
|
+
resolvedBy = 'descriptor'
|
|
2538
|
+
name = (TruncStr ([string]$cp.Name) 160)
|
|
2539
|
+
controlType = (ControlTypeName $cp.ControlType)
|
|
2540
|
+
className = [string]$cp.ClassName
|
|
2541
|
+
automationId = [string]$cp.AutomationId
|
|
2542
|
+
availablePatterns = @($pats)
|
|
2543
|
+
supportedAction = (SupportedActionOf $pats)
|
|
2544
|
+
enabled = [bool]$cp.IsEnabled
|
|
2545
|
+
isOffscreen = [bool]$cp.IsOffscreen
|
|
2546
|
+
rect = (RectOf $cp)
|
|
2547
|
+
}
|
|
2548
|
+
if ($null -ne $loc) {
|
|
2549
|
+
$d['matchedBy'] = $loc['matchedBy']
|
|
2550
|
+
$d['ladder'] = $loc['ladder']
|
|
2551
|
+
$d['score'] = $loc['score']
|
|
2552
|
+
$d['degraded'] = $loc['degraded']
|
|
2553
|
+
}
|
|
2554
|
+
# Same rule as DescriptorOf: only when the 160-cut display name differs from the real one,
|
|
2555
|
+
# so a recipe rebuilt from this descriptor can carry a name that still resolves.
|
|
2556
|
+
if ([string]$cp.Name -ne [string]$d['name']) { $d['fullName'] = [string]$cp.Name }
|
|
2557
|
+
$revSeen[$wid] = $entry.revision
|
|
2558
|
+
} else {
|
|
2559
|
+
Err 'missing_ref' ("step " + $i + " needs a ref or a by descriptor")
|
|
2560
|
+
}
|
|
2561
|
+
$actName = [string]$s.Item('action')
|
|
2562
|
+
# Validate the verb at prepare time. Prepare is the dry run: its whole job is to answer
|
|
2563
|
+
# "would this batch work?" before a single event reaches the desktop. It used to copy the
|
|
2564
|
+
# action through untouched, so "fly" resolved happily and only commit_batch refused it —
|
|
2565
|
+
# the model paid for two round-trips and a revision to learn a typo it could have heard
|
|
2566
|
+
# about immediately.
|
|
2567
|
+
if ($actName -eq '') { Err 'missing_arg' ("step " + $i + " needs an action") }
|
|
2568
|
+
# PowerShell's switch is case-INSENSITIVE by default, but the values it compares come from
|
|
2569
|
+
# model-authored JSON and a "Invoke" used to sail through prepare while the case-sensitive
|
|
2570
|
+
# hashtable check later refused it. Normalise once here so prepare and commit agree.
|
|
2571
|
+
$actName = $actName.ToLowerInvariant()
|
|
2572
|
+
if (-not $script:W.actionNames.ContainsKey($actName)) {
|
|
2573
|
+
Err 'unknown_action' ("step " + $i + " action '" + $actName + "' is not one of " + (($script:W.actionNames.Keys | Sort-Object) -join '|'))
|
|
2574
|
+
}
|
|
2575
|
+
$d['action'] = $actName
|
|
2576
|
+
$descs.Add($d) | Out-Null
|
|
2577
|
+
} catch {
|
|
2578
|
+
$allOk = $false
|
|
2579
|
+
$code, $msg = Split-Err $_
|
|
2580
|
+
$descs.Add([ordered]@{ index = $i; ref = $ref; action = [string]$s.Item('action'); error = $msg; code = $code }) | Out-Null
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
# A batch is validated against ONE revision (commit compares every step against the single value
|
|
2584
|
+
# returned here). Steps that span two snapshotted windows can never satisfy that: prepare passed
|
|
2585
|
+
# on the first window's revision, commit then died on the second window's step — reported as
|
|
2586
|
+
# "revision stale" when the real answer is "one batch per window". Refuse at the dry run, where
|
|
2587
|
+
# nothing has been executed and the caller can restructure for free.
|
|
2588
|
+
if ($revSeen.Count -gt 1) {
|
|
2589
|
+
$script:W.stats.refused += 1
|
|
2590
|
+
Err 'multi_window_batch' (("the steps span " + $revSeen.Count + " windows (" + ((@($revSeen.Keys) | Sort-Object) -join ',') + "); split them into one batch per window and run each batch with its own revision"))
|
|
2591
|
+
}
|
|
2592
|
+
$rev = 0
|
|
2593
|
+
if ($revSeen.Count -ge 1) { $rev = [int](@($revSeen.Values)[0]) }
|
|
2594
|
+
return [ordered]@{ descriptors = $descs; revision = $rev; allResolved = $allOk; revisionsByWindow = $revSeen; steps = $steps.Count }
|
|
2595
|
+
}
|
|
2596
|
+
|
|
2597
|
+
function Cmd-CommitBatch($A) {
|
|
2598
|
+
Apply-ModeArg $A
|
|
2599
|
+
$steps = ListOf (ArgOf $A 'steps')
|
|
2600
|
+
if ($steps.Count -eq 0) { Err 'missing_arg' 'commit_batch needs steps' }
|
|
2601
|
+
if ($steps.Count -gt 64) { Err 'too_many_steps' ('commit_batch supports at most 64 steps, got ' + $steps.Count) }
|
|
2602
|
+
$givenRev = ArgOf $A 'revision'
|
|
2603
|
+
if ($null -eq $givenRev) {
|
|
2604
|
+
$script:W.stats.refused += 1
|
|
2605
|
+
Err 'revision_mismatch' 'commit_batch requires the exact revision returned by prepare_batch; refusing to perform 0 actions'
|
|
2606
|
+
}
|
|
2607
|
+
$wantRev = [int]$givenRev
|
|
2608
|
+
$batchWid = StrArg $A 'windowId' ''
|
|
2609
|
+
# phase 1: resolve every step, perform nothing
|
|
2610
|
+
$plan = New-Object System.Collections.Generic.List[object]
|
|
2611
|
+
$i = -1
|
|
2612
|
+
foreach ($raw in $steps) {
|
|
2613
|
+
$i += 1
|
|
2614
|
+
$s = Dict $raw
|
|
2615
|
+
$ref = [string]$s.Item('ref')
|
|
2616
|
+
# Normalise exactly like prepare_batch, so a verb that passed the dry run cannot fail here on
|
|
2617
|
+
# casing alone. The two phases must agree on what they accepted.
|
|
2618
|
+
$action = ([string]$s.Item('action')).ToLowerInvariant()
|
|
2619
|
+
$entry = $null
|
|
2620
|
+
$re = $null
|
|
2621
|
+
$loc = $null
|
|
2622
|
+
if ($ref -ne '') {
|
|
2623
|
+
$re = Resolve-Ref $ref $null
|
|
2624
|
+
$entry = $script:W.windows.Item($re.windowId)
|
|
2625
|
+
if ($re.revision -ne $wantRev) {
|
|
2626
|
+
$script:W.stats.refused += 1
|
|
2627
|
+
Err 'revision_mismatch' ("ref " + $ref + " is at revision " + $re.revision + " of " + $re.windowId + " but the batch declared revision " + $wantRev + '; performing 0 actions')
|
|
2628
|
+
}
|
|
2629
|
+
} else {
|
|
2630
|
+
$wid = [string]$s.Item('windowId')
|
|
2631
|
+
# Same rule as prepare_batch: a replayed step has no per-step windowId, so inherit the
|
|
2632
|
+
# batch-level one instead of tripping Window-Entry('') with 'windowId is required'.
|
|
2633
|
+
if ($wid -eq '') { $wid = $batchWid }
|
|
2634
|
+
$entry = Window-Entry $wid
|
|
2635
|
+
if ($entry.revision -ne $wantRev) {
|
|
2636
|
+
$script:W.stats.refused += 1
|
|
2637
|
+
Err 'revision_mismatch' ("window " + $wid + " is at revision " + $entry.revision + " but the batch declared revision " + $wantRev + '; performing 0 actions')
|
|
2638
|
+
}
|
|
2639
|
+
$by = Dict $s.Item('by')
|
|
2640
|
+
if ($null -eq $by) { Err 'missing_ref' ("step " + $i + " needs a ref or a by descriptor") }
|
|
2641
|
+
$el = Find-ByDescriptor $entry $by
|
|
2642
|
+
if ($null -eq $el) { Err 'descriptor_unresolved' ("step " + $i + " descriptor matched nothing in " + $wid) }
|
|
2643
|
+
# Read from THIS resolution, not from prepare_batch: commit re-resolves on purpose (the tree
|
|
2644
|
+
# may have moved on), so the honest report is what the ladder decided now. Costs no extra
|
|
2645
|
+
# scan — the record is a by-product of the call above.
|
|
2646
|
+
$loc = Get-LocatorFields $script:W.lastMatch
|
|
2647
|
+
$cp = $el.Current
|
|
2648
|
+
$node = @{ controlType = (ControlTypeName $cp.ControlType); name = [string]$cp.Name; className = [string]$cp.ClassName; automationId = [string]$cp.AutomationId; patterns = (PatternsOf $el); enabled = [bool]$cp.IsEnabled; isOffscreen = [bool]$cp.IsOffscreen; rect = (RectOf $cp); depth = 0 }
|
|
2649
|
+
$re = New-Ref $entry $el $cp $node
|
|
2650
|
+
}
|
|
2651
|
+
$verifyOnly = $false
|
|
2652
|
+
if ($action -eq '' -or $action -eq 'verify' -or $action -eq 'no_op' -or $action -eq 'check') {
|
|
2653
|
+
$hasCheck = ($null -ne $s.Item('verify') -or $null -ne $s.Item('type'))
|
|
2654
|
+
if (-not $hasCheck) { Err 'missing_arg' ("step " + $i + " needs an action (or a verify/type for a check-only step)") }
|
|
2655
|
+
$verifyOnly = $true
|
|
2656
|
+
if ($action -eq '') { $action = 'verify' }
|
|
2657
|
+
}
|
|
2658
|
+
$plan.Add(@{ index = $i; s = $s; re = $re; entry = $entry; action = $action; verifyOnly = $verifyOnly; loc = $loc }) | Out-Null
|
|
2659
|
+
}
|
|
2660
|
+
# phase 2: perform in order, stop at the first failure
|
|
2661
|
+
$results = New-Object System.Collections.Generic.List[object]
|
|
2662
|
+
$performed = 0
|
|
2663
|
+
$stoppedAt = -1
|
|
2664
|
+
$status = 'ok'
|
|
2665
|
+
# ---- top-level window diff around phase 2 -----------------------------------------------
|
|
2666
|
+
# A dialog that pops up mid-batch is invisible to the model until its NEXT observation, and its
|
|
2667
|
+
# "确定/取消" text then hijacks the next find_text ranking. A read-only hwnd-set diff around
|
|
2668
|
+
# phase 2 (RootWindows is one FindAll over ~9 desktop roots, ~20-30 ms) surfaces it with the
|
|
2669
|
+
# result. The indicator overlay's own process is excluded when the caller passes its pid: the
|
|
2670
|
+
# capsule lights asynchronously at activity.claim, so a cold first batch can genuinely see it
|
|
2671
|
+
# appear — reporting our own overlay as a "new window" would be exactly the noise this diff
|
|
2672
|
+
# exists to kill. The renderer filters the same pid again as a belt-and-braces.
|
|
2673
|
+
$indicatorPid = IntArg $A 'indicatorPid' 0
|
|
2674
|
+
$hwndsBefore = @{}
|
|
2675
|
+
foreach ($w in (RootWindows)) {
|
|
2676
|
+
$h = 0
|
|
2677
|
+
try { $cpW = $w.Current; $h = [int]$cpW.NativeWindowHandle } catch { continue }
|
|
2678
|
+
if ($h -ne 0) { $hwndsBefore[[string]$h] = $true }
|
|
2679
|
+
}
|
|
2680
|
+
for ($k = 0; $k -lt $plan.Count; $k++) {
|
|
2681
|
+
$p = $plan[$k]
|
|
2682
|
+
if (Test-Escape) { $stoppedAt = $p.index; $status = 'cancelled'; break }
|
|
2683
|
+
$s = $p.s
|
|
2684
|
+
$re = $p.re
|
|
2685
|
+
$action = $p.action
|
|
2686
|
+
$value = $s.Item('value')
|
|
2687
|
+
$cur0 = Cursor-Pos
|
|
2688
|
+
$fg0 = Foreground-Hwnd
|
|
2689
|
+
$before = Read-Value $re.ae $re.patterns $re
|
|
2690
|
+
# scroll_percent_changed 的动作前基线:只在"这一步可能用它"时才读——本步是滚动动作,或
|
|
2691
|
+
# verify 声明了该类型(含 check-only 步,其条件就是步本身)。无关节点每步多读一次就是
|
|
2692
|
+
# 1-3ms × 步数的纯跨进程开销。
|
|
2693
|
+
$scrollBefore = $null
|
|
2694
|
+
$vpre = Dict $s.Item('verify')
|
|
2695
|
+
$vpreType = if ($null -ne $vpre) { [string]$vpre.Item('type') } else { [string]$s.Item('type') }
|
|
2696
|
+
if ($action -eq 'scroll_up' -or $action -eq 'scroll_down' -or $vpreType -eq 'scroll_percent_changed') {
|
|
2697
|
+
$scrollBefore = Read-ScrollPercent $re
|
|
2698
|
+
}
|
|
2699
|
+
$st = TickNow
|
|
2700
|
+
$res = [ordered]@{ index = $p.index; ref = $re.ref; action = $action; status = 'failed'; ms = 0; before = (TruncStr ([string]$before) 200); after = ''; performed = $false }
|
|
2701
|
+
# Same four fields the dry run reported, so the caller can see afterwards which steps were
|
|
2702
|
+
# resolved by a downgraded rung. Ref steps carry none (see Get-LocatorFields).
|
|
2703
|
+
if ($null -ne $p.loc) {
|
|
2704
|
+
$res['matchedBy'] = $p.loc['matchedBy']
|
|
2705
|
+
$res['ladder'] = $p.loc['ladder']
|
|
2706
|
+
$res['score'] = $p.loc['score']
|
|
2707
|
+
$res['degraded'] = $p.loc['degraded']
|
|
2708
|
+
}
|
|
2709
|
+
try {
|
|
2710
|
+
# Step-boundary budget check. The batch must stop ITSELF once its request budget is gone:
|
|
2711
|
+
# Node aborts the CALL after 30 s while the worker kept executing steps and delivering
|
|
2712
|
+
# actions, so a model that saw "timeout" retried a batch that was still landing (duplicate
|
|
2713
|
+
# input). Throwing INSIDE the try means the existing catch records this step as failed with
|
|
2714
|
+
# deadline_exceeded and the partial results return with an accurate performedCount.
|
|
2715
|
+
Test-Deadline 'commit_batch'
|
|
2716
|
+
if ($null -ne $s.Item('foreground') -and (BoolArg $s 'foreground' $false)) { Raise-Foreground $p.entry }
|
|
2717
|
+
if ($p.verifyOnly) {
|
|
2718
|
+
# check-only step: performs NOTHING, it only evaluates the condition that follows the
|
|
2719
|
+
# previous action. It never counts towards performedCount.
|
|
2720
|
+
$cond = Dict $s.Item('verify')
|
|
2721
|
+
if ($null -ne $cond) {
|
|
2722
|
+
if (-not $cond.ContainsKey('ref') -and $null -eq $cond.Item('by')) { $cond['ref'] = $re.ref }
|
|
2723
|
+
} else { $cond = $s }
|
|
2724
|
+
$vm = IntArg $s 'timeoutMs' 900
|
|
2725
|
+
# Same check right before the wait: budget that died mid-step must not enter a verify
|
|
2726
|
+
# clamped to 0ms and report "unmatched" for a condition that was never measured.
|
|
2727
|
+
Test-Deadline 'commit_batch'
|
|
2728
|
+
$vv = Wait-Condition $p.entry $cond $vm $before $null $scrollBefore
|
|
2729
|
+
$res['verify'] = $vv
|
|
2730
|
+
if ($vv.Contains('observed')) { $res['after'] = (TruncStr ([string]$vv.observed) 200) }
|
|
2731
|
+
if ($vv.matched) {
|
|
2732
|
+
$res['status'] = 'passed'
|
|
2733
|
+
$res['ms'] = MsFrom $st
|
|
2734
|
+
$results.Add($res) | Out-Null
|
|
2735
|
+
continue
|
|
2736
|
+
}
|
|
2737
|
+
$res['status'] = 'verify_failed'
|
|
2738
|
+
$res['detail'] = 'verify condition ' + [string]$vv.type + ' did not match within ' + $vm + 'ms'
|
|
2739
|
+
$res['ms'] = MsFrom $st
|
|
2740
|
+
$results.Add($res) | Out-Null
|
|
2741
|
+
$stoppedAt = $p.index
|
|
2742
|
+
$status = 'verify_failed'
|
|
2743
|
+
break
|
|
2744
|
+
}
|
|
2745
|
+
$via = Do-Action $re $action $value $s
|
|
2746
|
+
# Delivery has happened even if a later read/verify fails. Count it immediately.
|
|
2747
|
+
$performed += 1
|
|
2748
|
+
$script:W.stats.actionsPerformed += 1
|
|
2749
|
+
$res['performed'] = $true
|
|
2750
|
+
$res['via'] = $via
|
|
2751
|
+
$after = ''
|
|
2752
|
+
# $re.patterns, not a second PatternsOf scan: the ref already carries the pattern list taken
|
|
2753
|
+
# when this step resolved, and $before above read the same list.
|
|
2754
|
+
try { $after = Read-Value $re.ae $re.patterns $re } catch { }
|
|
2755
|
+
$res['after'] = (TruncStr ([string]$after) 200)
|
|
2756
|
+
$c1 = Cursor-Pos
|
|
2757
|
+
$res['cursorMoved'] = -not ($cur0.x -eq $c1.x -and $cur0.y -eq $c1.y)
|
|
2758
|
+
$res['foregroundChanged'] = ($fg0 -ne (Foreground-Hwnd))
|
|
2759
|
+
$v = Dict $s.Item('verify')
|
|
2760
|
+
if ($null -ne $v) {
|
|
2761
|
+
if (-not $v.ContainsKey('ref') -and $null -eq $v.Item('by')) { $v['ref'] = $re.ref }
|
|
2762
|
+
$vm = IntArg $v 'timeoutMs' 900
|
|
2763
|
+
# Budget may have died inside the action; a 0ms-clamped verify would report "unmatched"
|
|
2764
|
+
# for a condition that was never measured. deadline_exceeded says what actually happened
|
|
2765
|
+
# (and the result already carries performed=true: the action WAS delivered).
|
|
2766
|
+
Test-Deadline 'commit_batch'
|
|
2767
|
+
$vv = Wait-Condition $p.entry $v $vm $before $null $scrollBefore
|
|
2768
|
+
$res['verify'] = $vv
|
|
2769
|
+
if (-not $vv.matched) {
|
|
2770
|
+
$res['status'] = 'verify_failed'
|
|
2771
|
+
$res['ms'] = MsFrom $st
|
|
2772
|
+
$res['detail'] = 'verify condition ' + [string]$v.Item('type') + ' did not match within ' + $vm + 'ms'
|
|
2773
|
+
$results.Add($res) | Out-Null
|
|
2774
|
+
$stoppedAt = $p.index
|
|
2775
|
+
$status = 'verify_failed'
|
|
2776
|
+
break
|
|
2777
|
+
}
|
|
2778
|
+
}
|
|
2779
|
+
$res['status'] = 'passed'
|
|
2780
|
+
$res['ms'] = MsFrom $st
|
|
2781
|
+
$results.Add($res) | Out-Null
|
|
2782
|
+
} catch {
|
|
2783
|
+
$code, $msg = Split-Err $_
|
|
2784
|
+
$res['status'] = 'failed'
|
|
2785
|
+
$res['code'] = $code
|
|
2786
|
+
$res['detail'] = $msg
|
|
2787
|
+
$res['ms'] = MsFrom $st
|
|
2788
|
+
$results.Add($res) | Out-Null
|
|
2789
|
+
$stoppedAt = $p.index
|
|
2790
|
+
$status = 'failed'
|
|
2791
|
+
break
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
# Every step the batch never reached still gets a result entry, so the reply carries one line
|
|
2795
|
+
# per step. Previously the tail was invisible: the model only had performedCount and one stop
|
|
2796
|
+
# sentence, and could not tell which planned steps were skipped. not_executed means an earlier
|
|
2797
|
+
# step failed or the run was cancelled; the fixed Chinese wording is rendered on the Node side
|
|
2798
|
+
# (this file is parsed as ANSI, so Chinese string literals here would corrupt the parser).
|
|
2799
|
+
if ($stoppedAt -ge 0) {
|
|
2800
|
+
for ($k2 = ($stoppedAt + 1); $k2 -lt $steps.Count; $k2++) {
|
|
2801
|
+
$p2 = $null
|
|
2802
|
+
foreach ($pp in $plan) { if ($pp.index -eq $k2) { $p2 = $pp; break } }
|
|
2803
|
+
if ($null -eq $p2) { continue }
|
|
2804
|
+
$results.Add([ordered]@{
|
|
2805
|
+
index = $k2
|
|
2806
|
+
ref = $(if ($null -ne $p2.re) { $p2.re.ref } else { '' })
|
|
2807
|
+
action = $p2.action
|
|
2808
|
+
status = 'not_executed'
|
|
2809
|
+
ms = 0
|
|
2810
|
+
before = ''
|
|
2811
|
+
after = ''
|
|
2812
|
+
performed = $false
|
|
2813
|
+
detail = 'not executed: an earlier step failed or the run was cancelled'
|
|
2814
|
+
}) | Out-Null
|
|
2815
|
+
}
|
|
2816
|
+
}
|
|
2817
|
+
# The Node side reads "no stop" as stoppedAt === null (see tools.js allPassed check), so a
|
|
2818
|
+
# sentinel of -1 here would be mistaken for a stop at step -1 and would suppress the recipe
|
|
2819
|
+
# save on an otherwise clean batch. Emit the real index, or an explicit JSON null (DBNull, so
|
|
2820
|
+
# the generic serializer keeps the key instead of dropping it) when every step passed.
|
|
2821
|
+
$stoppedOut = if ($stoppedAt -lt 0) { [System.DBNull]::Value } else { $stoppedAt }
|
|
2822
|
+
# "after" half of the window diff: every top-level hwnd that did not exist before phase 2 is
|
|
2823
|
+
# reported with its title/class/pid. Empty when nothing appeared — the key stays ABSENT then, so
|
|
2824
|
+
# consumers can distinguish "no diff" from an empty diff without extra contract.
|
|
2825
|
+
$newWindows = @()
|
|
2826
|
+
foreach ($w in (RootWindows)) {
|
|
2827
|
+
$h = 0
|
|
2828
|
+
$cpW = $null
|
|
2829
|
+
try { $cpW = $w.Current; $h = [int]$cpW.NativeWindowHandle } catch { continue }
|
|
2830
|
+
if ($h -eq 0) { continue }
|
|
2831
|
+
if ($hwndsBefore.ContainsKey([string]$h)) { continue }
|
|
2832
|
+
if ($indicatorPid -gt 0 -and [int]$cpW.ProcessId -eq [int]$indicatorPid) { continue }
|
|
2833
|
+
$newWindows += [ordered]@{
|
|
2834
|
+
hwnd = $h
|
|
2835
|
+
pid = [int]$cpW.ProcessId
|
|
2836
|
+
title = (TruncStr ([string]$cpW.Name) 120)
|
|
2837
|
+
class = (TruncStr ([string]$cpW.ClassName) 80)
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
$r = [ordered]@{
|
|
2841
|
+
results = $results
|
|
2842
|
+
stoppedAt = $stoppedOut
|
|
2843
|
+
performedCount = $performed
|
|
2844
|
+
revision = $wantRev
|
|
2845
|
+
status = $status
|
|
2846
|
+
steps = $steps.Count
|
|
2847
|
+
batchOk = ($stoppedAt -lt 0)
|
|
2848
|
+
}
|
|
2849
|
+
if ($newWindows.Count -gt 0) { $r['newWindows'] = $newWindows }
|
|
2850
|
+
return $r
|
|
2851
|
+
}
|
|
2852
|
+
|
|
2853
|
+
function Cmd-Wait($A) {
|
|
2854
|
+
$cond = Dict (ArgOf $A 'condition')
|
|
2855
|
+
if ($null -eq $cond) { Err 'missing_arg' 'wait needs a condition' }
|
|
2856
|
+
$timeoutMs = IntArg $A 'timeoutMs' 3000
|
|
2857
|
+
$wid = StrArg $A 'windowId' ''
|
|
2858
|
+
$entry = $null
|
|
2859
|
+
if ($wid -ne '') { $entry = Window-Entry $wid }
|
|
2860
|
+
$type = [string]$cond.Item('type')
|
|
2861
|
+
if ($type -eq 'element_appears' -or $type -eq 'element_gone') {
|
|
2862
|
+
if ($null -eq $entry) {
|
|
2863
|
+
$st = TickNow
|
|
2864
|
+
$left = BudgetLeftMs
|
|
2865
|
+
if ($timeoutMs -gt $left) { $timeoutMs = [int]$left }
|
|
2866
|
+
$deadline = $st + ([Int64]$timeoutMs * 10000)
|
|
2867
|
+
$hitWin = ''
|
|
2868
|
+
while ($true) {
|
|
2869
|
+
$hit = $null
|
|
2870
|
+
foreach ($e in @($script:W.windows.Values)) {
|
|
2871
|
+
$el = Find-ByDescriptor $e (Dict $cond.Item('by'))
|
|
2872
|
+
if ($null -ne $el) { $hit = $e; break }
|
|
2873
|
+
}
|
|
2874
|
+
if ($type -eq 'element_appears') { if ($null -ne $hit) { $hitWin = $hit.id; break } }
|
|
2875
|
+
else { if ($null -eq $hit) { break } else { $hitWin = $hit.id } }
|
|
2876
|
+
if ((TickNow) -ge $deadline) { break }
|
|
2877
|
+
Start-Sleep -Milliseconds 120
|
|
2878
|
+
}
|
|
2879
|
+
$matched = if ($type -eq 'element_appears') { $hitWin -ne '' } else { $hitWin -eq '' }
|
|
2880
|
+
return [ordered]@{ matched = $matched; ms = [Math]::Round((MsFrom $st), 1); type = $type; windowId = $hitWin; scannedWindows = $script:W.windows.Count }
|
|
2881
|
+
}
|
|
2882
|
+
}
|
|
2883
|
+
if ($null -eq $entry) { Err 'missing_arg' 'wait needs windowId for this condition type' }
|
|
2884
|
+
return Wait-Condition $entry $cond $timeoutMs $null $null
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
function Cmd-CaptureScreen($A) {
|
|
2888
|
+
# Native 1:1 by default, same rule as the window capture: a downscaled desktop reads as "the
|
|
2889
|
+
# screen was cut off" and makes the model convert coordinates it could use directly.
|
|
2890
|
+
$maxDim = IntArg $A 'maxDim' 0
|
|
2891
|
+
$st = TickNow
|
|
2892
|
+
if ($null -eq ('Native' -as [type])) { Err 'native_missing' 'the P/Invoke helper did not compile; capture is unavailable' }
|
|
2893
|
+
$cap = [Native]::CaptureScreen($maxDim)
|
|
2894
|
+
$v = Get-VirtScreen
|
|
2895
|
+
$r = [ordered]@{
|
|
2896
|
+
scope = 'screen'
|
|
2897
|
+
method = [string]$cap.method
|
|
2898
|
+
blank = [bool]$cap.blank
|
|
2899
|
+
width = [int]$cap.width
|
|
2900
|
+
height = [int]$cap.height
|
|
2901
|
+
distinct = [int]$cap.distinct
|
|
2902
|
+
pngBytes = 0
|
|
2903
|
+
ms = (MsFrom $st)
|
|
2904
|
+
# Measured, not assumed: the virtual screen origin is negative when a monitor sits left of or
|
|
2905
|
+
# above the primary one, and it is re-read through GetSystemMetrics on every call.
|
|
2906
|
+
screenRect = @{ x = [int]$v.x; y = [int]$v.y; w = [int]$v.w; h = [int]$v.h }
|
|
2907
|
+
}
|
|
2908
|
+
if ($null -ne $cap.png) {
|
|
2909
|
+
$r['pngBytes'] = $cap.png.Length
|
|
2910
|
+
if (BoolArg $A 'inline' $true) { $r['pngBase64'] = [Convert]::ToBase64String($cap.png) }
|
|
2911
|
+
}
|
|
2912
|
+
if ($cap.width -gt 0 -and $cap.height -gt 0) {
|
|
2913
|
+
$r['imageWidth'] = [int]$cap.width
|
|
2914
|
+
$r['imageHeight'] = [int]$cap.height
|
|
2915
|
+
$r['scaleX'] = [Math]::Round([double]$v.w / [double]$cap.width, 4)
|
|
2916
|
+
$r['scaleY'] = [Math]::Round([double]$v.h / [double]$cap.height, 4)
|
|
2917
|
+
$r['coordinateMap'] = ('screenX = ' + [int]$v.x + ' + imgX * ' + [string]$r['scaleX'] + ' ; screenY = ' + [int]$v.y + ' + imgY * ' + [string]$r['scaleY'])
|
|
2918
|
+
}
|
|
2919
|
+
$note = [string]$cap.error
|
|
2920
|
+
if ($cap.blank) { $note += ('desktop capture came back blank (distinct colors=' + [int]$cap.distinct + '); the session may be locked or on a disconnected desktop') }
|
|
2921
|
+
if ($note -ne '') { $r['detail'] = (OneLine $note) }
|
|
2922
|
+
return $r
|
|
2923
|
+
}
|
|
2924
|
+
|
|
2925
|
+
function Cmd-Capture($A) {
|
|
2926
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
2927
|
+
# Native 1:1 by default. A downscaled window capture silently changes what the model can read —
|
|
2928
|
+
# small text turns to mush and the coordinateMap picks up a scale factor — so the honest default
|
|
2929
|
+
# is the window's real pixel size. Callers that want a cheaper preview pass maxDim explicitly.
|
|
2930
|
+
$maxDim = IntArg $A 'maxDim' 0
|
|
2931
|
+
$st = TickNow
|
|
2932
|
+
if ($null -eq ('Native' -as [type])) { Err 'native_missing' 'the P/Invoke helper did not compile; capture is unavailable' }
|
|
2933
|
+
$cap = [Native]::Capture([IntPtr]$entry.hwnd, $maxDim)
|
|
2934
|
+
$r = [ordered]@{
|
|
2935
|
+
windowId = $entry.id
|
|
2936
|
+
method = [string]$cap.method
|
|
2937
|
+
blank = [bool]$cap.blank
|
|
2938
|
+
width = [int]$cap.width
|
|
2939
|
+
height = [int]$cap.height
|
|
2940
|
+
distinct = [int]$cap.distinct
|
|
2941
|
+
isForeground = (Is-ForegroundHwnd $entry.hwnd)
|
|
2942
|
+
pngBytes = 0
|
|
2943
|
+
ms = (MsFrom $st)
|
|
2944
|
+
}
|
|
2945
|
+
if ($null -ne $cap.png) {
|
|
2946
|
+
$r['pngBytes'] = $cap.png.Length
|
|
2947
|
+
if (BoolArg $A 'inline' $true) { $r['pngBase64'] = [Convert]::ToBase64String($cap.png) }
|
|
2948
|
+
}
|
|
2949
|
+
# The PNG is window-relative and downscaled to maxDim, so its pixels are NOT click-space. Expose the
|
|
2950
|
+
# exact image->screen transform (in the same physical space pointer_click consumes) so a vision model
|
|
2951
|
+
# converts mechanically instead of guessing a factor: screenX = windowRect.x + imgX * scaleX.
|
|
2952
|
+
$wr = RectOf (Window-Ae $entry).Current
|
|
2953
|
+
if ($cap.width -gt 0 -and $cap.height -gt 0 -and $wr.w -gt 0 -and $wr.h -gt 0) {
|
|
2954
|
+
$r['windowRect'] = $wr
|
|
2955
|
+
$r['imageWidth'] = [int]$cap.width
|
|
2956
|
+
$r['imageHeight'] = [int]$cap.height
|
|
2957
|
+
$r['scaleX'] = [Math]::Round([double]$wr.w / [double]$cap.width, 4)
|
|
2958
|
+
$r['scaleY'] = [Math]::Round([double]$wr.h / [double]$cap.height, 4)
|
|
2959
|
+
$r['coordinateMap'] = ('screenX = ' + [int]$wr.x + ' + imgX * ' + [string]$r['scaleX'] + ' ; screenY = ' + [int]$wr.y + ' + imgY * ' + [string]$r['scaleY'])
|
|
2960
|
+
}
|
|
2961
|
+
$note = [string]$cap.error
|
|
2962
|
+
if ($cap.blank) { $note += ('capture came back blank (distinct colors=' + [int]$cap.distinct + '); the window is not rendering into the PrintWindow DC') }
|
|
2963
|
+
if ($note -ne '') { $r['detail'] = (OneLine $note) }
|
|
2964
|
+
return $r
|
|
2965
|
+
}
|
|
2966
|
+
|
|
2967
|
+
function Resolve-OcrExe {
|
|
2968
|
+
# The compiled WinRT shim. Shipped in worker\bin (7 KB, no model: Windows.Media.Ocr is an OS
|
|
2969
|
+
# component). DSH_OCR_EXE overrides it for testing. Returns $null when absent so the caller can
|
|
2970
|
+
# fail with a clear reason rather than a raw process error.
|
|
2971
|
+
$p = $env:DSH_OCR_EXE
|
|
2972
|
+
if ([string]::IsNullOrEmpty($p)) { $p = Join-Path $PSScriptRoot 'bin\ocr.exe' }
|
|
2973
|
+
if (-not (Test-Path -LiteralPath $p)) { return $null }
|
|
2974
|
+
return (Resolve-Path -LiteralPath $p).Path
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
function Invoke-OcrExe($exe, $pngPath) {
|
|
2978
|
+
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
2979
|
+
$psi.FileName = $exe
|
|
2980
|
+
$psi.Arguments = '"' + $pngPath + '"'
|
|
2981
|
+
$psi.UseShellExecute = $false
|
|
2982
|
+
$psi.RedirectStandardOutput = $true
|
|
2983
|
+
$psi.RedirectStandardError = $true
|
|
2984
|
+
$psi.CreateNoWindow = $true
|
|
2985
|
+
$psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8
|
|
2986
|
+
$proc = [System.Diagnostics.Process]::Start($psi)
|
|
2987
|
+
$stdout = $proc.StandardOutput.ReadToEnd()
|
|
2988
|
+
$stderr = $proc.StandardError.ReadToEnd()
|
|
2989
|
+
$proc.WaitForExit()
|
|
2990
|
+
return @{ code = $proc.ExitCode; out = $stdout; err = $stderr }
|
|
2991
|
+
}
|
|
2992
|
+
|
|
2993
|
+
function Cmd-Ocr($A) {
|
|
2994
|
+
$st = TickNow
|
|
2995
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
2996
|
+
$maxDim = IntArg $A 'maxDim' 1400
|
|
2997
|
+
$exe = Resolve-OcrExe
|
|
2998
|
+
if ($null -eq $exe) { Err 'ocr_unavailable' 'ocr.exe not found (place it in worker\bin or set DSH_OCR_EXE)' }
|
|
2999
|
+
$ae = Window-Ae $entry
|
|
3000
|
+
$wr = RectOf $ae.Current
|
|
3001
|
+
if ($wr.w -le 0 -or $wr.h -le 0) { Err 'no_rect' 'window has no usable rect (minimized?); activate/restore it first' }
|
|
3002
|
+
$cap = [Native]::Capture([IntPtr]$entry.hwnd, $maxDim)
|
|
3003
|
+
if ($null -eq $cap.png -or [bool]$cap.blank) {
|
|
3004
|
+
Err 'capture_blank' ('window did not render into the capture (method=' + [string]$cap.method + ' distinct=' + [int]$cap.distinct + ')')
|
|
3005
|
+
}
|
|
3006
|
+
$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('yuping-ocr-' + $PID + '-' + (Get-Random) + '.png')
|
|
3007
|
+
[System.IO.File]::WriteAllBytes($tmp, $cap.png)
|
|
3008
|
+
$imgW = [int]$cap.width; $imgH = [int]$cap.height
|
|
3009
|
+
$r = Invoke-OcrExe $exe $tmp
|
|
3010
|
+
try { Remove-Item -LiteralPath $tmp -ErrorAction SilentlyContinue } catch { }
|
|
3011
|
+
if ($r.code -ne 0) { Err 'ocr_failed' ('ocr.exe exit ' + [string]$r.code + ': ' + (TruncStr ([string]($r.err + $r.out)) 200)) }
|
|
3012
|
+
$parsed = $null
|
|
3013
|
+
try { $parsed = $r.out | ConvertFrom-Json } catch { Err 'ocr_parse' ('bad ocr json: ' + (TruncStr ([string]$r.out) 200)) }
|
|
3014
|
+
if ($null -eq $parsed -or -not [bool]$parsed.ok) { Err 'ocr_error' (TruncStr ([string]$parsed.error) 200) }
|
|
3015
|
+
# The capture is the whole window at its physical size (possibly downscaled to maxDim), so image
|
|
3016
|
+
# pixels map onto the window rect by a per-axis scale; word centers become clickable screen points.
|
|
3017
|
+
$sx = [double]$wr.w / [double]$imgW
|
|
3018
|
+
$sy = [double]$wr.h / [double]$imgH
|
|
3019
|
+
$words = @()
|
|
3020
|
+
foreach ($wd in $parsed.words) {
|
|
3021
|
+
$words += [ordered]@{
|
|
3022
|
+
text = [string]$wd.t
|
|
3023
|
+
cx = [int]([double]$wr.x + (([double]$wd.x + [double]$wd.w / 2.0) * $sx))
|
|
3024
|
+
cy = [int]([double]$wr.y + (([double]$wd.y + [double]$wd.h / 2.0) * $sy))
|
|
3025
|
+
rect = [ordered]@{
|
|
3026
|
+
x = [int]([double]$wr.x + [double]$wd.x * $sx)
|
|
3027
|
+
y = [int]([double]$wr.y + [double]$wd.y * $sy)
|
|
3028
|
+
w = [int]([double]$wd.w * $sx)
|
|
3029
|
+
h = [int]([double]$wd.h * $sy)
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
}
|
|
3033
|
+
return [ordered]@{
|
|
3034
|
+
windowId = $entry.id
|
|
3035
|
+
engine = 'windows-media-ocr'
|
|
3036
|
+
imageWidth = $imgW
|
|
3037
|
+
imageHeight = $imgH
|
|
3038
|
+
windowRect = $wr
|
|
3039
|
+
scaleX = [Math]::Round($sx, 4)
|
|
3040
|
+
scaleY = [Math]::Round($sy, 4)
|
|
3041
|
+
text = [string]$parsed.text
|
|
3042
|
+
count = $words.Count
|
|
3043
|
+
words = $words
|
|
3044
|
+
ms = (MsFrom $st)
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
|
|
3048
|
+
function Cmd-FindText($A) {
|
|
3049
|
+
$st = TickNow
|
|
3050
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
3051
|
+
$text = StrArg $A 'text' ''
|
|
3052
|
+
if ($text -eq '') { Err 'missing_arg' 'find_text needs text' }
|
|
3053
|
+
$exact = BoolArg $A 'exact' $false
|
|
3054
|
+
$max = IntArg $A 'max' 60
|
|
3055
|
+
$ae = Window-Ae $entry
|
|
3056
|
+
if ($null -eq $ae) { Err 'window_not_found' ("window " + $entry.id + " is gone") }
|
|
3057
|
+
# ---- cached scan: Activate a PRIVATE request (same property/pattern shape as the snapshot
|
|
3058
|
+
# request, incl. pattern availability + RuntimeId), so FindAll returns elements that already
|
|
3059
|
+
# carry their cache and the per-element loop reads $c.Cached with no per-node round-trips
|
|
3060
|
+
# (measured ~160 ms for a ~500-element tree vs ~650 ms of live Current reads). Deliberately a
|
|
3061
|
+
# SEPARATE request object (Find-CacheRequest), never the shared $script:snapReq. Mode stays Full,
|
|
3062
|
+
# so refs minted from these elements are still live elements and every later pattern call on
|
|
3063
|
+
# them works. The scope is popped before the element loop: the cache stays materialised on the
|
|
3064
|
+
# elements themselves. Any failure here falls back to the historical live scan below.
|
|
3065
|
+
$all = @()
|
|
3066
|
+
$usedCached = $false
|
|
3067
|
+
$freq = Find-CacheRequest
|
|
3068
|
+
if ($null -ne $freq) {
|
|
3069
|
+
try {
|
|
3070
|
+
# [void] on both Activate and Pop is load-bearing: Activate returns a CacheRequestActivation
|
|
3071
|
+
# marker, and a bare expression inside a function joins the function's OUTPUT STREAM — the
|
|
3072
|
+
# reply would then be [result, activation] and every consumer would read garbage.
|
|
3073
|
+
[void]$freq.Activate()
|
|
3074
|
+
try {
|
|
3075
|
+
$all = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, [System.Windows.Automation.Condition]::TrueCondition))
|
|
3076
|
+
# One probe decides the batch: an element without a usable cache throws on .Cached, and
|
|
3077
|
+
# then everything is re-enumerated through the live path below.
|
|
3078
|
+
if ($all.Count -gt 0) { $null = $all[0].Cached; $usedCached = $true }
|
|
3079
|
+
} finally {
|
|
3080
|
+
try { [void]$freq.Pop() } catch { }
|
|
3081
|
+
}
|
|
3082
|
+
} catch { $usedCached = $false }
|
|
3083
|
+
}
|
|
3084
|
+
if (-not $usedCached) {
|
|
3085
|
+
try { $all = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, [System.Windows.Automation.Condition]::TrueCondition)) } catch { Err 'uia_error' ('FindAll threw: ' + $_.Exception.Message) }
|
|
3086
|
+
}
|
|
3087
|
+
$out = New-Object System.Collections.Generic.List[object]
|
|
3088
|
+
# How many times each (name, controlType) pair has been emitted so far. A `by` descriptor is
|
|
3089
|
+
# resolved later by FindFirst, which always returns the first match — so without this, a window
|
|
3090
|
+
# with three "复制" buttons can only ever reach the first one and the model's second/third pick
|
|
3091
|
+
# silently lands on the wrong control ("点不准" with perfect coordinates). Carrying `nth` in the
|
|
3092
|
+
# descriptor makes each match individually addressable.
|
|
3093
|
+
$seen = @{}
|
|
3094
|
+
$matchedTotal = 0
|
|
3095
|
+
$truncated = $false
|
|
3096
|
+
foreach ($c in $all) {
|
|
3097
|
+
# Same per-element guard as before, but a timeout no longer DISCARDS the command: every hit
|
|
3098
|
+
# already collected is still true, so the partial list returns marked truncated (the old
|
|
3099
|
+
# deadline_exceeded error threw away all of it — the model paid for a full scan and got
|
|
3100
|
+
# nothing back).
|
|
3101
|
+
if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) { $truncated = $true; break }
|
|
3102
|
+
try { $cp = if ($usedCached) { $c.Cached } else { $c.Current } } catch { continue }
|
|
3103
|
+
$n = [string]$cp.Name
|
|
3104
|
+
$ctn = ''
|
|
3105
|
+
if ($n -eq '') {
|
|
3106
|
+
# A nameless Edit/Document/Text can still carry the text the caller is after (a label-less
|
|
3107
|
+
# input box's content lives in its value, not its name). This used to read $cp.Value — a
|
|
3108
|
+
# property AutomationElementInformation does not HAVE — so it silently returned '' forever
|
|
3109
|
+
# and the documented value search never fired. Read the value from ValuePattern, for that
|
|
3110
|
+
# narrow type set only, so the extra pattern call stays rare on container-heavy trees.
|
|
3111
|
+
try { $ctn = ControlTypeName $cp.ControlType } catch { $ctn = '' }
|
|
3112
|
+
if ($ctn -eq 'Edit' -or $ctn -eq 'Document' -or $ctn -eq 'Text') {
|
|
3113
|
+
try {
|
|
3114
|
+
$vp = $c.GetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern)
|
|
3115
|
+
if ($null -ne $vp) { $n = [string]$vp.Current.Value }
|
|
3116
|
+
} catch { $n = '' }
|
|
3117
|
+
}
|
|
3118
|
+
}
|
|
3119
|
+
if ($n.Length -eq 0) { continue }
|
|
3120
|
+
# Literal, case-insensitive containment. -like treated * ? [ ] in the caller's text as
|
|
3121
|
+
# wildcards, so searching for a name containing brackets matched unrelated controls.
|
|
3122
|
+
$m = if ($exact) { $n.Equals($text, [StringComparison]::OrdinalIgnoreCase) } else { $n.IndexOf($text, [StringComparison]::OrdinalIgnoreCase) -ge 0 }
|
|
3123
|
+
if (-not $m) { continue }
|
|
3124
|
+
# The honest hit total, INCLUDING everything past max: the scan already walked the tree, so
|
|
3125
|
+
# counting the tail costs one Name read per remaining element and turns the silent drop into
|
|
3126
|
+
# a reported truncation (matchedTotal > count ⇔ the reply must say so).
|
|
3127
|
+
$matchedTotal += 1
|
|
3128
|
+
if ($out.Count -ge $max) { $truncated = $true; continue }
|
|
3129
|
+
$rc = RectOf $cp
|
|
3130
|
+
if ($ctn -eq '') { $ctn = ControlTypeName $cp.ControlType }
|
|
3131
|
+
$key = $ctn + '#' + $n
|
|
3132
|
+
$nth = 1
|
|
3133
|
+
if ($seen.ContainsKey($key)) { $nth = $seen[$key] + 1 }
|
|
3134
|
+
$seen[$key] = $nth
|
|
3135
|
+
# The descriptor must be able to RESOLVE later, so it is built from the real identity, never
|
|
3136
|
+
# from the display text: a name cut at 160 chars could never satisfy an exact match, and a
|
|
3137
|
+
# non-empty AutomationId is a stable anchor when the visible label changes or repeats.
|
|
3138
|
+
$selName = $n
|
|
3139
|
+
$pats = @()
|
|
3140
|
+
try { $pats = PatternsOf $c } catch { $pats = @() }
|
|
3141
|
+
$node = [ordered]@{
|
|
3142
|
+
controlType = $ctn
|
|
3143
|
+
name = (TruncStr $n 160)
|
|
3144
|
+
className = [string]$cp.ClassName
|
|
3145
|
+
automationId = [string]$cp.AutomationId
|
|
3146
|
+
patterns = @($pats)
|
|
3147
|
+
enabled = [bool]$cp.IsEnabled
|
|
3148
|
+
isOffscreen = [bool]$cp.IsOffscreen
|
|
3149
|
+
rect = $rc
|
|
3150
|
+
depth = 0
|
|
3151
|
+
}
|
|
3152
|
+
# Same convention the snapshot uses: when the node's 160-cut display name differs from the
|
|
3153
|
+
# real one, carry the untruncated name so a recipe can re-resolve it strictly.
|
|
3154
|
+
if ($n.Length -gt 160) { $node['fullName'] = $n }
|
|
3155
|
+
$byDesc = @{ controlType = $ctn }
|
|
3156
|
+
if ($selName.Length -gt 200) {
|
|
3157
|
+
$byDesc['name'] = $selName.Substring(0, 200)
|
|
3158
|
+
$byDesc['nameExact'] = $false
|
|
3159
|
+
} else {
|
|
3160
|
+
$byDesc['name'] = $selName
|
|
3161
|
+
}
|
|
3162
|
+
if ([string]$node.automationId -ne '') { $byDesc['automationId'] = [string]$node.automationId }
|
|
3163
|
+
if ($nth -gt 1) { $byDesc['nth'] = $nth }
|
|
3164
|
+
# Issue a ref for every hit. find_text used to return only coordinates and a by-descriptor, so
|
|
3165
|
+
# computer_act (which takes a ref and nothing else) could not be driven from a search result —
|
|
3166
|
+
# the model had to fall back to a physical computer_click, moving the real cursor for what
|
|
3167
|
+
# should have been a background action. Refs cost one table entry each and make the two tools
|
|
3168
|
+
# compose.
|
|
3169
|
+
$refRec = $null
|
|
3170
|
+
try { $refRec = New-Ref $entry $c $cp $node } catch { $refRec = $null }
|
|
3171
|
+
# The item reads back what the node already holds — className/automationId/enabled/isOffscreen
|
|
3172
|
+
# were each read TWICE before (once for $node, once for $item), one avoidable round-trip each.
|
|
3173
|
+
$item = [ordered]@{
|
|
3174
|
+
name = $node.name
|
|
3175
|
+
controlType = $ctn
|
|
3176
|
+
className = $node.className
|
|
3177
|
+
automationId = $node.automationId
|
|
3178
|
+
rect = $rc
|
|
3179
|
+
enabled = $node.enabled
|
|
3180
|
+
isOffscreen = $node.isOffscreen
|
|
3181
|
+
patterns = $node.patterns
|
|
3182
|
+
ref = $(if ($null -ne $refRec) { $refRec.ref } else { $null })
|
|
3183
|
+
center = @{ x = ($rc.x + [int]($rc.w / 2)); y = ($rc.y + [int]($rc.h / 2)) }
|
|
3184
|
+
# nth is only meaningful once a duplicate exists; a unique hit keeps the old 1-field shape
|
|
3185
|
+
# and nth=1 so recipes saved before this change still replay against the same element.
|
|
3186
|
+
nth = $nth
|
|
3187
|
+
by = $byDesc
|
|
3188
|
+
}
|
|
3189
|
+
$out.Add($item) | Out-Null
|
|
3190
|
+
}
|
|
3191
|
+
$r = [ordered]@{ windowId = $entry.id; revision = $entry.revision; text = $text; matches = $out; count = $out.Count; scanned = $all.Count; matchedTotal = $matchedTotal; truncated = [bool]$truncated; ms = (MsFrom $st) }
|
|
3192
|
+
# Position metadata, same contract as snapshot's: advisory fields, omitted on failure.
|
|
3193
|
+
try {
|
|
3194
|
+
$obsHeader = Window-ObservationHeader $entry
|
|
3195
|
+
if ($null -ne $obsHeader) {
|
|
3196
|
+
foreach ($k in @($obsHeader.Keys)) { $r[$k] = $obsHeader[$k] }
|
|
3197
|
+
}
|
|
3198
|
+
} catch { }
|
|
3199
|
+
return $r
|
|
3200
|
+
}
|
|
3201
|
+
|
|
3202
|
+
function Resolve-LaunchTarget($app) {
|
|
3203
|
+
$info = @{ path = ''; via = '' }
|
|
3204
|
+
if ($null -eq $app -or [string]$app -eq '') { Err 'missing_arg' 'launch needs app, uri or msAppAlias' }
|
|
3205
|
+
$app = [string]$app
|
|
3206
|
+
if ($app -match '[\\/]' -and (Test-Path -LiteralPath $app)) {
|
|
3207
|
+
$info.path = (Resolve-Path -LiteralPath $app).Path
|
|
3208
|
+
$info.via = 'literal-path'
|
|
3209
|
+
return $info
|
|
3210
|
+
}
|
|
3211
|
+
$names = @($app)
|
|
3212
|
+
if ($app -notmatch '\.(exe|com)$') { $names = @(($app + '.exe'), $app) }
|
|
3213
|
+
$win = $env:SystemRoot
|
|
3214
|
+
foreach ($n in $names) {
|
|
3215
|
+
foreach ($dir in @(($win + '\System32'), ($win + '\SysWOW64'), $win)) {
|
|
3216
|
+
$f = Join-Path $dir $n
|
|
3217
|
+
if (Test-Path -LiteralPath $f -PathType Leaf) { $info.path = $f; $info.via = 'windows-dir'; return $info }
|
|
3218
|
+
}
|
|
3219
|
+
$wa = Join-Path $env:LOCALAPPDATA ('Microsoft\WindowsApps\' + $n)
|
|
3220
|
+
if (Test-Path -LiteralPath $wa) { $info.path = $wa; $info.via = 'app-execution-alias'; return $info }
|
|
3221
|
+
foreach ($hive in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths')) {
|
|
3222
|
+
$key = $hive + '\' + $n
|
|
3223
|
+
if (Test-Path -LiteralPath $key) {
|
|
3224
|
+
$v = (Get-ItemProperty -LiteralPath $key -ErrorAction SilentlyContinue).'(default)'
|
|
3225
|
+
if ($null -ne $v -and [string]$v -ne '' -and (Test-Path -LiteralPath ([string]$v))) { $info.path = [string]$v; $info.via = 'app-paths-registry'; return $info }
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
}
|
|
3229
|
+
# PATH, but only real Windows executables. Git's usr/bin ships POSIX scripts named
|
|
3230
|
+
# like windows tools; ShellExecute on those opens an editor instead of the tool.
|
|
3231
|
+
foreach ($n in $names) {
|
|
3232
|
+
foreach ($dir in ($env:PATH -split ';')) {
|
|
3233
|
+
if ($dir -eq '') { continue }
|
|
3234
|
+
if ($dir -match '(?i)\\git\\|\\usr\\bin|\\bin\\sh|\\msys|\\cygwin|\\busybox') { continue }
|
|
3235
|
+
$f = Join-Path $dir $n
|
|
3236
|
+
if (Test-Path -LiteralPath $f -PathType Leaf) {
|
|
3237
|
+
$it = Get-Item -LiteralPath $f
|
|
3238
|
+
if ($it.Extension -eq '.exe' -or $it.Extension -eq '.com') { $info.path = $it.FullName; $info.via = 'path'; return $info }
|
|
3239
|
+
}
|
|
3240
|
+
}
|
|
3241
|
+
}
|
|
3242
|
+
$roots = @(($env:APPDATA + '\Microsoft\Windows\Start Menu\Programs'), ($env:ProgramData + '\Microsoft\Windows\Start Menu\Programs')) | Where-Object { Test-Path -LiteralPath $_ }
|
|
3243
|
+
foreach ($n in $names) {
|
|
3244
|
+
$stem = ($n -replace '\.(exe|com)$', '')
|
|
3245
|
+
$lnk = Get-ChildItem -LiteralPath $roots[0] -Recurse -Filter '*.lnk' -ErrorAction SilentlyContinue | Where-Object { $_.BaseName -replace ' & ', '' -match ('(?i)^' + [regex]::Escape($stem) + '$') } | Select-Object -First 1
|
|
3246
|
+
if ($null -eq $lnk -and $roots.Count -gt 1) {
|
|
3247
|
+
$lnk = Get-ChildItem -LiteralPath $roots[1] -Recurse -Filter '*.lnk' -ErrorAction SilentlyContinue | Where-Object { $_.BaseName -replace ' & ', '' -match ('(?i)^' + [regex]::Escape($stem) + '$') } | Select-Object -First 1
|
|
3248
|
+
}
|
|
3249
|
+
if ($null -ne $lnk) { $info.path = $lnk.FullName; $info.via = 'start-menu'; return $info }
|
|
3250
|
+
}
|
|
3251
|
+
Err 'launch_failed' ("cannot resolve '" + $app + "' through windows-dir, app-execution-alias, app-paths, PATH or start-menu")
|
|
3252
|
+
}
|
|
3253
|
+
|
|
3254
|
+
function Cmd-Launch($A) {
|
|
3255
|
+
$app = StrArg $A 'app' ''
|
|
3256
|
+
$alias = StrArg $A 'msAppAlias' ''
|
|
3257
|
+
$uri = StrArg $A 'uri' ''
|
|
3258
|
+
$timeoutMs = IntArg $A 'timeoutMs' 8000
|
|
3259
|
+
$argList = ListOf (ArgOf $A 'args')
|
|
3260
|
+
$titleFilter = StrArg $A 'title' ''
|
|
3261
|
+
$classFilter = StrArg $A 'class' ''
|
|
3262
|
+
if ($app -eq '' -and $alias -eq '' -and $uri -eq '') { Err 'missing_arg' 'launch needs app, msAppAlias or uri' }
|
|
3263
|
+
# app accepts protocol URIs too (for example microsoft.windows.camera:). A drive
|
|
3264
|
+
# prefix, including drive-relative C:foo, is a Windows path rather than a URI scheme.
|
|
3265
|
+
if ($uri -eq '' -and $alias -eq '' -and $app -match '^[A-Za-z][A-Za-z0-9+.-]*:' -and $app -notmatch '^[A-Za-z]:') { $uri = $app }
|
|
3266
|
+
$exe = ''; $via = ''
|
|
3267
|
+
$st = TickNow
|
|
3268
|
+
if ($uri -ne '') { $exe = $uri; $via = 'uri-shell' }
|
|
3269
|
+
elseif ($alias -ne '') { $r = Resolve-LaunchTarget $alias; $exe = $r.path; $via = 'ms-app-alias:' + $r.via }
|
|
3270
|
+
else { $r = Resolve-LaunchTarget $app; $exe = $r.path; $via = $r.via }
|
|
3271
|
+
$argline = ''
|
|
3272
|
+
foreach ($a in $argList) {
|
|
3273
|
+
$sa = [string]$a
|
|
3274
|
+
if ($sa -match '[\s"]') { $argline += ' "' + $sa.Replace('"', '\"') + '"' } else { $argline += ' ' + $sa }
|
|
3275
|
+
}
|
|
3276
|
+
$argline = $argline.Trim()
|
|
3277
|
+
$beforePids = @{}
|
|
3278
|
+
foreach ($pr in [System.Diagnostics.Process]::GetProcesses()) { try { $beforePids[[string]$pr.Id] = 1 } catch { } }
|
|
3279
|
+
$beforeHwnds = @{}
|
|
3280
|
+
$beforeTitle = @{}
|
|
3281
|
+
foreach ($w in (RootWindows)) {
|
|
3282
|
+
$cp = $null
|
|
3283
|
+
try { $cp = $w.Current; $bh = [int]$cp.NativeWindowHandle } catch { continue }
|
|
3284
|
+
if ($bh -eq 0) { continue }
|
|
3285
|
+
$beforeHwnds[[string]$bh] = 1
|
|
3286
|
+
$beforeTitle[[string]$bh] = ([string]$cp.Name).ToLowerInvariant()
|
|
3287
|
+
}
|
|
3288
|
+
# Optional title/appName hint. On Windows 11 `notepad` is a store alias and the real
|
|
3289
|
+
# editor is a SINGLE process that owns every open document: launching a file folds it
|
|
3290
|
+
# into a window that already existed, so neither a new pid nor a new hwnd appears -- the
|
|
3291
|
+
# only observable event is that window's TITLE changing to mention our file. Deriving the
|
|
3292
|
+
# hint from the file argument's basename (never from the app name) is what lets us resolve
|
|
3293
|
+
# our own document without ever matching a foreign document (e.g. CARVE-*.md) in the same
|
|
3294
|
+
# process. An explicit title/appName always wins.
|
|
3295
|
+
$hint = ''
|
|
3296
|
+
foreach ($tok in @($titleFilter)) {
|
|
3297
|
+
$t = [string]$tok
|
|
3298
|
+
if ($t -ne '') { $hint = $t.ToLowerInvariant(); break }
|
|
3299
|
+
}
|
|
3300
|
+
if ($hint -eq '') {
|
|
3301
|
+
foreach ($a in $argList) {
|
|
3302
|
+
$sa = [string]$a
|
|
3303
|
+
if ($sa -match '[\\/]' -or $sa -match '\.[A-Za-z0-9]{1,8}$') {
|
|
3304
|
+
$base = ($sa -replace '[\\/]+$', '')
|
|
3305
|
+
$base = $base -replace '^.*[\\/]', ''
|
|
3306
|
+
$base = $base -replace '\.[A-Za-z0-9]{1,8}$', ''
|
|
3307
|
+
if ($base.Length -ge 3) { $hint = $base.ToLowerInvariant(); break }
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
}
|
|
3311
|
+
$launchedPid = 0
|
|
3312
|
+
try {
|
|
3313
|
+
$pi = New-Object System.Diagnostics.ProcessStartInfo
|
|
3314
|
+
$pi.FileName = $exe
|
|
3315
|
+
$pi.Arguments = $argline
|
|
3316
|
+
$pi.UseShellExecute = $true
|
|
3317
|
+
$cwd = StrArg $A 'cwd' ''
|
|
3318
|
+
if ($cwd -ne '') { $pi.WorkingDirectory = $cwd }
|
|
3319
|
+
$proc = [System.Diagnostics.Process]::Start($pi)
|
|
3320
|
+
if ($null -ne $proc) { $launchedPid = $proc.Id }
|
|
3321
|
+
} catch {
|
|
3322
|
+
Err 'launch_failed' ("Process.Start('" + $exe + "') threw: " + $_.Exception.Message)
|
|
3323
|
+
}
|
|
3324
|
+
$left = BudgetLeftMs
|
|
3325
|
+
$budget = $timeoutMs
|
|
3326
|
+
if ($budget -gt $left) { $budget = [int]$left }
|
|
3327
|
+
if ($budget -lt 200) { $budget = 200 }
|
|
3328
|
+
$deadline = (TickNow) + ([Int64]$budget * 10000)
|
|
3329
|
+
$foundEntry = $null
|
|
3330
|
+
$matchedBy = ''
|
|
3331
|
+
$foundPidNew = $false
|
|
3332
|
+
$fallbackEntry = $null
|
|
3333
|
+
$fallbackBy = ''
|
|
3334
|
+
$fallbackPidNew = $false
|
|
3335
|
+
while ($true) {
|
|
3336
|
+
Test-Deadline 'launch'
|
|
3337
|
+
foreach ($w in (RootWindows)) {
|
|
3338
|
+
$hwnd = 0; $cp = $null
|
|
3339
|
+
try { $cp = $w.Current; $hwnd = [int]$cp.NativeWindowHandle } catch { continue }
|
|
3340
|
+
if ($hwnd -eq 0) { continue }
|
|
3341
|
+
$hk = [string]$hwnd
|
|
3342
|
+
$isNew = -not $beforeHwnds.ContainsKey($hk)
|
|
3343
|
+
$p = [int]$cp.ProcessId
|
|
3344
|
+
$isPidNew = ($launchedPid -ne 0 -and $p -eq $launchedPid) -or (-not $beforePids.ContainsKey([string]$p))
|
|
3345
|
+
$tNow = ([string]$cp.Name).ToLowerInvariant()
|
|
3346
|
+
$titleChanged = ($beforeTitle.ContainsKey($hk) -and ($beforeTitle[$hk] -ne $tNow))
|
|
3347
|
+
$hintHit = ($hint -ne '' -and $tNow.Contains($hint))
|
|
3348
|
+
# A STRONG candidate is a top-level window that appeared after the start timestamp
|
|
3349
|
+
# (new hwnd or new owner pid -- the store-alias handoff) OR the window whose title
|
|
3350
|
+
# changed to mention our file after the start timestamp (Win11 single-process tab reuse).
|
|
3351
|
+
# A WEAK candidate is a visible top-level window that already carries our hint; it is only
|
|
3352
|
+
# used after the full budget, so a genuinely new window still wins over a stale same-named one.
|
|
3353
|
+
$strong = ($isNew -or $isPidNew) -or ($titleChanged -and $hintHit)
|
|
3354
|
+
$weak = ($hintHit -and -not $isNew -and -not $isPidNew -and -not $titleChanged)
|
|
3355
|
+
if (-not $strong -and -not $weak) { continue }
|
|
3356
|
+
# When we have a discriminator hint, even a new window must belong to it -- that is what
|
|
3357
|
+
# keeps an unrelated popup (or another document in the same process) from being grabbed.
|
|
3358
|
+
if ($hint -ne '' -and -not $hintHit) { continue }
|
|
3359
|
+
$rc = RectOf $cp
|
|
3360
|
+
$iconic = $false
|
|
3361
|
+
try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
|
|
3362
|
+
if (($rc.w -lt 40 -or $rc.h -lt 40) -and -not $iconic) { continue }
|
|
3363
|
+
if ($titleFilter -ne '' -and ([string]$tNow).IndexOf($titleFilter, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
|
|
3364
|
+
if ($classFilter -ne '' -and ([string]$cp.ClassName).IndexOf($classFilter, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
|
|
3365
|
+
$e = Ensure-Window $hwnd $w
|
|
3366
|
+
if ($null -eq $e) { continue }
|
|
3367
|
+
if ($strong) {
|
|
3368
|
+
$foundEntry = $e
|
|
3369
|
+
if ($p -eq $launchedPid) { $matchedBy = 'launched-pid' }
|
|
3370
|
+
elseif ($isPidNew -and -not $isNew) { $matchedBy = 'new-pid-handoff' }
|
|
3371
|
+
elseif ($isNew) { $matchedBy = 'new-hwnd' }
|
|
3372
|
+
else { $matchedBy = 'title-change-handoff' }
|
|
3373
|
+
$foundPidNew = $isPidNew
|
|
3374
|
+
break
|
|
3375
|
+
} elseif ($null -eq $fallbackEntry) {
|
|
3376
|
+
$fallbackEntry = $e; $fallbackBy = 'title-hint-reuse'; $fallbackPidNew = $isPidNew
|
|
3377
|
+
}
|
|
3378
|
+
}
|
|
3379
|
+
if ($null -ne $foundEntry) { break }
|
|
3380
|
+
if ((TickNow) -ge $deadline) { break }
|
|
3381
|
+
Start-Sleep -Milliseconds 150
|
|
3382
|
+
}
|
|
3383
|
+
if ($null -eq $foundEntry -and $null -ne $fallbackEntry) {
|
|
3384
|
+
$foundEntry = $fallbackEntry; $matchedBy = $fallbackBy; $foundPidNew = $fallbackPidNew
|
|
3385
|
+
}
|
|
3386
|
+
if ($null -eq $foundEntry) {
|
|
3387
|
+
$script:W.stats.refused += 1
|
|
3388
|
+
Err 'window_not_found' ("launched " + $exe + " (pid " + $launchedPid + ") but no matching new window appeared within " + $budget + 'ms')
|
|
3389
|
+
}
|
|
3390
|
+
$ae = Window-Ae $foundEntry
|
|
3391
|
+
$cp2 = $ae.Current
|
|
3392
|
+
# The plugin may only claim ownership of a window it actually created. When the owning
|
|
3393
|
+
# process already existed before this launch (the Win11 single-process hand-off), that same
|
|
3394
|
+
# process also hosts the user's other documents, so returning its pid would let a later
|
|
3395
|
+
# policy check treat those documents as ours and close them. In that case report the
|
|
3396
|
+
# launcher pid instead -- disjoint from the window owner -- so policy keeps treating the
|
|
3397
|
+
# window as foreign and it must be closed explicitly. Only a brand-new owner pid is claimed.
|
|
3398
|
+
$ownerPid = [int]$foundEntry.pid
|
|
3399
|
+
$claimPid = if ($foundPidNew) { $ownerPid } else { $launchedPid }
|
|
3400
|
+
return [ordered]@{
|
|
3401
|
+
pid = $claimPid
|
|
3402
|
+
ownerPid = $ownerPid
|
|
3403
|
+
windowId = $foundEntry.id
|
|
3404
|
+
title = (TruncStr ([string]$cp2.Name) 200)
|
|
3405
|
+
class = [string]$cp2.ClassName
|
|
3406
|
+
appearedMs = [Math]::Round((MsFrom $st), 1)
|
|
3407
|
+
launchedPid = $launchedPid
|
|
3408
|
+
matchedBy = $matchedBy
|
|
3409
|
+
exe = $exe
|
|
3410
|
+
via = $via
|
|
3411
|
+
revision = $foundEntry.revision
|
|
3412
|
+
}
|
|
3413
|
+
}
|
|
3414
|
+
|
|
3415
|
+
function Remove-Window($entry) {
|
|
3416
|
+
$refs = @()
|
|
3417
|
+
foreach ($snap in $entry.snapshots) { $refs += $snap.refs }
|
|
3418
|
+
foreach ($rk in $refs) {
|
|
3419
|
+
$r = $script:W.refs.Item($rk)
|
|
3420
|
+
if ($null -ne $r) {
|
|
3421
|
+
# No Marshal.ReleaseComObject here: managed UIA elements are not COM objects
|
|
3422
|
+
# (IsComObject(AutomationElement::RootElement) is False), so the call always threw and an
|
|
3423
|
+
# empty catch swallowed it. GC reclaims the wrappers once the last reference drops.
|
|
3424
|
+
$r.ae = $null
|
|
3425
|
+
$script:W.refs.Remove($rk) | Out-Null
|
|
3426
|
+
}
|
|
3427
|
+
$i = $script:W.refOrder.IndexOf($rk)
|
|
3428
|
+
if ($i -ge 0) { $script:W.refOrder.RemoveAt($i) }
|
|
3429
|
+
$script:W.totalRefs -= 1
|
|
3430
|
+
}
|
|
3431
|
+
$entry.snapshots.Clear()
|
|
3432
|
+
$script:W.winByHwnd.Remove([string]$entry.hwnd) | Out-Null
|
|
3433
|
+
$script:W.windows.Remove($entry.id) | Out-Null
|
|
3434
|
+
}
|
|
3435
|
+
|
|
3436
|
+
function Cmd-CloseWindow($A) {
|
|
3437
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
3438
|
+
$timeoutMs = IntArg $A 'timeoutMs' 3000
|
|
3439
|
+
$method = ''
|
|
3440
|
+
$ae = Window-Ae $entry
|
|
3441
|
+
if ($null -eq $ae) {
|
|
3442
|
+
Remove-Window $entry
|
|
3443
|
+
return [ordered]@{ windowId = $entry.id; closed = $true; method = 'already-gone' }
|
|
3444
|
+
}
|
|
3445
|
+
$wp = GetPattern $ae 'Window'
|
|
3446
|
+
if ($null -ne $wp) {
|
|
3447
|
+
try { $wp.Close(); $method = 'windowpattern' } catch { $method = 'windowpattern-threw' }
|
|
3448
|
+
}
|
|
3449
|
+
if ($method -eq '') {
|
|
3450
|
+
try {
|
|
3451
|
+
[void][Native]::PostMessageW([IntPtr]$entry.hwnd, 0x0010, [IntPtr]0, [IntPtr]0)
|
|
3452
|
+
$method = 'postmessage-wm_close'
|
|
3453
|
+
} catch { Err 'action_failed' ('PostMessage WM_CLOSE threw: ' + $_.Exception.Message) }
|
|
3454
|
+
}
|
|
3455
|
+
$st = TickNow
|
|
3456
|
+
$left = BudgetLeftMs
|
|
3457
|
+
$budget = $timeoutMs
|
|
3458
|
+
if ($budget -gt $left) { $budget = [int]$left }
|
|
3459
|
+
$gone = $false
|
|
3460
|
+
$dialogs = New-Object System.Collections.Generic.List[object]
|
|
3461
|
+
while ((TickNow) -lt ($st + ([Int64]$budget * 10000))) {
|
|
3462
|
+
$alive = $false
|
|
3463
|
+
foreach ($w in (RootWindows)) {
|
|
3464
|
+
$h = 0
|
|
3465
|
+
try { $cp = $w.Current; $h = [int]$cp.NativeWindowHandle } catch { continue }
|
|
3466
|
+
if ($h -eq $entry.hwnd) { $alive = $true; continue }
|
|
3467
|
+
if ([int]$cp.ProcessId -eq $entry.pid) {
|
|
3468
|
+
$cn = [string]$cp.ClassName
|
|
3469
|
+
if ($cn -eq '#32770' -or $cn -like '*Dialog*' -or $cn -like '*XamlWindow*') {
|
|
3470
|
+
$known = $false
|
|
3471
|
+
foreach ($d in $dialogs) { if ($d.hwnd -eq $h) { $known = $true } }
|
|
3472
|
+
if (-not $known) {
|
|
3473
|
+
$de = Ensure-Window $h $w
|
|
3474
|
+
$dialogs.Add([ordered]@{ windowId = $de.id; hwnd = $h; class = $cn; title = (TruncStr ([string]$cp.Name) 120) }) | Out-Null
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
}
|
|
3478
|
+
}
|
|
3479
|
+
if (-not $alive) { $gone = $true; break }
|
|
3480
|
+
Start-Sleep -Milliseconds 120
|
|
3481
|
+
}
|
|
3482
|
+
$r = [ordered]@{
|
|
3483
|
+
windowId = $entry.id
|
|
3484
|
+
method = $method
|
|
3485
|
+
closed = $gone
|
|
3486
|
+
pidStillRunning = $false
|
|
3487
|
+
waitedMs = (MsFrom $st)
|
|
3488
|
+
dialogAppeared = ($dialogs.Count -gt 0)
|
|
3489
|
+
}
|
|
3490
|
+
if (-not $gone) {
|
|
3491
|
+
try { $null = [System.Diagnostics.Process]::GetProcessById($entry.pid); $r['pidStillRunning'] = $true } catch { }
|
|
3492
|
+
if ($dialogs.Count -gt 0) {
|
|
3493
|
+
$r['dialogs'] = $dialogs
|
|
3494
|
+
$r['detail'] = 'a modal dialog is blocking the close; resolve it with find_text + act (the worker never clicks on its own)'
|
|
3495
|
+
} else {
|
|
3496
|
+
$r['detail'] = 'the window ignored the close request'
|
|
3497
|
+
}
|
|
3498
|
+
} else {
|
|
3499
|
+
Remove-Window $entry
|
|
3500
|
+
}
|
|
3501
|
+
return $r
|
|
3502
|
+
}
|
|
3503
|
+
|
|
3504
|
+
function Cmd-Shutdown($A) {
|
|
3505
|
+
return [ordered]@{
|
|
3506
|
+
closed = $true
|
|
3507
|
+
totalRefs = $script:W.totalRefs
|
|
3508
|
+
windows = $script:W.windows.Count
|
|
3509
|
+
workerPid = [int]$PID
|
|
3510
|
+
}
|
|
3511
|
+
}
|
|
3512
|
+
|
|
3513
|
+
# ---------------------------------------------------------------- physical pointer channel
|
|
3514
|
+
# This is the only place in the worker that puts motion on the desktop. It is deliberately
|
|
3515
|
+
# separate from the UIA action channel: `act`/`commit_batch` deliver in the background and must
|
|
3516
|
+
# keep the cursor still, while pointer_* moves the real OS cursor so a human (and the cursor
|
|
3517
|
+
# halo) can see the agent working.
|
|
3518
|
+
#
|
|
3519
|
+
# Mechanics:
|
|
3520
|
+
# * every event is SendInput(INPUT_MOUSE) with MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE |
|
|
3521
|
+
# MOUSEEVENTF_VIRTUALDESK, dx/dy normalised to 0..65535 across the VIRTUAL screen
|
|
3522
|
+
# * SetCursorPos is not used and not even declared: placing the cursor would produce a single
|
|
3523
|
+
# observable position, and the acceptance test measures a trajectory
|
|
3524
|
+
# * coordinates are screen pixels in the same space UIA BoundingRectangle reports (physical,
|
|
3525
|
+
# because the worker made itself per-monitor-v2 aware at startup)
|
|
3526
|
+
# * the default glide is clamp(90 + distance * 0.35, 90, 600) ms, sampled every 8 ms along an
|
|
3527
|
+
# ease-in-out cubic straight line, so the middle steps are the longest and nothing teleports
|
|
3528
|
+
# * a click or a drag re-reads the window under the point (WindowFromPoint) immediately before
|
|
3529
|
+
# it presses and refuses unless the caller's `expect` matches; the overlay windows this plugin
|
|
3530
|
+
# draws are WS_EX_TRANSPARENT, so hit-testing here is already overlay-free
|
|
3531
|
+
$script:ptrVirt = $null
|
|
3532
|
+
$script:ptrPrecision = $false
|
|
3533
|
+
|
|
3534
|
+
function Ensure-Pointer {
|
|
3535
|
+
if (-not $script:nativeLoaded) { Err 'native_unavailable' 'the SendInput helper did not compile (Add-Type failed), the pointer channel is off' }
|
|
3536
|
+
}
|
|
3537
|
+
|
|
3538
|
+
function Get-VirtScreen {
|
|
3539
|
+
if ($null -eq $script:ptrVirt) {
|
|
3540
|
+
$x = 0; $y = 0; $w = 0; $h = 0
|
|
3541
|
+
try {
|
|
3542
|
+
# SM_XVIRTUALSCREEN=76 SM_YVIRTUALSCREEN=77 SM_CXVIRTUALSCREEN=78 SM_CYVIRTUALSCREEN=79
|
|
3543
|
+
$x = [int][Native]::GetSystemMetrics(76); $y = [int][Native]::GetSystemMetrics(77)
|
|
3544
|
+
$w = [int][Native]::GetSystemMetrics(78); $h = [int][Native]::GetSystemMetrics(79)
|
|
3545
|
+
} catch { }
|
|
3546
|
+
if ($w -le 0 -or $h -le 0) {
|
|
3547
|
+
# Fall back to the primary monitor's metrics, never to a guessed resolution: a hardcoded
|
|
3548
|
+
# 1920x1080 makes every coordinate normalisation wrong on any other display, and the error
|
|
3549
|
+
# is silent — SendInput just lands somewhere else.
|
|
3550
|
+
try { $w = [int][Native]::GetSystemMetrics(0); $h = [int][Native]::GetSystemMetrics(1) } catch { }
|
|
3551
|
+
$x = 0; $y = 0
|
|
3552
|
+
}
|
|
3553
|
+
if ($w -le 0 -or $h -le 0) {
|
|
3554
|
+
# Last resort: ask the display stack directly (System.Windows.Forms knows the desktop even
|
|
3555
|
+
# when the user32 metrics call failed). Still measured, never assumed.
|
|
3556
|
+
try {
|
|
3557
|
+
$b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
|
|
3558
|
+
$x = [int]$b.X; $y = [int]$b.Y; $w = [int]$b.Width; $h = [int]$b.Height
|
|
3559
|
+
} catch { }
|
|
3560
|
+
}
|
|
3561
|
+
if ($w -le 0 -or $h -le 0) {
|
|
3562
|
+
Err 'screen_unknown' 'cannot measure the virtual screen: GetSystemMetrics and Screen.Bounds both reported no area'
|
|
3563
|
+
}
|
|
3564
|
+
$script:ptrVirt = @{ x = $x; y = $y; w = $w; h = $h }
|
|
3565
|
+
Log ('pointer virtual screen ' + $x + ',' + $y + ' ' + $w + 'x' + $h + ' inputByteSize=' + [Native]::InputByteSize)
|
|
3566
|
+
}
|
|
3567
|
+
return $script:ptrVirt
|
|
3568
|
+
}
|
|
3569
|
+
|
|
3570
|
+
# winmm timer resolution: without it Thread.Sleep(1) can overshoot to ~15 ms and an 8 ms cadence
|
|
3571
|
+
# quietly becomes a 16 ms one. Raised once for the life of the worker (it is cheap, and the cost
|
|
3572
|
+
# of raising/releasing around every glide is a first sample that lands late).
|
|
3573
|
+
function Begin-Precision {
|
|
3574
|
+
if ($script:ptrPrecision) { return }
|
|
3575
|
+
try { [void][Native]::timeBeginPeriod(1) } catch { }
|
|
3576
|
+
$script:ptrPrecision = $true
|
|
3577
|
+
}
|
|
3578
|
+
|
|
3579
|
+
# Pixel -> 0..65535. The +0.5 puts the event on the pixel centre, which is what makes the last
|
|
3580
|
+
# sample of a glide land on the requested pixel instead of one pixel short of it.
|
|
3581
|
+
function To-Norm($px, $py, $v) {
|
|
3582
|
+
$nx = [int][Math]::Round((([double]$px - [double]$v.x) + 0.5) / [double]$v.w * 65535.0)
|
|
3583
|
+
$ny = [int][Math]::Round((([double]$py - [double]$v.y) + 0.5) / [double]$v.h * 65535.0)
|
|
3584
|
+
if ($nx -lt 0) { $nx = 0 } elseif ($nx -gt 65535) { $nx = 65535 }
|
|
3585
|
+
if ($ny -lt 0) { $ny = 0 } elseif ($ny -gt 65535) { $ny = 65535 }
|
|
3586
|
+
return @{ x = $nx; y = $ny }
|
|
3587
|
+
}
|
|
3588
|
+
|
|
3589
|
+
function Pointer-Pos {
|
|
3590
|
+
$v = Get-VirtScreen
|
|
3591
|
+
try {
|
|
3592
|
+
$a = [Native]::CursorXY()
|
|
3593
|
+
$x = [int]$a[0]; $y = [int]$a[1]
|
|
3594
|
+
if ($x -eq -1 -and $y -eq -1) { return Cursor-Pos }
|
|
3595
|
+
if ($x -lt $v.x -or $x -ge ($v.x + $v.w) -or $y -lt $v.y -or $y -ge ($v.y + $v.h)) {
|
|
3596
|
+
Log ('pointer: cursor (' + $x + ',' + $y + ') is outside the reported virtual screen')
|
|
3597
|
+
}
|
|
3598
|
+
return @{ x = $x; y = $y }
|
|
3599
|
+
} catch { return Cursor-Pos }
|
|
3600
|
+
}
|
|
3601
|
+
|
|
3602
|
+
function Apply-Ease($t, $kind) {
|
|
3603
|
+
if ($t -le 0) { return 0.0 }
|
|
3604
|
+
if ($t -ge 1) { return 1.0 }
|
|
3605
|
+
switch ($kind) {
|
|
3606
|
+
'linear' { return [double]$t }
|
|
3607
|
+
'ease-in' { return $t * $t * $t }
|
|
3608
|
+
'ease-out' { $u = 1.0 - $t; return 1.0 - ($u * $u * $u) }
|
|
3609
|
+
default {
|
|
3610
|
+
if ($t -lt 0.5) { return 4.0 * $t * $t * $t }
|
|
3611
|
+
$u = -2.0 * $t + 2.0
|
|
3612
|
+
return 1.0 - ($u * $u * $u) / 2.0
|
|
3613
|
+
}
|
|
3614
|
+
}
|
|
3615
|
+
}
|
|
3616
|
+
|
|
3617
|
+
function Wait-Tick($deadlineTick) {
|
|
3618
|
+
while ((TickNow) -lt $deadlineTick) {
|
|
3619
|
+
$rem = ([double]$deadlineTick - [double](TickNow)) / 10000.0
|
|
3620
|
+
if ($rem -gt 2.5) {
|
|
3621
|
+
try { [Threading.Thread]::Sleep(1) } catch { break }
|
|
3622
|
+
} else {
|
|
3623
|
+
try { [Threading.Thread]::SpinWait(8) } catch { break }
|
|
3624
|
+
}
|
|
3625
|
+
}
|
|
3626
|
+
}
|
|
3627
|
+
|
|
3628
|
+
function Glide-Duration($distancePx, $requestedMs) {
|
|
3629
|
+
$auto = 90.0 + $distancePx * 0.35
|
|
3630
|
+
if ($auto -lt 90.0) { $auto = 90.0 }
|
|
3631
|
+
if ($auto -gt 600.0) { $auto = 600.0 }
|
|
3632
|
+
if ($requestedMs -gt 0) {
|
|
3633
|
+
$d = [double]$requestedMs
|
|
3634
|
+
if ($d -lt 8.0) { $d = 8.0 }
|
|
3635
|
+
if ($d -gt 4000.0) { $d = 4000.0 }
|
|
3636
|
+
return @{ durationMs = [int][Math]::Round($d); source = 'caller' }
|
|
3637
|
+
}
|
|
3638
|
+
return @{ durationMs = [int][Math]::Round($auto); source = 'formula' }
|
|
3639
|
+
}
|
|
3640
|
+
|
|
3641
|
+
# The path itself. Emits exactly floor(durationMs/8) absolute moves (or 2 when teleporting, which
|
|
3642
|
+
# only the acceptance test does), sleeping until each 8 ms slot rather than sleeping 8 ms, so the
|
|
3643
|
+
# cadence does not drift with timer resolution.
|
|
3644
|
+
function Send-Pointer-Path($fromX, $fromY, $toX, $toY, $durationMs, $ease, $teleport) {
|
|
3645
|
+
$v = Get-VirtScreen
|
|
3646
|
+
$st = TickNow
|
|
3647
|
+
$expected = [int][Math]::Floor([double]$durationMs / 8.0)
|
|
3648
|
+
if ($expected -lt 1) { $expected = 1 }
|
|
3649
|
+
$points = New-Object System.Collections.Generic.List[object]
|
|
3650
|
+
$sent = 0
|
|
3651
|
+
$t0 = TickNow
|
|
3652
|
+
Begin-Precision
|
|
3653
|
+
if ($teleport) {
|
|
3654
|
+
$a = To-Norm $fromX $fromY $v
|
|
3655
|
+
if ([Native]::AbsMove($a.x, $a.y) -ne 1) { Err 'input_blocked' 'SendInput refused the move event (UIPI or a blocked input desktop)' }
|
|
3656
|
+
$sent++
|
|
3657
|
+
[void]$points.Add([ordered]@{ x = [int]$fromX; y = [int]$fromY; t = (MsFrom $t0) })
|
|
3658
|
+
$b = To-Norm $toX $toY $v
|
|
3659
|
+
if ([Native]::AbsMove($b.x, $b.y) -ne 1) { Err 'input_blocked' 'SendInput refused the move event (UIPI or a blocked input desktop)' }
|
|
3660
|
+
$sent++
|
|
3661
|
+
[void]$points.Add([ordered]@{ x = [int]$toX; y = [int]$toY; t = (MsFrom $t0) })
|
|
3662
|
+
} else {
|
|
3663
|
+
for ($i = 1; $i -le $expected; $i++) {
|
|
3664
|
+
if (Test-Escape) { Err 'cancelled' 'ESC pressed during pointer motion; glide aborted' }
|
|
3665
|
+
$f = Apply-Ease ([double]$i / [double]$expected) $ease
|
|
3666
|
+
$px = [int][Math]::Round([double]$fromX + ([double]$toX - [double]$fromX) * $f)
|
|
3667
|
+
$py = [int][Math]::Round([double]$fromY + ([double]$toY - [double]$fromY) * $f)
|
|
3668
|
+
if ($i -eq $expected) { $px = [int]$toX; $py = [int]$toY } # never leave a rounding stub
|
|
3669
|
+
$n = To-Norm $px $py $v
|
|
3670
|
+
if ([Native]::AbsMove($n.x, $n.y) -ne 1) { Err 'input_blocked' ('SendInput dropped the move event at step ' + $i + ' of ' + $expected) }
|
|
3671
|
+
$sent++
|
|
3672
|
+
[void]$points.Add([ordered]@{ x = $px; y = $py; t = (MsFrom $t0) })
|
|
3673
|
+
Wait-Tick ($t0 + ([Int64]$i * 8 * 10000))
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
3676
|
+
return @{
|
|
3677
|
+
sent = $sent
|
|
3678
|
+
expected = $expected
|
|
3679
|
+
points = $points
|
|
3680
|
+
ms = (MsFrom $st)
|
|
3681
|
+
teleport = [bool]$teleport
|
|
3682
|
+
durationMs = [int]$durationMs
|
|
3683
|
+
ease = [string]$ease
|
|
3684
|
+
}
|
|
3685
|
+
}
|
|
3686
|
+
|
|
3687
|
+
function Req-Coord($A, $name, $label) {
|
|
3688
|
+
$v = ArgOf $A $name
|
|
3689
|
+
if ($null -eq $v) { Err 'missing_arg' ("pointer needs a '" + $name + "' coordinate" + $(if ($label) { ' of ' + $label } else { '' })) }
|
|
3690
|
+
$d = $null
|
|
3691
|
+
try { $d = [double]$v } catch { Err 'bad_arg' ("'" + $name + "' is not a number: " + (OneLine ([string]$v))) }
|
|
3692
|
+
if ([double]::IsNaN($d) -or [double]::IsInfinity($d)) { Err 'bad_arg' ("'" + $name + "' is not finite") }
|
|
3693
|
+
return [int][Math]::Round($d)
|
|
3694
|
+
}
|
|
3695
|
+
|
|
3696
|
+
function Assert-In-Station($x, $y) {
|
|
3697
|
+
$v = Get-VirtScreen
|
|
3698
|
+
if ($x -lt $v.x -or $x -gt ($v.x + $v.w - 1) -or $y -lt $v.y -or $y -gt ($v.y + $v.h - 1)) {
|
|
3699
|
+
Err 'out_of_bounds' ("point " + $x + "," + $y + " is outside the virtual screen " + $v.x + "," + $v.y + " " + $v.w + "x" + $v.h)
|
|
3700
|
+
}
|
|
3701
|
+
}
|
|
3702
|
+
|
|
3703
|
+
function Window-Under-Info($x, $y) {
|
|
3704
|
+
$h = [Native]::HitTest([int]$x, [int]$y)
|
|
3705
|
+
$app = ''
|
|
3706
|
+
if ($h.pid -gt 0) { $app = ProcNameOf ([int]$h.pid) }
|
|
3707
|
+
return [ordered]@{
|
|
3708
|
+
hwnd = [int64]$h.root
|
|
3709
|
+
hitHwnd = [int64]$h.hit
|
|
3710
|
+
class = (TruncStr ([string]$h.rootClass) 80)
|
|
3711
|
+
hitClass = (TruncStr ([string]$h.hitClass) 80)
|
|
3712
|
+
title = (TruncStr ([string]$h.title) 140)
|
|
3713
|
+
pid = [int64]$h.pid
|
|
3714
|
+
app = $app
|
|
3715
|
+
}
|
|
3716
|
+
}
|
|
3717
|
+
|
|
3718
|
+
function Expect-Of($A) {
|
|
3719
|
+
$e = Dict (ArgOf $A 'expect')
|
|
3720
|
+
if ($null -eq $e -or -not ($e -is [System.Collections.IDictionary])) { $e = @{} }
|
|
3721
|
+
$hwnd = $e.Item('hwnd')
|
|
3722
|
+
if ($null -eq $hwnd) { $hwnd = ArgOf $A 'expectHwnd' }
|
|
3723
|
+
$title = $e.Item('titleContains')
|
|
3724
|
+
if ($null -eq $title -or [string]$title -eq '') { $title = StrArg $A 'expectTitleContains' '' }
|
|
3725
|
+
$wid = [string]$e.Item('windowId')
|
|
3726
|
+
$allow = BoolArg $A 'allowAnyTarget' $false
|
|
3727
|
+
if ($null -ne $e.Item('allowAnyTarget')) { $allow = BoolArg $e 'allowAnyTarget' $allow }
|
|
3728
|
+
$hwndI = 0
|
|
3729
|
+
if ($null -ne $hwnd -and [string]$hwnd -ne '') {
|
|
3730
|
+
try { $hwndI = [int64][double]$hwnd } catch { Err 'bad_arg' ("expect.hwnd is not a number: " + (OneLine ([string]$hwnd))) }
|
|
3731
|
+
}
|
|
3732
|
+
if ($hwndI -eq 0 -and $wid -ne '') {
|
|
3733
|
+
$entry = $script:W.windows.Item($wid)
|
|
3734
|
+
if ($null -eq $entry) { Err 'unknown_window' ("expect.windowId '" + $wid + "' is not a window this worker knows") }
|
|
3735
|
+
try { $hwndI = [int64]$entry.hwnd } catch { $hwndI = 0 }
|
|
3736
|
+
}
|
|
3737
|
+
$titleS = [string]$title
|
|
3738
|
+
return @{ hwnd = $hwndI; title = $titleS; allowAny = [bool]$allow; named = (($hwndI -ne 0) -or ($titleS -ne '')) }
|
|
3739
|
+
}
|
|
3740
|
+
|
|
3741
|
+
# The safety gate. Returns the hit-test plus a verdict; it never throws, because the caller has
|
|
3742
|
+
# to put the cursor back before reporting the refusal.
|
|
3743
|
+
function Test-Pointer-Target($exp, $x, $y) {
|
|
3744
|
+
$under = Window-Under-Info $x $y
|
|
3745
|
+
if (-not $exp.named) {
|
|
3746
|
+
if ($exp.allowAny) { return @{ under = $under; pass = $true; reason = ''; expectation = 'none (allowAnyTarget)' } }
|
|
3747
|
+
return @{ under = $under; pass = $false; expectation = 'none'
|
|
3748
|
+
reason = ("refusing to click at " + $x + "," + $y + " because nothing was declared as the expected target; " +
|
|
3749
|
+
"pass expect:{hwnd|windowId|titleContains} or say allowAnyTarget:true") }
|
|
3750
|
+
}
|
|
3751
|
+
$ok = $true; $why = ''
|
|
3752
|
+
if ($exp.hwnd -ne 0) {
|
|
3753
|
+
$isUnder = [Native]::IsSelfOrDescendant([IntPtr][int64]$under.hitHwnd, [IntPtr][int64]$exp.hwnd)
|
|
3754
|
+
$isRoot = ([int64]$under.hwnd -eq [int64]$exp.hwnd)
|
|
3755
|
+
if (-not ($isUnder -or $isRoot)) {
|
|
3756
|
+
$ok = $false
|
|
3757
|
+
$why = ("the window under " + $x + "," + $y + " is hwnd " + $under.hwnd + " '" + $under.title + "' (hit hwnd " + $under.hitHwnd + "), not the expected hwnd " + $exp.hwnd)
|
|
3758
|
+
}
|
|
3759
|
+
}
|
|
3760
|
+
if ($ok -and $exp.title -ne '') {
|
|
3761
|
+
if (([string]$under.title).ToLowerInvariant().IndexOf($exp.title.ToLowerInvariant()) -lt 0) {
|
|
3762
|
+
$ok = $false
|
|
3763
|
+
$why = ("the window under " + $x + "," + $y + " is titled '" + $under.title + "', which does not contain '" + $exp.title + "'")
|
|
3764
|
+
}
|
|
3765
|
+
}
|
|
3766
|
+
return @{ under = $under; pass = $ok; reason = $why; expectation = ('hwnd=' + $exp.hwnd + ' titleContains=' + $exp.title) }
|
|
3767
|
+
}
|
|
3768
|
+
|
|
3769
|
+
function Cmd-PointerTarget($A) {
|
|
3770
|
+
Ensure-Pointer
|
|
3771
|
+
$x = Req-Coord $A 'x' ''; $y = Req-Coord $A 'y' ''
|
|
3772
|
+
Assert-In-Station $x $y
|
|
3773
|
+
$v = Get-VirtScreen
|
|
3774
|
+
$n = To-Norm $x $y $v
|
|
3775
|
+
$e = Expect-Of $A
|
|
3776
|
+
$check = $null
|
|
3777
|
+
if ($e.named) { $check = Test-Pointer-Target $e $x $y }
|
|
3778
|
+
$r = [ordered]@{
|
|
3779
|
+
x = [int]$x; y = [int]$y
|
|
3780
|
+
via = 'physical'
|
|
3781
|
+
norm = [ordered]@{ x = [int]$n.x; y = [int]$n.y }
|
|
3782
|
+
under = (Window-Under-Info $x $y)
|
|
3783
|
+
}
|
|
3784
|
+
if ($null -ne $check) { $r['pass'] = [bool]$check.pass; $r['reason'] = [string]$check.reason }
|
|
3785
|
+
return $r
|
|
3786
|
+
}
|
|
3787
|
+
|
|
3788
|
+
function Cmd-PointerClick($A) {
|
|
3789
|
+
Ensure-Pointer
|
|
3790
|
+
$x = Req-Coord $A 'x' ''; $y = Req-Coord $A 'y' ''
|
|
3791
|
+
Assert-In-Station $x $y
|
|
3792
|
+
$button = (StrArg $A 'button' 'left').ToLowerInvariant()
|
|
3793
|
+
if ($button -eq '') { $button = 'left' }
|
|
3794
|
+
if (@('left', 'right', 'middle') -notcontains $button) { Err 'bad_arg' ("button '" + $button + "' is not left|right|middle") }
|
|
3795
|
+
$double = BoolArg $A 'double' $false
|
|
3796
|
+
$moveFirst = BoolArg $A 'moveFirst' $true
|
|
3797
|
+
$ease = (StrArg $A 'ease' 'ease-in-out').ToLowerInvariant()
|
|
3798
|
+
if (@('ease-in-out', 'linear', 'ease-in', 'ease-out') -notcontains $ease) { $ease = 'ease-in-out' }
|
|
3799
|
+
$pressMs = IntArg $A 'pressMs' 40
|
|
3800
|
+
if ($pressMs -lt 8) { $pressMs = 8 }
|
|
3801
|
+
if ($pressMs -gt 600) { $pressMs = 600 }
|
|
3802
|
+
$exp = Expect-Of $A
|
|
3803
|
+
$st = TickNow
|
|
3804
|
+
$start = Pointer-Pos
|
|
3805
|
+
|
|
3806
|
+
# gate #1, before the cursor moves at all
|
|
3807
|
+
$g1 = Test-Pointer-Target $exp $x $y
|
|
3808
|
+
if (-not $g1.pass) {
|
|
3809
|
+
$script:W.stats.refused += 1
|
|
3810
|
+
Err 'target_mismatch' ("pointer_click refused without moving: " + $g1.reason)
|
|
3811
|
+
}
|
|
3812
|
+
|
|
3813
|
+
$glide = $null
|
|
3814
|
+
if ($moveFirst) {
|
|
3815
|
+
$dx = [double]($x - [int]$start.x); $dy = [double]($y - [int]$start.y)
|
|
3816
|
+
$dist = [Math]::Sqrt($dx * $dx + $dy * $dy)
|
|
3817
|
+
$g = Glide-Duration $dist (IntArg $A 'durationMs' 0)
|
|
3818
|
+
if ($g.durationMs + 260 -gt (BudgetLeftMs)) {
|
|
3819
|
+
Err 'deadline_exceeded' ("the approach glide (" + $g.durationMs + " ms) plus the press does not fit the " + (BudgetLeftMs) + " ms left in this request")
|
|
3820
|
+
}
|
|
3821
|
+
$glide = Send-Pointer-Path ([int]$start.x) ([int]$start.y) $x $y $g.durationMs $ease $false
|
|
3822
|
+
}
|
|
3823
|
+
|
|
3824
|
+
# gate #2, after the glide: the window under the point is re-read, not remembered
|
|
3825
|
+
$g2 = Test-Pointer-Target $exp $x $y
|
|
3826
|
+
if (-not $g2.pass) {
|
|
3827
|
+
$script:W.stats.refused += 1
|
|
3828
|
+
if ($null -ne $glide) {
|
|
3829
|
+
$cur = Pointer-Pos
|
|
3830
|
+
[void](Send-Pointer-Path ([int]$cur.x) ([int]$cur.y) ([int]$start.x) ([int]$start.y) 140 $ease $false)
|
|
3831
|
+
}
|
|
3832
|
+
Err 'target_mismatch' ("pointer_click refused after gliding and put the cursor back: " + $g2.reason)
|
|
3833
|
+
}
|
|
3834
|
+
|
|
3835
|
+
$v = Get-VirtScreen
|
|
3836
|
+
$n = To-Norm $x $y $v
|
|
3837
|
+
$presses = 0
|
|
3838
|
+
Begin-Precision
|
|
3839
|
+
if ([Native]::AbsButtonDown($n.x, $n.y, $button) -ne 1) { Err 'input_blocked' 'SendInput dropped the button-down event' }
|
|
3840
|
+
$presses++
|
|
3841
|
+
[Threading.Thread]::Sleep($pressMs)
|
|
3842
|
+
if ([Native]::AbsButtonUp($n.x, $n.y, $button) -ne 1) { Err 'input_blocked' 'SendInput dropped the button-up event' }
|
|
3843
|
+
if ($double) {
|
|
3844
|
+
[Threading.Thread]::Sleep(50)
|
|
3845
|
+
if ([Native]::AbsButtonDown($n.x, $n.y, $button) -ne 1) { Err 'input_blocked' 'SendInput dropped the second button-down event' }
|
|
3846
|
+
$presses++
|
|
3847
|
+
[Threading.Thread]::Sleep($pressMs)
|
|
3848
|
+
if ([Native]::AbsButtonUp($n.x, $n.y, $button) -ne 1) { Err 'input_blocked' 'SendInput dropped the second button-up event' }
|
|
3849
|
+
}
|
|
3850
|
+
$at = Pointer-Pos
|
|
3851
|
+
$script:W.stats.actionsPerformed += 1
|
|
3852
|
+
$r = [ordered]@{
|
|
3853
|
+
atCursor = [ordered]@{ x = [int]$at.x; y = [int]$at.y }
|
|
3854
|
+
via = 'physical'
|
|
3855
|
+
button = $button
|
|
3856
|
+
down = $true
|
|
3857
|
+
up = $true
|
|
3858
|
+
ms = [Math]::Round((MsFrom $st), 1)
|
|
3859
|
+
presses = [int]$presses
|
|
3860
|
+
double = [bool]$double
|
|
3861
|
+
pressMs = [int]$pressMs
|
|
3862
|
+
moved = [bool]($null -ne $glide)
|
|
3863
|
+
under = $g2.under
|
|
3864
|
+
gate = [ordered]@{ before = [bool]$g1.pass; after = [bool]$g2.pass; expectation = [string]$g2.expectation }
|
|
3865
|
+
}
|
|
3866
|
+
if ($null -ne $glide) {
|
|
3867
|
+
$r['distance'] = [Math]::Round([Math]::Sqrt([Math]::Pow([double]($x - [int]$start.x), 2) + [Math]::Pow([double]($y - [int]$start.y), 2)), 1)
|
|
3868
|
+
$r['samples'] = [int]$glide.sent
|
|
3869
|
+
$r['expectedSamples'] = [int]$glide.expected
|
|
3870
|
+
}
|
|
3871
|
+
return $r
|
|
3872
|
+
}
|
|
3873
|
+
|
|
3874
|
+
function Cmd-PointerDrag($A) {
|
|
3875
|
+
Ensure-Pointer
|
|
3876
|
+
$fd = Dict (ArgOf $A 'from')
|
|
3877
|
+
$td = Dict (ArgOf $A 'to')
|
|
3878
|
+
if ($null -eq $fd -or -not ($fd -is [System.Collections.IDictionary])) { Err 'missing_arg' 'pointer_drag needs from:{x,y}' }
|
|
3879
|
+
if ($null -eq $td -or -not ($td -is [System.Collections.IDictionary])) { Err 'missing_arg' 'pointer_drag needs to:{x,y}' }
|
|
3880
|
+
$fx = Req-Coord $fd 'x' 'from'; $fy = Req-Coord $fd 'y' 'from'
|
|
3881
|
+
$tx = Req-Coord $td 'x' 'to'; $ty = Req-Coord $td 'y' 'to'
|
|
3882
|
+
Assert-In-Station $fx $fy; Assert-In-Station $tx $ty
|
|
3883
|
+
$button = (StrArg $A 'button' 'left').ToLowerInvariant()
|
|
3884
|
+
if (@('left', 'right', 'middle') -notcontains $button) { Err 'bad_arg' ("button '" + $button + "' is not left|right|middle") }
|
|
3885
|
+
$ease = (StrArg $A 'ease' 'ease-in-out').ToLowerInvariant()
|
|
3886
|
+
if (@('ease-in-out', 'linear', 'ease-in', 'ease-out') -notcontains $ease) { $ease = 'ease-in-out' }
|
|
3887
|
+
$holdMs = IntArg $A 'holdMs' 60
|
|
3888
|
+
if ($holdMs -lt 8) { $holdMs = 8 }
|
|
3889
|
+
if ($holdMs -gt 1000) { $holdMs = 1000 }
|
|
3890
|
+
$exp = Expect-Of $A
|
|
3891
|
+
$st = TickNow
|
|
3892
|
+
$start = Pointer-Pos
|
|
3893
|
+
|
|
3894
|
+
# a drag is the most destructive gesture this channel can express, so the declared window has
|
|
3895
|
+
# to hold for the endpoints AND for points in between
|
|
3896
|
+
if ($exp.named) {
|
|
3897
|
+
foreach ($tf in @(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)) {
|
|
3898
|
+
$px = [int][Math]::Round([double]$fx + ([double]$tx - [double]$fx) * $tf)
|
|
3899
|
+
$py = [int][Math]::Round([double]$fy + ([double]$ty - [double]$fy) * $tf)
|
|
3900
|
+
$c = Test-Pointer-Target $exp $px $py
|
|
3901
|
+
if (-not $c.pass) {
|
|
3902
|
+
$script:W.stats.refused += 1
|
|
3903
|
+
Err 'target_mismatch' ("pointer_drag refused before moving (probe at " + [Math]::Round($tf * 100) + "% of the path): " + $c.reason)
|
|
3904
|
+
}
|
|
3905
|
+
}
|
|
3906
|
+
}
|
|
3907
|
+
|
|
3908
|
+
$d0x = [double]($fx - [int]$start.x); $d0y = [double]($fy - [int]$start.y)
|
|
3909
|
+
$dist0 = [Math]::Sqrt($d0x * $d0x + $d0y * $d0y)
|
|
3910
|
+
$dx = [double]($tx - $fx); $dy = [double]($ty - $fy)
|
|
3911
|
+
$dist = [Math]::Sqrt($dx * $dx + $dy * $dy)
|
|
3912
|
+
$g0 = Glide-Duration $dist0 (IntArg $A 'durationMs' 0)
|
|
3913
|
+
$g1 = Glide-Duration $dist (IntArg $A 'durationMs2' $g0.durationMs)
|
|
3914
|
+
$need = $g0.durationMs + $g1.durationMs + 2 * $holdMs + 300
|
|
3915
|
+
if ($need -gt (BudgetLeftMs)) {
|
|
3916
|
+
Err 'deadline_exceeded' ("this drag needs ~" + $need + " ms but only " + (BudgetLeftMs) + " ms are left in the request")
|
|
3917
|
+
}
|
|
3918
|
+
|
|
3919
|
+
$approach = Send-Pointer-Path ([int]$start.x) ([int]$start.y) $fx $fy $g0.durationMs $ease $false
|
|
3920
|
+
$v = Get-VirtScreen
|
|
3921
|
+
$n = To-Norm $fx $fy $v
|
|
3922
|
+
Begin-Precision
|
|
3923
|
+
if ([Native]::AbsButtonDown($n.x, $n.y, $button) -ne 1) { Err 'input_blocked' 'SendInput dropped the drag button-down event' }
|
|
3924
|
+
[Threading.Thread]::Sleep($holdMs)
|
|
3925
|
+
# the button stays logically down; the travel events are plain absolute moves, which is what a
|
|
3926
|
+
# real drag looks like on the wire
|
|
3927
|
+
$travel = Send-Pointer-Path $fx $fy $tx $ty $g1.durationMs $ease $false
|
|
3928
|
+
[Threading.Thread]::Sleep($holdMs)
|
|
3929
|
+
$n2 = To-Norm $tx $ty $v
|
|
3930
|
+
$upOk = $false
|
|
3931
|
+
try { $upOk = ([Native]::AbsButtonUp($n2.x, $n2.y, $button) -eq 1) } catch { }
|
|
3932
|
+
if (-not $upOk) {
|
|
3933
|
+
# never leave the desktop with a button held down: retry once, then say so loudly
|
|
3934
|
+
try { [void][Native]::AbsButtonUp($n2.x, $n2.y, $button) } catch { }
|
|
3935
|
+
Log 'pointer_drag: the button-up event was dropped twice; the desktop may still think the button is held'
|
|
3936
|
+
}
|
|
3937
|
+
$at = Pointer-Pos
|
|
3938
|
+
$under = Window-Under-Info $tx $ty
|
|
3939
|
+
$script:W.stats.actionsPerformed += 1
|
|
3940
|
+
return [ordered]@{
|
|
3941
|
+
from = [ordered]@{ x = [int]$fx; y = [int]$fy }
|
|
3942
|
+
to = [ordered]@{ x = [int]$tx; y = [int]$ty }
|
|
3943
|
+
via = 'physical'
|
|
3944
|
+
button = $button
|
|
3945
|
+
down = $true
|
|
3946
|
+
up = [bool]$upOk
|
|
3947
|
+
distance = [Math]::Round($dist, 1)
|
|
3948
|
+
durationMs = [int]$g1.durationMs
|
|
3949
|
+
samples = [int]$travel.sent
|
|
3950
|
+
expectedSamples = [int]$travel.expected
|
|
3951
|
+
approachSamples = [int]$approach.sent
|
|
3952
|
+
holdMs = [int]$holdMs
|
|
3953
|
+
atCursor = [ordered]@{ x = [int]$at.x; y = [int]$at.y }
|
|
3954
|
+
under = $under
|
|
3955
|
+
ms = [Math]::Round((MsFrom $st), 1)
|
|
3956
|
+
}
|
|
3957
|
+
}
|
|
3958
|
+
|
|
3959
|
+
# Read-only: where is the caret / the keyboard focus right now, for an element the caller already
|
|
3960
|
+
# has a ref for. This is the instrument that turns "an event was queued" into "the click landed".
|
|
3961
|
+
# Named-key -> virtual-key-code table for the physical keyboard channel (Cmd-Key). Letters and digits
|
|
3962
|
+
# are resolved by ASCII in Resolve-KeyVk; this table covers the rest.
|
|
3963
|
+
$script:VK = @{
|
|
3964
|
+
'ctrl' = 0x11; 'control' = 0x11; 'alt' = 0x12; 'option' = 0x12; 'shift' = 0x10;
|
|
3965
|
+
'win' = 0x5B; 'meta' = 0x5B; 'super' = 0x5B; 'cmd' = 0x5B; 'winright' = 0x5C;
|
|
3966
|
+
'enter' = 0x0D; 'return' = 0x0D; 'tab' = 0x09; 'esc' = 0x1B; 'escape' = 0x1B;
|
|
3967
|
+
'backspace' = 0x08; 'delete' = 0x2E; 'del' = 0x2E; 'insert' = 0x2D; 'space' = 0x20; 'spacebar' = 0x20;
|
|
3968
|
+
'up' = 0x26; 'down' = 0x28; 'left' = 0x25; 'right' = 0x27; 'home' = 0x24; 'end' = 0x23;
|
|
3969
|
+
'pageup' = 0x21; 'pgup' = 0x21; 'pagedown' = 0x22; 'pgdn' = 0x22;
|
|
3970
|
+
'printscreen' = 0x2C; 'capslock' = 0x14;
|
|
3971
|
+
'f1' = 0x70; 'f2' = 0x71; 'f3' = 0x72; 'f4' = 0x73; 'f5' = 0x74; 'f6' = 0x75;
|
|
3972
|
+
'f7' = 0x76; 'f8' = 0x77; 'f9' = 0x78; 'f10' = 0x79; 'f11' = 0x7A; 'f12' = 0x7B;
|
|
3973
|
+
}
|
|
3974
|
+
function Resolve-KeyVk($tok) {
|
|
3975
|
+
if ($script:VK.ContainsKey($tok)) { return [int]$script:VK[$tok] }
|
|
3976
|
+
if ($tok.Length -eq 1) {
|
|
3977
|
+
$code = [int][char]$tok[0]
|
|
3978
|
+
if ($code -ge 97 -and $code -le 122) { return $code - 32 } # a-z -> VK_A..VK_Z (ASCII uppercase)
|
|
3979
|
+
if ($code -ge 48 -and $code -le 57) { return $code } # 0-9 -> VK_0..VK_9 (ASCII digit)
|
|
3980
|
+
}
|
|
3981
|
+
Err 'unknown_key' ("unrecognized key '" + (OneLine $tok) + "' (use a name like enter/tab/f5/up or a single letter/digit)")
|
|
3982
|
+
}
|
|
3983
|
+
|
|
3984
|
+
function Cmd-TypeText($A) {
|
|
3985
|
+
Ensure-Pointer
|
|
3986
|
+
$text = ArgOf $A 'text'
|
|
3987
|
+
if ($null -eq $text) { Err 'missing_arg' 'type_text needs text' }
|
|
3988
|
+
$text = [string]$text
|
|
3989
|
+
if ($text.Length -gt 4000) { Err 'too_long' 'type_text accepts at most 4000 characters' }
|
|
3990
|
+
if ($text -eq '') { return [ordered]@{ sent = 0; chars = 0; ms = 0 } }
|
|
3991
|
+
# via = keyboard (default, per-character SendInput, semantics unchanged) | clipboard (write the
|
|
3992
|
+
# whole text with Set-Clipboard — built into Windows PowerShell 5.1, zero dependencies — and
|
|
3993
|
+
# deliver ONE ctrl+v through the same event pipeline Cmd-Key uses). The clipboard path is for
|
|
3994
|
+
# long text / text with newlines: 4000 characters as keyboard events is 8000 SendInput events,
|
|
3995
|
+
# one paste is 4. It deliberately does NOT save or restore the clipboard — documented loudly.
|
|
3996
|
+
$via = (StrArg $A 'via' 'keyboard').ToLowerInvariant()
|
|
3997
|
+
if (@('keyboard', 'clipboard') -notcontains $via) { Err 'bad_arg' ("via '" + (OneLine $via) + "' is not keyboard|clipboard") }
|
|
3998
|
+
$wid = StrArg $A 'windowId' ''
|
|
3999
|
+
if ($wid -ne '') {
|
|
4000
|
+
$entry = Window-Entry $wid
|
|
4001
|
+
try { [void][Native]::SetForegroundWindow([IntPtr]$entry.hwnd) } catch { }
|
|
4002
|
+
[Threading.Thread]::Sleep(30)
|
|
4003
|
+
}
|
|
4004
|
+
$st = TickNow
|
|
4005
|
+
if ($via -eq 'clipboard') {
|
|
4006
|
+
# Set-Clipboard can lose a race against a clipboard manager inspecting the same buffer —
|
|
4007
|
+
# retry once, then refuse honestly instead of pasting garbage.
|
|
4008
|
+
$clipOk = $false
|
|
4009
|
+
$clipErr = ''
|
|
4010
|
+
for ($attempt = 0; $attempt -lt 2 -and -not $clipOk; $attempt++) {
|
|
4011
|
+
try { Set-Clipboard -Value $text; $clipOk = $true } catch { $clipErr = $_.Exception.Message; Start-Sleep -Milliseconds 60 }
|
|
4012
|
+
}
|
|
4013
|
+
if (-not $clipOk) { Err 'clipboard_failed' ('Set-Clipboard threw twice (clipboard manager contention?): ' + (OneLine $clipErr)) }
|
|
4014
|
+
[Threading.Thread]::Sleep(30) # let the write settle before the paste
|
|
4015
|
+
# ctrl+v through the exact pipeline Cmd-Key uses (KeyDownVk/KeyUpVk + Sleep(15)). VK_CONTROL
|
|
4016
|
+
# = 0x11, VK_V = 0x56; 'v' resolves to the same code in Resolve-KeyVk.
|
|
4017
|
+
Begin-Precision
|
|
4018
|
+
if ([Native]::KeyDownVk(0x11) -ne 1) { Err 'input_blocked' 'SendInput dropped the ctrl key-down' }
|
|
4019
|
+
if ([Native]::KeyDownVk(0x56) -ne 1) { Err 'input_blocked' 'SendInput dropped the v key-down' }
|
|
4020
|
+
[Threading.Thread]::Sleep(15)
|
|
4021
|
+
if ([Native]::KeyUpVk(0x56) -ne 1) { Err 'input_blocked' 'SendInput dropped the v key-up' }
|
|
4022
|
+
[void][Native]::KeyUpVk(0x11)
|
|
4023
|
+
$script:W.stats.actionsPerformed += 1
|
|
4024
|
+
return [ordered]@{ sent = 4; chars = [int]$text.Length; via = 'clipboard'; ms = [Math]::Round((MsFrom $st), 1) }
|
|
4025
|
+
}
|
|
4026
|
+
$sent = [Native]::SendUnicode($text)
|
|
4027
|
+
if ($sent -lt 1) { Err 'input_blocked' 'SendInput accepted none of the key events (blocked input desktop?)' }
|
|
4028
|
+
$script:W.stats.actionsPerformed += 1
|
|
4029
|
+
return [ordered]@{ sent = [int]$sent; chars = [int]$text.Length; via = 'physical'; ms = [Math]::Round((MsFrom $st), 1) }
|
|
4030
|
+
}
|
|
4031
|
+
|
|
4032
|
+
function Cmd-Key($A) {
|
|
4033
|
+
Ensure-Pointer
|
|
4034
|
+
$combo = StrArg $A 'keys' ''
|
|
4035
|
+
if ($combo -eq '') { $combo = StrArg $A 'key' '' }
|
|
4036
|
+
if ($combo -eq '') { Err 'missing_arg' 'key needs keys, e.g. "enter" or "ctrl+c" or "alt+tab"' }
|
|
4037
|
+
$tokens = @(($combo.ToLowerInvariant() -split '\+') | Where-Object { $_ -ne '' })
|
|
4038
|
+
if ($tokens.Count -eq 0) { Err 'bad_arg' ('could not parse keys: ' + (OneLine $combo)) }
|
|
4039
|
+
$mods = New-Object System.Collections.Generic.List[int]
|
|
4040
|
+
$main = 0
|
|
4041
|
+
for ($i = 0; $i -lt $tokens.Count; $i++) {
|
|
4042
|
+
$vk = Resolve-KeyVk ([string]$tokens[$i])
|
|
4043
|
+
if ($i -lt $tokens.Count - 1) { $mods.Add([int]$vk) | Out-Null } else { $main = [int]$vk }
|
|
4044
|
+
}
|
|
4045
|
+
$st = TickNow
|
|
4046
|
+
Begin-Precision
|
|
4047
|
+
foreach ($m in $mods) { if ([Native]::KeyDownVk($m) -ne 1) { Err 'input_blocked' 'SendInput dropped a modifier key-down' } }
|
|
4048
|
+
if ([Native]::KeyDownVk($main) -ne 1) { Err 'input_blocked' 'SendInput dropped the key-down' }
|
|
4049
|
+
[Threading.Thread]::Sleep(15)
|
|
4050
|
+
if ([Native]::KeyUpVk($main) -ne 1) { Err 'input_blocked' 'SendInput dropped the key-up' }
|
|
4051
|
+
for ($j = $mods.Count - 1; $j -ge 0; $j--) { [void][Native]::KeyUpVk([int]$mods[$j]) }
|
|
4052
|
+
$script:W.stats.actionsPerformed += 1
|
|
4053
|
+
return [ordered]@{ keys = $combo; via = 'physical'; ms = [Math]::Round((MsFrom $st), 1) }
|
|
4054
|
+
}
|
|
4055
|
+
|
|
4056
|
+
function Cmd-PointerScroll($A) {
|
|
4057
|
+
Ensure-Pointer
|
|
4058
|
+
$x = Req-Coord $A 'x' ''; $y = Req-Coord $A 'y' ''
|
|
4059
|
+
Assert-In-Station $x $y
|
|
4060
|
+
$dir = (StrArg $A 'direction' 'down').ToLowerInvariant()
|
|
4061
|
+
if (@('up', 'down', 'left', 'right') -notcontains $dir) { Err 'bad_arg' ("direction '" + $dir + "' is not up|down|left|right") }
|
|
4062
|
+
$clicks = IntArg $A 'clicks' 3
|
|
4063
|
+
if ($clicks -lt 1) { $clicks = 1 }; if ($clicks -gt 50) { $clicks = 50 }
|
|
4064
|
+
$horiz = ($dir -eq 'left' -or $dir -eq 'right')
|
|
4065
|
+
$sign = if ($dir -eq 'down' -or $dir -eq 'left') { -1 } else { 1 }
|
|
4066
|
+
$exp = Expect-Of $A
|
|
4067
|
+
$g = Test-Pointer-Target $exp $x $y
|
|
4068
|
+
if (-not $g.pass) { $script:W.stats.refused += 1; Err 'target_mismatch' ('pointer_scroll refused: ' + $g.reason) }
|
|
4069
|
+
$v = Get-VirtScreen; $n = To-Norm $x $y $v
|
|
4070
|
+
Begin-Precision
|
|
4071
|
+
$st = TickNow
|
|
4072
|
+
if ([Native]::AbsMove($n.x, $n.y) -ne 1) { Err 'input_blocked' 'scroll move refused by SendInput' }
|
|
4073
|
+
$sent = 0
|
|
4074
|
+
for ($i = 0; $i -lt $clicks; $i++) {
|
|
4075
|
+
if (Test-Escape) { break }
|
|
4076
|
+
$d = $sign * 120
|
|
4077
|
+
$r = if ($horiz) { [Native]::AbsHWheel($n.x, $n.y, $d) } else { [Native]::AbsWheel($n.x, $n.y, $d) }
|
|
4078
|
+
if ($r -ne 1) { Err 'input_blocked' ('SendInput dropped the wheel event at ' + ($i + 1) + ' of ' + $clicks) }
|
|
4079
|
+
$sent++
|
|
4080
|
+
[Threading.Thread]::Sleep(12)
|
|
4081
|
+
}
|
|
4082
|
+
$script:W.stats.actionsPerformed += 1
|
|
4083
|
+
return [ordered]@{ at = [ordered]@{ x = [int]$x; y = [int]$y }; direction = $dir; clicks = [int]$sent; horizontal = [bool]$horiz; via = 'physical'; under = $g.under; ms = [Math]::Round((MsFrom $st), 1) }
|
|
4084
|
+
}
|
|
4085
|
+
|
|
4086
|
+
# ---------------------------------------------------------------- dispatch
|
|
4087
|
+
$handlers = @{
|
|
4088
|
+
ping = 'Cmd-Ping'
|
|
4089
|
+
list_windows = 'Cmd-ListWindows'
|
|
4090
|
+
resolve_window = 'Cmd-ResolveWindow'
|
|
4091
|
+
snapshot = 'Cmd-Snapshot'
|
|
4092
|
+
describe = 'Cmd-Describe'
|
|
4093
|
+
descriptor_match = 'Cmd-DescriptorMatch'
|
|
4094
|
+
act = 'Cmd-Act'
|
|
4095
|
+
set_pointer_mode = 'Cmd-SetPointerMode'
|
|
4096
|
+
escape_pressed = 'Cmd-EscapePressed'
|
|
4097
|
+
prepare_batch = 'Cmd-PrepareBatch'
|
|
4098
|
+
commit_batch = 'Cmd-CommitBatch'
|
|
4099
|
+
wait = 'Cmd-Wait'
|
|
4100
|
+
capture = 'Cmd-Capture'
|
|
4101
|
+
capture_screen = 'Cmd-CaptureScreen'
|
|
4102
|
+
ocr = 'Cmd-Ocr'
|
|
4103
|
+
find_text = 'Cmd-FindText'
|
|
4104
|
+
launch = 'Cmd-Launch'
|
|
4105
|
+
close_window = 'Cmd-CloseWindow'
|
|
4106
|
+
pointer_target = 'Cmd-PointerTarget'
|
|
4107
|
+
pointer_click = 'Cmd-PointerClick'
|
|
4108
|
+
pointer_drag = 'Cmd-PointerDrag'
|
|
4109
|
+
pointer_scroll = 'Cmd-PointerScroll'
|
|
4110
|
+
type_text = 'Cmd-TypeText'
|
|
4111
|
+
key = 'Cmd-Key'
|
|
4112
|
+
shutdown = 'Cmd-Shutdown'
|
|
4113
|
+
}
|
|
4114
|
+
$defaultBudget = @{
|
|
4115
|
+
snapshot = 15000
|
|
4116
|
+
commit_batch = 25000
|
|
4117
|
+
prepare_batch = 12000
|
|
4118
|
+
capture = 12000
|
|
4119
|
+
capture_screen = 15000
|
|
4120
|
+
ocr = 20000
|
|
4121
|
+
launch = 25000
|
|
4122
|
+
resolve_window = 15000
|
|
4123
|
+
wait = 25000
|
|
4124
|
+
find_text = 12000
|
|
4125
|
+
close_window = 12000
|
|
4126
|
+
act = 15000
|
|
4127
|
+
set_pointer_mode = 3000
|
|
4128
|
+
escape_pressed = 2000
|
|
4129
|
+
list_windows = 8000
|
|
4130
|
+
pointer_click = 5000
|
|
4131
|
+
pointer_drag = 8000
|
|
4132
|
+
pointer_scroll = 8000
|
|
4133
|
+
type_text = 8000
|
|
4134
|
+
key = 5000
|
|
4135
|
+
pointer_target = 3000
|
|
4136
|
+
describe = 8000
|
|
4137
|
+
descriptor_match = 6000
|
|
4138
|
+
ping = 5000
|
|
4139
|
+
}
|
|
4140
|
+
|
|
4141
|
+
function Invoke-Request($line) {
|
|
4142
|
+
$id = 0
|
|
4143
|
+
$cmd = ''
|
|
4144
|
+
$A = @{}
|
|
4145
|
+
try {
|
|
4146
|
+
$obj = $null
|
|
4147
|
+
try { $obj = ConvertFrom-Json $line } catch { Send-Err 0 'bad_json' ('not valid JSON: ' + $_.Exception.Message); return $true }
|
|
4148
|
+
if ($null -eq $obj) { Send-Err 0 'bad_json' 'empty request'; return $true }
|
|
4149
|
+
$pp = $obj.PSObject.Properties['id']
|
|
4150
|
+
if ($null -ne $pp -and $null -ne $pp.Value) { try { $id = [long]$pp.Value } catch { $id = 0 } }
|
|
4151
|
+
$pp = $obj.PSObject.Properties['cmd']
|
|
4152
|
+
if ($null -ne $pp -and $null -ne $pp.Value) { $cmd = [string]$pp.Value }
|
|
4153
|
+
$pp = $obj.PSObject.Properties['args']
|
|
4154
|
+
if ($null -ne $pp -and $null -ne $pp.Value) { $d = Dict $pp.Value; if ($d -is [System.Collections.IDictionary]) { $A = $d } }
|
|
4155
|
+
if ($cmd -eq '' -or -not $handlers.ContainsKey($cmd)) {
|
|
4156
|
+
Send-Err $id 'unknown_cmd' ("unknown cmd '" + (OneLine $cmd) + "'")
|
|
4157
|
+
return $true
|
|
4158
|
+
}
|
|
4159
|
+
$budgetMs = IntArg $A 'timeoutMs' 0
|
|
4160
|
+
if ($budgetMs -gt 0) { $budgetMs = $budgetMs + 2500 } else {
|
|
4161
|
+
$b = $defaultBudget[$cmd]
|
|
4162
|
+
if ($null -eq $b) { $b = 10000 }
|
|
4163
|
+
$budgetMs = [int]$b
|
|
4164
|
+
}
|
|
4165
|
+
Set-Deadline $budgetMs
|
|
4166
|
+
$fn = $handlers[$cmd]
|
|
4167
|
+
$result = & $fn $A
|
|
4168
|
+
Set-Deadline 0
|
|
4169
|
+
if ($cmd -eq 'shutdown') {
|
|
4170
|
+
Send-Ok $id $result
|
|
4171
|
+
Cleanup-All
|
|
4172
|
+
return $false
|
|
4173
|
+
}
|
|
4174
|
+
Send-Ok $id $result
|
|
4175
|
+
} catch {
|
|
4176
|
+
Set-Deadline 0
|
|
4177
|
+
$code, $msg = Split-Err $_
|
|
4178
|
+
$log = $cmd + ' -> ' + $code + ': ' + (OneLine $msg)
|
|
4179
|
+
if ($script:W.errors.Count -lt 200) { $script:W.errors.Add($log) | Out-Null }
|
|
4180
|
+
Log $log
|
|
4181
|
+
Send-Err $id $code $msg
|
|
4182
|
+
}
|
|
4183
|
+
return $true
|
|
4184
|
+
}
|
|
4185
|
+
|
|
4186
|
+
function Cleanup-All {
|
|
4187
|
+
# No Marshal.ReleaseComObject here either: managed UIA elements are not COM objects, so the
|
|
4188
|
+
# call always threw and the empty catch swallowed it. Dropping every reference and letting the
|
|
4189
|
+
# GC run below is the whole cleanup.
|
|
4190
|
+
foreach ($rk in @($script:W.refs.Keys)) {
|
|
4191
|
+
$r = $script:W.refs[$rk]
|
|
4192
|
+
if ($null -ne $r) { $r.ae = $null }
|
|
4193
|
+
}
|
|
4194
|
+
$script:W.refs.Clear()
|
|
4195
|
+
$script:W.refOrder.Clear()
|
|
4196
|
+
$script:W.windows.Clear()
|
|
4197
|
+
$script:W.winByHwnd.Clear()
|
|
4198
|
+
$script:W.totalRefs = 0
|
|
4199
|
+
try { [GC]::Collect(); [GC]::WaitForPendingFinalizers(); [GC]::Collect() } catch { }
|
|
4200
|
+
}
|
|
4201
|
+
|
|
4202
|
+
Log 'listening on stdin'
|
|
4203
|
+
$alive = $true
|
|
4204
|
+
try {
|
|
4205
|
+
while ($alive) {
|
|
4206
|
+
$line = [Console]::In.ReadLine()
|
|
4207
|
+
if ($null -eq $line) { Log 'stdin EOF, exiting'; break }
|
|
4208
|
+
if ($line.Trim().Length -eq 0) { continue }
|
|
4209
|
+
$alive = Invoke-Request $line
|
|
4210
|
+
}
|
|
4211
|
+
} catch {
|
|
4212
|
+
Log ('FATAL: ' + $_.Exception.Message)
|
|
4213
|
+
try { Send-Err 0 'internal_error' ('worker loop died: ' + $_.Exception.Message) } catch { }
|
|
4214
|
+
Cleanup-All
|
|
4215
|
+
exit 2
|
|
4216
|
+
}
|
|
4217
|
+
exit 0
|
|
4218
|
+
|
|
4219
|
+
|
|
4220
|
+
|