@aivin-labs/cli 1.0.50 → 1.0.57

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.
@@ -56,6 +56,7 @@ namespace AivinGui {
56
56
  [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hWnd, uint cmd);
57
57
  [DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hWnd, int index);
58
58
  [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdc, uint flags);
59
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string cls, string title);
59
60
  [DllImport("user32.dll")] public static extern uint SendInput(uint n, INPUT[] inputs, int size);
60
61
  [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
61
62
  [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
@@ -70,6 +71,18 @@ namespace AivinGui {
70
71
  [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
71
72
  [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int cx, int cy, uint flags);
72
73
  [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
74
+ [DllImport("user32.dll")] public static extern IntPtr RealChildWindowFromPoint(IntPtr parent, POINT clientPoint);
75
+ [DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr hWnd, ref POINT p);
76
+ [DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint thread, ref GUITHREADINFO info);
77
+ [StructLayout(LayoutKind.Sequential)] public struct GUITHREADINFO { public uint cbSize, flags; public IntPtr hwndActive, hwndFocus, hwndCapture, hwndMenuOwner, hwndMoveSize, hwndCaret; public RECT rcCaret; }
78
+ [DllImport("user32.dll", EntryPoint = "SendMessageTimeoutW")] public static extern IntPtr SendMessageTimeoutPtr(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam, uint flags, uint timeout, out IntPtr result);
79
+ [DllImport("user32.dll")] public static extern IntPtr GetMenu(IntPtr hWnd);
80
+ [DllImport("user32.dll")] public static extern IntPtr GetSubMenu(IntPtr menu, int pos);
81
+ [DllImport("user32.dll")] public static extern int GetMenuItemCount(IntPtr menu);
82
+ [DllImport("user32.dll")] public static extern uint GetMenuItemID(IntPtr menu, int pos);
83
+ [DllImport("user32.dll")] public static extern uint GetMenuState(IntPtr menu, uint id, uint flags);
84
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetMenuString(IntPtr menu, uint id, StringBuilder text, int max, uint flags);
85
+ [DllImport("oleacc.dll")] public static extern int AccessibleObjectFromWindow(IntPtr hWnd, uint objectId, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object acc);
73
86
  [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, IntPtr wParam, string lParam, uint flags, uint timeout, out IntPtr result);
74
87
  [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool attach);
75
88
  [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hWnd, int attr, out int value, int size);
@@ -114,11 +127,19 @@ namespace AivinGui {
114
127
  /** Điểm màn hình thật của lần bấm / cuộn / kéo chuột vừa rồi (tính SAU khi đưa cửa sổ lên) — cho screen_point. */
115
128
  static Dictionary<string, object> lastMousePoint = null;
116
129
 
130
+ /** Thao tác này chỉ được chạy nền (method "background"): tới bước cần chuột / phím thật thì dừng. */
131
+ static bool backgroundOnly = false;
132
+
133
+ /**
134
+ * Cửa duy nhất trước khi đụng chuột / phím thật (10/11/2026, user: "sao lại chiếm quyền điều khiển của user"). Có người vừa dùng máy thì
135
+ * báo GUI_PERSON_PRESENT, chưa làm gì; phía Node chờ họ ngừng tay rồi thử lại.
136
+ */
117
137
  static void GuardInput() {
138
+ if (backgroundOnly) throw new GuiError("GUI_NEEDS_REAL_INPUT", "This action needs the real mouse/keyboard");
118
139
  if (!pendingInputCheck) return;
119
140
  pendingInputCheck = false;
120
141
  long idle = UserIdleMs();
121
- if (idle < inputGraceMs) throw new GuiError("GUI_USER_ACTIVE", "The user is using the mouse/keyboard right now (" + idle + " ms ago) — this action needs the real mouse/keyboard");
142
+ if (idle < inputGraceMs) throw new GuiError("GUI_PERSON_PRESENT", "The person at this computer used the mouse/keyboard " + idle + " ms ago — this action needs the real mouse/keyboard");
122
143
  }
123
144
 
124
145
  /**
@@ -223,11 +244,19 @@ namespace AivinGui {
223
244
  case "to_back": {
224
245
  IntPtr h = ResolveWindow(a);
225
246
  IntPtr prev = ParseWindow(Str(a, "restore_to"));
226
- bool restored = prev != IntPtr.Zero && RestoreForeground(prev, h);
247
+ long contentWait = Bool(a, "wait_content", false) ? WaitForUwpContent(h, 3000) : 0;
248
+ bool restored = false;
249
+ IntPtr fgNow = Native.GetForegroundWindow();
250
+ if (prev != IntPtr.Zero && fgNow != prev && TookForeground(fgNow, h)) {
251
+ restored = RestoreForeground(prev, h);
252
+ // Ứng dụng Store không nhường bằng cách gắn luồng input → cách của gui.focus; lúc này focus đang ở ứng dụng AI vừa mở, phím Alt không rơi vào việc của người dùng.
253
+ if (!restored) { try { restored = ForceForeground(prev); } catch (GuiError) { } }
254
+ }
227
255
  SendToBack(h);
228
- return new Dictionary<string, object> { { "sent_to_back", true }, { "focus_returned_to_user", restored } };
256
+ return new Dictionary<string, object> { { "sent_to_back", true }, { "focus_returned_to_user", restored }, { "content_wait_ms", contentWait } };
229
257
  }
230
258
  case "act": return Act(a);
259
+ case "read_table": return ReadTable(a);
231
260
  case "wait_for": return WaitFor(a);
232
261
  case "office": return Office.Run(a);
233
262
  case "idle": return new Dictionary<string, object> { { "idle_ms", IdleMs() }, { "user_idle_ms", UserIdleMs() } };
@@ -345,9 +374,12 @@ namespace AivinGui {
345
374
  }
346
375
  if (!string.IsNullOrEmpty(w)) {
347
376
  string q = w.ToLowerInvariant();
348
- foreach (Dictionary<string, object> info in ListWindows(false)) {
349
- if (Convert.ToString(info["title"]).ToLowerInvariant().Contains(q) || Convert.ToString(info["process"]).ToLowerInvariant() == q) {
350
- return ParseWindow(Convert.ToString(info["window"]));
377
+ // Cửa sổ chính trước, rồi tới hộp thoại con (Save as, Options…) — nêu tiêu đề hộp thoại phải tìm được nó.
378
+ foreach (bool withDialogs in new[] { false, true }) {
379
+ foreach (Dictionary<string, object> info in ListWindows(withDialogs)) {
380
+ if (Convert.ToString(info["title"]).ToLowerInvariant().Contains(q) || Convert.ToString(info["process"]).ToLowerInvariant() == q) {
381
+ return ParseWindow(Convert.ToString(info["window"]));
382
+ }
351
383
  }
352
384
  }
353
385
  throw new GuiError("NOT_FOUND", "No window matches: " + w);
@@ -368,10 +400,37 @@ namespace AivinGui {
368
400
  return fg;
369
401
  }
370
402
 
403
+ /** Tiêu điểm đang ở ứng dụng vừa mở. Mọi ứng dụng Store chung tiến trình ApplicationFrameHost nên phải so đúng cửa sổ, kẻo giật focus khỏi ứng dụng Store người dùng vừa chuyển sang. */
404
+ static bool TookForeground(IntPtr fg, IntPtr h) {
405
+ if (fg == IntPtr.Zero || h == IntPtr.Zero) return false;
406
+ if (ClassOf(h) == "ApplicationFrameWindow") return fg == h;
407
+ uint pa, pb; Native.GetWindowThreadProcessId(fg, out pa); Native.GetWindowThreadProcessId(h, out pb);
408
+ return pa != 0 && pa == pb;
409
+ }
410
+
411
+ /** Ứng dụng Store: khung ApplicationFrameWindow có trước, nội dung (CoreWindow) gắn vào sau; lúc đang khởi động / bị treo tạm thì chưa có. */
412
+ static bool IsUwpFrameOnly(IntPtr h) {
413
+ if (ClassOf(h) != "ApplicationFrameWindow") return false;
414
+ // Chỉ còn thanh tiêu đề + lớp nhận input của khung. Ứng dụng không dùng CoreWindow (Sticky Notes…) vẫn có cửa sổ con khác.
415
+ for (IntPtr c = Native.FindWindowEx(h, IntPtr.Zero, null, null); c != IntPtr.Zero; c = Native.FindWindowEx(h, c, null, null)) {
416
+ string cls = ClassOf(c);
417
+ if (cls != "ApplicationFrameTitleBarWindow" && cls != "ApplicationFrameInputSinkWindow") return false;
418
+ }
419
+ return true;
420
+ }
421
+
422
+ /** Đẩy ứng dụng Store xuống quá sớm thì nó có thể bị treo tạm khi chưa dựng xong nội dung — chờ nội dung gắn vào khung (có giới hạn). */
423
+ static long WaitForUwpContent(IntPtr h, int timeoutMs) {
424
+ var sw = Stopwatch.StartNew();
425
+ while (IsUwpFrameOnly(h) && sw.ElapsedMilliseconds < timeoutMs) Thread.Sleep(100);
426
+ return sw.ElapsedMilliseconds;
427
+ }
428
+
371
429
  /** Đẩy cửa sổ xuống đáy chồng cửa sổ, không kích hoạt — nằm dưới cửa sổ người dùng, thao tác theo pattern vẫn chạy được. */
372
430
  static void SendToBack(IntPtr h) {
373
431
  if (h == IntPtr.Zero || !Native.IsWindow(h)) return;
374
- Native.SetWindowPos(h, new IntPtr(1), 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0010);
432
+ // SWP_ASYNCWINDOWPOS: cửa sổ của ứng dụng đang treo thì lệnh đồng bộ sẽ chờ tới khi nó hết treo.
433
+ Native.SetWindowPos(h, new IntPtr(1), 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0010 | 0x4000);
375
434
  }
376
435
 
377
436
  /** Cửa sổ trên cùng bị thao tác vừa rồi đổi đi → đưa cửa sổ cũ lên lại (gắn luồng input tạm, không phát phím giả). */
@@ -381,7 +440,7 @@ namespace AivinGui {
381
440
  uint pid;
382
441
  uint curThread = Native.GetWindowThreadProcessId(cur, out pid);
383
442
  uint me = Native.GetCurrentThreadId();
384
- bool attached = curThread != 0 && curThread != me && Native.AttachThreadInput(me, curThread, true);
443
+ bool attached = curThread != 0 && curThread != me && IsWindowResponsive(cur, 200) && Native.AttachThreadInput(me, curThread, true);
385
444
  try { Native.SetForegroundWindow(prev); } finally { if (attached) Native.AttachThreadInput(me, curThread, false); }
386
445
  return Native.GetForegroundWindow() == prev;
387
446
  }
@@ -432,6 +491,10 @@ namespace AivinGui {
432
491
  IntPtr hit = Native.WindowFromPoint(new Native.POINT { X = x, Y = y });
433
492
  uint pid = 0;
434
493
  if (hit != IntPtr.Zero) Native.GetWindowThreadProcessId(hit, out pid);
494
+ // Hộp Windows Security làm tối cả màn hình bằng một lớp phủ: nói thẳng nguyên nhân để Planner hỏi người dùng thay vì thử lại.
495
+ if (hit != IntPtr.Zero && ClassOf(RootOf(hit)) == "Shell_SystemDim") {
496
+ throw new GuiError("GUI_FOCUS_LOST", "A Windows Security prompt is covering the screen — nothing was clicked. Ask the person at this computer to answer it, or use an accessibility action (click by node_id / set_value)");
497
+ }
435
498
  string who = pid == 0 ? "nothing" : ProcessName(pid);
436
499
  throw new GuiError("GUI_FOCUS_LOST", "Another window (" + who + ") is on top of the target point — nothing was clicked. Observe again, or use an accessibility action (click by node_id / set_value)");
437
500
  }
@@ -442,9 +505,10 @@ namespace AivinGui {
442
505
  */
443
506
  static bool ForceForeground(IntPtr h) {
444
507
  if (h == IntPtr.Zero) return false;
508
+ if (Native.GetForegroundWindow() == h && !Native.IsIconic(h)) return true;
509
+ GuardInput();
445
510
  if (Native.IsIconic(h)) { Native.ShowWindow(h, 9); Thread.Sleep(120); }
446
511
  if (Native.GetForegroundWindow() == h) return true;
447
- GuardInput();
448
512
  // Windows chỉ cho đổi cửa sổ trước khi tiến trình vừa có input → nhấn nhả Alt (không tạo ký tự) rồi đặt.
449
513
  KeyTap(0x12);
450
514
  Native.SetForegroundWindow(h);
@@ -478,7 +542,10 @@ namespace AivinGui {
478
542
 
479
543
  static object FocusWindowOp(Dictionary<string, object> a) {
480
544
  IntPtr h = ResolveWindow(a);
481
- ForceForeground(h);
545
+ backgroundOnly = false;
546
+ inputGraceMs = Int(a, "user_input_grace_ms", 1500);
547
+ pendingInputCheck = Bool(a, "check_user_input", false);
548
+ try { ForceForeground(h); } finally { pendingInputCheck = false; }
482
549
  return new Dictionary<string, object> { { "focused", Native.GetForegroundWindow() == h }, { "window", WindowInfo(h, Native.GetForegroundWindow()) } };
483
550
  }
484
551
 
@@ -486,7 +553,7 @@ namespace AivinGui {
486
553
 
487
554
  static CacheRequest BuildCache() {
488
555
  var c = new CacheRequest();
489
- c.TreeScope = TreeScope.Element | TreeScope.Children;
556
+ c.TreeScope = TreeScope.Element;
490
557
  c.TreeFilter = Automation.ControlViewCondition;
491
558
  c.AutomationElementMode = AutomationElementMode.Full;
492
559
  c.Add(AutomationElement.NameProperty); c.Add(AutomationElement.ControlTypeProperty); c.Add(AutomationElement.AutomationIdProperty);
@@ -571,11 +638,72 @@ namespace AivinGui {
571
638
  return role == "button" || role == "edit" || role == "menuitem" || role == "hyperlink" || role == "listitem" || role == "tabitem" || role == "treeitem" || role == "checkbox" || role == "radiobutton" || role == "combobox";
572
639
  }
573
640
 
641
+ const int FIND_ELEMENT_BUDGET_MS = 3000, OBSERVE_BUDGET_MS = 5000, LIST_BUDGET_MS = 1500, MAX_CHILDREN_PER_NODE = 80, MAX_OFFSCREEN_CHILDREN = 15;
642
+ static readonly CacheRequest Lean = BuildLeanCache();
643
+ static CacheRequest BuildLeanCache() {
644
+ var c = new CacheRequest();
645
+ c.TreeScope = TreeScope.Element;
646
+ c.TreeFilter = Automation.ControlViewCondition;
647
+ c.Add(AutomationElement.IsOffscreenProperty);
648
+ return c;
649
+ }
650
+
651
+ /**
652
+ * Con của một phần tử. Khung thường dùng FindAll (nhanh hơn đi từng bước nhiều lần). Bảng / danh sách đi từng bước để dừng được giữa chừng:
653
+ * FindAll không huỷ được, và trên bảng dài (DataGridView qua cầu MSAA) mất hàng chục giây. Mỗi danh sách chỉ được dùng một phần ngân sách,
654
+ * để các nút nằm sau bảng vẫn đọc được. Dòng đã cuộn khuất chỉ giữ một phần và không tính vào trần: cuộn xuống sâu thì các dòng đầu đều khuất,
655
+ * dừng ở chúng sẽ không bao giờ thấy dòng đang hiện.
656
+ */
657
+ static List<AutomationElement> ChildrenOf(AutomationElement e, string role, CacheRequest cache, TreeWalker walker, Stopwatch sw, int budgetMs, ref bool cut) {
658
+ var kids = new List<AutomationElement>();
659
+ if (role != "table" && role != "datagrid" && role != "list" && role != "tree") {
660
+ try {
661
+ using (cache.Activate()) { foreach (AutomationElement k in e.FindAll(TreeScope.Children, Condition.TrueCondition)) kids.Add(k); }
662
+ } catch { /* phần tử vừa mất giữa chừng */ }
663
+ return kids;
664
+ }
665
+ long stopAt = Math.Min(sw.ElapsedMilliseconds + LIST_BUDGET_MS, budgetMs);
666
+ var visible = new List<AutomationElement>();
667
+ var hidden = new List<AutomationElement>();
668
+ try {
669
+ using (Lean.Activate()) {
670
+ // Đi bằng bộ đệm chỉ có IsOffscreen: qua cầu MSAA mỗi thuộc tính là một lượt hỏi sang ứng dụng, đọc đủ cho từng dòng thì không đi tới được dòng đang hiện.
671
+ AutomationElement k = walker.GetFirstChild(e, Lean);
672
+ int visibleRun = 0;
673
+ bool passedView = false;
674
+ while (k != null) {
675
+ if (visible.Count >= MAX_CHILDREN_PER_NODE || sw.ElapsedMilliseconds >= stopAt) { cut = true; break; }
676
+ if (!true.Equals(Cached(k, AutomationElement.IsOffscreenProperty))) { visible.Add(k); if (++visibleRun >= 3) passedView = true; }
677
+ else {
678
+ visibleRun = 0;
679
+ if (hidden.Count < MAX_OFFSCREEN_CHILDREN) hidden.Add(k);
680
+ else {
681
+ cut = true;
682
+ // Đã qua vùng đang hiện (ít nhất 3 dòng liền nhau, không phải dòng tiêu đề lẻ) và đủ phần khuất: phía sau chỉ còn dòng khuất.
683
+ if (passedView) break;
684
+ }
685
+ }
686
+ k = walker.GetNextSibling(k, Lean);
687
+ }
688
+ }
689
+ } catch { /* phần tử vừa mất giữa chừng: giữ phần đã đọc được */ }
690
+ // Đọc đủ thuộc tính sau cùng, dòng đang hiện trước: hết giờ thì mất phần khuất chứ không mất phần người dùng đang thấy.
691
+ using (cache.Activate()) {
692
+ visible.AddRange(hidden);
693
+ foreach (AutomationElement x in visible) {
694
+ if (sw.ElapsedMilliseconds >= budgetMs) { cut = true; break; }
695
+ try { kids.Add(x.GetUpdatedCache(cache)); } catch { /* dòng vừa mất */ }
696
+ }
697
+ }
698
+ return kids;
699
+ }
700
+
574
701
  static object Observe(Dictionary<string, object> a) {
575
702
  IntPtr h = ResolveWindow(a);
576
703
  if (h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused");
577
704
  int maxNodes = Math.Max(20, Math.Min(Int(a, "max_nodes", 300), 1500));
578
705
  int maxDepth = Math.Max(2, Math.Min(Int(a, "max_depth", 25), 60));
706
+ int budgetMs = Math.Max(500, Math.Min(Int(a, "budget_ms", OBSERVE_BUDGET_MS), 30000));
579
707
  var sw = Stopwatch.StartNew();
580
708
  AssertWindowResponsive(h);
581
709
  if (Native.IsIconic(h)) {
@@ -601,8 +729,12 @@ namespace AivinGui {
601
729
  root = root.GetUpdatedCache(cache);
602
730
  }
603
731
  queue.Enqueue(new KeyValuePair<AutomationElement, int>(root, 0));
732
+ var walker = new TreeWalker(Automation.ControlViewCondition);
733
+ bool timedOut = false, listCut = false;
734
+ var unreached = new List<AutomationElement>();
604
735
  while (queue.Count > 0) {
605
736
  if (nodes.Count >= maxNodes) { truncated = true; break; }
737
+ if (sw.ElapsedMilliseconds >= budgetMs) { truncated = true; timedOut = true; break; }
606
738
  var item = queue.Dequeue();
607
739
  AutomationElement e = item.Key;
608
740
  int idx = nodes.Count;
@@ -616,12 +748,19 @@ namespace AivinGui {
616
748
  if (IsInteractive(n)) interactive++;
617
749
  }
618
750
  if (item.Value >= maxDepth) continue;
619
- AutomationElementCollection kids;
620
- try {
621
- using (cache.Activate()) { kids = e.FindAll(TreeScope.Children, Condition.TrueCondition); }
622
- } catch { continue; }
623
- foreach (AutomationElement k in kids) queue.Enqueue(new KeyValuePair<AutomationElement, int>(k, item.Value + 1));
751
+ bool thisCut = false;
752
+ int visibleKids = 0;
753
+ foreach (AutomationElement k in ChildrenOf(e, Convert.ToString(n["role"]), cache, walker, sw, budgetMs, ref thisCut)) {
754
+ if (!true.Equals(Cached(k, AutomationElement.IsOffscreenProperty))) visibleKids++;
755
+ queue.Enqueue(new KeyValuePair<AutomationElement, int>(k, item.Value + 1));
756
+ }
757
+ if (thisCut) {
758
+ listCut = true;
759
+ // Không đi tới được dòng nào đang hiện (chỉ thấy dòng tiêu đề, thanh cuộn): bảng đã cuộn xa.
760
+ if (visibleKids <= 2) unreached.Add(e);
761
+ }
624
762
  }
763
+ if (listCut) truncated = true;
625
764
  lock (StateLock) {
626
765
  Snapshots[snap] = map;
627
766
  SnapshotWindow[snap] = h;
@@ -631,13 +770,18 @@ namespace AivinGui {
631
770
  Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest); OcrSnapshots.Remove(oldest);
632
771
  }
633
772
  }
773
+ foreach (AutomationElement list in unreached) AddVisibleRows(list, snap, nodes, wr, sw, budgetMs);
634
774
  // Cây nghèo: ít phần tử có tên / thao tác được (ứng dụng vẽ tay, canvas, Electron tắt trợ năng) → cần ảnh để định vị.
635
- string quality = (interactive >= 3 && named >= 5) ? "good" : "poor";
775
+ // Ứng dụng Store mới chỉ có khung: thanh tiêu đề đủ phần tử để chấm "good" nhưng chưa có nội dung thật.
776
+ bool frameOnly = IsUwpFrameOnly(h);
777
+ string quality = (!frameOnly && interactive >= 3 && named >= 5) ? "good" : "poor";
636
778
  var res = new Dictionary<string, object> {
637
779
  { "snapshot", snap }, { "window", WindowInfo(h, Native.GetForegroundWindow()) }, { "nodes", nodes }, { "node_count", nodes.Count },
638
780
  { "interactive_count", interactive }, { "tree_quality", quality }, { "truncated", truncated }, { "tree_ms", sw.ElapsedMilliseconds },
781
+ { "truncated_by", timedOut ? "time" : listCut ? "long_list" : truncated ? "node_limit" : null },
639
782
  { "dpi", (long)SafeDpi(h) },
640
783
  };
784
+ if (frameOnly) res["content_unavailable"] = true;
641
785
  bool wantImage = Bool(a, "include_image", false) || (quality == "poor" && Bool(a, "image_when_poor", true));
642
786
  // Cây nghèo → đọc chữ trên ảnh (OCR của Windows, chạy trên máy): mỗi cụm chữ thành một node "text" có toạ độ, thang quyết định đích
643
787
  // ở BE tìm được "nút Lưu" theo chữ như với phần tử thật thay vì đoán toạ độ trên ảnh.
@@ -662,6 +806,191 @@ namespace AivinGui {
662
806
  return res;
663
807
  }
664
808
 
809
+ /**
810
+ * Bảng dài đã cuộn xa: đi từng dòng qua cầu MSAA mất ~100 ms mỗi bước nên không tới được vùng đang hiện. Hỏi thẳng control dòng nào đang nằm ở
811
+ * từng độ cao (accHitTest không xét cửa sổ đang che, nên dùng được cả khi AI làm dưới nền). Mỗi dòng thành một node cùng kiểu với chữ OCR
812
+ * ("<snap>.t<k>"): có toạ độ, gui.act bấm được.
813
+ */
814
+ static void AddVisibleRows(AutomationElement list, int snap, List<object> nodes, Native.RECT wr, Stopwatch sw, int budgetMs) {
815
+ Accessibility.IAccessible client = AccessibleClient(OwnHandle(list));
816
+ object boxObj = Cached(list, AutomationElement.BoundingRectangleProperty);
817
+ if (client == null || !(boxObj is System.Windows.Rect)) return;
818
+ var box = (System.Windows.Rect)boxObj;
819
+ if (box.IsEmpty || box.Height < 4) return;
820
+ var known = new HashSet<string>();
821
+ foreach (object o in nodes) {
822
+ var d = (Dictionary<string, object>)o;
823
+ if (d.ContainsKey("name") && !d.ContainsKey("offscreen")) known.Add(Convert.ToString(d["name"]));
824
+ }
825
+ var rects = new List<System.Windows.Rect>();
826
+ lock (StateLock) { List<System.Windows.Rect> had; if (OcrSnapshots.TryGetValue(snap, out had)) rects = had; else OcrSnapshots[snap] = rects; }
827
+ int added = 0;
828
+ foreach (AccRow row in SampleRows(client, box, sw, budgetMs + 1000)) {
829
+ if (added >= 60 || !known.Add(row.Name)) continue;
830
+ var n = new Dictionary<string, object> {
831
+ { "id", snap + ".t" + rects.Count }, { "role", "row" }, { "name", Clip(row.Name, 200) }, { "source", "accessible" },
832
+ { "rect", new Dictionary<string, object> { { "x", row.Left - wr.Left }, { "y", row.Top - wr.Top }, { "w", row.Width }, { "h", row.Height } } },
833
+ };
834
+ if (!string.IsNullOrEmpty(row.Value)) n["value"] = Clip(row.Value, 400);
835
+ lock (StateLock) { rects.Add(new System.Windows.Rect(row.Left - wr.Left, row.Top - wr.Top, row.Width, row.Height)); }
836
+ nodes.Add(n);
837
+ added++;
838
+ }
839
+ }
840
+
841
+ class AccRow { public string Name, Value; public int Left, Top, Width, Height; }
842
+
843
+ /** Các dòng đang hiện của một bảng, từ trên xuống, hỏi thẳng control. Control không trả lời được thì trả phần đã đọc. */
844
+ static List<AccRow> SampleRows(Accessibility.IAccessible client, System.Windows.Rect box, Stopwatch sw, long stopAtMs) {
845
+ var rows = new List<AccRow>();
846
+ int x = (int)(box.Left + Math.Min(60, box.Width / 3));
847
+ double y = box.Top + 2;
848
+ try {
849
+ while (y < box.Bottom && sw.ElapsedMilliseconds < stopAtMs) {
850
+ object hit = client.accHitTest(x, (int)y);
851
+ Accessibility.IAccessible row = hit as Accessibility.IAccessible ?? client;
852
+ object child = hit is int ? hit : 0;
853
+ if (ReferenceEquals(row, client) && child is int && (int)child == 0) { y += 8; continue; }
854
+ // Trúng một ô: lấy cả dòng để có đủ các cột.
855
+ if (Convert.ToInt32(row.get_accRole(child)) == ROLE_SYSTEM_CELL) {
856
+ var parent = row.accParent as Accessibility.IAccessible;
857
+ if (parent != null) { row = parent; child = 0; }
858
+ }
859
+ int left, top, w, h;
860
+ row.accLocation(out left, out top, out w, out h, child);
861
+ if (h <= 0) { y += 8; continue; }
862
+ string name = row.get_accName(child);
863
+ if (!string.IsNullOrEmpty(name) && (rows.Count == 0 || rows[rows.Count - 1].Name != name)) {
864
+ string value = null;
865
+ try { value = row.get_accValue(child); } catch (COMException) { }
866
+ rows.Add(new AccRow { Name = name, Value = value, Left = left, Top = top, Width = w, Height = h });
867
+ }
868
+ y = Math.Max(y + 1, top + h + 1);
869
+ }
870
+ } catch (COMException) { } catch (ArgumentException) { } catch (InvalidCastException) { } catch (NotImplementedException) { }
871
+ return rows;
872
+ }
873
+
874
+ const int READ_TABLE_BUDGET_MS = 20000;
875
+ /**
876
+ * Số nấc lăn liên tiếp không đổi gì mới coi là tới đầu / cuối bảng. Một nấc có thể bị bỏ qua vì người dùng đang giữ Shift hay nút chuột
877
+ * (DataGridView tự kiểm phím thật): chạy thật 10/11/2026 dừng ở dòng 62/200 mà vẫn báo đã đọc hết.
878
+ */
879
+ const int READ_TABLE_STALL_NOTCHES = 8, READ_TABLE_STALL_WAIT_MS = 80;
880
+
881
+ /** Lăn một nấc và chờ control xử lý xong, để lần đọc sau thấy đúng vị trí mới. */
882
+ static bool Wheel(IntPtr control, int delta, IntPtr screenPoint) {
883
+ IntPtr r;
884
+ return Native.SendMessageTimeoutPtr(control, WM_MOUSEWHEEL, new IntPtr(delta << 16), screenPoint, SMTO_ABORTIFHUNG, 1000, out r) != IntPtr.Zero;
885
+ }
886
+
887
+ static string FirstDataRow(List<AccRow> page) {
888
+ foreach (AccRow row in page) if (row.Value != row.Name) return row.Name;
889
+ return null;
890
+ }
891
+
892
+ const int ROLE_SYSTEM_COLUMNHEADER = 0x19, ROLE_SYSTEM_ROWHEADER = 0x1A;
893
+
894
+ /** Ô sâu nhất tại một điểm của bảng (bảng → dòng → ô). null = không trúng mục nào. */
895
+ static Accessibility.IAccessible CellAt(Accessibility.IAccessible client, int x, int y) {
896
+ var cell = client.accHitTest(x, y) as Accessibility.IAccessible;
897
+ if (cell == null) return null;
898
+ var deeper = cell.accHitTest(x, y) as Accessibility.IAccessible;
899
+ return deeper ?? cell;
900
+ }
901
+
902
+ /**
903
+ * Tên cột: dò ngang dòng tiêu đề, chỉ lấy ô tiêu đề cột. Ô ngay trên cột đầu dòng (dưới nó là tiêu đề hàng) không phải một cột, nên bỏ;
904
+ * toạ độ dò theo bước nhỏ vì độ rộng các ô tiêu đề không phải control nào cũng báo đúng.
905
+ */
906
+ static List<object> ReadColumns(Accessibility.IAccessible client, System.Windows.Rect box, AccRow header) {
907
+ var cols = new List<object>();
908
+ try {
909
+ int y = header.Top + header.Height / 2, below = header.Top + header.Height + 4;
910
+ string last = null;
911
+ for (double x = box.Left + 2; x < box.Right && cols.Count < 100; x += 12) {
912
+ var cell = CellAt(client, (int)x, y);
913
+ if (cell == null || Convert.ToInt32(cell.get_accRole(0)) != ROLE_SYSTEM_COLUMNHEADER) continue;
914
+ var under = CellAt(client, (int)x, below);
915
+ if (under != null && Convert.ToInt32(under.get_accRole(0)) == ROLE_SYSTEM_ROWHEADER) continue;
916
+ string name = cell.get_accName(0);
917
+ if (string.IsNullOrEmpty(name) || name == last) continue;
918
+ cols.Add(Clip(name, 120));
919
+ last = name;
920
+ }
921
+ } catch (COMException) { } catch (ArgumentException) { } catch (InvalidCastException) { } catch (NotImplementedException) { }
922
+ return cols;
923
+ }
924
+
925
+ /**
926
+ * Đọc cả bảng dưới nền: cuộn lên đầu, đọc dòng đang hiện, lăn một nấc, lặp tới khi hết dòng mới, rồi cuộn về chỗ cũ. Mỗi lần một nấc để các trang gối nhau;
927
+ * hai trang liền nhau không có dòng chung (ứng dụng cuộn quá nhanh) thì báo gaps, không âm thầm bỏ sót.
928
+ */
929
+ static object ReadTable(Dictionary<string, object> a) {
930
+ IntPtr window;
931
+ AutomationElement el = NodeOf(Str(a, "node_id"), out window);
932
+ AssertWindowResponsive(window);
933
+ int maxRows = Math.Max(1, Math.Min(Int(a, "max_rows", 300), 2000));
934
+ IntPtr control = OwnHandle(el);
935
+ Accessibility.IAccessible client = AccessibleClient(control);
936
+ System.Windows.Rect box = el.Current.BoundingRectangle;
937
+ if (client == null || box.IsEmpty) throw new GuiError("GUI_NO_PATTERN", "This table cannot be read directly — use gui.observe / gui.find and scroll");
938
+ bool canScroll = AcceptsPostedInput(control);
939
+ var sw = Stopwatch.StartNew();
940
+ var seen = new HashSet<string>();
941
+ var rows = new List<object>();
942
+ List<object> columns = null;
943
+ bool gaps = false, endReached = false;
944
+ int notches = 0, stale = 0, movedUp = 0;
945
+ var lp = new IntPtr((((int)box.Top + 20 & 0xFFFF) << 16) | ((int)box.Left + 20 & 0xFFFF));
946
+ HashSet<string> previous = null;
947
+ // Bảng có thể đang cuộn dở: lên đầu trước, nhớ đã lên bao nhiêu nấc để trả về đúng chỗ.
948
+ if (canScroll) {
949
+ string top = FirstDataRow(SampleRows(client, box, sw, READ_TABLE_BUDGET_MS));
950
+ int stalled = 0;
951
+ while (top != null && movedUp < 2000 && stalled < READ_TABLE_STALL_NOTCHES && sw.ElapsedMilliseconds < READ_TABLE_BUDGET_MS / 2) {
952
+ if (!Wheel(control, 120, lp)) break;
953
+ string now = FirstDataRow(SampleRows(client, box, sw, READ_TABLE_BUDGET_MS));
954
+ if (now == top) { stalled++; Thread.Sleep(READ_TABLE_STALL_WAIT_MS); continue; }
955
+ stalled = 0;
956
+ top = now;
957
+ movedUp++;
958
+ }
959
+ }
960
+ while (rows.Count < maxRows && sw.ElapsedMilliseconds < READ_TABLE_BUDGET_MS) {
961
+ var page = SampleRows(client, box, sw, READ_TABLE_BUDGET_MS);
962
+ var names = new HashSet<string>();
963
+ int fresh = 0;
964
+ bool overlap = false;
965
+ foreach (AccRow row in page) {
966
+ bool header = row.Value == row.Name;
967
+ if (header) { if (columns == null) columns = ReadColumns(client, box, row); continue; }
968
+ names.Add(row.Name);
969
+ if (previous != null && previous.Contains(row.Name)) overlap = true;
970
+ if (!seen.Add(row.Name)) continue;
971
+ fresh++;
972
+ if (rows.Count < maxRows) rows.Add(Clip(string.IsNullOrEmpty(row.Value) ? row.Name : row.Value, 800));
973
+ }
974
+ if (previous != null && previous.Count > 0 && names.Count > 0 && !overlap) gaps = true;
975
+ previous = names;
976
+ if (!canScroll) break;
977
+ if (fresh == 0) {
978
+ if (++stale >= READ_TABLE_STALL_NOTCHES) { endReached = true; break; }
979
+ Thread.Sleep(READ_TABLE_STALL_WAIT_MS);
980
+ } else stale = 0;
981
+ if (!Wheel(control, -120, lp)) break;
982
+ notches++;
983
+ }
984
+ if (canScroll) {
985
+ for (int i = 0; i < notches; i++) if (!Wheel(control, 120, lp)) break;
986
+ for (int i = 0; i < movedUp; i++) if (!Wheel(control, -120, lp)) break;
987
+ }
988
+ string reason = endReached ? null : !canScroll ? "this app cannot be scrolled in the background: only the rows on screen were read" : rows.Count >= maxRows ? "max_rows reached" : "time limit reached";
989
+ return new Dictionary<string, object> {
990
+ { "columns", columns ?? new List<object>() }, { "rows", rows }, { "row_count", rows.Count }, { "complete", endReached }, { "reason", reason }, { "gaps", gaps }, { "ms", sw.ElapsedMilliseconds },
991
+ };
992
+ }
993
+
665
994
  static uint SafeDpi(IntPtr h) { try { return Native.GetDpiForWindow(h); } catch { return 96; } }
666
995
 
667
996
  /**
@@ -727,6 +1056,7 @@ namespace AivinGui {
727
1056
  string used;
728
1057
  var segments = Ocr.Read(bmp, lang, out used);
729
1058
  var rects = new List<System.Windows.Rect>();
1059
+ lock (StateLock) { List<System.Windows.Rect> had; if (OcrSnapshots.TryGetValue(snap, out had)) rects = had; }
730
1060
  foreach (var s in segments) {
731
1061
  if (rects.Count >= Math.Max(0, max)) break;
732
1062
  var r = s.Rect;
@@ -830,6 +1160,7 @@ namespace AivinGui {
830
1160
  string action = Str(a, "action") ?? "click";
831
1161
  string nodeId = Str(a, "node_id");
832
1162
  string method = Str(a, "method") ?? "auto";
1163
+ backgroundOnly = method == "background";
833
1164
  inputGraceMs = Int(a, "user_input_grace_ms", 1500);
834
1165
  pendingInputCheck = Bool(a, "check_user_input", true);
835
1166
  userInputCheck = pendingInputCheck;
@@ -875,22 +1206,35 @@ namespace AivinGui {
875
1206
  screenPoint = new Dictionary<string, object> { { "x", (int)Math.Round(sp.X) }, { "y", (int)Math.Round(sp.Y) } };
876
1207
  } catch { }
877
1208
  IntPtr fgBefore = Native.GetForegroundWindow();
1209
+ Native.POINT cursorBefore;
1210
+ bool haveCursor = Native.GetCursorPos(out cursorBefore);
878
1211
  string used = DoAction(action, method, el, window, a);
879
1212
  // Thao tác theo pattern không cần cửa sổ đích ở trên cùng, nhưng nhiều ứng dụng (WinForms qua MSAA) tự lấy focus khi bị SetValue /
880
1213
  // Expand → phím người dùng đang gõ ở cửa sổ khác rơi vào ô của AI (chạy thật 28/10/2026: ô Họ tên bị chèn "ã", "x", "ch"). Trả focus
881
1214
  // về cửa sổ người dùng đang dùng ngay sau thao tác.
882
1215
  bool restored = used != "mouse" && used != "keyboard" && RestoreForeground(fgBefore, window);
1216
+ // Vẫn chưa trả được (hay gặp với ô hỏi của linh vật) mà tiêu điểm đang ở ứng dụng AI vừa thao tác → cách của gui.focus; GuardInput trong đó
1217
+ // bỏ qua bước này khi người dùng đang gõ, để phím Alt không chen vào giữa.
1218
+ IntPtr fgAfter = Native.GetForegroundWindow();
1219
+ if (!restored && used != "mouse" && used != "keyboard" && fgBefore != IntPtr.Zero && fgAfter != fgBefore && Native.IsWindow(fgBefore) && TookForeground(fgAfter, window)) {
1220
+ try { restored = ForceForeground(fgBefore); } catch (GuiError) { }
1221
+ }
883
1222
  // Chạy nền: người dùng đang ở cửa sổ khác → cửa sổ của AI về lại dưới đáy (không chồng lên việc của người dùng).
1223
+ if (used == "mouse" || used == "keyboard") restored = GiveBackRealInput(action, window, fgBefore, haveCursor, cursorBefore);
884
1224
  if (restored || (used != "mouse" && used != "keyboard" && fgBefore != window && window != IntPtr.Zero)) SendToBack(window);
885
1225
  // Pattern actions expose their new state synchronously in most UIA providers. Keep a short grace for
886
1226
  // providers that publish property changes just after returning; real mouse/keyboard still needs longer.
887
- int defaultSettle = used == "mouse" || used == "keyboard" ? 250 : 30;
1227
+ int defaultSettle = used == "mouse" || used == "keyboard" ? 250 : used == "posted" ? 200 : 30;
888
1228
  Thread.Sleep(Math.Max(0, Math.Min(Int(a, "settle_ms", defaultSettle), 3000)));
889
1229
  var res = new Dictionary<string, object> { { "action", action }, { "method", used } };
1230
+ if (window != IntPtr.Zero && Native.IsWindow(window)) res["window_class"] = ClassOf(window);
890
1231
  if (lastMousePoint != null) screenPoint = lastMousePoint;
891
1232
  if (screenPoint != null) res["screen_point"] = screenPoint;
892
1233
  if (restored) res["focus_returned_to_user"] = true;
893
- if (el != null) res["target"] = Live(el);
1234
+ // Nút khởi chạy việc nặng làm luồng giao diện đứng: đọc bằng chứng lúc đó sẽ kẹt theo ứng dụng, nên báo đang bận rồi trả về ngay.
1235
+ bool appBusy = window != IntPtr.Zero && Native.IsWindow(window) && !IsWindowResponsive(window, 1500);
1236
+ if (appBusy) res["app_busy"] = true;
1237
+ if (el != null && !appBusy) res["target"] = Live(el);
894
1238
  IntPtr fg = Native.GetForegroundWindow();
895
1239
  res["foreground"] = WindowInfo(fg, fg);
896
1240
  if (window != IntPtr.Zero) {
@@ -901,7 +1245,7 @@ namespace AivinGui {
901
1245
  if (after != beforeTitle) res["window_title_changed"] = new Dictionary<string, object> { { "from", beforeTitle }, { "to", after } };
902
1246
  }
903
1247
  }
904
- try {
1248
+ if (!appBusy) try {
905
1249
  var fe = AutomationElement.FocusedElement;
906
1250
  if (fe != null) res["focused_element"] = new Dictionary<string, object> { { "role", fe.Current.ControlType.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant() }, { "name", Clip(fe.Current.Name, 120) } };
907
1251
  } catch { }
@@ -930,10 +1274,21 @@ namespace AivinGui {
930
1274
  throw new GuiError("GUI_NO_PATTERN", "Element has no click pattern — retry with method mouse");
931
1275
  }
932
1276
  }
1277
+ if (method == "auto" || method == "background") {
1278
+ string quiet = TryBackgroundClick(el, window, a, 1);
1279
+ if (quiet != null) return quiet;
1280
+ }
933
1281
  MouseAt(el, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1);
934
1282
  return "mouse";
935
1283
  }
936
- case "double_click": MouseAt(el, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 2); return "mouse";
1284
+ case "double_click": {
1285
+ if (method == "auto" || method == "background") {
1286
+ string quiet = TryBackgroundClick(el, window, a, 2);
1287
+ if (quiet != null) return quiet;
1288
+ }
1289
+ MouseAt(el, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 2);
1290
+ return "mouse";
1291
+ }
937
1292
  case "right_click": MouseAt(el, window, a, MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, 1); return "mouse";
938
1293
  case "set_value": {
939
1294
  string text = Str(a, "text") ?? "";
@@ -952,7 +1307,9 @@ namespace AivinGui {
952
1307
  if (allowPattern && TryBackgroundType(el, text)) return "background";
953
1308
  FocusTarget(el, window); TypeText(text, window); return "keyboard";
954
1309
  }
955
- case "key": FocusTarget(el, window); KeyCombo(Str(a, "keys") ?? "", window); return "keyboard";
1310
+ case "key":
1311
+ if ((method == "auto" || method == "background") && TryBackgroundKeys(el, window, Str(a, "keys") ?? "")) return "posted";
1312
+ FocusTarget(el, window); KeyCombo(Str(a, "keys") ?? "", window); return "keyboard";
956
1313
  case "scroll": {
957
1314
  string dir = (Str(a, "direction") ?? "down").ToLowerInvariant();
958
1315
  int amount = Math.Max(1, Math.Min(Int(a, "amount", 3), 30));
@@ -968,6 +1325,7 @@ namespace AivinGui {
968
1325
  return "scroll";
969
1326
  }
970
1327
  }
1328
+ if ((method == "auto" || method == "background") && TryBackgroundScroll(el, window, a, dir, amount)) return "posted";
971
1329
  RequireForeground(window);
972
1330
  var p = PointFor(el, window, a);
973
1331
  AssertPointOnWindow((int)p.X, (int)p.Y, window);
@@ -1097,6 +1455,236 @@ namespace AivinGui {
1097
1455
  return true;
1098
1456
  }
1099
1457
 
1458
+ const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_MOUSEWHEEL = 0x020A, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101;
1459
+ const uint OBJID_CLIENT = 0xFFFFFFFC;
1460
+ const int ROLE_SYSTEM_CELL = 0x1D;
1461
+ const int SELFLAG_TAKEFOCUS = 1, SELFLAG_TAKESELECTION = 2;
1462
+ static readonly HashSet<string> ClassicClasses = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
1463
+ "Button", "Edit", "Static", "ComboBox", "ComboLBox", "ListBox", "#32770", "SysListView32", "SysTreeView32", "SysTabControl32", "SysHeader32",
1464
+ "SysDateTimePick32", "SysMonthCal32", "SysLink", "ToolbarWindow32", "ReBarWindow32", "msctls_statusbar32", "msctls_updown32", "msctls_trackbar32",
1465
+ };
1466
+
1467
+ /**
1468
+ * Chỉ các ứng dụng Windows truyền thống xử lý đủ thông điệp chuột / phím gửi thẳng vào cửa sổ. Chromium, UWP, WPF, DirectUI bỏ qua hoặc xử lý
1469
+ * nửa vời mà không báo gì, nên danh sách này cố tình là danh sách cho phép: không chắc thì để đường chuột thật (có hỏi người dùng).
1470
+ */
1471
+ static bool AcceptsPostedInput(IntPtr h) {
1472
+ string c = ClassOf(h);
1473
+ if (c.StartsWith("WindowsForms10.") || c.StartsWith("Afx") || c.StartsWith("Thunder") || c.StartsWith("RichEdit", StringComparison.OrdinalIgnoreCase)) return true;
1474
+ if (c.Length > 1 && c[0] == 'T' && char.IsUpper(c[1])) return true; // Delphi / C++Builder: TForm1, TDBGrid, TPanel…
1475
+ return ClassicClasses.Contains(c);
1476
+ }
1477
+
1478
+ /** Cửa sổ con sâu nhất tại điểm màn hình, tính theo cây cửa sổ của đích nên không phụ thuộc cửa sổ nào đang che nó. */
1479
+ static IntPtr DeepestChildAt(IntPtr window, int x, int y) {
1480
+ Native.RECT r;
1481
+ if (window == IntPtr.Zero || Native.IsIconic(window) || !Native.GetWindowRect(window, out r)) return IntPtr.Zero;
1482
+ if (x < r.Left || x >= r.Right || y < r.Top || y >= r.Bottom) return IntPtr.Zero;
1483
+ IntPtr cur = window;
1484
+ for (int depth = 0; depth < 30; depth++) {
1485
+ var p = new Native.POINT { X = x, Y = y };
1486
+ Native.ScreenToClient(cur, ref p);
1487
+ IntPtr child = Native.RealChildWindowFromPoint(cur, p);
1488
+ if (child == IntPtr.Zero || child == cur) break;
1489
+ cur = child;
1490
+ }
1491
+ return cur;
1492
+ }
1493
+
1494
+ /** Điểm cần thao tác nền: phần tử đã cuộn khuất hay không có toạ độ thì không đoán. */
1495
+ static bool QuietPoint(AutomationElement el, IntPtr window, Dictionary<string, object> a, out int x, out int y) {
1496
+ x = 0; y = 0;
1497
+ if (window == IntPtr.Zero) return false;
1498
+ try {
1499
+ if (el != null && el.Current.IsOffscreen) return false;
1500
+ var p = PointFor(el, window, a);
1501
+ x = (int)p.X; y = (int)p.Y;
1502
+ return true;
1503
+ } catch (GuiError) { return false; } catch (ElementNotAvailableException) { return false; }
1504
+ }
1505
+
1506
+ /**
1507
+ * Mượn xong thì trả: con trỏ về chỗ cũ, tiêu điểm về cửa sổ người dùng đang dùng. Họ đã cầm lại chuột thì không kéo con trỏ của họ đi; menu AI vừa
1508
+ * mở thì giữ (mất tiêu điểm là menu đóng, bước sau không chọn được).
1509
+ */
1510
+ static bool GiveBackRealInput(string action, IntPtr window, IntPtr fgBefore, bool haveCursor, Native.POINT cursorBefore) {
1511
+ Native.POINT aiCursor;
1512
+ bool haveAi = Native.GetCursorPos(out aiCursor);
1513
+ Thread.Sleep(150); // để ứng dụng nhận xong cú bấm / phím trước khi đổi tiêu điểm
1514
+ Native.POINT now;
1515
+ if (haveCursor && haveAi && Native.GetCursorPos(out now) && now.X == aiCursor.X && now.Y == aiCursor.Y && (now.X != cursorBefore.X || now.Y != cursorBefore.Y)) {
1516
+ Native.SetCursorPos(cursorBefore.X, cursorBefore.Y);
1517
+ }
1518
+ if (action == "right_click" || InMenuMode(window)) return false;
1519
+ IntPtr fg = Native.GetForegroundWindow();
1520
+ if (fgBefore == IntPtr.Zero || fgBefore == window || !Native.IsWindow(fgBefore) || !TookForeground(fg, window)) return false;
1521
+ if (RestoreForeground(fgBefore, window)) return true;
1522
+ if (UserIdleMs() < 300) return false; // cách còn lại nhấn phím Alt, không chen vào lúc họ đang gõ
1523
+ try { return ForceForeground(fgBefore); } catch (GuiError) { return false; }
1524
+ }
1525
+
1526
+ static bool InMenuMode(IntPtr window) {
1527
+ uint pid;
1528
+ var info = new Native.GUITHREADINFO();
1529
+ info.cbSize = (uint)Marshal.SizeOf(info);
1530
+ uint thread = window == IntPtr.Zero ? 0 : Native.GetWindowThreadProcessId(window, out pid);
1531
+ if (thread == 0 || !Native.GetGUIThreadInfo(thread, ref info)) return false;
1532
+ return (info.flags & 0x14) != 0; // GUI_INMENUMODE | GUI_POPUPMENUMODE
1533
+ }
1534
+
1535
+ /**
1536
+ * Bấm không đụng chuột thật: gửi thẳng thông điệp bấm vào cửa sổ con; không được thì dùng lệnh mặc định của MSAA (chọn dòng, ô). WinForms chỉ
1537
+ * coi là cú bấm khi đúng điểm đó không bị cửa sổ khác che (nó tự kiểm WindowFromPoint), nên bị che thì bỏ qua cách gửi thông điệp.
1538
+ * Trả null = không làm được dưới nền, chưa có gì xảy ra.
1539
+ */
1540
+ static string TryBackgroundClick(AutomationElement el, IntPtr window, Dictionary<string, object> a, int times) {
1541
+ int x, y;
1542
+ if (!QuietPoint(el, window, a, out x, out y)) return null;
1543
+ IntPtr target = DeepestChildAt(window, x, y);
1544
+ if (target == IntPtr.Zero) return null;
1545
+ bool exposed = Native.WindowFromPoint(new Native.POINT { X = x, Y = y }) == target;
1546
+ if (AcceptsPostedInput(target) && (exposed || !ClassOf(target).StartsWith("WindowsForms10."))) {
1547
+ PostClick(target, x, y, times);
1548
+ return "posted";
1549
+ }
1550
+ if (times == 1 && TryAccessibleClick(target, x, y)) return "accessible";
1551
+ return null;
1552
+ }
1553
+
1554
+ static void PostClick(IntPtr h, int screenX, int screenY, int times) {
1555
+ var c = new Native.POINT { X = screenX, Y = screenY };
1556
+ Native.ScreenToClient(h, ref c);
1557
+ var lp = new IntPtr(((c.Y & 0xFFFF) << 16) | (c.X & 0xFFFF));
1558
+ var pressed = new IntPtr(1); // MK_LBUTTON
1559
+ Native.PostMessage(h, WM_MOUSEMOVE, IntPtr.Zero, lp);
1560
+ for (int i = 0; i < times; i++) {
1561
+ Native.PostMessage(h, i == 0 ? WM_LBUTTONDOWN : WM_LBUTTONDBLCLK, pressed, lp);
1562
+ Native.PostMessage(h, WM_LBUTTONUP, IntPtr.Zero, lp);
1563
+ }
1564
+ }
1565
+
1566
+ static Accessibility.IAccessible AccessibleClient(IntPtr control) {
1567
+ if (control == IntPtr.Zero) return null;
1568
+ object raw;
1569
+ var iid = new Guid("618736E0-3C3D-11CF-810C-00AA00389B71");
1570
+ if (Native.AccessibleObjectFromWindow(control, OBJID_CLIENT, ref iid, out raw) != 0) return null;
1571
+ return raw as Accessibility.IAccessible;
1572
+ }
1573
+
1574
+ /** Hỏi chính control (accHitTest không xét cửa sổ đang che) rồi chạy lệnh mặc định, không có thì chọn. Trả false nếu control không tự trả lời được. */
1575
+ static bool TryAccessibleClick(IntPtr target, int x, int y) {
1576
+ try {
1577
+ Accessibility.IAccessible client = AccessibleClient(target);
1578
+ if (client == null) return false;
1579
+ Accessibility.IAccessible node = client;
1580
+ object child = 0;
1581
+ // Đi xuống tới mục sâu nhất tại điểm đó (bảng → dòng → ô): chọn ô mới đổi ô hiện hành như một cú bấm, chọn dòng thì không.
1582
+ for (int depth = 0; depth < 5; depth++) {
1583
+ object hit = node.accHitTest(x, y);
1584
+ if (hit is Accessibility.IAccessible && !ReferenceEquals(hit, node)) { node = (Accessibility.IAccessible)hit; child = 0; continue; }
1585
+ if (hit is int && (int)hit != 0) child = hit;
1586
+ break;
1587
+ }
1588
+ if (ReferenceEquals(node, client) && child is int && (int)child == 0) return false; // chỉ trúng nền của control, không phải một mục cụ thể
1589
+ if (!string.IsNullOrEmpty(node.get_accDefaultAction(child))) node.accDoDefaultAction(child);
1590
+ else node.accSelect(SELFLAG_TAKEFOCUS | SELFLAG_TAKESELECTION, child);
1591
+ return true;
1592
+ } catch (COMException) { return false; } catch (ArgumentException) { return false; } catch (InvalidCastException) { return false; } catch (NotImplementedException) { return false; }
1593
+ }
1594
+
1595
+ static bool TryBackgroundScroll(AutomationElement el, IntPtr window, Dictionary<string, object> a, string dir, int amount) {
1596
+ if (dir != "up" && dir != "down") return false;
1597
+ int x, y;
1598
+ if (!QuietPoint(el, window, a, out x, out y)) return false;
1599
+ IntPtr target = DeepestChildAt(window, x, y);
1600
+ if (target == IntPtr.Zero || !AcceptsPostedInput(target)) return false;
1601
+ int notch = dir == "up" ? 120 : -120;
1602
+ var lp = new IntPtr(((y & 0xFFFF) << 16) | (x & 0xFFFF));
1603
+ for (int i = 0; i < amount; i++) Native.PostMessage(target, WM_MOUSEWHEEL, new IntPtr(notch << 16), lp);
1604
+ return true;
1605
+ }
1606
+
1607
+ const uint WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_UNDO = 0x0304, EM_SETSEL = 0x00B1, WM_COMMAND = 0x0111, WM_CLOSE = 0x0010, MF_BYPOSITION = 0x400, MF_GRAYED = 1, MF_DISABLED = 2;
1608
+
1609
+ static bool IsTextControl(IntPtr h) {
1610
+ string c = ClassOf(h);
1611
+ return c.IndexOf("EDIT", StringComparison.OrdinalIgnoreCase) >= 0 || c.IndexOf("Memo", StringComparison.Ordinal) >= 0 || c.IndexOf("TextBox", StringComparison.Ordinal) >= 0;
1612
+ }
1613
+
1614
+ /** "Ctrl + Shift+S" → "ctrl+s+shift": thứ tự phím bổ trợ khác nhau vẫn so được. */
1615
+ static string NormalizeChord(string s) {
1616
+ var parts = new List<string>(s.ToLowerInvariant().Replace(" ", "").Split(new[] { '+' }, StringSplitOptions.RemoveEmptyEntries));
1617
+ parts.Sort(StringComparer.Ordinal);
1618
+ return string.Join("+", parts);
1619
+ }
1620
+
1621
+ /** Lệnh trong menu của cửa sổ có ghi đúng phím tắt này (Ctrl+S…); mục đang mờ thì coi như không có. */
1622
+ static bool FindMenuCommand(IntPtr menu, string chord, int depth, out uint id) {
1623
+ id = 0;
1624
+ if (menu == IntPtr.Zero || depth > 4) return false;
1625
+ int count = Native.GetMenuItemCount(menu);
1626
+ for (int i = 0; i < count; i++) {
1627
+ IntPtr sub = Native.GetSubMenu(menu, i);
1628
+ if (sub != IntPtr.Zero) { if (FindMenuCommand(sub, chord, depth + 1, out id)) return true; continue; }
1629
+ var sb = new StringBuilder(256);
1630
+ if (Native.GetMenuString(menu, (uint)i, sb, sb.Capacity, MF_BYPOSITION) <= 0) continue;
1631
+ string text = sb.ToString();
1632
+ int tab = text.LastIndexOf('\t');
1633
+ if (tab < 0 || NormalizeChord(text.Substring(tab + 1)) != chord) continue;
1634
+ if ((Native.GetMenuState(menu, (uint)i, MF_BYPOSITION) & (MF_GRAYED | MF_DISABLED)) != 0) return false;
1635
+ id = Native.GetMenuItemID(menu, i);
1636
+ return id != 0xFFFFFFFF;
1637
+ }
1638
+ return false;
1639
+ }
1640
+
1641
+ /** Một phím tắt thành thông điệp tương đương; chưa gửi gì. null = phải dùng phím thật. */
1642
+ static Action ChordAsCommand(string combo, IntPtr target, IntPtr window) {
1643
+ string chord = NormalizeChord(combo);
1644
+ if (target != IntPtr.Zero && IsTextControl(target)) {
1645
+ uint msg = chord == "c+ctrl" ? WM_COPY : chord == "ctrl+x" ? WM_CUT : chord == "ctrl+v" ? WM_PASTE : chord == "ctrl+z" ? WM_UNDO : 0;
1646
+ if (msg != 0) return () => Native.PostMessage(target, msg, IntPtr.Zero, IntPtr.Zero);
1647
+ if (chord == "a+ctrl") return () => Native.PostMessage(target, EM_SETSEL, IntPtr.Zero, new IntPtr(-1));
1648
+ }
1649
+ if (chord == "alt+f4") return () => Native.PostMessage(window, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
1650
+ uint id;
1651
+ if (FindMenuCommand(Native.GetMenu(window), chord, 0, out id)) return () => Native.PostMessage(window, WM_COMMAND, new IntPtr(id), IntPtr.Zero);
1652
+ return null;
1653
+ }
1654
+
1655
+ /** Phím đơn gửi thẳng vào ô đích; tổ hợp có Ctrl / Shift / Alt đổi thành lệnh tương đương (ứng dụng đọc trạng thái phím thật nên không gửi phím được). Được cả chuỗi mới gửi. */
1656
+ static bool TryBackgroundKeys(AutomationElement el, IntPtr window, string spec) {
1657
+ if (window == IntPtr.Zero || spec.Length == 0) return false;
1658
+ IntPtr target = OwnHandle(el);
1659
+ if (el == null) {
1660
+ uint pid;
1661
+ var info = new Native.GUITHREADINFO();
1662
+ info.cbSize = (uint)Marshal.SizeOf(info);
1663
+ uint thread = Native.GetWindowThreadProcessId(window, out pid);
1664
+ if (thread == 0 || !Native.GetGUIThreadInfo(thread, ref info)) return false;
1665
+ target = info.hwndFocus;
1666
+ }
1667
+ // Không có ô đích (cửa sổ đang ở nền, chưa có ô nào được focus): phím đơn không biết gửi vào đâu, nhưng lệnh trong menu thì vẫn được.
1668
+ if (target != IntPtr.Zero && (!BelongsTo(target, window) || !AcceptsPostedInput(target))) target = IntPtr.Zero;
1669
+ var steps = new List<Action>();
1670
+ foreach (string raw in spec.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) {
1671
+ if (raw.Contains("+")) {
1672
+ Action cmd = ChordAsCommand(raw, target, window);
1673
+ if (cmd == null) return false;
1674
+ steps.Add(cmd);
1675
+ continue;
1676
+ }
1677
+ ushort vk;
1678
+ if (target == IntPtr.Zero || !Keys.TryGetValue(raw, out vk) || vk == 0x11 || vk == 0x10 || vk == 0x12 || vk == 0x5B) return false;
1679
+ steps.Add(() => {
1680
+ Native.PostMessage(target, WM_KEYDOWN, new IntPtr(vk), new IntPtr(1));
1681
+ Native.PostMessage(target, WM_KEYUP, new IntPtr(vk), new IntPtr(unchecked((int)0xC0000001)));
1682
+ });
1683
+ }
1684
+ foreach (Action step in steps) step();
1685
+ return true;
1686
+ }
1687
+
1100
1688
  /** Phím thật: cửa sổ đích phải lên được trên cùng (không thì GUI_FOCUS_LOST, không gõ), rồi focus phần tử. */
1101
1689
  static void FocusTarget(AutomationElement el, IntPtr window) {
1102
1690
  RequireForeground(window);
@@ -1137,18 +1725,20 @@ namespace AivinGui {
1137
1725
  if (IsCancelled(reqId)) throw new GuiError("CANCELLED", "Wait cancelled");
1138
1726
  bool alive = h == IntPtr.Zero || Native.IsWindow(h);
1139
1727
  Dictionary<string, object> match = null;
1728
+ bool incomplete = false;
1140
1729
  if (windowLevel) {
1141
1730
  if (h != IntPtr.Zero) {
1142
1731
  if (alive && WindowText(h).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) match = WindowInfo(h, Native.GetForegroundWindow());
1143
1732
  } else {
1144
- foreach (Dictionary<string, object> info in ListWindows(false)) {
1733
+ foreach (Dictionary<string, object> info in ListWindows(true)) { // gồm cả hộp thoại con: chờ "Save as" là việc hay gặp nhất
1145
1734
  if (Convert.ToString(info["title"]).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) { match = info; break; }
1146
1735
  }
1147
1736
  }
1148
1737
  } else if (alive) {
1149
- match = FindElement(h, name, aid, role);
1738
+ match = FindElement(h, name, aid, role, ref incomplete);
1150
1739
  }
1151
- if (gone ? match == null : match != null) {
1740
+ // Chưa duyệt xong cây (hết ngân sách / ứng dụng đang bận) thì chưa thể kết luận phần tử đã mất.
1741
+ if (gone ? (match == null && !incomplete) : match != null) {
1152
1742
  var res = new Dictionary<string, object> { { "met", true }, { "until", gone ? "gone" : "appears" }, { "waited_ms", sw.ElapsedMilliseconds } };
1153
1743
  if (match != null) res["match"] = match;
1154
1744
  if (!alive) res["window_closed"] = true;
@@ -1166,21 +1756,28 @@ namespace AivinGui {
1166
1756
  }
1167
1757
 
1168
1758
  /** Phần tử đầu tiên khớp (AutomationId trùng hẳn, hoặc tên chứa chữ — không phân biệt hoa thường), có lọc vai trò. */
1169
- static Dictionary<string, object> FindElement(IntPtr h, string name, string aid, string role) {
1170
- if (!IsWindowResponsive(h, 300)) return null;
1759
+ static Dictionary<string, object> FindElement(IntPtr h, string name, string aid, string role, ref bool incomplete) {
1760
+ if (!IsWindowResponsive(h, 300)) { incomplete = true; return null; }
1171
1761
  AutomationElement root;
1172
1762
  try { root = AutomationElement.FromHandle(h); } catch { return null; }
1173
1763
  var cache = new CacheRequest();
1174
1764
  cache.Add(AutomationElement.NameProperty); cache.Add(AutomationElement.ControlTypeProperty); cache.Add(AutomationElement.AutomationIdProperty);
1175
1765
  cache.Add(AutomationElement.IsOffscreenProperty);
1176
- cache.AutomationElementMode = AutomationElementMode.None;
1177
- Condition cond = string.IsNullOrEmpty(aid) ? Condition.TrueCondition : new PropertyCondition(AutomationElement.AutomationIdProperty, aid);
1178
- AutomationElementCollection all;
1179
- try { using (cache.Activate()) { all = root.FindAll(TreeScope.Descendants, cond); } } catch (ElementNotAvailableException) { return null; }
1180
- foreach (AutomationElement e in all) {
1766
+ // Đi theo tầng với trần thời gian, không FindAll(Descendants): trên cửa sổ có bảng dài một lượt hỏi mất hàng chục giây và không huỷ được.
1767
+ var walker = new TreeWalker(Automation.ControlViewCondition);
1768
+ var sw = Stopwatch.StartNew();
1769
+ try { using (cache.Activate()) { root = root.GetUpdatedCache(cache); } } catch (ElementNotAvailableException) { return null; }
1770
+ var queue = new Queue<AutomationElement>();
1771
+ queue.Enqueue(root);
1772
+ bool cut = false;
1773
+ while (queue.Count > 0) {
1774
+ if (sw.ElapsedMilliseconds >= FIND_ELEMENT_BUDGET_MS) { incomplete = true; return null; }
1775
+ AutomationElement e = queue.Dequeue();
1181
1776
  string n = Cached(e, AutomationElement.NameProperty) as string ?? "";
1182
1777
  var ct = Cached(e, AutomationElement.ControlTypeProperty) as ControlType;
1183
1778
  string r = ct == null ? "" : ct.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant();
1779
+ foreach (AutomationElement k in ChildrenOf(e, r, cache, walker, sw, FIND_ELEMENT_BUDGET_MS, ref cut)) queue.Enqueue(k);
1780
+ if (!string.IsNullOrEmpty(aid) && !string.Equals(Cached(e, AutomationElement.AutomationIdProperty) as string, aid, StringComparison.Ordinal)) continue;
1184
1781
  if (!string.IsNullOrEmpty(name) && n.IndexOf(name, StringComparison.OrdinalIgnoreCase) < 0) continue;
1185
1782
  if (!string.IsNullOrEmpty(role) && !string.Equals(r, role, StringComparison.OrdinalIgnoreCase)) continue;
1186
1783
  if (true.Equals(Cached(e, AutomationElement.IsOffscreenProperty)) && string.IsNullOrEmpty(aid)) continue;
@@ -1513,7 +2110,7 @@ export const WINDOWS_HOST_PS1 = String.raw`
1513
2110
  $ErrorActionPreference = 'Stop'
1514
2111
  $dll = $env:AIVIN_GUI_DLL
1515
2112
  $src = $env:AIVIN_GUI_SRC
1516
- $refs = @('UIAutomationClient', 'UIAutomationTypes', 'WindowsBase', 'System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions')
2113
+ $refs = @('UIAutomationClient', 'UIAutomationTypes', 'WindowsBase', 'System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions', 'Accessibility')
1517
2114
  if ($dll -and (Test-Path -LiteralPath $dll)) {
1518
2115
  Add-Type -Path $dll
1519
2116
  } else {