@copylee/dsh-computer-use 0.8.8 → 0.10.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.
@@ -21,6 +21,7 @@ using System.Drawing.Drawing2D;
21
21
  using System.Drawing.Imaging;
22
22
  using System.Drawing.Text;
23
23
  using System.IO;
24
+ using System.Reflection;
24
25
  using System.Runtime.InteropServices;
25
26
  using System.Text;
26
27
  using System.Threading;
@@ -278,7 +279,15 @@ namespace DshComputerUse
278
279
  case "screenshot": return Screen2.Capture(r);
279
280
  case "settle": return Screen2.Settle(r);
280
281
  case "cursor": { Native.POINT p; Native.GetCursorPos(out p); return Pt(p.X, p.Y); }
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 "move":
283
+ using (new PassThrough())
284
+ {
285
+ int mx = Args.Int(r, "x", 0), my = Args.Int(r, "y", 0);
286
+ Overlay.Dodge(mx, my);
287
+ Input.Move(mx, my);
288
+ if (Overlay.ShowClickTarget) Overlay.MarkPointer(mx, my, "DSH", 900);
289
+ }
290
+ return null;
282
291
  case "click":
283
292
  Native.POINT clickPoint;
284
293
  if (Args.Has(r, "x")) clickPoint = new Native.POINT(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
@@ -319,6 +328,7 @@ namespace DshComputerUse
319
328
  case "clipboard_restore": { var d = new Dictionary<string, object>(); d["restored"] = Clip.RestoreAgent(); return d; }
320
329
  case "ui": return Uia.Elements(r);
321
330
  case "text": return Uia.Text(r);
331
+ case "ocr": return Ocr.Read(r);
322
332
  case "overlay_show": Overlay.ExcludeFromCapture = Args.Bool(r, "excludeFromCapture", true); Overlay.Show(r); return null;
323
333
  case "overlay_pause": Overlay.SetPaused(Args.Bool(r, "paused", false)); return null;
324
334
  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));
@@ -401,9 +411,15 @@ namespace DshComputerUse
401
411
  finally { bmp.UnlockBits(data); }
402
412
  }
403
413
 
404
- /** What the screen looked like in the last screenshot the model was shown. */
405
- static byte[] marked;
406
- static string markedRect;
414
+ /** What the screen looked like in the last screenshot the model was shown (per slot: full vs zoom). */
415
+ sealed class MarkedFrame
416
+ {
417
+ public string Rect;
418
+ public byte[] Sample;
419
+ public long OutPixels;
420
+ public int Quality;
421
+ }
422
+ static readonly Dictionary<string, MarkedFrame> markedBySlot = new Dictionary<string, MarkedFrame>();
407
423
 
408
424
  static string RectKey(int x, int y, int w, int h) { return x + "," + y + "," + w + "," + h; }
409
425
 
@@ -448,14 +464,11 @@ namespace DshComputerUse
448
464
 
449
465
  static ImageCodecInfo jpegCodec;
450
466
 
451
- public static Dictionary<string, object> Capture(Dictionary<string, object> r)
467
+ public static Bitmap Grab(int x, int y, int w, int h, out string via)
452
468
  {
453
- int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0), w = Args.Int(r, "width", 0), h = Args.Int(r, "height", 0);
454
- int ow = Args.Int(r, "outWidth", w), oh = Args.Int(r, "outHeight", h);
455
- int quality = Args.Int(r, "quality", 80);
456
- if (w <= 0 || h <= 0 || ow <= 0 || oh <= 0) throw new Exception("invalid capture size");
457
- string via = "blt";
458
- using (var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb))
469
+ via = "blt";
470
+ var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb);
471
+ try
459
472
  {
460
473
  using (var g = Graphics.FromImage(bmp))
461
474
  {
@@ -466,7 +479,6 @@ namespace DshComputerUse
466
479
  // the card (no flicker). Fallback: hide the card for one BitBlt.
467
480
  bool done = false;
468
481
  var area = new Rectangle(x, y, w, h);
469
- via = "blt";
470
482
  if (CardLayer.Covers(area))
471
483
  {
472
484
  g.ReleaseHdc(dst);
@@ -487,20 +499,48 @@ namespace DshComputerUse
487
499
  }
488
500
  Native.ReleaseDC(IntPtr.Zero, src);
489
501
  }
502
+ return bmp;
503
+ }
504
+ catch
505
+ {
506
+ bmp.Dispose();
507
+ throw;
508
+ }
509
+ }
510
+
511
+ public static Dictionary<string, object> Capture(Dictionary<string, object> r)
512
+ {
513
+ int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0), w = Args.Int(r, "width", 0), h = Args.Int(r, "height", 0);
514
+ int ow = Args.Int(r, "outWidth", w), oh = Args.Int(r, "outHeight", h);
515
+ int quality = Args.Int(r, "quality", 80);
516
+ if (w <= 0 || h <= 0 || ow <= 0 || oh <= 0) throw new Exception("invalid capture size");
517
+ string via;
518
+ using (var bmp = Grab(x, y, w, h, out via))
519
+ {
490
520
  // compare: report "unchanged" instead of an identical image; mark: remember for next time.
491
521
  bool compare = Args.Bool(r, "compare", false), mark = Args.Bool(r, "mark", false) || compare;
492
522
  if (mark)
493
523
  {
524
+ string slot = Args.Str(r, "slot", "full");
525
+ if (slot.Length == 0) slot = "full";
494
526
  string key = RectKey(x, y, w, h);
495
527
  byte[] sample = SampleBitmap(bmp);
496
- if (compare && marked != null && markedRect == key && Changed(marked, sample) < Args.Double(r, "threshold", 0.0005))
528
+ long outPixels = (long)ow * oh;
529
+ MarkedFrame prev;
530
+ if (compare && markedBySlot.TryGetValue(slot, out prev) && prev.Rect == key
531
+ && outPixels <= prev.OutPixels && quality <= prev.Quality
532
+ && Changed(prev.Sample, sample) < Args.Double(r, "threshold", 0.0005))
497
533
  {
498
534
  var same = new Dictionary<string, object>();
499
535
  same["unchanged"] = true;
500
536
  return same;
501
537
  }
502
- marked = sample;
503
- markedRect = key;
538
+ var next = new MarkedFrame();
539
+ next.Rect = key;
540
+ next.Sample = sample;
541
+ next.OutPixels = outPixels;
542
+ next.Quality = quality;
543
+ markedBySlot[slot] = next;
504
544
  }
505
545
  Bitmap output = bmp;
506
546
  Bitmap scaled = null;
@@ -539,6 +579,298 @@ namespace DshComputerUse
539
579
  }
540
580
  }
541
581
 
582
+ /**
583
+ * Built-in Windows 10/11 OCR via WinRT reflection (Windows.Media.Ocr).
584
+ * Zero extra compile references or native DLLs: falls back cleanly if the
585
+ * host OS has no WinRT OCR language pack installed.
586
+ */
587
+ internal static class Ocr
588
+ {
589
+ static Type tEngine, tDecoder, tStream, tWriter, tAsyncInfo;
590
+ static object cachedEngine;
591
+ static string cachedLanguage = "";
592
+ static int cachedMaxDim = 2600;
593
+ static bool initTried;
594
+
595
+ static void EnsureTypes()
596
+ {
597
+ if (initTried) return;
598
+ initTried = true;
599
+ tEngine = Type.GetType("Windows.Media.Ocr.OcrEngine, Windows.Media, ContentType=WindowsRuntime", false);
600
+ tDecoder = Type.GetType("Windows.Graphics.Imaging.BitmapDecoder, Windows.Graphics, ContentType=WindowsRuntime", false);
601
+ tStream = Type.GetType("Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage, ContentType=WindowsRuntime", false);
602
+ tWriter = Type.GetType("Windows.Storage.Streams.DataWriter, Windows.Storage, ContentType=WindowsRuntime", false);
603
+ tAsyncInfo = Type.GetType("Windows.Foundation.IAsyncInfo, Windows.Foundation, ContentType=WindowsRuntime", false);
604
+ if (tEngine == null || tDecoder == null || tStream == null || tWriter == null || tAsyncInfo == null) return;
605
+ try
606
+ {
607
+ var create = tEngine.GetMethod("TryCreateFromUserProfileLanguages", BindingFlags.Public | BindingFlags.Static);
608
+ if (create != null) cachedEngine = create.Invoke(null, null);
609
+ if (cachedEngine != null)
610
+ {
611
+ object lang = GetProp(cachedEngine, "RecognizerLanguage");
612
+ if (lang != null) cachedLanguage = Convert.ToString(GetProp(lang, "LanguageTag")) ?? "";
613
+ var maxProp = tEngine.GetProperty("MaxImageDimension", BindingFlags.Public | BindingFlags.Static);
614
+ if (maxProp != null)
615
+ {
616
+ int dim = Convert.ToInt32(maxProp.GetValue(null, null));
617
+ if (dim >= 512) cachedMaxDim = dim;
618
+ }
619
+ }
620
+ }
621
+ catch (Exception) { cachedEngine = null; }
622
+ }
623
+
624
+ static MethodInfo FindMethod(Type t, string name, int argCount)
625
+ {
626
+ if (t == null) return null;
627
+ foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
628
+ if (m.Name == name && m.GetParameters().Length == argCount) return m;
629
+ foreach (var iface in t.GetInterfaces())
630
+ foreach (var m in iface.GetMethods(BindingFlags.Public | BindingFlags.Instance))
631
+ if (m.Name == name && m.GetParameters().Length == argCount) return m;
632
+ return null;
633
+ }
634
+
635
+ static object Invoke(object target, string name, params object[] args)
636
+ {
637
+ var m = FindMethod(target.GetType(), name, args == null ? 0 : args.Length);
638
+ if (m == null) throw new Exception("WinRT method not found: " + name);
639
+ return m.Invoke(target, args);
640
+ }
641
+
642
+ static object InvokeAsync(object target, string name, int timeoutMs, params object[] args)
643
+ {
644
+ var m = FindMethod(target.GetType(), name, args == null ? 0 : args.Length);
645
+ if (m == null) throw new Exception("WinRT method not found: " + name);
646
+ object op = m.Invoke(target, args);
647
+ return AwaitWinRt(op, m.ReturnType, timeoutMs);
648
+ }
649
+
650
+ static object GetProp(object target, string name)
651
+ {
652
+ var t = target.GetType();
653
+ var p = t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
654
+ if (p != null) return p.GetValue(target, null);
655
+ foreach (var iface in t.GetInterfaces())
656
+ {
657
+ p = iface.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
658
+ if (p != null) return p.GetValue(target, null);
659
+ }
660
+ return null;
661
+ }
662
+
663
+ static object AwaitWinRt(object asyncOp, Type asyncType, int timeoutMs)
664
+ {
665
+ if (asyncOp == null) return null;
666
+ var statusProp = tAsyncInfo.GetProperty("Status");
667
+ var errProp = tAsyncInfo.GetProperty("ErrorCode");
668
+ var watch = Stopwatch.StartNew();
669
+ while (true)
670
+ {
671
+ int status = Convert.ToInt32(statusProp.GetValue(asyncOp, null));
672
+ if (status == 1) // Completed
673
+ {
674
+ var getResults = FindMethod(asyncType, "GetResults", 0) ?? FindMethod(asyncOp.GetType(), "GetResults", 0);
675
+ return getResults != null ? getResults.Invoke(asyncOp, null) : null;
676
+ }
677
+ if (status == 2) throw new Exception("Windows OCR operation was cancelled");
678
+ if (status == 3)
679
+ {
680
+ object err = errProp != null ? errProp.GetValue(asyncOp, null) : null;
681
+ throw new Exception("Windows OCR failed: " + (err != null ? err.ToString() : "unknown error"));
682
+ }
683
+ if (watch.ElapsedMilliseconds >= timeoutMs)
684
+ {
685
+ try { var cancel = tAsyncInfo.GetMethod("Cancel"); if (cancel != null) cancel.Invoke(asyncOp, null); } catch (Exception) { }
686
+ throw new Exception("Windows OCR timed out");
687
+ }
688
+ Thread.Sleep(5);
689
+ }
690
+ }
691
+
692
+ static bool IsCjk(char c)
693
+ {
694
+ return (c >= '\u4E00' && c <= '\u9FFF') || (c >= '\u3400' && c <= '\u4DBF')
695
+ || (c >= '\u3000' && c <= '\u303F') || (c >= '\uFF00' && c <= '\uFFEF');
696
+ }
697
+
698
+ /** Collapse spaces Windows.Media.Ocr inserts between adjacent CJK characters. */
699
+ static string CleanLineText(string s)
700
+ {
701
+ if (string.IsNullOrEmpty(s)) return "";
702
+ var sb = new StringBuilder(s.Length);
703
+ for (int i = 0; i < s.Length; i++)
704
+ {
705
+ char c = s[i];
706
+ if (c == ' ' && sb.Length > 0 && i + 1 < s.Length && IsCjk(sb[sb.Length - 1]) && IsCjk(s[i + 1]))
707
+ continue;
708
+ sb.Append(c);
709
+ }
710
+ return sb.ToString();
711
+ }
712
+
713
+ static void TryDispose(object obj)
714
+ {
715
+ var d = obj as IDisposable;
716
+ if (d != null) { try { d.Dispose(); } catch (Exception) { } }
717
+ }
718
+
719
+ public static Dictionary<string, object> Read(Dictionary<string, object> r)
720
+ {
721
+ EnsureTypes();
722
+ if (cachedEngine == null)
723
+ throw new Exception("Windows OCR is not available on this system (no OCR language pack found).");
724
+
725
+ int x, y, w, h;
726
+ var meta = new Dictionary<string, object>();
727
+ if (Args.Has(r, "width") && Args.Has(r, "height"))
728
+ {
729
+ x = Args.Int(r, "x", 0);
730
+ y = Args.Int(r, "y", 0);
731
+ w = Args.Int(r, "width", 0);
732
+ h = Args.Int(r, "height", 0);
733
+ }
734
+ else
735
+ {
736
+ IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
737
+ var desc = Windows.Describe(hwnd);
738
+ if (desc.Count == 0) throw new Exception("No target window found for OCR.");
739
+ foreach (var kv in desc) meta[kv.Key] = kv.Value;
740
+ var vs = SystemInformation.VirtualScreen;
741
+ int rx = Convert.ToInt32(desc["x"]), ry = Convert.ToInt32(desc["y"]);
742
+ int rw = Convert.ToInt32(desc["width"]), rh = Convert.ToInt32(desc["height"]);
743
+ int left = Math.Max(vs.Left, rx);
744
+ int top = Math.Max(vs.Top, ry);
745
+ int right = Math.Min(vs.Right, rx + rw);
746
+ int bottom = Math.Min(vs.Bottom, ry + rh);
747
+ x = left; y = top; w = right - left; h = bottom - top;
748
+ }
749
+ if (w <= 2 || h <= 2) throw new Exception("Target area is too small for OCR.");
750
+
751
+ string via;
752
+ using (var rawBmp = Screen2.Grab(x, y, w, h, out via))
753
+ {
754
+ double scale = 1.0;
755
+ int maxSide = Math.Max(w, h);
756
+ if (maxSide > cachedMaxDim) scale = (double)cachedMaxDim / maxSide;
757
+ Bitmap work = rawBmp;
758
+ Bitmap resized = null;
759
+ byte[] pngBytes;
760
+ try
761
+ {
762
+ if (scale < 1.0)
763
+ {
764
+ int nw = Math.Max(1, (int)Math.Round(w * scale));
765
+ int nh = Math.Max(1, (int)Math.Round(h * scale));
766
+ resized = new Bitmap(nw, nh, PixelFormat.Format24bppRgb);
767
+ using (var g = Graphics.FromImage(resized))
768
+ {
769
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
770
+ g.DrawImage(rawBmp, 0, 0, nw, nh);
771
+ }
772
+ work = resized;
773
+ }
774
+ using (var ms = new MemoryStream())
775
+ {
776
+ work.Save(ms, ImageFormat.Png);
777
+ pngBytes = ms.ToArray();
778
+ }
779
+ }
780
+ finally { if (resized != null) resized.Dispose(); }
781
+
782
+ object ras = null, writer = null, softwareBitmap = null;
783
+ try
784
+ {
785
+ ras = Activator.CreateInstance(tStream);
786
+ writer = Activator.CreateInstance(tWriter, new object[] { ras });
787
+ Invoke(writer, "WriteBytes", new object[] { pngBytes });
788
+ InvokeAsync(writer, "StoreAsync", 8000);
789
+ InvokeAsync(writer, "FlushAsync", 8000);
790
+ Invoke(writer, "DetachStream");
791
+ TryDispose(writer); writer = null;
792
+ Invoke(ras, "Seek", new object[] { (ulong)0 });
793
+
794
+ MethodInfo createDecoder = null;
795
+ foreach (var m in tDecoder.GetMethods(BindingFlags.Public | BindingFlags.Static))
796
+ if (m.Name == "CreateAsync" && m.GetParameters().Length == 1) { createDecoder = m; break; }
797
+ if (createDecoder == null) throw new Exception("BitmapDecoder.CreateAsync not found");
798
+ object decoder = AwaitWinRt(createDecoder.Invoke(null, new object[] { ras }), createDecoder.ReturnType, 8000);
799
+ if (decoder == null) throw new Exception("BitmapDecoder returned null");
800
+ softwareBitmap = InvokeAsync(decoder, "GetSoftwareBitmapAsync", 8000);
801
+ if (softwareBitmap == null) throw new Exception("GetSoftwareBitmapAsync returned null");
802
+ object ocrResult = InvokeAsync(cachedEngine, "RecognizeAsync", 10000, new object[] { softwareBitmap });
803
+ if (ocrResult == null) throw new Exception("OcrEngine.RecognizeAsync returned null");
804
+
805
+ var linesOut = new List<object>();
806
+ var allLines = new List<string>();
807
+ double invScale = 1.0 / scale;
808
+ var rawLines = GetProp(ocrResult, "Lines") as IEnumerable;
809
+ if (rawLines != null)
810
+ {
811
+ foreach (var line in rawLines)
812
+ {
813
+ string lineText = CleanLineText(Convert.ToString(GetProp(line, "Text")) ?? "");
814
+ if (lineText.Trim().Length == 0) continue;
815
+ var wordsOut = new List<object>();
816
+ double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
817
+ var rawWords = GetProp(line, "Words") as IEnumerable;
818
+ if (rawWords != null)
819
+ {
820
+ foreach (var word in rawWords)
821
+ {
822
+ string wt = Convert.ToString(GetProp(word, "Text")) ?? "";
823
+ object rect = GetProp(word, "BoundingRect");
824
+ if (rect == null) continue;
825
+ double wx = Convert.ToDouble(GetProp(rect, "X")) * invScale;
826
+ double wy = Convert.ToDouble(GetProp(rect, "Y")) * invScale;
827
+ double ww = Convert.ToDouble(GetProp(rect, "Width")) * invScale;
828
+ double wh = Convert.ToDouble(GetProp(rect, "Height")) * invScale;
829
+ if (wx < minX) minX = wx;
830
+ if (wy < minY) minY = wy;
831
+ if (wx + ww > maxX) maxX = wx + ww;
832
+ if (wy + wh > maxY) maxY = wy + wh;
833
+ var wd = new Dictionary<string, object>();
834
+ wd["text"] = wt;
835
+ wd["x"] = x + (int)Math.Round(wx);
836
+ wd["y"] = y + (int)Math.Round(wy);
837
+ wd["width"] = Math.Max(1, (int)Math.Round(ww));
838
+ wd["height"] = Math.Max(1, (int)Math.Round(wh));
839
+ wordsOut.Add(wd);
840
+ }
841
+ }
842
+ if (minX == double.MaxValue) continue;
843
+ var ld = new Dictionary<string, object>();
844
+ ld["text"] = lineText;
845
+ ld["x"] = x + (int)Math.Round(minX);
846
+ ld["y"] = y + (int)Math.Round(minY);
847
+ ld["width"] = Math.Max(1, (int)Math.Round(maxX - minX));
848
+ ld["height"] = Math.Max(1, (int)Math.Round(maxY - minY));
849
+ ld["words"] = wordsOut;
850
+ linesOut.Add(ld);
851
+ allLines.Add(lineText);
852
+ }
853
+ }
854
+
855
+ meta["language"] = cachedLanguage;
856
+ meta["x"] = x;
857
+ meta["y"] = y;
858
+ meta["width"] = w;
859
+ meta["height"] = h;
860
+ meta["text"] = string.Join("\n", allLines.ToArray());
861
+ meta["lines"] = linesOut;
862
+ return meta;
863
+ }
864
+ finally
865
+ {
866
+ TryDispose(softwareBitmap);
867
+ TryDispose(writer);
868
+ TryDispose(ras);
869
+ }
870
+ }
871
+ }
872
+ }
873
+
542
874
  internal static class Input
543
875
  {
544
876
  static readonly int InputSize = Marshal.SizeOf(typeof(Native.INPUT));
@@ -625,18 +957,75 @@ namespace DshComputerUse
625
957
  Send(list);
626
958
  }
627
959
 
960
+ sealed class ClickRecord
961
+ {
962
+ public int X;
963
+ public int Y;
964
+ public DateTime At;
965
+ }
966
+ static readonly List<ClickRecord> ClickHistory = new List<ClickRecord>();
967
+ static readonly object ClickLock = new object();
968
+
969
+ static int NoteClick(int x, int y)
970
+ {
971
+ var now = DateTime.UtcNow;
972
+ var cutoff = now.AddMinutes(-2);
973
+ lock (ClickLock)
974
+ {
975
+ int removeCount = 0;
976
+ while (removeCount < ClickHistory.Count && ClickHistory[removeCount].At < cutoff) removeCount++;
977
+ if (removeCount > 0) ClickHistory.RemoveRange(0, removeCount);
978
+ var rec = new ClickRecord();
979
+ rec.X = x;
980
+ rec.Y = y;
981
+ rec.At = now;
982
+ ClickHistory.Add(rec);
983
+ int hits = 0;
984
+ for (int i = 0; i < ClickHistory.Count; i++)
985
+ {
986
+ var item = ClickHistory[i];
987
+ if (Math.Abs(item.X - x) <= 24 && Math.Abs(item.Y - y) <= 24) hits++;
988
+ }
989
+ return hits;
990
+ }
991
+ }
992
+
628
993
  public static object Click(Dictionary<string, object> r)
629
994
  {
630
- if (Args.Has(r, "x"))
995
+ int x, y;
996
+ bool moved = Args.Has(r, "x");
997
+ if (moved)
631
998
  {
632
- int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0);
999
+ x = Args.Int(r, "x", 0);
1000
+ y = Args.Int(r, "y", 0);
633
1001
  Overlay.Dodge(x, y);
634
1002
  Move(x, y);
635
- Thread.Sleep(30);
636
1003
  }
637
- uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
1004
+ else
1005
+ {
1006
+ Native.POINT pos;
1007
+ if (!Native.GetCursorPos(out pos)) { x = 0; y = 0; }
1008
+ else { x = pos.X; y = pos.Y; }
1009
+ }
1010
+ string button = Args.Str(r, "button", "left");
1011
+ if (button != "right" && button != "middle") button = "left";
1012
+ uint down, up; Flags(button, out down, out up);
638
1013
  int count = Math.Max(1, Math.Min(3, Args.Int(r, "count", 1)));
639
1014
  var mods = Args.Ints(r, "modifiers");
1015
+ string coordLabel = Args.Has(r, "labelX") && Args.Has(r, "labelY")
1016
+ ? Args.Int(r, "labelX", x) + ", " + Args.Int(r, "labelY", y)
1017
+ : x + ", " + y;
1018
+ bool showTarget = Overlay.ShowClickTarget;
1019
+ if (showTarget)
1020
+ {
1021
+ string preVerb = count >= 3 ? "三击" : count == 2 ? "双击" : button == "right" ? "右键" : button == "middle" ? "中键" : "点击";
1022
+ Overlay.Mark(x, y, preVerb + " " + coordLabel, Color.FromArgb(217, 119, 87), 2000, false, false);
1023
+ Thread.Sleep(160);
1024
+ }
1025
+ else if (moved)
1026
+ {
1027
+ Thread.Sleep(30);
1028
+ }
640
1029
  Modifiers(mods, false);
641
1030
  try
642
1031
  {
@@ -649,7 +1038,18 @@ namespace DshComputerUse
649
1038
  }
650
1039
  }
651
1040
  finally { Modifiers(mods, true); }
652
- return null;
1041
+ if (showTarget)
1042
+ {
1043
+ Overlay.MarkResult(x, y, button, count, coordLabel);
1044
+ }
1045
+ int repeat = NoteClick(x, y);
1046
+ var result = new Dictionary<string, object>();
1047
+ result["x"] = x;
1048
+ result["y"] = y;
1049
+ result["button"] = button;
1050
+ result["count"] = count;
1051
+ result["repeat"] = repeat;
1052
+ return result;
653
1053
  }
654
1054
 
655
1055
  public static object Button(Dictionary<string, object> r)
@@ -665,7 +1065,9 @@ namespace DshComputerUse
665
1065
  int x1 = Args.Int(r, "x1", 0), y1 = Args.Int(r, "y1", 0), x2 = Args.Int(r, "x2", 0), y2 = Args.Int(r, "y2", 0);
666
1066
  uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
667
1067
  Overlay.Dodge(x1, y1); Overlay.Dodge(x2, y2);
668
- Move(x1, y1); Thread.Sleep(40);
1068
+ Move(x1, y1);
1069
+ if (Overlay.ShowClickTarget) Overlay.MarkPointer(x1, y1, "拖动", 1200);
1070
+ Thread.Sleep(40);
669
1071
  Send(new List<Native.INPUT> { Mouse(down, 0) });
670
1072
  try
671
1073
  {
@@ -679,12 +1081,17 @@ namespace DshComputerUse
679
1081
  Thread.Sleep(60);
680
1082
  }
681
1083
  finally { Send(new List<Native.INPUT> { Mouse(up, 0) }); }
1084
+ if (Overlay.ShowClickTarget) Overlay.MarkPointer(x2, y2, "已拖动", 1200);
682
1085
  return null;
683
1086
  }
684
1087
 
685
1088
  public static object Scroll(Dictionary<string, object> r)
686
1089
  {
687
- if (Args.Has(r, "x")) { int x = Args.Int(r, "x", 0), y = Args.Int(r, "y", 0); Overlay.Dodge(x, y); Move(x, y); Thread.Sleep(30); }
1090
+ int sx = 0, sy = 0;
1091
+ bool hasPos = Args.Has(r, "x");
1092
+ if (hasPos) { sx = Args.Int(r, "x", 0); sy = Args.Int(r, "y", 0); Overlay.Dodge(sx, sy); Move(sx, sy); Thread.Sleep(30); }
1093
+ else { Native.POINT p; if (Native.GetCursorPos(out p)) { sx = p.X; sy = p.Y; } }
1094
+ if (Overlay.ShowClickTarget) Overlay.MarkPointer(sx, sy, "滚动", 900);
688
1095
  int dx = Args.Int(r, "dx", 0), dy = Args.Int(r, "dy", 0);
689
1096
  var mods = Args.Ints(r, "modifiers");
690
1097
  Modifiers(mods, false);
@@ -2479,6 +2886,11 @@ namespace DshComputerUse
2479
2886
  {
2480
2887
  Native.SetWindowPos(Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010 | 0x0200); // NOSIZE|NOMOVE|NOACTIVATE|NOOWNERZORDER
2481
2888
  }
2889
+
2890
+ public void SetCapturable(bool capturable)
2891
+ {
2892
+ try { Native.SetWindowDisplayAffinity(Handle, capturable ? 0u : 0x11u); } catch (Exception) { }
2893
+ }
2482
2894
  }
2483
2895
 
2484
2896
  /** The progress card's instruction box: a small focusable window laid over the card's field. */
@@ -2553,6 +2965,10 @@ namespace DshComputerUse
2553
2965
  static Native.LowLevelKeyboardProc hookProc;
2554
2966
  static volatile bool visible;
2555
2967
  static volatile bool paused;
2968
+ static volatile bool clickTargetEnabled = true;
2969
+ static LayeredForm markForm;
2970
+ static DateTime markExpiresAt = DateTime.MinValue;
2971
+ static bool markActive;
2556
2972
  static int lastTyping = int.MinValue / 2;
2557
2973
  static int lastEmit;
2558
2974
  static readonly object RectLock = new object();
@@ -2636,6 +3052,7 @@ namespace DshComputerUse
2636
3052
  catch (Exception) { icon = null; }
2637
3053
  }
2638
3054
  petAlpha = (byte)Math.Max(90, Math.Min(255, Args.Int(r, "petOpacity", 90) * 255 / 100));
3055
+ clickTargetEnabled = Args.Bool(r, "glow", true);
2639
3056
  if (visible && !petFinished) { RenderPill(); return; }
2640
3057
  if (visible) HideCore(); // the previous run's "done" card is still up
2641
3058
  petMode = Args.Bool(r, "pet", false);
@@ -2728,6 +3145,7 @@ namespace DshComputerUse
2728
3145
  Ui(delegate
2729
3146
  {
2730
3147
  if (!visible || !petMode) { HideCore(); return; }
3148
+ HideMark();
2731
3149
  CloseInput(false);
2732
3150
  foreach (var g in glows) g.Close();
2733
3151
  glows.Clear();
@@ -2755,6 +3173,7 @@ namespace DshComputerUse
2755
3173
  static void HideCore()
2756
3174
  {
2757
3175
  {
3176
+ HideMark();
2758
3177
  CloseInput(false);
2759
3178
  petFinished = false;
2760
3179
  visible = false;
@@ -2777,6 +3196,215 @@ namespace DshComputerUse
2777
3196
  try { Hide(); Ui(delegate { Application.ExitThread(); }); } catch (Exception) { }
2778
3197
  }
2779
3198
 
3199
+ public static bool ShowClickTarget { get { return visible && clickTargetEnabled; } }
3200
+
3201
+ static void MonitorAt(int x, int y, out float scale, out Rectangle bounds)
3202
+ {
3203
+ scale = 1f;
3204
+ bounds = Rectangle.Empty;
3205
+ bool found = false;
3206
+ foreach (Dictionary<string, object> d in Screen2.Displays())
3207
+ {
3208
+ var r = new Rectangle((int)d["x"], (int)d["y"], (int)d["width"], (int)d["height"]);
3209
+ float s = (int)d["dpi"] / 96f;
3210
+ if (r.Contains(x, y)) { scale = s; bounds = r; return; }
3211
+ if (!found || (bool)d["primary"]) { scale = s; bounds = r; found = true; }
3212
+ }
3213
+ }
3214
+
3215
+ /**
3216
+ * Collaborative Codex-style cursor badge: the corner nearest the pointer
3217
+ * tip stays tight (2px), while the other three corners are smoothly rounded.
3218
+ */
3219
+ static GraphicsPath TagShape(RectangleF r, bool flipX, bool flipY, float scale)
3220
+ {
3221
+ float tight = 2f * scale;
3222
+ float round = 7f * scale;
3223
+ float tl = (!flipX && !flipY) ? tight : round;
3224
+ float tr = (flipX && !flipY) ? tight : round;
3225
+ float br = (flipX && flipY) ? tight : round;
3226
+ float bl = (!flipX && flipY) ? tight : round;
3227
+ var p = new GraphicsPath();
3228
+ p.AddArc(r.X, r.Y, tl * 2f, tl * 2f, 180, 90);
3229
+ p.AddArc(r.Right - tr * 2f, r.Y, tr * 2f, tr * 2f, 270, 90);
3230
+ p.AddArc(r.Right - br * 2f, r.Bottom - br * 2f, br * 2f, br * 2f, 0, 90);
3231
+ p.AddArc(r.X, r.Bottom - bl * 2f, bl * 2f, bl * 2f, 90, 90);
3232
+ p.CloseFigure();
3233
+ return p;
3234
+ }
3235
+
3236
+ /**
3237
+ * Draw a sleek Codex-style collaborative AI pointer cursor whose tip sits
3238
+ * pixel-exact at (cx, cy): soft radial spotlight glow, crisp filled vector
3239
+ * arrow with white outline, attached rounded name-tag pill (auto-flipping
3240
+ * at all 4 screen edges), and a subtle click ripple ring on post-click.
3241
+ */
3242
+ static Bitmap DrawMark(string text, Color color, float scale, bool flipX, bool flipY, bool ripple, out int cx, out int cy)
3243
+ {
3244
+ float s = Math.Max(0.75f, Math.Min(3f, scale));
3245
+ float px = 1.333f * s;
3246
+ float glowR = (ripple ? 20f : 16f) * s;
3247
+ float pad = 4f * s;
3248
+ using (var font = new Font("Microsoft YaHei UI", 8f * px, FontStyle.Bold, GraphicsUnit.Pixel))
3249
+ using (var probe = new Bitmap(1, 1))
3250
+ using (var mg = Graphics.FromImage(probe))
3251
+ using (var fmt = new StringFormat(StringFormat.GenericTypographic))
3252
+ {
3253
+ mg.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
3254
+ fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap;
3255
+ SizeF textSize = string.IsNullOrEmpty(text) ? SizeF.Empty : mg.MeasureString(text, font, 10000, fmt);
3256
+ float pillPadX = 7f * s;
3257
+ float pillW = textSize.Width > 0 ? (float)Math.Ceiling(textSize.Width + 2f * pillPadX) : 0f;
3258
+ float pillH = textSize.Height > 0 ? Math.Max(19f * s, (float)Math.Ceiling(textSize.Height + 5f * s)) : 0f;
3259
+
3260
+ // Offsets relative to the pointer tip at (0, 0).
3261
+ float tagX = flipX ? (-10f * s - pillW) : (13f * s);
3262
+ float tagY = flipY ? (-10f * s - pillH) : (15f * s);
3263
+
3264
+ float minX = Math.Min(-glowR, pillW > 0 ? tagX : 0f) - pad;
3265
+ float maxX = Math.Max(glowR, Math.Max(14f * s, pillW > 0 ? tagX + pillW : 0f)) + pad;
3266
+ float minY = Math.Min(-glowR, pillH > 0 ? tagY : 0f) - pad;
3267
+ float maxY = Math.Max(glowR, Math.Max(22f * s, pillH > 0 ? tagY + pillH : 0f)) + pad;
3268
+
3269
+ int W = Math.Max(1, (int)Math.Ceiling(maxX - minX));
3270
+ int H = Math.Max(1, (int)Math.Ceiling(maxY - minY));
3271
+ cx = (int)Math.Round(-minX);
3272
+ cy = (int)Math.Round(-minY);
3273
+
3274
+ var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb);
3275
+ using (var g = Graphics.FromImage(bmp))
3276
+ {
3277
+ g.Clear(Color.Transparent);
3278
+ g.SmoothingMode = SmoothingMode.AntiAlias;
3279
+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
3280
+
3281
+ // 1. Soft radial spotlight centered right under the tip (cx, cy).
3282
+ using (var spot = new GraphicsPath())
3283
+ {
3284
+ spot.AddEllipse(cx - glowR, cy - glowR, glowR * 2f, glowR * 2f);
3285
+ using (var glow = new PathGradientBrush(spot))
3286
+ {
3287
+ glow.CenterPoint = new PointF(cx, cy);
3288
+ glow.CenterColor = Color.FromArgb(ripple ? 130 : 95, color);
3289
+ glow.SurroundColors = new Color[] { Color.FromArgb(0, color) };
3290
+ g.FillPath(glow, spot);
3291
+ }
3292
+ }
3293
+
3294
+ // 2. Post-click delicate ripple ring so exact placement reads cleanly in screenshots.
3295
+ if (ripple)
3296
+ {
3297
+ float rr = 11.5f * s;
3298
+ using (var ringHalo = new Pen(Color.FromArgb(140, 255, 255, 255), Math.Max(2.5f, 3.2f * s)))
3299
+ g.DrawEllipse(ringHalo, cx - rr, cy - rr, rr * 2f, rr * 2f);
3300
+ using (var ring = new Pen(Color.FromArgb(230, color), Math.Max(1.6f, 2f * s)))
3301
+ g.DrawEllipse(ring, cx - rr, cy - rr, rr * 2f, rr * 2f);
3302
+ }
3303
+
3304
+ // 3. Attached collaborative name-tag pill.
3305
+ if (pillW > 0 && pillH > 0)
3306
+ {
3307
+ float bx = cx + tagX;
3308
+ float by = cy + tagY;
3309
+ var shadowRect = new RectangleF(bx, by + 1.5f * s, pillW, pillH);
3310
+ using (var sp = TagShape(shadowRect, flipX, flipY, s))
3311
+ using (var sb = new SolidBrush(Color.FromArgb(62, 0, 0, 0)))
3312
+ g.FillPath(sb, sp);
3313
+
3314
+ var pillRect = new RectangleF(bx, by, pillW, pillH);
3315
+ using (var pp = TagShape(pillRect, flipX, flipY, s))
3316
+ {
3317
+ using (var fill = new SolidBrush(Color.FromArgb(245, color))) g.FillPath(fill, pp);
3318
+ using (var border = new Pen(Color.FromArgb(235, 255, 255, 255), Math.Max(1f, 1.25f * s))) g.DrawPath(border, pp);
3319
+ }
3320
+ using (var fg = new SolidBrush(Color.White))
3321
+ g.DrawString(text, font, fg, bx + (pillW - textSize.Width) / 2f, by + (pillH - textSize.Height) / 2f - 0.5f * s, fmt);
3322
+ }
3323
+
3324
+ // 4. Crisp vector cursor arrow whose tip sits pixel-exact at (cx, cy).
3325
+ var arrow = new PointF[]
3326
+ {
3327
+ new PointF(cx, cy),
3328
+ new PointF(cx, cy + 16.5f * s),
3329
+ new PointF(cx + 4.3f * s, cy + 12.8f * s),
3330
+ new PointF(cx + 7.4f * s, cy + 19.2f * s),
3331
+ new PointF(cx + 10.0f * s, cy + 17.9f * s),
3332
+ new PointF(cx + 6.9f * s, cy + 11.7f * s),
3333
+ new PointF(cx + 12.4f * s, cy + 11.4f * s),
3334
+ };
3335
+ var arrowShadow = new PointF[arrow.Length];
3336
+ for (int i = 0; i < arrow.Length; i++)
3337
+ arrowShadow[i] = new PointF(arrow[i].X + 0.8f * s, arrow[i].Y + 1.5f * s);
3338
+ using (var sb = new SolidBrush(Color.FromArgb(72, 0, 0, 0))) g.FillPolygon(sb, arrowShadow);
3339
+ using (var fill = new SolidBrush(Color.FromArgb(255, color))) g.FillPolygon(fill, arrow);
3340
+ using (var outline = new Pen(Color.FromArgb(248, 255, 255, 255), Math.Max(1.2f, 1.5f * s)))
3341
+ {
3342
+ outline.LineJoin = LineJoin.Round;
3343
+ g.DrawPolygon(outline, arrow);
3344
+ }
3345
+ }
3346
+ return bmp;
3347
+ }
3348
+ }
3349
+
3350
+ public static void MarkPointer(int x, int y, string text, int holdMs)
3351
+ {
3352
+ Mark(x, y, text, Accent, holdMs, false, false);
3353
+ }
3354
+
3355
+ public static void Mark(int x, int y, string text, Color color, int holdMs, bool capturable, bool ripple)
3356
+ {
3357
+ Ensure();
3358
+ Ui(delegate
3359
+ {
3360
+ if (markForm == null)
3361
+ {
3362
+ markForm = new LayeredForm(true);
3363
+ markForm.Show();
3364
+ }
3365
+ markForm.SetCapturable(capturable || !ExcludeFromCapture);
3366
+ float scale; Rectangle mon;
3367
+ MonitorAt(x, y, out scale, out mon);
3368
+ float s = Math.Max(0.75f, Math.Min(3f, scale));
3369
+ int estW = (int)((Math.Max(6, (text ?? "").Length) * 11 + 36) * s);
3370
+ bool flipX = !mon.IsEmpty && x + estW > mon.Right;
3371
+ bool flipY = !mon.IsEmpty && y + (int)(52 * s) > mon.Bottom;
3372
+ int cx, cy;
3373
+ using (var bmp = DrawMark(text, color, scale, flipX, flipY, ripple, out cx, out cy))
3374
+ {
3375
+ markForm.SetBitmap(bmp, new Rectangle(x - cx, y - cy, bmp.Width, bmp.Height), 255);
3376
+ }
3377
+ markForm.KeepOnTop();
3378
+ markActive = true;
3379
+ markExpiresAt = holdMs > 0 ? DateTime.UtcNow.AddMilliseconds(holdMs) : DateTime.MaxValue;
3380
+ if (!timer.Enabled) timer.Start();
3381
+ });
3382
+ }
3383
+
3384
+ public static void MarkResult(int x, int y, string button, int count, string coordLabel)
3385
+ {
3386
+ Color color;
3387
+ string verb;
3388
+ if (count >= 3) { color = Color.FromArgb(249, 115, 22); verb = "已三击"; }
3389
+ else if (count == 2) { color = Color.FromArgb(139, 92, 246); verb = "已双击"; }
3390
+ else if (button == "right") { color = Color.FromArgb(16, 185, 129); verb = "已右键"; }
3391
+ else if (button == "middle") { color = Color.FromArgb(6, 182, 212); verb = "已中键"; }
3392
+ else { color = Color.FromArgb(59, 130, 246); verb = "已单击"; }
3393
+ Mark(x, y, verb + " " + coordLabel, color, 4000, true, true);
3394
+ }
3395
+
3396
+ static void HideMark()
3397
+ {
3398
+ markActive = false;
3399
+ markExpiresAt = DateTime.MinValue;
3400
+ if (markForm != null)
3401
+ {
3402
+ markForm.SetCapturable(false);
3403
+ markForm.Close();
3404
+ markForm = null;
3405
+ }
3406
+ }
3407
+
2780
3408
  /// Move the status pill out of the way when an injected pointer action
2781
3409
  /// targets it: the pill is clickable for the user but invisible to the model.
2782
3410
  public static void Dodge(int x, int y)
@@ -2855,7 +3483,12 @@ namespace DshComputerUse
2855
3483
 
2856
3484
  static void Tick()
2857
3485
  {
2858
- if (!visible) return;
3486
+ if (markActive && DateTime.UtcNow >= markExpiresAt) HideMark();
3487
+ if (!visible)
3488
+ {
3489
+ if (!markActive) timer.Stop();
3490
+ return;
3491
+ }
2859
3492
  if (petFinished)
2860
3493
  {
2861
3494
  Native.POINT p; Native.GetCursorPos(out p);
@@ -2875,6 +3508,7 @@ namespace DshComputerUse
2875
3508
  foreach (var g in glows) g.KeepOnTop();
2876
3509
  if (pill != null) pill.KeepOnTop();
2877
3510
  if (pet != null) pet.KeepOnTop();
3511
+ if (markForm != null) markForm.KeepOnTop();
2878
3512
  if (input != null) Native.SetWindowPos(input.Handle, new IntPtr(-1), 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0010);
2879
3513
  }
2880
3514
  }