@aivin-labs/cli 1.0.57 → 1.0.60
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.
- package/bin/cli.mjs +2 -1
- package/bin/lib/auth.mjs +119 -88
- package/bin/lib/context.mjs +58 -5
- package/bin/lib/loginHandoff.mjs +87 -0
- package/bin/lib/openFile.mjs +29 -4
- package/bin/lib/remote/client.mjs +1456 -1454
- package/bin/lib/remote/credentials.mjs +131 -125
- package/bin/lib/remote/desktop/castAuth.mjs +274 -259
- package/bin/lib/remote/desktop/castConsent.mjs +155 -154
- package/bin/lib/remote/desktop/castTrust.mjs +220 -183
- package/bin/lib/remote/desktop/desktopCastSource.mjs +77 -31
- package/bin/lib/remote/desktop/strings.mjs +158 -138
- package/bin/lib/remote/desktop/traySource.mjs +89 -15
- package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
- package/bin/lib/remote/dpapiHelper.mjs +91 -0
- package/bin/lib/remote/gui/index.mjs +839 -567
- package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -2127
- package/bin/lib/remote/tokenStore.mjs +19 -2
- package/package.json +1 -1
|
@@ -1,2127 +1,2418 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Mã C# của tiến trình điều khiển giao diện trên Windows (UI Automation + SendInput + chụp cửa sổ). Nhúng thành chuỗi vì CLI đóng gói
|
|
3
|
-
* thành một tệp nhị phân (bun) — lúc chạy ghi ra thư mục cấu hình rồi PowerShell 5.1 biên dịch (`Add-Type`, CodeDom → chỉ cú pháp C# 5:
|
|
4
|
-
* không `$"..."`, không `?.`, không thân hàm `=>`). Bản dịch được lưu thành DLL theo dấu vân tay mã, lần sau nạp thẳng.
|
|
5
|
-
*
|
|
6
|
-
* Giao thức: mỗi dòng stdin một JSON `{ id, op, args }`, mỗi dòng stdout một JSON `{ id, ok, result | error, code }`. Chạy trên luồng MTA
|
|
7
|
-
* riêng (UI Automation phía client nên ở MTA). Toạ độ là pixel vật lý (tiến trình bật DPI-aware theo từng màn hình).
|
|
8
|
-
*
|
|
9
|
-
* Cùng tiến trình có đầu nối Office qua COM (officeHostSource.mjs, op `office`) — ghép sau phần chính.
|
|
10
|
-
*/
|
|
11
|
-
import { OFFICE_CSHARP } from './officeHostSource.mjs';
|
|
12
|
-
|
|
13
|
-
const MAIN_CSHARP = String.raw`
|
|
14
|
-
using System;
|
|
15
|
-
using System.Collections.Generic;
|
|
16
|
-
using System.Diagnostics;
|
|
17
|
-
using System.Drawing;
|
|
18
|
-
using System.Drawing.Drawing2D;
|
|
19
|
-
using System.Drawing.Imaging;
|
|
20
|
-
using System.IO;
|
|
21
|
-
using System.Reflection;
|
|
22
|
-
using System.Runtime.InteropServices;
|
|
23
|
-
using System.Text;
|
|
24
|
-
using System.Threading;
|
|
25
|
-
using System.Web.Script.Serialization;
|
|
26
|
-
using System.Windows.Automation;
|
|
27
|
-
|
|
28
|
-
namespace AivinGui {
|
|
29
|
-
public class GuiError : Exception {
|
|
30
|
-
public string Code;
|
|
31
|
-
public GuiError(string code, string message) : base(message) { Code = code; }
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
public static class Native {
|
|
35
|
-
[
|
|
36
|
-
[StructLayout(LayoutKind.Sequential)] public struct
|
|
37
|
-
[StructLayout(LayoutKind.Sequential)] public struct
|
|
38
|
-
[StructLayout(LayoutKind.Sequential)] public struct
|
|
39
|
-
[StructLayout(LayoutKind.Sequential)] public struct
|
|
40
|
-
[StructLayout(LayoutKind.
|
|
41
|
-
[StructLayout(LayoutKind.
|
|
42
|
-
public
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
[DllImport("user32.dll")] public static extern bool
|
|
46
|
-
[DllImport("user32.dll")] public static extern bool
|
|
47
|
-
[DllImport("user32.dll")] public static extern bool
|
|
48
|
-
[DllImport("user32.dll"
|
|
49
|
-
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int
|
|
50
|
-
[DllImport("user32.dll")] public static extern
|
|
51
|
-
[DllImport("user32.dll")] public static extern
|
|
52
|
-
[DllImport("user32.dll")] public static extern IntPtr
|
|
53
|
-
[DllImport("user32.dll")] public static extern
|
|
54
|
-
[DllImport("user32.dll")] public static extern bool
|
|
55
|
-
[DllImport("user32.dll")] public static extern bool
|
|
56
|
-
[DllImport("user32.dll")] public static extern
|
|
57
|
-
[DllImport("user32.dll")] public static extern
|
|
58
|
-
[DllImport("user32.dll")] public static extern bool
|
|
59
|
-
[DllImport("user32.dll"
|
|
60
|
-
[DllImport("user32.dll")] public static extern
|
|
61
|
-
[DllImport("user32.dll")] public static extern
|
|
62
|
-
[DllImport("user32.dll")] public static extern
|
|
63
|
-
[DllImport("user32.dll")] public static extern bool
|
|
64
|
-
[DllImport("user32.dll")] public static extern
|
|
65
|
-
[DllImport("user32.dll")] public static extern
|
|
66
|
-
[DllImport("user32.dll")] public static extern
|
|
67
|
-
[DllImport("user32.dll")] public static extern
|
|
68
|
-
[DllImport("user32.dll")] public static extern
|
|
69
|
-
[DllImport("user32.dll")] public static extern
|
|
70
|
-
[DllImport("
|
|
71
|
-
[DllImport("
|
|
72
|
-
[DllImport("
|
|
73
|
-
[DllImport("
|
|
74
|
-
[DllImport("user32.dll")] public static extern
|
|
75
|
-
[DllImport("user32.dll")] public static extern bool
|
|
76
|
-
[DllImport("user32.dll")] public static extern
|
|
77
|
-
[
|
|
78
|
-
[DllImport("user32.dll"
|
|
79
|
-
[
|
|
80
|
-
[DllImport("user32.dll")] public static extern IntPtr
|
|
81
|
-
[DllImport("user32.dll")] public static extern
|
|
82
|
-
[DllImport("user32.dll")] public static extern
|
|
83
|
-
[DllImport("user32.dll")] public static extern
|
|
84
|
-
[DllImport("user32.dll"
|
|
85
|
-
[DllImport("
|
|
86
|
-
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern
|
|
87
|
-
[DllImport("
|
|
88
|
-
[DllImport("
|
|
89
|
-
[DllImport("user32.dll")] public static extern IntPtr
|
|
90
|
-
[DllImport("user32.dll")] public static extern
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
const
|
|
99
|
-
const uint
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
static readonly
|
|
105
|
-
static readonly
|
|
106
|
-
|
|
107
|
-
static readonly
|
|
108
|
-
static readonly
|
|
109
|
-
/**
|
|
110
|
-
static readonly Dictionary<int,
|
|
111
|
-
static int
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
static
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
static
|
|
124
|
-
/**
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
/**
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
static
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
if (
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
static
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
}
|
|
258
|
-
case "
|
|
259
|
-
case "
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
return
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
static
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
return
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
if (
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
if (
|
|
440
|
-
|
|
441
|
-
uint
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
if (
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
if (
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
Native.
|
|
516
|
-
|
|
517
|
-
if (
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
string
|
|
638
|
-
return role == "
|
|
639
|
-
}
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
return
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
if (
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
if (
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
if (
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
if (!
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
return
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
/**
|
|
903
|
-
*
|
|
904
|
-
*
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
if (
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
*
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
}
|
|
1067
|
-
|
|
1068
|
-
}
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
try {
|
|
1205
|
-
var
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
}
|
|
1247
|
-
}
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
if (
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
if (
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
return
|
|
1686
|
-
}
|
|
1687
|
-
|
|
1688
|
-
/**
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
/**
|
|
1696
|
-
static
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
if (
|
|
1705
|
-
return
|
|
1706
|
-
}
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
IntPtr h = (
|
|
1720
|
-
if (
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
try {
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
}
|
|
1789
|
-
return
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
static
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
}
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
if (
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
return
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
if (
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
var
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
return
|
|
1910
|
-
}
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
}
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
}
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
}
|
|
1967
|
-
static
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
}
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
var
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
if (e
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
var
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
if (
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Mã C# của tiến trình điều khiển giao diện trên Windows (UI Automation + SendInput + chụp cửa sổ). Nhúng thành chuỗi vì CLI đóng gói
|
|
3
|
+
* thành một tệp nhị phân (bun) — lúc chạy ghi ra thư mục cấu hình rồi PowerShell 5.1 biên dịch (`Add-Type`, CodeDom → chỉ cú pháp C# 5:
|
|
4
|
+
* không `$"..."`, không `?.`, không thân hàm `=>`). Bản dịch được lưu thành DLL theo dấu vân tay mã, lần sau nạp thẳng.
|
|
5
|
+
*
|
|
6
|
+
* Giao thức: mỗi dòng stdin một JSON `{ id, op, args }`, mỗi dòng stdout một JSON `{ id, ok, result | error, code }`. Chạy trên luồng MTA
|
|
7
|
+
* riêng (UI Automation phía client nên ở MTA). Toạ độ là pixel vật lý (tiến trình bật DPI-aware theo từng màn hình).
|
|
8
|
+
*
|
|
9
|
+
* Cùng tiến trình có đầu nối Office qua COM (officeHostSource.mjs, op `office`) — ghép sau phần chính.
|
|
10
|
+
*/
|
|
11
|
+
import { OFFICE_CSHARP } from './officeHostSource.mjs';
|
|
12
|
+
|
|
13
|
+
const MAIN_CSHARP = String.raw`
|
|
14
|
+
using System;
|
|
15
|
+
using System.Collections.Generic;
|
|
16
|
+
using System.Diagnostics;
|
|
17
|
+
using System.Drawing;
|
|
18
|
+
using System.Drawing.Drawing2D;
|
|
19
|
+
using System.Drawing.Imaging;
|
|
20
|
+
using System.IO;
|
|
21
|
+
using System.Reflection;
|
|
22
|
+
using System.Runtime.InteropServices;
|
|
23
|
+
using System.Text;
|
|
24
|
+
using System.Threading;
|
|
25
|
+
using System.Web.Script.Serialization;
|
|
26
|
+
using System.Windows.Automation;
|
|
27
|
+
|
|
28
|
+
namespace AivinGui {
|
|
29
|
+
public class GuiError : Exception {
|
|
30
|
+
public string Code;
|
|
31
|
+
public GuiError(string code, string message) : base(message) { Code = code; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
public static class Native {
|
|
35
|
+
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] public static extern int AssocQueryString(int flags, int str, string assoc, string extra, StringBuilder outStr, ref uint outLen);
|
|
36
|
+
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
|
|
37
|
+
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
|
|
38
|
+
[StructLayout(LayoutKind.Sequential)] public struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
|
|
39
|
+
[StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
40
|
+
[StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
41
|
+
[StructLayout(LayoutKind.Explicit)] public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
|
|
42
|
+
[StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public INPUTUNION u; }
|
|
43
|
+
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
|
44
|
+
|
|
45
|
+
[DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam);
|
|
46
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
|
|
47
|
+
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd);
|
|
48
|
+
[DllImport("user32.dll")] public static extern bool IsWindow(IntPtr hWnd);
|
|
49
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder sb, int max);
|
|
50
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr hWnd, StringBuilder sb, int max);
|
|
51
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
|
|
52
|
+
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT r);
|
|
53
|
+
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
|
54
|
+
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
|
|
55
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int cmd);
|
|
56
|
+
[DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr hWnd);
|
|
57
|
+
[DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr hWnd, uint cmd);
|
|
58
|
+
[DllImport("user32.dll")] public static extern bool IsWindowEnabled(IntPtr hWnd);
|
|
59
|
+
[DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hWnd, int index);
|
|
60
|
+
[DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdc, uint flags);
|
|
61
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string cls, string title);
|
|
62
|
+
[DllImport("user32.dll")] public static extern uint SendInput(uint n, INPUT[] inputs, int size);
|
|
63
|
+
[DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
|
|
64
|
+
[DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
|
|
65
|
+
[DllImport("user32.dll")] public static extern bool GetLastInputInfo(ref LASTINPUTINFO info);
|
|
66
|
+
[DllImport("user32.dll")] public static extern short VkKeyScan(char ch);
|
|
67
|
+
[DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
|
|
68
|
+
[DllImport("user32.dll")] public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
|
|
69
|
+
[DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr hWnd);
|
|
70
|
+
[DllImport("user32.dll")] public static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access);
|
|
71
|
+
[DllImport("user32.dll")] public static extern bool CloseDesktop(IntPtr desk);
|
|
72
|
+
[DllImport("kernel32.dll")] public static extern uint GetTickCount();
|
|
73
|
+
[DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId();
|
|
74
|
+
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int cx, int cy, uint flags);
|
|
75
|
+
[DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
|
|
76
|
+
[DllImport("user32.dll")] public static extern IntPtr RealChildWindowFromPoint(IntPtr parent, POINT clientPoint);
|
|
77
|
+
[DllImport("user32.dll")] public static extern bool ScreenToClient(IntPtr hWnd, ref POINT p);
|
|
78
|
+
[DllImport("user32.dll")] public static extern bool GetGUIThreadInfo(uint thread, ref GUITHREADINFO info);
|
|
79
|
+
[StructLayout(LayoutKind.Sequential)] public struct GUITHREADINFO { public uint cbSize, flags; public IntPtr hwndActive, hwndFocus, hwndCapture, hwndMenuOwner, hwndMoveSize, hwndCaret; public RECT rcCaret; }
|
|
80
|
+
[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);
|
|
81
|
+
[DllImport("user32.dll")] public static extern IntPtr GetMenu(IntPtr hWnd);
|
|
82
|
+
[DllImport("user32.dll")] public static extern IntPtr GetSubMenu(IntPtr menu, int pos);
|
|
83
|
+
[DllImport("user32.dll")] public static extern int GetMenuItemCount(IntPtr menu);
|
|
84
|
+
[DllImport("user32.dll")] public static extern uint GetMenuItemID(IntPtr menu, int pos);
|
|
85
|
+
[DllImport("user32.dll")] public static extern uint GetMenuState(IntPtr menu, uint id, uint flags);
|
|
86
|
+
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetMenuString(IntPtr menu, uint id, StringBuilder text, int max, uint flags);
|
|
87
|
+
[DllImport("oleacc.dll")] public static extern int AccessibleObjectFromWindow(IntPtr hWnd, uint objectId, ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object acc);
|
|
88
|
+
[DllImport("oleacc.dll")] public static extern int AccessibleChildren(Accessibility.IAccessible container, int start, int count, [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] object[] children, out int obtained);
|
|
89
|
+
[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);
|
|
90
|
+
[DllImport("user32.dll")] public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool attach);
|
|
91
|
+
[DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hWnd, int attr, out int value, int size);
|
|
92
|
+
[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr hWnd, uint flags);
|
|
93
|
+
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
public class Host {
|
|
97
|
+
const int GWL_EXSTYLE = -20;
|
|
98
|
+
const int WS_EX_TOOLWINDOW = 0x80;
|
|
99
|
+
const uint INPUT_MOUSE = 0, INPUT_KEYBOARD = 1;
|
|
100
|
+
const uint MOUSEEVENTF_MOVE = 0x1, MOUSEEVENTF_LEFTDOWN = 0x2, MOUSEEVENTF_LEFTUP = 0x4, MOUSEEVENTF_RIGHTDOWN = 0x8, MOUSEEVENTF_RIGHTUP = 0x10;
|
|
101
|
+
const uint MOUSEEVENTF_WHEEL = 0x800, MOUSEEVENTF_ABSOLUTE = 0x8000, MOUSEEVENTF_VIRTUALDESK = 0x4000;
|
|
102
|
+
const uint KEYEVENTF_EXTENDEDKEY = 0x1, KEYEVENTF_KEYUP = 0x2, KEYEVENTF_UNICODE = 0x4;
|
|
103
|
+
|
|
104
|
+
static readonly JavaScriptSerializer Json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue, RecursionLimit = 200 };
|
|
105
|
+
static readonly object OutputLock = new object();
|
|
106
|
+
static readonly object StateLock = new object();
|
|
107
|
+
static readonly HashSet<string> CancelledIds = new HashSet<string>();
|
|
108
|
+
static readonly HashSet<string> ActiveWaits = new HashSet<string>();
|
|
109
|
+
/** Ả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. */
|
|
110
|
+
static readonly Dictionary<int, Dictionary<int, AutomationElement>> Snapshots = new Dictionary<int, Dictionary<int, AutomationElement>>();
|
|
111
|
+
static readonly Dictionary<int, IntPtr> SnapshotWindow = new Dictionary<int, IntPtr>();
|
|
112
|
+
/** 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ổ). */
|
|
113
|
+
static readonly Dictionary<int, List<System.Windows.Rect>> OcrSnapshots = new Dictionary<int, List<System.Windows.Rect>>();
|
|
114
|
+
static int snapSeq = 0;
|
|
115
|
+
const int KEEP_SNAPSHOTS = 6;
|
|
116
|
+
/** 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. */
|
|
117
|
+
static uint lastInjectedTick = 0;
|
|
118
|
+
/**
|
|
119
|
+
* Kiểm "người dùng đang dùng chuột / phím" CHỈ khi thao tác sắp phát input thật (chuột, phím, đổi cửa sổ trên cùng). Thao tác theo
|
|
120
|
+
* pattern (SetValue / Invoke / Toggle / Select) không chiếm chuột, không giật focus → chạy song song với người dùng được (chạy thật
|
|
121
|
+
* 28/10/2026: người dùng đang gõ ở cửa sổ khác, mọi set_value bị dừng oan 12 lượt).
|
|
122
|
+
*/
|
|
123
|
+
static bool pendingInputCheck = false;
|
|
124
|
+
/** Thao tác đang chạy có kiểm người dùng không (giữ suốt thao tác — pendingInputCheck chỉ cho lần kiểm đầu). */
|
|
125
|
+
static bool userInputCheck = false;
|
|
126
|
+
static long inputGraceMs = 1500;
|
|
127
|
+
/** Giữa các lô gõ: input mới hơn lô AI vừa phát quá ngưỡng này (ms) = của người dùng (lô của AI xử lý xong trong vài ms). */
|
|
128
|
+
const int BATCH_USER_INPUT_MARGIN_MS = 60;
|
|
129
|
+
const int TYPE_BATCH_PAUSE_MS = 80;
|
|
130
|
+
/** Đ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. */
|
|
131
|
+
static Dictionary<string, object> lastMousePoint = null;
|
|
132
|
+
|
|
133
|
+
/** 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. */
|
|
134
|
+
static bool backgroundOnly = false;
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* 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ì
|
|
138
|
+
* báo GUI_PERSON_PRESENT, chưa làm gì; phía Node chờ họ ngừng tay rồi thử lại.
|
|
139
|
+
*/
|
|
140
|
+
static void GuardInput() {
|
|
141
|
+
if (backgroundOnly) throw new GuiError("GUI_NEEDS_REAL_INPUT", "This action needs the real mouse/keyboard");
|
|
142
|
+
if (!pendingInputCheck) return;
|
|
143
|
+
pendingInputCheck = false;
|
|
144
|
+
long idle = UserIdleMs();
|
|
145
|
+
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");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Gõ dài nhiều lô (02/11/2026): người dùng chen vào giữa chừng → dừng. Kiểm con trỏ dời chỗ (gõ phím không di chuột) và input mới hơn lô
|
|
150
|
+
* cuối của AI quá BATCH_USER_INPUT_MARGIN_MS (UserIdleMs coi mọi input trong 150 ms sau lô AI là của AI → không thấy người gõ chen).
|
|
151
|
+
*/
|
|
152
|
+
static bool UserTouchedSince(Native.POINT cursorAtStart) {
|
|
153
|
+
Native.POINT now;
|
|
154
|
+
if (Native.GetCursorPos(out now) && (now.X != cursorAtStart.X || now.Y != cursorAtStart.Y)) return true;
|
|
155
|
+
var info = new Native.LASTINPUTINFO(); info.cbSize = (uint)Marshal.SizeOf(info);
|
|
156
|
+
if (!Native.GetLastInputInfo(ref info) || lastInjectedTick == 0) return false;
|
|
157
|
+
return (int)(info.dwTime - lastInjectedTick) > BATCH_USER_INPUT_MARGIN_MS;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
static void MoveCursor(int x, int y) { GuardInput(); Native.SetCursorPos(x, y); }
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Di chuột bằng SendInput (toạ độ tuyệt đối trên màn hình ảo) — sinh sự kiện di chuyển thật như chuột người. SetCursorPos chỉ đặt vị trí:
|
|
164
|
+
* ứng dụng nhận input kiểu pointer (Paint mới, canvas XAML / WinUI) không thấy nét kéo (gui-bench 13/11/2026: kéo trên Paint không vẽ gì).
|
|
165
|
+
*/
|
|
166
|
+
static void MoveCursorInput(int x, int y) {
|
|
167
|
+
GuardInput();
|
|
168
|
+
var vs = System.Windows.Forms.SystemInformation.VirtualScreen;
|
|
169
|
+
int nx = (int)Math.Round((x - vs.Left) * 65535.0 / Math.Max(1, vs.Width - 1));
|
|
170
|
+
int ny = (int)Math.Round((y - vs.Top) * 65535.0 / Math.Max(1, vs.Height - 1));
|
|
171
|
+
Send(new[] { MouseInput(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK, nx, ny, 0) });
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
public static void Run() {
|
|
175
|
+
try { Native.SetProcessDpiAwarenessContext(new IntPtr(-4)); } catch { }
|
|
176
|
+
// Host trước bị giết giữa lúc mở tệp → Excel / Word ẩn nó tạo còn sống, giữ khoá tệp: dọn (chỉ bản chắc chắn do host tạo).
|
|
177
|
+
try { Office.CleanupOrphans(); } catch { }
|
|
178
|
+
var t = new Thread(Loop);
|
|
179
|
+
t.SetApartmentState(ApartmentState.MTA);
|
|
180
|
+
t.Start();
|
|
181
|
+
t.Join();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
static void WriteLineSafe(StreamWriter output, Dictionary<string, object> res) {
|
|
185
|
+
string line = Json.Serialize(res);
|
|
186
|
+
lock (OutputLock) { output.WriteLine(line); }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
static bool IsCancelled(string reqId) {
|
|
190
|
+
if (string.IsNullOrEmpty(reqId)) return false;
|
|
191
|
+
lock (CancelledIds) { return CancelledIds.Contains(reqId); }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
static void ExecuteAndWrite(StreamWriter output, object id, string op, Dictionary<string, object> args) {
|
|
195
|
+
var res = new Dictionary<string, object>();
|
|
196
|
+
try {
|
|
197
|
+
res["result"] = Dispatch(op, args);
|
|
198
|
+
res["ok"] = true;
|
|
199
|
+
} catch (GuiError e) {
|
|
200
|
+
res["ok"] = false; res["code"] = e.Code; res["error"] = e.Message;
|
|
201
|
+
} catch (ElementNotAvailableException e) {
|
|
202
|
+
res["ok"] = false; res["code"] = "GUI_STALE_NODE"; res["error"] = "Element is gone: " + e.Message;
|
|
203
|
+
} catch (Exception e) {
|
|
204
|
+
res["ok"] = false; res["code"] = "EXECUTION_FAILED"; res["error"] = e.GetType().Name + ": " + e.Message;
|
|
205
|
+
}
|
|
206
|
+
res["id"] = id;
|
|
207
|
+
WriteLineSafe(output, res);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
static void Loop() {
|
|
211
|
+
var input = new StreamReader(Console.OpenStandardInput(), new UTF8Encoding(false));
|
|
212
|
+
var output = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false));
|
|
213
|
+
output.AutoFlush = true;
|
|
214
|
+
WriteLineSafe(output, new Dictionary<string, object> { { "ready", true } });
|
|
215
|
+
string line;
|
|
216
|
+
while ((line = input.ReadLine()) != null) {
|
|
217
|
+
if (line.Trim().Length == 0) continue;
|
|
218
|
+
object id = null;
|
|
219
|
+
try {
|
|
220
|
+
var req = (Dictionary<string, object>)Json.DeserializeObject(line);
|
|
221
|
+
string cancelId = Str(req, "cancel");
|
|
222
|
+
if (!string.IsNullOrEmpty(cancelId)) {
|
|
223
|
+
lock (CancelledIds) { if (ActiveWaits.Contains(cancelId)) CancelledIds.Add(cancelId); }
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
id = Get(req, "id");
|
|
227
|
+
string op = Str(req, "op");
|
|
228
|
+
var args = Get(req, "args") as Dictionary<string, object>;
|
|
229
|
+
if (args == null) args = new Dictionary<string, object>();
|
|
230
|
+
args["__req_id"] = id == null ? null : Convert.ToString(id);
|
|
231
|
+
// 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.
|
|
232
|
+
if (op == "wait_for" || op == "ping" || op == "idle") {
|
|
233
|
+
object reqId = id;
|
|
234
|
+
string reqOp = op;
|
|
235
|
+
var reqArgs = args;
|
|
236
|
+
string reqIdStr = id == null ? null : Convert.ToString(id);
|
|
237
|
+
if (op == "wait_for" && !string.IsNullOrEmpty(reqIdStr)) { lock (CancelledIds) { ActiveWaits.Add(reqIdStr); } }
|
|
238
|
+
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); } } } });
|
|
239
|
+
worker.IsBackground = true;
|
|
240
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
241
|
+
worker.Start();
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
ExecuteAndWrite(output, id, op, args);
|
|
245
|
+
} catch (Exception e) {
|
|
246
|
+
var errRes = new Dictionary<string, object> { { "id", id }, { "ok", false }, { "code", "EXECUTION_FAILED" }, { "error", e.GetType().Name + ": " + e.Message } };
|
|
247
|
+
WriteLineSafe(output, errRes);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
static object Dispatch(string op, Dictionary<string, object> a) {
|
|
253
|
+
switch (op) {
|
|
254
|
+
case "ping": return new Dictionary<string, object> { { "pong", true }, { "screens", Screens() }, { "interactive", InteractiveDesktop() } };
|
|
255
|
+
case "windows": return ListWindows(Bool(a, "all", false));
|
|
256
|
+
case "observe": return Observe(a);
|
|
257
|
+
case "window_info": { IntPtr h = ResolveWindow(a); if (h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused"); return WindowInfo(h, Native.GetForegroundWindow()); }
|
|
258
|
+
case "focus": return FocusWindowOp(a);
|
|
259
|
+
case "to_back": {
|
|
260
|
+
IntPtr h = ResolveWindow(a);
|
|
261
|
+
IntPtr prev = ParseWindow(Str(a, "restore_to"));
|
|
262
|
+
long contentWait = Bool(a, "wait_content", false) ? WaitForUwpContent(h, 3000) : 0;
|
|
263
|
+
bool restored = false;
|
|
264
|
+
IntPtr fgNow = Native.GetForegroundWindow();
|
|
265
|
+
if (prev != IntPtr.Zero && fgNow != prev && TookForeground(fgNow, h)) {
|
|
266
|
+
restored = RestoreForeground(prev, h);
|
|
267
|
+
// Ứ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.
|
|
268
|
+
if (!restored) { try { restored = ForceForeground(prev); } catch (GuiError) { } }
|
|
269
|
+
}
|
|
270
|
+
SendToBack(h);
|
|
271
|
+
return new Dictionary<string, object> { { "sent_to_back", true }, { "focus_returned_to_user", restored }, { "content_wait_ms", contentWait } };
|
|
272
|
+
}
|
|
273
|
+
case "act": return Act(a);
|
|
274
|
+
case "read_table": return ReadTable(a);
|
|
275
|
+
case "ocr": return OcrSnapshot(a);
|
|
276
|
+
case "wait_for": return WaitFor(a);
|
|
277
|
+
case "office": return Office.Run(a);
|
|
278
|
+
case "idle": return new Dictionary<string, object> { { "idle_ms", IdleMs() }, { "user_idle_ms", UserIdleMs() } };
|
|
279
|
+
case "assoc": return Assoc(Str(a, "ext"));
|
|
280
|
+
default: throw new GuiError("INVALID_ARGS", "Unknown op: " + op);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// ── tiện ích đọc tham số ────────────────────────────────────────────────────────────────────
|
|
285
|
+
|
|
286
|
+
static object Get(Dictionary<string, object> d, string k) { object v; return d != null && d.TryGetValue(k, out v) ? v : null; }
|
|
287
|
+
static string Str(Dictionary<string, object> d, string k) { var v = Get(d, k); return v == null ? null : Convert.ToString(v); }
|
|
288
|
+
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; } }
|
|
289
|
+
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; } }
|
|
290
|
+
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; } }
|
|
291
|
+
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; } }
|
|
292
|
+
|
|
293
|
+
static List<object> Screens() {
|
|
294
|
+
var list = new List<object>();
|
|
295
|
+
foreach (var s in System.Windows.Forms.Screen.AllScreens) {
|
|
296
|
+
list.Add(new Dictionary<string, object> { { "x", s.Bounds.X }, { "y", s.Bounds.Y }, { "w", s.Bounds.Width }, { "h", s.Bounds.Height }, { "primary", s.Primary } });
|
|
297
|
+
}
|
|
298
|
+
return list;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Màn hình đang khoá / chuyển sang desktop bảo mật (UAC) → không mở được desktop nhận input. */
|
|
302
|
+
static bool InteractiveDesktop() {
|
|
303
|
+
IntPtr d = Native.OpenInputDesktop(0, false, 0x0100);
|
|
304
|
+
if (d == IntPtr.Zero) return false;
|
|
305
|
+
Native.CloseDesktop(d);
|
|
306
|
+
return true;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Lệnh mà Windows sẽ chạy khi mở tệp có đuôi này bằng verb mặc định (cùng cách explorer.exe / ShellExecute chọn — kể cả khi ProgID mặc định
|
|
311
|
+
* hỏng và Windows rơi về verb đầu tiên còn lại, vd "Open with AIVIN Office Suite" ở SystemFileAssociations). Không có liên kết → command rỗng.
|
|
312
|
+
*/
|
|
313
|
+
static Dictionary<string, object> Assoc(string ext) {
|
|
314
|
+
if (string.IsNullOrEmpty(ext)) throw new GuiError("INVALID_ARGS", "ext is required");
|
|
315
|
+
if (ext[0] != '.') ext = "." + ext;
|
|
316
|
+
return new Dictionary<string, object> { { "command", AssocString(ext, 1) }, { "executable", AssocString(ext, 2) } };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
static string AssocString(string ext, int which) {
|
|
320
|
+
uint len = 2048;
|
|
321
|
+
var sb = new StringBuilder((int)len);
|
|
322
|
+
// ASSOCF_NOTRUNCATE (0x20); which: ASSOCSTR_COMMAND = 1, ASSOCSTR_EXECUTABLE = 2.
|
|
323
|
+
return Native.AssocQueryString(0x20, which, ext, null, sb, ref len) == 0 ? sb.ToString() : "";
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
static uint IdleMs() {
|
|
327
|
+
var info = new Native.LASTINPUTINFO(); info.cbSize = (uint)Marshal.SizeOf(info);
|
|
328
|
+
if (!Native.GetLastInputInfo(ref info)) return 0;
|
|
329
|
+
return Native.GetTickCount() - info.dwTime;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** Thời gian từ lần input gần nhất KHÔNG phải của AI (gần đúng: input mới hơn lần AI phát cuối + 150 ms là của người). */
|
|
333
|
+
static long UserIdleMs() {
|
|
334
|
+
var info = new Native.LASTINPUTINFO(); info.cbSize = (uint)Marshal.SizeOf(info);
|
|
335
|
+
if (!Native.GetLastInputInfo(ref info)) return long.MaxValue;
|
|
336
|
+
uint now = Native.GetTickCount();
|
|
337
|
+
if (lastInjectedTick != 0 && info.dwTime - lastInjectedTick < 150) return long.MaxValue;
|
|
338
|
+
return now - info.dwTime;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// ── cửa sổ ──────────────────────────────────────────────────────────────────────────────────
|
|
342
|
+
|
|
343
|
+
static string WindowText(IntPtr h) { var sb = new StringBuilder(512); Native.GetWindowText(h, sb, sb.Capacity); return sb.ToString(); }
|
|
344
|
+
static string ClassOf(IntPtr h) { var sb = new StringBuilder(256); Native.GetClassName(h, sb, sb.Capacity); return sb.ToString(); }
|
|
345
|
+
|
|
346
|
+
static string ProcessName(uint pid) {
|
|
347
|
+
try { return Process.GetProcessById((int)pid).ProcessName; } catch { return ""; }
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
static bool IsCloaked(IntPtr h) {
|
|
351
|
+
int cloaked = 0;
|
|
352
|
+
try { Native.DwmGetWindowAttribute(h, 14, out cloaked, 4); } catch { }
|
|
353
|
+
return cloaked != 0;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
static Dictionary<string, object> RectDict(Native.RECT r) {
|
|
357
|
+
return new Dictionary<string, object> { { "x", r.Left }, { "y", r.Top }, { "w", r.Right - r.Left }, { "h", r.Bottom - r.Top } };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
static Dictionary<string, object> WindowInfo(IntPtr h, IntPtr fg) {
|
|
361
|
+
uint pid; Native.GetWindowThreadProcessId(h, out pid);
|
|
362
|
+
Native.RECT r; Native.GetWindowRect(h, out r);
|
|
363
|
+
return new Dictionary<string, object> {
|
|
364
|
+
{ "window", "0x" + h.ToInt64().ToString("x") }, { "title", WindowText(h) }, { "process", ProcessName(pid) }, { "pid", (long)pid },
|
|
365
|
+
{ "class", ClassOf(h) }, { "rect", RectDict(r) }, { "focused", h == fg }, { "minimized", Native.IsIconic(h) },
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
static List<object> ListWindows(bool all) {
|
|
370
|
+
var list = new List<object>();
|
|
371
|
+
IntPtr fg = Native.GetForegroundWindow();
|
|
372
|
+
uint selfPid = (uint)Process.GetCurrentProcess().Id;
|
|
373
|
+
Native.EnumWindows(delegate (IntPtr h, IntPtr l) {
|
|
374
|
+
if (!Native.IsWindowVisible(h) || IsCloaked(h)) return true;
|
|
375
|
+
if (Native.GetWindow(h, 4) != IntPtr.Zero && !all) return true; // có cửa sổ chủ → hộp thoại con, lấy qua cửa sổ chủ
|
|
376
|
+
if ((Native.GetWindowLong(h, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) != 0) return true;
|
|
377
|
+
string title = WindowText(h);
|
|
378
|
+
if (title.Length == 0) return true;
|
|
379
|
+
uint pid; Native.GetWindowThreadProcessId(h, out pid);
|
|
380
|
+
if (pid == selfPid) return true;
|
|
381
|
+
list.Add(WindowInfo(h, fg));
|
|
382
|
+
return true;
|
|
383
|
+
}, IntPtr.Zero);
|
|
384
|
+
return list;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
static IntPtr ParseWindow(string s) {
|
|
388
|
+
if (string.IsNullOrEmpty(s)) return IntPtr.Zero;
|
|
389
|
+
try {
|
|
390
|
+
long v = s.StartsWith("0x") ? Convert.ToInt64(s.Substring(2), 16) : Convert.ToInt64(s);
|
|
391
|
+
return new IntPtr(v);
|
|
392
|
+
} catch { return IntPtr.Zero; }
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
static IntPtr ResolveWindow(Dictionary<string, object> a) { return ResolveWindow(a, false); }
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Cửa sổ theo handle, hoặc tìm theo tiêu đề / tên tiến trình (chứa, không phân biệt hoa thường); không có → cửa sổ đang focus (chỉ cho
|
|
399
|
+
* thao tác đọc). forInput (act không node_id, 02/11/2026): không nêu cửa sổ thì KHÔNG lấy cửa sổ đang focus — người dùng có thể vừa
|
|
400
|
+
* chuyển sang cửa sổ khác, phím / chuột rơi nhầm chỗ. Ngoại lệ: hỏi từ linh vật → cửa sổ chủ máy dùng ngay trước đó ("fallback").
|
|
401
|
+
*/
|
|
402
|
+
static IntPtr ResolveWindow(Dictionary<string, object> a, bool forInput) {
|
|
403
|
+
string w = Str(a, "window");
|
|
404
|
+
IntPtr h = ParseWindow(w);
|
|
405
|
+
if (h != IntPtr.Zero) {
|
|
406
|
+
if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "Window no longer exists: " + w);
|
|
407
|
+
return h;
|
|
408
|
+
}
|
|
409
|
+
if (!string.IsNullOrEmpty(w)) {
|
|
410
|
+
string q = w.ToLowerInvariant();
|
|
411
|
+
// 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ó.
|
|
412
|
+
foreach (bool withDialogs in new[] { false, true }) {
|
|
413
|
+
foreach (Dictionary<string, object> info in ListWindows(withDialogs)) {
|
|
414
|
+
if (Convert.ToString(info["title"]).ToLowerInvariant().Contains(q) || Convert.ToString(info["process"]).ToLowerInvariant() == q) {
|
|
415
|
+
return ParseWindow(Convert.ToString(info["window"]));
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
throw new GuiError("NOT_FOUND", "No window matches: " + w);
|
|
420
|
+
}
|
|
421
|
+
// Đ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ó.
|
|
422
|
+
IntPtr fg = Native.GetForegroundWindow();
|
|
423
|
+
long avoid = Long(a, "avoid_pid");
|
|
424
|
+
if (avoid > 0 && fg != IntPtr.Zero) {
|
|
425
|
+
uint fgPid; Native.GetWindowThreadProcessId(fg, out fgPid);
|
|
426
|
+
if (fgPid == avoid) {
|
|
427
|
+
IntPtr back = ParseWindow(Str(a, "fallback"));
|
|
428
|
+
if (back != IntPtr.Zero && Native.IsWindow(back)) return back;
|
|
429
|
+
if (forInput) throw new GuiError("INVALID_ARGS", "Name the window for this action (window: handle 0x… or a title/process)");
|
|
430
|
+
return IntPtr.Zero;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (forInput) throw new GuiError("INVALID_ARGS", "Name the window for this action (window: handle 0x… or a title/process) — input is never sent to whatever window happens to be focused");
|
|
434
|
+
return fg;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** 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. */
|
|
438
|
+
static bool TookForeground(IntPtr fg, IntPtr h) {
|
|
439
|
+
if (fg == IntPtr.Zero || h == IntPtr.Zero) return false;
|
|
440
|
+
if (ClassOf(h) == "ApplicationFrameWindow") return fg == h;
|
|
441
|
+
uint pa, pb; Native.GetWindowThreadProcessId(fg, out pa); Native.GetWindowThreadProcessId(h, out pb);
|
|
442
|
+
return pa != 0 && pa == pb;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** Ứ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ó. */
|
|
446
|
+
static bool IsUwpFrameOnly(IntPtr h) {
|
|
447
|
+
if (ClassOf(h) != "ApplicationFrameWindow") return false;
|
|
448
|
+
// 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.
|
|
449
|
+
for (IntPtr c = Native.FindWindowEx(h, IntPtr.Zero, null, null); c != IntPtr.Zero; c = Native.FindWindowEx(h, c, null, null)) {
|
|
450
|
+
string cls = ClassOf(c);
|
|
451
|
+
if (cls != "ApplicationFrameTitleBarWindow" && cls != "ApplicationFrameInputSinkWindow") return false;
|
|
452
|
+
}
|
|
453
|
+
return true;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** Đẩ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). */
|
|
457
|
+
static long WaitForUwpContent(IntPtr h, int timeoutMs) {
|
|
458
|
+
var sw = Stopwatch.StartNew();
|
|
459
|
+
while (IsUwpFrameOnly(h) && sw.ElapsedMilliseconds < timeoutMs) Thread.Sleep(100);
|
|
460
|
+
return sw.ElapsedMilliseconds;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** Đẩ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. */
|
|
464
|
+
static void SendToBack(IntPtr h) {
|
|
465
|
+
if (h == IntPtr.Zero || !Native.IsWindow(h)) return;
|
|
466
|
+
// 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.
|
|
467
|
+
Native.SetWindowPos(h, new IntPtr(1), 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0010 | 0x4000);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** 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ả). */
|
|
471
|
+
static bool RestoreForeground(IntPtr prev, IntPtr target) {
|
|
472
|
+
IntPtr cur = Native.GetForegroundWindow();
|
|
473
|
+
if (prev == IntPtr.Zero || cur == prev || prev == target || !Native.IsWindow(prev)) return false;
|
|
474
|
+
uint pid;
|
|
475
|
+
uint curThread = Native.GetWindowThreadProcessId(cur, out pid);
|
|
476
|
+
uint me = Native.GetCurrentThreadId();
|
|
477
|
+
bool attached = curThread != 0 && curThread != me && IsWindowResponsive(cur, 200) && Native.AttachThreadInput(me, curThread, true);
|
|
478
|
+
try { Native.SetForegroundWindow(prev); } finally { if (attached) Native.AttachThreadInput(me, curThread, false); }
|
|
479
|
+
return Native.GetForegroundWindow() == prev;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
const uint GA_ROOT = 2, GA_ROOTOWNER = 3;
|
|
483
|
+
const int GWL_STYLE = -16;
|
|
484
|
+
const int WS_POPUP = unchecked((int)0x80000000), WS_CAPTION = 0x00C00000;
|
|
485
|
+
|
|
486
|
+
static IntPtr RootOf(IntPtr h) {
|
|
487
|
+
if (h == IntPtr.Zero) return IntPtr.Zero;
|
|
488
|
+
IntPtr r = Native.GetAncestor(h, GA_ROOT);
|
|
489
|
+
return r == IntPtr.Zero ? h : r;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
static IntPtr RootOwnerOf(IntPtr h) {
|
|
493
|
+
if (h == IntPtr.Zero) return IntPtr.Zero;
|
|
494
|
+
IntPtr r = Native.GetAncestor(h, GA_ROOTOWNER);
|
|
495
|
+
return r == IntPtr.Zero ? RootOf(h) : r;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** w thuộc cửa sổ đích: cùng cửa sổ gốc, hoặc hộp thoại / popup cùng cây sở hữu (hộp thoại modal của đích lên trên cùng là đúng). */
|
|
499
|
+
static bool BelongsTo(IntPtr w, IntPtr target) {
|
|
500
|
+
if (w == IntPtr.Zero || target == IntPtr.Zero) return false;
|
|
501
|
+
IntPtr tr = RootOf(target), wr = RootOf(w);
|
|
502
|
+
if (wr == tr) return true;
|
|
503
|
+
IntPtr two = RootOwnerOf(target), wo = RootOwnerOf(w);
|
|
504
|
+
return wo == tr || wo == two || wr == two;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Điểm màn hình (x, y) hiện đang thuộc cửa sổ đích — không bị cửa sổ khác che. Menu Win32 / popup không khung cùng tiến trình cũng tính. */
|
|
508
|
+
static bool PointOnWindow(int x, int y, IntPtr target) {
|
|
509
|
+
var p = new Native.POINT { X = x, Y = y };
|
|
510
|
+
IntPtr hit = Native.WindowFromPoint(p);
|
|
511
|
+
if (BelongsTo(hit, target)) return true;
|
|
512
|
+
IntPtr root = RootOf(hit);
|
|
513
|
+
if (root == IntPtr.Zero) return false;
|
|
514
|
+
uint hp, tp;
|
|
515
|
+
Native.GetWindowThreadProcessId(root, out hp);
|
|
516
|
+
Native.GetWindowThreadProcessId(target, out tp);
|
|
517
|
+
if (hp != tp) return false;
|
|
518
|
+
int style = Native.GetWindowLong(root, GWL_STYLE);
|
|
519
|
+
return ClassOf(root) == "#32768" || ((style & WS_POPUP) != 0 && (style & WS_CAPTION) != WS_CAPTION);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** Bấm chuột thật: điểm bị cửa sổ khác che → không bấm (bấm sẽ rơi vào cửa sổ đang che, có thể là việc riêng của người dùng). */
|
|
523
|
+
static void AssertPointOnWindow(int x, int y, IntPtr target) {
|
|
524
|
+
if (PointOnWindow(x, y, target)) return;
|
|
525
|
+
IntPtr hit = Native.WindowFromPoint(new Native.POINT { X = x, Y = y });
|
|
526
|
+
uint pid = 0;
|
|
527
|
+
if (hit != IntPtr.Zero) Native.GetWindowThreadProcessId(hit, out pid);
|
|
528
|
+
// 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.
|
|
529
|
+
if (hit != IntPtr.Zero && ClassOf(RootOf(hit)) == "Shell_SystemDim") {
|
|
530
|
+
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)");
|
|
531
|
+
}
|
|
532
|
+
string who = pid == 0 ? "nothing" : ProcessName(pid);
|
|
533
|
+
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)");
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Đưa cửa sổ lên trên cùng (khôi phục nếu thu nhỏ). Trả true khi cửa sổ trên cùng đúng là đích (hoặc hộp thoại của nó) — Windows có thể từ
|
|
538
|
+
* chối SetForegroundWindow (tiến trình khác vừa có input, khoá đổi cửa sổ) mà không báo lỗi (02/11/2026: trước đây vẫn gõ / bấm tiếp).
|
|
539
|
+
*/
|
|
540
|
+
static bool ForceForeground(IntPtr h) {
|
|
541
|
+
if (h == IntPtr.Zero) return false;
|
|
542
|
+
if (Native.GetForegroundWindow() == h && !Native.IsIconic(h)) {
|
|
543
|
+
// Đang là cửa sổ được focus nhưng có thể đã bị SendToBack đẩy xuống đáy chồng (cửa sổ AI vừa mở / vừa thao tác) — vẫn bị cửa sổ khác che,
|
|
544
|
+
// chuột thật sẽ GUI_FOCUS_LOST (gui-bench 13/11/2026). Đưa lên trên cùng; không đổi focus nên không cần mẹo phím Alt.
|
|
545
|
+
Native.BringWindowToTop(h);
|
|
546
|
+
Native.SetWindowPos(h, IntPtr.Zero, 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0010);
|
|
547
|
+
Thread.Sleep(30);
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
GuardInput();
|
|
551
|
+
if (Native.IsIconic(h)) { Native.ShowWindow(h, 9); Thread.Sleep(120); }
|
|
552
|
+
if (Native.GetForegroundWindow() == h) return true;
|
|
553
|
+
// 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.
|
|
554
|
+
KeyTap(0x12);
|
|
555
|
+
Native.SetForegroundWindow(h);
|
|
556
|
+
Native.BringWindowToTop(h);
|
|
557
|
+
Thread.Sleep(80);
|
|
558
|
+
if (BelongsTo(Native.GetForegroundWindow(), h)) return true;
|
|
559
|
+
// Lần 2: gắn tạm luồng input với cửa sổ đang ở trên cùng rồi đặt lại.
|
|
560
|
+
IntPtr cur = Native.GetForegroundWindow();
|
|
561
|
+
uint pid;
|
|
562
|
+
uint curThread = cur == IntPtr.Zero ? 0 : Native.GetWindowThreadProcessId(cur, out pid);
|
|
563
|
+
uint me = Native.GetCurrentThreadId();
|
|
564
|
+
bool attached = curThread != 0 && curThread != me && Native.AttachThreadInput(me, curThread, true);
|
|
565
|
+
try { Native.SetForegroundWindow(h); Native.BringWindowToTop(h); } finally { if (attached) Native.AttachThreadInput(me, curThread, false); }
|
|
566
|
+
Thread.Sleep(80);
|
|
567
|
+
return BelongsTo(Native.GetForegroundWindow(), h);
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** Chuột / phím thật cần cửa sổ đích ở trên cùng; không đưa lên được → dừng, KHÔNG phát input vào cửa sổ đang ở trên. */
|
|
571
|
+
static void RequireForeground(IntPtr h) {
|
|
572
|
+
if (h == IntPtr.Zero) throw new GuiError("INVALID_ARGS", "Name the window for real mouse/keyboard input (window: handle 0x… or a title/process)");
|
|
573
|
+
if (!ForceForeground(h)) {
|
|
574
|
+
throw new GuiError("GUI_FOCUS_LOST", "Could not bring the target window to the front (Windows refused, or another window took focus) — nothing was clicked or typed. Prefer an accessibility action (set_value / click by node_id), or ask the user to switch to that window");
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** Giữa lúc gõ / bấm phím: cửa sổ trên cùng vẫn là đích, không thì dừng (phím sẽ rơi vào cửa sổ khác). */
|
|
579
|
+
static void AssertStillForeground(IntPtr h, string done) {
|
|
580
|
+
if (h == IntPtr.Zero || BelongsTo(Native.GetForegroundWindow(), h)) return;
|
|
581
|
+
throw new GuiError("GUI_FOCUS_LOST", "Another window took focus — stopped" + (string.IsNullOrEmpty(done) ? "" : " after " + done));
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
static object FocusWindowOp(Dictionary<string, object> a) {
|
|
585
|
+
IntPtr h = ResolveWindow(a);
|
|
586
|
+
backgroundOnly = false;
|
|
587
|
+
inputGraceMs = Int(a, "user_input_grace_ms", 1500);
|
|
588
|
+
pendingInputCheck = Bool(a, "check_user_input", false);
|
|
589
|
+
try { ForceForeground(h); } finally { pendingInputCheck = false; }
|
|
590
|
+
return new Dictionary<string, object> { { "focused", Native.GetForegroundWindow() == h }, { "window", WindowInfo(h, Native.GetForegroundWindow()) } };
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// ── observe: cây trợ năng rút gọn + ảnh ─────────────────────────────────────────────────────
|
|
594
|
+
|
|
595
|
+
static CacheRequest BuildCache() {
|
|
596
|
+
var c = new CacheRequest();
|
|
597
|
+
c.TreeScope = TreeScope.Element;
|
|
598
|
+
c.TreeFilter = Automation.ControlViewCondition;
|
|
599
|
+
c.AutomationElementMode = AutomationElementMode.Full;
|
|
600
|
+
c.Add(AutomationElement.NameProperty); c.Add(AutomationElement.ControlTypeProperty); c.Add(AutomationElement.AutomationIdProperty);
|
|
601
|
+
c.Add(AutomationElement.ClassNameProperty); c.Add(AutomationElement.BoundingRectangleProperty); c.Add(AutomationElement.IsEnabledProperty);
|
|
602
|
+
c.Add(AutomationElement.IsOffscreenProperty); c.Add(AutomationElement.IsPasswordProperty); c.Add(AutomationElement.HasKeyboardFocusProperty);
|
|
603
|
+
c.Add(AutomationElement.AcceleratorKeyProperty); c.Add(AutomationElement.AccessKeyProperty); c.Add(AutomationElement.HelpTextProperty);
|
|
604
|
+
c.Add(AutomationElement.IsInvokePatternAvailableProperty); c.Add(AutomationElement.IsValuePatternAvailableProperty);
|
|
605
|
+
c.Add(AutomationElement.IsTogglePatternAvailableProperty); c.Add(AutomationElement.IsSelectionItemPatternAvailableProperty);
|
|
606
|
+
c.Add(AutomationElement.IsExpandCollapsePatternAvailableProperty); c.Add(AutomationElement.IsScrollPatternAvailableProperty);
|
|
607
|
+
c.Add(AutomationElement.IsTextPatternAvailableProperty);
|
|
608
|
+
c.Add(ValuePattern.ValueProperty); c.Add(ValuePattern.IsReadOnlyProperty); c.Add(TogglePattern.ToggleStateProperty);
|
|
609
|
+
c.Add(SelectionItemPattern.IsSelectedProperty); c.Add(ExpandCollapsePattern.ExpandCollapseStateProperty);
|
|
610
|
+
return c;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
static object Cached(AutomationElement e, AutomationProperty p) {
|
|
614
|
+
try { var v = e.GetCachedPropertyValue(p, true); return v == AutomationElement.NotSupported ? null : v; } catch { return null; }
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
static string Clip(string s, int max) { if (s == null) return null; s = s.Replace("\r", " ").Replace("\n", " ").Trim(); return s.Length > max ? s.Substring(0, max) + "…" : s; }
|
|
618
|
+
|
|
619
|
+
class ObsItem { public AutomationElement E; public int Depth; public bool InChrome; }
|
|
620
|
+
|
|
621
|
+
/**
|
|
622
|
+
* Khung cửa sổ do hệ điều hành / khung ứng dụng vẽ: thanh tiêu đề, menu hệ thống ("System", AutomationId "Item 1"), nút thu nhỏ / phóng to /
|
|
623
|
+
* đóng. gui-bench 13/11/2026: "bấm 1" khớp AutomationId "Item 1" của menu hệ thống và bấm bằng chuột thật mà vẫn báo ok; "System" của Settings
|
|
624
|
+
* mơ hồ với menu hệ thống. Đánh dấu "chrome" để chọn đích bỏ qua (trừ khi nói thẳng thu nhỏ / đóng…) và để không tính vào chất lượng cây.
|
|
625
|
+
*/
|
|
626
|
+
static bool IsChromeRoot(Dictionary<string, object> n) {
|
|
627
|
+
string role = Convert.ToString(n["role"]);
|
|
628
|
+
string aid = n.ContainsKey("automation_id") ? Convert.ToString(n["automation_id"]) : "";
|
|
629
|
+
string cls = n.ContainsKey("class") ? Convert.ToString(n["class"]) : "";
|
|
630
|
+
return role == "titlebar" || aid == "TitleBar" || aid == "SystemMenuBar" || cls == "ApplicationFrameTitleBarWindow";
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** Trong vùng khung: chỉ phần tử của chính khung là chrome — tab / ô tìm kiếm ứng dụng tự đặt lên thanh tiêu đề (Explorer, Edge) vẫn là nội dung. */
|
|
634
|
+
static bool IsChromeNode(Dictionary<string, object> n) {
|
|
635
|
+
if (IsChromeRoot(n)) return true;
|
|
636
|
+
string role = Convert.ToString(n["role"]);
|
|
637
|
+
string aid = n.ContainsKey("automation_id") ? Convert.ToString(n["automation_id"]) : "";
|
|
638
|
+
return role == "menubar" || role == "menuitem" || IsCaptionButton(n);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* Nút thu nhỏ / phóng to / đóng của khung (ứng dụng Store có thêm một bộ ngoài thanh tiêu đề). Theo AutomationId (tên đổi theo ngôn ngữ:
|
|
643
|
+
* "Thu nhỏ", "Đóng"). Nút "Close" riêng của ứng dụng có cùng AutomationId cũng bị tính là khung — vô hại: nói "đóng / close" là vẫn chọn được.
|
|
644
|
+
*/
|
|
645
|
+
static bool IsCaptionButton(Dictionary<string, object> n) {
|
|
646
|
+
if (Convert.ToString(n["role"]) != "button" || !n.ContainsKey("automation_id")) return false;
|
|
647
|
+
string aid = Convert.ToString(n["automation_id"]);
|
|
648
|
+
return aid == "Minimize" || aid == "Maximize" || aid == "Restore" || aid == "Close";
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
static Dictionary<string, object> Describe(AutomationElement e, string nodeId, int depth, System.Windows.Rect win) {
|
|
652
|
+
var n = new Dictionary<string, object>();
|
|
653
|
+
n["id"] = nodeId;
|
|
654
|
+
var ct = Cached(e, AutomationElement.ControlTypeProperty) as ControlType;
|
|
655
|
+
n["role"] = ct == null ? "unknown" : ct.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant();
|
|
656
|
+
string name = Clip(Cached(e, AutomationElement.NameProperty) as string, 160);
|
|
657
|
+
if (!string.IsNullOrEmpty(name)) n["name"] = name;
|
|
658
|
+
string aid = Cached(e, AutomationElement.AutomationIdProperty) as string;
|
|
659
|
+
if (!string.IsNullOrEmpty(aid) && aid.Length <= 80) n["automation_id"] = aid;
|
|
660
|
+
string cls = Cached(e, AutomationElement.ClassNameProperty) as string;
|
|
661
|
+
if (!string.IsNullOrEmpty(cls) && cls.Length <= 60) n["class"] = cls;
|
|
662
|
+
n["depth"] = depth;
|
|
663
|
+
var patterns = new List<string>();
|
|
664
|
+
if (true.Equals(Cached(e, AutomationElement.IsInvokePatternAvailableProperty))) patterns.Add("invoke");
|
|
665
|
+
if (true.Equals(Cached(e, AutomationElement.IsValuePatternAvailableProperty))) {
|
|
666
|
+
patterns.Add("value");
|
|
667
|
+
if (!true.Equals(Cached(e, AutomationElement.IsPasswordProperty))) {
|
|
668
|
+
string v = Clip(Cached(e, ValuePattern.ValueProperty) as string, 300);
|
|
669
|
+
if (!string.IsNullOrEmpty(v)) n["value"] = v;
|
|
670
|
+
}
|
|
671
|
+
if (true.Equals(Cached(e, ValuePattern.IsReadOnlyProperty))) n["readonly"] = true;
|
|
672
|
+
}
|
|
673
|
+
if (true.Equals(Cached(e, AutomationElement.IsTogglePatternAvailableProperty))) {
|
|
674
|
+
patterns.Add("toggle");
|
|
675
|
+
var ts = Cached(e, TogglePattern.ToggleStateProperty);
|
|
676
|
+
if (ts != null) n["checked"] = ts.ToString().ToLowerInvariant();
|
|
677
|
+
}
|
|
678
|
+
if (true.Equals(Cached(e, AutomationElement.IsSelectionItemPatternAvailableProperty))) {
|
|
679
|
+
patterns.Add("select");
|
|
680
|
+
if (true.Equals(Cached(e, SelectionItemPattern.IsSelectedProperty))) n["selected"] = true;
|
|
681
|
+
}
|
|
682
|
+
if (true.Equals(Cached(e, AutomationElement.IsExpandCollapsePatternAvailableProperty))) {
|
|
683
|
+
patterns.Add("expand");
|
|
684
|
+
var es = Cached(e, ExpandCollapsePattern.ExpandCollapseStateProperty);
|
|
685
|
+
if (es != null) n["expanded"] = es.ToString().ToLowerInvariant();
|
|
686
|
+
}
|
|
687
|
+
if (true.Equals(Cached(e, AutomationElement.IsScrollPatternAvailableProperty))) patterns.Add("scroll");
|
|
688
|
+
if (true.Equals(Cached(e, AutomationElement.IsTextPatternAvailableProperty))) patterns.Add("text");
|
|
689
|
+
if (patterns.Count > 0) n["patterns"] = patterns;
|
|
690
|
+
if (true.Equals(Cached(e, AutomationElement.IsPasswordProperty))) n["password"] = true;
|
|
691
|
+
if (false.Equals(Cached(e, AutomationElement.IsEnabledProperty))) n["disabled"] = true;
|
|
692
|
+
if (true.Equals(Cached(e, AutomationElement.HasKeyboardFocusProperty))) n["focused"] = true;
|
|
693
|
+
string acc = Cached(e, AutomationElement.AcceleratorKeyProperty) as string;
|
|
694
|
+
if (!string.IsNullOrEmpty(acc)) n["shortcut"] = acc;
|
|
695
|
+
string help = Clip(Cached(e, AutomationElement.HelpTextProperty) as string, 120);
|
|
696
|
+
if (!string.IsNullOrEmpty(help) && help != name) n["help"] = help;
|
|
697
|
+
object rectObj = Cached(e, AutomationElement.BoundingRectangleProperty);
|
|
698
|
+
if (rectObj is System.Windows.Rect) {
|
|
699
|
+
var r = (System.Windows.Rect)rectObj;
|
|
700
|
+
if (!r.IsEmpty && r.Width > 0 && r.Height > 0) {
|
|
701
|
+
n["rect"] = new Dictionary<string, object> { { "x", (int)(r.X - win.X) }, { "y", (int)(r.Y - win.Y) }, { "w", (int)r.Width }, { "h", (int)r.Height } };
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
if (true.Equals(Cached(e, AutomationElement.IsOffscreenProperty))) n["offscreen"] = true;
|
|
705
|
+
return n;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
static bool IsInteractive(Dictionary<string, object> n) {
|
|
709
|
+
if (n.ContainsKey("patterns")) return true;
|
|
710
|
+
string role = Convert.ToString(n["role"]);
|
|
711
|
+
return role == "button" || role == "edit" || role == "menuitem" || role == "hyperlink" || role == "listitem" || role == "tabitem" || role == "treeitem" || role == "checkbox" || role == "radiobutton" || role == "combobox";
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
const int FIND_ELEMENT_BUDGET_MS = 3000, OBSERVE_BUDGET_MS = 5000, LIST_BUDGET_MS = 1500, MAX_CHILDREN_PER_NODE = 80, MAX_OFFSCREEN_CHILDREN = 15;
|
|
715
|
+
static readonly CacheRequest Lean = BuildLeanCache();
|
|
716
|
+
static CacheRequest BuildLeanCache() {
|
|
717
|
+
var c = new CacheRequest();
|
|
718
|
+
c.TreeScope = TreeScope.Element;
|
|
719
|
+
c.TreeFilter = Automation.ControlViewCondition;
|
|
720
|
+
c.Add(AutomationElement.IsOffscreenProperty);
|
|
721
|
+
return c;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* 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:
|
|
726
|
+
* 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,
|
|
727
|
+
* để 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,
|
|
728
|
+
* dừng ở chúng sẽ không bao giờ thấy dòng đang hiện.
|
|
729
|
+
*/
|
|
730
|
+
static List<AutomationElement> ChildrenOf(AutomationElement e, string role, CacheRequest cache, TreeWalker walker, Stopwatch sw, int budgetMs, ref bool cut) {
|
|
731
|
+
var kids = new List<AutomationElement>();
|
|
732
|
+
if (role != "table" && role != "datagrid" && role != "list" && role != "tree") {
|
|
733
|
+
try {
|
|
734
|
+
using (cache.Activate()) { foreach (AutomationElement k in e.FindAll(TreeScope.Children, Condition.TrueCondition)) kids.Add(k); }
|
|
735
|
+
} catch { /* phần tử vừa mất giữa chừng */ }
|
|
736
|
+
return kids;
|
|
737
|
+
}
|
|
738
|
+
long stopAt = Math.Min(sw.ElapsedMilliseconds + LIST_BUDGET_MS, budgetMs);
|
|
739
|
+
var visible = new List<AutomationElement>();
|
|
740
|
+
var hidden = new List<AutomationElement>();
|
|
741
|
+
try {
|
|
742
|
+
using (Lean.Activate()) {
|
|
743
|
+
// Đ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.
|
|
744
|
+
AutomationElement k = walker.GetFirstChild(e, Lean);
|
|
745
|
+
int visibleRun = 0;
|
|
746
|
+
bool passedView = false;
|
|
747
|
+
while (k != null) {
|
|
748
|
+
if (visible.Count >= MAX_CHILDREN_PER_NODE || sw.ElapsedMilliseconds >= stopAt) { cut = true; break; }
|
|
749
|
+
if (!true.Equals(Cached(k, AutomationElement.IsOffscreenProperty))) { visible.Add(k); if (++visibleRun >= 3) passedView = true; }
|
|
750
|
+
else {
|
|
751
|
+
visibleRun = 0;
|
|
752
|
+
if (hidden.Count < MAX_OFFSCREEN_CHILDREN) hidden.Add(k);
|
|
753
|
+
else {
|
|
754
|
+
cut = true;
|
|
755
|
+
// Đã 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.
|
|
756
|
+
if (passedView) break;
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
k = walker.GetNextSibling(k, Lean);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
} catch { /* phần tử vừa mất giữa chừng: giữ phần đã đọc được */ }
|
|
763
|
+
// Đọ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.
|
|
764
|
+
using (cache.Activate()) {
|
|
765
|
+
visible.AddRange(hidden);
|
|
766
|
+
foreach (AutomationElement x in visible) {
|
|
767
|
+
if (sw.ElapsedMilliseconds >= budgetMs) { cut = true; break; }
|
|
768
|
+
try { kids.Add(x.GetUpdatedCache(cache)); } catch { /* dòng vừa mất */ }
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
return kids;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Cửa sổ đang bị một hộp thoại modal của chính nó khoá (MessageBox "Xoá phiếu?", "Lưu thay đổi?", hộp Lưu thành): hộp thoại là cửa sổ riêng
|
|
776
|
+
* nên không có trong cây của cửa sổ chính — tìm "Không" / "No" trong cửa sổ chính không bao giờ thấy, mà cửa sổ chính thì không nhận thao
|
|
777
|
+
* tác nào. Trả hộp thoại đó (GW_ENABLEDPOPUP) để observe / find / gui.do làm việc thẳng trên nó; không có → IntPtr.Zero.
|
|
778
|
+
*/
|
|
779
|
+
static IntPtr ModalPopupOf(IntPtr h) {
|
|
780
|
+
if (h == IntPtr.Zero || Native.IsWindowEnabled(h)) return IntPtr.Zero;
|
|
781
|
+
IntPtr p = Native.GetWindow(h, 6);
|
|
782
|
+
return p != IntPtr.Zero && p != h && Native.IsWindowVisible(p) ? p : IntPtr.Zero;
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
static object Observe(Dictionary<string, object> a) {
|
|
786
|
+
IntPtr h = ResolveWindow(a);
|
|
787
|
+
if (h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused");
|
|
788
|
+
IntPtr blockedOwner = IntPtr.Zero;
|
|
789
|
+
IntPtr modal = ModalPopupOf(h);
|
|
790
|
+
if (modal != IntPtr.Zero) { blockedOwner = h; h = modal; }
|
|
791
|
+
int maxNodes = Math.Max(20, Math.Min(Int(a, "max_nodes", 300), 1500));
|
|
792
|
+
int maxDepth = Math.Max(2, Math.Min(Int(a, "max_depth", 25), 60));
|
|
793
|
+
int budgetMs = Math.Max(500, Math.Min(Int(a, "budget_ms", OBSERVE_BUDGET_MS), 30000));
|
|
794
|
+
var sw = Stopwatch.StartNew();
|
|
795
|
+
AssertWindowResponsive(h);
|
|
796
|
+
if (Native.IsIconic(h)) {
|
|
797
|
+
IntPtr fgBefore = Native.GetForegroundWindow();
|
|
798
|
+
Native.ShowWindow(h, 4);
|
|
799
|
+
if (fgBefore != IntPtr.Zero && fgBefore != h) {
|
|
800
|
+
RestoreForeground(fgBefore, h);
|
|
801
|
+
SendToBack(h);
|
|
802
|
+
}
|
|
803
|
+
Thread.Sleep(60);
|
|
804
|
+
}
|
|
805
|
+
AutomationElement root = AutomationElement.FromHandle(h);
|
|
806
|
+
var cache = BuildCache();
|
|
807
|
+
var nodes = new List<object>();
|
|
808
|
+
var map = new Dictionary<int, AutomationElement>();
|
|
809
|
+
int snap = ++snapSeq;
|
|
810
|
+
Native.RECT wr; Native.GetWindowRect(h, out wr);
|
|
811
|
+
var winRect = new System.Windows.Rect(wr.Left, wr.Top, Math.Max(1, wr.Right - wr.Left), Math.Max(1, wr.Bottom - wr.Top));
|
|
812
|
+
int named = 0, interactive = 0;
|
|
813
|
+
bool truncated = false;
|
|
814
|
+
var queue = new Queue<ObsItem>();
|
|
815
|
+
using (cache.Activate()) {
|
|
816
|
+
root = root.GetUpdatedCache(cache);
|
|
817
|
+
}
|
|
818
|
+
queue.Enqueue(new ObsItem { E = root, Depth = 0 });
|
|
819
|
+
var walker = new TreeWalker(Automation.ControlViewCondition);
|
|
820
|
+
bool timedOut = false, listCut = false;
|
|
821
|
+
var unreached = new List<AutomationElement>();
|
|
822
|
+
while (queue.Count > 0) {
|
|
823
|
+
if (nodes.Count >= maxNodes) { truncated = true; break; }
|
|
824
|
+
if (sw.ElapsedMilliseconds >= budgetMs) { truncated = true; timedOut = true; break; }
|
|
825
|
+
var item = queue.Dequeue();
|
|
826
|
+
AutomationElement e = item.E;
|
|
827
|
+
int idx = nodes.Count;
|
|
828
|
+
var n = Describe(e, snap + "." + idx, item.Depth, winRect);
|
|
829
|
+
bool inChrome = item.InChrome || IsChromeRoot(n);
|
|
830
|
+
bool chrome = (inChrome && IsChromeNode(n)) || IsCaptionButton(n);
|
|
831
|
+
if (chrome) n["chrome"] = true;
|
|
832
|
+
// Ngoài màn hình và không có chữ → bỏ (danh sách dài cuộn ẩn), vẫn đi vào con nếu là khung chứa.
|
|
833
|
+
bool skip = n.ContainsKey("offscreen") && !n.ContainsKey("name") && item.Depth > 0;
|
|
834
|
+
if (!skip) {
|
|
835
|
+
map[idx] = e;
|
|
836
|
+
nodes.Add(n);
|
|
837
|
+
// Khung cửa sổ (thanh tiêu đề, menu hệ thống, nút thu nhỏ / đóng) không tính: cửa sổ vẽ tay hoàn toàn vẫn có đủ chừng ấy phần tử,
|
|
838
|
+
// tính vào là chấm "good" và không bao giờ tự đọc chữ trên ảnh (gui-bench 13/11/2026).
|
|
839
|
+
if (!chrome && n.ContainsKey("name")) named++;
|
|
840
|
+
if (!chrome && IsInteractive(n)) interactive++;
|
|
841
|
+
}
|
|
842
|
+
if (item.Depth >= maxDepth) continue;
|
|
843
|
+
bool thisCut = false;
|
|
844
|
+
int visibleKids = 0;
|
|
845
|
+
foreach (AutomationElement k in ChildrenOf(e, Convert.ToString(n["role"]), cache, walker, sw, budgetMs, ref thisCut)) {
|
|
846
|
+
if (!true.Equals(Cached(k, AutomationElement.IsOffscreenProperty))) visibleKids++;
|
|
847
|
+
queue.Enqueue(new ObsItem { E = k, Depth = item.Depth + 1, InChrome = inChrome });
|
|
848
|
+
}
|
|
849
|
+
if (thisCut) {
|
|
850
|
+
listCut = true;
|
|
851
|
+
// 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.
|
|
852
|
+
if (visibleKids <= 2) unreached.Add(e);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
if (listCut) truncated = true;
|
|
856
|
+
lock (StateLock) {
|
|
857
|
+
Snapshots[snap] = map;
|
|
858
|
+
SnapshotWindow[snap] = h;
|
|
859
|
+
while (Snapshots.Count > KEEP_SNAPSHOTS) {
|
|
860
|
+
int oldest = int.MaxValue;
|
|
861
|
+
foreach (var k in Snapshots.Keys) if (k < oldest) oldest = k;
|
|
862
|
+
Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest); OcrSnapshots.Remove(oldest);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
foreach (AutomationElement list in unreached) AddVisibleRows(list, snap, nodes, wr, sw, budgetMs);
|
|
866
|
+
// 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ị.
|
|
867
|
+
// Ứ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.
|
|
868
|
+
bool frameOnly = IsUwpFrameOnly(h);
|
|
869
|
+
string quality = (!frameOnly && interactive >= 3 && named >= 5) ? "good" : "poor";
|
|
870
|
+
var res = new Dictionary<string, object> {
|
|
871
|
+
{ "snapshot", snap }, { "window", WindowInfo(h, Native.GetForegroundWindow()) }, { "nodes", nodes }, { "node_count", nodes.Count },
|
|
872
|
+
{ "interactive_count", interactive }, { "tree_quality", quality }, { "truncated", truncated }, { "tree_ms", sw.ElapsedMilliseconds },
|
|
873
|
+
{ "truncated_by", timedOut ? "time" : listCut ? "long_list" : truncated ? "node_limit" : null },
|
|
874
|
+
{ "dpi", (long)SafeDpi(h) },
|
|
875
|
+
};
|
|
876
|
+
if (frameOnly) res["content_unavailable"] = true;
|
|
877
|
+
if (blockedOwner != IntPtr.Zero) res["modal_dialog_of"] = WindowInfo(blockedOwner, Native.GetForegroundWindow());
|
|
878
|
+
bool wantImage = Bool(a, "include_image", false) || (quality == "poor" && Bool(a, "image_when_poor", true));
|
|
879
|
+
// 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
|
|
880
|
+
// ở 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.
|
|
881
|
+
bool wantOcr = Bool(a, "ocr", quality == "poor");
|
|
882
|
+
if (wantImage || wantOcr) {
|
|
883
|
+
var sw2 = Stopwatch.StartNew();
|
|
884
|
+
string imageError;
|
|
885
|
+
var bmp = GrabWindow(h, out imageError);
|
|
886
|
+
if (bmp == null) {
|
|
887
|
+
res["image_error"] = imageError;
|
|
888
|
+
if (wantOcr) res["ocr"] = new Dictionary<string, object> { { "error", "no usable screenshot: " + imageError } };
|
|
889
|
+
} else {
|
|
890
|
+
using (bmp) {
|
|
891
|
+
if (wantImage) {
|
|
892
|
+
res["image"] = EncodeImage(bmp, Int(a, "image_max_width", 1366), Int(a, "image_quality", 70));
|
|
893
|
+
res["image_ms"] = sw2.ElapsedMilliseconds;
|
|
894
|
+
}
|
|
895
|
+
if (wantOcr) AddOcrNodes(res, nodes, snap, bmp, Str(a, "ocr_lang"), Int(a, "ocr_max_nodes", 200));
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
return res;
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/**
|
|
903
|
+
* 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 ở
|
|
904
|
+
* 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
|
|
905
|
+
* ("<snap>.t<k>"): có toạ độ, gui.act bấm được.
|
|
906
|
+
*/
|
|
907
|
+
static void AddVisibleRows(AutomationElement list, int snap, List<object> nodes, Native.RECT wr, Stopwatch sw, int budgetMs) {
|
|
908
|
+
Accessibility.IAccessible client = AccessibleClient(OwnHandle(list));
|
|
909
|
+
object boxObj = Cached(list, AutomationElement.BoundingRectangleProperty);
|
|
910
|
+
if (client == null || !(boxObj is System.Windows.Rect)) return;
|
|
911
|
+
var box = (System.Windows.Rect)boxObj;
|
|
912
|
+
if (box.IsEmpty || box.Height < 4) return;
|
|
913
|
+
var known = new HashSet<string>();
|
|
914
|
+
foreach (object o in nodes) {
|
|
915
|
+
var d = (Dictionary<string, object>)o;
|
|
916
|
+
if (d.ContainsKey("name") && !d.ContainsKey("offscreen")) known.Add(Convert.ToString(d["name"]));
|
|
917
|
+
}
|
|
918
|
+
var rects = new List<System.Windows.Rect>();
|
|
919
|
+
lock (StateLock) { List<System.Windows.Rect> had; if (OcrSnapshots.TryGetValue(snap, out had)) rects = had; else OcrSnapshots[snap] = rects; }
|
|
920
|
+
int added = 0;
|
|
921
|
+
foreach (AccRow row in SampleRows(client, box, sw, budgetMs + 1000)) {
|
|
922
|
+
if (added >= 60 || !known.Add(row.Name)) continue;
|
|
923
|
+
var n = new Dictionary<string, object> {
|
|
924
|
+
{ "id", snap + ".t" + rects.Count }, { "role", "row" }, { "name", Clip(row.Name, 200) }, { "source", "accessible" },
|
|
925
|
+
{ "rect", new Dictionary<string, object> { { "x", row.Left - wr.Left }, { "y", row.Top - wr.Top }, { "w", row.Width }, { "h", row.Height } } },
|
|
926
|
+
};
|
|
927
|
+
if (!string.IsNullOrEmpty(row.Value)) n["value"] = Clip(row.Value, 400);
|
|
928
|
+
lock (StateLock) { rects.Add(new System.Windows.Rect(row.Left - wr.Left, row.Top - wr.Top, row.Width, row.Height)); }
|
|
929
|
+
nodes.Add(n);
|
|
930
|
+
added++;
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
class AccRow { public string Name, Value; public int Left, Top, Width, Height; }
|
|
935
|
+
|
|
936
|
+
/** 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. */
|
|
937
|
+
static List<AccRow> SampleRows(Accessibility.IAccessible client, System.Windows.Rect box, Stopwatch sw, long stopAtMs) {
|
|
938
|
+
var rows = new List<AccRow>();
|
|
939
|
+
int x = (int)(box.Left + Math.Min(60, box.Width / 3));
|
|
940
|
+
double y = box.Top + 2;
|
|
941
|
+
try {
|
|
942
|
+
while (y < box.Bottom && sw.ElapsedMilliseconds < stopAtMs) {
|
|
943
|
+
object hit = client.accHitTest(x, (int)y);
|
|
944
|
+
Accessibility.IAccessible row = hit as Accessibility.IAccessible ?? client;
|
|
945
|
+
object child = hit is int ? hit : 0;
|
|
946
|
+
if (ReferenceEquals(row, client) && child is int && (int)child == 0) { y += 8; continue; }
|
|
947
|
+
// Trúng một ô: lấy cả dòng để có đủ các cột.
|
|
948
|
+
if (Convert.ToInt32(row.get_accRole(child)) == ROLE_SYSTEM_CELL) {
|
|
949
|
+
var parent = row.accParent as Accessibility.IAccessible;
|
|
950
|
+
if (parent != null) { row = parent; child = 0; }
|
|
951
|
+
}
|
|
952
|
+
int left, top, w, h;
|
|
953
|
+
row.accLocation(out left, out top, out w, out h, child);
|
|
954
|
+
if (h <= 0) { y += 8; continue; }
|
|
955
|
+
string name = row.get_accName(child);
|
|
956
|
+
if (!string.IsNullOrEmpty(name) && (rows.Count == 0 || rows[rows.Count - 1].Name != name)) {
|
|
957
|
+
string value = null;
|
|
958
|
+
try { value = row.get_accValue(child); } catch (COMException) { }
|
|
959
|
+
rows.Add(new AccRow { Name = name, Value = value, Left = left, Top = top, Width = w, Height = h });
|
|
960
|
+
}
|
|
961
|
+
y = Math.Max(y + 1, top + h + 1);
|
|
962
|
+
}
|
|
963
|
+
} catch (COMException) { } catch (ArgumentException) { } catch (InvalidCastException) { } catch (NotImplementedException) { }
|
|
964
|
+
return rows;
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
const int READ_TABLE_BUDGET_MS = 20000;
|
|
968
|
+
/**
|
|
969
|
+
* 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
|
|
970
|
+
* (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.
|
|
971
|
+
*/
|
|
972
|
+
const int READ_TABLE_STALL_NOTCHES = 8, READ_TABLE_STALL_WAIT_MS = 80;
|
|
973
|
+
|
|
974
|
+
/** Lăn một nấc và chờ control xử lý xong, để lần đọc sau thấy đúng vị trí mới. */
|
|
975
|
+
static bool Wheel(IntPtr control, int delta, IntPtr screenPoint) {
|
|
976
|
+
IntPtr r;
|
|
977
|
+
return Native.SendMessageTimeoutPtr(control, WM_MOUSEWHEEL, new IntPtr(delta << 16), screenPoint, SMTO_ABORTIFHUNG, 1000, out r) != IntPtr.Zero;
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
static string FirstDataRow(List<AccRow> page) {
|
|
981
|
+
foreach (AccRow row in page) if (row.Value != row.Name) return row.Name;
|
|
982
|
+
return null;
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
const int ROLE_SYSTEM_COLUMNHEADER = 0x19, ROLE_SYSTEM_ROWHEADER = 0x1A;
|
|
986
|
+
|
|
987
|
+
/** Ô 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. */
|
|
988
|
+
static Accessibility.IAccessible CellAt(Accessibility.IAccessible client, int x, int y) {
|
|
989
|
+
var cell = client.accHitTest(x, y) as Accessibility.IAccessible;
|
|
990
|
+
if (cell == null) return null;
|
|
991
|
+
var deeper = cell.accHitTest(x, y) as Accessibility.IAccessible;
|
|
992
|
+
return deeper ?? cell;
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* 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ỏ;
|
|
997
|
+
* 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.
|
|
998
|
+
*/
|
|
999
|
+
static List<object> ReadColumns(Accessibility.IAccessible client, System.Windows.Rect box, AccRow header) {
|
|
1000
|
+
var cols = new List<object>();
|
|
1001
|
+
try {
|
|
1002
|
+
int y = header.Top + header.Height / 2, below = header.Top + header.Height + 4;
|
|
1003
|
+
string last = null;
|
|
1004
|
+
for (double x = box.Left + 2; x < box.Right && cols.Count < 100; x += 12) {
|
|
1005
|
+
var cell = CellAt(client, (int)x, y);
|
|
1006
|
+
if (cell == null || Convert.ToInt32(cell.get_accRole(0)) != ROLE_SYSTEM_COLUMNHEADER) continue;
|
|
1007
|
+
var under = CellAt(client, (int)x, below);
|
|
1008
|
+
if (under != null && Convert.ToInt32(under.get_accRole(0)) == ROLE_SYSTEM_ROWHEADER) continue;
|
|
1009
|
+
string name = cell.get_accName(0);
|
|
1010
|
+
if (string.IsNullOrEmpty(name) || name == last) continue;
|
|
1011
|
+
cols.Add(Clip(name, 120));
|
|
1012
|
+
last = name;
|
|
1013
|
+
}
|
|
1014
|
+
} catch (COMException) { } catch (ArgumentException) { } catch (InvalidCastException) { } catch (NotImplementedException) { }
|
|
1015
|
+
return cols;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* Đọ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;
|
|
1020
|
+
* 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.
|
|
1021
|
+
*/
|
|
1022
|
+
const int ROLE_SYSTEM_ROW = 0x1C, ROLE_SYSTEM_LISTITEM = 0x22, ROLE_SYSTEM_OUTLINEITEM = 0x24;
|
|
1023
|
+
|
|
1024
|
+
/**
|
|
1025
|
+
* Bảng MSAA (DataGridView, ListView Win32…) liệt kê được MỌI dòng — cả dòng đã cuộn khuất — qua AccessibleChildren, mỗi dòng một lần hỏi
|
|
1026
|
+
* tên + giá trị (giá trị = các ô nối bằng ";"). Không cuộn, không lấy mẫu theo toạ độ. gui-bench 13/11/2026: bảng 800 dòng cách cuộn +
|
|
1027
|
+
* accHitTest đọc được 104 dòng trong 20 s; cách này đọc hết. Control không liệt kê dòng kiểu đó (UIA thuần, ảo hoá) → null, đi đường cũ.
|
|
1028
|
+
*/
|
|
1029
|
+
static Dictionary<string, object> ReadRowsByChildren(Accessibility.IAccessible client, System.Windows.Rect box, int maxRows, Stopwatch sw) {
|
|
1030
|
+
try {
|
|
1031
|
+
int count = client.accChildCount;
|
|
1032
|
+
if (count < 2 || count > 500000) return null;
|
|
1033
|
+
int take = Math.Min(count, maxRows + 2);
|
|
1034
|
+
var kids = new object[take];
|
|
1035
|
+
int got;
|
|
1036
|
+
if (Native.AccessibleChildren(client, 0, take, kids, out got) != 0 || got < 2) return null;
|
|
1037
|
+
var rows = new List<object>();
|
|
1038
|
+
List<object> columns = null;
|
|
1039
|
+
int rowish = 0;
|
|
1040
|
+
for (int i = 0; i < got && rows.Count < maxRows; i++) {
|
|
1041
|
+
if (sw.ElapsedMilliseconds >= READ_TABLE_BUDGET_MS) break;
|
|
1042
|
+
Accessibility.IAccessible acc = kids[i] as Accessibility.IAccessible;
|
|
1043
|
+
object child = 0;
|
|
1044
|
+
if (acc == null) { if (!(kids[i] is int)) continue; acc = client; child = kids[i]; }
|
|
1045
|
+
int role;
|
|
1046
|
+
try { role = Convert.ToInt32(acc.get_accRole(child)); } catch (COMException) { continue; } catch (ArgumentException) { continue; }
|
|
1047
|
+
if (role != ROLE_SYSTEM_ROW && role != ROLE_SYSTEM_LISTITEM && role != ROLE_SYSTEM_OUTLINEITEM) continue;
|
|
1048
|
+
rowish++;
|
|
1049
|
+
string name = null, value = null;
|
|
1050
|
+
try { name = acc.get_accName(child); } catch (COMException) { }
|
|
1051
|
+
try { value = acc.get_accValue(child); } catch (COMException) { } catch (NotImplementedException) { }
|
|
1052
|
+
if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(value)) continue;
|
|
1053
|
+
// Dòng tiêu đề (DataGridView "Top Row"): giá trị trùng tên như ở đường lấy mẫu — đọc tên cột từ đó.
|
|
1054
|
+
if (value == name && rowish == 1) {
|
|
1055
|
+
if (columns == null) {
|
|
1056
|
+
int left, top, w, h;
|
|
1057
|
+
try { acc.accLocation(out left, out top, out w, out h, child); columns = ReadColumns(client, box, new AccRow { Name = name, Value = value, Left = left, Top = top, Width = w, Height = h }); } catch (COMException) { }
|
|
1058
|
+
}
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
rows.Add(Clip(string.IsNullOrEmpty(value) ? name : value, 800));
|
|
1062
|
+
}
|
|
1063
|
+
if (rows.Count < 1) return null;
|
|
1064
|
+
bool all = rowish >= count - 1 || rows.Count >= maxRows;
|
|
1065
|
+
return new Dictionary<string, object> {
|
|
1066
|
+
{ "columns", columns ?? new List<object>() }, { "rows", rows }, { "row_count", rows.Count }, { "complete", rows.Count < maxRows && got >= count && all },
|
|
1067
|
+
{ "reason", rows.Count >= maxRows ? "max_rows reached" : got < count ? "time limit reached" : null }, { "gaps", false }, { "ms", sw.ElapsedMilliseconds }, { "source", "children" },
|
|
1068
|
+
};
|
|
1069
|
+
} catch (COMException) { return null; } catch (InvalidCastException) { return null; } catch (NotImplementedException) { return null; }
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/** Chọn dòng của bảng MSAA có một ô đúng bằng "text" (hoặc tên dòng trùng): chọn + nhận focus, control tự cuộn tới. */
|
|
1073
|
+
static bool SelectRowByValue(AutomationElement table, string text) {
|
|
1074
|
+
try {
|
|
1075
|
+
Accessibility.IAccessible client = AccessibleClient(OwnHandle(table));
|
|
1076
|
+
if (client == null) return false;
|
|
1077
|
+
int count = client.accChildCount;
|
|
1078
|
+
if (count < 1 || count > 500000) return false;
|
|
1079
|
+
var kids = new object[count];
|
|
1080
|
+
int got;
|
|
1081
|
+
if (Native.AccessibleChildren(client, 0, count, kids, out got) != 0) return false;
|
|
1082
|
+
string want = text.Trim();
|
|
1083
|
+
for (int i = 0; i < got; i++) {
|
|
1084
|
+
Accessibility.IAccessible acc = kids[i] as Accessibility.IAccessible;
|
|
1085
|
+
object child = 0;
|
|
1086
|
+
if (acc == null) { if (!(kids[i] is int)) continue; acc = client; child = kids[i]; }
|
|
1087
|
+
string name = null, value = null;
|
|
1088
|
+
try { name = acc.get_accName(child); } catch (COMException) { }
|
|
1089
|
+
try { value = acc.get_accValue(child); } catch (COMException) { } catch (NotImplementedException) { }
|
|
1090
|
+
bool hit = string.Equals(name, want, StringComparison.OrdinalIgnoreCase);
|
|
1091
|
+
if (!hit && !string.IsNullOrEmpty(value)) foreach (string cell in value.Split(';')) if (string.Equals(cell.Trim(), want, StringComparison.OrdinalIgnoreCase)) { hit = true; break; }
|
|
1092
|
+
if (!hit) continue;
|
|
1093
|
+
// Chọn ô đầu của dòng như người bấm vào dòng: DataGridView mới đổi dòng hiện hành (CurrentRow) — chọn cả dòng chỉ tô dòng,
|
|
1094
|
+
// dòng hiện hành vẫn là dòng cũ (gui-bench 13/11/2026). Dòng không có ô con → chọn dòng.
|
|
1095
|
+
if (child is int && (int)child == 0 && SelectFirstCell(acc)) return true;
|
|
1096
|
+
acc.accSelect(SELFLAG_TAKEFOCUS | SELFLAG_TAKESELECTION, child);
|
|
1097
|
+
return true;
|
|
1098
|
+
}
|
|
1099
|
+
} catch (COMException) { } catch (InvalidCastException) { } catch (NotImplementedException) { } catch (ArgumentException) { }
|
|
1100
|
+
return false;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
static bool SelectFirstCell(Accessibility.IAccessible row) {
|
|
1104
|
+
try {
|
|
1105
|
+
int n = row.accChildCount;
|
|
1106
|
+
if (n < 1) return false;
|
|
1107
|
+
var cells = new object[Math.Min(n, 4)];
|
|
1108
|
+
int got;
|
|
1109
|
+
if (Native.AccessibleChildren(row, 0, cells.Length, cells, out got) != 0) return false;
|
|
1110
|
+
for (int i = 0; i < got; i++) {
|
|
1111
|
+
var cell = cells[i] as Accessibility.IAccessible;
|
|
1112
|
+
if (cell == null || Convert.ToInt32(cell.get_accRole(0)) != ROLE_SYSTEM_CELL) continue;
|
|
1113
|
+
cell.accSelect(SELFLAG_TAKEFOCUS | SELFLAG_TAKESELECTION, 0);
|
|
1114
|
+
// Lệnh mặc định của ô (DataGridView: đặt ô hiện hành) — accSelect chỉ tô chọn, chưa chắc đổi dòng hiện hành.
|
|
1115
|
+
string def = null;
|
|
1116
|
+
try { def = cell.get_accDefaultAction(0); } catch (COMException) { }
|
|
1117
|
+
if (!string.IsNullOrEmpty(def) && def.IndexOf("edit", StringComparison.OrdinalIgnoreCase) < 0) { try { cell.accDoDefaultAction(0); } catch (COMException) { } }
|
|
1118
|
+
return true;
|
|
1119
|
+
}
|
|
1120
|
+
} catch (COMException) { } catch (InvalidCastException) { } catch (NotImplementedException) { } catch (ArgumentException) { }
|
|
1121
|
+
return false;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
static object ReadTable(Dictionary<string, object> a) {
|
|
1125
|
+
IntPtr window;
|
|
1126
|
+
AutomationElement el = NodeOf(Str(a, "node_id"), out window);
|
|
1127
|
+
AssertWindowResponsive(window);
|
|
1128
|
+
int maxRows = Math.Max(1, Math.Min(Int(a, "max_rows", 300), 2000));
|
|
1129
|
+
IntPtr control = OwnHandle(el);
|
|
1130
|
+
Accessibility.IAccessible client = AccessibleClient(control);
|
|
1131
|
+
System.Windows.Rect box = el.Current.BoundingRectangle;
|
|
1132
|
+
if (client == null || box.IsEmpty) throw new GuiError("GUI_NO_PATTERN", "This table cannot be read directly — use gui.observe / gui.find and scroll");
|
|
1133
|
+
var sw = Stopwatch.StartNew();
|
|
1134
|
+
var direct = ReadRowsByChildren(client, box, maxRows, sw);
|
|
1135
|
+
if (direct != null) return direct;
|
|
1136
|
+
bool canScroll = AcceptsPostedInput(control);
|
|
1137
|
+
var seen = new HashSet<string>();
|
|
1138
|
+
var rows = new List<object>();
|
|
1139
|
+
List<object> columns = null;
|
|
1140
|
+
bool gaps = false, endReached = false;
|
|
1141
|
+
int notches = 0, stale = 0, movedUp = 0;
|
|
1142
|
+
var lp = new IntPtr((((int)box.Top + 20 & 0xFFFF) << 16) | ((int)box.Left + 20 & 0xFFFF));
|
|
1143
|
+
HashSet<string> previous = null;
|
|
1144
|
+
// 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ỗ.
|
|
1145
|
+
if (canScroll) {
|
|
1146
|
+
string top = FirstDataRow(SampleRows(client, box, sw, READ_TABLE_BUDGET_MS));
|
|
1147
|
+
int stalled = 0;
|
|
1148
|
+
while (top != null && movedUp < 2000 && stalled < READ_TABLE_STALL_NOTCHES && sw.ElapsedMilliseconds < READ_TABLE_BUDGET_MS / 2) {
|
|
1149
|
+
if (!Wheel(control, 120, lp)) break;
|
|
1150
|
+
string now = FirstDataRow(SampleRows(client, box, sw, READ_TABLE_BUDGET_MS));
|
|
1151
|
+
if (now == top) { stalled++; Thread.Sleep(READ_TABLE_STALL_WAIT_MS); continue; }
|
|
1152
|
+
stalled = 0;
|
|
1153
|
+
top = now;
|
|
1154
|
+
movedUp++;
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
while (rows.Count < maxRows && sw.ElapsedMilliseconds < READ_TABLE_BUDGET_MS) {
|
|
1158
|
+
var page = SampleRows(client, box, sw, READ_TABLE_BUDGET_MS);
|
|
1159
|
+
var names = new HashSet<string>();
|
|
1160
|
+
int fresh = 0;
|
|
1161
|
+
bool overlap = false;
|
|
1162
|
+
foreach (AccRow row in page) {
|
|
1163
|
+
bool header = row.Value == row.Name;
|
|
1164
|
+
if (header) { if (columns == null) columns = ReadColumns(client, box, row); continue; }
|
|
1165
|
+
names.Add(row.Name);
|
|
1166
|
+
if (previous != null && previous.Contains(row.Name)) overlap = true;
|
|
1167
|
+
if (!seen.Add(row.Name)) continue;
|
|
1168
|
+
fresh++;
|
|
1169
|
+
if (rows.Count < maxRows) rows.Add(Clip(string.IsNullOrEmpty(row.Value) ? row.Name : row.Value, 800));
|
|
1170
|
+
}
|
|
1171
|
+
if (previous != null && previous.Count > 0 && names.Count > 0 && !overlap) gaps = true;
|
|
1172
|
+
previous = names;
|
|
1173
|
+
if (!canScroll) break;
|
|
1174
|
+
if (fresh == 0) {
|
|
1175
|
+
if (++stale >= READ_TABLE_STALL_NOTCHES) { endReached = true; break; }
|
|
1176
|
+
Thread.Sleep(READ_TABLE_STALL_WAIT_MS);
|
|
1177
|
+
} else stale = 0;
|
|
1178
|
+
if (!Wheel(control, -120, lp)) break;
|
|
1179
|
+
notches++;
|
|
1180
|
+
}
|
|
1181
|
+
if (canScroll) {
|
|
1182
|
+
for (int i = 0; i < notches; i++) if (!Wheel(control, 120, lp)) break;
|
|
1183
|
+
for (int i = 0; i < movedUp; i++) if (!Wheel(control, -120, lp)) break;
|
|
1184
|
+
}
|
|
1185
|
+
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";
|
|
1186
|
+
return new Dictionary<string, object> {
|
|
1187
|
+
{ "columns", columns ?? new List<object>() }, { "rows", rows }, { "row_count", rows.Count }, { "complete", endReached }, { "reason", reason }, { "gaps", gaps }, { "ms", sw.ElapsedMilliseconds },
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
static uint SafeDpi(IntPtr h) { try { return Native.GetDpiForWindow(h); } catch { return 96; } }
|
|
1192
|
+
|
|
1193
|
+
/**
|
|
1194
|
+
* Ảnh cửa sổ bằng PrintWindow (chụp đúng cửa sổ kể cả khi bị che). PrintWindow hỏng / ảnh đen (vài ứng dụng GPU) → chụp vùng màn hình,
|
|
1195
|
+
* NHƯNG chỉ khi cửa sổ đích đang trên cùng và không bị che (02/11/2026): chụp vùng màn hình lấy cả cửa sổ khác đang đè lên (lộ việc riêng
|
|
1196
|
+
* của người dùng, VLM chọn toạ độ trên cửa sổ khác). Không an toàn → null + lý do (image_error), không trả ảnh sai.
|
|
1197
|
+
*/
|
|
1198
|
+
static Bitmap GrabWindow(IntPtr h, out string error) {
|
|
1199
|
+
error = null;
|
|
1200
|
+
Native.RECT r; Native.GetWindowRect(h, out r);
|
|
1201
|
+
int w = Math.Max(1, r.Right - r.Left), ht = Math.Max(1, r.Bottom - r.Top);
|
|
1202
|
+
var bmp = new Bitmap(w, ht, PixelFormat.Format32bppArgb);
|
|
1203
|
+
bool ok = false;
|
|
1204
|
+
try {
|
|
1205
|
+
using (var g = Graphics.FromImage(bmp)) {
|
|
1206
|
+
IntPtr hdc = g.GetHdc();
|
|
1207
|
+
try { ok = Native.PrintWindow(h, hdc, 2); } finally { g.ReleaseHdc(hdc); }
|
|
1208
|
+
if (!ok || IsMostlyBlack(bmp)) {
|
|
1209
|
+
error = ScreenCopyBlocker(h, r);
|
|
1210
|
+
if (error == null) g.CopyFromScreen(r.Left, r.Top, 0, 0, new Size(w, ht));
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
} catch { bmp.Dispose(); throw; }
|
|
1214
|
+
if (error != null) { bmp.Dispose(); return null; }
|
|
1215
|
+
return bmp;
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
/** null = chụp vùng màn hình của cửa sổ an toàn (đích trên cùng, tâm + lưới 3×3 điểm đều thuộc đích); không thì lý do. */
|
|
1219
|
+
static string ScreenCopyBlocker(IntPtr h, Native.RECT r) {
|
|
1220
|
+
if (Native.IsIconic(h)) return "the window is minimized and cannot be captured";
|
|
1221
|
+
if (!BelongsTo(Native.GetForegroundWindow(), h)) return "this app cannot be captured in the background and the window is not in front — bring it to the front (gui.focus) to get a screenshot";
|
|
1222
|
+
int inset = 8;
|
|
1223
|
+
int[] xs = { r.Left + inset, (r.Left + r.Right) / 2, r.Right - inset };
|
|
1224
|
+
int[] ys = { r.Top + inset, (r.Top + r.Bottom) / 2, r.Bottom - inset };
|
|
1225
|
+
foreach (int x in xs) foreach (int y in ys) {
|
|
1226
|
+
if (!PointOnWindow(x, y, h)) return "another window covers part of this window, so a screen capture would show it — bring the window to the front (gui.focus) to get a screenshot";
|
|
1227
|
+
}
|
|
1228
|
+
return null;
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
static Dictionary<string, object> EncodeImage(Bitmap bmp, int maxWidth, int quality) {
|
|
1232
|
+
int w = bmp.Width, ht = bmp.Height;
|
|
1233
|
+
double scale = w > maxWidth ? (double)maxWidth / w : 1.0;
|
|
1234
|
+
int ow = Math.Max(1, (int)(w * scale)), oh = Math.Max(1, (int)(ht * scale));
|
|
1235
|
+
using (var outBmp = new Bitmap(ow, oh, PixelFormat.Format24bppRgb)) {
|
|
1236
|
+
using (var g2 = Graphics.FromImage(outBmp)) {
|
|
1237
|
+
g2.InterpolationMode = InterpolationMode.HighQualityBicubic;
|
|
1238
|
+
g2.DrawImage(bmp, 0, 0, ow, oh);
|
|
1239
|
+
}
|
|
1240
|
+
var codec = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.MimeType == "image/jpeg");
|
|
1241
|
+
var ep = new EncoderParameters(1);
|
|
1242
|
+
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Max(30, Math.Min(quality, 95)));
|
|
1243
|
+
using (var ms = new MemoryStream()) {
|
|
1244
|
+
outBmp.Save(ms, codec, ep);
|
|
1245
|
+
return new Dictionary<string, object> { { "mime", "image/jpeg" }, { "base64", Convert.ToBase64String(ms.ToArray()) }, { "width", ow }, { "height", oh }, { "scale", scale } };
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/**
|
|
1251
|
+
* Đọc chữ trên ảnh cho một lần observe đã có (cùng snapshot, node chữ nối tiếp id "<snap>.t<k>") — không đi lại cây trợ năng. gui.do
|
|
1252
|
+
* cần OCR sau khi tìm trong cây không thấy: trước đây observe lại cả cửa sổ (form WinForms có bảng: ~2 s mỗi lần).
|
|
1253
|
+
*/
|
|
1254
|
+
static object OcrSnapshot(Dictionary<string, object> a) {
|
|
1255
|
+
int snap = Int(a, "snapshot", -1);
|
|
1256
|
+
IntPtr h;
|
|
1257
|
+
lock (StateLock) { if (!SnapshotWindow.TryGetValue(snap, out h)) throw new GuiError("GUI_STALE_NODE", "Snapshot " + snap + " is gone — observe again"); }
|
|
1258
|
+
if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The window of snapshot " + snap + " is closed");
|
|
1259
|
+
AssertWindowResponsive(h);
|
|
1260
|
+
var res = new Dictionary<string, object> { { "snapshot", snap } };
|
|
1261
|
+
var nodes = new List<object>();
|
|
1262
|
+
string imageError;
|
|
1263
|
+
var bmp = GrabWindow(h, out imageError);
|
|
1264
|
+
if (bmp == null) res["ocr"] = new Dictionary<string, object> { { "error", "no usable screenshot: " + imageError } };
|
|
1265
|
+
else using (bmp) AddOcrNodes(res, nodes, snap, bmp, Str(a, "ocr_lang"), Int(a, "ocr_max_nodes", 200));
|
|
1266
|
+
res["nodes"] = nodes;
|
|
1267
|
+
return res;
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
static void AddOcrNodes(Dictionary<string, object> res, List<object> nodes, int snap, Bitmap bmp, string lang, int max) {
|
|
1271
|
+
var sw = Stopwatch.StartNew();
|
|
1272
|
+
try {
|
|
1273
|
+
string used;
|
|
1274
|
+
var segments = Ocr.Read(bmp, lang, out used);
|
|
1275
|
+
var rects = new List<System.Windows.Rect>();
|
|
1276
|
+
lock (StateLock) { List<System.Windows.Rect> had; if (OcrSnapshots.TryGetValue(snap, out had)) rects = had; }
|
|
1277
|
+
foreach (var s in segments) {
|
|
1278
|
+
if (rects.Count >= Math.Max(0, max)) break;
|
|
1279
|
+
var r = s.Rect;
|
|
1280
|
+
nodes.Add(new Dictionary<string, object> {
|
|
1281
|
+
{ "id", snap + ".t" + rects.Count }, { "role", "text" }, { "name", s.Text }, { "source", "ocr" },
|
|
1282
|
+
{ "rect", new Dictionary<string, object> { { "x", (int)r.X }, { "y", (int)r.Y }, { "w", (int)r.Width }, { "h", (int)r.Height } } },
|
|
1283
|
+
});
|
|
1284
|
+
rects.Add(r);
|
|
1285
|
+
}
|
|
1286
|
+
lock (StateLock) { OcrSnapshots[snap] = rects; }
|
|
1287
|
+
var info = new Dictionary<string, object> { { "lang", used }, { "count", rects.Count }, { "ms", sw.ElapsedMilliseconds } };
|
|
1288
|
+
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)";
|
|
1289
|
+
res["ocr"] = info;
|
|
1290
|
+
res["node_count"] = nodes.Count;
|
|
1291
|
+
} catch (Exception e) {
|
|
1292
|
+
res["ocr"] = new Dictionary<string, object> { { "error", (e is GuiError ? e.Message : e.GetType().Name + ": " + e.Message) } };
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
static bool IsMostlyBlack(Bitmap b) {
|
|
1297
|
+
int dark = 0, total = 0;
|
|
1298
|
+
int w = b.Width, h = b.Height;
|
|
1299
|
+
if (w <= 0 || h <= 0) return true;
|
|
1300
|
+
var data = b.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
|
|
1301
|
+
try {
|
|
1302
|
+
int stride = Math.Abs(data.Stride);
|
|
1303
|
+
byte[] bytes = new byte[stride * h];
|
|
1304
|
+
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
|
|
1305
|
+
int stepX = Math.Max(1, w / 16), stepY = Math.Max(1, h / 16);
|
|
1306
|
+
for (int y = 0; y < h; y += stepY) {
|
|
1307
|
+
int row = y * stride;
|
|
1308
|
+
for (int x = 0; x < w; x += stepX) {
|
|
1309
|
+
int idx = row + x * 4;
|
|
1310
|
+
total++;
|
|
1311
|
+
if (bytes[idx + 2] < 8 && bytes[idx + 1] < 8 && bytes[idx] < 8) dark++;
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
} finally { b.UnlockBits(data); }
|
|
1315
|
+
// Đã thay GetPixel bằng LockBits + Marshal.Copy để đọc mảng byte trực tiếp trên bộ nhớ.
|
|
1316
|
+
/*
|
|
1317
|
+
var c = b.GetPixel(x, y); total++;
|
|
1318
|
+
if (c.R < 8 && c.G < 8 && c.B < 8) dark++;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
*/
|
|
1322
|
+
return total > 0 && dark * 10 >= total * 9;
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
// ── act ─────────────────────────────────────────────────────────────────────────────────────
|
|
1326
|
+
|
|
1327
|
+
static AutomationElement NodeOf(string nodeId, out IntPtr window) {
|
|
1328
|
+
window = IntPtr.Zero;
|
|
1329
|
+
int dot = nodeId == null ? -1 : nodeId.IndexOf('.');
|
|
1330
|
+
if (dot <= 0) throw new GuiError("INVALID_ARGS", "Bad node id: " + nodeId);
|
|
1331
|
+
int snap, idx;
|
|
1332
|
+
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);
|
|
1333
|
+
Dictionary<int, AutomationElement> map;
|
|
1334
|
+
AutomationElement e;
|
|
1335
|
+
lock (StateLock) {
|
|
1336
|
+
if (!Snapshots.TryGetValue(snap, out map)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
|
|
1337
|
+
if (!map.TryGetValue(idx, out e)) throw new GuiError("NOT_FOUND", "No node " + nodeId);
|
|
1338
|
+
window = SnapshotWindow[snap];
|
|
1339
|
+
}
|
|
1340
|
+
return e;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
static object Pattern(AutomationElement e, AutomationPattern p) {
|
|
1344
|
+
object o; return e.TryGetCurrentPattern(p, out o) ? o : null;
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
static Dictionary<string, object> Live(AutomationElement e) {
|
|
1348
|
+
var d = new Dictionary<string, object>();
|
|
1349
|
+
try {
|
|
1350
|
+
d["exists"] = true;
|
|
1351
|
+
d["name"] = Clip(e.Current.Name, 160);
|
|
1352
|
+
d["enabled"] = e.Current.IsEnabled;
|
|
1353
|
+
d["focused"] = e.Current.HasKeyboardFocus;
|
|
1354
|
+
var vp = Pattern(e, ValuePattern.Pattern) as ValuePattern;
|
|
1355
|
+
if (vp != null && !e.Current.IsPassword) d["value"] = Clip(vp.Current.Value, 300);
|
|
1356
|
+
var tp = Pattern(e, TogglePattern.Pattern) as TogglePattern;
|
|
1357
|
+
if (tp != null) d["checked"] = tp.Current.ToggleState.ToString().ToLowerInvariant();
|
|
1358
|
+
var sp = Pattern(e, SelectionItemPattern.Pattern) as SelectionItemPattern;
|
|
1359
|
+
if (sp != null) d["selected"] = sp.Current.IsSelected;
|
|
1360
|
+
var ep = Pattern(e, ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
|
|
1361
|
+
if (ep != null) d["expanded"] = ep.Current.ExpandCollapseState.ToString().ToLowerInvariant();
|
|
1362
|
+
} catch (ElementNotAvailableException) {
|
|
1363
|
+
d.Clear(); d["exists"] = false;
|
|
1364
|
+
}
|
|
1365
|
+
return d;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
static System.Windows.Point CenterOf(AutomationElement e) {
|
|
1369
|
+
System.Windows.Point p;
|
|
1370
|
+
try { if (e.TryGetClickablePoint(out p)) return p; } catch { }
|
|
1371
|
+
System.Windows.Rect r = e.Current.BoundingRectangle;
|
|
1372
|
+
if (r.IsEmpty) throw new GuiError("GUI_NOT_CLICKABLE", "Element has no position on screen");
|
|
1373
|
+
return new System.Windows.Point(r.X + r.Width / 2, r.Y + r.Height / 2);
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
static object Act(Dictionary<string, object> a) {
|
|
1377
|
+
string action = Str(a, "action") ?? "click";
|
|
1378
|
+
string nodeId = Str(a, "node_id");
|
|
1379
|
+
string method = Str(a, "method") ?? "auto";
|
|
1380
|
+
backgroundOnly = method == "background";
|
|
1381
|
+
inputGraceMs = Int(a, "user_input_grace_ms", 1500);
|
|
1382
|
+
pendingInputCheck = Bool(a, "check_user_input", true);
|
|
1383
|
+
userInputCheck = pendingInputCheck;
|
|
1384
|
+
lastMousePoint = null;
|
|
1385
|
+
if (!InteractiveDesktop()) throw new GuiError("GUI_LOCKED", "The screen is locked or a secure prompt is showing");
|
|
1386
|
+
AutomationElement el = null;
|
|
1387
|
+
IntPtr window = IntPtr.Zero;
|
|
1388
|
+
ocrPoint = null;
|
|
1389
|
+
ocrNodeId = null;
|
|
1390
|
+
if (!string.IsNullOrEmpty(nodeId) && nodeId.Contains(".t")) {
|
|
1391
|
+
ocrPoint = OcrPointOf(nodeId, out window);
|
|
1392
|
+
ocrNodeId = nodeId;
|
|
1393
|
+
if (action != "click" && action != "double_click" && action != "right_click" && action != "set_value" && action != "type") {
|
|
1394
|
+
throw new GuiError("INVALID_ARGS", "Text read from the screenshot (OCR) supports click / double_click / right_click / set_value / type only");
|
|
1395
|
+
}
|
|
1396
|
+
// 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
|
|
1397
|
+
// 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)
|
|
1398
|
+
// mới bấm vào toạ độ chữ rồi gõ bàn phím.
|
|
1399
|
+
if (action == "set_value" || action == "type") {
|
|
1400
|
+
AutomationElement nearby = FindNearbyInputForOcr(nodeId, window);
|
|
1401
|
+
if (nearby != null) {
|
|
1402
|
+
el = nearby;
|
|
1403
|
+
ocrPoint = null;
|
|
1404
|
+
ocrNodeId = null;
|
|
1405
|
+
} else {
|
|
1406
|
+
MouseAt(null, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1);
|
|
1407
|
+
method = "mouse";
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
else if (!string.IsNullOrEmpty(nodeId)) el = NodeOf(nodeId, out window);
|
|
1412
|
+
else window = ResolveWindow(a, true);
|
|
1413
|
+
string beforeTitle = window == IntPtr.Zero ? "" : WindowText(window);
|
|
1414
|
+
if (el != null) {
|
|
1415
|
+
bool isPassword = false;
|
|
1416
|
+
try { isPassword = el.Current.IsPassword; } catch (ElementNotAvailableException) { throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is gone — observe again"); }
|
|
1417
|
+
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");
|
|
1418
|
+
}
|
|
1419
|
+
AssertWindowResponsive(window);
|
|
1420
|
+
Dictionary<string, object> screenPoint = null;
|
|
1421
|
+
try {
|
|
1422
|
+
var sp = PointFor(el, window, a);
|
|
1423
|
+
screenPoint = new Dictionary<string, object> { { "x", (int)Math.Round(sp.X) }, { "y", (int)Math.Round(sp.Y) } };
|
|
1424
|
+
} catch { }
|
|
1425
|
+
IntPtr fgBefore = Native.GetForegroundWindow();
|
|
1426
|
+
Native.POINT cursorBefore;
|
|
1427
|
+
bool haveCursor = Native.GetCursorPos(out cursorBefore);
|
|
1428
|
+
string used = DoAction(action, method, el, window, a);
|
|
1429
|
+
// 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 /
|
|
1430
|
+
// 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
|
|
1431
|
+
// về cửa sổ người dùng đang dùng ngay sau thao tác.
|
|
1432
|
+
bool restored = used != "mouse" && used != "keyboard" && RestoreForeground(fgBefore, window);
|
|
1433
|
+
// 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 đó
|
|
1434
|
+
// bỏ qua bước này khi người dùng đang gõ, để phím Alt không chen vào giữa.
|
|
1435
|
+
IntPtr fgAfter = Native.GetForegroundWindow();
|
|
1436
|
+
if (!restored && used != "mouse" && used != "keyboard" && fgBefore != IntPtr.Zero && fgAfter != fgBefore && Native.IsWindow(fgBefore) && TookForeground(fgAfter, window)) {
|
|
1437
|
+
try { restored = ForceForeground(fgBefore); } catch (GuiError) { }
|
|
1438
|
+
}
|
|
1439
|
+
// 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).
|
|
1440
|
+
if (used == "mouse" || used == "keyboard") restored = GiveBackRealInput(action, window, fgBefore, haveCursor, cursorBefore);
|
|
1441
|
+
if (restored || (used != "mouse" && used != "keyboard" && fgBefore != window && window != IntPtr.Zero)) SendToBack(window);
|
|
1442
|
+
// Pattern actions expose their new state synchronously in most UIA providers. Keep a short grace for
|
|
1443
|
+
// providers that publish property changes just after returning; real mouse/keyboard still needs longer.
|
|
1444
|
+
int defaultSettle = used == "mouse" || used == "keyboard" ? 250 : used == "posted" ? 200 : 30;
|
|
1445
|
+
Thread.Sleep(Math.Max(0, Math.Min(Int(a, "settle_ms", defaultSettle), 3000)));
|
|
1446
|
+
var res = new Dictionary<string, object> { { "action", action }, { "method", used } };
|
|
1447
|
+
if (window != IntPtr.Zero && Native.IsWindow(window)) res["window_class"] = ClassOf(window);
|
|
1448
|
+
if (lastMousePoint != null) screenPoint = lastMousePoint;
|
|
1449
|
+
if (screenPoint != null) res["screen_point"] = screenPoint;
|
|
1450
|
+
if (restored) res["focus_returned_to_user"] = true;
|
|
1451
|
+
// 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.
|
|
1452
|
+
bool appBusy = window != IntPtr.Zero && Native.IsWindow(window) && !IsWindowResponsive(window, 1500);
|
|
1453
|
+
if (appBusy) res["app_busy"] = true;
|
|
1454
|
+
if (el != null && !appBusy) res["target"] = Live(el);
|
|
1455
|
+
IntPtr fg = Native.GetForegroundWindow();
|
|
1456
|
+
res["foreground"] = WindowInfo(fg, fg);
|
|
1457
|
+
if (window != IntPtr.Zero) {
|
|
1458
|
+
bool alive = Native.IsWindow(window);
|
|
1459
|
+
res["window_closed"] = !alive;
|
|
1460
|
+
if (alive) {
|
|
1461
|
+
string after = WindowText(window);
|
|
1462
|
+
if (after != beforeTitle) res["window_title_changed"] = new Dictionary<string, object> { { "from", beforeTitle }, { "to", after } };
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
if (!appBusy) try {
|
|
1466
|
+
var fe = AutomationElement.FocusedElement;
|
|
1467
|
+
if (fe != null) res["focused_element"] = new Dictionary<string, object> { { "role", fe.Current.ControlType.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant() }, { "name", Clip(fe.Current.Name, 120) } };
|
|
1468
|
+
} catch { }
|
|
1469
|
+
return res;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
static string DoAction(string action, string method, AutomationElement el, IntPtr window, Dictionary<string, object> a) {
|
|
1473
|
+
bool allowPattern = method != "mouse";
|
|
1474
|
+
switch (action) {
|
|
1475
|
+
case "click": {
|
|
1476
|
+
if (el != null && allowPattern) {
|
|
1477
|
+
var ip = Pattern(el, InvokePattern.Pattern) as InvokePattern;
|
|
1478
|
+
string role = el.Current.ControlType.ProgrammaticName;
|
|
1479
|
+
bool invokeRole = role.EndsWith("Button") || role.EndsWith("MenuItem") || role.EndsWith("Hyperlink") || role.EndsWith("SplitButton");
|
|
1480
|
+
// Nút Win32 / WinForms có handle riêng: gửi BM_CLICK (bất đồng bộ). Invoke qua MSAA là lời gọi đồng bộ — nút mở hộp modal
|
|
1481
|
+
// ("Xoá phiếu?") thì ứng dụng chạy MessageBox ngay trong lời gọi đó, host chờ tới hết hạn và cửa sổ bị coi là treo tới khi hộp
|
|
1482
|
+
// đóng (gui-bench 13/11/2026: 5 s rồi GUI_WINDOW_HUNG cho mọi bước sau).
|
|
1483
|
+
if (invokeRole && role.EndsWith(".Button") && PostButtonClick(el)) return "posted";
|
|
1484
|
+
if (ip != null && invokeRole) { ip.Invoke(); return "invoke"; }
|
|
1485
|
+
if (role.EndsWith("ListItem") || role.EndsWith("TabItem") || role.EndsWith("TreeItem") || role.EndsWith("RadioButton")) {
|
|
1486
|
+
var sp = Pattern(el, SelectionItemPattern.Pattern) as SelectionItemPattern;
|
|
1487
|
+
if (sp != null) { sp.Select(); return "select"; }
|
|
1488
|
+
}
|
|
1489
|
+
if (role.EndsWith("CheckBox")) {
|
|
1490
|
+
var tp = Pattern(el, TogglePattern.Pattern) as TogglePattern;
|
|
1491
|
+
if (tp != null) { tp.Toggle(); return "toggle"; }
|
|
1492
|
+
}
|
|
1493
|
+
if (method == "pattern") {
|
|
1494
|
+
if (ip != null) { ip.Invoke(); return "invoke"; }
|
|
1495
|
+
throw new GuiError("GUI_NO_PATTERN", "Element has no click pattern — retry with method mouse");
|
|
1496
|
+
}
|
|
1497
|
+
// Mục nằm dưới vùng cuộn (trang Settings dài, danh sách): chưa có toạ độ để bấm → cuộn tới trước; vẫn không có điểm mà phần tử
|
|
1498
|
+
// tự bấm được (Invoke) thì gọi thẳng (gui-bench 13/11/2026: "About" của Settings báo "no position on screen").
|
|
1499
|
+
if (!HasClickablePoint(el)) {
|
|
1500
|
+
ScrollIntoView(el);
|
|
1501
|
+
if (!HasClickablePoint(el) && ip != null) { ip.Invoke(); return "invoke"; }
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
if (method == "auto" || method == "background") {
|
|
1505
|
+
string quiet = TryBackgroundClick(el, window, a, 1);
|
|
1506
|
+
if (quiet != null) return quiet;
|
|
1507
|
+
}
|
|
1508
|
+
MouseAt(el, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1);
|
|
1509
|
+
return "mouse";
|
|
1510
|
+
}
|
|
1511
|
+
case "double_click": {
|
|
1512
|
+
if (method == "auto" || method == "background") {
|
|
1513
|
+
string quiet = TryBackgroundClick(el, window, a, 2);
|
|
1514
|
+
if (quiet != null) return quiet;
|
|
1515
|
+
}
|
|
1516
|
+
MouseAt(el, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 2);
|
|
1517
|
+
return "mouse";
|
|
1518
|
+
}
|
|
1519
|
+
case "right_click": MouseAt(el, window, a, MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, 1); return "mouse";
|
|
1520
|
+
case "set_value": {
|
|
1521
|
+
string text = Str(a, "text") ?? "";
|
|
1522
|
+
if (el != null && allowPattern) {
|
|
1523
|
+
var vp = Pattern(el, ValuePattern.Pattern) as ValuePattern;
|
|
1524
|
+
if (vp != null && !vp.Current.IsReadOnly) { vp.SetValue(text); return "value"; }
|
|
1525
|
+
if (TryBackgroundSetText(el, text)) return "background";
|
|
1526
|
+
}
|
|
1527
|
+
FocusTarget(el, window);
|
|
1528
|
+
KeyCombo("ctrl+a", window);
|
|
1529
|
+
TypeText(text, window);
|
|
1530
|
+
return "keyboard";
|
|
1531
|
+
}
|
|
1532
|
+
case "type": {
|
|
1533
|
+
string text = Str(a, "text") ?? "";
|
|
1534
|
+
if (allowPattern && TryBackgroundType(el, text)) return "background";
|
|
1535
|
+
FocusTarget(el, window); TypeText(text, window); return "keyboard";
|
|
1536
|
+
}
|
|
1537
|
+
case "key":
|
|
1538
|
+
if ((method == "auto" || method == "background") && TryBackgroundKeys(el, window, Str(a, "keys") ?? "")) return "posted";
|
|
1539
|
+
FocusTarget(el, window); KeyCombo(Str(a, "keys") ?? "", window); return "keyboard";
|
|
1540
|
+
case "scroll": {
|
|
1541
|
+
string dir = (Str(a, "direction") ?? "down").ToLowerInvariant();
|
|
1542
|
+
int amount = Math.Max(1, Math.Min(Int(a, "amount", 3), 30));
|
|
1543
|
+
if (el != null && allowPattern) {
|
|
1544
|
+
var sp = Pattern(el, ScrollPattern.Pattern) as ScrollPattern;
|
|
1545
|
+
if (sp != null) {
|
|
1546
|
+
for (int i = 0; i < amount; i++) {
|
|
1547
|
+
if (dir == "up") sp.ScrollVertical(ScrollAmount.SmallDecrement);
|
|
1548
|
+
else if (dir == "left") sp.ScrollHorizontal(ScrollAmount.SmallDecrement);
|
|
1549
|
+
else if (dir == "right") sp.ScrollHorizontal(ScrollAmount.SmallIncrement);
|
|
1550
|
+
else sp.ScrollVertical(ScrollAmount.SmallIncrement);
|
|
1551
|
+
}
|
|
1552
|
+
return "scroll";
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
if ((method == "auto" || method == "background") && TryBackgroundScroll(el, window, a, dir, amount)) return "posted";
|
|
1556
|
+
RequireForeground(window);
|
|
1557
|
+
var p = PointFor(el, window, a);
|
|
1558
|
+
AssertPointOnWindow((int)p.X, (int)p.Y, window);
|
|
1559
|
+
MoveCursor((int)p.X, (int)p.Y);
|
|
1560
|
+
lastMousePoint = new Dictionary<string, object> { { "x", (int)p.X }, { "y", (int)p.Y } };
|
|
1561
|
+
int delta = (dir == "up" ? 120 : -120) * amount;
|
|
1562
|
+
var inp = MouseInput(MOUSEEVENTF_WHEEL, 0, 0, delta);
|
|
1563
|
+
Send(new[] { inp });
|
|
1564
|
+
return "mouse";
|
|
1565
|
+
}
|
|
1566
|
+
case "select": {
|
|
1567
|
+
if (el == null) throw new GuiError("INVALID_ARGS", "select needs node_id");
|
|
1568
|
+
string option = Str(a, "option");
|
|
1569
|
+
if (!string.IsNullOrEmpty(option)) {
|
|
1570
|
+
// Mục của danh sách thường có sẵn trong cây khi đang đóng → chọn thẳng, không thả danh sách xuống (thả xuống kéo cửa sổ lên
|
|
1571
|
+
// trên cùng, giật focus của người dùng). Chỉ mở khi mục chưa có trong cây.
|
|
1572
|
+
// Bảng / danh sách: chọn theo giá trị ô qua danh sách con MSAA TRƯỚC — FindFirst theo tên trên bảng dài qua cầu MSAA đi từng ô
|
|
1573
|
+
// (800 dòng: hơn 60 s, gui-bench 13/11/2026) và tên ô không phải giá trị ô nên vẫn không thấy.
|
|
1574
|
+
string elRole = el.Current.ControlType.ProgrammaticName;
|
|
1575
|
+
bool tabular = elRole.EndsWith(".Table") || elRole.EndsWith(".DataGrid") || elRole.EndsWith(".List") || elRole.EndsWith(".Tree");
|
|
1576
|
+
if (tabular && SelectRowByValue(el, option)) return "select";
|
|
1577
|
+
var ep = Pattern(el, ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
|
|
1578
|
+
var match = tabular ? null : el.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, option, PropertyConditionFlags.IgnoreCase));
|
|
1579
|
+
bool expanded = false;
|
|
1580
|
+
if (match == null && ep != null) { try { ep.Expand(); expanded = true; Thread.Sleep(200); } catch { } }
|
|
1581
|
+
if (match == null && !tabular) match = FindByName(el, option);
|
|
1582
|
+
if (match == null) throw new GuiError("NOT_FOUND", "No option named: " + option);
|
|
1583
|
+
var sip = Pattern(match, SelectionItemPattern.Pattern) as SelectionItemPattern;
|
|
1584
|
+
if (sip != null) sip.Select(); else { var ip = Pattern(match, InvokePattern.Pattern) as InvokePattern; if (ip != null) ip.Invoke(); else throw new GuiError("GUI_NO_PATTERN", "Option cannot be selected"); }
|
|
1585
|
+
if (ep != null && expanded) { try { ep.Collapse(); } catch { } }
|
|
1586
|
+
return "select";
|
|
1587
|
+
}
|
|
1588
|
+
var sp2 = Pattern(el, SelectionItemPattern.Pattern) as SelectionItemPattern;
|
|
1589
|
+
if (sp2 == null) throw new GuiError("GUI_NO_PATTERN", "Element is not selectable");
|
|
1590
|
+
sp2.Select();
|
|
1591
|
+
return "select";
|
|
1592
|
+
}
|
|
1593
|
+
case "toggle": {
|
|
1594
|
+
if (el == null) throw new GuiError("INVALID_ARGS", "toggle needs node_id");
|
|
1595
|
+
var tp = Pattern(el, TogglePattern.Pattern) as TogglePattern;
|
|
1596
|
+
if (tp == null) throw new GuiError("GUI_NO_PATTERN", "Element is not a toggle");
|
|
1597
|
+
string want = Str(a, "state");
|
|
1598
|
+
for (int i = 0; i < 3; i++) {
|
|
1599
|
+
if (want != null && tp.Current.ToggleState.ToString().ToLowerInvariant() == want.ToLowerInvariant()) break;
|
|
1600
|
+
tp.Toggle();
|
|
1601
|
+
if (want == null) break;
|
|
1602
|
+
}
|
|
1603
|
+
return "toggle";
|
|
1604
|
+
}
|
|
1605
|
+
case "expand":
|
|
1606
|
+
case "collapse": {
|
|
1607
|
+
if (el == null) throw new GuiError("INVALID_ARGS", action + " needs node_id");
|
|
1608
|
+
var ep = Pattern(el, ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
|
|
1609
|
+
if (ep == null) throw new GuiError("GUI_NO_PATTERN", "Element cannot expand/collapse");
|
|
1610
|
+
if (action == "expand") ep.Expand(); else ep.Collapse();
|
|
1611
|
+
return "expand";
|
|
1612
|
+
}
|
|
1613
|
+
case "drag": {
|
|
1614
|
+
var toD = Get(a, "to") as Dictionary<string, object>;
|
|
1615
|
+
if (toD == null) throw new GuiError("INVALID_ARGS", "drag needs to {x,y}");
|
|
1616
|
+
RequireForeground(window);
|
|
1617
|
+
var start = PointFor(el, window, a);
|
|
1618
|
+
var to = WindowPoint(window, a, toD);
|
|
1619
|
+
AssertPointOnWindow((int)start.X, (int)start.Y, window);
|
|
1620
|
+
AssertPointOnWindow((int)to.X, (int)to.Y, window);
|
|
1621
|
+
lastMousePoint = new Dictionary<string, object> { { "x", (int)start.X }, { "y", (int)start.Y } };
|
|
1622
|
+
MoveCursorInput((int)start.X, (int)start.Y);
|
|
1623
|
+
Thread.Sleep(30);
|
|
1624
|
+
Send(new[] { MouseInput(MOUSEEVENTF_LEFTDOWN, 0, 0, 0) });
|
|
1625
|
+
Thread.Sleep(30);
|
|
1626
|
+
for (int i = 1; i <= 20; i++) {
|
|
1627
|
+
MoveCursorInput((int)(start.X + (to.X - start.X) * i / 20), (int)(start.Y + (to.Y - start.Y) * i / 20));
|
|
1628
|
+
Thread.Sleep(12);
|
|
1629
|
+
}
|
|
1630
|
+
Thread.Sleep(30);
|
|
1631
|
+
Send(new[] { MouseInput(MOUSEEVENTF_LEFTUP, 0, 0, 0) });
|
|
1632
|
+
return "mouse";
|
|
1633
|
+
}
|
|
1634
|
+
default: throw new GuiError("INVALID_ARGS", "Unknown action: " + action);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
/** Phần tử đang có chỗ trên màn hình để bấm (không khuất trong vùng cuộn, khung không rỗng). */
|
|
1639
|
+
static bool HasClickablePoint(AutomationElement el) {
|
|
1640
|
+
try {
|
|
1641
|
+
if (el.Current.IsOffscreen) return false;
|
|
1642
|
+
var r = el.Current.BoundingRectangle;
|
|
1643
|
+
return !r.IsEmpty && r.Width > 0 && r.Height > 0;
|
|
1644
|
+
} catch (ElementNotAvailableException) { return false; }
|
|
1645
|
+
}
|
|
1646
|
+
|
|
1647
|
+
/** Cuộn vùng chứa tới phần tử (ScrollItemPattern) — chạy bằng pattern, không cần cửa sổ ở trên cùng. Trả false nếu phần tử không hỗ trợ. */
|
|
1648
|
+
static bool ScrollIntoView(AutomationElement el) {
|
|
1649
|
+
var sip = Pattern(el, ScrollItemPattern.Pattern) as ScrollItemPattern;
|
|
1650
|
+
if (sip == null) return false;
|
|
1651
|
+
try { sip.ScrollIntoView(); Thread.Sleep(120); return true; } catch (InvalidOperationException) { return false; } catch (ElementNotAvailableException) { return false; }
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
static AutomationElement FindByName(AutomationElement root, string name) {
|
|
1655
|
+
var cond = new PropertyCondition(AutomationElement.NameProperty, name, PropertyConditionFlags.IgnoreCase);
|
|
1656
|
+
var hit = root.FindFirst(TreeScope.Descendants, cond);
|
|
1657
|
+
if (hit != null) return hit;
|
|
1658
|
+
// Danh sách thả xuống của ComboBox Win32 là cửa sổ riêng → tìm từ gốc màn hình trong các popup đang mở.
|
|
1659
|
+
return AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new AndCondition(cond, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)));
|
|
1660
|
+
}
|
|
1661
|
+
|
|
1662
|
+
const uint WM_SETTEXT = 0x000C, WM_CHAR = 0x0102, SMTO_ABORTIFHUNG = 0x0002;
|
|
1663
|
+
|
|
1664
|
+
/** 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ị đơ. */
|
|
1665
|
+
static bool IsWindowResponsive(IntPtr h, uint timeoutMs) {
|
|
1666
|
+
if (h == IntPtr.Zero || !Native.IsWindow(h)) return false;
|
|
1667
|
+
IntPtr r;
|
|
1668
|
+
return Native.SendMessageTimeout(h, 0, IntPtr.Zero, null, SMTO_ABORTIFHUNG, timeoutMs, out r) != IntPtr.Zero;
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
static void AssertWindowResponsive(IntPtr h) {
|
|
1672
|
+
if (h == IntPtr.Zero) return;
|
|
1673
|
+
if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The target window has closed");
|
|
1674
|
+
// 1,5 s: ứng dụng WinForms / ERP nặng vừa trả lời một loạt câu hỏi UIA (bảng dài qua cầu MSAA) có thể bận vài trăm ms — ngưỡng 500 ms
|
|
1675
|
+
// báo treo nhầm (gui-bench 13/11/2026). Windows chỉ coi là "Not Responding" sau 5 s.
|
|
1676
|
+
if (!IsWindowResponsive(h, 1500)) {
|
|
1677
|
+
if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The target window has closed");
|
|
1678
|
+
throw new GuiError("GUI_WINDOW_HUNG", "The target window is not responding (frozen UI thread)");
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
/** Handle Win32 riêng của phần tử (ô nhập / nút Win32, WinForms có; WPF / UWP / Chromium thì không). */
|
|
1683
|
+
static IntPtr OwnHandle(AutomationElement el) {
|
|
1684
|
+
if (el == null) return IntPtr.Zero;
|
|
1685
|
+
try { int h = el.Current.NativeWindowHandle; return h == 0 ? IntPtr.Zero : new IntPtr(h); } catch { return IntPtr.Zero; }
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
/**
|
|
1689
|
+
* Chạy NỀN (28/10/2026, user: "chạy nền, không chiếm focus"): ô Win32 có handle riêng → đặt chữ bằng WM_SETTEXT / gửi ký tự bằng
|
|
1690
|
+
* WM_CHAR thẳng vào handle — không đưa cửa sổ lên, không đụng bàn phím thật. Ô không có handle (WPF, UWP, trình duyệt) → false, nơi
|
|
1691
|
+
* gọi mới dùng bàn phím thật.
|
|
1692
|
+
*/
|
|
1693
|
+
const uint BM_CLICK = 0x00F5;
|
|
1694
|
+
|
|
1695
|
+
/** Nút Win32 thật (lớp "Button" hoặc nút WinForms) → PostMessage(BM_CLICK). Ô tích / nút chọn cùng lớp Button thì không (đi đường toggle). */
|
|
1696
|
+
static bool PostButtonClick(AutomationElement el) {
|
|
1697
|
+
IntPtr h = OwnHandle(el);
|
|
1698
|
+
if (h == IntPtr.Zero || !Native.IsWindowEnabled(h)) return false;
|
|
1699
|
+
string cls = ClassOf(h);
|
|
1700
|
+
bool button = string.Equals(cls, "Button", StringComparison.OrdinalIgnoreCase) || cls.IndexOf(".BUTTON.", StringComparison.OrdinalIgnoreCase) >= 0;
|
|
1701
|
+
if (!button) return false;
|
|
1702
|
+
int style = Native.GetWindowLong(h, GWL_STYLE) & 0xF;
|
|
1703
|
+
// BS_PUSHBUTTON 0, BS_DEFPUSHBUTTON 1, BS_COMMANDLINK 0xE / 0xF; ô tích / radio / groupbox là các kiểu khác.
|
|
1704
|
+
if (style != 0 && style != 1 && style != 0xE && style != 0xF) return false;
|
|
1705
|
+
return Native.PostMessage(h, BM_CLICK, IntPtr.Zero, IntPtr.Zero);
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
static bool TryBackgroundSetText(AutomationElement el, string text) {
|
|
1709
|
+
IntPtr h = OwnHandle(el);
|
|
1710
|
+
if (h == IntPtr.Zero) return false;
|
|
1711
|
+
// Chỉ ô nhập: WM_SETTEXT vào nhãn tĩnh / nút cũng "thành công" — đổi luôn chữ của nhãn mà không điền gì (gui-bench 13/11/2026: điền
|
|
1712
|
+
// "Họ tên" vào chính nhãn "Họ tên" báo background ok, ô nhập vẫn trống).
|
|
1713
|
+
if (!IsTextControl(h)) return false;
|
|
1714
|
+
IntPtr r;
|
|
1715
|
+
return Native.SendMessageTimeout(h, WM_SETTEXT, IntPtr.Zero, text, SMTO_ABORTIFHUNG, 2000, out r) != IntPtr.Zero;
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
static bool TryBackgroundType(AutomationElement el, string text) {
|
|
1719
|
+
IntPtr h = OwnHandle(el);
|
|
1720
|
+
if (h == IntPtr.Zero) return false;
|
|
1721
|
+
foreach (char ch in text) {
|
|
1722
|
+
if (ch == '\r') continue;
|
|
1723
|
+
Native.PostMessage(h, WM_CHAR, new IntPtr(ch == '\n' ? 13 : ch), IntPtr.Zero);
|
|
1724
|
+
}
|
|
1725
|
+
Thread.Sleep(30);
|
|
1726
|
+
return true;
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_MOUSEWHEEL = 0x020A, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101;
|
|
1730
|
+
const uint OBJID_CLIENT = 0xFFFFFFFC;
|
|
1731
|
+
const int ROLE_SYSTEM_CELL = 0x1D;
|
|
1732
|
+
const int SELFLAG_TAKEFOCUS = 1, SELFLAG_TAKESELECTION = 2;
|
|
1733
|
+
static readonly HashSet<string> ClassicClasses = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
|
|
1734
|
+
"Button", "Edit", "Static", "ComboBox", "ComboLBox", "ListBox", "#32770", "SysListView32", "SysTreeView32", "SysTabControl32", "SysHeader32",
|
|
1735
|
+
"SysDateTimePick32", "SysMonthCal32", "SysLink", "ToolbarWindow32", "ReBarWindow32", "msctls_statusbar32", "msctls_updown32", "msctls_trackbar32",
|
|
1736
|
+
};
|
|
1737
|
+
|
|
1738
|
+
/**
|
|
1739
|
+
* 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ý
|
|
1740
|
+
* 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).
|
|
1741
|
+
*/
|
|
1742
|
+
static bool AcceptsPostedInput(IntPtr h) {
|
|
1743
|
+
string c = ClassOf(h);
|
|
1744
|
+
if (c.StartsWith("WindowsForms10.") || c.StartsWith("Afx") || c.StartsWith("Thunder") || c.StartsWith("RichEdit", StringComparison.OrdinalIgnoreCase)) return true;
|
|
1745
|
+
if (c.Length > 1 && c[0] == 'T' && char.IsUpper(c[1])) return true; // Delphi / C++Builder: TForm1, TDBGrid, TPanel…
|
|
1746
|
+
return ClassicClasses.Contains(c);
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
/** 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ó. */
|
|
1750
|
+
static IntPtr DeepestChildAt(IntPtr window, int x, int y) {
|
|
1751
|
+
Native.RECT r;
|
|
1752
|
+
if (window == IntPtr.Zero || Native.IsIconic(window) || !Native.GetWindowRect(window, out r)) return IntPtr.Zero;
|
|
1753
|
+
if (x < r.Left || x >= r.Right || y < r.Top || y >= r.Bottom) return IntPtr.Zero;
|
|
1754
|
+
IntPtr cur = window;
|
|
1755
|
+
for (int depth = 0; depth < 30; depth++) {
|
|
1756
|
+
var p = new Native.POINT { X = x, Y = y };
|
|
1757
|
+
Native.ScreenToClient(cur, ref p);
|
|
1758
|
+
IntPtr child = Native.RealChildWindowFromPoint(cur, p);
|
|
1759
|
+
if (child == IntPtr.Zero || child == cur) break;
|
|
1760
|
+
cur = child;
|
|
1761
|
+
}
|
|
1762
|
+
return cur;
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
/** Đ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. */
|
|
1766
|
+
static bool QuietPoint(AutomationElement el, IntPtr window, Dictionary<string, object> a, out int x, out int y) {
|
|
1767
|
+
x = 0; y = 0;
|
|
1768
|
+
if (window == IntPtr.Zero) return false;
|
|
1769
|
+
try {
|
|
1770
|
+
if (el != null && el.Current.IsOffscreen) return false;
|
|
1771
|
+
var p = PointFor(el, window, a);
|
|
1772
|
+
x = (int)p.X; y = (int)p.Y;
|
|
1773
|
+
return true;
|
|
1774
|
+
} catch (GuiError) { return false; } catch (ElementNotAvailableException) { return false; }
|
|
1775
|
+
}
|
|
1776
|
+
|
|
1777
|
+
/**
|
|
1778
|
+
* 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
|
|
1779
|
+
* mở thì giữ (mất tiêu điểm là menu đóng, bước sau không chọn được).
|
|
1780
|
+
*/
|
|
1781
|
+
static bool GiveBackRealInput(string action, IntPtr window, IntPtr fgBefore, bool haveCursor, Native.POINT cursorBefore) {
|
|
1782
|
+
Native.POINT aiCursor;
|
|
1783
|
+
bool haveAi = Native.GetCursorPos(out aiCursor);
|
|
1784
|
+
Thread.Sleep(150); // để ứng dụng nhận xong cú bấm / phím trước khi đổi tiêu điểm
|
|
1785
|
+
Native.POINT now;
|
|
1786
|
+
if (haveCursor && haveAi && Native.GetCursorPos(out now) && now.X == aiCursor.X && now.Y == aiCursor.Y && (now.X != cursorBefore.X || now.Y != cursorBefore.Y)) {
|
|
1787
|
+
Native.SetCursorPos(cursorBefore.X, cursorBefore.Y);
|
|
1788
|
+
}
|
|
1789
|
+
if (action == "right_click" || InMenuMode(window)) return false;
|
|
1790
|
+
IntPtr fg = Native.GetForegroundWindow();
|
|
1791
|
+
if (fgBefore == IntPtr.Zero || fgBefore == window || !Native.IsWindow(fgBefore) || !TookForeground(fg, window)) return false;
|
|
1792
|
+
if (RestoreForeground(fgBefore, window)) return true;
|
|
1793
|
+
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õ
|
|
1794
|
+
try { return ForceForeground(fgBefore); } catch (GuiError) { return false; }
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
static bool InMenuMode(IntPtr window) {
|
|
1798
|
+
uint pid;
|
|
1799
|
+
var info = new Native.GUITHREADINFO();
|
|
1800
|
+
info.cbSize = (uint)Marshal.SizeOf(info);
|
|
1801
|
+
uint thread = window == IntPtr.Zero ? 0 : Native.GetWindowThreadProcessId(window, out pid);
|
|
1802
|
+
if (thread == 0 || !Native.GetGUIThreadInfo(thread, ref info)) return false;
|
|
1803
|
+
return (info.flags & 0x14) != 0; // GUI_INMENUMODE | GUI_POPUPMENUMODE
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
/**
|
|
1807
|
+
* 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ỉ
|
|
1808
|
+
* 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.
|
|
1809
|
+
* Trả null = không làm được dưới nền, chưa có gì xảy ra.
|
|
1810
|
+
*/
|
|
1811
|
+
static string TryBackgroundClick(AutomationElement el, IntPtr window, Dictionary<string, object> a, int times) {
|
|
1812
|
+
int x, y;
|
|
1813
|
+
if (!QuietPoint(el, window, a, out x, out y)) return null;
|
|
1814
|
+
IntPtr target = DeepestChildAt(window, x, y);
|
|
1815
|
+
if (target == IntPtr.Zero) return null;
|
|
1816
|
+
bool exposed = Native.WindowFromPoint(new Native.POINT { X = x, Y = y }) == target;
|
|
1817
|
+
if (AcceptsPostedInput(target) && (exposed || !ClassOf(target).StartsWith("WindowsForms10."))) {
|
|
1818
|
+
PostClick(target, x, y, times);
|
|
1819
|
+
return "posted";
|
|
1820
|
+
}
|
|
1821
|
+
if (times == 1 && TryAccessibleClick(target, x, y)) return "accessible";
|
|
1822
|
+
return null;
|
|
1823
|
+
}
|
|
1824
|
+
|
|
1825
|
+
static void PostClick(IntPtr h, int screenX, int screenY, int times) {
|
|
1826
|
+
var c = new Native.POINT { X = screenX, Y = screenY };
|
|
1827
|
+
Native.ScreenToClient(h, ref c);
|
|
1828
|
+
var lp = new IntPtr(((c.Y & 0xFFFF) << 16) | (c.X & 0xFFFF));
|
|
1829
|
+
var pressed = new IntPtr(1); // MK_LBUTTON
|
|
1830
|
+
Native.PostMessage(h, WM_MOUSEMOVE, IntPtr.Zero, lp);
|
|
1831
|
+
for (int i = 0; i < times; i++) {
|
|
1832
|
+
Native.PostMessage(h, i == 0 ? WM_LBUTTONDOWN : WM_LBUTTONDBLCLK, pressed, lp);
|
|
1833
|
+
Native.PostMessage(h, WM_LBUTTONUP, IntPtr.Zero, lp);
|
|
1834
|
+
}
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
static Accessibility.IAccessible AccessibleClient(IntPtr control) {
|
|
1838
|
+
if (control == IntPtr.Zero) return null;
|
|
1839
|
+
object raw;
|
|
1840
|
+
var iid = new Guid("618736E0-3C3D-11CF-810C-00AA00389B71");
|
|
1841
|
+
if (Native.AccessibleObjectFromWindow(control, OBJID_CLIENT, ref iid, out raw) != 0) return null;
|
|
1842
|
+
return raw as Accessibility.IAccessible;
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
/** 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. */
|
|
1846
|
+
static bool TryAccessibleClick(IntPtr target, int x, int y) {
|
|
1847
|
+
try {
|
|
1848
|
+
Accessibility.IAccessible client = AccessibleClient(target);
|
|
1849
|
+
if (client == null) return false;
|
|
1850
|
+
Accessibility.IAccessible node = client;
|
|
1851
|
+
object child = 0;
|
|
1852
|
+
// Đ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.
|
|
1853
|
+
for (int depth = 0; depth < 5; depth++) {
|
|
1854
|
+
object hit = node.accHitTest(x, y);
|
|
1855
|
+
if (hit is Accessibility.IAccessible && !ReferenceEquals(hit, node)) { node = (Accessibility.IAccessible)hit; child = 0; continue; }
|
|
1856
|
+
if (hit is int && (int)hit != 0) child = hit;
|
|
1857
|
+
break;
|
|
1858
|
+
}
|
|
1859
|
+
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ể
|
|
1860
|
+
if (!string.IsNullOrEmpty(node.get_accDefaultAction(child))) node.accDoDefaultAction(child);
|
|
1861
|
+
else node.accSelect(SELFLAG_TAKEFOCUS | SELFLAG_TAKESELECTION, child);
|
|
1862
|
+
return true;
|
|
1863
|
+
} catch (COMException) { return false; } catch (ArgumentException) { return false; } catch (InvalidCastException) { return false; } catch (NotImplementedException) { return false; }
|
|
1864
|
+
}
|
|
1865
|
+
|
|
1866
|
+
static bool TryBackgroundScroll(AutomationElement el, IntPtr window, Dictionary<string, object> a, string dir, int amount) {
|
|
1867
|
+
if (dir != "up" && dir != "down") return false;
|
|
1868
|
+
int x, y;
|
|
1869
|
+
if (!QuietPoint(el, window, a, out x, out y)) return false;
|
|
1870
|
+
IntPtr target = DeepestChildAt(window, x, y);
|
|
1871
|
+
if (target == IntPtr.Zero || !AcceptsPostedInput(target)) return false;
|
|
1872
|
+
int notch = dir == "up" ? 120 : -120;
|
|
1873
|
+
var lp = new IntPtr(((y & 0xFFFF) << 16) | (x & 0xFFFF));
|
|
1874
|
+
for (int i = 0; i < amount; i++) Native.PostMessage(target, WM_MOUSEWHEEL, new IntPtr(notch << 16), lp);
|
|
1875
|
+
return true;
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
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;
|
|
1879
|
+
|
|
1880
|
+
static bool IsTextControl(IntPtr h) {
|
|
1881
|
+
string c = ClassOf(h);
|
|
1882
|
+
return c.IndexOf("EDIT", StringComparison.OrdinalIgnoreCase) >= 0 || c.IndexOf("Memo", StringComparison.Ordinal) >= 0 || c.IndexOf("TextBox", StringComparison.Ordinal) >= 0;
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
/** "Ctrl + Shift+S" → "ctrl+s+shift": thứ tự phím bổ trợ khác nhau vẫn so được. */
|
|
1886
|
+
static string NormalizeChord(string s) {
|
|
1887
|
+
var parts = new List<string>(s.ToLowerInvariant().Replace(" ", "").Split(new[] { '+' }, StringSplitOptions.RemoveEmptyEntries));
|
|
1888
|
+
parts.Sort(StringComparer.Ordinal);
|
|
1889
|
+
return string.Join("+", parts);
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
/** 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ó. */
|
|
1893
|
+
static bool FindMenuCommand(IntPtr menu, string chord, int depth, out uint id) {
|
|
1894
|
+
id = 0;
|
|
1895
|
+
if (menu == IntPtr.Zero || depth > 4) return false;
|
|
1896
|
+
int count = Native.GetMenuItemCount(menu);
|
|
1897
|
+
for (int i = 0; i < count; i++) {
|
|
1898
|
+
IntPtr sub = Native.GetSubMenu(menu, i);
|
|
1899
|
+
if (sub != IntPtr.Zero) { if (FindMenuCommand(sub, chord, depth + 1, out id)) return true; continue; }
|
|
1900
|
+
var sb = new StringBuilder(256);
|
|
1901
|
+
if (Native.GetMenuString(menu, (uint)i, sb, sb.Capacity, MF_BYPOSITION) <= 0) continue;
|
|
1902
|
+
string text = sb.ToString();
|
|
1903
|
+
int tab = text.LastIndexOf('\t');
|
|
1904
|
+
if (tab < 0 || NormalizeChord(text.Substring(tab + 1)) != chord) continue;
|
|
1905
|
+
if ((Native.GetMenuState(menu, (uint)i, MF_BYPOSITION) & (MF_GRAYED | MF_DISABLED)) != 0) return false;
|
|
1906
|
+
id = Native.GetMenuItemID(menu, i);
|
|
1907
|
+
return id != 0xFFFFFFFF;
|
|
1908
|
+
}
|
|
1909
|
+
return false;
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
/** 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. */
|
|
1913
|
+
static Action ChordAsCommand(string combo, IntPtr target, IntPtr window) {
|
|
1914
|
+
string chord = NormalizeChord(combo);
|
|
1915
|
+
if (target != IntPtr.Zero && IsTextControl(target)) {
|
|
1916
|
+
uint msg = chord == "c+ctrl" ? WM_COPY : chord == "ctrl+x" ? WM_CUT : chord == "ctrl+v" ? WM_PASTE : chord == "ctrl+z" ? WM_UNDO : 0;
|
|
1917
|
+
if (msg != 0) return () => Native.PostMessage(target, msg, IntPtr.Zero, IntPtr.Zero);
|
|
1918
|
+
if (chord == "a+ctrl") return () => Native.PostMessage(target, EM_SETSEL, IntPtr.Zero, new IntPtr(-1));
|
|
1919
|
+
}
|
|
1920
|
+
if (chord == "alt+f4") return () => Native.PostMessage(window, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
|
|
1921
|
+
uint id;
|
|
1922
|
+
if (FindMenuCommand(Native.GetMenu(window), chord, 0, out id)) return () => Native.PostMessage(window, WM_COMMAND, new IntPtr(id), IntPtr.Zero);
|
|
1923
|
+
return null;
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1926
|
+
/** 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. */
|
|
1927
|
+
static bool TryBackgroundKeys(AutomationElement el, IntPtr window, string spec) {
|
|
1928
|
+
if (window == IntPtr.Zero || spec.Length == 0) return false;
|
|
1929
|
+
IntPtr target = OwnHandle(el);
|
|
1930
|
+
if (el == null) {
|
|
1931
|
+
uint pid;
|
|
1932
|
+
var info = new Native.GUITHREADINFO();
|
|
1933
|
+
info.cbSize = (uint)Marshal.SizeOf(info);
|
|
1934
|
+
uint thread = Native.GetWindowThreadProcessId(window, out pid);
|
|
1935
|
+
if (thread == 0 || !Native.GetGUIThreadInfo(thread, ref info)) return false;
|
|
1936
|
+
target = info.hwndFocus;
|
|
1937
|
+
}
|
|
1938
|
+
// 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.
|
|
1939
|
+
if (target != IntPtr.Zero && (!BelongsTo(target, window) || !AcceptsPostedInput(target))) target = IntPtr.Zero;
|
|
1940
|
+
var steps = new List<Action>();
|
|
1941
|
+
foreach (string raw in spec.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) {
|
|
1942
|
+
if (raw.Contains("+")) {
|
|
1943
|
+
Action cmd = ChordAsCommand(raw, target, window);
|
|
1944
|
+
if (cmd == null) return false;
|
|
1945
|
+
steps.Add(cmd);
|
|
1946
|
+
continue;
|
|
1947
|
+
}
|
|
1948
|
+
ushort vk;
|
|
1949
|
+
if (target == IntPtr.Zero || !Keys.TryGetValue(raw, out vk) || vk == 0x11 || vk == 0x10 || vk == 0x12 || vk == 0x5B) return false;
|
|
1950
|
+
steps.Add(() => {
|
|
1951
|
+
Native.PostMessage(target, WM_KEYDOWN, new IntPtr(vk), new IntPtr(1));
|
|
1952
|
+
Native.PostMessage(target, WM_KEYUP, new IntPtr(vk), new IntPtr(unchecked((int)0xC0000001)));
|
|
1953
|
+
});
|
|
1954
|
+
}
|
|
1955
|
+
foreach (Action step in steps) step();
|
|
1956
|
+
return true;
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
/** 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ử. */
|
|
1960
|
+
static void FocusTarget(AutomationElement el, IntPtr window) {
|
|
1961
|
+
RequireForeground(window);
|
|
1962
|
+
if (el != null) { try { el.SetFocus(); } catch { } Thread.Sleep(50); }
|
|
1963
|
+
AssertStillForeground(window, null);
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
/** Toạ độ theo ảnh của lần observe ({x,y} trong khung ảnh đã thu nhỏ, kèm scale) → toạ độ màn hình. */
|
|
1967
|
+
static System.Windows.Point WindowPoint(IntPtr window, Dictionary<string, object> a, Dictionary<string, object> pt) {
|
|
1968
|
+
if (window == IntPtr.Zero) throw new GuiError("INVALID_ARGS", "A window is required for x/y targets");
|
|
1969
|
+
Native.RECT r; Native.GetWindowRect(window, out r);
|
|
1970
|
+
double scale = Dbl(a, "image_scale", 1.0);
|
|
1971
|
+
if (scale <= 0) scale = 1.0;
|
|
1972
|
+
double x = Dbl(pt, "x", -1), y = Dbl(pt, "y", -1);
|
|
1973
|
+
if (x < 0 || y < 0) throw new GuiError("INVALID_ARGS", "x/y must be non-negative");
|
|
1974
|
+
double sx = r.Left + x / scale, sy = r.Top + y / scale;
|
|
1975
|
+
if (sx > r.Right || sy > r.Bottom) throw new GuiError("INVALID_ARGS", "x/y is outside the window");
|
|
1976
|
+
return new System.Windows.Point(sx, sy);
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1979
|
+
/**
|
|
1980
|
+
* 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
|
|
1981
|
+
* đ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.
|
|
1982
|
+
*/
|
|
1983
|
+
static object WaitFor(Dictionary<string, object> a) {
|
|
1984
|
+
string until = (Str(a, "until") ?? "appears").ToLowerInvariant();
|
|
1985
|
+
bool gone = until == "gone" || until == "disappears";
|
|
1986
|
+
string name = Str(a, "name"), aid = Str(a, "automation_id"), role = Str(a, "role"), title = Str(a, "title_contains");
|
|
1987
|
+
bool windowLevel = string.IsNullOrEmpty(name) && string.IsNullOrEmpty(aid);
|
|
1988
|
+
if (windowLevel && string.IsNullOrEmpty(title)) throw new GuiError("INVALID_ARGS", "Give name / automation_id (an element) or title_contains (a window)");
|
|
1989
|
+
int timeout = Math.Max(200, Math.Min(Int(a, "timeout_ms", 10000), 60000));
|
|
1990
|
+
IntPtr h = (!windowLevel || !string.IsNullOrEmpty(Str(a, "window"))) ? ResolveWindow(a) : IntPtr.Zero;
|
|
1991
|
+
if (!windowLevel && h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused");
|
|
1992
|
+
string reqId = Str(a, "__req_id");
|
|
1993
|
+
var sw = Stopwatch.StartNew();
|
|
1994
|
+
try {
|
|
1995
|
+
while (true) {
|
|
1996
|
+
if (IsCancelled(reqId)) throw new GuiError("CANCELLED", "Wait cancelled");
|
|
1997
|
+
bool alive = h == IntPtr.Zero || Native.IsWindow(h);
|
|
1998
|
+
Dictionary<string, object> match = null;
|
|
1999
|
+
bool incomplete = false;
|
|
2000
|
+
if (windowLevel) {
|
|
2001
|
+
if (h != IntPtr.Zero) {
|
|
2002
|
+
if (alive && WindowText(h).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) match = WindowInfo(h, Native.GetForegroundWindow());
|
|
2003
|
+
} else {
|
|
2004
|
+
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
|
|
2005
|
+
if (Convert.ToString(info["title"]).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) { match = info; break; }
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
} else if (alive) {
|
|
2009
|
+
match = FindElement(h, name, aid, role, ref incomplete);
|
|
2010
|
+
}
|
|
2011
|
+
// 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.
|
|
2012
|
+
if (gone ? (match == null && !incomplete) : match != null) {
|
|
2013
|
+
var res = new Dictionary<string, object> { { "met", true }, { "until", gone ? "gone" : "appears" }, { "waited_ms", sw.ElapsedMilliseconds } };
|
|
2014
|
+
if (match != null) res["match"] = match;
|
|
2015
|
+
if (!alive) res["window_closed"] = true;
|
|
2016
|
+
return res;
|
|
2017
|
+
}
|
|
2018
|
+
if (!alive) throw new GuiError("GUI_WINDOW_GONE", "The window closed while waiting for the element to appear");
|
|
2019
|
+
if (sw.ElapsedMilliseconds >= timeout) {
|
|
2020
|
+
throw new GuiError("GUI_WAIT_TIMEOUT", "Still " + (gone ? "present" : "not there") + " after " + sw.ElapsedMilliseconds + " ms — observe to see what the window shows instead");
|
|
2021
|
+
}
|
|
2022
|
+
Thread.Sleep(250);
|
|
2023
|
+
}
|
|
2024
|
+
} finally {
|
|
2025
|
+
if (!string.IsNullOrEmpty(reqId)) { lock (CancelledIds) { CancelledIds.Remove(reqId); } }
|
|
2026
|
+
}
|
|
2027
|
+
}
|
|
2028
|
+
|
|
2029
|
+
/** 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ò. */
|
|
2030
|
+
static Dictionary<string, object> FindElement(IntPtr h, string name, string aid, string role, ref bool incomplete) {
|
|
2031
|
+
if (!IsWindowResponsive(h, 300)) { incomplete = true; return null; }
|
|
2032
|
+
AutomationElement root;
|
|
2033
|
+
try { root = AutomationElement.FromHandle(h); } catch { return null; }
|
|
2034
|
+
var cache = new CacheRequest();
|
|
2035
|
+
cache.Add(AutomationElement.NameProperty); cache.Add(AutomationElement.ControlTypeProperty); cache.Add(AutomationElement.AutomationIdProperty);
|
|
2036
|
+
cache.Add(AutomationElement.IsOffscreenProperty);
|
|
2037
|
+
// Đ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.
|
|
2038
|
+
var walker = new TreeWalker(Automation.ControlViewCondition);
|
|
2039
|
+
var sw = Stopwatch.StartNew();
|
|
2040
|
+
try { using (cache.Activate()) { root = root.GetUpdatedCache(cache); } } catch (ElementNotAvailableException) { return null; }
|
|
2041
|
+
var queue = new Queue<AutomationElement>();
|
|
2042
|
+
queue.Enqueue(root);
|
|
2043
|
+
bool cut = false;
|
|
2044
|
+
while (queue.Count > 0) {
|
|
2045
|
+
if (sw.ElapsedMilliseconds >= FIND_ELEMENT_BUDGET_MS) { incomplete = true; return null; }
|
|
2046
|
+
AutomationElement e = queue.Dequeue();
|
|
2047
|
+
string n = Cached(e, AutomationElement.NameProperty) as string ?? "";
|
|
2048
|
+
var ct = Cached(e, AutomationElement.ControlTypeProperty) as ControlType;
|
|
2049
|
+
string r = ct == null ? "" : ct.ProgrammaticName.Replace("ControlType.", "").ToLowerInvariant();
|
|
2050
|
+
foreach (AutomationElement k in ChildrenOf(e, r, cache, walker, sw, FIND_ELEMENT_BUDGET_MS, ref cut)) queue.Enqueue(k);
|
|
2051
|
+
if (!string.IsNullOrEmpty(aid) && !string.Equals(Cached(e, AutomationElement.AutomationIdProperty) as string, aid, StringComparison.Ordinal)) continue;
|
|
2052
|
+
if (!string.IsNullOrEmpty(name) && n.IndexOf(name, StringComparison.OrdinalIgnoreCase) < 0) continue;
|
|
2053
|
+
if (!string.IsNullOrEmpty(role) && !string.Equals(r, role, StringComparison.OrdinalIgnoreCase)) continue;
|
|
2054
|
+
if (true.Equals(Cached(e, AutomationElement.IsOffscreenProperty)) && string.IsNullOrEmpty(aid)) continue;
|
|
2055
|
+
var m = new Dictionary<string, object> { { "role", r }, { "name", Clip(n, 120) } };
|
|
2056
|
+
string id = Cached(e, AutomationElement.AutomationIdProperty) as string;
|
|
2057
|
+
if (!string.IsNullOrEmpty(id)) m["automation_id"] = id;
|
|
2058
|
+
return m;
|
|
2059
|
+
}
|
|
2060
|
+
return null;
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
/** Đ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). */
|
|
2064
|
+
static System.Windows.Point? ocrPoint = null;
|
|
2065
|
+
/** node_id OCR của thao tác đang chạy — tính lại điểm theo vị trí cửa sổ lúc bấm (sau khi khôi phục cửa sổ thu nhỏ). */
|
|
2066
|
+
static string ocrNodeId = null;
|
|
2067
|
+
|
|
2068
|
+
static System.Windows.Point OcrPointOf(string nodeId, out IntPtr window) {
|
|
2069
|
+
window = IntPtr.Zero;
|
|
2070
|
+
int dot = nodeId.IndexOf(".t");
|
|
2071
|
+
int snap, idx;
|
|
2072
|
+
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);
|
|
2073
|
+
List<System.Windows.Rect> rects;
|
|
2074
|
+
lock (StateLock) {
|
|
2075
|
+
if (!OcrSnapshots.TryGetValue(snap, out rects)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
|
|
2076
|
+
if (idx < 0 || idx >= rects.Count) throw new GuiError("NOT_FOUND", "No node " + nodeId);
|
|
2077
|
+
window = SnapshotWindow[snap];
|
|
2078
|
+
}
|
|
2079
|
+
if (!Native.IsWindow(window)) throw new GuiError("GUI_STALE_NODE", "The window of " + nodeId + " is closed — observe again");
|
|
2080
|
+
// 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).
|
|
2081
|
+
Native.RECT wr; Native.GetWindowRect(window, out wr);
|
|
2082
|
+
var r = rects[idx];
|
|
2083
|
+
return new System.Windows.Point(wr.Left + r.X + r.Width / 2, wr.Top + r.Y + r.Height / 2);
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
/**
|
|
2087
|
+
* 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.
|
|
2088
|
+
* 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.
|
|
2089
|
+
*/
|
|
2090
|
+
static AutomationElement FindNearbyInputForOcr(string nodeId, IntPtr window) {
|
|
2091
|
+
if (window == IntPtr.Zero || !Native.IsWindow(window)) return null;
|
|
2092
|
+
int dot = nodeId.IndexOf(".t");
|
|
2093
|
+
int snap, idx;
|
|
2094
|
+
if (dot <= 0 || !int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 2), out idx)) return null;
|
|
2095
|
+
System.Windows.Rect ocrRect;
|
|
2096
|
+
var candidates = new List<AutomationElement>();
|
|
2097
|
+
lock (StateLock) {
|
|
2098
|
+
List<System.Windows.Rect> rects;
|
|
2099
|
+
if (!OcrSnapshots.TryGetValue(snap, out rects) || idx < 0 || idx >= rects.Count) return null;
|
|
2100
|
+
ocrRect = rects[idx];
|
|
2101
|
+
Dictionary<int, AutomationElement> map;
|
|
2102
|
+
if (Snapshots.TryGetValue(snap, out map)) {
|
|
2103
|
+
foreach (var kv in map) candidates.Add(kv.Value);
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
Native.RECT wr; Native.GetWindowRect(window, out wr);
|
|
2107
|
+
AutomationElement best = null;
|
|
2108
|
+
double bestScore = double.MaxValue;
|
|
2109
|
+
foreach (AutomationElement e in candidates) {
|
|
2110
|
+
try {
|
|
2111
|
+
if (!e.Current.IsEnabled || e.Current.IsOffscreen) continue;
|
|
2112
|
+
ControlType ct = e.Current.ControlType;
|
|
2113
|
+
bool isInput = ct == ControlType.Edit || ct == ControlType.ComboBox || ct == ControlType.Document;
|
|
2114
|
+
if (!isInput) {
|
|
2115
|
+
var vp = Pattern(e, ValuePattern.Pattern) as ValuePattern;
|
|
2116
|
+
if (vp == null || vp.Current.IsReadOnly) continue;
|
|
2117
|
+
}
|
|
2118
|
+
System.Windows.Rect er = e.Current.BoundingRectangle;
|
|
2119
|
+
if (er.IsEmpty || er.Width <= 4 || er.Height <= 4) continue;
|
|
2120
|
+
double rx = er.X - wr.Left, ry = er.Y - wr.Top, rw = er.Width, rh = er.Height;
|
|
2121
|
+
// Bỏ qua nếu chính phần tử bao trùm cả cửa sổ
|
|
2122
|
+
if (rw >= (wr.Right - wr.Left) * 0.95 && rh >= (wr.Bottom - wr.Top) * 0.9) continue;
|
|
2123
|
+
// 1. Ô nhập nằm bên phải nhãn (cùng hàng ngang)
|
|
2124
|
+
double overlapY = Math.Min(ocrRect.Bottom, ry + rh) - Math.Max(ocrRect.Top, ry);
|
|
2125
|
+
double minH = Math.Min(ocrRect.Height, rh);
|
|
2126
|
+
if (minH > 0 && overlapY >= minH * 0.35 && rx >= ocrRect.Right - 12 && rx - ocrRect.Right <= 280) {
|
|
2127
|
+
double dist = Math.Max(0, rx - ocrRect.Right) + Math.Abs((ry + rh / 2) - (ocrRect.Y + ocrRect.Height / 2)) * 2.0;
|
|
2128
|
+
if (dist < bestScore) { bestScore = dist; best = e; }
|
|
2129
|
+
}
|
|
2130
|
+
// 2. Ô nhập nằm ngay bên dưới nhãn (cùng cột dọc)
|
|
2131
|
+
double overlapX = Math.Min(ocrRect.Right, rx + rw) - Math.Max(ocrRect.Left, rx);
|
|
2132
|
+
if ((Math.Abs(rx - ocrRect.Left) <= 140 || overlapX >= ocrRect.Width * 0.4) && ry >= ocrRect.Bottom - 8 && ry - ocrRect.Bottom <= 72) {
|
|
2133
|
+
double dist = Math.Max(0, ry - ocrRect.Bottom) * 1.5 + Math.Abs(rx - ocrRect.Left);
|
|
2134
|
+
if (dist < bestScore) { bestScore = dist; best = e; }
|
|
2135
|
+
}
|
|
2136
|
+
} catch { continue; }
|
|
2137
|
+
}
|
|
2138
|
+
return best;
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
static System.Windows.Point PointFor(AutomationElement el, IntPtr window, Dictionary<string, object> a) {
|
|
2142
|
+
if (el != null) return CenterOf(el);
|
|
2143
|
+
if (ocrPoint.HasValue) {
|
|
2144
|
+
if (ocrNodeId != null) { IntPtr w; return OcrPointOf(ocrNodeId, out w); }
|
|
2145
|
+
return ocrPoint.Value;
|
|
2146
|
+
}
|
|
2147
|
+
var pt = Get(a, "point") as Dictionary<string, object>;
|
|
2148
|
+
if (pt == null) throw new GuiError("INVALID_ARGS", "Give node_id or point {x,y}");
|
|
2149
|
+
return WindowPoint(window, a, pt);
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
/**
|
|
2153
|
+
* Bấm chuột thật (02/11/2026): đưa cửa sổ lên (khôi phục nếu thu nhỏ) TRƯỚC khi tính toạ độ — cửa sổ thu nhỏ có toạ độ ảo; không lên được
|
|
2154
|
+
* trên cùng, hoặc điểm bấm đang bị cửa sổ khác che → GUI_FOCUS_LOST, không bấm.
|
|
2155
|
+
*/
|
|
2156
|
+
static void MouseAt(AutomationElement el, IntPtr window, Dictionary<string, object> a, uint down, uint up, int times) {
|
|
2157
|
+
RequireForeground(window);
|
|
2158
|
+
var p = PointFor(el, window, a);
|
|
2159
|
+
int x = (int)p.X, y = (int)p.Y;
|
|
2160
|
+
AssertPointOnWindow(x, y, window);
|
|
2161
|
+
MoveCursor(x, y);
|
|
2162
|
+
Thread.Sleep(30);
|
|
2163
|
+
// Trong lúc di chuột có cửa sổ khác nhảy lên (thông báo, hộp thoại của ứng dụng khác) → không bấm.
|
|
2164
|
+
AssertPointOnWindow(x, y, window);
|
|
2165
|
+
lastMousePoint = new Dictionary<string, object> { { "x", x }, { "y", y } };
|
|
2166
|
+
var list = new List<Native.INPUT>();
|
|
2167
|
+
for (int i = 0; i < times; i++) { list.Add(MouseInput(down, 0, 0, 0)); list.Add(MouseInput(up, 0, 0, 0)); }
|
|
2168
|
+
Send(list.ToArray());
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
static Native.INPUT MouseInput(uint flags, int dx, int dy, int data) {
|
|
2172
|
+
var i = new Native.INPUT { type = INPUT_MOUSE };
|
|
2173
|
+
i.u.mi = new Native.MOUSEINPUT { dx = dx, dy = dy, mouseData = data, dwFlags = flags };
|
|
2174
|
+
return i;
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
static Native.INPUT KeyInput(ushort vk, ushort scan, uint flags) {
|
|
2178
|
+
var i = new Native.INPUT { type = INPUT_KEYBOARD };
|
|
2179
|
+
i.u.ki = new Native.KEYBDINPUT { wVk = vk, wScan = scan, dwFlags = flags };
|
|
2180
|
+
return i;
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
static void Send(Native.INPUT[] inputs) {
|
|
2184
|
+
if (inputs.Length == 0) return;
|
|
2185
|
+
GuardInput();
|
|
2186
|
+
uint sent = Native.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(Native.INPUT)));
|
|
2187
|
+
lastInjectedTick = Native.GetTickCount();
|
|
2188
|
+
if (sent != inputs.Length) throw new GuiError("GUI_INPUT_BLOCKED", "Windows blocked the input (a higher-privilege window is in front?)");
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
static void KeyTap(ushort vk) { Send(new[] { KeyInput(vk, 0, 0), KeyInput(vk, 0, KEYEVENTF_KEYUP) }); }
|
|
2192
|
+
|
|
2193
|
+
/**
|
|
2194
|
+
* Gõ chữ theo lô 200 input. Trước MỖI lô (02/11/2026): cửa sổ trên cùng vẫn là đích, và (khi kiểm người dùng) người dùng không vừa đụng
|
|
2195
|
+
* chuột / phím từ lô trước — lệch thì dừng, báo đã gõ bao nhiêu ký tự (chữ còn lại không rơi vào cửa sổ khác).
|
|
2196
|
+
*/
|
|
2197
|
+
static void TypeText(string text, IntPtr window) {
|
|
2198
|
+
var list = new List<Native.INPUT>();
|
|
2199
|
+
Native.POINT cursor;
|
|
2200
|
+
bool haveCursor = Native.GetCursorPos(out cursor);
|
|
2201
|
+
int typed = 0, inBatch = 0, total = text.Replace("\r", "").Length;
|
|
2202
|
+
bool first = true;
|
|
2203
|
+
foreach (char ch in text) {
|
|
2204
|
+
if (ch == '\r') continue;
|
|
2205
|
+
if (ch == '\n') { list.Add(KeyInput(0x0D, 0, 0)); list.Add(KeyInput(0x0D, 0, KEYEVENTF_KEYUP)); }
|
|
2206
|
+
else {
|
|
2207
|
+
list.Add(KeyInput(0, ch, KEYEVENTF_UNICODE));
|
|
2208
|
+
list.Add(KeyInput(0, ch, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP));
|
|
2209
|
+
}
|
|
2210
|
+
inBatch++;
|
|
2211
|
+
if (list.Count >= 200) {
|
|
2212
|
+
SendTextBatch(list, window, first, haveCursor, cursor, typed, total);
|
|
2213
|
+
typed += inBatch; inBatch = 0; first = false; list.Clear();
|
|
2214
|
+
Thread.Sleep(TYPE_BATCH_PAUSE_MS);
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
SendTextBatch(list, window, first, haveCursor, cursor, typed, total);
|
|
2218
|
+
}
|
|
2219
|
+
|
|
2220
|
+
static void SendTextBatch(List<Native.INPUT> list, IntPtr window, bool first, bool haveCursor, Native.POINT cursor, int typed, int total) {
|
|
2221
|
+
if (list.Count == 0) return;
|
|
2222
|
+
string done = typed + " of " + total + " characters";
|
|
2223
|
+
if (!first && userInputCheck && haveCursor && UserTouchedSince(cursor)) {
|
|
2224
|
+
throw new GuiError("GUI_USER_ACTIVE", "The user started using the mouse/keyboard while the AI was typing — stopped after " + done);
|
|
2225
|
+
}
|
|
2226
|
+
AssertStillForeground(window, done);
|
|
2227
|
+
Send(list.ToArray());
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
static readonly Dictionary<string, ushort> Keys = new Dictionary<string, ushort> {
|
|
2231
|
+
{ "ctrl", 0x11 }, { "control", 0x11 }, { "shift", 0x10 }, { "alt", 0x12 }, { "win", 0x5B }, { "meta", 0x5B },
|
|
2232
|
+
{ "enter", 0x0D }, { "return", 0x0D }, { "tab", 0x09 }, { "esc", 0x1B }, { "escape", 0x1B }, { "space", 0x20 },
|
|
2233
|
+
{ "backspace", 0x08 }, { "delete", 0x2E }, { "del", 0x2E }, { "insert", 0x2D }, { "home", 0x24 }, { "end", 0x23 },
|
|
2234
|
+
{ "pageup", 0x21 }, { "pagedown", 0x22 }, { "up", 0x26 }, { "down", 0x28 }, { "left", 0x25 }, { "right", 0x27 },
|
|
2235
|
+
{ "f1", 0x70 }, { "f2", 0x71 }, { "f3", 0x72 }, { "f4", 0x73 }, { "f5", 0x74 }, { "f6", 0x75 }, { "f7", 0x76 }, { "f8", 0x77 },
|
|
2236
|
+
{ "f9", 0x78 }, { "f10", 0x79 }, { "f11", 0x7A }, { "f12", 0x7B }, { "apps", 0x5D }, { "menu", 0x5D },
|
|
2237
|
+
};
|
|
2238
|
+
static readonly HashSet<ushort> Extended = new HashSet<ushort> { 0x2E, 0x2D, 0x24, 0x23, 0x21, 0x22, 0x26, 0x28, 0x25, 0x27, 0x5B, 0x5D };
|
|
2239
|
+
|
|
2240
|
+
/** "ctrl+s", "alt+f4", "enter", "ctrl+shift+n" — nhiều tổ hợp cách nhau bằng dấu cách: "ctrl+a delete". */
|
|
2241
|
+
static void KeyCombo(string spec, IntPtr window) {
|
|
2242
|
+
int n = 0;
|
|
2243
|
+
foreach (string combo in spec.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) {
|
|
2244
|
+
// Mỗi tổ hợp: cửa sổ trên cùng vẫn là đích (tổ hợp trước có thể đã mở / đóng cửa sổ).
|
|
2245
|
+
AssertStillForeground(window, n == 0 ? null : n + " key combination(s)");
|
|
2246
|
+
n++;
|
|
2247
|
+
var vks = new List<ushort>();
|
|
2248
|
+
foreach (string raw in combo.ToLowerInvariant().Split('+')) {
|
|
2249
|
+
string k = raw.Trim();
|
|
2250
|
+
if (k.Length == 0) continue;
|
|
2251
|
+
ushort vk;
|
|
2252
|
+
if (Keys.TryGetValue(k, out vk)) { vks.Add(vk); continue; }
|
|
2253
|
+
if (k.Length == 1) {
|
|
2254
|
+
short s = Native.VkKeyScan(k[0]);
|
|
2255
|
+
if (s == -1) throw new GuiError("INVALID_ARGS", "Unknown key: " + k);
|
|
2256
|
+
vks.Add((ushort)(s & 0xFF));
|
|
2257
|
+
continue;
|
|
2258
|
+
}
|
|
2259
|
+
throw new GuiError("INVALID_ARGS", "Unknown key: " + k);
|
|
2260
|
+
}
|
|
2261
|
+
if (vks.Count == 0) continue;
|
|
2262
|
+
var list = new List<Native.INPUT>();
|
|
2263
|
+
foreach (var vk in vks) list.Add(KeyInput(vk, 0, Extended.Contains(vk) ? KEYEVENTF_EXTENDEDKEY : 0));
|
|
2264
|
+
for (int i = vks.Count - 1; i >= 0; i--) list.Add(KeyInput(vks[i], 0, KEYEVENTF_KEYUP | (Extended.Contains(vks[i]) ? KEYEVENTF_EXTENDEDKEY : 0)));
|
|
2265
|
+
Send(list.ToArray());
|
|
2266
|
+
Thread.Sleep(40);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
|
|
2271
|
+
/** 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. */
|
|
2272
|
+
public class OcrSegment {
|
|
2273
|
+
public string Text;
|
|
2274
|
+
public System.Windows.Rect Rect;
|
|
2275
|
+
}
|
|
2276
|
+
|
|
2277
|
+
/**
|
|
2278
|
+
* 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,
|
|
2279
|
+
* 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
|
|
2280
|
+
* ngữ hồ sơ người dùng.
|
|
2281
|
+
*/
|
|
2282
|
+
public static class Ocr {
|
|
2283
|
+
const string WRT = "System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
|
|
2284
|
+
static readonly Dictionary<string, object> Engines = new Dictionary<string, object>();
|
|
2285
|
+
static MethodInfo asTask;
|
|
2286
|
+
|
|
2287
|
+
static Type WinRT(string name, string asm) { return Type.GetType(name + ", " + asm + ", ContentType=WindowsRuntime", true); }
|
|
2288
|
+
|
|
2289
|
+
/** 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). */
|
|
2290
|
+
static object Call(MethodInfo mi, object target, params object[] args) {
|
|
2291
|
+
object op = mi.Invoke(target, args);
|
|
2292
|
+
if (asTask == null) {
|
|
2293
|
+
foreach (var m in Type.GetType("System.WindowsRuntimeSystemExtensions, " + WRT, true).GetMethods()) {
|
|
2294
|
+
var ps = m.GetParameters();
|
|
2295
|
+
if (m.Name == "AsTask" && m.IsGenericMethod && ps.Length == 1 && ps[0].ParameterType.GetGenericTypeDefinition().FullName == "Windows.Foundation.IAsyncOperation" + (char)96 + "1") { asTask = m; break; }
|
|
2296
|
+
}
|
|
2297
|
+
if (asTask == null) throw new GuiError("GUI_OCR_UNAVAILABLE", "WinRT async bridge not found");
|
|
2298
|
+
}
|
|
2299
|
+
var task = (System.Threading.Tasks.Task)asTask.MakeGenericMethod(mi.ReturnType.GetGenericArguments()[0]).Invoke(null, new[] { op });
|
|
2300
|
+
if (!task.Wait(15000)) throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR timed out");
|
|
2301
|
+
return task.GetType().GetProperty("Result").GetValue(task, null);
|
|
2302
|
+
}
|
|
2303
|
+
|
|
2304
|
+
static object Engine(string lang, out string used) {
|
|
2305
|
+
var engineT = WinRT("Windows.Media.Ocr.OcrEngine", "Windows.Media");
|
|
2306
|
+
var tries = new List<string>();
|
|
2307
|
+
if (!string.IsNullOrEmpty(lang)) tries.Add(lang);
|
|
2308
|
+
tries.Add("vi");
|
|
2309
|
+
tries.Add("");
|
|
2310
|
+
foreach (var t in tries) {
|
|
2311
|
+
object e;
|
|
2312
|
+
if (Engines.TryGetValue(t, out e) && e != null) { used = Tag(e); return e; }
|
|
2313
|
+
if (t.Length == 0) {
|
|
2314
|
+
e = engineT.GetMethod("TryCreateFromUserProfileLanguages").Invoke(null, null);
|
|
2315
|
+
} else {
|
|
2316
|
+
var langT = WinRT("Windows.Globalization.Language", "Windows.Globalization");
|
|
2317
|
+
object l;
|
|
2318
|
+
try { l = Activator.CreateInstance(langT, t); } catch { continue; }
|
|
2319
|
+
e = engineT.GetMethod("TryCreateFromLanguage").Invoke(null, new[] { l });
|
|
2320
|
+
}
|
|
2321
|
+
Engines[t] = e;
|
|
2322
|
+
if (e != null) { used = Tag(e); return e; }
|
|
2323
|
+
}
|
|
2324
|
+
throw new GuiError("GUI_OCR_UNAVAILABLE", "No OCR language is installed on this PC");
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
static string Tag(object engine) {
|
|
2328
|
+
var l = engine.GetType().GetProperty("RecognizerLanguage").GetValue(engine, null);
|
|
2329
|
+
return Convert.ToString(l.GetType().GetProperty("LanguageTag").GetValue(l, null));
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2332
|
+
static double D(object o, string p) { return Convert.ToDouble(o.GetType().GetProperty(p).GetValue(o, null)); }
|
|
2333
|
+
|
|
2334
|
+
public static List<OcrSegment> Read(Bitmap bmp, string lang, out string used) {
|
|
2335
|
+
try {
|
|
2336
|
+
return ReadInner(bmp, lang, out used);
|
|
2337
|
+
} catch (TargetInvocationException e) {
|
|
2338
|
+
throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR failed: " + (e.InnerException != null ? e.InnerException.Message : e.Message));
|
|
2339
|
+
} catch (AggregateException e) {
|
|
2340
|
+
throw new GuiError("GUI_OCR_UNAVAILABLE", "OCR failed: " + e.InnerException.Message);
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
/**
|
|
2345
|
+
* OCR của Windows chỉnh cho dòng chữ cỡ đọc sách: chữ trên nút nhỏ và ký tự đơn ("C", "7", "+") ở cỡ giao diện 100% hay bị bỏ qua hẳn
|
|
2346
|
+
* (gui-bench 13/11/2026: cả bàn phím Máy tính chỉ đọc được "CE"). Phóng ảnh 2 lần (nội suy bicubic) trước khi đọc rồi chia toạ độ lại;
|
|
2347
|
+
* ảnh đã lớn (màn hình 4K, cửa sổ phóng to) thì đọc nguyên cỡ để không vượt MaxImageDimension và không tốn thời gian.
|
|
2348
|
+
*/
|
|
2349
|
+
const int OCR_UPSCALE_MAX_SIDE = 1400;
|
|
2350
|
+
|
|
2351
|
+
static List<OcrSegment> ReadInner(Bitmap bmp, string lang, out string used) {
|
|
2352
|
+
double scale = Math.Max(bmp.Width, bmp.Height) <= OCR_UPSCALE_MAX_SIDE ? 2.0 : 1.0;
|
|
2353
|
+
if (scale == 1.0) return ReadAt(bmp, lang, 1.0, out used);
|
|
2354
|
+
using (var big = new Bitmap((int)(bmp.Width * scale), (int)(bmp.Height * scale), PixelFormat.Format32bppArgb)) {
|
|
2355
|
+
using (var g = Graphics.FromImage(big)) {
|
|
2356
|
+
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
|
|
2357
|
+
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
|
|
2358
|
+
g.DrawImage(bmp, 0, 0, big.Width, big.Height);
|
|
2359
|
+
}
|
|
2360
|
+
return ReadAt(big, lang, scale, out used);
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
|
|
2364
|
+
static List<OcrSegment> ReadAt(Bitmap bmp, string lang, double scale, out string used) {
|
|
2365
|
+
object engine = Engine(lang, out used);
|
|
2366
|
+
var engineT = engine.GetType();
|
|
2367
|
+
byte[] png;
|
|
2368
|
+
using (var ms = new MemoryStream()) { bmp.Save(ms, ImageFormat.Png); png = ms.ToArray(); }
|
|
2369
|
+
var ras = Type.GetType("System.IO.WindowsRuntimeStreamExtensions, " + WRT, true)
|
|
2370
|
+
.GetMethod("AsRandomAccessStream", new[] { typeof(Stream) }).Invoke(null, new object[] { new MemoryStream(png) });
|
|
2371
|
+
var decT = WinRT("Windows.Graphics.Imaging.BitmapDecoder", "Windows.Graphics");
|
|
2372
|
+
var decoder = Call(decT.GetMethod("CreateAsync", new[] { WinRT("Windows.Storage.Streams.IRandomAccessStream", "Windows.Storage") }), null, ras);
|
|
2373
|
+
var soft = Call(decT.GetMethod("GetSoftwareBitmapAsync", Type.EmptyTypes), decoder);
|
|
2374
|
+
var result = Call(WinRT("Windows.Media.Ocr.OcrEngine", "Windows.Media").GetMethod("RecognizeAsync"), engine, soft);
|
|
2375
|
+
var segments = new List<OcrSegment>();
|
|
2376
|
+
foreach (var line in (System.Collections.IEnumerable)result.GetType().GetProperty("Lines").GetValue(result, null)) {
|
|
2377
|
+
// 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ữ.
|
|
2378
|
+
OcrSegment cur = null;
|
|
2379
|
+
double lastRight = 0;
|
|
2380
|
+
foreach (var w in (System.Collections.IEnumerable)line.GetType().GetProperty("Words").GetValue(line, null)) {
|
|
2381
|
+
var r = w.GetType().GetProperty("BoundingRect").GetValue(w, null);
|
|
2382
|
+
var rect = new System.Windows.Rect(D(r, "X") / scale, D(r, "Y") / scale, D(r, "Width") / scale, D(r, "Height") / scale);
|
|
2383
|
+
string text = Convert.ToString(w.GetType().GetProperty("Text").GetValue(w, null));
|
|
2384
|
+
if (cur != null && rect.X - lastRight > Math.Max(8, Math.Max(rect.Height, cur.Rect.Height))) { segments.Add(cur); cur = null; }
|
|
2385
|
+
if (cur == null) cur = new OcrSegment { Text = text, Rect = rect };
|
|
2386
|
+
else { cur.Text += " " + text; cur.Rect = System.Windows.Rect.Union(cur.Rect, rect); }
|
|
2387
|
+
lastRight = rect.Right;
|
|
2388
|
+
}
|
|
2389
|
+
if (cur != null) segments.Add(cur);
|
|
2390
|
+
}
|
|
2391
|
+
return segments;
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
`;
|
|
2396
|
+
|
|
2397
|
+
export const WINDOWS_HOST_CSHARP = MAIN_CSHARP + OFFICE_CSHARP;
|
|
2398
|
+
|
|
2399
|
+
/** Script PowerShell: nạp DLL đã dịch (nếu có), không thì dịch từ mã C# rồi lưu DLL; sau đó chạy vòng đọc/ghi JSON. */
|
|
2400
|
+
export const WINDOWS_HOST_PS1 = String.raw`
|
|
2401
|
+
$ErrorActionPreference = 'Stop'
|
|
2402
|
+
$dll = $env:AIVIN_GUI_DLL
|
|
2403
|
+
$src = $env:AIVIN_GUI_SRC
|
|
2404
|
+
$refs = @('UIAutomationClient', 'UIAutomationTypes', 'WindowsBase', 'System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions', 'Accessibility')
|
|
2405
|
+
if ($dll -and (Test-Path -LiteralPath $dll)) {
|
|
2406
|
+
Add-Type -Path $dll
|
|
2407
|
+
} else {
|
|
2408
|
+
foreach ($r in $refs) { Add-Type -AssemblyName $r }
|
|
2409
|
+
if ($dll) {
|
|
2410
|
+
Add-Type -TypeDefinition ([IO.File]::ReadAllText($src)) -ReferencedAssemblies $refs -OutputAssembly $dll -OutputType Library
|
|
2411
|
+
Add-Type -Path $dll
|
|
2412
|
+
} else {
|
|
2413
|
+
Add-Type -TypeDefinition ([IO.File]::ReadAllText($src)) -ReferencedAssemblies $refs
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
foreach ($r in $refs) { Add-Type -AssemblyName $r }
|
|
2417
|
+
[AivinGui.Host]::Run()
|
|
2418
|
+
`;
|