@copylee/dsh-computer-use 0.12.0 → 0.13.1

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.
@@ -1,4749 +0,0 @@
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.Reflection;
25
- using System.Runtime.InteropServices;
26
- using System.Text;
27
- using System.Threading;
28
- using System.Web.Script.Serialization;
29
- using System.Windows.Automation;
30
- using System.Windows.Forms;
31
- using Microsoft.Win32;
32
-
33
- namespace DshComputerUse
34
- {
35
- internal static class Native
36
- {
37
- [DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
38
- [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
39
-
40
- [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; public POINT(int x, int y) { X = x; Y = y; } }
41
- [StructLayout(LayoutKind.Sequential)] public struct SIZE { public int cx; public int cy; public SIZE(int w, int h) { cx = w; cy = h; } }
42
- [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
43
-
44
- [StructLayout(LayoutKind.Sequential)]
45
- public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
46
- [StructLayout(LayoutKind.Sequential)]
47
- public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
48
- [StructLayout(LayoutKind.Explicit)]
49
- public struct InputUnion { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
50
- [StructLayout(LayoutKind.Sequential)]
51
- public struct INPUT { public uint type; public InputUnion u; }
52
-
53
- [DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint n, INPUT[] inputs, int size);
54
- [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
55
- [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
56
- [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint code, uint mapType);
57
-
58
- public delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdc, ref RECT rect, IntPtr data);
59
- [DllImport("user32.dll")] public static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr clip, MonitorEnumProc proc, IntPtr data);
60
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
61
- public struct MONITORINFOEX { public int cbSize; public RECT rcMonitor; public RECT rcWork; public uint dwFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string szDevice; }
62
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFOEX info);
63
- [DllImport("shcore.dll")] public static extern int GetDpiForMonitor(IntPtr hMonitor, int type, out uint dpiX, out uint dpiY);
64
-
65
- [DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hwnd);
66
- [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);
67
- [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);
68
- [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
69
- [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hdc);
70
- [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj);
71
- [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr obj);
72
-
73
- public delegate bool EnumWindowsProc(IntPtr hwnd, IntPtr data);
74
- [DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc proc, IntPtr data);
75
- [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hwnd);
76
- [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hwnd);
77
- [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hwnd);
78
- [DllImport("user32.dll")] public static extern bool IsZoomed(IntPtr hwnd);
79
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hwnd, StringBuilder sb, int max);
80
- [DllImport("user32.dll")] public static extern int GetWindowTextLength(IntPtr hwnd);
81
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr hwnd, StringBuilder sb, int max);
82
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string cls, string title);
83
- [DllImport("user32.dll")] public static extern IntPtr SendMessageTimeout(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam, uint flags, uint timeout, out IntPtr result);
84
- [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hwnd, uint cmd);
85
- [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hwnd, int index);
86
- [DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr hwnd, int index, int value);
87
- [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern bool SetProp(IntPtr hwnd, string name, IntPtr value);
88
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr GetProp(IntPtr hwnd, string name);
89
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr RemoveProp(IntPtr hwnd, string name);
90
- [DllImport("user32.dll")] public static extern bool GetLayeredWindowAttributes(IntPtr hwnd, out uint key, out byte alpha, out uint flags);
91
- [DllImport("user32.dll")] public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint key, byte alpha, uint flags);
92
- [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint pid);
93
- [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
94
- [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hwnd);
95
- [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hwnd);
96
- [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hwnd, int cmd);
97
- [DllImport("user32.dll")] public static extern void SwitchToThisWindow(IntPtr hwnd, bool altTab);
98
- [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool attach);
99
- [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
100
- [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hwnd, uint msg, IntPtr w, IntPtr l);
101
- [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
102
- [DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr hwnd, uint flags);
103
- [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags);
104
- [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hwnd, out RECT r);
105
- [StructLayout(LayoutKind.Sequential)]
106
- public struct WINDOWPLACEMENT { public int length; public int flags; public int showCmd; public POINT ptMinPosition; public POINT ptMaxPosition; public RECT rcNormalPosition; }
107
- [DllImport("user32.dll")] public static extern bool GetWindowPlacement(IntPtr hwnd, ref WINDOWPLACEMENT wp);
108
- [DllImport("user32.dll")] public static extern bool SetWindowPlacement(IntPtr hwnd, ref WINDOWPLACEMENT wp);
109
- [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int attr, out RECT value, int size);
110
- [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hwnd, int attr, out int value, int size);
111
-
112
- [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
113
- [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr h);
114
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern bool QueryFullProcessImageName(IntPtr h, int flags, StringBuilder sb, ref int size);
115
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr GetModuleHandle(string name);
116
-
117
- [StructLayout(LayoutKind.Sequential, Pack = 1)]
118
- public struct BLENDFUNCTION { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; }
119
- [DllImport("user32.dll", SetLastError = true)]
120
- 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);
121
- [DllImport("user32.dll", SetLastError = true)]
122
- public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, IntPtr psize, IntPtr hdcSrc, IntPtr pptSrc, int crKey, ref BLENDFUNCTION pblend, int flags);
123
- [DllImport("user32.dll")] public static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint affinity);
124
- [DllImport("user32.dll")] public static extern bool ReleaseCapture();
125
- [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr w, IntPtr l);
126
- [StructLayout(LayoutKind.Sequential)]
127
- public struct GUITHREADINFO { public int cbSize; public int flags; public IntPtr hwndActive; public IntPtr hwndFocus; public IntPtr hwndCapture; public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize; public IntPtr hwndCaret; public RECT rcCaret; }
128
- [DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint idThread, ref GUITHREADINFO lpgui);
129
-
130
- public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
131
- public delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
132
- [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc fn, IntPtr hMod, uint threadId);
133
- [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelMouseProc fn, IntPtr hMod, uint threadId);
134
- [DllImport("user32.dll")] public static extern bool UnhookWindowsHookEx(IntPtr hook);
135
- [DllImport("user32.dll")] public static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wParam, IntPtr lParam);
136
- [StructLayout(LayoutKind.Sequential)]
137
- public struct KBDLLHOOKSTRUCT { public uint vkCode; public uint scanCode; public uint flags; public uint time; public IntPtr dwExtraInfo; }
138
- [StructLayout(LayoutKind.Sequential)]
139
- public struct MSLLHOOKSTRUCT { public POINT pt; public uint mouseData; public uint flags; public uint time; public IntPtr dwExtraInfo; }
140
-
141
- public const uint INPUT_MOUSE = 0, INPUT_KEYBOARD = 1;
142
- public const uint KEYEVENTF_EXTENDEDKEY = 0x1, KEYEVENTF_KEYUP = 0x2, KEYEVENTF_UNICODE = 0x4;
143
- public const uint MOUSEEVENTF_MOVE = 0x1, MOUSEEVENTF_LEFTDOWN = 0x2, MOUSEEVENTF_LEFTUP = 0x4, MOUSEEVENTF_RIGHTDOWN = 0x8, MOUSEEVENTF_RIGHTUP = 0x10,
144
- MOUSEEVENTF_MIDDLEDOWN = 0x20, MOUSEEVENTF_MIDDLEUP = 0x40, MOUSEEVENTF_WHEEL = 0x800, MOUSEEVENTF_HWHEEL = 0x1000;
145
- public static readonly IntPtr Marker = new IntPtr(0x44534843); // "DSHC"
146
- }
147
-
148
- internal static class Args
149
- {
150
- public static bool Has(Dictionary<string, object> d, string k) { object v; return d.TryGetValue(k, out v) && v != null; }
151
- public static int Int(Dictionary<string, object> d, string k, int def)
152
- {
153
- object v; if (!d.TryGetValue(k, out v) || v == null) return def;
154
- return (int)Math.Round(Convert.ToDouble(v));
155
- }
156
- public static double Double(Dictionary<string, object> d, string k, double def)
157
- {
158
- object v;
159
- return d.TryGetValue(k, out v) && v != null ? Convert.ToDouble(v, System.Globalization.CultureInfo.InvariantCulture) : def;
160
- }
161
- public static string Str(Dictionary<string, object> d, string k, string def)
162
- {
163
- object v; if (!d.TryGetValue(k, out v) || v == null) return def;
164
- return Convert.ToString(v);
165
- }
166
- public static bool Bool(Dictionary<string, object> d, string k, bool def)
167
- {
168
- object v; if (!d.TryGetValue(k, out v) || v == null) return def;
169
- return Convert.ToBoolean(v);
170
- }
171
- public static List<string> Strs(Dictionary<string, object> d, string k)
172
- {
173
- var list = new List<string>(); object v;
174
- if (d.TryGetValue(k, out v) && v is IEnumerable && !(v is string))
175
- foreach (var item in (IEnumerable)v) list.Add(Convert.ToString(item));
176
- return list;
177
- }
178
- public static List<int> Ints(Dictionary<string, object> d, string k)
179
- {
180
- var list = new List<int>(); object v;
181
- if (d.TryGetValue(k, out v) && v is IEnumerable && !(v is string))
182
- foreach (var item in (IEnumerable)v) list.Add((int)Math.Round(Convert.ToDouble(item)));
183
- return list;
184
- }
185
- public static List<List<int>> IntLists(Dictionary<string, object> d, string k)
186
- {
187
- var list = new List<List<int>>(); object v;
188
- if (d.TryGetValue(k, out v) && v is IEnumerable && !(v is string))
189
- foreach (var row in (IEnumerable)v)
190
- {
191
- var inner = new List<int>();
192
- foreach (var item in (IEnumerable)row) inner.Add((int)Math.Round(Convert.ToDouble(item)));
193
- list.Add(inner);
194
- }
195
- return list;
196
- }
197
- }
198
-
199
- internal static class Program
200
- {
201
- static readonly object OutLock = new object();
202
- static TextWriter Out;
203
- public const string Version = "1";
204
-
205
- [STAThread]
206
- static int Main(string[] argv)
207
- {
208
- // Must precede every GDI / WinForms call, or the process is stuck in
209
- // DPI-virtualised coordinates.
210
- try { if (!Native.SetProcessDpiAwarenessContext(new IntPtr(-4))) Native.SetProcessDPIAware(); }
211
- catch (Exception) { try { Native.SetProcessDPIAware(); } catch (Exception) { } }
212
-
213
- var utf8 = new UTF8Encoding(false);
214
- var writer = new StreamWriter(Console.OpenStandardOutput(), utf8);
215
- writer.AutoFlush = true;
216
- Out = writer;
217
- var input = new StreamReader(Console.OpenStandardInput(), utf8);
218
- var parser = new JavaScriptSerializer();
219
- parser.MaxJsonLength = int.MaxValue;
220
- Apps.Warm();
221
- Windows.RecoverCards(false);
222
-
223
- var hello = new Dictionary<string, object>();
224
- hello["event"] = "ready"; hello["version"] = Version; hello["pid"] = Process.GetCurrentProcess().Id;
225
- Emit(hello);
226
-
227
- try {
228
- string line;
229
- while ((line = input.ReadLine()) != null)
230
- {
231
- if (line.Trim().Length == 0) continue;
232
- object id = null;
233
- var reply = new Dictionary<string, object>();
234
- try
235
- {
236
- var req = (Dictionary<string, object>)parser.DeserializeObject(line);
237
- if (req.ContainsKey("id")) id = req["id"];
238
- reply["id"] = id;
239
- reply["result"] = Commands.Run(req);
240
- reply["ok"] = true;
241
- }
242
- catch (Exception ex)
243
- {
244
- reply["id"] = id;
245
- reply["ok"] = false;
246
- reply["error"] = ex.Message;
247
- }
248
- Emit(reply);
249
- }
250
- }
251
- finally { Windows.RecoverCards(true); Overlay.Shutdown(); }
252
- return 0;
253
- }
254
-
255
- public static void Emit(Dictionary<string, object> msg)
256
- {
257
- lock (OutLock)
258
- {
259
- var s = new JavaScriptSerializer();
260
- s.MaxJsonLength = int.MaxValue;
261
- Out.Write(s.Serialize(msg));
262
- Out.Write('\n');
263
- Out.Flush();
264
- }
265
- }
266
-
267
- public static void EmitEvent(string name, string reason)
268
- {
269
- ThreadPool.QueueUserWorkItem(delegate
270
- {
271
- var e = new Dictionary<string, object>();
272
- e["event"] = name; e["reason"] = reason;
273
- try { Emit(e); } catch (Exception) { }
274
- });
275
- }
276
-
277
- public static void EmitDataEvent(string name, Dictionary<string, object> data)
278
- {
279
- ThreadPool.QueueUserWorkItem(delegate
280
- {
281
- var e = new Dictionary<string, object>();
282
- e["event"] = name;
283
- e["data"] = data;
284
- try { Emit(e); } catch (Exception) { }
285
- });
286
- }
287
- }
288
-
289
- internal static class Commands
290
- {
291
- public static object Run(Dictionary<string, object> r)
292
- {
293
- string cmd = Args.Str(r, "cmd", "");
294
- switch (cmd)
295
- {
296
- case "ping": { var d = new Dictionary<string, object>(); d["version"] = Program.Version; return d; }
297
- case "displays": return Screen2.Displays();
298
- case "screenshot": return Screen2.Capture(r);
299
- case "settle": return Screen2.Settle(r);
300
- case "cursor": { Native.POINT p; Native.GetCursorPos(out p); return Pt(p.X, p.Y); }
301
- case "move":
302
- using (new PassThrough())
303
- {
304
- int mx = Args.Int(r, "x", 0), my = Args.Int(r, "y", 0);
305
- Overlay.Dodge(mx, my);
306
- Input.Move(mx, my);
307
- if (Overlay.ShowClickTarget) Overlay.MarkPointer(mx, my, "DSH", 900);
308
- }
309
- return null;
310
- case "click":
311
- Native.POINT clickPoint;
312
- if (Args.Has(r, "x")) clickPoint = new Native.POINT(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
313
- else if (!Native.GetCursorPos(out clickPoint)) throw new Exception("Cannot read cursor position");
314
- using (CardLayer.UncoverClick(clickPoint))
315
- using (new PassThrough()) return Input.Click(r);
316
- case "button": using (new PassThrough()) return Input.Button(r);
317
- case "drag": using (new PassThrough()) return Input.Drag(r);
318
- case "scroll": using (new PassThrough()) return Input.Scroll(r);
319
- case "keys": return Input.Keys(r);
320
- case "key_state": return Input.KeyState(r);
321
- case "type": return Input.Type(Args.Str(r, "text", ""), Args.Int(r, "chunkDelay", 8), Args.Int(r, "charDelay", 0));
322
- case "clipboard_hold": Clip.Hold(); return null;
323
- case "clipboard_release": Clip.Release(); return null;
324
- case "paste": return Input.Paste(Args.Str(r, "text", ""), Args.Bool(r, "restore", true), Args.Int(r, "waitMs", 250));
325
- case "windows": return Windows.List();
326
- case "window_recover": Windows.RecoverCards(false); return null;
327
- case "background": return Windows.Background(Args.Bool(r, "tray", true));
328
- case "tray_restore": return Tray.Restore(Args.Str(r, "exe", ""));
329
- case "card_opacity": CardLayer.SetOpacity(Args.Int(r, "opacity", 100)); return null;
330
- case "foreground": return Windows.Describe(Native.GetForegroundWindow());
331
- case "window_at": return Windows.At(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
332
- case "focus":
333
- var focusHwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
334
- uint focusPid;
335
- if (Args.Has(r, "pid") && (Native.GetWindowThreadProcessId(focusHwnd, out focusPid) == 0 || focusPid != Convert.ToUInt32(r["pid"])))
336
- throw new Exception("window no longer belongs to the original process");
337
- return Windows.Focus(focusHwnd);
338
- case "window_cmd": return Windows.Command(new IntPtr(Convert.ToInt64(r["hwnd"])), Args.Str(r, "op", ""));
339
- case "apps": return Apps.Search(Args.Str(r, "query", ""), Args.Int(r, "limit", 8));
340
- case "launch": return Apps.Launch(r);
341
- case "open_url": return Apps.OpenUrl(Args.Str(r, "url", ""));
342
- case "browser_tab": return Uia.BrowserTab(r);
343
- case "browser_open_tab": return Uia.OpenBrowserTab(r);
344
- case "act": return Uia.Act(r);
345
- case "clipboard_get": { var d = new Dictionary<string, object>(); d["text"] = Clip.Get(); return d; }
346
- case "clipboard_set": if (Args.Bool(r, "agent", false)) Clip.AgentSet(Args.Str(r, "text", "")); else Clip.Set(Args.Str(r, "text", ""), false); return null;
347
- case "clipboard_restore": { var d = new Dictionary<string, object>(); d["restored"] = Clip.RestoreAgent(); return d; }
348
- case "ui": return Uia.Elements(r);
349
- case "text": return Uia.Text(r);
350
- case "ocr": return Ocr.Read(r);
351
- case "marks": return Uia.Marks(r);
352
- case "password_focus": return Uia.PasswordFocus();
353
- case "ui_point_click": return Uia.ClickAtPoint(r);
354
- case "overlay_show": Overlay.ExcludeFromCapture = Args.Bool(r, "excludeFromCapture", true); Overlay.Show(r); return null;
355
- case "overlay_pause": Overlay.SetPaused(Args.Bool(r, "paused", false)); return null;
356
- case "window_card": CardLayer.SetOpacity(Args.Int(r, "opacity", 100)); return Windows.Card(new IntPtr(Convert.ToInt64(r["hwnd"])), Args.Int(r, "x", 0), Args.Int(r, "y", 0), Args.Int(r, "width", 0), Args.Int(r, "height", 0));
357
- case "window_uncard": return Windows.Uncard(new IntPtr(Convert.ToInt64(r["hwnd"])));
358
- case "overlay_status": Overlay.Status(Args.Str(r, "status", "")); return null;
359
- case "pet_update": Overlay.PetUpdate(Args.Str(r, "thinking", ""), Args.Strs(r, "steps")); return null;
360
- case "pet_finish": Overlay.Finish(Args.Int(r, "holdMs", 4000)); return null;
361
- case "overlay_hide": Overlay.Hide(); return null;
362
- default: throw new Exception("unknown command: " + cmd);
363
- }
364
- }
365
-
366
- public static Dictionary<string, object> Pt(int x, int y) { var d = new Dictionary<string, object>(); d["x"] = x; d["y"] = y; return d; }
367
- }
368
-
369
- internal static class Screen2
370
- {
371
- public static List<object> Displays()
372
- {
373
- var list = new List<object>();
374
- Native.MonitorEnumProc cb = delegate (IntPtr h, IntPtr hdc, ref Native.RECT rc, IntPtr data)
375
- {
376
- var info = new Native.MONITORINFOEX();
377
- info.cbSize = Marshal.SizeOf(typeof(Native.MONITORINFOEX));
378
- Native.GetMonitorInfo(h, ref info);
379
- uint dx = 96, dy = 96;
380
- try { Native.GetDpiForMonitor(h, 0, out dx, out dy); } catch (Exception) { }
381
- var d = new Dictionary<string, object>();
382
- d["x"] = info.rcMonitor.Left; d["y"] = info.rcMonitor.Top;
383
- d["width"] = info.rcMonitor.Right - info.rcMonitor.Left; d["height"] = info.rcMonitor.Bottom - info.rcMonitor.Top;
384
- d["workX"] = info.rcWork.Left; d["workY"] = info.rcWork.Top;
385
- d["workWidth"] = info.rcWork.Right - info.rcWork.Left; d["workHeight"] = info.rcWork.Bottom - info.rcWork.Top;
386
- d["primary"] = (info.dwFlags & 1) != 0;
387
- d["dpi"] = (int)dx;
388
- d["name"] = info.szDevice;
389
- list.Add(d);
390
- return true;
391
- };
392
- Native.EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb, IntPtr.Zero);
393
- GC.KeepAlive(cb);
394
- return list;
395
- }
396
-
397
- /** Sample every 8th pixel of a screen rectangle (BGR bytes). */
398
- /** Sample the screen for settle detection; the card area is blanked (no flicker). */
399
- static byte[] Sample(int x, int y, int w, int h)
400
- {
401
- using (var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb))
402
- {
403
- using (var g = Graphics.FromImage(bmp))
404
- {
405
- IntPtr dst = g.GetHdc();
406
- IntPtr src = Native.GetDC(IntPtr.Zero);
407
- try { Native.BitBlt(dst, 0, 0, w, h, src, x, y, 0x00CC0020 | 0x40000000); }
408
- finally { Native.ReleaseDC(IntPtr.Zero, src); g.ReleaseHdc(dst); }
409
- CardLayer.Blank(g, x, y);
410
- }
411
- return SampleBitmap(bmp);
412
- }
413
- }
414
-
415
- /** Every 8th pixel of a 24-bit bitmap (BGR bytes). */
416
- static byte[] SampleBitmap(Bitmap bmp)
417
- {
418
- int w = bmp.Width, h = bmp.Height;
419
- var data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
420
- try
421
- {
422
- int sx = (w + 7) / 8, sy = (h + 7) / 8;
423
- var row = new byte[data.Stride];
424
- var outp = new byte[sx * sy * 3];
425
- int k = 0;
426
- for (int j = 0; j < sy; j++)
427
- {
428
- Marshal.Copy(new IntPtr(data.Scan0.ToInt64() + (long)j * 8 * data.Stride), row, 0, data.Stride);
429
- for (int i = 0; i < sx; i++) { int o = i * 8 * 3; outp[k++] = row[o]; outp[k++] = row[o + 1]; outp[k++] = row[o + 2]; }
430
- }
431
- return outp;
432
- }
433
- finally { bmp.UnlockBits(data); }
434
- }
435
-
436
- /** What the screen looked like in the last screenshot the model was shown (per slot: full vs zoom). */
437
- sealed class MarkedFrame
438
- {
439
- public string Rect;
440
- public byte[] Sample;
441
- public long OutPixels;
442
- public int Quality;
443
- }
444
- static readonly Dictionary<string, MarkedFrame> markedBySlot = new Dictionary<string, MarkedFrame>();
445
-
446
- static string RectKey(int x, int y, int w, int h) { return x + "," + y + "," + w + "," + h; }
447
-
448
- static double Changed(byte[] a, byte[] b)
449
- {
450
- int n = a.Length / 3, diff = 0;
451
- for (int i = 0; i < a.Length; i += 3)
452
- if (Math.Abs(a[i] - b[i]) + Math.Abs(a[i + 1] - b[i + 1]) + Math.Abs(a[i + 2] - b[i + 2]) > 30) diff++;
453
- return n == 0 ? 0 : (double)diff / n;
454
- }
455
-
456
- /**
457
- * Wait until the screen stops changing: at least minMs, then until two
458
- * consecutive samples (quietMs apart in total) differ in under 0.2% of
459
- * the sampled pixels, or maxMs passes (videos, spinners).
460
- */
461
- public static Dictionary<string, object> Settle(Dictionary<string, object> r)
462
- {
463
- 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);
464
- int minMs = Args.Int(r, "minMs", 300), maxMs = Args.Int(r, "maxMs", 2500), interval = Args.Int(r, "intervalMs", 120), quietMs = Args.Int(r, "quietMs", 240);
465
- if (w <= 0 || h <= 0) throw new Exception("invalid settle rect");
466
- var watch = System.Diagnostics.Stopwatch.StartNew();
467
- byte[] prev = Sample(x, y, w, h);
468
- long quietSince = -1;
469
- bool stable = false;
470
- while (true)
471
- {
472
- Thread.Sleep(interval);
473
- byte[] cur = Sample(x, y, w, h);
474
- long now = watch.ElapsedMilliseconds;
475
- if (Changed(prev, cur) < 0.002) { if (quietSince < 0) quietSince = now - interval; }
476
- else quietSince = -1;
477
- prev = cur;
478
- if (now >= minMs && quietSince >= 0 && now - quietSince >= quietMs) { stable = true; break; }
479
- if (now >= maxMs) break;
480
- }
481
- var d = new Dictionary<string, object>();
482
- d["ms"] = (int)watch.ElapsedMilliseconds;
483
- d["stable"] = stable;
484
- return d;
485
- }
486
-
487
- static ImageCodecInfo jpegCodec;
488
-
489
- public static Bitmap Grab(int x, int y, int w, int h, out string via)
490
- {
491
- via = "blt";
492
- var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb);
493
- try
494
- {
495
- using (var g = Graphics.FromImage(bmp))
496
- {
497
- IntPtr dst = g.GetHdc();
498
- IntPtr src = Native.GetDC(IntPtr.Zero);
499
- // The DSH card is for the user only: capture what is under it.
500
- // Preferred: the Magnification API renders the screen without
501
- // the card (no flicker). Fallback: hide the card for one BitBlt.
502
- bool done = false;
503
- var area = new Rectangle(x, y, w, h);
504
- if (CardLayer.Covers(area))
505
- {
506
- g.ReleaseHdc(dst);
507
- dst = IntPtr.Zero;
508
- using (var mag = MagCapture.Capture(area, CardLayer.Hwnd))
509
- {
510
- if (mag != null) { g.DrawImageUnscaled(mag, 0, 0); done = true; via = "mag"; }
511
- }
512
- if (!done) dst = g.GetHdc();
513
- }
514
- if (!done)
515
- {
516
- using (CardLayer.Hide(area))
517
- {
518
- try { Native.BitBlt(dst, 0, 0, w, h, src, x, y, 0x00CC0020 | 0x40000000); }
519
- finally { g.ReleaseHdc(dst); }
520
- }
521
- }
522
- Native.ReleaseDC(IntPtr.Zero, src);
523
- }
524
- return bmp;
525
- }
526
- catch
527
- {
528
- bmp.Dispose();
529
- throw;
530
- }
531
- }
532
-
533
- public static Dictionary<string, object> Capture(Dictionary<string, object> r)
534
- {
535
- 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);
536
- int ow = Args.Int(r, "outWidth", w), oh = Args.Int(r, "outHeight", h);
537
- int quality = Args.Int(r, "quality", 80);
538
- if (w <= 0 || h <= 0 || ow <= 0 || oh <= 0) throw new Exception("invalid capture size");
539
- string via;
540
- using (var bmp = Grab(x, y, w, h, out via))
541
- {
542
- // compare: report "unchanged" instead of an identical image; mark: remember for next time.
543
- bool compare = Args.Bool(r, "compare", false), mark = Args.Bool(r, "mark", false) || compare;
544
- if (mark)
545
- {
546
- string slot = Args.Str(r, "slot", "full");
547
- if (slot.Length == 0) slot = "full";
548
- string key = RectKey(x, y, w, h);
549
- byte[] sample = SampleBitmap(bmp);
550
- long outPixels = (long)ow * oh;
551
- MarkedFrame prev;
552
- if (compare && markedBySlot.TryGetValue(slot, out prev) && prev.Rect == key
553
- && outPixels <= prev.OutPixels && quality <= prev.Quality
554
- && Changed(prev.Sample, sample) < Args.Double(r, "threshold", 0.0005))
555
- {
556
- var same = new Dictionary<string, object>();
557
- same["unchanged"] = true;
558
- return same;
559
- }
560
- var next = new MarkedFrame();
561
- next.Rect = key;
562
- next.Sample = sample;
563
- next.OutPixels = outPixels;
564
- next.Quality = quality;
565
- markedBySlot[slot] = next;
566
- }
567
- Bitmap output = bmp;
568
- Bitmap scaled = null;
569
- try
570
- {
571
- if (ow != w || oh != h)
572
- {
573
- scaled = new Bitmap(ow, oh, PixelFormat.Format24bppRgb);
574
- using (var g2 = Graphics.FromImage(scaled))
575
- using (var attrs = new ImageAttributes())
576
- {
577
- attrs.SetWrapMode(WrapMode.TileFlipXY);
578
- g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
579
- g2.PixelOffsetMode = PixelOffsetMode.HighQuality;
580
- g2.CompositingQuality = CompositingQuality.HighQuality;
581
- g2.DrawImage(bmp, new Rectangle(0, 0, ow, oh), 0, 0, w, h, GraphicsUnit.Pixel, attrs);
582
- }
583
- output = scaled;
584
- }
585
- if (jpegCodec == null)
586
- foreach (var c in ImageCodecInfo.GetImageEncoders()) if (c.MimeType == "image/jpeg") jpegCodec = c;
587
- using (var ms = new MemoryStream())
588
- using (var ep = new EncoderParameters(1))
589
- {
590
- ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
591
- output.Save(ms, jpegCodec, ep);
592
- var d = new Dictionary<string, object>();
593
- d["data"] = Convert.ToBase64String(ms.ToArray());
594
- d["via"] = via == "blt" && MagCapture.Why.Length > 0 ? "blt (" + MagCapture.Why + ")" : via;
595
- d["width"] = ow; d["height"] = oh;
596
- return d;
597
- }
598
- }
599
- finally { if (scaled != null) scaled.Dispose(); }
600
- }
601
- }
602
- }
603
-
604
- /**
605
- * Built-in Windows 10/11 OCR via WinRT reflection (Windows.Media.Ocr).
606
- * Zero extra compile references or native DLLs: falls back cleanly if the
607
- * host OS has no WinRT OCR language pack installed.
608
- */
609
- internal static class Ocr
610
- {
611
- static Type tEngine, tDecoder, tStream, tWriter, tAsyncInfo;
612
- static object cachedEngine;
613
- static string cachedLanguage = "";
614
- static int cachedMaxDim = 2600;
615
- static bool initTried;
616
-
617
- static void EnsureTypes()
618
- {
619
- if (initTried) return;
620
- initTried = true;
621
- tEngine = Type.GetType("Windows.Media.Ocr.OcrEngine, Windows.Media, ContentType=WindowsRuntime", false);
622
- tDecoder = Type.GetType("Windows.Graphics.Imaging.BitmapDecoder, Windows.Graphics, ContentType=WindowsRuntime", false);
623
- tStream = Type.GetType("Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage, ContentType=WindowsRuntime", false);
624
- tWriter = Type.GetType("Windows.Storage.Streams.DataWriter, Windows.Storage, ContentType=WindowsRuntime", false);
625
- tAsyncInfo = Type.GetType("Windows.Foundation.IAsyncInfo, Windows.Foundation, ContentType=WindowsRuntime", false);
626
- if (tEngine == null || tDecoder == null || tStream == null || tWriter == null || tAsyncInfo == null) return;
627
- try
628
- {
629
- var create = tEngine.GetMethod("TryCreateFromUserProfileLanguages", BindingFlags.Public | BindingFlags.Static);
630
- if (create != null) cachedEngine = create.Invoke(null, null);
631
- if (cachedEngine != null)
632
- {
633
- object lang = GetProp(cachedEngine, "RecognizerLanguage");
634
- if (lang != null) cachedLanguage = Convert.ToString(GetProp(lang, "LanguageTag")) ?? "";
635
- var maxProp = tEngine.GetProperty("MaxImageDimension", BindingFlags.Public | BindingFlags.Static);
636
- if (maxProp != null)
637
- {
638
- int dim = Convert.ToInt32(maxProp.GetValue(null, null));
639
- if (dim >= 512) cachedMaxDim = dim;
640
- }
641
- }
642
- }
643
- catch (Exception) { cachedEngine = null; }
644
- }
645
-
646
- static MethodInfo FindMethod(Type t, string name, int argCount)
647
- {
648
- if (t == null) return null;
649
- foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
650
- if (m.Name == name && m.GetParameters().Length == argCount) return m;
651
- foreach (var iface in t.GetInterfaces())
652
- foreach (var m in iface.GetMethods(BindingFlags.Public | BindingFlags.Instance))
653
- if (m.Name == name && m.GetParameters().Length == argCount) return m;
654
- return null;
655
- }
656
-
657
- static object Invoke(object target, string name, params object[] args)
658
- {
659
- var m = FindMethod(target.GetType(), name, args == null ? 0 : args.Length);
660
- if (m == null) throw new Exception("WinRT method not found: " + name);
661
- return m.Invoke(target, args);
662
- }
663
-
664
- static object InvokeAsync(object target, string name, int timeoutMs, params object[] args)
665
- {
666
- var m = FindMethod(target.GetType(), name, args == null ? 0 : args.Length);
667
- if (m == null) throw new Exception("WinRT method not found: " + name);
668
- object op = m.Invoke(target, args);
669
- return AwaitWinRt(op, m.ReturnType, timeoutMs);
670
- }
671
-
672
- static object GetProp(object target, string name)
673
- {
674
- var t = target.GetType();
675
- var p = t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
676
- if (p != null) return p.GetValue(target, null);
677
- foreach (var iface in t.GetInterfaces())
678
- {
679
- p = iface.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
680
- if (p != null) return p.GetValue(target, null);
681
- }
682
- return null;
683
- }
684
-
685
- static object AwaitWinRt(object asyncOp, Type asyncType, int timeoutMs)
686
- {
687
- if (asyncOp == null) return null;
688
- var statusProp = tAsyncInfo.GetProperty("Status");
689
- var errProp = tAsyncInfo.GetProperty("ErrorCode");
690
- var watch = Stopwatch.StartNew();
691
- while (true)
692
- {
693
- int status = Convert.ToInt32(statusProp.GetValue(asyncOp, null));
694
- if (status == 1) // Completed
695
- {
696
- var getResults = FindMethod(asyncType, "GetResults", 0) ?? FindMethod(asyncOp.GetType(), "GetResults", 0);
697
- return getResults != null ? getResults.Invoke(asyncOp, null) : null;
698
- }
699
- if (status == 2) throw new Exception("Windows OCR operation was cancelled");
700
- if (status == 3)
701
- {
702
- object err = errProp != null ? errProp.GetValue(asyncOp, null) : null;
703
- throw new Exception("Windows OCR failed: " + (err != null ? err.ToString() : "unknown error"));
704
- }
705
- if (watch.ElapsedMilliseconds >= timeoutMs)
706
- {
707
- try { var cancel = tAsyncInfo.GetMethod("Cancel"); if (cancel != null) cancel.Invoke(asyncOp, null); } catch (Exception) { }
708
- throw new Exception("Windows OCR timed out");
709
- }
710
- Thread.Sleep(5);
711
- }
712
- }
713
-
714
- static bool IsCjk(char c)
715
- {
716
- return (c >= '\u4E00' && c <= '\u9FFF') || (c >= '\u3400' && c <= '\u4DBF')
717
- || (c >= '\u3000' && c <= '\u303F') || (c >= '\uFF00' && c <= '\uFFEF');
718
- }
719
-
720
- /** Collapse spaces Windows.Media.Ocr inserts between adjacent CJK characters. */
721
- static string CleanLineText(string s)
722
- {
723
- if (string.IsNullOrEmpty(s)) return "";
724
- var sb = new StringBuilder(s.Length);
725
- for (int i = 0; i < s.Length; i++)
726
- {
727
- char c = s[i];
728
- if (c == ' ' && sb.Length > 0 && i + 1 < s.Length && IsCjk(sb[sb.Length - 1]) && IsCjk(s[i + 1]))
729
- continue;
730
- sb.Append(c);
731
- }
732
- return sb.ToString();
733
- }
734
-
735
- static void TryDispose(object obj)
736
- {
737
- var d = obj as IDisposable;
738
- if (d != null) { try { d.Dispose(); } catch (Exception) { } }
739
- }
740
-
741
- public static Dictionary<string, object> Read(Dictionary<string, object> r)
742
- {
743
- EnsureTypes();
744
- if (cachedEngine == null)
745
- throw new Exception("Windows OCR is not available on this system (no OCR language pack found).");
746
-
747
- int x, y, w, h;
748
- var meta = new Dictionary<string, object>();
749
- if (Args.Has(r, "width") && Args.Has(r, "height"))
750
- {
751
- x = Args.Int(r, "x", 0);
752
- y = Args.Int(r, "y", 0);
753
- w = Args.Int(r, "width", 0);
754
- h = Args.Int(r, "height", 0);
755
- }
756
- else
757
- {
758
- IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
759
- var desc = Windows.Describe(hwnd);
760
- if (desc.Count == 0) throw new Exception("No target window found for OCR.");
761
- foreach (var kv in desc) meta[kv.Key] = kv.Value;
762
- var vs = SystemInformation.VirtualScreen;
763
- int rx = Convert.ToInt32(desc["x"]), ry = Convert.ToInt32(desc["y"]);
764
- int rw = Convert.ToInt32(desc["width"]), rh = Convert.ToInt32(desc["height"]);
765
- int left = Math.Max(vs.Left, rx);
766
- int top = Math.Max(vs.Top, ry);
767
- int right = Math.Min(vs.Right, rx + rw);
768
- int bottom = Math.Min(vs.Bottom, ry + rh);
769
- x = left; y = top; w = right - left; h = bottom - top;
770
- }
771
- if (w <= 2 || h <= 2) throw new Exception("Target area is too small for OCR.");
772
-
773
- string via;
774
- using (var rawBmp = Screen2.Grab(x, y, w, h, out via))
775
- {
776
- double scale = 1.0;
777
- int maxSide = Math.Max(w, h);
778
- if (maxSide > cachedMaxDim) scale = (double)cachedMaxDim / maxSide;
779
- Bitmap work = rawBmp;
780
- Bitmap resized = null;
781
- byte[] pngBytes;
782
- try
783
- {
784
- if (scale < 1.0)
785
- {
786
- int nw = Math.Max(1, (int)Math.Round(w * scale));
787
- int nh = Math.Max(1, (int)Math.Round(h * scale));
788
- resized = new Bitmap(nw, nh, PixelFormat.Format24bppRgb);
789
- using (var g = Graphics.FromImage(resized))
790
- {
791
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
792
- g.DrawImage(rawBmp, 0, 0, nw, nh);
793
- }
794
- work = resized;
795
- }
796
- using (var ms = new MemoryStream())
797
- {
798
- work.Save(ms, ImageFormat.Png);
799
- pngBytes = ms.ToArray();
800
- }
801
- }
802
- finally { if (resized != null) resized.Dispose(); }
803
-
804
- object ras = null, writer = null, softwareBitmap = null;
805
- try
806
- {
807
- ras = Activator.CreateInstance(tStream);
808
- writer = Activator.CreateInstance(tWriter, new object[] { ras });
809
- Invoke(writer, "WriteBytes", new object[] { pngBytes });
810
- InvokeAsync(writer, "StoreAsync", 8000);
811
- InvokeAsync(writer, "FlushAsync", 8000);
812
- Invoke(writer, "DetachStream");
813
- TryDispose(writer); writer = null;
814
- Invoke(ras, "Seek", new object[] { (ulong)0 });
815
-
816
- MethodInfo createDecoder = null;
817
- foreach (var m in tDecoder.GetMethods(BindingFlags.Public | BindingFlags.Static))
818
- if (m.Name == "CreateAsync" && m.GetParameters().Length == 1) { createDecoder = m; break; }
819
- if (createDecoder == null) throw new Exception("BitmapDecoder.CreateAsync not found");
820
- object decoder = AwaitWinRt(createDecoder.Invoke(null, new object[] { ras }), createDecoder.ReturnType, 8000);
821
- if (decoder == null) throw new Exception("BitmapDecoder returned null");
822
- softwareBitmap = InvokeAsync(decoder, "GetSoftwareBitmapAsync", 8000);
823
- if (softwareBitmap == null) throw new Exception("GetSoftwareBitmapAsync returned null");
824
- object ocrResult = InvokeAsync(cachedEngine, "RecognizeAsync", 10000, new object[] { softwareBitmap });
825
- if (ocrResult == null) throw new Exception("OcrEngine.RecognizeAsync returned null");
826
-
827
- var linesOut = new List<object>();
828
- var allLines = new List<string>();
829
- double invScale = 1.0 / scale;
830
- var rawLines = GetProp(ocrResult, "Lines") as IEnumerable;
831
- if (rawLines != null)
832
- {
833
- foreach (var line in rawLines)
834
- {
835
- string lineText = CleanLineText(Convert.ToString(GetProp(line, "Text")) ?? "");
836
- if (lineText.Trim().Length == 0) continue;
837
- var wordsOut = new List<object>();
838
- double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
839
- var rawWords = GetProp(line, "Words") as IEnumerable;
840
- if (rawWords != null)
841
- {
842
- foreach (var word in rawWords)
843
- {
844
- string wt = Convert.ToString(GetProp(word, "Text")) ?? "";
845
- object rect = GetProp(word, "BoundingRect");
846
- if (rect == null) continue;
847
- double wx = Convert.ToDouble(GetProp(rect, "X")) * invScale;
848
- double wy = Convert.ToDouble(GetProp(rect, "Y")) * invScale;
849
- double ww = Convert.ToDouble(GetProp(rect, "Width")) * invScale;
850
- double wh = Convert.ToDouble(GetProp(rect, "Height")) * invScale;
851
- if (wx < minX) minX = wx;
852
- if (wy < minY) minY = wy;
853
- if (wx + ww > maxX) maxX = wx + ww;
854
- if (wy + wh > maxY) maxY = wy + wh;
855
- var wd = new Dictionary<string, object>();
856
- wd["text"] = wt;
857
- wd["x"] = x + (int)Math.Round(wx);
858
- wd["y"] = y + (int)Math.Round(wy);
859
- wd["width"] = Math.Max(1, (int)Math.Round(ww));
860
- wd["height"] = Math.Max(1, (int)Math.Round(wh));
861
- wordsOut.Add(wd);
862
- }
863
- }
864
- if (minX == double.MaxValue) continue;
865
- var ld = new Dictionary<string, object>();
866
- ld["text"] = lineText;
867
- ld["x"] = x + (int)Math.Round(minX);
868
- ld["y"] = y + (int)Math.Round(minY);
869
- ld["width"] = Math.Max(1, (int)Math.Round(maxX - minX));
870
- ld["height"] = Math.Max(1, (int)Math.Round(maxY - minY));
871
- ld["words"] = wordsOut;
872
- linesOut.Add(ld);
873
- allLines.Add(lineText);
874
- }
875
- }
876
-
877
- meta["language"] = cachedLanguage;
878
- meta["x"] = x;
879
- meta["y"] = y;
880
- meta["width"] = w;
881
- meta["height"] = h;
882
- meta["text"] = string.Join("\n", allLines.ToArray());
883
- meta["lines"] = linesOut;
884
- return meta;
885
- }
886
- finally
887
- {
888
- TryDispose(softwareBitmap);
889
- TryDispose(writer);
890
- TryDispose(ras);
891
- }
892
- }
893
- }
894
- }
895
-
896
- internal static class Input
897
- {
898
- static readonly int InputSize = Marshal.SizeOf(typeof(Native.INPUT));
899
- 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 };
900
-
901
- static Native.INPUT Mouse(uint flags, uint data)
902
- {
903
- var i = new Native.INPUT(); i.type = Native.INPUT_MOUSE;
904
- i.u.mi.dwFlags = flags; i.u.mi.mouseData = data; i.u.mi.dwExtraInfo = Native.Marker;
905
- return i;
906
- }
907
-
908
- static Native.INPUT Key(int vk, bool up)
909
- {
910
- var i = new Native.INPUT(); i.type = Native.INPUT_KEYBOARD;
911
- i.u.ki.wVk = (ushort)vk;
912
- i.u.ki.wScan = (ushort)Native.MapVirtualKey((uint)vk, 0);
913
- i.u.ki.dwFlags = (up ? Native.KEYEVENTF_KEYUP : 0) | (Extended.Contains(vk) ? Native.KEYEVENTF_EXTENDEDKEY : 0);
914
- i.u.ki.dwExtraInfo = Native.Marker;
915
- return i;
916
- }
917
-
918
- static Native.INPUT Unicode(char c, bool up)
919
- {
920
- var i = new Native.INPUT(); i.type = Native.INPUT_KEYBOARD;
921
- i.u.ki.wVk = 0; i.u.ki.wScan = c;
922
- i.u.ki.dwFlags = Native.KEYEVENTF_UNICODE | (up ? Native.KEYEVENTF_KEYUP : 0);
923
- i.u.ki.dwExtraInfo = Native.Marker;
924
- return i;
925
- }
926
-
927
- static void Send(List<Native.INPUT> inputs)
928
- {
929
- if (inputs.Count == 0) return;
930
- WaitForInstructionBox();
931
- uint sent = Native.SendInput((uint)inputs.Count, inputs.ToArray(), InputSize);
932
- if (sent != inputs.Count)
933
- 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.");
934
- }
935
-
936
- /**
937
- * The user opened the progress card's instruction box mid-action (say,
938
- * halfway through typing): hold the rest until it closes and focus is
939
- * back, so no keystroke lands in the box.
940
- */
941
- static void WaitForInstructionBox()
942
- {
943
- if (Overlay.InputHwnd == IntPtr.Zero) return;
944
- var until = DateTime.UtcNow.AddSeconds(90);
945
- while (Overlay.InputHwnd != IntPtr.Zero)
946
- {
947
- if (DateTime.UtcNow > until) throw new Exception("Stopped: the user is typing an instruction to you in the progress card.");
948
- Thread.Sleep(100);
949
- }
950
- // The box hands the focus back to the window it took it from: wait until that happened.
951
- IntPtr target = Overlay.InputReturnsTo;
952
- var back = DateTime.UtcNow.AddSeconds(4);
953
- while (target != IntPtr.Zero && Native.IsWindow(target) && Native.GetForegroundWindow() != target && DateTime.UtcNow < back) Thread.Sleep(50);
954
- Thread.Sleep(150);
955
- }
956
-
957
- public static void Move(int x, int y)
958
- {
959
- Native.SetCursorPos(x, y);
960
- // A zero relative move lets apps that only watch WM_MOUSEMOVE notice the cursor.
961
- Send(new List<Native.INPUT> { Mouse(Native.MOUSEEVENTF_MOVE, 0) });
962
- }
963
-
964
- static void Flags(string button, out uint down, out uint up)
965
- {
966
- switch (button)
967
- {
968
- case "right": down = Native.MOUSEEVENTF_RIGHTDOWN; up = Native.MOUSEEVENTF_RIGHTUP; break;
969
- case "middle": down = Native.MOUSEEVENTF_MIDDLEDOWN; up = Native.MOUSEEVENTF_MIDDLEUP; break;
970
- default: down = Native.MOUSEEVENTF_LEFTDOWN; up = Native.MOUSEEVENTF_LEFTUP; break;
971
- }
972
- }
973
-
974
- static void Modifiers(List<int> vks, bool up)
975
- {
976
- var list = new List<Native.INPUT>();
977
- if (up) for (int i = vks.Count - 1; i >= 0; i--) list.Add(Key(vks[i], true));
978
- else foreach (var vk in vks) list.Add(Key(vk, false));
979
- Send(list);
980
- }
981
-
982
- sealed class ClickRecord
983
- {
984
- public int X;
985
- public int Y;
986
- public DateTime At;
987
- }
988
- static readonly List<ClickRecord> ClickHistory = new List<ClickRecord>();
989
- static readonly object ClickLock = new object();
990
-
991
- static int NoteClick(int x, int y)
992
- {
993
- var now = DateTime.UtcNow;
994
- var cutoff = now.AddMinutes(-2);
995
- lock (ClickLock)
996
- {
997
- int removeCount = 0;
998
- while (removeCount < ClickHistory.Count && ClickHistory[removeCount].At < cutoff) removeCount++;
999
- if (removeCount > 0) ClickHistory.RemoveRange(0, removeCount);
1000
- var rec = new ClickRecord();
1001
- rec.X = x;
1002
- rec.Y = y;
1003
- rec.At = now;
1004
- ClickHistory.Add(rec);
1005
- int hits = 0;
1006
- for (int i = 0; i < ClickHistory.Count; i++)
1007
- {
1008
- var item = ClickHistory[i];
1009
- if (Math.Abs(item.X - x) <= 24 && Math.Abs(item.Y - y) <= 24) hits++;
1010
- }
1011
- return hits;
1012
- }
1013
- }
1014
-
1015
- public static object Click(Dictionary<string, object> r)
1016
- {
1017
- int x, y;
1018
- Native.POINT savedCursor;
1019
- bool hadSavedCursor = Native.GetCursorPos(out savedCursor);
1020
- bool restorePointer = Args.Bool(r, "restorePointer", false);
1021
- bool moved = Args.Has(r, "x");
1022
- if (moved)
1023
- {
1024
- x = Args.Int(r, "x", 0);
1025
- y = Args.Int(r, "y", 0);
1026
- }
1027
- else
1028
- {
1029
- if (!hadSavedCursor) { x = 0; y = 0; }
1030
- else { x = savedCursor.X; y = savedCursor.Y; }
1031
- }
1032
- string button = Args.Str(r, "button", "left");
1033
- if (button != "right" && button != "middle") button = "left";
1034
- uint down, up; Flags(button, out down, out up);
1035
- int count = Math.Max(1, Math.Min(3, Args.Int(r, "count", 1)));
1036
- var mods = Args.Ints(r, "modifiers");
1037
- string coordLabel = Args.Has(r, "labelX") && Args.Has(r, "labelY")
1038
- ? Args.Int(r, "labelX", x) + ", " + Args.Int(r, "labelY", y)
1039
- : x + ", " + y;
1040
- bool showTarget = Overlay.ShowClickTarget;
1041
- if (showTarget)
1042
- {
1043
- string preVerb = count >= 3 ? "三击" : count == 2 ? "双击" : button == "right" ? "右键" : button == "middle" ? "中键" : "点击";
1044
- Overlay.GlideMark(x, y, preVerb + " " + coordLabel, Color.FromArgb(217, 119, 87), 2000, false, false);
1045
- }
1046
- if (moved)
1047
- {
1048
- Overlay.Dodge(x, y);
1049
- Move(x, y);
1050
- }
1051
- if (showTarget)
1052
- {
1053
- Thread.Sleep(70);
1054
- }
1055
- else if (moved)
1056
- {
1057
- Thread.Sleep(30);
1058
- }
1059
- Modifiers(mods, false);
1060
- try
1061
- {
1062
- for (int i = 0; i < count; i++)
1063
- {
1064
- Send(new List<Native.INPUT> { Mouse(down, 0) });
1065
- Thread.Sleep(20);
1066
- Send(new List<Native.INPUT> { Mouse(up, 0) });
1067
- if (i < count - 1) Thread.Sleep(40);
1068
- }
1069
- }
1070
- finally
1071
- {
1072
- Modifiers(mods, true);
1073
- if (restorePointer && moved && hadSavedCursor)
1074
- {
1075
- try { Native.SetCursorPos(savedCursor.X, savedCursor.Y); } catch (Exception) { }
1076
- }
1077
- }
1078
- if (showTarget)
1079
- {
1080
- Overlay.MarkResult(x, y, button, count, coordLabel);
1081
- }
1082
- int repeat = NoteClick(x, y);
1083
- var result = new Dictionary<string, object>();
1084
- result["x"] = x;
1085
- result["y"] = y;
1086
- result["button"] = button;
1087
- result["count"] = count;
1088
- result["repeat"] = repeat;
1089
- result["restoredPointer"] = restorePointer && moved && hadSavedCursor;
1090
- return result;
1091
- }
1092
-
1093
- public static object Button(Dictionary<string, object> r)
1094
- {
1095
- 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); }
1096
- uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
1097
- Send(new List<Native.INPUT> { Mouse(Args.Bool(r, "up", false) ? up : down, 0) });
1098
- return null;
1099
- }
1100
-
1101
- public static object Drag(Dictionary<string, object> r)
1102
- {
1103
- 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);
1104
- uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
1105
- Overlay.Dodge(x1, y1); Overlay.Dodge(x2, y2);
1106
- Move(x1, y1);
1107
- if (Overlay.ShowClickTarget) Overlay.MarkPointer(x1, y1, "拖动", 1200);
1108
- Thread.Sleep(40);
1109
- Send(new List<Native.INPUT> { Mouse(down, 0) });
1110
- try
1111
- {
1112
- Thread.Sleep(60);
1113
- int steps = Math.Max(8, Math.Min(40, (int)(Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) / 20)));
1114
- for (int i = 1; i <= steps; i++)
1115
- {
1116
- Move(x1 + (x2 - x1) * i / steps, y1 + (y2 - y1) * i / steps);
1117
- Thread.Sleep(12);
1118
- }
1119
- Thread.Sleep(60);
1120
- }
1121
- finally { Send(new List<Native.INPUT> { Mouse(up, 0) }); }
1122
- if (Overlay.ShowClickTarget) Overlay.MarkPointer(x2, y2, "已拖动", 1200);
1123
- return null;
1124
- }
1125
-
1126
- public static object Scroll(Dictionary<string, object> r)
1127
- {
1128
- int sx = 0, sy = 0;
1129
- bool hasPos = Args.Has(r, "x");
1130
- if (hasPos) { sx = Args.Int(r, "x", 0); sy = Args.Int(r, "y", 0); Overlay.Dodge(sx, sy); Move(sx, sy); Thread.Sleep(30); }
1131
- else { Native.POINT p; if (Native.GetCursorPos(out p)) { sx = p.X; sy = p.Y; } }
1132
- if (Overlay.ShowClickTarget) Overlay.MarkPointer(sx, sy, "滚动", 900);
1133
- int dx = Args.Int(r, "dx", 0), dy = Args.Int(r, "dy", 0);
1134
- var mods = Args.Ints(r, "modifiers");
1135
- Modifiers(mods, false);
1136
- try
1137
- {
1138
- // One notch per event, spaced out, so smooth-scrolling apps keep up.
1139
- 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); }
1140
- 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); }
1141
- }
1142
- finally { Modifiers(mods, true); }
1143
- return null;
1144
- }
1145
-
1146
- // combos: [[vk, vk, ...], ...] — each combo presses in order and releases in reverse.
1147
- public static object Keys(Dictionary<string, object> r)
1148
- {
1149
- var combos = Args.IntLists(r, "combos");
1150
- int hold = Args.Int(r, "holdMs", 0);
1151
- foreach (var combo in combos)
1152
- {
1153
- var downs = new List<Native.INPUT>();
1154
- foreach (var vk in combo) downs.Add(Key(vk, false));
1155
- Send(downs);
1156
- Thread.Sleep(hold > 0 ? hold : 25);
1157
- var ups = new List<Native.INPUT>();
1158
- for (int i = combo.Count - 1; i >= 0; i--) ups.Add(Key(combo[i], true));
1159
- Send(ups);
1160
- Thread.Sleep(30);
1161
- }
1162
- return null;
1163
- }
1164
-
1165
- public static object KeyState(Dictionary<string, object> r)
1166
- {
1167
- var vks = Args.Ints(r, "vks");
1168
- Modifiers(vks, Args.Bool(r, "up", false));
1169
- return null;
1170
- }
1171
-
1172
- /** charDelay > 0: one character at a time, like a person typing; otherwise fast batches. */
1173
- public static object Type(string text, int chunkDelay, int charDelay)
1174
- {
1175
- var batch = new List<Native.INPUT>();
1176
- int pause = charDelay > 0 ? charDelay : chunkDelay;
1177
- Action flush = delegate { if (batch.Count == 0) return; Send(batch); batch.Clear(); if (pause > 0) Thread.Sleep(pause); };
1178
- for (int i = 0; i < text.Length; i++)
1179
- {
1180
- char c = text[i];
1181
- if (c == '\r') { if (i + 1 < text.Length && text[i + 1] == '\n') continue; c = '\n'; }
1182
- if (c == '\n') { flush(); batch.Add(Key(0x0D, false)); batch.Add(Key(0x0D, true)); flush(); continue; }
1183
- if (c == '\t') { batch.Add(Key(0x09, false)); batch.Add(Key(0x09, true)); continue; }
1184
- batch.Add(Unicode(c, false)); batch.Add(Unicode(c, true));
1185
- if (char.IsHighSurrogate(c)) continue;
1186
- if (charDelay > 0 || batch.Count >= 40) flush();
1187
- }
1188
- flush();
1189
- return null;
1190
- }
1191
-
1192
- public static object Paste(string text, bool restore, int waitMs)
1193
- {
1194
- // Keep every format the user had (images, files, rich text), not just text.
1195
- DataObject previous = null;
1196
- if (restore) { try { previous = Clip.Snapshot(); } catch (Exception) { } }
1197
- Clip.Set(text, true);
1198
- Thread.Sleep(40);
1199
- Send(new List<Native.INPUT> { Key(0x11, false), Key(0x56, false) });
1200
- Thread.Sleep(30);
1201
- Send(new List<Native.INPUT> { Key(0x56, true), Key(0x11, true) });
1202
- Thread.Sleep(Math.Max(60, waitMs)); // the app reads the clipboard asynchronously
1203
- if (restore) { try { Clip.Put(previous); } catch (Exception) { } }
1204
- return null;
1205
- }
1206
- }
1207
-
1208
- internal static class Clip
1209
- {
1210
- public static string Get()
1211
- {
1212
- for (int i = 0; i < 5; i++)
1213
- {
1214
- try { return Clipboard.ContainsText() ? Clipboard.GetText() : ""; }
1215
- catch (ExternalException) { Thread.Sleep(50); }
1216
- }
1217
- throw new Exception("clipboard is busy");
1218
- }
1219
-
1220
- /** The user's clipboard before the agent first wrote to it, restored when control ends. */
1221
- static DataObject saved;
1222
- static bool hasSaved;
1223
- /** What the agent last put there, to tell whether the user copied something since. */
1224
- static string agentText;
1225
-
1226
- static string Normalize(string text)
1227
- {
1228
- return string.IsNullOrEmpty(text) ? "" : text.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n");
1229
- }
1230
-
1231
- /** Mark data as transient: clipboard history (Win+V), cloud clipboard and clipboard managers skip it. */
1232
- static void MarkPrivate(DataObject d)
1233
- {
1234
- d.SetData("ExcludeClipboardContentFromMonitorProcessing", false, new MemoryStream(new byte[] { 1, 0, 0, 0 }));
1235
- d.SetData("CanIncludeInClipboardHistory", false, new MemoryStream(BitConverter.GetBytes(0)));
1236
- d.SetData("CanUploadToCloudClipboard", false, new MemoryStream(BitConverter.GetBytes(0)));
1237
- }
1238
-
1239
- /** Copy every format currently on the clipboard (null when empty). */
1240
- public static DataObject Snapshot()
1241
- {
1242
- for (int i = 0; i < 5; i++)
1243
- {
1244
- try
1245
- {
1246
- var src = Clipboard.GetDataObject();
1247
- if (src == null) return null;
1248
- var formats = src.GetFormats(false);
1249
- if (formats.Length == 0) return null;
1250
- var dst = new DataObject();
1251
- foreach (var f in formats)
1252
- {
1253
- if (f == "CanIncludeInClipboardHistory" || f == "CanUploadToCloudClipboard" || f == "ExcludeClipboardContentFromMonitorProcessing") continue;
1254
- try { var v = src.GetData(f, false); if (v != null) dst.SetData(f, false, v); } catch (Exception) { }
1255
- }
1256
- return dst;
1257
- }
1258
- catch (ExternalException) { Thread.Sleep(50); }
1259
- }
1260
- throw new Exception("clipboard is busy");
1261
- }
1262
-
1263
- /** Put a snapshot back without adding a history entry (null clears). */
1264
- public static void Put(DataObject data)
1265
- {
1266
- for (int i = 0; i < 5; i++)
1267
- {
1268
- try
1269
- {
1270
- if (data == null) Clipboard.Clear();
1271
- else { MarkPrivate(data); Clipboard.SetDataObject(data, true); }
1272
- return;
1273
- }
1274
- catch (ExternalException) { Thread.Sleep(50); }
1275
- }
1276
- throw new Exception("clipboard is busy");
1277
- }
1278
-
1279
- /** The user's clipboard, kept aside while a streamed paste runs. */
1280
- static DataObject held;
1281
- static bool holding;
1282
-
1283
- public static void Hold()
1284
- {
1285
- if (holding) return;
1286
- held = Snapshot();
1287
- holding = true;
1288
- }
1289
-
1290
- public static void Release()
1291
- {
1292
- if (!holding) return;
1293
- var data = held;
1294
- held = null; holding = false;
1295
- Put(data);
1296
- }
1297
-
1298
- public static void Set(string text, bool isPrivate)
1299
- {
1300
- text = Normalize(text);
1301
- for (int i = 0; i < 5; i++)
1302
- {
1303
- try
1304
- {
1305
- if (text.Length == 0) Clipboard.Clear();
1306
- else
1307
- {
1308
- var d = new DataObject();
1309
- d.SetData(DataFormats.UnicodeText, false, text);
1310
- if (isPrivate) MarkPrivate(d);
1311
- Clipboard.SetDataObject(d, true);
1312
- }
1313
- return;
1314
- }
1315
- catch (ExternalException) { Thread.Sleep(50); }
1316
- }
1317
- throw new Exception("clipboard is busy");
1318
- }
1319
-
1320
- /** The agent writes the clipboard: remember the user's content first (once per control session). */
1321
- public static void AgentSet(string text)
1322
- {
1323
- if (!hasSaved) { saved = Snapshot(); hasSaved = true; }
1324
- Set(text, true);
1325
- agentText = Normalize(text);
1326
- }
1327
-
1328
- /** Control ended: put the user's clipboard back, unless they copied something since the agent's last write. */
1329
- public static bool RestoreAgent()
1330
- {
1331
- if (!hasSaved) return false;
1332
- bool ours = false;
1333
- try { ours = Get() == agentText; } catch (Exception) { }
1334
- var data = saved;
1335
- saved = null; hasSaved = false; agentText = null;
1336
- if (!ours) return false;
1337
- Put(data);
1338
- return true;
1339
- }
1340
- }
1341
-
1342
- /**
1343
- * The DeepSeek Harness card floats on top for the user only. To the agent
1344
- * it is transparent: while a screenshot is taken the card is made fully
1345
- * transparent for a few milliseconds (another process's window cannot be
1346
- * excluded from capture), and its pointer input passes through.
1347
- */
1348
- internal static class CardLayer
1349
- {
1350
- public static IntPtr Hwnd = IntPtr.Zero;
1351
- static int originalEx;
1352
- /** Resting alpha of the card (see-through); it turns opaque while the pointer rests on it. */
1353
- static byte alpha = 255;
1354
- static bool hot;
1355
- static int hiding;
1356
- static DateTime enteredAt = DateTime.MaxValue;
1357
- static System.Threading.Timer hover;
1358
- static readonly object Gate = new object();
1359
-
1360
- public static void SetOpacity(int percent)
1361
- {
1362
- lock (Gate)
1363
- {
1364
- alpha = (byte)Math.Max(64, Math.Min(255, (int)Math.Round(Math.Max(25, Math.Min(100, percent)) * 2.55)));
1365
- if (alpha < 255 && hover == null) hover = new System.Threading.Timer(delegate { Track(); }, null, 150, 150);
1366
- Apply();
1367
- }
1368
- }
1369
-
1370
- static byte Current() { return hot ? (byte)255 : alpha; }
1371
-
1372
- static void Apply()
1373
- {
1374
- if (hiding == 0 && Hwnd != IntPtr.Zero && Native.IsWindow(Hwnd)) Native.SetLayeredWindowAttributes(Hwnd, 0, Current(), 2);
1375
- }
1376
-
1377
- /** Opaque once the pointer has rested on the card for a moment (the user wants to read or click it). */
1378
- static void Track()
1379
- {
1380
- lock (Gate)
1381
- {
1382
- bool inside = false;
1383
- if (Live() && alpha < 255)
1384
- {
1385
- Native.POINT p; Native.GetCursorPos(out p);
1386
- inside = Frame(Hwnd).Contains(p.X, p.Y);
1387
- }
1388
- if (!inside) { enteredAt = DateTime.MaxValue; if (hot) { hot = false; Apply(); } return; }
1389
- if (enteredAt == DateTime.MaxValue) enteredAt = DateTime.UtcNow;
1390
- if (!hot && (DateTime.UtcNow - enteredAt).TotalMilliseconds >= 300) { hot = true; Apply(); }
1391
- }
1392
- }
1393
-
1394
- static bool Live()
1395
- {
1396
- return Hwnd != IntPtr.Zero && Native.IsWindow(Hwnd) && Native.IsWindowVisible(Hwnd) && !Native.IsIconic(Hwnd);
1397
- }
1398
-
1399
- public static uint Pid()
1400
- {
1401
- if (!Live()) return 0;
1402
- uint pid; Native.GetWindowThreadProcessId(Hwnd, out pid);
1403
- return pid;
1404
- }
1405
-
1406
- /** The card becomes a (fully opaque) layered window so its alpha can be dropped instantly. */
1407
- public static void Attach(IntPtr hwnd)
1408
- {
1409
- if (Hwnd == hwnd) return;
1410
- Detach();
1411
- Hwnd = hwnd;
1412
- originalEx = Native.GetWindowLong(hwnd, -20);
1413
- Native.SetWindowLong(hwnd, -20, originalEx | 0x80000);
1414
- lock (Gate) { hot = false; enteredAt = DateTime.MaxValue; Native.SetLayeredWindowAttributes(hwnd, 0, Current(), 2); }
1415
- }
1416
-
1417
- public static void Detach()
1418
- {
1419
- var hwnd = Hwnd;
1420
- Hwnd = IntPtr.Zero;
1421
- lock (Gate) {
1422
- if (hwnd != IntPtr.Zero && Native.IsWindow(hwnd)) Native.SetWindowLong(hwnd, -20, originalEx);
1423
- }
1424
- }
1425
-
1426
- public static Rectangle Frame(IntPtr hwnd)
1427
- {
1428
- Native.RECT rc;
1429
- if (Native.DwmGetWindowAttribute(hwnd, 9, out rc, Marshal.SizeOf(typeof(Native.RECT))) != 0) Native.GetWindowRect(hwnd, out rc);
1430
- return new Rectangle(rc.Left, rc.Top, rc.Right - rc.Left, rc.Bottom - rc.Top);
1431
- }
1432
-
1433
- /** g draws a bitmap whose (0, 0) is screen (ox, oy): fill the card area with a constant. */
1434
- public static void Blank(Graphics g, int ox, int oy)
1435
- {
1436
- if (!Live()) return;
1437
- var r = Frame(Hwnd);
1438
- r.Inflate(32, 32); // its drop shadow too (wide at 200% scaling)
1439
- g.FillRectangle(Brushes.Black, r.X - ox, r.Y - oy, r.Width, r.Height);
1440
- }
1441
-
1442
- /** Is the card visible over (any part of) this screen rectangle? */
1443
- public static bool Covers(Rectangle area)
1444
- {
1445
- if (!Live()) return false;
1446
- var r = Frame(Hwnd);
1447
- r.Inflate(32, 32);
1448
- return r.IntersectsWith(area);
1449
- }
1450
-
1451
- /** Make the card invisible while a capture of `area` runs (dispose to show it again). */
1452
- public static IDisposable Hide(Rectangle area)
1453
- {
1454
- if (!Live()) return new Hidden(IntPtr.Zero);
1455
- var r = Frame(Hwnd);
1456
- r.Inflate(32, 32);
1457
- return new Hidden(r.IntersectsWith(area) ? Hwnd : IntPtr.Zero);
1458
- }
1459
-
1460
- // Chromium cards can swallow SendInput even after WS_EX_TRANSPARENT has
1461
- // changed the hit test. Hide the card through dispatch only when it covers
1462
- // the click, keeping its position, z-order and the work window's focus.
1463
- public static IDisposable UncoverClick(Native.POINT point)
1464
- {
1465
- var hwnd = Hwnd;
1466
- if (!Live()) return null;
1467
- Native.RECT rect;
1468
- if (!Native.GetWindowRect(hwnd, out rect)) throw new Exception("Cannot verify the control card bounds");
1469
- if (point.X < rect.Left || point.X >= rect.Right || point.Y < rect.Top || point.Y >= rect.Bottom) return null;
1470
- if (Native.GetForegroundWindow() == hwnd) throw new Exception("The control card is focused. Focus the work window before clicking.");
1471
- object expected;
1472
- if (!Windows.At(point.X, point.Y).TryGetValue("hwnd", out expected))
1473
- throw new Exception("No work window found under the control card");
1474
- var uncovered = new Uncovered(hwnd);
1475
- try
1476
- {
1477
- object hit;
1478
- if (!Windows.At(point.X, point.Y).TryGetValue("hwnd", out hit) || !Object.Equals(expected, hit))
1479
- throw new Exception("The window under the control card changed. Look again before clicking.");
1480
- return uncovered;
1481
- }
1482
- catch
1483
- {
1484
- uncovered.Dispose();
1485
- throw;
1486
- }
1487
- }
1488
-
1489
- sealed class Uncovered : IDisposable
1490
- {
1491
- // NOSIZE | NOMOVE | NOZORDER | NOACTIVATE | NOOWNERZORDER.
1492
- const uint PreservePlacement = 0x0217;
1493
- readonly IntPtr hwnd;
1494
-
1495
- public Uncovered(IntPtr hwnd)
1496
- {
1497
- this.hwnd = hwnd;
1498
- if (!Native.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, PreservePlacement | 0x0080)
1499
- || Native.IsWindowVisible(hwnd))
1500
- throw new Exception("Cannot hide the control card for the click");
1501
- }
1502
-
1503
- public void Dispose()
1504
- {
1505
- if (Hwnd == hwnd && Native.IsWindow(hwnd)
1506
- && !Native.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, PreservePlacement | 0x0040))
1507
- Native.ShowWindow(hwnd, 4); // SW_SHOWNOACTIVATE
1508
- }
1509
- }
1510
-
1511
- sealed class Hidden : IDisposable
1512
- {
1513
- readonly IntPtr hwnd;
1514
- public Hidden(IntPtr hwnd)
1515
- {
1516
- this.hwnd = hwnd;
1517
- if (hwnd == IntPtr.Zero) return;
1518
- lock (Gate) { hiding++; Native.SetLayeredWindowAttributes(hwnd, 0, 0, 2); }
1519
- }
1520
- public void Dispose()
1521
- {
1522
- if (hwnd == IntPtr.Zero) return;
1523
- lock (Gate)
1524
- {
1525
- hiding--;
1526
- if (hiding == 0 && Native.IsWindow(hwnd)) Native.SetLayeredWindowAttributes(hwnd, 0, Current(), 2);
1527
- }
1528
- }
1529
- }
1530
- }
1531
-
1532
- /**
1533
- * Screen capture through the Windows Magnification API, which can leave
1534
- * out windows of other processes (MagSetWindowFilterList). The magnifier
1535
- * control lives in a never-shown host window; MagSetWindowSource renders
1536
- * synchronously into the scaling callback. Any failure disables it for the
1537
- * rest of the run and callers fall back to BitBlt.
1538
- */
1539
- internal static class MagCapture
1540
- {
1541
- [StructLayout(LayoutKind.Sequential)]
1542
- public struct MAGIMAGEHEADER { public uint width; public uint height; public Guid format; public uint stride; public uint offset; public UIntPtr cbSize; }
1543
-
1544
- delegate bool ScalingCallback(IntPtr hwnd, IntPtr srcdata, MAGIMAGEHEADER srcheader, IntPtr destdata, MAGIMAGEHEADER destheader, Native.RECT unclipped, Native.RECT clipped, IntPtr dirty);
1545
-
1546
- [DllImport("Magnification.dll")] static extern bool MagInitialize();
1547
- [DllImport("Magnification.dll")] static extern bool MagSetWindowSource(IntPtr hwnd, Native.RECT rect);
1548
- [DllImport("Magnification.dll")] static extern bool MagSetWindowFilterList(IntPtr hwnd, int mode, int count, IntPtr[] list);
1549
- [DllImport("Magnification.dll")] static extern bool MagSetImageScalingCallback(IntPtr hwnd, ScalingCallback cb);
1550
- [DllImport("user32.dll", CharSet = CharSet.Unicode)]
1551
- static extern IntPtr CreateWindowEx(int ex, string cls, string name, int style, int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr inst, IntPtr param);
1552
-
1553
- static bool broken;
1554
- public static string Why = "";
1555
- static Form host;
1556
- static IntPtr magnifier = IntPtr.Zero;
1557
- static ScalingCallback callback;
1558
- static Bitmap frame;
1559
-
1560
- static bool Ready()
1561
- {
1562
- if (broken) return false;
1563
- if (magnifier != IntPtr.Zero) return true;
1564
- try
1565
- {
1566
- if (!MagInitialize()) { broken = true; Why = "init"; return false; }
1567
- host = new Form { FormBorderStyle = FormBorderStyle.None, ShowInTaskbar = false, StartPosition = FormStartPosition.Manual, Location = new Point(0, 0), Size = new Size(16, 16) };
1568
- IntPtr parent = host.Handle; // created, never shown
1569
- magnifier = CreateWindowEx(0, "Magnifier", "cu-magnifier", 0x40000000 | 0x10000000, 0, 0, 16, 16, parent, IntPtr.Zero, Native.GetModuleHandle(null), IntPtr.Zero);
1570
- callback = OnImage;
1571
- if (magnifier == IntPtr.Zero || !MagSetImageScalingCallback(magnifier, callback)) { broken = true; Why = "callback"; return false; }
1572
- return true;
1573
- }
1574
- catch (Exception e) { broken = true; Why = "ready: " + e.Message; return false; }
1575
- }
1576
-
1577
- /** The screen rectangle without the `exclude` window, or null when unavailable. */
1578
- public static Bitmap Capture(Rectangle area, IntPtr exclude)
1579
- {
1580
- if (!Ready()) return null;
1581
- Bitmap result = null;
1582
- try
1583
- {
1584
- // The never-shown host must be as large as the capture, or the control is clipped.
1585
- Native.SetWindowPos(host.Handle, IntPtr.Zero, 0, 0, area.Width, area.Height, 0x0004 | 0x0010);
1586
- Native.SetWindowPos(magnifier, IntPtr.Zero, 0, 0, area.Width, area.Height, 0x0004 | 0x0010); // NOZORDER | NOACTIVATE
1587
- if (!MagSetWindowFilterList(magnifier, 0 /* MW_FILTERMODE_EXCLUDE */, 1, new[] { exclude })) { broken = true; Why = "filter"; return null; }
1588
- frame = null;
1589
- var rc = new Native.RECT { Left = area.Left, Top = area.Top, Right = area.Right, Bottom = area.Bottom };
1590
- if (!MagSetWindowSource(magnifier, rc)) { broken = true; Why = "source"; return null; }
1591
- result = frame;
1592
- frame = null;
1593
- if (result == null || result.Width != area.Width || result.Height != area.Height)
1594
- {
1595
- Why = result == null ? "no frame" : "size " + result.Width + "x" + result.Height;
1596
- if (result != null) result.Dispose();
1597
- broken = true;
1598
- return null;
1599
- }
1600
- if (!HasVisiblePixels(result))
1601
- {
1602
- result.Dispose();
1603
- broken = true;
1604
- Why = "black magnifier frame";
1605
- Console.Error.WriteLine("Magnification capture returned a black frame; using BitBlt for the rest of this helper process.");
1606
- return null;
1607
- }
1608
- return result;
1609
- }
1610
- catch (Exception e)
1611
- {
1612
- if (result != null) result.Dispose();
1613
- broken = true;
1614
- Why = "capture: " + e.Message;
1615
- return null;
1616
- }
1617
- }
1618
-
1619
- internal static bool HasVisiblePixels(Bitmap bitmap)
1620
- {
1621
- var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
1622
- try
1623
- {
1624
- var row = new byte[bitmap.Width * 4];
1625
- for (int y = 0; y < bitmap.Height; y++)
1626
- {
1627
- Marshal.Copy(IntPtr.Add(data.Scan0, y * data.Stride), row, 0, row.Length);
1628
- for (int x = 0; x < row.Length; x += 4)
1629
- {
1630
- // Ignore the padding byte and allow black-level noise.
1631
- if (row[x] > 3 || row[x + 1] > 3 || row[x + 2] > 3) return true;
1632
- }
1633
- }
1634
- return false;
1635
- }
1636
- finally { bitmap.UnlockBits(data); }
1637
- }
1638
-
1639
- static bool OnImage(IntPtr hwnd, IntPtr srcdata, MAGIMAGEHEADER h, IntPtr destdata, MAGIMAGEHEADER dh, Native.RECT unclipped, Native.RECT clipped, IntPtr dirty)
1640
- {
1641
- try
1642
- {
1643
- var bmp = new Bitmap((int)h.width, (int)h.height, PixelFormat.Format32bppRgb);
1644
- var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
1645
- try
1646
- {
1647
- int rowBytes = (int)h.width * 4;
1648
- var row = new byte[rowBytes];
1649
- for (int y = 0; y < h.height; y++)
1650
- {
1651
- Marshal.Copy(new IntPtr(srcdata.ToInt64() + h.offset + (long)y * h.stride), row, 0, rowBytes);
1652
- Marshal.Copy(row, 0, new IntPtr(data.Scan0.ToInt64() + (long)y * data.Stride), rowBytes);
1653
- }
1654
- }
1655
- finally { bmp.UnlockBits(data); }
1656
- frame = bmp;
1657
- }
1658
- catch (Exception) { frame = null; }
1659
- return true;
1660
- }
1661
- }
1662
-
1663
- /** While the agent moves, clicks or scrolls, the card lets the mouse through. */
1664
- internal sealed class PassThrough : IDisposable
1665
- {
1666
- readonly IntPtr[] hwnds;
1667
- readonly int[] oldEx;
1668
- bool active;
1669
-
1670
- /** The DSH card and our progress card let injected pointer input through. */
1671
- public PassThrough()
1672
- {
1673
- hwnds = new[] { CardLayer.Hwnd, Overlay.PetHwnd };
1674
- oldEx = new int[hwnds.Length];
1675
- for (int i = 0; i < hwnds.Length; i++)
1676
- {
1677
- if (hwnds[i] == IntPtr.Zero || !Native.IsWindow(hwnds[i])) { hwnds[i] = IntPtr.Zero; continue; }
1678
- oldEx[i] = Native.GetWindowLong(hwnds[i], -20);
1679
- Native.SetWindowLong(hwnds[i], -20, oldEx[i] | 0x20 | 0x80000); // WS_EX_TRANSPARENT (layered already)
1680
- active = true;
1681
- }
1682
- }
1683
-
1684
- public void Dispose()
1685
- {
1686
- if (!active) return;
1687
- Thread.Sleep(60); // let the injected input reach its target first
1688
- for (int i = 0; i < hwnds.Length; i++)
1689
- if (hwnds[i] != IntPtr.Zero && Native.IsWindow(hwnds[i])) Native.SetWindowLong(hwnds[i], -20, oldEx[i]);
1690
- }
1691
- }
1692
-
1693
- internal static class Windows
1694
- {
1695
- public static string ExePath(uint pid)
1696
- {
1697
- IntPtr h = Native.OpenProcess(0x1000, false, pid);
1698
- if (h == IntPtr.Zero) return "";
1699
- try
1700
- {
1701
- var sb = new StringBuilder(1024); int size = sb.Capacity;
1702
- return Native.QueryFullProcessImageName(h, 0, sb, ref size) ? sb.ToString() : "";
1703
- }
1704
- finally { Native.CloseHandle(h); }
1705
- }
1706
-
1707
- public static Dictionary<string, object> Describe(IntPtr hwnd)
1708
- {
1709
- var d = new Dictionary<string, object>();
1710
- if (hwnd == IntPtr.Zero || !Native.IsWindow(hwnd)) return d;
1711
- uint pid; Native.GetWindowThreadProcessId(hwnd, out pid);
1712
- int len = Native.GetWindowTextLength(hwnd);
1713
- var title = new StringBuilder(Math.Max(len + 1, 2)); Native.GetWindowText(hwnd, title, title.Capacity);
1714
- var cls = new StringBuilder(256); Native.GetClassName(hwnd, cls, cls.Capacity);
1715
- Native.RECT rc;
1716
- if (Native.DwmGetWindowAttribute(hwnd, 9, out rc, Marshal.SizeOf(typeof(Native.RECT))) != 0) Native.GetWindowRect(hwnd, out rc);
1717
- string path = ExePath(pid);
1718
- d["hwnd"] = hwnd.ToInt64();
1719
- d["title"] = title.ToString();
1720
- d["className"] = cls.ToString();
1721
- d["pid"] = (long)pid;
1722
- d["exe"] = path.Length > 0 ? Path.GetFileName(path) : "";
1723
- d["path"] = path;
1724
- d["x"] = rc.Left; d["y"] = rc.Top; d["width"] = rc.Right - rc.Left; d["height"] = rc.Bottom - rc.Top;
1725
- d["minimized"] = Native.IsIconic(hwnd);
1726
- d["maximized"] = Native.IsZoomed(hwnd);
1727
- return d;
1728
- }
1729
-
1730
- public static List<object> List()
1731
- {
1732
- var list = new List<object>();
1733
- IntPtr fg = Native.GetForegroundWindow();
1734
- uint self = (uint)Process.GetCurrentProcess().Id;
1735
- Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
1736
- {
1737
- if (!Native.IsWindowVisible(h) || Native.GetWindowTextLength(h) == 0) return true;
1738
- if (Native.GetWindow(h, 4) != IntPtr.Zero) return true; // owned popup
1739
- int ex = Native.GetWindowLong(h, -20);
1740
- if ((ex & 0x80) != 0 && (ex & 0x40000) == 0) return true; // tool window
1741
- int cloaked;
1742
- if (Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
1743
- uint pid; Native.GetWindowThreadProcessId(h, out pid);
1744
- if (pid == self) return true;
1745
- var d = Describe(h);
1746
- d["foreground"] = h == fg;
1747
- list.Add(d);
1748
- return true;
1749
- };
1750
- Native.EnumWindows(cb, IntPtr.Zero);
1751
- GC.KeepAlive(cb);
1752
- return list;
1753
- }
1754
-
1755
- public static Dictionary<string, object> At(int x, int y)
1756
- {
1757
- IntPtr h = Native.WindowFromPoint(new Native.POINT(x, y));
1758
- if (h != IntPtr.Zero) h = Native.GetAncestor(h, 2); // GA_ROOT
1759
- uint pid = 0;
1760
- if (h != IntPtr.Zero) Native.GetWindowThreadProcessId(h, out pid);
1761
- uint cardPid = CardLayer.Pid();
1762
- if (h == IntPtr.Zero || pid == (uint)Process.GetCurrentProcess().Id || (cardPid != 0 && pid == cardPid) || SeeThrough(pid))
1763
- {
1764
- // Our own status pill is under the point (it dodges before the
1765
- // click): report the topmost foreign window there instead.
1766
- IntPtr found = IntPtr.Zero;
1767
- uint self = (uint)Process.GetCurrentProcess().Id;
1768
- Native.EnumWindowsProc cb = delegate (IntPtr w, IntPtr data)
1769
- {
1770
- if (!Native.IsWindowVisible(w)) return true;
1771
- uint p; Native.GetWindowThreadProcessId(w, out p);
1772
- if (p == self || (cardPid != 0 && p == cardPid) || SeeThrough(p)) return true; // our overlay, the DSH card, game overlays
1773
- if ((Native.GetWindowLong(w, -20) & 0x20) != 0) return true; // WS_EX_TRANSPARENT
1774
- if (Native.IsIconic(w)) return true;
1775
- int cloaked;
1776
- if (Native.DwmGetWindowAttribute(w, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
1777
- Native.RECT rc; Native.GetWindowRect(w, out rc);
1778
- if (x >= rc.Left && x < rc.Right && y >= rc.Top && y < rc.Bottom) { found = w; return false; }
1779
- return true;
1780
- };
1781
- Native.EnumWindows(cb, IntPtr.Zero);
1782
- GC.KeepAlive(cb);
1783
- h = found;
1784
- }
1785
- return Describe(h);
1786
- }
1787
-
1788
- /** Full-screen overlays that never take input themselves (NVIDIA / Xbox Game Bar...). */
1789
- static readonly string[] Overlays = { "nvidia overlay.exe", "nvsphelper64.exe", "gamebar.exe", "gamebarftserver.exe" };
1790
-
1791
- static bool SeeThrough(uint pid)
1792
- {
1793
- if (pid == 0) return false;
1794
- string exe = Path.GetFileName(ExePath(pid)).ToLowerInvariant();
1795
- return Array.IndexOf(Overlays, exe) >= 0;
1796
- }
1797
-
1798
- /**
1799
- * Apps that run without any visible window (closed to the system tray):
1800
- * per program, its largest hidden, titled, unowned top-level window.
1801
- */
1802
- public static List<object> Background(bool withTray)
1803
- {
1804
- uint self = (uint)Process.GetCurrentProcess().Id;
1805
- var visible = new HashSet<uint>();
1806
- var best = new Dictionary<uint, KeyValuePair<IntPtr, int>>();
1807
- Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
1808
- {
1809
- uint pid; Native.GetWindowThreadProcessId(h, out pid);
1810
- if (pid == self || pid == 0) return true;
1811
- if (Native.GetWindow(h, 4) != IntPtr.Zero) return true; // owned
1812
- if (Native.IsWindowVisible(h))
1813
- {
1814
- int cloaked;
1815
- bool isCloaked = Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0;
1816
- if (!isCloaked && Native.GetWindowTextLength(h) > 0) visible.Add(pid);
1817
- return true;
1818
- }
1819
- if (Native.GetWindowTextLength(h) == 0) return true;
1820
- var cls = new StringBuilder(256); Native.GetClassName(h, cls, cls.Capacity);
1821
- string c = cls.ToString();
1822
- if (c == "ConsoleWindowClass" || c == "IME" || c == "MSCTFIME UI" || c.StartsWith("GDI+")) return true;
1823
- Native.RECT rc; Native.GetWindowRect(h, out rc);
1824
- int area = (rc.Right - rc.Left) * (rc.Bottom - rc.Top);
1825
- if (rc.Right - rc.Left < 240 || rc.Bottom - rc.Top < 160) return true;
1826
- KeyValuePair<IntPtr, int> seen;
1827
- if (!best.TryGetValue(pid, out seen) || seen.Value < area) best[pid] = new KeyValuePair<IntPtr, int>(h, area);
1828
- return true;
1829
- };
1830
- Native.EnumWindows(cb, IntPtr.Zero);
1831
- GC.KeepAlive(cb);
1832
- // Programs whose other process shows a window are not in the background.
1833
- var shownExes = new HashSet<string>();
1834
- foreach (var pid in visible) shownExes.Add(Path.GetFileName(ExePath(pid)).ToLowerInvariant());
1835
- var byExe = new Dictionary<string, Dictionary<string, object>>();
1836
- foreach (var pair in best)
1837
- {
1838
- if (visible.Contains(pair.Key)) continue;
1839
- var d = Describe(pair.Value.Key);
1840
- string exe = ((string)d["exe"]).ToLowerInvariant();
1841
- if (exe.Length == 0 || shownExes.Contains(exe) || exe == "explorer.exe" || exe == "textinputhost.exe" || exe == "shellexperiencehost.exe" || exe == "searchhost.exe" || exe == "startmenuexperiencehost.exe") continue;
1842
- Dictionary<string, object> prev;
1843
- if (byExe.TryGetValue(exe, out prev) && Convert.ToInt32(prev["width"]) * Convert.ToInt32(prev["height"]) >= pair.Value.Value) continue;
1844
- byExe[exe] = d;
1845
- }
1846
- // Looking through the notification area takes a second or more; skip it when only the list matters.
1847
- if (!withTray) return new List<object>(byExe.Values);
1848
- var owners = Tray.WindowsByPid();
1849
- var exeOf = new Dictionary<uint, string>();
1850
- foreach (var pid in owners.Keys) exeOf[pid] = Path.GetFileName(ExePath(pid));
1851
- foreach (var d in byExe.Values) d["tray"] = Tray.HasIcon((string)d["exe"], owners, exeOf);
1852
- return new List<object>(byExe.Values);
1853
- }
1854
-
1855
- /** Visible, titled, unowned windows of these processes. */
1856
- public static IntPtr ShownWindowOf(HashSet<uint> pids)
1857
- {
1858
- IntPtr found = IntPtr.Zero; int bestArea = 0;
1859
- Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
1860
- {
1861
- if (!Native.IsWindowVisible(h) || Native.GetWindowTextLength(h) == 0 || Native.GetWindow(h, 4) != IntPtr.Zero) return true;
1862
- uint pid; Native.GetWindowThreadProcessId(h, out pid);
1863
- if (!pids.Contains(pid)) return true;
1864
- int cloaked;
1865
- if (Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
1866
- Native.RECT rc; Native.GetWindowRect(h, out rc);
1867
- int area = (rc.Right - rc.Left) * (rc.Bottom - rc.Top);
1868
- if (area > bestArea) { bestArea = area; found = h; }
1869
- return true;
1870
- };
1871
- Native.EnumWindows(cb, IntPtr.Zero);
1872
- GC.KeepAlive(cb);
1873
- return found;
1874
- }
1875
-
1876
- public static Dictionary<string, object> Focus(IntPtr hwnd)
1877
- {
1878
- if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
1879
- if (Native.IsIconic(hwnd)) { Native.ShowWindow(hwnd, 9); Thread.Sleep(150); }
1880
- if (Native.GetForegroundWindow() != hwnd)
1881
- {
1882
- IntPtr fg = Native.GetForegroundWindow();
1883
- uint pid;
1884
- uint fgThread = Native.GetWindowThreadProcessId(fg, out pid);
1885
- uint cur = Native.GetCurrentThreadId();
1886
- bool attached = fgThread != 0 && fgThread != cur && Native.AttachThreadInput(cur, fgThread, true);
1887
- try
1888
- {
1889
- Native.BringWindowToTop(hwnd);
1890
- Native.SetForegroundWindow(hwnd);
1891
- }
1892
- finally { if (attached) Native.AttachThreadInput(cur, fgThread, false); }
1893
- Thread.Sleep(60);
1894
- if (Native.GetForegroundWindow() != hwnd)
1895
- {
1896
- Native.SwitchToThisWindow(hwnd, true);
1897
- Thread.Sleep(120);
1898
- }
1899
- if (Native.GetForegroundWindow() != hwnd)
1900
- {
1901
- // Holding Alt lifts the foreground lock; a no-op VK keeps the
1902
- // Alt release from opening the target's menu bar.
1903
- var inputs = new Native.INPUT[3];
1904
- var down = new Native.INPUT(); down.type = Native.INPUT_KEYBOARD; down.u.ki.wVk = 0x12; down.u.ki.dwExtraInfo = Native.Marker;
1905
- Native.SendInput(1, new[] { down }, Marshal.SizeOf(typeof(Native.INPUT)));
1906
- Native.SetForegroundWindow(hwnd);
1907
- var noop = new Native.INPUT(); noop.type = Native.INPUT_KEYBOARD; noop.u.ki.wVk = 0xFF; noop.u.ki.dwExtraInfo = Native.Marker;
1908
- var noopUp = noop; noopUp.u.ki.dwFlags = Native.KEYEVENTF_KEYUP;
1909
- var up = down; up.u.ki.dwFlags = Native.KEYEVENTF_KEYUP;
1910
- inputs[0] = noop; inputs[1] = noopUp; inputs[2] = up;
1911
- Native.SendInput(3, inputs, Marshal.SizeOf(typeof(Native.INPUT)));
1912
- Thread.Sleep(120);
1913
- }
1914
- if (Native.GetForegroundWindow() != hwnd)
1915
- {
1916
- // Last resort: restoring a minimized window always activates it.
1917
- bool zoomed = Native.IsZoomed(hwnd);
1918
- Native.ShowWindow(hwnd, 6); // SW_MINIMIZE
1919
- Thread.Sleep(150);
1920
- Native.ShowWindow(hwnd, zoomed ? 3 : 9); // SW_MAXIMIZE / SW_RESTORE
1921
- Thread.Sleep(200);
1922
- }
1923
- }
1924
- var d = Describe(hwnd);
1925
- d["focused"] = Native.GetForegroundWindow() == hwnd;
1926
- return d;
1927
- }
1928
-
1929
- // Values live on the target HWND, not in helper memory. A replacement
1930
- // helper can restore them after a timeout/kill, without stale HWND files.
1931
- const string CardPrefix = "DSH.ComputerUse.Card.v1.";
1932
- static readonly string[] CardFields = { "flags", "show", "minX", "minY", "maxX", "maxY", "left", "top", "right", "bottom", "ex", "key", "alpha", "layerFlags" };
1933
-
1934
- static void SaveCard(IntPtr hwnd)
1935
- {
1936
- if (Native.GetProp(hwnd, CardPrefix + "owner") != IntPtr.Zero) return;
1937
- var wp = new Native.WINDOWPLACEMENT(); wp.length = Marshal.SizeOf(wp);
1938
- if (!Native.GetWindowPlacement(hwnd, ref wp)) throw new Exception("Cannot save host window placement");
1939
- uint key, flags; byte alpha;
1940
- Native.GetLayeredWindowAttributes(hwnd, out key, out alpha, out flags);
1941
- int[] values = { wp.flags, wp.showCmd, wp.ptMinPosition.X, wp.ptMinPosition.Y, wp.ptMaxPosition.X, wp.ptMaxPosition.Y,
1942
- wp.rcNormalPosition.Left, wp.rcNormalPosition.Top, wp.rcNormalPosition.Right, wp.rcNormalPosition.Bottom,
1943
- Native.GetWindowLong(hwnd, -20), unchecked((int)key), alpha, unchecked((int)flags) };
1944
- try {
1945
- for (int i = 0; i < values.Length; i++)
1946
- if (!Native.SetProp(hwnd, CardPrefix + CardFields[i], new IntPtr(values[i]))) throw new Exception("Cannot save host window state");
1947
- // Commit marker is written last, before any window mutation.
1948
- if (!Native.SetProp(hwnd, CardPrefix + "owner", new IntPtr(Process.GetCurrentProcess().Id))) throw new Exception("Cannot save host window owner");
1949
- }
1950
- catch { ClearCard(hwnd); throw; }
1951
- }
1952
-
1953
- static void ClearCard(IntPtr hwnd)
1954
- {
1955
- Native.RemoveProp(hwnd, CardPrefix + "owner");
1956
- foreach (string field in CardFields) Native.RemoveProp(hwnd, CardPrefix + field);
1957
- }
1958
-
1959
- public static void RecoverCards(bool own)
1960
- {
1961
- int self = Process.GetCurrentProcess().Id;
1962
- Native.EnumWindowsProc cb = delegate(IntPtr hwnd, IntPtr data) {
1963
- int owner = Native.GetProp(hwnd, CardPrefix + "owner").ToInt32();
1964
- if (owner == 0) return true;
1965
- bool restore = own && owner == self;
1966
- if (!own && owner != self) {
1967
- try { using (var p = Process.GetProcessById(owner)) restore = p.HasExited; }
1968
- catch (ArgumentException) { restore = true; }
1969
- catch (Exception) { return true; } // do not touch a live/inaccessible helper
1970
- }
1971
- if (restore) { try { Uncard(hwnd); } catch (Exception) { } }
1972
- return true;
1973
- };
1974
- Native.EnumWindows(cb, IntPtr.Zero); GC.KeepAlive(cb);
1975
- }
1976
-
1977
- /// Shrink a window into an always-on-top card; Uncard restores it exactly.
1978
- public static object Card(IntPtr hwnd, int x, int y, int w, int h)
1979
- {
1980
- if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
1981
- SaveCard(hwnd);
1982
- CardLayer.Attach(hwnd);
1983
- // A minimized window restores to its previous state, which may be maximized: restore until normal.
1984
- for (int i = 0; i < 2 && (Native.IsIconic(hwnd) || Native.IsZoomed(hwnd)); i++) { Native.ShowWindow(hwnd, 9); Thread.Sleep(150); }
1985
- Native.SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x0010 | 0x0040); // TOPMOST, NOACTIVATE | SHOWWINDOW
1986
- // Apps enforce a minimum size (Electron does): keep the card anchored bottom-right.
1987
- Native.RECT rc;
1988
- if (Native.GetWindowRect(hwnd, out rc) && (rc.Right - rc.Left != w || rc.Bottom - rc.Top != h))
1989
- {
1990
- int nx = x + w - (rc.Right - rc.Left), ny = y + h - (rc.Bottom - rc.Top);
1991
- Native.SetWindowPos(hwnd, new IntPtr(-1), nx, ny, 0, 0, 0x0001 | 0x0010); // NOSIZE | NOACTIVATE
1992
- }
1993
- return Describe(hwnd);
1994
- }
1995
-
1996
- public static object Uncard(IntPtr hwnd)
1997
- {
1998
- if (CardLayer.Hwnd == hwnd) CardLayer.Detach();
1999
- if (!Native.IsWindow(hwnd)) return null;
2000
- if (Native.GetProp(hwnd, CardPrefix + "owner") != IntPtr.Zero)
2001
- {
2002
- int[] v = new int[CardFields.Length];
2003
- for (int i = 0; i < v.Length; i++) v[i] = Native.GetProp(hwnd, CardPrefix + CardFields[i]).ToInt32();
2004
- var wp = new Native.WINDOWPLACEMENT(); wp.length = Marshal.SizeOf(wp);
2005
- wp.flags = v[0]; wp.showCmd = v[1];
2006
- wp.ptMinPosition = new Native.POINT(v[2], v[3]); wp.ptMaxPosition = new Native.POINT(v[4], v[5]);
2007
- wp.rcNormalPosition = new Native.RECT { Left = v[6], Top = v[7], Right = v[8], Bottom = v[9] };
2008
- Native.SetWindowLong(hwnd, -20, v[10]);
2009
- if ((v[10] & 0x80000) != 0 && v[13] != 0) Native.SetLayeredWindowAttributes(hwnd, unchecked((uint)v[11]), (byte)v[12], unchecked((uint)v[13]));
2010
- if (!Native.SetWindowPos(hwnd, new IntPtr((v[10] & 8) != 0 ? -1 : -2), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010)) throw new Exception("Cannot restore host window style");
2011
- // Restore the normal rectangle first, then the original show state (maximized etc.).
2012
- int show = wp.showCmd;
2013
- wp.showCmd = 1; // SW_SHOWNORMAL
2014
- if (!Native.SetWindowPlacement(hwnd, ref wp)) throw new Exception("Cannot restore host window placement");
2015
- if (show == 3) Native.ShowWindow(hwnd, 3);
2016
- else if (show == 2) Native.ShowWindow(hwnd, 6);
2017
- ClearCard(hwnd);
2018
- }
2019
- return Describe(hwnd);
2020
- }
2021
-
2022
- public static object Command(IntPtr hwnd, string op)
2023
- {
2024
- if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
2025
- switch (op)
2026
- {
2027
- case "minimize": Native.ShowWindow(hwnd, 6); break;
2028
- case "maximize": Native.ShowWindow(hwnd, 3); break;
2029
- case "restore": Native.ShowWindow(hwnd, 9); break;
2030
- case "close": Native.PostMessage(hwnd, 0x0010, IntPtr.Zero, IntPtr.Zero); break;
2031
- default: throw new Exception("unknown window op: " + op);
2032
- }
2033
- Thread.Sleep(150);
2034
- return Describe(hwnd);
2035
- }
2036
- }
2037
-
2038
- /**
2039
- * Bring a program that lives in the system tray back the way the user
2040
- * would: click its notification-area icon (opening the "show hidden icons"
2041
- * overflow first). Launching it again would start a second instance (QQ
2042
- * shows a second login), and showing its hidden window directly leaves
2043
- * Electron / Qt apps frozen.
2044
- */
2045
- internal static class Tray
2046
- {
2047
- [StructLayout(LayoutKind.Sequential)]
2048
- struct NOTIFYICONIDENTIFIER { public int cbSize; public IntPtr hWnd; public uint uID; public Guid guidItem; }
2049
- [DllImport("shell32.dll")] static extern int Shell_NotifyIconGetRect(ref NOTIFYICONIDENTIFIER id, out Native.RECT rect);
2050
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string cls, string title);
2051
-
2052
- static bool IconRect(IntPtr hwnd, uint id, out Rectangle rect)
2053
- {
2054
- var n = new NOTIFYICONIDENTIFIER(); n.cbSize = Marshal.SizeOf(typeof(NOTIFYICONIDENTIFIER)); n.hWnd = hwnd; n.uID = id;
2055
- Native.RECT rc;
2056
- bool ok = Shell_NotifyIconGetRect(ref n, out rc) == 0 && rc.Right > rc.Left;
2057
- rect = ok ? new Rectangle(rc.Left, rc.Top, rc.Right - rc.Left, rc.Bottom - rc.Top) : Rectangle.Empty;
2058
- return ok;
2059
- }
2060
-
2061
- /** Top-level and message-only windows per process: tray icons are registered on one of them. */
2062
- public static Dictionary<uint, List<IntPtr>> WindowsByPid()
2063
- {
2064
- var map = new Dictionary<uint, List<IntPtr>>();
2065
- Action<IntPtr> add = delegate (IntPtr h)
2066
- {
2067
- uint pid; Native.GetWindowThreadProcessId(h, out pid);
2068
- List<IntPtr> list;
2069
- if (!map.TryGetValue(pid, out list)) map[pid] = list = new List<IntPtr>();
2070
- list.Add(h);
2071
- };
2072
- Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data) { add(h); return true; };
2073
- Native.EnumWindows(cb, IntPtr.Zero);
2074
- GC.KeepAlive(cb);
2075
- IntPtr m = IntPtr.Zero;
2076
- while ((m = FindWindowEx(new IntPtr(-3), m, null, null)) != IntPtr.Zero) add(m); // HWND_MESSAGE
2077
- return map;
2078
- }
2079
-
2080
- /** The icon's owner window and id. */
2081
- static bool Find(HashSet<uint> pids, Dictionary<uint, List<IntPtr>> byPid, out IntPtr owner, out uint id)
2082
- {
2083
- var windows = new List<IntPtr>();
2084
- foreach (var pid in pids) { List<IntPtr> list; if (byPid.TryGetValue(pid, out list)) windows.AddRange(list); }
2085
- foreach (var h in windows)
2086
- {
2087
- // Icon ids are small; scan further only on windows that look like tray hosts.
2088
- var cls = new StringBuilder(256); Native.GetClassName(h, cls, cls.Capacity);
2089
- string c = cls.ToString().ToLowerInvariant();
2090
- uint ids = c.Contains("tray") || c.Contains("notify") || c.Contains("icon") ? 128u : 16u;
2091
- for (uint i = 0; i < ids; i++)
2092
- {
2093
- Rectangle r;
2094
- if (IconRect(h, i, out r)) { owner = h; id = i; return true; }
2095
- }
2096
- }
2097
- owner = IntPtr.Zero; id = 0;
2098
- return false;
2099
- }
2100
-
2101
- public static bool HasIcon(string exe, Dictionary<uint, List<IntPtr>> byPid, Dictionary<uint, string> exeOf)
2102
- {
2103
- // Process.GetProcessesByName is slow; the processes owning windows are enough here.
2104
- var pids = new HashSet<uint>();
2105
- foreach (var pair in exeOf)
2106
- if (string.Equals(pair.Value, exe, StringComparison.OrdinalIgnoreCase)) pids.Add(pair.Key);
2107
- IntPtr owner; uint id;
2108
- return pids.Count > 0 && Find(pids, byPid, out owner, out id);
2109
- }
2110
-
2111
- static HashSet<uint> Pids(string exe)
2112
- {
2113
- var pids = new HashSet<uint>();
2114
- foreach (var p in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(exe))) { pids.Add((uint)p.Id); p.Dispose(); }
2115
- return pids;
2116
- }
2117
-
2118
- /** The taskbar's "show hidden icons" button. */
2119
- static Rectangle Chevron()
2120
- {
2121
- Rectangle found = Rectangle.Empty;
2122
- var worker = new Thread(delegate ()
2123
- {
2124
- try
2125
- {
2126
- var tray = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "Shell_TrayWnd"));
2127
- if (tray == null) return;
2128
- var buttons = tray.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));
2129
- AutomationElement pick = null;
2130
- foreach (AutomationElement b in buttons)
2131
- {
2132
- string name = b.Current.Name ?? "";
2133
- if (name.Contains("隐藏的图标") || name.ToLowerInvariant().Contains("hidden icons") || b.Current.ClassName == "NotifyIconOverflowButton") { pick = b; break; }
2134
- }
2135
- if (pick == null)
2136
- foreach (AutomationElement b in buttons)
2137
- if (b.Current.ClassName == "SystemTray.NormalButton") { pick = b; break; }
2138
- if (pick == null) return;
2139
- var r = pick.Current.BoundingRectangle;
2140
- found = new Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
2141
- }
2142
- catch (Exception) { }
2143
- });
2144
- worker.IsBackground = true;
2145
- worker.SetApartmentState(ApartmentState.MTA);
2146
- worker.Start();
2147
- worker.Join(4000);
2148
- return found;
2149
- }
2150
-
2151
- static void Click(Rectangle r, int count)
2152
- {
2153
- var d = new Dictionary<string, object>();
2154
- d["x"] = r.X + r.Width / 2; d["y"] = r.Y + r.Height / 2; d["count"] = count;
2155
- using (new PassThrough()) Input.Click(d);
2156
- }
2157
-
2158
- static IntPtr WaitShown(HashSet<uint> pids, int ms)
2159
- {
2160
- var until = DateTime.UtcNow.AddMilliseconds(ms);
2161
- do
2162
- {
2163
- IntPtr h = Windows.ShownWindowOf(pids);
2164
- if (h != IntPtr.Zero) return h;
2165
- Thread.Sleep(120);
2166
- } while (DateTime.UtcNow < until);
2167
- return IntPtr.Zero;
2168
- }
2169
-
2170
- public static object Restore(string exe)
2171
- {
2172
- var result = new Dictionary<string, object>();
2173
- var pids = Pids(exe);
2174
- result["running"] = pids.Count > 0;
2175
- IntPtr owner; uint id;
2176
- if (pids.Count == 0 || !Find(pids, WindowsByPid(), out owner, out id)) { result["icon"] = false; return result; }
2177
- result["icon"] = true;
2178
- Rectangle icon; IconRect(owner, id, out icon);
2179
- // An icon in the overflow reports the chevron's rectangle until the overflow is open.
2180
- Rectangle chevron = Chevron();
2181
- if (!chevron.IsEmpty && Math.Abs(chevron.X - icon.X) <= 2 && Math.Abs(chevron.Y - icon.Y) <= 2)
2182
- {
2183
- Click(chevron, 1);
2184
- Thread.Sleep(450);
2185
- IconRect(owner, id, out icon);
2186
- result["overflow"] = true;
2187
- }
2188
- Click(icon, 1);
2189
- IntPtr shown = WaitShown(pids, 1500);
2190
- if (shown == IntPtr.Zero)
2191
- {
2192
- // Some apps restore on a double click only.
2193
- Rectangle again;
2194
- if (IconRect(owner, id, out again) && !(Math.Abs(chevron.X - again.X) <= 2 && Math.Abs(chevron.Y - again.Y) <= 2)) Click(again, 2);
2195
- shown = WaitShown(pids, 1500);
2196
- }
2197
- if (shown != IntPtr.Zero) { result["window"] = Windows.Focus(shown); }
2198
- return result;
2199
- }
2200
- }
2201
-
2202
- internal static class Apps
2203
- {
2204
- [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
2205
- static extern int AssocQueryString(uint flags, uint str, string association, string verb, StringBuilder output, ref uint length);
2206
-
2207
- public static object OpenUrl(string value)
2208
- {
2209
- Uri url;
2210
- if (!Uri.TryCreate(value, UriKind.Absolute, out url) || (url.Scheme != "http" && url.Scheme != "https"))
2211
- throw new Exception("Expected an HTTP(S) URL");
2212
- const uint executable = 2;
2213
- var path = new StringBuilder(32768);
2214
- uint length = (uint)path.Capacity;
2215
- if (AssocQueryString(0, executable, url.Scheme, "open", path, ref length) != 0)
2216
- throw new Exception("Could not resolve the default browser for " + url.Scheme);
2217
- string exe = Path.GetFileName(path.ToString()).ToLowerInvariant();
2218
- string flag;
2219
- switch (exe)
2220
- {
2221
- case "chrome.exe": case "msedge.exe": case "brave.exe": case "vivaldi.exe": case "chromium.exe":
2222
- flag = "--new-window"; break;
2223
- case "firefox.exe": flag = "-new-window"; break;
2224
- default: throw new Exception("Cannot safely open a new window in the default browser (" + exe + ")");
2225
- }
2226
- string escapedUrl = url.AbsoluteUri.Replace("\"", "%22").Replace("\\", "%5C");
2227
- using (var process = Process.Start(new ProcessStartInfo(path.ToString(), flag + " \"" + escapedUrl + "\"") { UseShellExecute = false })) { }
2228
- return new Dictionary<string, object> { { "exe", exe } };
2229
- }
2230
- static List<KeyValuePair<string, string>> cache;
2231
- static DateTime cachedAt;
2232
- static readonly object Gate = new object();
2233
-
2234
- /// <summary>
2235
- /// Listing the Start menu takes about two seconds the first time. Do it
2236
- /// while the model is still thinking, not inside its first open_application.
2237
- /// </summary>
2238
- public static void Warm()
2239
- {
2240
- var worker = new Thread(delegate () { try { Windows.List(); } catch (Exception) { } try { All(); } catch (Exception) { } });
2241
- worker.IsBackground = true;
2242
- worker.SetApartmentState(ApartmentState.STA);
2243
- worker.Start();
2244
- }
2245
-
2246
- static List<KeyValuePair<string, string>> All()
2247
- {
2248
- lock (Gate) { return Load(); }
2249
- }
2250
-
2251
- static void AddIfNew(List<KeyValuePair<string, string>> list, HashSet<string> seen, string name, string id)
2252
- {
2253
- if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id)) return;
2254
- string key = name.Trim().ToLowerInvariant() + "\u0000" + id.Trim().ToLowerInvariant();
2255
- if (seen.Add(key)) list.Add(new KeyValuePair<string, string>(name.Trim(), id.Trim()));
2256
- }
2257
-
2258
- static string ExtractExePath(string raw)
2259
- {
2260
- if (string.IsNullOrEmpty(raw)) return "";
2261
- string s = raw.Trim();
2262
- if (s.StartsWith("\""))
2263
- {
2264
- int end = s.IndexOf('"', 1);
2265
- if (end > 1) s = s.Substring(1, end - 1);
2266
- }
2267
- else
2268
- {
2269
- int comma = s.IndexOf(',');
2270
- if (comma > 0) s = s.Substring(0, comma);
2271
- }
2272
- s = s.Trim();
2273
- if (!s.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return "";
2274
- return File.Exists(s) ? s : "";
2275
- }
2276
-
2277
- static void ScanStartFolder(string dir, int depth, List<KeyValuePair<string, string>> list, HashSet<string> seen)
2278
- {
2279
- if (depth > 3 || string.IsNullOrEmpty(dir) || !Directory.Exists(dir)) return;
2280
- try
2281
- {
2282
- foreach (var f in Directory.GetFiles(dir, "*.lnk"))
2283
- {
2284
- string name = Path.GetFileNameWithoutExtension(f);
2285
- if (name.IndexOf("uninstall", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("卸载", StringComparison.OrdinalIgnoreCase) >= 0) continue;
2286
- AddIfNew(list, seen, name, "lnk:" + f);
2287
- }
2288
- foreach (var sub in Directory.GetDirectories(dir))
2289
- ScanStartFolder(sub, depth + 1, list, seen);
2290
- }
2291
- catch (Exception) { }
2292
- }
2293
-
2294
- static void ScanRegistryApps(List<KeyValuePair<string, string>> list, HashSet<string> seen)
2295
- {
2296
- var roots = new RegistryKey[] { Registry.CurrentUser, Registry.LocalMachine };
2297
- foreach (var root in roots)
2298
- {
2299
- // 1. App Paths (e.g. WeChat.exe, chrome.exe, code.exe)
2300
- try
2301
- {
2302
- using (var ap = root.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths"))
2303
- {
2304
- if (ap != null)
2305
- {
2306
- foreach (var subName in ap.GetSubKeyNames())
2307
- {
2308
- try
2309
- {
2310
- using (var sub = ap.OpenSubKey(subName))
2311
- {
2312
- if (sub == null) continue;
2313
- string exe = ExtractExePath(Convert.ToString(sub.GetValue(null)) ?? "");
2314
- if (exe.Length > 0) AddIfNew(list, seen, Path.GetFileNameWithoutExtension(subName), "exe:" + exe);
2315
- }
2316
- }
2317
- catch (Exception) { }
2318
- }
2319
- }
2320
- }
2321
- }
2322
- catch (Exception) { }
2323
-
2324
- // 2. Uninstall table DisplayName + DisplayIcon (.exe)
2325
- var uninstallPaths = new string[] {
2326
- @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
2327
- @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
2328
- };
2329
- foreach (var upath in uninstallPaths)
2330
- {
2331
- try
2332
- {
2333
- using (var uk = root.OpenSubKey(upath))
2334
- {
2335
- if (uk == null) continue;
2336
- foreach (var subName in uk.GetSubKeyNames())
2337
- {
2338
- try
2339
- {
2340
- using (var sub = uk.OpenSubKey(subName))
2341
- {
2342
- if (sub == null) continue;
2343
- string displayName = Convert.ToString(sub.GetValue("DisplayName")) ?? "";
2344
- if (displayName.Length == 0) continue;
2345
- string iconExe = ExtractExePath(Convert.ToString(sub.GetValue("DisplayIcon")) ?? "");
2346
- if (iconExe.Length == 0) continue;
2347
- if (iconExe.IndexOf("unins", StringComparison.OrdinalIgnoreCase) >= 0 || iconExe.IndexOf("setup", StringComparison.OrdinalIgnoreCase) >= 0) continue;
2348
- AddIfNew(list, seen, displayName, "exe:" + iconExe);
2349
- }
2350
- }
2351
- catch (Exception) { }
2352
- }
2353
- }
2354
- }
2355
- catch (Exception) { }
2356
- }
2357
- }
2358
- }
2359
-
2360
- static List<KeyValuePair<string, string>> Load()
2361
- {
2362
- if (cache != null && (DateTime.UtcNow - cachedAt).TotalSeconds < 600) return cache;
2363
- var list = new List<KeyValuePair<string, string>>();
2364
- var seen = new HashSet<string>();
2365
- Type t = Type.GetTypeFromProgID("Shell.Application");
2366
- dynamic shell = Activator.CreateInstance(t);
2367
- try
2368
- {
2369
- dynamic folder = shell.NameSpace("shell:AppsFolder");
2370
- foreach (dynamic item in folder.Items())
2371
- {
2372
- string name = item.Name; string path = item.Path;
2373
- AddIfNew(list, seen, name, path);
2374
- }
2375
- }
2376
- finally { Marshal.FinalReleaseComObject(shell); }
2377
- // Desktop & Start Menu shortcuts: portable and classic apps often only live there.
2378
- foreach (var folder in new[] {
2379
- Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
2380
- Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory),
2381
- Environment.GetFolderPath(Environment.SpecialFolder.Programs),
2382
- Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
2383
- })
2384
- {
2385
- ScanStartFolder(folder, 0, list, seen);
2386
- }
2387
- // Registry App Paths & Uninstall executable locations.
2388
- ScanRegistryApps(list, seen);
2389
- cache = list; cachedAt = DateTime.UtcNow;
2390
- return list;
2391
- }
2392
-
2393
- public static List<object> Search(string query, int limit)
2394
- {
2395
- string q = query.Trim().ToLowerInvariant();
2396
- var scored = new List<KeyValuePair<int, KeyValuePair<string, string>>>();
2397
- foreach (var app in All())
2398
- {
2399
- string n = app.Key.ToLowerInvariant();
2400
- 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;
2401
- if (q.Length == 0) score = 5;
2402
- if (score >= 0) scored.Add(new KeyValuePair<int, KeyValuePair<string, string>>(score * 1000 + Math.Min(n.Length, 999), app));
2403
- }
2404
- scored.Sort(delegate (KeyValuePair<int, KeyValuePair<string, string>> a, KeyValuePair<int, KeyValuePair<string, string>> b) { return a.Key.CompareTo(b.Key); });
2405
- var result = new List<object>();
2406
- for (int i = 0; i < scored.Count && i < limit; i++)
2407
- {
2408
- var d = new Dictionary<string, object>();
2409
- d["name"] = scored[i].Value.Key; d["id"] = scored[i].Value.Value;
2410
- result.Add(d);
2411
- }
2412
- return result;
2413
- }
2414
-
2415
- public static object Launch(Dictionary<string, object> r)
2416
- {
2417
- string appId = Args.Str(r, "appId", "");
2418
- string target = Args.Str(r, "target", "");
2419
- string args = Args.Str(r, "args", "");
2420
- ProcessStartInfo psi;
2421
- if (appId.StartsWith("lnk:")) psi = new ProcessStartInfo(appId.Substring(4));
2422
- else if (appId.StartsWith("exe:")) psi = new ProcessStartInfo(appId.Substring(4));
2423
- else if (appId.Length > 0) psi = new ProcessStartInfo("explorer.exe", "shell:AppsFolder\\" + appId);
2424
- else { psi = new ProcessStartInfo(target); if (args.Length > 0) psi.Arguments = args; }
2425
- psi.UseShellExecute = true;
2426
- using (var p = Process.Start(psi)) { }
2427
- return null;
2428
- }
2429
- }
2430
-
2431
- internal static class Uia
2432
- {
2433
- static readonly ControlType[] Interactive = {
2434
- ControlType.Button, ControlType.Edit, ControlType.Hyperlink, ControlType.MenuItem, ControlType.ListItem,
2435
- ControlType.TabItem, ControlType.CheckBox, ControlType.RadioButton, ControlType.ComboBox, ControlType.TreeItem,
2436
- ControlType.DataItem, ControlType.SplitButton, ControlType.Slider, ControlType.Spinner, ControlType.Document,
2437
- ControlType.MenuBar, ControlType.Menu, ControlType.ScrollBar, ControlType.Group };
2438
-
2439
- // Wake the renderer, but keep collecting the window too: browser tabs,
2440
- // toolbars and the address bar are outside the renderer's subtree.
2441
- static IntPtr ChromiumRoot(IntPtr hwnd)
2442
- {
2443
- try
2444
- {
2445
- var cls = new StringBuilder(256);
2446
- Native.GetClassName(hwnd, cls, cls.Capacity);
2447
- if (!cls.ToString().StartsWith("Chrome_WidgetWin", StringComparison.Ordinal)) return hwnd;
2448
- IntPtr render = IntPtr.Zero;
2449
- while ((render = Native.FindWindowEx(hwnd, render, "Chrome_RenderWidgetHostHWND", null)) != IntPtr.Zero)
2450
- if (Native.IsWindowVisible(render)) return render;
2451
- return hwnd;
2452
- }
2453
- catch { return hwnd; }
2454
- }
2455
-
2456
- static bool IsEditorClass(string cls)
2457
- {
2458
- if (string.IsNullOrEmpty(cls)) return false;
2459
- string[] marks = { "ProseMirror", "tiptap", "CodeMirror", "monaco-editor", "ql-editor" };
2460
- foreach (var mark in marks)
2461
- if (cls.IndexOf(mark, StringComparison.OrdinalIgnoreCase) >= 0) return true;
2462
- return false;
2463
- }
2464
-
2465
- // Chromium builds its accessibility tree lazily. A standard AT request
2466
- // (WM_GETOBJECT/OBJID_CLIENT) wakes it; without this, apps such as
2467
- // VS Code expose only a few nodes even though the render host exists.
2468
- static void WakeAccessibility(IntPtr hwnd)
2469
- {
2470
- try
2471
- {
2472
- IntPtr result;
2473
- Native.SendMessageTimeout(hwnd, 0x003D /* WM_GETOBJECT */, IntPtr.Zero,
2474
- new IntPtr(-4) /* OBJID_CLIENT */, 0x0002 /* SMTO_ABORTIFHUNG */, 1000, out result);
2475
- }
2476
- catch { }
2477
- }
2478
-
2479
- // A broken provider may never return. Bound background queries rather
2480
- // than creating an unbounded number of stuck threads on repeated reads.
2481
- static readonly SemaphoreSlim WindowCollectors = new SemaphoreSlim(4, 4);
2482
-
2483
- static bool SameWindow(IntPtr hwnd, uint expectedPid)
2484
- {
2485
- uint pid;
2486
- return expectedPid != 0 && Native.GetWindowThreadProcessId(hwnd, out pid) != 0 && pid == expectedPid;
2487
- }
2488
-
2489
- static bool IsActionWindow(IntPtr hwnd, uint pid, Native.POINT point)
2490
- {
2491
- if (!SameWindow(hwnd, pid) || Native.GetForegroundWindow() != hwnd) return false;
2492
- var hit = Windows.At(point.X, point.Y);
2493
- return hit.ContainsKey("hwnd") && Convert.ToInt64(hit["hwnd"]) == hwnd.ToInt64();
2494
- }
2495
-
2496
- public static object Act(Dictionary<string, object> r)
2497
- {
2498
- var hwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
2499
- uint pid = Convert.ToUInt32(r["pid"]);
2500
- var point = new Native.POINT(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
2501
- string runtimeId = Args.Str(r, "runtimeId", "");
2502
- string action = Args.Str(r, "action", "");
2503
- var result = new Dictionary<string, object> { { "performed", false } };
2504
- if (runtimeId.Length == 0 || !IsActionWindow(hwnd, pid, point))
2505
- throw new Exception("The named target window changed");
2506
-
2507
- // FromPoint is scoped to the visible hit. Ancestors are searched only
2508
- // for the exact listed element; no action is attempted on a substitute.
2509
- var hit = AutomationElement.FromPoint(new System.Windows.Point(point.X, point.Y));
2510
- AutomationElement target = null;
2511
- for (var el = hit; el != null; el = TreeWalker.ControlViewWalker.GetParent(el))
2512
- {
2513
- if (String.Join(",", el.GetRuntimeId()) == runtimeId) { target = el; break; }
2514
- if (el.Current.ControlType == ControlType.Window) break;
2515
- }
2516
- // Some providers stop the hit test at a host pane. The caller can
2517
- // re-resolve the control and verify its window before a pointer click.
2518
- if (target == null) return result;
2519
- if (target.Current.IsOffscreen) throw new Exception("The named target is offscreen");
2520
- if (!target.Current.IsEnabled)
2521
- throw new Exception("The named target is disabled");
2522
- object pattern = null;
2523
- if (action == "invoke" && !target.TryGetCurrentPattern(InvokePattern.Pattern, out pattern)) return result;
2524
- if (action == "focus" && !target.Current.IsKeyboardFocusable) return result;
2525
- if (action != "invoke" && action != "focus") return result;
2526
- if (!IsActionWindow(hwnd, pid, point))
2527
- throw new Exception("The named target window changed");
2528
-
2529
- // A provider error after dispatch is indeterminate. Let it surface
2530
- // rather than claiming the host can safely click again.
2531
- if (action == "invoke") ((InvokePattern)pattern).Invoke();
2532
- else
2533
- {
2534
- target.SetFocus();
2535
- for (int i = 0; i < 10 && !target.Current.HasKeyboardFocus; i++) Thread.Sleep(25);
2536
- if (!target.Current.HasKeyboardFocus) throw new Exception("Could not verify focus on the named control");
2537
- }
2538
- result["performed"] = true;
2539
- return result;
2540
- }
2541
-
2542
- static bool BrowserChrome(AutomationElement element)
2543
- {
2544
- // Page content can supply arbitrary UIA names and IDs.
2545
- for (var parent = TreeWalker.ControlViewWalker.GetParent(element); parent != null; parent = TreeWalker.ControlViewWalker.GetParent(parent))
2546
- {
2547
- if (parent.Current.ControlType == ControlType.Document) return false;
2548
- if (parent.Current.ControlType == ControlType.Window) return true;
2549
- }
2550
- return false;
2551
- }
2552
-
2553
- static bool BrowserContentFocused()
2554
- {
2555
- for (var el = AutomationElement.FocusedElement; el != null; el = TreeWalker.ControlViewWalker.GetParent(el))
2556
- {
2557
- if (el.Current.ControlType == ControlType.Document) return true;
2558
- if (el.Current.ControlType == ControlType.Window) return false;
2559
- }
2560
- return false;
2561
- }
2562
-
2563
- public static object OpenBrowserTab(Dictionary<string, object> r)
2564
- {
2565
- var hwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
2566
- uint pid = Convert.ToUInt32(r["pid"]);
2567
- string expected = Args.Str(r, "tab", "");
2568
- Uri url;
2569
- if (!Uri.TryCreate(Args.Str(r, "url", ""), UriKind.Absolute, out url) || (url.Scheme != "http" && url.Scheme != "https"))
2570
- throw new Exception("Expected an HTTP(S) URL");
2571
- Func<bool> current = delegate { return SameWindow(hwnd, pid) && Native.GetForegroundWindow() == hwnd; };
2572
- Func<Dictionary<string, object>> read = delegate { return BrowserTab(r) as Dictionary<string, object>; };
2573
- var initial = new Dictionary<string, object>(r) { { "listTabs", true } };
2574
- var before = current() ? BrowserTab(initial) as Dictionary<string, object> : null;
2575
- object tabIds;
2576
- if (expected.Length == 0 || before == null || Args.Str(before, "tab", "") != expected || !current())
2577
- throw new Exception("The browser window or active tab changed before opening a new tab");
2578
- if (!before.TryGetValue("tabs", out tabIds) || !(tabIds is List<string>))
2579
- throw new Exception("Could not verify the browser's existing tabs");
2580
- var existing = new HashSet<string>((List<string>)tabIds);
2581
- if (!existing.Contains(expected)) throw new Exception("The active browser tab could not be verified");
2582
-
2583
- Input.Keys(new Dictionary<string, object> { { "combos", new[] { new[] { 0x11, 0x54 } } } });
2584
- var clock = Stopwatch.StartNew();
2585
- string created = "";
2586
- while (clock.ElapsedMilliseconds < 2400 && current())
2587
- {
2588
- var fresh = read();
2589
- if (fresh != null && !existing.Contains(Args.Str(fresh, "tab", ""))
2590
- && Args.Str(fresh, "url", "unavailable") == "")
2591
- {
2592
- created = Args.Str(fresh, "tab", "");
2593
- if (created.Length > 0) break;
2594
- }
2595
- Thread.Sleep(65);
2596
- }
2597
- if (created.Length == 0 || !current())
2598
- throw new Exception("Could not confirm a new blank tab in the original browser window");
2599
- Input.Keys(new Dictionary<string, object> { { "combos", new[] { new[] { 0x11, 0x4C } } } });
2600
- clock.Restart();
2601
- bool addressReady = false;
2602
- while (clock.ElapsedMilliseconds < 1200 && current())
2603
- {
2604
- var blank = read();
2605
- if (blank != null)
2606
- {
2607
- if (Args.Str(blank, "tab", "") != created || Args.Str(blank, "url", "unavailable") != "") break;
2608
- if (Args.Bool(blank, "addressFocused", false)) { addressReady = true; break; }
2609
- }
2610
- Thread.Sleep(65);
2611
- }
2612
- if (!addressReady || !current()) throw new Exception("Could not verify focus in the new tab's address bar");
2613
- Input.Paste(url.AbsoluteUri, true, 120);
2614
- clock.Restart();
2615
- while (clock.ElapsedMilliseconds < 1200 && current())
2616
- {
2617
- var address = read();
2618
- if (address != null)
2619
- {
2620
- if (Args.Str(address, "tab", "") != created || !Args.Bool(address, "addressFocused", false)) break;
2621
- if (Args.Str(address, "url", "") == url.AbsoluteUri && current())
2622
- {
2623
- Input.Keys(new Dictionary<string, object> { { "combos", new[] { new[] { 0x0D } } } });
2624
- return new Dictionary<string, object> { { "tab", created } };
2625
- }
2626
- }
2627
- Thread.Sleep(65);
2628
- }
2629
- throw new Exception("Could not verify the new tab's address before navigation");
2630
- }
2631
-
2632
- public static object BrowserTab(Dictionary<string, object> r)
2633
- {
2634
- IntPtr hwnd = new IntPtr(Convert.ToInt64(r["hwnd"]));
2635
- uint pid = Convert.ToUInt32(r["pid"]);
2636
- string select = Args.Str(r, "select", "");
2637
- if (!SameWindow(hwnd, pid) || !WindowCollectors.Wait(0)) return null;
2638
- var clock = Stopwatch.StartNew();
2639
- Dictionary<string, object> result = null;
2640
- var worker = new Thread(delegate ()
2641
- {
2642
- try
2643
- {
2644
- var root = AutomationElement.FromHandle(hwnd);
2645
- var controls = root.FindAll(TreeScope.Descendants, new OrCondition(
2646
- new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
2647
- new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem)));
2648
- var state = new Dictionary<string, object>();
2649
- var tabs = Args.Bool(r, "listTabs", false) ? new List<string>() : null;
2650
- foreach (AutomationElement el in controls)
2651
- {
2652
- if (el.Current.IsOffscreen && (tabs == null || el.Current.ControlType != ControlType.TabItem)) continue;
2653
- object pattern;
2654
- if (el.Current.ControlType == ControlType.Edit)
2655
- {
2656
- string id = el.Current.AutomationId;
2657
- string name = el.Current.Name;
2658
- if (id != "view_1012" && id != "urlbar-input" && name != "Address and search bar" && name != "地址和搜索栏") continue;
2659
- if (BrowserChrome(el) && el.TryGetCurrentPattern(ValuePattern.Pattern, out pattern))
2660
- {
2661
- state["url"] = ((ValuePattern)pattern).Current.Value;
2662
- state["addressFocused"] = el.Current.HasKeyboardFocus;
2663
- }
2664
- }
2665
- else if (el.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern) && BrowserChrome(el))
2666
- {
2667
- var tab = (SelectionItemPattern)pattern;
2668
- string id = String.Join(",", el.GetRuntimeId());
2669
- if (tabs != null) tabs.Add(id);
2670
- if (select.Length > 0 && id == select)
2671
- {
2672
- if (clock.ElapsedMilliseconds < 1200 && SameWindow(hwnd, pid) && Native.GetForegroundWindow() == hwnd)
2673
- {
2674
- if (!tab.Current.IsSelected) tab.Select();
2675
- state["selected"] = true;
2676
- }
2677
- break;
2678
- }
2679
- if (tab.Current.IsSelected) state["tab"] = id;
2680
- }
2681
- }
2682
- if (tabs != null) state["tabs"] = tabs;
2683
- if (Args.Bool(r, "details", false) && Native.GetForegroundWindow() == hwnd)
2684
- {
2685
- var render = ChromiumRoot(hwnd);
2686
- Native.RECT rect;
2687
- if (render != hwnd && Native.GetWindowRect(render, out rect) && rect.Right > rect.Left && rect.Bottom > rect.Top)
2688
- state["content"] = new Dictionary<string, object> {
2689
- { "x", rect.Left }, { "y", rect.Top }, { "width", rect.Right - rect.Left }, { "height", rect.Bottom - rect.Top },
2690
- };
2691
- state["contentFocused"] = BrowserContentFocused();
2692
- }
2693
- result = state;
2694
- }
2695
- catch (Exception) { }
2696
- finally { WindowCollectors.Release(); }
2697
- });
2698
- worker.IsBackground = true;
2699
- worker.SetApartmentState(ApartmentState.MTA);
2700
- worker.Start();
2701
- return worker.Join(1250) ? result : null;
2702
- }
2703
-
2704
- static List<object> CollectWindow(IntPtr hwnd, int max, bool includeText)
2705
- {
2706
- IntPtr render = ChromiumRoot(hwnd);
2707
- if (render == hwnd) return Collect(hwnd, max, includeText);
2708
- WakeAccessibility(render);
2709
- List<object> window = null;
2710
- Exception windowError = null;
2711
- Thread windowWorker = null;
2712
- if (WindowCollectors.Wait(0))
2713
- {
2714
- windowWorker = new Thread(delegate ()
2715
- {
2716
- try { window = Collect(hwnd, max, includeText); }
2717
- catch (Exception ex) { windowError = ex; }
2718
- finally { WindowCollectors.Release(); }
2719
- });
2720
- windowWorker.IsBackground = true;
2721
- windowWorker.SetApartmentState(ApartmentState.MTA);
2722
- windowWorker.Start();
2723
- }
2724
- // Electron can take >16s at the top level while its renderer takes
2725
- // <1s. Read independently; a slow/failed window must not lose DOM controls.
2726
- List<object> content = null;
2727
- Exception contentError = null;
2728
- try { content = Collect(render, max, includeText); }
2729
- catch (Exception ex) { contentError = ex; }
2730
- bool windowReady = windowWorker != null && windowWorker.Join(1000);
2731
- var result = windowReady && window != null ? window : new List<object>();
2732
- if (content == null && result.Count == 0 && contentError != null)
2733
- throw windowReady && windowError != null ? windowError : contentError;
2734
- if (content != null && result.Count < max)
2735
- {
2736
- foreach (Dictionary<string, object> extra in content)
2737
- {
2738
- bool duplicate = false;
2739
- foreach (Dictionary<string, object> item in result)
2740
- if (Equals(item["role"], extra["role"]) && Equals(item["name"], extra["name"])
2741
- && Equals(item["x"], extra["x"]) && Equals(item["y"], extra["y"])
2742
- && Equals(item["width"], extra["width"]) && Equals(item["height"], extra["height"]))
2743
- { duplicate = true; break; }
2744
- if (!duplicate) result.Add(extra);
2745
- if (result.Count >= max) break;
2746
- }
2747
- }
2748
- return result;
2749
- }
2750
-
2751
- public static object Elements(Dictionary<string, object> r)
2752
- {
2753
- IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
2754
- int max = Args.Int(r, "maxNodes", 150);
2755
- bool all = Args.Bool(r, "includeText", false);
2756
- bool popups = Args.Bool(r, "popups", false);
2757
- bool popupsOnly = Args.Bool(r, "popupsOnly", false);
2758
- List<object> result = null; Exception error = null;
2759
- var worker = new Thread(delegate ()
2760
- {
2761
- try
2762
- {
2763
- if (popupsOnly) result = new List<object>();
2764
- else
2765
- {
2766
- result = CollectWindow(hwnd, max, all);
2767
- if (result.Count < 4) { Thread.Sleep(400); result = CollectWindow(hwnd, max, all); } // Chromium builds its tree lazily
2768
- foreach (Dictionary<string, object> item in result) item["windowHwnd"] = hwnd.ToInt64();
2769
- }
2770
- // An open menu or flyout is a window of its own, not a descendant of the one it belongs to.
2771
- if (popups || popupsOnly) foreach (var extra in Popups(hwnd))
2772
- {
2773
- if (result.Count >= max) break;
2774
- try
2775
- {
2776
- var popup = CollectWindow(extra, max - result.Count, all);
2777
- foreach (Dictionary<string, object> item in popup) item["windowHwnd"] = extra.ToInt64();
2778
- result.AddRange(popup);
2779
- }
2780
- catch (Exception) { }
2781
- }
2782
- }
2783
- catch (Exception ex) { error = ex; }
2784
- });
2785
- worker.IsBackground = true;
2786
- worker.SetApartmentState(ApartmentState.MTA);
2787
- worker.Start();
2788
- if (!worker.Join(Args.Int(r, "timeoutMs", 8000))) throw new Exception("UI Automation timed out on this window");
2789
- if (error != null) throw error;
2790
- var d = Windows.Describe(hwnd);
2791
- d["elements"] = result;
2792
- return d;
2793
- }
2794
-
2795
- /// <summary>Other visible top-level windows of the same process: menus, flyouts, dropdown lists.</summary>
2796
- static List<IntPtr> Popups(IntPtr hwnd)
2797
- {
2798
- var list = new List<IntPtr>();
2799
- uint owner; Native.GetWindowThreadProcessId(hwnd, out owner);
2800
- Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
2801
- {
2802
- if (h == hwnd || !Native.IsWindowVisible(h) || Native.IsIconic(h)) return true;
2803
- uint pid; Native.GetWindowThreadProcessId(h, out pid);
2804
- if (pid == owner && list.Count < 6) list.Add(h);
2805
- return true;
2806
- };
2807
- Native.EnumWindows(cb, IntPtr.Zero);
2808
- GC.KeepAlive(cb);
2809
- return list;
2810
- }
2811
-
2812
- /// <summary>
2813
- /// What a window says, as text: the document or edit control's own text
2814
- /// when it offers one, else its value, else the visible labels in order.
2815
- /// </summary>
2816
- public static object Text(Dictionary<string, object> r)
2817
- {
2818
- IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
2819
- int tail = Math.Max(200, Math.Min(20000, Args.Int(r, "tail", 4000)));
2820
- string text = ""; string source = "none"; Exception error = null;
2821
- var worker = new Thread(delegate ()
2822
- {
2823
- try { text = Read(hwnd, out source); }
2824
- catch (Exception ex) { error = ex; }
2825
- });
2826
- worker.IsBackground = true;
2827
- worker.SetApartmentState(ApartmentState.MTA);
2828
- worker.Start();
2829
- if (!worker.Join(Args.Int(r, "timeoutMs", 8000))) throw new Exception("UI Automation timed out on this window");
2830
- if (error != null) throw error;
2831
- var d = Windows.Describe(hwnd);
2832
- d["length"] = text.Length;
2833
- d["truncated"] = text.Length > tail;
2834
- d["text"] = text.Length > tail ? text.Substring(text.Length - tail) : text;
2835
- d["source"] = source;
2836
- return d;
2837
- }
2838
-
2839
- const int ReadLimit = 200000;
2840
-
2841
- static string Read(IntPtr hwnd, out string source)
2842
- {
2843
- var root = AutomationElement.FromHandle(hwnd);
2844
- var visible = new PropertyCondition(AutomationElement.IsOffscreenProperty, false);
2845
-
2846
- // 1. The largest element with a text pattern: an editor's document, a browser's page.
2847
- var withText = root.FindAll(TreeScope.Subtree, new AndCondition(visible, new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true)));
2848
- string best = ""; double bestArea = -1;
2849
- int looked = 0;
2850
- foreach (AutomationElement el in withText)
2851
- {
2852
- if (++looked > 40) break;
2853
- try
2854
- {
2855
- var rect = el.Current.BoundingRectangle;
2856
- double area = rect.IsEmpty ? 0 : rect.Width * rect.Height;
2857
- if (area <= bestArea) continue;
2858
- object pattern;
2859
- if (!el.TryGetCurrentPattern(TextPattern.Pattern, out pattern)) continue;
2860
- string got = ((TextPattern)pattern).DocumentRange.GetText(ReadLimit);
2861
- if (got == null || got.Trim().Length == 0) continue;
2862
- best = got; bestArea = area;
2863
- }
2864
- catch (Exception) { }
2865
- }
2866
- if (best.Length > 0) { source = "text"; return best; }
2867
-
2868
- // 2. The longest value of an edit or document control.
2869
- var withValue = root.FindAll(TreeScope.Subtree, new AndCondition(visible, new PropertyCondition(AutomationElement.IsValuePatternAvailableProperty, true)));
2870
- looked = 0;
2871
- foreach (AutomationElement el in withValue)
2872
- {
2873
- if (++looked > 200) break;
2874
- try
2875
- {
2876
- if (IsPasswordElement(el)) continue;
2877
- object pattern;
2878
- if (!el.TryGetCurrentPattern(ValuePattern.Pattern, out pattern)) continue;
2879
- string got = ((ValuePattern)pattern).Current.Value;
2880
- if (got != null && got.Length > best.Length) best = got;
2881
- }
2882
- catch (Exception) { }
2883
- }
2884
- if (best.Trim().Length > 0) { source = "value"; return best.Length > ReadLimit ? best.Substring(best.Length - ReadLimit) : best; }
2885
-
2886
- // 3. Whatever labels are showing, in tree (reading) order.
2887
- var cache = new CacheRequest();
2888
- cache.Add(AutomationElement.NameProperty);
2889
- cache.AutomationElementMode = AutomationElementMode.None;
2890
- cache.TreeScope = TreeScope.Element;
2891
- AutomationElementCollection labels;
2892
- using (cache.Activate()) { labels = root.FindAll(TreeScope.Descendants, visible); }
2893
- var sb = new StringBuilder();
2894
- string last = null;
2895
- foreach (AutomationElement el in labels)
2896
- {
2897
- string name = el.GetCachedPropertyValue(AutomationElement.NameProperty) as string;
2898
- if (string.IsNullOrEmpty(name) || name == last) continue;
2899
- last = name;
2900
- sb.Append(name).Append('\n');
2901
- if (sb.Length > ReadLimit) break;
2902
- }
2903
- source = sb.Length > 0 ? "labels" : "none";
2904
- return sb.ToString();
2905
- }
2906
-
2907
- static bool IsWin32PasswordHwnd(IntPtr h)
2908
- {
2909
- if (h == IntPtr.Zero || !Native.IsWindow(h)) return false;
2910
- var cls = new StringBuilder(64);
2911
- Native.GetClassName(h, cls, cls.Capacity);
2912
- string c = cls.ToString();
2913
- if (c.IndexOf("Edit", StringComparison.OrdinalIgnoreCase) < 0 && c.IndexOf("RichEdit", StringComparison.OrdinalIgnoreCase) < 0)
2914
- return false;
2915
- int style = Native.GetWindowLong(h, -16); // GWL_STYLE
2916
- return (style & 0x0020) != 0; // ES_PASSWORD
2917
- }
2918
-
2919
- static bool IsPasswordElement(AutomationElement el)
2920
- {
2921
- if (el == null) return false;
2922
- try
2923
- {
2924
- if (el.Current.IsPassword) return true;
2925
- int nh = el.Current.NativeWindowHandle;
2926
- if (nh != 0 && IsWin32PasswordHwnd(new IntPtr(nh))) return true;
2927
- }
2928
- catch (Exception) { }
2929
- return false;
2930
- }
2931
-
2932
- /** Check whether keyboard focus is currently inside a password input (UIA IsPassword or Win32 ES_PASSWORD). */
2933
- public static object PasswordFocus()
2934
- {
2935
- bool isPwd = false;
2936
- string reason = "";
2937
- string name = "";
2938
- try
2939
- {
2940
- IntPtr fg = Native.GetForegroundWindow();
2941
- if (fg != IntPtr.Zero)
2942
- {
2943
- uint pid;
2944
- uint tid = Native.GetWindowThreadProcessId(fg, out pid);
2945
- var gti = new Native.GUITHREADINFO();
2946
- gti.cbSize = Marshal.SizeOf(typeof(Native.GUITHREADINFO));
2947
- if (Native.GetGUIThreadInfo(tid, ref gti) && gti.hwndFocus != IntPtr.Zero && IsWin32PasswordHwnd(gti.hwndFocus))
2948
- {
2949
- isPwd = true;
2950
- reason = "win32_es_password";
2951
- }
2952
- }
2953
- }
2954
- catch (Exception) { }
2955
- if (!isPwd)
2956
- {
2957
- var worker = new Thread(delegate ()
2958
- {
2959
- try
2960
- {
2961
- var focused = AutomationElement.FocusedElement;
2962
- if (focused != null && IsPasswordElement(focused))
2963
- {
2964
- isPwd = true;
2965
- reason = "uia_is_password";
2966
- name = focused.Current.Name ?? "";
2967
- }
2968
- }
2969
- catch (Exception) { }
2970
- });
2971
- worker.IsBackground = true;
2972
- worker.SetApartmentState(ApartmentState.MTA);
2973
- worker.Start();
2974
- worker.Join(500);
2975
- }
2976
- var d = new Dictionary<string, object>();
2977
- d["password"] = isPwd;
2978
- d["reason"] = reason;
2979
- d["name"] = name;
2980
- return d;
2981
- }
2982
-
2983
- /** Lightweight bounded lookup of the UIA control at physical point (x, y) for user-takeover feedback. */
2984
- public static void DescribeAtPoint(int x, int y, out string role, out string name, out bool isPassword)
2985
- {
2986
- string r = "", n = "";
2987
- bool pwd = false;
2988
- var worker = new Thread(delegate ()
2989
- {
2990
- try
2991
- {
2992
- var el = AutomationElement.FromPoint(new System.Windows.Point(x, y));
2993
- if (el == null) return;
2994
- pwd = IsPasswordElement(el);
2995
- var ct = el.Current.ControlType;
2996
- r = pwd ? "PasswordField" : (ct != null ? ct.ProgrammaticName.Replace("ControlType.", "") : "");
2997
- string raw = pwd ? "" : (el.Current.Name ?? "").Trim();
2998
- n = raw.Length > 60 ? raw.Substring(0, 60) + "…" : raw;
2999
- }
3000
- catch (Exception) { }
3001
- });
3002
- worker.IsBackground = true;
3003
- worker.SetApartmentState(ApartmentState.MTA);
3004
- worker.Start();
3005
- worker.Join(260);
3006
- role = r; name = n; isPassword = pwd;
3007
- }
3008
-
3009
- /** Lightweight bounded lookup of the focused UIA control for privacy-safe typing feedback. */
3010
- public static void DescribeFocused(out string role, out string name, out bool isPassword)
3011
- {
3012
- string r = "", n = "";
3013
- bool pwd = false;
3014
- var worker = new Thread(delegate ()
3015
- {
3016
- try
3017
- {
3018
- var el = AutomationElement.FocusedElement;
3019
- if (el == null) return;
3020
- pwd = IsPasswordElement(el);
3021
- var ct = el.Current.ControlType;
3022
- r = pwd ? "PasswordField" : (ct != null ? ct.ProgrammaticName.Replace("ControlType.", "") : "");
3023
- string raw = pwd ? "" : (el.Current.Name ?? "").Trim();
3024
- n = raw.Length > 60 ? raw.Substring(0, 60) + "…" : raw;
3025
- }
3026
- catch (Exception) { }
3027
- });
3028
- worker.IsBackground = true;
3029
- worker.SetApartmentState(ApartmentState.MTA);
3030
- worker.Start();
3031
- worker.Join(240);
3032
- role = r; name = n; isPassword = pwd;
3033
- }
3034
-
3035
- /**
3036
- * Try to invoke/toggle/select an enabled native UIA control directly under
3037
- * physical point (x, y) without moving the physical cursor or stealing focus.
3038
- */
3039
- public static object ClickAtPoint(Dictionary<string, object> r)
3040
- {
3041
- int x = Args.Int(r, "x", 0);
3042
- int y = Args.Int(r, "y", 0);
3043
- long expectedHwnd = Args.Has(r, "hwnd") ? Convert.ToInt64(r["hwnd"]) : 0;
3044
- bool ok = false;
3045
- string mechanism = "";
3046
- string role = "";
3047
- string name = "";
3048
- var worker = new Thread(delegate ()
3049
- {
3050
- try
3051
- {
3052
- var el = AutomationElement.FromPoint(new System.Windows.Point(x, y));
3053
- if (el == null) return;
3054
- if (!el.Current.IsEnabled || IsPasswordElement(el)) return;
3055
- var ct = el.Current.ControlType;
3056
- // Only intercept clearly semantic, single-click invocable controls;
3057
- // never intercept Edit/Document/Pane/Custom/Group where cursor placement matters.
3058
- bool allowed = ct == ControlType.Button || ct == ControlType.CheckBox || ct == ControlType.RadioButton
3059
- || ct == ControlType.MenuItem || ct == ControlType.TabItem || ct == ControlType.Hyperlink;
3060
- if (!allowed) return;
3061
- if (expectedHwnd != 0)
3062
- {
3063
- int nh = el.Current.NativeWindowHandle;
3064
- IntPtr root = nh != 0 ? Native.GetAncestor(new IntPtr(nh), 2) : IntPtr.Zero;
3065
- if (root != IntPtr.Zero && root.ToInt64() != expectedHwnd) return;
3066
- }
3067
- role = ct.ProgrammaticName.Replace("ControlType.", "");
3068
- name = el.Current.Name ?? "";
3069
- object pat;
3070
- if (el.TryGetCurrentPattern(InvokePattern.Pattern, out pat))
3071
- {
3072
- ((InvokePattern)pat).Invoke();
3073
- ok = true;
3074
- mechanism = "invoke";
3075
- return;
3076
- }
3077
- if (el.TryGetCurrentPattern(TogglePattern.Pattern, out pat))
3078
- {
3079
- ((TogglePattern)pat).Toggle();
3080
- ok = true;
3081
- mechanism = "toggle";
3082
- return;
3083
- }
3084
- if (el.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pat))
3085
- {
3086
- ((SelectionItemPattern)pat).Select();
3087
- ok = true;
3088
- mechanism = "select";
3089
- return;
3090
- }
3091
- }
3092
- catch (Exception) { }
3093
- });
3094
- worker.IsBackground = true;
3095
- worker.SetApartmentState(ApartmentState.MTA);
3096
- worker.Start();
3097
- worker.Join(900);
3098
- var d = new Dictionary<string, object>();
3099
- d["ok"] = ok;
3100
- d["mechanism"] = mechanism;
3101
- d["role"] = role;
3102
- d["name"] = name;
3103
- return d;
3104
- }
3105
-
3106
- /**
3107
- * Set-of-Marks annotated screenshot: capture the display, draw crisp numbered
3108
- * badges [1..N] over interactive UIA controls of the target window, and return
3109
- * both the JPEG image and the indexed element list.
3110
- */
3111
- public static object Marks(Dictionary<string, object> r)
3112
- {
3113
- int sx = Args.Int(r, "x", 0), sy = Args.Int(r, "y", 0);
3114
- int sw = Args.Int(r, "width", 0), sh = Args.Int(r, "height", 0);
3115
- int outW = Args.Int(r, "outWidth", sw), outH = Args.Int(r, "outHeight", sh);
3116
- int quality = Math.Max(30, Math.Min(100, Args.Int(r, "quality", 75)));
3117
- if (sw <= 0 || sh <= 0) throw new Exception("marks needs display width and height");
3118
- var ui = Elements(r) as Dictionary<string, object>;
3119
- var rawElements = ui != null && ui.ContainsKey("elements") ? ui["elements"] as List<object> : new List<object>();
3120
- if (rawElements == null) rawElements = new List<object>();
3121
-
3122
- string via;
3123
- using (var rawBmp = Screen2.Grab(sx, sy, sw, sh, out via))
3124
- using (var canvas = new Bitmap(outW, outH, PixelFormat.Format24bppRgb))
3125
- using (var g = Graphics.FromImage(canvas))
3126
- {
3127
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
3128
- g.SmoothingMode = SmoothingMode.AntiAlias;
3129
- g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
3130
- g.DrawImage(rawBmp, 0, 0, outW, outH);
3131
-
3132
- double scaleX = (double)outW / sw;
3133
- double scaleY = (double)outH / sh;
3134
- var placed = new List<RectangleF>();
3135
- using (var font = new Font("Microsoft YaHei UI", 10.5f, FontStyle.Bold, GraphicsUnit.Pixel))
3136
- using (var fmt = new StringFormat(StringFormat.GenericTypographic))
3137
- using (var bgBrush = new SolidBrush(Color.FromArgb(228, 217, 119, 87)))
3138
- using (var borderPen = new Pen(Color.FromArgb(245, 255, 255, 255), 1.3f))
3139
- using (var boxPen = new Pen(Color.FromArgb(140, 217, 119, 87), 1.1f))
3140
- {
3141
- fmt.FormatFlags |= StringFormatFlags.NoWrap;
3142
- int drawn = 0;
3143
- for (int i = 0; i < rawElements.Count && drawn < 120; i++)
3144
- {
3145
- var el = rawElements[i] as Dictionary<string, object>;
3146
- if (el == null) continue;
3147
- int ex = Convert.ToInt32(el["x"]), ey = Convert.ToInt32(el["y"]);
3148
- int ew = Convert.ToInt32(el["width"]), eh = Convert.ToInt32(el["height"]);
3149
- float rx = (float)((ex - sx) * scaleX);
3150
- float ry = (float)((ey - sy) * scaleY);
3151
- float rw = (float)(ew * scaleX);
3152
- float rh = (float)(eh * scaleY);
3153
- if (rx + rw < 0 || ry + rh < 0 || rx >= outW || ry >= outH) continue;
3154
- if (rw < 4 || rh < 4) continue;
3155
- el["mark"] = i + 1;
3156
- drawn++;
3157
- if (rw <= outW * 0.85f && rh <= outH * 0.85f)
3158
- g.DrawRectangle(boxPen, rx, ry, rw, rh);
3159
- string tag = (i + 1).ToString();
3160
- SizeF ts = g.MeasureString(tag, font, 1000, fmt);
3161
- float bw = Math.Max(16f, ts.Width + 6f);
3162
- float bh = Math.Max(15f, ts.Height + 2f);
3163
- float bx = Math.Max(1f, Math.Min(outW - bw - 1f, rx));
3164
- float by = Math.Max(1f, Math.Min(outH - bh - 1f, ry - bh * 0.35f));
3165
- var badge = new RectangleF(bx, by, bw, bh);
3166
- for (int attempt = 0; attempt < 3; attempt++)
3167
- {
3168
- bool overlap = false;
3169
- for (int j = 0; j < placed.Count; j++)
3170
- if (placed[j].IntersectsWith(badge)) { overlap = true; break; }
3171
- if (!overlap) break;
3172
- badge.X = Math.Min(outW - bw - 1f, badge.X + bw + 2f);
3173
- }
3174
- placed.Add(badge);
3175
- g.FillRectangle(bgBrush, badge);
3176
- g.DrawRectangle(borderPen, badge.X, badge.Y, badge.Width, badge.Height);
3177
- g.DrawString(tag, font, Brushes.White, badge.X + (badge.Width - ts.Width) / 2f, badge.Y + (badge.Height - ts.Height) / 2f - 0.5f, fmt);
3178
- }
3179
- }
3180
-
3181
- using (var ms = new MemoryStream())
3182
- {
3183
- ImageCodecInfo jpeg = null;
3184
- foreach (var c in ImageCodecInfo.GetImageEncoders()) if (c.MimeType == "image/jpeg") { jpeg = c; break; }
3185
- if (jpeg != null)
3186
- {
3187
- using (var ep = new EncoderParameters(1))
3188
- {
3189
- ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
3190
- canvas.Save(ms, jpeg, ep);
3191
- }
3192
- }
3193
- else canvas.Save(ms, ImageFormat.Jpeg);
3194
-
3195
- var outDict = new Dictionary<string, object>();
3196
- if (ui != null) foreach (var kv in ui) outDict[kv.Key] = kv.Value;
3197
- outDict["data"] = Convert.ToBase64String(ms.ToArray());
3198
- outDict["width"] = outW;
3199
- outDict["height"] = outH;
3200
- outDict["via"] = via;
3201
- return outDict;
3202
- }
3203
- }
3204
- }
3205
-
3206
- static List<object> Collect(IntPtr hwnd, int max, bool includeText)
3207
- {
3208
- var root = AutomationElement.FromHandle(hwnd);
3209
- var types = new List<Condition>();
3210
- foreach (var t in Interactive) types.Add(new PropertyCondition(AutomationElement.ControlTypeProperty, t));
3211
- if (includeText) types.Add(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text));
3212
- var cond = new AndCondition(new PropertyCondition(AutomationElement.IsOffscreenProperty, false), new OrCondition(types.ToArray()));
3213
- var cache = new CacheRequest();
3214
- cache.Add(AutomationElement.NameProperty);
3215
- cache.Add(AutomationElement.ControlTypeProperty);
3216
- cache.Add(AutomationElement.BoundingRectangleProperty);
3217
- cache.Add(AutomationElement.IsEnabledProperty);
3218
- cache.Add(AutomationElement.AutomationIdProperty);
3219
- cache.Add(AutomationElement.RuntimeIdProperty);
3220
- cache.Add(AutomationElement.ClassNameProperty);
3221
- cache.Add(AutomationElement.IsKeyboardFocusableProperty);
3222
- cache.Add(AutomationElement.IsPasswordProperty);
3223
- cache.Add(AutomationElement.NativeWindowHandleProperty);
3224
- cache.Add(ValuePattern.ValueProperty);
3225
- cache.Add(TogglePattern.ToggleStateProperty);
3226
- cache.AutomationElementMode = AutomationElementMode.None;
3227
- cache.TreeScope = TreeScope.Element;
3228
- AutomationElementCollection found;
3229
- using (cache.Activate()) { found = root.FindAll(TreeScope.Descendants, cond); }
3230
- var list = new List<object>();
3231
- foreach (AutomationElement el in found)
3232
- {
3233
- if (list.Count >= max) break;
3234
- var rect = (System.Windows.Rect)el.GetCachedPropertyValue(AutomationElement.BoundingRectangleProperty);
3235
- if (rect.IsEmpty || rect.Width < 2 || rect.Height < 2) continue;
3236
- var type = (ControlType)el.GetCachedPropertyValue(AutomationElement.ControlTypeProperty);
3237
- string name = (el.GetCachedPropertyValue(AutomationElement.NameProperty) as string) ?? "";
3238
- string cls = (el.GetCachedPropertyValue(AutomationElement.ClassNameProperty) as string) ?? "";
3239
- // Web 编辑器的 contenteditable 常是 Group(ProseMirror/tiptap 等),
3240
- // 不是 Edit;保留这类 Group,其余 Group 跳过,避免淹没按钮。
3241
- if (type == ControlType.Group && !IsEditorClass(cls)) continue;
3242
- bool isPwd = false;
3243
- try
3244
- {
3245
- object pwdProp = el.GetCachedPropertyValue(AutomationElement.IsPasswordProperty, true);
3246
- if (pwdProp is bool && (bool)pwdProp) isPwd = true;
3247
- if (!isPwd)
3248
- {
3249
- object nhProp = el.GetCachedPropertyValue(AutomationElement.NativeWindowHandleProperty, true);
3250
- if (nhProp is int && (int)nhProp != 0 && IsWin32PasswordHwnd(new IntPtr((int)nhProp))) isPwd = true;
3251
- }
3252
- }
3253
- catch (Exception) { }
3254
- var d = new Dictionary<string, object>();
3255
- d["role"] = type == ControlType.Group ? "Edit" : type.ProgrammaticName.Replace("ControlType.", "");
3256
- if (type == ControlType.Group) d["editable"] = true;
3257
- if (isPwd) d["password"] = true;
3258
- d["name"] = name.Length > 120 ? name.Substring(0, 120) + "…" : name;
3259
- string aid = (el.GetCachedPropertyValue(AutomationElement.AutomationIdProperty) as string) ?? "";
3260
- if (aid.Length > 0) d["automationId"] = aid;
3261
- var runtimeId = el.GetCachedPropertyValue(AutomationElement.RuntimeIdProperty, true) as int[];
3262
- if (runtimeId != null && runtimeId.Length > 0) d["runtimeId"] = String.Join(",", runtimeId);
3263
- d["focusable"] = (bool)el.GetCachedPropertyValue(AutomationElement.IsKeyboardFocusableProperty);
3264
- object value = el.GetCachedPropertyValue(ValuePattern.ValueProperty, true);
3265
- if (isPwd) { d["value"] = "[password]"; }
3266
- else if (value is string && ((string)value).Length > 0) { var v = (string)value; d["value"] = v.Length > 120 ? v.Substring(0, 120) + "…" : v; }
3267
- object toggle = el.GetCachedPropertyValue(TogglePattern.ToggleStateProperty, true);
3268
- if (toggle is ToggleState) d["checked"] = (ToggleState)toggle == ToggleState.On;
3269
- if (!(bool)el.GetCachedPropertyValue(AutomationElement.IsEnabledProperty)) d["disabled"] = true;
3270
- if (type == ControlType.Document && name.Length == 0 && !d.ContainsKey("value")) continue;
3271
- d["x"] = (int)rect.X; d["y"] = (int)rect.Y; d["width"] = (int)rect.Width; d["height"] = (int)rect.Height;
3272
- list.Add(d);
3273
- }
3274
- return list;
3275
- }
3276
- }
3277
-
3278
- // ---------------------------------------------------------------- overlay
3279
-
3280
- internal class LayeredForm : Form
3281
- {
3282
- readonly bool clickThrough;
3283
- public Rectangle Physical;
3284
-
3285
- public LayeredForm(bool clickThrough)
3286
- {
3287
- this.clickThrough = clickThrough;
3288
- FormBorderStyle = FormBorderStyle.None;
3289
- ShowInTaskbar = false;
3290
- StartPosition = FormStartPosition.Manual;
3291
- AutoScaleMode = AutoScaleMode.None;
3292
- TopMost = true;
3293
- }
3294
-
3295
- protected override bool ShowWithoutActivation { get { return true; } }
3296
-
3297
- protected override CreateParams CreateParams
3298
- {
3299
- get
3300
- {
3301
- var cp = base.CreateParams;
3302
- cp.ExStyle |= 0x80000 | 0x80 | 0x8000000 | 0x8; // LAYERED | TOOLWINDOW | NOACTIVATE | TOPMOST
3303
- if (clickThrough) cp.ExStyle |= 0x20; // TRANSPARENT
3304
- return cp;
3305
- }
3306
- }
3307
-
3308
- protected override void OnHandleCreated(EventArgs e)
3309
- {
3310
- base.OnHandleCreated(e);
3311
- // Keep the overlay out of every screenshot, including our own.
3312
- if (Overlay.ExcludeFromCapture) { try { Native.SetWindowDisplayAffinity(Handle, 0x11); } catch (Exception) { } }
3313
- }
3314
-
3315
- protected override void WndProc(ref Message m)
3316
- {
3317
- if (m.Msg == 0x21) { m.Result = new IntPtr(3); return; } // WM_MOUSEACTIVATE -> MA_NOACTIVATE
3318
- base.WndProc(ref m);
3319
- }
3320
-
3321
- public void SetBitmap(Bitmap bmp, Rectangle bounds, byte alpha)
3322
- {
3323
- Physical = bounds;
3324
- IntPtr screenDc = Native.GetDC(IntPtr.Zero);
3325
- IntPtr memDc = Native.CreateCompatibleDC(screenDc);
3326
- IntPtr hBitmap = IntPtr.Zero, old = IntPtr.Zero;
3327
- try
3328
- {
3329
- hBitmap = bmp.GetHbitmap(Color.FromArgb(0));
3330
- old = Native.SelectObject(memDc, hBitmap);
3331
- var size = new Native.SIZE(bmp.Width, bmp.Height);
3332
- var src = new Native.POINT(0, 0);
3333
- var dst = new Native.POINT(bounds.X, bounds.Y);
3334
- var blend = new Native.BLENDFUNCTION(); blend.BlendOp = 0; blend.SourceConstantAlpha = alpha; blend.AlphaFormat = 1;
3335
- Native.UpdateLayeredWindow(Handle, screenDc, ref dst, ref size, memDc, ref src, 0, ref blend, 2);
3336
- }
3337
- finally
3338
- {
3339
- Native.ReleaseDC(IntPtr.Zero, screenDc);
3340
- if (hBitmap != IntPtr.Zero) { Native.SelectObject(memDc, old); Native.DeleteObject(hBitmap); }
3341
- Native.DeleteDC(memDc);
3342
- }
3343
- }
3344
-
3345
- public void SetAlpha(byte alpha)
3346
- {
3347
- var blend = new Native.BLENDFUNCTION(); blend.BlendOp = 0; blend.SourceConstantAlpha = alpha; blend.AlphaFormat = 1;
3348
- Native.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, ref blend, 2);
3349
- }
3350
-
3351
- public void KeepOnTop()
3352
- {
3353
- Native.SetWindowPos(Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010 | 0x0200); // NOSIZE|NOMOVE|NOACTIVATE|NOOWNERZORDER
3354
- }
3355
-
3356
- public void SetCapturable(bool capturable)
3357
- {
3358
- try { Native.SetWindowDisplayAffinity(Handle, capturable ? 0u : 0x11u); } catch (Exception) { }
3359
- }
3360
- }
3361
-
3362
- /** The progress card's instruction box: a small focusable window laid over the card's field. */
3363
- internal class InputBox : Form
3364
- {
3365
- public readonly TextBox Box;
3366
- public event Action<string> Submitted;
3367
- public event Action Cancelled;
3368
- [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr SendMessage(IntPtr hwnd, int msg, IntPtr w, string l);
3369
-
3370
- public InputBox(Font font, Color back, Color fore, string cue)
3371
- {
3372
- FormBorderStyle = FormBorderStyle.None;
3373
- ShowInTaskbar = false;
3374
- StartPosition = FormStartPosition.Manual;
3375
- AutoScaleMode = AutoScaleMode.None;
3376
- TopMost = true;
3377
- BackColor = back;
3378
- Box = new TextBox();
3379
- Box.BorderStyle = BorderStyle.None;
3380
- Box.Font = font;
3381
- Box.BackColor = back;
3382
- Box.ForeColor = fore;
3383
- Controls.Add(Box);
3384
- Box.HandleCreated += delegate { SendMessage(Box.Handle, 0x1501, new IntPtr(1), cue); }; // EM_SETCUEBANNER
3385
- Box.KeyDown += delegate (object s, KeyEventArgs e)
3386
- {
3387
- if (e.KeyCode == System.Windows.Forms.Keys.Enter && !e.Shift) { e.SuppressKeyPress = true; if (Submitted != null) Submitted(Box.Text); }
3388
- else if (e.KeyCode == System.Windows.Forms.Keys.Escape) { e.SuppressKeyPress = true; if (Cancelled != null) Cancelled(); }
3389
- };
3390
- }
3391
-
3392
- protected override CreateParams CreateParams
3393
- {
3394
- get { var cp = base.CreateParams; cp.ExStyle |= 0x80 | 0x8; return cp; } // TOOLWINDOW | TOPMOST
3395
- }
3396
-
3397
- protected override void OnHandleCreated(EventArgs e)
3398
- {
3399
- base.OnHandleCreated(e);
3400
- if (Overlay.ExcludeFromCapture) { try { Native.SetWindowDisplayAffinity(Handle, 0x11); } catch (Exception) { } }
3401
- }
3402
-
3403
- public void Place(Rectangle r)
3404
- {
3405
- Bounds = r;
3406
- Box.Width = r.Width;
3407
- Box.Location = new Point(0, Math.Max(0, (r.Height - Box.PreferredHeight) / 2));
3408
- }
3409
- }
3410
-
3411
- internal static class Overlay
3412
- {
3413
- static readonly Color Accent = Color.FromArgb(217, 119, 87); // #D97757
3414
- static readonly Color AccentHi = Color.FromArgb(240, 160, 106); // #F0A06A
3415
-
3416
- public static volatile bool ExcludeFromCapture = true;
3417
- static Thread thread;
3418
- static Control invoker;
3419
- static readonly List<LayeredForm> glows = new List<LayeredForm>();
3420
- static LayeredForm pill;
3421
- static Rectangle pillRect;
3422
- static readonly List<KeyValuePair<Rectangle, string>> buttons = new List<KeyValuePair<Rectangle, string>>();
3423
- static bool pillAtBottom;
3424
- static string label = "", status = "", rendered = "";
3425
- static Image icon, iconLight;
3426
- static string iconPath = "", iconLightPath = "";
3427
- static int idleMs = 1500;
3428
- static System.Windows.Forms.Timer timer;
3429
- static DateTime shownAt;
3430
- static IntPtr hook = IntPtr.Zero;
3431
- static Native.LowLevelKeyboardProc hookProc;
3432
- static IntPtr mouseHook = IntPtr.Zero;
3433
- static Native.LowLevelMouseProc mouseHookProc;
3434
- static readonly object UserActionLock = new object();
3435
- static int lastClickTick = int.MinValue / 2;
3436
- static int lastClickX, lastClickY;
3437
- static int lastScrollTick = int.MinValue / 2;
3438
- static int lastKeySummaryTick = int.MinValue / 2;
3439
- static int keyBurstCount;
3440
- static volatile bool visible;
3441
- static volatile bool paused;
3442
- static volatile bool clickTargetEnabled = true;
3443
- static LayeredForm markForm;
3444
- static DateTime markExpiresAt = DateTime.MinValue;
3445
- static bool markActive;
3446
- static int lastTyping = int.MinValue / 2;
3447
- static int lastEmit;
3448
- static readonly object RectLock = new object();
3449
-
3450
- // The progress card ("pet"): replaces the pill while DeepSeek Harness is minimized.
3451
- static bool petMode;
3452
- static string petSize = "standard";
3453
- static string hoveredBtn = "";
3454
- static string pressedBtn = "";
3455
- static LayeredForm pet;
3456
- public static volatile IntPtr PetHwnd = IntPtr.Zero;
3457
- static string petThinking = "";
3458
- static List<string> petSteps = new List<string>();
3459
- /** Bottom-right corner of the card body; the card grows upward when expanded. */
3460
- static Point petAnchor = Point.Empty;
3461
- static int petShadow;
3462
- static Rectangle petBody;
3463
- static byte petAlpha = 230;
3464
- static bool petDragged, petExpanded, petFinished;
3465
- static DateTime finishedAt;
3466
- static int finishHoldMs = 4000;
3467
- // The instruction box under the card (a real, focusable window over the card's field).
3468
- static InputBox input;
3469
- public static volatile IntPtr InputHwnd = IntPtr.Zero;
3470
- /** The window that had the focus before the instruction box opened. */
3471
- public static volatile IntPtr InputReturnsTo = IntPtr.Zero;
3472
- static bool pausedByInput;
3473
- static IntPtr beforeInput = IntPtr.Zero;
3474
- static Rectangle inputBounds;
3475
- static string iconFont;
3476
-
3477
- static void Ensure()
3478
- {
3479
- if (thread != null) return;
3480
- var ready = new ManualResetEvent(false);
3481
- thread = new Thread(delegate ()
3482
- {
3483
- invoker = new Control();
3484
- var force = invoker.Handle;
3485
- timer = new System.Windows.Forms.Timer();
3486
- timer.Interval = 40;
3487
- timer.Tick += delegate { Tick(); };
3488
- ready.Set();
3489
- Application.Run();
3490
- });
3491
- thread.IsBackground = true;
3492
- thread.SetApartmentState(ApartmentState.STA);
3493
- thread.Start();
3494
- ready.WaitOne();
3495
- }
3496
-
3497
- static void Ui(MethodInvoker action) { invoker.Invoke(action); }
3498
-
3499
- public static void Show(Dictionary<string, object> r)
3500
- {
3501
- Ensure();
3502
- Ui(delegate
3503
- {
3504
- label = Args.Str(r, "label", "");
3505
- status = Args.Str(r, "status", "");
3506
- idleMs = Args.Int(r, "idleMs", 1500);
3507
- string path = Args.Str(r, "icon", "");
3508
- string light = Args.Str(r, "iconLight", "");
3509
- if (light != iconLightPath)
3510
- {
3511
- iconLightPath = light;
3512
- if (iconLight != null) { iconLight.Dispose(); iconLight = null; }
3513
- try
3514
- {
3515
- if (light.Length > 0 && File.Exists(light))
3516
- using (var raw = Image.FromFile(light)) iconLight = new Bitmap(raw);
3517
- }
3518
- catch (Exception) { iconLight = null; }
3519
- }
3520
- if (path != iconPath)
3521
- {
3522
- iconPath = path;
3523
- if (icon != null) { icon.Dispose(); icon = null; }
3524
- try
3525
- {
3526
- if (path.Length > 0 && File.Exists(path))
3527
- using (var raw = Image.FromFile(path)) icon = new Bitmap(raw);
3528
- }
3529
- catch (Exception) { icon = null; }
3530
- }
3531
- petAlpha = (byte)Math.Max(90, Math.Min(255, Args.Int(r, "petOpacity", 90) * 255 / 100));
3532
- string reqSize = Args.Str(r, "petSize", "");
3533
- if (reqSize == "compact" || reqSize == "standard" || reqSize == "detailed") petSize = reqSize;
3534
- clickTargetEnabled = Args.Bool(r, "glow", true);
3535
- if (visible && !petFinished) { RenderPill(); return; }
3536
- if (visible) HideCore(); // the previous run's "done" card is still up
3537
- petMode = Args.Bool(r, "pet", false);
3538
- hoveredBtn = "";
3539
- pressedBtn = "";
3540
- petThinking = Args.Str(r, "thinking", "");
3541
- petSteps = new List<string>();
3542
- if (status.Length > 0) petSteps.Add(status);
3543
- pillAtBottom = false;
3544
- paused = false;
3545
- foreach (var g in glows) g.Close();
3546
- glows.Clear();
3547
- if (Args.Bool(r, "glow", true))
3548
- {
3549
- foreach (Dictionary<string, object> d in Screen2.Displays())
3550
- {
3551
- var bounds = new Rectangle((int)d["x"], (int)d["y"], (int)d["width"], (int)d["height"]);
3552
- var form = new LayeredForm(true);
3553
- form.Show();
3554
- using (var bmp = DrawGlow(bounds.Width, bounds.Height, (int)d["dpi"] / 96f)) form.SetBitmap(bmp, bounds, 255);
3555
- glows.Add(form);
3556
- }
3557
- }
3558
- if (petMode)
3559
- {
3560
- if (pet == null)
3561
- {
3562
- pet = new LayeredForm(false);
3563
- pet.MouseMove += delegate (object s, MouseEventArgs e)
3564
- {
3565
- string hit = "";
3566
- foreach (var b in buttons) if (b.Key.Contains(e.Location)) { hit = b.Value; break; }
3567
- pet.Cursor = hit.Length > 0 ? Cursors.Hand : Cursors.SizeAll;
3568
- if (hit != hoveredBtn)
3569
- {
3570
- hoveredBtn = hit;
3571
- RenderPill();
3572
- }
3573
- };
3574
- pet.MouseLeave += delegate
3575
- {
3576
- if (hoveredBtn.Length > 0 || pressedBtn.Length > 0)
3577
- {
3578
- hoveredBtn = "";
3579
- pressedBtn = "";
3580
- RenderPill();
3581
- }
3582
- };
3583
- pet.MouseDown += delegate (object s, MouseEventArgs e)
3584
- {
3585
- if (e.Button != MouseButtons.Left) return;
3586
- foreach (var b in buttons)
3587
- {
3588
- if (b.Key.Contains(e.Location))
3589
- {
3590
- pressedBtn = b.Value;
3591
- RenderPill();
3592
- return;
3593
- }
3594
- }
3595
- // Drag the card anywhere; it keeps that place until the next run.
3596
- Native.ReleaseCapture();
3597
- Native.SendMessage(pet.Handle, 0xA1, new IntPtr(2), IntPtr.Zero); // WM_NCLBUTTONDOWN, HTCAPTION
3598
- Native.RECT rc;
3599
- if (pet != null && Native.GetWindowRect(pet.Handle, out rc)) petAnchor = new Point(rc.Right - petShadow, rc.Bottom - petShadow);
3600
- petDragged = true;
3601
- RenderPill();
3602
- };
3603
- pet.MouseUp += delegate (object s, MouseEventArgs e)
3604
- {
3605
- bool hadPressed = pressedBtn.Length > 0;
3606
- pressedBtn = "";
3607
- if (petDragged) { petDragged = false; return; }
3608
- foreach (var b in buttons)
3609
- if (b.Key.Contains(e.Location)) { Press(b.Value); return; }
3610
- if (hadPressed) RenderPill();
3611
- };
3612
- pet.Show();
3613
- PetHwnd = pet.Handle;
3614
- }
3615
- }
3616
- else if (pill == null)
3617
- {
3618
- pill = new LayeredForm(false);
3619
- pill.MouseUp += delegate (object s, MouseEventArgs e)
3620
- {
3621
- foreach (var b in buttons)
3622
- if (b.Key.Contains(e.Location)) { Press(b.Value); break; }
3623
- };
3624
- pill.Show();
3625
- }
3626
- RenderPill();
3627
- InstallHook();
3628
- shownAt = DateTime.UtcNow;
3629
- visible = true;
3630
- timer.Start();
3631
- });
3632
- }
3633
-
3634
- public static void Status(string newStatus)
3635
- {
3636
- if (thread == null || !visible) return;
3637
- Ui(delegate { status = newStatus; RenderPill(); });
3638
- }
3639
-
3640
- /** Latest host-provided reasoning and recent operations, oldest first. */
3641
- public static void PetUpdate(string thinking, List<string> steps)
3642
- {
3643
- if (thread == null || !visible || !petMode || petFinished) return;
3644
- invoker.BeginInvoke((MethodInvoker)delegate
3645
- {
3646
- if (petFinished) return;
3647
- petThinking = thinking;
3648
- if (steps.Count > 0) petSteps = steps;
3649
- RenderPill();
3650
- });
3651
- }
3652
-
3653
- /** The run ended: the card says so for a moment (longer while the pointer rests on it), then everything hides. */
3654
- public static void Finish(int holdMs)
3655
- {
3656
- if (thread == null) return;
3657
- Ui(delegate
3658
- {
3659
- if (!visible || !petMode) { HideCore(); return; }
3660
- HideMark();
3661
- CloseInput(false);
3662
- foreach (var g in glows) g.Close();
3663
- glows.Clear();
3664
- RemoveHook();
3665
- paused = false;
3666
- petFinished = true;
3667
- finishedAt = DateTime.UtcNow;
3668
- finishHoldMs = holdMs;
3669
- RenderPill();
3670
- });
3671
- }
3672
-
3673
- public static void SetPaused(bool value)
3674
- {
3675
- if (thread == null) return;
3676
- Ui(delegate { paused = value; RenderPill(); });
3677
- }
3678
-
3679
- public static void Hide()
3680
- {
3681
- if (thread == null) return;
3682
- Ui(delegate { HideCore(); });
3683
- }
3684
-
3685
- static void HideCore()
3686
- {
3687
- {
3688
- HideMark();
3689
- CloseInput(false);
3690
- petFinished = false;
3691
- visible = false;
3692
- paused = false;
3693
- timer.Stop();
3694
- foreach (var g in glows) g.Close();
3695
- glows.Clear();
3696
- if (pill != null) { pill.Close(); pill = null; }
3697
- if (pet != null) { PetHwnd = IntPtr.Zero; pet.Close(); pet = null; }
3698
- petMode = false;
3699
- rendered = "";
3700
- lock (RectLock) pillRect = Rectangle.Empty;
3701
- RemoveHook();
3702
- }
3703
- }
3704
-
3705
- public static void Shutdown()
3706
- {
3707
- if (thread == null) return;
3708
- try { Hide(); Ui(delegate { Application.ExitThread(); }); } catch (Exception) { }
3709
- }
3710
-
3711
- public static bool ShowClickTarget { get { return visible && clickTargetEnabled; } }
3712
-
3713
- static void MonitorAt(int x, int y, out float scale, out Rectangle bounds)
3714
- {
3715
- scale = 1f;
3716
- bounds = Rectangle.Empty;
3717
- bool found = false;
3718
- foreach (Dictionary<string, object> d in Screen2.Displays())
3719
- {
3720
- var r = new Rectangle((int)d["x"], (int)d["y"], (int)d["width"], (int)d["height"]);
3721
- float s = (int)d["dpi"] / 96f;
3722
- if (r.Contains(x, y)) { scale = s; bounds = r; return; }
3723
- if (!found || (bool)d["primary"]) { scale = s; bounds = r; found = true; }
3724
- }
3725
- }
3726
-
3727
- /**
3728
- * Collaborative Codex-style cursor badge: the corner nearest the pointer
3729
- * tip stays tight (2px), while the other three corners are smoothly rounded.
3730
- */
3731
- static GraphicsPath TagShape(RectangleF r, bool flipX, bool flipY, float scale)
3732
- {
3733
- float tight = 2f * scale;
3734
- float round = 7f * scale;
3735
- float tl = (!flipX && !flipY) ? tight : round;
3736
- float tr = (flipX && !flipY) ? tight : round;
3737
- float br = (flipX && flipY) ? tight : round;
3738
- float bl = (!flipX && flipY) ? tight : round;
3739
- var p = new GraphicsPath();
3740
- p.AddArc(r.X, r.Y, tl * 2f, tl * 2f, 180, 90);
3741
- p.AddArc(r.Right - tr * 2f, r.Y, tr * 2f, tr * 2f, 270, 90);
3742
- p.AddArc(r.Right - br * 2f, r.Bottom - br * 2f, br * 2f, br * 2f, 0, 90);
3743
- p.AddArc(r.X, r.Bottom - bl * 2f, bl * 2f, bl * 2f, 90, 90);
3744
- p.CloseFigure();
3745
- return p;
3746
- }
3747
-
3748
- /**
3749
- * Draw a sleek Codex-style collaborative AI pointer cursor whose tip sits
3750
- * pixel-exact at (cx, cy): soft radial spotlight glow, crisp filled vector
3751
- * arrow with white outline, attached rounded name-tag pill (auto-flipping
3752
- * at all 4 screen edges), and a subtle click ripple ring on post-click.
3753
- */
3754
- static Bitmap DrawMark(string text, Color color, float scale, bool flipX, bool flipY, bool ripple, out int cx, out int cy)
3755
- {
3756
- float s = Math.Max(0.75f, Math.Min(3f, scale));
3757
- float px = 1.333f * s;
3758
- float glowR = (ripple ? 20f : 16f) * s;
3759
- float pad = 4f * s;
3760
- using (var font = new Font("Microsoft YaHei UI", 8f * px, FontStyle.Bold, GraphicsUnit.Pixel))
3761
- using (var probe = new Bitmap(1, 1))
3762
- using (var mg = Graphics.FromImage(probe))
3763
- using (var fmt = new StringFormat(StringFormat.GenericTypographic))
3764
- {
3765
- mg.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
3766
- fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap;
3767
- SizeF textSize = string.IsNullOrEmpty(text) ? SizeF.Empty : mg.MeasureString(text, font, 10000, fmt);
3768
- float pillPadX = 7f * s;
3769
- float pillW = textSize.Width > 0 ? (float)Math.Ceiling(textSize.Width + 2f * pillPadX) : 0f;
3770
- float pillH = textSize.Height > 0 ? Math.Max(19f * s, (float)Math.Ceiling(textSize.Height + 5f * s)) : 0f;
3771
-
3772
- // Offsets relative to the pointer tip at (0, 0).
3773
- float tagX = flipX ? (-10f * s - pillW) : (13f * s);
3774
- float tagY = flipY ? (-10f * s - pillH) : (15f * s);
3775
-
3776
- float minX = Math.Min(-glowR, pillW > 0 ? tagX : 0f) - pad;
3777
- float maxX = Math.Max(glowR, Math.Max(14f * s, pillW > 0 ? tagX + pillW : 0f)) + pad;
3778
- float minY = Math.Min(-glowR, pillH > 0 ? tagY : 0f) - pad;
3779
- float maxY = Math.Max(glowR, Math.Max(22f * s, pillH > 0 ? tagY + pillH : 0f)) + pad;
3780
-
3781
- int W = Math.Max(1, (int)Math.Ceiling(maxX - minX));
3782
- int H = Math.Max(1, (int)Math.Ceiling(maxY - minY));
3783
- cx = (int)Math.Round(-minX);
3784
- cy = (int)Math.Round(-minY);
3785
-
3786
- var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb);
3787
- using (var g = Graphics.FromImage(bmp))
3788
- {
3789
- g.Clear(Color.Transparent);
3790
- g.SmoothingMode = SmoothingMode.AntiAlias;
3791
- g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
3792
-
3793
- // 1. Soft radial spotlight centered right under the tip (cx, cy).
3794
- using (var spot = new GraphicsPath())
3795
- {
3796
- spot.AddEllipse(cx - glowR, cy - glowR, glowR * 2f, glowR * 2f);
3797
- using (var glow = new PathGradientBrush(spot))
3798
- {
3799
- glow.CenterPoint = new PointF(cx, cy);
3800
- glow.CenterColor = Color.FromArgb(ripple ? 130 : 95, color);
3801
- glow.SurroundColors = new Color[] { Color.FromArgb(0, color) };
3802
- g.FillPath(glow, spot);
3803
- }
3804
- }
3805
-
3806
- // 2. Post-click delicate ripple ring so exact placement reads cleanly in screenshots.
3807
- if (ripple)
3808
- {
3809
- float rr = 11.5f * s;
3810
- using (var ringHalo = new Pen(Color.FromArgb(140, 255, 255, 255), Math.Max(2.5f, 3.2f * s)))
3811
- g.DrawEllipse(ringHalo, cx - rr, cy - rr, rr * 2f, rr * 2f);
3812
- using (var ring = new Pen(Color.FromArgb(230, color), Math.Max(1.6f, 2f * s)))
3813
- g.DrawEllipse(ring, cx - rr, cy - rr, rr * 2f, rr * 2f);
3814
- }
3815
-
3816
- // 3. Attached collaborative name-tag pill.
3817
- if (pillW > 0 && pillH > 0)
3818
- {
3819
- float bx = cx + tagX;
3820
- float by = cy + tagY;
3821
- var shadowRect = new RectangleF(bx, by + 1.5f * s, pillW, pillH);
3822
- using (var sp = TagShape(shadowRect, flipX, flipY, s))
3823
- using (var sb = new SolidBrush(Color.FromArgb(62, 0, 0, 0)))
3824
- g.FillPath(sb, sp);
3825
-
3826
- var pillRect = new RectangleF(bx, by, pillW, pillH);
3827
- using (var pp = TagShape(pillRect, flipX, flipY, s))
3828
- {
3829
- using (var fill = new SolidBrush(Color.FromArgb(245, color))) g.FillPath(fill, pp);
3830
- using (var border = new Pen(Color.FromArgb(235, 255, 255, 255), Math.Max(1f, 1.25f * s))) g.DrawPath(border, pp);
3831
- }
3832
- using (var fg = new SolidBrush(Color.White))
3833
- g.DrawString(text, font, fg, bx + (pillW - textSize.Width) / 2f, by + (pillH - textSize.Height) / 2f - 0.5f * s, fmt);
3834
- }
3835
-
3836
- // 4. Crisp vector cursor arrow whose tip sits pixel-exact at (cx, cy).
3837
- var arrow = new PointF[]
3838
- {
3839
- new PointF(cx, cy),
3840
- new PointF(cx, cy + 16.5f * s),
3841
- new PointF(cx + 4.3f * s, cy + 12.8f * s),
3842
- new PointF(cx + 7.4f * s, cy + 19.2f * s),
3843
- new PointF(cx + 10.0f * s, cy + 17.9f * s),
3844
- new PointF(cx + 6.9f * s, cy + 11.7f * s),
3845
- new PointF(cx + 12.4f * s, cy + 11.4f * s),
3846
- };
3847
- var arrowShadow = new PointF[arrow.Length];
3848
- for (int i = 0; i < arrow.Length; i++)
3849
- arrowShadow[i] = new PointF(arrow[i].X + 0.8f * s, arrow[i].Y + 1.5f * s);
3850
- using (var sb = new SolidBrush(Color.FromArgb(72, 0, 0, 0))) g.FillPolygon(sb, arrowShadow);
3851
- using (var fill = new SolidBrush(Color.FromArgb(255, color))) g.FillPolygon(fill, arrow);
3852
- using (var outline = new Pen(Color.FromArgb(248, 255, 255, 255), Math.Max(1.2f, 1.5f * s)))
3853
- {
3854
- outline.LineJoin = LineJoin.Round;
3855
- g.DrawPolygon(outline, arrow);
3856
- }
3857
- }
3858
- return bmp;
3859
- }
3860
- }
3861
-
3862
- static int lastMarkX, lastMarkY;
3863
- static bool hasLastMark;
3864
-
3865
- public static void MarkPointer(int x, int y, string text, int holdMs)
3866
- {
3867
- GlideMark(x, y, text, Accent, holdMs, false, false);
3868
- }
3869
-
3870
- /** Smooth single-segment EaseOutCubic glide (~160ms) to (x, y) before holding the Codex cursor. */
3871
- public static void GlideMark(int x, int y, string text, Color color, int holdMs, bool capturable, bool ripple)
3872
- {
3873
- int startX, startY;
3874
- if (hasLastMark)
3875
- {
3876
- startX = lastMarkX;
3877
- startY = lastMarkY;
3878
- }
3879
- else
3880
- {
3881
- Native.POINT cur;
3882
- if (Native.GetCursorPos(out cur)) { startX = cur.X; startY = cur.Y; }
3883
- else { startX = x; startY = y; }
3884
- }
3885
- double dist = Math.Sqrt((double)(x - startX) * (x - startX) + (double)(y - startY) * (y - startY));
3886
- if (dist >= 40.0)
3887
- {
3888
- int steps = Math.Max(5, Math.Min(10, (int)(dist / 90.0) + 5));
3889
- for (int i = 1; i < steps; i++)
3890
- {
3891
- double t = (double)i / steps;
3892
- double ease = 1.0 - Math.Pow(1.0 - t, 3.0); // EaseOutCubic
3893
- int ix = startX + (int)Math.Round((x - startX) * ease);
3894
- int iy = startY + (int)Math.Round((y - startY) * ease);
3895
- Mark(ix, iy, text, color, holdMs, capturable, false);
3896
- Thread.Sleep(16);
3897
- }
3898
- }
3899
- Mark(x, y, text, color, holdMs, capturable, ripple);
3900
- }
3901
-
3902
- public static void Mark(int x, int y, string text, Color color, int holdMs, bool capturable, bool ripple)
3903
- {
3904
- lastMarkX = x;
3905
- lastMarkY = y;
3906
- hasLastMark = true;
3907
- Ensure();
3908
- Ui(delegate
3909
- {
3910
- if (markForm == null)
3911
- {
3912
- markForm = new LayeredForm(true);
3913
- markForm.Show();
3914
- }
3915
- markForm.SetCapturable(capturable || !ExcludeFromCapture);
3916
- float scale; Rectangle mon;
3917
- MonitorAt(x, y, out scale, out mon);
3918
- float s = Math.Max(0.75f, Math.Min(3f, scale));
3919
- int estW = (int)((Math.Max(6, (text ?? "").Length) * 11 + 36) * s);
3920
- bool flipX = !mon.IsEmpty && x + estW > mon.Right;
3921
- bool flipY = !mon.IsEmpty && y + (int)(52 * s) > mon.Bottom;
3922
- int cx, cy;
3923
- using (var bmp = DrawMark(text, color, scale, flipX, flipY, ripple, out cx, out cy))
3924
- {
3925
- markForm.SetBitmap(bmp, new Rectangle(x - cx, y - cy, bmp.Width, bmp.Height), 255);
3926
- }
3927
- markForm.KeepOnTop();
3928
- markActive = true;
3929
- markExpiresAt = holdMs > 0 ? DateTime.UtcNow.AddMilliseconds(holdMs) : DateTime.MaxValue;
3930
- if (!timer.Enabled) timer.Start();
3931
- });
3932
- }
3933
-
3934
- public static void MarkResult(int x, int y, string button, int count, string coordLabel)
3935
- {
3936
- Color color;
3937
- string verb;
3938
- if (count >= 3) { color = Color.FromArgb(249, 115, 22); verb = "已三击"; }
3939
- else if (count == 2) { color = Color.FromArgb(139, 92, 246); verb = "已双击"; }
3940
- else if (button == "right") { color = Color.FromArgb(16, 185, 129); verb = "已右键"; }
3941
- else if (button == "middle") { color = Color.FromArgb(6, 182, 212); verb = "已中键"; }
3942
- else { color = Color.FromArgb(59, 130, 246); verb = "已单击"; }
3943
- Mark(x, y, verb + " " + coordLabel, color, 4000, true, true);
3944
- }
3945
-
3946
- static void HideMark()
3947
- {
3948
- markActive = false;
3949
- markExpiresAt = DateTime.MinValue;
3950
- if (markForm != null)
3951
- {
3952
- markForm.SetCapturable(false);
3953
- markForm.Close();
3954
- markForm = null;
3955
- }
3956
- }
3957
-
3958
- /// Move the status pill out of the way when an injected pointer action
3959
- /// targets it: the pill is clickable for the user but invisible to the model.
3960
- public static void Dodge(int x, int y)
3961
- {
3962
- Rectangle r;
3963
- lock (RectLock) r = pillRect;
3964
- if (r.IsEmpty) return;
3965
- var inflated = Rectangle.Inflate(r, 12, 12);
3966
- if (!inflated.Contains(x, y)) return;
3967
- Ui(delegate { pillAtBottom = !pillAtBottom; RenderPill(); });
3968
- Thread.Sleep(30);
3969
- }
3970
-
3971
- // pause / resume / stop, from Esc or the pill buttons.
3972
- static void Press(string action)
3973
- {
3974
- if (action == "stop") { paused = false; Program.EmitEvent("stop", "button"); }
3975
- else if (action == "pause") { paused = true; Program.EmitEvent("pause", "user"); }
3976
- else if (action == "resume") { paused = false; pausedByInput = false; Program.EmitEvent("resume", "user"); }
3977
- else if (action == "expand") petExpanded = !petExpanded;
3978
- else if (action == "input") { if (input == null) OpenInput(); else CloseInput(true); return; }
3979
- else if (action == "send") { if (input != null) SubmitInput(input.Box.Text); return; }
3980
- else if (action == "close") { HideCore(); return; }
3981
- RenderPill();
3982
- }
3983
-
3984
- static void OpenInput()
3985
- {
3986
- beforeInput = Native.GetForegroundWindow();
3987
- // Typing an instruction pauses the agent, so its keys cannot land in the box.
3988
- if (!paused) { paused = true; pausedByInput = true; Program.EmitEvent("pause", "input"); }
3989
- bool dark = DarkTheme();
3990
- float px = 1.333f * Scale();
3991
- input = new InputBox(new Font("Microsoft YaHei UI", 10f * px, FontStyle.Regular, GraphicsUnit.Pixel),
3992
- dark ? Color.FromArgb(52, 51, 49) : Color.White, dark ? Color.FromArgb(244, 243, 241) : Color.FromArgb(31, 30, 29),
3993
- "告诉 DeepSeek 接下来做什么(Enter 发送,Esc 取消)");
3994
- input.Submitted += SubmitInput;
3995
- input.Cancelled += delegate { CloseInput(true); };
3996
- inputBounds = Rectangle.Empty;
3997
- RenderPill(); // makes room for the field and places the box over it
3998
- input.Show();
3999
- InputHwnd = input.Handle;
4000
- var handle = input.Handle;
4001
- ThreadPool.QueueUserWorkItem(delegate
4002
- {
4003
- try { Windows.Focus(handle); } catch (Exception) { }
4004
- try { invoker.BeginInvoke((MethodInvoker)delegate { if (input != null) input.Box.Focus(); }); } catch (Exception) { }
4005
- });
4006
- }
4007
-
4008
- static void SubmitInput(string text)
4009
- {
4010
- text = (text ?? "").Trim();
4011
- if (text.Length > 0) Program.EmitEvent("message", text);
4012
- CloseInput(true);
4013
- }
4014
-
4015
- static void CloseInput(bool restoreFocus)
4016
- {
4017
- if (input == null) return;
4018
- var box = input;
4019
- input = null;
4020
- InputReturnsTo = restoreFocus ? beforeInput : IntPtr.Zero;
4021
- InputHwnd = IntPtr.Zero;
4022
- inputBounds = Rectangle.Empty;
4023
- box.Close();
4024
- if (pausedByInput) { paused = false; pausedByInput = false; Program.EmitEvent("resume", "input"); }
4025
- var target = beforeInput;
4026
- beforeInput = IntPtr.Zero;
4027
- if (restoreFocus && target != IntPtr.Zero && Native.IsWindow(target))
4028
- ThreadPool.QueueUserWorkItem(delegate { try { Windows.Focus(target); } catch (Exception) { } });
4029
- if (visible) RenderPill();
4030
- }
4031
-
4032
- static bool Typing() { return unchecked(Environment.TickCount - lastTyping) < idleMs; }
4033
-
4034
- static void Tick()
4035
- {
4036
- if (markActive && DateTime.UtcNow >= markExpiresAt) HideMark();
4037
- if (!visible)
4038
- {
4039
- if (!markActive) timer.Stop();
4040
- return;
4041
- }
4042
- if (petFinished)
4043
- {
4044
- Native.POINT p; Native.GetCursorPos(out p);
4045
- bool hovered = petBody.Contains(p.X, p.Y);
4046
- if (hovered) finishedAt = DateTime.UtcNow;
4047
- if ((DateTime.UtcNow - finishedAt).TotalMilliseconds >= finishHoldMs) HideCore();
4048
- return;
4049
- }
4050
- double t = (DateTime.UtcNow - shownAt).TotalSeconds;
4051
- double fadeIn = Math.Min(1.0, t / 0.35);
4052
- double breathe = paused ? 0.55 : 0.72 + 0.28 * (0.5 + 0.5 * Math.Sin(t * Math.PI * 2 / 2.6));
4053
- byte alpha = (byte)Math.Max(0, Math.Min(255, 255 * fadeIn * breathe));
4054
- foreach (var g in glows) g.SetAlpha(alpha);
4055
- if (Key() != rendered) RenderPill(); // typing started or stopped
4056
- if ((int)(t * 25) % 50 == 0)
4057
- {
4058
- foreach (var g in glows) g.KeepOnTop();
4059
- if (pill != null) pill.KeepOnTop();
4060
- if (pet != null) pet.KeepOnTop();
4061
- if (markForm != null) markForm.KeepOnTop();
4062
- if (input != null) Native.SetWindowPos(input.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);
4063
- }
4064
- }
4065
-
4066
- static Bitmap DrawGlow(int w, int h, float scale)
4067
- {
4068
- var bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb);
4069
- using (var g = Graphics.FromImage(bmp))
4070
- {
4071
- g.Clear(Color.Transparent);
4072
- int depth = Math.Max(14, (int)(30 * scale));
4073
- for (int i = 0; i < depth; i++)
4074
- {
4075
- double f = 1.0 - (double)i / depth;
4076
- int a = (int)(185 * Math.Pow(f, 1.9));
4077
- if (a <= 0) continue;
4078
- using (var pen = new Pen(Color.FromArgb(a, Accent), 1))
4079
- g.DrawRectangle(pen, i, i, w - 1 - 2 * i, h - 1 - 2 * i);
4080
- }
4081
- int line = Math.Max(2, (int)Math.Round(2.5 * scale));
4082
- using (var pen = new Pen(Color.FromArgb(235, AccentHi), line))
4083
- {
4084
- pen.Alignment = PenAlignment.Inset;
4085
- g.DrawRectangle(pen, 0, 0, w, h);
4086
- }
4087
- }
4088
- return bmp;
4089
- }
4090
-
4091
- static GraphicsPath Rounded(RectangleF r, float radius)
4092
- {
4093
- var p = new GraphicsPath();
4094
- float d = radius * 2;
4095
- p.AddArc(r.X, r.Y, d, d, 180, 90);
4096
- p.AddArc(r.Right - d, r.Y, d, d, 270, 90);
4097
- p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
4098
- p.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
4099
- p.CloseFigure();
4100
- return p;
4101
- }
4102
-
4103
- // What the pill should say right now; it is re-rendered whenever this changes.
4104
- static void Content(out string main, out string sub, out string[] actions, out string[] captions)
4105
- {
4106
- if (paused)
4107
- {
4108
- main = "已暂停"; sub = "按 Esc 继续";
4109
- actions = new[] { "resume", "stop" }; captions = new[] { "继续", "停止" };
4110
- return;
4111
- }
4112
- main = label;
4113
- sub = Typing() ? "你正在操作,已暂停" : status.Length > 0 ? status : "Esc 暂停";
4114
- actions = new[] { "stop" }; captions = new[] { "停止" };
4115
- }
4116
-
4117
- static string Key()
4118
- {
4119
- string main, sub; string[] actions, captions;
4120
- Content(out main, out sub, out actions, out captions);
4121
- return main + "|" + sub + "|" + string.Join(",", actions) + "|" + pillAtBottom + "|" + Typing();
4122
- }
4123
-
4124
- static bool DarkTheme()
4125
- {
4126
- try
4127
- {
4128
- using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"))
4129
- {
4130
- object v = key == null ? null : key.GetValue("AppsUseLightTheme");
4131
- return v is int && (int)v == 0;
4132
- }
4133
- }
4134
- catch (Exception) { return false; }
4135
- }
4136
-
4137
- /** The end of `s` that fits `width`, led by "…": a ticker that scrolls as text streams in. */
4138
- static string Tail(Graphics g, string s, Font font, float width, StringFormat fmt)
4139
- {
4140
- if (s.Length == 0 || g.MeasureString(s, font, 100000, fmt).Width <= width) return s;
4141
- int lo = 1, hi = s.Length - 1;
4142
- while (lo < hi)
4143
- {
4144
- int mid = (lo + hi) / 2;
4145
- if (g.MeasureString("…" + s.Substring(mid), font, 100000, fmt).Width <= width) hi = mid; else lo = mid + 1;
4146
- }
4147
- if (lo < s.Length && char.IsLowSurrogate(s[lo])) lo++;
4148
- return "…" + s.Substring(Math.Min(lo, s.Length));
4149
- }
4150
-
4151
- static float Scale()
4152
- {
4153
- float scale = 1f; bool found = false;
4154
- foreach (Dictionary<string, object> d in Screen2.Displays())
4155
- if (!found || (bool)d["primary"]) { scale = (int)d["dpi"] / 96f; found = true; }
4156
- return scale;
4157
- }
4158
-
4159
- static string IconFont()
4160
- {
4161
- if (iconFont != null) return iconFont;
4162
- iconFont = "";
4163
- foreach (var name in new[] { "Segoe Fluent Icons", "Segoe MDL2 Assets" })
4164
- using (var f = new Font(name, 10f)) if (f.Name == name) { iconFont = name; break; }
4165
- return iconFont;
4166
- }
4167
-
4168
- /** The end of `s` that fits in `width` x `height` when wrapped, led by "…". */
4169
- static string TailWrapped(Graphics g, string s, Font font, float width, float height, StringFormat fmt)
4170
- {
4171
- Func<string, bool> fits = delegate (string t) { return g.MeasureString(t, font, new SizeF(width, 100000), fmt).Height <= height; };
4172
- if (s.Length == 0 || fits(s)) return s;
4173
- int lo = 1, hi = s.Length - 1;
4174
- while (lo < hi)
4175
- {
4176
- int mid = (lo + hi) / 2;
4177
- if (fits("…" + s.Substring(mid))) hi = mid; else lo = mid + 1;
4178
- }
4179
- if (lo < s.Length && char.IsLowSurrogate(s[lo])) lo++;
4180
- return "…" + s.Substring(Math.Min(lo, s.Length));
4181
- }
4182
-
4183
- static string ButtonTip(string act)
4184
- {
4185
- if (act == "stop") return "停止本轮";
4186
- if (act == "pause") return "暂停操控";
4187
- if (act == "resume") return "继续操控";
4188
- if (act == "expand") return petExpanded ? "收起详情" : "展开详情";
4189
- if (act == "input") return input != null ? "关闭输入框" : "输入新指令";
4190
- if (act == "close") return "关闭卡片";
4191
- if (act == "send") return "发送指令";
4192
- return "";
4193
- }
4194
-
4195
- static void RenderPet()
4196
- {
4197
- if (pet == null) return;
4198
- Rectangle work = Rectangle.Empty; float scale = 1f;
4199
- foreach (Dictionary<string, object> d in Screen2.Displays())
4200
- {
4201
- if (work.IsEmpty || (bool)d["primary"])
4202
- {
4203
- work = new Rectangle((int)d["workX"], (int)d["workY"], (int)d["workWidth"], (int)d["workHeight"]);
4204
- scale = (int)d["dpi"] / 96f;
4205
- }
4206
- }
4207
- rendered = Key();
4208
- bool dark = DarkTheme();
4209
- Color bg = dark ? Color.FromArgb(petAlpha, 30, 30, 32) : Color.FromArgb(petAlpha, 252, 252, 251);
4210
- Color ink = dark ? Color.FromArgb(244, 243, 241) : Color.FromArgb(31, 30, 29);
4211
- Color muted = dark ? Color.FromArgb(168, 165, 160) : Color.FromArgb(112, 110, 106);
4212
- Color edge = dark ? Color.FromArgb(64, 255, 255, 255) : Color.FromArgb(38, 0, 0, 0);
4213
- Color chip = dark ? Color.FromArgb(64, 63, 66) : Color.FromArgb(236, 234, 230);
4214
- Color chipHover = dark ? Color.FromArgb(92, 86, 82) : Color.FromArgb(224, 214, 206);
4215
- Color chipPress = dark ? Color.FromArgb(110, 96, 88) : Color.FromArgb(212, 198, 188);
4216
- Color field = dark ? Color.FromArgb(50, 50, 52) : Color.White;
4217
-
4218
- bool isCompact = petSize == "compact";
4219
- bool isDetailed = petSize == "detailed";
4220
- string title = petFinished ? "已完成" : (isCompact && label.Length > 12 ? label.Substring(0, 11) + "…" : label);
4221
- string hoverTip = ButtonTip(hoveredBtn);
4222
- string state = hoverTip.Length > 0 ? hoverTip
4223
- : petFinished ? "" : paused ? (input != null ? "输入指令中…" : "已暂停 · Esc 继续")
4224
- : Typing() ? "你正在操作,已暂停" : (isCompact ? "" : "Esc 暂停");
4225
- // Header buttons, right to left.
4226
- var actions = new List<string>(); var glyphs = new List<string>();
4227
- if (petFinished) { actions.Add("close"); glyphs.Add("\uE711"); }
4228
- else
4229
- {
4230
- actions.Add("stop"); glyphs.Add("\uE71A");
4231
- if (paused) { actions.Add("resume"); glyphs.Add("\uE768"); } else { actions.Add("pause"); glyphs.Add("\uE769"); }
4232
- }
4233
- actions.Add("expand"); glyphs.Add(petExpanded ? "\uE70D" : "\uE70E");
4234
- if (!petFinished) { actions.Add("input"); glyphs.Add("\uE70F"); }
4235
-
4236
- float s = scale, px = 1.333f * scale;
4237
- int shadow = (int)(14 * s);
4238
- petShadow = shadow;
4239
- float bodyW = (isCompact ? 320f : isDetailed ? 484f : 420f) * s;
4240
- float pad = (isCompact ? 13f : 16f) * s;
4241
- float headH = (isCompact ? 40f : 44f) * s;
4242
- bool showThinking = !isCompact || petExpanded;
4243
- bool showTimeline = petExpanded || isDetailed;
4244
- float replyH = showThinking ? (isDetailed && !petExpanded ? 42f * s : 26f * s) : 0f;
4245
- string progress = petFinished ? "已交还电脑控制" : petThinking.Length > 0 ? "思考 · " + petThinking : "正在操作,等待下一步…";
4246
- if (showThinking && (petExpanded || isDetailed))
4247
- {
4248
- using (var probe = new Bitmap(1, 1))
4249
- using (var pg = Graphics.FromImage(probe))
4250
- using (var pf = new Font("Microsoft YaHei UI", (isCompact ? 9.5f : 10.5f) * 1.333f * scale, FontStyle.Regular, GraphicsUnit.Pixel))
4251
- {
4252
- float need = pg.MeasureString(progress, pf, new SizeF(bodyW - 2 * pad, 100000), new StringFormat(StringFormat.GenericTypographic)).Height + 6 * scale;
4253
- float cap = petExpanded ? (isDetailed ? 210f : 172f) * scale : 44f * scale;
4254
- replyH = Math.Max(26f * scale, Math.Min(cap, need));
4255
- }
4256
- }
4257
- int maxSteps = petExpanded ? (isDetailed ? 8 : 5) : (isDetailed ? 3 : 0);
4258
- int stepRows = showTimeline ? Math.Min(maxSteps, Math.Max(1, petSteps.Count)) : 0;
4259
- float listH = showTimeline ? 10 * s + stepRows * 22 * s : 24 * s;
4260
- float inputH = input != null ? 46 * s : 0;
4261
- float bodyH = headH + replyH + listH + inputH + (isCompact ? 10f : 12f) * s;
4262
- int W = (int)Math.Ceiling(bodyW) + 2 * shadow, H = (int)Math.Ceiling(bodyH) + 2 * shadow;
4263
- if (petAnchor.IsEmpty) petAnchor = new Point(work.Right - (int)(16 * s), work.Bottom - (int)(16 * s));
4264
- int x = petAnchor.X - (int)bodyW - shadow, y = petAnchor.Y - (int)bodyH - shadow;
4265
- y = Math.Max(work.Y - shadow, y);
4266
- petBody = new Rectangle(x + shadow, y + shadow, (int)bodyW, (int)bodyH);
4267
-
4268
- string glyphFont = IconFont();
4269
- using (var fHead = new Font("Microsoft YaHei UI", 8.5f * px, FontStyle.Bold, GraphicsUnit.Pixel))
4270
- using (var fState = new Font("Microsoft YaHei UI", 8.2f * px, FontStyle.Regular, GraphicsUnit.Pixel))
4271
- using (var fText = new Font("Microsoft YaHei UI", (isCompact ? 9.5f : 10.2f) * px, FontStyle.Regular, GraphicsUnit.Pixel))
4272
- using (var fAct = new Font("Microsoft YaHei UI", 8.5f * px, FontStyle.Regular, GraphicsUnit.Pixel))
4273
- using (var fGlyph = new Font(glyphFont.Length > 0 ? glyphFont : "Segoe UI Symbol", 8.5f * px, FontStyle.Regular, GraphicsUnit.Pixel))
4274
- using (var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb))
4275
- using (var g = Graphics.FromImage(bmp))
4276
- {
4277
- g.Clear(Color.Transparent);
4278
- g.SmoothingMode = SmoothingMode.AntiAlias;
4279
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
4280
- g.TextRenderingHint = TextRenderingHint.AntiAlias;
4281
- var fmt = new StringFormat(StringFormat.GenericTypographic);
4282
- fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap;
4283
- var wrap = new StringFormat(StringFormat.GenericTypographic);
4284
- wrap.Trimming = StringTrimming.None;
4285
- var center = new StringFormat(); center.Alignment = StringAlignment.Center; center.LineAlignment = StringAlignment.Center;
4286
-
4287
- var body = new RectangleF(shadow, shadow, bodyW, bodyH);
4288
- float radius = (isCompact ? 15f : 18f) * s;
4289
- for (int i = shadow; i > 0; i--)
4290
- {
4291
- double f = 1.0 - (double)i / shadow;
4292
- using (var path = Rounded(RectangleF.Inflate(body, i, i - 2 * s), radius + i))
4293
- using (var brush = new SolidBrush(Color.FromArgb((int)(16 * f * f), 0, 0, 0))) g.FillPath(brush, path);
4294
- }
4295
- using (var path = Rounded(body, radius))
4296
- {
4297
- using (var brush = new SolidBrush(bg)) g.FillPath(brush, path);
4298
- using (var pen = new Pen(petFinished ? Color.FromArgb(145, 46, 160, 67) : edge, Math.Max(1f, s))) g.DrawPath(pen, path);
4299
- }
4300
-
4301
- // Header: logo, title, state / button hover tooltip, tactile round icon buttons.
4302
- float hy = body.Y + (isCompact ? 8f : 10f) * s, hh = 26 * s;
4303
- float iconSize = 18 * s;
4304
- var iconRect = new RectangleF(body.X + pad, hy + (hh - iconSize) / 2f, iconSize, iconSize);
4305
- Image logo = dark ? icon : (iconLight ?? icon);
4306
- if (petFinished)
4307
- {
4308
- using (var brush = new SolidBrush(Color.FromArgb(46, 160, 67))) g.FillEllipse(brush, iconRect);
4309
- using (var b = new SolidBrush(Color.White)) g.DrawString(glyphFont.Length > 0 ? "\uE73E" : "✓", fGlyph, b, iconRect, center);
4310
- }
4311
- else if (logo != null) g.DrawImage(logo, iconRect);
4312
- else using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, RectangleF.Inflate(iconRect, -3 * s, -3 * s));
4313
- float tx = iconRect.Right + 8 * s;
4314
- SizeF headSize = g.MeasureString(title, fHead, 100000, fmt);
4315
- using (var b = new SolidBrush(ink)) g.DrawString(title, fHead, b, tx, hy + (hh - headSize.Height) / 2f, fmt);
4316
- tx += headSize.Width + 8 * s;
4317
-
4318
- buttons.Clear();
4319
- float d = (isCompact ? 24f : 26f) * s, bx = body.Right - pad;
4320
- for (int i = 0; i < actions.Count; i++)
4321
- {
4322
- string act = actions[i];
4323
- bx -= d;
4324
- var hitRect = new RectangleF(bx, hy + (hh - d) / 2f, d, d);
4325
- bool stop = act == "stop";
4326
- bool on = (act == "input" && input != null) || (act == "resume");
4327
- bool hover = hoveredBtn == act;
4328
- bool press = pressedBtn == act;
4329
- float inflate = press ? -0.8f * s : hover ? 1.1f * s : 0f;
4330
- var circle = RectangleF.Inflate(hitRect, inflate, inflate);
4331
- if (hover && stop)
4332
- {
4333
- using (var halo = new SolidBrush(Color.FromArgb(65, Accent)))
4334
- g.FillEllipse(halo, RectangleF.Inflate(circle, 2.6f * s, 2.6f * s));
4335
- }
4336
- Color btnFill = stop
4337
- ? (press ? Color.FromArgb(190, 92, 62) : hover ? AccentHi : Accent)
4338
- : on
4339
- ? Color.FromArgb(dark ? (hover ? 145 : 115) : (hover ? 95 : 65), Accent)
4340
- : (press ? chipPress : hover ? chipHover : chip);
4341
- using (var brush = new SolidBrush(btnFill)) g.FillEllipse(brush, circle);
4342
- if (hover && !stop)
4343
- {
4344
- using (var ring = new Pen(Color.FromArgb(dark ? 150 : 120, Accent), Math.Max(1f, 1.2f * s)))
4345
- g.DrawEllipse(ring, circle);
4346
- }
4347
- string glyph = glyphFont.Length > 0 ? glyphs[i] : (stop ? "■" : act == "pause" ? "❚❚" : act == "resume" ? "▶" : act == "expand" ? (petExpanded ? "˅" : "˄") : act == "close" ? "✕" : "✎");
4348
- Color glyphColor = stop ? Color.White : (hover || on) ? (dark ? Color.White : Color.FromArgb(168, 72, 42)) : ink;
4349
- using (var b = new SolidBrush(glyphColor)) g.DrawString(glyph, fGlyph, b, circle, center);
4350
- buttons.Add(new KeyValuePair<Rectangle, string>(Rectangle.Round(hitRect), act));
4351
- bx -= 6 * s;
4352
- }
4353
- if (state.Length > 0)
4354
- {
4355
- string st = Tail(g, state, fState, Math.Max(0, bx - tx - 4 * s), fmt);
4356
- SizeF stSize = g.MeasureString(st, fState, 100000, fmt);
4357
- Color stColor = (hoverTip.Length > 0 || paused) ? Accent : muted;
4358
- using (var b = new SolidBrush(stColor)) g.DrawString(st, fState, b, tx, hy + (hh - stSize.Height) / 2f, fmt);
4359
- }
4360
-
4361
- // Reasoning and operations use separate rows throughout.
4362
- float lineW = bodyW - 2 * pad;
4363
- float ry = body.Y + headH;
4364
- if (showThinking)
4365
- {
4366
- using (var b = new SolidBrush(petThinking.Length > 0 && !petFinished ? ink : muted))
4367
- {
4368
- if (petExpanded || isDetailed)
4369
- g.DrawString(TailWrapped(g, progress, fText, lineW, replyH, wrap), fText, b, new RectangleF(body.X + pad, ry, lineW, replyH), wrap);
4370
- else
4371
- {
4372
- string shown = petThinking.Length > 0 && !petFinished
4373
- ? "思考 · " + Tail(g, petThinking, fText, lineW - g.MeasureString("思考 · ", fText, 100000, fmt).Width, fmt)
4374
- : Tail(g, progress, fText, lineW, fmt);
4375
- SizeF size = g.MeasureString(shown.Length > 0 ? shown : " ", fText, 100000, fmt);
4376
- g.DrawString(shown, fText, b, body.X + pad, ry + (replyH - size.Height) / 2f, fmt);
4377
- }
4378
- }
4379
- }
4380
-
4381
- // Thinking and the step timeline.
4382
- float ly = ry + replyH;
4383
- if (showTimeline)
4384
- {
4385
- ly += 4 * s;
4386
- using (var pen = new Pen(edge, Math.Max(1f, s))) g.DrawLine(pen, body.X + pad, ly, body.Right - pad, ly);
4387
- ly += 5 * s;
4388
- int first = Math.Max(0, petSteps.Count - stepRows);
4389
- for (int i = first; i < petSteps.Count; i++)
4390
- {
4391
- bool current = i == petSteps.Count - 1 && !petFinished;
4392
- float cy = ly + 11 * s;
4393
- if (current)
4394
- {
4395
- using (var halo = new SolidBrush(Color.FromArgb(60, Accent))) g.FillEllipse(halo, body.X + pad, cy - 5 * s, 10 * s, 10 * s);
4396
- using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, body.X + pad + 2 * s, cy - 3 * s, 6 * s, 6 * s);
4397
- }
4398
- else using (var b = new SolidBrush(Color.FromArgb(46, 160, 67))) g.DrawString(glyphFont.Length > 0 ? "\uE73E" : "✓", fGlyph, b, new RectangleF(body.X + pad - 2 * s, ly, 14 * s, 22 * s), center);
4399
- string line = Tail(g, petSteps[i], fAct, lineW - 16 * s, fmt);
4400
- using (var b = new SolidBrush(current ? ink : muted)) g.DrawString(line, fAct, b, body.X + pad + 16 * s, ly + 3 * s, fmt);
4401
- ly += 22 * s;
4402
- }
4403
- }
4404
- else
4405
- {
4406
- string act;
4407
- if (petFinished) act = petSteps.Count > 0 ? "最后操作 · " + petSteps[petSteps.Count - 1] : "";
4408
- else if (isCompact) act = petSteps.Count > 0 ? petSteps[petSteps.Count - 1] : "准备操作…";
4409
- else
4410
- {
4411
- var parts = new List<string>();
4412
- for (int i = Math.Max(0, petSteps.Count - 4); i < petSteps.Count; i++) parts.Add(i < petSteps.Count - 1 ? "✓ " + petSteps[i] : petSteps[i]);
4413
- act = string.Join(" › ", parts);
4414
- }
4415
- if (!petFinished) using (var halo = new SolidBrush(Color.FromArgb(55, Accent))) g.FillEllipse(halo, body.X + pad - 2 * s, ly + 6 * s, 10 * s, 10 * s);
4416
- using (var brush = new SolidBrush(petFinished ? Color.FromArgb(46, 160, 67) : Accent)) g.FillEllipse(brush, body.X + pad, ly + 8 * s, 6 * s, 6 * s);
4417
- string shown = Tail(g, act, fAct, lineW - 14 * s, fmt);
4418
- using (var b = new SolidBrush(isCompact ? ink : muted)) g.DrawString(shown, fAct, b, body.X + pad + 14 * s, ly + 3 * s, fmt);
4419
- ly += 24 * s;
4420
- }
4421
-
4422
- // The instruction field: the card draws its frame and send button, a real text box sits on top.
4423
- if (input != null)
4424
- {
4425
- ly += 6 * s;
4426
- float sendD = 32 * s;
4427
- var fieldRect = new RectangleF(body.X + pad, ly, lineW - sendD - 8 * s, 34 * s);
4428
- using (var path = Rounded(fieldRect, 17 * s))
4429
- {
4430
- using (var brush = new SolidBrush(field)) g.FillPath(brush, path);
4431
- using (var pen = new Pen(Color.FromArgb(150, Accent), Math.Max(1f, 1.2f * s))) g.DrawPath(pen, path);
4432
- }
4433
- bool sendHover = hoveredBtn == "send";
4434
- bool sendPress = pressedBtn == "send";
4435
- var sendHit = new RectangleF(body.Right - pad - sendD, ly + (34 * s - sendD) / 2f, sendD, sendD);
4436
- var send = RectangleF.Inflate(sendHit, sendPress ? -0.8f * s : sendHover ? 1.1f * s : 0f, sendPress ? -0.8f * s : sendHover ? 1.1f * s : 0f);
4437
- if (sendHover) using (var halo = new SolidBrush(Color.FromArgb(65, Accent))) g.FillEllipse(halo, RectangleF.Inflate(send, 2.5f * s, 2.5f * s));
4438
- using (var brush = new SolidBrush(sendPress ? Color.FromArgb(190, 92, 62) : sendHover ? AccentHi : Accent)) g.FillEllipse(brush, send);
4439
- using (var b = new SolidBrush(Color.White)) g.DrawString(glyphFont.Length > 0 ? "\uE724" : "➤", fGlyph, b, send, center);
4440
- buttons.Add(new KeyValuePair<Rectangle, string>(Rectangle.Round(sendHit), "send"));
4441
- var boxRect = new Rectangle(x + (int)(fieldRect.X + 14 * s), y + (int)(fieldRect.Y + 3 * s), (int)(fieldRect.Width - 28 * s), (int)(fieldRect.Height - 6 * s));
4442
- if (boxRect != inputBounds) { inputBounds = boxRect; input.Place(boxRect); }
4443
- }
4444
-
4445
- pet.SetBitmap(bmp, new Rectangle(x, y, W, H), 255);
4446
- }
4447
- pet.KeepOnTop();
4448
- if (input != null) Native.SetWindowPos(input.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);
4449
- }
4450
-
4451
- static void RenderPill()
4452
- {
4453
- if (petMode) { RenderPet(); return; }
4454
- if (pill == null) return;
4455
- // The pill lives on the primary display (or the first one).
4456
- Rectangle work = Rectangle.Empty; float scale = 1f;
4457
- foreach (Dictionary<string, object> d in Screen2.Displays())
4458
- {
4459
- if (work.IsEmpty || (bool)d["primary"])
4460
- {
4461
- work = new Rectangle((int)d["workX"], (int)d["workY"], (int)d["workWidth"], (int)d["workHeight"]);
4462
- scale = (int)d["dpi"] / 96f;
4463
- }
4464
- }
4465
- string main, sub; string[] actions, captions;
4466
- Content(out main, out sub, out actions, out captions);
4467
- rendered = Key();
4468
- if (sub.Length > 48) sub = sub.Substring(0, 47) + "…";
4469
-
4470
- float px = 1.333f * scale; // points -> physical pixels
4471
- using (var fMain = new Font("Microsoft YaHei UI", 10f * px, FontStyle.Bold, GraphicsUnit.Pixel))
4472
- using (var fSub = new Font("Microsoft YaHei UI", 9f * px, FontStyle.Regular, GraphicsUnit.Pixel))
4473
- using (var fBtn = new Font("Microsoft YaHei UI", 9f * px, FontStyle.Bold, GraphicsUnit.Pixel))
4474
- using (var measureBmp = new Bitmap(1, 1))
4475
- using (var mg = Graphics.FromImage(measureBmp))
4476
- {
4477
- mg.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
4478
- var fmt = StringFormat.GenericTypographic;
4479
- fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
4480
- SizeF mainSize = mg.MeasureString(main, fMain, 10000, fmt);
4481
- SizeF subSize = mg.MeasureString(sub, fSub, 10000, fmt);
4482
- float pad = 14 * scale, gap = 11 * scale, iconSize = 24 * scale;
4483
- float height = 40 * scale, btnH = 26 * scale, btnGap = 6 * scale;
4484
- var btnSizes = new SizeF[captions.Length];
4485
- float btnsW = 0;
4486
- for (int i = 0; i < captions.Length; i++)
4487
- {
4488
- btnSizes[i] = mg.MeasureString(captions[i], fBtn, 10000, fmt);
4489
- btnsW += btnSizes[i].Width + 22 * scale + (i > 0 ? btnGap : 0);
4490
- }
4491
- float width = pad + iconSize + gap + mainSize.Width + gap + 1 * scale + gap + subSize.Width + gap + btnsW + (pad - 7 * scale);
4492
- int W = (int)Math.Ceiling(width), H = (int)Math.Ceiling(height);
4493
- int x = work.X + (work.Width - W) / 2;
4494
- int y = pillAtBottom ? work.Bottom - H - (int)(18 * scale) : work.Y + (int)(14 * scale);
4495
-
4496
- using (var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb))
4497
- using (var g = Graphics.FromImage(bmp))
4498
- {
4499
- g.Clear(Color.Transparent);
4500
- g.SmoothingMode = SmoothingMode.AntiAlias;
4501
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
4502
- g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
4503
- var body = new RectangleF(0.5f, 0.5f, W - 1, H - 1);
4504
- using (var path = Rounded(body, (H - 1) / 2f))
4505
- {
4506
- using (var brush = new SolidBrush(Color.FromArgb(242, 31, 30, 29))) g.FillPath(brush, path);
4507
- using (var pen = new Pen(Color.FromArgb(200, Accent), Math.Max(1f, 1.2f * scale))) g.DrawPath(pen, path);
4508
- }
4509
- var iconRect = new RectangleF(pad, (H - iconSize) / 2f, iconSize, iconSize);
4510
- if (icon != null) g.DrawImage(icon, iconRect);
4511
- else using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, RectangleF.Inflate(iconRect, -5 * scale, -5 * scale));
4512
- float tx = pad + iconSize + gap;
4513
- using (var b = new SolidBrush(Color.FromArgb(250, 250, 249))) g.DrawString(main, fMain, b, tx, (H - mainSize.Height) / 2f, fmt);
4514
- tx += mainSize.Width + gap;
4515
- 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);
4516
- tx += 1 * scale + gap;
4517
- using (var b = new SolidBrush(Color.FromArgb(175, 172, 168))) g.DrawString(sub, fSub, b, tx, (H - subSize.Height) / 2f, fmt);
4518
- tx += subSize.Width + gap;
4519
- buttons.Clear();
4520
- for (int i = 0; i < captions.Length; i++)
4521
- {
4522
- float bw = btnSizes[i].Width + 22 * scale;
4523
- var btn = new RectangleF(tx, (H - btnH) / 2f, bw, btnH);
4524
- bool primary = i == 0;
4525
- using (var path = Rounded(btn, btnH / 2f))
4526
- using (var brush = new SolidBrush(primary ? Accent : Color.FromArgb(70, 68, 66))) g.FillPath(brush, path);
4527
- using (var b = new SolidBrush(Color.White)) g.DrawString(captions[i], fBtn, b, btn.X + (bw - btnSizes[i].Width) / 2f, btn.Y + (btnH - btnSizes[i].Height) / 2f, fmt);
4528
- buttons.Add(new KeyValuePair<Rectangle, string>(Rectangle.Round(btn), actions[i]));
4529
- tx += bw + btnGap;
4530
- }
4531
- pill.SetBitmap(bmp, new Rectangle(x, y, W, H), 255);
4532
- }
4533
- lock (RectLock) pillRect = new Rectangle(x, y, W, H);
4534
- }
4535
- pill.KeepOnTop();
4536
- }
4537
-
4538
- static void InstallHook()
4539
- {
4540
- if (hook == IntPtr.Zero)
4541
- {
4542
- hookProc = HookCallback;
4543
- hook = Native.SetWindowsHookEx(13, hookProc, Native.GetModuleHandle(null), 0);
4544
- }
4545
- if (mouseHook == IntPtr.Zero)
4546
- {
4547
- mouseHookProc = MouseHookCallback;
4548
- mouseHook = Native.SetWindowsHookEx(14, mouseHookProc, Native.GetModuleHandle(null), 0);
4549
- }
4550
- }
4551
-
4552
- static void RemoveHook()
4553
- {
4554
- if (hook != IntPtr.Zero)
4555
- {
4556
- Native.UnhookWindowsHookEx(hook);
4557
- hook = IntPtr.Zero;
4558
- }
4559
- if (mouseHook != IntPtr.Zero)
4560
- {
4561
- Native.UnhookWindowsHookEx(mouseHook);
4562
- mouseHook = IntPtr.Zero;
4563
- }
4564
- }
4565
-
4566
- static bool IsOnOwnUi(int x, int y)
4567
- {
4568
- lock (RectLock)
4569
- {
4570
- if (!pillRect.IsEmpty && pillRect.Contains(x, y)) return true;
4571
- if (pet != null && !pet.Physical.IsEmpty && pet.Physical.Contains(x, y)) return true;
4572
- if (!inputBounds.IsEmpty && inputBounds.Contains(x, y)) return true;
4573
- }
4574
- IntPtr card = CardLayer.Hwnd;
4575
- if (card != IntPtr.Zero && Native.IsWindow(card))
4576
- {
4577
- Native.RECT rc;
4578
- if (Native.GetWindowRect(card, out rc) && x >= rc.Left && x < rc.Right && y >= rc.Top && y < rc.Bottom)
4579
- return true;
4580
- }
4581
- return false;
4582
- }
4583
-
4584
- static void RecordUserMouseAsync(string kind, string button, string direction, int x, int y)
4585
- {
4586
- ThreadPool.QueueUserWorkItem(delegate
4587
- {
4588
- try
4589
- {
4590
- var win = Windows.At(x, y);
4591
- string exe = win.ContainsKey("exe") ? Convert.ToString(win["exe"]) ?? "" : "";
4592
- string title = win.ContainsKey("title") ? Convert.ToString(win["title"]) ?? "" : "";
4593
- string exeLower = exe.ToLowerInvariant();
4594
- // Clicking the DSH chat window itself is the user reading/chatting, not taking over target apps.
4595
- if (exeLower == "cu-helper.exe" || exeLower == "deepseek harness.exe") return;
4596
- string role = "", name = "";
4597
- bool isPassword = false;
4598
- if (kind == "click" || kind == "double_click")
4599
- Uia.DescribeAtPoint(x, y, out role, out name, out isPassword);
4600
- var data = new Dictionary<string, object>();
4601
- data["kind"] = kind;
4602
- if (!string.IsNullOrEmpty(button)) data["button"] = button;
4603
- if (!string.IsNullOrEmpty(direction)) data["direction"] = direction;
4604
- data["x"] = x;
4605
- data["y"] = y;
4606
- if (exe.Length > 0) data["exe"] = exe;
4607
- if (title.Length > 0) data["title"] = title.Length > 80 ? title.Substring(0, 80) + "…" : title;
4608
- if (role.Length > 0) data["role"] = role;
4609
- if (name.Length > 0) data["name"] = name;
4610
- if (isPassword) data["password"] = true;
4611
- Program.EmitDataEvent("user_action", data);
4612
- }
4613
- catch (Exception) { }
4614
- });
4615
- }
4616
-
4617
- static void RecordUserKeyAsync(int count)
4618
- {
4619
- ThreadPool.QueueUserWorkItem(delegate
4620
- {
4621
- try
4622
- {
4623
- IntPtr fg = Native.GetForegroundWindow();
4624
- var win = Windows.Describe(fg);
4625
- string exe = win.ContainsKey("exe") ? Convert.ToString(win["exe"]) ?? "" : "";
4626
- string title = win.ContainsKey("title") ? Convert.ToString(win["title"]) ?? "" : "";
4627
- string exeLower = exe.ToLowerInvariant();
4628
- if (exeLower == "cu-helper.exe" || exeLower == "deepseek harness.exe") return;
4629
- string role, name;
4630
- bool isPassword;
4631
- Uia.DescribeFocused(out role, out name, out isPassword);
4632
- var data = new Dictionary<string, object>();
4633
- data["kind"] = "type";
4634
- data["keys"] = count;
4635
- if (exe.Length > 0) data["exe"] = exe;
4636
- if (title.Length > 0) data["title"] = title.Length > 80 ? title.Substring(0, 80) + "…" : title;
4637
- if (role.Length > 0) data["role"] = role;
4638
- if (name.Length > 0) data["name"] = name;
4639
- if (isPassword) data["password"] = true;
4640
- Program.EmitDataEvent("user_action", data);
4641
- }
4642
- catch (Exception) { }
4643
- });
4644
- }
4645
-
4646
- static IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
4647
- {
4648
- if (nCode >= 0 && visible)
4649
- {
4650
- int msg = wParam.ToInt32();
4651
- // Deliberately ignore WM_MOUSEMOVE (0x0200): nudging the mouse never triggers takeover.
4652
- bool isClick = msg == 0x0201 || msg == 0x0204 || msg == 0x0207;
4653
- bool isWheel = msg == 0x020A || msg == 0x020E;
4654
- if (isClick || isWheel)
4655
- {
4656
- var ms = (Native.MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.MSLLHOOKSTRUCT));
4657
- // Ignore synthetic clicks injected by our own SendInput (LLMHF_INJECTED = 0x01, lower IL = 0x02).
4658
- if ((ms.flags & 0x03) == 0 && ms.dwExtraInfo != Native.Marker && !IsOnOwnUi(ms.pt.X, ms.pt.Y))
4659
- {
4660
- int now = Environment.TickCount;
4661
- lastTyping = now;
4662
- if (isClick)
4663
- {
4664
- string button = msg == 0x0204 ? "right" : msg == 0x0207 ? "middle" : "left";
4665
- string kind = "click";
4666
- lock (UserActionLock)
4667
- {
4668
- if (button == "left" && unchecked(now - lastClickTick) <= 500
4669
- && Math.Abs(ms.pt.X - lastClickX) <= 6 && Math.Abs(ms.pt.Y - lastClickY) <= 6)
4670
- {
4671
- kind = "double_click";
4672
- lastClickTick = int.MinValue / 2;
4673
- }
4674
- else
4675
- {
4676
- lastClickTick = now;
4677
- lastClickX = ms.pt.X;
4678
- lastClickY = ms.pt.Y;
4679
- }
4680
- }
4681
- RecordUserMouseAsync(kind, button, "", ms.pt.X, ms.pt.Y);
4682
- }
4683
- else
4684
- {
4685
- bool shouldEmit = false;
4686
- lock (UserActionLock)
4687
- {
4688
- if (unchecked(now - lastScrollTick) > 600) { lastScrollTick = now; shouldEmit = true; }
4689
- }
4690
- if (shouldEmit)
4691
- {
4692
- short delta = (short)((ms.mouseData >> 16) & 0xFFFF);
4693
- string dir = msg == 0x020E ? (delta >= 0 ? "right" : "left") : (delta >= 0 ? "up" : "down");
4694
- RecordUserMouseAsync("scroll", "", dir, ms.pt.X, ms.pt.Y);
4695
- }
4696
- }
4697
- }
4698
- }
4699
- }
4700
- return Native.CallNextHookEx(mouseHook, nCode, wParam, lParam);
4701
- }
4702
-
4703
- static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
4704
- {
4705
- if (nCode >= 0 && visible)
4706
- {
4707
- int msg = wParam.ToInt32();
4708
- var kb = (Native.KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.KBDLLHOOKSTRUCT));
4709
- // Only physical keys count: our own SendInput sets LLKHF_INJECTED (0x10).
4710
- if ((kb.flags & 0x10) == 0 && !(InputHwnd != IntPtr.Zero && Native.GetForegroundWindow() == InputHwnd))
4711
- {
4712
- bool down = msg == 0x100 || msg == 0x104;
4713
- if (kb.vkCode == 0x1B)
4714
- {
4715
- // Esc toggles pause and is swallowed, so the focused app
4716
- // (DeepSeek Harness included) never turns it into "stop".
4717
- if (down) invoker.BeginInvoke((MethodInvoker)delegate { Press(paused ? "resume" : "pause"); });
4718
- return new IntPtr(1);
4719
- }
4720
- // Modifier-only presses (Shift to switch the IME, Ctrl, Alt, Win)
4721
- // and synthetic packets are not typing.
4722
- int vk = (int)kb.vkCode;
4723
- bool modifier = vk == 0x10 || vk == 0x11 || vk == 0x12 || (vk >= 0xA0 && vk <= 0xA5) || vk == 0x5B || vk == 0x5C || vk == 0x14 || vk == 0xE7 || vk == 0xFF;
4724
- if (down && !modifier)
4725
- {
4726
- // The user is typing: the host waits. Mouse movement is
4727
- // deliberately ignored (too easy to nudge).
4728
- int now = Environment.TickCount;
4729
- lastTyping = now;
4730
- if (unchecked(now - lastEmit) > 250) { lastEmit = now; Program.EmitEvent("user_input", "vk=0x" + vk.ToString("X2")); }
4731
- int emitCount = 0;
4732
- lock (UserActionLock)
4733
- {
4734
- keyBurstCount++;
4735
- if (unchecked(now - lastKeySummaryTick) > 900)
4736
- {
4737
- lastKeySummaryTick = now;
4738
- emitCount = keyBurstCount;
4739
- keyBurstCount = 0;
4740
- }
4741
- }
4742
- if (emitCount > 0) RecordUserKeyAsync(emitCount);
4743
- }
4744
- }
4745
- }
4746
- return Native.CallNextHookEx(hook, nCode, wParam, lParam);
4747
- }
4748
- }
4749
- }