@copylee/dsh-computer-use 0.2.2 → 0.5.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.
@@ -113,6 +113,8 @@ namespace DshComputerUse
113
113
  [DllImport("user32.dll", SetLastError = true)]
114
114
  public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, IntPtr pptDst, IntPtr psize, IntPtr hdcSrc, IntPtr pptSrc, int crKey, ref BLENDFUNCTION pblend, int flags);
115
115
  [DllImport("user32.dll")] public static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint affinity);
116
+ [DllImport("user32.dll")] public static extern bool ReleaseCapture();
117
+ [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr w, IntPtr l);
116
118
 
117
119
  public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
118
120
  [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc fn, IntPtr hMod, uint threadId);
@@ -151,6 +153,13 @@ namespace DshComputerUse
151
153
  object v; if (!d.TryGetValue(k, out v) || v == null) return def;
152
154
  return Convert.ToBoolean(v);
153
155
  }
156
+ public static List<string> Strs(Dictionary<string, object> d, string k)
157
+ {
158
+ var list = new List<string>(); object v;
159
+ if (d.TryGetValue(k, out v) && v is IEnumerable && !(v is string))
160
+ foreach (var item in (IEnumerable)v) list.Add(Convert.ToString(item));
161
+ return list;
162
+ }
154
163
  public static List<int> Ints(Dictionary<string, object> d, string k)
155
164
  {
156
165
  var list = new List<int>(); object v;
@@ -271,6 +280,9 @@ namespace DshComputerUse
271
280
  case "clipboard_release": Clip.Release(); return null;
272
281
  case "paste": return Input.Paste(Args.Str(r, "text", ""), Args.Bool(r, "restore", true), Args.Int(r, "waitMs", 250));
273
282
  case "windows": return Windows.List();
283
+ case "background": return Windows.Background();
284
+ case "tray_restore": return Tray.Restore(Args.Str(r, "exe", ""));
285
+ case "card_opacity": CardLayer.SetOpacity(Args.Int(r, "opacity", 100)); return null;
274
286
  case "foreground": return Windows.Describe(Native.GetForegroundWindow());
275
287
  case "window_at": return Windows.At(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
276
288
  case "focus": return Windows.Focus(new IntPtr(Convert.ToInt64(r["hwnd"])));
@@ -283,9 +295,11 @@ namespace DshComputerUse
283
295
  case "ui": return Uia.Elements(r);
284
296
  case "overlay_show": Overlay.ExcludeFromCapture = Args.Bool(r, "excludeFromCapture", true); Overlay.Show(r); return null;
285
297
  case "overlay_pause": Overlay.SetPaused(Args.Bool(r, "paused", false)); return null;
286
- case "window_card": 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));
298
+ 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));
287
299
  case "window_uncard": return Windows.Uncard(new IntPtr(Convert.ToInt64(r["hwnd"])));
288
300
  case "overlay_status": Overlay.Status(Args.Str(r, "status", "")); return null;
301
+ case "pet_update": Overlay.PetUpdate(Args.Str(r, "text", ""), Args.Str(r, "thinking", ""), Args.Strs(r, "steps"), Args.Bool(r, "thinkingLatest", false)); return null;
302
+ case "pet_finish": Overlay.Finish(Args.Str(r, "text", ""), Args.Int(r, "holdMs", 4000)); return null;
289
303
  case "overlay_hide": Overlay.Hide(); return null;
290
304
  default: throw new Exception("unknown command: " + cmd);
291
305
  }
@@ -533,11 +547,33 @@ namespace DshComputerUse
533
547
  static void Send(List<Native.INPUT> inputs)
534
548
  {
535
549
  if (inputs.Count == 0) return;
550
+ WaitForInstructionBox();
536
551
  uint sent = Native.SendInput((uint)inputs.Count, inputs.ToArray(), InputSize);
537
552
  if (sent != inputs.Count)
538
553
  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.");
539
554
  }
540
555
 
556
+ /**
557
+ * The user opened the progress card's instruction box mid-action (say,
558
+ * halfway through typing): hold the rest until it closes and focus is
559
+ * back, so no keystroke lands in the box.
560
+ */
561
+ static void WaitForInstructionBox()
562
+ {
563
+ if (Overlay.InputHwnd == IntPtr.Zero) return;
564
+ var until = DateTime.UtcNow.AddSeconds(90);
565
+ while (Overlay.InputHwnd != IntPtr.Zero)
566
+ {
567
+ if (DateTime.UtcNow > until) throw new Exception("Stopped: the user is typing an instruction to you in the progress card.");
568
+ Thread.Sleep(100);
569
+ }
570
+ // The box hands the focus back to the window it took it from: wait until that happened.
571
+ IntPtr target = Overlay.InputReturnsTo;
572
+ var back = DateTime.UtcNow.AddSeconds(4);
573
+ while (target != IntPtr.Zero && Native.IsWindow(target) && Native.GetForegroundWindow() != target && DateTime.UtcNow < back) Thread.Sleep(50);
574
+ Thread.Sleep(150);
575
+ }
576
+
541
577
  public static void Move(int x, int y)
542
578
  {
543
579
  Native.SetCursorPos(x, y);
@@ -842,6 +878,47 @@ namespace DshComputerUse
842
878
  {
843
879
  public static IntPtr Hwnd = IntPtr.Zero;
844
880
  static int originalEx;
881
+ /** Resting alpha of the card (see-through); it turns opaque while the pointer rests on it. */
882
+ static byte alpha = 255;
883
+ static bool hot;
884
+ static int hiding;
885
+ static DateTime enteredAt = DateTime.MaxValue;
886
+ static System.Threading.Timer hover;
887
+ static readonly object Gate = new object();
888
+
889
+ public static void SetOpacity(int percent)
890
+ {
891
+ lock (Gate)
892
+ {
893
+ alpha = (byte)Math.Max(64, Math.Min(255, (int)Math.Round(Math.Max(25, Math.Min(100, percent)) * 2.55)));
894
+ if (alpha < 255 && hover == null) hover = new System.Threading.Timer(delegate { Track(); }, null, 150, 150);
895
+ Apply();
896
+ }
897
+ }
898
+
899
+ static byte Current() { return hot ? (byte)255 : alpha; }
900
+
901
+ static void Apply()
902
+ {
903
+ if (hiding == 0 && Hwnd != IntPtr.Zero && Native.IsWindow(Hwnd)) Native.SetLayeredWindowAttributes(Hwnd, 0, Current(), 2);
904
+ }
905
+
906
+ /** Opaque once the pointer has rested on the card for a moment (the user wants to read or click it). */
907
+ static void Track()
908
+ {
909
+ lock (Gate)
910
+ {
911
+ bool inside = false;
912
+ if (Live() && alpha < 255)
913
+ {
914
+ Native.POINT p; Native.GetCursorPos(out p);
915
+ inside = Frame(Hwnd).Contains(p.X, p.Y);
916
+ }
917
+ if (!inside) { enteredAt = DateTime.MaxValue; if (hot) { hot = false; Apply(); } return; }
918
+ if (enteredAt == DateTime.MaxValue) enteredAt = DateTime.UtcNow;
919
+ if (!hot && (DateTime.UtcNow - enteredAt).TotalMilliseconds >= 300) { hot = true; Apply(); }
920
+ }
921
+ }
845
922
 
846
923
  static bool Live()
847
924
  {
@@ -863,7 +940,7 @@ namespace DshComputerUse
863
940
  Hwnd = hwnd;
864
941
  originalEx = Native.GetWindowLong(hwnd, -20);
865
942
  Native.SetWindowLong(hwnd, -20, originalEx | 0x80000);
866
- Native.SetLayeredWindowAttributes(hwnd, 0, 255, 2);
943
+ lock (Gate) { hot = false; enteredAt = DateTime.MaxValue; Native.SetLayeredWindowAttributes(hwnd, 0, Current(), 2); }
867
944
  }
868
945
 
869
946
  public static void Detach()
@@ -913,11 +990,17 @@ namespace DshComputerUse
913
990
  public Hidden(IntPtr hwnd)
914
991
  {
915
992
  this.hwnd = hwnd;
916
- if (hwnd != IntPtr.Zero) Native.SetLayeredWindowAttributes(hwnd, 0, 0, 2);
993
+ if (hwnd == IntPtr.Zero) return;
994
+ lock (Gate) { hiding++; Native.SetLayeredWindowAttributes(hwnd, 0, 0, 2); }
917
995
  }
918
996
  public void Dispose()
919
997
  {
920
- if (hwnd != IntPtr.Zero && Native.IsWindow(hwnd)) Native.SetLayeredWindowAttributes(hwnd, 0, 255, 2);
998
+ if (hwnd == IntPtr.Zero) return;
999
+ lock (Gate)
1000
+ {
1001
+ hiding--;
1002
+ if (hiding == 0 && Native.IsWindow(hwnd)) Native.SetLayeredWindowAttributes(hwnd, 0, Current(), 2);
1003
+ }
921
1004
  }
922
1005
  }
923
1006
  }
@@ -1021,24 +1104,30 @@ namespace DshComputerUse
1021
1104
  /** While the agent moves, clicks or scrolls, the card lets the mouse through. */
1022
1105
  internal sealed class PassThrough : IDisposable
1023
1106
  {
1024
- readonly IntPtr hwnd;
1025
- readonly int oldEx;
1026
- readonly bool active;
1107
+ readonly IntPtr[] hwnds;
1108
+ readonly int[] oldEx;
1109
+ bool active;
1027
1110
 
1111
+ /** The DSH card and our progress card let injected pointer input through. */
1028
1112
  public PassThrough()
1029
1113
  {
1030
- hwnd = CardLayer.Hwnd;
1031
- if (hwnd == IntPtr.Zero || !Native.IsWindow(hwnd)) return;
1032
- oldEx = Native.GetWindowLong(hwnd, -20);
1033
- Native.SetWindowLong(hwnd, -20, oldEx | 0x20 | 0x80000); // WS_EX_TRANSPARENT (layered already)
1034
- active = true;
1114
+ hwnds = new[] { CardLayer.Hwnd, Overlay.PetHwnd };
1115
+ oldEx = new int[hwnds.Length];
1116
+ for (int i = 0; i < hwnds.Length; i++)
1117
+ {
1118
+ if (hwnds[i] == IntPtr.Zero || !Native.IsWindow(hwnds[i])) { hwnds[i] = IntPtr.Zero; continue; }
1119
+ oldEx[i] = Native.GetWindowLong(hwnds[i], -20);
1120
+ Native.SetWindowLong(hwnds[i], -20, oldEx[i] | 0x20 | 0x80000); // WS_EX_TRANSPARENT (layered already)
1121
+ active = true;
1122
+ }
1035
1123
  }
1036
1124
 
1037
1125
  public void Dispose()
1038
1126
  {
1039
1127
  if (!active) return;
1040
1128
  Thread.Sleep(60); // let the injected input reach its target first
1041
- if (Native.IsWindow(hwnd)) Native.SetWindowLong(hwnd, -20, oldEx);
1129
+ for (int i = 0; i < hwnds.Length; i++)
1130
+ if (hwnds[i] != IntPtr.Zero && Native.IsWindow(hwnds[i])) Native.SetWindowLong(hwnds[i], -20, oldEx[i]);
1042
1131
  }
1043
1132
  }
1044
1133
 
@@ -1111,7 +1200,7 @@ namespace DshComputerUse
1111
1200
  uint pid = 0;
1112
1201
  if (h != IntPtr.Zero) Native.GetWindowThreadProcessId(h, out pid);
1113
1202
  uint cardPid = CardLayer.Pid();
1114
- if (h == IntPtr.Zero || pid == (uint)Process.GetCurrentProcess().Id || (cardPid != 0 && pid == cardPid))
1203
+ if (h == IntPtr.Zero || pid == (uint)Process.GetCurrentProcess().Id || (cardPid != 0 && pid == cardPid) || SeeThrough(pid))
1115
1204
  {
1116
1205
  // Our own status pill is under the point (it dodges before the
1117
1206
  // click): report the topmost foreign window there instead.
@@ -1121,7 +1210,7 @@ namespace DshComputerUse
1121
1210
  {
1122
1211
  if (!Native.IsWindowVisible(w)) return true;
1123
1212
  uint p; Native.GetWindowThreadProcessId(w, out p);
1124
- if (p == self || (cardPid != 0 && p == cardPid)) return true; // our overlay, the DSH card
1213
+ if (p == self || (cardPid != 0 && p == cardPid) || SeeThrough(p)) return true; // our overlay, the DSH card, game overlays
1125
1214
  if ((Native.GetWindowLong(w, -20) & 0x20) != 0) return true; // WS_EX_TRANSPARENT
1126
1215
  if (Native.IsIconic(w)) return true;
1127
1216
  int cloaked;
@@ -1137,6 +1226,92 @@ namespace DshComputerUse
1137
1226
  return Describe(h);
1138
1227
  }
1139
1228
 
1229
+ /** Full-screen overlays that never take input themselves (NVIDIA / Xbox Game Bar...). */
1230
+ static readonly string[] Overlays = { "nvidia overlay.exe", "nvsphelper64.exe", "gamebar.exe", "gamebarftserver.exe" };
1231
+
1232
+ static bool SeeThrough(uint pid)
1233
+ {
1234
+ if (pid == 0) return false;
1235
+ string exe = Path.GetFileName(ExePath(pid)).ToLowerInvariant();
1236
+ return Array.IndexOf(Overlays, exe) >= 0;
1237
+ }
1238
+
1239
+ /**
1240
+ * Apps that run without any visible window (closed to the system tray):
1241
+ * per program, its largest hidden, titled, unowned top-level window.
1242
+ */
1243
+ public static List<object> Background()
1244
+ {
1245
+ uint self = (uint)Process.GetCurrentProcess().Id;
1246
+ var visible = new HashSet<uint>();
1247
+ var best = new Dictionary<uint, KeyValuePair<IntPtr, int>>();
1248
+ Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
1249
+ {
1250
+ uint pid; Native.GetWindowThreadProcessId(h, out pid);
1251
+ if (pid == self || pid == 0) return true;
1252
+ if (Native.GetWindow(h, 4) != IntPtr.Zero) return true; // owned
1253
+ if (Native.IsWindowVisible(h))
1254
+ {
1255
+ int cloaked;
1256
+ bool isCloaked = Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0;
1257
+ if (!isCloaked && Native.GetWindowTextLength(h) > 0) visible.Add(pid);
1258
+ return true;
1259
+ }
1260
+ if (Native.GetWindowTextLength(h) == 0) return true;
1261
+ var cls = new StringBuilder(256); Native.GetClassName(h, cls, cls.Capacity);
1262
+ string c = cls.ToString();
1263
+ if (c == "ConsoleWindowClass" || c == "IME" || c == "MSCTFIME UI" || c.StartsWith("GDI+")) return true;
1264
+ Native.RECT rc; Native.GetWindowRect(h, out rc);
1265
+ int area = (rc.Right - rc.Left) * (rc.Bottom - rc.Top);
1266
+ if (rc.Right - rc.Left < 240 || rc.Bottom - rc.Top < 160) return true;
1267
+ KeyValuePair<IntPtr, int> seen;
1268
+ if (!best.TryGetValue(pid, out seen) || seen.Value < area) best[pid] = new KeyValuePair<IntPtr, int>(h, area);
1269
+ return true;
1270
+ };
1271
+ Native.EnumWindows(cb, IntPtr.Zero);
1272
+ GC.KeepAlive(cb);
1273
+ // Programs whose other process shows a window are not in the background.
1274
+ var shownExes = new HashSet<string>();
1275
+ foreach (var pid in visible) shownExes.Add(Path.GetFileName(ExePath(pid)).ToLowerInvariant());
1276
+ var byExe = new Dictionary<string, Dictionary<string, object>>();
1277
+ foreach (var pair in best)
1278
+ {
1279
+ if (visible.Contains(pair.Key)) continue;
1280
+ var d = Describe(pair.Value.Key);
1281
+ string exe = ((string)d["exe"]).ToLowerInvariant();
1282
+ if (exe.Length == 0 || shownExes.Contains(exe) || exe == "explorer.exe" || exe == "textinputhost.exe" || exe == "shellexperiencehost.exe" || exe == "searchhost.exe" || exe == "startmenuexperiencehost.exe") continue;
1283
+ Dictionary<string, object> prev;
1284
+ if (byExe.TryGetValue(exe, out prev) && Convert.ToInt32(prev["width"]) * Convert.ToInt32(prev["height"]) >= pair.Value.Value) continue;
1285
+ byExe[exe] = d;
1286
+ }
1287
+ var owners = Tray.WindowsByPid();
1288
+ var exeOf = new Dictionary<uint, string>();
1289
+ foreach (var pid in owners.Keys) exeOf[pid] = Path.GetFileName(ExePath(pid));
1290
+ foreach (var d in byExe.Values) d["tray"] = Tray.HasIcon((string)d["exe"], owners, exeOf);
1291
+ return new List<object>(byExe.Values);
1292
+ }
1293
+
1294
+ /** Visible, titled, unowned windows of these processes. */
1295
+ public static IntPtr ShownWindowOf(HashSet<uint> pids)
1296
+ {
1297
+ IntPtr found = IntPtr.Zero; int bestArea = 0;
1298
+ Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data)
1299
+ {
1300
+ if (!Native.IsWindowVisible(h) || Native.GetWindowTextLength(h) == 0 || Native.GetWindow(h, 4) != IntPtr.Zero) return true;
1301
+ uint pid; Native.GetWindowThreadProcessId(h, out pid);
1302
+ if (!pids.Contains(pid)) return true;
1303
+ int cloaked;
1304
+ if (Native.DwmGetWindowAttribute(h, 14, out cloaked, 4) == 0 && cloaked != 0) return true;
1305
+ Native.RECT rc; Native.GetWindowRect(h, out rc);
1306
+ int area = (rc.Right - rc.Left) * (rc.Bottom - rc.Top);
1307
+ if (area > bestArea) { bestArea = area; found = h; }
1308
+ return true;
1309
+ };
1310
+ Native.EnumWindows(cb, IntPtr.Zero);
1311
+ GC.KeepAlive(cb);
1312
+ return found;
1313
+ }
1314
+
1140
1315
  public static Dictionary<string, object> Focus(IntPtr hwnd)
1141
1316
  {
1142
1317
  if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
@@ -1253,6 +1428,170 @@ namespace DshComputerUse
1253
1428
  }
1254
1429
  }
1255
1430
 
1431
+ /**
1432
+ * Bring a program that lives in the system tray back the way the user
1433
+ * would: click its notification-area icon (opening the "show hidden icons"
1434
+ * overflow first). Launching it again would start a second instance (QQ
1435
+ * shows a second login), and showing its hidden window directly leaves
1436
+ * Electron / Qt apps frozen.
1437
+ */
1438
+ internal static class Tray
1439
+ {
1440
+ [StructLayout(LayoutKind.Sequential)]
1441
+ struct NOTIFYICONIDENTIFIER { public int cbSize; public IntPtr hWnd; public uint uID; public Guid guidItem; }
1442
+ [DllImport("shell32.dll")] static extern int Shell_NotifyIconGetRect(ref NOTIFYICONIDENTIFIER id, out Native.RECT rect);
1443
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string cls, string title);
1444
+
1445
+ static bool IconRect(IntPtr hwnd, uint id, out Rectangle rect)
1446
+ {
1447
+ var n = new NOTIFYICONIDENTIFIER(); n.cbSize = Marshal.SizeOf(typeof(NOTIFYICONIDENTIFIER)); n.hWnd = hwnd; n.uID = id;
1448
+ Native.RECT rc;
1449
+ bool ok = Shell_NotifyIconGetRect(ref n, out rc) == 0 && rc.Right > rc.Left;
1450
+ rect = ok ? new Rectangle(rc.Left, rc.Top, rc.Right - rc.Left, rc.Bottom - rc.Top) : Rectangle.Empty;
1451
+ return ok;
1452
+ }
1453
+
1454
+ /** Top-level and message-only windows per process: tray icons are registered on one of them. */
1455
+ public static Dictionary<uint, List<IntPtr>> WindowsByPid()
1456
+ {
1457
+ var map = new Dictionary<uint, List<IntPtr>>();
1458
+ Action<IntPtr> add = delegate (IntPtr h)
1459
+ {
1460
+ uint pid; Native.GetWindowThreadProcessId(h, out pid);
1461
+ List<IntPtr> list;
1462
+ if (!map.TryGetValue(pid, out list)) map[pid] = list = new List<IntPtr>();
1463
+ list.Add(h);
1464
+ };
1465
+ Native.EnumWindowsProc cb = delegate (IntPtr h, IntPtr data) { add(h); return true; };
1466
+ Native.EnumWindows(cb, IntPtr.Zero);
1467
+ GC.KeepAlive(cb);
1468
+ IntPtr m = IntPtr.Zero;
1469
+ while ((m = FindWindowEx(new IntPtr(-3), m, null, null)) != IntPtr.Zero) add(m); // HWND_MESSAGE
1470
+ return map;
1471
+ }
1472
+
1473
+ /** The icon's owner window and id. */
1474
+ static bool Find(HashSet<uint> pids, Dictionary<uint, List<IntPtr>> byPid, out IntPtr owner, out uint id)
1475
+ {
1476
+ var windows = new List<IntPtr>();
1477
+ foreach (var pid in pids) { List<IntPtr> list; if (byPid.TryGetValue(pid, out list)) windows.AddRange(list); }
1478
+ foreach (var h in windows)
1479
+ {
1480
+ // Icon ids are small; scan further only on windows that look like tray hosts.
1481
+ var cls = new StringBuilder(256); Native.GetClassName(h, cls, cls.Capacity);
1482
+ string c = cls.ToString().ToLowerInvariant();
1483
+ uint ids = c.Contains("tray") || c.Contains("notify") || c.Contains("icon") ? 128u : 16u;
1484
+ for (uint i = 0; i < ids; i++)
1485
+ {
1486
+ Rectangle r;
1487
+ if (IconRect(h, i, out r)) { owner = h; id = i; return true; }
1488
+ }
1489
+ }
1490
+ owner = IntPtr.Zero; id = 0;
1491
+ return false;
1492
+ }
1493
+
1494
+ public static bool HasIcon(string exe, Dictionary<uint, List<IntPtr>> byPid, Dictionary<uint, string> exeOf)
1495
+ {
1496
+ // Process.GetProcessesByName is slow; the processes owning windows are enough here.
1497
+ var pids = new HashSet<uint>();
1498
+ foreach (var pair in exeOf)
1499
+ if (string.Equals(pair.Value, exe, StringComparison.OrdinalIgnoreCase)) pids.Add(pair.Key);
1500
+ IntPtr owner; uint id;
1501
+ return pids.Count > 0 && Find(pids, byPid, out owner, out id);
1502
+ }
1503
+
1504
+ static HashSet<uint> Pids(string exe)
1505
+ {
1506
+ var pids = new HashSet<uint>();
1507
+ foreach (var p in Process.GetProcessesByName(Path.GetFileNameWithoutExtension(exe))) { pids.Add((uint)p.Id); p.Dispose(); }
1508
+ return pids;
1509
+ }
1510
+
1511
+ /** The taskbar's "show hidden icons" button. */
1512
+ static Rectangle Chevron()
1513
+ {
1514
+ Rectangle found = Rectangle.Empty;
1515
+ var worker = new Thread(delegate ()
1516
+ {
1517
+ try
1518
+ {
1519
+ var tray = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "Shell_TrayWnd"));
1520
+ if (tray == null) return;
1521
+ var buttons = tray.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));
1522
+ AutomationElement pick = null;
1523
+ foreach (AutomationElement b in buttons)
1524
+ {
1525
+ string name = b.Current.Name ?? "";
1526
+ if (name.Contains("隐藏的图标") || name.ToLowerInvariant().Contains("hidden icons") || b.Current.ClassName == "NotifyIconOverflowButton") { pick = b; break; }
1527
+ }
1528
+ if (pick == null)
1529
+ foreach (AutomationElement b in buttons)
1530
+ if (b.Current.ClassName == "SystemTray.NormalButton") { pick = b; break; }
1531
+ if (pick == null) return;
1532
+ var r = pick.Current.BoundingRectangle;
1533
+ found = new Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height);
1534
+ }
1535
+ catch (Exception) { }
1536
+ });
1537
+ worker.IsBackground = true;
1538
+ worker.SetApartmentState(ApartmentState.MTA);
1539
+ worker.Start();
1540
+ worker.Join(4000);
1541
+ return found;
1542
+ }
1543
+
1544
+ static void Click(Rectangle r, int count)
1545
+ {
1546
+ var d = new Dictionary<string, object>();
1547
+ d["x"] = r.X + r.Width / 2; d["y"] = r.Y + r.Height / 2; d["count"] = count;
1548
+ using (new PassThrough()) Input.Click(d);
1549
+ }
1550
+
1551
+ static IntPtr WaitShown(HashSet<uint> pids, int ms)
1552
+ {
1553
+ var until = DateTime.UtcNow.AddMilliseconds(ms);
1554
+ do
1555
+ {
1556
+ IntPtr h = Windows.ShownWindowOf(pids);
1557
+ if (h != IntPtr.Zero) return h;
1558
+ Thread.Sleep(120);
1559
+ } while (DateTime.UtcNow < until);
1560
+ return IntPtr.Zero;
1561
+ }
1562
+
1563
+ public static object Restore(string exe)
1564
+ {
1565
+ var result = new Dictionary<string, object>();
1566
+ var pids = Pids(exe);
1567
+ result["running"] = pids.Count > 0;
1568
+ IntPtr owner; uint id;
1569
+ if (pids.Count == 0 || !Find(pids, WindowsByPid(), out owner, out id)) { result["icon"] = false; return result; }
1570
+ result["icon"] = true;
1571
+ Rectangle icon; IconRect(owner, id, out icon);
1572
+ // An icon in the overflow reports the chevron's rectangle until the overflow is open.
1573
+ Rectangle chevron = Chevron();
1574
+ if (!chevron.IsEmpty && Math.Abs(chevron.X - icon.X) <= 2 && Math.Abs(chevron.Y - icon.Y) <= 2)
1575
+ {
1576
+ Click(chevron, 1);
1577
+ Thread.Sleep(450);
1578
+ IconRect(owner, id, out icon);
1579
+ result["overflow"] = true;
1580
+ }
1581
+ Click(icon, 1);
1582
+ IntPtr shown = WaitShown(pids, 1500);
1583
+ if (shown == IntPtr.Zero)
1584
+ {
1585
+ // Some apps restore on a double click only.
1586
+ Rectangle again;
1587
+ if (IconRect(owner, id, out again) && !(Math.Abs(chevron.X - again.X) <= 2 && Math.Abs(chevron.Y - again.Y) <= 2)) Click(again, 2);
1588
+ shown = WaitShown(pids, 1500);
1589
+ }
1590
+ if (shown != IntPtr.Zero) { result["window"] = Windows.Focus(shown); }
1591
+ return result;
1592
+ }
1593
+ }
1594
+
1256
1595
  internal static class Apps
1257
1596
  {
1258
1597
  static List<KeyValuePair<string, string>> cache;
@@ -1481,6 +1820,55 @@ namespace DshComputerUse
1481
1820
  }
1482
1821
  }
1483
1822
 
1823
+ /** The progress card's instruction box: a small focusable window laid over the card's field. */
1824
+ internal class InputBox : Form
1825
+ {
1826
+ public readonly TextBox Box;
1827
+ public event Action<string> Submitted;
1828
+ public event Action Cancelled;
1829
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr SendMessage(IntPtr hwnd, int msg, IntPtr w, string l);
1830
+
1831
+ public InputBox(Font font, Color back, Color fore, string cue)
1832
+ {
1833
+ FormBorderStyle = FormBorderStyle.None;
1834
+ ShowInTaskbar = false;
1835
+ StartPosition = FormStartPosition.Manual;
1836
+ AutoScaleMode = AutoScaleMode.None;
1837
+ TopMost = true;
1838
+ BackColor = back;
1839
+ Box = new TextBox();
1840
+ Box.BorderStyle = BorderStyle.None;
1841
+ Box.Font = font;
1842
+ Box.BackColor = back;
1843
+ Box.ForeColor = fore;
1844
+ Controls.Add(Box);
1845
+ Box.HandleCreated += delegate { SendMessage(Box.Handle, 0x1501, new IntPtr(1), cue); }; // EM_SETCUEBANNER
1846
+ Box.KeyDown += delegate (object s, KeyEventArgs e)
1847
+ {
1848
+ if (e.KeyCode == System.Windows.Forms.Keys.Enter && !e.Shift) { e.SuppressKeyPress = true; if (Submitted != null) Submitted(Box.Text); }
1849
+ else if (e.KeyCode == System.Windows.Forms.Keys.Escape) { e.SuppressKeyPress = true; if (Cancelled != null) Cancelled(); }
1850
+ };
1851
+ }
1852
+
1853
+ protected override CreateParams CreateParams
1854
+ {
1855
+ get { var cp = base.CreateParams; cp.ExStyle |= 0x80 | 0x8; return cp; } // TOOLWINDOW | TOPMOST
1856
+ }
1857
+
1858
+ protected override void OnHandleCreated(EventArgs e)
1859
+ {
1860
+ base.OnHandleCreated(e);
1861
+ if (Overlay.ExcludeFromCapture) { try { Native.SetWindowDisplayAffinity(Handle, 0x11); } catch (Exception) { } }
1862
+ }
1863
+
1864
+ public void Place(Rectangle r)
1865
+ {
1866
+ Bounds = r;
1867
+ Box.Width = r.Width;
1868
+ Box.Location = new Point(0, Math.Max(0, (r.Height - Box.PreferredHeight) / 2));
1869
+ }
1870
+ }
1871
+
1484
1872
  internal static class Overlay
1485
1873
  {
1486
1874
  static readonly Color Accent = Color.FromArgb(217, 119, 87); // #D97757
@@ -1495,8 +1883,8 @@ namespace DshComputerUse
1495
1883
  static readonly List<KeyValuePair<Rectangle, string>> buttons = new List<KeyValuePair<Rectangle, string>>();
1496
1884
  static bool pillAtBottom;
1497
1885
  static string label = "", status = "", rendered = "";
1498
- static Image icon;
1499
- static string iconPath = "";
1886
+ static Image icon, iconLight;
1887
+ static string iconPath = "", iconLightPath = "";
1500
1888
  static int idleMs = 1500;
1501
1889
  static System.Windows.Forms.Timer timer;
1502
1890
  static DateTime shownAt;
@@ -1508,6 +1896,31 @@ namespace DshComputerUse
1508
1896
  static int lastEmit;
1509
1897
  static readonly object RectLock = new object();
1510
1898
 
1899
+ // The progress card ("pet"): replaces the pill while DeepSeek Harness is minimized.
1900
+ static bool petMode;
1901
+ static LayeredForm pet;
1902
+ public static volatile IntPtr PetHwnd = IntPtr.Zero;
1903
+ static string petText = "", petThinking = "";
1904
+ static List<string> petSteps = new List<string>();
1905
+ static bool petThinkingLatest;
1906
+ /** Bottom-right corner of the card body; the card grows upward when expanded. */
1907
+ static Point petAnchor = Point.Empty;
1908
+ static int petShadow;
1909
+ static Rectangle petBody;
1910
+ static byte petAlpha = 230;
1911
+ static bool petDragged, petExpanded, petFinished;
1912
+ static DateTime finishedAt;
1913
+ static int finishHoldMs = 4000;
1914
+ // The instruction box under the card (a real, focusable window over the card's field).
1915
+ static InputBox input;
1916
+ public static volatile IntPtr InputHwnd = IntPtr.Zero;
1917
+ /** The window that had the focus before the instruction box opened. */
1918
+ public static volatile IntPtr InputReturnsTo = IntPtr.Zero;
1919
+ static bool pausedByInput;
1920
+ static IntPtr beforeInput = IntPtr.Zero;
1921
+ static Rectangle inputBounds;
1922
+ static string iconFont;
1923
+
1511
1924
  static void Ensure()
1512
1925
  {
1513
1926
  if (thread != null) return;
@@ -1539,6 +1952,18 @@ namespace DshComputerUse
1539
1952
  status = Args.Str(r, "status", "");
1540
1953
  idleMs = Args.Int(r, "idleMs", 1500);
1541
1954
  string path = Args.Str(r, "icon", "");
1955
+ string light = Args.Str(r, "iconLight", "");
1956
+ if (light != iconLightPath)
1957
+ {
1958
+ iconLightPath = light;
1959
+ if (iconLight != null) { iconLight.Dispose(); iconLight = null; }
1960
+ try
1961
+ {
1962
+ if (light.Length > 0 && File.Exists(light))
1963
+ using (var raw = Image.FromFile(light)) iconLight = new Bitmap(raw);
1964
+ }
1965
+ catch (Exception) { iconLight = null; }
1966
+ }
1542
1967
  if (path != iconPath)
1543
1968
  {
1544
1969
  iconPath = path;
@@ -1550,7 +1975,12 @@ namespace DshComputerUse
1550
1975
  }
1551
1976
  catch (Exception) { icon = null; }
1552
1977
  }
1553
- if (visible) { RenderPill(); return; }
1978
+ petAlpha = (byte)Math.Max(90, Math.Min(255, Args.Int(r, "petOpacity", 90) * 255 / 100));
1979
+ if (visible && !petFinished) { RenderPill(); return; }
1980
+ if (visible) HideCore(); // the previous run's "done" card is still up
1981
+ petMode = Args.Bool(r, "pet", false);
1982
+ petText = Args.Str(r, "text", ""); petThinking = ""; petSteps = new List<string>(); petThinkingLatest = false;
1983
+ if (status.Length > 0) petSteps.Add(status);
1554
1984
  pillAtBottom = false;
1555
1985
  paused = false;
1556
1986
  foreach (var g in glows) g.Close();
@@ -1566,7 +1996,34 @@ namespace DshComputerUse
1566
1996
  glows.Add(form);
1567
1997
  }
1568
1998
  }
1569
- if (pill == null)
1999
+ if (petMode)
2000
+ {
2001
+ if (pet == null)
2002
+ {
2003
+ pet = new LayeredForm(false);
2004
+ pet.MouseDown += delegate (object s, MouseEventArgs e)
2005
+ {
2006
+ if (e.Button != MouseButtons.Left) return;
2007
+ foreach (var b in buttons) if (b.Key.Contains(e.Location)) return;
2008
+ // Drag the card anywhere; it keeps that place until the next run.
2009
+ Native.ReleaseCapture();
2010
+ Native.SendMessage(pet.Handle, 0xA1, new IntPtr(2), IntPtr.Zero); // WM_NCLBUTTONDOWN, HTCAPTION
2011
+ Native.RECT rc;
2012
+ if (pet != null && Native.GetWindowRect(pet.Handle, out rc)) petAnchor = new Point(rc.Right - petShadow, rc.Bottom - petShadow);
2013
+ petDragged = true;
2014
+ RenderPill();
2015
+ };
2016
+ pet.MouseUp += delegate (object s, MouseEventArgs e)
2017
+ {
2018
+ if (petDragged) { petDragged = false; return; }
2019
+ foreach (var b in buttons)
2020
+ if (b.Key.Contains(e.Location)) { Press(b.Value); break; }
2021
+ };
2022
+ pet.Show();
2023
+ PetHwnd = pet.Handle;
2024
+ }
2025
+ }
2026
+ else if (pill == null)
1570
2027
  {
1571
2028
  pill = new LayeredForm(false);
1572
2029
  pill.MouseUp += delegate (object s, MouseEventArgs e)
@@ -1590,6 +2047,41 @@ namespace DshComputerUse
1590
2047
  Ui(delegate { status = newStatus; RenderPill(); });
1591
2048
  }
1592
2049
 
2050
+ /** New agent output for the progress card: reply text, thinking, and the recent steps (oldest first). */
2051
+ public static void PetUpdate(string text, string thinking, List<string> steps, bool thinkingLatest)
2052
+ {
2053
+ if (thread == null || !visible || !petMode || petFinished) return;
2054
+ invoker.BeginInvoke((MethodInvoker)delegate
2055
+ {
2056
+ if (petFinished) return;
2057
+ petText = text;
2058
+ petThinking = thinking;
2059
+ if (steps.Count > 0) petSteps = steps;
2060
+ petThinkingLatest = thinkingLatest;
2061
+ RenderPill();
2062
+ });
2063
+ }
2064
+
2065
+ /** The run ended: the card says so for a moment (longer while the pointer rests on it), then everything hides. */
2066
+ public static void Finish(string text, int holdMs)
2067
+ {
2068
+ if (thread == null) return;
2069
+ Ui(delegate
2070
+ {
2071
+ if (!visible || !petMode) { HideCore(); return; }
2072
+ CloseInput(false);
2073
+ foreach (var g in glows) g.Close();
2074
+ glows.Clear();
2075
+ RemoveHook();
2076
+ paused = false;
2077
+ if (text.Length > 0) petText = text;
2078
+ petFinished = true;
2079
+ finishedAt = DateTime.UtcNow;
2080
+ finishHoldMs = holdMs;
2081
+ RenderPill();
2082
+ });
2083
+ }
2084
+
1593
2085
  public static void SetPaused(bool value)
1594
2086
  {
1595
2087
  if (thread == null) return;
@@ -1599,18 +2091,26 @@ namespace DshComputerUse
1599
2091
  public static void Hide()
1600
2092
  {
1601
2093
  if (thread == null) return;
1602
- Ui(delegate
2094
+ Ui(delegate { HideCore(); });
2095
+ }
2096
+
2097
+ static void HideCore()
2098
+ {
1603
2099
  {
2100
+ CloseInput(false);
2101
+ petFinished = false;
1604
2102
  visible = false;
1605
2103
  paused = false;
1606
2104
  timer.Stop();
1607
2105
  foreach (var g in glows) g.Close();
1608
2106
  glows.Clear();
1609
2107
  if (pill != null) { pill.Close(); pill = null; }
2108
+ if (pet != null) { PetHwnd = IntPtr.Zero; pet.Close(); pet = null; }
2109
+ petMode = false;
1610
2110
  rendered = "";
1611
2111
  lock (RectLock) pillRect = Rectangle.Empty;
1612
2112
  RemoveHook();
1613
- });
2113
+ }
1614
2114
  }
1615
2115
 
1616
2116
  public static void Shutdown()
@@ -1637,15 +2137,75 @@ namespace DshComputerUse
1637
2137
  {
1638
2138
  if (action == "stop") { paused = false; Program.EmitEvent("stop", "button"); }
1639
2139
  else if (action == "pause") { paused = true; Program.EmitEvent("pause", "user"); }
1640
- else if (action == "resume") { paused = false; Program.EmitEvent("resume", "user"); }
2140
+ else if (action == "resume") { paused = false; pausedByInput = false; Program.EmitEvent("resume", "user"); }
2141
+ else if (action == "expand") petExpanded = !petExpanded;
2142
+ else if (action == "input") { if (input == null) OpenInput(); else CloseInput(true); return; }
2143
+ else if (action == "send") { if (input != null) SubmitInput(input.Box.Text); return; }
2144
+ else if (action == "close") { HideCore(); return; }
1641
2145
  RenderPill();
1642
2146
  }
1643
2147
 
2148
+ static void OpenInput()
2149
+ {
2150
+ beforeInput = Native.GetForegroundWindow();
2151
+ // Typing an instruction pauses the agent, so its keys cannot land in the box.
2152
+ if (!paused) { paused = true; pausedByInput = true; Program.EmitEvent("pause", "input"); }
2153
+ bool dark = DarkTheme();
2154
+ float px = 1.333f * Scale();
2155
+ input = new InputBox(new Font("Microsoft YaHei UI", 10f * px, FontStyle.Regular, GraphicsUnit.Pixel),
2156
+ dark ? Color.FromArgb(52, 51, 49) : Color.White, dark ? Color.FromArgb(244, 243, 241) : Color.FromArgb(31, 30, 29),
2157
+ "告诉 DeepSeek 接下来做什么(Enter 发送,Esc 取消)");
2158
+ input.Submitted += SubmitInput;
2159
+ input.Cancelled += delegate { CloseInput(true); };
2160
+ inputBounds = Rectangle.Empty;
2161
+ RenderPill(); // makes room for the field and places the box over it
2162
+ input.Show();
2163
+ InputHwnd = input.Handle;
2164
+ var handle = input.Handle;
2165
+ ThreadPool.QueueUserWorkItem(delegate
2166
+ {
2167
+ try { Windows.Focus(handle); } catch (Exception) { }
2168
+ try { invoker.BeginInvoke((MethodInvoker)delegate { if (input != null) input.Box.Focus(); }); } catch (Exception) { }
2169
+ });
2170
+ }
2171
+
2172
+ static void SubmitInput(string text)
2173
+ {
2174
+ text = (text ?? "").Trim();
2175
+ if (text.Length > 0) Program.EmitEvent("message", text);
2176
+ CloseInput(true);
2177
+ }
2178
+
2179
+ static void CloseInput(bool restoreFocus)
2180
+ {
2181
+ if (input == null) return;
2182
+ var box = input;
2183
+ input = null;
2184
+ InputReturnsTo = restoreFocus ? beforeInput : IntPtr.Zero;
2185
+ InputHwnd = IntPtr.Zero;
2186
+ inputBounds = Rectangle.Empty;
2187
+ box.Close();
2188
+ if (pausedByInput) { paused = false; pausedByInput = false; Program.EmitEvent("resume", "input"); }
2189
+ var target = beforeInput;
2190
+ beforeInput = IntPtr.Zero;
2191
+ if (restoreFocus && target != IntPtr.Zero && Native.IsWindow(target))
2192
+ ThreadPool.QueueUserWorkItem(delegate { try { Windows.Focus(target); } catch (Exception) { } });
2193
+ if (visible) RenderPill();
2194
+ }
2195
+
1644
2196
  static bool Typing() { return unchecked(Environment.TickCount - lastTyping) < idleMs; }
1645
2197
 
1646
2198
  static void Tick()
1647
2199
  {
1648
2200
  if (!visible) return;
2201
+ if (petFinished)
2202
+ {
2203
+ Native.POINT p; Native.GetCursorPos(out p);
2204
+ bool hovered = petBody.Contains(p.X, p.Y);
2205
+ if (hovered) finishedAt = DateTime.UtcNow;
2206
+ if ((DateTime.UtcNow - finishedAt).TotalMilliseconds >= finishHoldMs) HideCore();
2207
+ return;
2208
+ }
1649
2209
  double t = (DateTime.UtcNow - shownAt).TotalSeconds;
1650
2210
  double fadeIn = Math.Min(1.0, t / 0.35);
1651
2211
  double breathe = paused ? 0.55 : 0.72 + 0.28 * (0.5 + 0.5 * Math.Sin(t * Math.PI * 2 / 2.6));
@@ -1656,6 +2216,8 @@ namespace DshComputerUse
1656
2216
  {
1657
2217
  foreach (var g in glows) g.KeepOnTop();
1658
2218
  if (pill != null) pill.KeepOnTop();
2219
+ if (pet != null) pet.KeepOnTop();
2220
+ if (input != null) Native.SetWindowPos(input.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);
1659
2221
  }
1660
2222
  }
1661
2223
 
@@ -1714,11 +2276,288 @@ namespace DshComputerUse
1714
2276
  {
1715
2277
  string main, sub; string[] actions, captions;
1716
2278
  Content(out main, out sub, out actions, out captions);
1717
- return main + "|" + sub + "|" + string.Join(",", actions) + "|" + pillAtBottom;
2279
+ return main + "|" + sub + "|" + string.Join(",", actions) + "|" + pillAtBottom + "|" + Typing();
2280
+ }
2281
+
2282
+ static bool DarkTheme()
2283
+ {
2284
+ try
2285
+ {
2286
+ using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"))
2287
+ {
2288
+ object v = key == null ? null : key.GetValue("AppsUseLightTheme");
2289
+ return v is int && (int)v == 0;
2290
+ }
2291
+ }
2292
+ catch (Exception) { return false; }
2293
+ }
2294
+
2295
+ /** The end of `s` that fits `width`, led by "…": a ticker that scrolls as text streams in. */
2296
+ static string Tail(Graphics g, string s, Font font, float width, StringFormat fmt)
2297
+ {
2298
+ if (s.Length == 0 || g.MeasureString(s, font, 100000, fmt).Width <= width) return s;
2299
+ int lo = 1, hi = s.Length - 1;
2300
+ while (lo < hi)
2301
+ {
2302
+ int mid = (lo + hi) / 2;
2303
+ if (g.MeasureString("…" + s.Substring(mid), font, 100000, fmt).Width <= width) hi = mid; else lo = mid + 1;
2304
+ }
2305
+ if (lo < s.Length && char.IsLowSurrogate(s[lo])) lo++;
2306
+ return "…" + s.Substring(Math.Min(lo, s.Length));
2307
+ }
2308
+
2309
+ static float Scale()
2310
+ {
2311
+ float scale = 1f; bool found = false;
2312
+ foreach (Dictionary<string, object> d in Screen2.Displays())
2313
+ if (!found || (bool)d["primary"]) { scale = (int)d["dpi"] / 96f; found = true; }
2314
+ return scale;
2315
+ }
2316
+
2317
+ static string IconFont()
2318
+ {
2319
+ if (iconFont != null) return iconFont;
2320
+ iconFont = "";
2321
+ foreach (var name in new[] { "Segoe Fluent Icons", "Segoe MDL2 Assets" })
2322
+ using (var f = new Font(name, 10f)) if (f.Name == name) { iconFont = name; break; }
2323
+ return iconFont;
2324
+ }
2325
+
2326
+ /** The end of `s` that fits in `width` x `height` when wrapped, led by "…". */
2327
+ static string TailWrapped(Graphics g, string s, Font font, float width, float height, StringFormat fmt)
2328
+ {
2329
+ Func<string, bool> fits = delegate (string t) { return g.MeasureString(t, font, new SizeF(width, 100000), fmt).Height <= height; };
2330
+ if (s.Length == 0 || fits(s)) return s;
2331
+ int lo = 1, hi = s.Length - 1;
2332
+ while (lo < hi)
2333
+ {
2334
+ int mid = (lo + hi) / 2;
2335
+ if (fits("…" + s.Substring(mid))) hi = mid; else lo = mid + 1;
2336
+ }
2337
+ if (lo < s.Length && char.IsLowSurrogate(s[lo])) lo++;
2338
+ return "…" + s.Substring(Math.Min(lo, s.Length));
2339
+ }
2340
+
2341
+ static void RenderPet()
2342
+ {
2343
+ if (pet == null) return;
2344
+ Rectangle work = Rectangle.Empty; float scale = 1f;
2345
+ foreach (Dictionary<string, object> d in Screen2.Displays())
2346
+ {
2347
+ if (work.IsEmpty || (bool)d["primary"])
2348
+ {
2349
+ work = new Rectangle((int)d["workX"], (int)d["workY"], (int)d["workWidth"], (int)d["workHeight"]);
2350
+ scale = (int)d["dpi"] / 96f;
2351
+ }
2352
+ }
2353
+ rendered = Key();
2354
+ bool dark = DarkTheme();
2355
+ Color bg = dark ? Color.FromArgb(petAlpha, 32, 31, 30) : Color.FromArgb(petAlpha, 252, 252, 251);
2356
+ Color ink = dark ? Color.FromArgb(244, 243, 241) : Color.FromArgb(31, 30, 29);
2357
+ Color muted = dark ? Color.FromArgb(168, 165, 160) : Color.FromArgb(112, 110, 106);
2358
+ Color edge = dark ? Color.FromArgb(60, 255, 255, 255) : Color.FromArgb(34, 0, 0, 0);
2359
+ Color chip = dark ? Color.FromArgb(70, 68, 66) : Color.FromArgb(234, 232, 228);
2360
+ Color field = dark ? Color.FromArgb(52, 51, 49) : Color.White;
2361
+
2362
+ string title = petFinished ? "已完成" : label;
2363
+ string state = petFinished ? "" : paused ? (input != null ? "输入指令中…" : "已暂停 · Esc 继续") : Typing() ? "你正在操作,已暂停" : "Esc 暂停";
2364
+ // Header buttons, right to left.
2365
+ var actions = new List<string>(); var glyphs = new List<string>();
2366
+ if (petFinished) { actions.Add("close"); glyphs.Add("\uE711"); }
2367
+ else
2368
+ {
2369
+ actions.Add("stop"); glyphs.Add("\uE71A");
2370
+ if (paused) { actions.Add("resume"); glyphs.Add("\uE768"); } else { actions.Add("pause"); glyphs.Add("\uE769"); }
2371
+ }
2372
+ actions.Add("expand"); glyphs.Add(petExpanded ? "\uE70D" : "\uE70E");
2373
+ if (!petFinished) { actions.Add("input"); glyphs.Add("\uE70F"); }
2374
+
2375
+ float s = scale, px = 1.333f * scale;
2376
+ int shadow = (int)(14 * s);
2377
+ petShadow = shadow;
2378
+ float bodyW = 420 * s, pad = 16 * s;
2379
+ float headH = 44 * s, replyH = 26 * s;
2380
+ if (petExpanded)
2381
+ {
2382
+ // Grow with the reply, up to about eight lines.
2383
+ using (var probe = new Bitmap(1, 1))
2384
+ using (var pg = Graphics.FromImage(probe))
2385
+ using (var pf = new Font("Microsoft YaHei UI", 10.5f * 1.333f * scale, FontStyle.Regular, GraphicsUnit.Pixel))
2386
+ {
2387
+ string t = petText.Length > 0 ? petText : "正在操作…";
2388
+ float need = pg.MeasureString(t, pf, new SizeF(420 * scale - 32 * scale, 100000), new StringFormat(StringFormat.GenericTypographic)).Height + 6 * scale;
2389
+ replyH = Math.Max(26 * scale, Math.Min(172 * scale, need));
2390
+ }
2391
+ }
2392
+ int stepRows = petExpanded ? Math.Min(5, Math.Max(1, petSteps.Count)) : 0;
2393
+ bool thinkingRow = petExpanded && petThinking.Length > 0 && !petFinished;
2394
+ float listH = petExpanded ? 8 * s + (thinkingRow ? 24 * s : 0) + stepRows * 22 * s : 24 * s;
2395
+ float inputH = input != null ? 46 * s : 0;
2396
+ float bodyH = headH + replyH + listH + inputH + 12 * s;
2397
+ int W = (int)Math.Ceiling(bodyW) + 2 * shadow, H = (int)Math.Ceiling(bodyH) + 2 * shadow;
2398
+ if (petAnchor.IsEmpty) petAnchor = new Point(work.Right - (int)(16 * s), work.Bottom - (int)(16 * s));
2399
+ int x = petAnchor.X - (int)bodyW - shadow, y = petAnchor.Y - (int)bodyH - shadow;
2400
+ y = Math.Max(work.Y - shadow, y);
2401
+ petBody = new Rectangle(x + shadow, y + shadow, (int)bodyW, (int)bodyH);
2402
+
2403
+ string glyphFont = IconFont();
2404
+ using (var fHead = new Font("Microsoft YaHei UI", 8.5f * px, FontStyle.Bold, GraphicsUnit.Pixel))
2405
+ using (var fState = new Font("Microsoft YaHei UI", 8f * px, FontStyle.Regular, GraphicsUnit.Pixel))
2406
+ using (var fText = new Font("Microsoft YaHei UI", 10.5f * px, FontStyle.Regular, GraphicsUnit.Pixel))
2407
+ using (var fAct = new Font("Microsoft YaHei UI", 8.5f * px, FontStyle.Regular, GraphicsUnit.Pixel))
2408
+ using (var fGlyph = new Font(glyphFont.Length > 0 ? glyphFont : "Segoe UI Symbol", 8.5f * px, FontStyle.Regular, GraphicsUnit.Pixel))
2409
+ using (var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb))
2410
+ using (var g = Graphics.FromImage(bmp))
2411
+ {
2412
+ g.Clear(Color.Transparent);
2413
+ g.SmoothingMode = SmoothingMode.AntiAlias;
2414
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
2415
+ g.TextRenderingHint = TextRenderingHint.AntiAlias;
2416
+ var fmt = new StringFormat(StringFormat.GenericTypographic);
2417
+ fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap;
2418
+ var wrap = new StringFormat(StringFormat.GenericTypographic);
2419
+ wrap.Trimming = StringTrimming.None;
2420
+ var center = new StringFormat(); center.Alignment = StringAlignment.Center; center.LineAlignment = StringAlignment.Center;
2421
+
2422
+ var body = new RectangleF(shadow, shadow, bodyW, bodyH);
2423
+ float radius = 18 * s;
2424
+ for (int i = shadow; i > 0; i--)
2425
+ {
2426
+ double f = 1.0 - (double)i / shadow;
2427
+ using (var path = Rounded(RectangleF.Inflate(body, i, i - 2 * s), radius + i))
2428
+ using (var brush = new SolidBrush(Color.FromArgb((int)(16 * f * f), 0, 0, 0))) g.FillPath(brush, path);
2429
+ }
2430
+ using (var path = Rounded(body, radius))
2431
+ {
2432
+ using (var brush = new SolidBrush(bg)) g.FillPath(brush, path);
2433
+ using (var pen = new Pen(edge, Math.Max(1f, s))) g.DrawPath(pen, path);
2434
+ }
2435
+
2436
+ // Header: logo, title, state, round icon buttons.
2437
+ float hy = body.Y + 10 * s, hh = 28 * s;
2438
+ float iconSize = 18 * s;
2439
+ var iconRect = new RectangleF(body.X + pad, hy + (hh - iconSize) / 2f, iconSize, iconSize);
2440
+ Image logo = dark ? icon : (iconLight ?? icon);
2441
+ if (petFinished)
2442
+ {
2443
+ using (var brush = new SolidBrush(Color.FromArgb(46, 160, 67))) g.FillEllipse(brush, iconRect);
2444
+ using (var b = new SolidBrush(Color.White)) g.DrawString(glyphFont.Length > 0 ? "\uE73E" : "✓", fGlyph, b, iconRect, center);
2445
+ }
2446
+ else if (logo != null) g.DrawImage(logo, iconRect);
2447
+ else using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, RectangleF.Inflate(iconRect, -3 * s, -3 * s));
2448
+ float tx = iconRect.Right + 8 * s;
2449
+ SizeF headSize = g.MeasureString(title, fHead, 100000, fmt);
2450
+ using (var b = new SolidBrush(ink)) g.DrawString(title, fHead, b, tx, hy + (hh - headSize.Height) / 2f, fmt);
2451
+ tx += headSize.Width + 8 * s;
2452
+
2453
+ buttons.Clear();
2454
+ float d = 26 * s, bx = body.Right - pad;
2455
+ for (int i = 0; i < actions.Count; i++)
2456
+ {
2457
+ bx -= d;
2458
+ var circle = new RectangleF(bx, hy + (hh - d) / 2f, d, d);
2459
+ bool stop = actions[i] == "stop";
2460
+ bool on = (actions[i] == "input" && input != null) || (actions[i] == "resume");
2461
+ using (var brush = new SolidBrush(stop ? Accent : on ? Color.FromArgb(dark ? 110 : 60, Accent) : chip)) g.FillEllipse(brush, circle);
2462
+ string glyph = glyphFont.Length > 0 ? glyphs[i] : (stop ? "■" : actions[i] == "pause" ? "❚❚" : actions[i] == "resume" ? "▶" : actions[i] == "expand" ? (petExpanded ? "˅" : "˄") : actions[i] == "close" ? "✕" : "✎");
2463
+ using (var b = new SolidBrush(stop ? Color.White : ink)) g.DrawString(glyph, fGlyph, b, circle, center);
2464
+ buttons.Add(new KeyValuePair<Rectangle, string>(Rectangle.Round(circle), actions[i]));
2465
+ bx -= 6 * s;
2466
+ }
2467
+ if (state.Length > 0)
2468
+ {
2469
+ string st = Tail(g, state, fState, Math.Max(0, bx - tx - 4 * s), fmt);
2470
+ SizeF stSize = g.MeasureString(st, fState, 100000, fmt);
2471
+ using (var b = new SolidBrush(paused ? Accent : muted)) g.DrawString(st, fState, b, tx, hy + (hh - stSize.Height) / 2f, fmt);
2472
+ }
2473
+
2474
+ // The reply as it streams: one scrolling line, or the latest lines when expanded.
2475
+ float lineW = bodyW - 2 * pad;
2476
+ float ry = body.Y + headH;
2477
+ string text = petText.Length > 0 ? petText : (petFinished ? "" : "正在操作…");
2478
+ using (var b = new SolidBrush(petText.Length > 0 ? ink : muted))
2479
+ {
2480
+ if (petExpanded)
2481
+ g.DrawString(TailWrapped(g, text, fText, lineW, replyH, wrap), fText, b, new RectangleF(body.X + pad, ry, lineW, replyH), wrap);
2482
+ else
2483
+ {
2484
+ string shown = Tail(g, text, fText, lineW, fmt);
2485
+ SizeF size = g.MeasureString(shown.Length > 0 ? shown : " ", fText, 100000, fmt);
2486
+ g.DrawString(shown, fText, b, body.X + pad, ry + (replyH - size.Height) / 2f, fmt);
2487
+ }
2488
+ }
2489
+
2490
+ // Thinking and the step timeline.
2491
+ float ly = ry + replyH;
2492
+ if (petExpanded)
2493
+ {
2494
+ ly += 4 * s;
2495
+ using (var pen = new Pen(edge, Math.Max(1f, s))) g.DrawLine(pen, body.X + pad, ly, body.Right - pad, ly);
2496
+ ly += 4 * s;
2497
+ if (thinkingRow)
2498
+ {
2499
+ float prefixW = g.MeasureString("思考:", fAct, 100000, fmt).Width;
2500
+ string th = Tail(g, petThinking, fAct, lineW - prefixW, fmt);
2501
+ using (var b = new SolidBrush(muted)) { g.DrawString("思考:", fAct, b, body.X + pad, ly + 3 * s, fmt); g.DrawString(th, fAct, b, body.X + pad + prefixW, ly + 3 * s, fmt); }
2502
+ ly += 24 * s;
2503
+ }
2504
+ int first = Math.Max(0, petSteps.Count - stepRows);
2505
+ for (int i = first; i < petSteps.Count; i++)
2506
+ {
2507
+ bool current = i == petSteps.Count - 1 && !petFinished;
2508
+ float cy = ly + 11 * s;
2509
+ if (current) using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, body.X + pad + 2 * s, cy - 3 * s, 6 * s, 6 * s);
2510
+ 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);
2511
+ string line = Tail(g, petSteps[i], fAct, lineW - 16 * s, fmt);
2512
+ using (var b = new SolidBrush(current ? ink : muted)) g.DrawString(line, fAct, b, body.X + pad + 16 * s, ly + 3 * s, fmt);
2513
+ ly += 22 * s;
2514
+ }
2515
+ }
2516
+ else
2517
+ {
2518
+ string act;
2519
+ if (petFinished) act = petSteps.Count > 0 ? "共 " + petSteps.Count + " 步 · " + petSteps[petSteps.Count - 1] : "";
2520
+ else if (petThinkingLatest && petThinking.Length > 0) act = "思考:" + Tail(g, petThinking, fAct, lineW - 14 * s - g.MeasureString("思考:", fAct, 100000, fmt).Width, fmt);
2521
+ else
2522
+ {
2523
+ var parts = new List<string>();
2524
+ for (int i = Math.Max(0, petSteps.Count - 4); i < petSteps.Count; i++) parts.Add(i < petSteps.Count - 1 ? "✓ " + petSteps[i] : petSteps[i]);
2525
+ act = string.Join(" › ", parts);
2526
+ }
2527
+ 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);
2528
+ string shown = Tail(g, act, fAct, lineW - 14 * s, fmt);
2529
+ using (var b = new SolidBrush(muted)) g.DrawString(shown, fAct, b, body.X + pad + 14 * s, ly + 3 * s, fmt);
2530
+ ly += 24 * s;
2531
+ }
2532
+
2533
+ // The instruction field: the card draws its frame and send button, a real text box sits on top.
2534
+ if (input != null)
2535
+ {
2536
+ ly += 6 * s;
2537
+ float sendD = 32 * s;
2538
+ var fieldRect = new RectangleF(body.X + pad, ly, lineW - sendD - 8 * s, 34 * s);
2539
+ using (var path = Rounded(fieldRect, 17 * s))
2540
+ {
2541
+ using (var brush = new SolidBrush(field)) g.FillPath(brush, path);
2542
+ using (var pen = new Pen(Color.FromArgb(150, Accent), Math.Max(1f, 1.2f * s))) g.DrawPath(pen, path);
2543
+ }
2544
+ var send = new RectangleF(body.Right - pad - sendD, ly + (34 * s - sendD) / 2f, sendD, sendD);
2545
+ using (var brush = new SolidBrush(Accent)) g.FillEllipse(brush, send);
2546
+ using (var b = new SolidBrush(Color.White)) g.DrawString(glyphFont.Length > 0 ? "\uE724" : "➤", fGlyph, b, send, center);
2547
+ buttons.Add(new KeyValuePair<Rectangle, string>(Rectangle.Round(send), "send"));
2548
+ 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));
2549
+ if (boxRect != inputBounds) { inputBounds = boxRect; input.Place(boxRect); }
2550
+ }
2551
+
2552
+ pet.SetBitmap(bmp, new Rectangle(x, y, W, H), 255);
2553
+ }
2554
+ pet.KeepOnTop();
2555
+ if (input != null) Native.SetWindowPos(input.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);
1718
2556
  }
1719
2557
 
1720
2558
  static void RenderPill()
1721
2559
  {
2560
+ if (petMode) { RenderPet(); return; }
1722
2561
  if (pill == null) return;
1723
2562
  // The pill lives on the primary display (or the first one).
1724
2563
  Rectangle work = Rectangle.Empty; float scale = 1f;
@@ -1824,7 +2663,7 @@ namespace DshComputerUse
1824
2663
  int msg = wParam.ToInt32();
1825
2664
  var kb = (Native.KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.KBDLLHOOKSTRUCT));
1826
2665
  // Only physical keys count: our own SendInput sets LLKHF_INJECTED (0x10).
1827
- if ((kb.flags & 0x10) == 0)
2666
+ if ((kb.flags & 0x10) == 0 && !(InputHwnd != IntPtr.Zero && Native.GetForegroundWindow() == InputHwnd))
1828
2667
  {
1829
2668
  bool down = msg == 0x100 || msg == 0x104;
1830
2669
  if (kb.vkCode == 0x1B)