@aivin-labs/cli 1.0.8 → 1.0.13

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.
Files changed (63) hide show
  1. package/README.md +41 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1979 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +187 -37
  9. package/bin/lib/remote/callLedger.mjs +74 -15
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +174 -11
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +293 -0
  15. package/bin/lib/remote/constants.mjs +78 -0
  16. package/bin/lib/remote/dailyBrowser.mjs +9 -3
  17. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  18. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  19. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  20. package/bin/lib/remote/desktop/index.mjs +309 -0
  21. package/bin/lib/remote/desktop/linux.mjs +144 -0
  22. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
  23. package/bin/lib/remote/desktop/mac.mjs +187 -0
  24. package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
  25. package/bin/lib/remote/desktop/strings.mjs +74 -0
  26. package/bin/lib/remote/desktop/traySource.mjs +541 -0
  27. package/bin/lib/remote/deviceProfile.mjs +1 -0
  28. package/bin/lib/remote/docText.mjs +86 -1
  29. package/bin/lib/remote/fileIndexer.mjs +757 -399
  30. package/bin/lib/remote/folderRules.mjs +140 -0
  31. package/bin/lib/remote/gui/index.mjs +208 -18
  32. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  33. package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
  34. package/bin/lib/remote/idempotency.mjs +50 -21
  35. package/bin/lib/remote/localPolicy.mjs +17 -4
  36. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  37. package/bin/lib/remote/mascot/ask.mjs +768 -0
  38. package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
  39. package/bin/lib/remote/mascot/assets.mjs +825 -216
  40. package/bin/lib/remote/mascot/bot.mjs +397 -0
  41. package/bin/lib/remote/mascot/hostSource.mjs +500 -103
  42. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  43. package/bin/lib/remote/mascot/index.mjs +199 -28
  44. package/bin/lib/remote/mascot/labels.mjs +2 -3
  45. package/bin/lib/remote/mascot/rigSource.mjs +614 -0
  46. package/bin/lib/remote/mascot/strings.mjs +204 -18
  47. package/bin/lib/remote/mascot/ui.mjs +104 -0
  48. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  49. package/bin/lib/remote/meeting/index.mjs +415 -0
  50. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  51. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  52. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  53. package/bin/lib/remote/osSearch.mjs +107 -0
  54. package/bin/lib/remote/sqliteDb.mjs +51 -0
  55. package/bin/lib/remote/tabGroups.mjs +209 -0
  56. package/bin/lib/remote/toolHandlers.mjs +788 -726
  57. package/bin/lib/remoteControl.mjs +26 -26
  58. package/docs/AIVIN_MASCOT.md +130 -0
  59. package/docs/CLI.md +1504 -1353
  60. package/docs/media/aivin-mascot-live.gif +0 -0
  61. package/docs/media/aivin-mascot-live.png +0 -0
  62. package/docs/media/aivin-remote-architecture.svg +102 -0
  63. package/package.json +71 -71
@@ -84,9 +84,15 @@ namespace AivinGui {
84
84
  const uint KEYEVENTF_EXTENDEDKEY = 0x1, KEYEVENTF_KEYUP = 0x2, KEYEVENTF_UNICODE = 0x4;
85
85
 
86
86
  static readonly JavaScriptSerializer Json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue, RecursionLimit = 200 };
87
+ static readonly object OutputLock = new object();
88
+ static readonly object StateLock = new object();
89
+ static readonly HashSet<string> CancelledIds = new HashSet<string>();
90
+ static readonly HashSet<string> ActiveWaits = new HashSet<string>();
87
91
  /** Ảnh chụp của lần observe: node_id = "<snap>.<idx>" → phần tử. Giữ vài lần gần nhất, cũ hơn → GUI_STALE_NODE. */
88
92
  static readonly Dictionary<int, Dictionary<int, AutomationElement>> Snapshots = new Dictionary<int, Dictionary<int, AutomationElement>>();
89
93
  static readonly Dictionary<int, IntPtr> SnapshotWindow = new Dictionary<int, IntPtr>();
94
+ /** Chữ OCR của lần observe: node_id = "<snap>.t<k>" → khung chữ (pixel, so với góc trái trên cửa sổ). */
95
+ static readonly Dictionary<int, List<System.Windows.Rect>> OcrSnapshots = new Dictionary<int, List<System.Windows.Rect>>();
90
96
  static int snapSeq = 0;
91
97
  const int KEEP_SNAPSHOTS = 6;
92
98
  /** Mốc lần cuối chính tiến trình này phát input (chuột / phím) — để phân biệt với input của người dùng. */
@@ -116,32 +122,71 @@ namespace AivinGui {
116
122
  t.Join();
117
123
  }
118
124
 
125
+ static void WriteLineSafe(StreamWriter output, Dictionary<string, object> res) {
126
+ string line = Json.Serialize(res);
127
+ lock (OutputLock) { output.WriteLine(line); }
128
+ }
129
+
130
+ static bool IsCancelled(string reqId) {
131
+ if (string.IsNullOrEmpty(reqId)) return false;
132
+ lock (CancelledIds) { return CancelledIds.Contains(reqId); }
133
+ }
134
+
135
+ static void ExecuteAndWrite(StreamWriter output, object id, string op, Dictionary<string, object> args) {
136
+ var res = new Dictionary<string, object>();
137
+ try {
138
+ res["result"] = Dispatch(op, args);
139
+ res["ok"] = true;
140
+ } catch (GuiError e) {
141
+ res["ok"] = false; res["code"] = e.Code; res["error"] = e.Message;
142
+ } catch (ElementNotAvailableException e) {
143
+ res["ok"] = false; res["code"] = "GUI_STALE_NODE"; res["error"] = "Element is gone: " + e.Message;
144
+ } catch (Exception e) {
145
+ res["ok"] = false; res["code"] = "EXECUTION_FAILED"; res["error"] = e.GetType().Name + ": " + e.Message;
146
+ }
147
+ res["id"] = id;
148
+ WriteLineSafe(output, res);
149
+ }
150
+
119
151
  static void Loop() {
120
152
  var input = new StreamReader(Console.OpenStandardInput(), new UTF8Encoding(false));
121
153
  var output = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false));
122
154
  output.AutoFlush = true;
123
- output.WriteLine(Json.Serialize(new Dictionary<string, object> { { "ready", true } }));
155
+ WriteLineSafe(output, new Dictionary<string, object> { { "ready", true } });
124
156
  string line;
125
157
  while ((line = input.ReadLine()) != null) {
126
158
  if (line.Trim().Length == 0) continue;
127
159
  object id = null;
128
- var res = new Dictionary<string, object>();
129
160
  try {
130
161
  var req = (Dictionary<string, object>)Json.DeserializeObject(line);
162
+ string cancelId = Str(req, "cancel");
163
+ if (!string.IsNullOrEmpty(cancelId)) {
164
+ lock (CancelledIds) { if (ActiveWaits.Contains(cancelId)) CancelledIds.Add(cancelId); }
165
+ continue;
166
+ }
131
167
  id = Get(req, "id");
168
+ string op = Str(req, "op");
132
169
  var args = Get(req, "args") as Dictionary<string, object>;
133
170
  if (args == null) args = new Dictionary<string, object>();
134
- res["result"] = Dispatch(Str(req, "op"), args);
135
- res["ok"] = true;
136
- } catch (GuiError e) {
137
- res["ok"] = false; res["code"] = e.Code; res["error"] = e.Message;
138
- } catch (ElementNotAvailableException e) {
139
- res["ok"] = false; res["code"] = "GUI_STALE_NODE"; res["error"] = "Element is gone: " + e.Message;
171
+ args["__req_id"] = id == null ? null : Convert.ToString(id);
172
+ // wait_for / ping / idle chỉ đọc trạng thái → chạy trên luồng MTA riêng để wait_for (chờ tới 60s) không chặn observe / act / windows.
173
+ if (op == "wait_for" || op == "ping" || op == "idle") {
174
+ object reqId = id;
175
+ string reqOp = op;
176
+ var reqArgs = args;
177
+ string reqIdStr = id == null ? null : Convert.ToString(id);
178
+ if (op == "wait_for" && !string.IsNullOrEmpty(reqIdStr)) { lock (CancelledIds) { ActiveWaits.Add(reqIdStr); } }
179
+ var worker = new Thread(delegate () { try { ExecuteAndWrite(output, reqId, reqOp, reqArgs); } finally { if (reqOp == "wait_for" && !string.IsNullOrEmpty(reqIdStr)) { lock (CancelledIds) { ActiveWaits.Remove(reqIdStr); CancelledIds.Remove(reqIdStr); } } } });
180
+ worker.IsBackground = true;
181
+ worker.SetApartmentState(ApartmentState.MTA);
182
+ worker.Start();
183
+ continue;
184
+ }
185
+ ExecuteAndWrite(output, id, op, args);
140
186
  } catch (Exception e) {
141
- res["ok"] = false; res["code"] = "EXECUTION_FAILED"; res["error"] = e.GetType().Name + ": " + e.Message;
187
+ var errRes = new Dictionary<string, object> { { "id", id }, { "ok", false }, { "code", "EXECUTION_FAILED" }, { "error", e.GetType().Name + ": " + e.Message } };
188
+ WriteLineSafe(output, errRes);
142
189
  }
143
- res["id"] = id;
144
- output.WriteLine(Json.Serialize(res));
145
190
  }
146
191
  }
147
192
 
@@ -160,6 +205,7 @@ namespace AivinGui {
160
205
  return new Dictionary<string, object> { { "sent_to_back", true }, { "focus_returned_to_user", restored } };
161
206
  }
162
207
  case "act": return Act(a);
208
+ case "wait_for": return WaitFor(a);
163
209
  case "office": return Office.Run(a);
164
210
  case "idle": return new Dictionary<string, object> { { "idle_ms", IdleMs() }, { "user_idle_ms", UserIdleMs() } };
165
211
  default: throw new GuiError("INVALID_ARGS", "Unknown op: " + op);
@@ -170,6 +216,7 @@ namespace AivinGui {
170
216
 
171
217
  static object Get(Dictionary<string, object> d, string k) { object v; return d != null && d.TryGetValue(k, out v) ? v : null; }
172
218
  static string Str(Dictionary<string, object> d, string k) { var v = Get(d, k); return v == null ? null : Convert.ToString(v); }
219
+ static long Long(Dictionary<string, object> d, string k) { var v = Get(d, k); try { return v == null ? 0 : Convert.ToInt64(v); } catch { return 0; } }
173
220
  static int Int(Dictionary<string, object> d, string k, int def) { var v = Get(d, k); try { return v == null ? def : Convert.ToInt32(v); } catch { return def; } }
174
221
  static double Dbl(Dictionary<string, object> d, string k, double def) { var v = Get(d, k); try { return v == null ? def : Convert.ToDouble(v); } catch { return def; } }
175
222
  static bool Bool(Dictionary<string, object> d, string k, bool def) { var v = Get(d, k); try { return v == null ? def : Convert.ToBoolean(v); } catch { return def; } }
@@ -276,7 +323,17 @@ namespace AivinGui {
276
323
  }
277
324
  throw new GuiError("NOT_FOUND", "No window matches: " + w);
278
325
  }
279
- return Native.GetForegroundWindow();
326
+ // Đang focus là chính linh vật (chủ máy vừa bấm vào ô hỏi) → cửa sổ họ đang dùng ngay trước đó ("fallback"), không thì không có.
327
+ IntPtr fg = Native.GetForegroundWindow();
328
+ long avoid = Long(a, "avoid_pid");
329
+ if (avoid > 0 && fg != IntPtr.Zero) {
330
+ uint fgPid; Native.GetWindowThreadProcessId(fg, out fgPid);
331
+ if (fgPid == avoid) {
332
+ IntPtr back = ParseWindow(Str(a, "fallback"));
333
+ return back != IntPtr.Zero && Native.IsWindow(back) ? back : IntPtr.Zero;
334
+ }
335
+ }
336
+ return fg;
280
337
  }
281
338
 
282
339
  /** Đẩ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. */
@@ -409,6 +466,7 @@ namespace AivinGui {
409
466
  int maxNodes = Math.Max(20, Math.Min(Int(a, "max_nodes", 300), 1500));
410
467
  int maxDepth = Math.Max(2, Math.Min(Int(a, "max_depth", 25), 60));
411
468
  var sw = Stopwatch.StartNew();
469
+ AssertWindowResponsive(h);
412
470
  AutomationElement root = AutomationElement.FromHandle(h);
413
471
  var cache = BuildCache();
414
472
  var nodes = new List<object>();
@@ -444,12 +502,14 @@ namespace AivinGui {
444
502
  } catch { continue; }
445
503
  foreach (AutomationElement k in kids) queue.Enqueue(new KeyValuePair<AutomationElement, int>(k, item.Value + 1));
446
504
  }
447
- Snapshots[snap] = map;
448
- SnapshotWindow[snap] = h;
449
- while (Snapshots.Count > KEEP_SNAPSHOTS) {
450
- int oldest = int.MaxValue;
451
- foreach (var k in Snapshots.Keys) if (k < oldest) oldest = k;
452
- Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest);
505
+ lock (StateLock) {
506
+ Snapshots[snap] = map;
507
+ SnapshotWindow[snap] = h;
508
+ while (Snapshots.Count > KEEP_SNAPSHOTS) {
509
+ int oldest = int.MaxValue;
510
+ foreach (var k in Snapshots.Keys) if (k < oldest) oldest = k;
511
+ Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest); OcrSnapshots.Remove(oldest);
512
+ }
453
513
  }
454
514
  // 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ị.
455
515
  string quality = (interactive >= 3 && named >= 5) ? "good" : "poor";
@@ -459,45 +519,82 @@ namespace AivinGui {
459
519
  { "dpi", (long)SafeDpi(h) },
460
520
  };
461
521
  bool wantImage = Bool(a, "include_image", false) || (quality == "poor" && Bool(a, "image_when_poor", true));
462
- if (wantImage) {
522
+ // 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
523
+ // ở 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.
524
+ bool wantOcr = Bool(a, "ocr", quality == "poor");
525
+ if (wantImage || wantOcr) {
463
526
  var sw2 = Stopwatch.StartNew();
464
- res["image"] = CaptureWindow(h, Int(a, "image_max_width", 1366), Int(a, "image_quality", 70));
465
- res["image_ms"] = sw2.ElapsedMilliseconds;
527
+ using (var bmp = GrabWindow(h)) {
528
+ if (wantImage) {
529
+ res["image"] = EncodeImage(bmp, Int(a, "image_max_width", 1366), Int(a, "image_quality", 70));
530
+ res["image_ms"] = sw2.ElapsedMilliseconds;
531
+ }
532
+ if (wantOcr) AddOcrNodes(res, nodes, snap, bmp, Str(a, "ocr_lang"), Int(a, "ocr_max_nodes", 200));
533
+ }
466
534
  }
467
535
  return res;
468
536
  }
469
537
 
470
538
  static uint SafeDpi(IntPtr h) { try { return Native.GetDpiForWindow(h); } catch { return 96; } }
471
539
 
472
- static Dictionary<string, object> CaptureWindow(IntPtr h, int maxWidth, int quality) {
540
+ static Bitmap GrabWindow(IntPtr h) {
473
541
  Native.RECT r; Native.GetWindowRect(h, out r);
474
542
  int w = Math.Max(1, r.Right - r.Left), ht = Math.Max(1, r.Bottom - r.Top);
475
- using (var bmp = new Bitmap(w, ht, PixelFormat.Format32bppArgb)) {
476
- bool ok = false;
477
- using (var g = Graphics.FromImage(bmp)) {
478
- IntPtr hdc = g.GetHdc();
479
- try { ok = Native.PrintWindow(h, hdc, 2); } finally { g.ReleaseHdc(hdc); }
480
- // PrintWindow trả ảnh đen với vài ứng dụng GPU → chụp vùng màn hình (cửa sổ phải đang hiện trên cùng).
481
- if (!ok || IsMostlyBlack(bmp)) g.CopyFromScreen(r.Left, r.Top, 0, 0, new Size(w, ht));
543
+ var bmp = new Bitmap(w, ht, PixelFormat.Format32bppArgb);
544
+ bool ok = false;
545
+ using (var g = Graphics.FromImage(bmp)) {
546
+ IntPtr hdc = g.GetHdc();
547
+ try { ok = Native.PrintWindow(h, hdc, 2); } finally { g.ReleaseHdc(hdc); }
548
+ // PrintWindow trả ảnh đen với vài ứng dụng GPU → chụp vùng màn hình (cửa sổ phải đang hiện trên cùng).
549
+ if (!ok || IsMostlyBlack(bmp)) g.CopyFromScreen(r.Left, r.Top, 0, 0, new Size(w, ht));
550
+ }
551
+ return bmp;
552
+ }
553
+
554
+ static Dictionary<string, object> EncodeImage(Bitmap bmp, int maxWidth, int quality) {
555
+ int w = bmp.Width, ht = bmp.Height;
556
+ double scale = w > maxWidth ? (double)maxWidth / w : 1.0;
557
+ int ow = Math.Max(1, (int)(w * scale)), oh = Math.Max(1, (int)(ht * scale));
558
+ using (var outBmp = new Bitmap(ow, oh, PixelFormat.Format24bppRgb)) {
559
+ using (var g2 = Graphics.FromImage(outBmp)) {
560
+ g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
561
+ g2.DrawImage(bmp, 0, 0, ow, oh);
482
562
  }
483
- double scale = w > maxWidth ? (double)maxWidth / w : 1.0;
484
- int ow = Math.Max(1, (int)(w * scale)), oh = Math.Max(1, (int)(ht * scale));
485
- using (var outBmp = new Bitmap(ow, oh, PixelFormat.Format24bppRgb)) {
486
- using (var g2 = Graphics.FromImage(outBmp)) {
487
- g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
488
- g2.DrawImage(bmp, 0, 0, ow, oh);
489
- }
490
- var codec = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.MimeType == "image/jpeg");
491
- var ep = new EncoderParameters(1);
492
- ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Max(30, Math.Min(quality, 95)));
493
- using (var ms = new MemoryStream()) {
494
- outBmp.Save(ms, codec, ep);
495
- return new Dictionary<string, object> { { "mime", "image/jpeg" }, { "base64", Convert.ToBase64String(ms.ToArray()) }, { "width", ow }, { "height", oh }, { "scale", scale } };
496
- }
563
+ var codec = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.MimeType == "image/jpeg");
564
+ var ep = new EncoderParameters(1);
565
+ ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Max(30, Math.Min(quality, 95)));
566
+ using (var ms = new MemoryStream()) {
567
+ outBmp.Save(ms, codec, ep);
568
+ return new Dictionary<string, object> { { "mime", "image/jpeg" }, { "base64", Convert.ToBase64String(ms.ToArray()) }, { "width", ow }, { "height", oh }, { "scale", scale } };
497
569
  }
498
570
  }
499
571
  }
500
572
 
573
+ static void AddOcrNodes(Dictionary<string, object> res, List<object> nodes, int snap, Bitmap bmp, string lang, int max) {
574
+ var sw = Stopwatch.StartNew();
575
+ try {
576
+ string used;
577
+ var segments = Ocr.Read(bmp, lang, out used);
578
+ var rects = new List<System.Windows.Rect>();
579
+ foreach (var s in segments) {
580
+ if (rects.Count >= Math.Max(0, max)) break;
581
+ var r = s.Rect;
582
+ nodes.Add(new Dictionary<string, object> {
583
+ { "id", snap + ".t" + rects.Count }, { "role", "text" }, { "name", s.Text }, { "source", "ocr" },
584
+ { "rect", new Dictionary<string, object> { { "x", (int)r.X }, { "y", (int)r.Y }, { "w", (int)r.Width }, { "h", (int)r.Height } } },
585
+ });
586
+ rects.Add(r);
587
+ }
588
+ lock (StateLock) { OcrSnapshots[snap] = rects; }
589
+ var info = new Dictionary<string, object> { { "lang", used }, { "count", rects.Count }, { "ms", sw.ElapsedMilliseconds } };
590
+ if (!used.StartsWith("vi", StringComparison.OrdinalIgnoreCase)) info["hint"] = "No Vietnamese OCR on this PC — Vietnamese text loses its accents. Settings → Time & language → Language → add Vietnamese (Optical character recognition)";
591
+ res["ocr"] = info;
592
+ res["node_count"] = nodes.Count;
593
+ } catch (Exception e) {
594
+ res["ocr"] = new Dictionary<string, object> { { "error", (e is GuiError ? e.Message : e.GetType().Name + ": " + e.Message) } };
595
+ }
596
+ }
597
+
501
598
  static bool IsMostlyBlack(Bitmap b) {
502
599
  int dark = 0, total = 0;
503
600
  for (int x = 0; x < b.Width; x += Math.Max(1, b.Width / 16)) {
@@ -518,10 +615,12 @@ namespace AivinGui {
518
615
  int snap, idx;
519
616
  if (!int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 1), out idx)) throw new GuiError("INVALID_ARGS", "Bad node id: " + nodeId);
520
617
  Dictionary<int, AutomationElement> map;
521
- if (!Snapshots.TryGetValue(snap, out map)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
522
618
  AutomationElement e;
523
- if (!map.TryGetValue(idx, out e)) throw new GuiError("NOT_FOUND", "No node " + nodeId);
524
- window = SnapshotWindow[snap];
619
+ lock (StateLock) {
620
+ if (!Snapshots.TryGetValue(snap, out map)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
621
+ if (!map.TryGetValue(idx, out e)) throw new GuiError("NOT_FOUND", "No node " + nodeId);
622
+ window = SnapshotWindow[snap];
623
+ }
525
624
  return e;
526
625
  }
527
626
 
@@ -567,7 +666,27 @@ namespace AivinGui {
567
666
  if (!InteractiveDesktop()) throw new GuiError("GUI_LOCKED", "The screen is locked or a secure prompt is showing");
568
667
  AutomationElement el = null;
569
668
  IntPtr window = IntPtr.Zero;
570
- if (!string.IsNullOrEmpty(nodeId)) el = NodeOf(nodeId, out window);
669
+ ocrPoint = null;
670
+ if (!string.IsNullOrEmpty(nodeId) && nodeId.Contains(".t")) {
671
+ ocrPoint = OcrPointOf(nodeId, out window);
672
+ if (action != "click" && action != "double_click" && action != "right_click" && action != "set_value" && action != "type") {
673
+ throw new GuiError("INVALID_ARGS", "Text read from the screenshot (OCR) supports click / double_click / right_click / set_value / type only");
674
+ }
675
+ // Khi điền chữ vào nhãn OCR (vd "Họ tên:", "Số tiền"): tìm ô nhập thật (Edit / ComboBox / Document) nằm ngay bên phải hoặc ngay bên
676
+ // dưới nhãn trong cùng cửa sổ để dùng ValuePattern / WM_SETTEXT chạy nền. Chỉ khi không có ô nhập UIA nào (ứng dụng vẽ tay hoàn toàn)
677
+ // mới bấm vào toạ độ chữ rồi gõ bàn phím.
678
+ if (action == "set_value" || action == "type") {
679
+ AutomationElement nearby = FindNearbyInputForOcr(nodeId, window);
680
+ if (nearby != null) {
681
+ el = nearby;
682
+ ocrPoint = null;
683
+ } else {
684
+ MouseAt(null, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1);
685
+ method = "mouse";
686
+ }
687
+ }
688
+ }
689
+ else if (!string.IsNullOrEmpty(nodeId)) el = NodeOf(nodeId, out window);
571
690
  else window = ResolveWindow(a);
572
691
  string beforeTitle = window == IntPtr.Zero ? "" : WindowText(window);
573
692
  if (el != null) {
@@ -575,6 +694,7 @@ namespace AivinGui {
575
694
  try { isPassword = el.Current.IsPassword; } catch (ElementNotAvailableException) { throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is gone — observe again"); }
576
695
  if (isPassword && (action == "type" || action == "set_value")) throw new GuiError("GUI_PASSWORD_FIELD", "Typing into a password field is not allowed — ask the user to type it");
577
696
  }
697
+ AssertWindowResponsive(window);
578
698
  IntPtr fgBefore = Native.GetForegroundWindow();
579
699
  string used = DoAction(action, method, el, window, a);
580
700
  // 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 /
@@ -583,7 +703,10 @@ namespace AivinGui {
583
703
  bool restored = used != "mouse" && used != "keyboard" && RestoreForeground(fgBefore, window);
584
704
  // 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).
585
705
  if (restored || (used != "mouse" && used != "keyboard" && fgBefore != window && window != IntPtr.Zero)) SendToBack(window);
586
- Thread.Sleep(Math.Max(0, Math.Min(Int(a, "settle_ms", 250), 3000)));
706
+ // Pattern actions expose their new state synchronously in most UIA providers. Keep a short grace for
707
+ // providers that publish property changes just after returning; real mouse/keyboard still needs longer.
708
+ int defaultSettle = used == "mouse" || used == "keyboard" ? 250 : 30;
709
+ Thread.Sleep(Math.Max(0, Math.Min(Int(a, "settle_ms", defaultSettle), 3000)));
587
710
  var res = new Dictionary<string, object> { { "action", action }, { "method", used } };
588
711
  if (restored) res["focus_returned_to_user"] = true;
589
712
  if (el != null) res["target"] = Live(el);
@@ -741,7 +864,23 @@ namespace AivinGui {
741
864
  return AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new AndCondition(cond, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)));
742
865
  }
743
866
 
744
- const uint WM_SETTEXT = 0x000C, WM_CHAR = 0x0102, SMTO_ABORTIFHUNG = 0x0002;
867
+ const uint WM_SETTEXT = 0x000C, WM_CHAR = 0x0102, SMTO_ABORTIFHUNG = 0x0002;
868
+
869
+ /** Kiểm tra nhanh nhịp phản hồi của cửa sổ bằng WM_NULL + SMTO_ABORTIFHUNG để tránh UI Automation treo cứng khi ứng dụng đích bị đơ. */
870
+ static bool IsWindowResponsive(IntPtr h, uint timeoutMs) {
871
+ if (h == IntPtr.Zero || !Native.IsWindow(h)) return false;
872
+ IntPtr r;
873
+ return Native.SendMessageTimeout(h, 0, IntPtr.Zero, null, SMTO_ABORTIFHUNG, timeoutMs, out r) != IntPtr.Zero;
874
+ }
875
+
876
+ static void AssertWindowResponsive(IntPtr h) {
877
+ if (h == IntPtr.Zero) return;
878
+ if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The target window has closed");
879
+ if (!IsWindowResponsive(h, 500)) {
880
+ if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The target window has closed");
881
+ throw new GuiError("GUI_WINDOW_HUNG", "The target window is not responding (frozen UI thread)");
882
+ }
883
+ }
745
884
 
746
885
  /** Handle Win32 riêng của phần tử (ô nhập / nút Win32, WinForms có; WPF / UWP / Chromium thì không). */
747
886
  static IntPtr OwnHandle(AutomationElement el) {
@@ -790,8 +929,160 @@ namespace AivinGui {
790
929
  return new System.Windows.Point(sx, sy);
791
930
  }
792
931
 
932
+ /**
933
+ * Chờ giao diện tới trạng thái mong đợi thay vì Planner observe lặp: phần tử (tên chứa chữ / AutomationId, lọc vai trò) hiện ra hoặc mất
934
+ * đi trong cửa sổ, hoặc cửa sổ có tiêu đề chứa chữ hiện ra / đóng (không nói cửa sổ = tìm trong mọi cửa sổ). Hỏi lại mỗi ~250 ms.
935
+ */
936
+ static object WaitFor(Dictionary<string, object> a) {
937
+ string until = (Str(a, "until") ?? "appears").ToLowerInvariant();
938
+ bool gone = until == "gone" || until == "disappears";
939
+ string name = Str(a, "name"), aid = Str(a, "automation_id"), role = Str(a, "role"), title = Str(a, "title_contains");
940
+ bool windowLevel = string.IsNullOrEmpty(name) && string.IsNullOrEmpty(aid);
941
+ if (windowLevel && string.IsNullOrEmpty(title)) throw new GuiError("INVALID_ARGS", "Give name / automation_id (an element) or title_contains (a window)");
942
+ int timeout = Math.Max(200, Math.Min(Int(a, "timeout_ms", 10000), 60000));
943
+ IntPtr h = (!windowLevel || !string.IsNullOrEmpty(Str(a, "window"))) ? ResolveWindow(a) : IntPtr.Zero;
944
+ if (!windowLevel && h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused");
945
+ string reqId = Str(a, "__req_id");
946
+ var sw = Stopwatch.StartNew();
947
+ try {
948
+ while (true) {
949
+ if (IsCancelled(reqId)) throw new GuiError("CANCELLED", "Wait cancelled");
950
+ bool alive = h == IntPtr.Zero || Native.IsWindow(h);
951
+ Dictionary<string, object> match = null;
952
+ if (windowLevel) {
953
+ if (h != IntPtr.Zero) {
954
+ if (alive && WindowText(h).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) match = WindowInfo(h, Native.GetForegroundWindow());
955
+ } else {
956
+ foreach (Dictionary<string, object> info in ListWindows(false)) {
957
+ if (Convert.ToString(info["title"]).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) { match = info; break; }
958
+ }
959
+ }
960
+ } else if (alive) {
961
+ match = FindElement(h, name, aid, role);
962
+ }
963
+ if (gone ? match == null : match != null) {
964
+ var res = new Dictionary<string, object> { { "met", true }, { "until", gone ? "gone" : "appears" }, { "waited_ms", sw.ElapsedMilliseconds } };
965
+ if (match != null) res["match"] = match;
966
+ if (!alive) res["window_closed"] = true;
967
+ return res;
968
+ }
969
+ if (!alive) throw new GuiError("GUI_WINDOW_GONE", "The window closed while waiting for the element to appear");
970
+ if (sw.ElapsedMilliseconds >= timeout) {
971
+ throw new GuiError("GUI_WAIT_TIMEOUT", "Still " + (gone ? "present" : "not there") + " after " + sw.ElapsedMilliseconds + " ms — observe to see what the window shows instead");
972
+ }
973
+ Thread.Sleep(250);
974
+ }
975
+ } finally {
976
+ if (!string.IsNullOrEmpty(reqId)) { lock (CancelledIds) { CancelledIds.Remove(reqId); } }
977
+ }
978
+ }
979
+
980
+ /** 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ò. */
981
+ static Dictionary<string, object> FindElement(IntPtr h, string name, string aid, string role) {
982
+ if (!IsWindowResponsive(h, 300)) return null;
983
+ AutomationElement root;
984
+ try { root = AutomationElement.FromHandle(h); } catch { return null; }
985
+ var cache = new CacheRequest();
986
+ cache.Add(AutomationElement.NameProperty); cache.Add(AutomationElement.ControlTypeProperty); cache.Add(AutomationElement.AutomationIdProperty);
987
+ cache.Add(AutomationElement.IsOffscreenProperty);
988
+ cache.AutomationElementMode = AutomationElementMode.None;
989
+ Condition cond = string.IsNullOrEmpty(aid) ? Condition.TrueCondition : new PropertyCondition(AutomationElement.AutomationIdProperty, aid);
990
+ AutomationElementCollection all;
991
+ try { using (cache.Activate()) { all = root.FindAll(TreeScope.Descendants, cond); } } catch (ElementNotAvailableException) { return null; }
992
+ foreach (AutomationElement e in all) {
993
+ string n = Cached(e, AutomationElement.NameProperty) as string ?? "";
994
+ var ct = Cached(e, AutomationElement.ControlTypeProperty) as ControlType;
995
+ string r = ct == null ? "" : ct.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant();
996
+ if (!string.IsNullOrEmpty(name) && n.IndexOf(name, StringComparison.OrdinalIgnoreCase) < 0) continue;
997
+ if (!string.IsNullOrEmpty(role) && !string.Equals(r, role, StringComparison.OrdinalIgnoreCase)) continue;
998
+ if (true.Equals(Cached(e, AutomationElement.IsOffscreenProperty)) && string.IsNullOrEmpty(aid)) continue;
999
+ var m = new Dictionary<string, object> { { "role", r }, { "name", Clip(n, 120) } };
1000
+ string id = Cached(e, AutomationElement.AutomationIdProperty) as string;
1001
+ if (!string.IsNullOrEmpty(id)) m["automation_id"] = id;
1002
+ return m;
1003
+ }
1004
+ return null;
1005
+ }
1006
+
1007
+ /** Điểm màn hình của node chữ OCR của thao tác đang chạy (null = không phải node OCR). */
1008
+ static System.Windows.Point? ocrPoint = null;
1009
+
1010
+ static System.Windows.Point OcrPointOf(string nodeId, out IntPtr window) {
1011
+ window = IntPtr.Zero;
1012
+ int dot = nodeId.IndexOf(".t");
1013
+ int snap, idx;
1014
+ if (!int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 2), out idx)) throw new GuiError("INVALID_ARGS", "Bad node id: " + nodeId);
1015
+ List<System.Windows.Rect> rects;
1016
+ lock (StateLock) {
1017
+ if (!OcrSnapshots.TryGetValue(snap, out rects)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
1018
+ if (idx < 0 || idx >= rects.Count) throw new GuiError("NOT_FOUND", "No node " + nodeId);
1019
+ window = SnapshotWindow[snap];
1020
+ }
1021
+ if (!Native.IsWindow(window)) throw new GuiError("GUI_STALE_NODE", "The window of " + nodeId + " is closed — observe again");
1022
+ // Khung chữ tính theo góc cửa sổ lúc observe → cộng vị trí cửa sổ HIỆN TẠI (người dùng có thể đã kéo cửa sổ đi).
1023
+ Native.RECT wr; Native.GetWindowRect(window, out wr);
1024
+ var r = rects[idx];
1025
+ return new System.Windows.Point(wr.Left + r.X + r.Width / 2, wr.Top + r.Y + r.Height / 2);
1026
+ }
1027
+
1028
+ /**
1029
+ * Tìm ô nhập UIA (Edit / ComboBox / Document, hoặc có ValuePattern ghi được) nằm ngay bên phải hoặc ngay bên dưới một nhãn chữ OCR.
1030
+ * Giúp thao tác điền vào nhãn OCR điền thẳng vào ô nhập thật thay vì gõ vào chữ tĩnh.
1031
+ */
1032
+ static AutomationElement FindNearbyInputForOcr(string nodeId, IntPtr window) {
1033
+ if (window == IntPtr.Zero || !Native.IsWindow(window)) return null;
1034
+ int dot = nodeId.IndexOf(".t");
1035
+ int snap, idx;
1036
+ if (dot <= 0 || !int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 2), out idx)) return null;
1037
+ System.Windows.Rect ocrRect;
1038
+ var candidates = new List<AutomationElement>();
1039
+ lock (StateLock) {
1040
+ List<System.Windows.Rect> rects;
1041
+ if (!OcrSnapshots.TryGetValue(snap, out rects) || idx < 0 || idx >= rects.Count) return null;
1042
+ ocrRect = rects[idx];
1043
+ Dictionary<int, AutomationElement> map;
1044
+ if (Snapshots.TryGetValue(snap, out map)) {
1045
+ foreach (var kv in map) candidates.Add(kv.Value);
1046
+ }
1047
+ }
1048
+ Native.RECT wr; Native.GetWindowRect(window, out wr);
1049
+ AutomationElement best = null;
1050
+ double bestScore = double.MaxValue;
1051
+ foreach (AutomationElement e in candidates) {
1052
+ try {
1053
+ if (!e.Current.IsEnabled || e.Current.IsOffscreen) continue;
1054
+ ControlType ct = e.Current.ControlType;
1055
+ bool isInput = ct == ControlType.Edit || ct == ControlType.ComboBox || ct == ControlType.Document;
1056
+ if (!isInput) {
1057
+ var vp = Pattern(e, ValuePattern.Pattern) as ValuePattern;
1058
+ if (vp == null || vp.Current.IsReadOnly) continue;
1059
+ }
1060
+ System.Windows.Rect er = e.Current.BoundingRectangle;
1061
+ if (er.IsEmpty || er.Width <= 4 || er.Height <= 4) continue;
1062
+ double rx = er.X - wr.Left, ry = er.Y - wr.Top, rw = er.Width, rh = er.Height;
1063
+ // Bỏ qua nếu chính phần tử bao trùm cả cửa sổ
1064
+ if (rw >= (wr.Right - wr.Left) * 0.95 && rh >= (wr.Bottom - wr.Top) * 0.9) continue;
1065
+ // 1. Ô nhập nằm bên phải nhãn (cùng hàng ngang)
1066
+ double overlapY = Math.Min(ocrRect.Bottom, ry + rh) - Math.Max(ocrRect.Top, ry);
1067
+ double minH = Math.Min(ocrRect.Height, rh);
1068
+ if (minH > 0 && overlapY >= minH * 0.35 && rx >= ocrRect.Right - 12 && rx - ocrRect.Right <= 280) {
1069
+ double dist = Math.Max(0, rx - ocrRect.Right) + Math.Abs((ry + rh / 2) - (ocrRect.Y + ocrRect.Height / 2)) * 2.0;
1070
+ if (dist < bestScore) { bestScore = dist; best = e; }
1071
+ }
1072
+ // 2. Ô nhập nằm ngay bên dưới nhãn (cùng cột dọc)
1073
+ double overlapX = Math.Min(ocrRect.Right, rx + rw) - Math.Max(ocrRect.Left, rx);
1074
+ if ((Math.Abs(rx - ocrRect.Left) <= 140 || overlapX >= ocrRect.Width * 0.4) && ry >= ocrRect.Bottom - 8 && ry - ocrRect.Bottom <= 72) {
1075
+ double dist = Math.Max(0, ry - ocrRect.Bottom) * 1.5 + Math.Abs(rx - ocrRect.Left);
1076
+ if (dist < bestScore) { bestScore = dist; best = e; }
1077
+ }
1078
+ } catch { continue; }
1079
+ }
1080
+ return best;
1081
+ }
1082
+
793
1083
  static System.Windows.Point PointFor(AutomationElement el, IntPtr window, Dictionary<string, object> a) {
794
1084
  if (el != null) return CenterOf(el);
1085
+ if (ocrPoint.HasValue) return ocrPoint.Value;
795
1086
  var pt = Get(a, "point") as Dictionary<string, object>;
796
1087
  if (pt == null) throw new GuiError("INVALID_ARGS", "Give node_id or point {x,y}");
797
1088
  return WindowPoint(window, a, pt);
@@ -877,6 +1168,110 @@ namespace AivinGui {
877
1168
  }
878
1169
  }
879
1170
  }
1171
+
1172
+ /** Một cụm chữ OCR liền nhau trên cùng dòng (một nút / nhãn), khung theo pixel của ảnh. */
1173
+ public class OcrSegment {
1174
+ public string Text;
1175
+ public System.Windows.Rect Rect;
1176
+ }
1177
+
1178
+ /**
1179
+ * OCR có sẵn của Windows 10+ (Windows.Media.Ocr, chạy trên máy, không gửi ảnh đi đâu). Gọi WinRT qua reflection — Add-Type (CodeDom,
1180
+ * C# 5) không tham chiếu được .winmd. Lần đầu ~0,1 s, các lần sau ~15 ms. Ưu tiên tiếng Việt nếu máy có gói OCR tiếng Việt, rồi ngôn
1181
+ * ngữ hồ sơ người dùng.
1182
+ */
1183
+ public static class Ocr {
1184
+ const string WRT = "System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
1185
+ static readonly Dictionary<string, object> Engines = new Dictionary<string, object>();
1186
+ static MethodInfo asTask;
1187
+
1188
+ static Type WinRT(string name, string asm) { return Type.GetType(name + ", " + asm + ", ContentType=WindowsRuntime", true); }
1189
+
1190
+ /** Chờ một IAsyncOperation<T> của WinRT: kiểu T lấy từ kiểu trả về KHAI BÁO (đối tượng COM lúc chạy không lộ interface). */
1191
+ static object Call(MethodInfo mi, object target, params object[] args) {
1192
+ object op = mi.Invoke(target, args);
1193
+ if (asTask == null) {
1194
+ foreach (var m in Type.GetType("System.WindowsRuntimeSystemExtensions, " + WRT, true).GetMethods()) {
1195
+ var ps = m.GetParameters();
1196
+ if (m.Name == "AsTask" && m.IsGenericMethod && ps.Length == 1 && ps[0].ParameterType.GetGenericTypeDefinition().FullName == "Windows.Foundation.IAsyncOperation" + (char)96 + "1") { asTask = m; break; }
1197
+ }
1198
+ if (asTask == null) throw new GuiError("GUI_OCR_UNAVAILABLE", "WinRT async bridge not found");
1199
+ }
1200
+ var task = (System.Threading.Tasks.Task)asTask.MakeGenericMethod(mi.ReturnType.GetGenericArguments()[0]).Invoke(null, new[] { op });
1201
+ if (!task.Wait(15000)) throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR timed out");
1202
+ return task.GetType().GetProperty("Result").GetValue(task, null);
1203
+ }
1204
+
1205
+ static object Engine(string lang, out string used) {
1206
+ var engineT = WinRT("Windows.Media.Ocr.OcrEngine", "Windows.Media");
1207
+ var tries = new List<string>();
1208
+ if (!string.IsNullOrEmpty(lang)) tries.Add(lang);
1209
+ tries.Add("vi");
1210
+ tries.Add("");
1211
+ foreach (var t in tries) {
1212
+ object e;
1213
+ if (Engines.TryGetValue(t, out e) && e != null) { used = Tag(e); return e; }
1214
+ if (t.Length == 0) {
1215
+ e = engineT.GetMethod("TryCreateFromUserProfileLanguages").Invoke(null, null);
1216
+ } else {
1217
+ var langT = WinRT("Windows.Globalization.Language", "Windows.Globalization");
1218
+ object l;
1219
+ try { l = Activator.CreateInstance(langT, t); } catch { continue; }
1220
+ e = engineT.GetMethod("TryCreateFromLanguage").Invoke(null, new[] { l });
1221
+ }
1222
+ Engines[t] = e;
1223
+ if (e != null) { used = Tag(e); return e; }
1224
+ }
1225
+ throw new GuiError("GUI_OCR_UNAVAILABLE", "No OCR language is installed on this PC");
1226
+ }
1227
+
1228
+ static string Tag(object engine) {
1229
+ var l = engine.GetType().GetProperty("RecognizerLanguage").GetValue(engine, null);
1230
+ return Convert.ToString(l.GetType().GetProperty("LanguageTag").GetValue(l, null));
1231
+ }
1232
+
1233
+ static double D(object o, string p) { return Convert.ToDouble(o.GetType().GetProperty(p).GetValue(o, null)); }
1234
+
1235
+ public static List<OcrSegment> Read(Bitmap bmp, string lang, out string used) {
1236
+ try {
1237
+ return ReadInner(bmp, lang, out used);
1238
+ } catch (TargetInvocationException e) {
1239
+ throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR failed: " + (e.InnerException != null ? e.InnerException.Message : e.Message));
1240
+ } catch (AggregateException e) {
1241
+ throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR failed: " + e.InnerException.Message);
1242
+ }
1243
+ }
1244
+
1245
+ static List<OcrSegment> ReadInner(Bitmap bmp, string lang, out string used) {
1246
+ object engine = Engine(lang, out used);
1247
+ var engineT = engine.GetType();
1248
+ byte[] png;
1249
+ using (var ms = new MemoryStream()) { bmp.Save(ms, ImageFormat.Png); png = ms.ToArray(); }
1250
+ var ras = Type.GetType("System.IO.WindowsRuntimeStreamExtensions, " + WRT, true)
1251
+ .GetMethod("AsRandomAccessStream", new[] { typeof(Stream) }).Invoke(null, new object[] { new MemoryStream(png) });
1252
+ var decT = WinRT("Windows.Graphics.Imaging.BitmapDecoder", "Windows.Graphics");
1253
+ var decoder = Call(decT.GetMethod("CreateAsync", new[] { WinRT("Windows.Storage.Streams.IRandomAccessStream", "Windows.Storage") }), null, ras);
1254
+ var soft = Call(decT.GetMethod("GetSoftwareBitmapAsync", Type.EmptyTypes), decoder);
1255
+ var result = Call(WinRT("Windows.Media.Ocr.OcrEngine", "Windows.Media").GetMethod("RecognizeAsync"), engine, soft);
1256
+ var segments = new List<OcrSegment>();
1257
+ foreach (var line in (System.Collections.IEnumerable)result.GetType().GetProperty("Lines").GetValue(result, null)) {
1258
+ // Một dòng OCR hay gộp nhiều nút cạnh nhau ("Save As Cancel") → tách thành cụm khi khoảng trống giữa hai từ lớn hơn ~1 chiều cao chữ.
1259
+ OcrSegment cur = null;
1260
+ double lastRight = 0;
1261
+ foreach (var w in (System.Collections.IEnumerable)line.GetType().GetProperty("Words").GetValue(line, null)) {
1262
+ var r = w.GetType().GetProperty("BoundingRect").GetValue(w, null);
1263
+ var rect = new System.Windows.Rect(D(r, "X"), D(r, "Y"), D(r, "Width"), D(r, "Height"));
1264
+ string text = Convert.ToString(w.GetType().GetProperty("Text").GetValue(w, null));
1265
+ if (cur != null && rect.X - lastRight > Math.Max(8, Math.Max(rect.Height, cur.Rect.Height))) { segments.Add(cur); cur = null; }
1266
+ if (cur == null) cur = new OcrSegment { Text = text, Rect = rect };
1267
+ else { cur.Text += " " + text; cur.Rect = System.Windows.Rect.Union(cur.Rect, rect); }
1268
+ lastRight = rect.Right;
1269
+ }
1270
+ if (cur != null) segments.Add(cur);
1271
+ }
1272
+ return segments;
1273
+ }
1274
+ }
880
1275
  }
881
1276
  `;
882
1277