ai-battery 0.1.11 → 0.1.13

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.
@@ -1,351 +1,351 @@
1
- param(
2
- [int]$Interval = 5,
3
- [string]$Position = $(if ($env:AI_BATTERY_HUD_POSITION) { $env:AI_BATTERY_HUD_POSITION } elseif ($env:CLAUDEX_BATTERY_HUD_POSITION) { $env:CLAUDEX_BATTERY_HUD_POSITION } else { "saved" }),
4
- [ValidateSet("tray", "statusline", "floating")]
5
- [string]$Mode = $(if ($env:AI_BATTERY_HUD_MODE) { $env:AI_BATTERY_HUD_MODE } elseif ($env:CLAUDEX_BATTERY_HUD_MODE) { $env:CLAUDEX_BATTERY_HUD_MODE } else { "floating" }),
6
- [string]$BatteryCommand = $(if ($env:AI_BATTERY_COMMAND) { $env:AI_BATTERY_COMMAND } elseif ($env:CLAUDEX_BATTERY_COMMAND) { $env:CLAUDEX_BATTERY_COMMAND } else { "ai-battery --json" }),
7
- [string]$BatteryCommandBase64 = "",
8
- [string]$InitialJsonBase64 = "",
9
- [int]$Width = 282,
10
- [double]$Opacity = $(if ($env:AI_BATTERY_HUD_OPACITY) { [double]$env:AI_BATTERY_HUD_OPACITY } elseif ($env:CLAUDEX_BATTERY_HUD_OPACITY) { [double]$env:CLAUDEX_BATTERY_HUD_OPACITY } else { 1.0 }),
11
- [switch]$Locked,
12
- [switch]$Movable,
13
- [switch]$ClickThrough,
14
- [switch]$StopExisting,
15
- [switch]$UseWsl,
16
- [switch]$Once,
17
- [string]$ReadyPath = ""
18
- )
19
-
20
- $ErrorActionPreference = "Stop"
21
- Add-Type -AssemblyName System.Drawing
22
- [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
23
-
24
- if (-not [string]::IsNullOrWhiteSpace($BatteryCommandBase64)) {
25
- try {
26
- $BatteryCommand = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($BatteryCommandBase64))
27
- } catch {
28
- # Fall back to BatteryCommand/env defaults; the HUD can still show an error row.
29
- }
30
- }
31
-
32
- function Stop-ExistingHudProcesses {
33
- $currentPid = $PID
34
- Get-CimInstance Win32_Process |
35
- Where-Object {
36
- $_.ProcessId -ne $currentPid -and
37
- $_.Name -match '^(powershell|pwsh)(\.exe)?$' -and
38
- $_.CommandLine -and
39
- $_.CommandLine -like "*ai-battery-hud.ps1*" -and
40
- $_.CommandLine -notlike "*Start-Process*"
41
- } |
42
- ForEach-Object {
43
- try {
44
- Stop-Process -Id $_.ProcessId -Force -ErrorAction Stop
45
- Wait-Process -Id $_.ProcessId -Timeout 3 -ErrorAction SilentlyContinue
46
- } catch {
47
- # The process may already have exited.
48
- }
49
- }
50
- }
51
-
52
- if ($StopExisting) {
53
- Stop-ExistingHudProcesses
54
- if (-not $Once) {
55
- exit 0
56
- }
57
- } elseif (-not $Once) {
58
- Stop-ExistingHudProcesses
59
- }
60
-
61
- $script:singleInstanceMutex = $null
62
- if (-not $Once) {
63
- # A replaced instance we just stopped can hold the mutex handle for a
64
- # moment after Stop-Process returns; retry briefly before treating the
65
- # mutex owner as a genuinely running HUD.
66
- $createdNew = $false
67
- for ($mutexAttempt = 0; $mutexAttempt -lt 20; $mutexAttempt += 1) {
68
- $script:singleInstanceMutex = [System.Threading.Mutex]::new($true, "Local\AiBatteryHud", [ref]$createdNew)
69
- if ($createdNew) { break }
70
- $script:singleInstanceMutex.Dispose()
71
- $script:singleInstanceMutex = $null
72
- Start-Sleep -Milliseconds 150
73
- }
74
- if (-not $createdNew) {
75
- exit 0
76
- }
77
- }
78
-
79
- function Release-SingleInstance {
80
- if ($script:singleInstanceMutex) {
81
- try {
82
- $script:singleInstanceMutex.ReleaseMutex()
83
- } catch {
84
- # Already released.
85
- }
86
- $script:singleInstanceMutex.Dispose()
87
- $script:singleInstanceMutex = $null
88
- }
89
- }
90
-
91
- function Get-HudStatePath {
92
- $root = if ($env:LOCALAPPDATA) {
93
- Join-Path $env:LOCALAPPDATA "ai-battery"
94
- } else {
95
- Join-Path $env:TEMP "ai-battery"
96
- }
97
- New-Item -ItemType Directory -Force -Path $root | Out-Null
98
- return Join-Path $root "hud-position.json"
99
- }
100
-
101
- function Get-HudSourceId {
102
- if ($UseWsl) { return "wsl" }
103
- return "windows"
104
- }
105
-
106
- function Get-HudSnapshotPath {
107
- $root = if ($env:LOCALAPPDATA) {
108
- Join-Path $env:LOCALAPPDATA "ai-battery"
109
- } else {
110
- Join-Path $env:TEMP "ai-battery"
111
- }
112
- New-Item -ItemType Directory -Force -Path $root | Out-Null
113
- return Join-Path $root "hud-snapshot-$(Get-HudSourceId).json"
114
- }
115
-
116
- function Get-LegacyHudStatePath {
117
- $root = if ($env:LOCALAPPDATA) {
118
- Join-Path $env:LOCALAPPDATA "claudex-battery"
119
- } else {
120
- Join-Path $env:TEMP "claudex-battery"
121
- }
122
- return Join-Path $root "hud-position.json"
123
- }
124
-
125
- $script:hudAnchorX = "left"
126
- $script:hudAnchorY = "top"
127
- $script:codexRowVisible = $true
128
- $script:claudeRowVisible = $true
129
-
130
- function Signal-HudReady {
131
- if ([string]::IsNullOrWhiteSpace($ReadyPath)) { return }
132
- try {
133
- $dir = Split-Path -Parent $ReadyPath
134
- if ($dir) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
135
- @{
136
- Ready = $true
137
- Pid = $PID
138
- At = [datetime]::UtcNow.ToString("o")
139
- Mode = $Mode
140
- } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 -Path $ReadyPath
141
- } catch {
142
- # Readiness is diagnostic only.
143
- }
144
- }
145
-
146
- function Read-HudPlacement {
147
- foreach ($path in @((Get-HudStatePath), (Get-LegacyHudStatePath))) {
148
- try {
149
- if (-not (Test-Path $path)) { continue }
150
- $state = Get-Content $path -Raw | ConvertFrom-Json
151
- if ($null -ne $state.X -and $null -ne $state.Y) {
152
- return $state
153
- }
154
- } catch {
155
- # Try the next state path.
156
- }
157
- }
158
- return $null
159
- }
160
-
161
- function Read-HudPosition {
162
- $state = Read-HudPlacement
163
- if (-not $state) { return $null }
164
- return [System.Drawing.Point]::new([int]$state.X, [int]$state.Y)
165
- }
166
-
167
- function Write-HudPosition($Point) {
168
- try {
169
- $width = $null
170
- $height = $null
171
- if ($form -and -not $form.IsDisposed) {
172
- $width = [int]$form.Width
173
- $height = [int]$form.Height
174
- }
175
- @{
176
- X = [int]$Point.X
177
- Y = [int]$Point.Y
178
- Width = $width
179
- Height = $height
180
- } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 -Path (Get-HudStatePath)
181
- } catch {
182
- # Position persistence is helpful but not required for the HUD to run.
183
- }
184
- }
185
-
186
- function Get-SnapshotAgeSeconds($Snapshot) {
187
- if (-not $Snapshot -or -not $Snapshot.generatedAt) { return $null }
188
- try {
189
- return [math]::Max(0, [int](([datetime]::UtcNow - ([datetime]$Snapshot.generatedAt).ToUniversalTime()).TotalSeconds))
190
- } catch {
191
- return $null
192
- }
193
- }
194
-
195
- function Read-HudSnapshot {
196
- try {
197
- $path = Get-HudSnapshotPath
198
- if (-not (Test-Path $path)) { return $null }
199
- $snapshot = Get-Content $path -Raw | ConvertFrom-Json
200
- $age = Get-SnapshotAgeSeconds $snapshot
201
- $maxAge = if ($env:AI_BATTERY_HUD_CACHE_SECONDS) { [int]$env:AI_BATTERY_HUD_CACHE_SECONDS } else { 900 }
202
- if ($null -ne $age -and $age -le $maxAge) { return $snapshot }
203
- } catch {
204
- # Cached data is optional.
205
- }
206
- return $null
207
- }
208
-
209
- function Read-InitialHudSnapshot {
210
- if ([string]::IsNullOrWhiteSpace($InitialJsonBase64)) { return $null }
211
- try {
212
- $json = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($InitialJsonBase64))
213
- if ([string]::IsNullOrWhiteSpace($json)) { return $null }
214
- return $json | ConvertFrom-Json
215
- } catch {
216
- return $null
217
- }
218
- }
219
-
220
- function Write-HudSnapshot($Snapshot) {
221
- try {
222
- if (-not $Snapshot) { return }
223
- $Snapshot | Add-Member -NotePropertyName "hudSource" -NotePropertyValue (Get-HudSourceId) -Force
224
- $Snapshot | ConvertTo-Json -Depth 20 -Compress | Set-Content -Encoding UTF8 -Path (Get-HudSnapshotPath)
225
- } catch {
226
- # The HUD can still run without a warm-start cache.
227
- }
228
- }
229
-
230
- $script:initialHudSnapshot = Read-InitialHudSnapshot
231
-
232
- $nativeCode = @"
233
- using System;
234
- using System.Runtime.InteropServices;
235
- [StructLayout(LayoutKind.Sequential)]
236
- public struct AiBatteryRect {
237
- public int Left;
238
- public int Top;
239
- public int Right;
240
- public int Bottom;
241
- }
242
- [StructLayout(LayoutKind.Sequential)]
243
- public struct AiBatteryMonitorInfo {
244
- public int CbSize;
245
- public AiBatteryRect Monitor;
246
- public AiBatteryRect Work;
247
- public int Flags;
248
- }
249
- [StructLayout(LayoutKind.Sequential)]
250
- public struct AiBatteryPowerThrottlingState {
251
- public uint Version;
252
- public uint ControlMask;
253
- public uint StateMask;
254
- }
255
- public delegate void AiBatteryWinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
256
- public static class AiBatteryNative {
257
- public const int ProcessPowerThrottling = 4;
258
- public const uint PROCESS_POWER_THROTTLING_CURRENT_VERSION = 1;
259
- public const uint PROCESS_POWER_THROTTLING_EXECUTION_SPEED = 0x1;
260
- public const int OBJID_WINDOW = 0;
261
- public const int GWL_EXSTYLE = -20;
262
- public const int WS_EX_TRANSPARENT = 0x20;
263
- public const int WS_EX_TOOLWINDOW = 0x80;
264
- public const int WS_EX_NOACTIVATE = 0x08000000;
265
- public const int SW_HIDE = 0;
266
- public const int SW_SHOWNOACTIVATE = 4;
267
- public const UInt32 MONITOR_DEFAULTTONEAREST = 2;
268
- public const UInt32 GW_HWNDNEXT = 2;
269
- public const int DWMWA_CLOAKED = 14;
270
- public const uint EVENT_SYSTEM_FOREGROUND = 0x0003;
271
- public const uint EVENT_OBJECT_SHOW = 0x8002;
272
- public const uint EVENT_OBJECT_HIDE = 0x8003;
273
- public const uint EVENT_OBJECT_REORDER = 0x8004;
274
- public const uint EVENT_OBJECT_LOCATIONCHANGE = 0x800B;
275
- public const uint EVENT_OBJECT_CLOAKED = 0x8017;
276
- public const uint EVENT_OBJECT_UNCLOAKED = 0x8018;
277
- public const uint WINEVENT_OUTOFCONTEXT = 0x0000;
278
- public const uint WINEVENT_SKIPOWNPROCESS = 0x0002;
279
- public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
280
- public const UInt32 SWP_NOSIZE = 0x0001;
281
- public const UInt32 SWP_NOMOVE = 0x0002;
282
- public const UInt32 SWP_NOACTIVATE = 0x0010;
283
- public const UInt32 SWP_SHOWWINDOW = 0x0040;
284
- [DllImport("user32.dll")]
285
- public static extern IntPtr GetForegroundWindow();
286
- [DllImport("user32.dll")]
287
- public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
288
- [DllImport("user32.dll")]
289
- public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
290
- [DllImport("user32.dll")]
291
- public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, UInt32 uFlags);
292
- [DllImport("user32.dll")]
293
- public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
294
- [DllImport("user32.dll")]
295
- public static extern IntPtr GetWindow(IntPtr hWnd, UInt32 uCmd);
296
- [DllImport("user32.dll")]
297
- public static extern IntPtr GetTopWindow(IntPtr hWnd);
298
- [DllImport("user32.dll")]
299
- public static extern bool IsWindowVisible(IntPtr hWnd);
300
- [DllImport("user32.dll", CharSet=CharSet.Auto)]
301
- public static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount);
302
- [DllImport("dwmapi.dll")]
303
- public static extern int DwmGetWindowAttribute(IntPtr hWnd, int dwAttribute, out int pvAttribute, int cbAttribute);
304
- [DllImport("kernel32.dll")]
305
- public static extern IntPtr GetCurrentProcess();
306
- [DllImport("kernel32.dll", SetLastError=true)]
307
- public static extern bool SetProcessInformation(IntPtr hProcess, int ProcessInformationClass, ref AiBatteryPowerThrottlingState ProcessInformation, int ProcessInformationSize);
308
- [DllImport("user32.dll")]
309
- public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, AiBatteryWinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
310
- [DllImport("user32.dll")]
311
- public static extern bool UnhookWinEvent(IntPtr hWinEventHook);
312
- [DllImport("user32.dll", CharSet=CharSet.Auto)]
313
- public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
314
- [DllImport("user32.dll", CharSet=CharSet.Auto)]
315
- public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
316
- [DllImport("user32.dll")]
317
- public static extern bool GetWindowRect(IntPtr hWnd, out AiBatteryRect rect);
318
- [DllImport("user32.dll")]
319
- public static extern IntPtr MonitorFromWindow(IntPtr hWnd, UInt32 dwFlags);
320
- [DllImport("user32.dll")]
321
- public static extern bool GetMonitorInfo(IntPtr hMonitor, ref AiBatteryMonitorInfo lpmi);
322
- [DllImport("user32.dll")]
323
- public static extern bool DestroyIcon(IntPtr hIcon);
324
- }
325
- "@
326
- Add-Type -TypeDefinition $nativeCode
327
-
328
- function Disable-ProcessPowerThrottling {
329
- # When a fullscreen app is in the foreground, Windows applies EcoQoS power
330
- # throttling to background processes like this HUD, which stretches the
331
- # WinForms timer from 250ms out to several seconds. That made the HUD linger
332
- # over a fullscreen window for 3-5s before hiding (while unhide, which happens
333
- # after throttling lifts, stayed instant). Opt the process out so the
334
- # fullscreen check keeps firing on time even while backgrounded.
335
- try {
336
- $state = New-Object AiBatteryPowerThrottlingState
337
- $state.Version = [AiBatteryNative]::PROCESS_POWER_THROTTLING_CURRENT_VERSION
338
- $state.ControlMask = [AiBatteryNative]::PROCESS_POWER_THROTTLING_EXECUTION_SPEED
339
- $state.StateMask = 0
340
- $size = [System.Runtime.InteropServices.Marshal]::SizeOf([type][AiBatteryPowerThrottlingState])
341
- return [AiBatteryNative]::SetProcessInformation([AiBatteryNative]::GetCurrentProcess(), [AiBatteryNative]::ProcessPowerThrottling, [ref]$state, $size)
342
- } catch {
343
- # Older Windows builds lack ProcessPowerThrottling; the HUD still works.
344
- return $false
345
- }
346
- }
347
- $script:powerThrottlingDisabled = Disable-ProcessPowerThrottling
348
-
1
+ param(
2
+ [int]$Interval = 5,
3
+ [string]$Position = $(if ($env:AI_BATTERY_HUD_POSITION) { $env:AI_BATTERY_HUD_POSITION } elseif ($env:CLAUDEX_BATTERY_HUD_POSITION) { $env:CLAUDEX_BATTERY_HUD_POSITION } else { "saved" }),
4
+ [ValidateSet("tray", "statusline", "floating")]
5
+ [string]$Mode = $(if ($env:AI_BATTERY_HUD_MODE) { $env:AI_BATTERY_HUD_MODE } elseif ($env:CLAUDEX_BATTERY_HUD_MODE) { $env:CLAUDEX_BATTERY_HUD_MODE } else { "floating" }),
6
+ [string]$BatteryCommand = $(if ($env:AI_BATTERY_COMMAND) { $env:AI_BATTERY_COMMAND } elseif ($env:CLAUDEX_BATTERY_COMMAND) { $env:CLAUDEX_BATTERY_COMMAND } else { "ai-battery --json" }),
7
+ [string]$BatteryCommandBase64 = "",
8
+ [string]$InitialJsonBase64 = "",
9
+ [int]$Width = 282,
10
+ [double]$Opacity = $(if ($env:AI_BATTERY_HUD_OPACITY) { [double]$env:AI_BATTERY_HUD_OPACITY } elseif ($env:CLAUDEX_BATTERY_HUD_OPACITY) { [double]$env:CLAUDEX_BATTERY_HUD_OPACITY } else { 1.0 }),
11
+ [switch]$Locked,
12
+ [switch]$Movable,
13
+ [switch]$ClickThrough,
14
+ [switch]$StopExisting,
15
+ [switch]$UseWsl,
16
+ [switch]$Once,
17
+ [string]$ReadyPath = ""
18
+ )
19
+
20
+ $ErrorActionPreference = "Stop"
21
+ Add-Type -AssemblyName System.Drawing
22
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
23
+
24
+ if (-not [string]::IsNullOrWhiteSpace($BatteryCommandBase64)) {
25
+ try {
26
+ $BatteryCommand = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($BatteryCommandBase64))
27
+ } catch {
28
+ # Fall back to BatteryCommand/env defaults; the HUD can still show an error row.
29
+ }
30
+ }
31
+
32
+ function Stop-ExistingHudProcesses {
33
+ $currentPid = $PID
34
+ Get-CimInstance Win32_Process |
35
+ Where-Object {
36
+ $_.ProcessId -ne $currentPid -and
37
+ $_.Name -match '^(powershell|pwsh)(\.exe)?$' -and
38
+ $_.CommandLine -and
39
+ $_.CommandLine -like "*ai-battery-hud.ps1*" -and
40
+ $_.CommandLine -notlike "*Start-Process*"
41
+ } |
42
+ ForEach-Object {
43
+ try {
44
+ Stop-Process -Id $_.ProcessId -Force -ErrorAction Stop
45
+ Wait-Process -Id $_.ProcessId -Timeout 3 -ErrorAction SilentlyContinue
46
+ } catch {
47
+ # The process may already have exited.
48
+ }
49
+ }
50
+ }
51
+
52
+ if ($StopExisting) {
53
+ Stop-ExistingHudProcesses
54
+ if (-not $Once) {
55
+ exit 0
56
+ }
57
+ } elseif (-not $Once) {
58
+ Stop-ExistingHudProcesses
59
+ }
60
+
61
+ $script:singleInstanceMutex = $null
62
+ if (-not $Once) {
63
+ # A replaced instance we just stopped can hold the mutex handle for a
64
+ # moment after Stop-Process returns; retry briefly before treating the
65
+ # mutex owner as a genuinely running HUD.
66
+ $createdNew = $false
67
+ for ($mutexAttempt = 0; $mutexAttempt -lt 20; $mutexAttempt += 1) {
68
+ $script:singleInstanceMutex = [System.Threading.Mutex]::new($true, "Local\AiBatteryHud", [ref]$createdNew)
69
+ if ($createdNew) { break }
70
+ $script:singleInstanceMutex.Dispose()
71
+ $script:singleInstanceMutex = $null
72
+ Start-Sleep -Milliseconds 150
73
+ }
74
+ if (-not $createdNew) {
75
+ exit 0
76
+ }
77
+ }
78
+
79
+ function Release-SingleInstance {
80
+ if ($script:singleInstanceMutex) {
81
+ try {
82
+ $script:singleInstanceMutex.ReleaseMutex()
83
+ } catch {
84
+ # Already released.
85
+ }
86
+ $script:singleInstanceMutex.Dispose()
87
+ $script:singleInstanceMutex = $null
88
+ }
89
+ }
90
+
91
+ function Get-HudStatePath {
92
+ $root = if ($env:LOCALAPPDATA) {
93
+ Join-Path $env:LOCALAPPDATA "ai-battery"
94
+ } else {
95
+ Join-Path $env:TEMP "ai-battery"
96
+ }
97
+ New-Item -ItemType Directory -Force -Path $root | Out-Null
98
+ return Join-Path $root "hud-position.json"
99
+ }
100
+
101
+ function Get-HudSourceId {
102
+ if ($UseWsl) { return "wsl" }
103
+ return "windows"
104
+ }
105
+
106
+ function Get-HudSnapshotPath {
107
+ $root = if ($env:LOCALAPPDATA) {
108
+ Join-Path $env:LOCALAPPDATA "ai-battery"
109
+ } else {
110
+ Join-Path $env:TEMP "ai-battery"
111
+ }
112
+ New-Item -ItemType Directory -Force -Path $root | Out-Null
113
+ return Join-Path $root "hud-snapshot-$(Get-HudSourceId).json"
114
+ }
115
+
116
+ function Get-LegacyHudStatePath {
117
+ $root = if ($env:LOCALAPPDATA) {
118
+ Join-Path $env:LOCALAPPDATA "claudex-battery"
119
+ } else {
120
+ Join-Path $env:TEMP "claudex-battery"
121
+ }
122
+ return Join-Path $root "hud-position.json"
123
+ }
124
+
125
+ $script:hudAnchorX = "left"
126
+ $script:hudAnchorY = "top"
127
+ $script:codexRowVisible = $true
128
+ $script:claudeRowVisible = $true
129
+
130
+ function Signal-HudReady {
131
+ if ([string]::IsNullOrWhiteSpace($ReadyPath)) { return }
132
+ try {
133
+ $dir = Split-Path -Parent $ReadyPath
134
+ if ($dir) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
135
+ @{
136
+ Ready = $true
137
+ Pid = $PID
138
+ At = [datetime]::UtcNow.ToString("o")
139
+ Mode = $Mode
140
+ } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 -Path $ReadyPath
141
+ } catch {
142
+ # Readiness is diagnostic only.
143
+ }
144
+ }
145
+
146
+ function Read-HudPlacement {
147
+ foreach ($path in @((Get-HudStatePath), (Get-LegacyHudStatePath))) {
148
+ try {
149
+ if (-not (Test-Path $path)) { continue }
150
+ $state = Get-Content $path -Raw | ConvertFrom-Json
151
+ if ($null -ne $state.X -and $null -ne $state.Y) {
152
+ return $state
153
+ }
154
+ } catch {
155
+ # Try the next state path.
156
+ }
157
+ }
158
+ return $null
159
+ }
160
+
161
+ function Read-HudPosition {
162
+ $state = Read-HudPlacement
163
+ if (-not $state) { return $null }
164
+ return [System.Drawing.Point]::new([int]$state.X, [int]$state.Y)
165
+ }
166
+
167
+ function Write-HudPosition($Point) {
168
+ try {
169
+ $width = $null
170
+ $height = $null
171
+ if ($form -and -not $form.IsDisposed) {
172
+ $width = [int]$form.Width
173
+ $height = [int]$form.Height
174
+ }
175
+ @{
176
+ X = [int]$Point.X
177
+ Y = [int]$Point.Y
178
+ Width = $width
179
+ Height = $height
180
+ } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 -Path (Get-HudStatePath)
181
+ } catch {
182
+ # Position persistence is helpful but not required for the HUD to run.
183
+ }
184
+ }
185
+
186
+ function Get-SnapshotAgeSeconds($Snapshot) {
187
+ if (-not $Snapshot -or -not $Snapshot.generatedAt) { return $null }
188
+ try {
189
+ return [math]::Max(0, [int](([datetime]::UtcNow - ([datetime]$Snapshot.generatedAt).ToUniversalTime()).TotalSeconds))
190
+ } catch {
191
+ return $null
192
+ }
193
+ }
194
+
195
+ function Read-HudSnapshot {
196
+ try {
197
+ $path = Get-HudSnapshotPath
198
+ if (-not (Test-Path $path)) { return $null }
199
+ $snapshot = Get-Content $path -Raw | ConvertFrom-Json
200
+ $age = Get-SnapshotAgeSeconds $snapshot
201
+ $maxAge = if ($env:AI_BATTERY_HUD_CACHE_SECONDS) { [int]$env:AI_BATTERY_HUD_CACHE_SECONDS } else { 900 }
202
+ if ($null -ne $age -and $age -le $maxAge) { return $snapshot }
203
+ } catch {
204
+ # Cached data is optional.
205
+ }
206
+ return $null
207
+ }
208
+
209
+ function Read-InitialHudSnapshot {
210
+ if ([string]::IsNullOrWhiteSpace($InitialJsonBase64)) { return $null }
211
+ try {
212
+ $json = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($InitialJsonBase64))
213
+ if ([string]::IsNullOrWhiteSpace($json)) { return $null }
214
+ return $json | ConvertFrom-Json
215
+ } catch {
216
+ return $null
217
+ }
218
+ }
219
+
220
+ function Write-HudSnapshot($Snapshot) {
221
+ try {
222
+ if (-not $Snapshot) { return }
223
+ $Snapshot | Add-Member -NotePropertyName "hudSource" -NotePropertyValue (Get-HudSourceId) -Force
224
+ $Snapshot | ConvertTo-Json -Depth 20 -Compress | Set-Content -Encoding UTF8 -Path (Get-HudSnapshotPath)
225
+ } catch {
226
+ # The HUD can still run without a warm-start cache.
227
+ }
228
+ }
229
+
230
+ $script:initialHudSnapshot = Read-InitialHudSnapshot
231
+
232
+ $nativeCode = @"
233
+ using System;
234
+ using System.Runtime.InteropServices;
235
+ [StructLayout(LayoutKind.Sequential)]
236
+ public struct AiBatteryRect {
237
+ public int Left;
238
+ public int Top;
239
+ public int Right;
240
+ public int Bottom;
241
+ }
242
+ [StructLayout(LayoutKind.Sequential)]
243
+ public struct AiBatteryMonitorInfo {
244
+ public int CbSize;
245
+ public AiBatteryRect Monitor;
246
+ public AiBatteryRect Work;
247
+ public int Flags;
248
+ }
249
+ [StructLayout(LayoutKind.Sequential)]
250
+ public struct AiBatteryPowerThrottlingState {
251
+ public uint Version;
252
+ public uint ControlMask;
253
+ public uint StateMask;
254
+ }
255
+ public delegate void AiBatteryWinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
256
+ public static class AiBatteryNative {
257
+ public const int ProcessPowerThrottling = 4;
258
+ public const uint PROCESS_POWER_THROTTLING_CURRENT_VERSION = 1;
259
+ public const uint PROCESS_POWER_THROTTLING_EXECUTION_SPEED = 0x1;
260
+ public const int OBJID_WINDOW = 0;
261
+ public const int GWL_EXSTYLE = -20;
262
+ public const int WS_EX_TRANSPARENT = 0x20;
263
+ public const int WS_EX_TOOLWINDOW = 0x80;
264
+ public const int WS_EX_NOACTIVATE = 0x08000000;
265
+ public const int SW_HIDE = 0;
266
+ public const int SW_SHOWNOACTIVATE = 4;
267
+ public const UInt32 MONITOR_DEFAULTTONEAREST = 2;
268
+ public const UInt32 GW_HWNDNEXT = 2;
269
+ public const int DWMWA_CLOAKED = 14;
270
+ public const uint EVENT_SYSTEM_FOREGROUND = 0x0003;
271
+ public const uint EVENT_OBJECT_SHOW = 0x8002;
272
+ public const uint EVENT_OBJECT_HIDE = 0x8003;
273
+ public const uint EVENT_OBJECT_REORDER = 0x8004;
274
+ public const uint EVENT_OBJECT_LOCATIONCHANGE = 0x800B;
275
+ public const uint EVENT_OBJECT_CLOAKED = 0x8017;
276
+ public const uint EVENT_OBJECT_UNCLOAKED = 0x8018;
277
+ public const uint WINEVENT_OUTOFCONTEXT = 0x0000;
278
+ public const uint WINEVENT_SKIPOWNPROCESS = 0x0002;
279
+ public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
280
+ public const UInt32 SWP_NOSIZE = 0x0001;
281
+ public const UInt32 SWP_NOMOVE = 0x0002;
282
+ public const UInt32 SWP_NOACTIVATE = 0x0010;
283
+ public const UInt32 SWP_SHOWWINDOW = 0x0040;
284
+ [DllImport("user32.dll")]
285
+ public static extern IntPtr GetForegroundWindow();
286
+ [DllImport("user32.dll")]
287
+ public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
288
+ [DllImport("user32.dll")]
289
+ public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
290
+ [DllImport("user32.dll")]
291
+ public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, UInt32 uFlags);
292
+ [DllImport("user32.dll")]
293
+ public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
294
+ [DllImport("user32.dll")]
295
+ public static extern IntPtr GetWindow(IntPtr hWnd, UInt32 uCmd);
296
+ [DllImport("user32.dll")]
297
+ public static extern IntPtr GetTopWindow(IntPtr hWnd);
298
+ [DllImport("user32.dll")]
299
+ public static extern bool IsWindowVisible(IntPtr hWnd);
300
+ [DllImport("user32.dll", CharSet=CharSet.Auto)]
301
+ public static extern int GetClassName(IntPtr hWnd, System.Text.StringBuilder lpClassName, int nMaxCount);
302
+ [DllImport("dwmapi.dll")]
303
+ public static extern int DwmGetWindowAttribute(IntPtr hWnd, int dwAttribute, out int pvAttribute, int cbAttribute);
304
+ [DllImport("kernel32.dll")]
305
+ public static extern IntPtr GetCurrentProcess();
306
+ [DllImport("kernel32.dll", SetLastError=true)]
307
+ public static extern bool SetProcessInformation(IntPtr hProcess, int ProcessInformationClass, ref AiBatteryPowerThrottlingState ProcessInformation, int ProcessInformationSize);
308
+ [DllImport("user32.dll")]
309
+ public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, AiBatteryWinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
310
+ [DllImport("user32.dll")]
311
+ public static extern bool UnhookWinEvent(IntPtr hWinEventHook);
312
+ [DllImport("user32.dll", CharSet=CharSet.Auto)]
313
+ public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
314
+ [DllImport("user32.dll", CharSet=CharSet.Auto)]
315
+ public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
316
+ [DllImport("user32.dll")]
317
+ public static extern bool GetWindowRect(IntPtr hWnd, out AiBatteryRect rect);
318
+ [DllImport("user32.dll")]
319
+ public static extern IntPtr MonitorFromWindow(IntPtr hWnd, UInt32 dwFlags);
320
+ [DllImport("user32.dll")]
321
+ public static extern bool GetMonitorInfo(IntPtr hMonitor, ref AiBatteryMonitorInfo lpmi);
322
+ [DllImport("user32.dll")]
323
+ public static extern bool DestroyIcon(IntPtr hIcon);
324
+ }
325
+ "@
326
+ Add-Type -TypeDefinition $nativeCode
327
+
328
+ function Disable-ProcessPowerThrottling {
329
+ # When a fullscreen app is in the foreground, Windows applies EcoQoS power
330
+ # throttling to background processes like this HUD, which stretches the
331
+ # WinForms timer from 250ms out to several seconds. That made the HUD linger
332
+ # over a fullscreen window for 3-5s before hiding (while unhide, which happens
333
+ # after throttling lifts, stayed instant). Opt the process out so the
334
+ # fullscreen check keeps firing on time even while backgrounded.
335
+ try {
336
+ $state = New-Object AiBatteryPowerThrottlingState
337
+ $state.Version = [AiBatteryNative]::PROCESS_POWER_THROTTLING_CURRENT_VERSION
338
+ $state.ControlMask = [AiBatteryNative]::PROCESS_POWER_THROTTLING_EXECUTION_SPEED
339
+ $state.StateMask = 0
340
+ $size = [System.Runtime.InteropServices.Marshal]::SizeOf([type][AiBatteryPowerThrottlingState])
341
+ return [AiBatteryNative]::SetProcessInformation([AiBatteryNative]::GetCurrentProcess(), [AiBatteryNative]::ProcessPowerThrottling, [ref]$state, $size)
342
+ } catch {
343
+ # Older Windows builds lack ProcessPowerThrottling; the HUD still works.
344
+ return $false
345
+ }
346
+ }
347
+ $script:powerThrottlingDisabled = Disable-ProcessPowerThrottling
348
+
349
349
  function Invoke-AiBatteryJson {
350
350
  if ($UseWsl) {
351
351
  $output = & wsl.exe bash -lc "$BatteryCommand 2>/dev/null"
@@ -366,268 +366,268 @@ function Invoke-LocalBatteryCommandOutput([string]$Command) {
366
366
  return Invoke-Expression "& $Command 2>`$null"
367
367
  }
368
368
  }
369
-
370
- function Get-DurationText([Nullable[int]]$Seconds) {
371
- if ($null -eq $Seconds) { return "?" }
372
- if ($Seconds -le 0) { return "now" }
373
- $minutes = [math]::Floor($Seconds / 60)
374
- if ($minutes -lt 60) { return "${minutes}m" }
375
- $hours = [math]::Floor($minutes / 60)
376
- $restMinutes = $minutes % 60
377
- if ($hours -lt 48) {
378
- if ($restMinutes -gt 0) { return "${hours}h${restMinutes}m" }
379
- return "${hours}h"
380
- }
381
- $days = [math]::Floor($hours / 24)
382
- $restHours = $hours % 24
383
- if ($restHours -gt 0) { return "${days}d${restHours}h" }
384
- return "${days}d"
385
- }
386
-
387
- function Get-ResetClock($Limit) {
388
- if (-not $Limit -or -not $Limit.resetsAt) { return "--:--" }
389
- if ($Limit.resetPassed) { return "--:--" }
390
- try {
391
- return ([datetime]$Limit.resetsAt).ToLocalTime().ToString("HH:mm")
392
- } catch {
393
- return "--:--"
394
- }
395
- }
396
-
397
- function Get-WindowText($Minutes) {
398
- if ($Minutes -eq 300) { return "5h" }
399
- if ($Minutes -eq 10080) { return "7d" }
400
- if (-not $Minutes) { return "?" }
401
- if (($Minutes % 1440) -eq 0) { return "$($Minutes / 1440)d" }
402
- if (($Minutes % 60) -eq 0) { return "$($Minutes / 60)h" }
403
- return "${Minutes}m"
404
- }
405
-
406
- function Get-Bar([Nullable[int]]$Percent, [int]$Width = 10) {
407
- $unknown = [string][char]0x2500
408
- $fullBlock = [string][char]0x2588
409
- $emptyBlock = [string][char]0x2591
410
- if ($null -eq $Percent) { return $unknown * $Width }
411
- # Whole cells only, matching bar() in ai-battery.js: partial blocks read as
412
- # a hole in the bar and render inconsistently across fonts.
413
- $clamped = [math]::Max(0, [math]::Min(100, $Percent))
414
- $full = [int][math]::Round(($clamped / 100.0) * $Width)
415
- if ($clamped -gt 0 -and $full -eq 0) { $full = 1 }
416
- return ($fullBlock * $full) + ($emptyBlock * ($Width - $full))
417
- }
418
-
419
- function Get-BatteryIcon([Nullable[int]]$Percent) {
420
- return ""
421
- }
422
-
423
- function Get-PercentColor([Nullable[int]]$Percent) {
424
- if ($null -eq $Percent) { return [System.Drawing.Color]::FromArgb(150, 150, 150) }
425
- if ($Percent -le 20) { return [System.Drawing.Color]::FromArgb(255, 92, 92) }
426
- if ($Percent -le 40) { return [System.Drawing.Color]::FromArgb(255, 158, 67) }
427
- return [System.Drawing.Color]::FromArgb(80, 220, 120)
428
- }
429
-
430
- function Get-ActivityColor($Result) {
431
- if ($Result -and $Result.running) { return [System.Drawing.Color]::FromArgb(235, 235, 235) }
432
- return [System.Drawing.Color]::FromArgb(145, 145, 145)
433
- }
434
-
435
- function Get-DividerColor {
436
- return [System.Drawing.Color]::FromArgb(132, 132, 132)
437
- }
438
-
439
- function Format-Parts($Result, [string]$Name) {
440
- $isRunning = [bool]($Result -and $Result.running)
441
- $textColor = Get-ActivityColor $Result
442
- $displayName = $Name.PadRight(6)
443
- $resetText = ""
444
- $resetValue = ""
445
- $weekText = ""
446
- $weekValue = ""
447
- $extraText = ""
448
-
449
- if (-not $Result -or -not $Result.ok) {
450
- return @{
451
- Prefix = "$displayName "
452
- Icon = Get-BatteryIcon $null
453
- Percent = $null
454
- PercentText = ""
455
- ResetText = ""
456
- ResetValue = ""
457
- WeekText = ""
458
- WeekValue = ""
459
- ExtraText = "?"
460
- Suffix = " ?"
461
- Running = $isRunning
462
- TextColor = $textColor
463
- IconColor = Get-PercentColor $null
464
- }
465
- }
466
-
467
- if ($null -eq $Result.percentRemaining) {
468
- $resetValue = "5h --:--"
469
- $weekValue = "7d ---%"
470
- $divider = [string][char]0x2502
471
- return @{
472
- Prefix = "$displayName "
473
- Icon = Get-BatteryIcon $null
474
- Percent = $null
475
- PercentText = "--"
476
- ResetText = $resetValue
477
- ResetValue = $resetValue
478
- WeekText = $weekValue
479
- WeekValue = $weekValue
480
- ExtraText = ""
481
- Suffix = " $divider $resetValue $divider $weekValue"
482
- Running = $isRunning
483
- TextColor = $textColor
484
- IconColor = Get-PercentColor $null
485
- }
486
- }
487
-
488
- $divider = [string][char]0x2502
489
- if ($Result.primary) {
490
- $resetWindow = Get-WindowText $Result.primary.windowMinutes
491
- $resetValue = "$resetWindow $(Get-ResetClock $Result.primary)".PadRight(8)
492
- $resetText = $resetValue
493
- }
494
- if ($Result.secondary) {
495
- $weekWindow = Get-WindowText $Result.secondary.windowMinutes
496
- # Space plus a thin space (U+2009): a single space reads slightly tighter
497
- # here than the "5h <time>" gap because the digits hug their left edge,
498
- # while a full double space looks padded. The label keeps a fixed width,
499
- # so the HUD does not resize when the digit count changes.
500
- $weekValue = "$weekWindow $([char]0x2009)$([int]$Result.secondary.remainingPercent)%"
501
- $weekText = $weekValue
502
- }
503
- $percentText = "$($Result.percentRemaining)"
504
- $suffix = ""
505
- if ($resetText) {
506
- $suffix += " $divider " + $resetText
507
- }
508
- if ($weekText) {
509
- $suffix += " $divider " + $weekText
510
- }
511
- return @{
512
- Prefix = "$displayName "
513
- Icon = Get-BatteryIcon $Result.percentRemaining
514
- Percent = $Result.percentRemaining
515
- PercentText = $percentText
516
- ResetText = $resetText
517
- ResetValue = $resetValue
518
- WeekText = $weekText
519
- WeekValue = $weekValue
520
- ExtraText = ""
521
- Suffix = $suffix
522
- Running = $isRunning
523
- TextColor = $textColor
524
- IconColor = Get-PercentColor $Result.percentRemaining
525
- }
526
- }
527
-
528
- function Get-Provider($Snapshot, [string]$Name) {
529
- return @($Snapshot.results | Where-Object { $_.provider -eq $Name })[0]
530
- }
531
-
532
- function Copy-MissingProperty($Target, $Source, [string]$Name) {
533
- if (-not $Target -or -not $Source) { return }
534
- if ($null -eq $Target.$Name -and $null -ne $Source.$Name) {
535
- $Target | Add-Member -NotePropertyName $Name -NotePropertyValue $Source.$Name -Force
536
- }
537
- }
538
-
539
- function Merge-HudSnapshot($Snapshot, $CachedSnapshot) {
540
- if (-not $Snapshot -or -not $Snapshot.results) { return $CachedSnapshot }
541
- $Snapshot.results = @($Snapshot.results)
542
- $nowUtc = [datetime]::UtcNow
543
-
544
- for ($i = 0; $i -lt $Snapshot.results.Count; $i += 1) {
545
- $current = $Snapshot.results[$i]
546
- if (-not $current -or -not $current.provider) { continue }
547
-
548
- $usable = [bool]$current.ok -and $null -ne $current.percentRemaining
549
- if ($usable) {
550
- $current | Add-Member -NotePropertyName "hudCachedAt" -NotePropertyValue $nowUtc.ToString("o") -Force
551
- }
552
-
553
- $cached = $null
554
- if ($CachedSnapshot) { $cached = Get-Provider $CachedSnapshot $current.provider }
555
- if (-not $cached -or -not $cached.ok -or $null -eq $cached.percentRemaining) { continue }
556
-
557
- if ($usable) {
558
- Copy-MissingProperty $current $cached "secondary"
559
- continue
560
- }
561
-
562
- # A transient read failure or a fallback row would flash "?"; keep the
563
- # last good reading instead, as long as it is reasonably recent.
564
- $cachedAt = $cached.hudCachedAt
565
- if (-not $cachedAt) { $cachedAt = $CachedSnapshot.generatedAt }
566
- $ageSeconds = $null
567
- try {
568
- $ageSeconds = ($nowUtc - ([datetime]$cachedAt).ToUniversalTime()).TotalSeconds
569
- } catch {
570
- $ageSeconds = $null
571
- }
572
- if ($null -eq $ageSeconds -or $ageSeconds -lt -60 -or $ageSeconds -gt 1800) { continue }
573
-
574
- $replacement = $cached | Select-Object *
575
- if ($null -ne $current.running) {
576
- $replacement | Add-Member -NotePropertyName "running" -NotePropertyValue $current.running -Force
577
- }
578
- $Snapshot.results[$i] = $replacement
579
- }
580
-
581
- return $Snapshot
582
- }
583
-
584
- function ConvertTo-HudTexts($Snapshot) {
585
- $codex = Get-Provider $Snapshot "codex"
586
- $claude = Get-Provider $Snapshot "claude"
587
- $codexVisible = $null -ne $codex
588
- $claudeVisible = $null -ne $claude
589
- return @{
590
- Codex = $(if ($codexVisible) { Format-Parts $codex "Codex" } else { $null })
591
- Claude = $(if ($claudeVisible) { Format-Parts $claude "Claude" } else { $null })
592
- CodexResult = $codex
593
- ClaudeResult = $claude
594
- CodexVisible = $codexVisible
595
- ClaudeVisible = $claudeVisible
596
- }
597
- }
598
-
599
- function Get-Texts {
600
- $cachedSnapshot = Read-HudSnapshot
601
- if ($script:initialHudSnapshot) {
602
- $snapshot = Merge-HudSnapshot $script:initialHudSnapshot $cachedSnapshot
603
- $script:initialHudSnapshot = $null
604
- } else {
605
- try {
606
- $snapshot = Merge-HudSnapshot (Invoke-AiBatteryJson) $cachedSnapshot
607
- } catch {
608
- if ($cachedSnapshot) {
609
- $snapshot = $cachedSnapshot
610
- } else {
611
- throw
612
- }
613
- }
614
- }
615
- Write-HudSnapshot $snapshot
616
- return ConvertTo-HudTexts $snapshot
617
- }
618
-
619
- $script:latestSnapshot = $null
620
- $script:fetchPowerShell = $null
621
- $script:fetchHandle = $null
622
- $script:lastFetchStartUtc = [datetime]::MinValue
623
- $script:weeklyRetryCount = 0
624
-
625
- function Start-SnapshotFetch {
626
- if ($script:fetchPowerShell) { return }
627
- $ps = [powershell]::Create()
628
- $null = $ps.AddScript({
629
- param($Command, $UseWslShell)
630
- try {
369
+
370
+ function Get-DurationText([Nullable[int]]$Seconds) {
371
+ if ($null -eq $Seconds) { return "?" }
372
+ if ($Seconds -le 0) { return "now" }
373
+ $minutes = [math]::Floor($Seconds / 60)
374
+ if ($minutes -lt 60) { return "${minutes}m" }
375
+ $hours = [math]::Floor($minutes / 60)
376
+ $restMinutes = $minutes % 60
377
+ if ($hours -lt 48) {
378
+ if ($restMinutes -gt 0) { return "${hours}h${restMinutes}m" }
379
+ return "${hours}h"
380
+ }
381
+ $days = [math]::Floor($hours / 24)
382
+ $restHours = $hours % 24
383
+ if ($restHours -gt 0) { return "${days}d${restHours}h" }
384
+ return "${days}d"
385
+ }
386
+
387
+ function Get-ResetClock($Limit) {
388
+ if (-not $Limit -or -not $Limit.resetsAt) { return "--:--" }
389
+ if ($Limit.resetPassed) { return "--:--" }
390
+ try {
391
+ return ([datetime]$Limit.resetsAt).ToLocalTime().ToString("HH:mm")
392
+ } catch {
393
+ return "--:--"
394
+ }
395
+ }
396
+
397
+ function Get-WindowText($Minutes) {
398
+ if ($Minutes -eq 300) { return "5h" }
399
+ if ($Minutes -eq 10080) { return "7d" }
400
+ if (-not $Minutes) { return "?" }
401
+ if (($Minutes % 1440) -eq 0) { return "$($Minutes / 1440)d" }
402
+ if (($Minutes % 60) -eq 0) { return "$($Minutes / 60)h" }
403
+ return "${Minutes}m"
404
+ }
405
+
406
+ function Get-Bar([Nullable[int]]$Percent, [int]$Width = 10) {
407
+ $unknown = [string][char]0x2500
408
+ $fullBlock = [string][char]0x2588
409
+ $emptyBlock = [string][char]0x2591
410
+ if ($null -eq $Percent) { return $unknown * $Width }
411
+ # Whole cells only, matching bar() in ai-battery.js: partial blocks read as
412
+ # a hole in the bar and render inconsistently across fonts.
413
+ $clamped = [math]::Max(0, [math]::Min(100, $Percent))
414
+ $full = [int][math]::Round(($clamped / 100.0) * $Width)
415
+ if ($clamped -gt 0 -and $full -eq 0) { $full = 1 }
416
+ return ($fullBlock * $full) + ($emptyBlock * ($Width - $full))
417
+ }
418
+
419
+ function Get-BatteryIcon([Nullable[int]]$Percent) {
420
+ return ""
421
+ }
422
+
423
+ function Get-PercentColor([Nullable[int]]$Percent) {
424
+ if ($null -eq $Percent) { return [System.Drawing.Color]::FromArgb(150, 150, 150) }
425
+ if ($Percent -le 20) { return [System.Drawing.Color]::FromArgb(255, 92, 92) }
426
+ if ($Percent -le 40) { return [System.Drawing.Color]::FromArgb(255, 158, 67) }
427
+ return [System.Drawing.Color]::FromArgb(80, 220, 120)
428
+ }
429
+
430
+ function Get-ActivityColor($Result) {
431
+ if ($Result -and $Result.running) { return [System.Drawing.Color]::FromArgb(235, 235, 235) }
432
+ return [System.Drawing.Color]::FromArgb(145, 145, 145)
433
+ }
434
+
435
+ function Get-DividerColor {
436
+ return [System.Drawing.Color]::FromArgb(132, 132, 132)
437
+ }
438
+
439
+ function Format-Parts($Result, [string]$Name) {
440
+ $isRunning = [bool]($Result -and $Result.running)
441
+ $textColor = Get-ActivityColor $Result
442
+ $displayName = $Name.PadRight(6)
443
+ $resetText = ""
444
+ $resetValue = ""
445
+ $weekText = ""
446
+ $weekValue = ""
447
+ $extraText = ""
448
+
449
+ if (-not $Result -or -not $Result.ok) {
450
+ return @{
451
+ Prefix = "$displayName "
452
+ Icon = Get-BatteryIcon $null
453
+ Percent = $null
454
+ PercentText = ""
455
+ ResetText = ""
456
+ ResetValue = ""
457
+ WeekText = ""
458
+ WeekValue = ""
459
+ ExtraText = "?"
460
+ Suffix = " ?"
461
+ Running = $isRunning
462
+ TextColor = $textColor
463
+ IconColor = Get-PercentColor $null
464
+ }
465
+ }
466
+
467
+ if ($null -eq $Result.percentRemaining) {
468
+ $resetValue = "5h --:--"
469
+ $weekValue = "7d ---%"
470
+ $divider = [string][char]0x2502
471
+ return @{
472
+ Prefix = "$displayName "
473
+ Icon = Get-BatteryIcon $null
474
+ Percent = $null
475
+ PercentText = "--"
476
+ ResetText = $resetValue
477
+ ResetValue = $resetValue
478
+ WeekText = $weekValue
479
+ WeekValue = $weekValue
480
+ ExtraText = ""
481
+ Suffix = " $divider $resetValue $divider $weekValue"
482
+ Running = $isRunning
483
+ TextColor = $textColor
484
+ IconColor = Get-PercentColor $null
485
+ }
486
+ }
487
+
488
+ $divider = [string][char]0x2502
489
+ if ($Result.primary) {
490
+ $resetWindow = Get-WindowText $Result.primary.windowMinutes
491
+ $resetValue = "$resetWindow $(Get-ResetClock $Result.primary)".PadRight(8)
492
+ $resetText = $resetValue
493
+ }
494
+ if ($Result.secondary) {
495
+ $weekWindow = Get-WindowText $Result.secondary.windowMinutes
496
+ # Space plus a thin space (U+2009): a single space reads slightly tighter
497
+ # here than the "5h <time>" gap because the digits hug their left edge,
498
+ # while a full double space looks padded. The label keeps a fixed width,
499
+ # so the HUD does not resize when the digit count changes.
500
+ $weekValue = "$weekWindow $([char]0x2009)$([int]$Result.secondary.remainingPercent)%"
501
+ $weekText = $weekValue
502
+ }
503
+ $percentText = "$($Result.percentRemaining)"
504
+ $suffix = ""
505
+ if ($resetText) {
506
+ $suffix += " $divider " + $resetText
507
+ }
508
+ if ($weekText) {
509
+ $suffix += " $divider " + $weekText
510
+ }
511
+ return @{
512
+ Prefix = "$displayName "
513
+ Icon = Get-BatteryIcon $Result.percentRemaining
514
+ Percent = $Result.percentRemaining
515
+ PercentText = $percentText
516
+ ResetText = $resetText
517
+ ResetValue = $resetValue
518
+ WeekText = $weekText
519
+ WeekValue = $weekValue
520
+ ExtraText = ""
521
+ Suffix = $suffix
522
+ Running = $isRunning
523
+ TextColor = $textColor
524
+ IconColor = Get-PercentColor $Result.percentRemaining
525
+ }
526
+ }
527
+
528
+ function Get-Provider($Snapshot, [string]$Name) {
529
+ return @($Snapshot.results | Where-Object { $_.provider -eq $Name })[0]
530
+ }
531
+
532
+ function Copy-MissingProperty($Target, $Source, [string]$Name) {
533
+ if (-not $Target -or -not $Source) { return }
534
+ if ($null -eq $Target.$Name -and $null -ne $Source.$Name) {
535
+ $Target | Add-Member -NotePropertyName $Name -NotePropertyValue $Source.$Name -Force
536
+ }
537
+ }
538
+
539
+ function Merge-HudSnapshot($Snapshot, $CachedSnapshot) {
540
+ if (-not $Snapshot -or -not $Snapshot.results) { return $CachedSnapshot }
541
+ $Snapshot.results = @($Snapshot.results)
542
+ $nowUtc = [datetime]::UtcNow
543
+
544
+ for ($i = 0; $i -lt $Snapshot.results.Count; $i += 1) {
545
+ $current = $Snapshot.results[$i]
546
+ if (-not $current -or -not $current.provider) { continue }
547
+
548
+ $usable = [bool]$current.ok -and $null -ne $current.percentRemaining
549
+ if ($usable) {
550
+ $current | Add-Member -NotePropertyName "hudCachedAt" -NotePropertyValue $nowUtc.ToString("o") -Force
551
+ }
552
+
553
+ $cached = $null
554
+ if ($CachedSnapshot) { $cached = Get-Provider $CachedSnapshot $current.provider }
555
+ if (-not $cached -or -not $cached.ok -or $null -eq $cached.percentRemaining) { continue }
556
+
557
+ if ($usable) {
558
+ Copy-MissingProperty $current $cached "secondary"
559
+ continue
560
+ }
561
+
562
+ # A transient read failure or a fallback row would flash "?"; keep the
563
+ # last good reading instead, as long as it is reasonably recent.
564
+ $cachedAt = $cached.hudCachedAt
565
+ if (-not $cachedAt) { $cachedAt = $CachedSnapshot.generatedAt }
566
+ $ageSeconds = $null
567
+ try {
568
+ $ageSeconds = ($nowUtc - ([datetime]$cachedAt).ToUniversalTime()).TotalSeconds
569
+ } catch {
570
+ $ageSeconds = $null
571
+ }
572
+ if ($null -eq $ageSeconds -or $ageSeconds -lt -60 -or $ageSeconds -gt 1800) { continue }
573
+
574
+ $replacement = $cached | Select-Object *
575
+ if ($null -ne $current.running) {
576
+ $replacement | Add-Member -NotePropertyName "running" -NotePropertyValue $current.running -Force
577
+ }
578
+ $Snapshot.results[$i] = $replacement
579
+ }
580
+
581
+ return $Snapshot
582
+ }
583
+
584
+ function ConvertTo-HudTexts($Snapshot) {
585
+ $codex = Get-Provider $Snapshot "codex"
586
+ $claude = Get-Provider $Snapshot "claude"
587
+ $codexVisible = $null -ne $codex
588
+ $claudeVisible = $null -ne $claude
589
+ return @{
590
+ Codex = $(if ($codexVisible) { Format-Parts $codex "Codex" } else { $null })
591
+ Claude = $(if ($claudeVisible) { Format-Parts $claude "Claude" } else { $null })
592
+ CodexResult = $codex
593
+ ClaudeResult = $claude
594
+ CodexVisible = $codexVisible
595
+ ClaudeVisible = $claudeVisible
596
+ }
597
+ }
598
+
599
+ function Get-Texts {
600
+ $cachedSnapshot = Read-HudSnapshot
601
+ if ($script:initialHudSnapshot) {
602
+ $snapshot = Merge-HudSnapshot $script:initialHudSnapshot $cachedSnapshot
603
+ $script:initialHudSnapshot = $null
604
+ } else {
605
+ try {
606
+ $snapshot = Merge-HudSnapshot (Invoke-AiBatteryJson) $cachedSnapshot
607
+ } catch {
608
+ if ($cachedSnapshot) {
609
+ $snapshot = $cachedSnapshot
610
+ } else {
611
+ throw
612
+ }
613
+ }
614
+ }
615
+ Write-HudSnapshot $snapshot
616
+ return ConvertTo-HudTexts $snapshot
617
+ }
618
+
619
+ $script:latestSnapshot = $null
620
+ $script:fetchPowerShell = $null
621
+ $script:fetchHandle = $null
622
+ $script:lastFetchStartUtc = [datetime]::MinValue
623
+ $script:weeklyRetryCount = 0
624
+
625
+ function Start-SnapshotFetch {
626
+ if ($script:fetchPowerShell) { return }
627
+ $ps = [powershell]::Create()
628
+ $null = $ps.AddScript({
629
+ param($Command, $UseWslShell)
630
+ try {
631
631
  if ($UseWslShell) {
632
632
  $output = & wsl.exe bash -lc "$Command 2>/dev/null"
633
633
  } else {
@@ -641,1457 +641,1457 @@ function Start-SnapshotFetch {
641
641
  }
642
642
  ($output -join "`n").Trim()
643
643
  } catch {
644
- ""
645
- }
646
- }).AddArgument($BatteryCommand).AddArgument([bool]$UseWsl)
647
- $script:fetchHandle = $ps.BeginInvoke()
648
- $script:fetchPowerShell = $ps
649
- $script:lastFetchStartUtc = [datetime]::UtcNow
650
- }
651
-
652
- function Stop-SnapshotFetch {
653
- if (-not $script:fetchPowerShell) { return }
654
- try { $script:fetchPowerShell.Stop() } catch { }
655
- try { $script:fetchPowerShell.Dispose() } catch { }
656
- $script:fetchPowerShell = $null
657
- $script:fetchHandle = $null
658
- }
659
-
660
- function Complete-SnapshotFetch {
661
- if (-not $script:fetchPowerShell -or -not $script:fetchHandle.IsCompleted) { return $null }
662
- $text = ""
663
- try {
664
- $text = (($script:fetchPowerShell.EndInvoke($script:fetchHandle)) -join "`n").Trim()
665
- } catch {
666
- $text = ""
667
- }
668
- try { $script:fetchPowerShell.Dispose() } catch { }
669
- $script:fetchPowerShell = $null
670
- $script:fetchHandle = $null
671
- if (-not $text) { return $null }
672
- try {
673
- return $text | ConvertFrom-Json
674
- } catch {
675
- return $null
676
- }
677
- }
678
-
679
- if ($Once) {
680
- $texts = Get-Texts
681
- if ($texts.CodexVisible) { Write-Output "$($texts.Codex.Prefix)[battery]$($texts.Codex.Suffix)" }
682
- if ($texts.ClaudeVisible) { Write-Output "$($texts.Claude.Prefix)[battery]$($texts.Claude.Suffix)" }
683
- exit 0
684
- }
685
-
686
- Add-Type -AssemblyName System.Windows.Forms
687
- Add-Type -AssemblyName System.Drawing
688
- [System.Windows.Forms.Application]::EnableVisualStyles()
689
-
690
- function Get-LineText($Parts) {
691
- return "$($Parts.Prefix)[battery]$($Parts.Suffix)"
692
- }
693
-
694
- function Limit-Text([string]$Text, [int]$MaxLength) {
695
- if ($Text.Length -le $MaxLength) { return $Text }
696
- return $Text.Substring(0, [math]::Max(0, $MaxLength - 3)) + "..."
697
- }
698
-
699
- function Select-TrayPercent($Texts) {
700
- $items = @()
701
- foreach ($result in @($Texts.CodexResult, $Texts.ClaudeResult)) {
702
- if ($result -and $result.ok -and $null -ne $result.percentRemaining) {
703
- $items += [PSCustomObject]@{
704
- Percent = [int]$result.percentRemaining
705
- Running = [bool]$result.running
706
- }
707
- }
708
- }
709
-
710
- $runningItems = @($items | Where-Object { $_.Running })
711
- if ($runningItems.Count -gt 0) {
712
- return [Nullable[int]](@($runningItems | Sort-Object Percent)[0].Percent)
713
- }
714
- if ($items.Count -gt 0) {
715
- return [Nullable[int]](@($items | Sort-Object Percent)[0].Percent)
716
- }
717
- return $null
718
- }
719
-
720
- function New-ProviderTrayIcon([string]$ProviderLabel, [Nullable[int]]$Percent, [bool]$Running) {
721
- $bitmap = [System.Drawing.Bitmap]::new(32, 32)
722
- $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
723
- $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
724
- $graphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
725
- $graphics.Clear([System.Drawing.Color]::Transparent)
726
-
727
- $outlineColor = [System.Drawing.Color]::FromArgb(232, 232, 232)
728
- $mutedColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
729
- $activeOutlineColor = if ($Running) { $outlineColor } else { $mutedColor }
730
- $fillColor = if ($Running) { Get-PercentColor $Percent } else { $mutedColor }
731
- $textColor = if ($Running) { [System.Drawing.Color]::FromArgb(245, 245, 245) } else { $mutedColor }
732
- $outlinePen = [System.Drawing.Pen]::new($(if ($null -eq $Percent) { $mutedColor } else { $activeOutlineColor }), 1.6)
733
- $fillBrush = [System.Drawing.SolidBrush]::new($fillColor)
734
- $terminalBrush = [System.Drawing.SolidBrush]::new($(if ($null -eq $Percent) { $mutedColor } else { $activeOutlineColor }))
735
- $textBrush = [System.Drawing.SolidBrush]::new($textColor)
736
- $labelFont = [System.Drawing.Font]::new("Segoe UI", 7, [System.Drawing.FontStyle]::Bold)
737
- $percentText = if ($null -eq $Percent) { "--" } else { [string][int]$Percent }
738
- $percentFontSize = if ($percentText.Length -ge 3) { 8.2 } else { 9.2 }
739
- $percentFont = [System.Drawing.Font]::new("Segoe UI", $percentFontSize, [System.Drawing.FontStyle]::Bold)
740
- $centerFormat = [System.Drawing.StringFormat]::new()
741
- $centerFormat.Alignment = [System.Drawing.StringAlignment]::Center
742
- $centerFormat.LineAlignment = [System.Drawing.StringAlignment]::Center
743
-
744
- try {
745
- $graphics.DrawString($ProviderLabel, $labelFont, $textBrush, [System.Drawing.RectangleF]::new(0, -1, 32, 10), $centerFormat)
746
- $graphics.DrawRectangle($outlinePen, 3, 11, 23, 16)
747
- $graphics.FillRectangle($terminalBrush, 27, 16, 3, 6)
748
-
749
- if ($null -eq $Percent) {
750
- $dashPen = [System.Drawing.Pen]::new($mutedColor, 2)
751
- try {
752
- $graphics.DrawLine($dashPen, 8, 19, 21, 19)
753
- } finally {
754
- $dashPen.Dispose()
755
- }
756
- } else {
757
- $clamped = [math]::Max(0, [math]::Min(100, $Percent))
758
- $fillWidth = [math]::Floor(($clamped / 100.0) * 19)
759
- if ($clamped -gt 0 -and $fillWidth -lt 2) { $fillWidth = 2 }
760
- $graphics.FillRectangle($fillBrush, 5, 13, $fillWidth, 12)
761
- }
762
- $graphics.DrawString($percentText, $percentFont, $textBrush, [System.Drawing.RectangleF]::new(4, 11, 22, 16), $centerFormat)
763
- } finally {
764
- $outlinePen.Dispose()
765
- $fillBrush.Dispose()
766
- $terminalBrush.Dispose()
767
- $textBrush.Dispose()
768
- $labelFont.Dispose()
769
- $percentFont.Dispose()
770
- $centerFormat.Dispose()
771
- $graphics.Dispose()
772
- }
773
-
774
- $handle = $bitmap.GetHicon()
775
- $sourceIcon = [System.Drawing.Icon]::FromHandle($handle)
776
- $icon = $sourceIcon.Clone()
777
- $sourceIcon.Dispose()
778
- [AiBatteryNative]::DestroyIcon($handle) | Out-Null
779
- $bitmap.Dispose()
780
- return $icon
781
- }
782
-
783
- function New-SingleBatteryTrayIcon([Nullable[int]]$Percent) {
784
- $bitmap = [System.Drawing.Bitmap]::new(32, 32)
785
- $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
786
- $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
787
- $graphics.Clear([System.Drawing.Color]::Transparent)
788
-
789
- $outlineColor = [System.Drawing.Color]::FromArgb(232, 232, 232)
790
- $mutedColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
791
- $fillColor = Get-PercentColor $Percent
792
- $outlinePen = [System.Drawing.Pen]::new($(if ($null -eq $Percent) { $mutedColor } else { $outlineColor }), 2)
793
- $fillBrush = [System.Drawing.SolidBrush]::new($fillColor)
794
- $terminalBrush = [System.Drawing.SolidBrush]::new($(if ($null -eq $Percent) { $mutedColor } else { $outlineColor }))
795
-
796
- try {
797
- $graphics.DrawRectangle($outlinePen, 4, 9, 21, 14)
798
- $graphics.FillRectangle($terminalBrush, 26, 13, 3, 6)
799
-
800
- if ($null -eq $Percent) {
801
- $dashPen = [System.Drawing.Pen]::new($mutedColor, 2)
802
- try {
803
- $graphics.DrawLine($dashPen, 8, 16, 21, 16)
804
- } finally {
805
- $dashPen.Dispose()
806
- }
807
- } else {
808
- $clamped = [math]::Max(0, [math]::Min(100, $Percent))
809
- $fillWidth = [math]::Floor(($clamped / 100.0) * 17)
810
- if ($clamped -gt 0 -and $fillWidth -lt 2) { $fillWidth = 2 }
811
- $graphics.FillRectangle($fillBrush, 7, 12, $fillWidth, 8)
812
- }
813
- } finally {
814
- $outlinePen.Dispose()
815
- $fillBrush.Dispose()
816
- $terminalBrush.Dispose()
817
- $graphics.Dispose()
818
- }
819
-
820
- $handle = $bitmap.GetHicon()
821
- $sourceIcon = [System.Drawing.Icon]::FromHandle($handle)
822
- $icon = $sourceIcon.Clone()
823
- $sourceIcon.Dispose()
824
- [AiBatteryNative]::DestroyIcon($handle) | Out-Null
825
- $bitmap.Dispose()
826
- return $icon
827
- }
828
-
829
- function New-BatteryImage([Nullable[int]]$Percent, [bool]$Running = $true, [int]$Width = 34, [int]$Height = 16) {
830
- $bitmap = [System.Drawing.Bitmap]::new($Width, $Height)
831
- $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
832
- $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
833
- $graphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
834
- $graphics.Clear([System.Drawing.Color]::Transparent)
835
-
836
- $outlineColor = [System.Drawing.Color]::FromArgb(232, 232, 232)
837
- $mutedColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
838
- $activeOutlineColor = if ($Running) { $outlineColor } else { $mutedColor }
839
- # The fill always keeps its charge color (matching the terminal bar);
840
- # running state is signalled by the outline and text colors instead.
841
- $fillColor = Get-PercentColor $Percent
842
- $outlinePen = [System.Drawing.Pen]::new($(if ($null -eq $Percent) { $mutedColor } else { $activeOutlineColor }), 1.6)
843
- $fillBrush = [System.Drawing.SolidBrush]::new($fillColor)
844
- # A solid dark interior keeps the desktop from bleeding through the empty
845
- # part of the battery, so the percent text stays readable on any wallpaper.
846
- $interiorBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(46, 46, 46))
847
- $terminalBrush = [System.Drawing.SolidBrush]::new($(if ($null -eq $Percent) { $mutedColor } else { $activeOutlineColor }))
848
- $textBrush = [System.Drawing.SolidBrush]::new($(if ($Running) { [System.Drawing.Color]::FromArgb(250, 250, 250) } else { [System.Drawing.Color]::FromArgb(210, 210, 210) }))
849
- $textHaloBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(200, 15, 15, 15))
850
- $fontSize = if ($null -eq $Percent) { 7.8 } elseif ($Percent -ge 100) { 7.2 } else { 8.2 }
851
- $batteryFont = [System.Drawing.Font]::new("Segoe UI", $fontSize, [System.Drawing.FontStyle]::Bold)
852
- $centerFormat = [System.Drawing.StringFormat]::new()
853
- $centerFormat.Alignment = [System.Drawing.StringAlignment]::Center
854
- $centerFormat.LineAlignment = [System.Drawing.StringAlignment]::Center
855
-
856
- try {
857
- $bodyX = 1
858
- $bodyY = 3
859
- $bodyW = $Width - 6
860
- $bodyH = $Height - 6
861
- $capW = 3
862
- $capH = [math]::Max(4, [math]::Floor($bodyH / 2))
863
- $capY = $bodyY + [math]::Floor(($bodyH - $capH) / 2)
864
-
865
- $graphics.FillRectangle($interiorBrush, $bodyX + 1, $bodyY + 1, $bodyW - 1, $bodyH - 1)
866
- $graphics.DrawRectangle($outlinePen, $bodyX, $bodyY, $bodyW, $bodyH)
867
- $graphics.FillRectangle($terminalBrush, $bodyX + $bodyW + 1, $capY, $capW, $capH)
868
-
869
- if ($null -ne $Percent) {
870
- # The "--" text alone marks the unknown state; a dash line under it
871
- # just collides with the halo.
872
- $clamped = [math]::Max(0, [math]::Min(100, $Percent))
873
- $innerW = $bodyW - 5
874
- $fillW = [math]::Floor(($clamped / 100.0) * $innerW)
875
- if ($clamped -gt 0 -and $fillW -lt 2) { $fillW = 2 }
876
- $graphics.FillRectangle($fillBrush, $bodyX + 3, $bodyY + 3, $fillW, $bodyH - 5)
877
- }
878
- $batteryText = if ($null -eq $Percent) { "--" } else { [string][int]$Percent }
879
- $textRect = [System.Drawing.RectangleF]::new($bodyX + 2, $bodyY, $bodyW - 3, $bodyH + 1)
880
- # A one-pixel dark halo keeps the number legible over the green/orange/red
881
- # fill as well as over the dark empty region.
882
- foreach ($shift in @(@(-1, 0), @(1, 0), @(0, -1), @(0, 1))) {
883
- $haloRect = [System.Drawing.RectangleF]::new($textRect.X + $shift[0], $textRect.Y + $shift[1], $textRect.Width, $textRect.Height)
884
- $graphics.DrawString($batteryText, $batteryFont, $textHaloBrush, $haloRect, $centerFormat)
885
- }
886
- $graphics.DrawString($batteryText, $batteryFont, $textBrush, $textRect, $centerFormat)
887
- } finally {
888
- $outlinePen.Dispose()
889
- $fillBrush.Dispose()
890
- $interiorBrush.Dispose()
891
- $terminalBrush.Dispose()
892
- $textBrush.Dispose()
893
- $textHaloBrush.Dispose()
894
- $batteryFont.Dispose()
895
- $centerFormat.Dispose()
896
- $graphics.Dispose()
897
- }
898
-
899
- return $bitmap
900
- }
901
-
902
- function New-StatusMenuLabel($Font, [int]$Width, $Align = [System.Drawing.ContentAlignment]::MiddleLeft) {
903
- $label = New-Object System.Windows.Forms.Label
904
- $label.AutoSize = $false
905
- $label.Width = $Width
906
- $label.Height = 20
907
- $label.Font = $Font
908
- $label.TextAlign = $Align
909
- $label.Margin = [System.Windows.Forms.Padding]::new(0)
910
- $label.BackColor = [System.Drawing.SystemColors]::Menu
911
- return $label
912
- }
913
-
914
- function New-StatusMenuRow($Font) {
915
- $panel = New-Object System.Windows.Forms.FlowLayoutPanel
916
- $panel.Width = 252
917
- $panel.Height = 22
918
- $panel.FlowDirection = [System.Windows.Forms.FlowDirection]::LeftToRight
919
- $panel.WrapContents = $false
920
- $panel.Margin = [System.Windows.Forms.Padding]::new(0)
921
- $panel.Padding = [System.Windows.Forms.Padding]::new(4, 1, 4, 1)
922
- $panel.BackColor = [System.Drawing.SystemColors]::Menu
923
-
924
- $name = New-StatusMenuLabel $Font 44
925
- $icon = New-Object System.Windows.Forms.PictureBox
926
- $icon.Width = 36
927
- $icon.Height = 20
928
- $icon.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
929
- $icon.Margin = [System.Windows.Forms.Padding]::new(0)
930
- $icon.BackColor = [System.Drawing.SystemColors]::Menu
931
- $percent = New-StatusMenuLabel $Font 0 ([System.Drawing.ContentAlignment]::MiddleRight)
932
- $reset = New-StatusMenuLabel $Font 58
933
- $week = New-StatusMenuLabel $Font 50
934
- $extra = New-StatusMenuLabel $Font 58
935
-
936
- foreach ($control in @($name, $icon, $percent, $reset, $week, $extra)) {
937
- $panel.Controls.Add($control) | Out-Null
938
- }
939
-
940
- $rowHost = New-Object System.Windows.Forms.ToolStripControlHost($panel)
941
- $rowHost.AutoSize = $false
942
- $rowHost.Width = $panel.Width
943
- $rowHost.Height = $panel.Height
944
-
945
- return @{
946
- Host = $rowHost
947
- Panel = $panel
948
- Name = $name
949
- Icon = $icon
950
- Percent = $percent
951
- Reset = $reset
952
- Week = $week
953
- Extra = $extra
954
- }
955
- }
956
-
957
- function Set-StatusMenuRow($Row, $Parts) {
958
- $textColor = $Parts.TextColor
959
- $Row.Name.Text = $Parts.Prefix.TrimEnd()
960
- $Row.Percent.Text = $Parts.PercentText
961
- $Row.Reset.Text = $Parts.ResetText
962
- $Row.Week.Text = $Parts.WeekText
963
- $Row.Extra.Text = $Parts.ExtraText
964
-
965
- foreach ($label in @($Row.Name, $Row.Percent, $Row.Reset, $Row.Week, $Row.Extra)) {
966
- $label.ForeColor = $textColor
967
- }
968
-
969
- $oldImage = $Row.Icon.Image
970
- $Row.Icon.Image = New-BatteryImage $Parts.Percent $Parts.Running
971
- if ($oldImage) { $oldImage.Dispose() }
972
- }
973
-
974
- function Dispose-StatusMenuRow($Row) {
975
- if ($Row.Icon.Image) {
976
- $Row.Icon.Image.Dispose()
977
- $Row.Icon.Image = $null
978
- }
979
- }
980
-
981
- if ($Mode -eq "tray") {
982
- $context = [System.Windows.Forms.ApplicationContext]::new()
983
- $trayFont = [System.Drawing.Font]::new("Segoe UI", 9, [System.Drawing.FontStyle]::Regular)
984
- $menu = New-Object System.Windows.Forms.ContextMenuStrip
985
- $menu.Font = $trayFont
986
- $codexRow = New-StatusMenuRow $trayFont
987
- $claudeRow = New-StatusMenuRow $trayFont
988
- $menu.Items.Add($codexRow.Host) | Out-Null
989
- $menu.Items.Add($claudeRow.Host) | Out-Null
990
- $menu.Items.Add("-") | Out-Null
991
- $refreshItem = $menu.Items.Add("Refresh")
992
- $exitItem = $menu.Items.Add("Exit")
993
-
994
- $notifyIcon = New-Object System.Windows.Forms.NotifyIcon
995
- $notifyIcon.ContextMenuStrip = $menu
996
- $notifyIcon.Visible = $true
997
- $notifyIcon.Text = "AI Battery"
998
- $script:currentTrayIcon = $null
999
- $script:lastBalloonText = "AI Battery"
1000
-
1001
- function Set-SingleNotifyIcon($Texts) {
1002
- $trayPercent = Select-TrayPercent $Texts
1003
- $newIcon = New-SingleBatteryTrayIcon $trayPercent
1004
- $oldIcon = $script:currentTrayIcon
1005
- $notifyIcon.Icon = $newIcon
1006
- $script:currentTrayIcon = $newIcon
1007
- if ($oldIcon) { $oldIcon.Dispose() }
1008
-
1009
- $shortParts = @()
1010
- if ($Texts.CodexVisible) {
1011
- $shortParts += $(if ($null -ne $Texts.CodexResult.percentRemaining) { "Codex $($Texts.CodexResult.percentRemaining)%" } else { "Codex --%" })
1012
- }
1013
- if ($Texts.ClaudeVisible) {
1014
- $shortParts += $(if ($null -ne $Texts.ClaudeResult.percentRemaining) { "Claude $($Texts.ClaudeResult.percentRemaining)%" } else { "Claude --%" })
1015
- }
1016
- $notifyIcon.Text = Limit-Text "AI Battery: $($shortParts -join ', ')" 63
1017
- }
1018
-
1019
- function Update-Tray {
1020
- try {
1021
- $texts = Get-Texts
1022
- $codexRow.Host.Visible = $texts.CodexVisible
1023
- $claudeRow.Host.Visible = $texts.ClaudeVisible
1024
- $codexLine = if ($texts.CodexVisible) { Get-LineText $texts.Codex } else { "" }
1025
- $claudeLine = if ($texts.ClaudeVisible) { Get-LineText $texts.Claude } else { "" }
1026
- if ($texts.CodexVisible) { Set-StatusMenuRow $codexRow $texts.Codex }
1027
- if ($texts.ClaudeVisible) { Set-StatusMenuRow $claudeRow $texts.Claude }
1028
-
1029
- Set-SingleNotifyIcon $texts
1030
- $script:lastBalloonText = (@($codexLine, $claudeLine) | Where-Object { $_ }) -join "`n"
1031
- } catch {
1032
- Set-StatusMenuRow $codexRow @{
1033
- Prefix = "Codex "
1034
- Percent = $null
1035
- PercentText = "?"
1036
- ResetText = ""
1037
- WeekText = ""
1038
- ExtraText = "unavailable"
1039
- TextColor = [System.Drawing.Color]::FromArgb(255, 92, 92)
1040
- }
1041
- Set-StatusMenuRow $claudeRow @{
1042
- Prefix = "Claude "
1043
- Percent = $null
1044
- PercentText = "?"
1045
- ResetText = ""
1046
- WeekText = ""
1047
- ExtraText = ""
1048
- TextColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
1049
- }
1050
- $newIcon = New-SingleBatteryTrayIcon $null
1051
- $oldIcon = $script:currentTrayIcon
1052
- $notifyIcon.Icon = $newIcon
1053
- $script:currentTrayIcon = $newIcon
1054
- if ($oldIcon) { $oldIcon.Dispose() }
1055
- $notifyIcon.Text = "AI Battery unavailable"
1056
- $script:lastBalloonText = "AI Battery unavailable"
1057
- }
1058
- }
1059
-
1060
- $refreshItem.add_Click({ Update-Tray })
1061
- $exitItem.add_Click({
1062
- $notifyIcon.Visible = $false
1063
- Dispose-StatusMenuRow $codexRow
1064
- Dispose-StatusMenuRow $claudeRow
1065
- if ($notifyIcon.Icon) { $notifyIcon.Icon.Dispose() }
1066
- $notifyIcon.Dispose()
1067
- $trayFont.Dispose()
1068
- Release-SingleInstance
1069
- $context.ExitThread()
1070
- })
1071
- $openMenu = {
1072
- param($sender, $event)
1073
- if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
1074
- Update-Tray
1075
- $menu.Show([System.Windows.Forms.Cursor]::Position)
1076
- }
1077
- }
1078
- $notifyIcon.add_MouseClick($openMenu)
1079
-
1080
- $timer = New-Object System.Windows.Forms.Timer
1081
- $timer.Interval = [math]::Max(1, $Interval) * 1000
1082
- $timer.add_Tick({ Update-Tray })
1083
- Update-Tray
1084
- $timer.Start()
1085
- Signal-HudReady
1086
- [System.Windows.Forms.Application]::Run($context)
1087
- Release-SingleInstance
1088
- exit 0
1089
- }
1090
-
1091
- $form = New-Object System.Windows.Forms.Form
1092
- $form.Text = "AI Battery"
1093
- $form.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
1094
- $form.Width = $Width
1095
- $form.Height = if ($Mode -eq "floating") { 44 } elseif ($Mode -eq "statusline") { 44 } else { 54 }
1096
- $script:hudTwoRowHeight = $form.Height
1097
- $script:hudOneRowHeight = [math]::Max(20, $form.Height - 18)
1098
- $form.TopMost = $true
1099
- $form.ShowInTaskbar = $false
1100
- $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
1101
- $transparentBackColor = [System.Drawing.Color]::FromArgb(18, 18, 18)
1102
- $form.BackColor = $transparentBackColor
1103
- $form.TransparencyKey = $transparentBackColor
1104
- $form.Opacity = [math]::Max(0.2, [math]::Min(1.0, $Opacity))
1105
-
1106
- $font = [System.Drawing.Font]::new("Segoe UI", $(if ($Mode -eq "statusline") { 8.5 } else { 9 }), [System.Drawing.FontStyle]::Regular)
1107
- $symbolFont = [System.Drawing.Font]::new("Cascadia Mono", $(if ($Mode -eq "statusline") { 11.5 } else { 12 }), [System.Drawing.FontStyle]::Regular)
1108
-
1109
- $panel = New-Object System.Windows.Forms.TableLayoutPanel
1110
- $panel.Dock = [System.Windows.Forms.DockStyle]::Fill
1111
- $panel.RowCount = 2
1112
- $panel.ColumnCount = 1
1113
- $panel.GrowStyle = [System.Windows.Forms.TableLayoutPanelGrowStyle]::FixedSize
1114
- $panel.Padding = if ($Mode -eq "floating" -or $Mode -eq "statusline") {
1115
- [System.Windows.Forms.Padding]::new(6, 4, 2, 3)
1116
- } else {
1117
- [System.Windows.Forms.Padding]::new(10, 7, 10, 6)
1118
- }
1119
- $panel.BackColor = $form.BackColor
1120
- $panel.RowStyles.Add([System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)) | Out-Null
1121
- $panel.RowStyles.Add([System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)) | Out-Null
1122
- $panel.ColumnStyles.Add([System.Windows.Forms.ColumnStyle]::new([System.Windows.Forms.SizeType]::Percent, 100)) | Out-Null
1123
-
1124
- function New-HudRow {
1125
- $row = New-Object System.Windows.Forms.FlowLayoutPanel
1126
- $row.Dock = [System.Windows.Forms.DockStyle]::Fill
1127
- $row.FlowDirection = [System.Windows.Forms.FlowDirection]::LeftToRight
1128
- $row.WrapContents = $false
1129
- $row.Margin = [System.Windows.Forms.Padding]::new(0)
1130
- $row.Padding = [System.Windows.Forms.Padding]::new(0)
1131
- $row.BackColor = $form.BackColor
1132
- return $row
1133
- }
1134
-
1135
- function New-HudLabel([int]$RightMargin = 0) {
1136
- $label = New-Object System.Windows.Forms.Label
1137
- $label.AutoSize = $false
1138
- $label.Width = 0
1139
- $label.Height = 18
1140
- $label.Font = $font
1141
- $label.UseCompatibleTextRendering = $false
1142
- $label.BackColor = $form.BackColor
1143
- $label.Margin = [System.Windows.Forms.Padding]::new(0, 0, $RightMargin, 0)
1144
- $label.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
1145
- return $label
1146
- }
1147
-
1148
- function New-HudIconBox {
1149
- $box = New-Object System.Windows.Forms.PictureBox
1150
- $box.Width = 36
1151
- $box.Height = 18
1152
- $box.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
1153
- $box.BackColor = $form.BackColor
1154
- $box.Margin = [System.Windows.Forms.Padding]::new(0, 0, 2, 0)
1155
- return $box
1156
- }
1157
-
1158
- function New-HudLineIconBox {
1159
- $box = New-Object System.Windows.Forms.PictureBox
1160
- $box.Width = 21
1161
- $box.Height = 18
1162
- $box.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
1163
- $box.BackColor = $form.BackColor
1164
- $box.Margin = [System.Windows.Forms.Padding]::new(3, 0, 0, 0)
1165
- return $box
1166
- }
1167
-
1168
- function New-HudDivider {
1169
- $divider = New-Object System.Windows.Forms.Panel
1170
- $divider.AutoSize = $false
1171
- $divider.Width = 1
1172
- $divider.Height = 12
1173
- $divider.BackColor = Get-DividerColor
1174
- $divider.Margin = [System.Windows.Forms.Padding]::new(4, 3, 4, 3)
1175
- return $divider
1176
- }
1177
-
1178
- $codexRow = New-HudRow
1179
- $claudeRow = New-HudRow
1180
- $codexPrefixLabel = New-HudLabel
1181
- $codexIconLabel = New-HudIconBox
1182
- $codexDivider1 = New-HudDivider
1183
- $codexResetLabel = New-HudLabel
1184
- $codexDivider2 = New-HudDivider
1185
- $codexWeekLabel = New-HudLabel
1186
- $codexExtraLabel = New-HudLabel
1187
- $claudePrefixLabel = New-HudLabel
1188
- $claudeIconLabel = New-HudIconBox
1189
- $claudeDivider1 = New-HudDivider
1190
- $claudeResetLabel = New-HudLabel
1191
- $claudeDivider2 = New-HudDivider
1192
- $claudeWeekLabel = New-HudLabel
1193
- $claudeExtraLabel = New-HudLabel
1194
-
1195
- foreach ($label in @($codexPrefixLabel, $claudePrefixLabel)) {
1196
- $label.AutoSize = $false
1197
- $label.Width = 48
1198
- }
1199
- foreach ($label in @($codexIconLabel, $claudeIconLabel)) {
1200
- $label.Width = 38
1201
- }
1202
-
1203
- $codexHudControls = @($codexPrefixLabel, $codexIconLabel, $codexDivider1, $codexResetLabel, $codexDivider2, $codexWeekLabel, $codexExtraLabel)
1204
- $claudeHudControls = @($claudePrefixLabel, $claudeIconLabel, $claudeDivider1, $claudeResetLabel, $claudeDivider2, $claudeWeekLabel, $claudeExtraLabel)
1205
-
1206
- $menu = New-Object System.Windows.Forms.ContextMenuStrip
1207
- $menu.Font = $font
1208
- $exitItem = $menu.Items.Add("Exit")
1209
- $exitItem.add_Click({ $form.Close() })
1210
- $form.ContextMenuStrip = $menu
1211
- $panel.ContextMenuStrip = $menu
1212
- foreach ($label in $codexHudControls) {
1213
- $label.ContextMenuStrip = $menu
1214
- $codexRow.Controls.Add($label) | Out-Null
1215
- }
1216
- foreach ($label in $claudeHudControls) {
1217
- $label.ContextMenuStrip = $menu
1218
- $claudeRow.Controls.Add($label) | Out-Null
1219
- }
1220
- $codexRow.ContextMenuStrip = $menu
1221
- $claudeRow.ContextMenuStrip = $menu
1222
- $panel.Controls.Add($codexRow, 0, 0) | Out-Null
1223
- $panel.Controls.Add($claudeRow, 0, 1) | Out-Null
1224
- $form.Controls.Add($panel)
1225
-
1226
- $hitForm = $null
1227
- if (-not $ClickThrough) {
1228
- $hitForm = New-Object System.Windows.Forms.Form
1229
- $hitForm.Text = "AI Battery hit area"
1230
- $hitForm.Width = $form.Width
1231
- $hitForm.Height = $form.Height
1232
- $hitForm.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
1233
- $hitForm.ShowInTaskbar = $false
1234
- $hitForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
1235
- $hitForm.BackColor = [System.Drawing.Color]::Black
1236
- $hitForm.Opacity = 0.01
1237
- $hitForm.TopMost = $true
1238
- $hitForm.ContextMenuStrip = $menu
1239
- }
1240
-
1241
- function Sync-HitFormBounds {
1242
- if (-not $hitForm -or $hitForm.IsDisposed) { return }
1243
- $hitForm.Bounds = [System.Drawing.Rectangle]::new($form.Left, $form.Top, $form.Width, $form.Height)
1244
- }
1245
-
1246
- function Show-HitForm {
1247
- if (-not $hitForm -or $hitForm.IsDisposed) { return }
1248
- Sync-HitFormBounds
1249
- if (-not $hitForm.Visible) {
1250
- $hitForm.Show()
1251
- }
1252
- $style = [AiBatteryNative]::GetWindowLong($hitForm.Handle, [AiBatteryNative]::GWL_EXSTYLE)
1253
- $style = $style -bor [AiBatteryNative]::WS_EX_TOOLWINDOW -bor [AiBatteryNative]::WS_EX_NOACTIVATE
1254
- [AiBatteryNative]::SetWindowLong($hitForm.Handle, [AiBatteryNative]::GWL_EXSTYLE, $style) | Out-Null
1255
- }
1256
-
1257
- $dragging = $false
1258
- $dragOffset = [System.Drawing.Point]::new(0, 0)
1259
- $mouseDown = {
1260
- param($sender, $event)
1261
- if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
1262
- $script:dragging = $true
1263
- $screenPoint = $sender.PointToScreen([System.Drawing.Point]::new($event.X, $event.Y))
1264
- $script:dragOffset = [System.Drawing.Point]::new(
1265
- ($screenPoint.X - $form.Location.X),
1266
- ($screenPoint.Y - $form.Location.Y)
1267
- )
1268
- }
1269
- }
1270
- $mouseMove = {
1271
- param($sender, $event)
1272
- if ($script:dragging) {
1273
- $screenPoint = $sender.PointToScreen([System.Drawing.Point]::new($event.X, $event.Y))
1274
- $form.Location = [System.Drawing.Point]::new(($screenPoint.X - $script:dragOffset.X), ($screenPoint.Y - $script:dragOffset.Y))
1275
- Sync-HitFormBounds
1276
- }
1277
- }
1278
- $mouseUp = {
1279
- $script:dragging = $false
1280
- if ($canMove) {
1281
- Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1282
- Write-HudPosition $form.Location
1283
- Ensure-HudTopMost
1284
- }
1285
- }
1286
- $canMove = $Movable -or (($Mode -eq "floating") -and (-not $Locked))
1287
- $script:positionSaveReady = $false
1288
- $script:hudHiddenForFullscreen = $false
1289
-
1290
- function Save-HudPositionIfReady {
1291
- if (-not $canMove -or -not $script:positionSaveReady) { return }
1292
- Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1293
- Write-HudPosition $form.Location
1294
- }
1295
-
1296
- if ($canMove) {
1297
- $dragControls = @($form, $panel, $codexRow, $claudeRow) + $codexHudControls + $claudeHudControls
1298
- if ($hitForm) { $dragControls += $hitForm }
1299
- foreach ($control in $dragControls) {
1300
- $control.add_MouseDown($mouseDown)
1301
- $control.add_MouseMove($mouseMove)
1302
- $control.add_MouseUp($mouseUp)
1303
- }
1304
- }
1305
-
1306
- function Limit-Number([int]$Value, [int]$Min, [int]$Max) {
1307
- if ($Max -lt $Min) { return $Min }
1308
- return [math]::Max($Min, [math]::Min($Max, $Value))
1309
- }
1310
-
1311
- function Set-HudAnchorFromPlacement($Location, [Nullable[int]]$Width, [Nullable[int]]$Height) {
1312
- $placementWidth = if ($null -ne $Width -and $Width -gt 0) { [int]$Width } else { [int]$form.Width }
1313
- $placementHeight = if ($null -ne $Height -and $Height -gt 0) { [int]$Height } else { [int]$form.Height }
1314
- $center = [System.Drawing.Point]::new(
1315
- [int]($Location.X + [math]::Floor($placementWidth / 2)),
1316
- [int]($Location.Y + [math]::Floor($placementHeight / 2))
1317
- )
1318
- $bounds = [System.Windows.Forms.Screen]::FromPoint($center).Bounds
1319
- $leftDistance = [math]::Abs($Location.X - $bounds.Left)
1320
- $rightDistance = [math]::Abs($bounds.Right - ($Location.X + $placementWidth))
1321
- $topDistance = [math]::Abs($Location.Y - $bounds.Top)
1322
- $bottomDistance = [math]::Abs($bounds.Bottom - ($Location.Y + $placementHeight))
1323
-
1324
- $script:hudAnchorX = if ($rightDistance -lt $leftDistance) { "right" } else { "left" }
1325
- $script:hudAnchorY = if ($bottomDistance -lt $topDistance) { "bottom" } else { "top" }
1326
- }
1327
-
1328
- function Set-HudAnchorFromPositionKeyword {
1329
- $script:hudAnchorX = if ($Position -like "*left*") { "left" } else { "right" }
1330
- $script:hudAnchorY = if ($Position -like "top*") { "top" } else { "bottom" }
1331
- }
1332
-
1333
- function Get-WindowRectObject([IntPtr]$Handle) {
1334
- if ($Handle -eq [IntPtr]::Zero) { return $null }
1335
- $rect = New-Object AiBatteryRect
1336
- if (-not [AiBatteryNative]::GetWindowRect($Handle, [ref]$rect)) { return $null }
1337
- return [PSCustomObject]@{
1338
- Left = [int]$rect.Left
1339
- Top = [int]$rect.Top
1340
- Right = [int]$rect.Right
1341
- Bottom = [int]$rect.Bottom
1342
- Width = [int]($rect.Right - $rect.Left)
1343
- Height = [int]($rect.Bottom - $rect.Top)
1344
- }
1345
- }
1346
-
1347
- function Get-MonitorRectObject([IntPtr]$Monitor) {
1348
- if ($Monitor -eq [IntPtr]::Zero) { return $null }
1349
- $info = New-Object AiBatteryMonitorInfo
1350
- $info.CbSize = [System.Runtime.InteropServices.Marshal]::SizeOf($info)
1351
- if (-not [AiBatteryNative]::GetMonitorInfo($Monitor, [ref]$info)) { return $null }
1352
- return [PSCustomObject]@{
1353
- Left = [int]$info.Monitor.Left
1354
- Top = [int]$info.Monitor.Top
1355
- Right = [int]$info.Monitor.Right
1356
- Bottom = [int]$info.Monitor.Bottom
1357
- Width = [int]($info.Monitor.Right - $info.Monitor.Left)
1358
- Height = [int]($info.Monitor.Bottom - $info.Monitor.Top)
1359
- }
1360
- }
1361
-
1362
- function Test-RectCoversMonitor($WindowRect, $MonitorRect) {
1363
- if (-not $WindowRect -or -not $MonitorRect) { return $false }
1364
- $tolerance = 2
1365
- return (
1366
- $WindowRect.Left -le ($MonitorRect.Left + $tolerance) -and
1367
- $WindowRect.Top -le ($MonitorRect.Top + $tolerance) -and
1368
- $WindowRect.Right -ge ($MonitorRect.Right - $tolerance) -and
1369
- $WindowRect.Bottom -ge ($MonitorRect.Bottom - $tolerance)
1370
- )
1371
- }
1372
-
1373
- function Test-RectIsSubstantialOnMonitor($WindowRect, $MonitorRect) {
1374
- if (-not $WindowRect -or -not $MonitorRect) { return $false }
1375
- $left = [math]::Max([int]$WindowRect.Left, [int]$MonitorRect.Left)
1376
- $top = [math]::Max([int]$WindowRect.Top, [int]$MonitorRect.Top)
1377
- $right = [math]::Min([int]$WindowRect.Right, [int]$MonitorRect.Right)
1378
- $bottom = [math]::Min([int]$WindowRect.Bottom, [int]$MonitorRect.Bottom)
1379
- $width = [math]::Max(0, $right - $left)
1380
- $height = [math]::Max(0, $bottom - $top)
1381
- $monitorArea = [math]::Max(1, [int]$MonitorRect.Width * [int]$MonitorRect.Height)
1382
- $windowArea = $width * $height
1383
- return (($windowArea / $monitorArea) -ge 0.20)
1384
- }
1385
-
1386
- function Test-HudWindowHandle([IntPtr]$Handle) {
1387
- if ($Handle -eq [IntPtr]::Zero) { return $false }
1388
- if ($form -and -not $form.IsDisposed -and $Handle -eq $form.Handle) { return $true }
1389
- if ($hitForm -and -not $hitForm.IsDisposed -and $Handle -eq $hitForm.Handle) { return $true }
1390
- return $false
1391
- }
1392
-
1393
- function Get-WindowClassName([IntPtr]$Handle) {
1394
- if ($Handle -eq [IntPtr]::Zero) { return "" }
1395
- $builder = New-Object System.Text.StringBuilder 256
1396
- [AiBatteryNative]::GetClassName($Handle, $builder, $builder.Capacity) | Out-Null
1397
- return $builder.ToString()
1398
- }
1399
-
1400
- function Test-WindowCloaked([IntPtr]$Handle) {
1401
- if ($Handle -eq [IntPtr]::Zero) { return $false }
1402
- $value = 0
1403
- try {
1404
- $hr = [AiBatteryNative]::DwmGetWindowAttribute($Handle, [AiBatteryNative]::DWMWA_CLOAKED, [ref]$value, 4)
1405
- } catch {
1406
- return $false
1407
- }
1408
- if ($hr -ne 0) { return $false }
1409
- return ($value -ne 0)
1410
- }
1411
-
1412
- # Desktop and shell surfaces span the monitor but must never hide the HUD.
1413
- $script:hudSkipWindowClasses = @(
1414
- "Shell_TrayWnd",
1415
- "Shell_SecondaryTrayWnd",
1416
- "NotifyIconOverflowWindow",
1417
- "Progman",
1418
- "WorkerW"
1419
- )
1420
-
1421
- function Test-FullscreenOnHudMonitor {
1422
- if (-not $form -or $form.IsDisposed) { return $false }
1423
- $hudMonitor = [AiBatteryNative]::MonitorFromWindow($form.Handle, [AiBatteryNative]::MONITOR_DEFAULTTONEAREST)
1424
- if ($hudMonitor -eq [IntPtr]::Zero) { return $false }
1425
- $monitorRect = Get-MonitorRectObject $hudMonitor
1426
- if (-not $monitorRect) { return $false }
1427
-
1428
- # Walk the Z-order from the top down. Small transient overlays (volume, IME,
1429
- # Game Bar, browser controls) are ignored so we can still see the fullscreen
1430
- # window beneath them. A substantial normal window stops the search: any
1431
- # fullscreen window below it is not the visible fullscreen surface.
1432
- $handle = [AiBatteryNative]::GetTopWindow([IntPtr]::Zero)
1433
- for ($scanned = 0; $scanned -lt 400 -and $handle -ne [IntPtr]::Zero; $scanned += 1) {
1434
- $next = [AiBatteryNative]::GetWindow($handle, [AiBatteryNative]::GW_HWNDNEXT)
1435
- # Filter cheapest-first: most windows live on another monitor, so skip the
1436
- # DWM cloak and class-name lookups until a window is on the HUD monitor.
1437
- if ((-not (Test-HudWindowHandle $handle)) -and
1438
- [AiBatteryNative]::IsWindowVisible($handle) -and
1439
- ([AiBatteryNative]::MonitorFromWindow($handle, [AiBatteryNative]::MONITOR_DEFAULTTONEAREST) -eq $hudMonitor) -and
1440
- (-not (Test-WindowCloaked $handle)) -and
1441
- ($script:hudSkipWindowClasses -notcontains (Get-WindowClassName $handle))) {
1442
- $windowRect = Get-WindowRectObject $handle
1443
- if ($windowRect -and $windowRect.Width -gt 0 -and $windowRect.Height -gt 0) {
1444
- if (Test-RectCoversMonitor $windowRect $monitorRect) {
1445
- return $true
1446
- }
1447
- if (Test-RectIsSubstantialOnMonitor $windowRect $monitorRect) {
1448
- return $false
1449
- }
1450
- }
1451
- }
1452
- $handle = $next
1453
- }
1454
-
1455
- return $false
1456
- }
1457
-
1458
- function Set-TaskbarPosition {
1459
- $taskbarHandle = [AiBatteryNative]::FindWindow("Shell_TrayWnd", $null)
1460
- if ($taskbarHandle -eq [IntPtr]::Zero) { return $false }
1461
-
1462
- $taskbarRect = Get-WindowRectObject $taskbarHandle
1463
- if (-not $taskbarRect) { return $false }
1464
-
1465
- $trayHandle = [AiBatteryNative]::FindWindowEx($taskbarHandle, [IntPtr]::Zero, "TrayNotifyWnd", $null)
1466
- $trayRect = Get-WindowRectObject $trayHandle
1467
- if (-not $trayRect) {
1468
- $trayRect = [PSCustomObject]@{
1469
- Left = $taskbarRect.Right
1470
- Top = $taskbarRect.Bottom
1471
- Right = $taskbarRect.Right
1472
- Bottom = $taskbarRect.Bottom
1473
- Width = 0
1474
- Height = 0
1475
- }
1476
- }
1477
-
1478
- $screen = [System.Windows.Forms.Screen]::FromHandle($taskbarHandle)
1479
- $bounds = $screen.Bounds
1480
- $margin = 6
1481
- $isHorizontal = $taskbarRect.Width -ge $taskbarRect.Height
1482
-
1483
- if ($isHorizontal) {
1484
- $x = $trayRect.Left - $form.Width - $margin
1485
- $y = $taskbarRect.Top + [math]::Floor(($taskbarRect.Height - $form.Height) / 2)
1486
- } else {
1487
- $isLeft = $taskbarRect.Left -le $bounds.Left
1488
- $x = if ($isLeft) { $taskbarRect.Right + $margin } else { $taskbarRect.Left - $form.Width - $margin }
1489
- $y = $trayRect.Top - $form.Height - $margin
1490
- }
1491
-
1492
- $x = Limit-Number $x ($bounds.Left + $margin) ($bounds.Right - $form.Width - $margin)
1493
- $y = Limit-Number $y ($bounds.Top + $margin) ($bounds.Bottom - $form.Height - $margin)
1494
- $form.Location = [System.Drawing.Point]::new([int]$x, [int]$y)
1495
- Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1496
- return $true
1497
- }
1498
-
1499
- function Get-OnScreenPoint([int]$X, [int]$Y, [int]$W, [int]$H) {
1500
- $rect = [System.Drawing.Rectangle]::new($X, $Y, [math]::Max(1, $W), [math]::Max(1, $H))
1501
- foreach ($screen in [System.Windows.Forms.Screen]::AllScreens) {
1502
- # Compare against the full monitor bounds, not the working area: sitting
1503
- # on top of the taskbar is this HUD's primary use case, and the taskbar
1504
- # band is outside every working area.
1505
- $overlap = [System.Drawing.Rectangle]::Intersect($screen.Bounds, $rect)
1506
- if ($overlap.Width -ge 24 -and $overlap.Height -ge 10) {
1507
- return [System.Drawing.Point]::new($X, $Y)
1508
- }
1509
- }
1510
-
1511
- # The saved spot is no longer on any screen (monitor unplugged or layout
1512
- # changed), so pull the HUD back into the primary working area.
1513
- $area = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea
1514
- $margin = 18
1515
- $newX = Limit-Number $X ($area.Left + $margin) ($area.Right - $W - $margin)
1516
- $newY = Limit-Number $Y ($area.Top + $margin) ($area.Bottom - $H - $margin)
1517
- return [System.Drawing.Point]::new([int]$newX, [int]$newY)
1518
- }
1519
-
1520
- function Set-Position {
1521
- if ($Position -eq "saved") {
1522
- $savedPlacement = Read-HudPlacement
1523
- if ($savedPlacement) {
1524
- if ($null -ne $savedPlacement.Width -and $savedPlacement.Width -gt 0) {
1525
- $form.Width = [int]$savedPlacement.Width
1526
- }
1527
- if ($null -ne $savedPlacement.Height -and $savedPlacement.Height -gt 0) {
1528
- $form.Height = [int]$savedPlacement.Height
1529
- }
1530
- $form.Location = Get-OnScreenPoint ([int]$savedPlacement.X) ([int]$savedPlacement.Y) ([int]$form.Width) ([int]$form.Height)
1531
- Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1532
- return
1533
- }
1534
- }
1535
-
1536
- if ($Position -eq "taskbar") {
1537
- if (Set-TaskbarPosition) { return }
1538
- }
1539
-
1540
- $area = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea
1541
- $margin = if ($Mode -eq "statusline") { 8 } else { 18 }
1542
- $x = if ($Position -like "*left*") {
1543
- $area.Left + $margin
1544
- } elseif ($Position -like "*center*") {
1545
- $area.Left + [math]::Floor(($area.Width - $form.Width) / 2)
1546
- } else {
1547
- $area.Right - $form.Width - $margin
1548
- }
1549
- $y = if ($Position -like "top*") { $area.Top + $margin } else { $area.Bottom - $form.Height - $margin }
1550
- $form.Location = [System.Drawing.Point]::new($x, $y)
1551
- Set-HudAnchorFromPositionKeyword
1552
- }
1553
-
1554
- function Ensure-HudTopMost {
1555
- if (-not $form -or $form.IsDisposed) { return }
1556
- if ($script:hudHiddenForFullscreen) { return }
1557
- if ($hitForm -and -not $hitForm.IsDisposed -and $hitForm.Visible) {
1558
- $hitForm.TopMost = $true
1559
- [AiBatteryNative]::SetWindowPos(
1560
- $hitForm.Handle,
1561
- [AiBatteryNative]::HWND_TOPMOST,
1562
- 0,
1563
- 0,
1564
- 0,
1565
- 0,
1566
- [AiBatteryNative]::SWP_NOMOVE -bor [AiBatteryNative]::SWP_NOSIZE -bor [AiBatteryNative]::SWP_NOACTIVATE -bor [AiBatteryNative]::SWP_SHOWWINDOW
1567
- ) | Out-Null
1568
- }
1569
- $form.TopMost = $true
1570
- [AiBatteryNative]::SetWindowPos(
1571
- $form.Handle,
1572
- [AiBatteryNative]::HWND_TOPMOST,
1573
- 0,
1574
- 0,
1575
- 0,
1576
- 0,
1577
- [AiBatteryNative]::SWP_NOMOVE -bor [AiBatteryNative]::SWP_NOSIZE -bor [AiBatteryNative]::SWP_NOACTIVATE -bor [AiBatteryNative]::SWP_SHOWWINDOW
1578
- ) | Out-Null
1579
- }
1580
-
1581
- function Set-HudHiddenForFullscreen([bool]$Hidden) {
1582
- $script:hudHiddenForFullscreen = $Hidden
1583
- if ($Hidden) {
1584
- if ($hitForm -and -not $hitForm.IsDisposed -and $hitForm.Visible) {
1585
- [AiBatteryNative]::ShowWindow($hitForm.Handle, [AiBatteryNative]::SW_HIDE) | Out-Null
1586
- $hitForm.Hide()
1587
- }
1588
- if ($form -and -not $form.IsDisposed -and $form.Visible) {
1589
- [AiBatteryNative]::ShowWindow($form.Handle, [AiBatteryNative]::SW_HIDE) | Out-Null
1590
- $form.Hide()
1591
- }
1592
- return
1593
- }
1594
-
1595
- if ($form -and -not $form.IsDisposed -and -not $form.Visible) {
1596
- $form.Show()
1597
- [AiBatteryNative]::ShowWindow($form.Handle, [AiBatteryNative]::SW_SHOWNOACTIVATE) | Out-Null
1598
- }
1599
- Show-HitForm
1600
- Sync-HitFormBounds
1601
- }
1602
-
1603
- $script:fullscreenClearCount = 0
1604
-
1605
- function Update-HudVisibilityForFullscreen {
1606
- if (-not $form -or $form.IsDisposed) { return }
1607
- if (Test-FullscreenOnHudMonitor) {
1608
- $script:fullscreenClearCount = 0
1609
- Set-HudHiddenForFullscreen $true
1610
- return
1611
- }
1612
- if ($script:hudHiddenForFullscreen) {
1613
- $script:fullscreenClearCount += 1
1614
- if ($script:fullscreenClearCount -lt 2) { return }
1615
- }
1616
- $script:fullscreenClearCount = 0
1617
- Set-HudHiddenForFullscreen $false
1618
- Ensure-HudTopMost
1619
- }
1620
-
1621
- $script:fullscreenCheckPending = $false
1622
-
1623
- function Request-FullscreenCheck {
1624
- if (-not $form -or $form.IsDisposed) { return }
1625
- if ($form.InvokeRequired) {
1626
- if ($script:fullscreenCheckPending) { return }
1627
- $script:fullscreenCheckPending = $true
1628
- try {
1629
- $form.BeginInvoke([Action]{
1630
- $script:fullscreenCheckPending = $false
1631
- Update-HudVisibilityForFullscreen
1632
- }) | Out-Null
1633
- } catch {
1634
- $script:fullscreenCheckPending = $false
1635
- }
1636
- return
1637
- }
1638
- Update-HudVisibilityForFullscreen
1639
- }
1640
-
1641
- $script:fullscreenEventCallback = $null
1642
- $script:fullscreenEventHooks = @()
1643
-
1644
- function Start-FullscreenEventHooks {
1645
- if ($script:fullscreenEventCallback) { return }
1646
- $script:fullscreenEventCallback = [AiBatteryWinEventDelegate]{
1647
- param($hook, $eventType, $hwnd, $idObject, $idChild, $eventThread, $eventTime)
1648
- if ($idObject -ne [AiBatteryNative]::OBJID_WINDOW) { return }
1649
- Request-FullscreenCheck
1650
- }
1651
-
1652
- $events = @(
1653
- [AiBatteryNative]::EVENT_SYSTEM_FOREGROUND,
1654
- [AiBatteryNative]::EVENT_OBJECT_SHOW,
1655
- [AiBatteryNative]::EVENT_OBJECT_HIDE,
1656
- [AiBatteryNative]::EVENT_OBJECT_REORDER,
1657
- [AiBatteryNative]::EVENT_OBJECT_LOCATIONCHANGE,
1658
- [AiBatteryNative]::EVENT_OBJECT_CLOAKED,
1659
- [AiBatteryNative]::EVENT_OBJECT_UNCLOAKED
1660
- )
1661
- $flags = [AiBatteryNative]::WINEVENT_OUTOFCONTEXT -bor [AiBatteryNative]::WINEVENT_SKIPOWNPROCESS
1662
- foreach ($eventId in $events) {
1663
- try {
1664
- $hook = [AiBatteryNative]::SetWinEventHook($eventId, $eventId, [IntPtr]::Zero, $script:fullscreenEventCallback, 0, 0, $flags)
1665
- if ($hook -ne [IntPtr]::Zero) {
1666
- $script:fullscreenEventHooks += $hook
1667
- }
1668
- } catch {
1669
- # Polling still covers older or restricted Windows environments.
1670
- }
1671
- }
1672
- }
1673
-
1674
- function Stop-FullscreenEventHooks {
1675
- foreach ($hook in $script:fullscreenEventHooks) {
1676
- try {
1677
- [AiBatteryNative]::UnhookWinEvent($hook) | Out-Null
1678
- } catch {
1679
- # The hook may already be gone during shutdown.
1680
- }
1681
- }
1682
- $script:fullscreenEventHooks = @()
1683
- $script:fullscreenEventCallback = $null
1684
- }
1685
-
1686
- function Set-HudBatteryImage($Box, [Nullable[int]]$Percent, [bool]$Running) {
1687
- $oldImage = $Box.Image
1688
- $Box.Image = New-BatteryImage $Percent $Running
1689
- $Box.Visible = $true
1690
- $Box.Tag = $true
1691
- if ($oldImage) { $oldImage.Dispose() }
1692
- }
1693
-
1694
- function New-HudGlyphImage([string]$Kind, [System.Drawing.Color]$Color, [int]$Width = 21, [int]$Height = 18) {
1695
- $bitmap = [System.Drawing.Bitmap]::new($Width, $Height)
1696
- $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
1697
- $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
1698
- $graphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
1699
- $graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
1700
- $graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half
1701
- $graphics.Clear([System.Drawing.Color]::Transparent)
1702
-
1703
- if ($Kind -eq "reset") {
1704
- $pen = [System.Drawing.Pen]::new($Color, 2.1)
1705
- $pen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
1706
- $pen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
1707
- $brush = [System.Drawing.SolidBrush]::new($Color)
1708
- try {
1709
- $arcX = 3.6
1710
- $arcY = 2.5
1711
- $arcW = 13.0
1712
- $arcH = 13.0
1713
- $startAngle = 150.0
1714
- $sweepAngle = 190.0
1715
- $endAngle = ($startAngle + $sweepAngle) * [math]::PI / 180.0
1716
- $centerX = $arcX + ($arcW / 2.0)
1717
- $centerY = $arcY + ($arcH / 2.0)
1718
- $radiusX = $arcW / 2.0
1719
- $radiusY = $arcH / 2.0
1720
-
1721
- $graphics.DrawArc($pen, [single]$arcX, [single]$arcY, [single]$arcW, [single]$arcH, [single]$startAngle, [single]$sweepAngle)
1722
-
1723
- $tipX = $centerX + ($radiusX * [math]::Cos($endAngle))
1724
- $tipY = $centerY + ($radiusY * [math]::Sin($endAngle))
1725
- $dirX = -[math]::Sin($endAngle)
1726
- $dirY = [math]::Cos($endAngle)
1727
- $length = [math]::Sqrt(($dirX * $dirX) + ($dirY * $dirY))
1728
- if ($length -gt 0) {
1729
- $dirX = $dirX / $length
1730
- $dirY = $dirY / $length
1731
- }
1732
- $normalX = -$dirY
1733
- $normalY = $dirX
1734
- $headLength = 4.8
1735
- $headWidth = 3.3
1736
- $baseX = $tipX - ($dirX * $headLength)
1737
- $baseY = $tipY - ($dirY * $headLength)
1738
-
1739
- $points = @(
1740
- [System.Drawing.PointF]::new([single]$tipX, [single]$tipY),
1741
- [System.Drawing.PointF]::new([single]($baseX + ($normalX * $headWidth)), [single]($baseY + ($normalY * $headWidth))),
1742
- [System.Drawing.PointF]::new([single]($baseX - ($normalX * $headWidth)), [single]($baseY - ($normalY * $headWidth)))
1743
- )
1744
- $graphics.FillPolygon($brush, $points)
1745
- } finally {
1746
- $pen.Dispose()
1747
- $brush.Dispose()
1748
- $graphics.Dispose()
1749
- }
1750
- return $bitmap
1751
- }
1752
-
1753
- $sourceSize = 48
1754
- $source = [System.Drawing.Bitmap]::new($sourceSize, $sourceSize)
1755
- $sourceGraphics = [System.Drawing.Graphics]::FromImage($source)
1756
- $sourceGraphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
1757
- $sourceGraphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
1758
- $sourceGraphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half
1759
- $sourceGraphics.Clear([System.Drawing.Color]::Transparent)
1760
-
1761
- $brush = [System.Drawing.SolidBrush]::new($Color)
1762
- $format = [System.Drawing.StringFormat]::new()
1763
- $format.Alignment = [System.Drawing.StringAlignment]::Center
1764
- $format.LineAlignment = [System.Drawing.StringAlignment]::Near
1765
-
1766
- try {
1767
- $glyph = [string][char]0x2466
1768
- $maxIconWidth = 12
1769
- $maxIconHeight = 12
1770
- $sourceGraphics.DrawString(
1771
- $glyph,
1772
- $symbolFont,
1773
- $brush,
1774
- [System.Drawing.RectangleF]::new([single]0, [single]0, [single]$sourceSize, [single]$sourceSize),
1775
- $format
1776
- )
1777
-
1778
- $left = $sourceSize
1779
- $top = $sourceSize
1780
- $right = -1
1781
- $bottom = -1
1782
- for ($y = 0; $y -lt $sourceSize; $y += 1) {
1783
- for ($x = 0; $x -lt $sourceSize; $x += 1) {
1784
- if ($source.GetPixel($x, $y).A -gt 0) {
1785
- if ($x -lt $left) { $left = $x }
1786
- if ($x -gt $right) { $right = $x }
1787
- if ($y -lt $top) { $top = $y }
1788
- if ($y -gt $bottom) { $bottom = $y }
1789
- }
1790
- }
1791
- }
1792
-
1793
- if ($right -ge $left -and $bottom -ge $top) {
1794
- $sourceRect = [System.Drawing.Rectangle]::new($left, $top, ($right - $left + 1), ($bottom - $top + 1))
1795
- $scale = [math]::Min(1.0, [math]::Min(($maxIconWidth / [double]$sourceRect.Width), ($maxIconHeight / [double]$sourceRect.Height)))
1796
- $targetWidth = [math]::Max(1, [int][math]::Round($sourceRect.Width * $scale))
1797
- $targetHeight = [math]::Max(1, [int][math]::Round($sourceRect.Height * $scale))
1798
- $targetX = [math]::Floor(($Width - $targetWidth) / 2)
1799
- $targetY = [math]::Floor(($Height - $targetHeight) / 2)
1800
- $targetRect = [System.Drawing.Rectangle]::new([int]$targetX, [int]$targetY, $targetWidth, $targetHeight)
1801
- $graphics.DrawImage($source, $targetRect, $sourceRect, [System.Drawing.GraphicsUnit]::Pixel)
1802
- }
1803
- } finally {
1804
- $brush.Dispose()
1805
- $format.Dispose()
1806
- $sourceGraphics.Dispose()
1807
- $source.Dispose()
1808
- $graphics.Dispose()
1809
- }
1810
-
1811
- return $bitmap
1812
- }
1813
-
1814
- function Set-HudLineIconImage($Box, [string]$Kind, [string]$Value, [System.Drawing.Color]$Color) {
1815
- $oldImage = $Box.Image
1816
- if ([string]::IsNullOrWhiteSpace($Value)) {
1817
- $Box.Image = $null
1818
- $Box.Visible = $false
1819
- } else {
1820
- $Box.Image = New-HudGlyphImage $Kind $Color
1821
- $Box.Visible = $true
1822
- }
1823
- if ($oldImage) { $oldImage.Dispose() }
1824
- }
1825
-
1826
- function Set-HudMetricLabel($Label, [string]$Value, [System.Drawing.Color]$Color, [Nullable[int]]$FixedWidth = $null) {
1827
- $Label.Text = $Value
1828
- $Label.ForeColor = $Color
1829
- if ([string]::IsNullOrWhiteSpace($Value)) {
1830
- $Label.Width = 0
1831
- $Label.Visible = $false
1832
- $Label.Tag = $false
1833
- } else {
1834
- $Label.Width = if ($null -ne $FixedWidth -and $FixedWidth -gt 0) { [int]$FixedWidth } else { (Get-LabelTextWidth $Label) + 1 }
1835
- $Label.Visible = $true
1836
- $Label.Tag = $true
1837
- }
1838
- }
1839
-
1840
- function Set-HudDivider($Divider, [string]$Value) {
1841
- if ([string]::IsNullOrWhiteSpace($Value)) {
1842
- $Divider.Visible = $false
1843
- $Divider.Width = 0
1844
- $Divider.Tag = $false
1845
- } else {
1846
- $Divider.Visible = $true
1847
- $Divider.Width = 1
1848
- $Divider.Tag = $true
1849
- }
1850
- }
1851
-
1852
- function Set-HudParts($Parts, $PrefixLabel, $BatteryBox, $Divider1, $ResetLabel, $Divider2, $WeekLabel, $ExtraLabel) {
1853
- $PrefixLabel.Text = $Parts.Prefix
1854
- $PrefixLabel.ForeColor = $Parts.TextColor
1855
- $PrefixLabel.Width = 48
1856
- $PrefixLabel.Visible = $true
1857
- $PrefixLabel.Tag = $true
1858
- Set-HudBatteryImage $BatteryBox $Parts.Percent $Parts.Running
1859
- Set-HudDivider $Divider1 $Parts.ResetValue
1860
- Set-HudMetricLabel $ResetLabel $Parts.ResetValue $Parts.TextColor 52
1861
- Set-HudDivider $Divider2 $Parts.WeekValue
1862
- Set-HudMetricLabel $WeekLabel $Parts.WeekValue $Parts.TextColor 52
1863
- Set-HudMetricLabel $ExtraLabel $Parts.ExtraText $Parts.TextColor
1864
- }
1865
-
1866
- function Set-HudControlsVisible($Controls, [bool]$Visible) {
1867
- foreach ($control in $Controls) {
1868
- $control.Visible = $Visible
1869
- $control.Tag = $Visible
1870
- }
1871
- }
1872
-
1873
- function Get-LabelTextWidth($Label) {
1874
- if (-not $Label.Text) { return 0 }
1875
- return [System.Windows.Forms.TextRenderer]::MeasureText(
1876
- $Label.Text,
1877
- $Label.Font,
1878
- [System.Drawing.Size]::new(1000, 1000),
1879
- [System.Windows.Forms.TextFormatFlags]::NoPadding
1880
- ).Width
1881
- }
1882
-
1883
- function Get-ControlLayoutWidth($Control) {
1884
- # Control.Visible reads as $false while the form is still hidden, so track
1885
- # the intended visibility in Tag to keep pre-show layout math correct.
1886
- if ($Control.Tag -ne $true) { return 0 }
1887
- $baseWidth = $Control.Width
1888
- return $baseWidth + $Control.Margin.Left + $Control.Margin.Right
1889
- }
1890
-
1891
- function Get-HudControlsWidth($Controls) {
1892
- $width = 0
1893
- foreach ($control in $Controls) {
1894
- $width += Get-ControlLayoutWidth $control
1895
- }
1896
- return $width
1897
- }
1898
-
1899
- function Resize-HudToContent {
1900
- if ($Mode -eq "tray") { return }
1901
-
1902
- $oldRight = $form.Left + $form.Width
1903
- $oldBottom = $form.Top + $form.Height
1904
- $codexWidth = $(if ($script:codexRowVisible) { Get-HudControlsWidth $codexHudControls } else { 0 })
1905
- $claudeWidth = $(if ($script:claudeRowVisible) { Get-HudControlsWidth $claudeHudControls } else { 0 })
1906
- $contentWidth = [math]::Max($codexWidth, $claudeWidth)
1907
- $desiredWidth = $panel.Padding.Left + $panel.Padding.Right +
1908
- $contentWidth +
1909
- 1
1910
- $desiredWidth = [math]::Max(150, [int][math]::Ceiling($desiredWidth))
1911
-
1912
- $bothRows = $script:codexRowVisible -and $script:claudeRowVisible
1913
- $desiredHeight = [int]$(if ($bothRows) { $script:hudTwoRowHeight } else { $script:hudOneRowHeight })
1914
- if ($bothRows) {
1915
- $panel.RowStyles[0] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)
1916
- $panel.RowStyles[1] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)
1917
- } elseif ($script:claudeRowVisible) {
1918
- $panel.RowStyles[0] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Absolute, 0)
1919
- $panel.RowStyles[1] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 100)
1920
- } else {
1921
- $panel.RowStyles[0] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 100)
1922
- $panel.RowStyles[1] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Absolute, 0)
1923
- }
1924
-
1925
- if (([math]::Abs($form.Width - $desiredWidth) -gt 1) -or ($form.Height -ne $desiredHeight)) {
1926
- $form.Width = $desiredWidth
1927
- $form.Height = $desiredHeight
1928
- $newX = if ($script:hudAnchorX -eq "right") { $oldRight - $form.Width } else { $form.Left }
1929
- $newY = if ($script:hudAnchorY -eq "bottom") { $oldBottom - $form.Height } else { $form.Top }
1930
- $form.Location = [System.Drawing.Point]::new([int]$newX, [int]$newY)
1931
- Sync-HitFormBounds
1932
- Save-HudPositionIfReady
1933
- }
1934
- }
1935
-
1936
- function Show-HudMessage([string]$Message) {
1937
- $codexPrefixLabel.Text = $Message
1938
- $codexPrefixLabel.ForeColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
1939
- $codexPrefixLabel.Width = (Get-LabelTextWidth $codexPrefixLabel) + 1
1940
- $codexPrefixLabel.Visible = $true
1941
- $codexPrefixLabel.Tag = $true
1942
- foreach ($label in @($codexResetLabel, $codexWeekLabel, $codexExtraLabel, $claudePrefixLabel, $claudeResetLabel, $claudeWeekLabel, $claudeExtraLabel)) {
1943
- $label.Text = ""
1944
- $label.Width = 0
1945
- $label.Visible = $false
1946
- $label.Tag = $false
1947
- }
1948
- foreach ($divider in @($codexDivider1, $codexDivider2, $claudeDivider1, $claudeDivider2)) {
1949
- $divider.Visible = $false
1950
- $divider.Width = 0
1951
- $divider.Tag = $false
1952
- }
1953
- Set-HudBatteryImage $codexIconLabel $null $false
1954
- $oldImage = $claudeIconLabel.Image
1955
- $claudeIconLabel.Image = $null
1956
- $claudeIconLabel.Visible = $false
1957
- $claudeIconLabel.Tag = $false
1958
- if ($oldImage) { $oldImage.Dispose() }
1959
- $script:codexRowVisible = $true
1960
- $script:claudeRowVisible = $false
1961
- $codexRow.Visible = $true
1962
- $claudeRow.Visible = $false
1963
- Resize-HudToContent
1964
- }
1965
-
1966
- function Update-HudFromSnapshot($Snapshot) {
1967
- if (-not $Snapshot) {
1968
- Show-HudMessage "AI Battery starting..."
1969
- Update-HudVisibilityForFullscreen
1970
- return
1971
- }
1972
-
1973
- try {
1974
- $texts = ConvertTo-HudTexts $Snapshot
1975
- $script:codexRowVisible = [bool]$texts.CodexVisible
1976
- $script:claudeRowVisible = [bool]$texts.ClaudeVisible
1977
- if ($texts.CodexVisible) {
1978
- $codexRow.Visible = $true
1979
- Set-HudParts $texts.Codex $codexPrefixLabel $codexIconLabel $codexDivider1 $codexResetLabel $codexDivider2 $codexWeekLabel $codexExtraLabel
1980
- } else {
1981
- $codexRow.Visible = $false
1982
- Set-HudControlsVisible $codexHudControls $false
1983
- }
1984
- if ($texts.ClaudeVisible) {
1985
- $claudeRow.Visible = $true
1986
- Set-HudParts $texts.Claude $claudePrefixLabel $claudeIconLabel $claudeDivider1 $claudeResetLabel $claudeDivider2 $claudeWeekLabel $claudeExtraLabel
1987
- } else {
1988
- $claudeRow.Visible = $false
1989
- Set-HudControlsVisible $claudeHudControls $false
1990
- }
1991
- Resize-HudToContent
1992
- } catch {
1993
- Show-HudMessage "AI Battery unavailable"
1994
- }
1995
- Update-HudVisibilityForFullscreen
1996
- }
1997
-
1998
- function Invoke-HudPump {
1999
- # Everything here must return quickly: this runs on the UI thread, and the
2000
- # actual data fetch happens on a background runspace.
2001
- if ($script:fetchPowerShell -and -not $script:fetchHandle.IsCompleted -and
2002
- ([datetime]::UtcNow - $script:lastFetchStartUtc).TotalSeconds -gt 30) {
2003
- Stop-SnapshotFetch
2004
- }
2005
-
2006
- $fresh = Complete-SnapshotFetch
2007
- if ($fresh) {
2008
- $merged = Merge-HudSnapshot $fresh $script:latestSnapshot
2009
- $script:latestSnapshot = $merged
2010
- Write-HudSnapshot $merged
2011
- Update-HudFromSnapshot $merged
2012
-
2013
- $missingWeekly = @($merged.results | Where-Object { $_.ok -and $null -ne $_.percentRemaining -and $null -eq $_.secondary })
2014
- if ($missingWeekly.Count -gt 0 -and $script:weeklyRetryCount -lt 6) {
2015
- $script:weeklyRetryCount += 1
2016
- Start-SnapshotFetch
2017
- return
2018
- }
2019
- $script:weeklyRetryCount = 0
2020
- return
2021
- }
2022
-
2023
- if (-not $script:fetchPowerShell -and
2024
- ([datetime]::UtcNow - $script:lastFetchStartUtc).TotalSeconds -ge [math]::Max(1, $Interval)) {
2025
- Start-SnapshotFetch
2026
- }
2027
- }
2028
-
2029
- $timer = New-Object System.Windows.Forms.Timer
2030
- $timer.Interval = 1000
2031
- $timer.add_Tick({ Invoke-HudPump })
2032
- # WinEvent hooks wake fullscreen checks immediately on foreground/Z-order/show
2033
- # changes. The UI timer is only a fallback for Windows builds or shells that do
2034
- # not deliver every event we subscribe to.
2035
- $topMostTimer = New-Object System.Windows.Forms.Timer
2036
- $topMostTimer.Interval = 150
2037
- $topMostTimer.add_Tick({ Update-HudVisibilityForFullscreen })
2038
- $form.add_FormClosed({
2039
- if ($canMove) {
2040
- Write-HudPosition $form.Location
2041
- }
2042
- $timer.Stop()
2043
- $timer.Dispose()
2044
- $topMostTimer.Stop()
2045
- $topMostTimer.Dispose()
2046
- Stop-FullscreenEventHooks
2047
- Stop-SnapshotFetch
2048
- foreach ($box in @($codexIconLabel, $claudeIconLabel)) {
2049
- if ($box.Image) {
2050
- $box.Image.Dispose()
2051
- $box.Image = $null
2052
- }
2053
- }
2054
- $font.Dispose()
2055
- $symbolFont.Dispose()
2056
- if ($hitForm -and -not $hitForm.IsDisposed) {
2057
- $hitForm.Close()
2058
- $hitForm.Dispose()
2059
- }
2060
- Release-SingleInstance
2061
- })
2062
-
2063
- $form.add_LocationChanged({
2064
- # No position save here: writing the state file on every drag pixel causes
2065
- # visible hitches. MouseUp and Resize-HudToContent persist the placement.
2066
- Sync-HitFormBounds
2067
- })
2068
- $form.add_SizeChanged({ Sync-HitFormBounds })
2069
- $form.add_Shown({
2070
- Show-HitForm
2071
- Update-HudVisibilityForFullscreen
2072
- Signal-HudReady
2073
- })
2074
-
2075
- Set-Position
2076
- $script:positionSaveReady = $true
2077
-
2078
- $diskSnapshot = Read-HudSnapshot
2079
- if ($script:initialHudSnapshot) {
2080
- $script:latestSnapshot = Merge-HudSnapshot $script:initialHudSnapshot $diskSnapshot
2081
- $script:initialHudSnapshot = $null
2082
- Write-HudSnapshot $script:latestSnapshot
2083
- } else {
2084
- $script:latestSnapshot = $diskSnapshot
2085
- }
2086
- Update-HudFromSnapshot $script:latestSnapshot
2087
- Start-SnapshotFetch
2088
- $style = [AiBatteryNative]::GetWindowLong($form.Handle, [AiBatteryNative]::GWL_EXSTYLE)
2089
- $style = $style -bor [AiBatteryNative]::WS_EX_TOOLWINDOW -bor [AiBatteryNative]::WS_EX_NOACTIVATE
2090
- if ($ClickThrough) {
2091
- $style = $style -bor [AiBatteryNative]::WS_EX_TRANSPARENT
2092
- }
2093
- [AiBatteryNative]::SetWindowLong($form.Handle, [AiBatteryNative]::GWL_EXSTYLE, $style) | Out-Null
2094
- $timer.Start()
2095
- Start-FullscreenEventHooks
2096
- $topMostTimer.Start()
2097
- [System.Windows.Forms.Application]::Run($form)
644
+ ""
645
+ }
646
+ }).AddArgument($BatteryCommand).AddArgument([bool]$UseWsl)
647
+ $script:fetchHandle = $ps.BeginInvoke()
648
+ $script:fetchPowerShell = $ps
649
+ $script:lastFetchStartUtc = [datetime]::UtcNow
650
+ }
651
+
652
+ function Stop-SnapshotFetch {
653
+ if (-not $script:fetchPowerShell) { return }
654
+ try { $script:fetchPowerShell.Stop() } catch { }
655
+ try { $script:fetchPowerShell.Dispose() } catch { }
656
+ $script:fetchPowerShell = $null
657
+ $script:fetchHandle = $null
658
+ }
659
+
660
+ function Complete-SnapshotFetch {
661
+ if (-not $script:fetchPowerShell -or -not $script:fetchHandle.IsCompleted) { return $null }
662
+ $text = ""
663
+ try {
664
+ $text = (($script:fetchPowerShell.EndInvoke($script:fetchHandle)) -join "`n").Trim()
665
+ } catch {
666
+ $text = ""
667
+ }
668
+ try { $script:fetchPowerShell.Dispose() } catch { }
669
+ $script:fetchPowerShell = $null
670
+ $script:fetchHandle = $null
671
+ if (-not $text) { return $null }
672
+ try {
673
+ return $text | ConvertFrom-Json
674
+ } catch {
675
+ return $null
676
+ }
677
+ }
678
+
679
+ if ($Once) {
680
+ $texts = Get-Texts
681
+ if ($texts.CodexVisible) { Write-Output "$($texts.Codex.Prefix)[battery]$($texts.Codex.Suffix)" }
682
+ if ($texts.ClaudeVisible) { Write-Output "$($texts.Claude.Prefix)[battery]$($texts.Claude.Suffix)" }
683
+ exit 0
684
+ }
685
+
686
+ Add-Type -AssemblyName System.Windows.Forms
687
+ Add-Type -AssemblyName System.Drawing
688
+ [System.Windows.Forms.Application]::EnableVisualStyles()
689
+
690
+ function Get-LineText($Parts) {
691
+ return "$($Parts.Prefix)[battery]$($Parts.Suffix)"
692
+ }
693
+
694
+ function Limit-Text([string]$Text, [int]$MaxLength) {
695
+ if ($Text.Length -le $MaxLength) { return $Text }
696
+ return $Text.Substring(0, [math]::Max(0, $MaxLength - 3)) + "..."
697
+ }
698
+
699
+ function Select-TrayPercent($Texts) {
700
+ $items = @()
701
+ foreach ($result in @($Texts.CodexResult, $Texts.ClaudeResult)) {
702
+ if ($result -and $result.ok -and $null -ne $result.percentRemaining) {
703
+ $items += [PSCustomObject]@{
704
+ Percent = [int]$result.percentRemaining
705
+ Running = [bool]$result.running
706
+ }
707
+ }
708
+ }
709
+
710
+ $runningItems = @($items | Where-Object { $_.Running })
711
+ if ($runningItems.Count -gt 0) {
712
+ return [Nullable[int]](@($runningItems | Sort-Object Percent)[0].Percent)
713
+ }
714
+ if ($items.Count -gt 0) {
715
+ return [Nullable[int]](@($items | Sort-Object Percent)[0].Percent)
716
+ }
717
+ return $null
718
+ }
719
+
720
+ function New-ProviderTrayIcon([string]$ProviderLabel, [Nullable[int]]$Percent, [bool]$Running) {
721
+ $bitmap = [System.Drawing.Bitmap]::new(32, 32)
722
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
723
+ $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
724
+ $graphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
725
+ $graphics.Clear([System.Drawing.Color]::Transparent)
726
+
727
+ $outlineColor = [System.Drawing.Color]::FromArgb(232, 232, 232)
728
+ $mutedColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
729
+ $activeOutlineColor = if ($Running) { $outlineColor } else { $mutedColor }
730
+ $fillColor = if ($Running) { Get-PercentColor $Percent } else { $mutedColor }
731
+ $textColor = if ($Running) { [System.Drawing.Color]::FromArgb(245, 245, 245) } else { $mutedColor }
732
+ $outlinePen = [System.Drawing.Pen]::new($(if ($null -eq $Percent) { $mutedColor } else { $activeOutlineColor }), 1.6)
733
+ $fillBrush = [System.Drawing.SolidBrush]::new($fillColor)
734
+ $terminalBrush = [System.Drawing.SolidBrush]::new($(if ($null -eq $Percent) { $mutedColor } else { $activeOutlineColor }))
735
+ $textBrush = [System.Drawing.SolidBrush]::new($textColor)
736
+ $labelFont = [System.Drawing.Font]::new("Segoe UI", 7, [System.Drawing.FontStyle]::Bold)
737
+ $percentText = if ($null -eq $Percent) { "--" } else { [string][int]$Percent }
738
+ $percentFontSize = if ($percentText.Length -ge 3) { 8.2 } else { 9.2 }
739
+ $percentFont = [System.Drawing.Font]::new("Segoe UI", $percentFontSize, [System.Drawing.FontStyle]::Bold)
740
+ $centerFormat = [System.Drawing.StringFormat]::new()
741
+ $centerFormat.Alignment = [System.Drawing.StringAlignment]::Center
742
+ $centerFormat.LineAlignment = [System.Drawing.StringAlignment]::Center
743
+
744
+ try {
745
+ $graphics.DrawString($ProviderLabel, $labelFont, $textBrush, [System.Drawing.RectangleF]::new(0, -1, 32, 10), $centerFormat)
746
+ $graphics.DrawRectangle($outlinePen, 3, 11, 23, 16)
747
+ $graphics.FillRectangle($terminalBrush, 27, 16, 3, 6)
748
+
749
+ if ($null -eq $Percent) {
750
+ $dashPen = [System.Drawing.Pen]::new($mutedColor, 2)
751
+ try {
752
+ $graphics.DrawLine($dashPen, 8, 19, 21, 19)
753
+ } finally {
754
+ $dashPen.Dispose()
755
+ }
756
+ } else {
757
+ $clamped = [math]::Max(0, [math]::Min(100, $Percent))
758
+ $fillWidth = [math]::Floor(($clamped / 100.0) * 19)
759
+ if ($clamped -gt 0 -and $fillWidth -lt 2) { $fillWidth = 2 }
760
+ $graphics.FillRectangle($fillBrush, 5, 13, $fillWidth, 12)
761
+ }
762
+ $graphics.DrawString($percentText, $percentFont, $textBrush, [System.Drawing.RectangleF]::new(4, 11, 22, 16), $centerFormat)
763
+ } finally {
764
+ $outlinePen.Dispose()
765
+ $fillBrush.Dispose()
766
+ $terminalBrush.Dispose()
767
+ $textBrush.Dispose()
768
+ $labelFont.Dispose()
769
+ $percentFont.Dispose()
770
+ $centerFormat.Dispose()
771
+ $graphics.Dispose()
772
+ }
773
+
774
+ $handle = $bitmap.GetHicon()
775
+ $sourceIcon = [System.Drawing.Icon]::FromHandle($handle)
776
+ $icon = $sourceIcon.Clone()
777
+ $sourceIcon.Dispose()
778
+ [AiBatteryNative]::DestroyIcon($handle) | Out-Null
779
+ $bitmap.Dispose()
780
+ return $icon
781
+ }
782
+
783
+ function New-SingleBatteryTrayIcon([Nullable[int]]$Percent) {
784
+ $bitmap = [System.Drawing.Bitmap]::new(32, 32)
785
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
786
+ $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
787
+ $graphics.Clear([System.Drawing.Color]::Transparent)
788
+
789
+ $outlineColor = [System.Drawing.Color]::FromArgb(232, 232, 232)
790
+ $mutedColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
791
+ $fillColor = Get-PercentColor $Percent
792
+ $outlinePen = [System.Drawing.Pen]::new($(if ($null -eq $Percent) { $mutedColor } else { $outlineColor }), 2)
793
+ $fillBrush = [System.Drawing.SolidBrush]::new($fillColor)
794
+ $terminalBrush = [System.Drawing.SolidBrush]::new($(if ($null -eq $Percent) { $mutedColor } else { $outlineColor }))
795
+
796
+ try {
797
+ $graphics.DrawRectangle($outlinePen, 4, 9, 21, 14)
798
+ $graphics.FillRectangle($terminalBrush, 26, 13, 3, 6)
799
+
800
+ if ($null -eq $Percent) {
801
+ $dashPen = [System.Drawing.Pen]::new($mutedColor, 2)
802
+ try {
803
+ $graphics.DrawLine($dashPen, 8, 16, 21, 16)
804
+ } finally {
805
+ $dashPen.Dispose()
806
+ }
807
+ } else {
808
+ $clamped = [math]::Max(0, [math]::Min(100, $Percent))
809
+ $fillWidth = [math]::Floor(($clamped / 100.0) * 17)
810
+ if ($clamped -gt 0 -and $fillWidth -lt 2) { $fillWidth = 2 }
811
+ $graphics.FillRectangle($fillBrush, 7, 12, $fillWidth, 8)
812
+ }
813
+ } finally {
814
+ $outlinePen.Dispose()
815
+ $fillBrush.Dispose()
816
+ $terminalBrush.Dispose()
817
+ $graphics.Dispose()
818
+ }
819
+
820
+ $handle = $bitmap.GetHicon()
821
+ $sourceIcon = [System.Drawing.Icon]::FromHandle($handle)
822
+ $icon = $sourceIcon.Clone()
823
+ $sourceIcon.Dispose()
824
+ [AiBatteryNative]::DestroyIcon($handle) | Out-Null
825
+ $bitmap.Dispose()
826
+ return $icon
827
+ }
828
+
829
+ function New-BatteryImage([Nullable[int]]$Percent, [bool]$Running = $true, [int]$Width = 34, [int]$Height = 16) {
830
+ $bitmap = [System.Drawing.Bitmap]::new($Width, $Height)
831
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
832
+ $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
833
+ $graphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
834
+ $graphics.Clear([System.Drawing.Color]::Transparent)
835
+
836
+ $outlineColor = [System.Drawing.Color]::FromArgb(232, 232, 232)
837
+ $mutedColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
838
+ $activeOutlineColor = if ($Running) { $outlineColor } else { $mutedColor }
839
+ # The fill always keeps its charge color (matching the terminal bar);
840
+ # running state is signalled by the outline and text colors instead.
841
+ $fillColor = Get-PercentColor $Percent
842
+ $outlinePen = [System.Drawing.Pen]::new($(if ($null -eq $Percent) { $mutedColor } else { $activeOutlineColor }), 1.6)
843
+ $fillBrush = [System.Drawing.SolidBrush]::new($fillColor)
844
+ # A solid dark interior keeps the desktop from bleeding through the empty
845
+ # part of the battery, so the percent text stays readable on any wallpaper.
846
+ $interiorBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(46, 46, 46))
847
+ $terminalBrush = [System.Drawing.SolidBrush]::new($(if ($null -eq $Percent) { $mutedColor } else { $activeOutlineColor }))
848
+ $textBrush = [System.Drawing.SolidBrush]::new($(if ($Running) { [System.Drawing.Color]::FromArgb(250, 250, 250) } else { [System.Drawing.Color]::FromArgb(210, 210, 210) }))
849
+ $textHaloBrush = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(200, 15, 15, 15))
850
+ $fontSize = if ($null -eq $Percent) { 7.8 } elseif ($Percent -ge 100) { 7.2 } else { 8.2 }
851
+ $batteryFont = [System.Drawing.Font]::new("Segoe UI", $fontSize, [System.Drawing.FontStyle]::Bold)
852
+ $centerFormat = [System.Drawing.StringFormat]::new()
853
+ $centerFormat.Alignment = [System.Drawing.StringAlignment]::Center
854
+ $centerFormat.LineAlignment = [System.Drawing.StringAlignment]::Center
855
+
856
+ try {
857
+ $bodyX = 1
858
+ $bodyY = 3
859
+ $bodyW = $Width - 6
860
+ $bodyH = $Height - 6
861
+ $capW = 3
862
+ $capH = [math]::Max(4, [math]::Floor($bodyH / 2))
863
+ $capY = $bodyY + [math]::Floor(($bodyH - $capH) / 2)
864
+
865
+ $graphics.FillRectangle($interiorBrush, $bodyX + 1, $bodyY + 1, $bodyW - 1, $bodyH - 1)
866
+ $graphics.DrawRectangle($outlinePen, $bodyX, $bodyY, $bodyW, $bodyH)
867
+ $graphics.FillRectangle($terminalBrush, $bodyX + $bodyW + 1, $capY, $capW, $capH)
868
+
869
+ if ($null -ne $Percent) {
870
+ # The "--" text alone marks the unknown state; a dash line under it
871
+ # just collides with the halo.
872
+ $clamped = [math]::Max(0, [math]::Min(100, $Percent))
873
+ $innerW = $bodyW - 5
874
+ $fillW = [math]::Floor(($clamped / 100.0) * $innerW)
875
+ if ($clamped -gt 0 -and $fillW -lt 2) { $fillW = 2 }
876
+ $graphics.FillRectangle($fillBrush, $bodyX + 3, $bodyY + 3, $fillW, $bodyH - 5)
877
+ }
878
+ $batteryText = if ($null -eq $Percent) { "--" } else { [string][int]$Percent }
879
+ $textRect = [System.Drawing.RectangleF]::new($bodyX + 2, $bodyY, $bodyW - 3, $bodyH + 1)
880
+ # A one-pixel dark halo keeps the number legible over the green/orange/red
881
+ # fill as well as over the dark empty region.
882
+ foreach ($shift in @(@(-1, 0), @(1, 0), @(0, -1), @(0, 1))) {
883
+ $haloRect = [System.Drawing.RectangleF]::new($textRect.X + $shift[0], $textRect.Y + $shift[1], $textRect.Width, $textRect.Height)
884
+ $graphics.DrawString($batteryText, $batteryFont, $textHaloBrush, $haloRect, $centerFormat)
885
+ }
886
+ $graphics.DrawString($batteryText, $batteryFont, $textBrush, $textRect, $centerFormat)
887
+ } finally {
888
+ $outlinePen.Dispose()
889
+ $fillBrush.Dispose()
890
+ $interiorBrush.Dispose()
891
+ $terminalBrush.Dispose()
892
+ $textBrush.Dispose()
893
+ $textHaloBrush.Dispose()
894
+ $batteryFont.Dispose()
895
+ $centerFormat.Dispose()
896
+ $graphics.Dispose()
897
+ }
898
+
899
+ return $bitmap
900
+ }
901
+
902
+ function New-StatusMenuLabel($Font, [int]$Width, $Align = [System.Drawing.ContentAlignment]::MiddleLeft) {
903
+ $label = New-Object System.Windows.Forms.Label
904
+ $label.AutoSize = $false
905
+ $label.Width = $Width
906
+ $label.Height = 20
907
+ $label.Font = $Font
908
+ $label.TextAlign = $Align
909
+ $label.Margin = [System.Windows.Forms.Padding]::new(0)
910
+ $label.BackColor = [System.Drawing.SystemColors]::Menu
911
+ return $label
912
+ }
913
+
914
+ function New-StatusMenuRow($Font) {
915
+ $panel = New-Object System.Windows.Forms.FlowLayoutPanel
916
+ $panel.Width = 252
917
+ $panel.Height = 22
918
+ $panel.FlowDirection = [System.Windows.Forms.FlowDirection]::LeftToRight
919
+ $panel.WrapContents = $false
920
+ $panel.Margin = [System.Windows.Forms.Padding]::new(0)
921
+ $panel.Padding = [System.Windows.Forms.Padding]::new(4, 1, 4, 1)
922
+ $panel.BackColor = [System.Drawing.SystemColors]::Menu
923
+
924
+ $name = New-StatusMenuLabel $Font 44
925
+ $icon = New-Object System.Windows.Forms.PictureBox
926
+ $icon.Width = 36
927
+ $icon.Height = 20
928
+ $icon.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
929
+ $icon.Margin = [System.Windows.Forms.Padding]::new(0)
930
+ $icon.BackColor = [System.Drawing.SystemColors]::Menu
931
+ $percent = New-StatusMenuLabel $Font 0 ([System.Drawing.ContentAlignment]::MiddleRight)
932
+ $reset = New-StatusMenuLabel $Font 58
933
+ $week = New-StatusMenuLabel $Font 50
934
+ $extra = New-StatusMenuLabel $Font 58
935
+
936
+ foreach ($control in @($name, $icon, $percent, $reset, $week, $extra)) {
937
+ $panel.Controls.Add($control) | Out-Null
938
+ }
939
+
940
+ $rowHost = New-Object System.Windows.Forms.ToolStripControlHost($panel)
941
+ $rowHost.AutoSize = $false
942
+ $rowHost.Width = $panel.Width
943
+ $rowHost.Height = $panel.Height
944
+
945
+ return @{
946
+ Host = $rowHost
947
+ Panel = $panel
948
+ Name = $name
949
+ Icon = $icon
950
+ Percent = $percent
951
+ Reset = $reset
952
+ Week = $week
953
+ Extra = $extra
954
+ }
955
+ }
956
+
957
+ function Set-StatusMenuRow($Row, $Parts) {
958
+ $textColor = $Parts.TextColor
959
+ $Row.Name.Text = $Parts.Prefix.TrimEnd()
960
+ $Row.Percent.Text = $Parts.PercentText
961
+ $Row.Reset.Text = $Parts.ResetText
962
+ $Row.Week.Text = $Parts.WeekText
963
+ $Row.Extra.Text = $Parts.ExtraText
964
+
965
+ foreach ($label in @($Row.Name, $Row.Percent, $Row.Reset, $Row.Week, $Row.Extra)) {
966
+ $label.ForeColor = $textColor
967
+ }
968
+
969
+ $oldImage = $Row.Icon.Image
970
+ $Row.Icon.Image = New-BatteryImage $Parts.Percent $Parts.Running
971
+ if ($oldImage) { $oldImage.Dispose() }
972
+ }
973
+
974
+ function Dispose-StatusMenuRow($Row) {
975
+ if ($Row.Icon.Image) {
976
+ $Row.Icon.Image.Dispose()
977
+ $Row.Icon.Image = $null
978
+ }
979
+ }
980
+
981
+ if ($Mode -eq "tray") {
982
+ $context = [System.Windows.Forms.ApplicationContext]::new()
983
+ $trayFont = [System.Drawing.Font]::new("Segoe UI", 9, [System.Drawing.FontStyle]::Regular)
984
+ $menu = New-Object System.Windows.Forms.ContextMenuStrip
985
+ $menu.Font = $trayFont
986
+ $codexRow = New-StatusMenuRow $trayFont
987
+ $claudeRow = New-StatusMenuRow $trayFont
988
+ $menu.Items.Add($codexRow.Host) | Out-Null
989
+ $menu.Items.Add($claudeRow.Host) | Out-Null
990
+ $menu.Items.Add("-") | Out-Null
991
+ $refreshItem = $menu.Items.Add("Refresh")
992
+ $exitItem = $menu.Items.Add("Exit")
993
+
994
+ $notifyIcon = New-Object System.Windows.Forms.NotifyIcon
995
+ $notifyIcon.ContextMenuStrip = $menu
996
+ $notifyIcon.Visible = $true
997
+ $notifyIcon.Text = "AI Battery"
998
+ $script:currentTrayIcon = $null
999
+ $script:lastBalloonText = "AI Battery"
1000
+
1001
+ function Set-SingleNotifyIcon($Texts) {
1002
+ $trayPercent = Select-TrayPercent $Texts
1003
+ $newIcon = New-SingleBatteryTrayIcon $trayPercent
1004
+ $oldIcon = $script:currentTrayIcon
1005
+ $notifyIcon.Icon = $newIcon
1006
+ $script:currentTrayIcon = $newIcon
1007
+ if ($oldIcon) { $oldIcon.Dispose() }
1008
+
1009
+ $shortParts = @()
1010
+ if ($Texts.CodexVisible) {
1011
+ $shortParts += $(if ($null -ne $Texts.CodexResult.percentRemaining) { "Codex $($Texts.CodexResult.percentRemaining)%" } else { "Codex --%" })
1012
+ }
1013
+ if ($Texts.ClaudeVisible) {
1014
+ $shortParts += $(if ($null -ne $Texts.ClaudeResult.percentRemaining) { "Claude $($Texts.ClaudeResult.percentRemaining)%" } else { "Claude --%" })
1015
+ }
1016
+ $notifyIcon.Text = Limit-Text "AI Battery: $($shortParts -join ', ')" 63
1017
+ }
1018
+
1019
+ function Update-Tray {
1020
+ try {
1021
+ $texts = Get-Texts
1022
+ $codexRow.Host.Visible = $texts.CodexVisible
1023
+ $claudeRow.Host.Visible = $texts.ClaudeVisible
1024
+ $codexLine = if ($texts.CodexVisible) { Get-LineText $texts.Codex } else { "" }
1025
+ $claudeLine = if ($texts.ClaudeVisible) { Get-LineText $texts.Claude } else { "" }
1026
+ if ($texts.CodexVisible) { Set-StatusMenuRow $codexRow $texts.Codex }
1027
+ if ($texts.ClaudeVisible) { Set-StatusMenuRow $claudeRow $texts.Claude }
1028
+
1029
+ Set-SingleNotifyIcon $texts
1030
+ $script:lastBalloonText = (@($codexLine, $claudeLine) | Where-Object { $_ }) -join "`n"
1031
+ } catch {
1032
+ Set-StatusMenuRow $codexRow @{
1033
+ Prefix = "Codex "
1034
+ Percent = $null
1035
+ PercentText = "?"
1036
+ ResetText = ""
1037
+ WeekText = ""
1038
+ ExtraText = "unavailable"
1039
+ TextColor = [System.Drawing.Color]::FromArgb(255, 92, 92)
1040
+ }
1041
+ Set-StatusMenuRow $claudeRow @{
1042
+ Prefix = "Claude "
1043
+ Percent = $null
1044
+ PercentText = "?"
1045
+ ResetText = ""
1046
+ WeekText = ""
1047
+ ExtraText = ""
1048
+ TextColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
1049
+ }
1050
+ $newIcon = New-SingleBatteryTrayIcon $null
1051
+ $oldIcon = $script:currentTrayIcon
1052
+ $notifyIcon.Icon = $newIcon
1053
+ $script:currentTrayIcon = $newIcon
1054
+ if ($oldIcon) { $oldIcon.Dispose() }
1055
+ $notifyIcon.Text = "AI Battery unavailable"
1056
+ $script:lastBalloonText = "AI Battery unavailable"
1057
+ }
1058
+ }
1059
+
1060
+ $refreshItem.add_Click({ Update-Tray })
1061
+ $exitItem.add_Click({
1062
+ $notifyIcon.Visible = $false
1063
+ Dispose-StatusMenuRow $codexRow
1064
+ Dispose-StatusMenuRow $claudeRow
1065
+ if ($notifyIcon.Icon) { $notifyIcon.Icon.Dispose() }
1066
+ $notifyIcon.Dispose()
1067
+ $trayFont.Dispose()
1068
+ Release-SingleInstance
1069
+ $context.ExitThread()
1070
+ })
1071
+ $openMenu = {
1072
+ param($sender, $event)
1073
+ if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
1074
+ Update-Tray
1075
+ $menu.Show([System.Windows.Forms.Cursor]::Position)
1076
+ }
1077
+ }
1078
+ $notifyIcon.add_MouseClick($openMenu)
1079
+
1080
+ $timer = New-Object System.Windows.Forms.Timer
1081
+ $timer.Interval = [math]::Max(1, $Interval) * 1000
1082
+ $timer.add_Tick({ Update-Tray })
1083
+ Update-Tray
1084
+ $timer.Start()
1085
+ Signal-HudReady
1086
+ [System.Windows.Forms.Application]::Run($context)
1087
+ Release-SingleInstance
1088
+ exit 0
1089
+ }
1090
+
1091
+ $form = New-Object System.Windows.Forms.Form
1092
+ $form.Text = "AI Battery"
1093
+ $form.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
1094
+ $form.Width = $Width
1095
+ $form.Height = if ($Mode -eq "floating") { 44 } elseif ($Mode -eq "statusline") { 44 } else { 54 }
1096
+ $script:hudTwoRowHeight = $form.Height
1097
+ $script:hudOneRowHeight = [math]::Max(20, $form.Height - 18)
1098
+ $form.TopMost = $true
1099
+ $form.ShowInTaskbar = $false
1100
+ $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
1101
+ $transparentBackColor = [System.Drawing.Color]::FromArgb(18, 18, 18)
1102
+ $form.BackColor = $transparentBackColor
1103
+ $form.TransparencyKey = $transparentBackColor
1104
+ $form.Opacity = [math]::Max(0.2, [math]::Min(1.0, $Opacity))
1105
+
1106
+ $font = [System.Drawing.Font]::new("Segoe UI", $(if ($Mode -eq "statusline") { 8.5 } else { 9 }), [System.Drawing.FontStyle]::Regular)
1107
+ $symbolFont = [System.Drawing.Font]::new("Cascadia Mono", $(if ($Mode -eq "statusline") { 11.5 } else { 12 }), [System.Drawing.FontStyle]::Regular)
1108
+
1109
+ $panel = New-Object System.Windows.Forms.TableLayoutPanel
1110
+ $panel.Dock = [System.Windows.Forms.DockStyle]::Fill
1111
+ $panel.RowCount = 2
1112
+ $panel.ColumnCount = 1
1113
+ $panel.GrowStyle = [System.Windows.Forms.TableLayoutPanelGrowStyle]::FixedSize
1114
+ $panel.Padding = if ($Mode -eq "floating" -or $Mode -eq "statusline") {
1115
+ [System.Windows.Forms.Padding]::new(6, 4, 2, 3)
1116
+ } else {
1117
+ [System.Windows.Forms.Padding]::new(10, 7, 10, 6)
1118
+ }
1119
+ $panel.BackColor = $form.BackColor
1120
+ $panel.RowStyles.Add([System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)) | Out-Null
1121
+ $panel.RowStyles.Add([System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)) | Out-Null
1122
+ $panel.ColumnStyles.Add([System.Windows.Forms.ColumnStyle]::new([System.Windows.Forms.SizeType]::Percent, 100)) | Out-Null
1123
+
1124
+ function New-HudRow {
1125
+ $row = New-Object System.Windows.Forms.FlowLayoutPanel
1126
+ $row.Dock = [System.Windows.Forms.DockStyle]::Fill
1127
+ $row.FlowDirection = [System.Windows.Forms.FlowDirection]::LeftToRight
1128
+ $row.WrapContents = $false
1129
+ $row.Margin = [System.Windows.Forms.Padding]::new(0)
1130
+ $row.Padding = [System.Windows.Forms.Padding]::new(0)
1131
+ $row.BackColor = $form.BackColor
1132
+ return $row
1133
+ }
1134
+
1135
+ function New-HudLabel([int]$RightMargin = 0) {
1136
+ $label = New-Object System.Windows.Forms.Label
1137
+ $label.AutoSize = $false
1138
+ $label.Width = 0
1139
+ $label.Height = 18
1140
+ $label.Font = $font
1141
+ $label.UseCompatibleTextRendering = $false
1142
+ $label.BackColor = $form.BackColor
1143
+ $label.Margin = [System.Windows.Forms.Padding]::new(0, 0, $RightMargin, 0)
1144
+ $label.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
1145
+ return $label
1146
+ }
1147
+
1148
+ function New-HudIconBox {
1149
+ $box = New-Object System.Windows.Forms.PictureBox
1150
+ $box.Width = 36
1151
+ $box.Height = 18
1152
+ $box.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
1153
+ $box.BackColor = $form.BackColor
1154
+ $box.Margin = [System.Windows.Forms.Padding]::new(0, 0, 2, 0)
1155
+ return $box
1156
+ }
1157
+
1158
+ function New-HudLineIconBox {
1159
+ $box = New-Object System.Windows.Forms.PictureBox
1160
+ $box.Width = 21
1161
+ $box.Height = 18
1162
+ $box.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
1163
+ $box.BackColor = $form.BackColor
1164
+ $box.Margin = [System.Windows.Forms.Padding]::new(3, 0, 0, 0)
1165
+ return $box
1166
+ }
1167
+
1168
+ function New-HudDivider {
1169
+ $divider = New-Object System.Windows.Forms.Panel
1170
+ $divider.AutoSize = $false
1171
+ $divider.Width = 1
1172
+ $divider.Height = 12
1173
+ $divider.BackColor = Get-DividerColor
1174
+ $divider.Margin = [System.Windows.Forms.Padding]::new(4, 3, 4, 3)
1175
+ return $divider
1176
+ }
1177
+
1178
+ $codexRow = New-HudRow
1179
+ $claudeRow = New-HudRow
1180
+ $codexPrefixLabel = New-HudLabel
1181
+ $codexIconLabel = New-HudIconBox
1182
+ $codexDivider1 = New-HudDivider
1183
+ $codexResetLabel = New-HudLabel
1184
+ $codexDivider2 = New-HudDivider
1185
+ $codexWeekLabel = New-HudLabel
1186
+ $codexExtraLabel = New-HudLabel
1187
+ $claudePrefixLabel = New-HudLabel
1188
+ $claudeIconLabel = New-HudIconBox
1189
+ $claudeDivider1 = New-HudDivider
1190
+ $claudeResetLabel = New-HudLabel
1191
+ $claudeDivider2 = New-HudDivider
1192
+ $claudeWeekLabel = New-HudLabel
1193
+ $claudeExtraLabel = New-HudLabel
1194
+
1195
+ foreach ($label in @($codexPrefixLabel, $claudePrefixLabel)) {
1196
+ $label.AutoSize = $false
1197
+ $label.Width = 48
1198
+ }
1199
+ foreach ($label in @($codexIconLabel, $claudeIconLabel)) {
1200
+ $label.Width = 38
1201
+ }
1202
+
1203
+ $codexHudControls = @($codexPrefixLabel, $codexIconLabel, $codexDivider1, $codexResetLabel, $codexDivider2, $codexWeekLabel, $codexExtraLabel)
1204
+ $claudeHudControls = @($claudePrefixLabel, $claudeIconLabel, $claudeDivider1, $claudeResetLabel, $claudeDivider2, $claudeWeekLabel, $claudeExtraLabel)
1205
+
1206
+ $menu = New-Object System.Windows.Forms.ContextMenuStrip
1207
+ $menu.Font = $font
1208
+ $exitItem = $menu.Items.Add("Exit")
1209
+ $exitItem.add_Click({ $form.Close() })
1210
+ $form.ContextMenuStrip = $menu
1211
+ $panel.ContextMenuStrip = $menu
1212
+ foreach ($label in $codexHudControls) {
1213
+ $label.ContextMenuStrip = $menu
1214
+ $codexRow.Controls.Add($label) | Out-Null
1215
+ }
1216
+ foreach ($label in $claudeHudControls) {
1217
+ $label.ContextMenuStrip = $menu
1218
+ $claudeRow.Controls.Add($label) | Out-Null
1219
+ }
1220
+ $codexRow.ContextMenuStrip = $menu
1221
+ $claudeRow.ContextMenuStrip = $menu
1222
+ $panel.Controls.Add($codexRow, 0, 0) | Out-Null
1223
+ $panel.Controls.Add($claudeRow, 0, 1) | Out-Null
1224
+ $form.Controls.Add($panel)
1225
+
1226
+ $hitForm = $null
1227
+ if (-not $ClickThrough) {
1228
+ $hitForm = New-Object System.Windows.Forms.Form
1229
+ $hitForm.Text = "AI Battery hit area"
1230
+ $hitForm.Width = $form.Width
1231
+ $hitForm.Height = $form.Height
1232
+ $hitForm.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
1233
+ $hitForm.ShowInTaskbar = $false
1234
+ $hitForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
1235
+ $hitForm.BackColor = [System.Drawing.Color]::Black
1236
+ $hitForm.Opacity = 0.01
1237
+ $hitForm.TopMost = $true
1238
+ $hitForm.ContextMenuStrip = $menu
1239
+ }
1240
+
1241
+ function Sync-HitFormBounds {
1242
+ if (-not $hitForm -or $hitForm.IsDisposed) { return }
1243
+ $hitForm.Bounds = [System.Drawing.Rectangle]::new($form.Left, $form.Top, $form.Width, $form.Height)
1244
+ }
1245
+
1246
+ function Show-HitForm {
1247
+ if (-not $hitForm -or $hitForm.IsDisposed) { return }
1248
+ Sync-HitFormBounds
1249
+ if (-not $hitForm.Visible) {
1250
+ $hitForm.Show()
1251
+ }
1252
+ $style = [AiBatteryNative]::GetWindowLong($hitForm.Handle, [AiBatteryNative]::GWL_EXSTYLE)
1253
+ $style = $style -bor [AiBatteryNative]::WS_EX_TOOLWINDOW -bor [AiBatteryNative]::WS_EX_NOACTIVATE
1254
+ [AiBatteryNative]::SetWindowLong($hitForm.Handle, [AiBatteryNative]::GWL_EXSTYLE, $style) | Out-Null
1255
+ }
1256
+
1257
+ $dragging = $false
1258
+ $dragOffset = [System.Drawing.Point]::new(0, 0)
1259
+ $mouseDown = {
1260
+ param($sender, $event)
1261
+ if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
1262
+ $script:dragging = $true
1263
+ $screenPoint = $sender.PointToScreen([System.Drawing.Point]::new($event.X, $event.Y))
1264
+ $script:dragOffset = [System.Drawing.Point]::new(
1265
+ ($screenPoint.X - $form.Location.X),
1266
+ ($screenPoint.Y - $form.Location.Y)
1267
+ )
1268
+ }
1269
+ }
1270
+ $mouseMove = {
1271
+ param($sender, $event)
1272
+ if ($script:dragging) {
1273
+ $screenPoint = $sender.PointToScreen([System.Drawing.Point]::new($event.X, $event.Y))
1274
+ $form.Location = [System.Drawing.Point]::new(($screenPoint.X - $script:dragOffset.X), ($screenPoint.Y - $script:dragOffset.Y))
1275
+ Sync-HitFormBounds
1276
+ }
1277
+ }
1278
+ $mouseUp = {
1279
+ $script:dragging = $false
1280
+ if ($canMove) {
1281
+ Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1282
+ Write-HudPosition $form.Location
1283
+ Ensure-HudTopMost
1284
+ }
1285
+ }
1286
+ $canMove = $Movable -or (($Mode -eq "floating") -and (-not $Locked))
1287
+ $script:positionSaveReady = $false
1288
+ $script:hudHiddenForFullscreen = $false
1289
+
1290
+ function Save-HudPositionIfReady {
1291
+ if (-not $canMove -or -not $script:positionSaveReady) { return }
1292
+ Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1293
+ Write-HudPosition $form.Location
1294
+ }
1295
+
1296
+ if ($canMove) {
1297
+ $dragControls = @($form, $panel, $codexRow, $claudeRow) + $codexHudControls + $claudeHudControls
1298
+ if ($hitForm) { $dragControls += $hitForm }
1299
+ foreach ($control in $dragControls) {
1300
+ $control.add_MouseDown($mouseDown)
1301
+ $control.add_MouseMove($mouseMove)
1302
+ $control.add_MouseUp($mouseUp)
1303
+ }
1304
+ }
1305
+
1306
+ function Limit-Number([int]$Value, [int]$Min, [int]$Max) {
1307
+ if ($Max -lt $Min) { return $Min }
1308
+ return [math]::Max($Min, [math]::Min($Max, $Value))
1309
+ }
1310
+
1311
+ function Set-HudAnchorFromPlacement($Location, [Nullable[int]]$Width, [Nullable[int]]$Height) {
1312
+ $placementWidth = if ($null -ne $Width -and $Width -gt 0) { [int]$Width } else { [int]$form.Width }
1313
+ $placementHeight = if ($null -ne $Height -and $Height -gt 0) { [int]$Height } else { [int]$form.Height }
1314
+ $center = [System.Drawing.Point]::new(
1315
+ [int]($Location.X + [math]::Floor($placementWidth / 2)),
1316
+ [int]($Location.Y + [math]::Floor($placementHeight / 2))
1317
+ )
1318
+ $bounds = [System.Windows.Forms.Screen]::FromPoint($center).Bounds
1319
+ $leftDistance = [math]::Abs($Location.X - $bounds.Left)
1320
+ $rightDistance = [math]::Abs($bounds.Right - ($Location.X + $placementWidth))
1321
+ $topDistance = [math]::Abs($Location.Y - $bounds.Top)
1322
+ $bottomDistance = [math]::Abs($bounds.Bottom - ($Location.Y + $placementHeight))
1323
+
1324
+ $script:hudAnchorX = if ($rightDistance -lt $leftDistance) { "right" } else { "left" }
1325
+ $script:hudAnchorY = if ($bottomDistance -lt $topDistance) { "bottom" } else { "top" }
1326
+ }
1327
+
1328
+ function Set-HudAnchorFromPositionKeyword {
1329
+ $script:hudAnchorX = if ($Position -like "*left*") { "left" } else { "right" }
1330
+ $script:hudAnchorY = if ($Position -like "top*") { "top" } else { "bottom" }
1331
+ }
1332
+
1333
+ function Get-WindowRectObject([IntPtr]$Handle) {
1334
+ if ($Handle -eq [IntPtr]::Zero) { return $null }
1335
+ $rect = New-Object AiBatteryRect
1336
+ if (-not [AiBatteryNative]::GetWindowRect($Handle, [ref]$rect)) { return $null }
1337
+ return [PSCustomObject]@{
1338
+ Left = [int]$rect.Left
1339
+ Top = [int]$rect.Top
1340
+ Right = [int]$rect.Right
1341
+ Bottom = [int]$rect.Bottom
1342
+ Width = [int]($rect.Right - $rect.Left)
1343
+ Height = [int]($rect.Bottom - $rect.Top)
1344
+ }
1345
+ }
1346
+
1347
+ function Get-MonitorRectObject([IntPtr]$Monitor) {
1348
+ if ($Monitor -eq [IntPtr]::Zero) { return $null }
1349
+ $info = New-Object AiBatteryMonitorInfo
1350
+ $info.CbSize = [System.Runtime.InteropServices.Marshal]::SizeOf($info)
1351
+ if (-not [AiBatteryNative]::GetMonitorInfo($Monitor, [ref]$info)) { return $null }
1352
+ return [PSCustomObject]@{
1353
+ Left = [int]$info.Monitor.Left
1354
+ Top = [int]$info.Monitor.Top
1355
+ Right = [int]$info.Monitor.Right
1356
+ Bottom = [int]$info.Monitor.Bottom
1357
+ Width = [int]($info.Monitor.Right - $info.Monitor.Left)
1358
+ Height = [int]($info.Monitor.Bottom - $info.Monitor.Top)
1359
+ }
1360
+ }
1361
+
1362
+ function Test-RectCoversMonitor($WindowRect, $MonitorRect) {
1363
+ if (-not $WindowRect -or -not $MonitorRect) { return $false }
1364
+ $tolerance = 2
1365
+ return (
1366
+ $WindowRect.Left -le ($MonitorRect.Left + $tolerance) -and
1367
+ $WindowRect.Top -le ($MonitorRect.Top + $tolerance) -and
1368
+ $WindowRect.Right -ge ($MonitorRect.Right - $tolerance) -and
1369
+ $WindowRect.Bottom -ge ($MonitorRect.Bottom - $tolerance)
1370
+ )
1371
+ }
1372
+
1373
+ function Test-RectIsSubstantialOnMonitor($WindowRect, $MonitorRect) {
1374
+ if (-not $WindowRect -or -not $MonitorRect) { return $false }
1375
+ $left = [math]::Max([int]$WindowRect.Left, [int]$MonitorRect.Left)
1376
+ $top = [math]::Max([int]$WindowRect.Top, [int]$MonitorRect.Top)
1377
+ $right = [math]::Min([int]$WindowRect.Right, [int]$MonitorRect.Right)
1378
+ $bottom = [math]::Min([int]$WindowRect.Bottom, [int]$MonitorRect.Bottom)
1379
+ $width = [math]::Max(0, $right - $left)
1380
+ $height = [math]::Max(0, $bottom - $top)
1381
+ $monitorArea = [math]::Max(1, [int]$MonitorRect.Width * [int]$MonitorRect.Height)
1382
+ $windowArea = $width * $height
1383
+ return (($windowArea / $monitorArea) -ge 0.20)
1384
+ }
1385
+
1386
+ function Test-HudWindowHandle([IntPtr]$Handle) {
1387
+ if ($Handle -eq [IntPtr]::Zero) { return $false }
1388
+ if ($form -and -not $form.IsDisposed -and $Handle -eq $form.Handle) { return $true }
1389
+ if ($hitForm -and -not $hitForm.IsDisposed -and $Handle -eq $hitForm.Handle) { return $true }
1390
+ return $false
1391
+ }
1392
+
1393
+ function Get-WindowClassName([IntPtr]$Handle) {
1394
+ if ($Handle -eq [IntPtr]::Zero) { return "" }
1395
+ $builder = New-Object System.Text.StringBuilder 256
1396
+ [AiBatteryNative]::GetClassName($Handle, $builder, $builder.Capacity) | Out-Null
1397
+ return $builder.ToString()
1398
+ }
1399
+
1400
+ function Test-WindowCloaked([IntPtr]$Handle) {
1401
+ if ($Handle -eq [IntPtr]::Zero) { return $false }
1402
+ $value = 0
1403
+ try {
1404
+ $hr = [AiBatteryNative]::DwmGetWindowAttribute($Handle, [AiBatteryNative]::DWMWA_CLOAKED, [ref]$value, 4)
1405
+ } catch {
1406
+ return $false
1407
+ }
1408
+ if ($hr -ne 0) { return $false }
1409
+ return ($value -ne 0)
1410
+ }
1411
+
1412
+ # Desktop and shell surfaces span the monitor but must never hide the HUD.
1413
+ $script:hudSkipWindowClasses = @(
1414
+ "Shell_TrayWnd",
1415
+ "Shell_SecondaryTrayWnd",
1416
+ "NotifyIconOverflowWindow",
1417
+ "Progman",
1418
+ "WorkerW"
1419
+ )
1420
+
1421
+ function Test-FullscreenOnHudMonitor {
1422
+ if (-not $form -or $form.IsDisposed) { return $false }
1423
+ $hudMonitor = [AiBatteryNative]::MonitorFromWindow($form.Handle, [AiBatteryNative]::MONITOR_DEFAULTTONEAREST)
1424
+ if ($hudMonitor -eq [IntPtr]::Zero) { return $false }
1425
+ $monitorRect = Get-MonitorRectObject $hudMonitor
1426
+ if (-not $monitorRect) { return $false }
1427
+
1428
+ # Walk the Z-order from the top down. Small transient overlays (volume, IME,
1429
+ # Game Bar, browser controls) are ignored so we can still see the fullscreen
1430
+ # window beneath them. A substantial normal window stops the search: any
1431
+ # fullscreen window below it is not the visible fullscreen surface.
1432
+ $handle = [AiBatteryNative]::GetTopWindow([IntPtr]::Zero)
1433
+ for ($scanned = 0; $scanned -lt 400 -and $handle -ne [IntPtr]::Zero; $scanned += 1) {
1434
+ $next = [AiBatteryNative]::GetWindow($handle, [AiBatteryNative]::GW_HWNDNEXT)
1435
+ # Filter cheapest-first: most windows live on another monitor, so skip the
1436
+ # DWM cloak and class-name lookups until a window is on the HUD monitor.
1437
+ if ((-not (Test-HudWindowHandle $handle)) -and
1438
+ [AiBatteryNative]::IsWindowVisible($handle) -and
1439
+ ([AiBatteryNative]::MonitorFromWindow($handle, [AiBatteryNative]::MONITOR_DEFAULTTONEAREST) -eq $hudMonitor) -and
1440
+ (-not (Test-WindowCloaked $handle)) -and
1441
+ ($script:hudSkipWindowClasses -notcontains (Get-WindowClassName $handle))) {
1442
+ $windowRect = Get-WindowRectObject $handle
1443
+ if ($windowRect -and $windowRect.Width -gt 0 -and $windowRect.Height -gt 0) {
1444
+ if (Test-RectCoversMonitor $windowRect $monitorRect) {
1445
+ return $true
1446
+ }
1447
+ if (Test-RectIsSubstantialOnMonitor $windowRect $monitorRect) {
1448
+ return $false
1449
+ }
1450
+ }
1451
+ }
1452
+ $handle = $next
1453
+ }
1454
+
1455
+ return $false
1456
+ }
1457
+
1458
+ function Set-TaskbarPosition {
1459
+ $taskbarHandle = [AiBatteryNative]::FindWindow("Shell_TrayWnd", $null)
1460
+ if ($taskbarHandle -eq [IntPtr]::Zero) { return $false }
1461
+
1462
+ $taskbarRect = Get-WindowRectObject $taskbarHandle
1463
+ if (-not $taskbarRect) { return $false }
1464
+
1465
+ $trayHandle = [AiBatteryNative]::FindWindowEx($taskbarHandle, [IntPtr]::Zero, "TrayNotifyWnd", $null)
1466
+ $trayRect = Get-WindowRectObject $trayHandle
1467
+ if (-not $trayRect) {
1468
+ $trayRect = [PSCustomObject]@{
1469
+ Left = $taskbarRect.Right
1470
+ Top = $taskbarRect.Bottom
1471
+ Right = $taskbarRect.Right
1472
+ Bottom = $taskbarRect.Bottom
1473
+ Width = 0
1474
+ Height = 0
1475
+ }
1476
+ }
1477
+
1478
+ $screen = [System.Windows.Forms.Screen]::FromHandle($taskbarHandle)
1479
+ $bounds = $screen.Bounds
1480
+ $margin = 6
1481
+ $isHorizontal = $taskbarRect.Width -ge $taskbarRect.Height
1482
+
1483
+ if ($isHorizontal) {
1484
+ $x = $trayRect.Left - $form.Width - $margin
1485
+ $y = $taskbarRect.Top + [math]::Floor(($taskbarRect.Height - $form.Height) / 2)
1486
+ } else {
1487
+ $isLeft = $taskbarRect.Left -le $bounds.Left
1488
+ $x = if ($isLeft) { $taskbarRect.Right + $margin } else { $taskbarRect.Left - $form.Width - $margin }
1489
+ $y = $trayRect.Top - $form.Height - $margin
1490
+ }
1491
+
1492
+ $x = Limit-Number $x ($bounds.Left + $margin) ($bounds.Right - $form.Width - $margin)
1493
+ $y = Limit-Number $y ($bounds.Top + $margin) ($bounds.Bottom - $form.Height - $margin)
1494
+ $form.Location = [System.Drawing.Point]::new([int]$x, [int]$y)
1495
+ Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1496
+ return $true
1497
+ }
1498
+
1499
+ function Get-OnScreenPoint([int]$X, [int]$Y, [int]$W, [int]$H) {
1500
+ $rect = [System.Drawing.Rectangle]::new($X, $Y, [math]::Max(1, $W), [math]::Max(1, $H))
1501
+ foreach ($screen in [System.Windows.Forms.Screen]::AllScreens) {
1502
+ # Compare against the full monitor bounds, not the working area: sitting
1503
+ # on top of the taskbar is this HUD's primary use case, and the taskbar
1504
+ # band is outside every working area.
1505
+ $overlap = [System.Drawing.Rectangle]::Intersect($screen.Bounds, $rect)
1506
+ if ($overlap.Width -ge 24 -and $overlap.Height -ge 10) {
1507
+ return [System.Drawing.Point]::new($X, $Y)
1508
+ }
1509
+ }
1510
+
1511
+ # The saved spot is no longer on any screen (monitor unplugged or layout
1512
+ # changed), so pull the HUD back into the primary working area.
1513
+ $area = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea
1514
+ $margin = 18
1515
+ $newX = Limit-Number $X ($area.Left + $margin) ($area.Right - $W - $margin)
1516
+ $newY = Limit-Number $Y ($area.Top + $margin) ($area.Bottom - $H - $margin)
1517
+ return [System.Drawing.Point]::new([int]$newX, [int]$newY)
1518
+ }
1519
+
1520
+ function Set-Position {
1521
+ if ($Position -eq "saved") {
1522
+ $savedPlacement = Read-HudPlacement
1523
+ if ($savedPlacement) {
1524
+ if ($null -ne $savedPlacement.Width -and $savedPlacement.Width -gt 0) {
1525
+ $form.Width = [int]$savedPlacement.Width
1526
+ }
1527
+ if ($null -ne $savedPlacement.Height -and $savedPlacement.Height -gt 0) {
1528
+ $form.Height = [int]$savedPlacement.Height
1529
+ }
1530
+ $form.Location = Get-OnScreenPoint ([int]$savedPlacement.X) ([int]$savedPlacement.Y) ([int]$form.Width) ([int]$form.Height)
1531
+ Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1532
+ return
1533
+ }
1534
+ }
1535
+
1536
+ if ($Position -eq "taskbar") {
1537
+ if (Set-TaskbarPosition) { return }
1538
+ }
1539
+
1540
+ $area = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea
1541
+ $margin = if ($Mode -eq "statusline") { 8 } else { 18 }
1542
+ $x = if ($Position -like "*left*") {
1543
+ $area.Left + $margin
1544
+ } elseif ($Position -like "*center*") {
1545
+ $area.Left + [math]::Floor(($area.Width - $form.Width) / 2)
1546
+ } else {
1547
+ $area.Right - $form.Width - $margin
1548
+ }
1549
+ $y = if ($Position -like "top*") { $area.Top + $margin } else { $area.Bottom - $form.Height - $margin }
1550
+ $form.Location = [System.Drawing.Point]::new($x, $y)
1551
+ Set-HudAnchorFromPositionKeyword
1552
+ }
1553
+
1554
+ function Ensure-HudTopMost {
1555
+ if (-not $form -or $form.IsDisposed) { return }
1556
+ if ($script:hudHiddenForFullscreen) { return }
1557
+ if ($hitForm -and -not $hitForm.IsDisposed -and $hitForm.Visible) {
1558
+ $hitForm.TopMost = $true
1559
+ [AiBatteryNative]::SetWindowPos(
1560
+ $hitForm.Handle,
1561
+ [AiBatteryNative]::HWND_TOPMOST,
1562
+ 0,
1563
+ 0,
1564
+ 0,
1565
+ 0,
1566
+ [AiBatteryNative]::SWP_NOMOVE -bor [AiBatteryNative]::SWP_NOSIZE -bor [AiBatteryNative]::SWP_NOACTIVATE -bor [AiBatteryNative]::SWP_SHOWWINDOW
1567
+ ) | Out-Null
1568
+ }
1569
+ $form.TopMost = $true
1570
+ [AiBatteryNative]::SetWindowPos(
1571
+ $form.Handle,
1572
+ [AiBatteryNative]::HWND_TOPMOST,
1573
+ 0,
1574
+ 0,
1575
+ 0,
1576
+ 0,
1577
+ [AiBatteryNative]::SWP_NOMOVE -bor [AiBatteryNative]::SWP_NOSIZE -bor [AiBatteryNative]::SWP_NOACTIVATE -bor [AiBatteryNative]::SWP_SHOWWINDOW
1578
+ ) | Out-Null
1579
+ }
1580
+
1581
+ function Set-HudHiddenForFullscreen([bool]$Hidden) {
1582
+ $script:hudHiddenForFullscreen = $Hidden
1583
+ if ($Hidden) {
1584
+ if ($hitForm -and -not $hitForm.IsDisposed -and $hitForm.Visible) {
1585
+ [AiBatteryNative]::ShowWindow($hitForm.Handle, [AiBatteryNative]::SW_HIDE) | Out-Null
1586
+ $hitForm.Hide()
1587
+ }
1588
+ if ($form -and -not $form.IsDisposed -and $form.Visible) {
1589
+ [AiBatteryNative]::ShowWindow($form.Handle, [AiBatteryNative]::SW_HIDE) | Out-Null
1590
+ $form.Hide()
1591
+ }
1592
+ return
1593
+ }
1594
+
1595
+ if ($form -and -not $form.IsDisposed -and -not $form.Visible) {
1596
+ $form.Show()
1597
+ [AiBatteryNative]::ShowWindow($form.Handle, [AiBatteryNative]::SW_SHOWNOACTIVATE) | Out-Null
1598
+ }
1599
+ Show-HitForm
1600
+ Sync-HitFormBounds
1601
+ }
1602
+
1603
+ $script:fullscreenClearCount = 0
1604
+
1605
+ function Update-HudVisibilityForFullscreen {
1606
+ if (-not $form -or $form.IsDisposed) { return }
1607
+ if (Test-FullscreenOnHudMonitor) {
1608
+ $script:fullscreenClearCount = 0
1609
+ Set-HudHiddenForFullscreen $true
1610
+ return
1611
+ }
1612
+ if ($script:hudHiddenForFullscreen) {
1613
+ $script:fullscreenClearCount += 1
1614
+ if ($script:fullscreenClearCount -lt 2) { return }
1615
+ }
1616
+ $script:fullscreenClearCount = 0
1617
+ Set-HudHiddenForFullscreen $false
1618
+ Ensure-HudTopMost
1619
+ }
1620
+
1621
+ $script:fullscreenCheckPending = $false
1622
+
1623
+ function Request-FullscreenCheck {
1624
+ if (-not $form -or $form.IsDisposed) { return }
1625
+ if ($form.InvokeRequired) {
1626
+ if ($script:fullscreenCheckPending) { return }
1627
+ $script:fullscreenCheckPending = $true
1628
+ try {
1629
+ $form.BeginInvoke([Action]{
1630
+ $script:fullscreenCheckPending = $false
1631
+ Update-HudVisibilityForFullscreen
1632
+ }) | Out-Null
1633
+ } catch {
1634
+ $script:fullscreenCheckPending = $false
1635
+ }
1636
+ return
1637
+ }
1638
+ Update-HudVisibilityForFullscreen
1639
+ }
1640
+
1641
+ $script:fullscreenEventCallback = $null
1642
+ $script:fullscreenEventHooks = @()
1643
+
1644
+ function Start-FullscreenEventHooks {
1645
+ if ($script:fullscreenEventCallback) { return }
1646
+ $script:fullscreenEventCallback = [AiBatteryWinEventDelegate]{
1647
+ param($hook, $eventType, $hwnd, $idObject, $idChild, $eventThread, $eventTime)
1648
+ if ($idObject -ne [AiBatteryNative]::OBJID_WINDOW) { return }
1649
+ Request-FullscreenCheck
1650
+ }
1651
+
1652
+ $events = @(
1653
+ [AiBatteryNative]::EVENT_SYSTEM_FOREGROUND,
1654
+ [AiBatteryNative]::EVENT_OBJECT_SHOW,
1655
+ [AiBatteryNative]::EVENT_OBJECT_HIDE,
1656
+ [AiBatteryNative]::EVENT_OBJECT_REORDER,
1657
+ [AiBatteryNative]::EVENT_OBJECT_LOCATIONCHANGE,
1658
+ [AiBatteryNative]::EVENT_OBJECT_CLOAKED,
1659
+ [AiBatteryNative]::EVENT_OBJECT_UNCLOAKED
1660
+ )
1661
+ $flags = [AiBatteryNative]::WINEVENT_OUTOFCONTEXT -bor [AiBatteryNative]::WINEVENT_SKIPOWNPROCESS
1662
+ foreach ($eventId in $events) {
1663
+ try {
1664
+ $hook = [AiBatteryNative]::SetWinEventHook($eventId, $eventId, [IntPtr]::Zero, $script:fullscreenEventCallback, 0, 0, $flags)
1665
+ if ($hook -ne [IntPtr]::Zero) {
1666
+ $script:fullscreenEventHooks += $hook
1667
+ }
1668
+ } catch {
1669
+ # Polling still covers older or restricted Windows environments.
1670
+ }
1671
+ }
1672
+ }
1673
+
1674
+ function Stop-FullscreenEventHooks {
1675
+ foreach ($hook in $script:fullscreenEventHooks) {
1676
+ try {
1677
+ [AiBatteryNative]::UnhookWinEvent($hook) | Out-Null
1678
+ } catch {
1679
+ # The hook may already be gone during shutdown.
1680
+ }
1681
+ }
1682
+ $script:fullscreenEventHooks = @()
1683
+ $script:fullscreenEventCallback = $null
1684
+ }
1685
+
1686
+ function Set-HudBatteryImage($Box, [Nullable[int]]$Percent, [bool]$Running) {
1687
+ $oldImage = $Box.Image
1688
+ $Box.Image = New-BatteryImage $Percent $Running
1689
+ $Box.Visible = $true
1690
+ $Box.Tag = $true
1691
+ if ($oldImage) { $oldImage.Dispose() }
1692
+ }
1693
+
1694
+ function New-HudGlyphImage([string]$Kind, [System.Drawing.Color]$Color, [int]$Width = 21, [int]$Height = 18) {
1695
+ $bitmap = [System.Drawing.Bitmap]::new($Width, $Height)
1696
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
1697
+ $graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
1698
+ $graphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
1699
+ $graphics.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
1700
+ $graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half
1701
+ $graphics.Clear([System.Drawing.Color]::Transparent)
1702
+
1703
+ if ($Kind -eq "reset") {
1704
+ $pen = [System.Drawing.Pen]::new($Color, 2.1)
1705
+ $pen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
1706
+ $pen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
1707
+ $brush = [System.Drawing.SolidBrush]::new($Color)
1708
+ try {
1709
+ $arcX = 3.6
1710
+ $arcY = 2.5
1711
+ $arcW = 13.0
1712
+ $arcH = 13.0
1713
+ $startAngle = 150.0
1714
+ $sweepAngle = 190.0
1715
+ $endAngle = ($startAngle + $sweepAngle) * [math]::PI / 180.0
1716
+ $centerX = $arcX + ($arcW / 2.0)
1717
+ $centerY = $arcY + ($arcH / 2.0)
1718
+ $radiusX = $arcW / 2.0
1719
+ $radiusY = $arcH / 2.0
1720
+
1721
+ $graphics.DrawArc($pen, [single]$arcX, [single]$arcY, [single]$arcW, [single]$arcH, [single]$startAngle, [single]$sweepAngle)
1722
+
1723
+ $tipX = $centerX + ($radiusX * [math]::Cos($endAngle))
1724
+ $tipY = $centerY + ($radiusY * [math]::Sin($endAngle))
1725
+ $dirX = -[math]::Sin($endAngle)
1726
+ $dirY = [math]::Cos($endAngle)
1727
+ $length = [math]::Sqrt(($dirX * $dirX) + ($dirY * $dirY))
1728
+ if ($length -gt 0) {
1729
+ $dirX = $dirX / $length
1730
+ $dirY = $dirY / $length
1731
+ }
1732
+ $normalX = -$dirY
1733
+ $normalY = $dirX
1734
+ $headLength = 4.8
1735
+ $headWidth = 3.3
1736
+ $baseX = $tipX - ($dirX * $headLength)
1737
+ $baseY = $tipY - ($dirY * $headLength)
1738
+
1739
+ $points = @(
1740
+ [System.Drawing.PointF]::new([single]$tipX, [single]$tipY),
1741
+ [System.Drawing.PointF]::new([single]($baseX + ($normalX * $headWidth)), [single]($baseY + ($normalY * $headWidth))),
1742
+ [System.Drawing.PointF]::new([single]($baseX - ($normalX * $headWidth)), [single]($baseY - ($normalY * $headWidth)))
1743
+ )
1744
+ $graphics.FillPolygon($brush, $points)
1745
+ } finally {
1746
+ $pen.Dispose()
1747
+ $brush.Dispose()
1748
+ $graphics.Dispose()
1749
+ }
1750
+ return $bitmap
1751
+ }
1752
+
1753
+ $sourceSize = 48
1754
+ $source = [System.Drawing.Bitmap]::new($sourceSize, $sourceSize)
1755
+ $sourceGraphics = [System.Drawing.Graphics]::FromImage($source)
1756
+ $sourceGraphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
1757
+ $sourceGraphics.TextRenderingHint = [System.Drawing.Text.TextRenderingHint]::AntiAliasGridFit
1758
+ $sourceGraphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half
1759
+ $sourceGraphics.Clear([System.Drawing.Color]::Transparent)
1760
+
1761
+ $brush = [System.Drawing.SolidBrush]::new($Color)
1762
+ $format = [System.Drawing.StringFormat]::new()
1763
+ $format.Alignment = [System.Drawing.StringAlignment]::Center
1764
+ $format.LineAlignment = [System.Drawing.StringAlignment]::Near
1765
+
1766
+ try {
1767
+ $glyph = [string][char]0x2466
1768
+ $maxIconWidth = 12
1769
+ $maxIconHeight = 12
1770
+ $sourceGraphics.DrawString(
1771
+ $glyph,
1772
+ $symbolFont,
1773
+ $brush,
1774
+ [System.Drawing.RectangleF]::new([single]0, [single]0, [single]$sourceSize, [single]$sourceSize),
1775
+ $format
1776
+ )
1777
+
1778
+ $left = $sourceSize
1779
+ $top = $sourceSize
1780
+ $right = -1
1781
+ $bottom = -1
1782
+ for ($y = 0; $y -lt $sourceSize; $y += 1) {
1783
+ for ($x = 0; $x -lt $sourceSize; $x += 1) {
1784
+ if ($source.GetPixel($x, $y).A -gt 0) {
1785
+ if ($x -lt $left) { $left = $x }
1786
+ if ($x -gt $right) { $right = $x }
1787
+ if ($y -lt $top) { $top = $y }
1788
+ if ($y -gt $bottom) { $bottom = $y }
1789
+ }
1790
+ }
1791
+ }
1792
+
1793
+ if ($right -ge $left -and $bottom -ge $top) {
1794
+ $sourceRect = [System.Drawing.Rectangle]::new($left, $top, ($right - $left + 1), ($bottom - $top + 1))
1795
+ $scale = [math]::Min(1.0, [math]::Min(($maxIconWidth / [double]$sourceRect.Width), ($maxIconHeight / [double]$sourceRect.Height)))
1796
+ $targetWidth = [math]::Max(1, [int][math]::Round($sourceRect.Width * $scale))
1797
+ $targetHeight = [math]::Max(1, [int][math]::Round($sourceRect.Height * $scale))
1798
+ $targetX = [math]::Floor(($Width - $targetWidth) / 2)
1799
+ $targetY = [math]::Floor(($Height - $targetHeight) / 2)
1800
+ $targetRect = [System.Drawing.Rectangle]::new([int]$targetX, [int]$targetY, $targetWidth, $targetHeight)
1801
+ $graphics.DrawImage($source, $targetRect, $sourceRect, [System.Drawing.GraphicsUnit]::Pixel)
1802
+ }
1803
+ } finally {
1804
+ $brush.Dispose()
1805
+ $format.Dispose()
1806
+ $sourceGraphics.Dispose()
1807
+ $source.Dispose()
1808
+ $graphics.Dispose()
1809
+ }
1810
+
1811
+ return $bitmap
1812
+ }
1813
+
1814
+ function Set-HudLineIconImage($Box, [string]$Kind, [string]$Value, [System.Drawing.Color]$Color) {
1815
+ $oldImage = $Box.Image
1816
+ if ([string]::IsNullOrWhiteSpace($Value)) {
1817
+ $Box.Image = $null
1818
+ $Box.Visible = $false
1819
+ } else {
1820
+ $Box.Image = New-HudGlyphImage $Kind $Color
1821
+ $Box.Visible = $true
1822
+ }
1823
+ if ($oldImage) { $oldImage.Dispose() }
1824
+ }
1825
+
1826
+ function Set-HudMetricLabel($Label, [string]$Value, [System.Drawing.Color]$Color, [Nullable[int]]$FixedWidth = $null) {
1827
+ $Label.Text = $Value
1828
+ $Label.ForeColor = $Color
1829
+ if ([string]::IsNullOrWhiteSpace($Value)) {
1830
+ $Label.Width = 0
1831
+ $Label.Visible = $false
1832
+ $Label.Tag = $false
1833
+ } else {
1834
+ $Label.Width = if ($null -ne $FixedWidth -and $FixedWidth -gt 0) { [int]$FixedWidth } else { (Get-LabelTextWidth $Label) + 1 }
1835
+ $Label.Visible = $true
1836
+ $Label.Tag = $true
1837
+ }
1838
+ }
1839
+
1840
+ function Set-HudDivider($Divider, [string]$Value) {
1841
+ if ([string]::IsNullOrWhiteSpace($Value)) {
1842
+ $Divider.Visible = $false
1843
+ $Divider.Width = 0
1844
+ $Divider.Tag = $false
1845
+ } else {
1846
+ $Divider.Visible = $true
1847
+ $Divider.Width = 1
1848
+ $Divider.Tag = $true
1849
+ }
1850
+ }
1851
+
1852
+ function Set-HudParts($Parts, $PrefixLabel, $BatteryBox, $Divider1, $ResetLabel, $Divider2, $WeekLabel, $ExtraLabel) {
1853
+ $PrefixLabel.Text = $Parts.Prefix
1854
+ $PrefixLabel.ForeColor = $Parts.TextColor
1855
+ $PrefixLabel.Width = 48
1856
+ $PrefixLabel.Visible = $true
1857
+ $PrefixLabel.Tag = $true
1858
+ Set-HudBatteryImage $BatteryBox $Parts.Percent $Parts.Running
1859
+ Set-HudDivider $Divider1 $Parts.ResetValue
1860
+ Set-HudMetricLabel $ResetLabel $Parts.ResetValue $Parts.TextColor 52
1861
+ Set-HudDivider $Divider2 $Parts.WeekValue
1862
+ Set-HudMetricLabel $WeekLabel $Parts.WeekValue $Parts.TextColor 52
1863
+ Set-HudMetricLabel $ExtraLabel $Parts.ExtraText $Parts.TextColor
1864
+ }
1865
+
1866
+ function Set-HudControlsVisible($Controls, [bool]$Visible) {
1867
+ foreach ($control in $Controls) {
1868
+ $control.Visible = $Visible
1869
+ $control.Tag = $Visible
1870
+ }
1871
+ }
1872
+
1873
+ function Get-LabelTextWidth($Label) {
1874
+ if (-not $Label.Text) { return 0 }
1875
+ return [System.Windows.Forms.TextRenderer]::MeasureText(
1876
+ $Label.Text,
1877
+ $Label.Font,
1878
+ [System.Drawing.Size]::new(1000, 1000),
1879
+ [System.Windows.Forms.TextFormatFlags]::NoPadding
1880
+ ).Width
1881
+ }
1882
+
1883
+ function Get-ControlLayoutWidth($Control) {
1884
+ # Control.Visible reads as $false while the form is still hidden, so track
1885
+ # the intended visibility in Tag to keep pre-show layout math correct.
1886
+ if ($Control.Tag -ne $true) { return 0 }
1887
+ $baseWidth = $Control.Width
1888
+ return $baseWidth + $Control.Margin.Left + $Control.Margin.Right
1889
+ }
1890
+
1891
+ function Get-HudControlsWidth($Controls) {
1892
+ $width = 0
1893
+ foreach ($control in $Controls) {
1894
+ $width += Get-ControlLayoutWidth $control
1895
+ }
1896
+ return $width
1897
+ }
1898
+
1899
+ function Resize-HudToContent {
1900
+ if ($Mode -eq "tray") { return }
1901
+
1902
+ $oldRight = $form.Left + $form.Width
1903
+ $oldBottom = $form.Top + $form.Height
1904
+ $codexWidth = $(if ($script:codexRowVisible) { Get-HudControlsWidth $codexHudControls } else { 0 })
1905
+ $claudeWidth = $(if ($script:claudeRowVisible) { Get-HudControlsWidth $claudeHudControls } else { 0 })
1906
+ $contentWidth = [math]::Max($codexWidth, $claudeWidth)
1907
+ $desiredWidth = $panel.Padding.Left + $panel.Padding.Right +
1908
+ $contentWidth +
1909
+ 1
1910
+ $desiredWidth = [math]::Max(150, [int][math]::Ceiling($desiredWidth))
1911
+
1912
+ $bothRows = $script:codexRowVisible -and $script:claudeRowVisible
1913
+ $desiredHeight = [int]$(if ($bothRows) { $script:hudTwoRowHeight } else { $script:hudOneRowHeight })
1914
+ if ($bothRows) {
1915
+ $panel.RowStyles[0] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)
1916
+ $panel.RowStyles[1] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)
1917
+ } elseif ($script:claudeRowVisible) {
1918
+ $panel.RowStyles[0] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Absolute, 0)
1919
+ $panel.RowStyles[1] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 100)
1920
+ } else {
1921
+ $panel.RowStyles[0] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 100)
1922
+ $panel.RowStyles[1] = [System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Absolute, 0)
1923
+ }
1924
+
1925
+ if (([math]::Abs($form.Width - $desiredWidth) -gt 1) -or ($form.Height -ne $desiredHeight)) {
1926
+ $form.Width = $desiredWidth
1927
+ $form.Height = $desiredHeight
1928
+ $newX = if ($script:hudAnchorX -eq "right") { $oldRight - $form.Width } else { $form.Left }
1929
+ $newY = if ($script:hudAnchorY -eq "bottom") { $oldBottom - $form.Height } else { $form.Top }
1930
+ $form.Location = [System.Drawing.Point]::new([int]$newX, [int]$newY)
1931
+ Sync-HitFormBounds
1932
+ Save-HudPositionIfReady
1933
+ }
1934
+ }
1935
+
1936
+ function Show-HudMessage([string]$Message) {
1937
+ $codexPrefixLabel.Text = $Message
1938
+ $codexPrefixLabel.ForeColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
1939
+ $codexPrefixLabel.Width = (Get-LabelTextWidth $codexPrefixLabel) + 1
1940
+ $codexPrefixLabel.Visible = $true
1941
+ $codexPrefixLabel.Tag = $true
1942
+ foreach ($label in @($codexResetLabel, $codexWeekLabel, $codexExtraLabel, $claudePrefixLabel, $claudeResetLabel, $claudeWeekLabel, $claudeExtraLabel)) {
1943
+ $label.Text = ""
1944
+ $label.Width = 0
1945
+ $label.Visible = $false
1946
+ $label.Tag = $false
1947
+ }
1948
+ foreach ($divider in @($codexDivider1, $codexDivider2, $claudeDivider1, $claudeDivider2)) {
1949
+ $divider.Visible = $false
1950
+ $divider.Width = 0
1951
+ $divider.Tag = $false
1952
+ }
1953
+ Set-HudBatteryImage $codexIconLabel $null $false
1954
+ $oldImage = $claudeIconLabel.Image
1955
+ $claudeIconLabel.Image = $null
1956
+ $claudeIconLabel.Visible = $false
1957
+ $claudeIconLabel.Tag = $false
1958
+ if ($oldImage) { $oldImage.Dispose() }
1959
+ $script:codexRowVisible = $true
1960
+ $script:claudeRowVisible = $false
1961
+ $codexRow.Visible = $true
1962
+ $claudeRow.Visible = $false
1963
+ Resize-HudToContent
1964
+ }
1965
+
1966
+ function Update-HudFromSnapshot($Snapshot) {
1967
+ if (-not $Snapshot) {
1968
+ Show-HudMessage "AI Battery starting..."
1969
+ Update-HudVisibilityForFullscreen
1970
+ return
1971
+ }
1972
+
1973
+ try {
1974
+ $texts = ConvertTo-HudTexts $Snapshot
1975
+ $script:codexRowVisible = [bool]$texts.CodexVisible
1976
+ $script:claudeRowVisible = [bool]$texts.ClaudeVisible
1977
+ if ($texts.CodexVisible) {
1978
+ $codexRow.Visible = $true
1979
+ Set-HudParts $texts.Codex $codexPrefixLabel $codexIconLabel $codexDivider1 $codexResetLabel $codexDivider2 $codexWeekLabel $codexExtraLabel
1980
+ } else {
1981
+ $codexRow.Visible = $false
1982
+ Set-HudControlsVisible $codexHudControls $false
1983
+ }
1984
+ if ($texts.ClaudeVisible) {
1985
+ $claudeRow.Visible = $true
1986
+ Set-HudParts $texts.Claude $claudePrefixLabel $claudeIconLabel $claudeDivider1 $claudeResetLabel $claudeDivider2 $claudeWeekLabel $claudeExtraLabel
1987
+ } else {
1988
+ $claudeRow.Visible = $false
1989
+ Set-HudControlsVisible $claudeHudControls $false
1990
+ }
1991
+ Resize-HudToContent
1992
+ } catch {
1993
+ Show-HudMessage "AI Battery unavailable"
1994
+ }
1995
+ Update-HudVisibilityForFullscreen
1996
+ }
1997
+
1998
+ function Invoke-HudPump {
1999
+ # Everything here must return quickly: this runs on the UI thread, and the
2000
+ # actual data fetch happens on a background runspace.
2001
+ if ($script:fetchPowerShell -and -not $script:fetchHandle.IsCompleted -and
2002
+ ([datetime]::UtcNow - $script:lastFetchStartUtc).TotalSeconds -gt 30) {
2003
+ Stop-SnapshotFetch
2004
+ }
2005
+
2006
+ $fresh = Complete-SnapshotFetch
2007
+ if ($fresh) {
2008
+ $merged = Merge-HudSnapshot $fresh $script:latestSnapshot
2009
+ $script:latestSnapshot = $merged
2010
+ Write-HudSnapshot $merged
2011
+ Update-HudFromSnapshot $merged
2012
+
2013
+ $missingWeekly = @($merged.results | Where-Object { $_.ok -and $null -ne $_.percentRemaining -and $null -eq $_.secondary })
2014
+ if ($missingWeekly.Count -gt 0 -and $script:weeklyRetryCount -lt 6) {
2015
+ $script:weeklyRetryCount += 1
2016
+ Start-SnapshotFetch
2017
+ return
2018
+ }
2019
+ $script:weeklyRetryCount = 0
2020
+ return
2021
+ }
2022
+
2023
+ if (-not $script:fetchPowerShell -and
2024
+ ([datetime]::UtcNow - $script:lastFetchStartUtc).TotalSeconds -ge [math]::Max(1, $Interval)) {
2025
+ Start-SnapshotFetch
2026
+ }
2027
+ }
2028
+
2029
+ $timer = New-Object System.Windows.Forms.Timer
2030
+ $timer.Interval = 1000
2031
+ $timer.add_Tick({ Invoke-HudPump })
2032
+ # WinEvent hooks wake fullscreen checks immediately on foreground/Z-order/show
2033
+ # changes. The UI timer is only a fallback for Windows builds or shells that do
2034
+ # not deliver every event we subscribe to.
2035
+ $topMostTimer = New-Object System.Windows.Forms.Timer
2036
+ $topMostTimer.Interval = 150
2037
+ $topMostTimer.add_Tick({ Update-HudVisibilityForFullscreen })
2038
+ $form.add_FormClosed({
2039
+ if ($canMove) {
2040
+ Write-HudPosition $form.Location
2041
+ }
2042
+ $timer.Stop()
2043
+ $timer.Dispose()
2044
+ $topMostTimer.Stop()
2045
+ $topMostTimer.Dispose()
2046
+ Stop-FullscreenEventHooks
2047
+ Stop-SnapshotFetch
2048
+ foreach ($box in @($codexIconLabel, $claudeIconLabel)) {
2049
+ if ($box.Image) {
2050
+ $box.Image.Dispose()
2051
+ $box.Image = $null
2052
+ }
2053
+ }
2054
+ $font.Dispose()
2055
+ $symbolFont.Dispose()
2056
+ if ($hitForm -and -not $hitForm.IsDisposed) {
2057
+ $hitForm.Close()
2058
+ $hitForm.Dispose()
2059
+ }
2060
+ Release-SingleInstance
2061
+ })
2062
+
2063
+ $form.add_LocationChanged({
2064
+ # No position save here: writing the state file on every drag pixel causes
2065
+ # visible hitches. MouseUp and Resize-HudToContent persist the placement.
2066
+ Sync-HitFormBounds
2067
+ })
2068
+ $form.add_SizeChanged({ Sync-HitFormBounds })
2069
+ $form.add_Shown({
2070
+ Show-HitForm
2071
+ Update-HudVisibilityForFullscreen
2072
+ Signal-HudReady
2073
+ })
2074
+
2075
+ Set-Position
2076
+ $script:positionSaveReady = $true
2077
+
2078
+ $diskSnapshot = Read-HudSnapshot
2079
+ if ($script:initialHudSnapshot) {
2080
+ $script:latestSnapshot = Merge-HudSnapshot $script:initialHudSnapshot $diskSnapshot
2081
+ $script:initialHudSnapshot = $null
2082
+ Write-HudSnapshot $script:latestSnapshot
2083
+ } else {
2084
+ $script:latestSnapshot = $diskSnapshot
2085
+ }
2086
+ Update-HudFromSnapshot $script:latestSnapshot
2087
+ Start-SnapshotFetch
2088
+ $style = [AiBatteryNative]::GetWindowLong($form.Handle, [AiBatteryNative]::GWL_EXSTYLE)
2089
+ $style = $style -bor [AiBatteryNative]::WS_EX_TOOLWINDOW -bor [AiBatteryNative]::WS_EX_NOACTIVATE
2090
+ if ($ClickThrough) {
2091
+ $style = $style -bor [AiBatteryNative]::WS_EX_TRANSPARENT
2092
+ }
2093
+ [AiBatteryNative]::SetWindowLong($form.Handle, [AiBatteryNative]::GWL_EXSTYLE, $style) | Out-Null
2094
+ $timer.Start()
2095
+ Start-FullscreenEventHooks
2096
+ $topMostTimer.Start()
2097
+ [System.Windows.Forms.Application]::Run($form)