@copylee/dsh-computer-use 0.2.1 → 0.4.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;
@@ -266,9 +275,14 @@ namespace DshComputerUse
266
275
  case "scroll": using (new PassThrough()) return Input.Scroll(r);
267
276
  case "keys": return Input.Keys(r);
268
277
  case "key_state": return Input.KeyState(r);
269
- case "type": return Input.Type(Args.Str(r, "text", ""), Args.Int(r, "chunkDelay", 8));
270
- case "paste": return Input.Paste(Args.Str(r, "text", ""), Args.Bool(r, "restore", true));
278
+ case "type": return Input.Type(Args.Str(r, "text", ""), Args.Int(r, "chunkDelay", 8), Args.Int(r, "charDelay", 0));
279
+ case "clipboard_hold": Clip.Hold(); return null;
280
+ case "clipboard_release": Clip.Release(); return null;
281
+ case "paste": return Input.Paste(Args.Str(r, "text", ""), Args.Bool(r, "restore", true), Args.Int(r, "waitMs", 250));
271
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;
272
286
  case "foreground": return Windows.Describe(Native.GetForegroundWindow());
273
287
  case "window_at": return Windows.At(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
274
288
  case "focus": return Windows.Focus(new IntPtr(Convert.ToInt64(r["hwnd"])));
@@ -281,9 +295,11 @@ namespace DshComputerUse
281
295
  case "ui": return Uia.Elements(r);
282
296
  case "overlay_show": Overlay.ExcludeFromCapture = Args.Bool(r, "excludeFromCapture", true); Overlay.Show(r); return null;
283
297
  case "overlay_pause": Overlay.SetPaused(Args.Bool(r, "paused", false)); return null;
284
- 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));
285
299
  case "window_uncard": return Windows.Uncard(new IntPtr(Convert.ToInt64(r["hwnd"])));
286
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;
287
303
  case "overlay_hide": Overlay.Hide(); return null;
288
304
  default: throw new Exception("unknown command: " + cmd);
289
305
  }
@@ -531,11 +547,33 @@ namespace DshComputerUse
531
547
  static void Send(List<Native.INPUT> inputs)
532
548
  {
533
549
  if (inputs.Count == 0) return;
550
+ WaitForInstructionBox();
534
551
  uint sent = Native.SendInput((uint)inputs.Count, inputs.ToArray(), InputSize);
535
552
  if (sent != inputs.Count)
536
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.");
537
554
  }
538
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
+
539
577
  public static void Move(int x, int y)
540
578
  {
541
579
  Native.SetCursorPos(x, y);
@@ -660,10 +698,12 @@ namespace DshComputerUse
660
698
  return null;
661
699
  }
662
700
 
663
- public static object Type(string text, int chunkDelay)
701
+ /** charDelay > 0: one character at a time, like a person typing; otherwise fast batches. */
702
+ public static object Type(string text, int chunkDelay, int charDelay)
664
703
  {
665
704
  var batch = new List<Native.INPUT>();
666
- Action flush = delegate { Send(batch); batch.Clear(); if (chunkDelay > 0) Thread.Sleep(chunkDelay); };
705
+ int pause = charDelay > 0 ? charDelay : chunkDelay;
706
+ Action flush = delegate { if (batch.Count == 0) return; Send(batch); batch.Clear(); if (pause > 0) Thread.Sleep(pause); };
667
707
  for (int i = 0; i < text.Length; i++)
668
708
  {
669
709
  char c = text[i];
@@ -671,13 +711,14 @@ namespace DshComputerUse
671
711
  if (c == '\n') { flush(); batch.Add(Key(0x0D, false)); batch.Add(Key(0x0D, true)); flush(); continue; }
672
712
  if (c == '\t') { batch.Add(Key(0x09, false)); batch.Add(Key(0x09, true)); continue; }
673
713
  batch.Add(Unicode(c, false)); batch.Add(Unicode(c, true));
674
- if (batch.Count >= 40 && !char.IsHighSurrogate(c)) flush();
714
+ if (char.IsHighSurrogate(c)) continue;
715
+ if (charDelay > 0 || batch.Count >= 40) flush();
675
716
  }
676
717
  flush();
677
718
  return null;
678
719
  }
679
720
 
680
- public static object Paste(string text, bool restore)
721
+ public static object Paste(string text, bool restore, int waitMs)
681
722
  {
682
723
  // Keep every format the user had (images, files, rich text), not just text.
683
724
  DataObject previous = null;
@@ -687,7 +728,7 @@ namespace DshComputerUse
687
728
  Send(new List<Native.INPUT> { Key(0x11, false), Key(0x56, false) });
688
729
  Thread.Sleep(30);
689
730
  Send(new List<Native.INPUT> { Key(0x56, true), Key(0x11, true) });
690
- Thread.Sleep(250);
731
+ Thread.Sleep(Math.Max(60, waitMs)); // the app reads the clipboard asynchronously
691
732
  if (restore) { try { Clip.Put(previous); } catch (Exception) { } }
692
733
  return null;
693
734
  }
@@ -764,6 +805,25 @@ namespace DshComputerUse
764
805
  throw new Exception("clipboard is busy");
765
806
  }
766
807
 
808
+ /** The user's clipboard, kept aside while a streamed paste runs. */
809
+ static DataObject held;
810
+ static bool holding;
811
+
812
+ public static void Hold()
813
+ {
814
+ if (holding) return;
815
+ held = Snapshot();
816
+ holding = true;
817
+ }
818
+
819
+ public static void Release()
820
+ {
821
+ if (!holding) return;
822
+ var data = held;
823
+ held = null; holding = false;
824
+ Put(data);
825
+ }
826
+
767
827
  public static void Set(string text, bool isPrivate)
768
828
  {
769
829
  text = Normalize(text);
@@ -818,6 +878,47 @@ namespace DshComputerUse
818
878
  {
819
879
  public static IntPtr Hwnd = IntPtr.Zero;
820
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
+ }
821
922
 
822
923
  static bool Live()
823
924
  {
@@ -839,7 +940,7 @@ namespace DshComputerUse
839
940
  Hwnd = hwnd;
840
941
  originalEx = Native.GetWindowLong(hwnd, -20);
841
942
  Native.SetWindowLong(hwnd, -20, originalEx | 0x80000);
842
- Native.SetLayeredWindowAttributes(hwnd, 0, 255, 2);
943
+ lock (Gate) { hot = false; enteredAt = DateTime.MaxValue; Native.SetLayeredWindowAttributes(hwnd, 0, Current(), 2); }
843
944
  }
844
945
 
845
946
  public static void Detach()
@@ -889,11 +990,17 @@ namespace DshComputerUse
889
990
  public Hidden(IntPtr hwnd)
890
991
  {
891
992
  this.hwnd = hwnd;
892
- 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); }
893
995
  }
894
996
  public void Dispose()
895
997
  {
896
- 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
+ }
897
1004
  }
898
1005
  }
899
1006
  }
@@ -997,24 +1104,30 @@ namespace DshComputerUse
997
1104
  /** While the agent moves, clicks or scrolls, the card lets the mouse through. */
998
1105
  internal sealed class PassThrough : IDisposable
999
1106
  {
1000
- readonly IntPtr hwnd;
1001
- readonly int oldEx;
1002
- readonly bool active;
1107
+ readonly IntPtr[] hwnds;
1108
+ readonly int[] oldEx;
1109
+ bool active;
1003
1110
 
1111
+ /** The DSH card and our progress card let injected pointer input through. */
1004
1112
  public PassThrough()
1005
1113
  {
1006
- hwnd = CardLayer.Hwnd;
1007
- if (hwnd == IntPtr.Zero || !Native.IsWindow(hwnd)) return;
1008
- oldEx = Native.GetWindowLong(hwnd, -20);
1009
- Native.SetWindowLong(hwnd, -20, oldEx | 0x20 | 0x80000); // WS_EX_TRANSPARENT (layered already)
1010
- 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
+ }
1011
1123
  }
1012
1124
 
1013
1125
  public void Dispose()
1014
1126
  {
1015
1127
  if (!active) return;
1016
1128
  Thread.Sleep(60); // let the injected input reach its target first
1017
- 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]);
1018
1131
  }
1019
1132
  }
1020
1133
 
@@ -1087,7 +1200,7 @@ namespace DshComputerUse
1087
1200
  uint pid = 0;
1088
1201
  if (h != IntPtr.Zero) Native.GetWindowThreadProcessId(h, out pid);
1089
1202
  uint cardPid = CardLayer.Pid();
1090
- 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))
1091
1204
  {
1092
1205
  // Our own status pill is under the point (it dodges before the
1093
1206
  // click): report the topmost foreign window there instead.
@@ -1097,7 +1210,7 @@ namespace DshComputerUse
1097
1210
  {
1098
1211
  if (!Native.IsWindowVisible(w)) return true;
1099
1212
  uint p; Native.GetWindowThreadProcessId(w, out p);
1100
- 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
1101
1214
  if ((Native.GetWindowLong(w, -20) & 0x20) != 0) return true; // WS_EX_TRANSPARENT
1102
1215
  if (Native.IsIconic(w)) return true;
1103
1216
  int cloaked;
@@ -1113,6 +1226,92 @@ namespace DshComputerUse
1113
1226
  return Describe(h);
1114
1227
  }
1115
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
+
1116
1315
  public static Dictionary<string, object> Focus(IntPtr hwnd)
1117
1316
  {
1118
1317
  if (!Native.IsWindow(hwnd)) throw new Exception("window no longer exists");
@@ -1229,6 +1428,170 @@ namespace DshComputerUse
1229
1428
  }
1230
1429
  }
1231
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
+
1232
1595
  internal static class Apps
1233
1596
  {
1234
1597
  static List<KeyValuePair<string, string>> cache;
@@ -1457,6 +1820,55 @@ namespace DshComputerUse
1457
1820
  }
1458
1821
  }
1459
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
+
1460
1872
  internal static class Overlay
1461
1873
  {
1462
1874
  static readonly Color Accent = Color.FromArgb(217, 119, 87); // #D97757
@@ -1471,8 +1883,8 @@ namespace DshComputerUse
1471
1883
  static readonly List<KeyValuePair<Rectangle, string>> buttons = new List<KeyValuePair<Rectangle, string>>();
1472
1884
  static bool pillAtBottom;
1473
1885
  static string label = "", status = "", rendered = "";
1474
- static Image icon;
1475
- static string iconPath = "";
1886
+ static Image icon, iconLight;
1887
+ static string iconPath = "", iconLightPath = "";
1476
1888
  static int idleMs = 1500;
1477
1889
  static System.Windows.Forms.Timer timer;
1478
1890
  static DateTime shownAt;
@@ -1484,6 +1896,31 @@ namespace DshComputerUse
1484
1896
  static int lastEmit;
1485
1897
  static readonly object RectLock = new object();
1486
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
+
1487
1924
  static void Ensure()
1488
1925
  {
1489
1926
  if (thread != null) return;
@@ -1515,6 +1952,18 @@ namespace DshComputerUse
1515
1952
  status = Args.Str(r, "status", "");
1516
1953
  idleMs = Args.Int(r, "idleMs", 1500);
1517
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
+ }
1518
1967
  if (path != iconPath)
1519
1968
  {
1520
1969
  iconPath = path;
@@ -1526,7 +1975,12 @@ namespace DshComputerUse
1526
1975
  }
1527
1976
  catch (Exception) { icon = null; }
1528
1977
  }
1529
- 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);
1530
1984
  pillAtBottom = false;
1531
1985
  paused = false;
1532
1986
  foreach (var g in glows) g.Close();
@@ -1542,7 +1996,34 @@ namespace DshComputerUse
1542
1996
  glows.Add(form);
1543
1997
  }
1544
1998
  }
1545
- 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)
1546
2027
  {
1547
2028
  pill = new LayeredForm(false);
1548
2029
  pill.MouseUp += delegate (object s, MouseEventArgs e)
@@ -1566,6 +2047,41 @@ namespace DshComputerUse
1566
2047
  Ui(delegate { status = newStatus; RenderPill(); });
1567
2048
  }
1568
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
+
1569
2085
  public static void SetPaused(bool value)
1570
2086
  {
1571
2087
  if (thread == null) return;
@@ -1575,18 +2091,26 @@ namespace DshComputerUse
1575
2091
  public static void Hide()
1576
2092
  {
1577
2093
  if (thread == null) return;
1578
- Ui(delegate
2094
+ Ui(delegate { HideCore(); });
2095
+ }
2096
+
2097
+ static void HideCore()
2098
+ {
1579
2099
  {
2100
+ CloseInput(false);
2101
+ petFinished = false;
1580
2102
  visible = false;
1581
2103
  paused = false;
1582
2104
  timer.Stop();
1583
2105
  foreach (var g in glows) g.Close();
1584
2106
  glows.Clear();
1585
2107
  if (pill != null) { pill.Close(); pill = null; }
2108
+ if (pet != null) { PetHwnd = IntPtr.Zero; pet.Close(); pet = null; }
2109
+ petMode = false;
1586
2110
  rendered = "";
1587
2111
  lock (RectLock) pillRect = Rectangle.Empty;
1588
2112
  RemoveHook();
1589
- });
2113
+ }
1590
2114
  }
1591
2115
 
1592
2116
  public static void Shutdown()
@@ -1613,15 +2137,75 @@ namespace DshComputerUse
1613
2137
  {
1614
2138
  if (action == "stop") { paused = false; Program.EmitEvent("stop", "button"); }
1615
2139
  else if (action == "pause") { paused = true; Program.EmitEvent("pause", "user"); }
1616
- 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; }
1617
2145
  RenderPill();
1618
2146
  }
1619
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
+
1620
2196
  static bool Typing() { return unchecked(Environment.TickCount - lastTyping) < idleMs; }
1621
2197
 
1622
2198
  static void Tick()
1623
2199
  {
1624
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
+ }
1625
2209
  double t = (DateTime.UtcNow - shownAt).TotalSeconds;
1626
2210
  double fadeIn = Math.Min(1.0, t / 0.35);
1627
2211
  double breathe = paused ? 0.55 : 0.72 + 0.28 * (0.5 + 0.5 * Math.Sin(t * Math.PI * 2 / 2.6));
@@ -1632,6 +2216,8 @@ namespace DshComputerUse
1632
2216
  {
1633
2217
  foreach (var g in glows) g.KeepOnTop();
1634
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);
1635
2221
  }
1636
2222
  }
1637
2223
 
@@ -1690,11 +2276,288 @@ namespace DshComputerUse
1690
2276
  {
1691
2277
  string main, sub; string[] actions, captions;
1692
2278
  Content(out main, out sub, out actions, out captions);
1693
- 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);
1694
2556
  }
1695
2557
 
1696
2558
  static void RenderPill()
1697
2559
  {
2560
+ if (petMode) { RenderPet(); return; }
1698
2561
  if (pill == null) return;
1699
2562
  // The pill lives on the primary display (or the first one).
1700
2563
  Rectangle work = Rectangle.Empty; float scale = 1f;
@@ -1800,7 +2663,7 @@ namespace DshComputerUse
1800
2663
  int msg = wParam.ToInt32();
1801
2664
  var kb = (Native.KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(Native.KBDLLHOOKSTRUCT));
1802
2665
  // Only physical keys count: our own SendInput sets LLKHF_INJECTED (0x10).
1803
- if ((kb.flags & 0x10) == 0)
2666
+ if ((kb.flags & 0x10) == 0 && !(InputHwnd != IntPtr.Zero && Native.GetForegroundWindow() == InputHwnd))
1804
2667
  {
1805
2668
  bool down = msg == 0x100 || msg == 0x104;
1806
2669
  if (kb.vkCode == 0x1B)