dsh-native-uia 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +663 -2
  3. package/client/client.js +269 -0
  4. package/cordis.patch.yml +10 -0
  5. package/icon.svg +11 -0
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/package.json +75 -4
  9. package/scripts/bench-live.mjs +157 -0
  10. package/scripts/check-lease.mjs +308 -0
  11. package/scripts/install.mjs +154 -0
  12. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  13. package/scripts/lib/load-tools-source.mjs +25 -0
  14. package/scripts/lib/sources.mjs +62 -0
  15. package/scripts/load-tools.mjs +74 -0
  16. package/scripts/measure-parse.mjs +77 -0
  17. package/scripts/regression-halt-latch.mjs +100 -0
  18. package/scripts/regression-quality.mjs +207 -0
  19. package/scripts/regression-tools.mjs +192 -0
  20. package/scripts/regression-worker.ps1 +1071 -0
  21. package/scripts/smoke.mjs +158 -0
  22. package/scripts/verify-capture-scale.mjs +37 -0
  23. package/scripts/verify-live-clipboard.mjs +108 -0
  24. package/scripts/verify-live-style.mjs +46 -0
  25. package/scripts/verify-live.mjs +104 -0
  26. package/scripts/verify-locator.mjs +52 -0
  27. package/scripts/verify.mjs +2110 -0
  28. package/src/activity-window.js +276 -0
  29. package/src/dashboard.js +103 -0
  30. package/src/guard.js +201 -0
  31. package/src/index.js +525 -0
  32. package/src/native-uia-remote.js +80 -0
  33. package/src/notes.js +83 -0
  34. package/src/state.js +267 -0
  35. package/src/themes.js +74 -0
  36. package/src/tools/defs/act.js +533 -0
  37. package/src/tools/defs/lifecycle.js +205 -0
  38. package/src/tools/defs/observe.js +309 -0
  39. package/src/tools/defs/pointer.js +298 -0
  40. package/src/tools/format.js +301 -0
  41. package/src/tools/index.js +128 -0
  42. package/src/tools/ocr.js +91 -0
  43. package/src/tools/recipes.js +44 -0
  44. package/src/tools/runtime.js +42 -0
  45. package/src/worker-client.js +268 -0
  46. package/worker/assets/dsh-whale.path +1 -0
  47. package/worker/bin/build-ocr.ps1 +41 -0
  48. package/worker/bin/ocr.cs +69 -0
  49. package/worker/bin/ocr.exe +0 -0
  50. package/worker/indicator-server.ps1 +2963 -0
  51. package/worker/lib/01-core.ps1 +64 -0
  52. package/worker/lib/02-uia.ps1 +221 -0
  53. package/worker/lib/03-window.ps1 +194 -0
  54. package/worker/lib/04-match.ps1 +435 -0
  55. package/worker/lib/05-value.ps1 +149 -0
  56. package/worker/lib/06-snapshot.ps1 +345 -0
  57. package/worker/lib/07-action.ps1 +291 -0
  58. package/worker/lib/08-command.ps1 +1485 -0
  59. package/worker/lib/09-pointer.ps1 +840 -0
  60. package/worker/lib/10-dispatch.ps1 +134 -0
  61. package/worker/ps-stdio.ps1 +173 -0
  62. package/worker/uia-worker.ps1 +599 -0
@@ -0,0 +1,345 @@
1
+ # 06-snapshot.ps1 -- snapshot walker and node building
2
+ #
3
+ # Part of worker/uia-worker.ps1, dot-sourced by it in the order scripts/lib/sources.mjs declares.
4
+ # It lives in its own file only so a section can be read without scrolling the whole RPC server.
5
+ # Dot-sourcing shares the entry's script scope, so a helper here may use $script:W and may call
6
+ # any function from any other part: neighbour order is not a dependency.
7
+ # ---------------------------------------------------------------- snapshot
8
+ # One CacheRequest shared by every snapshot walk, handed to the walker's cached overloads
9
+ # (GetFirstChild/GetNextSibling with a request — reflection-confirmed overloads) and, at Subtree
10
+ # scope, to the one-shot GetUpdatedCache path. The request carries the seven properties the node
11
+ # builder reads, PLUS RuntimeIdProperty (probe-verified bit-identical to GetRuntimeId() on real
12
+ # trees — the old "cache returns an empty array" note was a probe artifact and did not reproduce),
13
+ # PLUS every Is*PatternAvailableProperty the managed client has (19 exist; there is no managed
14
+ # LegacyIAccessible availability property, so a cached pattern list never names it — accepted
15
+ # shrink, see Cached-PatternsOf), PLUS the four value-bearing pattern objects Read-Value's
16
+ # snapshot path reads from the cache. AutomationElementMode stays Full so refs minted from cached
17
+ # elements remain usable for live pattern calls later (invoke/set_value read patterns through the
18
+ # same element).
19
+ $script:snapReq = $null
20
+ $script:subTreeReq = $null
21
+ $script:findReq = $null
22
+ $script:snapProps = @(
23
+ 'NameProperty', 'ClassNameProperty', 'ControlTypeProperty', 'AutomationIdProperty',
24
+ 'IsEnabledProperty', 'IsOffscreenProperty', 'BoundingRectangleProperty', 'RuntimeIdProperty',
25
+ 'IsDockPatternAvailableProperty', 'IsExpandCollapsePatternAvailableProperty', 'IsGridItemPatternAvailableProperty',
26
+ 'IsGridPatternAvailableProperty', 'IsInvokePatternAvailableProperty', 'IsItemContainerPatternAvailableProperty',
27
+ 'IsMultipleViewPatternAvailableProperty', 'IsRangeValuePatternAvailableProperty', 'IsScrollItemPatternAvailableProperty',
28
+ 'IsScrollPatternAvailableProperty', 'IsSelectionItemPatternAvailableProperty', 'IsSelectionPatternAvailableProperty',
29
+ 'IsTableItemPatternAvailableProperty', 'IsTablePatternAvailableProperty', 'IsTextPatternAvailableProperty',
30
+ 'IsTogglePatternAvailableProperty', 'IsTransformPatternAvailableProperty', 'IsValuePatternAvailableProperty',
31
+ 'IsWindowPatternAvailableProperty'
32
+ )
33
+ $script:snapPatterns = @(
34
+ [System.Windows.Automation.ValuePattern]::Pattern,
35
+ [System.Windows.Automation.TogglePattern]::Pattern,
36
+ [System.Windows.Automation.RangeValuePattern]::Pattern,
37
+ [System.Windows.Automation.ExpandCollapsePattern]::Pattern
38
+ )
39
+ function New-SnapshotCacheRequest($scope) {
40
+ $req = New-Object System.Windows.Automation.CacheRequest
41
+ $req.TreeScope = $scope
42
+ $req.AutomationElementMode = [System.Windows.Automation.AutomationElementMode]::Full
43
+ foreach ($p in $script:snapProps) {
44
+ $req.Add([System.Windows.Automation.AutomationElement]::$p)
45
+ }
46
+ foreach ($pat in $script:snapPatterns) {
47
+ $req.Add($pat)
48
+ }
49
+ return $req
50
+ }
51
+ function Snapshot-CacheRequest {
52
+ if ($null -eq $script:snapReq) {
53
+ try {
54
+ $script:snapReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Element)
55
+ } catch {
56
+ Log ('CacheRequest build failed, snapshot falls back to live reads: ' + $_.Exception.Message)
57
+ }
58
+ }
59
+ return $script:snapReq
60
+ }
61
+ function Subtree-CacheRequest {
62
+ # One-shot path: the same property list at TreeScope=Subtree. GetUpdatedCache(Subtree)
63
+ # materialises the WHOLE subtree in one cross-process call (measured 0.10-0.16 ms/node vs
64
+ # ~1.5 ms/node for the Activate+FindAll shape and ~4.4 ms/node for the per-child walker).
65
+ # Kept as its own request object so the walker fallback never changes scope under it.
66
+ if ($null -eq $script:subTreeReq) {
67
+ try {
68
+ $script:subTreeReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Subtree)
69
+ } catch {
70
+ Log ('subtree CacheRequest build failed, snapshot falls back to the walker: ' + $_.Exception.Message)
71
+ }
72
+ }
73
+ return $script:subTreeReq
74
+ }
75
+ function Find-CacheRequest {
76
+ # find_text's own request object — deliberately NOT the shared $script:snapReq: the two callers
77
+ # must not fight over one request (find_text activates and pops within one command, and a
78
+ # snapshot in flight on the same thread would see its scope changed under it).
79
+ if ($null -eq $script:findReq) {
80
+ try {
81
+ $script:findReq = New-SnapshotCacheRequest ([System.Windows.Automation.TreeScope]::Element)
82
+ } catch {
83
+ Log ('find_text CacheRequest build failed, find_text falls back to live reads: ' + $_.Exception.Message)
84
+ }
85
+ }
86
+ return $script:findReq
87
+ }
88
+
89
+ # The walker used by the snapshot fallback path. One indirection so the test harness can walk a
90
+ # mock tree through the SAME code path (regression-worker.ps1 redefines this and feeds a mock
91
+ # walker); production always gets the ControlViewWalker.
92
+ function Get-SnapshotWalker {
93
+ return [System.Windows.Automation.TreeWalker]::ControlViewWalker
94
+ }
95
+
96
+ # Builds ONE snapshot node (shared by the one-shot subtree path and the walker fallback): the emit
97
+ # filter, the node fields, the ref minting and the value read all live here, so the two paths
98
+ # cannot drift. $ctx is the shared mutable state hashtable (a script-scope function cannot see
99
+ # Build-Snapshot's locals). A per-node provider failure records nodeProviderError and lets the
100
+ # walk continue — the per-node fault-tolerance contract is unchanged.
101
+ function Build-SnapshotNode($el, $depth, $cp, $ctx) {
102
+ try {
103
+ $ctx.visited += 1
104
+ # Hoist each cross-process property read once; Current/Cached does not cache these reads.
105
+ $ctRaw = $cp.ControlType
106
+ $nm = [string]$cp.Name
107
+ $cls = [string]$cp.ClassName
108
+ $off = [bool]$cp.IsOffscreen
109
+ $ctn = ControlTypeName $ctRaw
110
+ $emit = $true
111
+ if ($ctx.fCtSet.Count -gt 0 -and -not $ctx.fCtSet.ContainsKey($ctn)) { $emit = $false }
112
+ # Literal, case-insensitive containment: -like treats * ? [ ] in a caller's text as
113
+ # wildcards, so a control whose name really contains brackets matched the wrong things.
114
+ if ($ctx.fClass -ne '' -and $cls.IndexOf($ctx.fClass, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $emit = $false }
115
+ if ($ctx.fName -ne '' -and $nm.IndexOf($ctx.fName, [StringComparison]::OrdinalIgnoreCase) -lt 0) { $emit = $false }
116
+ if (-not $ctx.incOff -and $off -and $depth -gt 0) { $emit = $false }
117
+ $patterns = @()
118
+ if ($emit) {
119
+ if ($ctx.wantPatterns) { $patterns = PatternsOf $el }
120
+ $aid = [string]$cp.AutomationId
121
+ $enabled = [bool]$cp.IsEnabled
122
+ $rc = RectOf $cp
123
+ $node = [ordered]@{
124
+ ref = ('e' + ($script:W.refSeq + 1))
125
+ controlType = $ctn
126
+ name = (TruncStr $nm 160)
127
+ className = $cls
128
+ automationId = $aid
129
+ depth = $depth
130
+ patterns = @($patterns)
131
+ enabled = $enabled
132
+ isOffscreen = $off
133
+ rect = $rc
134
+ }
135
+ # Only when truncation happened: the untruncated name a saved recipe needs to re-resolve
136
+ # later (a 160-cut name with '~' can never satisfy a strict match). Short names carry no
137
+ # extra field, so the wire shape stays unchanged for the 99% case.
138
+ if ($nm.Length -gt 160) { $node['fullName'] = $nm }
139
+ if ($ctx.wantValues -and -not $off) {
140
+ $v = Read-Value $el $patterns $null $true
141
+ if ($v -ne '') {
142
+ $node['value'] = (TruncStr $v 200)
143
+ if ($v.Length -gt 200) { $node['valueTruncated'] = $true }
144
+ }
145
+ }
146
+ $null = New-Ref $ctx.entry $el $cp $node
147
+ $ctx.nodes.Add($node) | Out-Null
148
+ }
149
+ return $true
150
+ } catch {
151
+ $ctx.truncated = $true
152
+ $ctx.partialReasons['nodeProviderError'] = $true
153
+ $ctx.providerErrors += 1
154
+ return $true
155
+ }
156
+ }
157
+
158
+ function Build-Snapshot($entry, $A) {
159
+ $ae = Window-Ae $entry
160
+ if ($null -eq $ae) { Err 'window_not_found' ("window " + $entry.id + " (hwnd " + $entry.hwnd + ") is gone") }
161
+ $maxNodes = IntArg $A 'maxNodes' 300
162
+ if ($maxNodes -lt 1) { $maxNodes = 1 }
163
+ if ($maxNodes -gt $script:W.maxRefs) { $maxNodes = $script:W.maxRefs }
164
+ $wantPatterns = BoolArg $A 'patterns' $true
165
+ $wantValues = BoolArg $A 'values' $true
166
+ $maxDepth = IntArg $A 'maxDepth' 30
167
+ $filter = Dict (ArgOf $A 'filter')
168
+ $fCt = ''; $fCtSet = @{}; $fName = ''; $fClass = ''; $incOff = $true
169
+ if ($null -ne $filter) {
170
+ $fCt = [string](ArgOf $filter 'controlType')
171
+ # The tool contract advertises controlType as a comma-separated set ("Button,Edit"). Comparing
172
+ # the whole string against one node's type silently matched nothing, so a documented filter
173
+ # returned an empty tree. Split once and test membership.
174
+ foreach ($t in ($fCt -split ',')) {
175
+ $tt = $t.Trim()
176
+ if ($tt -ne '') { $fCtSet[$tt] = $true }
177
+ }
178
+ $fName = [string](ArgOf $filter 'nameContains')
179
+ $fClass = [string](ArgOf $filter 'className')
180
+ $io = ArgOf $filter 'includeOffscreen'
181
+ if ($null -eq $io) { $incOff = $false } else { $incOff = BoolArg $filter 'includeOffscreen' $false }
182
+ } else {
183
+ $incOff = BoolArg $A 'includeOffscreen' $true
184
+ }
185
+ $reserve = [Math]::Min($maxNodes, 900)
186
+ $evicted = Evict-ForReservation $reserve
187
+
188
+ $entry.revision += 1
189
+ $snap = @{ revision = $entry.revision; windowId = $entry.id; createdTick = TickNow; refs = (New-Object System.Collections.Generic.List[string]); started = (TickNow) }
190
+ $entry.snapshots.Add($snap)
191
+ $entry.lastSeen = (TickNow)
192
+ $script:W.stats.snapshots += 1
193
+
194
+ $walker = Get-SnapshotWalker
195
+ $req = Snapshot-CacheRequest
196
+ $nodes = New-Object System.Collections.Generic.List[object]
197
+ $siblingLimit = 512
198
+ $stack = New-Object System.Collections.Generic.Stack[object]
199
+ $stack.Push(@($ae, 0))
200
+ # Shared mutable walk state: one hashtable, because the node builder is a script-scope function
201
+ # and cannot see this function's locals. Same fields the old loop locals carried.
202
+ $ctx = @{
203
+ entry = $entry
204
+ nodes = $nodes
205
+ visited = 0
206
+ truncated = $false
207
+ partialReasons = @{}
208
+ providerErrors = 0
209
+ fCtSet = $fCtSet
210
+ fClass = $fClass
211
+ fName = $fName
212
+ incOff = $incOff
213
+ wantPatterns = $wantPatterns
214
+ wantValues = $wantValues
215
+ }
216
+
217
+ # ---- one-shot subtree path ---------------------------------------------------------------
218
+ # ONE cross-process call (GetUpdatedCache at TreeScope=Subtree) materialises the whole subtree
219
+ # with every property, pattern availability and RuntimeId already cached; everything after it
220
+ # is in-memory (measured 0.10-0.16 ms/node vs ~1.5 ms/node for an Activate+FindAll shape and
221
+ # ~4.4 ms/node for the per-child walker). This is NOT a cost cap: the whole-tree materialisation
222
+ # is paid BEFORE any node cap is checked (a Chromium window materialises its full a11y tree in
223
+ # that one call and it cannot be interrupted) — the cap below only stops the in-memory walk from
224
+ # continuing on a pathological tree, and the walker fallback after it is loss control, not fee
225
+ # control. A provider that refuses the bulk cache (or any failure here) falls back to the
226
+ # per-child walker below, which carries the same emit contract.
227
+ $oneShot = $null
228
+ $subReq = Subtree-CacheRequest
229
+ if ($null -ne $subReq) {
230
+ try {
231
+ $rootC = $ae.GetUpdatedCache($subReq)
232
+ if ($null -ne $rootC) {
233
+ $oneShot = New-Object System.Collections.Generic.List[object]
234
+ $nav = New-Object System.Collections.Generic.Stack[object]
235
+ $nav.Push(@($rootC, 0))
236
+ $hardCap = 3000
237
+ $tooBig = $false
238
+ while ($nav.Count -gt 0) {
239
+ $pair = $nav.Pop()
240
+ $oneShot.Add($pair) | Out-Null
241
+ if ($oneShot.Count -gt $hardCap) { $tooBig = $true; break }
242
+ $d = [int]$pair[1]
243
+ if ($d -ge $maxDepth) { $ctx.truncated = $true; $ctx.partialReasons['maxDepth'] = $true; continue }
244
+ try { $kids = $pair[0].CachedChildren } catch {
245
+ $ctx.truncated = $true; $ctx.partialReasons['childProviderError'] = $true; $ctx.providerErrors += 1
246
+ continue
247
+ }
248
+ for ($j = $kids.Count - 1; $j -ge 0; $j--) { $nav.Push(@($kids[$j], ($d + 1))) }
249
+ }
250
+ if ($tooBig) {
251
+ Log ('one-shot subtree exceeded ' + $hardCap + ' nodes; falling back to the walker path')
252
+ $oneShot = $null
253
+ }
254
+ }
255
+ } catch {
256
+ Log ('one-shot subtree cache failed, falling back to the walker: ' + $_.Exception.Message)
257
+ $oneShot = $null
258
+ }
259
+ }
260
+
261
+ if ($null -ne $oneShot) {
262
+ foreach ($pair in $oneShot) {
263
+ if ($nodes.Count -ge $maxNodes) { $ctx.truncated = $true; $ctx.partialReasons['maxNodes'] = $true; break }
264
+ Test-Deadline 'snapshot'
265
+ $el = $pair[0]; $depth = [int]$pair[1]
266
+ try {
267
+ # TreeScope=Subtree includes Element, so even the root carries its cache here — unlike the
268
+ # walker path below, where the depth-0 root is still read live.
269
+ $cp = $el.Cached
270
+ if ($null -eq $cp) { throw 'provider returned no Cached properties' }
271
+ } catch {
272
+ $ctx.truncated = $true; $ctx.partialReasons['nodeProviderError'] = $true; $ctx.providerErrors += 1
273
+ continue
274
+ }
275
+ [void](Build-SnapshotNode $el $depth $cp $ctx)
276
+ }
277
+ } else {
278
+ while ($stack.Count -gt 0) {
279
+ if ($nodes.Count -ge $maxNodes) { $ctx.truncated = $true; $ctx.partialReasons['maxNodes'] = $true; break }
280
+ Test-Deadline 'snapshot'
281
+ $pair = $stack.Pop()
282
+ $el = $pair[0]; $depth = [int]$pair[1]
283
+ # A single provider/property failure must not discard the rest of the snapshot. Keep
284
+ # walking this node's children as well: Current can fail while navigation still works.
285
+ try {
286
+ # Depth 0 is the live window element: the walker's cached overloads apply the request to the
287
+ # element they RETURN, so the root has no cached blob and one node's live reads are noise.
288
+ # Every node below it came back from GetFirstChild/GetNextSibling(el, request) and reads its
289
+ # seven properties from the cached blob with no cross-process round-trip. Same struct shape
290
+ # as Current, so the builder below is unchanged.
291
+ $cp = if ($null -ne $req -and $depth -gt 0) { $el.Cached } else { $el.Current }
292
+ if ($null -eq $cp) { throw 'provider returned no Current properties' }
293
+ [void](Build-SnapshotNode $el $depth $cp $ctx)
294
+ } catch {
295
+ $ctx.truncated = $true; $ctx.partialReasons['nodeProviderError'] = $true; $ctx.providerErrors += 1
296
+ }
297
+ if ($depth -ge $maxDepth) { $ctx.truncated = $true; $ctx.partialReasons['maxDepth'] = $true; continue }
298
+ $kids = New-Object System.Collections.Generic.List[object]
299
+ $c = $null
300
+ # The request overload returns the child WITH its properties already cached — one round-trip
301
+ # instead of one navigation call plus seven property reads (see Snapshot-CacheRequest).
302
+ try { $c = if ($null -ne $req) { $walker.GetFirstChild($el, $req) } else { $walker.GetFirstChild($el) } } catch {
303
+ $ctx.truncated = $true; $ctx.partialReasons['childProviderError'] = $true; $ctx.providerErrors += 1
304
+ }
305
+ while ($null -ne $c) {
306
+ if ($kids.Count -ge $siblingLimit) { $ctx.truncated = $true; $ctx.partialReasons['siblingLimit'] = $true; break }
307
+ $kids.Add($c) | Out-Null
308
+ try { $c = if ($null -ne $req) { $walker.GetNextSibling($c, $req) } else { $walker.GetNextSibling($c) } } catch {
309
+ $c = $null; $ctx.truncated = $true; $ctx.partialReasons['siblingProviderError'] = $true; $ctx.providerErrors += 1
310
+ }
311
+ }
312
+ for ($j = $kids.Count - 1; $j -ge 0; $j--) { $stack.Push(@($kids[$j], ($depth + 1))) }
313
+ }
314
+ }
315
+ $ms = MsFrom $snap.started
316
+ $result = [ordered]@{
317
+ revision = $entry.revision
318
+ windowId = $entry.id
319
+ nodeCount = $nodes.Count
320
+ visited = $ctx.visited
321
+ truncated = [bool]$ctx.truncated
322
+ maxNodesApplied = $maxNodes
323
+ ceiling = [int]$script:W.maxRefs
324
+ totalRefs = $script:W.totalRefs
325
+ evictions = $evicted.Count
326
+ ms = $ms
327
+ msPerNode = if ($nodes.Count -gt 0) { [Math]::Round($ms / $nodes.Count, 3) } else { 0 }
328
+ nodes = $nodes
329
+ }
330
+ if ($ctx.partialReasons.Count -gt 0) { $result['partialReason'] = (($ctx.partialReasons.Keys | Sort-Object) -join ',') }
331
+ if ($ctx.providerErrors -gt 0) { $result['providerErrors'] = $ctx.providerErrors }
332
+ if ($evicted.Count -gt 0) { $result['evicted'] = $evicted }
333
+ if ($nodes.Count -eq 0) { $result['detail'] = 'no nodes matched; check filter or take an unfiltered snapshot' }
334
+ # Position metadata: what is foreground and where the focus sits right now. Advisory,
335
+ # try/catch-guarded — a probe failure just omits the fields, it never fails the snapshot.
336
+ try {
337
+ $obsHeader = Window-ObservationHeader $entry
338
+ if ($null -ne $obsHeader) {
339
+ foreach ($k in @($obsHeader.Keys)) { $result[$k] = $obsHeader[$k] }
340
+ }
341
+ } catch { }
342
+ return $result
343
+ }
344
+
345
+
@@ -0,0 +1,291 @@
1
+ # 07-action.ps1 -- element actions and wait conditions
2
+ #
3
+ # Part of worker/uia-worker.ps1, dot-sourced by it in the order scripts/lib/sources.mjs declares.
4
+ # It lives in its own file only so a section can be read without scrolling the whole RPC server.
5
+ # Dot-sourcing shares the entry's script scope, so a helper here may use $script:W and may call
6
+ # any function from any other part: neighbour order is not a dependency.
7
+ # ---------------------------------------------------------------- actions
8
+ function Is-ForegroundHwnd($hwnd) {
9
+ try { return ([Native]::GetForegroundWindow() -eq [IntPtr]$hwnd) } catch { return $false }
10
+ }
11
+
12
+ function Foreground-Hwnd {
13
+ try { return [Native]::GetForegroundWindow() } catch { return [IntPtr]::Zero }
14
+ }
15
+
16
+ function Cursor-Pos {
17
+ try { $p = [System.Windows.Forms.Cursor]::Position; return @{ x = [int]$p.X; y = [int]$p.Y } } catch { return @{ x = -1; y = -1 } }
18
+ }
19
+
20
+ function Test-Escape {
21
+ # VK_ESCAPE high bit = physically held right now. Checked between batch steps and inside the
22
+ # pointer glide so a user pressing ESC stops the run promptly instead of only at the next command.
23
+ try { return (([int][Native]::GetAsyncKeyState(0x1B)) -band 0x8000) -ne 0 } catch { return $false }
24
+ }
25
+
26
+ function Invoke-PixelAction($re, $action, $value) {
27
+ # Drive the physical pointer at the element's own BoundingRectangle. Only used when the mode is
28
+ # foreground, or auto and the UIA path could not act on this element.
29
+ $rc = $re.rect
30
+ if ($null -eq $rc -or [int]$rc.w -le 0 -or [int]$rc.h -le 0) {
31
+ Err 'no_rect' ("pixel path needs a non-empty bounding rect for " + $re.controlType + " '" + (TruncStr $re.name 40) + "'")
32
+ }
33
+ $cx = [int]($rc.x + [Math]::Round($rc.w / 2)); $cy = [int]($rc.y + [Math]::Round($rc.h / 2))
34
+ $exp = @{ windowId = [string]$re.windowId }
35
+ switch ($action) {
36
+ { $_ -in @('invoke', 'select', 'toggle', 'expand', 'collapse', 'focus') } {
37
+ [void](Cmd-PointerClick @{ x = $cx; y = $cy; button = 'left'; expect = $exp }); return 'pixel-click'
38
+ }
39
+ 'set_value' {
40
+ [void](Cmd-PointerClick @{ x = $cx; y = $cy; button = 'left'; expect = $exp })
41
+ [void](Cmd-Key @{ keys = 'ctrl+a' })
42
+ # An empty value means "clear the field". Typing '' over the ctrl+a selection leaves it
43
+ # untouched, so delete the selection explicitly instead.
44
+ if ([string]$value -eq '') { [void](Cmd-Key @{ keys = 'del' }) }
45
+ else { [void](Cmd-TypeText @{ text = [string]$value }) }
46
+ return 'pixel-type'
47
+ }
48
+ 'text_append' {
49
+ [void](Cmd-PointerClick @{ x = $cx; y = $cy; button = 'left'; expect = $exp })
50
+ [void](Cmd-TypeText @{ text = [string]$value }); return 'pixel-type'
51
+ }
52
+ 'scroll_up' { [void](Cmd-PointerScroll @{ x = $cx; y = $cy; direction = 'up'; clicks = 3; expect = $exp }); return 'pixel-scroll' }
53
+ 'scroll_down' { [void](Cmd-PointerScroll @{ x = $cx; y = $cy; direction = 'down'; clicks = 3; expect = $exp }); return 'pixel-scroll' }
54
+ default { Err 'unknown_action' ("no pixel path for action '" + $action + "'") }
55
+ }
56
+ }
57
+
58
+ function Do-Action($re, $action, $value, $step) {
59
+ $mode = [string]$script:W.pointerMode
60
+ $s = Dict $step
61
+ if ($null -ne $s -and (BoolArg $s 'foreground' $false)) { $mode = 'foreground' }
62
+ if ($mode -eq 'foreground') { return Invoke-PixelAction $re $action $value }
63
+ if ($mode -eq 'auto') {
64
+ try { return Invoke-UiaAction $re $action $value $step }
65
+ catch {
66
+ $msg = $_.Exception.Message
67
+ if ($msg -like 'ERR|pattern_unsupported|*' -or $msg -like 'ERR|read_only|*' -or $msg -like 'ERR|action_failed|*') {
68
+ return Invoke-PixelAction $re $action $value
69
+ }
70
+ throw
71
+ }
72
+ }
73
+ return Invoke-UiaAction $re $action $value $step
74
+ }
75
+
76
+ function Invoke-UiaAction($re, $action, $value, $step) {
77
+ $el = $re.ae
78
+ $patterns = $re.patterns
79
+ $s = Dict $step
80
+ $forceFg = $false
81
+ if ($null -ne $s) { $forceFg = BoolArg $s 'foreground' $false }
82
+ $via = 'uia'
83
+ switch ($action) {
84
+ 'invoke' {
85
+ # No LegacyIAccessible fallback: the managed client has no LegacyIAccessiblePattern type, so
86
+ # GetPattern($el, 'LegacyIAccessible') always returned $null and this branch was unreachable.
87
+ # Patterns come from the ref's cache (Get-RefPattern): a set_value/focus reads the same
88
+ # pattern in before→action→after, which used to be three GetCurrentPattern round-trips.
89
+ $p = Get-RefPattern $re 'Invoke'
90
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " '" + (TruncStr $re.name 40) + "' does not support Invoke") }
91
+ $p.Invoke(); return $via
92
+ }
93
+ 'set_value' {
94
+ $p = Get-RefPattern $re 'Value'
95
+ if ($null -eq $p) {
96
+ Err 'pattern_unsupported' ("element " + $re.controlType + " '" + (TruncStr $re.name 40) + "' does not support Value")
97
+ }
98
+ try { if ($p.Current.IsReadOnly) { Err 'read_only' ("element " + $re.controlType + " '" + (TruncStr $re.name 40) + "' is read only") } } catch { }
99
+ $p.SetValue([string]$value); return $via
100
+ }
101
+ 'text_append' {
102
+ $p = Get-RefPattern $re 'Value'
103
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " '" + (TruncStr $re.name 40) + "' does not support Value, cannot append") }
104
+ try { if ($p.Current.IsReadOnly) { Err 'read_only' 'element is read only' } } catch { }
105
+ $cur = ''
106
+ try { $cur = [string]$p.Current.Value } catch { $cur = '' }
107
+ $p.SetValue($cur + [string]$value); return $via
108
+ }
109
+ 'toggle' {
110
+ $p = Get-RefPattern $re 'Toggle'
111
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support Toggle") }
112
+ $p.Toggle(); return $via
113
+ }
114
+ 'select' {
115
+ $p = Get-RefPattern $re 'SelectionItem'
116
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support SelectionItem") }
117
+ $p.Select(); return $via
118
+ }
119
+ 'expand' {
120
+ $p = Get-RefPattern $re 'ExpandCollapse'
121
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support ExpandCollapse") }
122
+ $p.Expand(); return $via
123
+ }
124
+ 'collapse' {
125
+ $p = Get-RefPattern $re 'ExpandCollapse'
126
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support ExpandCollapse") }
127
+ $p.Collapse(); return $via
128
+ }
129
+ 'scroll_up' {
130
+ $p = Get-RefPattern $re 'Scroll'
131
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support Scroll") }
132
+ try { if (-not [bool]$p.Current.VerticallyScrollable) { Err 'action_failed' ("element " + $re.controlType + " is not vertically scrollable") } } catch { }
133
+ try { $p.ScrollVertical([System.Windows.Automation.ScrollAmount]::SmallDecrement) } catch { Err 'action_failed' ('ScrollVertical threw: ' + $_.Exception.Message) }
134
+ return $via
135
+ }
136
+ 'scroll_down' {
137
+ $p = Get-RefPattern $re 'Scroll'
138
+ if ($null -eq $p) { Err 'pattern_unsupported' ("element " + $re.controlType + " does not support Scroll") }
139
+ try { if (-not [bool]$p.Current.VerticallyScrollable) { Err 'action_failed' ("element " + $re.controlType + " is not vertically scrollable") } } catch { }
140
+ try { $p.ScrollVertical([System.Windows.Automation.ScrollAmount]::SmallIncrement) } catch { Err 'action_failed' ('ScrollVertical threw: ' + $_.Exception.Message) }
141
+ return $via
142
+ }
143
+ 'focus' {
144
+ if (-not $forceFg -and -not (Is-ForegroundHwnd $re.hwnd)) {
145
+ $script:W.stats.refused += 1
146
+ Err 'needs_foreground' ('action focus on window ' + $re.windowId + ' would raise it; pass {"foreground":true} on the step to allow it')
147
+ }
148
+ if ($forceFg) { try { [void][Native]::SetForegroundWindow([IntPtr]$re.hwnd) } catch { } }
149
+ try { $el.SetFocus() } catch { Err 'action_failed' ('SetFocus threw: ' + $_.Exception.Message) }
150
+ return $via
151
+ }
152
+ default {
153
+ Err 'unknown_action' ("unsupported action '" + $action + "' (invoke|set_value|toggle|select|expand|collapse|scroll_up|scroll_down|focus|text_append)")
154
+ }
155
+ }
156
+ }
157
+
158
+ function Raise-Foreground($entry) {
159
+ $h = [IntPtr]$entry.hwnd
160
+ # A minimized window has no usable screen rect, so pixel coordinates taken from the last
161
+ # snapshot point at nothing. Restore it before raising so the raise is actually clickable.
162
+ try { if ([Native]::IsIconic($h)) { [void][Native]::ShowWindow($h, 9); Start-Sleep -Milliseconds 80 } } catch { }
163
+ try { [void][Native]::SetForegroundWindow($h) } catch { }
164
+ }
165
+
166
+ # ---------------------------------------------------------------- conditions
167
+ function Target-Element($entry, $cond, $refMap) {
168
+ $c = Dict $cond
169
+ $ref = $c.Item('ref')
170
+ if ($null -ne $ref -and [string]$ref -ne '') {
171
+ $re = Resolve-Ref $ref $refMap
172
+ return $re
173
+ }
174
+ $by = Dict $c.Item('by')
175
+ if ($null -eq $by) { $by = @{} }
176
+ if ($c.ContainsKey('windowId')) { $entry = Window-Entry ([string]$c.Item('windowId')) }
177
+ $el = Find-ByDescriptor $entry $by
178
+ if ($null -eq $el) { return $null }
179
+ return @{ synthetic = $true; ae = $el; windowId = $entry.id; hwnd = $entry.hwnd; patterns = (PatternsOf $el); name = [string]$el.Current.Name; controlType = (ControlTypeName $el.Current.ControlType); className = [string]$el.Current.ClassName; automationId = [string]$el.Current.AutomationId; ref = $null }
180
+ }
181
+
182
+ # Vertical scroll percent for the scroll_percent_changed verify. $null means "no usable Scroll
183
+ # reading" (pattern unsupported, element unreadable, or not scrollable - UIA reports -1 for the
184
+ # percent then), so the caller can tell that apart from a genuine 0%. Routes through the ref's
185
+ # pattern cache (Get-RefPattern) like every other before→action→after read.
186
+ function Read-ScrollPercent($re) {
187
+ if ($null -eq $re) { return $null }
188
+ $sp = Get-RefPattern $re 'Scroll'
189
+ if ($null -eq $sp) { return $null }
190
+ try {
191
+ $pct = [double]$sp.Current.VerticalScrollPercent
192
+ if ($pct -lt 0) { return $null }
193
+ return $pct
194
+ } catch { return $null }
195
+ }
196
+
197
+ function Eval-Once($type, $entry, $cond, $before, $refMap, $scrollBefore) {
198
+ $c = Dict $cond
199
+ $expect = $c.Item('expect')
200
+ switch ($type) {
201
+ 'element_appears' {
202
+ $t = Target-Element $entry $cond $refMap
203
+ $obs = 'absent'
204
+ if ($null -ne $t) { $obs = 'present' }
205
+ return @{ matched = ($null -ne $t); observed = $obs }
206
+ }
207
+ 'element_gone' {
208
+ $t = Target-Element $entry $cond $refMap
209
+ $obs = 'absent'
210
+ if ($null -ne $t) { $obs = 'present' }
211
+ return @{ matched = ($null -eq $t); observed = $obs }
212
+ }
213
+ }
214
+ $t = Target-Element $entry $cond $refMap
215
+ if ($null -eq $t) { return @{ matched = $false; observed = 'target missing'; error = 'element_gone' } }
216
+ $cp = $null
217
+ try { $cp = $t.ae.Current } catch { }
218
+ if ($null -eq $cp) { return @{ matched = $false; observed = 'unreadable'; error = 'element_gone' } }
219
+ $pats = $t.patterns
220
+ if ($null -eq $pats -or $pats.Count -eq 0) { $pats = PatternsOf $t.ae }
221
+ switch ($type) {
222
+ 'value_equals' {
223
+ $v = Read-Value $t.ae $pats
224
+ return @{ matched = ($v -eq [string]$expect); observed = (TruncStr $v 200) }
225
+ }
226
+ 'value_changed' {
227
+ $v = Read-Value $t.ae $pats
228
+ return @{ matched = ($v -ne [string]$before); observed = (TruncStr $v 200); before = (TruncStr ([string]$before) 200) }
229
+ }
230
+ 'no_change' {
231
+ $v = Read-Value $t.ae $pats
232
+ $n = [string]$cp.Name
233
+ return @{ matched = ($v -eq [string]$before); observed = (TruncStr $v 200); name = (TruncStr $n 80) }
234
+ }
235
+ 'name_contains' {
236
+ $n = [string]$cp.Name
237
+ return @{ matched = ($n.IndexOf([string]$expect, [StringComparison]::OrdinalIgnoreCase) -ge 0); observed = (TruncStr $n 120) }
238
+ }
239
+ 'enabled_is' {
240
+ $want = BoolArg (@{ v = $expect }) 'v' $true
241
+ $e = [bool]$cp.IsEnabled
242
+ return @{ matched = ($e -eq $want); observed = $e }
243
+ }
244
+ 'scroll_percent_changed' {
245
+ # 防循环的确定性判据:"滚了但列表没动"(动作缓存不记结果的无限滚动)在这里有读数可依:
246
+ # ScrollPattern.VerticalScrollPercent 与动作前读数($scrollBefore,动作步开始时读一次)
247
+ # 的差值 ≥ expect(默认 1)才命中。轮询复用上面的同一 Target-Element 管道。
248
+ $sp = Get-RefPattern $t 'Scroll'
249
+ if ($null -eq $sp) { return @{ matched = $false; observed = 'no Scroll pattern'; error = 'pattern_unsupported' } }
250
+ $pct = $null
251
+ try { $pct = [double]$sp.Current.VerticalScrollPercent } catch { $pct = $null }
252
+ if ($null -eq $pct -or $pct -lt 0) { return @{ matched = $false; observed = 'not scrollable'; error = 'pattern_unsupported' } }
253
+ $base = $scrollBefore
254
+ if ($null -eq $base) { $base = $pct } # 无动作前基线(独立 wait):首轮读数即基线
255
+ $want = 1.0
256
+ if ($null -ne $expect -and [string]$expect -ne '') { try { $want = [Math]::Abs([double]$expect) } catch { $want = 1.0 } }
257
+ $delta = [Math]::Abs($pct - [double]$base)
258
+ return @{ matched = ($delta -ge $want); observed = ('percent=' + $pct); before = ('percent=' + $base) }
259
+ }
260
+ default {
261
+ Err 'unknown_condition' ("unsupported condition type '" + $type + "'")
262
+ }
263
+ }
264
+ }
265
+
266
+ function Wait-Condition($entry, $cond, $timeoutMs, $before, $refMap, $scrollBefore) {
267
+ $c = Dict $cond
268
+ $type = [string]$c.Item('type')
269
+ if ($type -eq '') { Err 'missing_arg' 'condition needs a type' }
270
+ if ($null -eq $timeoutMs -or $timeoutMs -le 0) { $timeoutMs = 750 }
271
+ $budget = $timeoutMs
272
+ $left = BudgetLeftMs
273
+ if ($left -lt $budget) { $budget = [int]$left }
274
+ if ($budget -lt 0) { $budget = 0 }
275
+ $st = TickNow
276
+ $deadline = $st + ([Int64]$budget * 10000)
277
+ $last = $null
278
+ while ($true) {
279
+ $last = Eval-Once $type $entry $cond $before $refMap $scrollBefore
280
+ if ($last.matched) { break }
281
+ if ((TickNow) -ge $deadline) { break }
282
+ Start-Sleep -Milliseconds 80
283
+ }
284
+ $r = [ordered]@{ type = $type; matched = [bool]$last.matched; ms = (MsFrom $st) }
285
+ if ($last.ContainsKey('observed')) { $r['observed'] = $last.observed }
286
+ if ($last.ContainsKey('before')) { $r['beforeObserved'] = $last.before }
287
+ if ($last.ContainsKey('name')) { $r['observedName'] = $last.name }
288
+ if ($last.ContainsKey('error')) { $r['error'] = $last.error }
289
+ return $r
290
+ }
291
+