@copylee/dsh-computer-use 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1685 @@
1
+ // Orange border glow, Codex cursor indicator, 3-size tactile Pet progress card, CardLayer, and low-level hooks (C# 5).
2
+
3
+ using System;
4
+ using System.Collections;
5
+ using System.Collections.Generic;
6
+ using System.Diagnostics;
7
+ using System.Drawing;
8
+ using System.Drawing.Drawing2D;
9
+ using System.Drawing.Imaging;
10
+ using System.Drawing.Text;
11
+ using System.IO;
12
+ using System.Reflection;
13
+ using System.Runtime.InteropServices;
14
+ using System.Text;
15
+ using System.Threading;
16
+ using System.Web.Script.Serialization;
17
+ using System.Windows.Automation;
18
+ using System.Windows.Forms;
19
+ using Microsoft.Win32;
20
+
21
+ namespace DshComputerUse
22
+ {
23
+ /**
24
+ * The DeepSeek Harness card floats on top for the user only. To the agent
25
+ * it is transparent: while a screenshot is taken the card is made fully
26
+ * transparent for a few milliseconds (another process's window cannot be
27
+ * excluded from capture), and its pointer input passes through.
28
+ */
29
+ internal static class CardLayer
30
+ {
31
+ public static IntPtr Hwnd = IntPtr.Zero;
32
+ static int originalEx;
33
+ /** Resting alpha of the card (see-through); it turns opaque while the pointer rests on it. */
34
+ static byte alpha = 255;
35
+ static bool hot;
36
+ static int hiding;
37
+ static DateTime enteredAt = DateTime.MaxValue;
38
+ static System.Threading.Timer hover;
39
+ static readonly object Gate = new object();
40
+
41
+ public static void SetOpacity(int percent)
42
+ {
43
+ lock (Gate)
44
+ {
45
+ alpha = (byte)Math.Max(64, Math.Min(255, (int)Math.Round(Math.Max(25, Math.Min(100, percent)) * 2.55)));
46
+ if (alpha < 255 && hover == null) hover = new System.Threading.Timer(delegate { Track(); }, null, 150, 150);
47
+ Apply();
48
+ }
49
+ }
50
+
51
+ static byte Current() { return hot ? (byte)255 : alpha; }
52
+
53
+ static void Apply()
54
+ {
55
+ if (hiding == 0 && Hwnd != IntPtr.Zero && Native.IsWindow(Hwnd)) Native.SetLayeredWindowAttributes(Hwnd, 0, Current(), 2);
56
+ }
57
+
58
+ /** Opaque once the pointer has rested on the card for a moment (the user wants to read or click it). */
59
+ static void Track()
60
+ {
61
+ lock (Gate)
62
+ {
63
+ bool inside = false;
64
+ if (Live() && alpha < 255)
65
+ {
66
+ Native.POINT p; Native.GetCursorPos(out p);
67
+ inside = Frame(Hwnd).Contains(p.X, p.Y);
68
+ }
69
+ if (!inside) { enteredAt = DateTime.MaxValue; if (hot) { hot = false; Apply(); } return; }
70
+ if (enteredAt == DateTime.MaxValue) enteredAt = DateTime.UtcNow;
71
+ if (!hot && (DateTime.UtcNow - enteredAt).TotalMilliseconds >= 300) { hot = true; Apply(); }
72
+ }
73
+ }
74
+
75
+ static bool Live()
76
+ {
77
+ return Hwnd != IntPtr.Zero && Native.IsWindow(Hwnd) && Native.IsWindowVisible(Hwnd) && !Native.IsIconic(Hwnd);
78
+ }
79
+
80
+ public static uint Pid()
81
+ {
82
+ if (!Live()) return 0;
83
+ uint pid; Native.GetWindowThreadProcessId(Hwnd, out pid);
84
+ return pid;
85
+ }
86
+
87
+ /** The card becomes a (fully opaque) layered window so its alpha can be dropped instantly. */
88
+ public static void Attach(IntPtr hwnd)
89
+ {
90
+ if (Hwnd == hwnd) return;
91
+ Detach();
92
+ Hwnd = hwnd;
93
+ originalEx = Native.GetWindowLong(hwnd, -20);
94
+ Native.SetWindowLong(hwnd, -20, originalEx | 0x80000);
95
+ lock (Gate) { hot = false; enteredAt = DateTime.MaxValue; Native.SetLayeredWindowAttributes(hwnd, 0, Current(), 2); }
96
+ }
97
+
98
+ public static void Detach()
99
+ {
100
+ var hwnd = Hwnd;
101
+ Hwnd = IntPtr.Zero;
102
+ lock (Gate) {
103
+ if (hwnd != IntPtr.Zero && Native.IsWindow(hwnd)) Native.SetWindowLong(hwnd, -20, originalEx);
104
+ }
105
+ }
106
+
107
+ public static Rectangle Frame(IntPtr hwnd)
108
+ {
109
+ Native.RECT rc;
110
+ if (Native.DwmGetWindowAttribute(hwnd, 9, out rc, Marshal.SizeOf(typeof(Native.RECT))) != 0) Native.GetWindowRect(hwnd, out rc);
111
+ return new Rectangle(rc.Left, rc.Top, rc.Right - rc.Left, rc.Bottom - rc.Top);
112
+ }
113
+
114
+ /** g draws a bitmap whose (0, 0) is screen (ox, oy): fill the card area with a constant. */
115
+ public static void Blank(Graphics g, int ox, int oy)
116
+ {
117
+ if (!Live()) return;
118
+ var r = Frame(Hwnd);
119
+ r.Inflate(32, 32); // its drop shadow too (wide at 200% scaling)
120
+ g.FillRectangle(Brushes.Black, r.X - ox, r.Y - oy, r.Width, r.Height);
121
+ }
122
+
123
+ /** Is the card visible over (any part of) this screen rectangle? */
124
+ public static bool Covers(Rectangle area)
125
+ {
126
+ if (!Live()) return false;
127
+ var r = Frame(Hwnd);
128
+ r.Inflate(32, 32);
129
+ return r.IntersectsWith(area);
130
+ }
131
+
132
+ /** Make the card invisible while a capture of `area` runs (dispose to show it again). */
133
+ public static IDisposable Hide(Rectangle area)
134
+ {
135
+ if (!Live()) return new Hidden(IntPtr.Zero);
136
+ var r = Frame(Hwnd);
137
+ r.Inflate(32, 32);
138
+ return new Hidden(r.IntersectsWith(area) ? Hwnd : IntPtr.Zero);
139
+ }
140
+
141
+ // Chromium cards can swallow SendInput even after WS_EX_TRANSPARENT has
142
+ // changed the hit test. Hide the card through dispatch only when it covers
143
+ // the click, keeping its position, z-order and the work window's focus.
144
+ public static IDisposable UncoverClick(Native.POINT point)
145
+ {
146
+ var hwnd = Hwnd;
147
+ if (!Live()) return null;
148
+ Native.RECT rect;
149
+ if (!Native.GetWindowRect(hwnd, out rect)) throw new Exception("Cannot verify the control card bounds");
150
+ if (point.X < rect.Left || point.X >= rect.Right || point.Y < rect.Top || point.Y >= rect.Bottom) return null;
151
+ if (Native.GetForegroundWindow() == hwnd) throw new Exception("The control card is focused. Focus the work window before clicking.");
152
+ object expected;
153
+ if (!Windows.At(point.X, point.Y).TryGetValue("hwnd", out expected))
154
+ throw new Exception("No work window found under the control card");
155
+ var uncovered = new Uncovered(hwnd);
156
+ try
157
+ {
158
+ object hit;
159
+ if (!Windows.At(point.X, point.Y).TryGetValue("hwnd", out hit) || !Object.Equals(expected, hit))
160
+ throw new Exception("The window under the control card changed. Look again before clicking.");
161
+ return uncovered;
162
+ }
163
+ catch
164
+ {
165
+ uncovered.Dispose();
166
+ throw;
167
+ }
168
+ }
169
+
170
+ sealed class Uncovered : IDisposable
171
+ {
172
+ // NOSIZE | NOMOVE | NOZORDER | NOACTIVATE | NOOWNERZORDER.
173
+ const uint PreservePlacement = 0x0217;
174
+ readonly IntPtr hwnd;
175
+
176
+ public Uncovered(IntPtr hwnd)
177
+ {
178
+ this.hwnd = hwnd;
179
+ if (!Native.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, PreservePlacement | 0x0080)
180
+ || Native.IsWindowVisible(hwnd))
181
+ throw new Exception("Cannot hide the control card for the click");
182
+ }
183
+
184
+ public void Dispose()
185
+ {
186
+ if (Hwnd == hwnd && Native.IsWindow(hwnd)
187
+ && !Native.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, PreservePlacement | 0x0040))
188
+ Native.ShowWindow(hwnd, 4); // SW_SHOWNOACTIVATE
189
+ }
190
+ }
191
+
192
+ sealed class Hidden : IDisposable
193
+ {
194
+ readonly IntPtr hwnd;
195
+ public Hidden(IntPtr hwnd)
196
+ {
197
+ this.hwnd = hwnd;
198
+ if (hwnd == IntPtr.Zero) return;
199
+ lock (Gate) { hiding++; Native.SetLayeredWindowAttributes(hwnd, 0, 0, 2); }
200
+ }
201
+ public void Dispose()
202
+ {
203
+ if (hwnd == IntPtr.Zero) return;
204
+ lock (Gate)
205
+ {
206
+ hiding--;
207
+ if (hiding == 0 && Native.IsWindow(hwnd)) Native.SetLayeredWindowAttributes(hwnd, 0, Current(), 2);
208
+ }
209
+ }
210
+ }
211
+ }
212
+
213
+
214
+ // ---------------------------------------------------------------- overlay
215
+
216
+ internal class LayeredForm : Form
217
+ {
218
+ readonly bool clickThrough;
219
+ public Rectangle Physical;
220
+
221
+ public LayeredForm(bool clickThrough)
222
+ {
223
+ this.clickThrough = clickThrough;
224
+ FormBorderStyle = FormBorderStyle.None;
225
+ ShowInTaskbar = false;
226
+ StartPosition = FormStartPosition.Manual;
227
+ AutoScaleMode = AutoScaleMode.None;
228
+ TopMost = true;
229
+ }
230
+
231
+ protected override bool ShowWithoutActivation { get { return true; } }
232
+
233
+ protected override CreateParams CreateParams
234
+ {
235
+ get
236
+ {
237
+ var cp = base.CreateParams;
238
+ cp.ExStyle |= 0x80000 | 0x80 | 0x8000000 | 0x8; // LAYERED | TOOLWINDOW | NOACTIVATE | TOPMOST
239
+ if (clickThrough) cp.ExStyle |= 0x20; // TRANSPARENT
240
+ return cp;
241
+ }
242
+ }
243
+
244
+ protected override void OnHandleCreated(EventArgs e)
245
+ {
246
+ base.OnHandleCreated(e);
247
+ // Keep the overlay out of every screenshot, including our own.
248
+ if (Overlay.ExcludeFromCapture) { try { Native.SetWindowDisplayAffinity(Handle, 0x11); } catch (Exception) { } }
249
+ }
250
+
251
+ protected override void WndProc(ref Message m)
252
+ {
253
+ if (m.Msg == 0x21) { m.Result = new IntPtr(3); return; } // WM_MOUSEACTIVATE -> MA_NOACTIVATE
254
+ base.WndProc(ref m);
255
+ }
256
+
257
+ public void SetBitmap(Bitmap bmp, Rectangle bounds, byte alpha)
258
+ {
259
+ Physical = bounds;
260
+ IntPtr screenDc = Native.GetDC(IntPtr.Zero);
261
+ IntPtr memDc = Native.CreateCompatibleDC(screenDc);
262
+ IntPtr hBitmap = IntPtr.Zero, old = IntPtr.Zero;
263
+ try
264
+ {
265
+ hBitmap = bmp.GetHbitmap(Color.FromArgb(0));
266
+ old = Native.SelectObject(memDc, hBitmap);
267
+ var size = new Native.SIZE(bmp.Width, bmp.Height);
268
+ var src = new Native.POINT(0, 0);
269
+ var dst = new Native.POINT(bounds.X, bounds.Y);
270
+ var blend = new Native.BLENDFUNCTION(); blend.BlendOp = 0; blend.SourceConstantAlpha = alpha; blend.AlphaFormat = 1;
271
+ Native.UpdateLayeredWindow(Handle, screenDc, ref dst, ref size, memDc, ref src, 0, ref blend, 2);
272
+ }
273
+ finally
274
+ {
275
+ Native.ReleaseDC(IntPtr.Zero, screenDc);
276
+ if (hBitmap != IntPtr.Zero) { Native.SelectObject(memDc, old); Native.DeleteObject(hBitmap); }
277
+ Native.DeleteDC(memDc);
278
+ }
279
+ }
280
+
281
+ public void SetAlpha(byte alpha)
282
+ {
283
+ var blend = new Native.BLENDFUNCTION(); blend.BlendOp = 0; blend.SourceConstantAlpha = alpha; blend.AlphaFormat = 1;
284
+ Native.UpdateLayeredWindow(Handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0, ref blend, 2);
285
+ }
286
+
287
+ public void KeepOnTop()
288
+ {
289
+ Native.SetWindowPos(Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010 | 0x0200); // NOSIZE|NOMOVE|NOACTIVATE|NOOWNERZORDER
290
+ }
291
+
292
+ public void SetCapturable(bool capturable)
293
+ {
294
+ try { Native.SetWindowDisplayAffinity(Handle, capturable ? 0u : 0x11u); } catch (Exception) { }
295
+ }
296
+ }
297
+
298
+ /** The progress card's instruction box: a small focusable window laid over the card's field. */
299
+ internal class InputBox : Form
300
+ {
301
+ public readonly TextBox Box;
302
+ public event Action<string> Submitted;
303
+ public event Action Cancelled;
304
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr SendMessage(IntPtr hwnd, int msg, IntPtr w, string l);
305
+
306
+ public InputBox(Font font, Color back, Color fore, string cue)
307
+ {
308
+ FormBorderStyle = FormBorderStyle.None;
309
+ ShowInTaskbar = false;
310
+ StartPosition = FormStartPosition.Manual;
311
+ AutoScaleMode = AutoScaleMode.None;
312
+ TopMost = true;
313
+ BackColor = back;
314
+ Box = new TextBox();
315
+ Box.BorderStyle = BorderStyle.None;
316
+ Box.Font = font;
317
+ Box.BackColor = back;
318
+ Box.ForeColor = fore;
319
+ Controls.Add(Box);
320
+ Box.HandleCreated += delegate { SendMessage(Box.Handle, 0x1501, new IntPtr(1), cue); }; // EM_SETCUEBANNER
321
+ Box.KeyDown += delegate (object s, KeyEventArgs e)
322
+ {
323
+ if (e.KeyCode == System.Windows.Forms.Keys.Enter && !e.Shift) { e.SuppressKeyPress = true; if (Submitted != null) Submitted(Box.Text); }
324
+ else if (e.KeyCode == System.Windows.Forms.Keys.Escape) { e.SuppressKeyPress = true; if (Cancelled != null) Cancelled(); }
325
+ };
326
+ }
327
+
328
+ protected override CreateParams CreateParams
329
+ {
330
+ get { var cp = base.CreateParams; cp.ExStyle |= 0x80 | 0x8; return cp; } // TOOLWINDOW | TOPMOST
331
+ }
332
+
333
+ protected override void OnHandleCreated(EventArgs e)
334
+ {
335
+ base.OnHandleCreated(e);
336
+ if (Overlay.ExcludeFromCapture) { try { Native.SetWindowDisplayAffinity(Handle, 0x11); } catch (Exception) { } }
337
+ }
338
+
339
+ public void Place(Rectangle r)
340
+ {
341
+ Bounds = r;
342
+ Box.Width = r.Width;
343
+ Box.Location = new Point(0, Math.Max(0, (r.Height - Box.PreferredHeight) / 2));
344
+ }
345
+ }
346
+
347
+ internal static class Overlay
348
+ {
349
+ static readonly Color Accent = Color.FromArgb(217, 119, 87); // #D97757
350
+ static readonly Color AccentHi = Color.FromArgb(240, 160, 106); // #F0A06A
351
+
352
+ public static volatile bool ExcludeFromCapture = true;
353
+ static Thread thread;
354
+ static Control invoker;
355
+ static readonly List<LayeredForm> glows = new List<LayeredForm>();
356
+ static LayeredForm pill;
357
+ static Rectangle pillRect;
358
+ static readonly List<KeyValuePair<Rectangle, string>> buttons = new List<KeyValuePair<Rectangle, string>>();
359
+ static bool pillAtBottom;
360
+ static string label = "", status = "", rendered = "";
361
+ static Image icon, iconLight;
362
+ static string iconPath = "", iconLightPath = "";
363
+ static int idleMs = 1500;
364
+ static System.Windows.Forms.Timer timer;
365
+ static DateTime shownAt;
366
+ static IntPtr hook = IntPtr.Zero;
367
+ static Native.LowLevelKeyboardProc hookProc;
368
+ static IntPtr mouseHook = IntPtr.Zero;
369
+ static Native.LowLevelMouseProc mouseHookProc;
370
+ static readonly object UserActionLock = new object();
371
+ static int lastClickTick = int.MinValue / 2;
372
+ static int lastClickX, lastClickY;
373
+ static int lastScrollTick = int.MinValue / 2;
374
+ static int lastKeySummaryTick = int.MinValue / 2;
375
+ static int keyBurstCount;
376
+ static volatile bool visible;
377
+ static volatile bool paused;
378
+ static volatile bool clickTargetEnabled = true;
379
+ static LayeredForm markForm;
380
+ static DateTime markExpiresAt = DateTime.MinValue;
381
+ static bool markActive;
382
+ static int lastTyping = int.MinValue / 2;
383
+ static int lastEmit;
384
+ static readonly object RectLock = new object();
385
+
386
+ // The progress card ("pet"): replaces the pill while DeepSeek Harness is minimized.
387
+ static bool petMode;
388
+ static string petSize = "standard";
389
+ static string hoveredBtn = "";
390
+ static string pressedBtn = "";
391
+ static LayeredForm pet;
392
+ public static volatile IntPtr PetHwnd = IntPtr.Zero;
393
+ static string petThinking = "";
394
+ static List<string> petSteps = new List<string>();
395
+ /** Bottom-right corner of the card body; the card grows upward when expanded. */
396
+ static Point petAnchor = Point.Empty;
397
+ static int petShadow;
398
+ static Rectangle petBody;
399
+ static byte petAlpha = 230;
400
+ static bool petDragged, petExpanded, petFinished;
401
+ static DateTime finishedAt;
402
+ static int finishHoldMs = 4000;
403
+ // The instruction box under the card (a real, focusable window over the card's field).
404
+ static InputBox input;
405
+ public static volatile IntPtr InputHwnd = IntPtr.Zero;
406
+ /** The window that had the focus before the instruction box opened. */
407
+ public static volatile IntPtr InputReturnsTo = IntPtr.Zero;
408
+ static bool pausedByInput;
409
+ static IntPtr beforeInput = IntPtr.Zero;
410
+ static Rectangle inputBounds;
411
+ static string iconFont;
412
+
413
+ static void Ensure()
414
+ {
415
+ if (thread != null) return;
416
+ var ready = new ManualResetEvent(false);
417
+ thread = new Thread(delegate ()
418
+ {
419
+ invoker = new Control();
420
+ var force = invoker.Handle;
421
+ timer = new System.Windows.Forms.Timer();
422
+ timer.Interval = 40;
423
+ timer.Tick += delegate { Tick(); };
424
+ ready.Set();
425
+ Application.Run();
426
+ });
427
+ thread.IsBackground = true;
428
+ thread.SetApartmentState(ApartmentState.STA);
429
+ thread.Start();
430
+ ready.WaitOne();
431
+ }
432
+
433
+ static void Ui(MethodInvoker action) { invoker.Invoke(action); }
434
+
435
+ public static void Show(Dictionary<string, object> r)
436
+ {
437
+ Ensure();
438
+ Ui(delegate
439
+ {
440
+ label = Args.Str(r, "label", "");
441
+ status = Args.Str(r, "status", "");
442
+ idleMs = Args.Int(r, "idleMs", 1500);
443
+ string path = Args.Str(r, "icon", "");
444
+ string light = Args.Str(r, "iconLight", "");
445
+ if (light != iconLightPath)
446
+ {
447
+ iconLightPath = light;
448
+ if (iconLight != null) { iconLight.Dispose(); iconLight = null; }
449
+ try
450
+ {
451
+ if (light.Length > 0 && File.Exists(light))
452
+ using (var raw = Image.FromFile(light)) iconLight = new Bitmap(raw);
453
+ }
454
+ catch (Exception) { iconLight = null; }
455
+ }
456
+ if (path != iconPath)
457
+ {
458
+ iconPath = path;
459
+ if (icon != null) { icon.Dispose(); icon = null; }
460
+ try
461
+ {
462
+ if (path.Length > 0 && File.Exists(path))
463
+ using (var raw = Image.FromFile(path)) icon = new Bitmap(raw);
464
+ }
465
+ catch (Exception) { icon = null; }
466
+ }
467
+ petAlpha = (byte)Math.Max(90, Math.Min(255, Args.Int(r, "petOpacity", 90) * 255 / 100));
468
+ string reqSize = Args.Str(r, "petSize", "");
469
+ if (reqSize == "compact" || reqSize == "standard" || reqSize == "detailed") petSize = reqSize;
470
+ clickTargetEnabled = Args.Bool(r, "glow", true);
471
+ if (visible && !petFinished) { RenderPill(); return; }
472
+ if (visible) HideCore(); // the previous run's "done" card is still up
473
+ petMode = Args.Bool(r, "pet", false);
474
+ hoveredBtn = "";
475
+ pressedBtn = "";
476
+ petThinking = Args.Str(r, "thinking", "");
477
+ petSteps = new List<string>();
478
+ if (status.Length > 0) petSteps.Add(status);
479
+ pillAtBottom = false;
480
+ paused = false;
481
+ foreach (var g in glows) g.Close();
482
+ glows.Clear();
483
+ if (Args.Bool(r, "glow", true))
484
+ {
485
+ foreach (Dictionary<string, object> d in Screen2.Displays())
486
+ {
487
+ var bounds = new Rectangle((int)d["x"], (int)d["y"], (int)d["width"], (int)d["height"]);
488
+ var form = new LayeredForm(true);
489
+ form.Show();
490
+ using (var bmp = DrawGlow(bounds.Width, bounds.Height, (int)d["dpi"] / 96f)) form.SetBitmap(bmp, bounds, 255);
491
+ glows.Add(form);
492
+ }
493
+ }
494
+ if (petMode)
495
+ {
496
+ if (pet == null)
497
+ {
498
+ pet = new LayeredForm(false);
499
+ pet.MouseMove += delegate (object s, MouseEventArgs e)
500
+ {
501
+ string hit = "";
502
+ foreach (var b in buttons) if (b.Key.Contains(e.Location)) { hit = b.Value; break; }
503
+ pet.Cursor = hit.Length > 0 ? Cursors.Hand : Cursors.SizeAll;
504
+ if (hit != hoveredBtn)
505
+ {
506
+ hoveredBtn = hit;
507
+ RenderPill();
508
+ }
509
+ };
510
+ pet.MouseLeave += delegate
511
+ {
512
+ if (hoveredBtn.Length > 0 || pressedBtn.Length > 0)
513
+ {
514
+ hoveredBtn = "";
515
+ pressedBtn = "";
516
+ RenderPill();
517
+ }
518
+ };
519
+ pet.MouseDown += delegate (object s, MouseEventArgs e)
520
+ {
521
+ if (e.Button != MouseButtons.Left) return;
522
+ foreach (var b in buttons)
523
+ {
524
+ if (b.Key.Contains(e.Location))
525
+ {
526
+ pressedBtn = b.Value;
527
+ RenderPill();
528
+ return;
529
+ }
530
+ }
531
+ // Drag the card anywhere; it keeps that place until the next run.
532
+ Native.ReleaseCapture();
533
+ Native.SendMessage(pet.Handle, 0xA1, new IntPtr(2), IntPtr.Zero); // WM_NCLBUTTONDOWN, HTCAPTION
534
+ Native.RECT rc;
535
+ if (pet != null && Native.GetWindowRect(pet.Handle, out rc)) petAnchor = new Point(rc.Right - petShadow, rc.Bottom - petShadow);
536
+ petDragged = true;
537
+ RenderPill();
538
+ };
539
+ pet.MouseUp += delegate (object s, MouseEventArgs e)
540
+ {
541
+ bool hadPressed = pressedBtn.Length > 0;
542
+ pressedBtn = "";
543
+ if (petDragged) { petDragged = false; return; }
544
+ foreach (var b in buttons)
545
+ if (b.Key.Contains(e.Location)) { Press(b.Value); return; }
546
+ if (hadPressed) RenderPill();
547
+ };
548
+ pet.Show();
549
+ PetHwnd = pet.Handle;
550
+ }
551
+ }
552
+ else if (pill == null)
553
+ {
554
+ pill = new LayeredForm(false);
555
+ pill.MouseUp += delegate (object s, MouseEventArgs e)
556
+ {
557
+ foreach (var b in buttons)
558
+ if (b.Key.Contains(e.Location)) { Press(b.Value); break; }
559
+ };
560
+ pill.Show();
561
+ }
562
+ RenderPill();
563
+ InstallHook();
564
+ shownAt = DateTime.UtcNow;
565
+ visible = true;
566
+ timer.Start();
567
+ });
568
+ }
569
+
570
+ public static void Status(string newStatus)
571
+ {
572
+ if (thread == null || !visible) return;
573
+ Ui(delegate { status = newStatus; RenderPill(); });
574
+ }
575
+
576
+ /** Latest host-provided reasoning and recent operations, oldest first. */
577
+ public static void PetUpdate(string thinking, List<string> steps)
578
+ {
579
+ if (thread == null || !visible || !petMode || petFinished) return;
580
+ invoker.BeginInvoke((MethodInvoker)delegate
581
+ {
582
+ if (petFinished) return;
583
+ petThinking = thinking;
584
+ if (steps.Count > 0) petSteps = steps;
585
+ RenderPill();
586
+ });
587
+ }
588
+
589
+ /** The run ended: the card says so for a moment (longer while the pointer rests on it), then everything hides. */
590
+ public static void Finish(int holdMs)
591
+ {
592
+ if (thread == null) return;
593
+ Ui(delegate
594
+ {
595
+ if (!visible || !petMode) { HideCore(); return; }
596
+ HideMark();
597
+ CloseInput(false);
598
+ foreach (var g in glows) g.Close();
599
+ glows.Clear();
600
+ RemoveHook();
601
+ paused = false;
602
+ petFinished = true;
603
+ finishedAt = DateTime.UtcNow;
604
+ finishHoldMs = holdMs;
605
+ RenderPill();
606
+ });
607
+ }
608
+
609
+ public static void SetPaused(bool value)
610
+ {
611
+ if (thread == null) return;
612
+ Ui(delegate { paused = value; RenderPill(); });
613
+ }
614
+
615
+ public static void Hide()
616
+ {
617
+ if (thread == null) return;
618
+ Ui(delegate { HideCore(); });
619
+ }
620
+
621
+ static void HideCore()
622
+ {
623
+ {
624
+ HideMark();
625
+ CloseInput(false);
626
+ petFinished = false;
627
+ visible = false;
628
+ paused = false;
629
+ timer.Stop();
630
+ foreach (var g in glows) g.Close();
631
+ glows.Clear();
632
+ if (pill != null) { pill.Close(); pill = null; }
633
+ if (pet != null) { PetHwnd = IntPtr.Zero; pet.Close(); pet = null; }
634
+ petMode = false;
635
+ rendered = "";
636
+ lock (RectLock) pillRect = Rectangle.Empty;
637
+ RemoveHook();
638
+ }
639
+ }
640
+
641
+ public static void Shutdown()
642
+ {
643
+ if (thread == null) return;
644
+ try { Hide(); Ui(delegate { Application.ExitThread(); }); } catch (Exception) { }
645
+ }
646
+
647
+ public static bool ShowClickTarget { get { return visible && clickTargetEnabled; } }
648
+
649
+ static void MonitorAt(int x, int y, out float scale, out Rectangle bounds)
650
+ {
651
+ scale = 1f;
652
+ bounds = Rectangle.Empty;
653
+ bool found = false;
654
+ foreach (Dictionary<string, object> d in Screen2.Displays())
655
+ {
656
+ var r = new Rectangle((int)d["x"], (int)d["y"], (int)d["width"], (int)d["height"]);
657
+ float s = (int)d["dpi"] / 96f;
658
+ if (r.Contains(x, y)) { scale = s; bounds = r; return; }
659
+ if (!found || (bool)d["primary"]) { scale = s; bounds = r; found = true; }
660
+ }
661
+ }
662
+
663
+ /**
664
+ * Collaborative Codex-style cursor badge: the corner nearest the pointer
665
+ * tip stays tight (2px), while the other three corners are smoothly rounded.
666
+ */
667
+ static GraphicsPath TagShape(RectangleF r, bool flipX, bool flipY, float scale)
668
+ {
669
+ float tight = 2f * scale;
670
+ float round = 7f * scale;
671
+ float tl = (!flipX && !flipY) ? tight : round;
672
+ float tr = (flipX && !flipY) ? tight : round;
673
+ float br = (flipX && flipY) ? tight : round;
674
+ float bl = (!flipX && flipY) ? tight : round;
675
+ var p = new GraphicsPath();
676
+ p.AddArc(r.X, r.Y, tl * 2f, tl * 2f, 180, 90);
677
+ p.AddArc(r.Right - tr * 2f, r.Y, tr * 2f, tr * 2f, 270, 90);
678
+ p.AddArc(r.Right - br * 2f, r.Bottom - br * 2f, br * 2f, br * 2f, 0, 90);
679
+ p.AddArc(r.X, r.Bottom - bl * 2f, bl * 2f, bl * 2f, 90, 90);
680
+ p.CloseFigure();
681
+ return p;
682
+ }
683
+
684
+ /**
685
+ * Draw a sleek Codex-style collaborative AI pointer cursor whose tip sits
686
+ * pixel-exact at (cx, cy): soft radial spotlight glow, crisp filled vector
687
+ * arrow with white outline, attached rounded name-tag pill (auto-flipping
688
+ * at all 4 screen edges), and a subtle click ripple ring on post-click.
689
+ */
690
+ static Bitmap DrawMark(string text, Color color, float scale, bool flipX, bool flipY, bool ripple, out int cx, out int cy)
691
+ {
692
+ float s = Math.Max(0.75f, Math.Min(3f, scale));
693
+ float px = 1.333f * s;
694
+ float glowR = (ripple ? 20f : 16f) * s;
695
+ float pad = 4f * s;
696
+ using (var font = new Font("Microsoft YaHei UI", 8f * px, FontStyle.Bold, GraphicsUnit.Pixel))
697
+ using (var probe = new Bitmap(1, 1))
698
+ using (var mg = Graphics.FromImage(probe))
699
+ using (var fmt = new StringFormat(StringFormat.GenericTypographic))
700
+ {
701
+ mg.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
702
+ fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap;
703
+ SizeF textSize = string.IsNullOrEmpty(text) ? SizeF.Empty : mg.MeasureString(text, font, 10000, fmt);
704
+ float pillPadX = 7f * s;
705
+ float pillW = textSize.Width > 0 ? (float)Math.Ceiling(textSize.Width + 2f * pillPadX) : 0f;
706
+ float pillH = textSize.Height > 0 ? Math.Max(19f * s, (float)Math.Ceiling(textSize.Height + 5f * s)) : 0f;
707
+
708
+ // Offsets relative to the pointer tip at (0, 0).
709
+ float tagX = flipX ? (-10f * s - pillW) : (13f * s);
710
+ float tagY = flipY ? (-10f * s - pillH) : (15f * s);
711
+
712
+ float minX = Math.Min(-glowR, pillW > 0 ? tagX : 0f) - pad;
713
+ float maxX = Math.Max(glowR, Math.Max(14f * s, pillW > 0 ? tagX + pillW : 0f)) + pad;
714
+ float minY = Math.Min(-glowR, pillH > 0 ? tagY : 0f) - pad;
715
+ float maxY = Math.Max(glowR, Math.Max(22f * s, pillH > 0 ? tagY + pillH : 0f)) + pad;
716
+
717
+ int W = Math.Max(1, (int)Math.Ceiling(maxX - minX));
718
+ int H = Math.Max(1, (int)Math.Ceiling(maxY - minY));
719
+ cx = (int)Math.Round(-minX);
720
+ cy = (int)Math.Round(-minY);
721
+
722
+ var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb);
723
+ using (var g = Graphics.FromImage(bmp))
724
+ {
725
+ g.Clear(Color.Transparent);
726
+ g.SmoothingMode = SmoothingMode.AntiAlias;
727
+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
728
+
729
+ // 1. Soft radial spotlight centered right under the tip (cx, cy).
730
+ using (var spot = new GraphicsPath())
731
+ {
732
+ spot.AddEllipse(cx - glowR, cy - glowR, glowR * 2f, glowR * 2f);
733
+ using (var glow = new PathGradientBrush(spot))
734
+ {
735
+ glow.CenterPoint = new PointF(cx, cy);
736
+ glow.CenterColor = Color.FromArgb(ripple ? 130 : 95, color);
737
+ glow.SurroundColors = new Color[] { Color.FromArgb(0, color) };
738
+ g.FillPath(glow, spot);
739
+ }
740
+ }
741
+
742
+ // 2. Post-click delicate ripple ring so exact placement reads cleanly in screenshots.
743
+ if (ripple)
744
+ {
745
+ float rr = 11.5f * s;
746
+ using (var ringHalo = new Pen(Color.FromArgb(140, 255, 255, 255), Math.Max(2.5f, 3.2f * s)))
747
+ g.DrawEllipse(ringHalo, cx - rr, cy - rr, rr * 2f, rr * 2f);
748
+ using (var ring = new Pen(Color.FromArgb(230, color), Math.Max(1.6f, 2f * s)))
749
+ g.DrawEllipse(ring, cx - rr, cy - rr, rr * 2f, rr * 2f);
750
+ }
751
+
752
+ // 3. Attached collaborative name-tag pill.
753
+ if (pillW > 0 && pillH > 0)
754
+ {
755
+ float bx = cx + tagX;
756
+ float by = cy + tagY;
757
+ var shadowRect = new RectangleF(bx, by + 1.5f * s, pillW, pillH);
758
+ using (var sp = TagShape(shadowRect, flipX, flipY, s))
759
+ using (var sb = new SolidBrush(Color.FromArgb(62, 0, 0, 0)))
760
+ g.FillPath(sb, sp);
761
+
762
+ var pillRect = new RectangleF(bx, by, pillW, pillH);
763
+ using (var pp = TagShape(pillRect, flipX, flipY, s))
764
+ {
765
+ using (var fill = new SolidBrush(Color.FromArgb(245, color))) g.FillPath(fill, pp);
766
+ using (var border = new Pen(Color.FromArgb(235, 255, 255, 255), Math.Max(1f, 1.25f * s))) g.DrawPath(border, pp);
767
+ }
768
+ using (var fg = new SolidBrush(Color.White))
769
+ g.DrawString(text, font, fg, bx + (pillW - textSize.Width) / 2f, by + (pillH - textSize.Height) / 2f - 0.5f * s, fmt);
770
+ }
771
+
772
+ // 4. Crisp vector cursor arrow whose tip sits pixel-exact at (cx, cy).
773
+ var arrow = new PointF[]
774
+ {
775
+ new PointF(cx, cy),
776
+ new PointF(cx, cy + 16.5f * s),
777
+ new PointF(cx + 4.3f * s, cy + 12.8f * s),
778
+ new PointF(cx + 7.4f * s, cy + 19.2f * s),
779
+ new PointF(cx + 10.0f * s, cy + 17.9f * s),
780
+ new PointF(cx + 6.9f * s, cy + 11.7f * s),
781
+ new PointF(cx + 12.4f * s, cy + 11.4f * s),
782
+ };
783
+ var arrowShadow = new PointF[arrow.Length];
784
+ for (int i = 0; i < arrow.Length; i++)
785
+ arrowShadow[i] = new PointF(arrow[i].X + 0.8f * s, arrow[i].Y + 1.5f * s);
786
+ using (var sb = new SolidBrush(Color.FromArgb(72, 0, 0, 0))) g.FillPolygon(sb, arrowShadow);
787
+ using (var fill = new SolidBrush(Color.FromArgb(255, color))) g.FillPolygon(fill, arrow);
788
+ using (var outline = new Pen(Color.FromArgb(248, 255, 255, 255), Math.Max(1.2f, 1.5f * s)))
789
+ {
790
+ outline.LineJoin = LineJoin.Round;
791
+ g.DrawPolygon(outline, arrow);
792
+ }
793
+ }
794
+ return bmp;
795
+ }
796
+ }
797
+
798
+ static int lastMarkX, lastMarkY;
799
+ static bool hasLastMark;
800
+
801
+ public static void MarkPointer(int x, int y, string text, int holdMs)
802
+ {
803
+ GlideMark(x, y, text, Accent, holdMs, false, false);
804
+ }
805
+
806
+ /** Smooth single-segment EaseOutCubic glide (~160ms) to (x, y) before holding the Codex cursor. */
807
+ public static void GlideMark(int x, int y, string text, Color color, int holdMs, bool capturable, bool ripple)
808
+ {
809
+ int startX, startY;
810
+ if (hasLastMark)
811
+ {
812
+ startX = lastMarkX;
813
+ startY = lastMarkY;
814
+ }
815
+ else
816
+ {
817
+ Native.POINT cur;
818
+ if (Native.GetCursorPos(out cur)) { startX = cur.X; startY = cur.Y; }
819
+ else { startX = x; startY = y; }
820
+ }
821
+ double dist = Math.Sqrt((double)(x - startX) * (x - startX) + (double)(y - startY) * (y - startY));
822
+ if (dist >= 40.0)
823
+ {
824
+ int steps = Math.Max(5, Math.Min(10, (int)(dist / 90.0) + 5));
825
+ for (int i = 1; i < steps; i++)
826
+ {
827
+ double t = (double)i / steps;
828
+ double ease = 1.0 - Math.Pow(1.0 - t, 3.0); // EaseOutCubic
829
+ int ix = startX + (int)Math.Round((x - startX) * ease);
830
+ int iy = startY + (int)Math.Round((y - startY) * ease);
831
+ Mark(ix, iy, text, color, holdMs, capturable, false);
832
+ Thread.Sleep(16);
833
+ }
834
+ }
835
+ Mark(x, y, text, color, holdMs, capturable, ripple);
836
+ }
837
+
838
+ public static void Mark(int x, int y, string text, Color color, int holdMs, bool capturable, bool ripple)
839
+ {
840
+ lastMarkX = x;
841
+ lastMarkY = y;
842
+ hasLastMark = true;
843
+ Ensure();
844
+ Ui(delegate
845
+ {
846
+ if (markForm == null)
847
+ {
848
+ markForm = new LayeredForm(true);
849
+ markForm.Show();
850
+ }
851
+ markForm.SetCapturable(capturable || !ExcludeFromCapture);
852
+ float scale; Rectangle mon;
853
+ MonitorAt(x, y, out scale, out mon);
854
+ float s = Math.Max(0.75f, Math.Min(3f, scale));
855
+ int estW = (int)((Math.Max(6, (text ?? "").Length) * 11 + 36) * s);
856
+ bool flipX = !mon.IsEmpty && x + estW > mon.Right;
857
+ bool flipY = !mon.IsEmpty && y + (int)(52 * s) > mon.Bottom;
858
+ int cx, cy;
859
+ using (var bmp = DrawMark(text, color, scale, flipX, flipY, ripple, out cx, out cy))
860
+ {
861
+ markForm.SetBitmap(bmp, new Rectangle(x - cx, y - cy, bmp.Width, bmp.Height), 255);
862
+ }
863
+ markForm.KeepOnTop();
864
+ markActive = true;
865
+ markExpiresAt = holdMs > 0 ? DateTime.UtcNow.AddMilliseconds(holdMs) : DateTime.MaxValue;
866
+ if (!timer.Enabled) timer.Start();
867
+ });
868
+ }
869
+
870
+ public static void MarkResult(int x, int y, string button, int count, string coordLabel)
871
+ {
872
+ Color color;
873
+ string verb;
874
+ if (count >= 3) { color = Color.FromArgb(249, 115, 22); verb = "已三击"; }
875
+ else if (count == 2) { color = Color.FromArgb(139, 92, 246); verb = "已双击"; }
876
+ else if (button == "right") { color = Color.FromArgb(16, 185, 129); verb = "已右键"; }
877
+ else if (button == "middle") { color = Color.FromArgb(6, 182, 212); verb = "已中键"; }
878
+ else { color = Color.FromArgb(59, 130, 246); verb = "已单击"; }
879
+ Mark(x, y, verb + " " + coordLabel, color, 4000, true, true);
880
+ }
881
+
882
+ static void HideMark()
883
+ {
884
+ markActive = false;
885
+ markExpiresAt = DateTime.MinValue;
886
+ if (markForm != null)
887
+ {
888
+ markForm.SetCapturable(false);
889
+ markForm.Close();
890
+ markForm = null;
891
+ }
892
+ }
893
+
894
+ /// Move the status pill out of the way when an injected pointer action
895
+ /// targets it: the pill is clickable for the user but invisible to the model.
896
+ public static void Dodge(int x, int y)
897
+ {
898
+ Rectangle r;
899
+ lock (RectLock) r = pillRect;
900
+ if (r.IsEmpty) return;
901
+ var inflated = Rectangle.Inflate(r, 12, 12);
902
+ if (!inflated.Contains(x, y)) return;
903
+ Ui(delegate { pillAtBottom = !pillAtBottom; RenderPill(); });
904
+ Thread.Sleep(30);
905
+ }
906
+
907
+ // pause / resume / stop, from Esc or the pill buttons.
908
+ static void Press(string action)
909
+ {
910
+ if (action == "stop") { paused = false; Program.EmitEvent("stop", "button"); }
911
+ else if (action == "pause") { paused = true; Program.EmitEvent("pause", "user"); }
912
+ else if (action == "resume") { paused = false; pausedByInput = false; Program.EmitEvent("resume", "user"); }
913
+ else if (action == "expand") petExpanded = !petExpanded;
914
+ else if (action == "input") { if (input == null) OpenInput(); else CloseInput(true); return; }
915
+ else if (action == "send") { if (input != null) SubmitInput(input.Box.Text); return; }
916
+ else if (action == "close") { HideCore(); return; }
917
+ RenderPill();
918
+ }
919
+
920
+ static void OpenInput()
921
+ {
922
+ beforeInput = Native.GetForegroundWindow();
923
+ // Typing an instruction pauses the agent, so its keys cannot land in the box.
924
+ if (!paused) { paused = true; pausedByInput = true; Program.EmitEvent("pause", "input"); }
925
+ bool dark = DarkTheme();
926
+ float px = 1.333f * Scale();
927
+ input = new InputBox(new Font("Microsoft YaHei UI", 10f * px, FontStyle.Regular, GraphicsUnit.Pixel),
928
+ dark ? Color.FromArgb(52, 51, 49) : Color.White, dark ? Color.FromArgb(244, 243, 241) : Color.FromArgb(31, 30, 29),
929
+ "告诉 DeepSeek 接下来做什么(Enter 发送,Esc 取消)");
930
+ input.Submitted += SubmitInput;
931
+ input.Cancelled += delegate { CloseInput(true); };
932
+ inputBounds = Rectangle.Empty;
933
+ RenderPill(); // makes room for the field and places the box over it
934
+ input.Show();
935
+ InputHwnd = input.Handle;
936
+ var handle = input.Handle;
937
+ ThreadPool.QueueUserWorkItem(delegate
938
+ {
939
+ try { Windows.Focus(handle); } catch (Exception) { }
940
+ try { invoker.BeginInvoke((MethodInvoker)delegate { if (input != null) input.Box.Focus(); }); } catch (Exception) { }
941
+ });
942
+ }
943
+
944
+ static void SubmitInput(string text)
945
+ {
946
+ text = (text ?? "").Trim();
947
+ if (text.Length > 0) Program.EmitEvent("message", text);
948
+ CloseInput(true);
949
+ }
950
+
951
+ static void CloseInput(bool restoreFocus)
952
+ {
953
+ if (input == null) return;
954
+ var box = input;
955
+ input = null;
956
+ InputReturnsTo = restoreFocus ? beforeInput : IntPtr.Zero;
957
+ InputHwnd = IntPtr.Zero;
958
+ inputBounds = Rectangle.Empty;
959
+ box.Close();
960
+ if (pausedByInput) { paused = false; pausedByInput = false; Program.EmitEvent("resume", "input"); }
961
+ var target = beforeInput;
962
+ beforeInput = IntPtr.Zero;
963
+ if (restoreFocus && target != IntPtr.Zero && Native.IsWindow(target))
964
+ ThreadPool.QueueUserWorkItem(delegate { try { Windows.Focus(target); } catch (Exception) { } });
965
+ if (visible) RenderPill();
966
+ }
967
+
968
+ static bool Typing() { return unchecked(Environment.TickCount - lastTyping) < idleMs; }
969
+
970
+ static void Tick()
971
+ {
972
+ if (markActive && DateTime.UtcNow >= markExpiresAt) HideMark();
973
+ if (!visible)
974
+ {
975
+ if (!markActive) timer.Stop();
976
+ return;
977
+ }
978
+ if (petFinished)
979
+ {
980
+ Native.POINT p; Native.GetCursorPos(out p);
981
+ bool hovered = petBody.Contains(p.X, p.Y);
982
+ if (hovered) finishedAt = DateTime.UtcNow;
983
+ if ((DateTime.UtcNow - finishedAt).TotalMilliseconds >= finishHoldMs) HideCore();
984
+ return;
985
+ }
986
+ double t = (DateTime.UtcNow - shownAt).TotalSeconds;
987
+ double fadeIn = Math.Min(1.0, t / 0.35);
988
+ double breathe = paused ? 0.55 : 0.72 + 0.28 * (0.5 + 0.5 * Math.Sin(t * Math.PI * 2 / 2.6));
989
+ byte alpha = (byte)Math.Max(0, Math.Min(255, 255 * fadeIn * breathe));
990
+ foreach (var g in glows) g.SetAlpha(alpha);
991
+ if (Key() != rendered) RenderPill(); // typing started or stopped
992
+ if ((int)(t * 25) % 50 == 0)
993
+ {
994
+ foreach (var g in glows) g.KeepOnTop();
995
+ if (pill != null) pill.KeepOnTop();
996
+ if (pet != null) pet.KeepOnTop();
997
+ if (markForm != null) markForm.KeepOnTop();
998
+ if (input != null) Native.SetWindowPos(input.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);
999
+ }
1000
+ }
1001
+
1002
+ static Bitmap DrawGlow(int w, int h, float scale)
1003
+ {
1004
+ var bmp = new Bitmap(w, h, PixelFormat.Format32bppArgb);
1005
+ using (var g = Graphics.FromImage(bmp))
1006
+ {
1007
+ g.Clear(Color.Transparent);
1008
+ int depth = Math.Max(14, (int)(30 * scale));
1009
+ for (int i = 0; i < depth; i++)
1010
+ {
1011
+ double f = 1.0 - (double)i / depth;
1012
+ int a = (int)(185 * Math.Pow(f, 1.9));
1013
+ if (a <= 0) continue;
1014
+ using (var pen = new Pen(Color.FromArgb(a, Accent), 1))
1015
+ g.DrawRectangle(pen, i, i, w - 1 - 2 * i, h - 1 - 2 * i);
1016
+ }
1017
+ int line = Math.Max(2, (int)Math.Round(2.5 * scale));
1018
+ using (var pen = new Pen(Color.FromArgb(235, AccentHi), line))
1019
+ {
1020
+ pen.Alignment = PenAlignment.Inset;
1021
+ g.DrawRectangle(pen, 0, 0, w, h);
1022
+ }
1023
+ }
1024
+ return bmp;
1025
+ }
1026
+
1027
+ static GraphicsPath Rounded(RectangleF r, float radius)
1028
+ {
1029
+ var p = new GraphicsPath();
1030
+ float d = radius * 2;
1031
+ p.AddArc(r.X, r.Y, d, d, 180, 90);
1032
+ p.AddArc(r.Right - d, r.Y, d, d, 270, 90);
1033
+ p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
1034
+ p.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
1035
+ p.CloseFigure();
1036
+ return p;
1037
+ }
1038
+
1039
+ // What the pill should say right now; it is re-rendered whenever this changes.
1040
+ static void Content(out string main, out string sub, out string[] actions, out string[] captions)
1041
+ {
1042
+ if (paused)
1043
+ {
1044
+ main = "已暂停"; sub = "按 Esc 继续";
1045
+ actions = new[] { "resume", "stop" }; captions = new[] { "继续", "停止" };
1046
+ return;
1047
+ }
1048
+ main = label;
1049
+ sub = Typing() ? "你正在操作,已暂停" : status.Length > 0 ? status : "Esc 暂停";
1050
+ actions = new[] { "stop" }; captions = new[] { "停止" };
1051
+ }
1052
+
1053
+ static string Key()
1054
+ {
1055
+ string main, sub; string[] actions, captions;
1056
+ Content(out main, out sub, out actions, out captions);
1057
+ return main + "|" + sub + "|" + string.Join(",", actions) + "|" + pillAtBottom + "|" + Typing();
1058
+ }
1059
+
1060
+ static bool DarkTheme()
1061
+ {
1062
+ try
1063
+ {
1064
+ using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"))
1065
+ {
1066
+ object v = key == null ? null : key.GetValue("AppsUseLightTheme");
1067
+ return v is int && (int)v == 0;
1068
+ }
1069
+ }
1070
+ catch (Exception) { return false; }
1071
+ }
1072
+
1073
+ /** The end of `s` that fits `width`, led by "…": a ticker that scrolls as text streams in. */
1074
+ static string Tail(Graphics g, string s, Font font, float width, StringFormat fmt)
1075
+ {
1076
+ if (s.Length == 0 || g.MeasureString(s, font, 100000, fmt).Width <= width) return s;
1077
+ int lo = 1, hi = s.Length - 1;
1078
+ while (lo < hi)
1079
+ {
1080
+ int mid = (lo + hi) / 2;
1081
+ if (g.MeasureString("…" + s.Substring(mid), font, 100000, fmt).Width <= width) hi = mid; else lo = mid + 1;
1082
+ }
1083
+ if (lo < s.Length && char.IsLowSurrogate(s[lo])) lo++;
1084
+ return "…" + s.Substring(Math.Min(lo, s.Length));
1085
+ }
1086
+
1087
+ static float Scale()
1088
+ {
1089
+ float scale = 1f; bool found = false;
1090
+ foreach (Dictionary<string, object> d in Screen2.Displays())
1091
+ if (!found || (bool)d["primary"]) { scale = (int)d["dpi"] / 96f; found = true; }
1092
+ return scale;
1093
+ }
1094
+
1095
+ static string IconFont()
1096
+ {
1097
+ if (iconFont != null) return iconFont;
1098
+ iconFont = "";
1099
+ foreach (var name in new[] { "Segoe Fluent Icons", "Segoe MDL2 Assets" })
1100
+ using (var f = new Font(name, 10f)) if (f.Name == name) { iconFont = name; break; }
1101
+ return iconFont;
1102
+ }
1103
+
1104
+ /** The end of `s` that fits in `width` x `height` when wrapped, led by "…". */
1105
+ static string TailWrapped(Graphics g, string s, Font font, float width, float height, StringFormat fmt)
1106
+ {
1107
+ Func<string, bool> fits = delegate (string t) { return g.MeasureString(t, font, new SizeF(width, 100000), fmt).Height <= height; };
1108
+ if (s.Length == 0 || fits(s)) return s;
1109
+ int lo = 1, hi = s.Length - 1;
1110
+ while (lo < hi)
1111
+ {
1112
+ int mid = (lo + hi) / 2;
1113
+ if (fits("…" + s.Substring(mid))) hi = mid; else lo = mid + 1;
1114
+ }
1115
+ if (lo < s.Length && char.IsLowSurrogate(s[lo])) lo++;
1116
+ return "…" + s.Substring(Math.Min(lo, s.Length));
1117
+ }
1118
+
1119
+ static string ButtonTip(string act)
1120
+ {
1121
+ if (act == "stop") return "停止本轮";
1122
+ if (act == "pause") return "暂停操控";
1123
+ if (act == "resume") return "继续操控";
1124
+ if (act == "expand") return petExpanded ? "收起详情" : "展开详情";
1125
+ if (act == "input") return input != null ? "关闭输入框" : "输入新指令";
1126
+ if (act == "close") return "关闭卡片";
1127
+ if (act == "send") return "发送指令";
1128
+ return "";
1129
+ }
1130
+
1131
+ static void RenderPet()
1132
+ {
1133
+ if (pet == null) return;
1134
+ Rectangle work = Rectangle.Empty; float scale = 1f;
1135
+ foreach (Dictionary<string, object> d in Screen2.Displays())
1136
+ {
1137
+ if (work.IsEmpty || (bool)d["primary"])
1138
+ {
1139
+ work = new Rectangle((int)d["workX"], (int)d["workY"], (int)d["workWidth"], (int)d["workHeight"]);
1140
+ scale = (int)d["dpi"] / 96f;
1141
+ }
1142
+ }
1143
+ rendered = Key();
1144
+ bool dark = DarkTheme();
1145
+ Color bg = dark ? Color.FromArgb(petAlpha, 30, 30, 32) : Color.FromArgb(petAlpha, 252, 252, 251);
1146
+ Color ink = dark ? Color.FromArgb(244, 243, 241) : Color.FromArgb(31, 30, 29);
1147
+ Color muted = dark ? Color.FromArgb(168, 165, 160) : Color.FromArgb(112, 110, 106);
1148
+ Color edge = dark ? Color.FromArgb(64, 255, 255, 255) : Color.FromArgb(38, 0, 0, 0);
1149
+ Color chip = dark ? Color.FromArgb(64, 63, 66) : Color.FromArgb(236, 234, 230);
1150
+ Color chipHover = dark ? Color.FromArgb(92, 86, 82) : Color.FromArgb(224, 214, 206);
1151
+ Color chipPress = dark ? Color.FromArgb(110, 96, 88) : Color.FromArgb(212, 198, 188);
1152
+ Color field = dark ? Color.FromArgb(50, 50, 52) : Color.White;
1153
+
1154
+ bool isCompact = petSize == "compact";
1155
+ bool isDetailed = petSize == "detailed";
1156
+ string title = petFinished ? "已完成" : (isCompact && label.Length > 12 ? label.Substring(0, 11) + "…" : label);
1157
+ string hoverTip = ButtonTip(hoveredBtn);
1158
+ string state = hoverTip.Length > 0 ? hoverTip
1159
+ : petFinished ? "" : paused ? (input != null ? "输入指令中…" : "已暂停 · Esc 继续")
1160
+ : Typing() ? "你正在操作,已暂停" : (isCompact ? "" : "Esc 暂停");
1161
+ // Header buttons, right to left.
1162
+ var actions = new List<string>(); var glyphs = new List<string>();
1163
+ if (petFinished) { actions.Add("close"); glyphs.Add("\uE711"); }
1164
+ else
1165
+ {
1166
+ actions.Add("stop"); glyphs.Add("\uE71A");
1167
+ if (paused) { actions.Add("resume"); glyphs.Add("\uE768"); } else { actions.Add("pause"); glyphs.Add("\uE769"); }
1168
+ }
1169
+ actions.Add("expand"); glyphs.Add(petExpanded ? "\uE70D" : "\uE70E");
1170
+ if (!petFinished) { actions.Add("input"); glyphs.Add("\uE70F"); }
1171
+
1172
+ float s = scale, px = 1.333f * scale;
1173
+ int shadow = (int)(14 * s);
1174
+ petShadow = shadow;
1175
+ float bodyW = (isCompact ? 320f : isDetailed ? 484f : 420f) * s;
1176
+ float pad = (isCompact ? 13f : 16f) * s;
1177
+ float headH = (isCompact ? 40f : 44f) * s;
1178
+ bool showThinking = !isCompact || petExpanded;
1179
+ bool showTimeline = petExpanded || isDetailed;
1180
+ float replyH = showThinking ? (isDetailed && !petExpanded ? 42f * s : 26f * s) : 0f;
1181
+ string progress = petFinished ? "已交还电脑控制" : petThinking.Length > 0 ? "思考 · " + petThinking : "正在操作,等待下一步…";
1182
+ if (showThinking && (petExpanded || isDetailed))
1183
+ {
1184
+ using (var probe = new Bitmap(1, 1))
1185
+ using (var pg = Graphics.FromImage(probe))
1186
+ using (var pf = new Font("Microsoft YaHei UI", (isCompact ? 9.5f : 10.5f) * 1.333f * scale, FontStyle.Regular, GraphicsUnit.Pixel))
1187
+ {
1188
+ float need = pg.MeasureString(progress, pf, new SizeF(bodyW - 2 * pad, 100000), new StringFormat(StringFormat.GenericTypographic)).Height + 6 * scale;
1189
+ float cap = petExpanded ? (isDetailed ? 210f : 172f) * scale : 44f * scale;
1190
+ replyH = Math.Max(26f * scale, Math.Min(cap, need));
1191
+ }
1192
+ }
1193
+ int maxSteps = petExpanded ? (isDetailed ? 8 : 5) : (isDetailed ? 3 : 0);
1194
+ int stepRows = showTimeline ? Math.Min(maxSteps, Math.Max(1, petSteps.Count)) : 0;
1195
+ float listH = showTimeline ? 10 * s + stepRows * 22 * s : 24 * s;
1196
+ float inputH = input != null ? 46 * s : 0;
1197
+ float bodyH = headH + replyH + listH + inputH + (isCompact ? 10f : 12f) * s;
1198
+ int W = (int)Math.Ceiling(bodyW) + 2 * shadow, H = (int)Math.Ceiling(bodyH) + 2 * shadow;
1199
+ if (petAnchor.IsEmpty) petAnchor = new Point(work.Right - (int)(16 * s), work.Bottom - (int)(16 * s));
1200
+ int x = petAnchor.X - (int)bodyW - shadow, y = petAnchor.Y - (int)bodyH - shadow;
1201
+ y = Math.Max(work.Y - shadow, y);
1202
+ petBody = new Rectangle(x + shadow, y + shadow, (int)bodyW, (int)bodyH);
1203
+
1204
+ string glyphFont = IconFont();
1205
+ using (var fHead = new Font("Microsoft YaHei UI", 8.5f * px, FontStyle.Bold, GraphicsUnit.Pixel))
1206
+ using (var fState = new Font("Microsoft YaHei UI", 8.2f * px, FontStyle.Regular, GraphicsUnit.Pixel))
1207
+ using (var fText = new Font("Microsoft YaHei UI", (isCompact ? 9.5f : 10.2f) * px, FontStyle.Regular, GraphicsUnit.Pixel))
1208
+ using (var fAct = new Font("Microsoft YaHei UI", 8.5f * px, FontStyle.Regular, GraphicsUnit.Pixel))
1209
+ using (var fGlyph = new Font(glyphFont.Length > 0 ? glyphFont : "Segoe UI Symbol", 8.5f * px, FontStyle.Regular, GraphicsUnit.Pixel))
1210
+ using (var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb))
1211
+ using (var g = Graphics.FromImage(bmp))
1212
+ {
1213
+ g.Clear(Color.Transparent);
1214
+ g.SmoothingMode = SmoothingMode.AntiAlias;
1215
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
1216
+ g.TextRenderingHint = TextRenderingHint.AntiAlias;
1217
+ var fmt = new StringFormat(StringFormat.GenericTypographic);
1218
+ fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap;
1219
+ var wrap = new StringFormat(StringFormat.GenericTypographic);
1220
+ wrap.Trimming = StringTrimming.None;
1221
+ var center = new StringFormat(); center.Alignment = StringAlignment.Center; center.LineAlignment = StringAlignment.Center;
1222
+
1223
+ var body = new RectangleF(shadow, shadow, bodyW, bodyH);
1224
+ float radius = (isCompact ? 15f : 18f) * s;
1225
+ for (int i = shadow; i > 0; i--)
1226
+ {
1227
+ double f = 1.0 - (double)i / shadow;
1228
+ using (var path = Rounded(RectangleF.Inflate(body, i, i - 2 * s), radius + i))
1229
+ using (var brush = new SolidBrush(Color.FromArgb((int)(16 * f * f), 0, 0, 0))) g.FillPath(brush, path);
1230
+ }
1231
+ using (var path = Rounded(body, radius))
1232
+ {
1233
+ using (var brush = new SolidBrush(bg)) g.FillPath(brush, path);
1234
+ using (var pen = new Pen(petFinished ? Color.FromArgb(145, 46, 160, 67) : edge, Math.Max(1f, s))) g.DrawPath(pen, path);
1235
+ }
1236
+
1237
+ // Header: logo, title, state / button hover tooltip, tactile round icon buttons.
1238
+ float hy = body.Y + (isCompact ? 8f : 10f) * s, hh = 26 * s;
1239
+ float iconSize = 18 * s;
1240
+ var iconRect = new RectangleF(body.X + pad, hy + (hh - iconSize) / 2f, iconSize, iconSize);
1241
+ Image logo = dark ? icon : (iconLight ?? icon);
1242
+ if (petFinished)
1243
+ {
1244
+ using (var brush = new SolidBrush(Color.FromArgb(46, 160, 67))) g.FillEllipse(brush, iconRect);
1245
+ using (var b = new SolidBrush(Color.White)) g.DrawString(glyphFont.Length > 0 ? "\uE73E" : "✓", fGlyph, b, iconRect, center);
1246
+ }
1247
+ else if (logo != null) g.DrawImage(logo, iconRect);
1248
+ else using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, RectangleF.Inflate(iconRect, -3 * s, -3 * s));
1249
+ float tx = iconRect.Right + 8 * s;
1250
+ SizeF headSize = g.MeasureString(title, fHead, 100000, fmt);
1251
+ using (var b = new SolidBrush(ink)) g.DrawString(title, fHead, b, tx, hy + (hh - headSize.Height) / 2f, fmt);
1252
+ tx += headSize.Width + 8 * s;
1253
+
1254
+ buttons.Clear();
1255
+ float d = (isCompact ? 24f : 26f) * s, bx = body.Right - pad;
1256
+ for (int i = 0; i < actions.Count; i++)
1257
+ {
1258
+ string act = actions[i];
1259
+ bx -= d;
1260
+ var hitRect = new RectangleF(bx, hy + (hh - d) / 2f, d, d);
1261
+ bool stop = act == "stop";
1262
+ bool on = (act == "input" && input != null) || (act == "resume");
1263
+ bool hover = hoveredBtn == act;
1264
+ bool press = pressedBtn == act;
1265
+ float inflate = press ? -0.8f * s : hover ? 1.1f * s : 0f;
1266
+ var circle = RectangleF.Inflate(hitRect, inflate, inflate);
1267
+ if (hover && stop)
1268
+ {
1269
+ using (var halo = new SolidBrush(Color.FromArgb(65, Accent)))
1270
+ g.FillEllipse(halo, RectangleF.Inflate(circle, 2.6f * s, 2.6f * s));
1271
+ }
1272
+ Color btnFill = stop
1273
+ ? (press ? Color.FromArgb(190, 92, 62) : hover ? AccentHi : Accent)
1274
+ : on
1275
+ ? Color.FromArgb(dark ? (hover ? 145 : 115) : (hover ? 95 : 65), Accent)
1276
+ : (press ? chipPress : hover ? chipHover : chip);
1277
+ using (var brush = new SolidBrush(btnFill)) g.FillEllipse(brush, circle);
1278
+ if (hover && !stop)
1279
+ {
1280
+ using (var ring = new Pen(Color.FromArgb(dark ? 150 : 120, Accent), Math.Max(1f, 1.2f * s)))
1281
+ g.DrawEllipse(ring, circle);
1282
+ }
1283
+ string glyph = glyphFont.Length > 0 ? glyphs[i] : (stop ? "■" : act == "pause" ? "❚❚" : act == "resume" ? "▶" : act == "expand" ? (petExpanded ? "˅" : "˄") : act == "close" ? "✕" : "✎");
1284
+ Color glyphColor = stop ? Color.White : (hover || on) ? (dark ? Color.White : Color.FromArgb(168, 72, 42)) : ink;
1285
+ using (var b = new SolidBrush(glyphColor)) g.DrawString(glyph, fGlyph, b, circle, center);
1286
+ buttons.Add(new KeyValuePair<Rectangle, string>(Rectangle.Round(hitRect), act));
1287
+ bx -= 6 * s;
1288
+ }
1289
+ if (state.Length > 0)
1290
+ {
1291
+ string st = Tail(g, state, fState, Math.Max(0, bx - tx - 4 * s), fmt);
1292
+ SizeF stSize = g.MeasureString(st, fState, 100000, fmt);
1293
+ Color stColor = (hoverTip.Length > 0 || paused) ? Accent : muted;
1294
+ using (var b = new SolidBrush(stColor)) g.DrawString(st, fState, b, tx, hy + (hh - stSize.Height) / 2f, fmt);
1295
+ }
1296
+
1297
+ // Reasoning and operations use separate rows throughout.
1298
+ float lineW = bodyW - 2 * pad;
1299
+ float ry = body.Y + headH;
1300
+ if (showThinking)
1301
+ {
1302
+ using (var b = new SolidBrush(petThinking.Length > 0 && !petFinished ? ink : muted))
1303
+ {
1304
+ if (petExpanded || isDetailed)
1305
+ g.DrawString(TailWrapped(g, progress, fText, lineW, replyH, wrap), fText, b, new RectangleF(body.X + pad, ry, lineW, replyH), wrap);
1306
+ else
1307
+ {
1308
+ string shown = petThinking.Length > 0 && !petFinished
1309
+ ? "思考 · " + Tail(g, petThinking, fText, lineW - g.MeasureString("思考 · ", fText, 100000, fmt).Width, fmt)
1310
+ : Tail(g, progress, fText, lineW, fmt);
1311
+ SizeF size = g.MeasureString(shown.Length > 0 ? shown : " ", fText, 100000, fmt);
1312
+ g.DrawString(shown, fText, b, body.X + pad, ry + (replyH - size.Height) / 2f, fmt);
1313
+ }
1314
+ }
1315
+ }
1316
+
1317
+ // Thinking and the step timeline.
1318
+ float ly = ry + replyH;
1319
+ if (showTimeline)
1320
+ {
1321
+ ly += 4 * s;
1322
+ using (var pen = new Pen(edge, Math.Max(1f, s))) g.DrawLine(pen, body.X + pad, ly, body.Right - pad, ly);
1323
+ ly += 5 * s;
1324
+ int first = Math.Max(0, petSteps.Count - stepRows);
1325
+ for (int i = first; i < petSteps.Count; i++)
1326
+ {
1327
+ bool current = i == petSteps.Count - 1 && !petFinished;
1328
+ float cy = ly + 11 * s;
1329
+ if (current)
1330
+ {
1331
+ using (var halo = new SolidBrush(Color.FromArgb(60, Accent))) g.FillEllipse(halo, body.X + pad, cy - 5 * s, 10 * s, 10 * s);
1332
+ using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, body.X + pad + 2 * s, cy - 3 * s, 6 * s, 6 * s);
1333
+ }
1334
+ 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);
1335
+ string line = Tail(g, petSteps[i], fAct, lineW - 16 * s, fmt);
1336
+ using (var b = new SolidBrush(current ? ink : muted)) g.DrawString(line, fAct, b, body.X + pad + 16 * s, ly + 3 * s, fmt);
1337
+ ly += 22 * s;
1338
+ }
1339
+ }
1340
+ else
1341
+ {
1342
+ string act;
1343
+ if (petFinished) act = petSteps.Count > 0 ? "最后操作 · " + petSteps[petSteps.Count - 1] : "";
1344
+ else if (isCompact) act = petSteps.Count > 0 ? petSteps[petSteps.Count - 1] : "准备操作…";
1345
+ else
1346
+ {
1347
+ var parts = new List<string>();
1348
+ for (int i = Math.Max(0, petSteps.Count - 4); i < petSteps.Count; i++) parts.Add(i < petSteps.Count - 1 ? "✓ " + petSteps[i] : petSteps[i]);
1349
+ act = string.Join(" › ", parts);
1350
+ }
1351
+ 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);
1352
+ 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);
1353
+ string shown = Tail(g, act, fAct, lineW - 14 * s, fmt);
1354
+ using (var b = new SolidBrush(isCompact ? ink : muted)) g.DrawString(shown, fAct, b, body.X + pad + 14 * s, ly + 3 * s, fmt);
1355
+ ly += 24 * s;
1356
+ }
1357
+
1358
+ // The instruction field: the card draws its frame and send button, a real text box sits on top.
1359
+ if (input != null)
1360
+ {
1361
+ ly += 6 * s;
1362
+ float sendD = 32 * s;
1363
+ var fieldRect = new RectangleF(body.X + pad, ly, lineW - sendD - 8 * s, 34 * s);
1364
+ using (var path = Rounded(fieldRect, 17 * s))
1365
+ {
1366
+ using (var brush = new SolidBrush(field)) g.FillPath(brush, path);
1367
+ using (var pen = new Pen(Color.FromArgb(150, Accent), Math.Max(1f, 1.2f * s))) g.DrawPath(pen, path);
1368
+ }
1369
+ bool sendHover = hoveredBtn == "send";
1370
+ bool sendPress = pressedBtn == "send";
1371
+ var sendHit = new RectangleF(body.Right - pad - sendD, ly + (34 * s - sendD) / 2f, sendD, sendD);
1372
+ var send = RectangleF.Inflate(sendHit, sendPress ? -0.8f * s : sendHover ? 1.1f * s : 0f, sendPress ? -0.8f * s : sendHover ? 1.1f * s : 0f);
1373
+ if (sendHover) using (var halo = new SolidBrush(Color.FromArgb(65, Accent))) g.FillEllipse(halo, RectangleF.Inflate(send, 2.5f * s, 2.5f * s));
1374
+ using (var brush = new SolidBrush(sendPress ? Color.FromArgb(190, 92, 62) : sendHover ? AccentHi : Accent)) g.FillEllipse(brush, send);
1375
+ using (var b = new SolidBrush(Color.White)) g.DrawString(glyphFont.Length > 0 ? "\uE724" : "➤", fGlyph, b, send, center);
1376
+ buttons.Add(new KeyValuePair<Rectangle, string>(Rectangle.Round(sendHit), "send"));
1377
+ 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));
1378
+ if (boxRect != inputBounds) { inputBounds = boxRect; input.Place(boxRect); }
1379
+ }
1380
+
1381
+ pet.SetBitmap(bmp, new Rectangle(x, y, W, H), 255);
1382
+ }
1383
+ pet.KeepOnTop();
1384
+ if (input != null) Native.SetWindowPos(input.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);
1385
+ }
1386
+
1387
+ static void RenderPill()
1388
+ {
1389
+ if (petMode) { RenderPet(); return; }
1390
+ if (pill == null) return;
1391
+ // The pill lives on the primary display (or the first one).
1392
+ Rectangle work = Rectangle.Empty; float scale = 1f;
1393
+ foreach (Dictionary<string, object> d in Screen2.Displays())
1394
+ {
1395
+ if (work.IsEmpty || (bool)d["primary"])
1396
+ {
1397
+ work = new Rectangle((int)d["workX"], (int)d["workY"], (int)d["workWidth"], (int)d["workHeight"]);
1398
+ scale = (int)d["dpi"] / 96f;
1399
+ }
1400
+ }
1401
+ string main, sub; string[] actions, captions;
1402
+ Content(out main, out sub, out actions, out captions);
1403
+ rendered = Key();
1404
+ if (sub.Length > 48) sub = sub.Substring(0, 47) + "…";
1405
+
1406
+ float px = 1.333f * scale; // points -> physical pixels
1407
+ using (var fMain = new Font("Microsoft YaHei UI", 10f * px, FontStyle.Bold, GraphicsUnit.Pixel))
1408
+ using (var fSub = new Font("Microsoft YaHei UI", 9f * px, FontStyle.Regular, GraphicsUnit.Pixel))
1409
+ using (var fBtn = new Font("Microsoft YaHei UI", 9f * px, FontStyle.Bold, GraphicsUnit.Pixel))
1410
+ using (var measureBmp = new Bitmap(1, 1))
1411
+ using (var mg = Graphics.FromImage(measureBmp))
1412
+ {
1413
+ mg.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
1414
+ var fmt = StringFormat.GenericTypographic;
1415
+ fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
1416
+ SizeF mainSize = mg.MeasureString(main, fMain, 10000, fmt);
1417
+ SizeF subSize = mg.MeasureString(sub, fSub, 10000, fmt);
1418
+ float pad = 14 * scale, gap = 11 * scale, iconSize = 24 * scale;
1419
+ float height = 40 * scale, btnH = 26 * scale, btnGap = 6 * scale;
1420
+ var btnSizes = new SizeF[captions.Length];
1421
+ float btnsW = 0;
1422
+ for (int i = 0; i < captions.Length; i++)
1423
+ {
1424
+ btnSizes[i] = mg.MeasureString(captions[i], fBtn, 10000, fmt);
1425
+ btnsW += btnSizes[i].Width + 22 * scale + (i > 0 ? btnGap : 0);
1426
+ }
1427
+ float width = pad + iconSize + gap + mainSize.Width + gap + 1 * scale + gap + subSize.Width + gap + btnsW + (pad - 7 * scale);
1428
+ int W = (int)Math.Ceiling(width), H = (int)Math.Ceiling(height);
1429
+ int x = work.X + (work.Width - W) / 2;
1430
+ int y = pillAtBottom ? work.Bottom - H - (int)(18 * scale) : work.Y + (int)(14 * scale);
1431
+
1432
+ using (var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb))
1433
+ using (var g = Graphics.FromImage(bmp))
1434
+ {
1435
+ g.Clear(Color.Transparent);
1436
+ g.SmoothingMode = SmoothingMode.AntiAlias;
1437
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
1438
+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
1439
+ var body = new RectangleF(0.5f, 0.5f, W - 1, H - 1);
1440
+ using (var path = Rounded(body, (H - 1) / 2f))
1441
+ {
1442
+ using (var brush = new SolidBrush(Color.FromArgb(242, 31, 30, 29))) g.FillPath(brush, path);
1443
+ using (var pen = new Pen(Color.FromArgb(200, Accent), Math.Max(1f, 1.2f * scale))) g.DrawPath(pen, path);
1444
+ }
1445
+ var iconRect = new RectangleF(pad, (H - iconSize) / 2f, iconSize, iconSize);
1446
+ if (icon != null) g.DrawImage(icon, iconRect);
1447
+ else using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, RectangleF.Inflate(iconRect, -5 * scale, -5 * scale));
1448
+ float tx = pad + iconSize + gap;
1449
+ using (var b = new SolidBrush(Color.FromArgb(250, 250, 249))) g.DrawString(main, fMain, b, tx, (H - mainSize.Height) / 2f, fmt);
1450
+ tx += mainSize.Width + gap;
1451
+ 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);
1452
+ tx += 1 * scale + gap;
1453
+ using (var b = new SolidBrush(Color.FromArgb(175, 172, 168))) g.DrawString(sub, fSub, b, tx, (H - subSize.Height) / 2f, fmt);
1454
+ tx += subSize.Width + gap;
1455
+ buttons.Clear();
1456
+ for (int i = 0; i < captions.Length; i++)
1457
+ {
1458
+ float bw = btnSizes[i].Width + 22 * scale;
1459
+ var btn = new RectangleF(tx, (H - btnH) / 2f, bw, btnH);
1460
+ bool primary = i == 0;
1461
+ using (var path = Rounded(btn, btnH / 2f))
1462
+ using (var brush = new SolidBrush(primary ? Accent : Color.FromArgb(70, 68, 66))) g.FillPath(brush, path);
1463
+ 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);
1464
+ buttons.Add(new KeyValuePair<Rectangle, string>(Rectangle.Round(btn), actions[i]));
1465
+ tx += bw + btnGap;
1466
+ }
1467
+ pill.SetBitmap(bmp, new Rectangle(x, y, W, H), 255);
1468
+ }
1469
+ lock (RectLock) pillRect = new Rectangle(x, y, W, H);
1470
+ }
1471
+ pill.KeepOnTop();
1472
+ }
1473
+
1474
+ static void InstallHook()
1475
+ {
1476
+ if (hook == IntPtr.Zero)
1477
+ {
1478
+ hookProc = HookCallback;
1479
+ hook = Native.SetWindowsHookEx(13, hookProc, Native.GetModuleHandle(null), 0);
1480
+ }
1481
+ if (mouseHook == IntPtr.Zero)
1482
+ {
1483
+ mouseHookProc = MouseHookCallback;
1484
+ mouseHook = Native.SetWindowsHookEx(14, mouseHookProc, Native.GetModuleHandle(null), 0);
1485
+ }
1486
+ }
1487
+
1488
+ static void RemoveHook()
1489
+ {
1490
+ if (hook != IntPtr.Zero)
1491
+ {
1492
+ Native.UnhookWindowsHookEx(hook);
1493
+ hook = IntPtr.Zero;
1494
+ }
1495
+ if (mouseHook != IntPtr.Zero)
1496
+ {
1497
+ Native.UnhookWindowsHookEx(mouseHook);
1498
+ mouseHook = IntPtr.Zero;
1499
+ }
1500
+ }
1501
+
1502
+ static bool IsOnOwnUi(int x, int y)
1503
+ {
1504
+ lock (RectLock)
1505
+ {
1506
+ if (!pillRect.IsEmpty && pillRect.Contains(x, y)) return true;
1507
+ if (pet != null) { Rectangle pr = pet.Physical; if (!pr.IsEmpty && pr.Contains(x, y)) return true; }
1508
+ if (!inputBounds.IsEmpty && inputBounds.Contains(x, y)) return true;
1509
+ }
1510
+ IntPtr card = CardLayer.Hwnd;
1511
+ if (card != IntPtr.Zero && Native.IsWindow(card))
1512
+ {
1513
+ Native.RECT rc;
1514
+ if (Native.GetWindowRect(card, out rc) && x >= rc.Left && x < rc.Right && y >= rc.Top && y < rc.Bottom)
1515
+ return true;
1516
+ }
1517
+ return false;
1518
+ }
1519
+
1520
+ static void RecordUserMouseAsync(string kind, string button, string direction, int x, int y)
1521
+ {
1522
+ ThreadPool.QueueUserWorkItem(delegate
1523
+ {
1524
+ try
1525
+ {
1526
+ var win = Windows.At(x, y);
1527
+ string exe = win.ContainsKey("exe") ? Convert.ToString(win["exe"]) ?? "" : "";
1528
+ string title = win.ContainsKey("title") ? Convert.ToString(win["title"]) ?? "" : "";
1529
+ string exeLower = exe.ToLowerInvariant();
1530
+ // Clicking the DSH chat window itself is the user reading/chatting, not taking over target apps.
1531
+ if (exeLower == "cu-helper.exe" || exeLower == "deepseek harness.exe") return;
1532
+ string role = "", name = "";
1533
+ bool isPassword = false;
1534
+ if (kind == "click" || kind == "double_click")
1535
+ Uia.DescribeAtPoint(x, y, out role, out name, out isPassword);
1536
+ var data = new Dictionary<string, object>();
1537
+ data["kind"] = kind;
1538
+ if (!string.IsNullOrEmpty(button)) data["button"] = button;
1539
+ if (!string.IsNullOrEmpty(direction)) data["direction"] = direction;
1540
+ data["x"] = x;
1541
+ data["y"] = y;
1542
+ if (exe.Length > 0) data["exe"] = exe;
1543
+ if (title.Length > 0) data["title"] = title.Length > 80 ? title.Substring(0, 80) + "…" : title;
1544
+ if (role.Length > 0) data["role"] = role;
1545
+ if (name.Length > 0) data["name"] = name;
1546
+ if (isPassword) data["password"] = true;
1547
+ Program.EmitDataEvent("user_action", data);
1548
+ }
1549
+ catch (Exception) { }
1550
+ });
1551
+ }
1552
+
1553
+ static void RecordUserKeyAsync(int count)
1554
+ {
1555
+ ThreadPool.QueueUserWorkItem(delegate
1556
+ {
1557
+ try
1558
+ {
1559
+ IntPtr fg = Native.GetForegroundWindow();
1560
+ var win = Windows.Describe(fg);
1561
+ string exe = win.ContainsKey("exe") ? Convert.ToString(win["exe"]) ?? "" : "";
1562
+ string title = win.ContainsKey("title") ? Convert.ToString(win["title"]) ?? "" : "";
1563
+ string exeLower = exe.ToLowerInvariant();
1564
+ if (exeLower == "cu-helper.exe" || exeLower == "deepseek harness.exe") return;
1565
+ string role, name;
1566
+ bool isPassword;
1567
+ Uia.DescribeFocused(out role, out name, out isPassword);
1568
+ var data = new Dictionary<string, object>();
1569
+ data["kind"] = "type";
1570
+ data["keys"] = count;
1571
+ if (exe.Length > 0) data["exe"] = exe;
1572
+ if (title.Length > 0) data["title"] = title.Length > 80 ? title.Substring(0, 80) + "…" : title;
1573
+ if (role.Length > 0) data["role"] = role;
1574
+ if (name.Length > 0) data["name"] = name;
1575
+ if (isPassword) data["password"] = true;
1576
+ Program.EmitDataEvent("user_action", data);
1577
+ }
1578
+ catch (Exception) { }
1579
+ });
1580
+ }
1581
+
1582
+ static IntPtr MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam)
1583
+ {
1584
+ if (nCode >= 0 && visible)
1585
+ {
1586
+ int msg = wParam.ToInt32();
1587
+ // Deliberately ignore WM_MOUSEMOVE (0x0200): nudging the mouse never triggers takeover.
1588
+ bool isClick = msg == 0x0201 || msg == 0x0204 || msg == 0x0207;
1589
+ bool isWheel = msg == 0x020A || msg == 0x020E;
1590
+ if (isClick || isWheel)
1591
+ {
1592
+ var ms = (Native.MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.MSLLHOOKSTRUCT));
1593
+ // Ignore synthetic clicks injected by our own SendInput (LLMHF_INJECTED = 0x01, lower IL = 0x02).
1594
+ if ((ms.flags & 0x03) == 0 && ms.dwExtraInfo != Native.Marker && !IsOnOwnUi(ms.pt.X, ms.pt.Y))
1595
+ {
1596
+ int now = Environment.TickCount;
1597
+ lastTyping = now;
1598
+ if (isClick)
1599
+ {
1600
+ string button = msg == 0x0204 ? "right" : msg == 0x0207 ? "middle" : "left";
1601
+ string kind = "click";
1602
+ lock (UserActionLock)
1603
+ {
1604
+ if (button == "left" && unchecked(now - lastClickTick) <= 500
1605
+ && Math.Abs(ms.pt.X - lastClickX) <= 6 && Math.Abs(ms.pt.Y - lastClickY) <= 6)
1606
+ {
1607
+ kind = "double_click";
1608
+ lastClickTick = int.MinValue / 2;
1609
+ }
1610
+ else
1611
+ {
1612
+ lastClickTick = now;
1613
+ lastClickX = ms.pt.X;
1614
+ lastClickY = ms.pt.Y;
1615
+ }
1616
+ }
1617
+ RecordUserMouseAsync(kind, button, "", ms.pt.X, ms.pt.Y);
1618
+ }
1619
+ else
1620
+ {
1621
+ bool shouldEmit = false;
1622
+ lock (UserActionLock)
1623
+ {
1624
+ if (unchecked(now - lastScrollTick) > 600) { lastScrollTick = now; shouldEmit = true; }
1625
+ }
1626
+ if (shouldEmit)
1627
+ {
1628
+ short delta = (short)((ms.mouseData >> 16) & 0xFFFF);
1629
+ string dir = msg == 0x020E ? (delta >= 0 ? "right" : "left") : (delta >= 0 ? "up" : "down");
1630
+ RecordUserMouseAsync("scroll", "", dir, ms.pt.X, ms.pt.Y);
1631
+ }
1632
+ }
1633
+ }
1634
+ }
1635
+ }
1636
+ return Native.CallNextHookEx(mouseHook, nCode, wParam, lParam);
1637
+ }
1638
+
1639
+ static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
1640
+ {
1641
+ if (nCode >= 0 && visible)
1642
+ {
1643
+ int msg = wParam.ToInt32();
1644
+ var kb = (Native.KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.KBDLLHOOKSTRUCT));
1645
+ // Only physical keys count: our own SendInput sets LLKHF_INJECTED (0x10).
1646
+ if ((kb.flags & 0x10) == 0 && !(InputHwnd != IntPtr.Zero && Native.GetForegroundWindow() == InputHwnd))
1647
+ {
1648
+ bool down = msg == 0x100 || msg == 0x104;
1649
+ if (kb.vkCode == 0x1B)
1650
+ {
1651
+ // Esc toggles pause and is swallowed, so the focused app
1652
+ // (DeepSeek Harness included) never turns it into "stop".
1653
+ if (down) invoker.BeginInvoke((MethodInvoker)delegate { Press(paused ? "resume" : "pause"); });
1654
+ return new IntPtr(1);
1655
+ }
1656
+ // Modifier-only presses (Shift to switch the IME, Ctrl, Alt, Win)
1657
+ // and synthetic packets are not typing.
1658
+ int vk = (int)kb.vkCode;
1659
+ bool modifier = vk == 0x10 || vk == 0x11 || vk == 0x12 || (vk >= 0xA0 && vk <= 0xA5) || vk == 0x5B || vk == 0x5C || vk == 0x14 || vk == 0xE7 || vk == 0xFF;
1660
+ if (down && !modifier)
1661
+ {
1662
+ // The user is typing: the host waits. Mouse movement is
1663
+ // deliberately ignored (too easy to nudge).
1664
+ int now = Environment.TickCount;
1665
+ lastTyping = now;
1666
+ if (unchecked(now - lastEmit) > 250) { lastEmit = now; Program.EmitEvent("user_input", "vk=0x" + vk.ToString("X2")); }
1667
+ int emitCount = 0;
1668
+ lock (UserActionLock)
1669
+ {
1670
+ keyBurstCount++;
1671
+ if (unchecked(now - lastKeySummaryTick) > 900)
1672
+ {
1673
+ lastKeySummaryTick = now;
1674
+ emitCount = keyBurstCount;
1675
+ keyBurstCount = 0;
1676
+ }
1677
+ }
1678
+ if (emitCount > 0) RecordUserKeyAsync(emitCount);
1679
+ }
1680
+ }
1681
+ }
1682
+ return Native.CallNextHookEx(hook, nCode, wParam, lParam);
1683
+ }
1684
+ }
1685
+ }