dsh-native-uia 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +431 -2
  3. package/client/client.js +81 -0
  4. package/cordis.patch.yml +11 -0
  5. package/icon.svg +11 -0
  6. package/locale/desktop/en.json +6 -0
  7. package/locale/desktop/zh.json +6 -0
  8. package/locale/en.json +6 -0
  9. package/locale/zh.json +6 -0
  10. package/package.json +80 -4
  11. package/scripts/bench-live.mjs +157 -0
  12. package/scripts/check-lease.mjs +308 -0
  13. package/scripts/install.mjs +154 -0
  14. package/scripts/lib/load-tools-source.mjs +24 -0
  15. package/scripts/measure-parse.mjs +77 -0
  16. package/scripts/regression-halt-latch.mjs +100 -0
  17. package/scripts/regression-quality.mjs +207 -0
  18. package/scripts/regression-tools.mjs +88 -0
  19. package/scripts/regression-worker.ps1 +1042 -0
  20. package/scripts/smoke.mjs +158 -0
  21. package/scripts/verify-capture-scale.mjs +37 -0
  22. package/scripts/verify-live-clipboard.mjs +108 -0
  23. package/scripts/verify-live.mjs +110 -0
  24. package/scripts/verify-locator.mjs +52 -0
  25. package/scripts/verify.mjs +1459 -0
  26. package/src/activity-window.js +212 -0
  27. package/src/dashboard.js +145 -0
  28. package/src/guard.js +191 -0
  29. package/src/index.js +377 -0
  30. package/src/native-uia-remote.js +80 -0
  31. package/src/panel-face.js +14 -0
  32. package/src/state.js +177 -0
  33. package/src/tools.js +1482 -0
  34. package/src/worker-client.js +246 -0
  35. package/web/control.html +1413 -0
  36. package/worker/bin/build-ocr.ps1 +41 -0
  37. package/worker/bin/ocr.cs +69 -0
  38. package/worker/bin/ocr.exe +0 -0
  39. package/worker/indicator-server.ps1 +1928 -0
  40. package/worker/ps-stdio.ps1 +168 -0
  41. package/worker/uia-worker.ps1 +4220 -0
@@ -0,0 +1,1928 @@
1
+ # indicator-server.ps1 -- resident screen-overlay indicator for the Yuping desktop-control plugin.
2
+ #
3
+ # WHAT IT PAINTS
4
+ # One WPF window over ONE monitor only: a glowing ring inside that monitor's edges plus a
5
+ # small top-centre pill ("Yuping - currently controlling", phase-specific text). It is the
6
+ # "the agent is driving your desktop" signal for the person at the keyboard.
7
+ #
8
+ # TRANSPORT
9
+ # stdio JSON-lines: one request object per line in, one response object per line out.
10
+ # {"id":N,"cmd":"...","args":{...}} -> {"id":N,"ok":true,"result":{...}}
11
+ # -> {"id":N,"ok":false,"error":"one line","code":"token"}
12
+ # stdout carries nothing but responses and every response is escaped to pure ASCII
13
+ # (chars > 0x7E become \uXXXX) because the pipe encoding between Node and powershell.exe is
14
+ # not guaranteed on this box. Diagnostics go to stderr ONLY. Unknown cmd -> code unknown_cmd
15
+ # and the loop survives; every exception becomes an error response, never a dead loop.
16
+ #
17
+ # SOURCE IS 7-BIT ASCII ON PURPOSE
18
+ # Windows PowerShell 5.1 decodes a BOM-less .ps1 with the system codepage (GBK here), so a
19
+ # UTF-8 CJK literal in this file would arrive as mojibake. Every non-ASCII string is therefore
20
+ # built from Unicode code points (CU / $script:TEXT / $script:PILL) so the source encoding can
21
+ # never corrupt the pill text. Because of that, the glyph check in Test-FontCoverage really is
22
+ # a test of the FONT, not of this file.
23
+ #
24
+ # COORDINATE SPACE
25
+ # The process makes itself PER_MONITOR_AWARE_V2 (the same call uia-worker.ps1 makes, and that is
26
+ # the process which produces the target-window rects) so every rect crossing this pipe is
27
+ # PHYSICAL PIXELS. WPF lays out in DIPs, so incoming bounds are divided by (monitorDpi/96) on the
28
+ # way in and the window's real GetWindowRect is reported back in physical pixels for audit.
29
+ #
30
+ # THREADING
31
+ # Every WPF object is touched on the STA/UI-dispatcher thread only. stdin is read by a SEPARATE
32
+ # RUNSPACE (PowerShell session state is not thread-safe) that does nothing but
33
+ # Console.In.ReadLine() into a ConcurrentQueue; a dispatcher timer pumps that queue, and every
34
+ # render frame drains it too. The reader never calls back into this session.
35
+ #
36
+ # LIFETIME / SAFETY NETS
37
+ # * EOF on stdin exits immediately (the Node parent owns the lifetime).
38
+ # * no command for idleHideMs (default 120000, settable per show) -> auto-hide + stderr log.
39
+ # * phase stopped -> red flash, then auto-hide after 1200 ms.
40
+ # * never activated (ShowActivated=false, WS_EX_NOACTIVATE), never in the taskbar or alt-tab
41
+ # (ShowInTaskbar=false, WS_EX_TOOLWINDOW), mouse-transparent (WS_EX_TRANSPARENT), and the
42
+ # visuals are IsHitTestVisible=false as a second line of defence. A watchdog asserts the overlay
43
+ # never becomes GetForegroundWindow(); if it ever did that is logged and counted
44
+ # (state().fgThefts) instead of being silently accepted.
45
+ #
46
+ # Run: powershell.exe -NoProfile -ExecutionPolicy Bypass -File indicator-server.ps1
47
+ $ErrorActionPreference = 'Stop'
48
+ Set-StrictMode -Off
49
+
50
+ # ---------------------------------------------------------------- configuration
51
+ function EnvInt($name, $default) {
52
+ $v = [Environment]::GetEnvironmentVariable($name)
53
+ if ($null -eq $v) { return $default }
54
+ $n = 0
55
+ if (-not [int]::TryParse(([string]$v), [ref]$n)) { return $default }
56
+ if ($n -lt 0) { return $default }
57
+ return $n
58
+ }
59
+ $CFG = [ordered]@{
60
+ renderMs = EnvInt 'DSH_INDICATOR_RENDER_MS' 100 # visual update interval of the pulse (ms)
61
+ pulseMs = EnvInt 'DSH_INDICATOR_PULSE_MS' 2400 # acting pulse period
62
+ idleMs = EnvInt 'DSH_INDICATOR_IDLE_MS' 120000 # default auto-hide after silence
63
+ ringPx = EnvInt 'DSH_INDICATOR_RING_PX' 26 # ring thickness in PHYSICAL pixels
64
+ haloPx = EnvInt 'DSH_INDICATOR_HALO_PX' 16 # cursor-halo radius in PHYSICAL pixels
65
+ haloOn = EnvInt 'DSH_INDICATOR_HALO_ON' 1 # follow the pointer with an outline glow in the acting phase
66
+ pillTopPx = EnvInt 'DSH_INDICATOR_PILL_TOP_PX' 24 # pill gap from monitor top, physical px
67
+ dpiAware = EnvInt 'DSH_INDICATOR_DPI_AWARE' 1 # 1 = PerMonitorV2 (match uia-worker)
68
+ pumpMs = EnvInt 'DSH_INDICATOR_PUMP_MS' 250 # idle input pump; arrivals wake the dispatcher directly
69
+ renderHook= EnvInt 'DSH_INDICATOR_RENDER_HOOK' 0 # 1 = also subscribe CompositionTarget.Rendering (measured: it forces ~55 Hz full-surface compositing)
70
+ stoppedMs = EnvInt 'DSH_INDICATOR_STOPPED_MS' 1200 # phase stopped -> auto hide delay
71
+ }
72
+
73
+ # ---------------------------------------------------------------- stderr log
74
+ $script:stdErr = [Console]::Error
75
+ function Log($msg) {
76
+ try { $script:stdErr.WriteLine('[indicator-server] ' + $msg) } catch { }
77
+ }
78
+
79
+ # ---------------------------------------------------------------- assemblies
80
+ $script:loadMs = 0
81
+ $tl = [Diagnostics.Stopwatch]::GetTimestamp()
82
+ foreach ($asm in @('PresentationFramework', 'PresentationCore', 'WindowsBase', 'System.Xaml',
83
+ 'System.Drawing', 'System.Windows.Forms')) {
84
+ try { Add-Type -AssemblyName $asm } catch { Log ('assembly missing: ' + $asm + ' (' + $_.Exception.Message + ')') }
85
+ }
86
+ $script:loadMs = [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $tl) / 10000.0, 1)
87
+ $script:wpfAssemblies = $false
88
+ try { if ($null -ne [System.Windows.Window]) { $script:wpfAssemblies = $true } } catch { Log 'WPF types unavailable' }
89
+
90
+ # ---------------------------------------------------------------- native: user32 / shcore
91
+ $nativeSrc = @'
92
+ using System;
93
+ using System.Runtime.InteropServices;
94
+
95
+ public static class IndNative {
96
+ [DllImport("user32.dll")] public static extern IntPtr SetProcessDpiAwarenessContext(IntPtr ctx);
97
+ [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
98
+ [DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
99
+ [DllImport("user32.dll")] public static extern uint GetDpiForSystem();
100
+ [DllImport("shcore.dll")] public static extern int GetDpiForMonitor(IntPtr hmonitor, int dpiType, out uint dpiX, out uint dpiY);
101
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
102
+ [DllImport("user32.dll")] public static extern bool GetCursorPos(out POINT p);
103
+ // VK_ESCAPE probe for the host watchdog: this process is idle by design and answers in ms, so
104
+ // Esc stays observable even while the ACTION worker sits inside a long OCR/wait/batch.
105
+ [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int vKey);
106
+ public static int[] CursorXY() {
107
+ POINT p = new POINT();
108
+ try { if (GetCursorPos(out p)) return new int[] { p.X, p.Y }; } catch { }
109
+ return new int[] { -1, -1 };
110
+ }
111
+ // ---- current cursor bitmap, so the halo traces WHATEVER the cursor is (arrow / hand / ibeam / resize) ----
112
+ [StructLayout(LayoutKind.Sequential)] public struct CURINFO { public int cbSize; public int flags; public IntPtr hCursor; public POINT pt; }
113
+ [StructLayout(LayoutKind.Sequential)] public struct ICONINFO { [MarshalAs(UnmanagedType.Bool)] public bool fIcon; public int xHotspot; public int yHotspot; public IntPtr hbmMask; public IntPtr hbmColor; }
114
+ [StructLayout(LayoutKind.Sequential)] public struct BIH { public int biSize; public int biWidth; public int biHeight; public short biPlanes; public short biBitCount; public int biCompression; public int biSizeImage; public int biXPels; public int biYPels; public int biClrUsed; public int biClrImportant; }
115
+ [StructLayout(LayoutKind.Sequential)] public struct BIMAPINFO { public BIH bmiHeader; public int bmiColors0; }
116
+ [DllImport("user32.dll")] public static extern bool GetCursorInfo(ref CURINFO pci);
117
+ [DllImport("user32.dll")] public static extern IntPtr CopyIcon(IntPtr hIcon);
118
+ [DllImport("user32.dll")] public static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO pii);
119
+ [DllImport("user32.dll")] public static extern bool DestroyIcon(IntPtr hIcon);
120
+ [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc);
121
+ [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hdc);
122
+ [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr h);
123
+ [DllImport("gdi32.dll")] public static extern int GetDIBits(IntPtr hdc, IntPtr hbm, uint start, uint lines, byte[] bits, ref BIMAPINFO bmi, uint usage);
124
+ public class CursData {
125
+ public bool ok = false; public byte[] bgra; public int w; public int h; public int xHot; public int yHot; public IntPtr hCursor;
126
+ }
127
+ public static CursData ReadCursor() {
128
+ CursData r = new CursData();
129
+ try {
130
+ CURINFO ci = new CURINFO(); ci.cbSize = Marshal.SizeOf(typeof(CURINFO));
131
+ if (!GetCursorInfo(ref ci)) return r;
132
+ r.hCursor = ci.hCursor;
133
+ IntPtr ic = CopyIcon(ci.hCursor);
134
+ if (ic == IntPtr.Zero) return r;
135
+ ICONINFO ii;
136
+ if (!GetIconInfo(ic, out ii)) { DestroyIcon(ic); return r; }
137
+ r.xHot = ii.xHotspot; r.yHot = ii.yHotspot;
138
+ if (ii.hbmColor != IntPtr.Zero) {
139
+ IntPtr dc = CreateCompatibleDC(IntPtr.Zero);
140
+ BIMAPINFO bi = new BIMAPINFO();
141
+ bi.bmiHeader.biSize = Marshal.SizeOf(typeof(BIH));
142
+ GetDIBits(dc, ii.hbmColor, 0, 0, null, ref bi, 0);
143
+ int w = bi.bmiHeader.biWidth, h = Math.Abs(bi.bmiHeader.biHeight);
144
+ if (w > 0 && h > 0 && w <= 256 && h <= 256) {
145
+ bi.bmiHeader.biHeight = -h; bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biCompression = 0; bi.bmiHeader.biSizeImage = w * h * 4;
146
+ byte[] bits = new byte[w * h * 4];
147
+ if (GetDIBits(dc, ii.hbmColor, 0, (uint)h, bits, ref bi, 0) > 0) {
148
+ // The AND mask is the authoritative shape (calibrated: bit 0 = shape pixel). The colour
149
+ // bitmap's alpha is NOT reliable as the silhouette: for some cursors it is a solid
150
+ // square, fully transparent, or even a square-with-arrow-hole, each of which rendered a
151
+ // solid coloured block. So prefer the mask and fall back to alpha only when absent.
152
+ if (ii.hbmMask != IntPtr.Zero) {
153
+ byte[] sil = MaskSilhouette(dc, ii.hbmMask, w, h);
154
+ if (sil != null) { r.bgra = sil; r.w = w; r.h = h; r.ok = true; }
155
+ } else {
156
+ int opaque = 0, clear = 0;
157
+ for (int i = 0; i < w * h; i++) { byte a = bits[i * 4 + 3]; if (a > 120) opaque++; else if (a < 40) clear++; }
158
+ if (opaque > 0 && clear > 0) { r.bgra = bits; r.w = w; r.h = h; r.ok = true; }
159
+ }
160
+ }
161
+ }
162
+ DeleteDC(dc);
163
+ }
164
+ DestroyIcon(ic);
165
+ } catch { }
166
+ return r;
167
+ }
168
+ // AND mask -> Pbgra32 silhouette: mask bit 0 = shape pixel (opaque), bit 1 = transparent.
169
+ static byte[] MaskSilhouette(IntPtr dc, IntPtr hMask, int w, int h) {
170
+ try {
171
+ BIMAPINFO bi = new BIMAPINFO();
172
+ bi.bmiHeader.biSize = Marshal.SizeOf(typeof(BIH));
173
+ bi.bmiHeader.biWidth = w; bi.bmiHeader.biHeight = -h; bi.bmiHeader.biPlanes = 1;
174
+ bi.bmiHeader.biBitCount = 1; bi.bmiHeader.biCompression = 0;
175
+ int stride = ((w + 31) / 32) * 4;
176
+ byte[] mbits = new byte[stride * h];
177
+ if (GetDIBits(dc, hMask, 0, (uint)h, mbits, ref bi, 0) <= 0) return null;
178
+ byte[] outb = new byte[w * h * 4];
179
+ for (int y = 0; y < h; y++) {
180
+ for (int x = 0; x < w; x++) {
181
+ int byteIdx = y * stride + (x >> 3);
182
+ int bit = 7 - (x & 7);
183
+ bool shape = ((mbits[byteIdx] >> bit) & 1) == 0; // AND mask bit 0 = shape pixel, bit 1 = transparent (calibrated against the colour alpha: bit==0 agrees 95.7%)
184
+ int px = (y * w + x) * 4;
185
+ byte v = shape ? (byte)255 : (byte)0;
186
+ outb[px] = outb[px + 1] = outb[px + 2] = v;
187
+ outb[px + 3] = v;
188
+ }
189
+ }
190
+ return outb;
191
+ } catch { return null; }
192
+ }
193
+ [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr h);
194
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
195
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
196
+ [DllImport("user32.dll", EntryPoint = "GetWindowLongW")] static extern int GetWindowLongW(IntPtr h, int idx);
197
+ [DllImport("user32.dll", EntryPoint = "SetWindowLongW")] static extern int SetWindowLongW(IntPtr h, int idx, int val);
198
+ [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
199
+
200
+ [DllImport("user32.dll")] public static extern IntPtr MonitorFromPoint(POINT p, uint flags);
201
+ [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow();
202
+ [DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr h);
203
+
204
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
205
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
206
+
207
+ public static IntPtr MonitorAt(int x, int y) {
208
+ POINT p = new POINT(); p.X = x; p.Y = y;
209
+ try { return MonitorFromPoint(p, 2); } catch { return IntPtr.Zero; } // MONITOR_DEFAULTTONEAREST
210
+ }
211
+ public static int DpiForHwnd(IntPtr h) {
212
+ try { uint d = GetDpiForWindow(h); if (d > 0) return (int)d; } catch { }
213
+ return 0;
214
+ }
215
+
216
+ static int g_aware = 0;
217
+ // 0 = not applied, 1 = SetProcessDPIAware (system aware), 2 = per-monitor v2 context
218
+ public static int MakeAware() {
219
+ if (g_aware != 0) return g_aware;
220
+ try {
221
+ IntPtr r = SetProcessDpiAwarenessContext(new IntPtr(-4));
222
+ if (r != IntPtr.Zero) { g_aware = 2; return g_aware; }
223
+ } catch { }
224
+ try { if (SetProcessDPIAware()) { g_aware = 1; return g_aware; } } catch { }
225
+ return 0;
226
+ }
227
+ public static int Awareness { get { return g_aware; } }
228
+
229
+ // GWL_EXSTYLE = -20. The ex-style field is 32-bit, so the W entry point is the correct one here.
230
+ public static int GetExStyle(IntPtr h) { try { return GetWindowLongW(h, -20); } catch { return 0; } }
231
+ public static int SetExStyle(IntPtr h, int v) { try { return SetWindowLongW(h, -20, v); } catch { return 0; } }
232
+ // SWP_NOSIZE 0x1 | SWP_NOMOVE 0x2 | SWP_NOZORDER 0x4 | SWP_NOACTIVATE 0x10 | SWP_FRAMECHANGED 0x20
233
+ public static bool ForceFrame(IntPtr h) {
234
+ try { return SetWindowPos(h, IntPtr.Zero, 0, 0, 0, 0, 0x1 | 0x2 | 0x4 | 0x10 | 0x20); } catch { return false; }
235
+ }
236
+ public static int MonitorDpi(IntPtr hmonitor) {
237
+ uint x = 96, y = 96;
238
+ if (hmonitor == IntPtr.Zero) { try { return (int)GetDpiForSystem(); } catch { return 96; } }
239
+ try { if (GetDpiForMonitor(hmonitor, 0, out x, out y) == 0 && x > 0) return (int)x; } catch { }
240
+ try { return (int)GetDpiForSystem(); } catch { return 96; }
241
+ }
242
+ public static int PhysWidth { get { try { return GetSystemMetrics(0); } catch { return 0; } } }
243
+ public static int PhysHeight { get { try { return GetSystemMetrics(1); } catch { return 0; } } }
244
+ }
245
+ '@
246
+ $script:nativeLoaded = $false
247
+ $script:dpiMode = 0
248
+ try {
249
+ Add-Type -TypeDefinition $nativeSrc -ReferencedAssemblies @('System.Core') -ErrorAction Stop
250
+ $script:nativeLoaded = $true
251
+ } catch {
252
+ Log ('Add-Type native helper failed: ' + $_.Exception.Message)
253
+ }
254
+ if ($script:nativeLoaded -and $CFG.dpiAware -eq 1) {
255
+ try { $script:dpiMode = [IndNative]::MakeAware() } catch { Log ('MakeAware threw: ' + $_.Exception.Message) }
256
+ }
257
+
258
+ # ---------------------------------------------------------------- WPF helper (render hook + glyph probe)
259
+ # CompositionTarget.Rendering is a STATIC event, and on this framework its delegate is plain
260
+ # System.EventHandler. PowerShell cannot subscribe to a static event on the UI thread
261
+ # (Register-ObjectEvent would run the handler on a pool thread and break WPF affinity), so the
262
+ # subscription lives here and calls back into a PowerShell Action on the thread that raises the
263
+ # event -- the dispatcher thread, exactly like DispatcherTimer.Tick.
264
+ $renderSrc = @'
265
+ using System;
266
+ using System.Collections.Generic;
267
+ using System.Globalization;
268
+ using System.Text;
269
+ using System.Threading;
270
+ using System.Windows;
271
+ using System.Windows.Media;
272
+
273
+ public class FontProbe {
274
+ public string family = "";
275
+ public string fontUri = "";
276
+ public bool hasFace = false;
277
+ public string missing = "";
278
+ public double width = 0.0;
279
+ public int glyphCount = 0;
280
+ public int probed = 0;
281
+ public string note = "";
282
+ }
283
+
284
+ // Thread-safe "there is a line waiting" signal. The stdin runspace calls Notify(); it never runs
285
+ // PowerShell code. The Action handed to Init was created on the UI thread and is only ever
286
+ // invoked BY the dispatcher, so session state stays single-threaded.
287
+ public static class IndWake {
288
+ static System.Windows.Threading.Dispatcher _d;
289
+ static Action _on;
290
+ static int _queued;
291
+ public static void Init(System.Windows.Threading.Dispatcher d, Action on) { _d = d; _on = on; Interlocked.Exchange(ref _queued, 0); }
292
+ public static void Notify() {
293
+ System.Windows.Threading.Dispatcher d = _d;
294
+ Action on = _on;
295
+ if (d == null || on == null) return;
296
+ if (Interlocked.Exchange(ref _queued, 1) == 1) return;
297
+ try { d.BeginInvoke(on, System.Windows.Threading.DispatcherPriority.Normal); }
298
+ catch { Interlocked.Exchange(ref _queued, 0); }
299
+ }
300
+ public static void Clear() { Interlocked.Exchange(ref _queued, 0); }
301
+ }
302
+
303
+ public static class IndWpf {
304
+ static EventHandler _h;
305
+ static Action _cb;
306
+ public static void StartRendering(Action cb) {
307
+ StopRendering();
308
+ _cb = cb;
309
+ _h = new EventHandler(delegate(object s, EventArgs e) { Action a = _cb; if (a != null) a(); });
310
+ CompositionTarget.Rendering += _h;
311
+ }
312
+ public static void StopRendering() {
313
+ if (_h != null) { try { CompositionTarget.Rendering -= _h; } catch { } _h = null; }
314
+ _cb = null;
315
+ }
316
+ public static bool RenderingOn { get { return _h != null; } }
317
+
318
+ // Real glyph coverage, read off the face's own character->glyph map: a code point that is absent,
319
+ // or that maps to glyph id 0 (.notdef), is reported -- plus the font FILE the face came from.
320
+ public static FontProbe Probe(string familyName, string text, double emPx) {
321
+ FontProbe r = new FontProbe();
322
+ r.family = familyName;
323
+ try {
324
+ Typeface tf = new Typeface(new FontFamily(familyName), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
325
+ GlyphTypeface face;
326
+ r.hasFace = tf.TryGetGlyphTypeface(out face);
327
+ if (r.hasFace && face != null) {
328
+ try { r.fontUri = face.FontUri.ToString(); } catch { }
329
+ try { r.glyphCount = face.GlyphCount; } catch { }
330
+ IDictionary<int, ushort> cmap = face.CharacterToGlyphMap;
331
+ StringBuilder sb = new StringBuilder();
332
+ r.probed = 0;
333
+ for (int i = 0; i < text.Length; i++) {
334
+ char ch = text[i];
335
+ if (ch == ' ') continue;
336
+ r.probed++;
337
+ ushort gid = 0;
338
+ bool found = cmap != null && cmap.TryGetValue((int)ch, out gid);
339
+ if (!found || gid == 0) {
340
+ if (sb.Length > 0) sb.Append(',');
341
+ sb.Append("U+").Append(((int)ch).ToString("x4", CultureInfo.InvariantCulture));
342
+ }
343
+ }
344
+ r.missing = sb.ToString();
345
+ } else {
346
+ r.note = "no glyph typeface for this family";
347
+ }
348
+ FormattedText ft = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, tf, emPx, Brushes.White, 1.0);
349
+ r.width = ft.WidthIncludingTrailingWhitespace;
350
+ } catch (Exception ex) { r.note = "probe error: " + ex.GetType().Name; }
351
+ return r;
352
+ }
353
+ }
354
+ '@
355
+ $script:renderLoaded = $false
356
+ if ($script:wpfAssemblies) {
357
+ # By simple NAME the compiler inside Add-Type does not resolve the WPF assemblies on this box;
358
+ # the loaded locations do. Measured, not assumed.
359
+ $wpfRefs = @()
360
+ try { $wpfRefs += [System.Windows.Media.CompositionTarget].Assembly.Location } catch { }
361
+ try { $wpfRefs += [System.Windows.Threading.Dispatcher].Assembly.Location } catch { }
362
+ try { $wpfRefs += [System.Windows.Window].Assembly.Location } catch { }
363
+ try {
364
+ Add-Type -TypeDefinition $renderSrc -ReferencedAssemblies $wpfRefs -ErrorAction Stop
365
+ $script:renderLoaded = $true
366
+ } catch {
367
+ Log ('Add-Type WPF helper failed: ' + $_.Exception.Message + ' -- render loop falls back to DispatcherTimer')
368
+ }
369
+ }
370
+
371
+ # ---------------------------------------------------------------- non-ASCII text, by code point
372
+ function CU([int[]]$codes) { $s = ''; foreach ($c in $codes) { $s = $s + [string][char]$c }; return $s }
373
+ $script:TEXT = [ordered]@{
374
+ brand = CU @(0x5FA1, 0x5C4F) # "Yu ping"
375
+ dot = CU @(0x00B7) # middle dot
376
+ acting = CU @(0x6B63, 0x5728, 0x64CD, 0x63A7) # "currently controlling"
377
+ stopped = CU @(0x5DF2, 0x505C, 0x6B62) # "stopped"
378
+ }
379
+ # Every visible phase carries the brand: the label identifies WHO is on the screen, so a phase
380
+ # change must recolour and reword the state without dropping the 御屏 name itself.
381
+ # There are two visible phases, not three: a paused state was removed from the product, so the
382
+ # capsule only ever says "acting" or (briefly, on the way out) "stopped".
383
+ $script:PILL = @{
384
+ acting = ($script:TEXT.brand + ' ' + $script:TEXT.dot + ' ' + $script:TEXT.acting)
385
+ stopped = ($script:TEXT.brand + ' ' + $script:TEXT.dot + ' ' + $script:TEXT.stopped)
386
+ hidden = ''
387
+ }
388
+ $script:TITLE = 'dsh-yuping-indicator'
389
+
390
+ # ---------------------------------------------------------------- phase palettes (RGB triples)
391
+ function ColA([double]$a, $rgb) {
392
+ $al = [int][Math]::Round($a * 255.0)
393
+ if ($al -lt 0) { $al = 0 }; if ($al -gt 255) { $al = 255 }
394
+ return [System.Windows.Media.Color]::FromArgb([byte]$al, [byte]$rgb[0], [byte]$rgb[1], [byte]$rgb[2])
395
+ }
396
+ $script:PH = @{
397
+ acting = @{ periodMs = [int]$CFG.pulseMs; lo = 0.55; hi = 1.00; base = @(205, 188, 243); g0 = @(217, 204, 247); g1 = @(192, 168, 238) }
398
+ stopped = @{ periodMs = 900; lo = 0.72; hi = 1.00; base = @(255, 91, 93); g0 = @(255, 93, 93); g1 = @(232, 54, 93) }
399
+ hidden = @{ periodMs = [int]$CFG.pulseMs; lo = 0.55; hi = 1.00; base = @(205, 188, 243); g0 = @(217, 204, 247); g1 = @(192, 168, 238) }
400
+ }
401
+
402
+ # ---------------------------------------------------------------- plugin-supplied palette
403
+ function Hex-Triple($v) {
404
+ if ($null -eq $v) { return $null }
405
+ $s = ([string]$v).Trim().TrimStart('#')
406
+ if ($s.Length -ne 6) { return $null }
407
+ try {
408
+ return @([Convert]::ToInt32($s.Substring(0,2),16), [Convert]::ToInt32($s.Substring(2,2),16), [Convert]::ToInt32($s.Substring(4,2),16))
409
+ } catch { return $null }
410
+ }
411
+
412
+ function PalGet($d, $k) {
413
+ if ($null -eq $d) { return $null }
414
+ foreach ($key in $d.Keys) { if ([string]$key -eq [string]$k) { return $d[$key] } }
415
+ return $null
416
+ }
417
+
418
+ # Colour is plugin data: the Node side owns it and hands it over on every
419
+ # state-changing command. Unusable values are reported back instead of being
420
+ # silently dropped, so a parameter nobody reads cannot survive as a green answer.
421
+ function Apply-Palette($A) {
422
+ # The receipt is written to script state, not returned: a PowerShell function's
423
+ # return value collects every stray pipeline object, so a returned hashtable can
424
+ # silently arrive at the caller as Object[].
425
+ $script:S.lastPalette = [ordered]@{ applied = $false; keys = @(); rejected = @() }
426
+ $p = ArgOf $A 'palette'
427
+ if ($null -eq $p) { return }
428
+ $d = $null
429
+ try { $d = Dict $p } catch { $d = $null }
430
+ if ($d -isnot [System.Collections.IDictionary]) {
431
+ $script:S.lastPalette.rejected = @('palette is not an object')
432
+ return
433
+ }
434
+ $keys = New-Object System.Collections.Generic.List[string]
435
+ $rejected = New-Object System.Collections.Generic.List[string]
436
+ $pairs = @{ acting = @('ringFrom','ringTo'); hidden = @('ringFrom','ringTo') }
437
+ $accent = Hex-Triple (PalGet $d 'pillBorder')
438
+ foreach ($phase in @('acting','hidden')) {
439
+ $from = Hex-Triple (PalGet $d $pairs[$phase][0])
440
+ $to = Hex-Triple (PalGet $d $pairs[$phase][1])
441
+ if ($null -eq $from -or $null -eq $to) {
442
+ [void]$rejected.Add($phase + ': missing ' + $pairs[$phase][0] + '/' + $pairs[$phase][1])
443
+ continue
444
+ }
445
+ $script:PH[$phase].g0 = $from
446
+ $script:PH[$phase].g1 = $to
447
+ if ($null -ne $accent) { $script:PH[$phase].base = $accent }
448
+ [void]$keys.Add($phase)
449
+ }
450
+ $bg = Hex-Triple (PalGet $d 'pillBg')
451
+ if ($null -ne $bg) { $script:S.pillBg = $bg; [void]$keys.Add('pillBg') }
452
+ $fg = Hex-Triple (PalGet $d 'pillText')
453
+ if ($null -ne $fg) { $script:S.pillText = $fg; [void]$keys.Add('pillText') }
454
+ $hexOf = { param($t) if ($null -eq $t -or $t.Count -lt 3) { return '' }; ('#{0:X2}{1:X2}{2:X2}' -f [int]$t[0], [int]$t[1], [int]$t[2]) }
455
+ $script:S.lastPalette = [ordered]@{
456
+ applied = ($keys.Count -gt 0)
457
+ keys = @($keys)
458
+ rejected = @($rejected)
459
+ # The colours now actually in the render table: what the screen will show,
460
+ # not merely what the caller asked for.
461
+ acting = [ordered]@{ g0 = (& $hexOf $script:PH.acting.g0); g1 = (& $hexOf $script:PH.acting.g1); base = (& $hexOf $script:PH.acting.base) }
462
+ }
463
+ return
464
+ }
465
+
466
+ # ---------------------------------------------------------------- server state
467
+ $script:S = [ordered]@{
468
+ startTick = [Diagnostics.Stopwatch]::GetTimestamp()
469
+ app = $null
470
+ dispatcher = $null
471
+ win = $null
472
+ canvas = $null
473
+ ring = @()
474
+ bloom = @()
475
+ outline = $null
476
+ halo = $null
477
+ haloBlooms = @()
478
+ haloX = 0
479
+ haloY = 0
480
+ haloOn = $false
481
+ haloCurs = $null
482
+ haloShape = [IntPtr]::Zero
483
+ haloPad = 0
484
+ pill = $null
485
+ pillText = $null
486
+ pillSub = $null
487
+ built = $false
488
+ visible = $false
489
+ hwnd = [Int64]0
490
+ monitorIndex = -1
491
+ monitorBounds = $null
492
+ scale = 1.0
493
+ dpi = 96
494
+ phase = 'hidden'
495
+ mode = 'background'
496
+ textOverride = ''
497
+ subtext = ''
498
+ framesRendered = [Int64]0
499
+ renderCallbacks = [Int64]0
500
+ visualUpdates = [Int64]0
501
+ appliedAlpha = $null
502
+ renderOn = $false
503
+ renderHookOn = $false
504
+ renderDriver = ''
505
+ lastPulseStamp = [Int64]0
506
+ lastPulseMsWall = [Int64]0
507
+ phaseStartTick = [Diagnostics.Stopwatch]::GetTimestamp()
508
+ pulseOffset = 0.0
509
+ pulseAlpha = 0.0
510
+ exStyles = 0
511
+ straddle = $false
512
+ idleHideMs = [int]$CFG.idleMs
513
+ lastCmdTick = [Diagnostics.Stopwatch]::GetTimestamp()
514
+ autoHides = [Int64]0
515
+ showCount = [Int64]0
516
+ hideCount = [Int64]0
517
+ hwndCreateCount = [Int64]0
518
+ hwndChanges = [Int64]0
519
+ hwndSeen = @()
520
+ fitPasses = 0
521
+ fitConverged = $false
522
+ fitDelta = $null
523
+ fitRect = $null
524
+ fgThefts = [Int64]0
525
+ fontProbe = $null
526
+ chosenFont = ''
527
+ dipW = 0.0
528
+ dipH = 0.0
529
+ ringDip = 0.0
530
+ pillX = 0
531
+ pillY = 0
532
+ pillW = 0
533
+ pillH = 0
534
+ exitCode = 0
535
+ closing = $false
536
+ screens = @()
537
+ timers = @()
538
+ stats = @{ commands = 0; refused = 0; beats = 0; autoHides = 0 }
539
+ }
540
+
541
+ # ---------------------------------------------------------------- framing / io
542
+ $script:utf8NoBom = New-Object System.Text.UTF8Encoding($false)
543
+ try {
544
+ [Console]::InputEncoding = $script:utf8NoBom
545
+ [Console]::OutputEncoding = $script:utf8NoBom
546
+ } catch { }
547
+
548
+ # Esc/JsonOf/OneLine/Err/ArgOf/IntArg/StrArg/BoolArg/Dict/Split-Err are shared verbatim
549
+ # with uia-worker.ps1 via ps-stdio.ps1 (the escaping contract is documented there).
550
+ # Send-Ok/Send-Err stay here: they write $script:S.stats and decorate results with
551
+ # exStyles/palette (Add-Ex below), which are indicator-owned contracts.
552
+ . (Join-Path $PSScriptRoot 'ps-stdio.ps1')
553
+
554
+ function ExHex($v) { return '0x' + (([int64]$v -band 0xFFFFFFFFL).ToString('x8')) }
555
+
556
+ $EX_MAP = [ordered]@{
557
+ WS_EX_TRANSPARENT = 0x00000020
558
+ WS_EX_LAYERED = 0x00080000
559
+ WS_EX_TOOLWINDOW = 0x00000080
560
+ WS_EX_NOACTIVATE = 0x08000000
561
+ WS_EX_TOPMOST = 0x00000008
562
+ }
563
+ function Ex-Flags($v) {
564
+ $out = New-Object System.Collections.Generic.List[string]
565
+ foreach ($k in $EX_MAP.Keys) {
566
+ $bit = [int64]$EX_MAP[$k]
567
+ if ((([int64]$v -band $bit) -eq $bit)) { $out.Add([string]$k) }
568
+ }
569
+ return $out.ToArray()
570
+ }
571
+ function Ex-Has($v, [int64]$bit) { return (([int64]$v -band $bit) -eq $bit) }
572
+
573
+ # exStyles travels in EVERY response so a reviewer can audit the click-through bits at any moment.
574
+ function Add-Ex($result) {
575
+ if ($null -eq $result) { return $result }
576
+ if ($result -is [System.Collections.IDictionary]) {
577
+ $result['exStyles'] = (ExHex $script:S.exStyles)
578
+ $result['exFlags'] = (Ex-Flags $script:S.exStyles)
579
+ }
580
+ return $result
581
+ }
582
+
583
+ function NowMs { return [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $script:S.startTick) / 10000.0, 1) }
584
+ function SinceMs($tick) { return [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $tick) / 10000.0, 1) }
585
+ function Elapsed($t0) { return [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $t0) / 10000.0, 1) }
586
+
587
+ function Send-Ok($id, $result) {
588
+ $script:S.stats.commands += 1
589
+ if ($null -eq $result -or $result -isnot [System.Collections.IDictionary]) {
590
+ # A handler that let a stray pipeline value escape shows up here as an array.
591
+ # Answering with it would break every client's shape assumption, so refuse loudly.
592
+ $shape = if ($null -eq $result) { 'null' } else { $result.GetType().Name }
593
+ Send-Err $id 'bad_result_shape' ("handler result is $shape, not an object; check for a leaked pipeline value")
594
+ return
595
+ }
596
+ $r = [ordered]@{ id = $id; ok = $true }
597
+ $r['result'] = (Add-Ex $result)
598
+ if ($null -ne $script:S.lastPalette) { $r['result']['palette'] = $script:S.lastPalette }
599
+ $r['stats'] = $script:S.stats
600
+ [Console]::Out.Write((JsonOf $r))
601
+ [Console]::Out.Write("`n")
602
+ [Console]::Out.Flush()
603
+ }
604
+
605
+ function Send-Err($id, $code, $message) {
606
+ $script:S.stats.commands += 1
607
+ $script:S.stats.refused += 1
608
+ $r = [ordered]@{ id = $id; ok = $false; code = [string]$code; error = (OneLine $message) }
609
+ $r['exStyles'] = (ExHex $script:S.exStyles)
610
+ $r['stats'] = $script:S.stats
611
+ [Console]::Out.Write((JsonOf $r))
612
+ [Console]::Out.Write("`n")
613
+ [Console]::Out.Flush()
614
+ }
615
+
616
+ # ---------------------------------------------------------------- monitor model
617
+ function Refresh-Screens {
618
+ $list = New-Object System.Collections.Generic.List[object]
619
+ $i = 0
620
+ foreach ($sc in [System.Windows.Forms.Screen]::AllScreens) {
621
+ $b = $sc.Bounds
622
+ # WinForms Screen.Handle is not usable here (measured: it converts to a null IntPtr and the
623
+ # P/Invoke throws), so the HMONITOR is taken from the point at the centre of the monitor.
624
+ $dpi = 0
625
+ if ($script:nativeLoaded) {
626
+ try {
627
+ $cx = [int]($b.X + ($b.Width / 2))
628
+ $cy = [int]($b.Y + ($b.Height / 2))
629
+ $hm = [IndNative]::MonitorAt($cx, $cy)
630
+ $dpi = [IndNative]::MonitorDpi($hm)
631
+ } catch { $dpi = 0 }
632
+ }
633
+ if ($dpi -le 0) {
634
+ # last resort: WPF's own device scale, which is the number the layout will actually use
635
+ $ds = (Get-DeviceScale)
636
+ if ($ds -gt 0) { $dpi = [int][Math]::Round(96.0 * $ds) } else { $dpi = 96 }
637
+ }
638
+ [void]$list.Add([ordered]@{
639
+ index = $i
640
+ device = [string]$sc.DeviceName
641
+ bounds = [ordered]@{ x = [int]$b.X; y = [int]$b.Y; w = [int]$b.Width; h = [int]$b.Height }
642
+ work = [ordered]@{ x = [int]$sc.WorkingArea.X; y = [int]$sc.WorkingArea.Y; w = [int]$sc.WorkingArea.Width; h = [int]$sc.WorkingArea.Height }
643
+ primary = [bool]$sc.Primary
644
+ dpi = [int]$dpi
645
+ })
646
+ $i++
647
+ }
648
+ # NOTE: .ToArray(), never @($list) -- an array built from a List whose only element is an
649
+ # IDictionary makes PowerShell's hashtable assignment throw "parameter type mismatch" on this box.
650
+ $script:S.screens = $list.ToArray()
651
+ return $script:S.screens
652
+ }
653
+
654
+ # WPF's own DIP -> device-pixel factor for this window. Measured, because GetDpiForMonitor through
655
+ # PowerShell's adapter is unreliable on this box (it returned 96 for a 150 % panel).
656
+ function Get-DeviceScale {
657
+ try {
658
+ if ($null -eq $script:S.win -or -not $script:S.win.IsLoaded) { return 0.0 }
659
+ $src = [System.Windows.PresentationSource]::FromVisual($script:S.win)
660
+ if ($null -eq $src) { return 0.0 }
661
+ $ct = $src.CompositionTarget
662
+ if ($null -eq $ct) { return 0.0 }
663
+ $m = [double]$ct.TransformToDevice.M11
664
+ if ($m -gt 0 -and -not [double]::IsNaN($m)) { return $m }
665
+ } catch { }
666
+ return 0.0
667
+ }
668
+
669
+ function Intersect($a, $b) {
670
+ $x0 = [Math]::Max([int]$a.x, [int]$b.x)
671
+ $y0 = [Math]::Max([int]$a.y, [int]$b.y)
672
+ $x1 = [Math]::Min(([int]$a.x + [int]$a.w), ([int]$b.x + [int]$b.w))
673
+ $y1 = [Math]::Min(([int]$a.y + [int]$a.h), ([int]$b.y + [int]$b.h))
674
+ if ($x1 -le $x0 -or $y1 -le $y0) { return [int64]0 }
675
+ return [int64]($x1 - $x0) * [int64]($y1 - $y0)
676
+ }
677
+
678
+ function RectCenter($r) {
679
+ return [ordered]@{ x = [int]([int]$r.x + ([int]$r.w / 2)); y = [int]([int]$r.y + ([int]$r.h / 2)) }
680
+ }
681
+
682
+ function RectContains($b, [int]$x, [int]$y) {
683
+ return ($x -ge [int]$b.x -and $x -lt ([int]$b.x + [int]$b.w) -and $y -ge [int]$b.y -and $y -lt ([int]$b.y + [int]$b.h))
684
+ }
685
+
686
+ function DistTo($r, $m) {
687
+ $c = RectCenter $r
688
+ $nx = [Math]::Min([Math]::Max($c.x, [int]$m.x), ([int]$m.x + [int]$m.w))
689
+ $ny = [Math]::Min([Math]::Max($c.y, [int]$m.y), ([int]$m.y + [int]$m.h))
690
+ $dx = [double]($c.x - $nx); $dy = [double]($c.y - $ny)
691
+ return [Math]::Sqrt($dx * $dx + $dy * $dy)
692
+ }
693
+
694
+ # Picks the monitor that CONTAINS the target rect. When a rect straddles several, the one with the
695
+ # LARGEST INTERSECTION wins. A rect touching nothing falls back to the monitor nearest the rect
696
+ # centre, so a bad rect from the model can never mean "no overlay at all".
697
+ function Pick-Monitor($rect) {
698
+ $screens = $script:S.screens
699
+ if ($null -eq $screens -or ([array]$screens).Count -eq 0) { $screens = Refresh-Screens }
700
+ if (([array]$screens).Count -eq 0) { Err 'no_screen' 'no monitor reported by this session' }
701
+ $best = -1
702
+ $bestArea = [int64]-1
703
+ $touch = 0
704
+ foreach ($m in $screens) {
705
+ $a = Intersect $rect $m.bounds
706
+ if ($a -gt 0) { $touch += 1 }
707
+ if ($a -gt $bestArea) { $bestArea = $a; $best = [int]$m.index }
708
+ }
709
+ $reason = 'contains'
710
+ $straddle = $false
711
+ if ($best -lt 0 -or $bestArea -le 0) {
712
+ $nb = [double]1.0E+18; $ni = 0
713
+ foreach ($m in $screens) {
714
+ $d = DistTo $rect $m.bounds
715
+ if ($d -lt $nb) { $nb = $d; $ni = [int]$m.index }
716
+ }
717
+ $best = $ni
718
+ $reason = 'nearest_fallback'
719
+ } else {
720
+ $c = RectCenter $rect
721
+ $picked = $null
722
+ foreach ($m in $screens) { if ([int]$m.index -eq $best) { $picked = $m } }
723
+ if (-not (RectContains $picked.bounds $c.x $c.y)) { $reason = 'largest_intersection' }
724
+ if ($touch -gt 1) { $straddle = $true }
725
+ }
726
+ $out = $null
727
+ foreach ($m in $screens) { if ([int]$m.index -eq $best) { $out = $m } }
728
+ return [ordered]@{ monitor = $out; straddle = $straddle; reason = $reason; area = [int64]$bestArea; monitorsTouched = $touch }
729
+ }
730
+
731
+ # Proves the CJK glyphs exist in the face rather than trusting the string constant. The compiled
732
+ # helper reads GlyphTypeface.CharacterToGlyphMap: a code point that is absent, or that maps to glyph
733
+ # id 0 (.notdef), is reported, together with the font file the face actually came from.
734
+ function Test-FontCoverage([string]$familyName, [string]$text) {
735
+ $res = @{ candidate = $familyName; ok = $false; probed = 0; missing = @(); fontUri = ''; glyphCount = 0; advancePx = 0.0; note = '' }
736
+ if (-not $script:renderLoaded) {
737
+ $res.note = 'compiled glyph probe unavailable'
738
+ return $res
739
+ }
740
+ try {
741
+ $p = [IndWpf]::Probe($familyName, $text, 14.0)
742
+ $res.probed = [int]$p.probed
743
+ $res.fontUri = [string]$p.fontUri
744
+ $res.glyphCount = [int]$p.glyphCount
745
+ $res.advancePx = [Math]::Round([double]$p.width, 2)
746
+ $res.note = [string]$p.note
747
+ if ($p.hasFace) {
748
+ if ([string]::IsNullOrEmpty([string]$p.missing)) { $res.ok = ($res.probed -gt 0) }
749
+ else { $res.missing = ([string]$p.missing).Split(',') }
750
+ }
751
+ return $res
752
+ } catch {
753
+ $res.note = 'probe threw: ' + (OneLine $_.Exception.Message)
754
+ return $res
755
+ }
756
+ }
757
+
758
+ $script:FONT_CANDIDATES = @('Microsoft YaHei UI', 'Microsoft YaHei', 'Segoe UI Variable Text', 'Segoe UI', 'SimSun', 'NSimSun')
759
+ function Choose-Font {
760
+ $probe = New-Object System.Collections.Generic.List[object]
761
+ $all = [string]($script:PILL.acting + $script:PILL.stopped)
762
+ $chosen = ''
763
+ foreach ($f in $script:FONT_CANDIDATES) {
764
+ $p = Test-FontCoverage $f $all
765
+ [void]$probe.Add($p)
766
+ if ($chosen -eq '' -and [bool]$p.ok) { $chosen = $f }
767
+ }
768
+ $script:S.fontProbe = @{ probed = $probe.ToArray(); allGlyphsPresent = ($chosen -ne ''); text = $all }
769
+ if ($chosen -eq '') {
770
+ $chosen = 'Microsoft YaHei UI, Segoe UI Variable Text, Microsoft YaHei, Segoe UI'
771
+ Log ('no single family carried every glyph; relying on WPF per-glyph fallback: ' + $chosen)
772
+ }
773
+ $script:S.chosenFont = $chosen
774
+ return $chosen
775
+ }
776
+
777
+ # ---------------------------------------------------------------- visuals
778
+ function New-Solid($rgb, [double]$a) {
779
+ $b = New-Object System.Windows.Media.SolidColorBrush -ArgumentList (ColA $a $rgb)
780
+ [void]$b.Freeze()
781
+ return $b
782
+ }
783
+
784
+ function New-GradH($rgb0, $rgb1, [double]$a, [bool]$flip) {
785
+ # colour ramp across the ring direction, constant alpha
786
+ $b = New-Object System.Windows.Media.LinearGradientBrush
787
+ if ($flip) {
788
+ $b.StartPoint = New-Object System.Windows.Point -ArgumentList 1.0, 0.5
789
+ $b.EndPoint = New-Object System.Windows.Point -ArgumentList 0.0, 0.5
790
+ } else {
791
+ $b.StartPoint = New-Object System.Windows.Point -ArgumentList 0.0, 0.5
792
+ $b.EndPoint = New-Object System.Windows.Point -ArgumentList 1.0, 0.5
793
+ }
794
+ $s0 = New-Object System.Windows.Media.GradientStop
795
+ $s0.Color = (ColA $a $rgb0); $s0.Offset = 0.0
796
+ $s1 = New-Object System.Windows.Media.GradientStop
797
+ $s1.Color = (ColA $a $rgb1); $s1.Offset = 1.0
798
+ [void]$b.GradientStops.Add($s0)
799
+ [void]$b.GradientStops.Add($s1)
800
+ [void]$b.Freeze()
801
+ return $b
802
+ }
803
+
804
+ function New-Fade([double]$sx, [double]$sy, [double]$ex, [double]$ey, [double]$strength) {
805
+ # opacity mask: solid at the monitor edge, fading inward
806
+ $b = New-Object System.Windows.Media.LinearGradientBrush
807
+ $b.StartPoint = New-Object System.Windows.Point -ArgumentList $sx, $sy
808
+ $b.EndPoint = New-Object System.Windows.Point -ArgumentList $ex, $ey
809
+ $a255 = [int][Math]::Round([Math]::Min(1.0, $strength) * 255.0)
810
+ $p0 = New-Object System.Windows.Media.GradientStop
811
+ $p0.Color = [System.Windows.Media.Color]::FromArgb([byte]$a255, 255, 255, 255); $p0.Offset = 0.0
812
+ $p1 = New-Object System.Windows.Media.GradientStop
813
+ $p1.Color = [System.Windows.Media.Color]::FromArgb([byte]($a255 * 0.40), 255, 255, 255); $p1.Offset = 0.42
814
+ $p2 = New-Object System.Windows.Media.GradientStop
815
+ $p2.Color = [System.Windows.Media.Color]::FromArgb([byte]0, 255, 255, 255); $p2.Offset = 1.0
816
+ foreach ($p in @($p0, $p1, $p2)) { [void]$b.GradientStops.Add($p) }
817
+ [void]$b.Freeze()
818
+ return $b
819
+ }
820
+
821
+ function New-Bar([double]$x, [double]$y, [double]$w, [double]$h, $fill, $mask) {
822
+ $r = New-Object System.Windows.Shapes.Rectangle
823
+ $r.Width = [Math]::Max(0.5, $w)
824
+ $r.Height = [Math]::Max(0.5, $h)
825
+ $r.Fill = $fill
826
+ if ($null -ne $mask) { $r.OpacityMask = $mask }
827
+ [System.Windows.Controls.Canvas]::SetLeft($r, $x)
828
+ [System.Windows.Controls.Canvas]::SetTop($r, $y)
829
+ $r.SnapsToDevicePixels = $true
830
+ $r.IsHitTestVisible = $false
831
+ return $r
832
+ }
833
+
834
+ # Ring geometry for a window surface of W x H DIPs, thickness T DIPs.
835
+ # BOTH pairs of bars span their full edge (horizontals full width, verticals full height) and therefore
836
+ # overlap in the four T x T corner squares. That overlap is what makes the frame continuous -- if either
837
+ # pair is inset, the corner is left to the perpendicular bar's fading tail and reads as a dark break.
838
+ # The corner overlap only lifts alpha a little (pale lavender, perpendicular fades), so it glows rather
839
+ # than burns.
840
+ function Build-Ring([double]$W, [double]$H, [double]$T, $ph) {
841
+ $bars = New-Object System.Collections.Generic.List[object]
842
+ $bloom = New-Object System.Collections.Generic.List[object]
843
+ $a = 0.90
844
+ [void]$bars.Add((New-Bar 0 0 $W $T (New-GradH $ph.g0 $ph.g1 $a $false) (New-Fade 0.5 0.0 0.5 1.0 1.0)))
845
+ [void]$bars.Add((New-Bar 0 ($H - $T) $W $T (New-GradH $ph.g0 $ph.g1 $a $true) (New-Fade 0.5 1.0 0.5 0.0 1.0)))
846
+ [void]$bars.Add((New-Bar 0 0 $T $H (New-GradH $ph.g0 $ph.g1 $a $false) (New-Fade 0.0 0.5 1.0 0.5 1.0)))
847
+ [void]$bars.Add((New-Bar ($W - $T) 0 $T $H (New-GradH $ph.g0 $ph.g1 $a $true) (New-Fade 1.0 0.5 0.0 0.5 1.0)))
848
+ $bt = $T * 2.4
849
+ [void]$bloom.Add((New-Bar 0 0 $W $bt (New-GradH $ph.g0 $ph.g1 0.30 $false) (New-Fade 0.5 0.0 0.5 1.0 1.0)))
850
+ [void]$bloom.Add((New-Bar 0 ($H - $bt) $W $bt (New-GradH $ph.g0 $ph.g1 0.30 $true) (New-Fade 0.5 1.0 0.5 0.0 1.0)))
851
+ [void]$bloom.Add((New-Bar 0 0 $bt $H (New-GradH $ph.g0 $ph.g1 0.30 $false) (New-Fade 0.0 0.5 1.0 0.5 1.0)))
852
+ [void]$bloom.Add((New-Bar ($W - $bt) 0 $bt $H (New-GradH $ph.g0 $ph.g1 0.30 $true) (New-Fade 1.0 0.5 0.0 0.5 1.0)))
853
+ $hair = New-Object System.Windows.Shapes.Rectangle
854
+ $hair.Stroke = (New-Solid $ph.base 0.85)
855
+ $hair.StrokeThickness = 1.0
856
+ $hair.Fill = $null
857
+ $hair.Width = [Math]::Max(1.0, $W - 1.0)
858
+ $hair.Height = [Math]::Max(1.0, $H - 1.0)
859
+ [System.Windows.Controls.Canvas]::SetLeft($hair, 0.5)
860
+ [System.Windows.Controls.Canvas]::SetTop($hair, 0.5)
861
+ $hair.IsHitTestVisible = $false
862
+ return @{ bars = $bars; bloom = $bloom; hair = $hair }
863
+ }
864
+
865
+ function New-CursorGlowSource($cd, $ph, $opacity) {
866
+ # OUTER-GLOW halo: a soft coloured glow that hugs the cursor's OUTLINE and spreads outward, while the
867
+ # cursor's own interior is left fully transparent so the real pointer stays visible (we never swap the
868
+ # system cursor). Build the silhouette, box-blur it, subtract the sharp core (glow = blur*(255-core)/255)
869
+ # so nothing is painted where the cursor itself is, then premultiply into Pbgra32 (R<=A). A symmetric pad
870
+ # around the bitmap lets the glow spill past the cursor's bounding box without clipping at the edges.
871
+ # NOTE: PowerShell variables are CASE-INSENSITIVE, so the padded size uses $gw/$gh, never $W/$H (which
872
+ # would silently clobber the cursor's own $w/$h).
873
+ $w = $cd.w; $h = $cd.h
874
+ if ($w -le 0 -or $h -le 0 -or $cd.bgra.Length -lt $w * $h * 4) { return $null }
875
+ $src = $cd.bgra
876
+ $R = [int][Math]::Max(2, [Math]::Round([double]$CFG.haloPx * 0.5))
877
+ $pad = $R + 2
878
+ $gw = $w + 2 * $pad; $gh = $h + 2 * $pad
879
+ $core = [int[]]::new($gw * $gh)
880
+ for ($y = 0; $y -lt $h; $y++) { for ($x = 0; $x -lt $w; $x++) { $core[($y + $pad) * $gw + ($x + $pad)] = [int]$src[($y * $w + $x) * 4 + 3] } }
881
+ $tmp = [int[]]::new($gw * $gh)
882
+ $blur = [int[]]::new($gw * $gh)
883
+ for ($y = 0; $y -lt $gh; $y++) {
884
+ for ($x = 0; $x -lt $gw; $x++) {
885
+ $lo = [Math]::Max(0, $x - $R); $hi = [Math]::Min($gw - 1, $x + $R); $s = 0
886
+ for ($k = $lo; $k -le $hi; $k++) { $s += $core[$y * $gw + $k] }
887
+ $tmp[$y * $gw + $x] = [int][Math]::Round($s / ($hi - $lo + 1))
888
+ }
889
+ }
890
+ for ($x = 0; $x -lt $gw; $x++) {
891
+ for ($y = 0; $y -lt $gh; $y++) {
892
+ $lo = [Math]::Max(0, $y - $R); $hi = [Math]::Min($gh - 1, $y + $R); $s = 0
893
+ for ($k = $lo; $k -le $hi; $k++) { $s += $tmp[$k * $gw + $x] }
894
+ $blur[$y * $gw + $x] = [int][Math]::Round($s / ($hi - $lo + 1))
895
+ }
896
+ }
897
+ $out = New-Object byte[] ($gw * $gh * 4)
898
+ $r = [double]$ph.g0[0]; $g = [double]$ph.g0[1]; $b = [double]$ph.g0[2]
899
+ for ($i = 0; $i -lt $gw * $gh; $i++) {
900
+ $c = $core[$i]
901
+ $a = [int][Math]::Round($blur[$i] * (255 - $c) / 255.0 * $opacity)
902
+ if ($a -le 0) { $out[$i * 4 + 0] = 0; $out[$i * 4 + 1] = 0; $out[$i * 4 + 2] = 0; $out[$i * 4 + 3] = 0; continue }
903
+ if ($a -gt 255) { $a = 255 }
904
+ $f = $a / 255.0
905
+ $out[$i * 4 + 0] = [byte][Math]::Round($b * $f)
906
+ $out[$i * 4 + 1] = [byte][Math]::Round($g * $f)
907
+ $out[$i * 4 + 2] = [byte][Math]::Round($r * $f)
908
+ $out[$i * 4 + 3] = [byte]$a
909
+ }
910
+ $bmp = [System.Windows.Media.Imaging.BitmapSource]::Create($gw, $gh, 96, 96, [System.Windows.Media.PixelFormats]::Pbgra32, $null, $out, $gw * 4)
911
+ return @{ bmp = $bmp; w = $gw; h = $gh; pad = $pad }
912
+ }
913
+
914
+ function Build-Halo($ph, $sc) {
915
+ # The halo glows along the LIVE cursor bitmap, so it follows the cursor's actual shape (arrow,
916
+ # hand, ibeam, resize...) instead of assuming one. The image is rebuilt only when the OS cursor
917
+ # handle changes; each track tick just repositions it, so per-tick cost stays tiny (no blur re-run).
918
+ if ($sc -le 0) { $sc = 1.0 }
919
+ $radDip = [double]$CFG.haloPx / $sc
920
+ $img = New-Object System.Windows.Controls.Image
921
+ # Stretch=Fill so the bitmap is drawn at the Image's Width/Height (set to cursorPx/scale in
922
+ # Update-HaloGlow), i.e. its true PHYSICAL size. Stretch=None would ignore those and render the
923
+ # bitmap's pixels 1:1 as DIPs -- on a 150% display that inflates the halo to 1.5x the real cursor.
924
+ $img.Stretch = [System.Windows.Media.Stretch]::Fill
925
+ $img.IsHitTestVisible = $false
926
+ $blur = New-Object System.Windows.Media.Effects.BlurEffect
927
+ $blur.Radius = [Math]::Max(1.2, $radDip * 0.18)
928
+ $img.Effect = $blur
929
+ return @{ items = @($img); img = $img; radDip = $radDip }
930
+ }
931
+
932
+ function Update-HaloGlow($ph) {
933
+ if ($null -eq $script:S.halo -or $null -eq $script:S.halo.img) { return }
934
+ $cd = [IndNative]::ReadCursor()
935
+ if (-not $cd.ok) { $script:S.haloCurs = $null; return }
936
+ $script:S.haloCurs = $cd
937
+ if ($cd.hCursor -ne $script:S.haloShape) {
938
+ $glow = New-CursorGlowSource $cd $ph 0.85
939
+ if ($null -ne $glow) {
940
+ $sc = [double]$script:S.scale; if ($sc -le 0) { $sc = 1.0 }
941
+ $script:S.halo.img.Source = $glow.bmp
942
+ $script:S.halo.img.Width = [double]$glow.w / $sc
943
+ $script:S.halo.img.Height = [double]$glow.h / $sc
944
+ $script:S.haloPad = [int]$glow.pad
945
+ $script:S.haloShape = $cd.hCursor
946
+ }
947
+ }
948
+ }
949
+
950
+ function Position-Halo {
951
+ if ($null -eq $script:S.halo) { return }
952
+ $sc = [double]$script:S.scale; if ($sc -le 0) { $sc = 1.0 }
953
+ if (-not $script:nativeLoaded) { return }
954
+ $mb = $script:S.monitorBounds
955
+ $ph = $script:PH[$script:S.phase]; if ($null -eq $ph) { $ph = $script:PH['acting'] }
956
+ if ($null -ne $mb -and [int]$CFG.haloOn -eq 1 -and [string]$script:S.phase -eq 'acting' -and [string]$script:S.mode -in @('foreground', 'auto')) {
957
+ $c = [IndNative]::CursorXY()
958
+ if ($c[0] -lt 0) { if ($script:S.haloOn) { $script:S.haloOn = $false; foreach ($it in $script:S.halo.items) { $it.Opacity = 0.0 } }; return }
959
+ Update-HaloGlow $ph
960
+ if ($null -eq $script:S.haloCurs) { if ($script:S.haloOn) { $script:S.haloOn = $false; foreach ($it in $script:S.halo.items) { $it.Opacity = 0.0 } }; return }
961
+ $cd = $script:S.haloCurs
962
+ $pad = [int]$script:S.haloPad
963
+ $lx = (([double]$c[0] - [double]$mb.x) - ($cd.xHot + $pad)) / $sc
964
+ $ly = (([double]$c[1] - [double]$mb.y) - ($cd.yHot + $pad)) / $sc
965
+ $lt = New-Object System.Windows.Media.TranslateTransform -ArgumentList $lx, $ly
966
+ foreach ($it in $script:S.halo.items) { $it.RenderTransform = $lt; $it.Opacity = 1.0 }
967
+ $script:S.haloOn = $true
968
+ $script:S.haloX = $c[0]; $script:S.haloY = $c[1]
969
+ } elseif ($script:S.haloOn) {
970
+ $script:S.haloOn = $false
971
+ foreach ($it in $script:S.halo.items) { $it.Opacity = 0.0 }
972
+ }
973
+ }
974
+
975
+ function Build-Pill($ph) {
976
+ $border = New-Object System.Windows.Controls.Border
977
+ $border.CornerRadius = New-Object System.Windows.CornerRadius -ArgumentList 18
978
+ # dark glass unless the plugin hands over a pillBg triple
979
+ $bgT = $script:S.pillBg; if ($null -eq $bgT) { $bgT = @(27, 32, 39) }
980
+ $border.Background = (New-Object System.Windows.Media.SolidColorBrush -ArgumentList ([System.Windows.Media.Color]::FromArgb([byte]219, [byte]$bgT[0], [byte]$bgT[1], [byte]$bgT[2])))
981
+ $border.BorderBrush = (New-Solid $ph.base 0.5) # base colour at 0.5
982
+ $border.BorderThickness = New-Object System.Windows.Thickness -ArgumentList 1.0
983
+ $border.Padding = New-Object System.Windows.Thickness -ArgumentList 15, 8, 15, 9
984
+ $stack = New-Object System.Windows.Controls.StackPanel
985
+ $stack.Orientation = [System.Windows.Controls.Orientation]::Vertical
986
+ $txt = New-Object System.Windows.Controls.TextBlock
987
+ $txt.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Center
988
+ $txt.FontSize = 14.0
989
+ $txt.FontFamily = New-Object System.Windows.Media.FontFamily -ArgumentList $script:S.chosenFont
990
+ $txt.FontWeight = [System.Windows.FontWeights]::SemiBold
991
+ $fgT = $script:S.pillText; if ($null -eq $fgT) { $fgT = @(236, 243, 255) }
992
+ $txt.Foreground = (New-Solid $fgT 1.0)
993
+ $txt.Text = ''
994
+ $sub = New-Object System.Windows.Controls.TextBlock
995
+ $sub.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Center
996
+ $sub.FontSize = 11.5
997
+ $sub.FontFamily = New-Object System.Windows.Media.FontFamily -ArgumentList $script:S.chosenFont
998
+ $sub.Foreground = (New-Solid @(159, 179, 209) 0.95)
999
+ $sub.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 1, 0, 0
1000
+ $sub.Text = ''
1001
+ $sub.Visibility = [System.Windows.Visibility]::Collapsed
1002
+ [void]$stack.Children.Add($txt)
1003
+ [void]$stack.Children.Add($sub)
1004
+ $border.Child = $stack
1005
+ $border.IsHitTestVisible = $false
1006
+ return @{ border = $border; text = $txt; sub = $sub }
1007
+ }
1008
+
1009
+ function Clear-Canvas {
1010
+ if ($null -ne $script:S.canvas) { $script:S.canvas.Children.Clear() }
1011
+ $script:S.ring = @(); $script:S.bloom = @(); $script:S.outline = $null
1012
+ $script:S.pill = $null; $script:S.pillText = $null; $script:S.pillSub = $null
1013
+ $script:S.halo = $null; $script:S.haloBlooms = @(); $script:S.haloOn = $false
1014
+ $script:S.haloCurs = $null; $script:S.haloShape = [IntPtr]::Zero
1015
+ }
1016
+
1017
+ # Rebuilds the visual set for the current monitor geometry + phase. The Window object is never
1018
+ # touched here, so the HWND (and hwndCreateCount) survives every phase change.
1019
+ function Render-Layout {
1020
+ $m = $script:S.monitorBounds
1021
+ if ($null -eq $m) { return $false }
1022
+ $sc = [double]$script:S.scale
1023
+ if ($sc -le 0) { $sc = 1.0 }
1024
+ $W = [double]$m.w / $sc
1025
+ $H = [double]$m.h / $sc
1026
+ $T = [double]$CFG.ringPx / $sc
1027
+ $script:S.dipW = $W
1028
+ $script:S.dipH = $H
1029
+ $script:S.ringDip = $T
1030
+ $ph = $script:PH[$script:S.phase]
1031
+ if ($null -eq $ph) { $ph = $script:PH['acting'] }
1032
+ Clear-Canvas
1033
+ $ring = Build-Ring $W $H $T $ph
1034
+ foreach ($b in $ring.bloom) { [void]$script:S.canvas.Children.Add($b) }
1035
+ foreach ($b in $ring.bars) { [void]$script:S.canvas.Children.Add($b) }
1036
+ [void]$script:S.canvas.Children.Add($ring.hair)
1037
+ $script:S.ring = $ring.bars.ToArray()
1038
+ $script:S.bloom = $ring.bloom.ToArray()
1039
+ $script:S.outline = $ring.hair
1040
+ $p = Build-Pill $ph
1041
+ [void]$script:S.canvas.Children.Add($p.border)
1042
+ $script:S.pill = $p.border
1043
+ $script:S.pillText = $p.text
1044
+ $script:S.pillSub = $p.sub
1045
+ $halo = Build-Halo $ph $sc
1046
+ foreach ($it in $halo.items) { [void]$script:S.canvas.Children.Add($it) }
1047
+ $script:S.halo = $halo
1048
+ $script:S.haloOn = $false
1049
+ Update-PillText
1050
+ Position-Halo
1051
+ return $true
1052
+ }
1053
+
1054
+ function CurrentPillText {
1055
+ if (-not [string]::IsNullOrEmpty([string]$script:S.textOverride)) { return [string]$script:S.textOverride }
1056
+ $t = $script:PILL[$script:S.phase]
1057
+ if ($null -eq $t) { return '' }
1058
+ return [string]$t
1059
+ }
1060
+
1061
+ function Update-PillText {
1062
+ if ($null -eq $script:S.pillText) { return }
1063
+ $script:S.pillText.Text = (CurrentPillText)
1064
+ $sub = [string]$script:S.subtext
1065
+ if ($sub.Length -gt 120) { $sub = $sub.Substring(0, 120) }
1066
+ $script:S.pillSub.Text = $sub
1067
+ if ($sub.Length -gt 0) { $script:S.pillSub.Visibility = [System.Windows.Visibility]::Visible }
1068
+ else { $script:S.pillSub.Visibility = [System.Windows.Visibility]::Collapsed }
1069
+ Position-Pill
1070
+ }
1071
+
1072
+ # Horizontally centred, pillTopPx physical pixels below the top of THAT monitor.
1073
+ function Position-Pill {
1074
+ if ($null -eq $script:S.pill -or $null -eq $script:S.canvas) { return }
1075
+ $inf = New-Object System.Windows.Size -ArgumentList ([double]::PositiveInfinity), ([double]::PositiveInfinity)
1076
+ $script:S.pill.Measure($inf)
1077
+ $dw = [double]$script:S.pill.DesiredSize.Width
1078
+ $dh = [double]$script:S.pill.DesiredSize.Height
1079
+ if ($dw -le 0 -or [double]::IsNaN($dw)) { return }
1080
+ $sc = [double]$script:S.scale
1081
+ if ($sc -le 0) { $sc = 1.0 }
1082
+ $topDip = [double]$CFG.pillTopPx / $sc
1083
+ $leftDip = (([double]$script:S.dipW - $dw) / 2.0)
1084
+ if ($leftDip -lt 0) { $leftDip = 0.0 }
1085
+ [System.Windows.Controls.Canvas]::SetLeft($script:S.pill, [Math]::Round($leftDip, 2))
1086
+ [System.Windows.Controls.Canvas]::SetTop($script:S.pill, [Math]::Round($topDip, 2))
1087
+ $script:S.pillDipX = [Math]::Round($leftDip, 2)
1088
+ $script:S.pillDipY = [Math]::Round($topDip, 2)
1089
+ $script:S.pillDipW = [Math]::Round($dw, 2)
1090
+ $mb = $script:S.monitorBounds
1091
+ if ($null -ne $mb) {
1092
+ $script:S.pillX = [int]([double]$mb.x + $leftDip * $sc)
1093
+ $script:S.pillY = [int]([double]$mb.y + $topDip * $sc)
1094
+ $script:S.pillW = [int][Math]::Ceiling($dw * $sc)
1095
+ $script:S.pillH = [int][Math]::Ceiling($dh * $sc)
1096
+ }
1097
+ }
1098
+
1099
+ # ---------------------------------------------------------------- extended styles
1100
+ $EX_NEEDED = 0x00000020 -bor 0x00080000 -bor 0x00000080 -bor 0x08000000 # TRANSPARENT|LAYERED|TOOLWINDOW|NOACTIVATE
1101
+
1102
+ function Apply-ExStyles([IntPtr]$h) {
1103
+ if (-not $script:nativeLoaded) { return [int64]0 }
1104
+ if ($h -eq [IntPtr]::Zero) { return [int64]0 }
1105
+ try {
1106
+ $cur = [int64]([IndNative]::GetExStyle($h)) -band 0xFFFFFFFFL
1107
+ $want = ($cur -bor [int64]$EX_NEEDED -bor [int64]0x8) -band 0xFFFFFFFFL # TOPMOST is what we asked for too
1108
+ [void][IndNative]::SetExStyle($h, [int]$want)
1109
+ [void][IndNative]::ForceFrame($h)
1110
+ $final = [int64]([IndNative]::GetExStyle($h)) -band 0xFFFFFFFFL
1111
+ $script:S.exStyles = $final
1112
+ $missing = @()
1113
+ foreach ($bit in @(0x20L, 0x80000L, 0x80L, 0x8000000L)) {
1114
+ if (([int64]$final -band $bit) -ne $bit) { $missing += (ExHex $bit) }
1115
+ }
1116
+ if ($missing.Count -gt 0) {
1117
+ Log ('exStyles still missing ' + ([string]::Join(',', $missing)) + ' -- retrying')
1118
+ [void][IndNative]::SetExStyle($h, [int]$want)
1119
+ [void][IndNative]::ForceFrame($h)
1120
+ $final = [int64]([IndNative]::GetExStyle($h)) -band 0xFFFFFFFFL
1121
+ $script:S.exStyles = $final
1122
+ }
1123
+ return $final
1124
+ } catch {
1125
+ Log ('Apply-ExStyles threw: ' + $_.Exception.Message)
1126
+ return [int64]0
1127
+ }
1128
+ }
1129
+
1130
+ # ---------------------------------------------------------------- window lifecycle
1131
+ # WPF can hand out a different HWND between SourceInitialized and the end of the first Show (it
1132
+ # recreates the source when AllowsTransparency is involved), and styles applied to a discarded HWND
1133
+ # do nothing at all. So the live handle is re-read before every command and the extended styles are
1134
+ # re-applied whenever the handle moved or a bit went missing.
1135
+ function Sync-Hwnd {
1136
+ if ($null -eq $script:S.win) { return [IntPtr]::Zero }
1137
+ try {
1138
+ $helper = New-Object System.Windows.Interop.WindowInteropHelper -ArgumentList $script:S.win
1139
+ $h = $helper.Handle
1140
+ if ($h -eq [IntPtr]::Zero) { return [IntPtr]::Zero }
1141
+ $cur = [Int64]$h
1142
+ if ($cur -ne [Int64]$script:S.hwnd) {
1143
+ Log ('hwnd changed ' + [Int64]$script:S.hwnd + ' -> ' + $cur + ' (applying styles to the live handle)')
1144
+ $script:S.hwndChanges += 1
1145
+ if ([Int64]$script:S.hwnd -ne 0) { $script:S.hwndSeen += @([Int64]$script:S.hwnd) }
1146
+ $script:S.hwndSeen += @($cur)
1147
+ $script:S.hwnd = $cur
1148
+ $script:S.exStyles = 0
1149
+ Apply-ExStyles $h | Out-Null
1150
+ } else {
1151
+ # keep the bits honest: a stray SetWindowLong from WPF layout would be repaired here
1152
+ $live = [int64]([IndNative]::GetExStyle($h)) -band 0xFFFFFFFFL
1153
+ if (([int64]$live -band [int64]$EX_NEEDED) -ne [int64]$EX_NEEDED) {
1154
+ Log ('exStyles drifted to ' + (ExHex $live) + ' -- re-applying')
1155
+ Apply-ExStyles $h | Out-Null
1156
+ } else {
1157
+ $script:S.exStyles = $live
1158
+ }
1159
+ }
1160
+ return $h
1161
+ } catch {
1162
+ Log ('Sync-Hwnd threw: ' + $_.Exception.Message)
1163
+ return [IntPtr]::Zero
1164
+ }
1165
+ }
1166
+
1167
+ function Ensure-Window {
1168
+ if ($null -ne $script:S.win) { return $script:S.win }
1169
+ if ($script:S.chosenFont -eq '') { Choose-Font | Out-Null }
1170
+ $win = New-Object System.Windows.Window
1171
+ $win.Title = $script:TITLE
1172
+ $win.WindowStyle = [System.Windows.WindowStyle]::None
1173
+ $win.AllowsTransparency = $true
1174
+ $win.Background = (New-Object System.Windows.Media.SolidColorBrush -ArgumentList ([System.Windows.Media.Color]::FromArgb(0, 0, 0, 0)))
1175
+ $win.ResizeMode = [System.Windows.ResizeMode]::NoResize
1176
+ $win.ShowInTaskbar = $false
1177
+ $win.ShowActivated = $false
1178
+ $win.Topmost = $true
1179
+ $win.WindowState = [System.Windows.WindowState]::Normal
1180
+ $win.Focusable = $false
1181
+ $win.SizeToContent = [System.Windows.SizeToContent]::Manual
1182
+ $win.SnapsToDevicePixels = $true
1183
+ $win.UseLayoutRounding = $true
1184
+ $win.IsHitTestVisible = $false
1185
+ $canvas = New-Object System.Windows.Controls.Canvas
1186
+ $canvas.Background = (New-Object System.Windows.Media.SolidColorBrush -ArgumentList ([System.Windows.Media.Color]::FromArgb(0, 0, 0, 0)))
1187
+ $canvas.IsHitTestVisible = $false
1188
+ $win.Content = $canvas
1189
+ $script:S.canvas = $canvas
1190
+ $script:S.win = $win
1191
+ $script:S.built = $true
1192
+ # extended styles the moment the HWND exists, before the surface is first painted
1193
+ $win.Add_SourceInitialized({
1194
+ try {
1195
+ $helper = New-Object System.Windows.Interop.WindowInteropHelper -ArgumentList $script:S.win
1196
+ $h = $helper.Handle
1197
+ if ($h -ne [IntPtr]::Zero) {
1198
+ $script:S.hwnd = [Int64]$h
1199
+ $script:S.hwndCreateCount += 1
1200
+ Apply-ExStyles $h | Out-Null
1201
+ Log ('hwnd ' + [Int64]$script:S.hwnd + ' created, exStyles ' + (ExHex $script:S.exStyles))
1202
+ }
1203
+ } catch { Log ('SourceInitialized failed: ' + $_.Exception.Message) }
1204
+ })
1205
+ return $win
1206
+ }
1207
+
1208
+ function Move-To-Monitor($m) {
1209
+ $sc = [double]$script:S.scale
1210
+ if ($sc -le 0) { $sc = 1.0 }
1211
+ $win = $script:S.win
1212
+ # WPF measures Left/Top/Width/Height in DIPs while the pipe speaks physical pixels.
1213
+ $win.Width = [double]$m.bounds.w / $sc
1214
+ $win.Height = [double]$m.bounds.h / $sc
1215
+ $win.Left = [double]$m.bounds.x / $sc
1216
+ $win.Top = [double]$m.bounds.y / $sc
1217
+ }
1218
+
1219
+ # The window must land on the monitor to the pixel, so the scale is never trusted from one API:
1220
+ # set the size, read the real GetWindowRect back, and re-derive the DIP->pixel factor from what the
1221
+ # HWND actually did. Two passes converge; state reports the residual delta so a bad fit is visible.
1222
+ function Fit-To-Monitor($m, [int]$maxPasses) {
1223
+ $win = $script:S.win
1224
+ if ($null -eq $win -or $null -eq $m) { return }
1225
+ $target = $m.bounds
1226
+ for ($pass = 1; $pass -le $maxPasses; $pass++) {
1227
+ try { $win.UpdateLayout() } catch { }
1228
+ $r = Get-WindowRect
1229
+ if ($null -eq $r) { return }
1230
+ $script:S.fitPasses = $pass
1231
+ $script:S.fitRect = $r
1232
+ $dw = [int]$target.w - [int]$r.w
1233
+ $dh = [int]$target.h - [int]$r.h
1234
+ $dx = [int]$target.x - [int]$r.x
1235
+ $dy = [int]$target.y - [int]$r.y
1236
+ $script:S.fitDelta = [ordered]@{ w = $dw; h = $dh; x = $dx; y = $dy }
1237
+ if ([Math]::Abs($dw) -le 1 -and [Math]::Abs($dh) -le 1 -and [Math]::Abs($dx) -le 1 -and [Math]::Abs($dy) -le 1) {
1238
+ $script:S.fitConverged = $true
1239
+ return
1240
+ }
1241
+ $script:S.fitConverged = $false
1242
+ # re-derive the factor from the observed geometry, then correct
1243
+ $sc = [double]$script:S.scale
1244
+ if ([double]$win.Width -gt 1) {
1245
+ $obs = [double]$r.w / [double]$win.Width
1246
+ if ($obs -gt 0.05 -and [Math]::Abs($obs - $sc) / $sc -gt 0.002) {
1247
+ $script:S.scale = $obs
1248
+ $sc = $obs
1249
+ Render-Layout | Out-Null # ring / pill geometry is in DIPs, so rebuild it
1250
+ }
1251
+ }
1252
+ Move-To-Monitor $m
1253
+ }
1254
+ }
1255
+
1256
+ function Show-Overlay($m) {
1257
+ $win = Ensure-Window
1258
+ $script:S.monitorBounds = $m.bounds
1259
+ $script:S.monitorIndex = [int]$m.index
1260
+ $script:S.dpi = [int]$m.dpi
1261
+ # WPF's own device scale wins over the DPI APIs (measured: TransformToDevice is the number the
1262
+ # layout really uses); fall back to dpi/96 only before the first layout pass exists.
1263
+ $ds = (Get-DeviceScale)
1264
+ if ($ds -gt 0) { $script:S.scale = $ds } else { $script:S.scale = ([double]$m.dpi / 96.0) }
1265
+ Render-Layout | Out-Null
1266
+ Move-To-Monitor $m
1267
+ if (-not $script:S.visible) {
1268
+ $win.Show() # ShowActivated=false, so this never takes the foreground
1269
+ $script:S.visible = $true
1270
+ }
1271
+ Sync-Hwnd | Out-Null
1272
+ Fit-To-Monitor $m 3
1273
+ Sync-Hwnd | Out-Null
1274
+ Update-Pulse ([Diagnostics.Stopwatch]::GetTimestamp()) | Out-Null
1275
+ Start-HaloLoop
1276
+ return [IntPtr]$script:S.hwnd
1277
+ }
1278
+
1279
+ function Hide-Overlay([string]$why) {
1280
+ if ($null -eq $script:S.win) {
1281
+ $script:S.visible = $false
1282
+ $script:S.phase = 'hidden'
1283
+ Stop-RenderLoop
1284
+ Stop-HaloLoop
1285
+ return
1286
+ }
1287
+ try { $script:S.win.Hide() } catch { Log ('hide threw: ' + $_.Exception.Message) }
1288
+ $script:S.visible = $false
1289
+ $script:S.hideCount += 1
1290
+ $script:S.phase = 'hidden'
1291
+ Stop-RenderLoop
1292
+ Stop-HaloLoop
1293
+ Log ('overlay hidden (' + $why + ')')
1294
+ }
1295
+
1296
+ # ---------------------------------------------------------------- render loop / pulse
1297
+ # Only ever called when DSH_INDICATOR_RENDER_HOOK=1. renderCallbacks counts real composition frames;
1298
+ # framesRendered counts pulse updates pushed, from timer or render event whichever is driving.
1299
+ function On-Frame {
1300
+ $script:S.renderCallbacks += 1
1301
+ Pump-Inbox
1302
+ Tick-Pulse
1303
+ }
1304
+
1305
+ function Start-RenderLoop {
1306
+ if ($script:S.renderOn) { return }
1307
+ # The pulse is driven by a dispatcher timer. That is the loop: every tick pushes new values into
1308
+ # the visual tree, which is what makes WPF composite a new frame.
1309
+ if ($null -eq $script:pulseTimer) {
1310
+ $t = New-Object System.Windows.Threading.DispatcherTimer
1311
+ $t.Interval = [TimeSpan]::FromMilliseconds([double]$CFG.renderMs)
1312
+ $t.Add_Tick({ Pump-Inbox; Tick-Pulse })
1313
+ $t.Start()
1314
+ $script:pulseTimer = $t
1315
+ $script:S.timers += $t
1316
+ }
1317
+ # Subscribing to WPF's render event is only an OBSERVER, and an expensive one: measured on this
1318
+ # box it kept a 2560x1600 layered surface compositing at ~55 Hz even while only 4 updates a
1319
+ # second were pushed (14 pushes -> 189 callbacks in 3.4 s). Off by default, on for diagnostics.
1320
+ $hooked = $false
1321
+ if ($script:renderLoaded -and [int]$CFG.renderHook -eq 1) {
1322
+ try {
1323
+ [IndWpf]::StartRendering([System.Action]{ On-Frame })
1324
+ $hooked = [bool][IndWpf]::RenderingOn
1325
+ } catch {
1326
+ Log ('render subscription failed: ' + $_.Exception.Message)
1327
+ }
1328
+ }
1329
+ $script:S.renderHookOn = $hooked
1330
+ $script:S.renderDriver = if ($hooked) { 'dispatcher-timer+composition-render-event' } else { 'dispatcher-timer' }
1331
+ $script:S.renderOn = $true
1332
+ }
1333
+
1334
+ function Stop-RenderLoop {
1335
+ if ($script:renderLoaded) { try { [IndWpf]::StopRendering() } catch { } }
1336
+ if ($null -ne $script:pulseTimer) { try { $script:pulseTimer.Stop() } catch { } }
1337
+ $script:S.renderOn = $false
1338
+ $script:S.renderHookOn = $false
1339
+ }
1340
+
1341
+ $script:pulseTimer = $null
1342
+ $script:haloTimer = $null
1343
+
1344
+ # The halo is decoupled from the 100 ms pulse: a dedicated ~16 ms loop repositions it with
1345
+ # GetCursorPos, so it tracks the pointer without the one-beat lag a shared pulse tick would cause.
1346
+ function Start-HaloLoop {
1347
+ if ($null -ne $script:haloTimer) { return }
1348
+ $t = New-Object System.Windows.Threading.DispatcherTimer
1349
+ $t.Interval = [TimeSpan]::FromMilliseconds(10)
1350
+ $t.Add_Tick({ Position-Halo })
1351
+ $t.Start()
1352
+ $script:haloTimer = $t
1353
+ }
1354
+ function Stop-HaloLoop {
1355
+ if ($null -ne $script:haloTimer) { try { $script:haloTimer.Stop() } catch { } ; $script:haloTimer = $null }
1356
+ }
1357
+
1358
+ function Update-Pulse([Int64]$now) {
1359
+ $ph = $script:PH[$script:S.phase]
1360
+ $script:S.lastPulseMsWall = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1361
+ if ($null -eq $ph) { return $false }
1362
+ $period = [double]$ph.periodMs
1363
+ if ($period -le 0) { $period = 2400.0 }
1364
+ $elapsed = [double](($now - $script:S.phaseStartTick) / 10000.0)
1365
+ $frac = ($elapsed % $period) / $period
1366
+ $wave = 0.5 - 0.5 * [Math]::Cos($frac * 2.0 * [Math]::PI)
1367
+ $alpha = [double]$ph.lo + ([double]$ph.hi - [double]$ph.lo) * $wave
1368
+ $script:S.appliedAlpha = $alpha
1369
+ $script:S.pulseOffset = $frac
1370
+ $script:S.pulseAlpha = [Math]::Round($alpha, 4)
1371
+ foreach ($b in $script:S.ring) { if ($null -ne $b) { $b.Opacity = $alpha } }
1372
+ if ($null -ne $script:S.outline) { $script:S.outline.Opacity = [Math]::Min(1.0, $alpha + 0.10) }
1373
+ $bloomAlpha = $alpha * 0.55
1374
+ foreach ($b in $script:S.bloom) { if ($null -ne $b) { $b.Opacity = $bloomAlpha } }
1375
+ if ($null -ne $script:S.pill) { $script:S.pill.Opacity = [Math]::Min(1.0, 0.84 + 0.16 * $wave) }
1376
+ return $true
1377
+ }
1378
+
1379
+ # One pulse tick, from whatever source raised it. framesRendered counts ticks where a visual update
1380
+ # was actually pushed; renderCallbacks counts composition frames WPF presented.
1381
+ function Tick-Pulse {
1382
+ if ($script:S.closing -or -not $script:S.visible) { return }
1383
+ $now = [Diagnostics.Stopwatch]::GetTimestamp()
1384
+ $sinceMs = [double]$CFG.renderMs + 1
1385
+ if ($script:S.lastPulseStamp -ne 0) { $sinceMs = ($now - $script:S.lastPulseStamp) / 10000.0 }
1386
+ if ($sinceMs -lt [double]$CFG.renderMs) { return }
1387
+ $script:S.lastPulseStamp = $now
1388
+ $script:S.framesRendered += 1
1389
+ if (Update-Pulse $now) { $script:S.visualUpdates += 1 }
1390
+ Position-Halo
1391
+ }
1392
+
1393
+ # ---------------------------------------------------------------- timers
1394
+ # NOTE: this .NET Framework build's DispatcherTimer exposes only Dispatcher/IsEnabled/Interval/Tag
1395
+ # (measured) -- there is no Priority setter, so stdin latency is covered by draining the inbox in
1396
+ # every render frame as well as on this timer.
1397
+ function New-ServerTimer([double]$ms, $body) {
1398
+ $t = New-Object System.Windows.Threading.DispatcherTimer
1399
+ $t.Interval = [TimeSpan]::FromMilliseconds($ms)
1400
+ $t.Add_Tick($body)
1401
+ $t.Start()
1402
+ $script:S.timers += $t
1403
+ return $t
1404
+ }
1405
+
1406
+ # ---------------------------------------------------------------- phase
1407
+ $script:stoppedTimer = $null
1408
+ function Schedule-StoppedHide {
1409
+ if ($null -ne $script:stoppedTimer) { try { $script:stoppedTimer.Stop() } catch { } }
1410
+ $t = New-Object System.Windows.Threading.DispatcherTimer
1411
+ $t.Interval = [TimeSpan]::FromMilliseconds([double]$CFG.stoppedMs)
1412
+ $t.Add_Tick({
1413
+ try { $t.Stop() } catch { }
1414
+ if ($script:S.phase -eq 'stopped') { Hide-Overlay 'stopped auto-hide' }
1415
+ })
1416
+ $t.Start()
1417
+ $script:stoppedTimer = $t
1418
+ }
1419
+
1420
+ function Set-PhaseInPlace([string]$phase) {
1421
+ if (-not $script:PH.ContainsKey($phase)) { Err 'bad_phase' ('unknown phase ' + (OneLine $phase)) }
1422
+ $changed = ([string]$script:S.phase -ne [string]$phase)
1423
+ $script:S.phase = $phase
1424
+ $script:S.phaseStartTick = [Diagnostics.Stopwatch]::GetTimestamp()
1425
+ if ($changed -and $script:S.built) { Render-Layout | Out-Null } # recolour, same HWND
1426
+ Update-PillText
1427
+ $script:S.appliedAlpha = $null
1428
+ Update-Pulse ([Diagnostics.Stopwatch]::GetTimestamp()) | Out-Null
1429
+ }
1430
+
1431
+ # ---------------------------------------------------------------- commands
1432
+ function Screen-Json($m) {
1433
+ return [ordered]@{
1434
+ index = [int]$m.index
1435
+ device = [string]$m.device
1436
+ bounds = $m.bounds
1437
+ work = $m.work
1438
+ primary = [bool]$m.primary
1439
+ dpi = [int]$m.dpi
1440
+ }
1441
+ }
1442
+
1443
+ function Cmd-Ping($A) {
1444
+ $screens = Refresh-Screens
1445
+ $list = New-Object System.Collections.Generic.List[object]
1446
+ foreach ($m in $screens) { [void]$list.Add((Screen-Json $m)) }
1447
+ $u = [System.Windows.Forms.SystemInformation]::VirtualScreen
1448
+ $physW = 0; $physH = 0
1449
+ if ($script:nativeLoaded) { $physW = [IndNative]::PhysWidth; $physH = [IndNative]::PhysHeight }
1450
+ return [ordered]@{
1451
+ psVersion = $PSVersionTable.PSVersion.ToString()
1452
+ workerPid = [int]$PID
1453
+ apartment = [string]([Threading.Thread]::CurrentThread.GetApartmentState())
1454
+ dpiAware = [int]$script:dpiMode
1455
+ screenCount = ([array]$screens).Count
1456
+ screens = $list.ToArray()
1457
+ virtualScreen = [ordered]@{ x = [int]$u.X; y = [int]$u.Y; w = [int]$u.Width; h = [int]$u.Height }
1458
+ systemMetrics = [ordered]@{ w = [int]$physW; h = [int]$physH }
1459
+ ringPx = [int]$CFG.ringPx
1460
+ defaults = [ordered]@{ idleHideMs = [int]$CFG.idleMs; pulseMs = [int]$CFG.pulseMs; renderMs = [int]$CFG.renderMs; stoppedMs = [int]$CFG.stoppedMs; pumpMs = [int]$CFG.pumpMs; renderHook = [int]$CFG.renderHook }
1461
+ startupMs = (NowMs)
1462
+ loadMs = [double]$script:loadMs
1463
+ nativeLoaded = [bool]$script:nativeLoaded
1464
+ wpfHelper = [bool]$script:renderLoaded
1465
+ chosenFont = [string]$script:S.chosenFont
1466
+ phases = @('acting', 'stopped', 'hidden')
1467
+ }
1468
+ }
1469
+
1470
+ function Rect-From-Args($A) {
1471
+ $b = ArgOf $A 'bounds'
1472
+ if ($null -eq $b) { return $null }
1473
+ $d = Dict $b
1474
+ if (-not ($d -is [System.Collections.IDictionary])) { Err 'bad_args' 'bounds must be an object {x,y,w,h}' }
1475
+ $x = IntArg $d 'x' 0
1476
+ $y = IntArg $d 'y' 0
1477
+ $w = IntArg $d 'w' 0
1478
+ $h = IntArg $d 'h' 0
1479
+ if ($w -le 0 -or $h -le 0) { Err 'bad_args' ('bounds needs positive w/h, got w=' + $w + ' h=' + $h) }
1480
+ return [ordered]@{ x = $x; y = $y; w = $w; h = $h }
1481
+ }
1482
+
1483
+ function Get-Fg {
1484
+ if (-not $script:nativeLoaded) { return [Int64]0 }
1485
+ return [Int64]([IndNative]::GetForegroundWindow())
1486
+ }
1487
+
1488
+ function Cmd-Show($A) {
1489
+ $t0 = [Diagnostics.Stopwatch]::GetTimestamp()
1490
+ $rect = Rect-From-Args $A
1491
+ if ($null -eq $rect) {
1492
+ $prim = [System.Windows.Forms.Screen]::PrimaryScreen
1493
+ if ($null -eq $prim) { Err 'no_screen' 'no primary screen and no bounds given' }
1494
+ $b = $prim.Bounds
1495
+ $rect = [ordered]@{ x = [int]$b.X; y = [int]$b.Y; w = [int]$b.Width; h = [int]$b.Height }
1496
+ }
1497
+ $script:S.idleHideMs = IntArg $A 'idleHideMs' ([int]$CFG.idleMs)
1498
+ $phase = (StrArg $A 'phase' 'acting')
1499
+ if (-not $script:PH.ContainsKey($phase)) { Err 'bad_phase' ('unknown phase ' + (OneLine $phase)) }
1500
+ $pick = Pick-Monitor $rect
1501
+ $m = $pick.monitor
1502
+ if ($null -eq $m) { Err 'no_screen' 'monitor pick returned nothing' }
1503
+ $script:S.textOverride = (StrArg $A 'text' '')
1504
+ $script:S.subtext = (StrArg $A 'subtext' '')
1505
+ # The delivery mode decides whether the cursor halo may be drawn: only when 御屏 actually drives
1506
+ # the physical pointer (foreground, or auto which may fall back to it). In background the pointer
1507
+ # stays the user's own, so a halo there would follow their hand and misreport the action.
1508
+ $script:S.mode = (StrArg $A 'mode' 'background')
1509
+ if ($null -ne $script:stoppedTimer) { try { $script:stoppedTimer.Stop() } catch { } }
1510
+ $fgBefore = (Get-Fg)
1511
+ $hwndBefore = [Int64]$script:S.hwnd
1512
+ $prevPhase = [string]$script:S.phase
1513
+ $script:S.phase = $phase
1514
+ $script:S.phaseStartTick = [Diagnostics.Stopwatch]::GetTimestamp()
1515
+ Show-Overlay $m | Out-Null
1516
+ if ($phase -eq 'stopped') { Schedule-StoppedHide }
1517
+ if ($phase -eq 'hidden') { Hide-Overlay 'show asked for phase hidden' }
1518
+ Start-RenderLoop
1519
+ Sync-Hwnd | Out-Null
1520
+ $script:S.showCount += 1
1521
+ $script:S.straddle = [bool]$pick.straddle
1522
+ $fgAfter = (Get-Fg)
1523
+ return [ordered]@{
1524
+ visible = [bool]$script:S.visible
1525
+ hwnd = [Int64]$script:S.hwnd
1526
+ monitor = [ordered]@{ index = [int]$m.index; bounds = $m.bounds; dpi = [int]$m.dpi; device = [string]$m.device }
1527
+ monitorPicked = [int]$m.index
1528
+ pickReason = [string]$pick.reason
1529
+ straddle = [bool]$pick.straddle
1530
+ monitorsTouched = [int]$pick.monitorsTouched
1531
+ requestedBounds = $rect
1532
+ windowRect = (Get-WindowRect)
1533
+ topmost = (Ex-Has $script:S.exStyles 0x8)
1534
+ activateAttempted = $false
1535
+ foregroundBefore = $fgBefore
1536
+ foregroundAfter = $fgAfter
1537
+ foregroundMoved = ($fgBefore -ne $fgAfter)
1538
+ reusedHwnd = ($hwndBefore -ne 0 -and $hwndBefore -eq [Int64]$script:S.hwnd)
1539
+ phase = [string]$script:S.phase
1540
+ prevPhase = $prevPhase
1541
+ text = (CurrentPillText)
1542
+ dpi = [int]$script:S.dpi
1543
+ scale = [Math]::Round([double]$script:S.scale, 4)
1544
+ ringDip = [Math]::Round([double]$script:S.ringDip, 2)
1545
+ deviceScale = [Math]::Round((Get-DeviceScale), 4)
1546
+ fitPasses = [int]$script:S.fitPasses
1547
+ fitConverged = [bool]$script:S.fitConverged
1548
+ fitDelta = $script:S.fitDelta
1549
+ hwndChanges = [Int64]$script:S.hwndChanges
1550
+ pillRect = (Get-PillRect)
1551
+ idleHideMs = [int]$script:S.idleHideMs
1552
+ hwndCreateCount = [Int64]$script:S.hwndCreateCount
1553
+ ms = (Elapsed $t0)
1554
+ }
1555
+ }
1556
+
1557
+ function Cmd-Beat($A) {
1558
+ $t0 = [Diagnostics.Stopwatch]::GetTimestamp()
1559
+ Sync-Hwnd | Out-Null
1560
+ $hwndBefore = [Int64]$script:S.hwnd
1561
+ if (-not $script:S.built -or $null -eq $script:S.monitorBounds) {
1562
+ # nothing to re-assert yet: paint on the primary so a heartbeat can always be seen
1563
+ $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
1564
+ $rect = [ordered]@{ x = [int]$b.X; y = [int]$b.Y; w = [int]$b.Width; h = [int]$b.Height }
1565
+ $pick = Pick-Monitor $rect
1566
+ Show-Overlay $pick.monitor | Out-Null
1567
+ Start-RenderLoop
1568
+ }
1569
+ $tx = ArgOf $A 'text'
1570
+ if ($null -ne $tx) { $script:S.textOverride = [string]$tx }
1571
+ $sb = ArgOf $A 'subtext'
1572
+ if ($null -ne $sb) { $script:S.subtext = [string]$sb }
1573
+ $md = ArgOf $A 'mode'
1574
+ if ($null -ne $md) { $script:S.mode = [string]$md }
1575
+ if ($null -ne $script:stoppedTimer) { try { $script:stoppedTimer.Stop() } catch { } }
1576
+ if ($script:S.phase -eq 'stopped') {
1577
+ Set-PhaseInPlace 'acting'
1578
+ } elseif (-not $script:S.visible) {
1579
+ $script:S.win.Show()
1580
+ $script:S.visible = $true
1581
+ Set-PhaseInPlace 'acting'
1582
+ Start-RenderLoop
1583
+ } else {
1584
+ Update-PillText
1585
+ }
1586
+ $script:S.stats.beats += 1
1587
+ return [ordered]@{
1588
+ visible = [bool]$script:S.visible
1589
+ hwnd = [Int64]$script:S.hwnd
1590
+ reusedHwnd = ($hwndBefore -ne 0 -and $hwndBefore -eq [Int64]$script:S.hwnd)
1591
+ hwndCreateCount = [Int64]$script:S.hwndCreateCount
1592
+ phase = [string]$script:S.phase
1593
+ text = (CurrentPillText)
1594
+ subtext = [string]$script:S.subtext
1595
+ framesRendered = [Int64]$script:S.framesRendered
1596
+ ms = (Elapsed $t0)
1597
+ }
1598
+ }
1599
+
1600
+ function Cmd-Phase($A) {
1601
+ $t0 = [Diagnostics.Stopwatch]::GetTimestamp()
1602
+ Sync-Hwnd | Out-Null
1603
+ $phase = (StrArg $A 'phase' '')
1604
+ if ([string]::IsNullOrEmpty($phase)) { Err 'bad_args' 'phase requires a phase name' }
1605
+ if (-not $script:PH.ContainsKey($phase)) { Err 'bad_phase' ('unknown phase ' + (OneLine $phase)) }
1606
+ if ($null -ne (ArgOf $A 'text')) { $script:S.textOverride = [string](ArgOf $A 'text') }
1607
+ else { $script:S.textOverride = '' } # a phase change shows the phase's own wording
1608
+ $sb = ArgOf $A 'subtext'
1609
+ if ($null -ne $sb) { $script:S.subtext = [string]$sb }
1610
+ $hwndBefore = [Int64]$script:S.hwnd
1611
+ $wasVisible = [bool]$script:S.visible
1612
+ $autoHide = $null
1613
+ if ($phase -eq 'stopped') { $autoHide = [int]$CFG.stoppedMs }
1614
+ if ($phase -eq 'hidden') {
1615
+ Hide-Overlay 'phase hidden'
1616
+ } else {
1617
+ if ($null -eq $script:S.monitorBounds) {
1618
+ # never shown in this process: the primary monitor is the only sane default
1619
+ $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
1620
+ $rect = [ordered]@{ x = [int]$b.X; y = [int]$b.Y; w = [int]$b.Width; h = [int]$b.Height }
1621
+ $pick = Pick-Monitor $rect
1622
+ Show-Overlay $pick.monitor | Out-Null
1623
+ } elseif (-not $wasVisible) {
1624
+ $mm = [ordered]@{ index = [int]$script:S.monitorIndex; bounds = $script:S.monitorBounds; dpi = [int]$script:S.dpi }
1625
+ Show-Overlay $mm | Out-Null
1626
+ }
1627
+ Set-PhaseInPlace $phase
1628
+ if ($phase -eq 'stopped') { Schedule-StoppedHide }
1629
+ Start-RenderLoop
1630
+ }
1631
+ return [ordered]@{
1632
+ visible = [bool]$script:S.visible
1633
+ hwnd = [Int64]$script:S.hwnd
1634
+ reusedHwnd = ($hwndBefore -ne 0 -and $hwndBefore -eq [Int64]$script:S.hwnd)
1635
+ hwndCreateCount = [Int64]$script:S.hwndCreateCount
1636
+ phase = [string]$script:S.phase
1637
+ text = (CurrentPillText)
1638
+ periodMs = [int]$script:PH[$script:S.phase].periodMs
1639
+ autoHideAfterMs = $autoHide
1640
+ ms = (Elapsed $t0)
1641
+ }
1642
+ }
1643
+
1644
+ function Test-HwndAlive {
1645
+ if ($script:S.hwnd -eq 0) { return $false }
1646
+ if (-not $script:nativeLoaded) { return $true }
1647
+ try { return [bool][IndNative]::IsWindow([IntPtr]$script:S.hwnd) } catch { return $false }
1648
+ }
1649
+
1650
+ function Get-WindowRect {
1651
+ if ($script:S.hwnd -eq 0) { return $null }
1652
+ if (-not $script:nativeLoaded) { return $null }
1653
+ try {
1654
+ $r = New-Object 'IndNative+RECT'
1655
+ if ([IndNative]::GetWindowRect([IntPtr]$script:S.hwnd, [ref]$r)) {
1656
+ return [ordered]@{ x = [int]$r.Left; y = [int]$r.Top; w = [int]($r.Right - $r.Left); h = [int]($r.Bottom - $r.Top) }
1657
+ }
1658
+ } catch { }
1659
+ return $null
1660
+ }
1661
+
1662
+ function Get-PillRect {
1663
+ return [ordered]@{
1664
+ x = [int]$script:S.pillX
1665
+ y = [int]$script:S.pillY
1666
+ w = [int]$script:S.pillW
1667
+ h = [int]$script:S.pillH
1668
+ dipX = [double]$script:S.pillDipX
1669
+ dipY = [double]$script:S.pillDipY
1670
+ dipW = [double]$script:S.pillDipW
1671
+ centre = [int]([int]$script:S.pillX + [int]([int]$script:S.pillW / 2))
1672
+ }
1673
+ }
1674
+
1675
+ function Cmd-Shutdown($A) {
1676
+ $t0 = [Diagnostics.Stopwatch]::GetTimestamp()
1677
+ return [ordered]@{
1678
+ closed = $true
1679
+ visible = [bool]$script:S.visible
1680
+ framesRendered = [Int64]$script:S.framesRendered
1681
+ uptimeMs = (NowMs)
1682
+ ms = (Elapsed $t0)
1683
+ }
1684
+ }
1685
+
1686
+ function Cmd-EscapePressed($A) {
1687
+ # Mirrors the worker's escape_pressed contract ({pressed: bool}), but latches instead of
1688
+ # sampling. The old probe read only the high bit ("is the key down at this instant"), so a
1689
+ # normal tap shorter than the host's 40 ms poll interval could be pressed and released
1690
+ # entirely between two probes and never seen - the "点 ESC 停止很慢" complaint. GetAsyncKeyState's
1691
+ # LOW bit means "the key was pressed since the previous call to this function", which is exactly
1692
+ # the edge we were missing: the next poll consumes it no matter how brief the press was.
1693
+ # Both bits are consumed in one call, so a single tap cannot report twice.
1694
+ $pressed = $false
1695
+ if ($script:nativeLoaded) {
1696
+ try {
1697
+ $state = [int][IndNative]::GetAsyncKeyState(0x1B)
1698
+ $held = ($state -band 0x8000) -ne 0
1699
+ $edge = ($state -band 0x0001) -ne 0
1700
+ $pressed = $held -or $edge
1701
+ } catch { $pressed = $false }
1702
+ }
1703
+ return [ordered]@{ pressed = [bool]$pressed }
1704
+ }
1705
+
1706
+ # ---------------------------------------------------------------- dispatch
1707
+ $handlers = @{
1708
+ ping = 'Cmd-Ping'
1709
+ show = 'Cmd-Show'
1710
+ beat = 'Cmd-Beat'
1711
+ phase = 'Cmd-Phase'
1712
+ shutdown = 'Cmd-Shutdown'
1713
+ escape_pressed = 'Cmd-EscapePressed'
1714
+ }
1715
+
1716
+ function Invoke-Request($line) {
1717
+ $id = 0
1718
+ $cmd = ''
1719
+ $A = @{}
1720
+ $script:S.lastCmdTick = [Diagnostics.Stopwatch]::GetTimestamp()
1721
+ try {
1722
+ $obj = $null
1723
+ try { $obj = ConvertFrom-Json $line } catch { Send-Err 0 'bad_json' ('not valid JSON: ' + $_.Exception.Message); return $true }
1724
+ if ($null -eq $obj) { Send-Err 0 'bad_json' 'empty request'; return $true }
1725
+ $pp = $obj.PSObject.Properties['id']
1726
+ if ($null -ne $pp -and $null -ne $pp.Value) { try { $id = [long]$pp.Value } catch { $id = 0 } }
1727
+ $pp = $obj.PSObject.Properties['cmd']
1728
+ if ($null -ne $pp -and $null -ne $pp.Value) { $cmd = [string]$pp.Value }
1729
+ $pp = $obj.PSObject.Properties['args']
1730
+ if ($null -ne $pp -and $null -ne $pp.Value) { $d = Dict $pp.Value; if ($d -is [System.Collections.IDictionary]) { $A = $d } }
1731
+ if ($cmd -eq '' -or -not $handlers.ContainsKey($cmd)) {
1732
+ Send-Err $id 'unknown_cmd' ("unknown cmd '" + (OneLine $cmd) + "'")
1733
+ return $true
1734
+ }
1735
+ $fn = $handlers[$cmd]
1736
+ # One choke point for plugin-supplied colour: every command that carries a
1737
+ # palette gets it applied here, and the outcome rides back in the response so
1738
+ # an unread parameter cannot pass as success.
1739
+ $script:S.lastPalette = $null
1740
+ if ($null -ne (ArgOf $A 'palette')) {
1741
+ Apply-Palette $A | Out-Null
1742
+ if ($script:S.lastPalette.applied -and $script:S.built) { Render-Layout | Out-Null }
1743
+ }
1744
+ $result = & $fn $A
1745
+ if ($cmd -eq 'shutdown') {
1746
+ Send-Ok $id $result
1747
+ Close-Server 'shutdown command'
1748
+ return $false
1749
+ }
1750
+ Send-Ok $id $result
1751
+ } catch {
1752
+ $code, $msg = Split-Err $_
1753
+ Log ((OneLine $cmd) + ' -> ' + $code + ': ' + (OneLine $msg))
1754
+ Send-Err $id $code $msg
1755
+ }
1756
+ return $true
1757
+ }
1758
+
1759
+ # ---------------------------------------------------------------- stdin reader (separate runspace)
1760
+ $script:inbox = New-Object System.Collections.Concurrent.ConcurrentQueue[string]
1761
+ $script:readerPs = $null
1762
+ $script:readerRs = $null
1763
+
1764
+ function Start-StdinReader {
1765
+ $rs = [runspacefactory]::CreateRunspace()
1766
+ $rs.ApartmentState = 'MTA'
1767
+ $rs.ThreadOptions = 'ReuseThread'
1768
+ $rs.Open()
1769
+ $ps = [PowerShell]::Create()
1770
+ $ps.Runspace = $rs
1771
+ [void]$ps.AddScript({
1772
+ param($q, $wake)
1773
+ $eof = '__EOF__'
1774
+ try {
1775
+ while ($true) {
1776
+ $line = $null
1777
+ try { $line = [Console]::In.ReadLine() } catch { [void]$q.Enqueue($eof); if ($wake) { [IndWake]::Notify() }; return }
1778
+ if ($null -eq $line) { [void]$q.Enqueue($eof); if ($wake) { [IndWake]::Notify() }; return }
1779
+ if ($line.Length -eq 0) { continue }
1780
+ if ($line.Length -gt 200000) { [void]$q.Enqueue('__TOOLONG__'); if ($wake) { [IndWake]::Notify() }; continue }
1781
+ [void]$q.Enqueue($line)
1782
+ if ($wake) { [IndWake]::Notify() }
1783
+ }
1784
+ } catch {
1785
+ [void]$q.Enqueue($eof)
1786
+ if ($wake) { [IndWake]::Notify() }
1787
+ }
1788
+ })
1789
+ [void]$ps.AddArgument($script:inbox)
1790
+ [void]$ps.AddArgument([bool]$script:nativeLoaded)
1791
+ $script:readerRs = $rs
1792
+ $script:readerPs = $ps
1793
+ [void]$ps.BeginInvoke()
1794
+ }
1795
+
1796
+ function Pump-Inbox {
1797
+ $line = $null
1798
+ $n = 0
1799
+ while ($n -lt 32) {
1800
+ if (-not $script:inbox.TryDequeue([ref]$line)) { break }
1801
+ $n += 1
1802
+ if ($line -eq '__EOF__') {
1803
+ Log 'stdin EOF, exiting'
1804
+ Close-Server 'stdin EOF'
1805
+ return
1806
+ }
1807
+ if ($line -eq '__TOOLONG__') { Send-Err 0 'bad_json' 'request line exceeds 200000 chars'; $line = $null; continue }
1808
+ if (-not (Invoke-Request $line)) { return }
1809
+ $line = $null
1810
+ }
1811
+ }
1812
+
1813
+ # ---------------------------------------------------------------- shutdown path
1814
+ function Close-Server([string]$why) {
1815
+ if ($script:S.closing) { return }
1816
+ $script:S.closing = $true
1817
+ Log ('closing (' + $why + ')')
1818
+ try { Stop-RenderLoop } catch { }
1819
+ try { if ($null -ne $script:stoppedTimer) { $script:stoppedTimer.Stop() } } catch { }
1820
+ foreach ($t in $script:S.timers) { try { $t.Stop() } catch { } }
1821
+ if ($null -ne $script:S.win) {
1822
+ try { $script:S.win.Hide() } catch { }
1823
+ $script:S.visible = $false
1824
+ $aliveBefore = (Test-HwndAlive)
1825
+ try { $script:S.win.Close() } catch { Log ('window close threw: ' + $_.Exception.Message) }
1826
+ $aliveAfter = (Test-HwndAlive)
1827
+ Log ('hwnd ' + [Int64]$script:S.hwnd + ' IsWindow before close = ' + $aliveBefore + ', after close = ' + $aliveAfter)
1828
+ }
1829
+ try { $script:S.canvas = $null; $script:S.win = $null; $script:S.ring = @(); $script:S.bloom = @() } catch { }
1830
+ try { if ($null -ne $script:S.app) { $script:S.app.Shutdown() } } catch { }
1831
+ try { if ($null -ne $script:dispatcher) { $script:dispatcher.InvokeShutdown() } } catch { }
1832
+ # A stuck overlay is the worst failure mode on this list, so unwinding the dispatcher is not
1833
+ # trusted to be the only exit path: if Run() has not returned within 1500 ms the process exits
1834
+ # from a thread-pool timer. The window is already hidden and closed at this point.
1835
+ try {
1836
+ $code = [int]$script:S.exitCode
1837
+ $timer = [System.Threading.Timer]::new(
1838
+ [System.Threading.TimerCallback]{ param($st) try { [Environment]::Exit($code) } catch { } },
1839
+ $null, 1500, [System.Threading.Timeout]::Infinite)
1840
+ $script:exitWatchdog = $timer
1841
+ } catch { Log ('exit watchdog failed: ' + $_.Exception.Message) }
1842
+ }
1843
+
1844
+ # ---------------------------------------------------------------- bootstrap
1845
+ $script:dispatcher = [System.Windows.Threading.Dispatcher]::CurrentDispatcher
1846
+ $script:S.dispatcher = $script:dispatcher
1847
+ $script:pumpAction = [System.Action]{ Pump-Inbox; [IndWake]::Clear() }
1848
+ $app = New-Object System.Windows.Application
1849
+ $app.ShutdownMode = [System.Windows.ShutdownMode]::OnExplicitShutdown
1850
+ $script:S.app = $app
1851
+ try { [IndWake]::Init($script:dispatcher, $script:pumpAction) } catch { Log ('wake init failed: ' + $_.Exception.Message) }
1852
+ Refresh-Screens | Out-Null
1853
+ Choose-Font | Out-Null
1854
+ $script:S.lastPulseMsWall = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
1855
+
1856
+ # Idle safety-net pump. Lines are normally handled the moment they arrive via [IndWake]::Notify,
1857
+ # so this only has to catch a missed signal; 250 ms costs almost nothing when nothing is happening.
1858
+ New-ServerTimer ([double]$CFG.pumpMs) { Pump-Inbox } | Out-Null
1859
+
1860
+ # watchdog: idle auto-hide + a focus-theft tripwire
1861
+ New-ServerTimer 250 {
1862
+ if ($script:S.visible) {
1863
+ $idle = (SinceMs $script:S.lastCmdTick)
1864
+ if ([int]$script:S.idleHideMs -gt 0 -and $idle -gt [double]$script:S.idleHideMs) {
1865
+ $script:S.autoHides += 1
1866
+ $script:S.stats.autoHides += 1
1867
+ Log ('idle ' + [Math]::Round($idle, 0) + ' ms > idleHideMs ' + $script:S.idleHideMs + ' -- auto-hiding')
1868
+ Hide-Overlay 'idle auto-hide'
1869
+ }
1870
+ if ($script:nativeLoaded -and [Int64]$script:S.hwnd -ne 0) {
1871
+ try {
1872
+ if ((Get-Fg) -eq [Int64]$script:S.hwnd) {
1873
+ $script:S.fgThefts += 1
1874
+ Log 'tripwire: the overlay became GetForegroundWindow() despite NOACTIVATE'
1875
+ }
1876
+ } catch { }
1877
+ }
1878
+ }
1879
+ } | Out-Null
1880
+
1881
+ # Warm the HWND and the render pipeline NOW rather than at run start: the first Show() of an
1882
+ # AllowsTransparency surface costs about a second (measured 1038 ms before this existed), which is
1883
+ # the difference between the overlay appearing with the action and appearing after it. The window is
1884
+ # parked far off every monitor, sized 4x4, shown once and hidden again -- the log line records the
1885
+ # rect it actually landed at, so "off screen" is a measurement and not a claim.
1886
+ function Warm-Window {
1887
+ try {
1888
+ $win = Ensure-Window
1889
+ $script:S.monitorBounds = $null
1890
+ $win.Width = 4.0
1891
+ $win.Height = 4.0
1892
+ $win.Left = -32000.0
1893
+ $win.Top = -32000.0
1894
+ $win.Show()
1895
+ $script:S.visible = $true
1896
+ Sync-Hwnd | Out-Null
1897
+ try { $win.Hide() } catch { }
1898
+ $script:S.visible = $false
1899
+ $r = Get-WindowRect
1900
+ $where = if ($null -eq $r) { 'unknown' } else { ([string]$r.x) + ',' + ([string]$r.y) + ' ' + ([string]$r.w) + 'x' + ([string]$r.h) }
1901
+ Log ('warm: hwnd ' + [Int64]$script:S.hwnd + ' parked at ' + $where + ', exStyles ' + (ExHex $script:S.exStyles) + ', ms ' + (NowMs))
1902
+ } catch {
1903
+ Log ('warm-up failed: ' + $_.Exception.Message)
1904
+ }
1905
+ }
1906
+
1907
+ Warm-Window
1908
+
1909
+ Start-StdinReader
1910
+ Log ('listening on stdin (pid ' + $PID + ', ps ' + $PSVersionTable.PSVersion + ', apt ' +
1911
+ ([Threading.Thread]::CurrentThread.GetApartmentState()) + ', dpiAware ' + $script:dpiMode +
1912
+ ', screens ' + ([array]$script:S.screens).Count + ', font "' + $script:S.chosenFont + '" glyphsOk ' +
1913
+ [bool]$script:S.fontProbe.allGlyphsPresent + ', wpfHelper ' + [bool]$script:renderLoaded +
1914
+ ', startup ' + (NowMs) + ' ms)')
1915
+
1916
+ # Dispatcher.Run() is a STATIC method on this framework (it drives the current thread's dispatcher),
1917
+ # so it cannot be called through the instance reference.
1918
+ [System.Windows.Threading.Dispatcher]::Run()
1919
+ Log 'dispatcher returned'
1920
+
1921
+ # The reader runspace is deliberately NOT disposed: its pipeline is parked in Console.In.ReadLine(),
1922
+ # and Dispose() waits for the pipeline to finish -- which never happens while the parent still holds
1923
+ # the pipe open. That hang was measured (shutdown answered, process lived on). Environment.Exit
1924
+ # tears the process down for real, and the window is already hidden and closed by Close-Server.
1925
+ $exitCode = 0
1926
+ try { $exitCode = [int]$script:S.exitCode } catch { }
1927
+ Log ('exiting ' + $exitCode + ' (uptime ' + (NowMs) + ' ms, frames ' + [Int64]$script:S.framesRendered + ')')
1928
+ [System.Environment]::Exit($exitCode)