dsh-native-uia 0.0.0-stage → 0.4.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 +663 -2
- package/client/client.js +269 -0
- package/cordis.patch.yml +10 -0
- package/icon.svg +11 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -4
- package/scripts/bench-live.mjs +157 -0
- package/scripts/check-lease.mjs +308 -0
- package/scripts/install.mjs +154 -0
- package/scripts/lib/dsh-tools-stub.mjs +14 -0
- package/scripts/lib/load-tools-source.mjs +25 -0
- package/scripts/lib/sources.mjs +62 -0
- package/scripts/load-tools.mjs +74 -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 +192 -0
- package/scripts/regression-worker.ps1 +1071 -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-style.mjs +46 -0
- package/scripts/verify-live.mjs +104 -0
- package/scripts/verify-locator.mjs +52 -0
- package/scripts/verify.mjs +2110 -0
- package/src/activity-window.js +276 -0
- package/src/dashboard.js +103 -0
- package/src/guard.js +201 -0
- package/src/index.js +525 -0
- package/src/native-uia-remote.js +80 -0
- package/src/notes.js +83 -0
- package/src/state.js +267 -0
- package/src/themes.js +74 -0
- package/src/tools/defs/act.js +533 -0
- package/src/tools/defs/lifecycle.js +205 -0
- package/src/tools/defs/observe.js +309 -0
- package/src/tools/defs/pointer.js +298 -0
- package/src/tools/format.js +301 -0
- package/src/tools/index.js +128 -0
- package/src/tools/ocr.js +91 -0
- package/src/tools/recipes.js +44 -0
- package/src/tools/runtime.js +42 -0
- package/src/worker-client.js +268 -0
- package/worker/assets/dsh-whale.path +1 -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 +2963 -0
- package/worker/lib/01-core.ps1 +64 -0
- package/worker/lib/02-uia.ps1 +221 -0
- package/worker/lib/03-window.ps1 +194 -0
- package/worker/lib/04-match.ps1 +435 -0
- package/worker/lib/05-value.ps1 +149 -0
- package/worker/lib/06-snapshot.ps1 +345 -0
- package/worker/lib/07-action.ps1 +291 -0
- package/worker/lib/08-command.ps1 +1485 -0
- package/worker/lib/09-pointer.ps1 +840 -0
- package/worker/lib/10-dispatch.ps1 +134 -0
- package/worker/ps-stdio.ps1 +173 -0
- package/worker/uia-worker.ps1 +599 -0
|
@@ -0,0 +1,599 @@
|
|
|
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
|
+
|
|
60
|
+
# stderr logging helper (defined before anything can use it; stdout is reserved for responses)
|
|
61
|
+
$script:stdErr = [Console]::Error
|
|
62
|
+
function Log($msg) {
|
|
63
|
+
try { $script:stdErr.WriteLine('[uia-worker] ' + $msg) } catch { }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
# ---------------------------------------------------------------- assemblies
|
|
67
|
+
$script:asmMs = 0
|
|
68
|
+
$t0 = [Diagnostics.Stopwatch]::GetTimestamp()
|
|
69
|
+
Add-Type -AssemblyName UIAutomationClient
|
|
70
|
+
Add-Type -AssemblyName UIAutomationTypes
|
|
71
|
+
Add-Type -AssemblyName System.Drawing
|
|
72
|
+
Add-Type -AssemblyName System.Windows.Forms
|
|
73
|
+
$script:asmMs = [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $t0) / 10000.0, 1)
|
|
74
|
+
|
|
75
|
+
$AE = [System.Windows.Automation.AutomationElement]
|
|
76
|
+
$TW = [System.Windows.Automation.TreeWalker]
|
|
77
|
+
|
|
78
|
+
# ---------------------------------------------------------------- native helper
|
|
79
|
+
$script:nativeSrc = @'
|
|
80
|
+
using System;
|
|
81
|
+
using System.Collections.Generic;
|
|
82
|
+
using System.Diagnostics;
|
|
83
|
+
using System.Runtime.InteropServices;
|
|
84
|
+
using System.Drawing;
|
|
85
|
+
using System.Drawing.Imaging;
|
|
86
|
+
using System.IO;
|
|
87
|
+
|
|
88
|
+
public static class Native {
|
|
89
|
+
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
|
|
90
|
+
[DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
|
|
91
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
92
|
+
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
|
93
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
|
|
94
|
+
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
|
|
95
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
|
|
96
|
+
// Window geometry: MoveWindow is enough for move and resize (same call, different intent) and
|
|
97
|
+
// avoids SetWindowPos flags that differ per DPI awareness context.
|
|
98
|
+
[DllImport("user32.dll")] public static extern bool MoveWindow(IntPtr h, int x, int y, int w, int hgt, bool repaint);
|
|
99
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
|
100
|
+
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hwnd, IntPtr hdcBlt, uint nFlags);
|
|
101
|
+
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
|
|
102
|
+
[DllImport("user32.dll")] public static extern IntPtr PostMessageW(IntPtr h, uint msg, IntPtr w, IntPtr l);
|
|
103
|
+
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr h, uint cmd);
|
|
104
|
+
[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags);
|
|
105
|
+
[DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr h);
|
|
106
|
+
[DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr h, IntPtr dc);
|
|
107
|
+
[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);
|
|
108
|
+
// Whole-desktop capture: StretchBlt so one call serves both native 1:1 and a token-bounded
|
|
109
|
+
// preview, with HALFTONE so downscaled text stays legible.
|
|
110
|
+
[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);
|
|
111
|
+
[DllImport("gdi32.dll")] public static extern int SetStretchBltMode(IntPtr hdc, int mode);
|
|
112
|
+
[DllImport("gdi32.dll")] public static extern bool SetBrushOrgEx(IntPtr hdc, int x, int y, IntPtr prev);
|
|
113
|
+
|
|
114
|
+
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
|
|
115
|
+
|
|
116
|
+
public class CapResult {
|
|
117
|
+
public string method = "none";
|
|
118
|
+
public bool blank = true;
|
|
119
|
+
public int width = 0;
|
|
120
|
+
public int height = 0;
|
|
121
|
+
public int distinct = 0;
|
|
122
|
+
public byte[] png = null;
|
|
123
|
+
public string error = "";
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
static int Distinct(Bitmap bmp, out bool allTransparent) {
|
|
127
|
+
HashSet<int> seen = new HashSet<int>();
|
|
128
|
+
allTransparent = true;
|
|
129
|
+
int w = bmp.Width, h = bmp.Height;
|
|
130
|
+
if (w <= 0 || h <= 0) return 0;
|
|
131
|
+
int stepX = Math.Max(1, (int)(w / 90));
|
|
132
|
+
int stepY = Math.Max(1, (int)(h / 90));
|
|
133
|
+
BitmapData bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
|
|
134
|
+
try {
|
|
135
|
+
int[] row = new int[w];
|
|
136
|
+
for (int y = 0; y < h; y += stepY) {
|
|
137
|
+
IntPtr ptr = IntPtr.Add(bd.Scan0, y * bd.Stride);
|
|
138
|
+
Marshal.Copy(ptr, row, 0, w);
|
|
139
|
+
for (int x = 0; x < w; x += stepX) {
|
|
140
|
+
int c = row[x];
|
|
141
|
+
if (((c >> 24) & 0xFF) != 0) allTransparent = false;
|
|
142
|
+
if (!seen.Contains(c)) { seen.Add(c); if (seen.Count > 40) return seen.Count; }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
} finally { bmp.UnlockBits(bd); }
|
|
146
|
+
return seen.Count;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/// Whole-desktop capture across the virtual screen (all monitors, negative origins included).
|
|
150
|
+
/// computer_capture could only ever see ONE window, so anything the model needed from the rest
|
|
151
|
+
/// of the screen — a second app, a dialog belonging to another process, the taskbar, a
|
|
152
|
+
/// multi-monitor desktop — was simply absent ("设备屏幕截不全"). This captures the composed
|
|
153
|
+
/// desktop as the user sees it, which is also the honest picture for a self-drawn app that
|
|
154
|
+
/// PrintWindow cannot render.
|
|
155
|
+
public static CapResult CaptureScreen(int maxDim) {
|
|
156
|
+
CapResult res = new CapResult();
|
|
157
|
+
// SM_XVIRTUALSCREEN=76 SM_YVIRTUALSCREEN=77 SM_CXVIRTUALSCREEN=78 SM_CYVIRTUALSCREEN=79.
|
|
158
|
+
// The origin is NOT always 0:0 — a monitor placed left of the primary has a negative X.
|
|
159
|
+
// This inline copy exists because C# cannot call the PowerShell Get-VirtScreen function, which
|
|
160
|
+
// is the AUTHORITATIVE station-size measurement (measured fallback chain, screen_unknown on
|
|
161
|
+
// failure); if the two ever disagree, fix Get-VirtScreen and mirror it here.
|
|
162
|
+
int vx = GetSystemMetrics(76), vy = GetSystemMetrics(77);
|
|
163
|
+
int vw = GetSystemMetrics(78), vh = GetSystemMetrics(79);
|
|
164
|
+
if (vw <= 0 || vh <= 0) { res.error = "virtual screen reports no area (" + vw + "x" + vh + ")"; return res; }
|
|
165
|
+
int w = vw, h = vh;
|
|
166
|
+
if (maxDim > 0) {
|
|
167
|
+
if (w > maxDim) { h = (int)((long)h * maxDim / w); w = maxDim; }
|
|
168
|
+
if (h > maxDim) { w = (int)((long)w * maxDim / h); h = maxDim; }
|
|
169
|
+
}
|
|
170
|
+
if (w < 2) w = 2;
|
|
171
|
+
if (h < 2) h = 2;
|
|
172
|
+
res.width = w; res.height = h;
|
|
173
|
+
using (Bitmap bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb)) {
|
|
174
|
+
using (Graphics g = Graphics.FromImage(bmp)) {
|
|
175
|
+
// Copy from the virtual-screen origin, then let GDI+ scale to the requested bitmap size so
|
|
176
|
+
// one capture serves both "native 1:1" (maxDim=0) and a token-bounded preview.
|
|
177
|
+
IntPtr screen = GetDC(IntPtr.Zero);
|
|
178
|
+
try {
|
|
179
|
+
IntPtr hdc = g.GetHdc();
|
|
180
|
+
try {
|
|
181
|
+
// SetStretchBltMode + HALFTONE keeps downscaled text legible instead of aliasing it.
|
|
182
|
+
SetStretchBltMode(hdc, 4); // HALFTONE
|
|
183
|
+
SetBrushOrgEx(hdc, 0, 0, IntPtr.Zero);
|
|
184
|
+
bool ok = StretchBlt(hdc, 0, 0, w, h, screen, vx, vy, vw, vh, 0x00CC0020u); // SRCCOPY
|
|
185
|
+
if (!ok) res.error = "StretchBlt from the desktop returned false; ";
|
|
186
|
+
} finally { g.ReleaseHdc(hdc); }
|
|
187
|
+
} finally { ReleaseDC(IntPtr.Zero, screen); }
|
|
188
|
+
}
|
|
189
|
+
bool transparent;
|
|
190
|
+
int d = Distinct(bmp, out transparent);
|
|
191
|
+
res.method = "desktop-gdi";
|
|
192
|
+
res.distinct = d;
|
|
193
|
+
res.blank = (d <= 1 || transparent);
|
|
194
|
+
res.png = ToPng(bmp);
|
|
195
|
+
return res;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/// Scale a whole native-size rendering down to the requested token budget.
|
|
200
|
+
/// PrintWindow and BitBlt both paint at the WINDOW's real pixel size: drawing them into a
|
|
201
|
+
/// pre-shrunk bitmap silently kept only the top-left corner of the frame, so every downscaled
|
|
202
|
+
/// window capture was cropped at the right and bottom and every OCR coordinate taken from it
|
|
203
|
+
/// was displaced. Capture at native size, then scale the complete frame.
|
|
204
|
+
static Bitmap Fit(Bitmap src, int w, int h) {
|
|
205
|
+
Bitmap dst = new Bitmap(w, h, PixelFormat.Format32bppArgb);
|
|
206
|
+
using (Graphics g = Graphics.FromImage(dst)) {
|
|
207
|
+
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
|
|
208
|
+
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
|
|
209
|
+
g.DrawImage(src, new Rectangle(0, 0, w, h));
|
|
210
|
+
}
|
|
211
|
+
return dst;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
public static CapResult Capture(IntPtr hwnd, int maxDim) {
|
|
215
|
+
CapResult res = new CapResult();
|
|
216
|
+
RECT r;
|
|
217
|
+
if (!GetWindowRect(hwnd, out r)) { res.error = "GetWindowRect failed"; return res; }
|
|
218
|
+
// Native size is what the window paints at; the target size is only the token budget.
|
|
219
|
+
int nw = r.Right - r.Left, nh = r.Bottom - r.Top;
|
|
220
|
+
if (nw <= 1 || nh <= 1) { res.error = "window has no area (" + nw + "x" + nh + ")"; return res; }
|
|
221
|
+
int w = nw, h = nh;
|
|
222
|
+
// maxDim caps the longer edge to keep the PNG (and its tokens) bounded. maxDim <= 0 means
|
|
223
|
+
// "native": capture at the window's real physical size, 1 image px = 1 screen px (scale = 1).
|
|
224
|
+
if (maxDim > 0) {
|
|
225
|
+
if (w > maxDim) { h = (int)((long)h * maxDim / w); w = maxDim; }
|
|
226
|
+
if (h > maxDim) { w = (int)((long)w * maxDim / h); h = maxDim; }
|
|
227
|
+
}
|
|
228
|
+
if (w < 2) w = 2;
|
|
229
|
+
if (h < 2) h = 2;
|
|
230
|
+
res.width = w; res.height = h;
|
|
231
|
+
|
|
232
|
+
bool transparent;
|
|
233
|
+
// attempt 1: PrintWindow with PW_RENDERFULLCONTENT (2), painted at native size
|
|
234
|
+
using (Bitmap full = new Bitmap(nw, nh, PixelFormat.Format32bppArgb)) {
|
|
235
|
+
using (Graphics g = Graphics.FromImage(full)) {
|
|
236
|
+
IntPtr hdc = g.GetHdc();
|
|
237
|
+
bool ok = PrintWindow(hwnd, hdc, 2);
|
|
238
|
+
g.ReleaseHdc();
|
|
239
|
+
if (!ok) res.error = "PrintWindow(2) returned false; ";
|
|
240
|
+
}
|
|
241
|
+
int d = Distinct(full, out transparent);
|
|
242
|
+
res.method = "printwindow-full"; res.distinct = d;
|
|
243
|
+
res.blank = (d <= 1 || transparent);
|
|
244
|
+
if (!res.blank) {
|
|
245
|
+
using (Bitmap bmp = Fit(full, w, h)) { res.png = ToPng(bmp); }
|
|
246
|
+
return res;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// attempt 2: plain PrintWindow (0), also at native size
|
|
250
|
+
using (Bitmap full2 = new Bitmap(nw, nh, PixelFormat.Format32bppArgb)) {
|
|
251
|
+
using (Graphics g = Graphics.FromImage(full2)) {
|
|
252
|
+
IntPtr hdc = g.GetHdc();
|
|
253
|
+
PrintWindow(hwnd, hdc, 0);
|
|
254
|
+
g.ReleaseHdc();
|
|
255
|
+
}
|
|
256
|
+
int d = Distinct(full2, out transparent);
|
|
257
|
+
if (d > res.distinct) { res.distinct = d; }
|
|
258
|
+
res.method = "printwindow";
|
|
259
|
+
res.blank = (d <= 1 || transparent);
|
|
260
|
+
if (!res.blank) {
|
|
261
|
+
using (Bitmap bmp = Fit(full2, w, h)) { res.png = ToPng(bmp); }
|
|
262
|
+
return res;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
// attempt 3: BitBlt from screen (only what is actually visible), native region then scaled
|
|
266
|
+
using (Bitmap full3 = new Bitmap(nw, nh, PixelFormat.Format32bppArgb)) {
|
|
267
|
+
IntPtr screen = GetDC(IntPtr.Zero);
|
|
268
|
+
using (Graphics g = Graphics.FromImage(full3)) {
|
|
269
|
+
IntPtr hdc = g.GetHdc();
|
|
270
|
+
BitBlt(hdc, 0, 0, nw, nh, screen, r.Left, r.Top, 0x00CC0020u);
|
|
271
|
+
g.ReleaseHdc();
|
|
272
|
+
}
|
|
273
|
+
ReleaseDC(IntPtr.Zero, screen);
|
|
274
|
+
int d = Distinct(full3, out transparent);
|
|
275
|
+
res.method = "bitblt"; res.distinct = d;
|
|
276
|
+
res.blank = (d <= 1 || transparent);
|
|
277
|
+
using (Bitmap bmp = Fit(full3, w, h)) { res.png = ToPng(bmp); }
|
|
278
|
+
return res;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
static byte[] ToPng(Bitmap bmp) {
|
|
283
|
+
using (MemoryStream ms = new MemoryStream()) {
|
|
284
|
+
bmp.Save(ms, ImageFormat.Png);
|
|
285
|
+
return ms.ToArray();
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
public static string ProcName(int pid) {
|
|
290
|
+
try { return Process.GetProcessById(pid).ProcessName; } catch { return ""; }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
[DllImport("user32.dll")] static extern IntPtr SetProcessDpiAwarenessContext(IntPtr ctx);
|
|
294
|
+
static int g_aware = 0;
|
|
295
|
+
// 0 = not applied, 1 = SetProcessDPIAware (system aware), 2 = per-monitor v2 context
|
|
296
|
+
public static int MakeAware() {
|
|
297
|
+
if (g_aware != 0) return g_aware;
|
|
298
|
+
try {
|
|
299
|
+
IntPtr r = SetProcessDpiAwarenessContext(new IntPtr(-4)); // DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
|
|
300
|
+
if (r != IntPtr.Zero) { g_aware = 2; return g_aware; }
|
|
301
|
+
} catch { }
|
|
302
|
+
try { if (SetProcessDPIAware()) { g_aware = 1; return g_aware; } } catch { }
|
|
303
|
+
return 0;
|
|
304
|
+
}
|
|
305
|
+
public static int Awareness { get { return g_aware; } }
|
|
306
|
+
public static int PhysWidth { get { return GetSystemMetrics(0); } }
|
|
307
|
+
public static int PhysHeight { get { return GetSystemMetrics(1); } }
|
|
308
|
+
|
|
309
|
+
// ---- physical pointer channel ---------------------------------------------------------
|
|
310
|
+
// Motion is SendInput with MOUSEEVENTF_ABSOLUTE only. SetCursorPos is deliberately NOT
|
|
311
|
+
// declared anywhere in this file: a pointer that is placed instead of moved produces one
|
|
312
|
+
// observable position instead of a trajectory, and the whole point of this channel is that
|
|
313
|
+
// the trajectory can be measured by an independent sampler.
|
|
314
|
+
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; }
|
|
315
|
+
|
|
316
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
317
|
+
public struct MOUSEINPUT {
|
|
318
|
+
public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo;
|
|
319
|
+
}
|
|
320
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
321
|
+
public struct KEYBDINPUT {
|
|
322
|
+
public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo;
|
|
323
|
+
}
|
|
324
|
+
// Both arms share offset 0 in an explicit union so Marshal.SizeOf(INPUT) stays the native
|
|
325
|
+
// 40 bytes (x64) for mouse AND keyboard events -- SendInput rejects a cbSize that disagrees with
|
|
326
|
+
// sizeof(INPUT), so the keyboard path must reuse the same union, not a smaller struct.
|
|
327
|
+
[StructLayout(LayoutKind.Explicit)]
|
|
328
|
+
public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
|
|
329
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
330
|
+
public struct INPUT { public uint type; public INPUTUNION u; }
|
|
331
|
+
|
|
332
|
+
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
|
|
333
|
+
[DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vKey);
|
|
334
|
+
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
|
|
335
|
+
[DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
|
|
336
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowTextW(IntPtr h, System.Text.StringBuilder buf, int max);
|
|
337
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassNameW(IntPtr h, System.Text.StringBuilder buf, int max);
|
|
338
|
+
[DllImport("winmm.dll")] public static extern uint timeBeginPeriod(uint ms);
|
|
339
|
+
[DllImport("winmm.dll")] public static extern uint timeEndPeriod(uint ms);
|
|
340
|
+
|
|
341
|
+
const uint MF_MOVE = 0x0001u;
|
|
342
|
+
const uint MF_LDOWN = 0x0002u, MF_LUP = 0x0004u;
|
|
343
|
+
const uint MF_RDOWN = 0x0008u, MF_RUP = 0x0010u;
|
|
344
|
+
const uint MF_MDOWN = 0x0020u, MF_MUP = 0x0040u;
|
|
345
|
+
const uint MF_ABSOLUTE = 0x8000u;
|
|
346
|
+
const uint MF_VIRTUALDESK = 0x4000u;
|
|
347
|
+
const uint KF_UNICODE = 0x0004u, KF_KEYUP = 0x0002u;
|
|
348
|
+
|
|
349
|
+
public static int InputByteSize { get { return Marshal.SizeOf(typeof(INPUT)); } }
|
|
350
|
+
|
|
351
|
+
static INPUT MkMouse(int dx, int dy, uint flags, uint data) {
|
|
352
|
+
INPUT i = new INPUT();
|
|
353
|
+
i.type = 0u; // INPUT_MOUSE
|
|
354
|
+
i.u.mi.dx = dx; i.u.mi.dy = dy;
|
|
355
|
+
i.u.mi.mouseData = data; i.u.mi.dwFlags = flags;
|
|
356
|
+
i.u.mi.time = 0u; i.u.mi.dwExtraInfo = IntPtr.Zero;
|
|
357
|
+
return i;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
static INPUT MkKey(ushort vk, ushort scan, uint flags) {
|
|
361
|
+
INPUT i = new INPUT();
|
|
362
|
+
i.type = 1u; // INPUT_KEYBOARD
|
|
363
|
+
i.u.ki.wVk = vk; i.u.ki.wScan = scan; i.u.ki.dwFlags = flags;
|
|
364
|
+
i.u.ki.time = 0u; i.u.ki.dwExtraInfo = IntPtr.Zero;
|
|
365
|
+
return i;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// Type a string into the focused control via KEYEVENTF_UNICODE: each UTF-16 code unit is sent as a
|
|
369
|
+
// down+up pair. This is the only SendInput path that types CJK reliably (VK/SendKeys cannot), which
|
|
370
|
+
// is what "type 你好 into WeChat's box" needs. Returns the number of INPUT events the OS accepted.
|
|
371
|
+
public static int SendUnicode(string s) {
|
|
372
|
+
if (string.IsNullOrEmpty(s)) return 0;
|
|
373
|
+
System.Collections.Generic.List<INPUT> list = new System.Collections.Generic.List<INPUT>();
|
|
374
|
+
foreach (char c in s) {
|
|
375
|
+
list.Add(MkKey(0, c, KF_UNICODE));
|
|
376
|
+
list.Add(MkKey(0, c, KF_UNICODE | KF_KEYUP));
|
|
377
|
+
}
|
|
378
|
+
INPUT[] arr = list.ToArray();
|
|
379
|
+
return (int)SendInput((uint)arr.Length, arr, Marshal.SizeOf(typeof(INPUT)));
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Every event on this path carries ABSOLUTE|VIRTUALDESK|MOVE plus the button bit, so the
|
|
383
|
+
// pointer position is asserted by the same event that presses or releases: a button event
|
|
384
|
+
// can never land somewhere other than the point the caller asked for.
|
|
385
|
+
static uint AbsEvent(int nx, int ny, uint buttonFlags) {
|
|
386
|
+
INPUT[] a = new INPUT[] { MkMouse(nx, ny, MF_ABSOLUTE | MF_VIRTUALDESK | MF_MOVE | buttonFlags, 0u) };
|
|
387
|
+
return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT)));
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
public static uint AbsMove(int nx, int ny) { return AbsEvent(nx, ny, 0u); }
|
|
391
|
+
|
|
392
|
+
public static int DownFlag(string button) {
|
|
393
|
+
if (button == "right") return (int)MF_RDOWN;
|
|
394
|
+
if (button == "middle") return (int)MF_MDOWN;
|
|
395
|
+
return (int)MF_LDOWN;
|
|
396
|
+
}
|
|
397
|
+
public static int UpFlag(string button) {
|
|
398
|
+
if (button == "right") return (int)MF_RUP;
|
|
399
|
+
if (button == "middle") return (int)MF_MUP;
|
|
400
|
+
return (int)MF_LUP;
|
|
401
|
+
}
|
|
402
|
+
public static uint AbsButtonDown(int nx, int ny, string button) { return AbsEvent(nx, ny, (uint)DownFlag(button)); }
|
|
403
|
+
public static uint AbsButtonUp(int nx, int ny, string button) { return AbsEvent(nx, ny, (uint)UpFlag(button)); }
|
|
404
|
+
|
|
405
|
+
const uint MF_WHEEL = 0x0800u, MF_HWHEEL = 0x1000u;
|
|
406
|
+
// Wheel events also carry ABSOLUTE|VIRTUALDESK|MOVE so the scroll happens at the asserted point,
|
|
407
|
+
// same guarantee as the button events. delta is in WHEEL_DELTA units (120/notch), negative = down/left.
|
|
408
|
+
public static uint AbsWheel(int nx, int ny, int delta) {
|
|
409
|
+
INPUT[] a = new INPUT[] { MkMouse(nx, ny, MF_ABSOLUTE | MF_VIRTUALDESK | MF_MOVE | MF_WHEEL, (uint)delta) };
|
|
410
|
+
return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT)));
|
|
411
|
+
}
|
|
412
|
+
public static uint AbsHWheel(int nx, int ny, int delta) {
|
|
413
|
+
INPUT[] a = new INPUT[] { MkMouse(nx, ny, MF_ABSOLUTE | MF_VIRTUALDESK | MF_MOVE | MF_HWHEEL, (uint)delta) };
|
|
414
|
+
return SendInput((uint)a.Length, a, Marshal.SizeOf(typeof(INPUT)));
|
|
415
|
+
}
|
|
416
|
+
// VK key down/up for control keys and hotkeys (Enter/Tab/arrows/Ctrl+C...). KEYEVENTF_KEYUP = 0x2.
|
|
417
|
+
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))); }
|
|
418
|
+
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))); }
|
|
419
|
+
|
|
420
|
+
// one GetCursorPos call, both axes: [0]=x [1]=y, physical pixels for a DPI-aware worker
|
|
421
|
+
public static int[] CursorXY() {
|
|
422
|
+
POINT p = new POINT();
|
|
423
|
+
try { if (!GetCursorPos(out p)) return new int[] { -1, -1 }; } catch { return new int[] { -1, -1 }; }
|
|
424
|
+
return new int[] { p.x, p.y };
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
public class HitInfo {
|
|
428
|
+
public long hit = 0; public long root = 0; public long pid = 0;
|
|
429
|
+
public string hitClass = ""; public string rootClass = ""; public string title = "";
|
|
430
|
+
}
|
|
431
|
+
// What is actually under a screen point right now. The overlay windows this plugin draws are
|
|
432
|
+
// WS_EX_TRANSPARENT, so WindowFromPoint skips them and the answer is the real target window.
|
|
433
|
+
public static HitInfo HitTest(int x, int y) {
|
|
434
|
+
HitInfo r = new HitInfo();
|
|
435
|
+
POINT p = new POINT(); p.x = x; p.y = y;
|
|
436
|
+
IntPtr h = IntPtr.Zero;
|
|
437
|
+
try { h = WindowFromPoint(p); } catch { h = IntPtr.Zero; }
|
|
438
|
+
r.hit = (h == IntPtr.Zero ? 0 : h.ToInt64());
|
|
439
|
+
IntPtr root = RootOf(h);
|
|
440
|
+
r.root = (root == IntPtr.Zero ? 0 : root.ToInt64());
|
|
441
|
+
r.hitClass = ClassOf(h);
|
|
442
|
+
r.rootClass = ClassOf(root);
|
|
443
|
+
r.title = TitleOf(root);
|
|
444
|
+
uint pid = 0;
|
|
445
|
+
try { GetWindowThreadProcessId(root, out pid); } catch { pid = 0; }
|
|
446
|
+
r.pid = pid;
|
|
447
|
+
return r;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
public static IntPtr WindowUnder(int x, int y) {
|
|
451
|
+
POINT p = new POINT(); p.x = x; p.y = y;
|
|
452
|
+
try { return WindowFromPoint(p); } catch { return IntPtr.Zero; }
|
|
453
|
+
}
|
|
454
|
+
public static IntPtr RootOf(IntPtr h) {
|
|
455
|
+
if (h == IntPtr.Zero) return IntPtr.Zero;
|
|
456
|
+
try { IntPtr r = GetAncestor(h, 2u); return (r == IntPtr.Zero) ? h : r; } catch { return h; }
|
|
457
|
+
}
|
|
458
|
+
// self-or-descendant: is `node` the ancestor itself or living inside it (GA_PARENT walk)?
|
|
459
|
+
public static bool IsSelfOrDescendant(IntPtr node, IntPtr ancestor) {
|
|
460
|
+
if (node == IntPtr.Zero || ancestor == IntPtr.Zero) return false;
|
|
461
|
+
IntPtr cur = node;
|
|
462
|
+
for (int i = 0; i < 40 && cur != IntPtr.Zero; i++) {
|
|
463
|
+
if (cur == ancestor) return true;
|
|
464
|
+
IntPtr par;
|
|
465
|
+
try { par = GetAncestor(cur, 1u); } catch { break; } // GA_PARENT
|
|
466
|
+
if (par == IntPtr.Zero || par == cur) break;
|
|
467
|
+
cur = par;
|
|
468
|
+
}
|
|
469
|
+
return false;
|
|
470
|
+
}
|
|
471
|
+
public static string TitleOf(IntPtr h) {
|
|
472
|
+
if (h == IntPtr.Zero) return "";
|
|
473
|
+
System.Text.StringBuilder sb = new System.Text.StringBuilder(512);
|
|
474
|
+
try { GetWindowTextW(h, sb, sb.Capacity); } catch { return ""; }
|
|
475
|
+
return sb.ToString();
|
|
476
|
+
}
|
|
477
|
+
public static string ClassOf(IntPtr h) {
|
|
478
|
+
if (h == IntPtr.Zero) return "";
|
|
479
|
+
System.Text.StringBuilder sb = new System.Text.StringBuilder(256);
|
|
480
|
+
try { GetClassNameW(h, sb, sb.Capacity); } catch { return ""; }
|
|
481
|
+
return sb.ToString();
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// win32 truth about where the input focus and the caret actually are. Used to prove that a
|
|
485
|
+
// physical click landed in a document, rather than only proving that an event was queued.
|
|
486
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
487
|
+
public struct GUITHREADINFO {
|
|
488
|
+
public int cbSize; public int flags;
|
|
489
|
+
public IntPtr hwndActive; public IntPtr hwndFocus; public IntPtr hwndCapture;
|
|
490
|
+
public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize; public IntPtr hwndCaret;
|
|
491
|
+
public RECT rcCaret;
|
|
492
|
+
}
|
|
493
|
+
[DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint idThread, out GUITHREADINFO r);
|
|
494
|
+
[DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h, ref POINT p);
|
|
495
|
+
// rcCaret is client-relative for some providers (Win11 Notepad's RichEditD2DPT is one) and
|
|
496
|
+
// screen-absolute for others, so both readings are returned and the caller can tell which one
|
|
497
|
+
// lines up with the element it is looking at.
|
|
498
|
+
public static int[] ClientToScreenPt(long hwnd, int x, int y) {
|
|
499
|
+
POINT p = new POINT(); p.x = x; p.y = y;
|
|
500
|
+
try { if (hwnd != 0 && ClientToScreen(new IntPtr(hwnd), ref p)) return new int[] { p.x, p.y }; } catch { }
|
|
501
|
+
return new int[] { x, y };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
public class CaretInfo {
|
|
505
|
+
public long hwndFocus = 0; public long hwndCaret = 0; public long tid = 0;
|
|
506
|
+
public int x = 0; public int y = 0; public int w = 0; public int h = 0;
|
|
507
|
+
public int sx = 0; public int sy = 0;
|
|
508
|
+
public bool hasCaret = false;
|
|
509
|
+
}
|
|
510
|
+
// The second instrument for "the click landed": UIA reports which element has focus,
|
|
511
|
+
// GetGUIThreadInfo reports which window owns the caret and where the system put it.
|
|
512
|
+
public static CaretInfo FindCaret(int pid) {
|
|
513
|
+
CaretInfo r = new CaretInfo();
|
|
514
|
+
try {
|
|
515
|
+
Process p = Process.GetProcessById(pid);
|
|
516
|
+
foreach (ProcessThread pt in p.Threads) {
|
|
517
|
+
GUITHREADINFO g = new GUITHREADINFO();
|
|
518
|
+
g.cbSize = Marshal.SizeOf(typeof(GUITHREADINFO));
|
|
519
|
+
bool got = false;
|
|
520
|
+
try { got = GetGUIThreadInfo((uint)pt.Id, out g); } catch { got = false; }
|
|
521
|
+
if (!got) continue;
|
|
522
|
+
if (g.hwndFocus == IntPtr.Zero && g.hwndCaret == IntPtr.Zero) continue;
|
|
523
|
+
r.hwndFocus = g.hwndFocus.ToInt64();
|
|
524
|
+
r.hwndCaret = g.hwndCaret.ToInt64();
|
|
525
|
+
r.x = g.rcCaret.Left; r.y = g.rcCaret.Top;
|
|
526
|
+
r.w = g.rcCaret.Right - g.rcCaret.Left; r.h = g.rcCaret.Bottom - g.rcCaret.Top;
|
|
527
|
+
int[] sc = ClientToScreenPt(r.hwndCaret, r.x, r.y);
|
|
528
|
+
r.sx = sc[0]; r.sy = sc[1];
|
|
529
|
+
r.tid = pt.Id;
|
|
530
|
+
r.hasCaret = (g.hwndCaret != IntPtr.Zero);
|
|
531
|
+
if (g.hwndCaret != IntPtr.Zero) break; // prefer the thread that actually owns a caret
|
|
532
|
+
}
|
|
533
|
+
} catch { }
|
|
534
|
+
return r;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
'@
|
|
538
|
+
$script:nativeMs = 0
|
|
539
|
+
$t0 = [Diagnostics.Stopwatch]::GetTimestamp()
|
|
540
|
+
$script:nativeLoaded = $false
|
|
541
|
+
$script:dpiMode = 0
|
|
542
|
+
try {
|
|
543
|
+
Add-Type -TypeDefinition $script:nativeSrc -ReferencedAssemblies @('System.Drawing', 'System.Core') -ErrorAction Stop
|
|
544
|
+
$script:nativeLoaded = $true
|
|
545
|
+
} catch {
|
|
546
|
+
Log ('Add-Type native helper failed: ' + $_.Exception.Message)
|
|
547
|
+
}
|
|
548
|
+
if ($script:nativeLoaded) {
|
|
549
|
+
try { $script:dpiMode = [Native]::MakeAware() } catch { Log ('MakeAware threw: ' + $_.Exception.Message) }
|
|
550
|
+
}
|
|
551
|
+
$script:nativeMs = [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $t0) / 10000.0, 1)
|
|
552
|
+
|
|
553
|
+
# ---------------------------------------------------------------- parts
|
|
554
|
+
# The body lives in worker/lib/. This entry keeps only process-level setup: the shared state map,
|
|
555
|
+
# the assemblies, the native helper class and the stdio loop. The order below is the one
|
|
556
|
+
# scripts/lib/sources.mjs declares (WORKER_FILES), and the gates read that list, so a part
|
|
557
|
+
# cannot exist on one side only. Dot-sourcing shares this script scope, which is what lets any
|
|
558
|
+
# part use $script:W or call any function from any other part. Assemblies are loaded BEFORE the
|
|
559
|
+
# parts: 02-uia.ps1 has a top-level pattern table that names UIA types at load time.
|
|
560
|
+
$workerParts = @(
|
|
561
|
+
'01-core.ps1'
|
|
562
|
+
'02-uia.ps1'
|
|
563
|
+
'03-window.ps1'
|
|
564
|
+
'04-match.ps1'
|
|
565
|
+
'05-value.ps1'
|
|
566
|
+
'06-snapshot.ps1'
|
|
567
|
+
'07-action.ps1'
|
|
568
|
+
'08-command.ps1'
|
|
569
|
+
'09-pointer.ps1'
|
|
570
|
+
'10-dispatch.ps1'
|
|
571
|
+
)
|
|
572
|
+
foreach ($part in $workerParts) {
|
|
573
|
+
$partPath = Join-Path $PSScriptRoot ('lib\' + $part)
|
|
574
|
+
if (-not (Test-Path -LiteralPath $partPath)) { throw ('missing worker part: ' + $partPath) }
|
|
575
|
+
. $partPath
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
Log ("ready ps=" + $PSVersionTable.PSVersion.ToString() + " assemblies=" + $script:asmMs + 'ms native=' + $script:nativeMs + 'ms pid=' + $PID)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
Log 'listening on stdin'
|
|
582
|
+
$alive = $true
|
|
583
|
+
try {
|
|
584
|
+
while ($alive) {
|
|
585
|
+
$line = [Console]::In.ReadLine()
|
|
586
|
+
if ($null -eq $line) { Log 'stdin EOF, exiting'; break }
|
|
587
|
+
if ($line.Trim().Length -eq 0) { continue }
|
|
588
|
+
$alive = Invoke-Request $line
|
|
589
|
+
}
|
|
590
|
+
} catch {
|
|
591
|
+
Log ('FATAL: ' + $_.Exception.Message)
|
|
592
|
+
try { Send-Err 0 'internal_error' ('worker loop died: ' + $_.Exception.Message) } catch { }
|
|
593
|
+
Cleanup-All
|
|
594
|
+
exit 2
|
|
595
|
+
}
|
|
596
|
+
exit 0
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
|