@copylee/dsh-computer-use 0.8.7 → 0.9.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.
@@ -279,7 +279,12 @@ namespace DshComputerUse
279
279
  case "settle": return Screen2.Settle(r);
280
280
  case "cursor": { Native.POINT p; Native.GetCursorPos(out p); return Pt(p.X, p.Y); }
281
281
  case "move": using (new PassThrough()) { Overlay.Dodge(Args.Int(r, "x", 0), Args.Int(r, "y", 0)); Input.Move(Args.Int(r, "x", 0), Args.Int(r, "y", 0)); } return null;
282
- case "click": using (new PassThrough()) return Input.Click(r);
282
+ case "click":
283
+ Native.POINT clickPoint;
284
+ if (Args.Has(r, "x")) clickPoint = new Native.POINT(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
285
+ else if (!Native.GetCursorPos(out clickPoint)) throw new Exception("Cannot read cursor position");
286
+ using (CardLayer.UncoverClick(clickPoint))
287
+ using (new PassThrough()) return Input.Click(r);
283
288
  case "button": using (new PassThrough()) return Input.Button(r);
284
289
  case "drag": using (new PassThrough()) return Input.Drag(r);
285
290
  case "scroll": using (new PassThrough()) return Input.Scroll(r);
@@ -396,9 +401,15 @@ namespace DshComputerUse
396
401
  finally { bmp.UnlockBits(data); }
397
402
  }
398
403
 
399
- /** What the screen looked like in the last screenshot the model was shown. */
400
- static byte[] marked;
401
- static string markedRect;
404
+ /** What the screen looked like in the last screenshot the model was shown (per slot: full vs zoom). */
405
+ sealed class MarkedFrame
406
+ {
407
+ public string Rect;
408
+ public byte[] Sample;
409
+ public long OutPixels;
410
+ public int Quality;
411
+ }
412
+ static readonly Dictionary<string, MarkedFrame> markedBySlot = new Dictionary<string, MarkedFrame>();
402
413
 
403
414
  static string RectKey(int x, int y, int w, int h) { return x + "," + y + "," + w + "," + h; }
404
415
 
@@ -486,16 +497,26 @@ namespace DshComputerUse
486
497
  bool compare = Args.Bool(r, "compare", false), mark = Args.Bool(r, "mark", false) || compare;
487
498
  if (mark)
488
499
  {
500
+ string slot = Args.Str(r, "slot", "full");
501
+ if (slot.Length == 0) slot = "full";
489
502
  string key = RectKey(x, y, w, h);
490
503
  byte[] sample = SampleBitmap(bmp);
491
- if (compare && marked != null && markedRect == key && Changed(marked, sample) < Args.Double(r, "threshold", 0.0005))
504
+ long outPixels = (long)ow * oh;
505
+ MarkedFrame prev;
506
+ if (compare && markedBySlot.TryGetValue(slot, out prev) && prev.Rect == key
507
+ && outPixels <= prev.OutPixels && quality <= prev.Quality
508
+ && Changed(prev.Sample, sample) < Args.Double(r, "threshold", 0.0005))
492
509
  {
493
510
  var same = new Dictionary<string, object>();
494
511
  same["unchanged"] = true;
495
512
  return same;
496
513
  }
497
- marked = sample;
498
- markedRect = key;
514
+ var next = new MarkedFrame();
515
+ next.Rect = key;
516
+ next.Sample = sample;
517
+ next.OutPixels = outPixels;
518
+ next.Quality = quality;
519
+ markedBySlot[slot] = next;
499
520
  }
500
521
  Bitmap output = bmp;
501
522
  Bitmap scaled = null;
@@ -620,18 +641,75 @@ namespace DshComputerUse
620
641
  Send(list);
621
642
  }
622
643
 
644
+ sealed class ClickRecord
645
+ {
646
+ public int X;
647
+ public int Y;
648
+ public DateTime At;
649
+ }
650
+ static readonly List<ClickRecord> ClickHistory = new List<ClickRecord>();
651
+ static readonly object ClickLock = new object();
652
+
653
+ static int NoteClick(int x, int y)
654
+ {
655
+ var now = DateTime.UtcNow;
656
+ var cutoff = now.AddMinutes(-2);
657
+ lock (ClickLock)
658
+ {
659
+ int removeCount = 0;
660
+ while (removeCount < ClickHistory.Count && ClickHistory[removeCount].At < cutoff) removeCount++;
661
+ if (removeCount > 0) ClickHistory.RemoveRange(0, removeCount);
662
+ var rec = new ClickRecord();
663
+ rec.X = x;
664
+ rec.Y = y;
665
+ rec.At = now;
666
+ ClickHistory.Add(rec);
667
+ int hits = 0;
668
+ for (int i = 0; i < ClickHistory.Count; i++)
669
+ {
670
+ var item = ClickHistory[i];
671
+ if (Math.Abs(item.X - x) <= 24 && Math.Abs(item.Y - y) <= 24) hits++;
672
+ }
673
+ return hits;
674
+ }
675
+ }
676
+
623
677
  public static object Click(Dictionary<string, object> r)
624
678
  {
625
- if (Args.Has(r, "x"))
679
+ int x, y;
680
+ bool moved = Args.Has(r, "x");
681
+ if (moved)
626
682
  {
627
- int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0);
683
+ x = Args.Int(r, "x", 0);
684
+ y = Args.Int(r, "y", 0);
628
685
  Overlay.Dodge(x, y);
629
686
  Move(x, y);
630
- Thread.Sleep(30);
631
687
  }
632
- uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
688
+ else
689
+ {
690
+ Native.POINT pos;
691
+ if (!Native.GetCursorPos(out pos)) { x = 0; y = 0; }
692
+ else { x = pos.X; y = pos.Y; }
693
+ }
694
+ string button = Args.Str(r, "button", "left");
695
+ if (button != "right" && button != "middle") button = "left";
696
+ uint down, up; Flags(button, out down, out up);
633
697
  int count = Math.Max(1, Math.Min(3, Args.Int(r, "count", 1)));
634
698
  var mods = Args.Ints(r, "modifiers");
699
+ string coordLabel = Args.Has(r, "labelX") && Args.Has(r, "labelY")
700
+ ? Args.Int(r, "labelX", x) + ", " + Args.Int(r, "labelY", y)
701
+ : x + ", " + y;
702
+ bool showTarget = Overlay.ShowClickTarget;
703
+ if (showTarget)
704
+ {
705
+ string preVerb = count >= 3 ? "三击" : count == 2 ? "双击" : button == "right" ? "右键" : button == "middle" ? "中键" : "点击";
706
+ Overlay.Mark(x, y, preVerb + " " + coordLabel, Color.FromArgb(217, 119, 87), 2000, false);
707
+ Thread.Sleep(200);
708
+ }
709
+ else if (moved)
710
+ {
711
+ Thread.Sleep(30);
712
+ }
635
713
  Modifiers(mods, false);
636
714
  try
637
715
  {
@@ -644,7 +722,18 @@ namespace DshComputerUse
644
722
  }
645
723
  }
646
724
  finally { Modifiers(mods, true); }
647
- return null;
725
+ if (showTarget)
726
+ {
727
+ Overlay.MarkResult(x, y, button, count, coordLabel);
728
+ }
729
+ int repeat = NoteClick(x, y);
730
+ var result = new Dictionary<string, object>();
731
+ result["x"] = x;
732
+ result["y"] = y;
733
+ result["button"] = button;
734
+ result["count"] = count;
735
+ result["repeat"] = repeat;
736
+ return result;
648
737
  }
649
738
 
650
739
  public static object Button(Dictionary<string, object> r)
@@ -1007,6 +1096,57 @@ namespace DshComputerUse
1007
1096
  return new Hidden(r.IntersectsWith(area) ? Hwnd : IntPtr.Zero);
1008
1097
  }
1009
1098
 
1099
+ // Chromium cards can swallow SendInput even after WS_EX_TRANSPARENT has
1100
+ // changed the hit test. Hide the card through dispatch only when it covers
1101
+ // the click, keeping its position, z-order and the work window's focus.
1102
+ public static IDisposable UncoverClick(Native.POINT point)
1103
+ {
1104
+ var hwnd = Hwnd;
1105
+ if (!Live()) return null;
1106
+ Native.RECT rect;
1107
+ if (!Native.GetWindowRect(hwnd, out rect)) throw new Exception("Cannot verify the control card bounds");
1108
+ if (point.X < rect.Left || point.X >= rect.Right || point.Y < rect.Top || point.Y >= rect.Bottom) return null;
1109
+ if (Native.GetForegroundWindow() == hwnd) throw new Exception("The control card is focused. Focus the work window before clicking.");
1110
+ object expected;
1111
+ if (!Windows.At(point.X, point.Y).TryGetValue("hwnd", out expected))
1112
+ throw new Exception("No work window found under the control card");
1113
+ var uncovered = new Uncovered(hwnd);
1114
+ try
1115
+ {
1116
+ object hit;
1117
+ if (!Windows.At(point.X, point.Y).TryGetValue("hwnd", out hit) || !Object.Equals(expected, hit))
1118
+ throw new Exception("The window under the control card changed. Look again before clicking.");
1119
+ return uncovered;
1120
+ }
1121
+ catch
1122
+ {
1123
+ uncovered.Dispose();
1124
+ throw;
1125
+ }
1126
+ }
1127
+
1128
+ sealed class Uncovered : IDisposable
1129
+ {
1130
+ // NOSIZE | NOMOVE | NOZORDER | NOACTIVATE | NOOWNERZORDER.
1131
+ const uint PreservePlacement = 0x0217;
1132
+ readonly IntPtr hwnd;
1133
+
1134
+ public Uncovered(IntPtr hwnd)
1135
+ {
1136
+ this.hwnd = hwnd;
1137
+ if (!Native.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, PreservePlacement | 0x0080)
1138
+ || Native.IsWindowVisible(hwnd))
1139
+ throw new Exception("Cannot hide the control card for the click");
1140
+ }
1141
+
1142
+ public void Dispose()
1143
+ {
1144
+ if (Hwnd == hwnd && Native.IsWindow(hwnd)
1145
+ && !Native.SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, PreservePlacement | 0x0040))
1146
+ Native.ShowWindow(hwnd, 4); // SW_SHOWNOACTIVATE
1147
+ }
1148
+ }
1149
+
1010
1150
  sealed class Hidden : IDisposable
1011
1151
  {
1012
1152
  readonly IntPtr hwnd;
@@ -1900,8 +2040,12 @@ namespace DshComputerUse
1900
2040
  if (String.Join(",", el.GetRuntimeId()) == runtimeId) { target = el; break; }
1901
2041
  if (el.Current.ControlType == ControlType.Window) break;
1902
2042
  }
1903
- if (target == null || target.Current.IsOffscreen || !target.Current.IsEnabled)
1904
- throw new Exception("The named target changed or is no longer actionable");
2043
+ // Some providers stop the hit test at a host pane. The caller can
2044
+ // re-resolve the control and verify its window before a pointer click.
2045
+ if (target == null) return result;
2046
+ if (target.Current.IsOffscreen) throw new Exception("The named target is offscreen");
2047
+ if (!target.Current.IsEnabled)
2048
+ throw new Exception("The named target is disabled");
1905
2049
  object pattern = null;
1906
2050
  if (action == "invoke" && !target.TryGetCurrentPattern(InvokePattern.Pattern, out pattern)) return result;
1907
2051
  if (action == "focus" && !target.Current.IsKeyboardFocusable) return result;
@@ -2419,6 +2563,11 @@ namespace DshComputerUse
2419
2563
  {
2420
2564
  Native.SetWindowPos(Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010 | 0x0200); // NOSIZE|NOMOVE|NOACTIVATE|NOOWNERZORDER
2421
2565
  }
2566
+
2567
+ public void SetCapturable(bool capturable)
2568
+ {
2569
+ try { Native.SetWindowDisplayAffinity(Handle, capturable ? 0u : 0x11u); } catch (Exception) { }
2570
+ }
2422
2571
  }
2423
2572
 
2424
2573
  /** The progress card's instruction box: a small focusable window laid over the card's field. */
@@ -2493,6 +2642,10 @@ namespace DshComputerUse
2493
2642
  static Native.LowLevelKeyboardProc hookProc;
2494
2643
  static volatile bool visible;
2495
2644
  static volatile bool paused;
2645
+ static volatile bool clickTargetEnabled = true;
2646
+ static LayeredForm markForm;
2647
+ static DateTime markExpiresAt = DateTime.MinValue;
2648
+ static bool markActive;
2496
2649
  static int lastTyping = int.MinValue / 2;
2497
2650
  static int lastEmit;
2498
2651
  static readonly object RectLock = new object();
@@ -2576,6 +2729,7 @@ namespace DshComputerUse
2576
2729
  catch (Exception) { icon = null; }
2577
2730
  }
2578
2731
  petAlpha = (byte)Math.Max(90, Math.Min(255, Args.Int(r, "petOpacity", 90) * 255 / 100));
2732
+ clickTargetEnabled = Args.Bool(r, "glow", true);
2579
2733
  if (visible && !petFinished) { RenderPill(); return; }
2580
2734
  if (visible) HideCore(); // the previous run's "done" card is still up
2581
2735
  petMode = Args.Bool(r, "pet", false);
@@ -2668,6 +2822,7 @@ namespace DshComputerUse
2668
2822
  Ui(delegate
2669
2823
  {
2670
2824
  if (!visible || !petMode) { HideCore(); return; }
2825
+ HideMark();
2671
2826
  CloseInput(false);
2672
2827
  foreach (var g in glows) g.Close();
2673
2828
  glows.Clear();
@@ -2695,6 +2850,7 @@ namespace DshComputerUse
2695
2850
  static void HideCore()
2696
2851
  {
2697
2852
  {
2853
+ HideMark();
2698
2854
  CloseInput(false);
2699
2855
  petFinished = false;
2700
2856
  visible = false;
@@ -2717,6 +2873,141 @@ namespace DshComputerUse
2717
2873
  try { Hide(); Ui(delegate { Application.ExitThread(); }); } catch (Exception) { }
2718
2874
  }
2719
2875
 
2876
+ public static bool ShowClickTarget { get { return visible && clickTargetEnabled; } }
2877
+
2878
+ static void MonitorAt(int x, int y, out float scale, out Rectangle bounds)
2879
+ {
2880
+ scale = 1f;
2881
+ bounds = Rectangle.Empty;
2882
+ bool found = false;
2883
+ foreach (Dictionary<string, object> d in Screen2.Displays())
2884
+ {
2885
+ var r = new Rectangle((int)d["x"], (int)d["y"], (int)d["width"], (int)d["height"]);
2886
+ float s = (int)d["dpi"] / 96f;
2887
+ if (r.Contains(x, y)) { scale = s; bounds = r; return; }
2888
+ if (!found || (bool)d["primary"]) { scale = s; bounds = r; found = true; }
2889
+ }
2890
+ }
2891
+
2892
+ static Bitmap DrawMark(string text, Color color, float scale, bool labelAbove, out int cx, out int cy)
2893
+ {
2894
+ float s = Math.Max(0.75f, scale);
2895
+ float px = 1.333f * s;
2896
+ float ringR = 18f * s;
2897
+ float arm = 25f * s;
2898
+ float gap = 6f * s;
2899
+ float pad = 4f * s;
2900
+ float labelGap = 6f * s;
2901
+ using (var font = new Font("Microsoft YaHei UI", 8.5f * px, FontStyle.Bold, GraphicsUnit.Pixel))
2902
+ using (var probe = new Bitmap(1, 1))
2903
+ using (var mg = Graphics.FromImage(probe))
2904
+ using (var fmt = new StringFormat(StringFormat.GenericTypographic))
2905
+ {
2906
+ mg.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
2907
+ fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap;
2908
+ SizeF textSize = string.IsNullOrEmpty(text) ? SizeF.Empty : mg.MeasureString(text, font, 10000, fmt);
2909
+ float pillPadX = 8f * s, pillPadY = 3f * s;
2910
+ float pillW = textSize.Width > 0 ? textSize.Width + 2f * pillPadX : 0f;
2911
+ float pillH = textSize.Height > 0 ? textSize.Height + 2f * pillPadY : 0f;
2912
+ float ringSpan = 2f * (arm + pad);
2913
+ int W = (int)Math.Ceiling(Math.Max(ringSpan, pillW + 2f * pad));
2914
+ if (W % 2 == 1) W++;
2915
+ int H = (int)Math.Ceiling(ringSpan + (pillH > 0 ? labelGap + pillH + pad : 0f));
2916
+ cx = W / 2;
2917
+ cy = labelAbove && pillH > 0 ? (int)Math.Round(pad + pillH + labelGap + arm) : (int)Math.Round(pad + arm);
2918
+
2919
+ var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb);
2920
+ using (var g = Graphics.FromImage(bmp))
2921
+ {
2922
+ g.Clear(Color.Transparent);
2923
+ g.SmoothingMode = SmoothingMode.AntiAlias;
2924
+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
2925
+
2926
+ // Soft tinted halo inside the ring so the mark reads clearly in screenshots.
2927
+ using (var fill = new SolidBrush(Color.FromArgb(40, color)))
2928
+ g.FillEllipse(fill, cx - ringR, cy - ringR, ringR * 2f, ringR * 2f);
2929
+ // High-contrast dark outline behind the colored ring & crosshair.
2930
+ using (var halo = new Pen(Color.FromArgb(180, 20, 20, 20), Math.Max(3.5f, 4.2f * s)))
2931
+ g.DrawEllipse(halo, cx - ringR, cy - ringR, ringR * 2f, ringR * 2f);
2932
+ using (var pen = new Pen(Color.FromArgb(245, color), Math.Max(2f, 2.6f * s)))
2933
+ {
2934
+ g.DrawEllipse(pen, cx - ringR, cy - ringR, ringR * 2f, ringR * 2f);
2935
+ g.DrawLine(pen, cx - arm, cy, cx - gap, cy);
2936
+ g.DrawLine(pen, cx + gap, cy, cx + arm, cy);
2937
+ g.DrawLine(pen, cx, cy - arm, cx, cy - gap);
2938
+ g.DrawLine(pen, cx, cy + gap, cx, cy + arm);
2939
+ }
2940
+ float dotR = Math.Max(2f, 2.4f * s);
2941
+ using (var dot = new SolidBrush(Color.FromArgb(245, color)))
2942
+ g.FillEllipse(dot, cx - dotR, cy - dotR, dotR * 2f, dotR * 2f);
2943
+
2944
+ if (pillW > 0 && pillH > 0)
2945
+ {
2946
+ float pillY = labelAbove ? pad : cy + arm + labelGap;
2947
+ var pillBox = new RectangleF((W - pillW) / 2f, pillY, pillW, pillH);
2948
+ using (var path = Rounded(pillBox, pillH / 2f))
2949
+ {
2950
+ using (var bg = new SolidBrush(Color.FromArgb(228, 28, 27, 26))) g.FillPath(bg, path);
2951
+ using (var border = new Pen(Color.FromArgb(230, color), Math.Max(1f, 1.3f * s))) g.DrawPath(border, path);
2952
+ }
2953
+ using (var fg = new SolidBrush(Color.White))
2954
+ g.DrawString(text, font, fg, pillBox.X + pillPadX, pillBox.Y + (pillH - textSize.Height) / 2f, fmt);
2955
+ }
2956
+ }
2957
+ return bmp;
2958
+ }
2959
+ }
2960
+
2961
+ public static void Mark(int x, int y, string text, Color color, int holdMs, bool capturable)
2962
+ {
2963
+ Ensure();
2964
+ Ui(delegate
2965
+ {
2966
+ if (markForm == null)
2967
+ {
2968
+ markForm = new LayeredForm(true);
2969
+ markForm.Show();
2970
+ }
2971
+ markForm.SetCapturable(capturable || !ExcludeFromCapture);
2972
+ float scale; Rectangle mon;
2973
+ MonitorAt(x, y, out scale, out mon);
2974
+ bool labelAbove = !mon.IsEmpty && y + (int)(66 * scale) > mon.Bottom;
2975
+ int cx, cy;
2976
+ using (var bmp = DrawMark(text, color, scale, labelAbove, out cx, out cy))
2977
+ {
2978
+ markForm.SetBitmap(bmp, new Rectangle(x - cx, y - cy, bmp.Width, bmp.Height), 255);
2979
+ }
2980
+ markForm.KeepOnTop();
2981
+ markActive = true;
2982
+ markExpiresAt = holdMs > 0 ? DateTime.UtcNow.AddMilliseconds(holdMs) : DateTime.MaxValue;
2983
+ if (!timer.Enabled) timer.Start();
2984
+ });
2985
+ }
2986
+
2987
+ public static void MarkResult(int x, int y, string button, int count, string coordLabel)
2988
+ {
2989
+ Color color;
2990
+ string verb;
2991
+ if (count >= 3) { color = Color.FromArgb(249, 115, 22); verb = "已三击"; }
2992
+ else if (count == 2) { color = Color.FromArgb(147, 51, 234); verb = "已双击"; }
2993
+ else if (button == "right") { color = Color.FromArgb(34, 197, 94); verb = "已右键"; }
2994
+ else if (button == "middle") { color = Color.FromArgb(6, 182, 212); verb = "已中键"; }
2995
+ else { color = Color.FromArgb(59, 130, 246); verb = "已单击"; }
2996
+ Mark(x, y, verb + " " + coordLabel, color, 4000, true);
2997
+ }
2998
+
2999
+ static void HideMark()
3000
+ {
3001
+ markActive = false;
3002
+ markExpiresAt = DateTime.MinValue;
3003
+ if (markForm != null)
3004
+ {
3005
+ markForm.SetCapturable(false);
3006
+ markForm.Close();
3007
+ markForm = null;
3008
+ }
3009
+ }
3010
+
2720
3011
  /// Move the status pill out of the way when an injected pointer action
2721
3012
  /// targets it: the pill is clickable for the user but invisible to the model.
2722
3013
  public static void Dodge(int x, int y)
@@ -2795,7 +3086,12 @@ namespace DshComputerUse
2795
3086
 
2796
3087
  static void Tick()
2797
3088
  {
2798
- if (!visible) return;
3089
+ if (markActive && DateTime.UtcNow >= markExpiresAt) HideMark();
3090
+ if (!visible)
3091
+ {
3092
+ if (!markActive) timer.Stop();
3093
+ return;
3094
+ }
2799
3095
  if (petFinished)
2800
3096
  {
2801
3097
  Native.POINT p; Native.GetCursorPos(out p);
@@ -2815,6 +3111,7 @@ namespace DshComputerUse
2815
3111
  foreach (var g in glows) g.KeepOnTop();
2816
3112
  if (pill != null) pill.KeepOnTop();
2817
3113
  if (pet != null) pet.KeepOnTop();
3114
+ if (markForm != null) markForm.KeepOnTop();
2818
3115
  if (input != null) Native.SetWindowPos(input.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);
2819
3116
  }
2820
3117
  }