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.
- package/LICENSE +21 -0
- package/README.md +663 -2
- package/client/client.js +269 -0
- package/cordis.patch.yml +10 -0
- package/icon.svg +11 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -4
- package/scripts/bench-live.mjs +157 -0
- package/scripts/check-lease.mjs +308 -0
- package/scripts/install.mjs +154 -0
- package/scripts/lib/dsh-tools-stub.mjs +14 -0
- package/scripts/lib/load-tools-source.mjs +25 -0
- package/scripts/lib/sources.mjs +62 -0
- package/scripts/load-tools.mjs +74 -0
- package/scripts/measure-parse.mjs +77 -0
- package/scripts/regression-halt-latch.mjs +100 -0
- package/scripts/regression-quality.mjs +207 -0
- package/scripts/regression-tools.mjs +192 -0
- package/scripts/regression-worker.ps1 +1071 -0
- package/scripts/smoke.mjs +158 -0
- package/scripts/verify-capture-scale.mjs +37 -0
- package/scripts/verify-live-clipboard.mjs +108 -0
- package/scripts/verify-live-style.mjs +46 -0
- package/scripts/verify-live.mjs +104 -0
- package/scripts/verify-locator.mjs +52 -0
- package/scripts/verify.mjs +2110 -0
- package/src/activity-window.js +276 -0
- package/src/dashboard.js +103 -0
- package/src/guard.js +201 -0
- package/src/index.js +525 -0
- package/src/native-uia-remote.js +80 -0
- package/src/notes.js +83 -0
- package/src/state.js +267 -0
- package/src/themes.js +74 -0
- package/src/tools/defs/act.js +533 -0
- package/src/tools/defs/lifecycle.js +205 -0
- package/src/tools/defs/observe.js +309 -0
- package/src/tools/defs/pointer.js +298 -0
- package/src/tools/format.js +301 -0
- package/src/tools/index.js +128 -0
- package/src/tools/ocr.js +91 -0
- package/src/tools/recipes.js +44 -0
- package/src/tools/runtime.js +42 -0
- package/src/worker-client.js +268 -0
- package/worker/assets/dsh-whale.path +1 -0
- package/worker/bin/build-ocr.ps1 +41 -0
- package/worker/bin/ocr.cs +69 -0
- package/worker/bin/ocr.exe +0 -0
- package/worker/indicator-server.ps1 +2963 -0
- package/worker/lib/01-core.ps1 +64 -0
- package/worker/lib/02-uia.ps1 +221 -0
- package/worker/lib/03-window.ps1 +194 -0
- package/worker/lib/04-match.ps1 +435 -0
- package/worker/lib/05-value.ps1 +149 -0
- package/worker/lib/06-snapshot.ps1 +345 -0
- package/worker/lib/07-action.ps1 +291 -0
- package/worker/lib/08-command.ps1 +1485 -0
- package/worker/lib/09-pointer.ps1 +840 -0
- package/worker/lib/10-dispatch.ps1 +134 -0
- package/worker/ps-stdio.ps1 +173 -0
- package/worker/uia-worker.ps1 +599 -0
|
@@ -0,0 +1,1485 @@
|
|
|
1
|
+
# 08-command.ps1 -- request handlers (snapshot..shutdown)
|
|
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
|
+
# ---------------------------------------------------------------- commands
|
|
8
|
+
function Cmd-Ping($A) {
|
|
9
|
+
if ($script:dpiMode -eq 0 -and $script:nativeLoaded) {
|
|
10
|
+
try { $script:dpiMode = [Native]::MakeAware() } catch { }
|
|
11
|
+
}
|
|
12
|
+
# The station size comes from the ONE authoritative measurement (Get-VirtScreen: the virtual
|
|
13
|
+
# screen with its measured fallback chain). Ping used to re-derive it from its own SM_CXSCREEN
|
|
14
|
+
# read plus the WinForms primary-screen bounds, and also reported a dead "logical" pair no
|
|
15
|
+
# consumer ever read — a second opinion that disagreed with the pointer channel's answer on
|
|
16
|
+
# multi-monitor boxes, exactly the silent drift the "measure, never hardcode" rule exists for.
|
|
17
|
+
# MakeAware has already run at startup (and above), so the metrics are physical.
|
|
18
|
+
$v = Get-VirtScreen
|
|
19
|
+
$w = [int]$v.w; $h = [int]$v.h
|
|
20
|
+
return [ordered]@{
|
|
21
|
+
psVersion = $PSVersionTable.PSVersion.ToString()
|
|
22
|
+
station = @{ width = $w; height = $h }
|
|
23
|
+
workerPid = [int]$PID
|
|
24
|
+
maxRefs = [int]$script:W.maxRefs
|
|
25
|
+
windowCount = $script:W.windows.Count
|
|
26
|
+
totalRefs = $script:W.totalRefs
|
|
27
|
+
startupMs = [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $script:W.startTick) / 10000.0, 1)
|
|
28
|
+
nativeLoaded = [bool]$script:nativeLoaded
|
|
29
|
+
dpiAware = [int]$script:dpiMode
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function Match-RootWindow($w, $wantPid, $wantTitle, $wantClass, $titleExact, $wantRegex) {
|
|
34
|
+
$cp = $null
|
|
35
|
+
try { $cp = $w.Current } catch { return $false }
|
|
36
|
+
$hwnd = [int]$cp.NativeWindowHandle
|
|
37
|
+
if ($hwnd -eq 0) { return $false }
|
|
38
|
+
$rc = RectOf $cp
|
|
39
|
+
$iconic = $false
|
|
40
|
+
try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
|
|
41
|
+
if (($rc.w -le 0 -or $rc.h -le 0) -and -not $iconic) { return $false }
|
|
42
|
+
if ($wantPid -gt 0 -and [int]$cp.ProcessId -ne $wantPid) { return $false }
|
|
43
|
+
if ($wantClass -ne '' -and ([string]$cp.ClassName).IndexOf($wantClass, [StringComparison]::OrdinalIgnoreCase) -lt 0) { return $false }
|
|
44
|
+
$t = [string]$cp.Name
|
|
45
|
+
if ($wantTitle -ne '') {
|
|
46
|
+
if ($titleExact) { if (-not $t.Equals($wantTitle, [StringComparison]::OrdinalIgnoreCase)) { return $false } }
|
|
47
|
+
elseif ($t.IndexOf($wantTitle, [StringComparison]::OrdinalIgnoreCase) -lt 0) { return $false }
|
|
48
|
+
}
|
|
49
|
+
if ($wantRegex -ne '') {
|
|
50
|
+
try { if ($t -notmatch $wantRegex) { return $false } } catch { return $false }
|
|
51
|
+
}
|
|
52
|
+
return $true
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function Cmd-ResolveWindow($A) {
|
|
56
|
+
$windowId = StrArg $A 'windowId' ''
|
|
57
|
+
if ($windowId -ne '') {
|
|
58
|
+
$e = Window-Entry $windowId
|
|
59
|
+
$ae = Window-Ae $e
|
|
60
|
+
if ($null -eq $ae) { Err 'window_not_found' ("windowId " + $windowId + " is gone") }
|
|
61
|
+
$info = WindowInfo $e ($ae.Current)
|
|
62
|
+
$info['appearedMs'] = 0
|
|
63
|
+
return $info
|
|
64
|
+
}
|
|
65
|
+
$wantPid = IntArg $A 'pid' 0
|
|
66
|
+
$wantTitle = StrArg $A 'title' ''
|
|
67
|
+
$wantClass = StrArg $A 'class' ''
|
|
68
|
+
$wantRegex = StrArg $A 'titleRegex' ''
|
|
69
|
+
$titleExact = BoolArg $A 'titleExact' $false
|
|
70
|
+
$timeoutMs = IntArg $A 'timeoutMs' 4000
|
|
71
|
+
if ($wantPid -eq 0 -and $wantTitle -eq '' -and $wantClass -eq '' -and $wantRegex -eq '') { Err 'missing_arg' 'resolve_window needs windowId, pid, title, class or titleRegex' }
|
|
72
|
+
$st = TickNow
|
|
73
|
+
$left = BudgetLeftMs
|
|
74
|
+
if ($timeoutMs -gt $left) { $timeoutMs = [int]$left }
|
|
75
|
+
if ($timeoutMs -lt 0) { $timeoutMs = 0 }
|
|
76
|
+
$deadline = $st + ([Int64]$timeoutMs * 10000)
|
|
77
|
+
while ($true) {
|
|
78
|
+
foreach ($w in (RootWindows)) {
|
|
79
|
+
if (Match-RootWindow $w $wantPid $wantTitle $wantClass $titleExact $wantRegex) {
|
|
80
|
+
$hwnd = 0
|
|
81
|
+
try { $hwnd = [int]$w.Current.NativeWindowHandle } catch { continue }
|
|
82
|
+
$e = Ensure-Window $hwnd $w
|
|
83
|
+
if ($null -eq $e) { continue }
|
|
84
|
+
$info = WindowInfo $e ($w.Current)
|
|
85
|
+
$info['appearedMs'] = [Math]::Round((MsFrom $st), 1)
|
|
86
|
+
return $info
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if ((TickNow) -ge $deadline) { break }
|
|
90
|
+
Start-Sleep -Milliseconds 150
|
|
91
|
+
}
|
|
92
|
+
$script:W.stats.refused += 1
|
|
93
|
+
Err 'window_not_found' ("no window matching pid=" + $wantPid + " title='" + $wantTitle + "' class='" + $wantClass + "' after " + $timeoutMs + 'ms of polling')
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function Cmd-ListWindows($A) {
|
|
97
|
+
$onlyVisible = BoolArg $A 'onlyVisible' $true
|
|
98
|
+
$out = New-Object System.Collections.Generic.List[object]
|
|
99
|
+
foreach ($w in (RootWindows)) {
|
|
100
|
+
$cp = $null
|
|
101
|
+
try { $cp = $w.Current } catch { continue }
|
|
102
|
+
$hwnd = [int]$cp.NativeWindowHandle
|
|
103
|
+
if ($hwnd -eq 0) { continue }
|
|
104
|
+
$rc = RectOf $cp
|
|
105
|
+
$iconic = $false
|
|
106
|
+
try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
|
|
107
|
+
$vis = $false
|
|
108
|
+
try { $vis = [Native]::IsWindowVisible([IntPtr]$hwnd) } catch { }
|
|
109
|
+
if ($onlyVisible -and (($rc.w -le 0 -or $rc.h -le 0) -or (-not $vis -and -not $iconic))) { continue }
|
|
110
|
+
$e = Ensure-Window $hwnd $w
|
|
111
|
+
if ($null -eq $e) { continue }
|
|
112
|
+
$info = WindowInfo $e $cp
|
|
113
|
+
$info['isMinimized'] = $iconic
|
|
114
|
+
$out.Add($info) | Out-Null
|
|
115
|
+
}
|
|
116
|
+
return [ordered]@{ windows = $out; count = $out.Count; totalRefs = $script:W.totalRefs }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function Cmd-Snapshot($A) {
|
|
120
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
121
|
+
return Build-Snapshot $entry $A
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function Cmd-Describe($A) {
|
|
125
|
+
$ref = StrArg $A 'ref' ''
|
|
126
|
+
$re = Resolve-Ref $ref $A
|
|
127
|
+
# The descriptor rides the ref record: New-Ref already cached controlType/name/className/
|
|
128
|
+
# automationId/patterns/enabled/isOffscreen/rect at snapshot time, and the only caller
|
|
129
|
+
# (computer_act's Node-side policy precheck) needs exactly those fields — the same
|
|
130
|
+
# cached-descriptor semantics Cmd-PrepareBatch has always judged policy on. The live COM re-read
|
|
131
|
+
# is confined to the cache-miss branch: a rebound ref's cached fields belong to the OLD element
|
|
132
|
+
# (Resolve-Ref swaps $re.ae without refreshing them), so only there is a re-read honest.
|
|
133
|
+
if ($re.rebound) {
|
|
134
|
+
$d = DescriptorOf $re $true
|
|
135
|
+
$d['rebound'] = $true
|
|
136
|
+
return $d
|
|
137
|
+
}
|
|
138
|
+
return DescriptorOf $re $false
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function Cmd-DescriptorMatch($A) {
|
|
142
|
+
# Read-only: resolves a by-descriptor exactly the way act / commit_batch / wait would, and reports
|
|
143
|
+
# WHY (which rung of the ladder, how confident, whether it degraded) or what it nearly matched.
|
|
144
|
+
# It sends no input, moves no pointer and mints no ref, so it is safe to call before a batch.
|
|
145
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
146
|
+
$by = Dict (ArgOf $A 'by')
|
|
147
|
+
if ($null -eq $by) { Err 'missing_arg' 'descriptor_match needs a by descriptor' }
|
|
148
|
+
$el = Find-ByDescriptor $entry $by
|
|
149
|
+
$lm = $script:W.lastMatch
|
|
150
|
+
if ($null -eq $lm) {
|
|
151
|
+
$lm = @{
|
|
152
|
+
matchedBy = ''; ladder = ''; score = 0.0; degraded = $false; candidateCount = 0
|
|
153
|
+
scanned = 'all'; nameExact = $true; reason = 'no_match'; tried = @(); candidates = @()
|
|
154
|
+
ambiguityAt = ''; diagnosticTruncated = $false
|
|
155
|
+
candidateCountKnown = $true; fastCond = $null
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
# The strict fast path resolved through FindFirst, which stops at the first hit and leaves the
|
|
159
|
+
# real same-name count unknown (candidateCountKnown=false). This command is the read-only
|
|
160
|
+
# diagnostic, so it re-runs the EXACT condition the resolver used as a full enumeration: a
|
|
161
|
+
# same-name ambiguity surfaces here with its true candidate count instead of hiding behind a
|
|
162
|
+
# fabricated one. Reads only — no input, no refs.
|
|
163
|
+
if ($null -ne $el -and -not [bool]$lm.candidateCountKnown -and $null -ne $lm.fastCond) {
|
|
164
|
+
$aeD = Window-Ae $entry
|
|
165
|
+
if ($null -ne $aeD) {
|
|
166
|
+
$recount = @()
|
|
167
|
+
try { $recount = @($aeD.FindAll([System.Windows.Automation.TreeScope]::Descendants, $lm.fastCond)) } catch { $recount = @() }
|
|
168
|
+
if ($recount.Count -ge 1) {
|
|
169
|
+
$lm.candidateCount = $recount.Count
|
|
170
|
+
$lm.candidateCountKnown = $true
|
|
171
|
+
if ($recount.Count -gt 1 -and [string]$lm.ambiguityAt -eq '') { $lm.ambiguityAt = [string]$lm.ladder }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
$r = [ordered]@{
|
|
176
|
+
found = [bool]($null -ne $el)
|
|
177
|
+
windowId = $entry.id
|
|
178
|
+
matchedBy = [string]$lm.matchedBy
|
|
179
|
+
ladder = [string]$lm.ladder
|
|
180
|
+
score = [double]$lm.score
|
|
181
|
+
degraded = [bool]$lm.degraded
|
|
182
|
+
candidateCount = [int]$lm.candidateCount
|
|
183
|
+
# true = counted from a full enumeration (or the recount above); false = the resolver only
|
|
184
|
+
# ran FindFirst, so the count is "at least one" and a same-name ambiguity may still hide.
|
|
185
|
+
candidateCountKnown = [bool]$lm.candidateCountKnown
|
|
186
|
+
scanned = [string]$lm.scanned
|
|
187
|
+
nameExact = [bool]$lm.nameExact
|
|
188
|
+
# NOT @($lm.tried)/@($lm.candidates): Windows PowerShell 5.1 throws "Argument types do not
|
|
189
|
+
# match" for @() around a List[object] made by New-Object (verified on 5.1.26100). JsonOf walks
|
|
190
|
+
# IEnumerable, so the raw collections serialise as arrays without the cast.
|
|
191
|
+
tried = $lm.tried
|
|
192
|
+
candidates = $lm.candidates
|
|
193
|
+
}
|
|
194
|
+
if ([string]$lm.reason -ne '') { $r['reason'] = [string]$lm.reason }
|
|
195
|
+
if ([string]$lm.ambiguityAt -ne '') { $r['ambiguityAt'] = [string]$lm.ambiguityAt }
|
|
196
|
+
if ([bool]$lm.diagnosticTruncated) { $r['diagnosticTruncated'] = $true }
|
|
197
|
+
if ($null -ne $el) {
|
|
198
|
+
$cp = $null
|
|
199
|
+
try { $cp = $el.Current } catch { $cp = $null }
|
|
200
|
+
if ($null -ne $cp) {
|
|
201
|
+
$r['element'] = [ordered]@{
|
|
202
|
+
name = (TruncStr ([string]$cp.Name) 160)
|
|
203
|
+
automationId = [string]$cp.AutomationId
|
|
204
|
+
controlType = (ControlTypeName $cp.ControlType)
|
|
205
|
+
className = [string]$cp.ClassName
|
|
206
|
+
enabled = [bool]$cp.IsEnabled
|
|
207
|
+
isOffscreen = [bool]$cp.IsOffscreen
|
|
208
|
+
rect = (RectOf $cp)
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if ([string]$r['matchedBy'] -eq '' -and $r.Contains('matchedBy')) {
|
|
213
|
+
$r.Remove('matchedBy')
|
|
214
|
+
if ($r.Contains('ladder')) { $r.Remove('ladder') }
|
|
215
|
+
}
|
|
216
|
+
return $r
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function Apply-ModeArg($A) {
|
|
220
|
+
# The Node side sends the user's chosen delivery mode on every act/commit_batch, so a fresh worker
|
|
221
|
+
# (respawned lazily) picks it up on the next action instead of resetting to the default.
|
|
222
|
+
$m = (StrArg $A 'mode' '').ToLowerInvariant()
|
|
223
|
+
if (@('background', 'auto', 'foreground') -contains $m) { $script:W.pointerMode = $m }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function Cmd-SetPointerMode($A) {
|
|
227
|
+
$m = (StrArg $A 'mode' '').ToLowerInvariant()
|
|
228
|
+
if (@('background', 'auto', 'foreground') -notcontains $m) { Err 'bad_arg' ("pointer mode '" + $m + "' is not background|auto|foreground") }
|
|
229
|
+
$script:W.pointerMode = $m
|
|
230
|
+
return [ordered]@{ mode = $m }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function Cmd-EscapePressed($A) {
|
|
234
|
+
# Fallback probe for the Node host's global-ESC watcher (the indicator is the primary channel).
|
|
235
|
+
# Same latch as the indicator: the low bit reports "pressed since the previous call", so a tap
|
|
236
|
+
# shorter than the poll interval still counts once. Test-Escape stays the plain held-read for
|
|
237
|
+
# aborting a batch mid-step, where "is it down right now" is the correct question.
|
|
238
|
+
try {
|
|
239
|
+
$state = [int][Native]::GetAsyncKeyState(0x1B)
|
|
240
|
+
return [ordered]@{ pressed = [bool](($state -band 0x8000) -ne 0 -or ($state -band 0x0001) -ne 0) }
|
|
241
|
+
} catch {
|
|
242
|
+
return [ordered]@{ pressed = $false }
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function Ensure-InView($re) {
|
|
247
|
+
# A ref can be valid and still be scrolled out of the viewport (the tree carries offscreen nodes,
|
|
248
|
+
# that is the point of UIA). Before acting, ask the provider to scroll it in: ScrollItem.ScrollIntoView
|
|
249
|
+
# is the non-destructive, focus-free way, and it is exactly what a human does before clicking.
|
|
250
|
+
# Returns $true when it actually scrolled, so the caller can report it instead of pretending the
|
|
251
|
+
# click landed where the model thought.
|
|
252
|
+
try {
|
|
253
|
+
$cp = $re.ae.Current
|
|
254
|
+
if (-not [bool]$cp.IsOffscreen) { return $false }
|
|
255
|
+
$p = $null
|
|
256
|
+
try { $p = $re.ae.GetCurrentPattern([System.Windows.Automation.ScrollItemPattern]::Pattern) } catch { $p = $null }
|
|
257
|
+
if ($null -eq $p) { return $false }
|
|
258
|
+
$p.ScrollIntoView()
|
|
259
|
+
Start-Sleep -Milliseconds 120
|
|
260
|
+
return $true
|
|
261
|
+
} catch { return $false }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function Cmd-Act($A) {
|
|
265
|
+
Apply-ModeArg $A
|
|
266
|
+
$ref = StrArg $A 'ref' ''
|
|
267
|
+
$action = StrArg $A 'action' ''
|
|
268
|
+
if ($action -eq '') { Err 'missing_arg' 'act needs an action' }
|
|
269
|
+
$value = ArgOf $A 'value'
|
|
270
|
+
$re = Resolve-Ref $ref $A
|
|
271
|
+
# Offscreen refs are acted on, not refused: scroll the element into view first unless the caller
|
|
272
|
+
# turned it off. Reported as `scrolled` so the reply can say the viewport moved.
|
|
273
|
+
$scrolled = $false
|
|
274
|
+
if (-not (BoolArg $A 'noScrollIntoView' $false)) { $scrolled = Ensure-InView $re }
|
|
275
|
+
# Third arg = the ref record: before/action/after then share ONE cached pattern object each
|
|
276
|
+
# instead of re-running GetCurrentPattern for the same pattern three times.
|
|
277
|
+
$before = Read-Value $re.ae $re.patterns $re
|
|
278
|
+
# scroll_percent_changed 的动作前基线:只有滚动动作或 verify 明确要它才多读一次(否则每个
|
|
279
|
+
# act 都白付一次跨进程 pattern 读)。
|
|
280
|
+
$scrollBefore = $null
|
|
281
|
+
$vpre = Dict (ArgOf $A 'verify')
|
|
282
|
+
$vpreType = if ($null -ne $vpre) { [string]$vpre.Item('type') } else { '' }
|
|
283
|
+
if ($action -eq 'scroll_up' -or $action -eq 'scroll_down' -or $vpreType -eq 'scroll_percent_changed') {
|
|
284
|
+
$scrollBefore = Read-ScrollPercent $re
|
|
285
|
+
}
|
|
286
|
+
$cur0 = Cursor-Pos
|
|
287
|
+
$fg0 = Foreground-Hwnd
|
|
288
|
+
$st = TickNow
|
|
289
|
+
$via = Do-Action $re $action $value $A
|
|
290
|
+
$script:W.stats.actionsPerformed += 1
|
|
291
|
+
$ms = MsFrom $st
|
|
292
|
+
$re2 = Resolve-Ref $ref $A
|
|
293
|
+
$after = Read-Value $re2.ae $re2.patterns $re2
|
|
294
|
+
$cur1 = Cursor-Pos
|
|
295
|
+
$fg1 = Foreground-Hwnd
|
|
296
|
+
$r = [ordered]@{
|
|
297
|
+
applied = $true
|
|
298
|
+
before = (TruncStr ([string]$before) 200)
|
|
299
|
+
after = (TruncStr ([string]$after) 200)
|
|
300
|
+
ms = $ms
|
|
301
|
+
via = $via
|
|
302
|
+
ref = $ref
|
|
303
|
+
action = $action
|
|
304
|
+
scrolled = [bool]$scrolled
|
|
305
|
+
cursorMoved = -not ($cur0.x -eq $cur1.x -and $cur0.y -eq $cur1.y)
|
|
306
|
+
foregroundChanged = ($fg0 -ne $fg1)
|
|
307
|
+
revision = $re.revision
|
|
308
|
+
}
|
|
309
|
+
$v = Dict (ArgOf $A 'verify')
|
|
310
|
+
if ($null -ne $v) {
|
|
311
|
+
$entry = $script:W.windows.Item($re.windowId)
|
|
312
|
+
# A verify that does not name its own target is a claim about the element this very action
|
|
313
|
+
# just touched, so default it to that ref. Without this, value_equals resolves nothing and
|
|
314
|
+
# every post-action check reads "target missing" no matter how correct the action was.
|
|
315
|
+
if (-not $v.ContainsKey('ref') -and $null -eq $v.Item('by')) { $v['ref'] = $ref }
|
|
316
|
+
$vm = IntArg $v 'timeoutMs' 900
|
|
317
|
+
$vv = Wait-Condition $entry $v $vm $before $null $scrollBefore
|
|
318
|
+
$r['verify'] = $vv
|
|
319
|
+
$verdict = if ([bool]$vv.matched) { 'matched' } else { 'unmatched' }
|
|
320
|
+
$r['detail'] = ('verify=' + [string]$vv.type + ':' + $verdict)
|
|
321
|
+
}
|
|
322
|
+
return $r
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function Cmd-PrepareBatch($A) {
|
|
326
|
+
$steps = ListOf (ArgOf $A 'steps')
|
|
327
|
+
if ($steps.Count -eq 0) { Err 'missing_arg' 'prepare_batch needs steps' }
|
|
328
|
+
if ($steps.Count -gt 64) { Err 'too_many_steps' ('prepare_batch supports at most 64 steps, got ' + $steps.Count) }
|
|
329
|
+
$descs = New-Object System.Collections.Generic.List[object]
|
|
330
|
+
$allOk = $true
|
|
331
|
+
$revSeen = @{}
|
|
332
|
+
$batchWid = StrArg $A 'windowId' ''
|
|
333
|
+
$i = -1
|
|
334
|
+
foreach ($raw in $steps) {
|
|
335
|
+
$i += 1
|
|
336
|
+
$s = Dict $raw
|
|
337
|
+
$ref = [string]$s.Item('ref')
|
|
338
|
+
$by = Dict $s.Item('by')
|
|
339
|
+
$re = $null
|
|
340
|
+
try {
|
|
341
|
+
if ($ref -ne '') {
|
|
342
|
+
$re = Resolve-Ref $ref $null
|
|
343
|
+
$d = DescriptorOf $re $false
|
|
344
|
+
$d['index'] = $i
|
|
345
|
+
$e = $script:W.windows.Item($re.windowId)
|
|
346
|
+
$revSeen[$re.windowId] = $e.revision
|
|
347
|
+
} elseif ($null -ne $by) {
|
|
348
|
+
$wid = [string]$s.Item('windowId')
|
|
349
|
+
# A replayed recipe step carries only a `by` descriptor; the window it belongs to comes
|
|
350
|
+
# from the batch-level windowId, not from the step. Fall back to it before refusing.
|
|
351
|
+
if ($wid -eq '') { $wid = $batchWid }
|
|
352
|
+
if ($wid -eq '') { Err 'missing_arg' ("step " + $i + " has a by-descriptor but no windowId") }
|
|
353
|
+
$entry = Window-Entry $wid
|
|
354
|
+
$el = Find-ByDescriptor $entry $by
|
|
355
|
+
if ($null -eq $el) { Err 'descriptor_unresolved' ("step " + $i + " descriptor matched nothing in " + $wid) }
|
|
356
|
+
# A by-descriptor is a guess (a name can churn, an id can be ambiguous), so the dry run has
|
|
357
|
+
# to say HOW the guess was reached. These fields come from the ladder record the call above
|
|
358
|
+
# just left behind, and only the by branch gets them: a ref is an exact identity, not a
|
|
359
|
+
# locator decision, so attaching a score to it would describe a match that never happened.
|
|
360
|
+
$loc = Get-LocatorFields $script:W.lastMatch
|
|
361
|
+
$cp = $el.Current
|
|
362
|
+
$pats = PatternsOf $el
|
|
363
|
+
$d = [ordered]@{
|
|
364
|
+
index = $i
|
|
365
|
+
windowId = $wid
|
|
366
|
+
resolvedBy = 'descriptor'
|
|
367
|
+
name = (TruncStr ([string]$cp.Name) 160)
|
|
368
|
+
controlType = (ControlTypeName $cp.ControlType)
|
|
369
|
+
className = [string]$cp.ClassName
|
|
370
|
+
automationId = [string]$cp.AutomationId
|
|
371
|
+
availablePatterns = @($pats)
|
|
372
|
+
supportedAction = (SupportedActionOf $pats)
|
|
373
|
+
enabled = [bool]$cp.IsEnabled
|
|
374
|
+
isOffscreen = [bool]$cp.IsOffscreen
|
|
375
|
+
rect = (RectOf $cp)
|
|
376
|
+
}
|
|
377
|
+
if ($null -ne $loc) {
|
|
378
|
+
$d['matchedBy'] = $loc['matchedBy']
|
|
379
|
+
$d['ladder'] = $loc['ladder']
|
|
380
|
+
$d['score'] = $loc['score']
|
|
381
|
+
$d['degraded'] = $loc['degraded']
|
|
382
|
+
}
|
|
383
|
+
# Same rule as DescriptorOf: only when the 160-cut display name differs from the real one,
|
|
384
|
+
# so a recipe rebuilt from this descriptor can carry a name that still resolves.
|
|
385
|
+
if ([string]$cp.Name -ne [string]$d['name']) { $d['fullName'] = [string]$cp.Name }
|
|
386
|
+
$revSeen[$wid] = $entry.revision
|
|
387
|
+
} else {
|
|
388
|
+
Err 'missing_ref' ("step " + $i + " needs a ref or a by descriptor")
|
|
389
|
+
}
|
|
390
|
+
$actName = [string]$s.Item('action')
|
|
391
|
+
# Validate the verb at prepare time. Prepare is the dry run: its whole job is to answer
|
|
392
|
+
# "would this batch work?" before a single event reaches the desktop. It used to copy the
|
|
393
|
+
# action through untouched, so "fly" resolved happily and only commit_batch refused it —
|
|
394
|
+
# the model paid for two round-trips and a revision to learn a typo it could have heard
|
|
395
|
+
# about immediately.
|
|
396
|
+
if ($actName -eq '') { Err 'missing_arg' ("step " + $i + " needs an action") }
|
|
397
|
+
# PowerShell's switch is case-INSENSITIVE by default, but the values it compares come from
|
|
398
|
+
# model-authored JSON and a "Invoke" used to sail through prepare while the case-sensitive
|
|
399
|
+
# hashtable check later refused it. Normalise once here so prepare and commit agree.
|
|
400
|
+
$actName = $actName.ToLowerInvariant()
|
|
401
|
+
if (-not $script:W.actionNames.ContainsKey($actName)) {
|
|
402
|
+
Err 'unknown_action' ("step " + $i + " action '" + $actName + "' is not one of " + (($script:W.actionNames.Keys | Sort-Object) -join '|'))
|
|
403
|
+
}
|
|
404
|
+
$d['action'] = $actName
|
|
405
|
+
$descs.Add($d) | Out-Null
|
|
406
|
+
} catch {
|
|
407
|
+
$allOk = $false
|
|
408
|
+
$code, $msg = Split-Err $_
|
|
409
|
+
$descs.Add([ordered]@{ index = $i; ref = $ref; action = [string]$s.Item('action'); error = $msg; code = $code }) | Out-Null
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
# A batch is validated against ONE revision (commit compares every step against the single value
|
|
413
|
+
# returned here). Steps that span two snapshotted windows can never satisfy that: prepare passed
|
|
414
|
+
# on the first window's revision, commit then died on the second window's step — reported as
|
|
415
|
+
# "revision stale" when the real answer is "one batch per window". Refuse at the dry run, where
|
|
416
|
+
# nothing has been executed and the caller can restructure for free.
|
|
417
|
+
if ($revSeen.Count -gt 1) {
|
|
418
|
+
$script:W.stats.refused += 1
|
|
419
|
+
Err 'multi_window_batch' (("the steps span " + $revSeen.Count + " windows (" + ((@($revSeen.Keys) | Sort-Object) -join ',') + "); split them into one batch per window and run each batch with its own revision"))
|
|
420
|
+
}
|
|
421
|
+
$rev = 0
|
|
422
|
+
if ($revSeen.Count -ge 1) { $rev = [int](@($revSeen.Values)[0]) }
|
|
423
|
+
return [ordered]@{ descriptors = $descs; revision = $rev; allResolved = $allOk; revisionsByWindow = $revSeen; steps = $steps.Count }
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function Cmd-CommitBatch($A) {
|
|
427
|
+
Apply-ModeArg $A
|
|
428
|
+
$steps = ListOf (ArgOf $A 'steps')
|
|
429
|
+
if ($steps.Count -eq 0) { Err 'missing_arg' 'commit_batch needs steps' }
|
|
430
|
+
if ($steps.Count -gt 64) { Err 'too_many_steps' ('commit_batch supports at most 64 steps, got ' + $steps.Count) }
|
|
431
|
+
$givenRev = ArgOf $A 'revision'
|
|
432
|
+
if ($null -eq $givenRev) {
|
|
433
|
+
$script:W.stats.refused += 1
|
|
434
|
+
Err 'revision_mismatch' 'commit_batch requires the exact revision returned by prepare_batch; refusing to perform 0 actions'
|
|
435
|
+
}
|
|
436
|
+
$wantRev = [int]$givenRev
|
|
437
|
+
$batchWid = StrArg $A 'windowId' ''
|
|
438
|
+
# phase 1: resolve every step, perform nothing
|
|
439
|
+
$plan = New-Object System.Collections.Generic.List[object]
|
|
440
|
+
$i = -1
|
|
441
|
+
foreach ($raw in $steps) {
|
|
442
|
+
$i += 1
|
|
443
|
+
$s = Dict $raw
|
|
444
|
+
$ref = [string]$s.Item('ref')
|
|
445
|
+
# Normalise exactly like prepare_batch, so a verb that passed the dry run cannot fail here on
|
|
446
|
+
# casing alone. The two phases must agree on what they accepted.
|
|
447
|
+
$action = ([string]$s.Item('action')).ToLowerInvariant()
|
|
448
|
+
$entry = $null
|
|
449
|
+
$re = $null
|
|
450
|
+
$loc = $null
|
|
451
|
+
if ($ref -ne '') {
|
|
452
|
+
$re = Resolve-Ref $ref $null
|
|
453
|
+
$entry = $script:W.windows.Item($re.windowId)
|
|
454
|
+
if ($re.revision -ne $wantRev) {
|
|
455
|
+
$script:W.stats.refused += 1
|
|
456
|
+
Err 'revision_mismatch' ("ref " + $ref + " is at revision " + $re.revision + " of " + $re.windowId + " but the batch declared revision " + $wantRev + '; performing 0 actions')
|
|
457
|
+
}
|
|
458
|
+
} else {
|
|
459
|
+
$wid = [string]$s.Item('windowId')
|
|
460
|
+
# Same rule as prepare_batch: a replayed step has no per-step windowId, so inherit the
|
|
461
|
+
# batch-level one instead of tripping Window-Entry('') with 'windowId is required'.
|
|
462
|
+
if ($wid -eq '') { $wid = $batchWid }
|
|
463
|
+
$entry = Window-Entry $wid
|
|
464
|
+
if ($entry.revision -ne $wantRev) {
|
|
465
|
+
$script:W.stats.refused += 1
|
|
466
|
+
Err 'revision_mismatch' ("window " + $wid + " is at revision " + $entry.revision + " but the batch declared revision " + $wantRev + '; performing 0 actions')
|
|
467
|
+
}
|
|
468
|
+
$by = Dict $s.Item('by')
|
|
469
|
+
if ($null -eq $by) { Err 'missing_ref' ("step " + $i + " needs a ref or a by descriptor") }
|
|
470
|
+
$el = Find-ByDescriptor $entry $by
|
|
471
|
+
if ($null -eq $el) { Err 'descriptor_unresolved' ("step " + $i + " descriptor matched nothing in " + $wid) }
|
|
472
|
+
# Read from THIS resolution, not from prepare_batch: commit re-resolves on purpose (the tree
|
|
473
|
+
# may have moved on), so the honest report is what the ladder decided now. Costs no extra
|
|
474
|
+
# scan — the record is a by-product of the call above.
|
|
475
|
+
$loc = Get-LocatorFields $script:W.lastMatch
|
|
476
|
+
$cp = $el.Current
|
|
477
|
+
$node = @{ controlType = (ControlTypeName $cp.ControlType); name = [string]$cp.Name; className = [string]$cp.ClassName; automationId = [string]$cp.AutomationId; patterns = (PatternsOf $el); enabled = [bool]$cp.IsEnabled; isOffscreen = [bool]$cp.IsOffscreen; rect = (RectOf $cp); depth = 0 }
|
|
478
|
+
$re = New-Ref $entry $el $cp $node
|
|
479
|
+
}
|
|
480
|
+
$verifyOnly = $false
|
|
481
|
+
if ($action -eq '' -or $action -eq 'verify' -or $action -eq 'no_op' -or $action -eq 'check') {
|
|
482
|
+
$hasCheck = ($null -ne $s.Item('verify') -or $null -ne $s.Item('type'))
|
|
483
|
+
if (-not $hasCheck) { Err 'missing_arg' ("step " + $i + " needs an action (or a verify/type for a check-only step)") }
|
|
484
|
+
$verifyOnly = $true
|
|
485
|
+
if ($action -eq '') { $action = 'verify' }
|
|
486
|
+
}
|
|
487
|
+
$plan.Add(@{ index = $i; s = $s; re = $re; entry = $entry; action = $action; verifyOnly = $verifyOnly; loc = $loc }) | Out-Null
|
|
488
|
+
}
|
|
489
|
+
# phase 2: perform in order, stop at the first failure
|
|
490
|
+
$results = New-Object System.Collections.Generic.List[object]
|
|
491
|
+
$performed = 0
|
|
492
|
+
$stoppedAt = -1
|
|
493
|
+
$status = 'ok'
|
|
494
|
+
# ---- top-level window diff around phase 2 -----------------------------------------------
|
|
495
|
+
# A dialog that pops up mid-batch is invisible to the model until its NEXT observation, and its
|
|
496
|
+
# "确定/取消" text then hijacks the next find_text ranking. A read-only hwnd-set diff around
|
|
497
|
+
# phase 2 (RootWindows is one FindAll over ~9 desktop roots, ~20-30 ms) surfaces it with the
|
|
498
|
+
# result. The indicator overlay's own process is excluded when the caller passes its pid: the
|
|
499
|
+
# capsule lights asynchronously at activity.claim, so a cold first batch can genuinely see it
|
|
500
|
+
# appear — reporting our own overlay as a "new window" would be exactly the noise this diff
|
|
501
|
+
# exists to kill. The renderer filters the same pid again as a belt-and-braces.
|
|
502
|
+
$indicatorPid = IntArg $A 'indicatorPid' 0
|
|
503
|
+
$hwndsBefore = @{}
|
|
504
|
+
foreach ($w in (RootWindows)) {
|
|
505
|
+
$h = 0
|
|
506
|
+
try { $cpW = $w.Current; $h = [int]$cpW.NativeWindowHandle } catch { continue }
|
|
507
|
+
if ($h -ne 0) { $hwndsBefore[[string]$h] = $true }
|
|
508
|
+
}
|
|
509
|
+
for ($k = 0; $k -lt $plan.Count; $k++) {
|
|
510
|
+
$p = $plan[$k]
|
|
511
|
+
if (Test-Escape) { $stoppedAt = $p.index; $status = 'cancelled'; break }
|
|
512
|
+
$s = $p.s
|
|
513
|
+
$re = $p.re
|
|
514
|
+
$action = $p.action
|
|
515
|
+
$value = $s.Item('value')
|
|
516
|
+
$cur0 = Cursor-Pos
|
|
517
|
+
$fg0 = Foreground-Hwnd
|
|
518
|
+
$before = Read-Value $re.ae $re.patterns $re
|
|
519
|
+
# scroll_percent_changed 的动作前基线:只在"这一步可能用它"时才读——本步是滚动动作,或
|
|
520
|
+
# verify 声明了该类型(含 check-only 步,其条件就是步本身)。无关节点每步多读一次就是
|
|
521
|
+
# 1-3ms × 步数的纯跨进程开销。
|
|
522
|
+
$scrollBefore = $null
|
|
523
|
+
$vpre = Dict $s.Item('verify')
|
|
524
|
+
$vpreType = if ($null -ne $vpre) { [string]$vpre.Item('type') } else { [string]$s.Item('type') }
|
|
525
|
+
if ($action -eq 'scroll_up' -or $action -eq 'scroll_down' -or $vpreType -eq 'scroll_percent_changed') {
|
|
526
|
+
$scrollBefore = Read-ScrollPercent $re
|
|
527
|
+
}
|
|
528
|
+
$st = TickNow
|
|
529
|
+
$res = [ordered]@{ index = $p.index; ref = $re.ref; action = $action; status = 'failed'; ms = 0; before = (TruncStr ([string]$before) 200); after = ''; performed = $false }
|
|
530
|
+
# Same four fields the dry run reported, so the caller can see afterwards which steps were
|
|
531
|
+
# resolved by a downgraded rung. Ref steps carry none (see Get-LocatorFields).
|
|
532
|
+
if ($null -ne $p.loc) {
|
|
533
|
+
$res['matchedBy'] = $p.loc['matchedBy']
|
|
534
|
+
$res['ladder'] = $p.loc['ladder']
|
|
535
|
+
$res['score'] = $p.loc['score']
|
|
536
|
+
$res['degraded'] = $p.loc['degraded']
|
|
537
|
+
}
|
|
538
|
+
try {
|
|
539
|
+
# Step-boundary budget check. The batch must stop ITSELF once its request budget is gone:
|
|
540
|
+
# Node aborts the CALL after 30 s while the worker kept executing steps and delivering
|
|
541
|
+
# actions, so a model that saw "timeout" retried a batch that was still landing (duplicate
|
|
542
|
+
# input). Throwing INSIDE the try means the existing catch records this step as failed with
|
|
543
|
+
# deadline_exceeded and the partial results return with an accurate performedCount.
|
|
544
|
+
Test-Deadline 'commit_batch'
|
|
545
|
+
if ($null -ne $s.Item('foreground') -and (BoolArg $s 'foreground' $false)) { Raise-Foreground $p.entry }
|
|
546
|
+
if ($p.verifyOnly) {
|
|
547
|
+
# check-only step: performs NOTHING, it only evaluates the condition that follows the
|
|
548
|
+
# previous action. It never counts towards performedCount.
|
|
549
|
+
$cond = Dict $s.Item('verify')
|
|
550
|
+
if ($null -ne $cond) {
|
|
551
|
+
if (-not $cond.ContainsKey('ref') -and $null -eq $cond.Item('by')) { $cond['ref'] = $re.ref }
|
|
552
|
+
} else { $cond = $s }
|
|
553
|
+
$vm = IntArg $s 'timeoutMs' 900
|
|
554
|
+
# Same check right before the wait: budget that died mid-step must not enter a verify
|
|
555
|
+
# clamped to 0ms and report "unmatched" for a condition that was never measured.
|
|
556
|
+
Test-Deadline 'commit_batch'
|
|
557
|
+
$vv = Wait-Condition $p.entry $cond $vm $before $null $scrollBefore
|
|
558
|
+
$res['verify'] = $vv
|
|
559
|
+
if ($vv.Contains('observed')) { $res['after'] = (TruncStr ([string]$vv.observed) 200) }
|
|
560
|
+
if ($vv.matched) {
|
|
561
|
+
$res['status'] = 'passed'
|
|
562
|
+
$res['ms'] = MsFrom $st
|
|
563
|
+
$results.Add($res) | Out-Null
|
|
564
|
+
continue
|
|
565
|
+
}
|
|
566
|
+
$res['status'] = 'verify_failed'
|
|
567
|
+
$res['detail'] = 'verify condition ' + [string]$vv.type + ' did not match within ' + $vm + 'ms'
|
|
568
|
+
$res['ms'] = MsFrom $st
|
|
569
|
+
$results.Add($res) | Out-Null
|
|
570
|
+
$stoppedAt = $p.index
|
|
571
|
+
$status = 'verify_failed'
|
|
572
|
+
break
|
|
573
|
+
}
|
|
574
|
+
if (-not (BoolArg $s 'noScrollIntoView' $false)) { $res['scrolled'] = [bool](Ensure-InView $re) }
|
|
575
|
+
$via = Do-Action $re $action $value $s
|
|
576
|
+
# Delivery has happened even if a later read/verify fails. Count it immediately.
|
|
577
|
+
$performed += 1
|
|
578
|
+
$script:W.stats.actionsPerformed += 1
|
|
579
|
+
$res['performed'] = $true
|
|
580
|
+
$res['via'] = $via
|
|
581
|
+
$after = ''
|
|
582
|
+
# $re.patterns, not a second PatternsOf scan: the ref already carries the pattern list taken
|
|
583
|
+
# when this step resolved, and $before above read the same list.
|
|
584
|
+
try { $after = Read-Value $re.ae $re.patterns $re } catch { }
|
|
585
|
+
$res['after'] = (TruncStr ([string]$after) 200)
|
|
586
|
+
$c1 = Cursor-Pos
|
|
587
|
+
$res['cursorMoved'] = -not ($cur0.x -eq $c1.x -and $cur0.y -eq $c1.y)
|
|
588
|
+
$res['foregroundChanged'] = ($fg0 -ne (Foreground-Hwnd))
|
|
589
|
+
$v = Dict $s.Item('verify')
|
|
590
|
+
if ($null -ne $v) {
|
|
591
|
+
if (-not $v.ContainsKey('ref') -and $null -eq $v.Item('by')) { $v['ref'] = $re.ref }
|
|
592
|
+
$vm = IntArg $v 'timeoutMs' 900
|
|
593
|
+
# Budget may have died inside the action; a 0ms-clamped verify would report "unmatched"
|
|
594
|
+
# for a condition that was never measured. deadline_exceeded says what actually happened
|
|
595
|
+
# (and the result already carries performed=true: the action WAS delivered).
|
|
596
|
+
Test-Deadline 'commit_batch'
|
|
597
|
+
$vv = Wait-Condition $p.entry $v $vm $before $null $scrollBefore
|
|
598
|
+
$res['verify'] = $vv
|
|
599
|
+
if (-not $vv.matched) {
|
|
600
|
+
$res['status'] = 'verify_failed'
|
|
601
|
+
$res['ms'] = MsFrom $st
|
|
602
|
+
$res['detail'] = 'verify condition ' + [string]$v.Item('type') + ' did not match within ' + $vm + 'ms'
|
|
603
|
+
$results.Add($res) | Out-Null
|
|
604
|
+
$stoppedAt = $p.index
|
|
605
|
+
$status = 'verify_failed'
|
|
606
|
+
break
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
$res['status'] = 'passed'
|
|
610
|
+
$res['ms'] = MsFrom $st
|
|
611
|
+
$results.Add($res) | Out-Null
|
|
612
|
+
} catch {
|
|
613
|
+
$code, $msg = Split-Err $_
|
|
614
|
+
$res['status'] = 'failed'
|
|
615
|
+
$res['code'] = $code
|
|
616
|
+
$res['detail'] = $msg
|
|
617
|
+
$res['ms'] = MsFrom $st
|
|
618
|
+
$results.Add($res) | Out-Null
|
|
619
|
+
$stoppedAt = $p.index
|
|
620
|
+
$status = 'failed'
|
|
621
|
+
break
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
# Every step the batch never reached still gets a result entry, so the reply carries one line
|
|
625
|
+
# per step. Previously the tail was invisible: the model only had performedCount and one stop
|
|
626
|
+
# sentence, and could not tell which planned steps were skipped. not_executed means an earlier
|
|
627
|
+
# step failed or the run was cancelled; the fixed Chinese wording is rendered on the Node side
|
|
628
|
+
# (this file is parsed as ANSI, so Chinese string literals here would corrupt the parser).
|
|
629
|
+
if ($stoppedAt -ge 0) {
|
|
630
|
+
for ($k2 = ($stoppedAt + 1); $k2 -lt $steps.Count; $k2++) {
|
|
631
|
+
$p2 = $null
|
|
632
|
+
foreach ($pp in $plan) { if ($pp.index -eq $k2) { $p2 = $pp; break } }
|
|
633
|
+
if ($null -eq $p2) { continue }
|
|
634
|
+
$results.Add([ordered]@{
|
|
635
|
+
index = $k2
|
|
636
|
+
ref = $(if ($null -ne $p2.re) { $p2.re.ref } else { '' })
|
|
637
|
+
action = $p2.action
|
|
638
|
+
status = 'not_executed'
|
|
639
|
+
ms = 0
|
|
640
|
+
before = ''
|
|
641
|
+
after = ''
|
|
642
|
+
performed = $false
|
|
643
|
+
detail = 'not executed: an earlier step failed or the run was cancelled'
|
|
644
|
+
}) | Out-Null
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
# The Node side reads "no stop" as stoppedAt === null (see tools.js allPassed check), so a
|
|
648
|
+
# sentinel of -1 here would be mistaken for a stop at step -1 and would suppress the recipe
|
|
649
|
+
# save on an otherwise clean batch. Emit the real index, or an explicit JSON null (DBNull, so
|
|
650
|
+
# the generic serializer keeps the key instead of dropping it) when every step passed.
|
|
651
|
+
$stoppedOut = if ($stoppedAt -lt 0) { [System.DBNull]::Value } else { $stoppedAt }
|
|
652
|
+
# "after" half of the window diff: every top-level hwnd that did not exist before phase 2 is
|
|
653
|
+
# reported with its title/class/pid. Empty when nothing appeared — the key stays ABSENT then, so
|
|
654
|
+
# consumers can distinguish "no diff" from an empty diff without extra contract.
|
|
655
|
+
$newWindows = @()
|
|
656
|
+
foreach ($w in (RootWindows)) {
|
|
657
|
+
$h = 0
|
|
658
|
+
$cpW = $null
|
|
659
|
+
try { $cpW = $w.Current; $h = [int]$cpW.NativeWindowHandle } catch { continue }
|
|
660
|
+
if ($h -eq 0) { continue }
|
|
661
|
+
if ($hwndsBefore.ContainsKey([string]$h)) { continue }
|
|
662
|
+
if ($indicatorPid -gt 0 -and [int]$cpW.ProcessId -eq [int]$indicatorPid) { continue }
|
|
663
|
+
$newWindows += [ordered]@{
|
|
664
|
+
hwnd = $h
|
|
665
|
+
pid = [int]$cpW.ProcessId
|
|
666
|
+
title = (TruncStr ([string]$cpW.Name) 120)
|
|
667
|
+
class = (TruncStr ([string]$cpW.ClassName) 80)
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
$r = [ordered]@{
|
|
671
|
+
results = $results
|
|
672
|
+
stoppedAt = $stoppedOut
|
|
673
|
+
performedCount = $performed
|
|
674
|
+
revision = $wantRev
|
|
675
|
+
status = $status
|
|
676
|
+
steps = $steps.Count
|
|
677
|
+
batchOk = ($stoppedAt -lt 0)
|
|
678
|
+
}
|
|
679
|
+
if ($newWindows.Count -gt 0) { $r['newWindows'] = $newWindows }
|
|
680
|
+
return $r
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function Cmd-Wait($A) {
|
|
684
|
+
$cond = Dict (ArgOf $A 'condition')
|
|
685
|
+
if ($null -eq $cond) { Err 'missing_arg' 'wait needs a condition' }
|
|
686
|
+
$timeoutMs = IntArg $A 'timeoutMs' 3000
|
|
687
|
+
$wid = StrArg $A 'windowId' ''
|
|
688
|
+
$entry = $null
|
|
689
|
+
if ($wid -ne '') { $entry = Window-Entry $wid }
|
|
690
|
+
$type = [string]$cond.Item('type')
|
|
691
|
+
if ($type -eq 'element_appears' -or $type -eq 'element_gone') {
|
|
692
|
+
if ($null -eq $entry) {
|
|
693
|
+
$st = TickNow
|
|
694
|
+
$left = BudgetLeftMs
|
|
695
|
+
if ($timeoutMs -gt $left) { $timeoutMs = [int]$left }
|
|
696
|
+
$deadline = $st + ([Int64]$timeoutMs * 10000)
|
|
697
|
+
$hitWin = ''
|
|
698
|
+
while ($true) {
|
|
699
|
+
$hit = $null
|
|
700
|
+
foreach ($e in @($script:W.windows.Values)) {
|
|
701
|
+
$el = Find-ByDescriptor $e (Dict $cond.Item('by'))
|
|
702
|
+
if ($null -ne $el) { $hit = $e; break }
|
|
703
|
+
}
|
|
704
|
+
if ($type -eq 'element_appears') { if ($null -ne $hit) { $hitWin = $hit.id; break } }
|
|
705
|
+
else { if ($null -eq $hit) { break } else { $hitWin = $hit.id } }
|
|
706
|
+
if ((TickNow) -ge $deadline) { break }
|
|
707
|
+
Start-Sleep -Milliseconds 120
|
|
708
|
+
}
|
|
709
|
+
$matched = if ($type -eq 'element_appears') { $hitWin -ne '' } else { $hitWin -eq '' }
|
|
710
|
+
return [ordered]@{ matched = $matched; ms = [Math]::Round((MsFrom $st), 1); type = $type; windowId = $hitWin; scannedWindows = $script:W.windows.Count }
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
if ($type -eq 'window_appears' -or $type -eq 'window_gone' -or $type -eq 'window_title_contains') {
|
|
714
|
+
return Wait-Window $entry $cond $timeoutMs
|
|
715
|
+
}
|
|
716
|
+
if ($null -eq $entry) { Err 'missing_arg' 'wait needs windowId for this condition type' }
|
|
717
|
+
return Wait-Condition $entry $cond $timeoutMs $null $null
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
function Wait-Window($entry, $cond, $timeoutMs) {
|
|
721
|
+
# Window-level waits. "did the dialog appear" was previously only expressible as a sleep plus a
|
|
722
|
+
# list_windows round trip, which is exactly the guesswork computer_wait exists to remove.
|
|
723
|
+
# window_appears — a top-level window matching titleContains/class/pid exists; returns its windowId
|
|
724
|
+
# window_gone — the given windowId closed, or no window matches the criteria any more
|
|
725
|
+
# window_title_contains — one known window's title now contains the text (retitle, save-as path)
|
|
726
|
+
$c = $cond
|
|
727
|
+
$type = [string]$c.Item('type')
|
|
728
|
+
if (@('window_appears', 'window_gone', 'window_title_contains') -notcontains $type) {
|
|
729
|
+
Err 'unknown_condition' ("Wait-Window does not handle '" + (OneLine $type) + "'")
|
|
730
|
+
}
|
|
731
|
+
if ($needle -eq '') { $needle = [string]$c.Item('title') }
|
|
732
|
+
$wantClass = [string]$c.Item('class')
|
|
733
|
+
$wantPid = 0
|
|
734
|
+
try { $wantPid = [int]$c.Item('pid') } catch { $wantPid = 0 }
|
|
735
|
+
$hasCriteria = ($needle -ne '' -or $wantClass -ne '' -or $wantPid -ne 0)
|
|
736
|
+
if ($type -eq 'window_title_contains' -and $null -eq $entry) { Err 'missing_arg' 'window_title_contains needs windowId' }
|
|
737
|
+
if ($type -ne 'window_title_contains' -and $null -eq $entry -and -not $hasCriteria) {
|
|
738
|
+
Err 'bad_arg' ($type + ' needs titleContains, class or pid (or a windowId, for window_gone)')
|
|
739
|
+
}
|
|
740
|
+
$budget = $timeoutMs
|
|
741
|
+
$left = BudgetLeftMs
|
|
742
|
+
if ($left -lt $budget) { $budget = [int]$left }
|
|
743
|
+
if ($budget -lt 0) { $budget = 0 }
|
|
744
|
+
$st = TickNow
|
|
745
|
+
$deadline = $st + ([Int64]$budget * 10000)
|
|
746
|
+
$matched = $false
|
|
747
|
+
$hitId = ''
|
|
748
|
+
$hitTitle = ''
|
|
749
|
+
$obs = ''
|
|
750
|
+
while ($true) {
|
|
751
|
+
$hit = $null
|
|
752
|
+
if ($type -eq 'window_title_contains') {
|
|
753
|
+
$ae = Window-Ae $entry
|
|
754
|
+
$nm = ''
|
|
755
|
+
if ($null -ne $ae) { try { $nm = [string]$ae.Current.Name } catch { } }
|
|
756
|
+
$obs = 'title="' + (TruncStr $nm 60) + '"'
|
|
757
|
+
if ($nm -ne '' -and ($needle -eq '' -or $nm.IndexOf($needle, [StringComparison]::OrdinalIgnoreCase) -ge 0)) { $hit = $entry; $hitTitle = $nm }
|
|
758
|
+
} elseif ($type -eq 'window_gone' -and $null -ne $entry -and -not $hasCriteria) {
|
|
759
|
+
$ae = Window-Ae $entry
|
|
760
|
+
if ($null -eq $ae) { $matched = $true; $obs = 'window closed' } else { $obs = 'still open' }
|
|
761
|
+
} else {
|
|
762
|
+
foreach ($w in (RootWindows)) {
|
|
763
|
+
$cp = $null
|
|
764
|
+
try { $cp = $w.Current } catch { continue }
|
|
765
|
+
$title = [string]$cp.Name
|
|
766
|
+
if ($needle -ne '' -and $title.IndexOf($needle, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
|
|
767
|
+
$hwnd = [int]$cp.NativeWindowHandle
|
|
768
|
+
if ($hwnd -eq 0) { continue }
|
|
769
|
+
if ($wantClass -ne '') {
|
|
770
|
+
$cls = ''
|
|
771
|
+
try { $cls = [string]$cp.ClassName } catch { }
|
|
772
|
+
if ($cls.IndexOf($wantClass, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
|
|
773
|
+
}
|
|
774
|
+
if ($wantPid -ne 0) {
|
|
775
|
+
$wpid = 0
|
|
776
|
+
try { $wpid = [int]$cp.ProcessId } catch { $wpid = 0 }
|
|
777
|
+
if ($wpid -ne $wantPid) { continue }
|
|
778
|
+
}
|
|
779
|
+
$e = Ensure-Window $hwnd $w
|
|
780
|
+
if ($null -ne $e) { $hit = $e; $hitTitle = $title; break }
|
|
781
|
+
}
|
|
782
|
+
if ($type -eq 'window_gone') {
|
|
783
|
+
$matched = ($null -eq $hit)
|
|
784
|
+
$obs = if ($matched) { 'no matching window' } else { 'still ' + $hit.id }
|
|
785
|
+
} else {
|
|
786
|
+
$obs = if ($null -ne $hit) { 'found ' + $hit.id } else { 'not found' }
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
if ($type -ne 'window_gone' -and $null -ne $hit) { $matched = $true; $hitId = [string]$hit.id }
|
|
790
|
+
if ($matched) { break }
|
|
791
|
+
if ((TickNow) -ge $deadline) { break }
|
|
792
|
+
Start-Sleep -Milliseconds 120
|
|
793
|
+
}
|
|
794
|
+
$r = [ordered]@{ type = $type; matched = [bool]$matched; ms = [Math]::Round((MsFrom $st), 1); observed = $obs }
|
|
795
|
+
if ($hitId -ne '') { $r['windowId'] = $hitId }
|
|
796
|
+
if ($hitTitle -ne '') { $r['title'] = (TruncStr $hitTitle 80) }
|
|
797
|
+
return $r
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
function Cmd-CaptureScreen($A) {
|
|
801
|
+
# Native 1:1 by default, same rule as the window capture: a downscaled desktop reads as "the
|
|
802
|
+
# screen was cut off" and makes the model convert coordinates it could use directly.
|
|
803
|
+
$maxDim = IntArg $A 'maxDim' 0
|
|
804
|
+
$st = TickNow
|
|
805
|
+
if ($null -eq ('Native' -as [type])) { Err 'native_missing' 'the P/Invoke helper did not compile; capture is unavailable' }
|
|
806
|
+
$cap = [Native]::CaptureScreen($maxDim)
|
|
807
|
+
$v = Get-VirtScreen
|
|
808
|
+
$r = [ordered]@{
|
|
809
|
+
scope = 'screen'
|
|
810
|
+
method = [string]$cap.method
|
|
811
|
+
blank = [bool]$cap.blank
|
|
812
|
+
width = [int]$cap.width
|
|
813
|
+
height = [int]$cap.height
|
|
814
|
+
distinct = [int]$cap.distinct
|
|
815
|
+
pngBytes = 0
|
|
816
|
+
ms = (MsFrom $st)
|
|
817
|
+
# Measured, not assumed: the virtual screen origin is negative when a monitor sits left of or
|
|
818
|
+
# above the primary one, and it is re-read through GetSystemMetrics on every call.
|
|
819
|
+
screenRect = @{ x = [int]$v.x; y = [int]$v.y; w = [int]$v.w; h = [int]$v.h }
|
|
820
|
+
}
|
|
821
|
+
if ($null -ne $cap.png) {
|
|
822
|
+
$r['pngBytes'] = $cap.png.Length
|
|
823
|
+
if (BoolArg $A 'inline' $true) { $r['pngBase64'] = [Convert]::ToBase64String($cap.png) }
|
|
824
|
+
}
|
|
825
|
+
if ($cap.width -gt 0 -and $cap.height -gt 0) {
|
|
826
|
+
$r['imageWidth'] = [int]$cap.width
|
|
827
|
+
$r['imageHeight'] = [int]$cap.height
|
|
828
|
+
$r['scaleX'] = [Math]::Round([double]$v.w / [double]$cap.width, 4)
|
|
829
|
+
$r['scaleY'] = [Math]::Round([double]$v.h / [double]$cap.height, 4)
|
|
830
|
+
$r['coordinateMap'] = ('screenX = ' + [int]$v.x + ' + imgX * ' + [string]$r['scaleX'] + ' ; screenY = ' + [int]$v.y + ' + imgY * ' + [string]$r['scaleY'])
|
|
831
|
+
}
|
|
832
|
+
$note = [string]$cap.error
|
|
833
|
+
if ($cap.blank) { $note += ('desktop capture came back blank (distinct colors=' + [int]$cap.distinct + '); the session may be locked or on a disconnected desktop') }
|
|
834
|
+
if ($note -ne '') { $r['detail'] = (OneLine $note) }
|
|
835
|
+
return $r
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function Parse-Region($A, $wr) {
|
|
839
|
+
# region = [x0,y0,x1,y1] in WINDOW physical pixels (the space snapshot rects live in), so a model
|
|
840
|
+
# that zoomed by cropping can keep using the same numbers it read from the tree. Returns $null
|
|
841
|
+
# when absent; clamps to the window and refuses a degenerate box instead of silently cropping 0px.
|
|
842
|
+
$raw = ArgOf $A 'region'
|
|
843
|
+
if ($null -eq $raw) { return $null }
|
|
844
|
+
$arr = @()
|
|
845
|
+
if ($raw -is [System.Collections.IEnumerable] -and -not ($raw -is [string])) { foreach ($v in $raw) { $arr += [double]$v } }
|
|
846
|
+
else { $arr = @(([string]$raw) -split ',' | ForEach-Object { [double]$_.Trim() }) }
|
|
847
|
+
if ($arr.Count -ne 4) { Err 'bad_arg' 'region must be [x0,y0,x1,y1]' }
|
|
848
|
+
$x0 = [int][Math]::Max([double]$wr.x, [Math]::Min($arr[0], $arr[2]))
|
|
849
|
+
$y0 = [int][Math]::Max([double]$wr.y, [Math]::Min($arr[1], $arr[3]))
|
|
850
|
+
$x1 = [int][Math]::Min([double]($wr.x + $wr.w), [Math]::Max($arr[0], $arr[2]))
|
|
851
|
+
$y1 = [int][Math]::Min([double]($wr.y + $wr.h), [Math]::Max($arr[1], $arr[3]))
|
|
852
|
+
if ($x1 - $x0 -lt 8 -or $y1 - $y0 -lt 8) { Err 'bad_arg' 'region is empty or smaller than 8x8 inside the window' }
|
|
853
|
+
return [ordered]@{ x = $x0; y = $y0; w = ($x1 - $x0); h = ($y1 - $y0) }
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
function Crop-PngBox($bytes, $x, $y, $w, $h) {
|
|
857
|
+
$ms = New-Object System.IO.MemoryStream(, $bytes)
|
|
858
|
+
$img = [System.Drawing.Image]::FromStream($ms)
|
|
859
|
+
try {
|
|
860
|
+
if ($x -lt 0 -or $y -lt 0 -or ($x + $w) -gt $img.Width -or ($y + $h) -gt $img.Height) {
|
|
861
|
+
Err 'bad_arg' ('crop box ' + $x + ',' + $y + ' ' + $w + 'x' + $h + ' exceeds the ' + $img.Width + 'x' + $img.Height + ' capture')
|
|
862
|
+
}
|
|
863
|
+
$bmp = New-Object System.Drawing.Bitmap($w, $h)
|
|
864
|
+
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
|
865
|
+
try {
|
|
866
|
+
$g.DrawImage($img, (New-Object System.Drawing.Rectangle(0, 0, $w, $h)), (New-Object System.Drawing.Rectangle($x, $y, $w, $h)), [System.Drawing.GraphicsUnit]::Pixel)
|
|
867
|
+
} finally { $g.Dispose() }
|
|
868
|
+
$out = New-Object System.IO.MemoryStream
|
|
869
|
+
try { $bmp.Save($out, [System.Drawing.Imaging.ImageFormat]::Png) } finally { $bmp.Dispose() }
|
|
870
|
+
return $out.ToArray()
|
|
871
|
+
} finally {
|
|
872
|
+
$img.Dispose()
|
|
873
|
+
$ms.Dispose()
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
function Cmd-Capture($A) {
|
|
878
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
879
|
+
# Native 1:1 by default. A downscaled window capture silently changes what the model can read —
|
|
880
|
+
# small text turns to mush and the coordinateMap picks up a scale factor — so the honest default
|
|
881
|
+
# is the window's real pixel size. Callers that want a cheaper preview pass maxDim explicitly.
|
|
882
|
+
$maxDim = IntArg $A 'maxDim' 0
|
|
883
|
+
$st = TickNow
|
|
884
|
+
if ($null -eq ('Native' -as [type])) { Err 'native_missing' 'the P/Invoke helper did not compile; capture is unavailable' }
|
|
885
|
+
$cap = [Native]::Capture([IntPtr]$entry.hwnd, $maxDim)
|
|
886
|
+
$r = [ordered]@{
|
|
887
|
+
windowId = $entry.id
|
|
888
|
+
method = [string]$cap.method
|
|
889
|
+
blank = [bool]$cap.blank
|
|
890
|
+
width = [int]$cap.width
|
|
891
|
+
height = [int]$cap.height
|
|
892
|
+
distinct = [int]$cap.distinct
|
|
893
|
+
isForeground = (Is-ForegroundHwnd $entry.hwnd)
|
|
894
|
+
pngBytes = 0
|
|
895
|
+
ms = (MsFrom $st)
|
|
896
|
+
}
|
|
897
|
+
if ($null -ne $cap.png) {
|
|
898
|
+
$r['pngBytes'] = $cap.png.Length
|
|
899
|
+
if (BoolArg $A 'inline' $true) { $r['pngBase64'] = [Convert]::ToBase64String($cap.png) }
|
|
900
|
+
}
|
|
901
|
+
# region crops the capture to a window-space box (zoom for small text). The crop happens in image
|
|
902
|
+
# pixels, but the reported rect stays in the caller's coordinate space, so coordinateMap keeps
|
|
903
|
+
# producing click/tree coordinates without the model doing region arithmetic.
|
|
904
|
+
$wr = RectOf (Window-Ae $entry).Current
|
|
905
|
+
$reg = Parse-Region $A $wr
|
|
906
|
+
if ($null -ne $reg -and $null -ne $cap.png -and [int]$cap.width -gt 0 -and [int]$cap.height -gt 0 -and $wr.w -gt 0 -and $wr.h -gt 0) {
|
|
907
|
+
$sx0 = [double]$wr.w / [double]$cap.width
|
|
908
|
+
$sy0 = [double]$wr.h / [double]$cap.height
|
|
909
|
+
$ix = [int][Math]::Max(0, [Math]::Round(([double]$reg.x - [double]$wr.x) / $sx0))
|
|
910
|
+
$iy = [int][Math]::Max(0, [Math]::Round(([double]$reg.y - [double]$wr.y) / $sy0))
|
|
911
|
+
$iw = [int][Math]::Max(1, [Math]::Min([int]$cap.width - $ix, [Math]::Round([double]$reg.w / $sx0)))
|
|
912
|
+
$ih = [int][Math]::Max(1, [Math]::Min([int]$cap.height - $iy, [Math]::Round([double]$reg.h / $sy0)))
|
|
913
|
+
$cap.png = Crop-PngBox $cap.png $ix $iy $iw $ih
|
|
914
|
+
$cap.width = $iw; $cap.height = $ih
|
|
915
|
+
$r['cropped'] = $true
|
|
916
|
+
$r['regionRect'] = $reg
|
|
917
|
+
}
|
|
918
|
+
$eff = if ($null -ne $reg) { $reg } else { $wr }
|
|
919
|
+
if ($cap.width -gt 0 -and $cap.height -gt 0 -and $eff.w -gt 0 -and $eff.h -gt 0) {
|
|
920
|
+
$r['windowRect'] = $eff
|
|
921
|
+
$r['imageWidth'] = [int]$cap.width
|
|
922
|
+
$r['imageHeight'] = [int]$cap.height
|
|
923
|
+
$r['scaleX'] = [Math]::Round([double]$eff.w / [double]$cap.width, 4)
|
|
924
|
+
$r['scaleY'] = [Math]::Round([double]$eff.h / [double]$cap.height, 4)
|
|
925
|
+
$r['coordinateMap'] = ('screenX = ' + [int]$eff.x + ' + imgX * ' + [string]$r['scaleX'] + ' ; screenY = ' + [int]$eff.y + ' + imgY * ' + [string]$r['scaleY'])
|
|
926
|
+
}
|
|
927
|
+
$note = [string]$cap.error
|
|
928
|
+
if ($cap.blank) { $note += ('capture came back blank (distinct colors=' + [int]$cap.distinct + '); the window is not rendering into the PrintWindow DC') }
|
|
929
|
+
if ($note -ne '') { $r['detail'] = (OneLine $note) }
|
|
930
|
+
return $r
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function Resolve-OcrExe {
|
|
934
|
+
# The compiled WinRT shim. Shipped in worker\bin (7 KB, no model: Windows.Media.Ocr is an OS
|
|
935
|
+
# component). DSH_OCR_EXE overrides it for testing. Returns $null when absent so the caller can
|
|
936
|
+
# fail with a clear reason rather than a raw process error.
|
|
937
|
+
$p = $env:DSH_OCR_EXE
|
|
938
|
+
# $PSScriptRoot is worker/lib here, so the bundled OCR helper sits one level up.
|
|
939
|
+
if ([string]::IsNullOrEmpty($p)) { $p = Join-Path $PSScriptRoot '..\bin\ocr.exe' }
|
|
940
|
+
if (-not (Test-Path -LiteralPath $p)) { return $null }
|
|
941
|
+
return (Resolve-Path -LiteralPath $p).Path
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function Invoke-OcrExe($exe, $pngPath) {
|
|
945
|
+
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
946
|
+
$psi.FileName = $exe
|
|
947
|
+
$psi.Arguments = '"' + $pngPath + '"'
|
|
948
|
+
$psi.UseShellExecute = $false
|
|
949
|
+
$psi.RedirectStandardOutput = $true
|
|
950
|
+
$psi.RedirectStandardError = $true
|
|
951
|
+
$psi.CreateNoWindow = $true
|
|
952
|
+
$psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8
|
|
953
|
+
$proc = [System.Diagnostics.Process]::Start($psi)
|
|
954
|
+
$stdout = $proc.StandardOutput.ReadToEnd()
|
|
955
|
+
$stderr = $proc.StandardError.ReadToEnd()
|
|
956
|
+
$proc.WaitForExit()
|
|
957
|
+
return @{ code = $proc.ExitCode; out = $stdout; err = $stderr }
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function Cmd-Ocr($A) {
|
|
961
|
+
$st = TickNow
|
|
962
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
963
|
+
$maxDim = IntArg $A 'maxDim' 1400
|
|
964
|
+
$exe = Resolve-OcrExe
|
|
965
|
+
if ($null -eq $exe) { Err 'ocr_unavailable' 'ocr.exe not found (place it in worker\bin or set DSH_OCR_EXE)' }
|
|
966
|
+
$ae = Window-Ae $entry
|
|
967
|
+
$wr = RectOf $ae.Current
|
|
968
|
+
if ($wr.w -le 0 -or $wr.h -le 0) { Err 'no_rect' 'window has no usable rect (minimized?); activate/restore it first' }
|
|
969
|
+
$cap = [Native]::Capture([IntPtr]$entry.hwnd, $maxDim)
|
|
970
|
+
if ($null -eq $cap.png -or [bool]$cap.blank) {
|
|
971
|
+
Err 'capture_blank' ('window did not render into the capture (method=' + [string]$cap.method + ' distinct=' + [int]$cap.distinct + ')')
|
|
972
|
+
}
|
|
973
|
+
# OCR a region when asked: cropping first is what makes small text readable, because the OCR engine
|
|
974
|
+
# sees the pixels at full size instead of inside a 1400-px-wide window shot.
|
|
975
|
+
$reg = Parse-Region $A $wr
|
|
976
|
+
if ($null -ne $reg -and [int]$cap.width -gt 0 -and [int]$cap.height -gt 0) {
|
|
977
|
+
$sx0 = [double]$wr.w / [double]$cap.width
|
|
978
|
+
$sy0 = [double]$wr.h / [double]$cap.height
|
|
979
|
+
$ix = [int][Math]::Max(0, [Math]::Round(([double]$reg.x - [double]$wr.x) / $sx0))
|
|
980
|
+
$iy = [int][Math]::Max(0, [Math]::Round(([double]$reg.y - [double]$wr.y) / $sy0))
|
|
981
|
+
$iw = [int][Math]::Max(1, [Math]::Min([int]$cap.width - $ix, [Math]::Round([double]$reg.w / $sx0)))
|
|
982
|
+
$ih = [int][Math]::Max(1, [Math]::Min([int]$cap.height - $iy, [Math]::Round([double]$reg.h / $sy0)))
|
|
983
|
+
$cap.png = Crop-PngBox $cap.png $ix $iy $iw $ih
|
|
984
|
+
$wr = $reg
|
|
985
|
+
}
|
|
986
|
+
$tmp = Join-Path ([System.IO.Path]::GetTempPath()) ('yuping-ocr-' + $PID + '-' + (Get-Random) + '.png')
|
|
987
|
+
[System.IO.File]::WriteAllBytes($tmp, $cap.png)
|
|
988
|
+
$imgW = [int]$cap.width; $imgH = [int]$cap.height
|
|
989
|
+
$r = Invoke-OcrExe $exe $tmp
|
|
990
|
+
try { Remove-Item -LiteralPath $tmp -ErrorAction SilentlyContinue } catch { }
|
|
991
|
+
if ($r.code -ne 0) { Err 'ocr_failed' ('ocr.exe exit ' + [string]$r.code + ': ' + (TruncStr ([string]($r.err + $r.out)) 200)) }
|
|
992
|
+
$parsed = $null
|
|
993
|
+
try { $parsed = $r.out | ConvertFrom-Json } catch { Err 'ocr_parse' ('bad ocr json: ' + (TruncStr ([string]$r.out) 200)) }
|
|
994
|
+
if ($null -eq $parsed -or -not [bool]$parsed.ok) { Err 'ocr_error' (TruncStr ([string]$parsed.error) 200) }
|
|
995
|
+
# The capture is the whole window at its physical size (possibly downscaled to maxDim), so image
|
|
996
|
+
# pixels map onto the window rect by a per-axis scale; word centers become clickable screen points.
|
|
997
|
+
$sx = [double]$wr.w / [double]$imgW
|
|
998
|
+
$sy = [double]$wr.h / [double]$imgH
|
|
999
|
+
$words = @()
|
|
1000
|
+
foreach ($wd in $parsed.words) {
|
|
1001
|
+
$words += [ordered]@{
|
|
1002
|
+
text = [string]$wd.t
|
|
1003
|
+
cx = [int]([double]$wr.x + (([double]$wd.x + [double]$wd.w / 2.0) * $sx))
|
|
1004
|
+
cy = [int]([double]$wr.y + (([double]$wd.y + [double]$wd.h / 2.0) * $sy))
|
|
1005
|
+
rect = [ordered]@{
|
|
1006
|
+
x = [int]([double]$wr.x + [double]$wd.x * $sx)
|
|
1007
|
+
y = [int]([double]$wr.y + [double]$wd.y * $sy)
|
|
1008
|
+
w = [int]([double]$wd.w * $sx)
|
|
1009
|
+
h = [int]([double]$wd.h * $sy)
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
return [ordered]@{
|
|
1014
|
+
windowId = $entry.id
|
|
1015
|
+
engine = 'windows-media-ocr'
|
|
1016
|
+
imageWidth = $imgW
|
|
1017
|
+
imageHeight = $imgH
|
|
1018
|
+
windowRect = $wr
|
|
1019
|
+
cropped = [bool]($null -ne $reg)
|
|
1020
|
+
scaleX = [Math]::Round($sx, 4)
|
|
1021
|
+
scaleY = [Math]::Round($sy, 4)
|
|
1022
|
+
text = [string]$parsed.text
|
|
1023
|
+
count = $words.Count
|
|
1024
|
+
words = $words
|
|
1025
|
+
ms = (MsFrom $st)
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
function Cmd-FindText($A) {
|
|
1030
|
+
$st = TickNow
|
|
1031
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
1032
|
+
$text = StrArg $A 'text' ''
|
|
1033
|
+
if ($text -eq '') { Err 'missing_arg' 'find_text needs text' }
|
|
1034
|
+
$exact = BoolArg $A 'exact' $false
|
|
1035
|
+
$max = IntArg $A 'max' 60
|
|
1036
|
+
$ae = Window-Ae $entry
|
|
1037
|
+
if ($null -eq $ae) { Err 'window_not_found' ("window " + $entry.id + " is gone") }
|
|
1038
|
+
# ---- cached scan: Activate a PRIVATE request (same property/pattern shape as the snapshot
|
|
1039
|
+
# request, incl. pattern availability + RuntimeId), so FindAll returns elements that already
|
|
1040
|
+
# carry their cache and the per-element loop reads $c.Cached with no per-node round-trips
|
|
1041
|
+
# (measured ~160 ms for a ~500-element tree vs ~650 ms of live Current reads). Deliberately a
|
|
1042
|
+
# SEPARATE request object (Find-CacheRequest), never the shared $script:snapReq. Mode stays Full,
|
|
1043
|
+
# so refs minted from these elements are still live elements and every later pattern call on
|
|
1044
|
+
# them works. The scope is popped before the element loop: the cache stays materialised on the
|
|
1045
|
+
# elements themselves. Any failure here falls back to the historical live scan below.
|
|
1046
|
+
$all = @()
|
|
1047
|
+
$usedCached = $false
|
|
1048
|
+
$freq = Find-CacheRequest
|
|
1049
|
+
if ($null -ne $freq) {
|
|
1050
|
+
try {
|
|
1051
|
+
# [void] on both Activate and Pop is load-bearing: Activate returns a CacheRequestActivation
|
|
1052
|
+
# marker, and a bare expression inside a function joins the function's OUTPUT STREAM — the
|
|
1053
|
+
# reply would then be [result, activation] and every consumer would read garbage.
|
|
1054
|
+
[void]$freq.Activate()
|
|
1055
|
+
try {
|
|
1056
|
+
$all = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, [System.Windows.Automation.Condition]::TrueCondition))
|
|
1057
|
+
# One probe decides the batch: an element without a usable cache throws on .Cached, and
|
|
1058
|
+
# then everything is re-enumerated through the live path below.
|
|
1059
|
+
if ($all.Count -gt 0) { $null = $all[0].Cached; $usedCached = $true }
|
|
1060
|
+
} finally {
|
|
1061
|
+
try { [void]$freq.Pop() } catch { }
|
|
1062
|
+
}
|
|
1063
|
+
} catch { $usedCached = $false }
|
|
1064
|
+
}
|
|
1065
|
+
if (-not $usedCached) {
|
|
1066
|
+
try { $all = @($ae.FindAll([System.Windows.Automation.TreeScope]::Descendants, [System.Windows.Automation.Condition]::TrueCondition)) } catch { Err 'uia_error' ('FindAll threw: ' + $_.Exception.Message) }
|
|
1067
|
+
}
|
|
1068
|
+
$out = New-Object System.Collections.Generic.List[object]
|
|
1069
|
+
# How many times each (name, controlType) pair has been emitted so far. A `by` descriptor is
|
|
1070
|
+
# resolved later by FindFirst, which always returns the first match — so without this, a window
|
|
1071
|
+
# with three "复制" buttons can only ever reach the first one and the model's second/third pick
|
|
1072
|
+
# silently lands on the wrong control ("点不准" with perfect coordinates). Carrying `nth` in the
|
|
1073
|
+
# descriptor makes each match individually addressable.
|
|
1074
|
+
$seen = @{}
|
|
1075
|
+
$matchedTotal = 0
|
|
1076
|
+
$truncated = $false
|
|
1077
|
+
foreach ($c in $all) {
|
|
1078
|
+
# Same per-element guard as before, but a timeout no longer DISCARDS the command: every hit
|
|
1079
|
+
# already collected is still true, so the partial list returns marked truncated (the old
|
|
1080
|
+
# deadline_exceeded error threw away all of it — the model paid for a full scan and got
|
|
1081
|
+
# nothing back).
|
|
1082
|
+
if ($script:W.dl -ne [Int64]::MaxValue -and (TickNow) -gt $script:W.dl) { $truncated = $true; break }
|
|
1083
|
+
try { $cp = if ($usedCached) { $c.Cached } else { $c.Current } } catch { continue }
|
|
1084
|
+
$n = [string]$cp.Name
|
|
1085
|
+
$ctn = ''
|
|
1086
|
+
if ($n -eq '') {
|
|
1087
|
+
# A nameless Edit/Document/Text can still carry the text the caller is after (a label-less
|
|
1088
|
+
# input box's content lives in its value, not its name). This used to read $cp.Value — a
|
|
1089
|
+
# property AutomationElementInformation does not HAVE — so it silently returned '' forever
|
|
1090
|
+
# and the documented value search never fired. Read the value from ValuePattern, for that
|
|
1091
|
+
# narrow type set only, so the extra pattern call stays rare on container-heavy trees.
|
|
1092
|
+
try { $ctn = ControlTypeName $cp.ControlType } catch { $ctn = '' }
|
|
1093
|
+
if ($ctn -eq 'Edit' -or $ctn -eq 'Document' -or $ctn -eq 'Text') {
|
|
1094
|
+
try {
|
|
1095
|
+
$vp = $c.GetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern)
|
|
1096
|
+
if ($null -ne $vp) { $n = [string]$vp.Current.Value }
|
|
1097
|
+
} catch { $n = '' }
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
if ($n.Length -eq 0) { continue }
|
|
1101
|
+
# Literal, case-insensitive containment. -like treated * ? [ ] in the caller's text as
|
|
1102
|
+
# wildcards, so searching for a name containing brackets matched unrelated controls.
|
|
1103
|
+
$m = if ($exact) { $n.Equals($text, [StringComparison]::OrdinalIgnoreCase) } else { $n.IndexOf($text, [StringComparison]::OrdinalIgnoreCase) -ge 0 }
|
|
1104
|
+
if (-not $m) { continue }
|
|
1105
|
+
# The honest hit total, INCLUDING everything past max: the scan already walked the tree, so
|
|
1106
|
+
# counting the tail costs one Name read per remaining element and turns the silent drop into
|
|
1107
|
+
# a reported truncation (matchedTotal > count ⇔ the reply must say so).
|
|
1108
|
+
$matchedTotal += 1
|
|
1109
|
+
if ($out.Count -ge $max) { $truncated = $true; continue }
|
|
1110
|
+
$rc = RectOf $cp
|
|
1111
|
+
if ($ctn -eq '') { $ctn = ControlTypeName $cp.ControlType }
|
|
1112
|
+
$key = $ctn + '#' + $n
|
|
1113
|
+
$nth = 1
|
|
1114
|
+
if ($seen.ContainsKey($key)) { $nth = $seen[$key] + 1 }
|
|
1115
|
+
$seen[$key] = $nth
|
|
1116
|
+
# The descriptor must be able to RESOLVE later, so it is built from the real identity, never
|
|
1117
|
+
# from the display text: a name cut at 160 chars could never satisfy an exact match, and a
|
|
1118
|
+
# non-empty AutomationId is a stable anchor when the visible label changes or repeats.
|
|
1119
|
+
$selName = $n
|
|
1120
|
+
$pats = @()
|
|
1121
|
+
try { $pats = PatternsOf $c } catch { $pats = @() }
|
|
1122
|
+
$node = [ordered]@{
|
|
1123
|
+
controlType = $ctn
|
|
1124
|
+
name = (TruncStr $n 160)
|
|
1125
|
+
className = [string]$cp.ClassName
|
|
1126
|
+
automationId = [string]$cp.AutomationId
|
|
1127
|
+
patterns = @($pats)
|
|
1128
|
+
enabled = [bool]$cp.IsEnabled
|
|
1129
|
+
isOffscreen = [bool]$cp.IsOffscreen
|
|
1130
|
+
rect = $rc
|
|
1131
|
+
depth = 0
|
|
1132
|
+
}
|
|
1133
|
+
# Same convention the snapshot uses: when the node's 160-cut display name differs from the
|
|
1134
|
+
# real one, carry the untruncated name so a recipe can re-resolve it strictly.
|
|
1135
|
+
if ($n.Length -gt 160) { $node['fullName'] = $n }
|
|
1136
|
+
$byDesc = @{ controlType = $ctn }
|
|
1137
|
+
if ($selName.Length -gt 200) {
|
|
1138
|
+
$byDesc['name'] = $selName.Substring(0, 200)
|
|
1139
|
+
$byDesc['nameExact'] = $false
|
|
1140
|
+
} else {
|
|
1141
|
+
$byDesc['name'] = $selName
|
|
1142
|
+
}
|
|
1143
|
+
if ([string]$node.automationId -ne '') { $byDesc['automationId'] = [string]$node.automationId }
|
|
1144
|
+
if ($nth -gt 1) { $byDesc['nth'] = $nth }
|
|
1145
|
+
# Issue a ref for every hit. find_text used to return only coordinates and a by-descriptor, so
|
|
1146
|
+
# computer_act (which takes a ref and nothing else) could not be driven from a search result —
|
|
1147
|
+
# the model had to fall back to a physical computer_click, moving the real cursor for what
|
|
1148
|
+
# should have been a background action. Refs cost one table entry each and make the two tools
|
|
1149
|
+
# compose.
|
|
1150
|
+
$refRec = $null
|
|
1151
|
+
try { $refRec = New-Ref $entry $c $cp $node } catch { $refRec = $null }
|
|
1152
|
+
# The item reads back what the node already holds — className/automationId/enabled/isOffscreen
|
|
1153
|
+
# were each read TWICE before (once for $node, once for $item), one avoidable round-trip each.
|
|
1154
|
+
$item = [ordered]@{
|
|
1155
|
+
name = $node.name
|
|
1156
|
+
controlType = $ctn
|
|
1157
|
+
className = $node.className
|
|
1158
|
+
automationId = $node.automationId
|
|
1159
|
+
rect = $rc
|
|
1160
|
+
enabled = $node.enabled
|
|
1161
|
+
isOffscreen = $node.isOffscreen
|
|
1162
|
+
patterns = $node.patterns
|
|
1163
|
+
ref = $(if ($null -ne $refRec) { $refRec.ref } else { $null })
|
|
1164
|
+
center = @{ x = ($rc.x + [int]($rc.w / 2)); y = ($rc.y + [int]($rc.h / 2)) }
|
|
1165
|
+
# nth is only meaningful once a duplicate exists; a unique hit keeps the old 1-field shape
|
|
1166
|
+
# and nth=1 so recipes saved before this change still replay against the same element.
|
|
1167
|
+
nth = $nth
|
|
1168
|
+
by = $byDesc
|
|
1169
|
+
}
|
|
1170
|
+
$out.Add($item) | Out-Null
|
|
1171
|
+
}
|
|
1172
|
+
$r = [ordered]@{ windowId = $entry.id; revision = $entry.revision; text = $text; matches = $out; count = $out.Count; scanned = $all.Count; matchedTotal = $matchedTotal; truncated = [bool]$truncated; ms = (MsFrom $st) }
|
|
1173
|
+
# Position metadata, same contract as snapshot's: advisory fields, omitted on failure.
|
|
1174
|
+
try {
|
|
1175
|
+
$obsHeader = Window-ObservationHeader $entry
|
|
1176
|
+
if ($null -ne $obsHeader) {
|
|
1177
|
+
foreach ($k in @($obsHeader.Keys)) { $r[$k] = $obsHeader[$k] }
|
|
1178
|
+
}
|
|
1179
|
+
} catch { }
|
|
1180
|
+
return $r
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
function Resolve-LaunchTarget($app) {
|
|
1184
|
+
$info = @{ path = ''; via = '' }
|
|
1185
|
+
if ($null -eq $app -or [string]$app -eq '') { Err 'missing_arg' 'launch needs app, uri or msAppAlias' }
|
|
1186
|
+
$app = [string]$app
|
|
1187
|
+
if ($app -match '[\\/]' -and (Test-Path -LiteralPath $app)) {
|
|
1188
|
+
$info.path = (Resolve-Path -LiteralPath $app).Path
|
|
1189
|
+
$info.via = 'literal-path'
|
|
1190
|
+
return $info
|
|
1191
|
+
}
|
|
1192
|
+
$names = @($app)
|
|
1193
|
+
if ($app -notmatch '\.(exe|com)$') { $names = @(($app + '.exe'), $app) }
|
|
1194
|
+
$win = $env:SystemRoot
|
|
1195
|
+
foreach ($n in $names) {
|
|
1196
|
+
foreach ($dir in @(($win + '\System32'), ($win + '\SysWOW64'), $win)) {
|
|
1197
|
+
$f = Join-Path $dir $n
|
|
1198
|
+
if (Test-Path -LiteralPath $f -PathType Leaf) { $info.path = $f; $info.via = 'windows-dir'; return $info }
|
|
1199
|
+
}
|
|
1200
|
+
$wa = Join-Path $env:LOCALAPPDATA ('Microsoft\WindowsApps\' + $n)
|
|
1201
|
+
if (Test-Path -LiteralPath $wa) { $info.path = $wa; $info.via = 'app-execution-alias'; return $info }
|
|
1202
|
+
foreach ($hive in @('HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths', 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths')) {
|
|
1203
|
+
$key = $hive + '\' + $n
|
|
1204
|
+
if (Test-Path -LiteralPath $key) {
|
|
1205
|
+
$v = (Get-ItemProperty -LiteralPath $key -ErrorAction SilentlyContinue).'(default)'
|
|
1206
|
+
if ($null -ne $v -and [string]$v -ne '' -and (Test-Path -LiteralPath ([string]$v))) { $info.path = [string]$v; $info.via = 'app-paths-registry'; return $info }
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
# PATH, but only real Windows executables. Git's usr/bin ships POSIX scripts named
|
|
1211
|
+
# like windows tools; ShellExecute on those opens an editor instead of the tool.
|
|
1212
|
+
foreach ($n in $names) {
|
|
1213
|
+
foreach ($dir in ($env:PATH -split ';')) {
|
|
1214
|
+
if ($dir -eq '') { continue }
|
|
1215
|
+
if ($dir -match '(?i)\\git\\|\\usr\\bin|\\bin\\sh|\\msys|\\cygwin|\\busybox') { continue }
|
|
1216
|
+
$f = Join-Path $dir $n
|
|
1217
|
+
if (Test-Path -LiteralPath $f -PathType Leaf) {
|
|
1218
|
+
$it = Get-Item -LiteralPath $f
|
|
1219
|
+
if ($it.Extension -eq '.exe' -or $it.Extension -eq '.com') { $info.path = $it.FullName; $info.via = 'path'; return $info }
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
$roots = @(($env:APPDATA + '\Microsoft\Windows\Start Menu\Programs'), ($env:ProgramData + '\Microsoft\Windows\Start Menu\Programs')) | Where-Object { Test-Path -LiteralPath $_ }
|
|
1224
|
+
foreach ($n in $names) {
|
|
1225
|
+
$stem = ($n -replace '\.(exe|com)$', '')
|
|
1226
|
+
$lnk = Get-ChildItem -LiteralPath $roots[0] -Recurse -Filter '*.lnk' -ErrorAction SilentlyContinue | Where-Object { $_.BaseName -replace ' & ', '' -match ('(?i)^' + [regex]::Escape($stem) + '$') } | Select-Object -First 1
|
|
1227
|
+
if ($null -eq $lnk -and $roots.Count -gt 1) {
|
|
1228
|
+
$lnk = Get-ChildItem -LiteralPath $roots[1] -Recurse -Filter '*.lnk' -ErrorAction SilentlyContinue | Where-Object { $_.BaseName -replace ' & ', '' -match ('(?i)^' + [regex]::Escape($stem) + '$') } | Select-Object -First 1
|
|
1229
|
+
}
|
|
1230
|
+
if ($null -ne $lnk) { $info.path = $lnk.FullName; $info.via = 'start-menu'; return $info }
|
|
1231
|
+
}
|
|
1232
|
+
Err 'launch_failed' ("cannot resolve '" + $app + "' through windows-dir, app-execution-alias, app-paths, PATH or start-menu")
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
function Cmd-Launch($A) {
|
|
1236
|
+
$app = StrArg $A 'app' ''
|
|
1237
|
+
$alias = StrArg $A 'msAppAlias' ''
|
|
1238
|
+
$uri = StrArg $A 'uri' ''
|
|
1239
|
+
$timeoutMs = IntArg $A 'timeoutMs' 8000
|
|
1240
|
+
$argList = ListOf (ArgOf $A 'args')
|
|
1241
|
+
$titleFilter = StrArg $A 'title' ''
|
|
1242
|
+
$classFilter = StrArg $A 'class' ''
|
|
1243
|
+
if ($app -eq '' -and $alias -eq '' -and $uri -eq '') { Err 'missing_arg' 'launch needs app, msAppAlias or uri' }
|
|
1244
|
+
# app accepts protocol URIs too (for example microsoft.windows.camera:). A drive
|
|
1245
|
+
# prefix, including drive-relative C:foo, is a Windows path rather than a URI scheme.
|
|
1246
|
+
if ($uri -eq '' -and $alias -eq '' -and $app -match '^[A-Za-z][A-Za-z0-9+.-]*:' -and $app -notmatch '^[A-Za-z]:') { $uri = $app }
|
|
1247
|
+
$exe = ''; $via = ''
|
|
1248
|
+
$st = TickNow
|
|
1249
|
+
if ($uri -ne '') { $exe = $uri; $via = 'uri-shell' }
|
|
1250
|
+
elseif ($alias -ne '') { $r = Resolve-LaunchTarget $alias; $exe = $r.path; $via = 'ms-app-alias:' + $r.via }
|
|
1251
|
+
else { $r = Resolve-LaunchTarget $app; $exe = $r.path; $via = $r.via }
|
|
1252
|
+
$argline = ''
|
|
1253
|
+
foreach ($a in $argList) {
|
|
1254
|
+
$sa = [string]$a
|
|
1255
|
+
if ($sa -match '[\s"]') { $argline += ' "' + $sa.Replace('"', '\"') + '"' } else { $argline += ' ' + $sa }
|
|
1256
|
+
}
|
|
1257
|
+
$argline = $argline.Trim()
|
|
1258
|
+
$beforePids = @{}
|
|
1259
|
+
foreach ($pr in [System.Diagnostics.Process]::GetProcesses()) { try { $beforePids[[string]$pr.Id] = 1 } catch { } }
|
|
1260
|
+
$beforeHwnds = @{}
|
|
1261
|
+
$beforeTitle = @{}
|
|
1262
|
+
foreach ($w in (RootWindows)) {
|
|
1263
|
+
$cp = $null
|
|
1264
|
+
try { $cp = $w.Current; $bh = [int]$cp.NativeWindowHandle } catch { continue }
|
|
1265
|
+
if ($bh -eq 0) { continue }
|
|
1266
|
+
$beforeHwnds[[string]$bh] = 1
|
|
1267
|
+
$beforeTitle[[string]$bh] = ([string]$cp.Name).ToLowerInvariant()
|
|
1268
|
+
}
|
|
1269
|
+
# Optional title/appName hint. On Windows 11 `notepad` is a store alias and the real
|
|
1270
|
+
# editor is a SINGLE process that owns every open document: launching a file folds it
|
|
1271
|
+
# into a window that already existed, so neither a new pid nor a new hwnd appears -- the
|
|
1272
|
+
# only observable event is that window's TITLE changing to mention our file. Deriving the
|
|
1273
|
+
# hint from the file argument's basename (never from the app name) is what lets us resolve
|
|
1274
|
+
# our own document without ever matching a foreign document (e.g. CARVE-*.md) in the same
|
|
1275
|
+
# process. An explicit title/appName always wins.
|
|
1276
|
+
$hint = ''
|
|
1277
|
+
foreach ($tok in @($titleFilter)) {
|
|
1278
|
+
$t = [string]$tok
|
|
1279
|
+
if ($t -ne '') { $hint = $t.ToLowerInvariant(); break }
|
|
1280
|
+
}
|
|
1281
|
+
if ($hint -eq '') {
|
|
1282
|
+
foreach ($a in $argList) {
|
|
1283
|
+
$sa = [string]$a
|
|
1284
|
+
if ($sa -match '[\\/]' -or $sa -match '\.[A-Za-z0-9]{1,8}$') {
|
|
1285
|
+
$base = ($sa -replace '[\\/]+$', '')
|
|
1286
|
+
$base = $base -replace '^.*[\\/]', ''
|
|
1287
|
+
$base = $base -replace '\.[A-Za-z0-9]{1,8}$', ''
|
|
1288
|
+
if ($base.Length -ge 3) { $hint = $base.ToLowerInvariant(); break }
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
}
|
|
1292
|
+
$launchedPid = 0
|
|
1293
|
+
try {
|
|
1294
|
+
$pi = New-Object System.Diagnostics.ProcessStartInfo
|
|
1295
|
+
$pi.FileName = $exe
|
|
1296
|
+
$pi.Arguments = $argline
|
|
1297
|
+
$pi.UseShellExecute = $true
|
|
1298
|
+
$cwd = StrArg $A 'cwd' ''
|
|
1299
|
+
if ($cwd -ne '') { $pi.WorkingDirectory = $cwd }
|
|
1300
|
+
$proc = [System.Diagnostics.Process]::Start($pi)
|
|
1301
|
+
if ($null -ne $proc) { $launchedPid = $proc.Id }
|
|
1302
|
+
} catch {
|
|
1303
|
+
Err 'launch_failed' ("Process.Start('" + $exe + "') threw: " + $_.Exception.Message)
|
|
1304
|
+
}
|
|
1305
|
+
$left = BudgetLeftMs
|
|
1306
|
+
$budget = $timeoutMs
|
|
1307
|
+
if ($budget -gt $left) { $budget = [int]$left }
|
|
1308
|
+
if ($budget -lt 200) { $budget = 200 }
|
|
1309
|
+
$deadline = (TickNow) + ([Int64]$budget * 10000)
|
|
1310
|
+
$foundEntry = $null
|
|
1311
|
+
$matchedBy = ''
|
|
1312
|
+
$foundPidNew = $false
|
|
1313
|
+
$fallbackEntry = $null
|
|
1314
|
+
$fallbackBy = ''
|
|
1315
|
+
$fallbackPidNew = $false
|
|
1316
|
+
while ($true) {
|
|
1317
|
+
Test-Deadline 'launch'
|
|
1318
|
+
foreach ($w in (RootWindows)) {
|
|
1319
|
+
$hwnd = 0; $cp = $null
|
|
1320
|
+
try { $cp = $w.Current; $hwnd = [int]$cp.NativeWindowHandle } catch { continue }
|
|
1321
|
+
if ($hwnd -eq 0) { continue }
|
|
1322
|
+
$hk = [string]$hwnd
|
|
1323
|
+
$isNew = -not $beforeHwnds.ContainsKey($hk)
|
|
1324
|
+
$p = [int]$cp.ProcessId
|
|
1325
|
+
$isPidNew = ($launchedPid -ne 0 -and $p -eq $launchedPid) -or (-not $beforePids.ContainsKey([string]$p))
|
|
1326
|
+
$tNow = ([string]$cp.Name).ToLowerInvariant()
|
|
1327
|
+
$titleChanged = ($beforeTitle.ContainsKey($hk) -and ($beforeTitle[$hk] -ne $tNow))
|
|
1328
|
+
$hintHit = ($hint -ne '' -and $tNow.Contains($hint))
|
|
1329
|
+
# A STRONG candidate is a top-level window that appeared after the start timestamp
|
|
1330
|
+
# (new hwnd or new owner pid -- the store-alias handoff) OR the window whose title
|
|
1331
|
+
# changed to mention our file after the start timestamp (Win11 single-process tab reuse).
|
|
1332
|
+
# A WEAK candidate is a visible top-level window that already carries our hint; it is only
|
|
1333
|
+
# used after the full budget, so a genuinely new window still wins over a stale same-named one.
|
|
1334
|
+
$strong = ($isNew -or $isPidNew) -or ($titleChanged -and $hintHit)
|
|
1335
|
+
$weak = ($hintHit -and -not $isNew -and -not $isPidNew -and -not $titleChanged)
|
|
1336
|
+
if (-not $strong -and -not $weak) { continue }
|
|
1337
|
+
# When we have a discriminator hint, even a new window must belong to it -- that is what
|
|
1338
|
+
# keeps an unrelated popup (or another document in the same process) from being grabbed.
|
|
1339
|
+
if ($hint -ne '' -and -not $hintHit) { continue }
|
|
1340
|
+
$rc = RectOf $cp
|
|
1341
|
+
$iconic = $false
|
|
1342
|
+
try { $iconic = [Native]::IsIconic([IntPtr]$hwnd) } catch { }
|
|
1343
|
+
if (($rc.w -lt 40 -or $rc.h -lt 40) -and -not $iconic) { continue }
|
|
1344
|
+
if ($titleFilter -ne '' -and ([string]$tNow).IndexOf($titleFilter, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
|
|
1345
|
+
if ($classFilter -ne '' -and ([string]$cp.ClassName).IndexOf($classFilter, [StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
|
|
1346
|
+
$e = Ensure-Window $hwnd $w
|
|
1347
|
+
if ($null -eq $e) { continue }
|
|
1348
|
+
if ($strong) {
|
|
1349
|
+
$foundEntry = $e
|
|
1350
|
+
if ($p -eq $launchedPid) { $matchedBy = 'launched-pid' }
|
|
1351
|
+
elseif ($isPidNew -and -not $isNew) { $matchedBy = 'new-pid-handoff' }
|
|
1352
|
+
elseif ($isNew) { $matchedBy = 'new-hwnd' }
|
|
1353
|
+
else { $matchedBy = 'title-change-handoff' }
|
|
1354
|
+
$foundPidNew = $isPidNew
|
|
1355
|
+
break
|
|
1356
|
+
} elseif ($null -eq $fallbackEntry) {
|
|
1357
|
+
$fallbackEntry = $e; $fallbackBy = 'title-hint-reuse'; $fallbackPidNew = $isPidNew
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
if ($null -ne $foundEntry) { break }
|
|
1361
|
+
if ((TickNow) -ge $deadline) { break }
|
|
1362
|
+
Start-Sleep -Milliseconds 150
|
|
1363
|
+
}
|
|
1364
|
+
if ($null -eq $foundEntry -and $null -ne $fallbackEntry) {
|
|
1365
|
+
$foundEntry = $fallbackEntry; $matchedBy = $fallbackBy; $foundPidNew = $fallbackPidNew
|
|
1366
|
+
}
|
|
1367
|
+
if ($null -eq $foundEntry) {
|
|
1368
|
+
$script:W.stats.refused += 1
|
|
1369
|
+
Err 'window_not_found' ("launched " + $exe + " (pid " + $launchedPid + ") but no matching new window appeared within " + $budget + 'ms')
|
|
1370
|
+
}
|
|
1371
|
+
$ae = Window-Ae $foundEntry
|
|
1372
|
+
$cp2 = $ae.Current
|
|
1373
|
+
# The plugin may only claim ownership of a window it actually created. When the owning
|
|
1374
|
+
# process already existed before this launch (the Win11 single-process hand-off), that same
|
|
1375
|
+
# process also hosts the user's other documents, so returning its pid would let a later
|
|
1376
|
+
# policy check treat those documents as ours and close them. In that case report the
|
|
1377
|
+
# launcher pid instead -- disjoint from the window owner -- so policy keeps treating the
|
|
1378
|
+
# window as foreign and it must be closed explicitly. Only a brand-new owner pid is claimed.
|
|
1379
|
+
$ownerPid = [int]$foundEntry.pid
|
|
1380
|
+
$claimPid = if ($foundPidNew) { $ownerPid } else { $launchedPid }
|
|
1381
|
+
return [ordered]@{
|
|
1382
|
+
pid = $claimPid
|
|
1383
|
+
ownerPid = $ownerPid
|
|
1384
|
+
windowId = $foundEntry.id
|
|
1385
|
+
title = (TruncStr ([string]$cp2.Name) 200)
|
|
1386
|
+
class = [string]$cp2.ClassName
|
|
1387
|
+
appearedMs = [Math]::Round((MsFrom $st), 1)
|
|
1388
|
+
launchedPid = $launchedPid
|
|
1389
|
+
matchedBy = $matchedBy
|
|
1390
|
+
exe = $exe
|
|
1391
|
+
via = $via
|
|
1392
|
+
revision = $foundEntry.revision
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
function Remove-Window($entry) {
|
|
1397
|
+
$refs = @()
|
|
1398
|
+
foreach ($snap in $entry.snapshots) { $refs += $snap.refs }
|
|
1399
|
+
foreach ($rk in $refs) {
|
|
1400
|
+
$r = $script:W.refs.Item($rk)
|
|
1401
|
+
if ($null -ne $r) {
|
|
1402
|
+
# No Marshal.ReleaseComObject here: managed UIA elements are not COM objects
|
|
1403
|
+
# (IsComObject(AutomationElement::RootElement) is False), so the call always threw and an
|
|
1404
|
+
# empty catch swallowed it. GC reclaims the wrappers once the last reference drops.
|
|
1405
|
+
$r.ae = $null
|
|
1406
|
+
$script:W.refs.Remove($rk) | Out-Null
|
|
1407
|
+
}
|
|
1408
|
+
$i = $script:W.refOrder.IndexOf($rk)
|
|
1409
|
+
if ($i -ge 0) { $script:W.refOrder.RemoveAt($i) }
|
|
1410
|
+
$script:W.totalRefs -= 1
|
|
1411
|
+
}
|
|
1412
|
+
$entry.snapshots.Clear()
|
|
1413
|
+
$script:W.winByHwnd.Remove([string]$entry.hwnd) | Out-Null
|
|
1414
|
+
$script:W.windows.Remove($entry.id) | Out-Null
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
function Cmd-CloseWindow($A) {
|
|
1418
|
+
$entry = Window-Entry (StrArg $A 'windowId' '')
|
|
1419
|
+
$timeoutMs = IntArg $A 'timeoutMs' 3000
|
|
1420
|
+
$method = ''
|
|
1421
|
+
$ae = Window-Ae $entry
|
|
1422
|
+
if ($null -eq $ae) {
|
|
1423
|
+
Remove-Window $entry
|
|
1424
|
+
return [ordered]@{ windowId = $entry.id; closed = $true; method = 'already-gone' }
|
|
1425
|
+
}
|
|
1426
|
+
$wp = GetPattern $ae 'Window'
|
|
1427
|
+
if ($null -ne $wp) {
|
|
1428
|
+
try { $wp.Close(); $method = 'windowpattern' } catch { $method = 'windowpattern-threw' }
|
|
1429
|
+
}
|
|
1430
|
+
if ($method -eq '') {
|
|
1431
|
+
try {
|
|
1432
|
+
[void][Native]::PostMessageW([IntPtr]$entry.hwnd, 0x0010, [IntPtr]0, [IntPtr]0)
|
|
1433
|
+
$method = 'postmessage-wm_close'
|
|
1434
|
+
} catch { Err 'action_failed' ('PostMessage WM_CLOSE threw: ' + $_.Exception.Message) }
|
|
1435
|
+
}
|
|
1436
|
+
$st = TickNow
|
|
1437
|
+
$left = BudgetLeftMs
|
|
1438
|
+
$budget = $timeoutMs
|
|
1439
|
+
if ($budget -gt $left) { $budget = [int]$left }
|
|
1440
|
+
$gone = $false
|
|
1441
|
+
$dialogs = New-Object System.Collections.Generic.List[object]
|
|
1442
|
+
while ((TickNow) -lt ($st + ([Int64]$budget * 10000))) {
|
|
1443
|
+
$alive = $false
|
|
1444
|
+
foreach ($w in (RootWindows)) {
|
|
1445
|
+
$h = 0
|
|
1446
|
+
try { $cp = $w.Current; $h = [int]$cp.NativeWindowHandle } catch { continue }
|
|
1447
|
+
if ($h -eq $entry.hwnd) { $alive = $true; continue }
|
|
1448
|
+
if ([int]$cp.ProcessId -eq $entry.pid) {
|
|
1449
|
+
$cn = [string]$cp.ClassName
|
|
1450
|
+
if ($cn -eq '#32770' -or $cn -like '*Dialog*' -or $cn -like '*XamlWindow*') {
|
|
1451
|
+
$known = $false
|
|
1452
|
+
foreach ($d in $dialogs) { if ($d.hwnd -eq $h) { $known = $true } }
|
|
1453
|
+
if (-not $known) {
|
|
1454
|
+
$de = Ensure-Window $h $w
|
|
1455
|
+
$dialogs.Add([ordered]@{ windowId = $de.id; hwnd = $h; class = $cn; title = (TruncStr ([string]$cp.Name) 120) }) | Out-Null
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
if (-not $alive) { $gone = $true; break }
|
|
1461
|
+
Start-Sleep -Milliseconds 120
|
|
1462
|
+
}
|
|
1463
|
+
$r = [ordered]@{
|
|
1464
|
+
windowId = $entry.id
|
|
1465
|
+
method = $method
|
|
1466
|
+
closed = $gone
|
|
1467
|
+
pidStillRunning = $false
|
|
1468
|
+
waitedMs = (MsFrom $st)
|
|
1469
|
+
dialogAppeared = ($dialogs.Count -gt 0)
|
|
1470
|
+
}
|
|
1471
|
+
if (-not $gone) {
|
|
1472
|
+
try { $null = [System.Diagnostics.Process]::GetProcessById($entry.pid); $r['pidStillRunning'] = $true } catch { }
|
|
1473
|
+
if ($dialogs.Count -gt 0) {
|
|
1474
|
+
$r['dialogs'] = $dialogs
|
|
1475
|
+
$r['detail'] = 'a modal dialog is blocking the close; resolve it with find_text + act (the worker never clicks on its own)'
|
|
1476
|
+
} else {
|
|
1477
|
+
$r['detail'] = 'the window ignored the close request'
|
|
1478
|
+
}
|
|
1479
|
+
} else {
|
|
1480
|
+
Remove-Window $entry
|
|
1481
|
+
}
|
|
1482
|
+
return $r
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
|