dsh-native-uia 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +663 -2
  3. package/client/client.js +269 -0
  4. package/cordis.patch.yml +10 -0
  5. package/icon.svg +11 -0
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/package.json +75 -4
  9. package/scripts/bench-live.mjs +157 -0
  10. package/scripts/check-lease.mjs +308 -0
  11. package/scripts/install.mjs +154 -0
  12. package/scripts/lib/dsh-tools-stub.mjs +14 -0
  13. package/scripts/lib/load-tools-source.mjs +25 -0
  14. package/scripts/lib/sources.mjs +62 -0
  15. package/scripts/load-tools.mjs +74 -0
  16. package/scripts/measure-parse.mjs +77 -0
  17. package/scripts/regression-halt-latch.mjs +100 -0
  18. package/scripts/regression-quality.mjs +207 -0
  19. package/scripts/regression-tools.mjs +192 -0
  20. package/scripts/regression-worker.ps1 +1071 -0
  21. package/scripts/smoke.mjs +158 -0
  22. package/scripts/verify-capture-scale.mjs +37 -0
  23. package/scripts/verify-live-clipboard.mjs +108 -0
  24. package/scripts/verify-live-style.mjs +46 -0
  25. package/scripts/verify-live.mjs +104 -0
  26. package/scripts/verify-locator.mjs +52 -0
  27. package/scripts/verify.mjs +2110 -0
  28. package/src/activity-window.js +276 -0
  29. package/src/dashboard.js +103 -0
  30. package/src/guard.js +201 -0
  31. package/src/index.js +525 -0
  32. package/src/native-uia-remote.js +80 -0
  33. package/src/notes.js +83 -0
  34. package/src/state.js +267 -0
  35. package/src/themes.js +74 -0
  36. package/src/tools/defs/act.js +533 -0
  37. package/src/tools/defs/lifecycle.js +205 -0
  38. package/src/tools/defs/observe.js +309 -0
  39. package/src/tools/defs/pointer.js +298 -0
  40. package/src/tools/format.js +301 -0
  41. package/src/tools/index.js +128 -0
  42. package/src/tools/ocr.js +91 -0
  43. package/src/tools/recipes.js +44 -0
  44. package/src/tools/runtime.js +42 -0
  45. package/src/worker-client.js +268 -0
  46. package/worker/assets/dsh-whale.path +1 -0
  47. package/worker/bin/build-ocr.ps1 +41 -0
  48. package/worker/bin/ocr.cs +69 -0
  49. package/worker/bin/ocr.exe +0 -0
  50. package/worker/indicator-server.ps1 +2963 -0
  51. package/worker/lib/01-core.ps1 +64 -0
  52. package/worker/lib/02-uia.ps1 +221 -0
  53. package/worker/lib/03-window.ps1 +194 -0
  54. package/worker/lib/04-match.ps1 +435 -0
  55. package/worker/lib/05-value.ps1 +149 -0
  56. package/worker/lib/06-snapshot.ps1 +345 -0
  57. package/worker/lib/07-action.ps1 +291 -0
  58. package/worker/lib/08-command.ps1 +1485 -0
  59. package/worker/lib/09-pointer.ps1 +840 -0
  60. package/worker/lib/10-dispatch.ps1 +134 -0
  61. package/worker/ps-stdio.ps1 +173 -0
  62. package/worker/uia-worker.ps1 +599 -0
@@ -0,0 +1,2963 @@
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' 33 # 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 @(0x44, 0x53, 0x48) # "DSH" — the host's name, not the plugin's
375
+ dot = CU @(0x00B7) # middle dot
376
+ acting = CU @(0x6B63, 0x5728, 0x64CD, 0x63A7, 0x7535, 0x8111) # "currently controlling the computer"
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. The brand is the
381
+ # host (DSH), because the person at the keyboard is sharing their desktop with the harness, not
382
+ # with a plugin — 御屏 is what this thing is called in the plugin list, not what is on their screen.
383
+ # There are two visible phases, not three: a paused state was removed from the product, so the
384
+ # capsule only ever says "acting" or (briefly, on the way out) "stopped".
385
+ $script:PILL = @{
386
+ acting = ($script:TEXT.brand + ' ' + $script:TEXT.dot + ' ' + $script:TEXT.acting)
387
+ stopped = ($script:TEXT.brand + ' ' + $script:TEXT.dot + ' ' + $script:TEXT.stopped)
388
+ hidden = ''
389
+ }
390
+ $script:TITLE = 'dsh-yuping-indicator'
391
+
392
+ # ---------------------------------------------------------------- phase palettes (RGB triples)
393
+ function ColA([double]$a, $rgb) {
394
+ $al = [int][Math]::Round($a * 255.0)
395
+ if ($al -lt 0) { $al = 0 }; if ($al -gt 255) { $al = 255 }
396
+ return [System.Windows.Media.Color]::FromArgb([byte]$al, [byte]$rgb[0], [byte]$rgb[1], [byte]$rgb[2])
397
+ }
398
+ $script:PH = @{
399
+ acting = @{ periodMs = [int]$CFG.pulseMs; lo = 0.68; hi = 1.00; base = @(169, 180, 196); g0 = @(230, 235, 242); g1 = @(147, 161, 181) }
400
+ # stopped stays warm red on purpose: silver means "machine is driving", red means "it let go".
401
+ stopped = @{ periodMs = 900; lo = 0.72; hi = 1.00; base = @(255, 91, 93); g0 = @(255, 93, 93); g1 = @(232, 54, 93) }
402
+ hidden = @{ periodMs = [int]$CFG.pulseMs; lo = 0.55; hi = 1.00; base = @(169, 180, 196); g0 = @(230, 235, 242); g1 = @(147, 161, 181) }
403
+ }
404
+
405
+ # ---------------------------------------------------------------- plugin-supplied palette
406
+ function Hex-Triple($v) {
407
+ if ($null -eq $v) { return $null }
408
+ $s = ([string]$v).Trim().TrimStart('#')
409
+ if ($s.Length -ne 6) { return $null }
410
+ try {
411
+ return @([Convert]::ToInt32($s.Substring(0,2),16), [Convert]::ToInt32($s.Substring(2,2),16), [Convert]::ToInt32($s.Substring(4,2),16))
412
+ } catch { return $null }
413
+ }
414
+
415
+ function PalGet($d, $k) {
416
+ if ($null -eq $d) { return $null }
417
+ foreach ($key in $d.Keys) { if ([string]$key -eq [string]$k) { return $d[$key] } }
418
+ return $null
419
+ }
420
+
421
+ # Colour is plugin data: the Node side owns it and hands it over on every
422
+ # state-changing command. Unusable values are reported back instead of being
423
+ # silently dropped, so a parameter nobody reads cannot survive as a green answer.
424
+ function Apply-Palette($A) {
425
+ # The receipt is written to script state, not returned: a PowerShell function's
426
+ # return value collects every stray pipeline object, so a returned hashtable can
427
+ # silently arrive at the caller as Object[].
428
+ $script:S.lastPalette = [ordered]@{ applied = $false; keys = @(); rejected = @() }
429
+ $p = ArgOf $A 'palette'
430
+ if ($null -eq $p) { return }
431
+ $d = $null
432
+ try { $d = Dict $p } catch { $d = $null }
433
+ if ($d -isnot [System.Collections.IDictionary]) {
434
+ $script:S.lastPalette.rejected = @('palette is not an object')
435
+ return
436
+ }
437
+ $keys = New-Object System.Collections.Generic.List[string]
438
+ $rejected = New-Object System.Collections.Generic.List[string]
439
+ $pairs = @{ acting = @('ringFrom','ringTo'); hidden = @('ringFrom','ringTo') }
440
+ $accent = Hex-Triple (PalGet $d 'pillBorder')
441
+ foreach ($phase in @('acting','hidden')) {
442
+ $from = Hex-Triple (PalGet $d $pairs[$phase][0])
443
+ $to = Hex-Triple (PalGet $d $pairs[$phase][1])
444
+ if ($null -eq $from -or $null -eq $to) {
445
+ [void]$rejected.Add($phase + ': missing ' + $pairs[$phase][0] + '/' + $pairs[$phase][1])
446
+ continue
447
+ }
448
+ $script:PH[$phase].g0 = $from
449
+ $script:PH[$phase].g1 = $to
450
+ if ($null -ne $accent) { $script:PH[$phase].base = $accent }
451
+ [void]$keys.Add($phase)
452
+ }
453
+ $bg = Hex-Triple (PalGet $d 'pillBg')
454
+ if ($null -ne $bg) { $script:S.pillBg = $bg; [void]$keys.Add('pillBg') }
455
+ $fg = Hex-Triple (PalGet $d 'pillText')
456
+ if ($null -ne $fg) { $script:S.pillText = $fg; [void]$keys.Add('pillText') }
457
+ $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]) }
458
+ $script:S.lastPalette = [ordered]@{
459
+ applied = ($keys.Count -gt 0)
460
+ keys = @($keys)
461
+ rejected = @($rejected)
462
+ # The colours now actually in the render table: what the screen will show,
463
+ # not merely what the caller asked for.
464
+ acting = [ordered]@{ g0 = (& $hexOf $script:PH.acting.g0); g1 = (& $hexOf $script:PH.acting.g1); base = (& $hexOf $script:PH.acting.base) }
465
+ }
466
+ return
467
+ }
468
+
469
+ # ---------------------------------------------------------------- server state
470
+ $script:S = [ordered]@{
471
+ startTick = [Diagnostics.Stopwatch]::GetTimestamp()
472
+ app = $null
473
+ dispatcher = $null
474
+ win = $null
475
+ canvas = $null
476
+ ring = @()
477
+ bloom = @()
478
+ outline = $null
479
+ halo = $null
480
+ haloBlooms = @()
481
+ haloX = 0
482
+ haloY = 0
483
+ haloOn = $false
484
+ haloCurs = $null
485
+ haloShape = [IntPtr]::Zero
486
+ haloPad = 0
487
+ pill = $null
488
+ pillText = $null
489
+ pillSub = $null
490
+ pillOrb = $null
491
+ pillOrbScale = $null
492
+ pillOrbHalo = $null
493
+ pillOrbHaloScale = $null
494
+ pillBars = @()
495
+ pillStyle = 'orb'
496
+ # Whether the thin smoke at the lip is drawn. Decoration only, so it is the person's switch; it
497
+ # is part of the look, which is why it joins the layout key rather than being applied in place.
498
+ mistOn = $true
499
+ lookVersion = 0
500
+ # How many times the visual tree has been thrown away (each one replays the intro animation).
501
+ layoutBuilds = 0
502
+ # The palette signature last baked into the tree. The plugin re-sends the palette on every command,
503
+ # so this is what distinguishes "same colours again" from "the person changed the theme".
504
+ paletteSig = ''
505
+ layoutKey = ''
506
+ pillScale = $null
507
+ pillBrandRun = $null
508
+ pillRestRun = $null
509
+ built = $false
510
+ visible = $false
511
+ hwnd = [Int64]0
512
+ monitorIndex = -1
513
+ monitorBounds = $null
514
+ scale = 1.0
515
+ dpi = 96
516
+ phase = 'hidden'
517
+ mode = 'background'
518
+ textOverride = ''
519
+ subtext = ''
520
+ framesRendered = [Int64]0
521
+ renderCallbacks = [Int64]0
522
+ visualUpdates = [Int64]0
523
+ appliedAlpha = $null
524
+ renderOn = $false
525
+ renderHookOn = $false
526
+ renderDriver = ''
527
+ lastPulseStamp = [Int64]0
528
+ lastPulseMsWall = [Int64]0
529
+ phaseStartTick = [Diagnostics.Stopwatch]::GetTimestamp()
530
+ pulseOffset = 0.0
531
+ pulseAlpha = 0.0
532
+ exStyles = 0
533
+ straddle = $false
534
+ idleHideMs = [int]$CFG.idleMs
535
+ lastCmdTick = [Diagnostics.Stopwatch]::GetTimestamp()
536
+ autoHides = [Int64]0
537
+ showCount = [Int64]0
538
+ hideCount = [Int64]0
539
+ hwndCreateCount = [Int64]0
540
+ hwndChanges = [Int64]0
541
+ hwndSeen = @()
542
+ fitPasses = 0
543
+ fitConverged = $false
544
+ fitDelta = $null
545
+ fitRect = $null
546
+ fgThefts = [Int64]0
547
+ fontProbe = $null
548
+ chosenFont = ''
549
+ dipW = 0.0
550
+ dipH = 0.0
551
+ ringDip = 0.0
552
+ pillX = 0
553
+ pillY = 0
554
+ pillW = 0
555
+ pillH = 0
556
+ exitCode = 0
557
+ closing = $false
558
+ screens = @()
559
+ timers = @()
560
+ stats = @{ commands = 0; refused = 0; beats = 0; autoHides = 0 }
561
+ }
562
+
563
+ # ---------------------------------------------------------------- framing / io
564
+ $script:utf8NoBom = New-Object System.Text.UTF8Encoding($false)
565
+ try {
566
+ [Console]::InputEncoding = $script:utf8NoBom
567
+ [Console]::OutputEncoding = $script:utf8NoBom
568
+ } catch { }
569
+
570
+ # Esc/JsonOf/OneLine/Err/ArgOf/IntArg/StrArg/BoolArg/Dict/Split-Err are shared verbatim
571
+ # with uia-worker.ps1 via ps-stdio.ps1 (the escaping contract is documented there).
572
+ # Send-Ok/Send-Err stay here: they write $script:S.stats and decorate results with
573
+ # exStyles/palette (Add-Ex below), which are indicator-owned contracts.
574
+ . (Join-Path $PSScriptRoot 'ps-stdio.ps1')
575
+
576
+ function ExHex($v) { return '0x' + (([int64]$v -band 0xFFFFFFFFL).ToString('x8')) }
577
+
578
+ $EX_MAP = [ordered]@{
579
+ WS_EX_TRANSPARENT = 0x00000020
580
+ WS_EX_LAYERED = 0x00080000
581
+ WS_EX_TOOLWINDOW = 0x00000080
582
+ WS_EX_NOACTIVATE = 0x08000000
583
+ WS_EX_TOPMOST = 0x00000008
584
+ }
585
+ function Ex-Flags($v) {
586
+ $out = New-Object System.Collections.Generic.List[string]
587
+ foreach ($k in $EX_MAP.Keys) {
588
+ $bit = [int64]$EX_MAP[$k]
589
+ if ((([int64]$v -band $bit) -eq $bit)) { $out.Add([string]$k) }
590
+ }
591
+ return $out.ToArray()
592
+ }
593
+ function Ex-Has($v, [int64]$bit) { return (([int64]$v -band $bit) -eq $bit) }
594
+
595
+ # exStyles travels in EVERY response so a reviewer can audit the click-through bits at any moment.
596
+ function Add-Ex($result) {
597
+ if ($null -eq $result) { return $result }
598
+ if ($result -is [System.Collections.IDictionary]) {
599
+ $result['exStyles'] = (ExHex $script:S.exStyles)
600
+ $result['exFlags'] = (Ex-Flags $script:S.exStyles)
601
+ }
602
+ return $result
603
+ }
604
+
605
+ function NowMs { return [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $script:S.startTick) / 10000.0, 1) }
606
+ function SinceMs($tick) { return [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $tick) / 10000.0, 1) }
607
+ function Elapsed($t0) { return [Math]::Round(([Diagnostics.Stopwatch]::GetTimestamp() - $t0) / 10000.0, 1) }
608
+
609
+ function Send-Ok($id, $result) {
610
+ $script:S.stats.commands += 1
611
+ if ($null -eq $result -or $result -isnot [System.Collections.IDictionary]) {
612
+ # A handler that let a stray pipeline value escape shows up here as an array.
613
+ # Answering with it would break every client's shape assumption, so refuse loudly.
614
+ $shape = if ($null -eq $result) { 'null' } else { $result.GetType().Name }
615
+ Send-Err $id 'bad_result_shape' ("handler result is $shape, not an object; check for a leaked pipeline value")
616
+ return
617
+ }
618
+ $r = [ordered]@{ id = $id; ok = $true }
619
+ $r['result'] = (Add-Ex $result)
620
+ if ($null -ne $script:S.lastPalette) { $r['result']['palette'] = $script:S.lastPalette }
621
+ $r['stats'] = $script:S.stats
622
+ [Console]::Out.Write((JsonOf $r))
623
+ [Console]::Out.Write("`n")
624
+ [Console]::Out.Flush()
625
+ }
626
+
627
+ function Send-Err($id, $code, $message) {
628
+ $script:S.stats.commands += 1
629
+ $script:S.stats.refused += 1
630
+ $r = [ordered]@{ id = $id; ok = $false; code = [string]$code; error = (OneLine $message) }
631
+ $r['exStyles'] = (ExHex $script:S.exStyles)
632
+ $r['stats'] = $script:S.stats
633
+ [Console]::Out.Write((JsonOf $r))
634
+ [Console]::Out.Write("`n")
635
+ [Console]::Out.Flush()
636
+ }
637
+
638
+ # ---------------------------------------------------------------- monitor model
639
+ function Refresh-Screens {
640
+ $list = New-Object System.Collections.Generic.List[object]
641
+ $i = 0
642
+ foreach ($sc in [System.Windows.Forms.Screen]::AllScreens) {
643
+ $b = $sc.Bounds
644
+ # WinForms Screen.Handle is not usable here (measured: it converts to a null IntPtr and the
645
+ # P/Invoke throws), so the HMONITOR is taken from the point at the centre of the monitor.
646
+ $dpi = 0
647
+ if ($script:nativeLoaded) {
648
+ try {
649
+ $cx = [int]($b.X + ($b.Width / 2))
650
+ $cy = [int]($b.Y + ($b.Height / 2))
651
+ $hm = [IndNative]::MonitorAt($cx, $cy)
652
+ $dpi = [IndNative]::MonitorDpi($hm)
653
+ } catch { $dpi = 0 }
654
+ }
655
+ if ($dpi -le 0) {
656
+ # last resort: WPF's own device scale, which is the number the layout will actually use
657
+ $ds = (Get-DeviceScale)
658
+ if ($ds -gt 0) { $dpi = [int][Math]::Round(96.0 * $ds) } else { $dpi = 96 }
659
+ }
660
+ [void]$list.Add([ordered]@{
661
+ index = $i
662
+ device = [string]$sc.DeviceName
663
+ bounds = [ordered]@{ x = [int]$b.X; y = [int]$b.Y; w = [int]$b.Width; h = [int]$b.Height }
664
+ work = [ordered]@{ x = [int]$sc.WorkingArea.X; y = [int]$sc.WorkingArea.Y; w = [int]$sc.WorkingArea.Width; h = [int]$sc.WorkingArea.Height }
665
+ primary = [bool]$sc.Primary
666
+ dpi = [int]$dpi
667
+ })
668
+ $i++
669
+ }
670
+ # NOTE: .ToArray(), never @($list) -- an array built from a List whose only element is an
671
+ # IDictionary makes PowerShell's hashtable assignment throw "parameter type mismatch" on this box.
672
+ $script:S.screens = $list.ToArray()
673
+ return $script:S.screens
674
+ }
675
+
676
+ # WPF's own DIP -> device-pixel factor for this window. Measured, because GetDpiForMonitor through
677
+ # PowerShell's adapter is unreliable on this box (it returned 96 for a 150 % panel).
678
+ function Get-DeviceScale {
679
+ try {
680
+ if ($null -eq $script:S.win -or -not $script:S.win.IsLoaded) { return 0.0 }
681
+ $src = [System.Windows.PresentationSource]::FromVisual($script:S.win)
682
+ if ($null -eq $src) { return 0.0 }
683
+ $ct = $src.CompositionTarget
684
+ if ($null -eq $ct) { return 0.0 }
685
+ $m = [double]$ct.TransformToDevice.M11
686
+ if ($m -gt 0 -and -not [double]::IsNaN($m)) { return $m }
687
+ } catch { }
688
+ return 0.0
689
+ }
690
+
691
+ function Intersect($a, $b) {
692
+ $x0 = [Math]::Max([int]$a.x, [int]$b.x)
693
+ $y0 = [Math]::Max([int]$a.y, [int]$b.y)
694
+ $x1 = [Math]::Min(([int]$a.x + [int]$a.w), ([int]$b.x + [int]$b.w))
695
+ $y1 = [Math]::Min(([int]$a.y + [int]$a.h), ([int]$b.y + [int]$b.h))
696
+ if ($x1 -le $x0 -or $y1 -le $y0) { return [int64]0 }
697
+ return [int64]($x1 - $x0) * [int64]($y1 - $y0)
698
+ }
699
+
700
+ function RectCenter($r) {
701
+ return [ordered]@{ x = [int]([int]$r.x + ([int]$r.w / 2)); y = [int]([int]$r.y + ([int]$r.h / 2)) }
702
+ }
703
+
704
+ function RectContains($b, [int]$x, [int]$y) {
705
+ 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))
706
+ }
707
+
708
+ function DistTo($r, $m) {
709
+ $c = RectCenter $r
710
+ $nx = [Math]::Min([Math]::Max($c.x, [int]$m.x), ([int]$m.x + [int]$m.w))
711
+ $ny = [Math]::Min([Math]::Max($c.y, [int]$m.y), ([int]$m.y + [int]$m.h))
712
+ $dx = [double]($c.x - $nx); $dy = [double]($c.y - $ny)
713
+ return [Math]::Sqrt($dx * $dx + $dy * $dy)
714
+ }
715
+
716
+ # Picks the monitor that CONTAINS the target rect. When a rect straddles several, the one with the
717
+ # LARGEST INTERSECTION wins. A rect touching nothing falls back to the monitor nearest the rect
718
+ # centre, so a bad rect from the model can never mean "no overlay at all".
719
+ function Pick-Monitor($rect) {
720
+ $screens = $script:S.screens
721
+ if ($null -eq $screens -or ([array]$screens).Count -eq 0) { $screens = Refresh-Screens }
722
+ if (([array]$screens).Count -eq 0) { Err 'no_screen' 'no monitor reported by this session' }
723
+ $best = -1
724
+ $bestArea = [int64]-1
725
+ $touch = 0
726
+ foreach ($m in $screens) {
727
+ $a = Intersect $rect $m.bounds
728
+ if ($a -gt 0) { $touch += 1 }
729
+ if ($a -gt $bestArea) { $bestArea = $a; $best = [int]$m.index }
730
+ }
731
+ $reason = 'contains'
732
+ $straddle = $false
733
+ if ($best -lt 0 -or $bestArea -le 0) {
734
+ $nb = [double]1.0E+18; $ni = 0
735
+ foreach ($m in $screens) {
736
+ $d = DistTo $rect $m.bounds
737
+ if ($d -lt $nb) { $nb = $d; $ni = [int]$m.index }
738
+ }
739
+ $best = $ni
740
+ $reason = 'nearest_fallback'
741
+ } else {
742
+ $c = RectCenter $rect
743
+ $picked = $null
744
+ foreach ($m in $screens) { if ([int]$m.index -eq $best) { $picked = $m } }
745
+ if (-not (RectContains $picked.bounds $c.x $c.y)) { $reason = 'largest_intersection' }
746
+ if ($touch -gt 1) { $straddle = $true }
747
+ }
748
+ $out = $null
749
+ foreach ($m in $screens) { if ([int]$m.index -eq $best) { $out = $m } }
750
+ return [ordered]@{ monitor = $out; straddle = $straddle; reason = $reason; area = [int64]$bestArea; monitorsTouched = $touch }
751
+ }
752
+
753
+ # Proves the CJK glyphs exist in the face rather than trusting the string constant. The compiled
754
+ # helper reads GlyphTypeface.CharacterToGlyphMap: a code point that is absent, or that maps to glyph
755
+ # id 0 (.notdef), is reported, together with the font file the face actually came from.
756
+ function Test-FontCoverage([string]$familyName, [string]$text) {
757
+ $res = @{ candidate = $familyName; ok = $false; probed = 0; missing = @(); fontUri = ''; glyphCount = 0; advancePx = 0.0; note = '' }
758
+ if (-not $script:renderLoaded) {
759
+ $res.note = 'compiled glyph probe unavailable'
760
+ return $res
761
+ }
762
+ try {
763
+ $p = [IndWpf]::Probe($familyName, $text, 14.0)
764
+ $res.probed = [int]$p.probed
765
+ $res.fontUri = [string]$p.fontUri
766
+ $res.glyphCount = [int]$p.glyphCount
767
+ $res.advancePx = [Math]::Round([double]$p.width, 2)
768
+ $res.note = [string]$p.note
769
+ if ($p.hasFace) {
770
+ if ([string]::IsNullOrEmpty([string]$p.missing)) { $res.ok = ($res.probed -gt 0) }
771
+ else { $res.missing = ([string]$p.missing).Split(',') }
772
+ }
773
+ return $res
774
+ } catch {
775
+ $res.note = 'probe threw: ' + (OneLine $_.Exception.Message)
776
+ return $res
777
+ }
778
+ }
779
+
780
+ $script:FONT_CANDIDATES = @('Microsoft YaHei UI', 'Microsoft YaHei', 'Segoe UI Variable Text', 'Segoe UI', 'SimSun', 'NSimSun')
781
+ function Choose-Font {
782
+ $probe = New-Object System.Collections.Generic.List[object]
783
+ $all = [string]($script:PILL.acting + $script:PILL.stopped)
784
+ $chosen = ''
785
+ foreach ($f in $script:FONT_CANDIDATES) {
786
+ $p = Test-FontCoverage $f $all
787
+ [void]$probe.Add($p)
788
+ if ($chosen -eq '' -and [bool]$p.ok) { $chosen = $f }
789
+ }
790
+ $script:S.fontProbe = @{ probed = $probe.ToArray(); allGlyphsPresent = ($chosen -ne ''); text = $all }
791
+ if ($chosen -eq '') {
792
+ $chosen = 'Microsoft YaHei UI, Segoe UI Variable Text, Microsoft YaHei, Segoe UI'
793
+ Log ('no single family carried every glyph; relying on WPF per-glyph fallback: ' + $chosen)
794
+ }
795
+ $script:S.chosenFont = $chosen
796
+ return $chosen
797
+ }
798
+
799
+ # ---------------------------------------------------------------- visuals
800
+ function New-Solid($rgb, [double]$a) {
801
+ $b = New-Object System.Windows.Media.SolidColorBrush -ArgumentList (ColA $a $rgb)
802
+ [void]$b.Freeze()
803
+ return $b
804
+ }
805
+
806
+ function New-GradH($rgb0, $rgb1, [double]$a, [bool]$flip) {
807
+ # colour ramp across the ring direction, constant alpha
808
+ $b = New-Object System.Windows.Media.LinearGradientBrush
809
+ if ($flip) {
810
+ $b.StartPoint = New-Object System.Windows.Point -ArgumentList 1.0, 0.5
811
+ $b.EndPoint = New-Object System.Windows.Point -ArgumentList 0.0, 0.5
812
+ } else {
813
+ $b.StartPoint = New-Object System.Windows.Point -ArgumentList 0.0, 0.5
814
+ $b.EndPoint = New-Object System.Windows.Point -ArgumentList 1.0, 0.5
815
+ }
816
+ $s0 = New-Object System.Windows.Media.GradientStop
817
+ $s0.Color = (ColA $a $rgb0); $s0.Offset = 0.0
818
+ $s1 = New-Object System.Windows.Media.GradientStop
819
+ $s1.Color = (ColA $a $rgb1); $s1.Offset = 1.0
820
+ [void]$b.GradientStops.Add($s0)
821
+ [void]$b.GradientStops.Add($s1)
822
+ [void]$b.Freeze()
823
+ return $b
824
+ }
825
+
826
+ function Test-DarkAmbient($rgb) {
827
+ # A ramp whose average luminance is below mid-grey is an ambient that DARKENS the screen instead
828
+ # of lighting it. The two need opposite geometry (see New-Vignette), so the distinction has to be
829
+ # made from the palette, not hardcoded per theme id.
830
+ if ($null -eq $rgb -or $rgb.Count -lt 3) { return $false }
831
+ $l = 0.299 * [double]$rgb[0] + 0.587 * [double]$rgb[1] + 0.114 * $rgb[2]
832
+ return ($l -lt 96.0)
833
+ }
834
+
835
+ function New-Fade([double]$sx, [double]$sy, [double]$ex, [double]$ey, [double]$strength) {
836
+ # opacity mask: solid at the monitor edge, fading inward
837
+ $b = New-Object System.Windows.Media.LinearGradientBrush
838
+ $b.StartPoint = New-Object System.Windows.Point -ArgumentList $sx, $sy
839
+ $b.EndPoint = New-Object System.Windows.Point -ArgumentList $ex, $ey
840
+ $a255 = [int][Math]::Round([Math]::Min(1.0, $strength) * 255.0)
841
+ # One continuous falloff: no mid-stop shelf, no second hard edge. The old 0.42 shelf plus the
842
+ # separate solid ring bar is what read as two stacked bands around the screen.
843
+ foreach ($p in @(
844
+ @{ o = 0.00; a = $a255 },
845
+ @{ o = 0.16; a = [int]($a255 * 0.86) },
846
+ @{ o = 0.36; a = [int]($a255 * 0.58) },
847
+ @{ o = 0.58; a = [int]($a255 * 0.30) },
848
+ @{ o = 0.78; a = [int]($a255 * 0.10) },
849
+ @{ o = 1.00; a = 0 }
850
+ )) {
851
+ $gs = New-Object System.Windows.Media.GradientStop
852
+ $gs.Color = [System.Windows.Media.Color]::FromArgb([byte]$p.a, 255, 255, 255)
853
+ $gs.Offset = [double]$p.o
854
+ [void]$b.GradientStops.Add($gs)
855
+ }
856
+ [void]$b.Freeze()
857
+ return $b
858
+ }
859
+
860
+ function New-Vignette([double]$sx, [double]$sy, [double]$ex, [double]$ey, [double]$strength) {
861
+ # The mask for a DARK ambient. A black rim drawn with New-Fade's profile is densest at the screen
862
+ # edge and dissolves inward, which on a dark desktop reads as "the screen is a bit dim at the
863
+ # border" -- measured at luminance 4..21 against a desktop edge of 75, i.e. it merged into the
864
+ # wallpaper and was invisible as a deliberate effect. A vignette has the opposite profile: it
865
+ # ramps UP over the first part of the band, holds at full density through the middle, and then
866
+ # releases -- so the darkest part sits just inside the edge, where the eye reads it as a frame
867
+ # rather than as missing pixels. That is what makes a black ambient look intentional.
868
+ $b = New-Object System.Windows.Media.LinearGradientBrush
869
+ $b.StartPoint = New-Object System.Windows.Point -ArgumentList $sx, $sy
870
+ $b.EndPoint = New-Object System.Windows.Point -ArgumentList $ex, $ey
871
+ $a255 = [int][Math]::Round([Math]::Min(1.0, $strength) * 255.0)
872
+ foreach ($p in @(
873
+ @{ o = 0.00; a = [int]($a255 * 0.55) },
874
+ @{ o = 0.18; a = $a255 },
875
+ @{ o = 0.46; a = $a255 },
876
+ @{ o = 0.70; a = [int]($a255 * 0.72) },
877
+ @{ o = 0.88; a = [int]($a255 * 0.28) },
878
+ @{ o = 1.00; a = 0 }
879
+ )) {
880
+ $gs = New-Object System.Windows.Media.GradientStop
881
+ $gs.Color = [System.Windows.Media.Color]::FromArgb([byte]$p.a, 255, 255, 255)
882
+ $gs.Offset = [double]$p.o
883
+ [void]$b.GradientStops.Add($gs)
884
+ }
885
+ [void]$b.Freeze()
886
+ return $b
887
+ }
888
+
889
+ function New-Bar([double]$x, [double]$y, [double]$w, [double]$h, $fill, $mask) {
890
+ $r = New-Object System.Windows.Shapes.Rectangle
891
+ $r.Width = [Math]::Max(0.5, $w)
892
+ $r.Height = [Math]::Max(0.5, $h)
893
+ $r.Fill = $fill
894
+ if ($null -ne $mask) { $r.OpacityMask = $mask }
895
+ [System.Windows.Controls.Canvas]::SetLeft($r, $x)
896
+ [System.Windows.Controls.Canvas]::SetTop($r, $y)
897
+ $r.SnapsToDevicePixels = $true
898
+ $r.IsHitTestVisible = $false
899
+ return $r
900
+ }
901
+
902
+ # Ring geometry for a window surface of W x H DIPs, thickness T DIPs.
903
+ # BOTH pairs of bars span their full edge (horizontals full width, verticals full height) and therefore
904
+ # overlap in the four T x T corner squares. That overlap is what makes the frame continuous -- if either
905
+ # pair is inset, the corner is left to the perpendicular bar's fading tail and reads as a dark break.
906
+ # The corner overlap only lifts alpha a little (pale lavender, perpendicular fades), so it glows rather
907
+ # than burns.
908
+ function Build-Ring([double]$W, [double]$H, [double]$T, $ph) {
909
+ $bars = New-Object System.Collections.Generic.List[object]
910
+ $bloom = New-Object System.Collections.Generic.List[object]
911
+ # One wide falloff layer per edge, no separate hard ring bar: the edge light is a single soft
912
+ # gradient that dissolves inward, so there are no stacked bands.
913
+ #
914
+ # The ramp is g0 -> g1, i.e. the palette's ringFrom -> ringTo. It used to be base -> base, and
915
+ # `base` is pillBorder -- which BOTH palettes carry identically. That is why choosing an ambient
916
+ # moved the stored value and not one pixel of the ring: the theme only ever reached the capsule.
917
+ #
918
+ # The MASK depends on whether the ambient lightens or darkens. A light ramp with the edge-dense
919
+ # falloff looks like light bleeding in from the frame; a dark ramp with the same profile just looks
920
+ # like a slightly dimmer border that merges into the wallpaper (measured: luminance 4..21 against a
921
+ # desktop edge of 75 -- present, and invisible as an effect). A dark ambient gets the vignette
922
+ # profile instead, which puts its darkest band just inside the edge so the eye reads a frame.
923
+ $dark = Test-DarkAmbient $ph.g0
924
+ $E = $T * 4.0
925
+ $mask = if ($dark) { 'New-Vignette' } else { 'New-Fade' }
926
+ [void]$bloom.Add((New-Bar 0 0 $W $E (New-GradH $ph.g0 $ph.g1 0.85 $false) (& $mask 0.5 0.0 0.5 1.0 1.0)))
927
+ [void]$bloom.Add((New-Bar 0 ($H - $E) $W $E (New-GradH $ph.g1 $ph.g0 0.85 $false) (& $mask 0.5 1.0 0.5 0.0 1.0)))
928
+ [void]$bloom.Add((New-Bar 0 0 $E $H (New-GradH $ph.g0 $ph.g1 0.85 $true) (& $mask 0.0 0.5 1.0 0.5 1.0)))
929
+ [void]$bloom.Add((New-Bar ($W - $E) 0 $E $H (New-GradH $ph.g0 $ph.g1 0.85 $false) (& $mask 1.0 0.5 0.0 0.5 1.0)))
930
+ return @{ bars = $bars; bloom = $bloom }
931
+ }
932
+
933
+ function New-CursorGlowSource($cd, $ph, $opacity) {
934
+ # OUTER-GLOW halo: a soft coloured glow that hugs the cursor's OUTLINE and spreads outward, while the
935
+ # cursor's own interior is left fully transparent so the real pointer stays visible (we never swap the
936
+ # system cursor). Build the silhouette, box-blur it, subtract the sharp core (glow = blur*(255-core)/255)
937
+ # so nothing is painted where the cursor itself is, then premultiply into Pbgra32 (R<=A). A symmetric pad
938
+ # around the bitmap lets the glow spill past the cursor's bounding box without clipping at the edges.
939
+ # NOTE: PowerShell variables are CASE-INSENSITIVE, so the padded size uses $gw/$gh, never $W/$H (which
940
+ # would silently clobber the cursor's own $w/$h).
941
+ $w = $cd.w; $h = $cd.h
942
+ if ($w -le 0 -or $h -le 0 -or $cd.bgra.Length -lt $w * $h * 4) { return $null }
943
+ $src = $cd.bgra
944
+ $R = [int][Math]::Max(2, [Math]::Round([double]$CFG.haloPx * 0.5))
945
+ $pad = $R + 2
946
+ $gw = $w + 2 * $pad; $gh = $h + 2 * $pad
947
+ $core = [int[]]::new($gw * $gh)
948
+ 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] } }
949
+ $tmp = [int[]]::new($gw * $gh)
950
+ $blur = [int[]]::new($gw * $gh)
951
+ for ($y = 0; $y -lt $gh; $y++) {
952
+ for ($x = 0; $x -lt $gw; $x++) {
953
+ $lo = [Math]::Max(0, $x - $R); $hi = [Math]::Min($gw - 1, $x + $R); $s = 0
954
+ for ($k = $lo; $k -le $hi; $k++) { $s += $core[$y * $gw + $k] }
955
+ $tmp[$y * $gw + $x] = [int][Math]::Round($s / ($hi - $lo + 1))
956
+ }
957
+ }
958
+ for ($x = 0; $x -lt $gw; $x++) {
959
+ for ($y = 0; $y -lt $gh; $y++) {
960
+ $lo = [Math]::Max(0, $y - $R); $hi = [Math]::Min($gh - 1, $y + $R); $s = 0
961
+ for ($k = $lo; $k -le $hi; $k++) { $s += $tmp[$k * $gw + $x] }
962
+ $blur[$y * $gw + $x] = [int][Math]::Round($s / ($hi - $lo + 1))
963
+ }
964
+ }
965
+ $out = New-Object byte[] ($gw * $gh * 4)
966
+ $r = [double]$ph.g0[0]; $g = [double]$ph.g0[1]; $b = [double]$ph.g0[2]
967
+ for ($i = 0; $i -lt $gw * $gh; $i++) {
968
+ $c = $core[$i]
969
+ $a = [int][Math]::Round($blur[$i] * (255 - $c) / 255.0 * $opacity)
970
+ 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 }
971
+ if ($a -gt 255) { $a = 255 }
972
+ $f = $a / 255.0
973
+ $out[$i * 4 + 0] = [byte][Math]::Round($b * $f)
974
+ $out[$i * 4 + 1] = [byte][Math]::Round($g * $f)
975
+ $out[$i * 4 + 2] = [byte][Math]::Round($r * $f)
976
+ $out[$i * 4 + 3] = [byte]$a
977
+ }
978
+ $bmp = [System.Windows.Media.Imaging.BitmapSource]::Create($gw, $gh, 96, 96, [System.Windows.Media.PixelFormats]::Pbgra32, $null, $out, $gw * 4)
979
+ return @{ bmp = $bmp; w = $gw; h = $gh; pad = $pad }
980
+ }
981
+
982
+ function Build-Halo($ph, $sc) {
983
+ # The halo glows along the LIVE cursor bitmap, so it follows the cursor's actual shape (arrow,
984
+ # hand, ibeam, resize...) instead of assuming one. The image is rebuilt only when the OS cursor
985
+ # handle changes; each track tick just repositions it, so per-tick cost stays tiny (no blur re-run).
986
+ if ($sc -le 0) { $sc = 1.0 }
987
+ $radDip = [double]$CFG.haloPx / $sc
988
+ $img = New-Object System.Windows.Controls.Image
989
+ # Stretch=Fill so the bitmap is drawn at the Image's Width/Height (set to cursorPx/scale in
990
+ # Update-HaloGlow), i.e. its true PHYSICAL size. Stretch=None would ignore those and render the
991
+ # bitmap's pixels 1:1 as DIPs -- on a 150% display that inflates the halo to 1.5x the real cursor.
992
+ $img.Stretch = [System.Windows.Media.Stretch]::Fill
993
+ $img.IsHitTestVisible = $false
994
+ $blur = New-Object System.Windows.Media.Effects.BlurEffect
995
+ $blur.Radius = [Math]::Max(1.2, $radDip * 0.18)
996
+ $img.Effect = $blur
997
+ return @{ items = @($img); img = $img; radDip = $radDip }
998
+ }
999
+
1000
+ function Update-HaloGlow($ph) {
1001
+ if ($null -eq $script:S.halo -or $null -eq $script:S.halo.img) { return }
1002
+ $cd = [IndNative]::ReadCursor()
1003
+ if (-not $cd.ok) { $script:S.haloCurs = $null; return }
1004
+ $script:S.haloCurs = $cd
1005
+ if ($cd.hCursor -ne $script:S.haloShape) {
1006
+ $glow = New-CursorGlowSource $cd $ph 0.85
1007
+ if ($null -ne $glow) {
1008
+ $sc = [double]$script:S.scale; if ($sc -le 0) { $sc = 1.0 }
1009
+ $script:S.halo.img.Source = $glow.bmp
1010
+ $script:S.halo.img.Width = [double]$glow.w / $sc
1011
+ $script:S.halo.img.Height = [double]$glow.h / $sc
1012
+ $script:S.haloPad = [int]$glow.pad
1013
+ $script:S.haloShape = $cd.hCursor
1014
+ }
1015
+ }
1016
+ }
1017
+
1018
+ function Position-Halo {
1019
+ if ($null -eq $script:S.halo) { return }
1020
+ $sc = [double]$script:S.scale; if ($sc -le 0) { $sc = 1.0 }
1021
+ if (-not $script:nativeLoaded) { return }
1022
+ $mb = $script:S.monitorBounds
1023
+ $ph = $script:PH[$script:S.phase]; if ($null -eq $ph) { $ph = $script:PH['acting'] }
1024
+ 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')) {
1025
+ $c = [IndNative]::CursorXY()
1026
+ 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 }
1027
+ Update-HaloGlow $ph
1028
+ 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 }
1029
+ $cd = $script:S.haloCurs
1030
+ $pad = [int]$script:S.haloPad
1031
+ $lx = (([double]$c[0] - [double]$mb.x) - ($cd.xHot + $pad)) / $sc
1032
+ $ly = (([double]$c[1] - [double]$mb.y) - ($cd.yHot + $pad)) / $sc
1033
+ $lt = New-Object System.Windows.Media.TranslateTransform -ArgumentList $lx, $ly
1034
+ foreach ($it in $script:S.halo.items) { $it.RenderTransform = $lt; $it.Opacity = 1.0 }
1035
+ $script:S.haloOn = $true
1036
+ $script:S.haloX = $c[0]; $script:S.haloY = $c[1]
1037
+ } elseif ($script:S.haloOn) {
1038
+ $script:S.haloOn = $false
1039
+ foreach ($it in $script:S.halo.items) { $it.Opacity = 0.0 }
1040
+ }
1041
+ }
1042
+
1043
+ function Get-WhaleWagPoint([System.Windows.Point]$p, [double]$angle, [double]$thr, [double]$tip, [double]$px, [double]$py) {
1044
+ # Skinning weight along the body: zero at the peduncle, one at the fluke tip. The blend band is
1045
+ # narrow (2 units), so the fluke rotates as a near-rigid piece and keeps its own shape instead of
1046
+ # shearing into a blob; the outline stays one closed figure, so there is no seam and no joint.
1047
+ $t = ($p.X - $thr) / ($tip - $thr)
1048
+ if ($t -lt 0.0) { $t = 0.0 } elseif ($t -gt 1.0) { $t = 1.0 }
1049
+ $w = $t * $t * (3.0 - 2.0 * $t)
1050
+ if ($w -le 0.0001) { return $p }
1051
+ $rad = ($angle * $w) * [Math]::PI / 180.0
1052
+ $c = [Math]::Cos($rad); $s = [Math]::Sin($rad)
1053
+ $dx = $p.X - $px; $dy = $p.Y - $py
1054
+ return New-Object System.Windows.Point -ArgumentList ($px + $dx * $c - $dy * $s), ($py + $dx * $s + $dy * $c)
1055
+ }
1056
+
1057
+ function Add-WhaleWagAnimation($target, $dp, [System.Windows.Point]$p, [double]$swing, [double]$thr, [double]$tip, [double]$px, [double]$py, $ease) {
1058
+ $from = Get-WhaleWagPoint $p (-$swing) $thr $tip $px $py
1059
+ $to = Get-WhaleWagPoint $p $swing $thr $tip $px $py
1060
+ if ([Math]::Abs($from.X - $to.X) -lt 0.0005 -and [Math]::Abs($from.Y - $to.Y) -lt 0.0005) {
1061
+ $target.SetValue($dp, $p)
1062
+ return
1063
+ }
1064
+ $anim = New-Object System.Windows.Media.Animation.PointAnimation
1065
+ $anim.From = $from
1066
+ $anim.To = $to
1067
+ $anim.Duration = [TimeSpan]::FromMilliseconds(1200)
1068
+ [System.Windows.Media.Animation.Timeline]::SetDesiredFrameRate($anim, 30)
1069
+ $anim.AutoReverse = $true
1070
+ $anim.RepeatBehavior = [System.Windows.Media.Animation.RepeatBehavior]::Forever
1071
+ $anim.EasingFunction = $ease
1072
+ $target.BeginAnimation($dp, $anim)
1073
+ }
1074
+
1075
+ function Get-WhaleWagEnvelope([System.Windows.Media.PathGeometry]$source, [double]$swing) {
1076
+ # The union of the silhouette over the whole swing, as a Rect. This is what the measured bounds
1077
+ # have to be pinned to: a frame drawn from the REST bounds only fixes the left side, while the
1078
+ # fluke travels outward by up to ~3.5 DIP, so DesiredSize still changed every frame and the
1079
+ # element was re-arranged anyway. Sampling the swing (both extremes, plus zero) and taking the
1080
+ # union makes the measured size constant for every angle in between.
1081
+ $thr = 161.0; $tip = 165.0; $px = 163.8; $py = 20.6
1082
+ $x0 = [double]::MaxValue; $y0 = [double]::MaxValue
1083
+ $x1 = [double]::MinValue; $y1 = [double]::MinValue
1084
+ foreach ($angle in @((-1.0 * $swing), 0.0, (1.0 * $swing))) {
1085
+ $g = New-Object System.Windows.Media.PathGeometry
1086
+ $g.FillRule = $source.FillRule
1087
+ foreach ($f in $source.Figures) {
1088
+ $nf = New-Object System.Windows.Media.PathFigure
1089
+ $nf.StartPoint = (Get-WhaleWagPoint $f.StartPoint $angle $thr $tip $px $py)
1090
+ $nf.IsClosed = $f.IsClosed
1091
+ $nf.IsFilled = $f.IsFilled
1092
+ foreach ($seg in $f.Segments) {
1093
+ if ($seg -is [System.Windows.Media.PolyBezierSegment]) {
1094
+ $pts = $seg.Points
1095
+ for ($i = 0; $i + 2 -lt $pts.Count; $i += 3) {
1096
+ [void]$nf.Segments.Add((New-Object System.Windows.Media.BezierSegment -ArgumentList `
1097
+ (Get-WhaleWagPoint $pts[$i] $angle $thr $tip $px $py), `
1098
+ (Get-WhaleWagPoint $pts[$i + 1] $angle $thr $tip $px $py), `
1099
+ (Get-WhaleWagPoint $pts[$i + 2] $angle $thr $tip $px $py), $true))
1100
+ }
1101
+ } elseif ($seg -is [System.Windows.Media.PolyLineSegment]) {
1102
+ foreach ($pt in $seg.Points) {
1103
+ [void]$nf.Segments.Add((New-Object System.Windows.Media.LineSegment -ArgumentList (Get-WhaleWagPoint $pt $angle $thr $tip $px $py), $true))
1104
+ }
1105
+ } elseif ($seg -is [System.Windows.Media.BezierSegment]) {
1106
+ [void]$nf.Segments.Add((New-Object System.Windows.Media.BezierSegment -ArgumentList `
1107
+ (Get-WhaleWagPoint $seg.Point1 $angle $thr $tip $px $py), `
1108
+ (Get-WhaleWagPoint $seg.Point2 $angle $thr $tip $px $py), `
1109
+ (Get-WhaleWagPoint $seg.Point3 $angle $thr $tip $px $py), $true))
1110
+ } else {
1111
+ [void]$nf.Segments.Add($seg.Clone())
1112
+ }
1113
+ }
1114
+ [void]$g.Figures.Add($nf)
1115
+ }
1116
+ $b = $g.Bounds
1117
+ if ($b.X -lt $x0) { $x0 = $b.X }
1118
+ if ($b.Y -lt $y0) { $y0 = $b.Y }
1119
+ if (($b.X + $b.Width) -gt $x1) { $x1 = $b.X + $b.Width }
1120
+ if (($b.Y + $b.Height) -gt $y1) { $y1 = $b.Y + $b.Height }
1121
+ }
1122
+ return New-Object System.Windows.Rect -ArgumentList $x0, $y0, ($x1 - $x0), ($y1 - $y0)
1123
+ }
1124
+
1125
+ function New-WhaleWagGeometry([System.Windows.Media.PathGeometry]$source, [double]$swing) {
1126
+ # WPF has no SMIL, so the same idea is applied to the vector itself: every Bezier control point in
1127
+ # the tail gets a weighted PointAnimation. One closed figure stays one closed figure throughout.
1128
+ $thr = 161.0; $tip = 165.0; $px = 163.8; $py = 20.6
1129
+ $ease = New-Object System.Windows.Media.Animation.SineEase
1130
+ $ease.EasingMode = [System.Windows.Media.Animation.EasingMode]::EaseInOut
1131
+ $pg = New-Object System.Windows.Media.PathGeometry
1132
+ $pg.FillRule = $source.FillRule
1133
+ foreach ($f in $source.Figures) {
1134
+ $nf = New-Object System.Windows.Media.PathFigure
1135
+ $nf.StartPoint = $f.StartPoint
1136
+ $nf.IsClosed = $f.IsClosed
1137
+ $nf.IsFilled = $f.IsFilled
1138
+ Add-WhaleWagAnimation $nf ([System.Windows.Media.PathFigure]::StartPointProperty) $f.StartPoint $swing $thr $tip $px $py $ease
1139
+ foreach ($seg in $f.Segments) {
1140
+ if ($seg -is [System.Windows.Media.PolyBezierSegment]) {
1141
+ $pts = $seg.Points
1142
+ for ($i = 0; $i + 2 -lt $pts.Count; $i += 3) {
1143
+ $bs = New-Object System.Windows.Media.BezierSegment -ArgumentList $pts[$i], $pts[$i + 1], $pts[$i + 2], $true
1144
+ Add-WhaleWagAnimation $bs ([System.Windows.Media.BezierSegment]::Point1Property) $pts[$i] $swing $thr $tip $px $py $ease
1145
+ Add-WhaleWagAnimation $bs ([System.Windows.Media.BezierSegment]::Point2Property) $pts[$i + 1] $swing $thr $tip $px $py $ease
1146
+ Add-WhaleWagAnimation $bs ([System.Windows.Media.BezierSegment]::Point3Property) $pts[$i + 2] $swing $thr $tip $px $py $ease
1147
+ [void]$nf.Segments.Add($bs)
1148
+ }
1149
+ } elseif ($seg -is [System.Windows.Media.PolyLineSegment]) {
1150
+ foreach ($pt in $seg.Points) {
1151
+ $ls = New-Object System.Windows.Media.LineSegment -ArgumentList $pt, $true
1152
+ Add-WhaleWagAnimation $ls ([System.Windows.Media.LineSegment]::PointProperty) $pt $swing $thr $tip $px $py $ease
1153
+ [void]$nf.Segments.Add($ls)
1154
+ }
1155
+ } elseif ($seg -is [System.Windows.Media.BezierSegment]) {
1156
+ $bs = New-Object System.Windows.Media.BezierSegment -ArgumentList $seg.Point1, $seg.Point2, $seg.Point3, $true
1157
+ Add-WhaleWagAnimation $bs ([System.Windows.Media.BezierSegment]::Point1Property) $seg.Point1 $swing $thr $tip $px $py $ease
1158
+ Add-WhaleWagAnimation $bs ([System.Windows.Media.BezierSegment]::Point2Property) $seg.Point2 $swing $thr $tip $px $py $ease
1159
+ Add-WhaleWagAnimation $bs ([System.Windows.Media.BezierSegment]::Point3Property) $seg.Point3 $swing $thr $tip $px $py $ease
1160
+ [void]$nf.Segments.Add($bs)
1161
+ } else {
1162
+ [void]$nf.Segments.Add($seg.Clone())
1163
+ }
1164
+ }
1165
+ [void]$pg.Figures.Add($nf)
1166
+ }
1167
+ return $pg
1168
+ }
1169
+
1170
+ function New-WhaleShape([double]$slot, [double]$inset, $stops, [bool]$animate) {
1171
+ # One whale, two homes. The orb floats it on the dark shell and the paper capsule sets it inside
1172
+ # its chip; both must be the SAME vector, or the identity mark becomes two different drawings.
1173
+ # `slot` is the square the mark lives in, `inset` how much of it the silhouette may use.
1174
+ $canvas = New-Object System.Windows.Controls.Canvas
1175
+ $canvas.Width = $slot
1176
+ $canvas.Height = $slot
1177
+ $canvas.ClipToBounds = $false
1178
+ $pathFile = Join-Path $PSScriptRoot 'assets\dsh-whale.path'
1179
+ if (-not (Test-Path -LiteralPath $pathFile)) {
1180
+ Log 'whale path missing: worker\assets\dsh-whale.path'
1181
+ return $canvas
1182
+ }
1183
+ $d = (Get-Content -LiteralPath $pathFile -Raw).Trim()
1184
+ $source = [System.Windows.Media.PathGeometry]::CreateFromGeometry([System.Windows.Media.Geometry]::Parse($d))
1185
+ $shape = New-Object System.Windows.Shapes.Path
1186
+ $b = $source.Bounds
1187
+ # The measured size is what makes the icon shake, so it is removed from the picture entirely.
1188
+ #
1189
+ # A Path with Stretch=None reports DesiredSize from its geometry's bounds. When that geometry is
1190
+ # animated, the bounds move with the animation: measured across the swing the scaled right edge
1191
+ # travels 3.47 DIP (5.2 physical px at 1.5x). WPF then re-arranges the element every frame, and
1192
+ # because the arrange offset is derived from the size, the DRAWN ORIGIN moves too -- the whole
1193
+ # silhouette shifts a pixel while the tail barely moves. A filmstrip showed it plainly: most
1194
+ # frames identical, then one frame where the entire outline changed at once.
1195
+ #
1196
+ # An invisible "frame" figure pinned to the swing's union does NOT fix this: WPF computes Bounds
1197
+ # from the geometry's BASE value, so the frame pins the base and the animated points still move
1198
+ # the live bounds. Verified in the bench.
1199
+ #
1200
+ # So the element gets an explicit, constant Width/Height and Stretch=Fill: layout measures the
1201
+ # constant, and the geometry is mapped into that box by the stretch instead of by its own size.
1202
+ # The transform then only has to place the box, and it is built from the same union so no angle
1203
+ # can ever push the fluke outside it.
1204
+ $env = if ($animate) { Get-WhaleWagEnvelope $source 20.0 } else { $b }
1205
+ $slotW = $env.Width
1206
+ $slotH = $env.Height
1207
+ $shape.Width = $slotW
1208
+ $shape.Height = $slotH
1209
+ $shape.Stretch = [System.Windows.Media.Stretch]::Fill
1210
+ $shape.IsHitTestVisible = $false
1211
+ $shape.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Left
1212
+ $shape.VerticalAlignment = [System.Windows.VerticalAlignment]::Top
1213
+ if ($animate) {
1214
+ $shape.Data = New-WhaleWagGeometry $source 20.0
1215
+ } else {
1216
+ $shape.Data = $source
1217
+ }
1218
+ # Place the constant box in the slot, centred, at the requested inset.
1219
+ $fit = $inset / [Math]::Max($env.Width, $env.Height)
1220
+ $tx = ($slot - $slotW * $fit) / 2.0
1221
+ $ty = ($slot - $slotH * $fit) / 2.0
1222
+ $shape.RenderTransform = New-Object System.Windows.Media.MatrixTransform -ArgumentList $fit, 0.0, 0.0, $fit, $tx, $ty
1223
+ $brush = New-Object System.Windows.Media.LinearGradientBrush
1224
+ $brush.MappingMode = [System.Windows.Media.BrushMappingMode]::Absolute
1225
+ $brush.StartPoint = New-Object System.Windows.Point -ArgumentList $b.X, $b.Y
1226
+ $brush.EndPoint = New-Object System.Windows.Point -ArgumentList ($b.X + $b.Width), ($b.Y + $b.Height)
1227
+ foreach ($s in $stops) {
1228
+ $gs = New-Object System.Windows.Media.GradientStop
1229
+ $gs.Color = [System.Windows.Media.Color]::FromArgb([byte]$s.c[0], [byte]$s.c[1], [byte]$s.c[2], [byte]$s.c[3])
1230
+ $gs.Offset = [double]$s.o
1231
+ [void]$brush.GradientStops.Add($gs)
1232
+ }
1233
+ $shape.Fill = $brush
1234
+ [void]$canvas.Children.Add($shape)
1235
+ return $canvas
1236
+ }
1237
+
1238
+ function New-PillOrb($ph, [bool]$inverse) {
1239
+ # The identity mark is the DSH whale itself, cut out of the shell: no glass bead, no specular dot,
1240
+ # no painted rim, and -- on either shell -- no chip behind it. The vector path is the same one the
1241
+ # host uses in its welcome wordmark; it is scaled into an 18 DIP slot so the silhouette stays
1242
+ # crisp at any DPI.
1243
+ #
1244
+ # The paper capsule used to wrap this in a 20 DIP rounded chip so a white whale had something to
1245
+ # sit on. That chip was the "why does the white capsule's whale have its own background" problem:
1246
+ # the mark carried a second surface the black capsule never had, and the two shapes no longer read
1247
+ # as the same object. The whale is drawn straight onto the shell instead, in ink for paper.
1248
+ $wrap = New-Object System.Windows.Controls.Grid
1249
+ $wrap.Width = 18; $wrap.Height = 18
1250
+ $wrap.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
1251
+ $scale = New-Object System.Windows.Media.ScaleTransform -ArgumentList 1.0, 1.0
1252
+ $wrap.RenderTransform = $scale
1253
+ $wrap.RenderTransformOrigin = New-Object System.Windows.Point -ArgumentList 0.5, 0.5
1254
+ $stops = if ($inverse) {
1255
+ # Ink on paper: the same ramp the black shell uses, inverted, so the silhouette keeps its
1256
+ # modelled light (bright at the top of the form) instead of flattening to one grey.
1257
+ @(
1258
+ @{ o = 0.00; c = @(255, 26, 29, 34) },
1259
+ @{ o = 0.26; c = @(255, 44, 49, 57) },
1260
+ @{ o = 0.52; c = @(255, 74, 82, 93) },
1261
+ @{ o = 0.76; c = @(255, 116, 125, 137) },
1262
+ @{ o = 1.00; c = @(255, 158, 166, 176) }
1263
+ )
1264
+ } else {
1265
+ @(
1266
+ @{ o = 0.00; c = @(255, 252, 253, 255) },
1267
+ @{ o = 0.26; c = @(255, 226, 232, 240) },
1268
+ @{ o = 0.52; c = @(255, 190, 201, 214) },
1269
+ @{ o = 0.76; c = @(255, 146, 158, 173) },
1270
+ @{ o = 1.00; c = @(255, 104, 116, 130) }
1271
+ )
1272
+ }
1273
+ [void]$wrap.Children.Add((New-WhaleShape 18.0 17.0 $stops $true))
1274
+ $wrap.IsHitTestVisible = $false
1275
+ return @{ wrap = $wrap; scale = $scale; halo = $null; haloScale = $null }
1276
+ }
1277
+
1278
+ function New-PillBars($ph) {
1279
+ # The information-dense shape: three bars in a fixed 18 DIP slot, so animating their heights never
1280
+ # re-measures the capsule.
1281
+ $panel = New-Object System.Windows.Controls.StackPanel
1282
+ $panel.Orientation = [System.Windows.Controls.Orientation]::Horizontal
1283
+ $panel.Height = 18
1284
+ $panel.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
1285
+ $panel.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 0, 10, 0
1286
+ $bars = New-Object System.Collections.Generic.List[object]
1287
+ for ($i = 0; $i -lt 3; $i++) {
1288
+ $bar = New-Object System.Windows.Shapes.Rectangle
1289
+ $bar.Width = 2.4
1290
+ $bar.Height = 5.0
1291
+ $bar.RadiusX = 1.2; $bar.RadiusY = 1.2
1292
+ $bar.Fill = (New-Solid $ph.base 0.92)
1293
+ $bar.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
1294
+ $bar.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 0, 2.6, 0
1295
+ $bar.IsHitTestVisible = $false
1296
+ [void]$panel.Children.Add($bar)
1297
+ [void]$bars.Add($bar)
1298
+ }
1299
+ return @{ panel = $panel; bars = $bars }
1300
+ }
1301
+
1302
+ function New-PillMark {
1303
+ # A 20 DIP rounded square holding the identity mark, for the `mark` style only -- here the chip IS
1304
+ # the shape, so it has a surface of its own on purpose.
1305
+ #
1306
+ # The paper capsule used to come through this function too, which is why its whale looked like it
1307
+ # had a separate background: it did. `inverse` now draws the bare whale like `orb` does, in ink,
1308
+ # so no style except this one carries a second surface.
1309
+ $chip = New-Object System.Windows.Controls.Border
1310
+ $chip.Width = 20; $chip.Height = 20
1311
+ $chip.CornerRadius = New-Object System.Windows.CornerRadius -ArgumentList 6
1312
+ $chip.Background = New-Solid @(242, 245, 250) 1.0
1313
+ $chip.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
1314
+ $chip.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 0, 9, 0
1315
+ $chip.IsHitTestVisible = $false
1316
+ # Dark whale on the light chip.
1317
+ $ink = @(
1318
+ @{ o = 0.00; c = @(255, 30, 33, 39) },
1319
+ @{ o = 0.60; c = @(255, 12, 14, 18) },
1320
+ @{ o = 1.00; c = @(255, 4, 5, 7) }
1321
+ )
1322
+ $chip.Child = (New-WhaleShape 20.0 13.0 $ink $false)
1323
+ return $chip
1324
+ }
1325
+
1326
+ # ---------------------------------------------------------------- the thin smoke
1327
+ # Thin smoke is not "a few puffs of fog". A row of shapes is countable, and anything countable reads
1328
+ # as ticks on a ruler. What reads as smoke is a DENSITY FIELD: no silhouette, no period, no unit you
1329
+ # can point at, densest at the lip and gone before it reaches the text. So this layer draws no shape
1330
+ # at all; it bakes a noise texture per tone and drifts it.
1331
+ #
1332
+ # The three things that actually decide whether it reads as smoke (each measured, not assumed):
1333
+ # 1. ANISOTROPY. Strands are long in x and short in y. Isotropic noise is a cloud, and a cloud on
1334
+ # a 16 DIP lip reads as dirt. The lattice is therefore sparse across and dense down.
1335
+ # 2. THE THRESHOLD IS A PERCENTILE OF THE FIELD. fBm's mean sits near 0.5 and its range is narrow,
1336
+ # so any fixed cut-off silently produces either nothing or a solid bar. The cut is taken from
1337
+ # the sorted field (62nd / 72nd percentile), so "most of the tile is empty" is a property.
1338
+ # 3. THE VERTICAL ENVELOPE IS BAKED INTO ALPHA. (1-y)^2.1 is what makes it rise from the lip
1339
+ # instead of ending at a hard top edge.
1340
+ # The lattice wraps horizontally, so the tile is seamless and a one-way drift never jumps. Two
1341
+ # layers at different scale and speed drift the same way; the mismatch is where depth comes from.
1342
+ # The soft ends are an OpacityMask on the host, so the mist dissolves instead of being cut off.
1343
+ $script:MIST = [ordered]@{
1344
+ # "A bigger sheet, thinner": wider than the text block so the smoke reads as a sheet lying under
1345
+ # the whole capsule rather than a patch in the middle, and short enough that it never reaches the
1346
+ # type. The old 152 x 17 was a band; a sheet wants more width than height by a wider margin.
1347
+ width = 186.0 # host width in DIP; the mask fades the outer 14% at each end
1348
+ height = 13.0 # host height in DIP
1349
+ inset = 2.0 # distance from the shell's inner bottom edge, DIP
1350
+ }
1351
+
1352
+ function New-SmokeTexture([int]$w, [int]$h, [int]$seed, [double]$cellsX, [double]$cellsY,
1353
+ [double]$gamma, [double]$peak, [double]$cut, [double]$densPow,
1354
+ [int]$cr, [int]$cg, [int]$cb) {
1355
+ # Value-noise fBm on a wrapping lattice, anisotropic, with the vertical envelope in the alpha.
1356
+ # The wrap is what makes the drift seamless: the column right of the last one is the first one.
1357
+ $rnd = New-Object System.Random $seed
1358
+ $oct = 3
1359
+ $lwA = New-Object 'int[]' $oct
1360
+ $lhA = New-Object 'int[]' $oct
1361
+ $dataA = New-Object 'object[]' $oct
1362
+ $norm = 0.0
1363
+ $amp = 1.0
1364
+ for ($o = 0; $o -lt $oct; $o++) {
1365
+ $f = [Math]::Pow(2.0, $o)
1366
+ $lw = [int][Math]::Max(2, [Math]::Round($cellsX * $f))
1367
+ $lh = [int][Math]::Max(2, [Math]::Round($cellsY * $f))
1368
+ $d = New-Object 'double[]' ($lw * $lh)
1369
+ for ($i = 0; $i -lt $d.Length; $i++) { $d[$i] = $rnd.NextDouble() }
1370
+ $lwA[$o] = $lw; $lhA[$o] = $lh; $dataA[$o] = $d
1371
+ $norm += $amp
1372
+ $amp *= 0.5
1373
+ }
1374
+ $fld = New-Object 'double[]' ($w * $h)
1375
+ for ($y = 0; $y -lt $h; $y++) {
1376
+ for ($x = 0; $x -lt $w; $x++) {
1377
+ $n = 0.0
1378
+ $a = 1.0
1379
+ for ($o = 0; $o -lt $oct; $o++) {
1380
+ $lw = $lwA[$o]; $lh = $lhA[$o]; $d = $dataA[$o]
1381
+ $u = ((($x + 0.5) / [double]$w) * $lw)
1382
+ $v = ((($y + 0.5) / [double]$h) * $lh)
1383
+ $i0 = [int][Math]::Floor($u); $j0 = [int][Math]::Floor($v)
1384
+ $fx = $u - $i0; $fy = $v - $j0
1385
+ $sx = $fx * $fx * (3.0 - 2.0 * $fx)
1386
+ $sy = $fy * $fy * (3.0 - 2.0 * $fy)
1387
+ $x0 = $i0 % $lw; if ($x0 -lt 0) { $x0 += $lw }
1388
+ $x1 = ($i0 + 1) % $lw; if ($x1 -lt 0) { $x1 += $lw }
1389
+ $y0 = $j0 % $lh; if ($y0 -lt 0) { $y0 += $lh }
1390
+ $y1 = ($j0 + 1) % $lh; if ($y1 -lt 0) { $y1 += $lh }
1391
+ $v00 = $d[($y0 * $lw) + $x0]; $v10 = $d[($y0 * $lw) + $x1]
1392
+ $v01 = $d[($y1 * $lw) + $x0]; $v11 = $d[($y1 * $lw) + $x1]
1393
+ $top = $v00 + ($v10 - $v00) * $sx
1394
+ $bot = $v01 + ($v11 - $v01) * $sx
1395
+ $n += $a * ($top + ($bot - $top) * $sy)
1396
+ $a *= 0.5
1397
+ }
1398
+ $fld[($y * $w) + $x] = $n / $norm
1399
+ }
1400
+ }
1401
+ # The cut is a percentile of what this seed actually produced, so the fill ratio is a measured
1402
+ # property of the tile rather than a guess that happens to look right on one monitor.
1403
+ $sorted = New-Object 'double[]' $fld.Length
1404
+ [Array]::Copy($fld, $sorted, $fld.Length)
1405
+ [Array]::Sort($sorted)
1406
+ $lo = $sorted[[int][Math]::Min($sorted.Length - 1, $sorted.Length * $cut)]
1407
+ $hi = $sorted[[int][Math]::Min($sorted.Length - 1, $sorted.Length * 0.995)]
1408
+ $span = $hi - $lo
1409
+ if ($span -le 0.0001) { $span = 0.0001 }
1410
+ $px = New-Object 'byte[]' ($w * $h * 4)
1411
+ for ($y = 0; $y -lt $h; $y++) {
1412
+ # Row 0 is the TOP of the band and row h-1 is the lip, because the host is pinned to the
1413
+ # shell's bottom edge. The envelope therefore grows with y: writing (1-y) here put the densest
1414
+ # smoke at the top of the band and left the lip empty, which is backwards.
1415
+ $ny = if ($h -gt 1) { $y / [double]($h - 1) } else { 1.0 }
1416
+ $dens = [Math]::Pow($ny, $densPow)
1417
+ for ($x = 0; $x -lt $w; $x++) {
1418
+ $t = ($fld[($y * $w) + $x] - $lo) / $span
1419
+ if ($t -lt 0.0) { $t = 0.0 } elseif ($t -gt 1.0) { $t = 1.0 }
1420
+ $t = $t * $t * (3.0 - 2.0 * $t)
1421
+ $t = [Math]::Pow($t, $gamma)
1422
+ $al = [int][Math]::Round(255.0 * $peak * $dens * $t)
1423
+ if ($al -gt 255) { $al = 255 } elseif ($al -lt 0) { $al = 0 }
1424
+ $i = (($y * $w) + $x) * 4
1425
+ # Bgra32, straight alpha: premultiplying here would make a low-alpha veil darker than the
1426
+ # tone that was asked for.
1427
+ $px[$i] = [byte]$cb; $px[$i + 1] = [byte]$cg; $px[$i + 2] = [byte]$cr; $px[$i + 3] = [byte]$al
1428
+ }
1429
+ }
1430
+ $bmp = [System.Windows.Media.Imaging.BitmapSource]::Create($w, $h, 96.0, 96.0,
1431
+ [System.Windows.Media.PixelFormats]::Bgra32, $null, $px, $w * 4)
1432
+ $bmp.Freeze()
1433
+ return $bmp
1434
+ }
1435
+
1436
+ $script:smokeCache = @{}
1437
+ function Get-SmokeTexture([string]$key, [scriptblock]$build) {
1438
+ # Baking costs a few hundred noise samples per texel, and Render-Layout rebuilds the tree on every
1439
+ # phase/look change. The texture is immutable and frozen, so it is built once per tone.
1440
+ if ($script:smokeCache.ContainsKey($key)) { return $script:smokeCache[$key] }
1441
+ $tex = & $build
1442
+ $script:smokeCache[$key] = $tex
1443
+ return $tex
1444
+ }
1445
+
1446
+ function New-SmokeLayer($tex, [double]$tileW, [double]$layerH, [double]$hostW, [double]$opacity, [double]$driftSec, [double]$blurPx, [double]$yoff) {
1447
+ # One tile is drawn once and repeated by the brush; the element is two tiles wider than the host
1448
+ # and slides exactly one tile, so the wrap is invisible and the motion never reverses. A repeating
1449
+ # AutoReverse animation is exactly what made the old lobes look like they were breathing.
1450
+ $brush = New-Object System.Windows.Media.ImageBrush
1451
+ $brush.ImageSource = $tex
1452
+ $brush.Stretch = [System.Windows.Media.Stretch]::Fill
1453
+ $brush.TileMode = [System.Windows.Media.TileMode]::Tile
1454
+ $brush.ViewportUnits = [System.Windows.Media.BrushMappingMode]::Absolute
1455
+ $brush.Viewport = New-Object System.Windows.Rect -ArgumentList 0.0, 0.0, $tileW, $layerH
1456
+ $brush.AlignmentX = [System.Windows.Media.AlignmentX]::Left
1457
+ $brush.AlignmentY = [System.Windows.Media.AlignmentY]::Top
1458
+ $brush.Freeze()
1459
+ $layer = New-Object System.Windows.Controls.Border
1460
+ $layer.Width = $hostW + ($tileW * 2.0)
1461
+ $layer.Height = $layerH
1462
+ $layer.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Left
1463
+ $layer.VerticalAlignment = [System.Windows.VerticalAlignment]::Bottom
1464
+ $layer.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 0, 0, ([double]$yoff)
1465
+ $layer.Background = $brush
1466
+ $layer.Opacity = $opacity
1467
+ $layer.IsHitTestVisible = $false
1468
+ if ($blurPx -gt 0) {
1469
+ # A small blur removes the last lattice anisotropy; the softness itself is already in the
1470
+ # texture, so this stays cheap and there is still no edge to see.
1471
+ $blur = New-Object System.Windows.Media.Effects.BlurEffect
1472
+ $blur.Radius = $blurPx
1473
+ $blur.KernelType = [System.Windows.Media.Effects.KernelType]::Gaussian
1474
+ $layer.Effect = $blur
1475
+ }
1476
+ $move = New-Object System.Windows.Media.TranslateTransform -ArgumentList 0.0, 0.0
1477
+ $layer.RenderTransform = $move
1478
+ $drift = New-Object System.Windows.Media.Animation.DoubleAnimation
1479
+ $drift.From = 0.0
1480
+ $drift.To = -$tileW
1481
+ $drift.Duration = [TimeSpan]::FromMilliseconds([double]$driftSec * 1000.0)
1482
+ $drift.RepeatBehavior = [System.Windows.Media.Animation.RepeatBehavior]::Forever
1483
+ $move.BeginAnimation([System.Windows.Media.TranslateTransform]::XProperty, $drift)
1484
+ return $layer
1485
+ }
1486
+
1487
+ function New-PillFloor([bool]$inverse) {
1488
+ # The smoke lives in its own window-level layer instead of inside the text Border: Border child
1489
+ # layout kept centring it on the text row. Here it is a bottom-pinned host, and Build-Pill pins
1490
+ # that host to the shell's inner floor.
1491
+ #
1492
+ # The host carries NO width of its own and stretches instead. A fixed width participates in the
1493
+ # capsule's measurement: WPF takes the widest child, so a 186 DIP smoke host made the pill 218 DIP
1494
+ # wide with ~80 empty DIP of shell to the right of the text. Measured width comes from the TEXT,
1495
+ # and the smoke sheet simply fills whatever the text produced.
1496
+ $M = $script:MIST
1497
+ $floor = New-Object System.Windows.Controls.Grid
1498
+ $floor.Height = [double]$M.height
1499
+ $floor.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Stretch
1500
+ $floor.VerticalAlignment = [System.Windows.VerticalAlignment]::Bottom
1501
+ $floor.ClipToBounds = $true
1502
+ $floor.IsHitTestVisible = $false
1503
+
1504
+ # The smoke is LIGHT on a dark shell: a veil of the capsule's own accent, brightest where it is
1505
+ # densest. On the paper capsule that inverts badly -- the same veil reads as a grey smudge along
1506
+ # the lip, because on a near-white surface any darkening is dirt rather than smoke. So the paper
1507
+ # shell does not get a darker mist; it gets a WHITE one, which is how thin smoke actually appears
1508
+ # when the light behind it is stronger than the surface: a bright haze, not a stain.
1509
+ $mr = if ($inverse) { 255 } else { 236 }
1510
+ $mg = if ($inverse) { 255 } else { 244 }
1511
+ $mb = if ($inverse) { 255 } else { 254 }
1512
+
1513
+ # The source: a half-ellipse of light right at the lip, so the mist has somewhere to come from.
1514
+ # It has no edge of its own -- the radial falloff is the whole shape. Wider and flatter than the
1515
+ # layer it feeds, because the sheet should look like it is spreading out of a broad seam.
1516
+ $anchor = New-Object System.Windows.Controls.Border
1517
+ $anchor.Width = 140; $anchor.Height = 3.8
1518
+ $anchor.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Center
1519
+ $anchor.VerticalAlignment = [System.Windows.VerticalAlignment]::Bottom
1520
+ $anchor.Opacity = 0.32
1521
+ $anchor.IsHitTestVisible = $false
1522
+ $ab = New-Object System.Windows.Media.RadialGradientBrush
1523
+ $ab.Center = New-Object System.Windows.Point -ArgumentList 0.5, 1.0
1524
+ $ab.GradientOrigin = New-Object System.Windows.Point -ArgumentList 0.5, 1.0
1525
+ $ab.RadiusX = 0.5; $ab.RadiusY = 1.0
1526
+ foreach ($sp in @(
1527
+ @{ o = 0.00; a = 110 },
1528
+ @{ o = 0.50; a = 26 },
1529
+ @{ o = 1.00; a = 0 }
1530
+ )) {
1531
+ $gs = New-Object System.Windows.Media.GradientStop
1532
+ $gs.Color = [System.Windows.Media.Color]::FromArgb([byte]$sp.a, [byte]$mr, [byte]$mg, [byte]$mb)
1533
+ $gs.Offset = [double]$sp.o
1534
+ [void]$ab.GradientStops.Add($gs)
1535
+ }
1536
+ $anchor.Background = $ab
1537
+ [void]$floor.Children.Add($anchor)
1538
+
1539
+ # Far layer: long slow billows, wider tile -- the body of the haze. Fewer cells across than the
1540
+ # near layer, so a tile holds a few long strands instead of a texture, and a longer tile means the
1541
+ # pattern is bigger than the capsule before it repeats.
1542
+ $farTex = Get-SmokeTexture (('far|' + [string]$inverse)) {
1543
+ New-SmokeTexture 192 32 7301 4.2 1.0 1.4 1.00 0.66 3.8 $mr $mg $mb
1544
+ }
1545
+ [void]$floor.Children.Add((New-SmokeLayer $farTex 124.0 12.0 ([double]$M.width) $(if ($inverse) { 0.30 } else { 0.58 }) 55.0 6.5 0.7))
1546
+ # Near layer: finer filaments, quicker, shorter tile -- the surface of it. The two periods never
1547
+ # divide into each other, so the pair never falls back into a visible loop. Thin on purpose: this
1548
+ # is the layer that would make the sheet read as a wash if it were strong.
1549
+ $nearTex = Get-SmokeTexture (('near|' + [string]$inverse)) {
1550
+ New-SmokeTexture 128 24 4409 7.4 1.4 1.1 0.66 0.72 3.4 $mr $mg $mb
1551
+ }
1552
+ [void]$floor.Children.Add((New-SmokeLayer $nearTex 83.0 13.0 ([double]$M.width) $(if ($inverse) { 0.14 } else { 0.28 }) 31.0 3.6 0.0))
1553
+
1554
+ # The ends dissolve: an alpha ramp on the host, so the smoke thins out instead of stopping. The
1555
+ # plateau is wide (10%..90%) because the sheet is supposed to span the capsule, not sit in its
1556
+ # middle: a narrow plateau made the previous build read as a patch under the type.
1557
+ $mask = New-Object System.Windows.Media.LinearGradientBrush
1558
+ $mask.StartPoint = New-Object System.Windows.Point -ArgumentList 0.0, 0.5
1559
+ $mask.EndPoint = New-Object System.Windows.Point -ArgumentList 1.0, 0.5
1560
+ foreach ($st in @(
1561
+ @{ o = 0.00; a = 0 },
1562
+ @{ o = 0.10; a = 255 },
1563
+ @{ o = 0.50; a = 255 },
1564
+ @{ o = 0.90; a = 255 },
1565
+ @{ o = 1.00; a = 0 }
1566
+ )) {
1567
+ $gs = New-Object System.Windows.Media.GradientStop
1568
+ $gs.Color = [System.Windows.Media.Color]::FromArgb([byte]$st.a, 0, 0, 0)
1569
+ $gs.Offset = [double]$st.o
1570
+ [void]$mask.GradientStops.Add($gs)
1571
+ }
1572
+ $floor.OpacityMask = $mask
1573
+ return $floor
1574
+ }
1575
+
1576
+ function Build-Pill($ph) {
1577
+ # Four shapes, two things to decide: the shell (black or paper) and the mark.
1578
+ #
1579
+ # ALL FOUR are the same size: 44 DIP, 22 DIP radius. `inverse` used to be grouped with `wave` as
1580
+ # a "dense" two-line shape, so the paper capsule came out 56 DIP tall with a 25 DIP radius and
1581
+ # switching to it moved the pill under the pointer. Size is not part of what "paper" means, so the
1582
+ # shell colour and the height are decided separately now.
1583
+ #
1584
+ # The mark is the whale on every style. `orb` and `inverse` draw it bare on the shell; `mark`
1585
+ # keeps the chip, because that chip IS the shape; `wave` shows bars instead.
1586
+ $style = [string]$script:S.pillStyle
1587
+ if ($style -eq '') { $style = 'orb' }
1588
+ $inverse = ($style -eq 'inverse')
1589
+ $border = New-Object System.Windows.Controls.Border
1590
+ $border.CornerRadius = New-Object System.Windows.CornerRadius -ArgumentList 22
1591
+ $border.MinHeight = 44
1592
+ # FIXED width. The capsule used to size to its content, which made its length a function of the
1593
+ # text: the thin-smoke host (186 DIP) was the widest child and stretched every capsule to 218 DIP
1594
+ # with ~80 empty DIP of shell past the type. A fixed length keeps the silhouette stable --
1595
+ # constant shape, constant position of everything inside it, no layout shift when the state word
1596
+ # changes -- and the smoke sheet fills whatever this width is instead of dictating it.
1597
+ # 172 DIP: mark(18) + gap(9) + heading(~34) + gap(10) + longest state word(~78) + padding(26).
1598
+ # 160 was tried and squeezed the heading against the state word; the user settled on 172.
1599
+ $border.Width = 172.0
1600
+ $bgT = $script:S.pillBg; if ($null -eq $bgT) { $bgT = @(11, 13, 16) }
1601
+ $bgBrush = New-Object System.Windows.Media.LinearGradientBrush
1602
+ $bgBrush.StartPoint = New-Object System.Windows.Point -ArgumentList 0.0, 0.0
1603
+ $bgBrush.EndPoint = New-Object System.Windows.Point -ArgumentList 0.0, 1.0
1604
+ $bg0 = New-Object System.Windows.Media.GradientStop
1605
+ $bg1 = New-Object System.Windows.Media.GradientStop
1606
+ if ($inverse) {
1607
+ $bgT = @(244, 246, 249)
1608
+ $bg0.Color = [System.Windows.Media.Color]::FromArgb([byte]252, 255, 255, 255); $bg0.Offset = 0.0
1609
+ $bg1.Color = [System.Windows.Media.Color]::FromArgb([byte]245, [byte]233, [byte]237, [byte]242); $bg1.Offset = 1.0
1610
+ } else {
1611
+ $bg0.Color = [System.Windows.Media.Color]::FromArgb([byte]248, [byte]$bgT[0], [byte]$bgT[1], [byte]$bgT[2]); $bg0.Offset = 0.0
1612
+ $bg1.Color = [System.Windows.Media.Color]::FromArgb([byte]236, [byte]$bgT[0], [byte]$bgT[1], [byte]$bgT[2]); $bg1.Offset = 1.0
1613
+ }
1614
+ [void]$bgBrush.GradientStops.Add($bg0); [void]$bgBrush.GradientStops.Add($bg1)
1615
+ $border.Background = $bgBrush
1616
+ # A vertical hairline (brighter on top) instead of a coloured stroke: coloured borders read as
1617
+ # a badge, light-on-glass reads as a surface. On paper the hairline turns dark for the same reason.
1618
+ $edge = New-Object System.Windows.Media.LinearGradientBrush
1619
+ $edge.StartPoint = New-Object System.Windows.Point -ArgumentList 0.0, 0.0
1620
+ $edge.EndPoint = New-Object System.Windows.Point -ArgumentList 0.0, 1.0
1621
+ $e0 = New-Object System.Windows.Media.GradientStop
1622
+ $e1 = New-Object System.Windows.Media.GradientStop
1623
+ if ($inverse) {
1624
+ $e0.Color = [System.Windows.Media.Color]::FromArgb([byte]44, 0, 0, 0); $e0.Offset = 0.0
1625
+ $e1.Color = [System.Windows.Media.Color]::FromArgb([byte]10, 0, 0, 0); $e1.Offset = 1.0
1626
+ } else {
1627
+ $e0.Color = [System.Windows.Media.Color]::FromArgb([byte]54, 255, 255, 255); $e0.Offset = 0.0
1628
+ $e1.Color = [System.Windows.Media.Color]::FromArgb([byte]10, 255, 255, 255); $e1.Offset = 1.0
1629
+ }
1630
+ [void]$edge.GradientStops.Add($e0); [void]$edge.GradientStops.Add($e1)
1631
+ $border.BorderBrush = $edge
1632
+ $border.BorderThickness = New-Object System.Windows.Thickness -ArgumentList 1.0
1633
+ # Symmetric padding, and the content grid CENTRED: the shell is a fixed-length capsule now, so
1634
+ # left-aligned content would pile all the slack on the right (the "右边空间分明无用" complaint).
1635
+ # Centring splits the remaining width evenly, whatever the state word measures.
1636
+ $border.Padding = New-Object System.Windows.Thickness -ArgumentList 13, 0, 13, 0
1637
+ # The bloom is the phase accent at low opacity, spread evenly (depth 0), so the capsule sits in its
1638
+ # own light instead of casting a grey office shadow.
1639
+ $glow = New-Object System.Windows.Media.Effects.DropShadowEffect
1640
+ if ($inverse) {
1641
+ $glow.Color = [System.Windows.Media.Color]::FromRgb(214, 220, 228)
1642
+ $glow.Opacity = 0.30
1643
+ } else {
1644
+ $glow.Color = [System.Windows.Media.Color]::FromRgb([byte]$ph.base[0], [byte]$ph.base[1], [byte]$ph.base[2])
1645
+ $glow.Opacity = 0.40
1646
+ }
1647
+ $glow.BlurRadius = 24
1648
+ $glow.ShadowDepth = 0
1649
+ $border.Effect = $glow
1650
+ $border.IsHitTestVisible = $false
1651
+
1652
+ $grid = New-Object System.Windows.Controls.Grid
1653
+ $grid.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
1654
+ # The state column STRETCHES and its text right-aligns inside it. The state word changes length
1655
+ # per phase (正在操控电脑 is 6 chars, 已停止 is 3), so left-aligning it would leave a different
1656
+ # right-hand gap per phase on a fixed-length shell. Stretching the column and right-aligning the
1657
+ # text pins the text's RIGHT edge to one constant x: the stopped capsule ends its wording exactly
1658
+ # where the acting one does, and the slack accumulates between the mark and the text instead.
1659
+ $grid.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Stretch
1660
+ # Three columns: mark | DSH heading | state word. The mark and the heading keep FIXED positions
1661
+ # (same x as always); only the state word lives in the stretching column, right-aligned, so its
1662
+ # right edge stays at one constant x no matter how long the phase wording is. The gap between the
1663
+ # heading and the state word is elastic and absorbs the length difference.
1664
+ $c0 = New-Object System.Windows.Controls.ColumnDefinition
1665
+ $c0.Width = [System.Windows.GridLength]::Auto
1666
+ $c1 = New-Object System.Windows.Controls.ColumnDefinition
1667
+ $c1.Width = [System.Windows.GridLength]::Auto
1668
+ $c2 = New-Object System.Windows.Controls.ColumnDefinition
1669
+ # ::new() is the form that works here: the two-argument New-Object variant fails to convert the
1670
+ # enum parameter on this framework build (measured: internal_error, 无法转换 GridLength 参数 1).
1671
+ $c2.Width = [System.Windows.GridLength]::new(1.0, [System.Windows.GridUnitType]::Star)
1672
+ [void]$grid.ColumnDefinitions.Add($c0); [void]$grid.ColumnDefinitions.Add($c1); [void]$grid.ColumnDefinitions.Add($c2)
1673
+
1674
+ $orb = $null
1675
+ $bars = $null
1676
+ $indicator = $null
1677
+ switch ($style) {
1678
+ 'orb' { $orb = New-PillOrb $ph $false; $orb.wrap.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 0, 9, 0; $indicator = $orb.wrap }
1679
+ 'wave' { $bars = New-PillBars $ph; $indicator = $bars.panel }
1680
+ 'mark' { $indicator = New-PillMark }
1681
+ # Same bare whale as `orb`, inked for the paper shell: no chip, same 18 DIP slot, same position.
1682
+ 'inverse' { $orb = New-PillOrb $ph $true; $orb.wrap.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 0, 9, 0; $indicator = $orb.wrap }
1683
+ default { $orb = New-PillOrb $ph $false; $orb.wrap.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 0, 9, 0; $indicator = $orb.wrap }
1684
+ }
1685
+ [System.Windows.Controls.Grid]::SetColumn($indicator, 0)
1686
+ [void]$grid.Children.Add($indicator)
1687
+
1688
+ $stack = New-Object System.Windows.Controls.StackPanel
1689
+ $stack.Orientation = [System.Windows.Controls.Orientation]::Vertical
1690
+ $stack.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
1691
+ # The HEADING ("DSH", bold) lives in its own fixed column, so its x never moves.
1692
+ $txt = New-Object System.Windows.Controls.TextBlock
1693
+ $txt.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Left
1694
+ $txt.FontSize = 13.0
1695
+ $txt.FontFamily = New-Object System.Windows.Media.FontFamily -ArgumentList $script:S.chosenFont
1696
+ $fgT = $script:S.pillText; if ($null -eq $fgT) { $fgT = @(242, 245, 250) }
1697
+ if ($inverse) { $fgT = @(8, 9, 11) }
1698
+ $txt.Foreground = (New-Solid $fgT 1.0)
1699
+ $brandRun = New-Object System.Windows.Documents.Run -ArgumentList $script:TEXT.brand
1700
+ $brandRun.FontWeight = [System.Windows.FontWeights]::Bold
1701
+ [void]$txt.Inlines.Add($brandRun)
1702
+ # Column 1 is a vertical pair: the fixed heading on top, the (rare) second line under it. Both
1703
+ # keep their x because the column is Auto-sized and left-aligned.
1704
+ $stack = New-Object System.Windows.Controls.StackPanel
1705
+ $stack.Orientation = [System.Windows.Controls.Orientation]::Vertical
1706
+ $stack.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
1707
+ [void]$stack.Children.Add($txt)
1708
+ # The STATE word lives in the stretching column, right-aligned: its right edge is the one
1709
+ # constant the person compares across phases (正在操控电脑 vs 已停止 differ by 3 chars, and on a
1710
+ # fixed-length shell that difference must show up in the middle gap, never in the right margin).
1711
+ $restTxt = New-Object System.Windows.Controls.TextBlock
1712
+ $restTxt.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Right
1713
+ $restTxt.VerticalAlignment = [System.Windows.VerticalAlignment]::Center
1714
+ $restTxt.FontSize = 13.0
1715
+ $restTxt.FontFamily = New-Object System.Windows.Media.FontFamily -ArgumentList $script:S.chosenFont
1716
+ $restTxt.Foreground = (New-Solid $fgT 0.74)
1717
+ $restRun = New-Object System.Windows.Documents.Run -ArgumentList ''
1718
+ [void]$restTxt.Inlines.Add($restRun)
1719
+ [System.Windows.Controls.Grid]::SetColumn($restTxt, 2)
1720
+ [void]$grid.Children.Add($restTxt)
1721
+ $sub = New-Object System.Windows.Controls.TextBlock
1722
+ $sub.HorizontalAlignment = [System.Windows.HorizontalAlignment]::Left
1723
+ $sub.FontSize = 10.5
1724
+ $sub.FontFamily = New-Object System.Windows.Media.FontFamily -ArgumentList $script:S.chosenFont
1725
+ $sub.Foreground = if ($inverse) { New-Solid @(90, 96, 104) 0.70 } else { New-Solid @(214, 221, 230) 0.62 }
1726
+ $sub.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 1, 0, 0
1727
+ $sub.Text = ''
1728
+ $sub.Visibility = [System.Windows.Visibility]::Collapsed
1729
+ [void]$stack.Children.Add($sub)
1730
+ [System.Windows.Controls.Grid]::SetColumn($stack, 1)
1731
+ [void]$grid.Children.Add($stack)
1732
+
1733
+ # The smoke sits on the inner lip of the shell, inset by MIST.inset so it never reads as an outer
1734
+ # underline. It is its own full-size layer; the text grid only carries the orb and the runs.
1735
+ #
1736
+ # The layer is skipped entirely when the person turned it off, rather than being made transparent:
1737
+ # a zero-opacity layer still costs a tile brush, a blur and a running drift animation for every
1738
+ # frame of the capsule's life.
1739
+ $root = New-Object System.Windows.Controls.Grid
1740
+ $root.ClipToBounds = $true
1741
+ [void]$root.Children.Add($grid)
1742
+ if ($script:S.mistOn) {
1743
+ $floor = New-PillFloor $inverse
1744
+ $floor.Margin = New-Object System.Windows.Thickness -ArgumentList 0, 0, 0, ([double]$script:MIST.inset)
1745
+ [void]$root.Children.Add($floor)
1746
+ }
1747
+ $border.Child = $root
1748
+
1749
+ # Scale from slightly small and translucent: the island "opens" instead of popping in.
1750
+ $scale = New-Object System.Windows.Media.ScaleTransform -ArgumentList 0.90, 0.90
1751
+ $border.RenderTransform = $scale
1752
+ $border.RenderTransformOrigin = New-Object System.Windows.Point -ArgumentList 0.5, 0.5
1753
+ $border.Opacity = 0.0
1754
+ return @{
1755
+ border = $border; text = $txt; sub = $sub; scale = $scale; brandRun = $brandRun; restRun = $restRun
1756
+ orb = if ($null -ne $orb) { $orb.wrap } else { $null }
1757
+ orbScale = if ($null -ne $orb) { $orb.scale } else { $null }
1758
+ orbHalo = if ($null -ne $orb) { $orb.halo } else { $null }
1759
+ orbHaloScale = if ($null -ne $orb) { $orb.haloScale } else { $null }
1760
+ bars = if ($null -ne $bars) { $bars.bars } else { @() }
1761
+ }
1762
+ }
1763
+
1764
+ function Start-PillIntro {
1765
+ if ($null -eq $script:S.pill) { return }
1766
+ $dur = [TimeSpan]::FromMilliseconds(340)
1767
+ $ease = New-Object System.Windows.Media.Animation.BackEase
1768
+ $ease.EasingMode = [System.Windows.Media.Animation.EasingMode]::EaseOut
1769
+ $ease.Amplitude = 0.28
1770
+ $sx = New-Object System.Windows.Media.Animation.DoubleAnimation -ArgumentList 0.90, 1.0, $dur
1771
+ $sx.EasingFunction = $ease
1772
+ $sy = New-Object System.Windows.Media.Animation.DoubleAnimation -ArgumentList 0.90, 1.0, $dur
1773
+ $sy.EasingFunction = $ease
1774
+ $op = New-Object System.Windows.Media.Animation.DoubleAnimation -ArgumentList 0.0, 1.0, ([TimeSpan]::FromMilliseconds(180))
1775
+ if ($null -ne $script:S.pillScale) {
1776
+ $script:S.pillScale.BeginAnimation([System.Windows.Media.ScaleTransform]::ScaleXProperty, $sx)
1777
+ $script:S.pillScale.BeginAnimation([System.Windows.Media.ScaleTransform]::ScaleYProperty, $sy)
1778
+ }
1779
+ $script:S.pill.BeginAnimation([System.Windows.UIElement]::OpacityProperty, $op)
1780
+ }
1781
+
1782
+ function Start-PillOrb([bool]$on) {
1783
+ # The whale is fixed in size. Only its tail control points move; there is no whole-icon breathing
1784
+ # and no halo bloom left from the glass-bead version.
1785
+ $wrap = $script:S.pillOrb
1786
+ if ($null -eq $wrap) { return }
1787
+ $scale = $script:S.pillOrbScale
1788
+ $halo = $script:S.pillOrbHalo
1789
+ $haloScale = $script:S.pillOrbHaloScale
1790
+ if (-not $on) {
1791
+ try {
1792
+ $scale.BeginAnimation([System.Windows.Media.ScaleTransform]::ScaleXProperty, $null)
1793
+ $scale.BeginAnimation([System.Windows.Media.ScaleTransform]::ScaleYProperty, $null)
1794
+ if ($null -ne $halo) { $halo.BeginAnimation([System.Windows.UIElement]::OpacityProperty, $null) }
1795
+ if ($null -ne $haloScale) {
1796
+ $haloScale.BeginAnimation([System.Windows.Media.ScaleTransform]::ScaleXProperty, $null)
1797
+ $haloScale.BeginAnimation([System.Windows.Media.ScaleTransform]::ScaleYProperty, $null)
1798
+ }
1799
+ } catch { }
1800
+ $scale.ScaleX = 1.0; $scale.ScaleY = 1.0
1801
+ if ($null -ne $halo) { $halo.Opacity = 0.30 }
1802
+ if ($null -ne $haloScale) { $haloScale.ScaleX = 1.0; $haloScale.ScaleY = 1.0 }
1803
+ return
1804
+ }
1805
+ $scale.ScaleX = 1.0; $scale.ScaleY = 1.0
1806
+ if ($null -ne $halo) {
1807
+ $bloom = New-Object System.Windows.Media.Animation.DoubleAnimation
1808
+ $bloom.From = 0.24; $bloom.To = 0.62
1809
+ $bloom.Duration = [TimeSpan]::FromMilliseconds(2600)
1810
+ $bloom.AutoReverse = $true
1811
+ $bloom.RepeatBehavior = [System.Windows.Media.Animation.RepeatBehavior]::Forever
1812
+ $bloom.EasingFunction = $ease
1813
+ $halo.BeginAnimation([System.Windows.UIElement]::OpacityProperty, $bloom)
1814
+ }
1815
+ if ($null -ne $haloScale) {
1816
+ foreach ($axis in @([System.Windows.Media.ScaleTransform]::ScaleXProperty, [System.Windows.Media.ScaleTransform]::ScaleYProperty)) {
1817
+ $pulse = New-Object System.Windows.Media.Animation.DoubleAnimation
1818
+ $pulse.From = 0.92; $pulse.To = 1.10
1819
+ $pulse.Duration = [TimeSpan]::FromMilliseconds(2600)
1820
+ $pulse.AutoReverse = $true
1821
+ $pulse.RepeatBehavior = [System.Windows.Media.Animation.RepeatBehavior]::Forever
1822
+ $pulse.EasingFunction = $ease
1823
+ $haloScale.BeginAnimation($axis, $pulse)
1824
+ }
1825
+ }
1826
+ }
1827
+
1828
+ function Start-PillBars([bool]$on) {
1829
+ # The wave style's own heartbeat: three bars at staggered delays, so the group reads as sound rather
1830
+ # than three independent dots. Off freezes them mid-height and lets the colour carry the state.
1831
+ $bars = @($script:S.pillBars)
1832
+ if ($bars.Count -eq 0) { return }
1833
+ $ease = New-Object System.Windows.Media.Animation.SineEase
1834
+ $ease.EasingMode = [System.Windows.Media.Animation.EasingMode]::EaseInOut
1835
+ $delays = @(0, 160, 320)
1836
+ for ($i = 0; $i -lt $bars.Count; $i++) {
1837
+ $bar = $bars[$i]
1838
+ if (-not $on) {
1839
+ try { $bar.BeginAnimation([System.Windows.FrameworkElement]::HeightProperty, $null) } catch { }
1840
+ $bar.Height = 5.0
1841
+ continue
1842
+ }
1843
+ $anim = New-Object System.Windows.Media.Animation.DoubleAnimation
1844
+ $anim.From = 4.0; $anim.To = 15.0
1845
+ $anim.Duration = [TimeSpan]::FromMilliseconds(620)
1846
+ $anim.AutoReverse = $true
1847
+ $anim.RepeatBehavior = [System.Windows.Media.Animation.RepeatBehavior]::Forever
1848
+ $anim.EasingFunction = $ease
1849
+ $anim.BeginTime = [TimeSpan]::FromMilliseconds($delays[$i % 3])
1850
+ $bar.BeginAnimation([System.Windows.FrameworkElement]::HeightProperty, $anim)
1851
+ }
1852
+ }
1853
+
1854
+ function Clear-Canvas {
1855
+ # Every call throws away the visual tree, so every call restarts the intro animation. Counting it
1856
+ # is what makes "one flash per action" measurable instead of a matter of opinion: a run that does
1857
+ # twenty actions must show layoutBuilds = 1, not 20.
1858
+ $script:S.layoutBuilds += 1
1859
+ if ($null -ne $script:S.canvas) { $script:S.canvas.Children.Clear() }
1860
+ $script:S.ring = @(); $script:S.bloom = @()
1861
+ $script:S.pill = $null; $script:S.pillText = $null; $script:S.pillSub = $null
1862
+ $script:S.pillOrb = $null; $script:S.pillOrbScale = $null; $script:S.pillOrbHalo = $null; $script:S.pillOrbHaloScale = $null; $script:S.pillBars = @()
1863
+ $script:S.pillScale = $null; $script:S.pillBrandRun = $null; $script:S.pillRestRun = $null
1864
+ $script:S.halo = $null; $script:S.haloBlooms = @(); $script:S.haloOn = $false
1865
+ $script:S.haloCurs = $null; $script:S.haloShape = [IntPtr]::Zero
1866
+ }
1867
+
1868
+ # Rebuilds the visual set for the current monitor geometry + phase. The Window object is never
1869
+ # touched here, so the HWND (and hwndCreateCount) survives every phase change.
1870
+ function Update-PhaseLook {
1871
+ # Recolour the live tree for the current phase, WITHOUT rebuilding it.
1872
+ #
1873
+ # The phase used to be part of Render-Layout's cache key, so acting -> stopped cleared the canvas
1874
+ # and rebuilt every visual, which replayed the intro animation: the person saw the capsule turn
1875
+ # red and then pop in again -- "the stopped state flashes twice". A phase change only needs new
1876
+ # colours, so this rewrites the brushes that depend on the phase and leaves geometry, layout and
1877
+ # the running animations alone.
1878
+ #
1879
+ # Only the ring/bloom and the pill's own accent depend on the phase; the shell colour, the text
1880
+ # and the mark come from the palette/style and are already correct.
1881
+ if ($null -eq $script:S.canvas) { return }
1882
+ $ph = $script:PH[$script:S.phase]
1883
+ if ($null -eq $ph) { return }
1884
+ $m = $script:S.monitorBounds
1885
+ if ($null -eq $m) { return }
1886
+ $sc = [double]$script:S.scale; if ($sc -le 0) { $sc = 1.0 }
1887
+ $W = [double]$m.w / $sc
1888
+ $H = [double]$m.h / $sc
1889
+ $T = [double]$CFG.ringPx / $sc
1890
+ $dark = Test-DarkAmbient $ph.g0
1891
+ $mask = if ($dark) { 'New-Vignette' } else { 'New-Fade' }
1892
+ # Rebuild only the four ring/bloom bars in place: they are pure colour + mask, no layout state.
1893
+ $E = $T * 4.0
1894
+ # `$edges`, not `$specs`: a gate forbids that name outside the smoke builder, where it used to be
1895
+ # the signature of the drawn mist lobes.
1896
+ $edges = @(
1897
+ @{ x = 0; y = 0; w = $W; h = $E; g0 = $ph.g0; g1 = $ph.g1; flip = $false; m = @(0.5, 0.0, 0.5, 1.0) },
1898
+ @{ x = 0; y = ($H - $E); w = $W; h = $E; g0 = $ph.g1; g1 = $ph.g0; flip = $false; m = @(0.5, 1.0, 0.5, 0.0) },
1899
+ @{ x = 0; y = 0; w = $E; h = $H; g0 = $ph.g0; g1 = $ph.g1; flip = $true; m = @(0.0, 0.5, 1.0, 0.5) },
1900
+ @{ x = ($W - $E); y = 0; w = $E; h = $H; g0 = $ph.g0; g1 = $ph.g1; flip = $false; m = @(1.0, 0.5, 0.0, 0.5) }
1901
+ )
1902
+ $i = 0
1903
+ foreach ($b in @($script:S.bloom)) {
1904
+ if ($null -eq $b -or $i -ge $edges.Count) { break }
1905
+ $s = $edges[$i]
1906
+ $b.Fill = (New-GradH $s.g0 $s.g1 0.85 ([bool]$s.flip))
1907
+ $b.OpacityMask = (& $mask $s.m[0] $s.m[1] $s.m[2] $s.m[3] 1.0)
1908
+ $i++
1909
+ }
1910
+ # The pill's bloom is the phase accent, so it has to follow too -- otherwise a red stopped phase
1911
+ # sits in a silver halo.
1912
+ if ($null -ne $script:S.pill) {
1913
+ $glow = $script:S.pill.Effect
1914
+ if ($glow -is [System.Windows.Media.Effects.DropShadowEffect]) {
1915
+ # Effect objects are frozen once assigned, so swap in a fresh one.
1916
+ $fresh = New-Object System.Windows.Media.Effects.DropShadowEffect
1917
+ $inverse = ($script:S.pillStyle -eq 'inverse')
1918
+ if ($inverse) {
1919
+ $fresh.Color = [System.Windows.Media.Color]::FromRgb(214, 220, 228)
1920
+ $fresh.Opacity = 0.30
1921
+ } else {
1922
+ $fresh.Color = [System.Windows.Media.Color]::FromRgb([byte]$ph.base[0], [byte]$ph.base[1], [byte]$ph.base[2])
1923
+ $fresh.Opacity = 0.40
1924
+ }
1925
+ $fresh.BlurRadius = 24
1926
+ $fresh.ShadowDepth = 0
1927
+ $script:S.pill.Effect = $fresh
1928
+ }
1929
+ }
1930
+ $script:S.appliedAlpha = $null
1931
+ }
1932
+
1933
+ function Render-Layout {
1934
+ $m = $script:S.monitorBounds
1935
+ if ($null -eq $m) { return $false }
1936
+ $sc = [double]$script:S.scale
1937
+ if ($sc -le 0) { $sc = 1.0 }
1938
+ $W = [double]$m.w / $sc
1939
+ $H = [double]$m.h / $sc
1940
+ $T = [double]$CFG.ringPx / $sc
1941
+ # A repeated `show` for the same look must not rebuild the visual tree: Clear-Canvas would
1942
+ # restart every animation, which read as one hard flash per tool action. Reuse the live tree and
1943
+ # only refresh text/position; the tail and the edge breath keep their phase.
1944
+ #
1945
+ # The phase is deliberately NOT part of the key. It used to be, so acting -> stopped rebuilt the
1946
+ # whole tree and replayed Start-PillIntro's 340 ms scale-and-fade on the way out: the person saw
1947
+ # the colour turn red AND the capsule pop in again, which is the "stopped flashes twice" report.
1948
+ # A phase change is a RECOLOUR, and Set-PhaseInPlace already does that in place.
1949
+ # The smoke flag IS part of the key: turning it on or off changes which children the tree has, so
1950
+ # it is a structural change and has to rebuild. It is a rare, deliberate act (a click on the plugin
1951
+ # page), not something that happens per action, so it does not reintroduce the per-action flash.
1952
+ $layoutKey = ([string]$script:S.pillStyle) + '|' + ([string]$script:S.lookVersion) + '|' + ([string]$script:S.mistOn) + '|' + ([string]$m.x) + ',' + ([string]$m.y) + ',' + ([string]$m.w) + ',' + ([string]$m.h) + '|' + ([string]([Math]::Round($sc, 3)))
1953
+ if ($script:S.built -and $null -ne $script:S.pill -and $script:S.layoutKey -eq $layoutKey) {
1954
+ Update-PillText
1955
+ Position-Pill
1956
+ return $true
1957
+ }
1958
+ $script:S.layoutKey = $layoutKey
1959
+ $script:S.dipW = $W
1960
+ $script:S.dipH = $H
1961
+ $script:S.ringDip = $T
1962
+ $ph = $script:PH[$script:S.phase]
1963
+ if ($null -eq $ph) { $ph = $script:PH['acting'] }
1964
+ Clear-Canvas
1965
+ $ring = Build-Ring $W $H $T $ph
1966
+ foreach ($b in $ring.bloom) { [void]$script:S.canvas.Children.Add($b) }
1967
+ foreach ($b in $ring.bars) { [void]$script:S.canvas.Children.Add($b) }
1968
+ $script:S.ring = $ring.bars.ToArray()
1969
+ $script:S.bloom = $ring.bloom.ToArray()
1970
+ $p = Build-Pill $ph
1971
+ [void]$script:S.canvas.Children.Add($p.border)
1972
+ $script:S.pill = $p.border
1973
+ $script:S.pillText = $p.text
1974
+ $script:S.pillSub = $p.sub
1975
+ $script:S.pillOrb = $p.orb
1976
+ $script:S.pillOrbScale = $p.orbScale
1977
+ $script:S.pillOrbHalo = $p.orbHalo
1978
+ $script:S.pillOrbHaloScale = $p.orbHaloScale
1979
+ $script:S.pillBars = @($p.bars)
1980
+ $script:S.pillScale = $p.scale
1981
+ $script:S.pillBrandRun = $p.brandRun
1982
+ $script:S.pillRestRun = $p.restRun
1983
+ $halo = Build-Halo $ph $sc
1984
+ foreach ($it in $halo.items) { [void]$script:S.canvas.Children.Add($it) }
1985
+ $script:S.halo = $halo
1986
+ $script:S.haloOn = $false
1987
+ Update-PillText
1988
+ Start-PillIntro
1989
+ Start-PillOrb ($script:S.phase -eq 'acting' -and $script:S.pillStyle -eq 'orb')
1990
+ Start-PillBars ($script:S.phase -eq 'acting' -and $script:S.pillStyle -eq 'wave')
1991
+ Position-Halo
1992
+ return $true
1993
+ }
1994
+
1995
+ function CurrentPillText {
1996
+ if (-not [string]::IsNullOrEmpty([string]$script:S.textOverride)) { return [string]$script:S.textOverride }
1997
+ $t = $script:PILL[$script:S.phase]
1998
+ if ($null -eq $t) { return '' }
1999
+ return [string]$t
2000
+ }
2001
+
2002
+ function Update-PillText {
2003
+ if ($null -eq $script:S.pillText) { return }
2004
+ # The visual is two runs with a gap, no separator dot: "DSH 正在操控电脑". The API string keeps the
2005
+ # middle dot so callers and probes still read one unambiguous sentence.
2006
+ $override = [string]$script:S.textOverride
2007
+ if ($override -ne '') {
2008
+ $script:S.pillBrandRun.Text = ''
2009
+ $script:S.pillRestRun.Text = $override
2010
+ } else {
2011
+ $script:S.pillBrandRun.Text = $script:TEXT.brand
2012
+ $word = if ($script:S.phase -eq 'acting') { $script:TEXT.acting } elseif ($script:S.phase -eq 'stopped') { $script:TEXT.stopped } else { '' }
2013
+ $script:S.pillRestRun.Text = if ($word -ne '') { ' ' + $word } else { '' }
2014
+ }
2015
+ $sub = [string]$script:S.subtext
2016
+ if ($sub.Length -gt 120) { $sub = $sub.Substring(0, 120) }
2017
+ $script:S.pillSub.Text = $sub
2018
+ # Single line is the product: progress lives in the plugin panel, not on the capsule. Every style
2019
+ # is 44 DIP, so a second line is not a per-style capability -- it exists only for an explicit
2020
+ # textOverride, which is how a caller puts a longer message on the capsule.
2021
+ $showSub = $sub.Length -gt 0 -and $script:S.textOverride -ne ''
2022
+ if ($showSub) { $script:S.pillSub.Visibility = [System.Windows.Visibility]::Visible }
2023
+ else { $script:S.pillSub.Visibility = [System.Windows.Visibility]::Collapsed }
2024
+ Position-Pill
2025
+ }
2026
+
2027
+ # Horizontally centred, pillTopPx physical pixels below the top of THAT monitor.
2028
+ function Position-Pill {
2029
+ if ($null -eq $script:S.pill -or $null -eq $script:S.canvas) { return }
2030
+ $inf = New-Object System.Windows.Size -ArgumentList ([double]::PositiveInfinity), ([double]::PositiveInfinity)
2031
+ $script:S.pill.Measure($inf)
2032
+ $dw = [double]$script:S.pill.DesiredSize.Width
2033
+ $dh = [double]$script:S.pill.DesiredSize.Height
2034
+ if ($dw -le 0 -or [double]::IsNaN($dw)) { return }
2035
+ $sc = [double]$script:S.scale
2036
+ if ($sc -le 0) { $sc = 1.0 }
2037
+ $topDip = [double]$CFG.pillTopPx / $sc
2038
+ $leftDip = (([double]$script:S.dipW - $dw) / 2.0)
2039
+ if ($leftDip -lt 0) { $leftDip = 0.0 }
2040
+ [System.Windows.Controls.Canvas]::SetLeft($script:S.pill, [Math]::Round($leftDip, 2))
2041
+ [System.Windows.Controls.Canvas]::SetTop($script:S.pill, [Math]::Round($topDip, 2))
2042
+ $script:S.pillDipX = [Math]::Round($leftDip, 2)
2043
+ $script:S.pillDipY = [Math]::Round($topDip, 2)
2044
+ $script:S.pillDipW = [Math]::Round($dw, 2)
2045
+ $mb = $script:S.monitorBounds
2046
+ if ($null -ne $mb) {
2047
+ $script:S.pillX = [int]([double]$mb.x + $leftDip * $sc)
2048
+ $script:S.pillY = [int]([double]$mb.y + $topDip * $sc)
2049
+ $script:S.pillW = [int][Math]::Ceiling($dw * $sc)
2050
+ $script:S.pillH = [int][Math]::Ceiling($dh * $sc)
2051
+ }
2052
+ }
2053
+
2054
+ # ---------------------------------------------------------------- extended styles
2055
+ $EX_NEEDED = 0x00000020 -bor 0x00080000 -bor 0x00000080 -bor 0x08000000 # TRANSPARENT|LAYERED|TOOLWINDOW|NOACTIVATE
2056
+
2057
+ function Apply-ExStyles([IntPtr]$h) {
2058
+ if (-not $script:nativeLoaded) { return [int64]0 }
2059
+ if ($h -eq [IntPtr]::Zero) { return [int64]0 }
2060
+ try {
2061
+ $cur = [int64]([IndNative]::GetExStyle($h)) -band 0xFFFFFFFFL
2062
+ $want = ($cur -bor [int64]$EX_NEEDED -bor [int64]0x8) -band 0xFFFFFFFFL # TOPMOST is what we asked for too
2063
+ [void][IndNative]::SetExStyle($h, [int]$want)
2064
+ [void][IndNative]::ForceFrame($h)
2065
+ $final = [int64]([IndNative]::GetExStyle($h)) -band 0xFFFFFFFFL
2066
+ $script:S.exStyles = $final
2067
+ $missing = @()
2068
+ foreach ($bit in @(0x20L, 0x80000L, 0x80L, 0x8000000L)) {
2069
+ if (([int64]$final -band $bit) -ne $bit) { $missing += (ExHex $bit) }
2070
+ }
2071
+ if ($missing.Count -gt 0) {
2072
+ Log ('exStyles still missing ' + ([string]::Join(',', $missing)) + ' -- retrying')
2073
+ [void][IndNative]::SetExStyle($h, [int]$want)
2074
+ [void][IndNative]::ForceFrame($h)
2075
+ $final = [int64]([IndNative]::GetExStyle($h)) -band 0xFFFFFFFFL
2076
+ $script:S.exStyles = $final
2077
+ }
2078
+ return $final
2079
+ } catch {
2080
+ Log ('Apply-ExStyles threw: ' + $_.Exception.Message)
2081
+ return [int64]0
2082
+ }
2083
+ }
2084
+
2085
+ # ---------------------------------------------------------------- window lifecycle
2086
+ # WPF can hand out a different HWND between SourceInitialized and the end of the first Show (it
2087
+ # recreates the source when AllowsTransparency is involved), and styles applied to a discarded HWND
2088
+ # do nothing at all. So the live handle is re-read before every command and the extended styles are
2089
+ # re-applied whenever the handle moved or a bit went missing.
2090
+ function Sync-Hwnd {
2091
+ if ($null -eq $script:S.win) { return [IntPtr]::Zero }
2092
+ try {
2093
+ $helper = New-Object System.Windows.Interop.WindowInteropHelper -ArgumentList $script:S.win
2094
+ $h = $helper.Handle
2095
+ if ($h -eq [IntPtr]::Zero) { return [IntPtr]::Zero }
2096
+ $cur = [Int64]$h
2097
+ if ($cur -ne [Int64]$script:S.hwnd) {
2098
+ Log ('hwnd changed ' + [Int64]$script:S.hwnd + ' -> ' + $cur + ' (applying styles to the live handle)')
2099
+ $script:S.hwndChanges += 1
2100
+ if ([Int64]$script:S.hwnd -ne 0) { $script:S.hwndSeen += @([Int64]$script:S.hwnd) }
2101
+ $script:S.hwndSeen += @($cur)
2102
+ $script:S.hwnd = $cur
2103
+ $script:S.exStyles = 0
2104
+ Apply-ExStyles $h | Out-Null
2105
+ } else {
2106
+ # keep the bits honest: a stray SetWindowLong from WPF layout would be repaired here
2107
+ $live = [int64]([IndNative]::GetExStyle($h)) -band 0xFFFFFFFFL
2108
+ if (([int64]$live -band [int64]$EX_NEEDED) -ne [int64]$EX_NEEDED) {
2109
+ Log ('exStyles drifted to ' + (ExHex $live) + ' -- re-applying')
2110
+ Apply-ExStyles $h | Out-Null
2111
+ } else {
2112
+ $script:S.exStyles = $live
2113
+ }
2114
+ }
2115
+ return $h
2116
+ } catch {
2117
+ Log ('Sync-Hwnd threw: ' + $_.Exception.Message)
2118
+ return [IntPtr]::Zero
2119
+ }
2120
+ }
2121
+
2122
+ function Ensure-Window {
2123
+ if ($null -ne $script:S.win) { return $script:S.win }
2124
+ if ($script:S.chosenFont -eq '') { Choose-Font | Out-Null }
2125
+ $win = New-Object System.Windows.Window
2126
+ $win.Title = $script:TITLE
2127
+ $win.WindowStyle = [System.Windows.WindowStyle]::None
2128
+ $win.AllowsTransparency = $true
2129
+ $win.Background = (New-Object System.Windows.Media.SolidColorBrush -ArgumentList ([System.Windows.Media.Color]::FromArgb(0, 0, 0, 0)))
2130
+ $win.ResizeMode = [System.Windows.ResizeMode]::NoResize
2131
+ $win.ShowInTaskbar = $false
2132
+ $win.ShowActivated = $false
2133
+ $win.Topmost = $true
2134
+ $win.WindowState = [System.Windows.WindowState]::Normal
2135
+ $win.Focusable = $false
2136
+ $win.SizeToContent = [System.Windows.SizeToContent]::Manual
2137
+ $win.SnapsToDevicePixels = $true
2138
+ $win.UseLayoutRounding = $true
2139
+ $win.IsHitTestVisible = $false
2140
+ $canvas = New-Object System.Windows.Controls.Canvas
2141
+ $canvas.Background = (New-Object System.Windows.Media.SolidColorBrush -ArgumentList ([System.Windows.Media.Color]::FromArgb(0, 0, 0, 0)))
2142
+ $canvas.IsHitTestVisible = $false
2143
+ $win.Content = $canvas
2144
+ $script:S.canvas = $canvas
2145
+ $script:S.win = $win
2146
+ $script:S.built = $true
2147
+ # extended styles the moment the HWND exists, before the surface is first painted
2148
+ $win.Add_SourceInitialized({
2149
+ try {
2150
+ $helper = New-Object System.Windows.Interop.WindowInteropHelper -ArgumentList $script:S.win
2151
+ $h = $helper.Handle
2152
+ if ($h -ne [IntPtr]::Zero) {
2153
+ $script:S.hwnd = [Int64]$h
2154
+ $script:S.hwndCreateCount += 1
2155
+ Apply-ExStyles $h | Out-Null
2156
+ Log ('hwnd ' + [Int64]$script:S.hwnd + ' created, exStyles ' + (ExHex $script:S.exStyles))
2157
+ }
2158
+ } catch { Log ('SourceInitialized failed: ' + $_.Exception.Message) }
2159
+ })
2160
+ return $win
2161
+ }
2162
+
2163
+ function Move-To-Monitor($m) {
2164
+ $sc = [double]$script:S.scale
2165
+ if ($sc -le 0) { $sc = 1.0 }
2166
+ $win = $script:S.win
2167
+ # WPF measures Left/Top/Width/Height in DIPs while the pipe speaks physical pixels.
2168
+ $win.Width = [double]$m.bounds.w / $sc
2169
+ $win.Height = [double]$m.bounds.h / $sc
2170
+ $win.Left = [double]$m.bounds.x / $sc
2171
+ $win.Top = [double]$m.bounds.y / $sc
2172
+ }
2173
+
2174
+ # The window must land on the monitor to the pixel, so the scale is never trusted from one API:
2175
+ # set the size, read the real GetWindowRect back, and re-derive the DIP->pixel factor from what the
2176
+ # HWND actually did. Two passes converge; state reports the residual delta so a bad fit is visible.
2177
+ function Fit-To-Monitor($m, [int]$maxPasses) {
2178
+ $win = $script:S.win
2179
+ if ($null -eq $win -or $null -eq $m) { return }
2180
+ $target = $m.bounds
2181
+ for ($pass = 1; $pass -le $maxPasses; $pass++) {
2182
+ try { $win.UpdateLayout() } catch { }
2183
+ $r = Get-WindowRect
2184
+ if ($null -eq $r) { return }
2185
+ $script:S.fitPasses = $pass
2186
+ $script:S.fitRect = $r
2187
+ $dw = [int]$target.w - [int]$r.w
2188
+ $dh = [int]$target.h - [int]$r.h
2189
+ $dx = [int]$target.x - [int]$r.x
2190
+ $dy = [int]$target.y - [int]$r.y
2191
+ $script:S.fitDelta = [ordered]@{ w = $dw; h = $dh; x = $dx; y = $dy }
2192
+ if ([Math]::Abs($dw) -le 1 -and [Math]::Abs($dh) -le 1 -and [Math]::Abs($dx) -le 1 -and [Math]::Abs($dy) -le 1) {
2193
+ $script:S.fitConverged = $true
2194
+ return
2195
+ }
2196
+ $script:S.fitConverged = $false
2197
+ # re-derive the factor from the observed geometry, then correct
2198
+ $sc = [double]$script:S.scale
2199
+ if ([double]$win.Width -gt 1) {
2200
+ $obs = [double]$r.w / [double]$win.Width
2201
+ if ($obs -gt 0.05 -and [Math]::Abs($obs - $sc) / $sc -gt 0.002) {
2202
+ $script:S.scale = $obs
2203
+ $sc = $obs
2204
+ Render-Layout | Out-Null # ring / pill geometry is in DIPs, so rebuild it
2205
+ }
2206
+ }
2207
+ Move-To-Monitor $m
2208
+ }
2209
+ }
2210
+
2211
+ function Show-Overlay($m) {
2212
+ $win = Ensure-Window
2213
+ $script:S.monitorBounds = $m.bounds
2214
+ $script:S.monitorIndex = [int]$m.index
2215
+ $script:S.dpi = [int]$m.dpi
2216
+ # WPF's own device scale wins over the DPI APIs (measured: TransformToDevice is the number the
2217
+ # layout really uses); fall back to dpi/96 only before the first layout pass exists.
2218
+ $ds = (Get-DeviceScale)
2219
+ if ($ds -gt 0) { $script:S.scale = $ds } else { $script:S.scale = ([double]$m.dpi / 96.0) }
2220
+ Render-Layout | Out-Null
2221
+ Move-To-Monitor $m
2222
+ if (-not $script:S.visible) {
2223
+ $win.Show() # ShowActivated=false, so this never takes the foreground
2224
+ $script:S.visible = $true
2225
+ }
2226
+ Sync-Hwnd | Out-Null
2227
+ Fit-To-Monitor $m 3
2228
+ Sync-Hwnd | Out-Null
2229
+ Update-Pulse ([Diagnostics.Stopwatch]::GetTimestamp()) | Out-Null
2230
+ Start-HaloLoop
2231
+ return [IntPtr]$script:S.hwnd
2232
+ }
2233
+
2234
+ function Hide-Overlay([string]$why) {
2235
+ if ($null -eq $script:S.win) {
2236
+ $script:S.visible = $false
2237
+ $script:S.phase = 'hidden'
2238
+ Stop-RenderLoop
2239
+ Stop-HaloLoop
2240
+ return
2241
+ }
2242
+ try { $script:S.win.Hide() } catch { Log ('hide threw: ' + $_.Exception.Message) }
2243
+ $script:S.visible = $false
2244
+ $script:S.hideCount += 1
2245
+ $script:S.phase = 'hidden'
2246
+ Stop-RenderLoop
2247
+ Stop-HaloLoop
2248
+ Log ('overlay hidden (' + $why + ')')
2249
+ }
2250
+
2251
+ # ---------------------------------------------------------------- render loop / pulse
2252
+ # Only ever called when DSH_INDICATOR_RENDER_HOOK=1. renderCallbacks counts real composition frames;
2253
+ # framesRendered counts pulse updates pushed, from timer or render event whichever is driving.
2254
+ function On-Frame {
2255
+ $script:S.renderCallbacks += 1
2256
+ Pump-Inbox
2257
+ Tick-Pulse
2258
+ }
2259
+
2260
+ function Start-RenderLoop {
2261
+ if ($script:S.renderOn) { return }
2262
+ # The pulse is driven by a dispatcher timer. That is the loop: every tick pushes new values into
2263
+ # the visual tree, which is what makes WPF composite a new frame.
2264
+ if ($null -eq $script:pulseTimer) {
2265
+ $t = New-Object System.Windows.Threading.DispatcherTimer
2266
+ $t.Interval = [TimeSpan]::FromMilliseconds([double]$CFG.renderMs)
2267
+ $t.Add_Tick({ Pump-Inbox; Tick-Pulse })
2268
+ $t.Start()
2269
+ $script:pulseTimer = $t
2270
+ $script:S.timers += $t
2271
+ }
2272
+ # Subscribing to WPF's render event is only an OBSERVER, and an expensive one: measured on this
2273
+ # box it kept a 2560x1600 layered surface compositing at ~55 Hz even while only 4 updates a
2274
+ # second were pushed (14 pushes -> 189 callbacks in 3.4 s). Off by default, on for diagnostics.
2275
+ $hooked = $false
2276
+ if ($script:renderLoaded -and [int]$CFG.renderHook -eq 1) {
2277
+ try {
2278
+ [IndWpf]::StartRendering([System.Action]{ On-Frame })
2279
+ $hooked = [bool][IndWpf]::RenderingOn
2280
+ } catch {
2281
+ Log ('render subscription failed: ' + $_.Exception.Message)
2282
+ }
2283
+ }
2284
+ $script:S.renderHookOn = $hooked
2285
+ $script:S.renderDriver = if ($hooked) { 'dispatcher-timer+composition-render-event' } else { 'dispatcher-timer' }
2286
+ $script:S.renderOn = $true
2287
+ }
2288
+
2289
+ function Stop-RenderLoop {
2290
+ if ($script:renderLoaded) { try { [IndWpf]::StopRendering() } catch { } }
2291
+ if ($null -ne $script:pulseTimer) { try { $script:pulseTimer.Stop() } catch { } }
2292
+ $script:S.renderOn = $false
2293
+ $script:S.renderHookOn = $false
2294
+ }
2295
+
2296
+ $script:pulseTimer = $null
2297
+ $script:haloTimer = $null
2298
+
2299
+ # The halo is decoupled from the 100 ms pulse: a dedicated ~16 ms loop repositions it with
2300
+ # GetCursorPos, so it tracks the pointer without the one-beat lag a shared pulse tick would cause.
2301
+ function Start-HaloLoop {
2302
+ if ($null -ne $script:haloTimer) { return }
2303
+ $t = New-Object System.Windows.Threading.DispatcherTimer
2304
+ $t.Interval = [TimeSpan]::FromMilliseconds(10)
2305
+ $t.Add_Tick({ Position-Halo })
2306
+ $t.Start()
2307
+ $script:haloTimer = $t
2308
+ }
2309
+ function Stop-HaloLoop {
2310
+ if ($null -ne $script:haloTimer) { try { $script:haloTimer.Stop() } catch { } ; $script:haloTimer = $null }
2311
+ }
2312
+
2313
+ function Update-Pulse([Int64]$now) {
2314
+ $ph = $script:PH[$script:S.phase]
2315
+ $script:S.lastPulseMsWall = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
2316
+ if ($null -eq $ph) { return $false }
2317
+ $period = [double]$ph.periodMs
2318
+ if ($period -le 0) { $period = 2400.0 }
2319
+ $elapsed = [double](($now - $script:S.phaseStartTick) / 10000.0)
2320
+ $frac = ($elapsed % $period) / $period
2321
+ # Smoothstep instead of raw cosine: the breath eases in and out at both ends, so the edge light
2322
+ # settles for a beat instead of reversing abruptly. Phase is preserved across repeated `show`s,
2323
+ # so a tool action never restarts the breath.
2324
+ $wave = 0.5 - 0.5 * [Math]::Cos($frac * 2.0 * [Math]::PI)
2325
+ $wave = $wave * $wave * (3.0 - 2.0 * $wave)
2326
+ $alpha = [double]$ph.lo + ([double]$ph.hi - [double]$ph.lo) * $wave
2327
+ if ($alpha -lt 0.0) { $alpha = 0.0 } elseif ($alpha -gt 1.0) { $alpha = 1.0 }
2328
+ # Phase changes reset phaseStartTick, which snaps the fresh phase's alpha to its `lo` — the
2329
+ # running ring could be at 1.0 the instant before, so the switch to stopped DIMMED the whole edge
2330
+ # 28% in one frame and then the red climbed back: the "running dies, then stopped appears"
2331
+ # disconnect. This slew limiter moves alpha toward the freshly computed target at a bounded rate
2332
+ # (full 0..1 sweep in ~150 ms at a 33 ms tick) instead of jumping, so the colour AND the breath
2333
+ # level both glide across the phase boundary. Steady-state breathing is untouched: the target
2334
+ # moves slowly enough that the limiter never clips it.
2335
+ if ($script:S.appliedAlpha -ne $null) {
2336
+ $prev = [double]$script:S.appliedAlpha
2337
+ $step = 0.22
2338
+ if ($alpha -gt $prev + $step) { $alpha = $prev + $step }
2339
+ elseif ($alpha -lt $prev - $step) { $alpha = $prev - $step }
2340
+ }
2341
+ $script:S.appliedAlpha = $alpha
2342
+ $script:S.pulseOffset = $frac
2343
+ $script:S.pulseAlpha = [Math]::Round($alpha, 4)
2344
+ foreach ($b in $script:S.ring) { if ($null -ne $b) { $b.Opacity = $alpha } }
2345
+ $bloomAlpha = $alpha * 0.72
2346
+ foreach ($b in $script:S.bloom) { if ($null -ne $b) { $b.Opacity = $bloomAlpha } }
2347
+ foreach ($bar in @($script:S.pillBars)) {
2348
+ if ($null -ne $bar) { $bar.Opacity = 0.62 + 0.38 * $wave }
2349
+ }
2350
+ return $true
2351
+ }
2352
+
2353
+ # One pulse tick, from whatever source raised it. framesRendered counts ticks where a visual update
2354
+ # was actually pushed; renderCallbacks counts composition frames WPF presented.
2355
+ function Tick-Pulse {
2356
+ if ($script:S.closing -or -not $script:S.visible) { return }
2357
+ $now = [Diagnostics.Stopwatch]::GetTimestamp()
2358
+ $sinceMs = [double]$CFG.renderMs + 1
2359
+ if ($script:S.lastPulseStamp -ne 0) { $sinceMs = ($now - $script:S.lastPulseStamp) / 10000.0 }
2360
+ if ($sinceMs -lt [double]$CFG.renderMs) { return }
2361
+ $script:S.lastPulseStamp = $now
2362
+ $script:S.framesRendered += 1
2363
+ if (Update-Pulse $now) { $script:S.visualUpdates += 1 }
2364
+ Position-Halo
2365
+ }
2366
+
2367
+ # ---------------------------------------------------------------- timers
2368
+ # NOTE: this .NET Framework build's DispatcherTimer exposes only Dispatcher/IsEnabled/Interval/Tag
2369
+ # (measured) -- there is no Priority setter, so stdin latency is covered by draining the inbox in
2370
+ # every render frame as well as on this timer.
2371
+ function New-ServerTimer([double]$ms, $body) {
2372
+ $t = New-Object System.Windows.Threading.DispatcherTimer
2373
+ $t.Interval = [TimeSpan]::FromMilliseconds($ms)
2374
+ $t.Add_Tick($body)
2375
+ $t.Start()
2376
+ $script:S.timers += $t
2377
+ return $t
2378
+ }
2379
+
2380
+ # ---------------------------------------------------------------- phase
2381
+ $script:stoppedTimer = $null
2382
+ function Schedule-StoppedHide {
2383
+ if ($null -ne $script:stoppedTimer) { try { $script:stoppedTimer.Stop() } catch { } }
2384
+ $t = New-Object System.Windows.Threading.DispatcherTimer
2385
+ $t.Interval = [TimeSpan]::FromMilliseconds([double]$CFG.stoppedMs)
2386
+ $t.Add_Tick({
2387
+ try { $t.Stop() } catch { }
2388
+ if ($script:S.phase -eq 'stopped') { Hide-Overlay 'stopped auto-hide' }
2389
+ })
2390
+ $t.Start()
2391
+ $script:stoppedTimer = $t
2392
+ }
2393
+
2394
+ function Set-PhaseInPlace([string]$phase) {
2395
+ if (-not $script:PH.ContainsKey($phase)) { Err 'bad_phase' ('unknown phase ' + (OneLine $phase)) }
2396
+ $changed = ([string]$script:S.phase -ne [string]$phase)
2397
+ $script:S.phase = $phase
2398
+ if ($changed -or -not $script:S.visible) { $script:S.phaseStartTick = [Diagnostics.Stopwatch]::GetTimestamp() }
2399
+ # A phase change is a RECOLOUR, not a rebuild. Calling Render-Layout here cleared the canvas and
2400
+ # replayed the intro animation, so the stopped state both turned red and popped in again.
2401
+ if ($changed -and $script:S.built) { Update-PhaseLook }
2402
+ Update-PillText
2403
+ $script:S.appliedAlpha = $null
2404
+ Update-Pulse ([Diagnostics.Stopwatch]::GetTimestamp()) | Out-Null
2405
+ }
2406
+
2407
+ # ---------------------------------------------------------------- commands
2408
+ function Screen-Json($m) {
2409
+ return [ordered]@{
2410
+ index = [int]$m.index
2411
+ device = [string]$m.device
2412
+ bounds = $m.bounds
2413
+ work = $m.work
2414
+ primary = [bool]$m.primary
2415
+ dpi = [int]$m.dpi
2416
+ }
2417
+ }
2418
+
2419
+ function Cmd-Ping($A) {
2420
+ $screens = Refresh-Screens
2421
+ $list = New-Object System.Collections.Generic.List[object]
2422
+ foreach ($m in $screens) { [void]$list.Add((Screen-Json $m)) }
2423
+ $u = [System.Windows.Forms.SystemInformation]::VirtualScreen
2424
+ $physW = 0; $physH = 0
2425
+ if ($script:nativeLoaded) { $physW = [IndNative]::PhysWidth; $physH = [IndNative]::PhysHeight }
2426
+ return [ordered]@{
2427
+ psVersion = $PSVersionTable.PSVersion.ToString()
2428
+ workerPid = [int]$PID
2429
+ apartment = [string]([Threading.Thread]::CurrentThread.GetApartmentState())
2430
+ dpiAware = [int]$script:dpiMode
2431
+ screenCount = ([array]$screens).Count
2432
+ screens = $list.ToArray()
2433
+ virtualScreen = [ordered]@{ x = [int]$u.X; y = [int]$u.Y; w = [int]$u.Width; h = [int]$u.Height }
2434
+ systemMetrics = [ordered]@{ w = [int]$physW; h = [int]$physH }
2435
+ ringPx = [int]$CFG.ringPx
2436
+ 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 }
2437
+ startupMs = (NowMs)
2438
+ loadMs = [double]$script:loadMs
2439
+ nativeLoaded = [bool]$script:nativeLoaded
2440
+ wpfHelper = [bool]$script:renderLoaded
2441
+ chosenFont = [string]$script:S.chosenFont
2442
+ phases = @('acting', 'stopped', 'hidden')
2443
+ }
2444
+ }
2445
+
2446
+ function Rect-From-Args($A) {
2447
+ $b = ArgOf $A 'bounds'
2448
+ if ($null -eq $b) { return $null }
2449
+ $d = Dict $b
2450
+ if (-not ($d -is [System.Collections.IDictionary])) { Err 'bad_args' 'bounds must be an object {x,y,w,h}' }
2451
+ $x = IntArg $d 'x' 0
2452
+ $y = IntArg $d 'y' 0
2453
+ $w = IntArg $d 'w' 0
2454
+ $h = IntArg $d 'h' 0
2455
+ if ($w -le 0 -or $h -le 0) { Err 'bad_args' ('bounds needs positive w/h, got w=' + $w + ' h=' + $h) }
2456
+ return [ordered]@{ x = $x; y = $y; w = $w; h = $h }
2457
+ }
2458
+
2459
+ function Get-Fg {
2460
+ if (-not $script:nativeLoaded) { return [Int64]0 }
2461
+ return [Int64]([IndNative]::GetForegroundWindow())
2462
+ }
2463
+
2464
+ function Cmd-Show($A) {
2465
+ $t0 = [Diagnostics.Stopwatch]::GetTimestamp()
2466
+ $rect = Rect-From-Args $A
2467
+ if ($null -eq $rect) {
2468
+ $prim = [System.Windows.Forms.Screen]::PrimaryScreen
2469
+ if ($null -eq $prim) { Err 'no_screen' 'no primary screen and no bounds given' }
2470
+ $b = $prim.Bounds
2471
+ $rect = [ordered]@{ x = [int]$b.X; y = [int]$b.Y; w = [int]$b.Width; h = [int]$b.Height }
2472
+ }
2473
+ $script:S.idleHideMs = IntArg $A 'idleHideMs' ([int]$CFG.idleMs)
2474
+ $phase = (StrArg $A 'phase' 'acting')
2475
+ if (-not $script:PH.ContainsKey($phase)) { Err 'bad_phase' ('unknown phase ' + (OneLine $phase)) }
2476
+ $pick = Pick-Monitor $rect
2477
+ $m = $pick.monitor
2478
+ if ($null -eq $m) { Err 'no_screen' 'monitor pick returned nothing' }
2479
+ $script:S.textOverride = (StrArg $A 'text' '')
2480
+ $script:S.subtext = (StrArg $A 'subtext' '')
2481
+ # The delivery mode decides whether the cursor halo may be drawn: only when 御屏 actually drives
2482
+ # the physical pointer (foreground, or auto which may fall back to it). In background the pointer
2483
+ # stays the user's own, so a halo there would follow their hand and misreport the action.
2484
+ $script:S.mode = (StrArg $A 'mode' 'background')
2485
+ if ($null -ne $script:stoppedTimer) { try { $script:stoppedTimer.Stop() } catch { } }
2486
+ $fgBefore = (Get-Fg)
2487
+ $hwndBefore = [Int64]$script:S.hwnd
2488
+ $prevPhase = [string]$script:S.phase
2489
+ $phaseChanged = ($phase -ne $prevPhase) -or (-not $script:S.visible)
2490
+ $script:S.phase = $phase
2491
+ if ($phaseChanged) { $script:S.phaseStartTick = [Diagnostics.Stopwatch]::GetTimestamp() }
2492
+ Show-Overlay $m | Out-Null
2493
+ if ($phase -eq 'stopped') { Schedule-StoppedHide }
2494
+ if ($phase -eq 'hidden') { Hide-Overlay 'show asked for phase hidden' }
2495
+ Start-RenderLoop
2496
+ Sync-Hwnd | Out-Null
2497
+ $script:S.showCount += 1
2498
+ $script:S.straddle = [bool]$pick.straddle
2499
+ $fgAfter = (Get-Fg)
2500
+ return [ordered]@{
2501
+ visible = [bool]$script:S.visible
2502
+ hwnd = [Int64]$script:S.hwnd
2503
+ monitor = [ordered]@{ index = [int]$m.index; bounds = $m.bounds; dpi = [int]$m.dpi; device = [string]$m.device }
2504
+ monitorPicked = [int]$m.index
2505
+ pickReason = [string]$pick.reason
2506
+ straddle = [bool]$pick.straddle
2507
+ monitorsTouched = [int]$pick.monitorsTouched
2508
+ requestedBounds = $rect
2509
+ windowRect = (Get-WindowRect)
2510
+ topmost = (Ex-Has $script:S.exStyles 0x8)
2511
+ activateAttempted = $false
2512
+ foregroundBefore = $fgBefore
2513
+ foregroundAfter = $fgAfter
2514
+ foregroundMoved = ($fgBefore -ne $fgAfter)
2515
+ reusedHwnd = ($hwndBefore -ne 0 -and $hwndBefore -eq [Int64]$script:S.hwnd)
2516
+ phase = [string]$script:S.phase
2517
+ prevPhase = $prevPhase
2518
+ style = [string]$script:S.pillStyle
2519
+ text = (CurrentPillText)
2520
+ dpi = [int]$script:S.dpi
2521
+ scale = [Math]::Round([double]$script:S.scale, 4)
2522
+ ringDip = [Math]::Round([double]$script:S.ringDip, 2)
2523
+ deviceScale = [Math]::Round((Get-DeviceScale), 4)
2524
+ fitPasses = [int]$script:S.fitPasses
2525
+ fitConverged = [bool]$script:S.fitConverged
2526
+ fitDelta = $script:S.fitDelta
2527
+ hwndChanges = [Int64]$script:S.hwndChanges
2528
+ pillRect = (Get-PillRect)
2529
+ idleHideMs = [int]$script:S.idleHideMs
2530
+ hwndCreateCount = [Int64]$script:S.hwndCreateCount
2531
+ # Same counter beat/phase report: without it here, "did this show rebuild the tree?" is
2532
+ # unanswerable and a flash regression on the first command would be invisible.
2533
+ layoutBuilds = [Int64]$script:S.layoutBuilds
2534
+ ms = (Elapsed $t0)
2535
+ }
2536
+ }
2537
+
2538
+ function Cmd-Beat($A) {
2539
+ $t0 = [Diagnostics.Stopwatch]::GetTimestamp()
2540
+ Sync-Hwnd | Out-Null
2541
+ $hwndBefore = [Int64]$script:S.hwnd
2542
+ if (-not $script:S.built -or $null -eq $script:S.monitorBounds) {
2543
+ # nothing to re-assert yet: paint on the primary so a heartbeat can always be seen
2544
+ $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
2545
+ $rect = [ordered]@{ x = [int]$b.X; y = [int]$b.Y; w = [int]$b.Width; h = [int]$b.Height }
2546
+ $pick = Pick-Monitor $rect
2547
+ Show-Overlay $pick.monitor | Out-Null
2548
+ Start-RenderLoop
2549
+ }
2550
+ $tx = ArgOf $A 'text'
2551
+ if ($null -ne $tx) { $script:S.textOverride = [string]$tx }
2552
+ $sb = ArgOf $A 'subtext'
2553
+ if ($null -ne $sb) { $script:S.subtext = [string]$sb }
2554
+ $md = ArgOf $A 'mode'
2555
+ if ($null -ne $md) { $script:S.mode = [string]$md }
2556
+ if ($null -ne $script:stoppedTimer) { try { $script:stoppedTimer.Stop() } catch { } }
2557
+ # A beat has to leave the capsule genuinely ON SCREEN, not merely "text updated".
2558
+ #
2559
+ # The bug this fixes: Show-Overlay sets $script:S.visible = $true but leaves the phase at
2560
+ # 'hidden', so the old `elseif (-not $script:S.visible)` never ran, the window was never Show()n,
2561
+ # and the text was written into an invisible tree. Any caller that sends a bare `beat` to a
2562
+ # process which has never shown anything hits this: the message is composed and never drawn.
2563
+ if ($script:S.phase -eq 'stopped') {
2564
+ Set-PhaseInPlace 'acting'
2565
+ } else {
2566
+ # Covers both "never shown" (phase hidden) and "hidden after an auto-hide".
2567
+ if (-not $script:S.visible -or $script:S.phase -eq 'hidden') {
2568
+ if (-not $script:S.visible) {
2569
+ try { $script:S.win.Show() } catch { }
2570
+ $script:S.visible = $true
2571
+ }
2572
+ Set-PhaseInPlace 'acting'
2573
+ Start-RenderLoop
2574
+ }
2575
+ Update-PillText
2576
+ }
2577
+ $script:S.stats.beats += 1
2578
+ return [ordered]@{
2579
+ visible = [bool]$script:S.visible
2580
+ hwnd = [Int64]$script:S.hwnd
2581
+ reusedHwnd = ($hwndBefore -ne 0 -and $hwndBefore -eq [Int64]$script:S.hwnd)
2582
+ hwndCreateCount = [Int64]$script:S.hwndCreateCount
2583
+ phase = [string]$script:S.phase
2584
+ text = (CurrentPillText)
2585
+ subtext = [string]$script:S.subtext
2586
+ framesRendered = [Int64]$script:S.framesRendered
2587
+ # The intro replay is a rebuild, so this is the number that answers "does it flash per action".
2588
+ layoutBuilds = [Int64]$script:S.layoutBuilds
2589
+ ms = (Elapsed $t0)
2590
+ }
2591
+ }
2592
+
2593
+ function Cmd-Phase($A) {
2594
+ $t0 = [Diagnostics.Stopwatch]::GetTimestamp()
2595
+ Sync-Hwnd | Out-Null
2596
+ $phase = (StrArg $A 'phase' '')
2597
+ if ([string]::IsNullOrEmpty($phase)) { Err 'bad_args' 'phase requires a phase name' }
2598
+ if (-not $script:PH.ContainsKey($phase)) { Err 'bad_phase' ('unknown phase ' + (OneLine $phase)) }
2599
+ if ($null -ne (ArgOf $A 'text')) { $script:S.textOverride = [string](ArgOf $A 'text') }
2600
+ else { $script:S.textOverride = '' } # a phase change shows the phase's own wording
2601
+ $sb = ArgOf $A 'subtext'
2602
+ if ($null -ne $sb) { $script:S.subtext = [string]$sb }
2603
+ $hwndBefore = [Int64]$script:S.hwnd
2604
+ $wasVisible = [bool]$script:S.visible
2605
+ $autoHide = $null
2606
+ if ($phase -eq 'stopped') { $autoHide = [int]$CFG.stoppedMs }
2607
+ if ($phase -eq 'hidden') {
2608
+ Hide-Overlay 'phase hidden'
2609
+ } else {
2610
+ if ($null -eq $script:S.monitorBounds) {
2611
+ # never shown in this process: the primary monitor is the only sane default
2612
+ $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
2613
+ $rect = [ordered]@{ x = [int]$b.X; y = [int]$b.Y; w = [int]$b.Width; h = [int]$b.Height }
2614
+ $pick = Pick-Monitor $rect
2615
+ Show-Overlay $pick.monitor | Out-Null
2616
+ } elseif (-not $wasVisible) {
2617
+ $mm = [ordered]@{ index = [int]$script:S.monitorIndex; bounds = $script:S.monitorBounds; dpi = [int]$script:S.dpi }
2618
+ Show-Overlay $mm | Out-Null
2619
+ }
2620
+ Set-PhaseInPlace $phase
2621
+ if ($phase -eq 'stopped') { Schedule-StoppedHide }
2622
+ Start-RenderLoop
2623
+ }
2624
+ return [ordered]@{
2625
+ visible = [bool]$script:S.visible
2626
+ hwnd = [Int64]$script:S.hwnd
2627
+ reusedHwnd = ($hwndBefore -ne 0 -and $hwndBefore -eq [Int64]$script:S.hwnd)
2628
+ hwndCreateCount = [Int64]$script:S.hwndCreateCount
2629
+ phase = [string]$script:S.phase
2630
+ text = (CurrentPillText)
2631
+ periodMs = [int]$script:PH[$script:S.phase].periodMs
2632
+ autoHideAfterMs = $autoHide
2633
+ ms = (Elapsed $t0)
2634
+ }
2635
+ }
2636
+
2637
+ function Test-HwndAlive {
2638
+ if ($script:S.hwnd -eq 0) { return $false }
2639
+ if (-not $script:nativeLoaded) { return $true }
2640
+ try { return [bool][IndNative]::IsWindow([IntPtr]$script:S.hwnd) } catch { return $false }
2641
+ }
2642
+
2643
+ function Get-WindowRect {
2644
+ if ($script:S.hwnd -eq 0) { return $null }
2645
+ if (-not $script:nativeLoaded) { return $null }
2646
+ try {
2647
+ $r = New-Object 'IndNative+RECT'
2648
+ if ([IndNative]::GetWindowRect([IntPtr]$script:S.hwnd, [ref]$r)) {
2649
+ return [ordered]@{ x = [int]$r.Left; y = [int]$r.Top; w = [int]($r.Right - $r.Left); h = [int]($r.Bottom - $r.Top) }
2650
+ }
2651
+ } catch { }
2652
+ return $null
2653
+ }
2654
+
2655
+ function Get-PillRect {
2656
+ return [ordered]@{
2657
+ x = [int]$script:S.pillX
2658
+ y = [int]$script:S.pillY
2659
+ w = [int]$script:S.pillW
2660
+ h = [int]$script:S.pillH
2661
+ dipX = [double]$script:S.pillDipX
2662
+ dipY = [double]$script:S.pillDipY
2663
+ dipW = [double]$script:S.pillDipW
2664
+ centre = [int]([int]$script:S.pillX + [int]([int]$script:S.pillW / 2))
2665
+ }
2666
+ }
2667
+
2668
+ function Cmd-Shutdown($A) {
2669
+ $t0 = [Diagnostics.Stopwatch]::GetTimestamp()
2670
+ return [ordered]@{
2671
+ closed = $true
2672
+ visible = [bool]$script:S.visible
2673
+ framesRendered = [Int64]$script:S.framesRendered
2674
+ uptimeMs = (NowMs)
2675
+ ms = (Elapsed $t0)
2676
+ }
2677
+ }
2678
+
2679
+ function Cmd-EscapePressed($A) {
2680
+ # Mirrors the worker's escape_pressed contract ({pressed: bool}), but latches instead of
2681
+ # sampling. The old probe read only the high bit ("is the key down at this instant"), so a
2682
+ # normal tap shorter than the host's 40 ms poll interval could be pressed and released
2683
+ # entirely between two probes and never seen - the "点 ESC 停止很慢" complaint. GetAsyncKeyState's
2684
+ # LOW bit means "the key was pressed since the previous call to this function", which is exactly
2685
+ # the edge we were missing: the next poll consumes it no matter how brief the press was.
2686
+ # Both bits are consumed in one call, so a single tap cannot report twice.
2687
+ $pressed = $false
2688
+ if ($script:nativeLoaded) {
2689
+ try {
2690
+ $state = [int][IndNative]::GetAsyncKeyState(0x1B)
2691
+ $held = ($state -band 0x8000) -ne 0
2692
+ $edge = ($state -band 0x0001) -ne 0
2693
+ $pressed = $held -or $edge
2694
+ } catch { $pressed = $false }
2695
+ }
2696
+ return [ordered]@{ pressed = [bool]$pressed }
2697
+ }
2698
+
2699
+ # ---------------------------------------------------------------- dispatch
2700
+ $handlers = @{
2701
+ ping = 'Cmd-Ping'
2702
+ show = 'Cmd-Show'
2703
+ beat = 'Cmd-Beat'
2704
+ phase = 'Cmd-Phase'
2705
+ shutdown = 'Cmd-Shutdown'
2706
+ escape_pressed = 'Cmd-EscapePressed'
2707
+ }
2708
+
2709
+ function Invoke-Request($line) {
2710
+ $id = 0
2711
+ $cmd = ''
2712
+ $A = @{}
2713
+ $script:S.lastCmdTick = [Diagnostics.Stopwatch]::GetTimestamp()
2714
+ try {
2715
+ $obj = $null
2716
+ try { $obj = ConvertFrom-Json $line } catch { Send-Err 0 'bad_json' ('not valid JSON: ' + $_.Exception.Message); return $true }
2717
+ if ($null -eq $obj) { Send-Err 0 'bad_json' 'empty request'; return $true }
2718
+ $pp = $obj.PSObject.Properties['id']
2719
+ if ($null -ne $pp -and $null -ne $pp.Value) { try { $id = [long]$pp.Value } catch { $id = 0 } }
2720
+ $pp = $obj.PSObject.Properties['cmd']
2721
+ if ($null -ne $pp -and $null -ne $pp.Value) { $cmd = [string]$pp.Value }
2722
+ $pp = $obj.PSObject.Properties['args']
2723
+ if ($null -ne $pp -and $null -ne $pp.Value) { $d = Dict $pp.Value; if ($d -is [System.Collections.IDictionary]) { $A = $d } }
2724
+ if ($cmd -eq '' -or -not $handlers.ContainsKey($cmd)) {
2725
+ Send-Err $id 'unknown_cmd' ("unknown cmd '" + (OneLine $cmd) + "'")
2726
+ return $true
2727
+ }
2728
+ $fn = $handlers[$cmd]
2729
+ # One choke point for plugin-supplied look: colour and capsule style both arrive on every command
2730
+ # that carries them, are applied here, and the outcome rides back in the response so an unread
2731
+ # parameter cannot pass as success.
2732
+ $script:S.lastPalette = $null
2733
+ $lookDirty = $false
2734
+ $styleArg = ArgOf $A 'style'
2735
+ # ArgOf already unwraps to the bare value; the old `$styleArg.Value` read null off a string,
2736
+ # so the style argument was silently ignored and every capsule rendered as `orb`. Pinning the
2737
+ # bare form is what makes the four shapes actually selectable.
2738
+ if ($null -ne $styleArg) {
2739
+ $st = [string]$styleArg
2740
+ if (@('orb','wave','mark','inverse') -notcontains $st) {
2741
+ Send-Err $id 'bad_style' ('unknown capsule style ' + (OneLine $st))
2742
+ return $true
2743
+ }
2744
+ if ($st -ne [string]$script:S.pillStyle) { $script:S.pillStyle = $st; $lookDirty = $true }
2745
+ }
2746
+ if ($null -ne (ArgOf $A 'palette')) {
2747
+ Apply-Palette $A | Out-Null
2748
+ # Only a palette that actually CHANGED the render table is a dirty look. The plugin sends the
2749
+ # palette on every show/phase/beat, so treating "palette present" as "look changed" bumped
2750
+ # lookVersion on every command, which missed the layout cache and rebuilt the tree -- replaying
2751
+ # the 340 ms intro on every single action. That is the "one flash per action" the person sees.
2752
+ # Apply-Palette already reports whether any colour landed; compare those colours with what was
2753
+ # there before to decide.
2754
+ $appliedNow = $script:S.lastPalette
2755
+ if ($appliedNow.applied) {
2756
+ $sig = (@($appliedNow.acting.g0, $appliedNow.acting.g1, $appliedNow.acting.base) -join '|')
2757
+ if ($sig -ne [string]$script:S.paletteSig) {
2758
+ $script:S.paletteSig = $sig
2759
+ $lookDirty = $true
2760
+ }
2761
+ }
2762
+ }
2763
+ # The smoke switch travels with the look on every command, like the palette and the style. Only a
2764
+ # real flip is dirty; the layout key already carries the flag, so an unchanged value costs
2765
+ # nothing.
2766
+ $mistArg = ArgOf $A 'mist'
2767
+ if ($null -ne $mistArg) {
2768
+ # BoolArg handles the JSON shapes ConvertFrom-Json produces (a real bool, or the strings
2769
+ # "true"/"1"/"yes"). Testing `-is [bool]` directly was wrong: the value arrives as a
2770
+ # PSCustomObject-wrapped scalar, so the test failed and the string compare then saw "True"
2771
+ # against "true" and pinned the flag to false.
2772
+ $wantMist = BoolArg $A 'mist' ([bool]$script:S.mistOn)
2773
+ if ($wantMist -ne [bool]$script:S.mistOn) { $script:S.mistOn = $wantMist; $lookDirty = $true }
2774
+ }
2775
+ if ($lookDirty -and $script:S.built) {
2776
+ $script:S.lookVersion += 1
2777
+ Render-Layout | Out-Null
2778
+ }
2779
+ $result = & $fn $A
2780
+ if ($cmd -eq 'shutdown') {
2781
+ Send-Ok $id $result
2782
+ Close-Server 'shutdown command'
2783
+ return $false
2784
+ }
2785
+ Send-Ok $id $result
2786
+ } catch {
2787
+ $code, $msg = Split-Err $_
2788
+ Log ((OneLine $cmd) + ' -> ' + $code + ': ' + (OneLine $msg))
2789
+ Send-Err $id $code $msg
2790
+ }
2791
+ return $true
2792
+ }
2793
+
2794
+ # ---------------------------------------------------------------- stdin reader (separate runspace)
2795
+ $script:inbox = New-Object System.Collections.Concurrent.ConcurrentQueue[string]
2796
+ $script:readerPs = $null
2797
+ $script:readerRs = $null
2798
+
2799
+ function Start-StdinReader {
2800
+ $rs = [runspacefactory]::CreateRunspace()
2801
+ $rs.ApartmentState = 'MTA'
2802
+ $rs.ThreadOptions = 'ReuseThread'
2803
+ $rs.Open()
2804
+ $ps = [PowerShell]::Create()
2805
+ $ps.Runspace = $rs
2806
+ [void]$ps.AddScript({
2807
+ param($q, $wake)
2808
+ $eof = '__EOF__'
2809
+ try {
2810
+ while ($true) {
2811
+ $line = $null
2812
+ try { $line = [Console]::In.ReadLine() } catch { [void]$q.Enqueue($eof); if ($wake) { [IndWake]::Notify() }; return }
2813
+ if ($null -eq $line) { [void]$q.Enqueue($eof); if ($wake) { [IndWake]::Notify() }; return }
2814
+ if ($line.Length -eq 0) { continue }
2815
+ if ($line.Length -gt 200000) { [void]$q.Enqueue('__TOOLONG__'); if ($wake) { [IndWake]::Notify() }; continue }
2816
+ [void]$q.Enqueue($line)
2817
+ if ($wake) { [IndWake]::Notify() }
2818
+ }
2819
+ } catch {
2820
+ [void]$q.Enqueue($eof)
2821
+ if ($wake) { [IndWake]::Notify() }
2822
+ }
2823
+ })
2824
+ [void]$ps.AddArgument($script:inbox)
2825
+ [void]$ps.AddArgument([bool]$script:nativeLoaded)
2826
+ $script:readerRs = $rs
2827
+ $script:readerPs = $ps
2828
+ [void]$ps.BeginInvoke()
2829
+ }
2830
+
2831
+ function Pump-Inbox {
2832
+ $line = $null
2833
+ $n = 0
2834
+ while ($n -lt 32) {
2835
+ if (-not $script:inbox.TryDequeue([ref]$line)) { break }
2836
+ $n += 1
2837
+ if ($line -eq '__EOF__') {
2838
+ Log 'stdin EOF, exiting'
2839
+ Close-Server 'stdin EOF'
2840
+ return
2841
+ }
2842
+ if ($line -eq '__TOOLONG__') { Send-Err 0 'bad_json' 'request line exceeds 200000 chars'; $line = $null; continue }
2843
+ if (-not (Invoke-Request $line)) { return }
2844
+ $line = $null
2845
+ }
2846
+ }
2847
+
2848
+ # ---------------------------------------------------------------- shutdown path
2849
+ function Close-Server([string]$why) {
2850
+ if ($script:S.closing) { return }
2851
+ $script:S.closing = $true
2852
+ Log ('closing (' + $why + ')')
2853
+ try { Stop-RenderLoop } catch { }
2854
+ try { if ($null -ne $script:stoppedTimer) { $script:stoppedTimer.Stop() } } catch { }
2855
+ foreach ($t in $script:S.timers) { try { $t.Stop() } catch { } }
2856
+ if ($null -ne $script:S.win) {
2857
+ try { $script:S.win.Hide() } catch { }
2858
+ $script:S.visible = $false
2859
+ $aliveBefore = (Test-HwndAlive)
2860
+ try { $script:S.win.Close() } catch { Log ('window close threw: ' + $_.Exception.Message) }
2861
+ $aliveAfter = (Test-HwndAlive)
2862
+ Log ('hwnd ' + [Int64]$script:S.hwnd + ' IsWindow before close = ' + $aliveBefore + ', after close = ' + $aliveAfter)
2863
+ }
2864
+ try { $script:S.canvas = $null; $script:S.win = $null; $script:S.ring = @(); $script:S.bloom = @() } catch { }
2865
+ try { if ($null -ne $script:S.app) { $script:S.app.Shutdown() } } catch { }
2866
+ try { if ($null -ne $script:dispatcher) { $script:dispatcher.InvokeShutdown() } } catch { }
2867
+ # A stuck overlay is the worst failure mode on this list, so unwinding the dispatcher is not
2868
+ # trusted to be the only exit path: if Run() has not returned within 1500 ms the process exits
2869
+ # from a thread-pool timer. The window is already hidden and closed at this point.
2870
+ try {
2871
+ $code = [int]$script:S.exitCode
2872
+ $timer = [System.Threading.Timer]::new(
2873
+ [System.Threading.TimerCallback]{ param($st) try { [Environment]::Exit($code) } catch { } },
2874
+ $null, 1500, [System.Threading.Timeout]::Infinite)
2875
+ $script:exitWatchdog = $timer
2876
+ } catch { Log ('exit watchdog failed: ' + $_.Exception.Message) }
2877
+ }
2878
+
2879
+ # ---------------------------------------------------------------- bootstrap
2880
+ $script:dispatcher = [System.Windows.Threading.Dispatcher]::CurrentDispatcher
2881
+ $script:S.dispatcher = $script:dispatcher
2882
+ $script:pumpAction = [System.Action]{ Pump-Inbox; [IndWake]::Clear() }
2883
+ $app = New-Object System.Windows.Application
2884
+ $app.ShutdownMode = [System.Windows.ShutdownMode]::OnExplicitShutdown
2885
+ $script:S.app = $app
2886
+ try { [IndWake]::Init($script:dispatcher, $script:pumpAction) } catch { Log ('wake init failed: ' + $_.Exception.Message) }
2887
+ Refresh-Screens | Out-Null
2888
+ Choose-Font | Out-Null
2889
+ $script:S.lastPulseMsWall = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
2890
+
2891
+ # Idle safety-net pump. Lines are normally handled the moment they arrive via [IndWake]::Notify,
2892
+ # so this only has to catch a missed signal; 250 ms costs almost nothing when nothing is happening.
2893
+ New-ServerTimer ([double]$CFG.pumpMs) { Pump-Inbox } | Out-Null
2894
+
2895
+ # watchdog: idle auto-hide + a focus-theft tripwire
2896
+ New-ServerTimer 250 {
2897
+ if ($script:S.visible) {
2898
+ $idle = (SinceMs $script:S.lastCmdTick)
2899
+ if ([int]$script:S.idleHideMs -gt 0 -and $idle -gt [double]$script:S.idleHideMs) {
2900
+ $script:S.autoHides += 1
2901
+ $script:S.stats.autoHides += 1
2902
+ Log ('idle ' + [Math]::Round($idle, 0) + ' ms > idleHideMs ' + $script:S.idleHideMs + ' -- auto-hiding')
2903
+ Hide-Overlay 'idle auto-hide'
2904
+ }
2905
+ if ($script:nativeLoaded -and [Int64]$script:S.hwnd -ne 0) {
2906
+ try {
2907
+ if ((Get-Fg) -eq [Int64]$script:S.hwnd) {
2908
+ $script:S.fgThefts += 1
2909
+ Log 'tripwire: the overlay became GetForegroundWindow() despite NOACTIVATE'
2910
+ }
2911
+ } catch { }
2912
+ }
2913
+ }
2914
+ } | Out-Null
2915
+
2916
+ # Warm the HWND and the render pipeline NOW rather than at run start: the first Show() of an
2917
+ # AllowsTransparency surface costs about a second (measured 1038 ms before this existed), which is
2918
+ # the difference between the overlay appearing with the action and appearing after it. The window is
2919
+ # parked far off every monitor, sized 4x4, shown once and hidden again -- the log line records the
2920
+ # rect it actually landed at, so "off screen" is a measurement and not a claim.
2921
+ function Warm-Window {
2922
+ try {
2923
+ $win = Ensure-Window
2924
+ $script:S.monitorBounds = $null
2925
+ $win.Width = 4.0
2926
+ $win.Height = 4.0
2927
+ $win.Left = -32000.0
2928
+ $win.Top = -32000.0
2929
+ $win.Show()
2930
+ $script:S.visible = $true
2931
+ Sync-Hwnd | Out-Null
2932
+ try { $win.Hide() } catch { }
2933
+ $script:S.visible = $false
2934
+ $r = Get-WindowRect
2935
+ $where = if ($null -eq $r) { 'unknown' } else { ([string]$r.x) + ',' + ([string]$r.y) + ' ' + ([string]$r.w) + 'x' + ([string]$r.h) }
2936
+ Log ('warm: hwnd ' + [Int64]$script:S.hwnd + ' parked at ' + $where + ', exStyles ' + (ExHex $script:S.exStyles) + ', ms ' + (NowMs))
2937
+ } catch {
2938
+ Log ('warm-up failed: ' + $_.Exception.Message)
2939
+ }
2940
+ }
2941
+
2942
+ Warm-Window
2943
+
2944
+ Start-StdinReader
2945
+ Log ('listening on stdin (pid ' + $PID + ', ps ' + $PSVersionTable.PSVersion + ', apt ' +
2946
+ ([Threading.Thread]::CurrentThread.GetApartmentState()) + ', dpiAware ' + $script:dpiMode +
2947
+ ', screens ' + ([array]$script:S.screens).Count + ', font "' + $script:S.chosenFont + '" glyphsOk ' +
2948
+ [bool]$script:S.fontProbe.allGlyphsPresent + ', wpfHelper ' + [bool]$script:renderLoaded +
2949
+ ', startup ' + (NowMs) + ' ms)')
2950
+
2951
+ # Dispatcher.Run() is a STATIC method on this framework (it drives the current thread's dispatcher),
2952
+ # so it cannot be called through the instance reference.
2953
+ [System.Windows.Threading.Dispatcher]::Run()
2954
+ Log 'dispatcher returned'
2955
+
2956
+ # The reader runspace is deliberately NOT disposed: its pipeline is parked in Console.In.ReadLine(),
2957
+ # and Dispose() waits for the pipeline to finish -- which never happens while the parent still holds
2958
+ # the pipe open. That hang was measured (shutdown answered, process lived on). Environment.Exit
2959
+ # tears the process down for real, and the window is already hidden and closed by Close-Server.
2960
+ $exitCode = 0
2961
+ try { $exitCode = [int]$script:S.exitCode } catch { }
2962
+ Log ('exiting ' + $exitCode + ' (uptime ' + (NowMs) + ' ms, frames ' + [Int64]$script:S.framesRendered + ')')
2963
+ [System.Environment]::Exit($exitCode)