dsh-windows-parallel-mcp 0.0.1 → 0.1.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/INSTALL.md +84 -0
- package/README.md +114 -7
- package/cordis.patch.yml +15 -0
- package/docs/refusals.md +67 -0
- package/dsh.plugin.json +18 -0
- package/lib/config.js +125 -0
- package/lib/engine.js +225 -0
- package/lib/host-tools.js +138 -0
- package/lib/index.js +330 -0
- package/lib/peers-schemastery.js +17 -0
- package/lib/peers-tools.js +6 -0
- package/package.json +46 -11
- package/src/engine/decide.ps1 +155 -0
- package/src/engine/engine.ps1 +313 -0
- package/src/engine/overlay.ps1 +368 -0
- package/src/engine/win.ps1 +581 -0
- package/src/engine/worker.ps1 +156 -0
- package/src/schema/tools.json +205 -0
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
# win.ps1 -- the IO half of the R2' engine: probe a target's doors, act through the cheapest
|
|
2
|
+
# door it has, and put the owner's focus back when the action cost them a flash.
|
|
3
|
+
#
|
|
4
|
+
# Layering is deliberate. decide.ps1 owns every judgement (pure, unit-tested). This file owns
|
|
5
|
+
# every syscall and no judgement: it reports facts, and it executes what it is told. When a
|
|
6
|
+
# behaviour is wrong, the question is then 'was the fact wrong or the table wrong', and those
|
|
7
|
+
# live in different files with different tests.
|
|
8
|
+
#
|
|
9
|
+
# WHAT THIS FILE REFUSES TO DO, because the stance predates the code:
|
|
10
|
+
# * no SendInput / keybd_event / mouse_event -- no physical injection, not even as a fallback
|
|
11
|
+
# * no forged Alt key to defeat the foreground lock (it works; it also drops the owner's next
|
|
12
|
+
# keystroke into whichever window the trick raised)
|
|
13
|
+
# * no acting on a window this process did not create, UNLESS it was named as the target by
|
|
14
|
+
# hwnd -- and the restore path only ever reverses an activation this process caused
|
|
15
|
+
#
|
|
16
|
+
# All coordinates crossing this boundary are SCREEN pixels. Client-space conversion happens only
|
|
17
|
+
# at the moment a message is posted to a child window, because lParam for WM_LBUTTONDOWN is
|
|
18
|
+
# child-relative and getting that wrong clicks the title bar instead of the control.
|
|
19
|
+
|
|
20
|
+
Set-StrictMode -Version 2.0
|
|
21
|
+
|
|
22
|
+
Add-Type -AssemblyName WindowsBase
|
|
23
|
+
Add-Type -AssemblyName UIAutomationClient
|
|
24
|
+
Add-Type -AssemblyName UIAutomationTypes
|
|
25
|
+
|
|
26
|
+
if (-not ('WpmWin' -as [type])) {
|
|
27
|
+
Add-Type -TypeDefinition @'
|
|
28
|
+
using System;
|
|
29
|
+
using System.Collections.Generic;
|
|
30
|
+
using System.Runtime.InteropServices;
|
|
31
|
+
using System.Text;
|
|
32
|
+
using System.Threading;
|
|
33
|
+
|
|
34
|
+
public static class WpmWin
|
|
35
|
+
{
|
|
36
|
+
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
|
|
37
|
+
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
|
|
38
|
+
[StructLayout(LayoutKind.Sequential)] public struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
|
|
39
|
+
[StructLayout(LayoutKind.Sequential)] public struct GUITHREADINFO
|
|
40
|
+
{
|
|
41
|
+
public uint cbSize; public uint flags; public IntPtr hwndActive; public IntPtr hwndFocus;
|
|
42
|
+
public IntPtr hwndCapture; public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize;
|
|
43
|
+
public IntPtr hwndCaret; public RECT rcCaret;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
public delegate bool EnumProc(IntPtr h, IntPtr l);
|
|
47
|
+
|
|
48
|
+
[DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr l);
|
|
49
|
+
[DllImport("user32.dll")] public static extern bool EnumChildWindows(IntPtr parent, EnumProc cb, IntPtr l);
|
|
50
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassNameW(IntPtr h, StringBuilder s, int n);
|
|
51
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
|
|
52
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
|
|
53
|
+
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
|
|
54
|
+
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
|
|
55
|
+
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
|
|
56
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
|
57
|
+
|
|
58
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
59
|
+
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
|
60
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
|
|
61
|
+
[DllImport("user32.dll")] static extern bool AttachThreadInput(uint attach, uint to, bool join);
|
|
62
|
+
[DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();
|
|
63
|
+
[DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint tid, ref GUITHREADINFO gti);
|
|
64
|
+
|
|
65
|
+
[DllImport("user32.dll")] public static extern IntPtr SendMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
|
|
66
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageStrW(IntPtr h, uint m, IntPtr w, string l);
|
|
67
|
+
[DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
|
|
68
|
+
|
|
69
|
+
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
|
|
70
|
+
[DllImport("user32.dll")] public static extern IntPtr ChildWindowFromPointEx(IntPtr h, POINT p, uint flags);
|
|
71
|
+
[DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr h, ref POINT p);
|
|
72
|
+
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
|
|
73
|
+
[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr h, uint flags);
|
|
74
|
+
|
|
75
|
+
[DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO l);
|
|
76
|
+
[DllImport("kernel32.dll")] static extern ulong GetTickCount64();
|
|
77
|
+
|
|
78
|
+
// ---- integrity level: the REAL elevated_target check -------------------------------------
|
|
79
|
+
// The old comment in Get-WpmFacts said this was deliberately unwired because "a wrong check is
|
|
80
|
+
// worse than none". That is still true, which is why the check below is the documented,
|
|
81
|
+
// side-effect-free one: OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION) -> GetTokenInformation
|
|
82
|
+
// (TokenIntegrityLevel) -> the RID's last sub-authority. No writes, no SeDebug privilege, and
|
|
83
|
+
// it degrades to -1 (unknown) on any failure -- unknown is NOT treated as elevated, because
|
|
84
|
+
// that would refuse every window the moment a handle read failed, which is the opposite wrong
|
|
85
|
+
// check. Unknown instead falls through to the door probe, and a genuinely elevated target then
|
|
86
|
+
// simply produces no effect, which the app-side verification reports as unverified.
|
|
87
|
+
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
|
|
88
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
|
|
89
|
+
[DllImport("advapi32.dll")] static extern bool OpenProcessToken(IntPtr p, uint access, out IntPtr tok);
|
|
90
|
+
[DllImport("advapi32.dll", SetLastError = true)]
|
|
91
|
+
static extern bool GetTokenInformation(IntPtr tok, int cls, IntPtr info, uint len, out uint need);
|
|
92
|
+
[DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr h);
|
|
93
|
+
|
|
94
|
+
const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
|
|
95
|
+
const uint TOKEN_QUERY = 0x0008;
|
|
96
|
+
const int TokenIntegrityLevel = 25;
|
|
97
|
+
|
|
98
|
+
/// <summary>Integrity RID of a pid: 0x1000 low, 0x2000 medium, 0x3000 high, 0x4000 system. -1 = unknown.</summary>
|
|
99
|
+
public static long IntegrityOf(uint pid)
|
|
100
|
+
{
|
|
101
|
+
IntPtr proc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
|
|
102
|
+
if (proc == IntPtr.Zero) return -1;
|
|
103
|
+
try
|
|
104
|
+
{
|
|
105
|
+
IntPtr tok;
|
|
106
|
+
if (!OpenProcessToken(proc, TOKEN_QUERY, out tok)) return -1;
|
|
107
|
+
try
|
|
108
|
+
{
|
|
109
|
+
uint need;
|
|
110
|
+
// Two-pass: the SIZE-PROBE call is DOCUMENTED to fail -- it returns FALSE with
|
|
111
|
+
// ERROR_INSUFFICIENT_BUFFER and fills `needed`. Treating that false as a dead end
|
|
112
|
+
// made every read come back unknown on the first run of test/integrity-probe.ps1,
|
|
113
|
+
// which is exactly how a 'wrong check is worse than none' failure looks in the wild:
|
|
114
|
+
// the flag stayed false everywhere, so nothing was refused and nothing was claimed.
|
|
115
|
+
// The real condition is `needed > 0`, not the return value.
|
|
116
|
+
GetTokenInformation(tok, TokenIntegrityLevel, IntPtr.Zero, 0, out need);
|
|
117
|
+
if (need == 0) return -1;
|
|
118
|
+
IntPtr buf = Marshal.AllocHGlobal((int)need);
|
|
119
|
+
try
|
|
120
|
+
{
|
|
121
|
+
if (!GetTokenInformation(tok, TokenIntegrityLevel, buf, need, out need)) return -1;
|
|
122
|
+
// TOKEN_MANDATORY_LABEL { SID_AND_ATTRIBUTES Label }; Label.Sid is at offset 0.
|
|
123
|
+
IntPtr sid = Marshal.ReadIntPtr(buf);
|
|
124
|
+
if (sid == IntPtr.Zero) return -1;
|
|
125
|
+
// SID layout: Revision(1) | SubAuthorityCount(1) | IdentifierAuthority(6) |
|
|
126
|
+
// SubAuthority(4*n). The integrity RID is the LAST sub-authority.
|
|
127
|
+
//
|
|
128
|
+
// GetLengthSid was the first attempt and is NOT used: on this host it returns
|
|
129
|
+
// TRUE with length 0 for a SID whose bytes read back correctly (revision 1,
|
|
130
|
+
// count 1, authority 0x10, RID 0x2000 = medium) -- a silent contradiction that
|
|
131
|
+
// made every read come back unknown. The length is therefore computed from the
|
|
132
|
+
// SID's own header, which is the authoritative source anyway. Two wrong
|
|
133
|
+
// behaviours this replaced, both discovered only by measuring: trusting the
|
|
134
|
+
// size-probe's return value, and trusting GetLengthSid's output.
|
|
135
|
+
int rev = Marshal.ReadByte(sid, 0);
|
|
136
|
+
int count = Marshal.ReadByte(sid, 1);
|
|
137
|
+
if (rev != 1 || count < 1 || count > 15) return -1;
|
|
138
|
+
int needed = 8 + 4 * count;
|
|
139
|
+
if (needed > (int)need) return -1; // header claims more than the buffer holds
|
|
140
|
+
// The integrity RID is the LAST sub-authority.
|
|
141
|
+
return (long)BitConverter.ToUInt32(
|
|
142
|
+
new byte[] { Marshal.ReadByte(sid, 8 + 4 * (count - 1)),
|
|
143
|
+
Marshal.ReadByte(sid, 9 + 4 * (count - 1)),
|
|
144
|
+
Marshal.ReadByte(sid, 10 + 4 * (count - 1)),
|
|
145
|
+
Marshal.ReadByte(sid, 11 + 4 * (count - 1)) }, 0);
|
|
146
|
+
}
|
|
147
|
+
finally { Marshal.FreeHGlobal(buf); }
|
|
148
|
+
}
|
|
149
|
+
finally { CloseHandle(tok); }
|
|
150
|
+
}
|
|
151
|
+
finally { CloseHandle(proc); }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/// <summary>Whether the target outruns us. Equal integrity is NOT elevated for our purposes.</summary>
|
|
155
|
+
public static bool IsElevatedTarget(uint pid)
|
|
156
|
+
{
|
|
157
|
+
long mine = IntegrityOf((uint)System.Diagnostics.Process.GetCurrentProcess().Id);
|
|
158
|
+
long theirs = IntegrityOf(pid);
|
|
159
|
+
if (mine < 0 || theirs < 0) return false; // unknown never claims elevated
|
|
160
|
+
return theirs > mine;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// ---- overlay support: ex-styles, hotkey, and the cross-thread control board --------------
|
|
164
|
+
// WpmCtl is the ONE shared state between the worker's main thread (stdin/protocol/actions)
|
|
165
|
+
// and the overlay thread (WPF dispatcher, global hotkey). A PowerShell script variable is
|
|
166
|
+
// not visible across runspaces, so a static holder is the honest shape; the bools are
|
|
167
|
+
// volatile because the hotkey handler writes them from another thread while actions read
|
|
168
|
+
// them mid-flight.
|
|
169
|
+
[DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr h, int i);
|
|
170
|
+
[DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr h, int i, int v);
|
|
171
|
+
[DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr h, int id, uint mods, uint vk);
|
|
172
|
+
[DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr h, int id);
|
|
173
|
+
|
|
174
|
+
public const int GWL_EXSTYLE = -20;
|
|
175
|
+
public const int WS_EX_TOPMOST = 0x00000008;
|
|
176
|
+
public const int WS_EX_TRANSPARENT = 0x00000020;
|
|
177
|
+
public const int WS_EX_LAYERED = 0x00080000;
|
|
178
|
+
public const int WS_EX_NOACTIVATE = 0x08000000;
|
|
179
|
+
public const int WM_HOTKEY = 0x0312;
|
|
180
|
+
public const int WM_CLOSE = 0x0010;
|
|
181
|
+
public const uint MOD_CONTROL = 0x0002;
|
|
182
|
+
public const uint MOD_ALT = 0x0001;
|
|
183
|
+
|
|
184
|
+
[DllImport("user32.dll", SetLastError=true)] static extern bool SetProcessDPIAware();
|
|
185
|
+
[DllImport("user32.dll", SetLastError=true)] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr ctx);
|
|
186
|
+
|
|
187
|
+
/// <summary>
|
|
188
|
+
/// Declare this process DPI aware, BEFORE any window exists.
|
|
189
|
+
/// Why this is not cosmetic: PowerShell starts DPI UNAWARE, so Windows virtualises every
|
|
190
|
+
/// coordinate it passes to user32. The engine receives PHYSICAL screen pixels (that is what a
|
|
191
|
+
/// click point is), the marker is placed through the same user32 -- and with an unaware process
|
|
192
|
+
/// a target of (470,410) rendered the marker at (303,263), exactly /1.5 on this 150% display.
|
|
193
|
+
/// Two components, one coordinate space, or the AI cursor points at the wrong place while every
|
|
194
|
+
/// style assertion still passes. Must run before any window is created (per-process setting);
|
|
195
|
+
/// returns false when the manifest already set it, which is success, not failure.
|
|
196
|
+
/// </summary>
|
|
197
|
+
public static bool EnsureDpiAware() {
|
|
198
|
+
try { SetThreadDpiAwarenessContext(new IntPtr(-4)); } catch { } // PER_MONITOR_AWARE_V2
|
|
199
|
+
try { return SetProcessDPIAware(); } catch { return false; }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
|
|
203
|
+
public const uint SWP_NOZORDER = 0x0004;
|
|
204
|
+
public const uint SWP_NOACTIVATE = 0x0010;
|
|
205
|
+
|
|
206
|
+
/// <summary>
|
|
207
|
+
/// Move a window in PHYSICAL pixels without activating it or changing its z-order.
|
|
208
|
+
/// This exists instead of WPF's Window.Left/Top because WPF's units are device independent while
|
|
209
|
+
/// every coordinate this product receives from Win32 is physical. Measured on this machine
|
|
210
|
+
/// (150% display): setting Left/Top put the marker at (303,263) for a target of (470,410) -- the
|
|
211
|
+
/// DIP conversion and the window's actual rendering disagreed by the scale factor, and no amount
|
|
212
|
+
/// of matrix arithmetic inside the process fixes a process-wide DPI-awareness mismatch.
|
|
213
|
+
/// SetWindowPos takes the same units the caller has, so there is nothing left to guess.
|
|
214
|
+
/// </summary>
|
|
215
|
+
public static bool MoveNoActivate(IntPtr h, int x, int y, int cx, int cy) {
|
|
216
|
+
return SetWindowPos(h, IntPtr.Zero, x, y, cx, cy, SWP_NOZORDER | SWP_NOACTIVATE);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/// <summary>Add ex-style bits and return the new value (the trio lives here, once).</summary>
|
|
220
|
+
public static int AddExStyles(IntPtr h, int bits) {
|
|
221
|
+
int v = GetWindowLong(h, GWL_EXSTYLE);
|
|
222
|
+
SetWindowLong(h, GWL_EXSTYLE, v | bits);
|
|
223
|
+
return v | bits;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
public const int SW_MINIMIZE = 6;
|
|
227
|
+
public const int SW_SHOWNA = 8;
|
|
228
|
+
public const int SW_RESTORE = 9;
|
|
229
|
+
|
|
230
|
+
public static string Cls(IntPtr h) { var s = new StringBuilder(512); GetClassNameW(h, s, s.Capacity); return s.ToString(); }
|
|
231
|
+
public static string Txt(IntPtr h) { var s = new StringBuilder(1024); GetWindowTextW(h, s, s.Capacity); return s.ToString(); }
|
|
232
|
+
public static string Fg() { return GetForegroundWindow().ToInt64().ToString(); }
|
|
233
|
+
public static IntPtr FgHandle() { return GetForegroundWindow(); }
|
|
234
|
+
public static string Cursor() { POINT p; GetCursorPos(out p); return p.X + "," + p.Y; }
|
|
235
|
+
public static uint PidOf(IntPtr h) { uint p; GetWindowThreadProcessId(h, out p); return p; }
|
|
236
|
+
public static IntPtr Root(IntPtr h) { IntPtr r = GetAncestor(h, 2); return r == IntPtr.Zero ? h : r; }
|
|
237
|
+
|
|
238
|
+
public static List<long> Children(IntPtr parent)
|
|
239
|
+
{
|
|
240
|
+
var acc = new List<long>();
|
|
241
|
+
EnumChildWindows(parent, delegate (IntPtr h, IntPtr l) { if (IsWindowVisible(h)) acc.Add(h.ToInt64()); return true; }, IntPtr.Zero);
|
|
242
|
+
return acc;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Age of the last physical input, in ms; -1 when the call fails. Callers must treat -1 as
|
|
246
|
+
// UNKNOWN rather than as 'idle' -- counting unknown as idle is how a software-caused change
|
|
247
|
+
// gets laundered into 'the owner was away'.
|
|
248
|
+
public static long LastInputAgeMs()
|
|
249
|
+
{
|
|
250
|
+
LASTINPUTINFO i = new LASTINPUTINFO();
|
|
251
|
+
i.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
|
|
252
|
+
if (!GetLastInputInfo(ref i)) return -1;
|
|
253
|
+
uint now = (uint)(GetTickCount64() & 0xFFFFFFFF);
|
|
254
|
+
return (long)((now - i.dwTime) & 0xFFFFFFFF);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// hwndActive / hwndFocus for the foreground thread. hwndFocus is the CONTROL inside the
|
|
258
|
+
// window; that distinction is what makes 'the window came back' testable separately from
|
|
259
|
+
// 'the caret came back'.
|
|
260
|
+
public static long[] GuiFocusOfForeground()
|
|
261
|
+
{
|
|
262
|
+
GUITHREADINFO g = new GUITHREADINFO();
|
|
263
|
+
g.cbSize = (uint)Marshal.SizeOf(typeof(GUITHREADINFO));
|
|
264
|
+
IntPtr fg = GetForegroundWindow();
|
|
265
|
+
uint pid; uint tid = GetWindowThreadProcessId(fg, out pid);
|
|
266
|
+
if (!GetGUIThreadInfo(tid, ref g)) return new long[] { 0, 0, 0 };
|
|
267
|
+
return new long[] { g.hwndActive.ToInt64(), g.hwndFocus.ToInt64(), (long)tid };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Restore the foreground to a window we previously took it from. Joins the input queue of the
|
|
271
|
+
// thread that OWNS THE CURRENT foreground (the documented unlock) rather than of the window
|
|
272
|
+
// being restored to -- the earlier failure in this repo was joining the wrong one and
|
|
273
|
+
// concluding the door was locked.
|
|
274
|
+
public static string RestoreForeground(IntPtr want)
|
|
275
|
+
{
|
|
276
|
+
IntPtr cur = GetForegroundWindow();
|
|
277
|
+
uint pid; uint tid = GetWindowThreadProcessId(cur, out pid);
|
|
278
|
+
bool joined = AttachThreadInput(GetCurrentThreadId(), tid, true);
|
|
279
|
+
bool ok = false;
|
|
280
|
+
try { ok = SetForegroundWindow(want); }
|
|
281
|
+
finally { if (joined) AttachThreadInput(GetCurrentThreadId(), tid, false); }
|
|
282
|
+
Thread.Sleep(40);
|
|
283
|
+
return (ok ? "true" : "false") + "|" + (joined ? "true" : "false") + "|" + GetForegroundWindow().ToInt64();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Click a child control by POSTING mouse messages inside it. lParam is child-relative, which
|
|
287
|
+
// is why the conversion happens here and not at the call site.
|
|
288
|
+
public static string MessageClick(IntPtr child, int screenX, int screenY)
|
|
289
|
+
{
|
|
290
|
+
POINT p = new POINT(); p.X = screenX; p.Y = screenY;
|
|
291
|
+
if (!ScreenToClient(child, ref p)) return "convert-failed";
|
|
292
|
+
IntPtr lp = (IntPtr)((p.Y * 0x10000) + (p.X & 0xFFFF));
|
|
293
|
+
SendMessageW(child, 0x0201, (IntPtr)1, lp);
|
|
294
|
+
Thread.Sleep(30);
|
|
295
|
+
SendMessageW(child, 0x0202, IntPtr.Zero, lp);
|
|
296
|
+
return "ok|" + p.X + "," + p.Y;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
public static string MessageText(IntPtr child, string text, bool replace)
|
|
300
|
+
{
|
|
301
|
+
if (!replace)
|
|
302
|
+
{
|
|
303
|
+
for (int i = 0; i < text.Length; i++) SendMessageW(child, 0x0102, (IntPtr)text[i], IntPtr.Zero);
|
|
304
|
+
return "char|" + text.Length;
|
|
305
|
+
}
|
|
306
|
+
SendMessageStrW(child, 0x000C, IntPtr.Zero, text);
|
|
307
|
+
return "settext|" + text.Length;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
'@
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (-not ('WpmCtl' -as [type])) {
|
|
314
|
+
Add-Type -TypeDefinition @'
|
|
315
|
+
using System;
|
|
316
|
+
public static class WpmCtl {
|
|
317
|
+
public static volatile bool Paused = false;
|
|
318
|
+
public static volatile bool OverlayOn = false;
|
|
319
|
+
public static volatile bool HotkeyOk = false;
|
|
320
|
+
// The chord that ACTUALLY registered, not the one the docs promise: on this machine Ctrl+Alt+Q
|
|
321
|
+
// is already owned by another app (RegisterHotKey -> 1409, measured in
|
|
322
|
+
// scripts/hotkey-availability.ps1, 7/8 other candidates free). A silent fallback would make the
|
|
323
|
+
// README's "Ctrl+Alt+Q" untrue with nothing to notice; the real chord is reported instead.
|
|
324
|
+
public static string HotkeyLabel = "";
|
|
325
|
+
// Marker placement travels through these fields INSTEAD of a cross-thread Dispatcher.Invoke.
|
|
326
|
+
// Measured (.tmp/ov-seg.log): Invoke(priority, Action) from the worker's thread cost 1818ms and
|
|
327
|
+
// sometimes never returned -- the delegate is a PowerShell scriptblock and the overlay thread is
|
|
328
|
+
// already inside Dispatcher.Run(), so the engine has to reach a runspace that is busy. Writing
|
|
329
|
+
// three fields costs nothing, and the overlay's own pump applies them from its own thread.
|
|
330
|
+
public static volatile int MarkerX = -1;
|
|
331
|
+
public static volatile int MarkerY = -1;
|
|
332
|
+
public static volatile bool MarkerHide = false;
|
|
333
|
+
public static volatile int MarkerSeq = 0; // incremented per request; the pump compares it
|
|
334
|
+
// volatile is illegal on long in C# (the compiler rejects it, which is the point: a 64-bit
|
|
335
|
+
// read is not guaranteed atomic). The hwnd is written once before any reader exists and read
|
|
336
|
+
// as a value, so plain static is honest here; Interlocked would be the answer if it changed.
|
|
337
|
+
public static long OverlayHwnd = 0;
|
|
338
|
+
public static string Reason = "";
|
|
339
|
+
public static object Dispatcher = null; // overlay thread's WPF dispatcher (set by that thread)
|
|
340
|
+
public static object Window = null; // the marker window (touched ONLY on its own thread)
|
|
341
|
+
public static object Timer = null; // auto-hide timer (same rule)
|
|
342
|
+
}
|
|
343
|
+
'@
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
# Before anything can create a window. See EnsureDpiAware: an unaware process virtualises the same
|
|
347
|
+
# coordinates the engine uses for clicks, which is how the marker ended up off by the display scale.
|
|
348
|
+
$script:WpmDpiAware = [WpmWin]::EnsureDpiAware()
|
|
349
|
+
|
|
350
|
+
$script:WpmUia = $null
|
|
351
|
+
function Get-WpmUiaCached {
|
|
352
|
+
# Each pattern type is resolved independently and a missing one is simply absent from the table.
|
|
353
|
+
# The first version built the table in one literal, and on this runtime
|
|
354
|
+
# [System.Windows.Automation.LegacyIAccessiblePattern] does not exist -- so the constructor threw,
|
|
355
|
+
# the table came back empty, every target reported 'no pattern', and the engine refused windows
|
|
356
|
+
# that demonstrably had patterns. One optional identifier took the whole engine down because the
|
|
357
|
+
# lookup was all-or-nothing. Now a missing type costs only that type.
|
|
358
|
+
if (-not $script:WpmUia) {
|
|
359
|
+
$t = @{}
|
|
360
|
+
$map = @{
|
|
361
|
+
invoke = 'System.Windows.Automation.InvokePattern'
|
|
362
|
+
value = 'System.Windows.Automation.ValuePattern'
|
|
363
|
+
toggle = 'System.Windows.Automation.TogglePattern'
|
|
364
|
+
select = 'System.Windows.Automation.SelectionItemPattern'
|
|
365
|
+
legacy = 'System.Windows.Automation.LegacyIAccessiblePattern'
|
|
366
|
+
range = 'System.Windows.Automation.RangeValuePattern'
|
|
367
|
+
}
|
|
368
|
+
foreach ($k in $map.Keys) {
|
|
369
|
+
try {
|
|
370
|
+
# Resolve against the assemblies already loaded by Add-Type -AssemblyName above. Probing
|
|
371
|
+
# by assembly-qualified name failed here because the assembly's simple name is not what
|
|
372
|
+
# GetType expects, and guessing names is how a resolver turns into a silent 'type not
|
|
373
|
+
# found'. Asking the loaded assemblies what they actually contain cannot guess wrong.
|
|
374
|
+
$ty = $null
|
|
375
|
+
foreach ($asm in [AppDomain]::CurrentDomain.GetAssemblies()) {
|
|
376
|
+
try { $ty = $asm.GetType($map[$k]); } catch { $ty = $null }
|
|
377
|
+
if ($ty) { break }
|
|
378
|
+
}
|
|
379
|
+
if ($ty) {
|
|
380
|
+
# Pattern is a public static FIELD on these classes, not a property. Asking only for a
|
|
381
|
+
# property returned $null for every pattern and produced 'no identifiers resolved' -- the
|
|
382
|
+
# same shape of mistake as reading an empty field as evidence.
|
|
383
|
+
$v = $null
|
|
384
|
+
$pr = $ty.GetProperty('Pattern')
|
|
385
|
+
if ($pr) { $v = $pr.GetValue($null) }
|
|
386
|
+
if (-not $v) {
|
|
387
|
+
$fl = $ty.GetField('Pattern')
|
|
388
|
+
if ($fl) { $v = $fl.GetValue($null) }
|
|
389
|
+
}
|
|
390
|
+
if ($v) { $t[$k] = $v }
|
|
391
|
+
}
|
|
392
|
+
} catch { }
|
|
393
|
+
}
|
|
394
|
+
if ($t.Count -eq 0) { throw 'no UIA pattern identifiers resolved; the automation client is unusable' }
|
|
395
|
+
$script:WpmUia = $t
|
|
396
|
+
}
|
|
397
|
+
return $script:WpmUia
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function Get-WpmFamily([IntPtr]$Hwnd, [string]$Cls) {
|
|
401
|
+
# Family decides which door is even possible, so it is measured from the class name rather than
|
|
402
|
+
# guessed from the title: a title is the user's text, a class is the toolkit's identity.
|
|
403
|
+
if ($Cls -like 'CASCADIA_HOSTING_WINDOW_CLASS*') { return 'terminal' }
|
|
404
|
+
if ($Cls -like 'WindowsForms10*') { return 'winforms' }
|
|
405
|
+
if ($Cls -like 'HwndWrapper*') { return 'wpf' }
|
|
406
|
+
if ($Cls -eq 'ApplicationFrameWindow' -or $Cls -eq 'Windows.UI.Core.CoreWindow') { return 'uwp' }
|
|
407
|
+
if ($Cls -like 'Chrome_WidgetWin*') { return 'chromium' }
|
|
408
|
+
if ($Cls -like 'Edit' -or $Cls -like 'RichEdit*' -or $Cls -eq '#32770') { return 'win32-classic' }
|
|
409
|
+
return 'unknown'
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function Get-WpmFacts {
|
|
413
|
+
<#
|
|
414
|
+
Measure a target's doors. Returns the hashtable decide.ps1 consumes, plus the raw handles the
|
|
415
|
+
executor needs. Cached per hwnd because UIA enumeration costs hundreds of ms and a batch of 50
|
|
416
|
+
clicks must not pay it 50 times -- but the cache is keyed on hwnd AND invalidated by the caller
|
|
417
|
+
when the window set changes, never assumed fresh.
|
|
418
|
+
#>
|
|
419
|
+
param([IntPtr]$Hwnd, [string]$Action = 'click', [string]$ElementName = '', [switch]$NoCache)
|
|
420
|
+
|
|
421
|
+
$cls = [WpmWin]::Cls($Hwnd)
|
|
422
|
+
$fam = Get-WpmFamily $Hwnd $cls
|
|
423
|
+
$kids = @([WpmWin]::Children($Hwnd))
|
|
424
|
+
$childHandles = @()
|
|
425
|
+
$doorKinds = @()
|
|
426
|
+
$doorHandles = @()
|
|
427
|
+
foreach ($k in $kids) {
|
|
428
|
+
$kh = [IntPtr]$k
|
|
429
|
+
$kc = [WpmWin]::Cls($kh)
|
|
430
|
+
# WinForms child classes are NOT 'Edit'/'Button': they are
|
|
431
|
+
# WindowsForms10.EDIT.app.0.<hash>_rN_adN / .BUTTON. / .RichEdit20W.
|
|
432
|
+
# and the old exact-ish match ('Edit', 'Button') never hit one of those -- the message door
|
|
433
|
+
# silently did not exist on the one toolkit where it demonstrably works, and the engine
|
|
434
|
+
# reported WinForms as `unreachable`. Found end-to-end by test/llm-action-battery.mjs; the
|
|
435
|
+
# census scripts had their own matching and never exercised this path. The base class is the
|
|
436
|
+
# segment after the `WindowsForms10.` prefix, taken before the next dot.
|
|
437
|
+
$base = $kc
|
|
438
|
+
if ($kc -like 'WindowsForms10.*') { $base = (($kc -split '\.')[1]) }
|
|
439
|
+
$kind = ''
|
|
440
|
+
if ($base -like 'Edit*' -or $base -like 'RichEdit*' -or $kc -like '*TextBox*') { $kind = 'text' }
|
|
441
|
+
elseif ($base -like 'BUTTON*' -or $base -like 'Button*' -or $kc -eq 'ComboBox') { $kind = 'click' }
|
|
442
|
+
if ($kind) {
|
|
443
|
+
$doorKinds += $kind
|
|
444
|
+
$childHandles += $kh
|
|
445
|
+
$doorHandles += @{ kind = $kind; hwnd = $kh }
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
# An element named by the caller always gets a UIA probe, even when a message door exists: the
|
|
450
|
+
# door tiers address a whole window, so 'click the Save button' cannot be expressed in them
|
|
451
|
+
# without coordinates. Naming an element is how a caller asks for a specific control instead of
|
|
452
|
+
# whichever one happens to be found first -- and 'first found' is not a contract, it is an
|
|
453
|
+
# accident of tree order that changes between app versions.
|
|
454
|
+
$hasPattern = $false
|
|
455
|
+
$patKind = 'none'
|
|
456
|
+
$uiaElement = $null
|
|
457
|
+
$uiaErr = ''
|
|
458
|
+
if ($doorKinds.Count -eq 0 -or $ElementName) {
|
|
459
|
+
try {
|
|
460
|
+
$root = [System.Windows.Automation.AutomationElement]::FromHandle($Hwnd)
|
|
461
|
+
$cond = New-Object System.Windows.Automation.PropertyCondition(
|
|
462
|
+
[System.Windows.Automation.AutomationElement]::IsEnabledProperty, $true)
|
|
463
|
+
$found = $root.FindAll([System.Windows.Automation.TreeScope]::Descendants, $cond)
|
|
464
|
+
$pats = Get-WpmUiaCached
|
|
465
|
+
$limit = [Math]::Min($found.Count, 200)
|
|
466
|
+
for ($i = 0; $i -lt $limit; $i++) {
|
|
467
|
+
$el = $found[$i]
|
|
468
|
+
if ($ElementName) {
|
|
469
|
+
# Match on Name or AutomationId. The two are different fields: Name is the visible label
|
|
470
|
+
# (localised, may change), AutomationId is the developer's id (stable). Accepting either
|
|
471
|
+
# keeps the caller from having to know which one a given app populates.
|
|
472
|
+
$nm = ''; $aid = ''
|
|
473
|
+
try { $nm = [string]$el.Current.Name } catch { }
|
|
474
|
+
try { $aid = [string]$el.Current.AutomationId } catch { }
|
|
475
|
+
if ($nm -ne $ElementName -and $aid -ne $ElementName) { continue }
|
|
476
|
+
}
|
|
477
|
+
foreach ($k in @('invoke', 'value', 'toggle', 'select', 'legacy')) {
|
|
478
|
+
if (-not $pats.ContainsKey($k)) { continue }
|
|
479
|
+
$obj = $null
|
|
480
|
+
try { if ($el.TryGetCurrentPattern($pats[$k], [ref]$obj)) { } } catch { continue }
|
|
481
|
+
if ($obj) { $hasPattern = $true; $patKind = $k; $uiaElement = $el; break }
|
|
482
|
+
}
|
|
483
|
+
if ($hasPattern) { break }
|
|
484
|
+
}
|
|
485
|
+
} catch {
|
|
486
|
+
# NOT swallowed. A silent catch here made the probe report 'no pattern' on a target that
|
|
487
|
+
# demonstrably had one, and the engine then refused a perfectly reachable window -- with no
|
|
488
|
+
# diagnostic anywhere. The error travels out with the facts so a refusal can say why.
|
|
489
|
+
$uiaErr = $_.Exception.Message
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
# Elevation is now measured, not assumed. WpmWin::IsElevatedTarget compares the target's
|
|
494
|
+
# integrity RID against ours; a failure to read either side returns false rather than guessing,
|
|
495
|
+
# because guessing 'elevated' would refuse every window whose handle read failed. The flag is
|
|
496
|
+
# consumed by decide.ps1's table, which checks it BEFORE any capability -- so an elevated target
|
|
497
|
+
# is refused outright and never probed for doors it cannot answer.
|
|
498
|
+
|
|
499
|
+
$tpid = [WpmWin]::PidOf($Hwnd)
|
|
500
|
+
$elevated = [WpmWin]::IsElevatedTarget($tpid)
|
|
501
|
+
|
|
502
|
+
$facts = New-WpmFacts -Hwnd ($Hwnd.ToInt64().ToString()) -Family $fam `
|
|
503
|
+
-MessageDoor ($doorKinds.Count -gt 0) -HasPattern $hasPattern -PatternKind $patKind `
|
|
504
|
+
-Action $Action -FactsMeasured $true -ElevatedTarget $elevated
|
|
505
|
+
|
|
506
|
+
return @{
|
|
507
|
+
facts = $facts
|
|
508
|
+
cls = $cls
|
|
509
|
+
family = $fam
|
|
510
|
+
childHandles = $childHandles
|
|
511
|
+
doorHandles = $doorHandles
|
|
512
|
+
doorKinds = @($doorKinds | Sort-Object -Unique)
|
|
513
|
+
uiaElement = $uiaElement
|
|
514
|
+
uiaErr = $uiaErr
|
|
515
|
+
pid = [WpmWin]::PidOf($Hwnd)
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function Get-WpmFocusEntry {
|
|
520
|
+
# The focus table entry required by R2'.4: foreground HWND, the control that holds focus, and the
|
|
521
|
+
# owning thread id (needed for the input-queue join). Keyed by HWND, never by pid: on this
|
|
522
|
+
# desktop ApplicationFrameHost owns every UWP frame, so pid both misses the target's own
|
|
523
|
+
# CoreWindow and blames unrelated apps.
|
|
524
|
+
$g = [WpmWin]::GuiFocusOfForeground()
|
|
525
|
+
$fg = [WpmWin]::FgHandle()
|
|
526
|
+
return @{
|
|
527
|
+
fgHwnd = $fg.ToInt64().ToString()
|
|
528
|
+
fgPid = ([WpmWin]::PidOf($fg)).ToString()
|
|
529
|
+
activeHwnd = ([IntPtr]$g[0]).ToInt64().ToString()
|
|
530
|
+
focusHwnd = ([IntPtr]$g[1]).ToInt64().ToString()
|
|
531
|
+
threadId = $g[2]
|
|
532
|
+
lastInputAgeMs = [WpmWin]::LastInputAgeMs()
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function Restore-WpmFocus {
|
|
537
|
+
<#
|
|
538
|
+
Put the foreground back, honouring the restore table. Returns the table's verdict plus what the
|
|
539
|
+
syscall actually did, so 'we decided to restore' and 'it worked' stay separate numbers.
|
|
540
|
+
#>
|
|
541
|
+
param([hashtable]$Entry, [string]$RaisedHwnd, [string]$TargetPid, [string]$RaisedElsewhere = '', [bool]$AlreadyRestored = $false)
|
|
542
|
+
|
|
543
|
+
# The foreground moved to a window that is NOT our target. That is never ours to reverse: either
|
|
544
|
+
# the target app opened its own window (a dialog, same pid) or a third party took the focus.
|
|
545
|
+
# This branch has to come first. An earlier version set RaisedHwnd to whatever held the
|
|
546
|
+
# foreground after the action, so a dialog launched by the action looked like "our raised window"
|
|
547
|
+
# and got restored away -- the exact failure R2'.6 exists to prevent, caught by the measurement
|
|
548
|
+
# rather than by review.
|
|
549
|
+
if ($RaisedElsewhere -and -not $RaisedHwnd) {
|
|
550
|
+
$ep = [WpmWin]::PidOf([IntPtr][int64]$RaisedElsewhere)
|
|
551
|
+
if ($TargetPid -and ("$ep" -eq "$TargetPid")) {
|
|
552
|
+
return @{ restore = $false; outcome = 'skip-dialog'; setFg = ''; joined = ''; fgAfter = $RaisedElsewhere
|
|
553
|
+
reason = 'the target app opened this window itself (same pid); restoring would close the dialog it just opened' }
|
|
554
|
+
}
|
|
555
|
+
return @{ restore = $false; outcome = 'skip-taken'; setFg = ''; joined = ''; fgAfter = $RaisedElsewhere
|
|
556
|
+
reason = 'a third-party window holds the foreground; never pull it from the owner' }
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
$cur = [WpmWin]::FgHandle()
|
|
560
|
+
$verdict = Get-WpmRestoreDecision -CurrentFg ($cur.ToInt64().ToString()) -RaisedHwnd $RaisedHwnd `
|
|
561
|
+
-TargetPid $TargetPid -CurrentFgPid ([WpmWin]::PidOf($cur)).ToString() `
|
|
562
|
+
-RaisedHappened ([bool]($RaisedHwnd -ne '')) -AlreadyRestored $AlreadyRestored
|
|
563
|
+
|
|
564
|
+
$res = @{ restore = $verdict.restore; outcome = $verdict.outcome; reason = $verdict.reason
|
|
565
|
+
setFg = ''; joined = ''; fgAfter = '' }
|
|
566
|
+
|
|
567
|
+
if ($verdict.restore -and $Entry -and $Entry.fgHwnd) {
|
|
568
|
+
$want = [IntPtr][int64]$Entry.fgHwnd
|
|
569
|
+
if ([WpmWin]::IsWindow($want)) {
|
|
570
|
+
$r = [WpmWin]::RestoreForeground($want)
|
|
571
|
+
$parts = $r.Split('|')
|
|
572
|
+
$res.setFg = $parts[0]; $res.joined = $parts[1]; $res.fgAfter = $parts[2]
|
|
573
|
+
} else {
|
|
574
|
+
# The window we would restore to no longer exists. Nothing legal is left to do: this process
|
|
575
|
+
# may not move the owner's focus to a window it does not own, and the target window belongs
|
|
576
|
+
# to another process. Reported so the caller can surface it instead of pretending.
|
|
577
|
+
$res.outcome = 'skip-vanished'; $res.reason = 'the window that held focus before the action no longer exists'
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
return $res
|
|
581
|
+
}
|