@copylee/dsh-computer-use 0.9.0 → 0.11.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,12 +21,14 @@ 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;
27
28
  using System.Web.Script.Serialization;
28
29
  using System.Windows.Automation;
29
30
  using System.Windows.Forms;
31
+ using Microsoft.Win32;
30
32
 
31
33
  namespace DshComputerUse
32
34
  {
@@ -121,6 +123,9 @@ namespace DshComputerUse
121
123
  [DllImport("user32.dll")] public static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint affinity);
122
124
  [DllImport("user32.dll")] public static extern bool ReleaseCapture();
123
125
  [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hwnd, uint msg, IntPtr w, IntPtr l);
126
+ [StructLayout(LayoutKind.Sequential)]
127
+ public struct GUITHREADINFO { public int cbSize; public int flags; public IntPtr hwndActive; public IntPtr hwndFocus; public IntPtr hwndCapture; public IntPtr hwndMenuOwner; public IntPtr hwndMoveSize; public IntPtr hwndCaret; public RECT rcCaret; }
128
+ [DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint idThread, ref GUITHREADINFO lpgui);
124
129
 
125
130
  public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
126
131
  [DllImport("user32.dll", SetLastError = true)] public static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc fn, IntPtr hMod, uint threadId);
@@ -278,7 +283,15 @@ namespace DshComputerUse
278
283
  case "screenshot": return Screen2.Capture(r);
279
284
  case "settle": return Screen2.Settle(r);
280
285
  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;
286
+ case "move":
287
+ using (new PassThrough())
288
+ {
289
+ int mx = Args.Int(r, "x", 0), my = Args.Int(r, "y", 0);
290
+ Overlay.Dodge(mx, my);
291
+ Input.Move(mx, my);
292
+ if (Overlay.ShowClickTarget) Overlay.MarkPointer(mx, my, "DSH", 900);
293
+ }
294
+ return null;
282
295
  case "click":
283
296
  Native.POINT clickPoint;
284
297
  if (Args.Has(r, "x")) clickPoint = new Native.POINT(Args.Int(r, "x", 0), Args.Int(r, "y", 0));
@@ -319,6 +332,10 @@ namespace DshComputerUse
319
332
  case "clipboard_restore": { var d = new Dictionary<string, object>(); d["restored"] = Clip.RestoreAgent(); return d; }
320
333
  case "ui": return Uia.Elements(r);
321
334
  case "text": return Uia.Text(r);
335
+ case "ocr": return Ocr.Read(r);
336
+ case "marks": return Uia.Marks(r);
337
+ case "password_focus": return Uia.PasswordFocus();
338
+ case "ui_point_click": return Uia.ClickAtPoint(r);
322
339
  case "overlay_show": Overlay.ExcludeFromCapture = Args.Bool(r, "excludeFromCapture", true); Overlay.Show(r); return null;
323
340
  case "overlay_pause": Overlay.SetPaused(Args.Bool(r, "paused", false)); return null;
324
341
  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));
@@ -454,14 +471,11 @@ namespace DshComputerUse
454
471
 
455
472
  static ImageCodecInfo jpegCodec;
456
473
 
457
- public static Dictionary<string, object> Capture(Dictionary<string, object> r)
474
+ public static Bitmap Grab(int x, int y, int w, int h, out string via)
458
475
  {
459
- 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);
460
- int ow = Args.Int(r, "outWidth", w), oh = Args.Int(r, "outHeight", h);
461
- int quality = Args.Int(r, "quality", 80);
462
- if (w <= 0 || h <= 0 || ow <= 0 || oh <= 0) throw new Exception("invalid capture size");
463
- string via = "blt";
464
- using (var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb))
476
+ via = "blt";
477
+ var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb);
478
+ try
465
479
  {
466
480
  using (var g = Graphics.FromImage(bmp))
467
481
  {
@@ -472,7 +486,6 @@ namespace DshComputerUse
472
486
  // the card (no flicker). Fallback: hide the card for one BitBlt.
473
487
  bool done = false;
474
488
  var area = new Rectangle(x, y, w, h);
475
- via = "blt";
476
489
  if (CardLayer.Covers(area))
477
490
  {
478
491
  g.ReleaseHdc(dst);
@@ -493,6 +506,24 @@ namespace DshComputerUse
493
506
  }
494
507
  Native.ReleaseDC(IntPtr.Zero, src);
495
508
  }
509
+ return bmp;
510
+ }
511
+ catch
512
+ {
513
+ bmp.Dispose();
514
+ throw;
515
+ }
516
+ }
517
+
518
+ public static Dictionary<string, object> Capture(Dictionary<string, object> r)
519
+ {
520
+ 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);
521
+ int ow = Args.Int(r, "outWidth", w), oh = Args.Int(r, "outHeight", h);
522
+ int quality = Args.Int(r, "quality", 80);
523
+ if (w <= 0 || h <= 0 || ow <= 0 || oh <= 0) throw new Exception("invalid capture size");
524
+ string via;
525
+ using (var bmp = Grab(x, y, w, h, out via))
526
+ {
496
527
  // compare: report "unchanged" instead of an identical image; mark: remember for next time.
497
528
  bool compare = Args.Bool(r, "compare", false), mark = Args.Bool(r, "mark", false) || compare;
498
529
  if (mark)
@@ -555,6 +586,298 @@ namespace DshComputerUse
555
586
  }
556
587
  }
557
588
 
589
+ /**
590
+ * Built-in Windows 10/11 OCR via WinRT reflection (Windows.Media.Ocr).
591
+ * Zero extra compile references or native DLLs: falls back cleanly if the
592
+ * host OS has no WinRT OCR language pack installed.
593
+ */
594
+ internal static class Ocr
595
+ {
596
+ static Type tEngine, tDecoder, tStream, tWriter, tAsyncInfo;
597
+ static object cachedEngine;
598
+ static string cachedLanguage = "";
599
+ static int cachedMaxDim = 2600;
600
+ static bool initTried;
601
+
602
+ static void EnsureTypes()
603
+ {
604
+ if (initTried) return;
605
+ initTried = true;
606
+ tEngine = Type.GetType("Windows.Media.Ocr.OcrEngine, Windows.Media, ContentType=WindowsRuntime", false);
607
+ tDecoder = Type.GetType("Windows.Graphics.Imaging.BitmapDecoder, Windows.Graphics, ContentType=WindowsRuntime", false);
608
+ tStream = Type.GetType("Windows.Storage.Streams.InMemoryRandomAccessStream, Windows.Storage, ContentType=WindowsRuntime", false);
609
+ tWriter = Type.GetType("Windows.Storage.Streams.DataWriter, Windows.Storage, ContentType=WindowsRuntime", false);
610
+ tAsyncInfo = Type.GetType("Windows.Foundation.IAsyncInfo, Windows.Foundation, ContentType=WindowsRuntime", false);
611
+ if (tEngine == null || tDecoder == null || tStream == null || tWriter == null || tAsyncInfo == null) return;
612
+ try
613
+ {
614
+ var create = tEngine.GetMethod("TryCreateFromUserProfileLanguages", BindingFlags.Public | BindingFlags.Static);
615
+ if (create != null) cachedEngine = create.Invoke(null, null);
616
+ if (cachedEngine != null)
617
+ {
618
+ object lang = GetProp(cachedEngine, "RecognizerLanguage");
619
+ if (lang != null) cachedLanguage = Convert.ToString(GetProp(lang, "LanguageTag")) ?? "";
620
+ var maxProp = tEngine.GetProperty("MaxImageDimension", BindingFlags.Public | BindingFlags.Static);
621
+ if (maxProp != null)
622
+ {
623
+ int dim = Convert.ToInt32(maxProp.GetValue(null, null));
624
+ if (dim >= 512) cachedMaxDim = dim;
625
+ }
626
+ }
627
+ }
628
+ catch (Exception) { cachedEngine = null; }
629
+ }
630
+
631
+ static MethodInfo FindMethod(Type t, string name, int argCount)
632
+ {
633
+ if (t == null) return null;
634
+ foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Instance))
635
+ if (m.Name == name && m.GetParameters().Length == argCount) return m;
636
+ foreach (var iface in t.GetInterfaces())
637
+ foreach (var m in iface.GetMethods(BindingFlags.Public | BindingFlags.Instance))
638
+ if (m.Name == name && m.GetParameters().Length == argCount) return m;
639
+ return null;
640
+ }
641
+
642
+ static object Invoke(object target, string name, 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
+ return m.Invoke(target, args);
647
+ }
648
+
649
+ static object InvokeAsync(object target, string name, int timeoutMs, params object[] args)
650
+ {
651
+ var m = FindMethod(target.GetType(), name, args == null ? 0 : args.Length);
652
+ if (m == null) throw new Exception("WinRT method not found: " + name);
653
+ object op = m.Invoke(target, args);
654
+ return AwaitWinRt(op, m.ReturnType, timeoutMs);
655
+ }
656
+
657
+ static object GetProp(object target, string name)
658
+ {
659
+ var t = target.GetType();
660
+ var p = t.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
661
+ if (p != null) return p.GetValue(target, null);
662
+ foreach (var iface in t.GetInterfaces())
663
+ {
664
+ p = iface.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
665
+ if (p != null) return p.GetValue(target, null);
666
+ }
667
+ return null;
668
+ }
669
+
670
+ static object AwaitWinRt(object asyncOp, Type asyncType, int timeoutMs)
671
+ {
672
+ if (asyncOp == null) return null;
673
+ var statusProp = tAsyncInfo.GetProperty("Status");
674
+ var errProp = tAsyncInfo.GetProperty("ErrorCode");
675
+ var watch = Stopwatch.StartNew();
676
+ while (true)
677
+ {
678
+ int status = Convert.ToInt32(statusProp.GetValue(asyncOp, null));
679
+ if (status == 1) // Completed
680
+ {
681
+ var getResults = FindMethod(asyncType, "GetResults", 0) ?? FindMethod(asyncOp.GetType(), "GetResults", 0);
682
+ return getResults != null ? getResults.Invoke(asyncOp, null) : null;
683
+ }
684
+ if (status == 2) throw new Exception("Windows OCR operation was cancelled");
685
+ if (status == 3)
686
+ {
687
+ object err = errProp != null ? errProp.GetValue(asyncOp, null) : null;
688
+ throw new Exception("Windows OCR failed: " + (err != null ? err.ToString() : "unknown error"));
689
+ }
690
+ if (watch.ElapsedMilliseconds >= timeoutMs)
691
+ {
692
+ try { var cancel = tAsyncInfo.GetMethod("Cancel"); if (cancel != null) cancel.Invoke(asyncOp, null); } catch (Exception) { }
693
+ throw new Exception("Windows OCR timed out");
694
+ }
695
+ Thread.Sleep(5);
696
+ }
697
+ }
698
+
699
+ static bool IsCjk(char c)
700
+ {
701
+ return (c >= '\u4E00' && c <= '\u9FFF') || (c >= '\u3400' && c <= '\u4DBF')
702
+ || (c >= '\u3000' && c <= '\u303F') || (c >= '\uFF00' && c <= '\uFFEF');
703
+ }
704
+
705
+ /** Collapse spaces Windows.Media.Ocr inserts between adjacent CJK characters. */
706
+ static string CleanLineText(string s)
707
+ {
708
+ if (string.IsNullOrEmpty(s)) return "";
709
+ var sb = new StringBuilder(s.Length);
710
+ for (int i = 0; i < s.Length; i++)
711
+ {
712
+ char c = s[i];
713
+ if (c == ' ' && sb.Length > 0 && i + 1 < s.Length && IsCjk(sb[sb.Length - 1]) && IsCjk(s[i + 1]))
714
+ continue;
715
+ sb.Append(c);
716
+ }
717
+ return sb.ToString();
718
+ }
719
+
720
+ static void TryDispose(object obj)
721
+ {
722
+ var d = obj as IDisposable;
723
+ if (d != null) { try { d.Dispose(); } catch (Exception) { } }
724
+ }
725
+
726
+ public static Dictionary<string, object> Read(Dictionary<string, object> r)
727
+ {
728
+ EnsureTypes();
729
+ if (cachedEngine == null)
730
+ throw new Exception("Windows OCR is not available on this system (no OCR language pack found).");
731
+
732
+ int x, y, w, h;
733
+ var meta = new Dictionary<string, object>();
734
+ if (Args.Has(r, "width") && Args.Has(r, "height"))
735
+ {
736
+ x = Args.Int(r, "x", 0);
737
+ y = Args.Int(r, "y", 0);
738
+ w = Args.Int(r, "width", 0);
739
+ h = Args.Int(r, "height", 0);
740
+ }
741
+ else
742
+ {
743
+ IntPtr hwnd = Args.Has(r, "hwnd") ? new IntPtr(Convert.ToInt64(r["hwnd"])) : Native.GetForegroundWindow();
744
+ var desc = Windows.Describe(hwnd);
745
+ if (desc.Count == 0) throw new Exception("No target window found for OCR.");
746
+ foreach (var kv in desc) meta[kv.Key] = kv.Value;
747
+ var vs = SystemInformation.VirtualScreen;
748
+ int rx = Convert.ToInt32(desc["x"]), ry = Convert.ToInt32(desc["y"]);
749
+ int rw = Convert.ToInt32(desc["width"]), rh = Convert.ToInt32(desc["height"]);
750
+ int left = Math.Max(vs.Left, rx);
751
+ int top = Math.Max(vs.Top, ry);
752
+ int right = Math.Min(vs.Right, rx + rw);
753
+ int bottom = Math.Min(vs.Bottom, ry + rh);
754
+ x = left; y = top; w = right - left; h = bottom - top;
755
+ }
756
+ if (w <= 2 || h <= 2) throw new Exception("Target area is too small for OCR.");
757
+
758
+ string via;
759
+ using (var rawBmp = Screen2.Grab(x, y, w, h, out via))
760
+ {
761
+ double scale = 1.0;
762
+ int maxSide = Math.Max(w, h);
763
+ if (maxSide > cachedMaxDim) scale = (double)cachedMaxDim / maxSide;
764
+ Bitmap work = rawBmp;
765
+ Bitmap resized = null;
766
+ byte[] pngBytes;
767
+ try
768
+ {
769
+ if (scale < 1.0)
770
+ {
771
+ int nw = Math.Max(1, (int)Math.Round(w * scale));
772
+ int nh = Math.Max(1, (int)Math.Round(h * scale));
773
+ resized = new Bitmap(nw, nh, PixelFormat.Format24bppRgb);
774
+ using (var g = Graphics.FromImage(resized))
775
+ {
776
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
777
+ g.DrawImage(rawBmp, 0, 0, nw, nh);
778
+ }
779
+ work = resized;
780
+ }
781
+ using (var ms = new MemoryStream())
782
+ {
783
+ work.Save(ms, ImageFormat.Png);
784
+ pngBytes = ms.ToArray();
785
+ }
786
+ }
787
+ finally { if (resized != null) resized.Dispose(); }
788
+
789
+ object ras = null, writer = null, softwareBitmap = null;
790
+ try
791
+ {
792
+ ras = Activator.CreateInstance(tStream);
793
+ writer = Activator.CreateInstance(tWriter, new object[] { ras });
794
+ Invoke(writer, "WriteBytes", new object[] { pngBytes });
795
+ InvokeAsync(writer, "StoreAsync", 8000);
796
+ InvokeAsync(writer, "FlushAsync", 8000);
797
+ Invoke(writer, "DetachStream");
798
+ TryDispose(writer); writer = null;
799
+ Invoke(ras, "Seek", new object[] { (ulong)0 });
800
+
801
+ MethodInfo createDecoder = null;
802
+ foreach (var m in tDecoder.GetMethods(BindingFlags.Public | BindingFlags.Static))
803
+ if (m.Name == "CreateAsync" && m.GetParameters().Length == 1) { createDecoder = m; break; }
804
+ if (createDecoder == null) throw new Exception("BitmapDecoder.CreateAsync not found");
805
+ object decoder = AwaitWinRt(createDecoder.Invoke(null, new object[] { ras }), createDecoder.ReturnType, 8000);
806
+ if (decoder == null) throw new Exception("BitmapDecoder returned null");
807
+ softwareBitmap = InvokeAsync(decoder, "GetSoftwareBitmapAsync", 8000);
808
+ if (softwareBitmap == null) throw new Exception("GetSoftwareBitmapAsync returned null");
809
+ object ocrResult = InvokeAsync(cachedEngine, "RecognizeAsync", 10000, new object[] { softwareBitmap });
810
+ if (ocrResult == null) throw new Exception("OcrEngine.RecognizeAsync returned null");
811
+
812
+ var linesOut = new List<object>();
813
+ var allLines = new List<string>();
814
+ double invScale = 1.0 / scale;
815
+ var rawLines = GetProp(ocrResult, "Lines") as IEnumerable;
816
+ if (rawLines != null)
817
+ {
818
+ foreach (var line in rawLines)
819
+ {
820
+ string lineText = CleanLineText(Convert.ToString(GetProp(line, "Text")) ?? "");
821
+ if (lineText.Trim().Length == 0) continue;
822
+ var wordsOut = new List<object>();
823
+ double minX = double.MaxValue, minY = double.MaxValue, maxX = double.MinValue, maxY = double.MinValue;
824
+ var rawWords = GetProp(line, "Words") as IEnumerable;
825
+ if (rawWords != null)
826
+ {
827
+ foreach (var word in rawWords)
828
+ {
829
+ string wt = Convert.ToString(GetProp(word, "Text")) ?? "";
830
+ object rect = GetProp(word, "BoundingRect");
831
+ if (rect == null) continue;
832
+ double wx = Convert.ToDouble(GetProp(rect, "X")) * invScale;
833
+ double wy = Convert.ToDouble(GetProp(rect, "Y")) * invScale;
834
+ double ww = Convert.ToDouble(GetProp(rect, "Width")) * invScale;
835
+ double wh = Convert.ToDouble(GetProp(rect, "Height")) * invScale;
836
+ if (wx < minX) minX = wx;
837
+ if (wy < minY) minY = wy;
838
+ if (wx + ww > maxX) maxX = wx + ww;
839
+ if (wy + wh > maxY) maxY = wy + wh;
840
+ var wd = new Dictionary<string, object>();
841
+ wd["text"] = wt;
842
+ wd["x"] = x + (int)Math.Round(wx);
843
+ wd["y"] = y + (int)Math.Round(wy);
844
+ wd["width"] = Math.Max(1, (int)Math.Round(ww));
845
+ wd["height"] = Math.Max(1, (int)Math.Round(wh));
846
+ wordsOut.Add(wd);
847
+ }
848
+ }
849
+ if (minX == double.MaxValue) continue;
850
+ var ld = new Dictionary<string, object>();
851
+ ld["text"] = lineText;
852
+ ld["x"] = x + (int)Math.Round(minX);
853
+ ld["y"] = y + (int)Math.Round(minY);
854
+ ld["width"] = Math.Max(1, (int)Math.Round(maxX - minX));
855
+ ld["height"] = Math.Max(1, (int)Math.Round(maxY - minY));
856
+ ld["words"] = wordsOut;
857
+ linesOut.Add(ld);
858
+ allLines.Add(lineText);
859
+ }
860
+ }
861
+
862
+ meta["language"] = cachedLanguage;
863
+ meta["x"] = x;
864
+ meta["y"] = y;
865
+ meta["width"] = w;
866
+ meta["height"] = h;
867
+ meta["text"] = string.Join("\n", allLines.ToArray());
868
+ meta["lines"] = linesOut;
869
+ return meta;
870
+ }
871
+ finally
872
+ {
873
+ TryDispose(softwareBitmap);
874
+ TryDispose(writer);
875
+ TryDispose(ras);
876
+ }
877
+ }
878
+ }
879
+ }
880
+
558
881
  internal static class Input
559
882
  {
560
883
  static readonly int InputSize = Marshal.SizeOf(typeof(Native.INPUT));
@@ -677,19 +1000,19 @@ namespace DshComputerUse
677
1000
  public static object Click(Dictionary<string, object> r)
678
1001
  {
679
1002
  int x, y;
1003
+ Native.POINT savedCursor;
1004
+ bool hadSavedCursor = Native.GetCursorPos(out savedCursor);
1005
+ bool restorePointer = Args.Bool(r, "restorePointer", false);
680
1006
  bool moved = Args.Has(r, "x");
681
1007
  if (moved)
682
1008
  {
683
1009
  x = Args.Int(r, "x", 0);
684
1010
  y = Args.Int(r, "y", 0);
685
- Overlay.Dodge(x, y);
686
- Move(x, y);
687
1011
  }
688
1012
  else
689
1013
  {
690
- Native.POINT pos;
691
- if (!Native.GetCursorPos(out pos)) { x = 0; y = 0; }
692
- else { x = pos.X; y = pos.Y; }
1014
+ if (!hadSavedCursor) { x = 0; y = 0; }
1015
+ else { x = savedCursor.X; y = savedCursor.Y; }
693
1016
  }
694
1017
  string button = Args.Str(r, "button", "left");
695
1018
  if (button != "right" && button != "middle") button = "left";
@@ -703,8 +1026,16 @@ namespace DshComputerUse
703
1026
  if (showTarget)
704
1027
  {
705
1028
  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);
1029
+ Overlay.GlideMark(x, y, preVerb + " " + coordLabel, Color.FromArgb(217, 119, 87), 2000, false, false);
1030
+ }
1031
+ if (moved)
1032
+ {
1033
+ Overlay.Dodge(x, y);
1034
+ Move(x, y);
1035
+ }
1036
+ if (showTarget)
1037
+ {
1038
+ Thread.Sleep(70);
708
1039
  }
709
1040
  else if (moved)
710
1041
  {
@@ -721,7 +1052,14 @@ namespace DshComputerUse
721
1052
  if (i < count - 1) Thread.Sleep(40);
722
1053
  }
723
1054
  }
724
- finally { Modifiers(mods, true); }
1055
+ finally
1056
+ {
1057
+ Modifiers(mods, true);
1058
+ if (restorePointer && moved && hadSavedCursor)
1059
+ {
1060
+ try { Native.SetCursorPos(savedCursor.X, savedCursor.Y); } catch (Exception) { }
1061
+ }
1062
+ }
725
1063
  if (showTarget)
726
1064
  {
727
1065
  Overlay.MarkResult(x, y, button, count, coordLabel);
@@ -733,6 +1071,7 @@ namespace DshComputerUse
733
1071
  result["button"] = button;
734
1072
  result["count"] = count;
735
1073
  result["repeat"] = repeat;
1074
+ result["restoredPointer"] = restorePointer && moved && hadSavedCursor;
736
1075
  return result;
737
1076
  }
738
1077
 
@@ -749,7 +1088,9 @@ namespace DshComputerUse
749
1088
  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);
750
1089
  uint down, up; Flags(Args.Str(r, "button", "left"), out down, out up);
751
1090
  Overlay.Dodge(x1, y1); Overlay.Dodge(x2, y2);
752
- Move(x1, y1); Thread.Sleep(40);
1091
+ Move(x1, y1);
1092
+ if (Overlay.ShowClickTarget) Overlay.MarkPointer(x1, y1, "拖动", 1200);
1093
+ Thread.Sleep(40);
753
1094
  Send(new List<Native.INPUT> { Mouse(down, 0) });
754
1095
  try
755
1096
  {
@@ -763,12 +1104,17 @@ namespace DshComputerUse
763
1104
  Thread.Sleep(60);
764
1105
  }
765
1106
  finally { Send(new List<Native.INPUT> { Mouse(up, 0) }); }
1107
+ if (Overlay.ShowClickTarget) Overlay.MarkPointer(x2, y2, "已拖动", 1200);
766
1108
  return null;
767
1109
  }
768
1110
 
769
1111
  public static object Scroll(Dictionary<string, object> r)
770
1112
  {
771
- 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); }
1113
+ int sx = 0, sy = 0;
1114
+ bool hasPos = Args.Has(r, "x");
1115
+ if (hasPos) { sx = Args.Int(r, "x", 0); sy = Args.Int(r, "y", 0); Overlay.Dodge(sx, sy); Move(sx, sy); Thread.Sleep(30); }
1116
+ else { Native.POINT p; if (Native.GetCursorPos(out p)) { sx = p.X; sy = p.Y; } }
1117
+ if (Overlay.ShowClickTarget) Overlay.MarkPointer(sx, sy, "滚动", 900);
772
1118
  int dx = Args.Int(r, "dx", 0), dy = Args.Int(r, "dy", 0);
773
1119
  var mods = Args.Ints(r, "modifiers");
774
1120
  Modifiers(mods, false);
@@ -1887,10 +2233,120 @@ namespace DshComputerUse
1887
2233
  lock (Gate) { return Load(); }
1888
2234
  }
1889
2235
 
2236
+ static void AddIfNew(List<KeyValuePair<string, string>> list, HashSet<string> seen, string name, string id)
2237
+ {
2238
+ if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(id)) return;
2239
+ string key = name.Trim().ToLowerInvariant() + "\u0000" + id.Trim().ToLowerInvariant();
2240
+ if (seen.Add(key)) list.Add(new KeyValuePair<string, string>(name.Trim(), id.Trim()));
2241
+ }
2242
+
2243
+ static string ExtractExePath(string raw)
2244
+ {
2245
+ if (string.IsNullOrEmpty(raw)) return "";
2246
+ string s = raw.Trim();
2247
+ if (s.StartsWith("\""))
2248
+ {
2249
+ int end = s.IndexOf('"', 1);
2250
+ if (end > 1) s = s.Substring(1, end - 1);
2251
+ }
2252
+ else
2253
+ {
2254
+ int comma = s.IndexOf(',');
2255
+ if (comma > 0) s = s.Substring(0, comma);
2256
+ }
2257
+ s = s.Trim();
2258
+ if (!s.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return "";
2259
+ return File.Exists(s) ? s : "";
2260
+ }
2261
+
2262
+ static void ScanStartFolder(string dir, int depth, List<KeyValuePair<string, string>> list, HashSet<string> seen)
2263
+ {
2264
+ if (depth > 3 || string.IsNullOrEmpty(dir) || !Directory.Exists(dir)) return;
2265
+ try
2266
+ {
2267
+ foreach (var f in Directory.GetFiles(dir, "*.lnk"))
2268
+ {
2269
+ string name = Path.GetFileNameWithoutExtension(f);
2270
+ if (name.IndexOf("uninstall", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("卸载", StringComparison.OrdinalIgnoreCase) >= 0) continue;
2271
+ AddIfNew(list, seen, name, "lnk:" + f);
2272
+ }
2273
+ foreach (var sub in Directory.GetDirectories(dir))
2274
+ ScanStartFolder(sub, depth + 1, list, seen);
2275
+ }
2276
+ catch (Exception) { }
2277
+ }
2278
+
2279
+ static void ScanRegistryApps(List<KeyValuePair<string, string>> list, HashSet<string> seen)
2280
+ {
2281
+ var roots = new RegistryKey[] { Registry.CurrentUser, Registry.LocalMachine };
2282
+ foreach (var root in roots)
2283
+ {
2284
+ // 1. App Paths (e.g. WeChat.exe, chrome.exe, code.exe)
2285
+ try
2286
+ {
2287
+ using (var ap = root.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths"))
2288
+ {
2289
+ if (ap != null)
2290
+ {
2291
+ foreach (var subName in ap.GetSubKeyNames())
2292
+ {
2293
+ try
2294
+ {
2295
+ using (var sub = ap.OpenSubKey(subName))
2296
+ {
2297
+ if (sub == null) continue;
2298
+ string exe = ExtractExePath(Convert.ToString(sub.GetValue(null)) ?? "");
2299
+ if (exe.Length > 0) AddIfNew(list, seen, Path.GetFileNameWithoutExtension(subName), "exe:" + exe);
2300
+ }
2301
+ }
2302
+ catch (Exception) { }
2303
+ }
2304
+ }
2305
+ }
2306
+ }
2307
+ catch (Exception) { }
2308
+
2309
+ // 2. Uninstall table DisplayName + DisplayIcon (.exe)
2310
+ var uninstallPaths = new string[] {
2311
+ @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
2312
+ @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall",
2313
+ };
2314
+ foreach (var upath in uninstallPaths)
2315
+ {
2316
+ try
2317
+ {
2318
+ using (var uk = root.OpenSubKey(upath))
2319
+ {
2320
+ if (uk == null) continue;
2321
+ foreach (var subName in uk.GetSubKeyNames())
2322
+ {
2323
+ try
2324
+ {
2325
+ using (var sub = uk.OpenSubKey(subName))
2326
+ {
2327
+ if (sub == null) continue;
2328
+ string displayName = Convert.ToString(sub.GetValue("DisplayName")) ?? "";
2329
+ if (displayName.Length == 0) continue;
2330
+ string iconExe = ExtractExePath(Convert.ToString(sub.GetValue("DisplayIcon")) ?? "");
2331
+ if (iconExe.Length == 0) continue;
2332
+ if (iconExe.IndexOf("unins", StringComparison.OrdinalIgnoreCase) >= 0 || iconExe.IndexOf("setup", StringComparison.OrdinalIgnoreCase) >= 0) continue;
2333
+ AddIfNew(list, seen, displayName, "exe:" + iconExe);
2334
+ }
2335
+ }
2336
+ catch (Exception) { }
2337
+ }
2338
+ }
2339
+ }
2340
+ catch (Exception) { }
2341
+ }
2342
+ }
2343
+ }
2344
+
1890
2345
  static List<KeyValuePair<string, string>> Load()
1891
2346
  {
1892
2347
  if (cache != null && (DateTime.UtcNow - cachedAt).TotalSeconds < 600) return cache;
1893
2348
  var list = new List<KeyValuePair<string, string>>();
2349
+ var seen = new HashSet<string>();
1894
2350
  Type t = Type.GetTypeFromProgID("Shell.Application");
1895
2351
  dynamic shell = Activator.CreateInstance(t);
1896
2352
  try
@@ -1899,21 +2355,22 @@ namespace DshComputerUse
1899
2355
  foreach (dynamic item in folder.Items())
1900
2356
  {
1901
2357
  string name = item.Name; string path = item.Path;
1902
- if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(path)) list.Add(new KeyValuePair<string, string>(name, path));
2358
+ AddIfNew(list, seen, name, path);
1903
2359
  }
1904
2360
  }
1905
2361
  finally { Marshal.FinalReleaseComObject(shell); }
1906
- // Desktop shortcuts too: portable apps often only live there.
1907
- foreach (var folder in new[] { Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) })
2362
+ // Desktop & Start Menu shortcuts: portable and classic apps often only live there.
2363
+ foreach (var folder in new[] {
2364
+ Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory),
2365
+ Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory),
2366
+ Environment.GetFolderPath(Environment.SpecialFolder.Programs),
2367
+ Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
2368
+ })
1908
2369
  {
1909
- try
1910
- {
1911
- if (folder.Length == 0 || !Directory.Exists(folder)) continue;
1912
- foreach (var f in Directory.GetFiles(folder, "*.lnk"))
1913
- list.Add(new KeyValuePair<string, string>(Path.GetFileNameWithoutExtension(f), "lnk:" + f));
1914
- }
1915
- catch (Exception) { }
2370
+ ScanStartFolder(folder, 0, list, seen);
1916
2371
  }
2372
+ // Registry App Paths & Uninstall executable locations.
2373
+ ScanRegistryApps(list, seen);
1917
2374
  cache = list; cachedAt = DateTime.UtcNow;
1918
2375
  return list;
1919
2376
  }
@@ -1947,6 +2404,7 @@ namespace DshComputerUse
1947
2404
  string args = Args.Str(r, "args", "");
1948
2405
  ProcessStartInfo psi;
1949
2406
  if (appId.StartsWith("lnk:")) psi = new ProcessStartInfo(appId.Substring(4));
2407
+ else if (appId.StartsWith("exe:")) psi = new ProcessStartInfo(appId.Substring(4));
1950
2408
  else if (appId.Length > 0) psi = new ProcessStartInfo("explorer.exe", "shell:AppsFolder\\" + appId);
1951
2409
  else { psi = new ProcessStartInfo(target); if (args.Length > 0) psi.Arguments = args; }
1952
2410
  psi.UseShellExecute = true;
@@ -2400,6 +2858,7 @@ namespace DshComputerUse
2400
2858
  if (++looked > 200) break;
2401
2859
  try
2402
2860
  {
2861
+ if (IsPasswordElement(el)) continue;
2403
2862
  object pattern;
2404
2863
  if (!el.TryGetCurrentPattern(ValuePattern.Pattern, out pattern)) continue;
2405
2864
  string got = ((ValuePattern)pattern).Current.Value;
@@ -2430,6 +2889,253 @@ namespace DshComputerUse
2430
2889
  return sb.ToString();
2431
2890
  }
2432
2891
 
2892
+ static bool IsWin32PasswordHwnd(IntPtr h)
2893
+ {
2894
+ if (h == IntPtr.Zero || !Native.IsWindow(h)) return false;
2895
+ var cls = new StringBuilder(64);
2896
+ Native.GetClassName(h, cls, cls.Capacity);
2897
+ string c = cls.ToString();
2898
+ if (c.IndexOf("Edit", StringComparison.OrdinalIgnoreCase) < 0 && c.IndexOf("RichEdit", StringComparison.OrdinalIgnoreCase) < 0)
2899
+ return false;
2900
+ int style = Native.GetWindowLong(h, -16); // GWL_STYLE
2901
+ return (style & 0x0020) != 0; // ES_PASSWORD
2902
+ }
2903
+
2904
+ static bool IsPasswordElement(AutomationElement el)
2905
+ {
2906
+ if (el == null) return false;
2907
+ try
2908
+ {
2909
+ if (el.Current.IsPassword) return true;
2910
+ int nh = el.Current.NativeWindowHandle;
2911
+ if (nh != 0 && IsWin32PasswordHwnd(new IntPtr(nh))) return true;
2912
+ }
2913
+ catch (Exception) { }
2914
+ return false;
2915
+ }
2916
+
2917
+ /** Check whether keyboard focus is currently inside a password input (UIA IsPassword or Win32 ES_PASSWORD). */
2918
+ public static object PasswordFocus()
2919
+ {
2920
+ bool isPwd = false;
2921
+ string reason = "";
2922
+ string name = "";
2923
+ try
2924
+ {
2925
+ IntPtr fg = Native.GetForegroundWindow();
2926
+ if (fg != IntPtr.Zero)
2927
+ {
2928
+ uint pid;
2929
+ uint tid = Native.GetWindowThreadProcessId(fg, out pid);
2930
+ var gti = new Native.GUITHREADINFO();
2931
+ gti.cbSize = Marshal.SizeOf(typeof(Native.GUITHREADINFO));
2932
+ if (Native.GetGUIThreadInfo(tid, ref gti) && gti.hwndFocus != IntPtr.Zero && IsWin32PasswordHwnd(gti.hwndFocus))
2933
+ {
2934
+ isPwd = true;
2935
+ reason = "win32_es_password";
2936
+ }
2937
+ }
2938
+ }
2939
+ catch (Exception) { }
2940
+ if (!isPwd)
2941
+ {
2942
+ var worker = new Thread(delegate ()
2943
+ {
2944
+ try
2945
+ {
2946
+ var focused = AutomationElement.FocusedElement;
2947
+ if (focused != null && IsPasswordElement(focused))
2948
+ {
2949
+ isPwd = true;
2950
+ reason = "uia_is_password";
2951
+ name = focused.Current.Name ?? "";
2952
+ }
2953
+ }
2954
+ catch (Exception) { }
2955
+ });
2956
+ worker.IsBackground = true;
2957
+ worker.SetApartmentState(ApartmentState.MTA);
2958
+ worker.Start();
2959
+ worker.Join(500);
2960
+ }
2961
+ var d = new Dictionary<string, object>();
2962
+ d["password"] = isPwd;
2963
+ d["reason"] = reason;
2964
+ d["name"] = name;
2965
+ return d;
2966
+ }
2967
+
2968
+ /**
2969
+ * Try to invoke/toggle/select an enabled native UIA control directly under
2970
+ * physical point (x, y) without moving the physical cursor or stealing focus.
2971
+ */
2972
+ public static object ClickAtPoint(Dictionary<string, object> r)
2973
+ {
2974
+ int x = Args.Int(r, "x", 0);
2975
+ int y = Args.Int(r, "y", 0);
2976
+ long expectedHwnd = Args.Has(r, "hwnd") ? Convert.ToInt64(r["hwnd"]) : 0;
2977
+ bool ok = false;
2978
+ string mechanism = "";
2979
+ string role = "";
2980
+ string name = "";
2981
+ var worker = new Thread(delegate ()
2982
+ {
2983
+ try
2984
+ {
2985
+ var el = AutomationElement.FromPoint(new System.Windows.Point(x, y));
2986
+ if (el == null) return;
2987
+ if (!el.Current.IsEnabled || IsPasswordElement(el)) return;
2988
+ var ct = el.Current.ControlType;
2989
+ // Only intercept clearly semantic, single-click invocable controls;
2990
+ // never intercept Edit/Document/Pane/Custom/Group where cursor placement matters.
2991
+ bool allowed = ct == ControlType.Button || ct == ControlType.CheckBox || ct == ControlType.RadioButton
2992
+ || ct == ControlType.MenuItem || ct == ControlType.TabItem || ct == ControlType.Hyperlink;
2993
+ if (!allowed) return;
2994
+ if (expectedHwnd != 0)
2995
+ {
2996
+ int nh = el.Current.NativeWindowHandle;
2997
+ IntPtr root = nh != 0 ? Native.GetAncestor(new IntPtr(nh), 2) : IntPtr.Zero;
2998
+ if (root != IntPtr.Zero && root.ToInt64() != expectedHwnd) return;
2999
+ }
3000
+ role = ct.ProgrammaticName.Replace("ControlType.", "");
3001
+ name = el.Current.Name ?? "";
3002
+ object pat;
3003
+ if (el.TryGetCurrentPattern(InvokePattern.Pattern, out pat))
3004
+ {
3005
+ ((InvokePattern)pat).Invoke();
3006
+ ok = true;
3007
+ mechanism = "invoke";
3008
+ return;
3009
+ }
3010
+ if (el.TryGetCurrentPattern(TogglePattern.Pattern, out pat))
3011
+ {
3012
+ ((TogglePattern)pat).Toggle();
3013
+ ok = true;
3014
+ mechanism = "toggle";
3015
+ return;
3016
+ }
3017
+ if (el.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pat))
3018
+ {
3019
+ ((SelectionItemPattern)pat).Select();
3020
+ ok = true;
3021
+ mechanism = "select";
3022
+ return;
3023
+ }
3024
+ }
3025
+ catch (Exception) { }
3026
+ });
3027
+ worker.IsBackground = true;
3028
+ worker.SetApartmentState(ApartmentState.MTA);
3029
+ worker.Start();
3030
+ worker.Join(900);
3031
+ var d = new Dictionary<string, object>();
3032
+ d["ok"] = ok;
3033
+ d["mechanism"] = mechanism;
3034
+ d["role"] = role;
3035
+ d["name"] = name;
3036
+ return d;
3037
+ }
3038
+
3039
+ /**
3040
+ * Set-of-Marks annotated screenshot: capture the display, draw crisp numbered
3041
+ * badges [1..N] over interactive UIA controls of the target window, and return
3042
+ * both the JPEG image and the indexed element list.
3043
+ */
3044
+ public static object Marks(Dictionary<string, object> r)
3045
+ {
3046
+ int sx = Args.Int(r, "x", 0), sy = Args.Int(r, "y", 0);
3047
+ int sw = Args.Int(r, "width", 0), sh = Args.Int(r, "height", 0);
3048
+ int outW = Args.Int(r, "outWidth", sw), outH = Args.Int(r, "outHeight", sh);
3049
+ int quality = Math.Max(30, Math.Min(100, Args.Int(r, "quality", 75)));
3050
+ if (sw <= 0 || sh <= 0) throw new Exception("marks needs display width and height");
3051
+ var ui = Elements(r) as Dictionary<string, object>;
3052
+ var rawElements = ui != null && ui.ContainsKey("elements") ? ui["elements"] as List<object> : new List<object>();
3053
+ if (rawElements == null) rawElements = new List<object>();
3054
+
3055
+ string via;
3056
+ using (var rawBmp = Screen2.Grab(sx, sy, sw, sh, out via))
3057
+ using (var canvas = new Bitmap(outW, outH, PixelFormat.Format24bppRgb))
3058
+ using (var g = Graphics.FromImage(canvas))
3059
+ {
3060
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
3061
+ g.SmoothingMode = SmoothingMode.AntiAlias;
3062
+ g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
3063
+ g.DrawImage(rawBmp, 0, 0, outW, outH);
3064
+
3065
+ double scaleX = (double)outW / sw;
3066
+ double scaleY = (double)outH / sh;
3067
+ var placed = new List<RectangleF>();
3068
+ using (var font = new Font("Microsoft YaHei UI", 10.5f, FontStyle.Bold, GraphicsUnit.Pixel))
3069
+ using (var fmt = new StringFormat(StringFormat.GenericTypographic))
3070
+ using (var bgBrush = new SolidBrush(Color.FromArgb(228, 217, 119, 87)))
3071
+ using (var borderPen = new Pen(Color.FromArgb(245, 255, 255, 255), 1.3f))
3072
+ using (var boxPen = new Pen(Color.FromArgb(140, 217, 119, 87), 1.1f))
3073
+ {
3074
+ fmt.FormatFlags |= StringFormatFlags.NoWrap;
3075
+ int drawn = 0;
3076
+ for (int i = 0; i < rawElements.Count && drawn < 120; i++)
3077
+ {
3078
+ var el = rawElements[i] as Dictionary<string, object>;
3079
+ if (el == null) continue;
3080
+ int ex = Convert.ToInt32(el["x"]), ey = Convert.ToInt32(el["y"]);
3081
+ int ew = Convert.ToInt32(el["width"]), eh = Convert.ToInt32(el["height"]);
3082
+ float rx = (float)((ex - sx) * scaleX);
3083
+ float ry = (float)((ey - sy) * scaleY);
3084
+ float rw = (float)(ew * scaleX);
3085
+ float rh = (float)(eh * scaleY);
3086
+ if (rx + rw < 0 || ry + rh < 0 || rx >= outW || ry >= outH) continue;
3087
+ if (rw < 4 || rh < 4) continue;
3088
+ el["mark"] = i + 1;
3089
+ drawn++;
3090
+ if (rw <= outW * 0.85f && rh <= outH * 0.85f)
3091
+ g.DrawRectangle(boxPen, rx, ry, rw, rh);
3092
+ string tag = (i + 1).ToString();
3093
+ SizeF ts = g.MeasureString(tag, font, 1000, fmt);
3094
+ float bw = Math.Max(16f, ts.Width + 6f);
3095
+ float bh = Math.Max(15f, ts.Height + 2f);
3096
+ float bx = Math.Max(1f, Math.Min(outW - bw - 1f, rx));
3097
+ float by = Math.Max(1f, Math.Min(outH - bh - 1f, ry - bh * 0.35f));
3098
+ var badge = new RectangleF(bx, by, bw, bh);
3099
+ for (int attempt = 0; attempt < 3; attempt++)
3100
+ {
3101
+ bool overlap = false;
3102
+ for (int j = 0; j < placed.Count; j++)
3103
+ if (placed[j].IntersectsWith(badge)) { overlap = true; break; }
3104
+ if (!overlap) break;
3105
+ badge.X = Math.Min(outW - bw - 1f, badge.X + bw + 2f);
3106
+ }
3107
+ placed.Add(badge);
3108
+ g.FillRectangle(bgBrush, badge);
3109
+ g.DrawRectangle(borderPen, badge.X, badge.Y, badge.Width, badge.Height);
3110
+ g.DrawString(tag, font, Brushes.White, badge.X + (badge.Width - ts.Width) / 2f, badge.Y + (badge.Height - ts.Height) / 2f - 0.5f, fmt);
3111
+ }
3112
+ }
3113
+
3114
+ using (var ms = new MemoryStream())
3115
+ {
3116
+ ImageCodecInfo jpeg = null;
3117
+ foreach (var c in ImageCodecInfo.GetImageEncoders()) if (c.MimeType == "image/jpeg") { jpeg = c; break; }
3118
+ if (jpeg != null)
3119
+ {
3120
+ using (var ep = new EncoderParameters(1))
3121
+ {
3122
+ ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
3123
+ canvas.Save(ms, jpeg, ep);
3124
+ }
3125
+ }
3126
+ else canvas.Save(ms, ImageFormat.Jpeg);
3127
+
3128
+ var outDict = new Dictionary<string, object>();
3129
+ if (ui != null) foreach (var kv in ui) outDict[kv.Key] = kv.Value;
3130
+ outDict["data"] = Convert.ToBase64String(ms.ToArray());
3131
+ outDict["width"] = outW;
3132
+ outDict["height"] = outH;
3133
+ outDict["via"] = via;
3134
+ return outDict;
3135
+ }
3136
+ }
3137
+ }
3138
+
2433
3139
  static List<object> Collect(IntPtr hwnd, int max, bool includeText)
2434
3140
  {
2435
3141
  var root = AutomationElement.FromHandle(hwnd);
@@ -2446,6 +3152,8 @@ namespace DshComputerUse
2446
3152
  cache.Add(AutomationElement.RuntimeIdProperty);
2447
3153
  cache.Add(AutomationElement.ClassNameProperty);
2448
3154
  cache.Add(AutomationElement.IsKeyboardFocusableProperty);
3155
+ cache.Add(AutomationElement.IsPasswordProperty);
3156
+ cache.Add(AutomationElement.NativeWindowHandleProperty);
2449
3157
  cache.Add(ValuePattern.ValueProperty);
2450
3158
  cache.Add(TogglePattern.ToggleStateProperty);
2451
3159
  cache.AutomationElementMode = AutomationElementMode.None;
@@ -2464,9 +3172,22 @@ namespace DshComputerUse
2464
3172
  // Web 编辑器的 contenteditable 常是 Group(ProseMirror/tiptap 等),
2465
3173
  // 不是 Edit;保留这类 Group,其余 Group 跳过,避免淹没按钮。
2466
3174
  if (type == ControlType.Group && !IsEditorClass(cls)) continue;
3175
+ bool isPwd = false;
3176
+ try
3177
+ {
3178
+ object pwdProp = el.GetCachedPropertyValue(AutomationElement.IsPasswordProperty, true);
3179
+ if (pwdProp is bool && (bool)pwdProp) isPwd = true;
3180
+ if (!isPwd)
3181
+ {
3182
+ object nhProp = el.GetCachedPropertyValue(AutomationElement.NativeWindowHandleProperty, true);
3183
+ if (nhProp is int && (int)nhProp != 0 && IsWin32PasswordHwnd(new IntPtr((int)nhProp))) isPwd = true;
3184
+ }
3185
+ }
3186
+ catch (Exception) { }
2467
3187
  var d = new Dictionary<string, object>();
2468
3188
  d["role"] = type == ControlType.Group ? "Edit" : type.ProgrammaticName.Replace("ControlType.", "");
2469
3189
  if (type == ControlType.Group) d["editable"] = true;
3190
+ if (isPwd) d["password"] = true;
2470
3191
  d["name"] = name.Length > 120 ? name.Substring(0, 120) + "…" : name;
2471
3192
  string aid = (el.GetCachedPropertyValue(AutomationElement.AutomationIdProperty) as string) ?? "";
2472
3193
  if (aid.Length > 0) d["automationId"] = aid;
@@ -2474,7 +3195,8 @@ namespace DshComputerUse
2474
3195
  if (runtimeId != null && runtimeId.Length > 0) d["runtimeId"] = String.Join(",", runtimeId);
2475
3196
  d["focusable"] = (bool)el.GetCachedPropertyValue(AutomationElement.IsKeyboardFocusableProperty);
2476
3197
  object value = el.GetCachedPropertyValue(ValuePattern.ValueProperty, true);
2477
- if (value is string && ((string)value).Length > 0) { var v = (string)value; d["value"] = v.Length > 120 ? v.Substring(0, 120) + "…" : v; }
3198
+ if (isPwd) { d["value"] = "[password]"; }
3199
+ else if (value is string && ((string)value).Length > 0) { var v = (string)value; d["value"] = v.Length > 120 ? v.Substring(0, 120) + "…" : v; }
2478
3200
  object toggle = el.GetCachedPropertyValue(TogglePattern.ToggleStateProperty, true);
2479
3201
  if (toggle is ToggleState) d["checked"] = (ToggleState)toggle == ToggleState.On;
2480
3202
  if (!(bool)el.GetCachedPropertyValue(AutomationElement.IsEnabledProperty)) d["disabled"] = true;
@@ -2889,16 +3611,40 @@ namespace DshComputerUse
2889
3611
  }
2890
3612
  }
2891
3613
 
2892
- static Bitmap DrawMark(string text, Color color, float scale, bool labelAbove, out int cx, out int cy)
3614
+ /**
3615
+ * Collaborative Codex-style cursor badge: the corner nearest the pointer
3616
+ * tip stays tight (2px), while the other three corners are smoothly rounded.
3617
+ */
3618
+ static GraphicsPath TagShape(RectangleF r, bool flipX, bool flipY, float scale)
3619
+ {
3620
+ float tight = 2f * scale;
3621
+ float round = 7f * scale;
3622
+ float tl = (!flipX && !flipY) ? tight : round;
3623
+ float tr = (flipX && !flipY) ? tight : round;
3624
+ float br = (flipX && flipY) ? tight : round;
3625
+ float bl = (!flipX && flipY) ? tight : round;
3626
+ var p = new GraphicsPath();
3627
+ p.AddArc(r.X, r.Y, tl * 2f, tl * 2f, 180, 90);
3628
+ p.AddArc(r.Right - tr * 2f, r.Y, tr * 2f, tr * 2f, 270, 90);
3629
+ p.AddArc(r.Right - br * 2f, r.Bottom - br * 2f, br * 2f, br * 2f, 0, 90);
3630
+ p.AddArc(r.X, r.Bottom - bl * 2f, bl * 2f, bl * 2f, 90, 90);
3631
+ p.CloseFigure();
3632
+ return p;
3633
+ }
3634
+
3635
+ /**
3636
+ * Draw a sleek Codex-style collaborative AI pointer cursor whose tip sits
3637
+ * pixel-exact at (cx, cy): soft radial spotlight glow, crisp filled vector
3638
+ * arrow with white outline, attached rounded name-tag pill (auto-flipping
3639
+ * at all 4 screen edges), and a subtle click ripple ring on post-click.
3640
+ */
3641
+ static Bitmap DrawMark(string text, Color color, float scale, bool flipX, bool flipY, bool ripple, out int cx, out int cy)
2893
3642
  {
2894
- float s = Math.Max(0.75f, scale);
3643
+ float s = Math.Max(0.75f, Math.Min(3f, scale));
2895
3644
  float px = 1.333f * s;
2896
- float ringR = 18f * s;
2897
- float arm = 25f * s;
2898
- float gap = 6f * s;
3645
+ float glowR = (ripple ? 20f : 16f) * s;
2899
3646
  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))
3647
+ using (var font = new Font("Microsoft YaHei UI", 8f * px, FontStyle.Bold, GraphicsUnit.Pixel))
2902
3648
  using (var probe = new Bitmap(1, 1))
2903
3649
  using (var mg = Graphics.FromImage(probe))
2904
3650
  using (var fmt = new StringFormat(StringFormat.GenericTypographic))
@@ -2906,15 +3652,23 @@ namespace DshComputerUse
2906
3652
  mg.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
2907
3653
  fmt.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.NoWrap;
2908
3654
  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);
3655
+ float pillPadX = 7f * s;
3656
+ float pillW = textSize.Width > 0 ? (float)Math.Ceiling(textSize.Width + 2f * pillPadX) : 0f;
3657
+ float pillH = textSize.Height > 0 ? Math.Max(19f * s, (float)Math.Ceiling(textSize.Height + 5f * s)) : 0f;
3658
+
3659
+ // Offsets relative to the pointer tip at (0, 0).
3660
+ float tagX = flipX ? (-10f * s - pillW) : (13f * s);
3661
+ float tagY = flipY ? (-10f * s - pillH) : (15f * s);
3662
+
3663
+ float minX = Math.Min(-glowR, pillW > 0 ? tagX : 0f) - pad;
3664
+ float maxX = Math.Max(glowR, Math.Max(14f * s, pillW > 0 ? tagX + pillW : 0f)) + pad;
3665
+ float minY = Math.Min(-glowR, pillH > 0 ? tagY : 0f) - pad;
3666
+ float maxY = Math.Max(glowR, Math.Max(22f * s, pillH > 0 ? tagY + pillH : 0f)) + pad;
3667
+
3668
+ int W = Math.Max(1, (int)Math.Ceiling(maxX - minX));
3669
+ int H = Math.Max(1, (int)Math.Ceiling(maxY - minY));
3670
+ cx = (int)Math.Round(-minX);
3671
+ cy = (int)Math.Round(-minY);
2918
3672
 
2919
3673
  var bmp = new Bitmap(W, H, PixelFormat.Format32bppArgb);
2920
3674
  using (var g = Graphics.FromImage(bmp))
@@ -2923,43 +3677,120 @@ namespace DshComputerUse
2923
3677
  g.SmoothingMode = SmoothingMode.AntiAlias;
2924
3678
  g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
2925
3679
 
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)))
3680
+ // 1. Soft radial spotlight centered right under the tip (cx, cy).
3681
+ using (var spot = new GraphicsPath())
2933
3682
  {
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);
3683
+ spot.AddEllipse(cx - glowR, cy - glowR, glowR * 2f, glowR * 2f);
3684
+ using (var glow = new PathGradientBrush(spot))
3685
+ {
3686
+ glow.CenterPoint = new PointF(cx, cy);
3687
+ glow.CenterColor = Color.FromArgb(ripple ? 130 : 95, color);
3688
+ glow.SurroundColors = new Color[] { Color.FromArgb(0, color) };
3689
+ g.FillPath(glow, spot);
3690
+ }
2939
3691
  }
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
3692
 
3693
+ // 2. Post-click delicate ripple ring so exact placement reads cleanly in screenshots.
3694
+ if (ripple)
3695
+ {
3696
+ float rr = 11.5f * s;
3697
+ using (var ringHalo = new Pen(Color.FromArgb(140, 255, 255, 255), Math.Max(2.5f, 3.2f * s)))
3698
+ g.DrawEllipse(ringHalo, cx - rr, cy - rr, rr * 2f, rr * 2f);
3699
+ using (var ring = new Pen(Color.FromArgb(230, color), Math.Max(1.6f, 2f * s)))
3700
+ g.DrawEllipse(ring, cx - rr, cy - rr, rr * 2f, rr * 2f);
3701
+ }
3702
+
3703
+ // 3. Attached collaborative name-tag pill.
2944
3704
  if (pillW > 0 && pillH > 0)
2945
3705
  {
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))
3706
+ float bx = cx + tagX;
3707
+ float by = cy + tagY;
3708
+ var shadowRect = new RectangleF(bx, by + 1.5f * s, pillW, pillH);
3709
+ using (var sp = TagShape(shadowRect, flipX, flipY, s))
3710
+ using (var sb = new SolidBrush(Color.FromArgb(62, 0, 0, 0)))
3711
+ g.FillPath(sb, sp);
3712
+
3713
+ var pillRect = new RectangleF(bx, by, pillW, pillH);
3714
+ using (var pp = TagShape(pillRect, flipX, flipY, s))
2949
3715
  {
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);
3716
+ using (var fill = new SolidBrush(Color.FromArgb(245, color))) g.FillPath(fill, pp);
3717
+ using (var border = new Pen(Color.FromArgb(235, 255, 255, 255), Math.Max(1f, 1.25f * s))) g.DrawPath(border, pp);
2952
3718
  }
2953
3719
  using (var fg = new SolidBrush(Color.White))
2954
- g.DrawString(text, font, fg, pillBox.X + pillPadX, pillBox.Y + (pillH - textSize.Height) / 2f, fmt);
3720
+ g.DrawString(text, font, fg, bx + (pillW - textSize.Width) / 2f, by + (pillH - textSize.Height) / 2f - 0.5f * s, fmt);
3721
+ }
3722
+
3723
+ // 4. Crisp vector cursor arrow whose tip sits pixel-exact at (cx, cy).
3724
+ var arrow = new PointF[]
3725
+ {
3726
+ new PointF(cx, cy),
3727
+ new PointF(cx, cy + 16.5f * s),
3728
+ new PointF(cx + 4.3f * s, cy + 12.8f * s),
3729
+ new PointF(cx + 7.4f * s, cy + 19.2f * s),
3730
+ new PointF(cx + 10.0f * s, cy + 17.9f * s),
3731
+ new PointF(cx + 6.9f * s, cy + 11.7f * s),
3732
+ new PointF(cx + 12.4f * s, cy + 11.4f * s),
3733
+ };
3734
+ var arrowShadow = new PointF[arrow.Length];
3735
+ for (int i = 0; i < arrow.Length; i++)
3736
+ arrowShadow[i] = new PointF(arrow[i].X + 0.8f * s, arrow[i].Y + 1.5f * s);
3737
+ using (var sb = new SolidBrush(Color.FromArgb(72, 0, 0, 0))) g.FillPolygon(sb, arrowShadow);
3738
+ using (var fill = new SolidBrush(Color.FromArgb(255, color))) g.FillPolygon(fill, arrow);
3739
+ using (var outline = new Pen(Color.FromArgb(248, 255, 255, 255), Math.Max(1.2f, 1.5f * s)))
3740
+ {
3741
+ outline.LineJoin = LineJoin.Round;
3742
+ g.DrawPolygon(outline, arrow);
2955
3743
  }
2956
3744
  }
2957
3745
  return bmp;
2958
3746
  }
2959
3747
  }
2960
3748
 
2961
- public static void Mark(int x, int y, string text, Color color, int holdMs, bool capturable)
3749
+ static int lastMarkX, lastMarkY;
3750
+ static bool hasLastMark;
3751
+
3752
+ public static void MarkPointer(int x, int y, string text, int holdMs)
3753
+ {
3754
+ GlideMark(x, y, text, Accent, holdMs, false, false);
3755
+ }
3756
+
3757
+ /** Smooth single-segment EaseOutCubic glide (~160ms) to (x, y) before holding the Codex cursor. */
3758
+ public static void GlideMark(int x, int y, string text, Color color, int holdMs, bool capturable, bool ripple)
3759
+ {
3760
+ int startX, startY;
3761
+ if (hasLastMark)
3762
+ {
3763
+ startX = lastMarkX;
3764
+ startY = lastMarkY;
3765
+ }
3766
+ else
3767
+ {
3768
+ Native.POINT cur;
3769
+ if (Native.GetCursorPos(out cur)) { startX = cur.X; startY = cur.Y; }
3770
+ else { startX = x; startY = y; }
3771
+ }
3772
+ double dist = Math.Sqrt((double)(x - startX) * (x - startX) + (double)(y - startY) * (y - startY));
3773
+ if (dist >= 40.0)
3774
+ {
3775
+ int steps = Math.Max(5, Math.Min(10, (int)(dist / 90.0) + 5));
3776
+ for (int i = 1; i < steps; i++)
3777
+ {
3778
+ double t = (double)i / steps;
3779
+ double ease = 1.0 - Math.Pow(1.0 - t, 3.0); // EaseOutCubic
3780
+ int ix = startX + (int)Math.Round((x - startX) * ease);
3781
+ int iy = startY + (int)Math.Round((y - startY) * ease);
3782
+ Mark(ix, iy, text, color, holdMs, capturable, false);
3783
+ Thread.Sleep(16);
3784
+ }
3785
+ }
3786
+ Mark(x, y, text, color, holdMs, capturable, ripple);
3787
+ }
3788
+
3789
+ public static void Mark(int x, int y, string text, Color color, int holdMs, bool capturable, bool ripple)
2962
3790
  {
3791
+ lastMarkX = x;
3792
+ lastMarkY = y;
3793
+ hasLastMark = true;
2963
3794
  Ensure();
2964
3795
  Ui(delegate
2965
3796
  {
@@ -2971,9 +3802,12 @@ namespace DshComputerUse
2971
3802
  markForm.SetCapturable(capturable || !ExcludeFromCapture);
2972
3803
  float scale; Rectangle mon;
2973
3804
  MonitorAt(x, y, out scale, out mon);
2974
- bool labelAbove = !mon.IsEmpty && y + (int)(66 * scale) > mon.Bottom;
3805
+ float s = Math.Max(0.75f, Math.Min(3f, scale));
3806
+ int estW = (int)((Math.Max(6, (text ?? "").Length) * 11 + 36) * s);
3807
+ bool flipX = !mon.IsEmpty && x + estW > mon.Right;
3808
+ bool flipY = !mon.IsEmpty && y + (int)(52 * s) > mon.Bottom;
2975
3809
  int cx, cy;
2976
- using (var bmp = DrawMark(text, color, scale, labelAbove, out cx, out cy))
3810
+ using (var bmp = DrawMark(text, color, scale, flipX, flipY, ripple, out cx, out cy))
2977
3811
  {
2978
3812
  markForm.SetBitmap(bmp, new Rectangle(x - cx, y - cy, bmp.Width, bmp.Height), 255);
2979
3813
  }
@@ -2989,11 +3823,11 @@ namespace DshComputerUse
2989
3823
  Color color;
2990
3824
  string verb;
2991
3825
  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 = "已右键"; }
3826
+ else if (count == 2) { color = Color.FromArgb(139, 92, 246); verb = "已双击"; }
3827
+ else if (button == "right") { color = Color.FromArgb(16, 185, 129); verb = "已右键"; }
2994
3828
  else if (button == "middle") { color = Color.FromArgb(6, 182, 212); verb = "已中键"; }
2995
3829
  else { color = Color.FromArgb(59, 130, 246); verb = "已单击"; }
2996
- Mark(x, y, verb + " " + coordLabel, color, 4000, true);
3830
+ Mark(x, y, verb + " " + coordLabel, color, 4000, true, true);
2997
3831
  }
2998
3832
 
2999
3833
  static void HideMark()