dsh-windows-parallel-mcp 0.0.1 → 0.1.1

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.
@@ -0,0 +1,313 @@
1
+ # engine.ps1 -- the only place where a decision becomes a syscall.
2
+ #
3
+ # One entry point, Invoke-WpmAction, and it always returns a result object rather than throwing on
4
+ # a refusal: 'refused' is a normal outcome of this product, not an error path, and R3.2 requires
5
+ # the reason to survive to the caller. Every result carries which channel ran, which tier it cost,
6
+ # whether the owner's focus was taken and given back, and how long the whole thing took.
7
+ #
8
+ # ORDER OF OPERATIONS IS THE SAFETY DESIGN:
9
+ # 1. measure the target's doors (facts; a target with no facts is refused)
10
+ # 2. decide (pure table; pause/elevation/integrity first)
11
+ # 3. if the tier costs a flash: capture the focus table BEFORE touching anything
12
+ # 4. act through the cheapest available door
13
+ # 5. if a flash was taken: restore, once, through the restore table
14
+ # Nothing in step 4 can run for a target whose step 2 said refuse, and nothing in step 5 can pull
15
+ # the focus from a window the owner chose.
16
+
17
+ Set-StrictMode -Version 2.0
18
+ $script:WpmEngineRoot = $PSScriptRoot
19
+ . (Join-Path $PSScriptRoot 'decide.ps1')
20
+ . (Join-Path $PSScriptRoot 'win.ps1')
21
+
22
+ # THE PAUSE FLAG LIVES IN [WpmCtl], a static holder -- not in a script variable. The global hotkey
23
+ # (Ctrl+Alt+Q, overlay.ps1) flips it from the overlay thread while actions read it on the main
24
+ # thread; two copies across threads is the bug pattern this repo keeps meeting, and a script-scope
25
+ # variable is exactly that second copy. $script:WpmPauseReason stays here because it is only ever
26
+ # set through Set-WpmPaused, which runs on the main thread.
27
+ $script:WpmPauseReason = ''
28
+
29
+ function Set-WpmPaused([bool]$On, [string]$Reason = 'owner') {
30
+ [WpmCtl]::Paused = $On
31
+ $script:WpmPauseReason = if ($On) { $Reason } else { '' }
32
+ }
33
+
34
+ function Get-WpmStatus {
35
+ $entry = Get-WpmFocusEntry
36
+ return @{
37
+ paused = [bool][WpmCtl]::Paused
38
+ pauseReason = $script:WpmPauseReason
39
+ foreground = $entry.fgHwnd
40
+ foregroundPid = $entry.fgPid
41
+ focusControl = $entry.focusHwnd
42
+ lastInputAgeMs = $entry.lastInputAgeMs
43
+ # The control board travels with status: whether the owner's overlay/hotkey surface is up, and
44
+ # whether the hotkey actually registered. A silent 'overlay off' would make the README's
45
+ # Ctrl+Alt+Q promise untrue with no way to notice.
46
+ overlayRunning = [bool][WpmCtl]::OverlayOn
47
+ hotkeyRegistered = [bool][WpmCtl]::HotkeyOk
48
+ hotkeyLabel = [string][WpmCtl]::HotkeyLabel
49
+ overlayReason = [string][WpmCtl]::Reason
50
+ dpiAware = [bool]$script:WpmDpiAware
51
+ stance = 'no physical injection; no forged-Alt foreground trick'
52
+ }
53
+ }
54
+
55
+ function Get-WpmWindowList {
56
+ # Read-only enumeration for the model to choose a target by hwnd. Only visible, titled, non-cloaked
57
+ # windows are listed: a list padded with invisible helper windows makes target selection guesswork.
58
+ $acc = @()
59
+ $cb = [WpmWin+EnumProc] {
60
+ param([IntPtr]$h, [IntPtr]$l)
61
+ if (-not [WpmWin]::IsWindowVisible($h)) { return $true }
62
+ $t = [WpmWin]::Txt($h)
63
+ if (-not $t) { return $true }
64
+ if ([WpmWin]::IsIconic($h)) { return $true }
65
+ $r = New-Object 'WpmWin+RECT'
66
+ [void][WpmWin]::GetWindowRect($h, [ref]$r)
67
+ $script:WpmEnumAcc += [pscustomobject]@{
68
+ hwnd = $h.ToInt64().ToString()
69
+ title = $t
70
+ cls = [WpmWin]::Cls($h)
71
+ pid = [WpmWin]::PidOf($h)
72
+ rect = "$($r.Left),$($r.Top),$($r.Right),$($r.Bottom)"
73
+ }
74
+ return $true
75
+ }
76
+ $script:WpmEnumAcc = @()
77
+ [void][WpmWin]::EnumWindows($cb, [IntPtr]::Zero)
78
+ $out = $script:WpmEnumAcc
79
+ $script:WpmEnumAcc = $null
80
+ return $out
81
+ }
82
+
83
+ function Resolve-WpmChildAtPoint([IntPtr]$Hwnd, [int]$X, [int]$Y) {
84
+ # Which child HWND actually sits under a screen point. Uses ChildWindowFromPointEx (the same
85
+ # approach the competitor uses) instead of trusting a fixed child index: index order is not a
86
+ # contract, and clicking the wrong child is indistinguishable from clicking the right one until
87
+ # the app does something else.
88
+ $p = New-Object 'WpmWin+POINT'
89
+ $p.X = $X; $p.Y = $Y
90
+ $hit = [WpmWin]::WindowFromPoint($p)
91
+ if ($hit -eq [IntPtr]::Zero) { return [IntPtr]::Zero }
92
+ $root = [WpmWin]::Root($hit)
93
+ if ($root -ne $Hwnd) {
94
+ # The point belongs to some other top-level window; acting there would be acting on a window
95
+ # the caller did not name.
96
+ return [IntPtr]::Zero
97
+ }
98
+ return $hit
99
+ }
100
+
101
+ function Invoke-WpmAction {
102
+ param(
103
+ [Parameter(Mandatory)][string]$Hwnd,
104
+ [Parameter(Mandatory)][ValidateSet('click', 'type', 'focus', 'status')][string]$Action,
105
+ [int]$X = -1,
106
+ [int]$Y = -1,
107
+ [string]$Text = '',
108
+ [string]$ElementName = '',
109
+ [switch]$Replace,
110
+ [int]$SettleMs = 350
111
+ )
112
+ $started = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
113
+ $h = [IntPtr][int64]$Hwnd
114
+ $result = @{
115
+ ok = $false; action = $Action; hwnd = $Hwnd; channel = ''; tier = ''
116
+ refusal = ''; reason = ''; detail = ''; latencyMs = 0
117
+ focusTaken = 'false'; restoreOutcome = ''; restoreSetFg = ''; restoreJoined = ''
118
+ effect = 'unverified'
119
+ }
120
+
121
+ # A QUERY IS NOT AN ACTION, and this branch is early on purpose. It used to sit inside the action
122
+ # chain, where 'status' fell through to the UIA branch and INVOKED the pattern it found -- a call
123
+ # whose entire purpose is to report state would click a control. It is also placed before the
124
+ # target check because a query has no target: 'what holds the focus' is answerable whatever the
125
+ # caller passed, and refusing it for an unreachable window would be a query lying about why it
126
+ # is empty. (Found by reading the branch order while writing the refusal cases, not by a failing
127
+ # run -- the assertion in test/refusals-test.ps1 pins the fixed behaviour, it did not catch it.)
128
+ if ($Action -eq 'status') {
129
+ $st = Get-WpmStatus
130
+ $result.ok = $true
131
+ $result.channel = 'none'; $result.tier = 'none'
132
+ $result.detail = 'status: query only, no action taken'
133
+ $result.foreground = $st.foreground
134
+ $result.foregroundPid = $st.foregroundPid
135
+ $result.focusControl = $st.focusControl
136
+ $result.lastInputAgeMs = $st.lastInputAgeMs
137
+ $result.paused = $st.paused
138
+ $result.stance = $st.stance
139
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
140
+ return $result
141
+ }
142
+
143
+ if (-not [WpmWin]::IsWindow($h)) {
144
+ $result.refusal = 'no_hwnd'; $result.reason = 'the hwnd does not identify a live window'
145
+ return $result
146
+ }
147
+
148
+ $probe = Get-WpmFacts -Hwnd $h -Action $Action -ElementName $ElementName
149
+ $facts = $probe.facts
150
+ $facts.paused = [bool][WpmCtl]::Paused
151
+ if ($ElementName) {
152
+ # A named control cannot be addressed through a window message: the message tiers take
153
+ # coordinates or a child HWND, and "the Save button" is neither. Suppressing the door here is
154
+ # what makes 'click the named button' honest -- claiming the quiet tier while actually having
155
+ # to raise the window would report the cheap tier for the expensive action.
156
+ $facts.messageDoor = $false
157
+ }
158
+ $decision = Get-WpmChannelDecision $facts
159
+
160
+ $result.channel = $decision.channel; $result.tier = $decision.tier
161
+ $result.family = $probe.family; $result.cls = $probe.cls
162
+ if ($decision.channel -eq 'refuse') {
163
+ $result.refusal = $decision.refusal; $result.reason = $decision.reason
164
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
165
+ return $result
166
+ }
167
+
168
+ # Capture the focus table BEFORE the action when the tier may cost a flash. For the quiet tier it
169
+ # is still captured, because 'the quiet channel did not take focus' is a claim that needs a
170
+ # before-value to be falsifiable.
171
+ $entry = Get-WpmFocusEntry
172
+ $raisedHwnd = ''
173
+ $tAct = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
174
+
175
+ try {
176
+ if ($decision.channel -eq 'message') {
177
+ if ($Action -eq 'type') {
178
+ # The door kind is decided ONCE, in the probe (win.ps1), and consumed here by kind.
179
+ # This path used to re-match class names with its own copy of the pattern -- and that copy
180
+ # carried the same 'Edit' vs 'WindowsForms10.EDIT.*' bug, so a fix in one place would have
181
+ # silently left the other broken. One matcher, one truth.
182
+ $target = $null
183
+ foreach ($d in $probe.doorHandles) {
184
+ if ($d.kind -eq 'text') { $target = [IntPtr]$d.hwnd; break }
185
+ }
186
+ if (-not $target) {
187
+ $result.refusal = 'unreachable'; $result.reason = 'no editable child window for the message tier'
188
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
189
+ return $result
190
+ }
191
+ $r = [WpmWin]::MessageText($target, $Text, [bool]$Replace)
192
+ $result.detail = "msg=$r child=$($target.ToInt64())"
193
+ $result.effect = 'reported-by-send'
194
+ } elseif ($Action -eq 'click') {
195
+ if ($X -lt 0 -or $Y -lt 0) {
196
+ $result.refusal = 'unreachable'; $result.reason = 'click needs screen coordinates'
197
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
198
+ return $result
199
+ }
200
+ $child = Resolve-WpmChildAtPoint $h $X $Y
201
+ if ($child -eq [IntPtr]::Zero) {
202
+ $result.refusal = 'unreachable'; $result.reason = 'no child window of the target sits under that point'
203
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
204
+ return $result
205
+ }
206
+ $r = [WpmWin]::MessageClick($child, $X, $Y)
207
+ $result.detail = "msg=$r child=$($child.ToInt64())"
208
+ $result.effect = 'reported-by-send'
209
+ }
210
+ } elseif ($Action -eq 'focus') {
211
+ # Focusing a control is a real operation an agent needs (type into a field, then read it).
212
+ # It is also the one action that MUST change keyboard focus, so it is the honest way to
213
+ # exercise the bounded-flash path: an Invoke can complete without activating anything, but
214
+ # SetFocus cannot -- it transfers focus by definition.
215
+ if ($decision.channel -ne 'uia') {
216
+ $result.refusal = 'unreachable'; $result.reason = 'focus requires a UIA element; the message tier cannot set keyboard focus'
217
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
218
+ return $result
219
+ }
220
+ $el = $probe.uiaElement
221
+ if (-not $el) {
222
+ $result.refusal = 'unreachable'; $result.reason = 'no element to focus'
223
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
224
+ return $result
225
+ }
226
+ $el.SetFocus()
227
+ $result.detail = 'uia=SetFocus'
228
+ $result.effect = 'reported-by-pattern'
229
+ } elseif ($decision.channel -eq 'uia') {
230
+ $el = $probe.uiaElement
231
+ if (-not $el) {
232
+ $result.refusal = 'unreachable'; $result.reason = 'pattern was reported but no element could be re-obtained'
233
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
234
+ return $result
235
+ }
236
+ $pats = Get-WpmUiaCached
237
+ $kind = $facts.patternKind
238
+ if ($kind -eq 'invoke') {
239
+ $pat = $el.GetCurrentPattern($pats.invoke)
240
+ $pat.Invoke()
241
+ } elseif ($kind -eq 'value') {
242
+ $pat = $el.GetCurrentPattern($pats.value)
243
+ $pat.SetValue($(if ($Replace) { $Text } else { [string]$pat.Current.Value + $Text }))
244
+ } elseif ($kind -eq 'toggle') {
245
+ $pat = $el.GetCurrentPattern($pats.toggle); $pat.Toggle()
246
+ } elseif ($kind -eq 'select') {
247
+ $pat = $el.GetCurrentPattern($pats.select); $pat.Select()
248
+ } elseif ($kind -eq 'legacy') {
249
+ $pat = $el.GetCurrentPattern($pats.legacy); $pat.SetValue($Text)
250
+ }
251
+ $result.detail = "uia=$kind"
252
+ $result.effect = 'reported-by-pattern'
253
+ }
254
+ } catch {
255
+ $result.refusal = 'action_failed'
256
+ $result.reason = 'the channel call threw: ' + $_.Exception.Message
257
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
258
+ }
259
+
260
+ Start-Sleep -Milliseconds $SettleMs
261
+
262
+ # Did the action actually take the owner's focus? Measured, not assumed -- the quiet tier is
263
+ # expected to say no and the flash tier yes, and a run where both say the same thing is a broken
264
+ # instrument rather than a good result.
265
+ #
266
+ # WHICH window now holds the foreground matters, and the first version got it wrong: it recorded
267
+ # whatever held the foreground as "the window we raised". When an action causes the TARGET APP to
268
+ # open a dialog, that dialog is what comes forward -- so it looked like our own raised window and
269
+ # was promptly restored away, shutting the dialog's focus the agent had just asked for. Only the
270
+ # target itself counts as ours; anything else is the app's own window or a third party's, and it
271
+ # is classified, never reversed.
272
+ $nowFg = [WpmWin]::Fg()
273
+ $targetStr = $h.ToInt64().ToString()
274
+ $raisedHwnd = ''
275
+ $raisedElsewhere = ''
276
+ if ($nowFg -ne $entry.fgHwnd) {
277
+ $result.focusTaken = 'true'
278
+ if ($nowFg -eq $targetStr) { $raisedHwnd = $nowFg } else { $raisedElsewhere = $nowFg }
279
+ }
280
+ $result.raisedOurs = ($raisedHwnd -ne '').ToString().ToLower()
281
+ if ($raisedElsewhere) { $result.raisedElsewhere = $raisedElsewhere }
282
+
283
+ if ($decision.needsRestore) {
284
+ $res = Restore-WpmFocus -Entry $entry -RaisedHwnd $raisedHwnd -RaisedElsewhere $raisedElsewhere `
285
+ -TargetPid ($probe.pid.ToString())
286
+ $result.restoreOutcome = $res.outcome
287
+ $result.restoreReason = $res.reason
288
+ $result.restoreSetFg = $res.setFg
289
+ $result.restoreJoined = $res.joined
290
+ $result.fgAfterRestore = $res.fgAfter
291
+ # A restore the table authorised but the OS refused is a named failure, not a success with a
292
+ # caveat: the owner is left in a window they did not choose, so the caller must surface it.
293
+ # The span the owner actually pays: from the moment the action was issued to the moment the
294
+ # focus was back. Reported separately from end-to-end latency because latency includes the
295
+ # door probe and the settle wait, and a 'budget' quoted from latency would overstate the
296
+ # disturbance by an order of magnitude.
297
+ # Only meaningful when focus was actually taken: reporting a 'flash span' for an action that
298
+ # never disturbed the owner would put a scary number next to a non-event.
299
+ if ($result.focusTaken -eq 'true') {
300
+ $result.flashMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $tAct
301
+ }
302
+ if ($res.outcome -eq 'restore' -and $res.setFg -ne 'true') {
303
+ $result.refusal = 'restore_failed'
304
+ $result.reason = 'the OS refused to return the foreground; the owner is still in the wrong window'
305
+ }
306
+ }
307
+
308
+ $result.ok = ($result.refusal -eq '')
309
+ $result.latencyMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $started
310
+ $result.fgBefore = $entry.fgHwnd
311
+ $result.fgNow = [WpmWin]::Fg()
312
+ return $result
313
+ }
@@ -0,0 +1,368 @@
1
+ # overlay.ps1 -- the product's visible surface: an AI marker that never takes the foreground,
2
+ # and a global hotkey that pauses the engine server-side. (task_54)
3
+ #
4
+ # WHAT THIS IS FOR. Two README claims need a real surface:
5
+ # * "AI cursor is a click-through topmost overlay, not a system cursor" (R2.4) -- the trio
6
+ # WS_EX_TOPMOST + WS_EX_NOACTIVATE + WS_EX_TRANSPARENT must exist and be MEASURED: ex-style
7
+ # read-back, GetForegroundWindow unchanged across Show(), WindowFromPoint passing through the
8
+ # marker (test/overlay-test.ps1 does all three).
9
+ # * "the owner pauses explicitly and the SERVER refuses" (R2.5) -- one global key from ANY window
10
+ # flips the engine's own pause flag. The flag lives in [WpmCtl] (a static, process-wide holder),
11
+ # not in a script variable: the hotkey fires on the overlay's thread while actions run on the
12
+ # worker's main thread, and two copies of one switch is the bug pattern this repo keeps meeting.
13
+ #
14
+ # WHY A RUNSPACE AND NOT A RAW .NET THREAD. Measured, three times over, before this shape won:
15
+ # * [System.Threading.Thread]::new($scriptblock) -- a PowerShell scriptblock is NOT a
16
+ # ParameterizedThreadStart; the cast produces a delegate that dies at invoke time and the
17
+ # thread runs NOTHING (reason stayed empty, hwnd stayed 0, exit code 2).
18
+ # * SetApartmentState on a Thread object -- returns false here; the apartment never sticks.
19
+ # * CreateRunspace([ApartmentState]) -- no such overload on PS 5.1.
20
+ # What works (verified in .tmp before it was deleted): InitialSessionState.CreateDefault2 ->
21
+ # CreateRunspace($iss) -> $rs.ApartmentState = STA -> Open. The runspace owns its pipeline thread,
22
+ # WPF shows a window on it, and types compiled by the main thread ([WpmCtl]/[WpmWin]) are
23
+ # process-wide and reachable. The body therefore lives in a here-string compiled INSIDE the
24
+ # runspace -- no cross-thread scriptblock capture at all, which kills the whole GetNewClosure
25
+ # hazard class in this file.
26
+ #
27
+ # THREADING RULE (unchanged): the WPF window is touched only on its own thread. The main thread
28
+ # goes through [WpmCtl]::Dispatcher.Invoke.
29
+
30
+ Set-StrictMode -Version 2.0
31
+
32
+ if (-not ('WpmCtl' -as [type])) {
33
+ . (Join-Path $PSScriptRoot 'win.ps1')
34
+ }
35
+
36
+ # IDEMPOTENT INITIALISATION. This file is dot-sourced again on every `overlay`/`marker` request
37
+ # (worker.ps1 does that so a fresh process can answer them), and the first version reset the
38
+ # runspace/handle to $null at the top of every load. The overlay kept running -- the WPF thread
39
+ # does not care about our variables -- but the caller lost the handle it needs to EndInvoke, so
40
+ # Stop-WpmOverlay could not see the pipeline end and had to fall back to the hard bound. Measured
41
+ # cost before this guard: `marker` 1844ms and `overlay off` 2618ms over the real worker protocol
42
+ # (.tmp/worker-overlay.mjs), against a few ms for the same calls in one dot-sourced process.
43
+ if (-not (Get-Variable -Name WpmOvRunspace -Scope Script -ErrorAction SilentlyContinue)) {
44
+ $script:WpmOvRunspace = $null
45
+ $script:WpmOvPowerShell = $null
46
+ $script:WpmOvHandle = $null
47
+ }
48
+ $script:WpmHotkeyId = 0xB001
49
+
50
+ # The documented chord comes first, then fallbacks -- because the documented one is not always
51
+ # available. Measured on this machine (scripts/hotkey-availability.ps1): Ctrl+Alt+Q is TAKEN by
52
+ # another app (Win32 1409, ERROR_HOTKEY_ALREADY_REGISTERED) while all seven other candidates are
53
+ # free. Shipping only Ctrl+Alt+Q means the pause switch silently does not exist on some desktops,
54
+ # and the alternative -- one global key quietly not working -- is the failure mode R2.5 forbids.
55
+ # Whatever registers is written to [WpmCtl]::HotkeyLabel and surfaced by wpm_status.
56
+ $script:WpmHotkeyChords = @(
57
+ @{ label = 'Ctrl+Alt+Q'; mods = 0x0003; vk = 0x51 }, # MOD_CONTROL|MOD_ALT
58
+ @{ label = 'Ctrl+Alt+W'; mods = 0x0003; vk = 0x57 },
59
+ @{ label = 'Ctrl+Alt+P'; mods = 0x0003; vk = 0x50 },
60
+ @{ label = 'Ctrl+Alt+Space'; mods = 0x0003; vk = 0x20 },
61
+ @{ label = 'Ctrl+Shift+Q'; mods = 0x0006; vk = 0x51 }, # MOD_CONTROL|MOD_SHIFT
62
+ @{ label = 'Ctrl+Alt+Shift+Q'; mods = 0x0007; vk = 0x51 }
63
+ )
64
+
65
+ $script:WpmOverlayBody = @'
66
+ param([int]$MarkerSize, [int]$HotkeyId, [object[]]$Chords)
67
+ try {
68
+ Add-Type -AssemblyName PresentationFramework
69
+ Add-Type -AssemblyName PresentationCore
70
+ Add-Type -AssemblyName WindowsBase
71
+
72
+ $win = [System.Windows.Window]::new()
73
+ $win.Title = 'WpmOverlay'
74
+ $win.WindowStyle = [System.Windows.WindowStyle]::None
75
+ $win.AllowsTransparency = $true
76
+ $win.ShowActivated = $false # WPF-side half of NOACTIVATE: Show() must not steal foreground
77
+ $win.Focusable = $false
78
+ $win.IsHitTestVisible = $false
79
+ $win.ResizeMode = [System.Windows.ResizeMode]::NoResize
80
+ $win.Width = [double]$MarkerSize
81
+ $win.Height = [double]$MarkerSize
82
+ $win.Left = -2000.0
83
+ $win.Top = -2000.0
84
+ $win.WindowStartupLocation = [System.Windows.WindowStartupLocation]::Manual
85
+ $win.ShowInTaskbar = $false
86
+ $win.Topmost = $true
87
+ $win.Opacity = 0.85
88
+
89
+ $ring = [System.Windows.Shapes.Ellipse]::new()
90
+ $ring.Width = [double]$MarkerSize
91
+ $ring.Height = [double]$MarkerSize
92
+ $ring.Stroke = [System.Windows.Media.Brushes]::DeepSkyBlue
93
+ $ring.StrokeThickness = 2.0
94
+ $ring.Fill = [System.Windows.Media.SolidColorBrush]::new(
95
+ [System.Windows.Media.Color]::FromArgb(60, 0, 191, 255))
96
+ $grid = [System.Windows.Controls.Grid]::new()
97
+ [void]$grid.Children.Add($ring)
98
+ $win.Content = $grid
99
+
100
+ $win.Show()
101
+ $hwnd = (New-Object System.Windows.Interop.WindowInteropHelper($win)).Handle
102
+ [WpmCtl]::OverlayHwnd = [int64]$hwnd
103
+
104
+ # The trio, applied once the HWND exists. TOPMOST is also WPF-side, but the measured promise is
105
+ # the ex-style value itself, so all four bits are set explicitly and read back by the test.
106
+ $bits = [WpmWin]::WS_EX_TOPMOST -bor [WpmWin]::WS_EX_NOACTIVATE -bor
107
+ [WpmWin]::WS_EX_TRANSPARENT -bor [WpmWin]::WS_EX_LAYERED
108
+ [void][WpmWin]::AddExStyles($hwnd, $bits)
109
+
110
+ # The marker's PHYSICAL size, read once from Win32. Placement is done with SetWindowPos (physical
111
+ # units) because WPF's own coordinates are device independent and did not agree with this desktop
112
+ # (measured: marker at (303,263) for a target of (470,410) at 150%). Reading the real rect once is
113
+ # cheaper and more honest than assuming MarkerSize is the physical edge length.
114
+ $rc0 = New-Object 'WpmWin+RECT'
115
+ [void][WpmWin]::GetWindowRect([IntPtr]$hwnd, [ref]$rc0)
116
+ $script:OvPhysW = [int]($rc0.Right - $rc0.Left)
117
+ $script:OvPhysH = [int]($rc0.Bottom - $rc0.Top)
118
+ if ($script:OvPhysW -le 0) { $script:OvPhysW = $MarkerSize }
119
+ if ($script:OvPhysH -le 0) { $script:OvPhysH = $MarkerSize }
120
+
121
+ $hkOk = $false
122
+ $hkLabel = ''
123
+ $tried = @()
124
+ foreach ($c in $Chords) {
125
+ $label = [string]$c.label
126
+ $tried += $label
127
+ if ([WpmWin]::RegisterHotKey($hwnd, $HotkeyId, [uint32]$c.mods, [uint32]$c.vk)) {
128
+ $hkOk = $true
129
+ $hkLabel = $label
130
+ break
131
+ }
132
+ }
133
+ [WpmCtl]::HotkeyOk = [bool]$hkOk
134
+ [WpmCtl]::HotkeyLabel = $hkLabel
135
+ if (-not $hkOk) {
136
+ [WpmCtl]::Reason = 'RegisterHotKey false for every candidate (' + ($tried -join ', ') + '); the settings switch still pauses'
137
+ } elseif ($hkLabel -ne 'Ctrl+Alt+Q') {
138
+ # Reported, not hidden: the promise in the README is the first chord, and when the desktop
139
+ # already owns it this is the only place the owner can learn which key actually works.
140
+ [WpmCtl]::Reason = "Ctrl+Alt+Q is owned by another app (RegisterHotKey 1409); registered $hkLabel instead"
141
+ }
142
+
143
+ # WM_HOTKEY -> flip the ONE pause flag. The owner's switch: server-side refusal, not a hint.
144
+ $src = [System.Windows.Interop.HwndSource]::FromHwnd($hwnd)
145
+ # No DIP matrix is kept here on purpose. Converting to device-independent units is exactly the
146
+ # step that put the marker at (303,263) for a target of (470,410): this process's idea of the
147
+ # scale and the window's actual rendering disagreed. Placement is SetWindowPos in physical pixels
148
+ # (see the pump), so there is nothing to convert and no second coordinate system to get wrong.
149
+ if ($src) {
150
+ $hook = [System.Windows.Interop.HwndSourceHook] {
151
+ param($h, $m, $wp, $lp, [ref]$handled)
152
+ if ($m -eq [WpmWin]::WM_HOTKEY -and [int]$wp -eq $HotkeyId) {
153
+ [WpmCtl]::Paused = -not [WpmCtl]::Paused
154
+ $handled.Value = $true
155
+ return [IntPtr]::Zero
156
+ }
157
+ $handled.Value = $false
158
+ return [IntPtr]::Zero
159
+ }
160
+ [void]$src.AddHook($hook)
161
+ }
162
+
163
+ # THE MARKER IS DRIVEN FROM THIS THREAD, ON A PUMP -- not by cross-thread Invokes.
164
+ #
165
+ # Why: Set-WpmOverlayMarker used to marshal a PowerShell scriptblock onto this thread with
166
+ # Dispatcher.Invoke. Measured (.tmp/ov-seg.log): that call took 1818ms and once never returned.
167
+ # The delegate is a scriptblock and this thread is inside Dispatcher.Run(), so the engine has to
168
+ # reach a runspace that is already busy -- a deadlock with a timeout, not a slow call. Writing
169
+ # three static fields costs nothing; this pump (a DispatcherTimer, which runs on THIS thread the
170
+ # same way the hotkey hook does) applies them at 16ms.
171
+ #
172
+ # Auto-hide is measured from the LAST placement, so the deadline is re-armed per request: a
173
+ # free-running 1.5s timer kicks the marker off screen at an arbitrary phase, which can be the
174
+ # same millisecond it was placed (measured in .tmp/ov-hide.log: -2000 within 400ms of placing).
175
+ # That version passed a naive "is it hidden" glance while breaking the promise in the other
176
+ # direction -- it never stayed visible long enough to be pointed at.
177
+ $script:OvSeenSeq = [WpmCtl]::MarkerSeq
178
+ $script:OvHideAt = [DateTime]::MinValue
179
+ $pump = [System.Windows.Threading.DispatcherTimer]::new()
180
+ $pump.Interval = [TimeSpan]::FromMilliseconds(16)
181
+ $pump.Add_Tick({
182
+ $w = [WpmCtl]::Window
183
+ if (-not $w -or -not [WpmCtl]::OverlayOn) { return }
184
+ $seq = [WpmCtl]::MarkerSeq
185
+ if ($seq -ne $script:OvSeenSeq) {
186
+ $script:OvSeenSeq = $seq
187
+ if ([WpmCtl]::MarkerHide) {
188
+ [void][WpmWin]::MoveNoActivate([IntPtr][WpmCtl]::OverlayHwnd, -2000, -2000, 1, 1)
189
+ $script:OvHideAt = [DateTime]::MinValue
190
+ } else {
191
+ $mx = [WpmCtl]::MarkerX
192
+ $my = [WpmCtl]::MarkerY
193
+ if ($mx -ge 0 -and $my -ge 0) {
194
+ $pw = [int]$script:OvPhysW
195
+ $ph = [int]$script:OvPhysH
196
+ [void][WpmWin]::MoveNoActivate([IntPtr][WpmCtl]::OverlayHwnd, $mx - [int][Math]::Floor($pw / 2), $my - [int][Math]::Floor($ph / 2), $pw, $ph)
197
+ $script:OvHideAt = [DateTime]::UtcNow.AddMilliseconds(1500)
198
+ }
199
+ }
200
+ } elseif ($script:OvHideAt -ne [DateTime]::MinValue -and [DateTime]::UtcNow -ge $script:OvHideAt) {
201
+ [void][WpmWin]::MoveNoActivate([IntPtr][WpmCtl]::OverlayHwnd, -2000, -2000, 1, 1)
202
+ $script:OvHideAt = [DateTime]::MinValue
203
+ }
204
+ })
205
+ $pump.Start()
206
+
207
+ [WpmCtl]::Dispatcher = [System.Windows.Threading.Dispatcher]::CurrentDispatcher
208
+ [WpmCtl]::Window = $win
209
+ [WpmCtl]::Timer = $pump
210
+ [WpmCtl]::OverlayOn = $true
211
+
212
+ # Block this runspace thread pumping the dispatcher until the window closes (Stop-WpmOverlay).
213
+ [System.Windows.Threading.Dispatcher]::Run()
214
+ } catch {
215
+ [WpmCtl]::Reason = $_.Exception.Message
216
+ } finally {
217
+ [WpmCtl]::OverlayOn = $false
218
+ [WpmCtl]::HotkeyOk = $false
219
+ [WpmCtl]::HotkeyLabel = ''
220
+ [WpmCtl]::Window = $null
221
+ [WpmCtl]::Timer = $null
222
+ [WpmCtl]::Dispatcher = $null
223
+ [WpmCtl]::OverlayHwnd = 0
224
+ }
225
+ '@
226
+
227
+ function Start-WpmOverlay {
228
+ param([int]$MarkerSize = 22)
229
+ if ($script:WpmOvRunspace -and $script:WpmOvRunspace.RunspaceStateInfo.State -eq 'Opened') {
230
+ return @{ started = $false; reason = 'already running' }
231
+ }
232
+ [WpmCtl]::Reason = ''
233
+ $iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault2()
234
+ $rs = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($iss)
235
+ $rs.ApartmentState = [System.Threading.ApartmentState]::STA
236
+ $rs.ThreadOptions = [System.Management.Automation.Runspaces.PSThreadOptions]::Default
237
+ $rs.Open()
238
+ if ($rs.RunspaceStateInfo.State -ne 'Opened') {
239
+ return @{ started = $false; reason = "runspace failed to open: $($rs.RunspaceStateInfo)" }
240
+ }
241
+ $ps = [PowerShell]::Create()
242
+ $ps.Runspace = $rs
243
+ [void]$ps.AddScript($script:WpmOverlayBody).AddArgument($MarkerSize).AddArgument($script:WpmHotkeyId).AddArgument($script:WpmHotkeyChords)
244
+ $script:WpmOvHandle = $ps.BeginInvoke()
245
+ $script:WpmOvRunspace = $rs
246
+ $script:WpmOvPowerShell = $ps
247
+ return @{ started = $true; runspace = [string]$rs.Id }
248
+ }
249
+
250
+ function Get-WpmOverlayState {
251
+ param([int]$WaitMs = 2500)
252
+ $deadline = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + $WaitMs
253
+ while ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -lt $deadline -and [WpmCtl]::OverlayHwnd -eq 0) {
254
+ Start-Sleep -Milliseconds 100
255
+ }
256
+ $hwnd = [WpmCtl]::OverlayHwnd
257
+ $ex = 0
258
+ if ($hwnd -ne 0) { $ex = [WpmWin]::GetWindowLong([IntPtr]$hwnd, [WpmWin]::GWL_EXSTYLE) }
259
+ return @{
260
+ running = [bool][WpmCtl]::OverlayOn
261
+ hwnd = [string]$hwnd
262
+ hotkeyRegistered = [bool][WpmCtl]::HotkeyOk
263
+ hotkeyLabel = [string][WpmCtl]::HotkeyLabel
264
+ paused = [bool][WpmCtl]::Paused
265
+ reason = [string][WpmCtl]::Reason
266
+ exStyle = '0x{0:X8}' -f $ex
267
+ topmost = [bool]($ex -band [WpmWin]::WS_EX_TOPMOST)
268
+ noActivate = [bool]($ex -band [WpmWin]::WS_EX_NOACTIVATE)
269
+ transparent = [bool]($ex -band [WpmWin]::WS_EX_TRANSPARENT)
270
+ foregroundNow = [WpmWin]::Fg()
271
+ }
272
+ }
273
+
274
+ function Set-WpmOverlayMarker {
275
+ # A REQUEST, NOT AN ACTION. The fields are written here and applied by the overlay's own pump;
276
+ # nothing is marshalled across threads. Returns as soon as the request is posted (sub-millisecond),
277
+ # which is the property that matters: this is called after every successful action.
278
+ param([int]$X, [int]$Y, [switch]$Hide)
279
+ if (-not [WpmCtl]::OverlayOn -or [WpmCtl]::OverlayHwnd -eq 0) {
280
+ return @{ ok = $false; reason = 'overlay not running' }
281
+ }
282
+ [WpmCtl]::MarkerX = $X
283
+ [WpmCtl]::MarkerY = $Y
284
+ [WpmCtl]::MarkerHide = [bool]$Hide
285
+ [WpmCtl]::MarkerSeq = [WpmCtl]::MarkerSeq + 1
286
+ return @{ ok = $true; x = $X; y = $Y; hidden = [bool]$Hide }
287
+ }
288
+
289
+ function Get-WpmOverlayMarker {
290
+ # Read the marker's REAL on-screen rect with GetWindowRect -- a Win32 call that is safe from any
291
+ # thread. The previous version read WPF's Window.Left through Dispatcher.Invoke (1818ms, see the
292
+ # pump comment in the body) and, before that, read the property straight off the wrong thread,
293
+ # which is a DispatcherObject.VerifyAccess violation rather than a measurement.
294
+ $hwnd = [WpmCtl]::OverlayHwnd
295
+ if ($hwnd -eq 0) {
296
+ return @{ ok = $false; reason = 'overlay not running'; left = 0.0; top = 0.0; offscreen = $true }
297
+ }
298
+ $rc = New-Object 'WpmWin+RECT'
299
+ if (-not [WpmWin]::GetWindowRect([IntPtr]$hwnd, [ref]$rc)) {
300
+ $err = [Runtime.InteropServices.Marshal]::GetLastWin32Error()
301
+ return @{ ok = $false; reason = "GetWindowRect failed win32=$err"; left = 0.0; top = 0.0; offscreen = $true }
302
+ }
303
+ $left = [double]$rc.Left
304
+ return @{
305
+ ok = $true
306
+ reason = ''
307
+ left = $left
308
+ top = [double]$rc.Top
309
+ width = [int]($rc.Right - $rc.Left)
310
+ height = [int]($rc.Bottom - $rc.Top)
311
+ offscreen = ($left -lt -1000.0)
312
+ }
313
+ }
314
+
315
+ function Stop-WpmOverlay {
316
+ # TEARDOWN IS A WINDOW MESSAGE, NOT A MARSHALLED SCRIPTBLOCK -- the same lesson as the pump.
317
+ # First version: $d.Invoke(...) closing the window never returned (the runspace thread is parked
318
+ # in Dispatcher.Run(); .tmp/ov-step.log shows the trace stopping right there). Second version
319
+ # posted the same scriptblock with BeginInvoke, which returned immediately but took ~1.8s or more
320
+ # to actually run, so `overlay off` measured 2618-3654ms over the worker protocol
321
+ # (.tmp/worker-overlay.mjs). WM_CLOSE is handled by WPF itself: the window closes, Dispatcher.Run
322
+ # returns, the pipeline ends. PostMessage returns immediately and needs no runspace at all.
323
+ # RegisterHotKey is owned by the window, so destroying it unregisters the chord automatically.
324
+ $hwnd = [WpmCtl]::OverlayHwnd
325
+ $posted = $false
326
+ if ($hwnd -ne 0) {
327
+ try { $posted = [bool][WpmWin]::PostMessageW([IntPtr]$hwnd, [uint32][WpmWin]::WM_CLOSE, [IntPtr]::Zero, [IntPtr]::Zero) } catch { $posted = $false }
328
+ }
329
+ $completed = $false
330
+ # WM_CLOSE only closes the WINDOW. Dispatcher.Run() (which is what the overlay thread is parked
331
+ # in) keeps running until Shutdown is requested -- measured: with the message alone the pipeline
332
+ # was still alive after 1000ms of waiting and only ended once InvokeShutdown was forced, for
333
+ # 1542ms total. So: give the window a short grace period to close cleanly, then shut the
334
+ # dispatcher down, which is the call that actually ends the thread.
335
+ if ($script:WpmOvHandle) {
336
+ $spin = 0
337
+ while (-not $script:WpmOvHandle.IsCompleted -and $spin -lt 6) { Start-Sleep -Milliseconds 50; $spin++ }
338
+ $completed = [bool]$script:WpmOvHandle.IsCompleted
339
+ }
340
+ if (-not $completed) {
341
+ $d = [WpmCtl]::Dispatcher
342
+ if ($d) { try { [void]$d.InvokeShutdown() } catch { } }
343
+ $spin = 0
344
+ while ($script:WpmOvHandle -and -not $script:WpmOvHandle.IsCompleted -and $spin -lt 20) { Start-Sleep -Milliseconds 25; $spin++ }
345
+ $completed = [bool]($script:WpmOvHandle -and $script:WpmOvHandle.IsCompleted)
346
+ }
347
+ if ($script:WpmOvHandle) {
348
+ try { $script:WpmOvPowerShell.EndInvoke($script:WpmOvHandle) | Out-Null } catch { }
349
+ }
350
+ if ($script:WpmOvPowerShell) { try { $script:WpmOvPowerShell.Dispose() } catch { }; $script:WpmOvPowerShell = $null }
351
+ if ($script:WpmOvRunspace) { try { $script:WpmOvRunspace.Dispose() } catch { }; $script:WpmOvRunspace = $null }
352
+ $script:WpmOvHandle = $null
353
+ # The body's finally block owns the flags, but it only runs if the pipeline really ended. If the
354
+ # bound expired we must not leave a lie in [WpmCtl]: clear the state here and report the fact.
355
+ $st = Get-WpmOverlayState -WaitMs 200
356
+ if (-not $completed) {
357
+ [WpmCtl]::OverlayOn = $false
358
+ [WpmCtl]::HotkeyOk = $false
359
+ [WpmCtl]::HotkeyLabel = ''
360
+ [WpmCtl]::Window = $null
361
+ [WpmCtl]::Timer = $null
362
+ [WpmCtl]::Dispatcher = $null
363
+ [WpmCtl]::OverlayHwnd = [int64]0
364
+ $st = Get-WpmOverlayState -WaitMs 200
365
+ $st.reason = 'overlay pipeline did not end within the bound; state cleared by Stop-WpmOverlay'
366
+ }
367
+ return @{ stopped = $true; completed = $completed; posted = $posted; state = $st }
368
+ }