@copylee/dsh-computer-use 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.
@@ -0,0 +1,1236 @@
1
+ // dsh-computer-use helper: a long-lived Windows process driven over stdin/stdout
2
+ // (one JSON object per line). Compiled on first use with the .NET Framework
3
+ // csc.exe that ships with Windows, so the npm package carries no native binary.
4
+ //
5
+ // Language level: C# 5 (no string interpolation, no ?. operator, no expression
6
+ // bodies) because that is what the in-box csc.exe understands.
7
+ //
8
+ // Request: {"id": 1, "cmd": "screenshot", ...}
9
+ // Response: {"id": 1, "ok": true, "result": {...}} | {"id": 1, "ok": false, "error": "..."}
10
+ // Event: {"event": "stop", "reason": "esc"} (no id)
11
+ //
12
+ // All coordinates are physical pixels in virtual-screen space: the process is
13
+ // Per-Monitor-V2 DPI aware before any GDI / WinForms code runs.
14
+
15
+ using System;
16
+ using System.Collections;
17
+ using System.Collections.Generic;
18
+ using System.Diagnostics;
19
+ using System.Drawing;
20
+ using System.Drawing.Drawing2D;
21
+ using System.Drawing.Imaging;
22
+ using System.Drawing.Text;
23
+ using System.IO;
24
+ using System.Runtime.InteropServices;
25
+ using System.Text;
26
+ using System.Threading;
27
+ using System.Web.Script.Serialization;
28
+ using System.Windows.Automation;
29
+ using System.Windows.Forms;
30
+
31
+ namespace DshComputerUse
32
+ {
33
+ internal static class Native
34
+ {
35
+ [DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
36
+ [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
37
+
38
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; public POINT(int x, int y) { X = x; Y = y; } }
39
+ [StructLayout(LayoutKind.Sequential)] public struct SIZE { public int cx; public int cy; public SIZE(int w, int h) { cx = w; cy = h; } }
40
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
41
+
42
+ [StructLayout(LayoutKind.Sequential)]
43
+ public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
44
+ [StructLayout(LayoutKind.Sequential)]
45
+ public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
46
+ [StructLayout(LayoutKind.Explicit)]
47
+ public struct InputUnion { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
48
+ [StructLayout(LayoutKind.Sequential)]
49
+ public struct INPUT { public uint type; public InputUnion u; }
50
+
51
+ [DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint n, INPUT[] inputs, int size);
52
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
53
+ [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
54
+ [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint code, uint mapType);
55
+
56
+ public delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdc, ref RECT rect, IntPtr data);
57
+ [DllImport("user32.dll")] public static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr clip, MonitorEnumProc proc, IntPtr data);
58
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
59
+ public struct MONITORINFOEX { public int cbSize; public RECT rcMonitor; public RECT rcWork; public uint dwFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szDevice; }
60
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFOEX info);
61
+ [DllImport("shcore.dll")] public static extern int GetDpiForMonitor(IntPtr hMonitor, int type, out uint dpiX, out uint dpiY);
62
+
63
+ [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hwnd);
64
+ [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
65
+ [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr dst, int x, int y, int w, int h, IntPtr src, int sx, int sy, uint rop);
66
+ [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
67
+ [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hdc);
68
+ [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj);
69
+ [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr obj);
70
+
71
+ public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr data);
72
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc proc, IntPtr data);
73
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
74
+ [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
75
+ [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hwnd);
76
+ [DllImport("user32.dll")] public static extern bool IsZoomed(IntPtr hwnd);
77
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hwnd, StringBuilder sb, int max);
78
+ [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr hwnd);
79
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr hwnd, StringBuilder sb, int max);
80
+ [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hwnd, uint cmd);
81
+ [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hwnd, int index);
82
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid);
83
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
84
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hwnd);
85
+ [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hwnd);
86
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hwnd, int cmd);
87
+ [DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr hwnd, bool altTab);
88
+ [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool attach);
89
+ [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
90
+ [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hwnd, uint msg, IntPtr w, IntPtr l);
91
+ [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
92
+ [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr hwnd, uint flags);
93
+ [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
94
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out RECT r);
95
+ [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int attr, out RECT value, int size);
96
+ [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int attr, out int value, int size);
97
+
98
+ [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
99
+ [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr h);
100
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern bool QueryFullProcessImageName(IntPtr h, int flags, StringBuilder sb, ref int size);
101
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr GetModuleHandle(string name);
102
+
103
+ [StructLayout(LayoutKind.Sequential, Pack = 1)]
104
+ public struct BLENDFUNCTION { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; }
105
+ [DllImport("user32.dll", SetLastError = true)]
106
+ public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize, IntPtr hdcSrc, ref POINT pptSrc, int crKey, ref BLENDFUNCTION pblend, int flags);
107
+ [DllImport("user32.dll", SetLastError = true)]
108
+ public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, IntPtr psize, IntPtr hdcSrc, IntPtr pptSrc, int crKey, ref BLENDFUNCTION pblend, int flags);
109
+ [DllImport("user32.dll")] public static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint affinity);
110
+
111
+ public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
112
+ [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc fn, IntPtr hMod, uint threadId);
113
+ [DllImport("user32.dll")] public static extern bool UnhookWindowsHookEx(IntPtr hook);
114
+ [DllImport("user32.dll")] public static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wParam, IntPtr lParam);
115
+ [StructLayout(LayoutKind.Sequential)]
116
+ public struct KBDLLHOOKSTRUCT { public uint vkCode; public uint scanCode; public uint flags; public uint time; public IntPtr dwExtraInfo; }
117
+
118
+ public const uint INPUT_MOUSE = 0, INPUT_KEYBOARD = 1;
119
+ public const uint KEYEVENTF_EXTENDEDKEY = 0x1, KEYEVENTF_KEYUP = 0x2, KEYEVENTF_UNICODE = 0x4;
120
+ public const uint MOUSEEVENTF_MOVE = 0x1, MOUSEEVENTF_LEFTDOWN = 0x2, MOUSEEVENTF_LEFTUP = 0x4, MOUSEEVENTF_RIGHTDOWN = 0x8, MOUSEEVENTF_RIGHTUP = 0x10,
121
+ MOUSEEVENTF_MIDDLEDOWN = 0x20, MOUSEEVENTF_MIDDLEUP = 0x40, MOUSEEVENTF_WHEEL = 0x800, MOUSEEVENTF_HWHEEL = 0x1000;
122
+ public static readonly IntPtr Marker = new IntPtr(0x44534843); // "DSHC"
123
+ }
124
+
125
+ internal static class Args
126
+ {
127
+ public static bool Has(Dictionary<string, object> d, string k) { object v; return d.TryGetValue(k, out v) && v != null; }
128
+ public static int Int(Dictionary<string, object> d, string k, int def)
129
+ {
130
+ object v; if (!d.TryGetValue(k, out v) || v == null) return def;
131
+ return (int)Math.Round(Convert.ToDouble(v));
132
+ }
133
+ public static string Str(Dictionary<string, object> d, string k, string def)
134
+ {
135
+ object v; if (!d.TryGetValue(k, out v) || v == null) return def;
136
+ return Convert.ToString(v);
137
+ }
138
+ public static bool Bool(Dictionary<string, object> d, string k, bool def)
139
+ {
140
+ object v; if (!d.TryGetValue(k, out v) || v == null) return def;
141
+ return Convert.ToBoolean(v);
142
+ }
143
+ public static List<int> Ints(Dictionary<string, object> d, string k)
144
+ {
145
+ var list = new List<int>(); object v;
146
+ if (d.TryGetValue(k, out v) && v is IEnumerable && !(v is string))
147
+ foreach (var item in (IEnumerable)v) list.Add((int)Math.Round(Convert.ToDouble(item)));
148
+ return list;
149
+ }
150
+ public static List<List<int>> IntLists(Dictionary<string, object> d, string k)
151
+ {
152
+ var list = new List<List<int>>(); object v;
153
+ if (d.TryGetValue(k, out v) && v is IEnumerable && !(v is string))
154
+ foreach (var row in (IEnumerable)v)
155
+ {
156
+ var inner = new List<int>();
157
+ foreach (var item in (IEnumerable)row) inner.Add((int)Math.Round(Convert.ToDouble(item)));
158
+ list.Add(inner);
159
+ }
160
+ return list;
161
+ }
162
+ }
163
+
164
+ internal static class Program
165
+ {
166
+ static readonly object OutLock = new object();
167
+ static TextWriter Out;
168
+ public const string Version = "1";
169
+
170
+ [STAThread]
171
+ static int Main(string[] argv)
172
+ {
173
+ // Must precede every GDI / WinForms call, or the process is stuck in
174
+ // DPI-virtualised coordinates.
175
+ try { if (!Native.SetProcessDpiAwarenessContext(new IntPtr(-4))) Native.SetProcessDPIAware(); }
176
+ catch (Exception) { try { Native.SetProcessDPIAware(); } catch (Exception) { } }
177
+
178
+ var utf8 = new UTF8Encoding(false);
179
+ var writer = new StreamWriter(Console.OpenStandardOutput(), utf8);
180
+ writer.AutoFlush = true;
181
+ Out = writer;
182
+ var input = new StreamReader(Console.OpenStandardInput(), utf8);
183
+ var parser = new JavaScriptSerializer();
184
+ parser.MaxJsonLength = int.MaxValue;
185
+
186
+ var hello = new Dictionary<string, object>();
187
+ hello["event"] = "ready"; hello["version"] = Version; hello["pid"] = Process.GetCurrentProcess().Id;
188
+ Emit(hello);
189
+
190
+ string line;
191
+ while ((line = input.ReadLine()) != null)
192
+ {
193
+ if (line.Trim().Length == 0) continue;
194
+ object id = null;
195
+ var reply = new Dictionary<string, object>();
196
+ try
197
+ {
198
+ var req = (Dictionary<string, object>)parser.DeserializeObject(line);
199
+ if (req.ContainsKey("id")) id = req["id"];
200
+ reply["id"] = id;
201
+ reply["result"] = Commands.Run(req);
202
+ reply["ok"] = true;
203
+ }
204
+ catch (Exception ex)
205
+ {
206
+ reply["id"] = id;
207
+ reply["ok"] = false;
208
+ reply["error"] = ex.Message;
209
+ }
210
+ Emit(reply);
211
+ }
212
+ Overlay.Shutdown();
213
+ return 0;
214
+ }
215
+
216
+ public static void Emit(Dictionary<string, object> msg)
217
+ {
218
+ lock (OutLock)
219
+ {
220
+ var s = new JavaScriptSerializer();
221
+ s.MaxJsonLength = int.MaxValue;
222
+ Out.Write(s.Serialize(msg));
223
+ Out.Write('\n');
224
+ Out.Flush();
225
+ }
226
+ }
227
+
228
+ public static void EmitEvent(string name, string reason)
229
+ {
230
+ ThreadPool.QueueUserWorkItem(delegate
231
+ {
232
+ var e = new Dictionary<string, object>();
233
+ e["event"] = name; e["reason"] = reason;
234
+ try { Emit(e); } catch (Exception) { }
235
+ });
236
+ }
237
+ }
238
+
239
+ internal static class Commands
240
+ {
241
+ public static object Run(Dictionary<string, object> r)
242
+ {
243
+ string cmd = Args.Str(r, "cmd", "");
244
+ switch (cmd)
245
+ {
246
+ case "ping": { var d = new Dictionary<string, object>(); d["version"] = Program.Version; return d; }
247
+ case "displays": return Screen2.Displays();
248
+ case "screenshot": return Screen2.Capture(r);
249
+ case "cursor": { Native.POINT p; Native.GetCursorPos(out p); return Pt(p.X, p.Y); }
250
+ case "move": Overlay.Dodge(Args.Int(r, "x", 0), Args.Int(r, "y", 0)); Input.Move(Args.Int(r, "x", 0), Args.Int(r, "y", 0)); return null;
251
+ case "click": return Input.Click(r);
252
+ case "button": return Input.Button(r);
253
+ case "drag": return Input.Drag(r);
254
+ case "scroll": return Input.Scroll(r);
255
+ case "keys": return Input.Keys(r);
256
+ case "key_state": return Input.KeyState(r);
257
+ case "type": return Input.Type(Args.Str(r, "text", ""), Args.Int(r, "chunkDelay", 8));
258
+ case "paste": return Input.Paste(Args.Str(r, "text", ""), Args.Bool(r, "restore", true));
259
+ case "windows": return Windows.List();
260
+ case "foreground": return Windows.Describe(Native.GetForegroundWindow());
261
+ case "window_at": return Windows.At(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
262
+ case "focus": return Windows.Focus(new IntPtr(Convert.ToInt64(r["hwnd"])));
263
+ case "window_cmd": return Windows.Command(new IntPtr(Convert.ToInt64(r["hwnd"])), Args.Str(r, "op", ""));
264
+ case "apps": return Apps.Search(Args.Str(r, "query", ""), Args.Int(r, "limit", 8));
265
+ case "launch": return Apps.Launch(r);
266
+ case "clipboard_get": { var d = new Dictionary<string, object>(); d["text"] = Clip.Get(); return d; }
267
+ case "clipboard_set": Clip.Set(Args.Str(r, "text", "")); return null;
268
+ case "ui": return Uia.Elements(r);
269
+ case "overlay_show": Overlay.ExcludeFromCapture = Args.Bool(r, "excludeFromCapture", true); Overlay.Show(Args.Str(r, "label", ""), Args.Str(r, "status", ""), Args.Bool(r, "glow", true)); return null;
270
+ case "overlay_status": Overlay.Status(Args.Str(r, "status", "")); return null;
271
+ case "overlay_hide": Overlay.Hide(); return null;
272
+ default: throw new Exception("unknown command: " + cmd);
273
+ }
274
+ }
275
+
276
+ public static Dictionary<string, object> Pt(int x, int y) { var d = new Dictionary<string, object>(); d["x"] = x; d["y"] = y; return d; }
277
+ }
278
+
279
+ internal static class Screen2
280
+ {
281
+ public static List<object> Displays()
282
+ {
283
+ var list = new List<object>();
284
+ Native.MonitorEnumProc cb = delegate (IntPtr h, IntPtr hdc, ref Native.RECT rc, IntPtr data)
285
+ {
286
+ var info = new Native.MONITORINFOEX();
287
+ info.cbSize = Marshal.SizeOf(typeof(Native.MONITORINFOEX));
288
+ Native.GetMonitorInfo(h, ref info);
289
+ uint dx = 96, dy = 96;
290
+ try { Native.GetDpiForMonitor(h, 0, out dx, out dy); } catch (Exception) { }
291
+ var d = new Dictionary<string, object>();
292
+ d["x"] = info.rcMonitor.Left; d["y"] = info.rcMonitor.Top;
293
+ d["width"] = info.rcMonitor.Right - info.rcMonitor.Left; d["height"] = info.rcMonitor.Bottom - info.rcMonitor.Top;
294
+ d["workX"] = info.rcWork.Left; d["workY"] = info.rcWork.Top;
295
+ d["workWidth"] = info.rcWork.Right - info.rcWork.Left; d["workHeight"] = info.rcWork.Bottom - info.rcWork.Top;
296
+ d["primary"] = (info.dwFlags & 1) != 0;
297
+ d["dpi"] = (int)dx;
298
+ d["name"] = info.szDevice;
299
+ list.Add(d);
300
+ return true;
301
+ };
302
+ Native.EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb, IntPtr.Zero);
303
+ GC.KeepAlive(cb);
304
+ return list;
305
+ }
306
+
307
+ static ImageCodecInfo jpegCodec;
308
+
309
+ public static Dictionary<string, object> Capture(Dictionary<string, object> r)
310
+ {
311
+ int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0), w = Args.Int(r, "width", 0), h = Args.Int(r, "height", 0);
312
+ int ow = Args.Int(r, "outWidth", w), oh = Args.Int(r, "outHeight", h);
313
+ int quality = Args.Int(r, "quality", 80);
314
+ if (w <= 0 || h <= 0 || ow <= 0 || oh <= 0) throw new Exception("invalid capture size");
315
+ using (var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb))
316
+ {
317
+ using (var g = Graphics.FromImage(bmp))
318
+ {
319
+ IntPtr dst = g.GetHdc();
320
+ IntPtr src = Native.GetDC(IntPtr.Zero);
321
+ try { Native.BitBlt(dst, 0, 0, w, h, src, x, y, 0x00CC0020 | 0x40000000); }
322
+ finally { Native.ReleaseDC(IntPtr.Zero, src); g.ReleaseHdc(dst); }
323
+ }
324
+ Bitmap output = bmp;
325
+ Bitmap scaled = null;
326
+ try
327
+ {
328
+ if (ow != w || oh != h)
329
+ {
330
+ scaled = new Bitmap(ow, oh, PixelFormat.Format24bppRgb);
331
+ using (var g2 = Graphics.FromImage(scaled))
332
+ using (var attrs = new ImageAttributes())
333
+ {
334
+ attrs.SetWrapMode(WrapMode.TileFlipXY);
335
+ g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
336
+ g2.PixelOffsetMode = PixelOffsetMode.HighQuality;
337
+ g2.CompositingQuality = CompositingQuality.HighQuality;
338
+ g2.DrawImage(bmp, new Rectangle(0, 0, ow, oh), 0, 0, w, h, GraphicsUnit.Pixel, attrs);
339
+ }
340
+ output = scaled;
341
+ }
342
+ if (jpegCodec == null)
343
+ foreach (var c in ImageCodecInfo.GetImageEncoders()) if (c.MimeType == "image/jpeg") jpegCodec = c;
344
+ using (var ms = new MemoryStream())
345
+ using (var ep = new EncoderParameters(1))
346
+ {
347
+ ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
348
+ output.Save(ms, jpegCodec, ep);
349
+ var d = new Dictionary<string, object>();
350
+ d["data"] = Convert.ToBase64String(ms.ToArray());
351
+ d["width"] = ow; d["height"] = oh;
352
+ return d;
353
+ }
354
+ }
355
+ finally { if (scaled != null) scaled.Dispose(); }
356
+ }
357
+ }
358
+ }
359
+
360
+ internal static class Input
361
+ {
362
+ static readonly int InputSize = Marshal.SizeOf(typeof(Native.INPUT));
363
+ static readonly HashSet<int> Extended = new HashSet<int> { 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x2C, 0x2D, 0x2E, 0x5B, 0x5C, 0x5D, 0x6F, 0x90, 0xA3, 0xA5 };
364
+
365
+ static Native.INPUT Mouse(uint flags, uint data)
366
+ {
367
+ var i = new Native.INPUT(); i.type = Native.INPUT_MOUSE;
368
+ i.u.mi.dwFlags = flags; i.u.mi.mouseData = data; i.u.mi.dwExtraInfo = Native.Marker;
369
+ return i;
370
+ }
371
+
372
+ static Native.INPUT Key(int vk, bool up)
373
+ {
374
+ var i = new Native.INPUT(); i.type = Native.INPUT_KEYBOARD;
375
+ i.u.ki.wVk = (ushort)vk;
376
+ i.u.ki.wScan = (ushort)Native.MapVirtualKey((uint)vk, 0);
377
+ i.u.ki.dwFlags = (up ? Native.KEYEVENTF_KEYUP : 0) | (Extended.Contains(vk) ? Native.KEYEVENTF_EXTENDEDKEY : 0);
378
+ i.u.ki.dwExtraInfo = Native.Marker;
379
+ return i;
380
+ }
381
+
382
+ static Native.INPUT Unicode(char c, bool up)
383
+ {
384
+ var i = new Native.INPUT(); i.type = Native.INPUT_KEYBOARD;
385
+ i.u.ki.wVk = 0; i.u.ki.wScan = c;
386
+ i.u.ki.dwFlags = Native.KEYEVENTF_UNICODE | (up ? Native.KEYEVENTF_KEYUP : 0);
387
+ i.u.ki.dwExtraInfo = Native.Marker;
388
+ return i;
389
+ }
390
+
391
+ static void Send(List<Native.INPUT> inputs)
392
+ {
393
+ if (inputs.Count == 0) return;
394
+ uint sent = Native.SendInput((uint)inputs.Count, inputs.ToArray(), InputSize);
395
+ if (sent != inputs.Count)
396
+ throw new Exception("SendInput was blocked (error " + Marshal.GetLastWin32Error() + "). The target may be running elevated (as administrator) or the secure desktop (UAC / lock screen) is active.");
397
+ }
398
+
399
+ public static void Move(int x, int y)
400
+ {
401
+ Native.SetCursorPos(x, y);
402
+ // A zero relative move lets apps that only watch WM_MOUSEMOVE notice the cursor.
403
+ Send(new List<Native.INPUT> { Mouse(Native.MOUSEEVENTF_MOVE, 0) });
404
+ }
405
+
406
+ static void Flags(string button, out uint down, out uint up)
407
+ {
408
+ switch (button)
409
+ {
410
+ case "right": down = Native.MOUSEEVENTF_RIGHTDOWN; up = Native.MOUSEEVENTF_RIGHTUP; break;
411
+ case "middle": down = Native.MOUSEEVENTF_MIDDLEDOWN; up = Native.MOUSEEVENTF_MIDDLEUP; break;
412
+ default: down = Native.MOUSEEVENTF_LEFTDOWN; up = Native.MOUSEEVENTF_LEFTUP; break;
413
+ }
414
+ }
415
+
416
+ static void Modifiers(List<int> vks, bool up)
417
+ {
418
+ var list = new List<Native.INPUT>();
419
+ if (up) for (int i = vks.Count - 1; i >= 0; i--) list.Add(Key(vks[i], true));
420
+ else foreach (var vk in vks) list.Add(Key(vk, false));
421
+ Send(list);
422
+ }
423
+
424
+ public static object Click(Dictionary<string, object> r)
425
+ {
426
+ if (Args.Has(r, "x"))
427
+ {
428
+ int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0);
429
+ Overlay.Dodge(x, y);
430
+ Move(x, y);
431
+ Thread.Sleep(30);
432
+ }
433
+ uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
434
+ int count = Math.Max(1, Math.Min(3, Args.Int(r, "count", 1)));
435
+ var mods = Args.Ints(r, "modifiers");
436
+ Modifiers(mods, false);
437
+ try
438
+ {
439
+ for (int i = 0; i < count; i++)
440
+ {
441
+ Send(new List<Native.INPUT> { Mouse(down, 0) });
442
+ Thread.Sleep(20);
443
+ Send(new List<Native.INPUT> { Mouse(up, 0) });
444
+ if (i < count - 1) Thread.Sleep(40);
445
+ }
446
+ }
447
+ finally { Modifiers(mods, true); }
448
+ return null;
449
+ }
450
+
451
+ public static object Button(Dictionary<string, object> r)
452
+ {
453
+ if (Args.Has(r, "x")) { int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0); Overlay.Dodge(x, y); Move(x, y); Thread.Sleep(20); }
454
+ uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
455
+ Send(new List<Native.INPUT> { Mouse(Args.Bool(r, "up", false) ? up : down, 0) });
456
+ return null;
457
+ }
458
+
459
+ public static object Drag(Dictionary<string, object> r)
460
+ {
461
+ int x1 = Args.Int(r, "x1", 0), y1 = Args.Int(r, "y1", 0), x2 = Args.Int(r, "x2", 0), y2 = Args.Int(r, "y2", 0);
462
+ uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
463
+ Overlay.Dodge(x1, y1); Overlay.Dodge(x2, y2);
464
+ Move(x1, y1); Thread.Sleep(40);
465
+ Send(new List<Native.INPUT> { Mouse(down, 0) });
466
+ try
467
+ {
468
+ Thread.Sleep(60);
469
+ int steps = Math.Max(8, Math.Min(40, (int)(Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) / 20)));
470
+ for (int i = 1; i <= steps; i++)
471
+ {
472
+ Move(x1 + (x2 - x1) * i / steps, y1 + (y2 - y1) * i / steps);
473
+ Thread.Sleep(12);
474
+ }
475
+ Thread.Sleep(60);
476
+ }
477
+ finally { Send(new List<Native.INPUT> { Mouse(up, 0) }); }
478
+ return null;
479
+ }
480
+
481
+ public static object Scroll(Dictionary<string, object> r)
482
+ {
483
+ if (Args.Has(r, "x")) { int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0); Overlay.Dodge(x, y); Move(x, y); Thread.Sleep(30); }
484
+ int dx = Args.Int(r, "dx", 0), dy = Args.Int(r, "dy", 0);
485
+ var mods = Args.Ints(r, "modifiers");
486
+ Modifiers(mods, false);
487
+ try
488
+ {
489
+ // One notch per event, spaced out, so smooth-scrolling apps keep up.
490
+ for (int i = 0; i < Math.Abs(dy); i++) { Send(new List<Native.INPUT> { Mouse(Native.MOUSEEVENTF_WHEEL, (uint)(dy > 0 ? -120 : 120)) }); Thread.Sleep(15); }
491
+ for (int i = 0; i < Math.Abs(dx); i++) { Send(new List<Native.INPUT> { Mouse(Native.MOUSEEVENTF_HWHEEL, (uint)(dx > 0 ? 120 : -120)) }); Thread.Sleep(15); }
492
+ }
493
+ finally { Modifiers(mods, true); }
494
+ return null;
495
+ }
496
+
497
+ // combos: [[vk, vk, ...], ...] — each combo presses in order and releases in reverse.
498
+ public static object Keys(Dictionary<string, object> r)
499
+ {
500
+ var combos = Args.IntLists(r, "combos");
501
+ int hold = Args.Int(r, "holdMs", 0);
502
+ foreach (var combo in combos)
503
+ {
504
+ var downs = new List<Native.INPUT>();
505
+ foreach (var vk in combo) downs.Add(Key(vk, false));
506
+ Send(downs);
507
+ Thread.Sleep(hold > 0 ? hold : 25);
508
+ var ups = new List<Native.INPUT>();
509
+ for (int i = combo.Count - 1; i >= 0; i--) ups.Add(Key(combo[i], true));
510
+ Send(ups);
511
+ Thread.Sleep(30);
512
+ }
513
+ return null;
514
+ }
515
+
516
+ public static object KeyState(Dictionary<string, object> r)
517
+ {
518
+ var vks = Args.Ints(r, "vks");
519
+ Modifiers(vks, Args.Bool(r, "up", false));
520
+ return null;
521
+ }
522
+
523
+ public static object Type(string text, int chunkDelay)
524
+ {
525
+ var batch = new List<Native.INPUT>();
526
+ Action flush = delegate { Send(batch); batch.Clear(); if (chunkDelay > 0) Thread.Sleep(chunkDelay); };
527
+ for (int i = 0; i < text.Length; i++)
528
+ {
529
+ char c = text[i];
530
+ if (c == '\r') { if (i + 1 < text.Length && text[i + 1] == '\n') continue; c = '\n'; }
531
+ if (c == '\n') { flush(); batch.Add(Key(0x0D, false)); batch.Add(Key(0x0D, true)); flush(); continue; }
532
+ if (c == '\t') { batch.Add(Key(0x09, false)); batch.Add(Key(0x09, true)); continue; }
533
+ batch.Add(Unicode(c, false)); batch.Add(Unicode(c, true));
534
+ if (batch.Count >= 40 && !char.IsHighSurrogate(c)) flush();
535
+ }
536
+ flush();
537
+ return null;
538
+ }
539
+
540
+ public static object Paste(string text, bool restore)
541
+ {
542
+ string previous = null;
543
+ if (restore) { try { previous = Clip.Get(); } catch (Exception) { } }
544
+ Clip.Set(text);
545
+ Thread.Sleep(40);
546
+ Send(new List<Native.INPUT> { Key(0x11, false), Key(0x56, false) });
547
+ Thread.Sleep(30);
548
+ Send(new List<Native.INPUT> { Key(0x56, true), Key(0x11, true) });
549
+ Thread.Sleep(250);
550
+ if (restore && previous != null) { try { Clip.Set(previous); } catch (Exception) { } }
551
+ return null;
552
+ }
553
+ }
554
+
555
+ internal static class Clip
556
+ {
557
+ public static string Get()
558
+ {
559
+ for (int i = 0; i < 5; i++)
560
+ {
561
+ try { return Clipboard.ContainsText() ? Clipboard.GetText() : ""; }
562
+ catch (ExternalException) { Thread.Sleep(50); }
563
+ }
564
+ throw new Exception("clipboard is busy");
565
+ }
566
+
567
+ public static void Set(string text)
568
+ {
569
+ for (int i = 0; i < 5; i++)
570
+ {
571
+ try
572
+ {
573
+ if (string.IsNullOrEmpty(text)) Clipboard.Clear(); else Clipboard.SetText(text);
574
+ return;
575
+ }
576
+ catch (ExternalException) { Thread.Sleep(50); }
577
+ }
578
+ throw new Exception("clipboard is busy");
579
+ }
580
+ }
581
+
582
+ internal static class Windows
583
+ {
584
+ public static string ExePath(uint pid)
585
+ {
586
+ IntPtr h = Native.OpenProcess(0x1000, false, pid);
587
+ if (h == IntPtr.Zero) return "";
588
+ try
589
+ {
590
+ var sb = new StringBuilder(1024); int size = sb.Capacity;
591
+ return Native.QueryFullProcessImageName(h, 0, sb, ref size) ? sb.ToString() : "";
592
+ }
593
+ finally { Native.CloseHandle(h); }
594
+ }
595
+
596
+ public static Dictionary<string, object> Describe(IntPtr hwnd)
597
+ {
598
+ var d = new Dictionary<string, object>();
599
+ if (hwnd == IntPtr.Zero || !Native.IsWindow(hwnd)) return d;
600
+ uint pid; Native.GetWindowThreadProcessId(hwnd, out pid);
601
+ int len = Native.GetWindowTextLength(hwnd);
602
+ var title = new StringBuilder(Math.Max(len + 1, 2)); Native.GetWindowText(hwnd, title, title.Capacity);
603
+ var cls = new StringBuilder(256); Native.GetClassName(hwnd, cls, cls.Capacity);
604
+ Native.RECT rc;
605
+ if (Native.DwmGetWindowAttribute(hwnd, 9, out rc, Marshal.SizeOf(typeof(Native.RECT))) != 0) Native.GetWindowRect(hwnd, out rc);
606
+ string path = ExePath(pid);
607
+ d["hwnd"] = hwnd.ToInt64();
608
+ d["title"] = title.ToString();
609
+ d["className"] = cls.ToString();
610
+ d["pid"] = (long)pid;
611
+ d["exe"] = path.Length > 0 ? Path.GetFileName(path) : "";
612
+ d["path"] = path;
613
+ d["x"] = rc.Left; d["y"] = rc.Top; d["width"] = rc.Right - rc.Left; d["height"] = rc.Bottom - rc.Top;
614
+ d["minimized"] = Native.IsIconic(hwnd);
615
+ d["maximized"] = Native.IsZoomed(hwnd);
616
+ return d;
617
+ }
618
+
619
+ public static List<object> List()
620
+ {
621
+ var list = new List<object>();
622
+ IntPtr fg = Native.GetForegroundWindow();
623
+ uint self = (uint)Process.GetCurrentProcess().Id;
624
+ Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
625
+ {
626
+ if (!Native.IsWindowVisible(h) || Native.GetWindowTextLength(h) == 0) return true;
627
+ if (Native.GetWindow(h, 4) != IntPtr.Zero) return true; // owned popup
628
+ int ex = Native.GetWindowLong(h, -20);
629
+ if ((ex & 0x80) != 0 && (ex & 0x40000) == 0) return true; // tool window
630
+ int cloaked;
631
+ if (Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
632
+ uint pid; Native.GetWindowThreadProcessId(h, out pid);
633
+ if (pid == self) return true;
634
+ var d = Describe(h);
635
+ d["foreground"] = h == fg;
636
+ list.Add(d);
637
+ return true;
638
+ };
639
+ Native.EnumWindows(cb, IntPtr.Zero);
640
+ GC.KeepAlive(cb);
641
+ return list;
642
+ }
643
+
644
+ public static Dictionary<string, object> At(int x, int y)
645
+ {
646
+ IntPtr h = Native.WindowFromPoint(new Native.POINT(x, y));
647
+ if (h != IntPtr.Zero) h = Native.GetAncestor(h, 2); // GA_ROOT
648
+ uint pid = 0;
649
+ if (h != IntPtr.Zero) Native.GetWindowThreadProcessId(h, out pid);
650
+ if (h == IntPtr.Zero || pid == (uint)Process.GetCurrentProcess().Id)
651
+ {
652
+ // Our own status pill is under the point (it dodges before the
653
+ // click): report the topmost foreign window there instead.
654
+ IntPtr found = IntPtr.Zero;
655
+ uint self = (uint)Process.GetCurrentProcess().Id;
656
+ Native.EnumWindowsProc cb = delegate (IntPtr w, IntPtr data)
657
+ {
658
+ if (!Native.IsWindowVisible(w)) return true;
659
+ uint p; Native.GetWindowThreadProcessId(w, out p);
660
+ if (p == self) return true;
661
+ if ((Native.GetWindowLong(w, -20) & 0x20) != 0) return true; // WS_EX_TRANSPARENT
662
+ int cloaked;
663
+ if (Native.DwmGetWindowAttribute(w, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
664
+ Native.RECT rc; Native.GetWindowRect(w, out rc);
665
+ if (x >= rc.Left && x < rc.Right && y >= rc.Top && y < rc.Bottom) { found = w; return false; }
666
+ return true;
667
+ };
668
+ Native.EnumWindows(cb, IntPtr.Zero);
669
+ GC.KeepAlive(cb);
670
+ h = found;
671
+ }
672
+ return Describe(h);
673
+ }
674
+
675
+ public static Dictionary<string, object> Focus(IntPtr hwnd)
676
+ {
677
+ if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
678
+ if (Native.IsIconic(hwnd)) { Native.ShowWindow(hwnd, 9); Thread.Sleep(150); }
679
+ if (Native.GetForegroundWindow() != hwnd)
680
+ {
681
+ IntPtr fg = Native.GetForegroundWindow();
682
+ uint pid;
683
+ uint fgThread = Native.GetWindowThreadProcessId(fg, out pid);
684
+ uint cur = Native.GetCurrentThreadId();
685
+ bool attached = fgThread != 0 && fgThread != cur && Native.AttachThreadInput(cur, fgThread, true);
686
+ try
687
+ {
688
+ Native.BringWindowToTop(hwnd);
689
+ Native.SetForegroundWindow(hwnd);
690
+ }
691
+ finally { if (attached) Native.AttachThreadInput(cur, fgThread, false); }
692
+ Thread.Sleep(60);
693
+ if (Native.GetForegroundWindow() != hwnd)
694
+ {
695
+ Native.SwitchToThisWindow(hwnd, true);
696
+ Thread.Sleep(120);
697
+ }
698
+ if (Native.GetForegroundWindow() != hwnd)
699
+ {
700
+ // Holding Alt lifts the foreground lock; a no-op VK keeps the
701
+ // Alt release from opening the target's menu bar.
702
+ var inputs = new Native.INPUT[3];
703
+ var down = new Native.INPUT(); down.type = Native.INPUT_KEYBOARD; down.u.ki.wVk = 0x12; down.u.ki.dwExtraInfo = Native.Marker;
704
+ Native.SendInput(1, new[] { down }, Marshal.SizeOf(typeof(Native.INPUT)));
705
+ Native.SetForegroundWindow(hwnd);
706
+ var noop = new Native.INPUT(); noop.type = Native.INPUT_KEYBOARD; noop.u.ki.wVk = 0xFF; noop.u.ki.dwExtraInfo = Native.Marker;
707
+ var noopUp = noop; noopUp.u.ki.dwFlags = Native.KEYEVENTF_KEYUP;
708
+ var up = down; up.u.ki.dwFlags = Native.KEYEVENTF_KEYUP;
709
+ inputs[0] = noop; inputs[1] = noopUp; inputs[2] = up;
710
+ Native.SendInput(3, inputs, Marshal.SizeOf(typeof(Native.INPUT)));
711
+ Thread.Sleep(120);
712
+ }
713
+ }
714
+ var d = Describe(hwnd);
715
+ d["focused"] = Native.GetForegroundWindow() == hwnd;
716
+ return d;
717
+ }
718
+
719
+ public static object Command(IntPtr hwnd, string op)
720
+ {
721
+ if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
722
+ switch (op)
723
+ {
724
+ case "minimize": Native.ShowWindow(hwnd, 6); break;
725
+ case "maximize": Native.ShowWindow(hwnd, 3); break;
726
+ case "restore": Native.ShowWindow(hwnd, 9); break;
727
+ case "close": Native.PostMessage(hwnd, 0x0010, IntPtr.Zero, IntPtr.Zero); break;
728
+ default: throw new Exception("unknown window op: " + op);
729
+ }
730
+ Thread.Sleep(150);
731
+ return Describe(hwnd);
732
+ }
733
+ }
734
+
735
+ internal static class Apps
736
+ {
737
+ static List<KeyValuePair<string, string>> cache;
738
+ static DateTime cachedAt;
739
+
740
+ static List<KeyValuePair<string, string>> All()
741
+ {
742
+ if (cache != null && (DateTime.UtcNow - cachedAt).TotalSeconds < 120) return cache;
743
+ var list = new List<KeyValuePair<string, string>>();
744
+ Type t = Type.GetTypeFromProgID("Shell.Application");
745
+ dynamic shell = Activator.CreateInstance(t);
746
+ try
747
+ {
748
+ dynamic folder = shell.NameSpace("shell:AppsFolder");
749
+ foreach (dynamic item in folder.Items())
750
+ {
751
+ string name = item.Name; string path = item.Path;
752
+ if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(path)) list.Add(new KeyValuePair<string, string>(name, path));
753
+ }
754
+ }
755
+ finally { Marshal.FinalReleaseComObject(shell); }
756
+ cache = list; cachedAt = DateTime.UtcNow;
757
+ return list;
758
+ }
759
+
760
+ public static List<object> Search(string query, int limit)
761
+ {
762
+ string q = query.Trim().ToLowerInvariant();
763
+ var scored = new List<KeyValuePair<int, KeyValuePair<string, string>>>();
764
+ foreach (var app in All())
765
+ {
766
+ string n = app.Key.ToLowerInvariant();
767
+ int score = n == q ? 0 : n.StartsWith(q) ? 1 : n.Contains(q) ? 2 : (q.Length > 0 && q.Contains(n)) ? 3 : app.Value.ToLowerInvariant().Contains(q) ? 4 : -1;
768
+ if (q.Length == 0) score = 5;
769
+ if (score >= 0) scored.Add(new KeyValuePair<int, KeyValuePair<string, string>>(score * 1000 + Math.Min(n.Length, 999), app));
770
+ }
771
+ scored.Sort(delegate (KeyValuePair<int, KeyValuePair<string, string>> a, KeyValuePair<int, KeyValuePair<string, string>> b) { return a.Key.CompareTo(b.Key); });
772
+ var result = new List<object>();
773
+ for (int i = 0; i < scored.Count && i < limit; i++)
774
+ {
775
+ var d = new Dictionary<string, object>();
776
+ d["name"] = scored[i].Value.Key; d["id"] = scored[i].Value.Value;
777
+ result.Add(d);
778
+ }
779
+ return result;
780
+ }
781
+
782
+ public static object Launch(Dictionary<string, object> r)
783
+ {
784
+ string appId = Args.Str(r, "appId", "");
785
+ string target = Args.Str(r, "target", "");
786
+ string args = Args.Str(r, "args", "");
787
+ ProcessStartInfo psi;
788
+ if (appId.Length > 0) psi = new ProcessStartInfo("explorer.exe", "shell:AppsFolder\\" + appId);
789
+ else { psi = new ProcessStartInfo(target); if (args.Length > 0) psi.Arguments = args; }
790
+ psi.UseShellExecute = true;
791
+ using (var p = Process.Start(psi)) { }
792
+ return null;
793
+ }
794
+ }
795
+
796
+ internal static class Uia
797
+ {
798
+ static readonly ControlType[] Interactive = {
799
+ ControlType.Button, ControlType.Edit, ControlType.Hyperlink, ControlType.MenuItem, ControlType.ListItem,
800
+ ControlType.TabItem, ControlType.CheckBox, ControlType.RadioButton, ControlType.ComboBox, ControlType.TreeItem,
801
+ ControlType.DataItem, ControlType.SplitButton, ControlType.Slider, ControlType.Spinner, ControlType.Document,
802
+ ControlType.MenuBar, ControlType.Menu, ControlType.ScrollBar };
803
+
804
+ public static object Elements(Dictionary<string, object> r)
805
+ {
806
+ IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
807
+ int max = Args.Int(r, "maxNodes", 150);
808
+ bool all = Args.Bool(r, "includeText", false);
809
+ List<object> result = null; Exception error = null;
810
+ var worker = new Thread(delegate ()
811
+ {
812
+ try
813
+ {
814
+ result = Collect(hwnd, max, all);
815
+ if (result.Count < 4) { Thread.Sleep(400); result = Collect(hwnd, max, all); } // Chromium builds its tree lazily
816
+ }
817
+ catch (Exception ex) { error = ex; }
818
+ });
819
+ worker.IsBackground = true;
820
+ worker.SetApartmentState(ApartmentState.MTA);
821
+ worker.Start();
822
+ if (!worker.Join(Args.Int(r, "timeoutMs", 8000))) throw new Exception("UI Automation timed out on this window");
823
+ if (error != null) throw error;
824
+ var d = Windows.Describe(hwnd);
825
+ d["elements"] = result;
826
+ return d;
827
+ }
828
+
829
+ static List<object> Collect(IntPtr hwnd, int max, bool includeText)
830
+ {
831
+ var root = AutomationElement.FromHandle(hwnd);
832
+ var types = new List<Condition>();
833
+ foreach (var t in Interactive) types.Add(new PropertyCondition(AutomationElement.ControlTypeProperty, t));
834
+ if (includeText) types.Add(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text));
835
+ var cond = new AndCondition(new PropertyCondition(AutomationElement.IsOffscreenProperty, false), new OrCondition(types.ToArray()));
836
+ var cache = new CacheRequest();
837
+ cache.Add(AutomationElement.NameProperty);
838
+ cache.Add(AutomationElement.ControlTypeProperty);
839
+ cache.Add(AutomationElement.BoundingRectangleProperty);
840
+ cache.Add(AutomationElement.IsEnabledProperty);
841
+ cache.Add(AutomationElement.AutomationIdProperty);
842
+ cache.Add(ValuePattern.ValueProperty);
843
+ cache.Add(TogglePattern.ToggleStateProperty);
844
+ cache.AutomationElementMode = AutomationElementMode.None;
845
+ cache.TreeScope = TreeScope.Element;
846
+ AutomationElementCollection found;
847
+ using (cache.Activate()) { found = root.FindAll(TreeScope.Descendants, cond); }
848
+ var list = new List<object>();
849
+ foreach (AutomationElement el in found)
850
+ {
851
+ if (list.Count >= max) break;
852
+ var rect = (System.Windows.Rect)el.GetCachedPropertyValue(AutomationElement.BoundingRectangleProperty);
853
+ if (rect.IsEmpty || rect.Width < 2 || rect.Height < 2) continue;
854
+ var type = (ControlType)el.GetCachedPropertyValue(AutomationElement.ControlTypeProperty);
855
+ string name = (el.GetCachedPropertyValue(AutomationElement.NameProperty) as string) ?? "";
856
+ var d = new Dictionary<string, object>();
857
+ d["role"] = type.ProgrammaticName.Replace("ControlType.", "");
858
+ d["name"] = name.Length > 120 ? name.Substring(0, 120) + "…" : name;
859
+ object value = el.GetCachedPropertyValue(ValuePattern.ValueProperty, true);
860
+ if (value is string && ((string)value).Length > 0) { var v = (string)value; d["value"] = v.Length > 120 ? v.Substring(0, 120) + "…" : v; }
861
+ object toggle = el.GetCachedPropertyValue(TogglePattern.ToggleStateProperty, true);
862
+ if (toggle is ToggleState) d["checked"] = (ToggleState)toggle == ToggleState.On;
863
+ if (!(bool)el.GetCachedPropertyValue(AutomationElement.IsEnabledProperty)) d["disabled"] = true;
864
+ if (type == ControlType.Document && name.Length == 0 && !d.ContainsKey("value")) continue;
865
+ d["x"] = (int)rect.X; d["y"] = (int)rect.Y; d["width"] = (int)rect.Width; d["height"] = (int)rect.Height;
866
+ list.Add(d);
867
+ }
868
+ return list;
869
+ }
870
+ }
871
+
872
+ // ---------------------------------------------------------------- overlay
873
+
874
+ internal class LayeredForm : Form
875
+ {
876
+ readonly bool clickThrough;
877
+ public Rectangle Physical;
878
+
879
+ public LayeredForm(bool clickThrough)
880
+ {
881
+ this.clickThrough = clickThrough;
882
+ FormBorderStyle = FormBorderStyle.None;
883
+ ShowInTaskbar = false;
884
+ StartPosition = FormStartPosition.Manual;
885
+ AutoScaleMode = AutoScaleMode.None;
886
+ TopMost = true;
887
+ }
888
+
889
+ protected override bool ShowWithoutActivation { get { return true; } }
890
+
891
+ protected override CreateParams CreateParams
892
+ {
893
+ get
894
+ {
895
+ var cp = base.CreateParams;
896
+ cp.ExStyle |= 0x80000 | 0x80 | 0x8000000 | 0x8; // LAYERED | TOOLWINDOW | NOACTIVATE | TOPMOST
897
+ if (clickThrough) cp.ExStyle |= 0x20; // TRANSPARENT
898
+ return cp;
899
+ }
900
+ }
901
+
902
+ protected override void OnHandleCreated(EventArgs e)
903
+ {
904
+ base.OnHandleCreated(e);
905
+ // Keep the overlay out of every screenshot, including our own.
906
+ if (Overlay.ExcludeFromCapture) { try { Native.SetWindowDisplayAffinity(Handle, 0x11); } catch (Exception) { } }
907
+ }
908
+
909
+ protected override void WndProc(ref Message m)
910
+ {
911
+ if (m.Msg == 0x21) { m.Result = new IntPtr(3); return; } // WM_MOUSEACTIVATE -> MA_NOACTIVATE
912
+ base.WndProc(ref m);
913
+ }
914
+
915
+ public void SetBitmap(Bitmap bmp, Rectangle bounds, byte alpha)
916
+ {
917
+ Physical = bounds;
918
+ IntPtr screenDc = Native.GetDC(IntPtr.Zero);
919
+ IntPtr memDc = Native.CreateCompatibleDC(screenDc);
920
+ IntPtr hBitmap = IntPtr.Zero, old = IntPtr.Zero;
921
+ try
922
+ {
923
+ hBitmap = bmp.GetHbitmap(Color.FromArgb(0));
924
+ old = Native.SelectObject(memDc, hBitmap);
925
+ var size = new Native.SIZE(bmp.Width, bmp.Height);
926
+ var src = new Native.POINT(0, 0);
927
+ var dst = new Native.POINT(bounds.X, bounds.Y);
928
+ var blend = new Native.BLENDFUNCTION(); blend.BlendOp = 0; blend.SourceConstantAlpha = alpha; blend.AlphaFormat = 1;
929
+ Native.UpdateLayeredWindow(Handle, screenDc, ref dst, ref size, memDc, ref src, 0, ref blend, 2);
930
+ }
931
+ finally
932
+ {
933
+ Native.ReleaseDC(IntPtr.Zero, screenDc);
934
+ if (hBitmap != IntPtr.Zero) { Native.SelectObject(memDc, old); Native.DeleteObject(hBitmap); }
935
+ Native.DeleteDC(memDc);
936
+ }
937
+ }
938
+
939
+ public void SetAlpha(byte alpha)
940
+ {
941
+ var blend = new Native.BLENDFUNCTION(); blend.BlendOp = 0; blend.SourceConstantAlpha = alpha; blend.AlphaFormat = 1;
942
+ Native.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, ref blend, 2);
943
+ }
944
+
945
+ public void KeepOnTop()
946
+ {
947
+ Native.SetWindowPos(Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010 | 0x0200); // NOSIZE|NOMOVE|NOACTIVATE|NOOWNERZORDER
948
+ }
949
+ }
950
+
951
+ internal static class Overlay
952
+ {
953
+ static readonly Color Accent = Color.FromArgb(217, 119, 87); // #D97757
954
+ static readonly Color AccentHi = Color.FromArgb(240, 160, 106); // #F0A06A
955
+
956
+ public static volatile bool ExcludeFromCapture = true;
957
+ static Thread thread;
958
+ static Control invoker;
959
+ static readonly List<LayeredForm> glows = new List<LayeredForm>();
960
+ static LayeredForm pill;
961
+ static Rectangle pillRect, stopRect, pillDisplay;
962
+ static bool pillAtBottom;
963
+ static string label = "", status = "";
964
+ static float pillScale = 1f;
965
+ static System.Windows.Forms.Timer timer;
966
+ static DateTime shownAt;
967
+ static IntPtr hook = IntPtr.Zero;
968
+ static Native.LowLevelKeyboardProc hookProc;
969
+ static volatile bool visible;
970
+ static readonly object RectLock = new object();
971
+
972
+ static void Ensure()
973
+ {
974
+ if (thread != null) return;
975
+ var ready = new ManualResetEvent(false);
976
+ thread = new Thread(delegate ()
977
+ {
978
+ invoker = new Control();
979
+ var force = invoker.Handle;
980
+ timer = new System.Windows.Forms.Timer();
981
+ timer.Interval = 40;
982
+ timer.Tick += delegate { Tick(); };
983
+ ready.Set();
984
+ Application.Run();
985
+ });
986
+ thread.IsBackground = true;
987
+ thread.SetApartmentState(ApartmentState.STA);
988
+ thread.Start();
989
+ ready.WaitOne();
990
+ }
991
+
992
+ static void Ui(MethodInvoker action) { invoker.Invoke(action); }
993
+
994
+ public static void Show(string newLabel, string newStatus, bool glow)
995
+ {
996
+ Ensure();
997
+ Ui(delegate
998
+ {
999
+ label = newLabel; status = newStatus;
1000
+ if (visible) { RenderPill(); return; }
1001
+ pillAtBottom = false;
1002
+ foreach (var g in glows) g.Close();
1003
+ glows.Clear();
1004
+ if (glow)
1005
+ {
1006
+ foreach (Dictionary<string, object> d in Screen2.Displays())
1007
+ {
1008
+ var bounds = new Rectangle((int)d["x"], (int)d["y"], (int)d["width"], (int)d["height"]);
1009
+ var form = new LayeredForm(true);
1010
+ form.Show();
1011
+ using (var bmp = DrawGlow(bounds.Width, bounds.Height, (int)d["dpi"] / 96f)) form.SetBitmap(bmp, bounds, 255);
1012
+ glows.Add(form);
1013
+ }
1014
+ }
1015
+ if (pill == null)
1016
+ {
1017
+ pill = new LayeredForm(false);
1018
+ pill.MouseUp += delegate (object s, MouseEventArgs e)
1019
+ {
1020
+ if (stopRect.Contains(e.Location)) { Program.EmitEvent("stop", "button"); }
1021
+ };
1022
+ pill.Show();
1023
+ }
1024
+ RenderPill();
1025
+ InstallHook();
1026
+ shownAt = DateTime.UtcNow;
1027
+ visible = true;
1028
+ timer.Start();
1029
+ });
1030
+ }
1031
+
1032
+ public static void Status(string newStatus)
1033
+ {
1034
+ if (thread == null || !visible) return;
1035
+ Ui(delegate { status = newStatus; RenderPill(); });
1036
+ }
1037
+
1038
+ public static void Hide()
1039
+ {
1040
+ if (thread == null) return;
1041
+ Ui(delegate
1042
+ {
1043
+ visible = false;
1044
+ timer.Stop();
1045
+ foreach (var g in glows) g.Close();
1046
+ glows.Clear();
1047
+ if (pill != null) { pill.Close(); pill = null; }
1048
+ lock (RectLock) pillRect = Rectangle.Empty;
1049
+ RemoveHook();
1050
+ });
1051
+ }
1052
+
1053
+ public static void Shutdown()
1054
+ {
1055
+ if (thread == null) return;
1056
+ try { Hide(); Ui(delegate { Application.ExitThread(); }); } catch (Exception) { }
1057
+ }
1058
+
1059
+ /// Move the status pill out of the way when an injected pointer action
1060
+ /// targets it: the pill is clickable for the user but invisible to the model.
1061
+ public static void Dodge(int x, int y)
1062
+ {
1063
+ Rectangle r;
1064
+ lock (RectLock) r = pillRect;
1065
+ if (r.IsEmpty) return;
1066
+ var inflated = Rectangle.Inflate(r, 12, 12);
1067
+ if (!inflated.Contains(x, y)) return;
1068
+ Ui(delegate { pillAtBottom = !pillAtBottom; RenderPill(); });
1069
+ Thread.Sleep(30);
1070
+ }
1071
+
1072
+ static void Tick()
1073
+ {
1074
+ if (!visible) return;
1075
+ double t = (DateTime.UtcNow - shownAt).TotalSeconds;
1076
+ double fadeIn = Math.Min(1.0, t / 0.35);
1077
+ double breathe = 0.72 + 0.28 * (0.5 + 0.5 * Math.Sin(t * Math.PI * 2 / 2.6));
1078
+ byte alpha = (byte)Math.Max(0, Math.Min(255, 255 * fadeIn * breathe));
1079
+ foreach (var g in glows) g.SetAlpha(alpha);
1080
+ if ((int)(t * 25) % 50 == 0)
1081
+ {
1082
+ foreach (var g in glows) g.KeepOnTop();
1083
+ if (pill != null) pill.KeepOnTop();
1084
+ }
1085
+ }
1086
+
1087
+ static Bitmap DrawGlow(int w, int h, float scale)
1088
+ {
1089
+ var bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb);
1090
+ using (var g = Graphics.FromImage(bmp))
1091
+ {
1092
+ g.Clear(Color.Transparent);
1093
+ int depth = Math.Max(14, (int)(30 * scale));
1094
+ for (int i = 0; i < depth; i++)
1095
+ {
1096
+ double f = 1.0 - (double)i / depth;
1097
+ int a = (int)(185 * Math.Pow(f, 1.9));
1098
+ if (a <= 0) continue;
1099
+ using (var pen = new Pen(Color.FromArgb(a, Accent), 1))
1100
+ g.DrawRectangle(pen, i, i, w - 1 - 2 * i, h - 1 - 2 * i);
1101
+ }
1102
+ int line = Math.Max(2, (int)Math.Round(2.5 * scale));
1103
+ using (var pen = new Pen(Color.FromArgb(235, AccentHi), line))
1104
+ {
1105
+ pen.Alignment = PenAlignment.Inset;
1106
+ g.DrawRectangle(pen, 0, 0, w, h);
1107
+ }
1108
+ }
1109
+ return bmp;
1110
+ }
1111
+
1112
+ static GraphicsPath Rounded(RectangleF r, float radius)
1113
+ {
1114
+ var p = new GraphicsPath();
1115
+ float d = radius * 2;
1116
+ p.AddArc(r.X, r.Y, d, d, 180, 90);
1117
+ p.AddArc(r.Right - d, r.Y, d, d, 270, 90);
1118
+ p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
1119
+ p.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
1120
+ p.CloseFigure();
1121
+ return p;
1122
+ }
1123
+
1124
+ static void DrawSpark(Graphics g, float cx, float cy, float radius, Color color, float width)
1125
+ {
1126
+ using (var pen = new Pen(color, width))
1127
+ {
1128
+ pen.StartCap = LineCap.Round; pen.EndCap = LineCap.Round;
1129
+ for (int i = 0; i < 6; i++)
1130
+ {
1131
+ double a = Math.PI * i / 6;
1132
+ float dx = (float)(Math.Cos(a) * radius), dy = (float)(Math.Sin(a) * radius);
1133
+ g.DrawLine(pen, cx - dx, cy - dy, cx + dx, cy + dy);
1134
+ }
1135
+ }
1136
+ }
1137
+
1138
+ static void RenderPill()
1139
+ {
1140
+ if (pill == null) return;
1141
+ // The pill lives on the primary display (or the first one).
1142
+ Rectangle work = Rectangle.Empty; float scale = 1f;
1143
+ foreach (Dictionary<string, object> d in Screen2.Displays())
1144
+ {
1145
+ if (work.IsEmpty || (bool)d["primary"])
1146
+ {
1147
+ work = new Rectangle((int)d["workX"], (int)d["workY"], (int)d["workWidth"], (int)d["workHeight"]);
1148
+ scale = (int)d["dpi"] / 96f;
1149
+ }
1150
+ }
1151
+ pillDisplay = work; pillScale = scale;
1152
+
1153
+ string main = label;
1154
+ string hint = "Esc 停止";
1155
+ float px = 1.333f * scale; // points -> physical pixels
1156
+ using (var fMain = new Font("Microsoft YaHei UI", 10f * px, FontStyle.Bold, GraphicsUnit.Pixel))
1157
+ using (var fSub = new Font("Microsoft YaHei UI", 9f * px, FontStyle.Regular, GraphicsUnit.Pixel))
1158
+ using (var fBtn = new Font("Microsoft YaHei UI", 9f * px, FontStyle.Bold, GraphicsUnit.Pixel))
1159
+ using (var measureBmp = new Bitmap(1, 1))
1160
+ using (var mg = Graphics.FromImage(measureBmp))
1161
+ {
1162
+ mg.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
1163
+ var fmt = StringFormat.GenericTypographic;
1164
+ fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
1165
+ string sub = status.Length > 0 ? status : hint;
1166
+ if (sub.Length > 48) sub = sub.Substring(0, 47) + "…";
1167
+ SizeF mainSize = mg.MeasureString(main, fMain, 10000, fmt);
1168
+ SizeF subSize = mg.MeasureString(sub, fSub, 10000, fmt);
1169
+ SizeF btnSize = mg.MeasureString("停止", fBtn, 10000, fmt);
1170
+ float pad = 14 * scale, gap = 10 * scale, icon = 18 * scale;
1171
+ float height = 40 * scale;
1172
+ float btnW = btnSize.Width + 22 * scale, btnH = 26 * scale;
1173
+ float width = pad + icon + gap + mainSize.Width + gap + 1 * scale + gap + subSize.Width + gap + btnW + (pad - 7 * scale);
1174
+ int W = (int)Math.Ceiling(width), H = (int)Math.Ceiling(height);
1175
+ int x = work.X + (work.Width - W) / 2;
1176
+ int y = pillAtBottom ? work.Bottom - H - (int)(18 * scale) : work.Y + (int)(14 * scale);
1177
+
1178
+ using (var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb))
1179
+ using (var g = Graphics.FromImage(bmp))
1180
+ {
1181
+ g.Clear(Color.Transparent);
1182
+ g.SmoothingMode = SmoothingMode.AntiAlias;
1183
+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
1184
+ var body = new RectangleF(0.5f, 0.5f, W - 1, H - 1);
1185
+ using (var path = Rounded(body, (H - 1) / 2f))
1186
+ {
1187
+ using (var brush = new SolidBrush(Color.FromArgb(242, 31, 30, 29))) g.FillPath(brush, path);
1188
+ using (var pen = new Pen(Color.FromArgb(200, Accent), Math.Max(1f, 1.2f * scale))) g.DrawPath(pen, path);
1189
+ }
1190
+ float cx = pad + icon / 2, cy = H / 2f;
1191
+ DrawSpark(g, cx, cy, icon / 2, Accent, Math.Max(1.6f, 2.1f * scale));
1192
+ float tx = pad + icon + gap;
1193
+ using (var b = new SolidBrush(Color.FromArgb(250, 250, 249))) g.DrawString(main, fMain, b, tx, (H - mainSize.Height) / 2f, fmt);
1194
+ tx += mainSize.Width + gap;
1195
+ using (var pen = new Pen(Color.FromArgb(90, 255, 255, 255), Math.Max(1f, scale))) g.DrawLine(pen, tx, H * 0.3f, tx, H * 0.7f);
1196
+ tx += 1 * scale + gap;
1197
+ using (var b = new SolidBrush(Color.FromArgb(175, 172, 168))) g.DrawString(sub, fSub, b, tx, (H - subSize.Height) / 2f, fmt);
1198
+ tx += subSize.Width + gap;
1199
+ var btn = new RectangleF(tx, (H - btnH) / 2f, btnW, btnH);
1200
+ using (var path = Rounded(btn, btnH / 2f))
1201
+ using (var brush = new SolidBrush(Accent)) g.FillPath(brush, path);
1202
+ using (var b = new SolidBrush(Color.White)) g.DrawString("停止", fBtn, b, btn.X + (btnW - btnSize.Width) / 2f, btn.Y + (btnH - btnSize.Height) / 2f, fmt);
1203
+ stopRect = Rectangle.Round(btn);
1204
+ pill.SetBitmap(bmp, new Rectangle(x, y, W, H), 255);
1205
+ }
1206
+ lock (RectLock) pillRect = new Rectangle(x, y, W, H);
1207
+ }
1208
+ pill.KeepOnTop();
1209
+ }
1210
+
1211
+ static void InstallHook()
1212
+ {
1213
+ if (hook != IntPtr.Zero) return;
1214
+ hookProc = HookCallback;
1215
+ hook = Native.SetWindowsHookEx(13, hookProc, Native.GetModuleHandle(null), 0);
1216
+ }
1217
+
1218
+ static void RemoveHook()
1219
+ {
1220
+ if (hook == IntPtr.Zero) return;
1221
+ Native.UnhookWindowsHookEx(hook);
1222
+ hook = IntPtr.Zero;
1223
+ }
1224
+
1225
+ static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
1226
+ {
1227
+ if (nCode >= 0 && visible && (wParam.ToInt32() == 0x100 || wParam.ToInt32() == 0x104))
1228
+ {
1229
+ var kb = (Native.KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.KBDLLHOOKSTRUCT));
1230
+ // Only a physical Esc counts: our own SendInput sets LLKHF_INJECTED (0x10).
1231
+ if (kb.vkCode == 0x1B && (kb.flags & 0x10) == 0) Program.EmitEvent("stop", "esc");
1232
+ }
1233
+ return Native.CallNextHookEx(hook, nCode, wParam, lParam);
1234
+ }
1235
+ }
1236
+ }