ai-battery 0.1.20 → 0.1.21

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,48 +1,48 @@
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
- [string]$Backdrop = $(if ($env:AI_BATTERY_HUD_BACKDROP) { $env:AI_BATTERY_HUD_BACKDROP } elseif ($env:CLAUDEX_BATTERY_HUD_BACKDROP) { $env:CLAUDEX_BATTERY_HUD_BACKDROP } else { "off" }),
11
- [string]$Text = $(if ($env:AI_BATTERY_HUD_TEXT) { $env:AI_BATTERY_HUD_TEXT } elseif ($env:CLAUDEX_BATTERY_HUD_TEXT) { $env:CLAUDEX_BATTERY_HUD_TEXT } else { "light" }),
12
- [string]$Transparent = "",
13
- [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 }),
14
- [switch]$Locked,
15
- [switch]$Movable,
16
- [switch]$ClickThrough,
17
- [switch]$StopExisting,
18
- [switch]$UseWsl,
19
- [switch]$Once,
20
- [string]$ReadyPath = "",
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
+ [string]$Backdrop = $(if ($env:AI_BATTERY_HUD_BACKDROP) { $env:AI_BATTERY_HUD_BACKDROP } elseif ($env:CLAUDEX_BATTERY_HUD_BACKDROP) { $env:CLAUDEX_BATTERY_HUD_BACKDROP } else { "off" }),
11
+ [string]$Text = $(if ($env:AI_BATTERY_HUD_TEXT) { $env:AI_BATTERY_HUD_TEXT } elseif ($env:CLAUDEX_BATTERY_HUD_TEXT) { $env:CLAUDEX_BATTERY_HUD_TEXT } else { "light" }),
12
+ [string]$Transparent = "",
13
+ [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 }),
14
+ [switch]$Locked,
15
+ [switch]$Movable,
16
+ [switch]$ClickThrough,
17
+ [switch]$StopExisting,
18
+ [switch]$UseWsl,
19
+ [switch]$Once,
20
+ [string]$ReadyPath = "",
21
21
  [Int64]$DockWindowHandle = 0,
22
22
  [Int64]$DockSession = 0,
23
23
  [int]$DockOwnerPid = 0,
24
24
  [ValidateSet("", "codex", "claude")]
25
25
  [string]$DockProvider = "",
26
26
  [string]$DockMarkerPath = "",
27
- [ValidateSet("bottom", "tabs")]
28
- [string]$DockPlacement = $(if ($env:AI_BATTERY_WIN_DOCK_POSITION) { $env:AI_BATTERY_WIN_DOCK_POSITION } elseif ($env:CLAUDEX_BATTERY_WIN_DOCK_POSITION) { $env:CLAUDEX_BATTERY_WIN_DOCK_POSITION } else { "bottom" })
29
- )
30
-
31
- $ErrorActionPreference = "Stop"
32
- Add-Type -AssemblyName System.Drawing
33
- [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
34
- if ($env:AI_BATTERY_HUD_DEBUG_LOG) { Add-Content $env:AI_BATTERY_HUD_DEBUG_LOG "boot dock=$DockWindowHandle placement=$DockPlacement once=$Once mode=$Mode" }
35
-
36
- if (-not [string]::IsNullOrWhiteSpace($BatteryCommandBase64)) {
37
- try {
38
- $BatteryCommand = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($BatteryCommandBase64))
39
- } catch {
40
- # Fall back to BatteryCommand/env defaults; the HUD can still show an error row.
41
- }
42
- }
43
-
44
- $script:hudStopScanFailed = $false
45
-
27
+ [ValidateSet("bottom", "tabs")]
28
+ [string]$DockPlacement = $(if ($env:AI_BATTERY_WIN_DOCK_POSITION) { $env:AI_BATTERY_WIN_DOCK_POSITION } elseif ($env:CLAUDEX_BATTERY_WIN_DOCK_POSITION) { $env:CLAUDEX_BATTERY_WIN_DOCK_POSITION } else { "bottom" })
29
+ )
30
+
31
+ $ErrorActionPreference = "Stop"
32
+ Add-Type -AssemblyName System.Drawing
33
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
34
+ if ($env:AI_BATTERY_HUD_DEBUG_LOG) { Add-Content $env:AI_BATTERY_HUD_DEBUG_LOG "boot dock=$DockWindowHandle placement=$DockPlacement once=$Once mode=$Mode" }
35
+
36
+ if (-not [string]::IsNullOrWhiteSpace($BatteryCommandBase64)) {
37
+ try {
38
+ $BatteryCommand = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($BatteryCommandBase64))
39
+ } catch {
40
+ # Fall back to BatteryCommand/env defaults; the HUD can still show an error row.
41
+ }
42
+ }
43
+
44
+ $script:hudStopScanFailed = $false
45
+
46
46
  function Stop-ExistingHudProcesses([bool]$DockedOnly = $false) {
47
47
  $script:hudStopScanFailed = $false
48
48
  $currentPid = $PID
@@ -53,50 +53,50 @@ function Stop-ExistingHudProcesses([bool]$DockedOnly = $false) {
53
53
  "-DockWindowHandle"
54
54
  }
55
55
  try {
56
- $hudProcesses = @(Get-CimInstance Win32_Process -ErrorAction Stop |
57
- Where-Object {
58
- $_.ProcessId -ne $currentPid -and
59
- $_.Name -match '^(powershell|pwsh)(\.exe)?$' -and
60
- $_.CommandLine -and
61
- $_.CommandLine -like "*ai-battery-hud.ps1*" -and
62
- $_.CommandLine -notlike "*Start-Process*" -and
56
+ $hudProcesses = @(Get-CimInstance Win32_Process -ErrorAction Stop |
57
+ Where-Object {
58
+ $_.ProcessId -ne $currentPid -and
59
+ $_.Name -match '^(powershell|pwsh)(\.exe)?$' -and
60
+ $_.CommandLine -and
61
+ $_.CommandLine -like "*ai-battery-hud.ps1*" -and
62
+ $_.CommandLine -notlike "*Start-Process*" -and
63
63
  ($(if ($DockedOnly) { $_.CommandLine -match $dockHandlePattern } else { $_.CommandLine -notlike "*-DockWindowHandle*" }))
64
- })
65
- } catch {
66
- $script:hudStopScanFailed = $true
67
- if ($env:AI_BATTERY_HUD_DEBUG_LOG) {
68
- try { Add-Content $env:AI_BATTERY_HUD_DEBUG_LOG "stop scan unavailable: $($_.Exception.Message)" } catch { }
69
- }
70
- return
71
- }
72
-
73
- foreach ($hudProcess in $hudProcesses) {
74
- try {
75
- Stop-Process -Id $hudProcess.ProcessId -Force -ErrorAction Stop
76
- Wait-Process -Id $hudProcess.ProcessId -Timeout 3 -ErrorAction SilentlyContinue
77
- } catch {
78
- # The process may already have exited.
79
- }
80
- }
81
- }
82
-
83
- function Get-HudDockRequestPath {
84
- $root = if ($env:LOCALAPPDATA) {
85
- Join-Path $env:LOCALAPPDATA "ai-battery"
86
- } else {
87
- Join-Path $env:TEMP "ai-battery"
88
- }
89
- New-Item -ItemType Directory -Force -Path $root | Out-Null
64
+ })
65
+ } catch {
66
+ $script:hudStopScanFailed = $true
67
+ if ($env:AI_BATTERY_HUD_DEBUG_LOG) {
68
+ try { Add-Content $env:AI_BATTERY_HUD_DEBUG_LOG "stop scan unavailable: $($_.Exception.Message)" } catch { }
69
+ }
70
+ return
71
+ }
72
+
73
+ foreach ($hudProcess in $hudProcesses) {
74
+ try {
75
+ Stop-Process -Id $hudProcess.ProcessId -Force -ErrorAction Stop
76
+ Wait-Process -Id $hudProcess.ProcessId -Timeout 3 -ErrorAction SilentlyContinue
77
+ } catch {
78
+ # The process may already have exited.
79
+ }
80
+ }
81
+ }
82
+
83
+ function Get-HudDockRequestPath {
84
+ $root = if ($env:LOCALAPPDATA) {
85
+ Join-Path $env:LOCALAPPDATA "ai-battery"
86
+ } else {
87
+ Join-Path $env:TEMP "ai-battery"
88
+ }
89
+ New-Item -ItemType Directory -Force -Path $root | Out-Null
90
90
  $name = if ($DockWindowHandle -ne 0) { "tui-dock-request-$DockWindowHandle.json" } else { "hud-dock-request.json" }
91
- return Join-Path $root $name
92
- }
93
-
94
- function Get-HudDockHostPath {
95
- $root = if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA "ai-battery" } else { Join-Path $env:TEMP "ai-battery" }
96
- New-Item -ItemType Directory -Force -Path $root | Out-Null
91
+ return Join-Path $root $name
92
+ }
93
+
94
+ function Get-HudDockHostPath {
95
+ $root = if ($env:LOCALAPPDATA) { Join-Path $env:LOCALAPPDATA "ai-battery" } else { Join-Path $env:TEMP "ai-battery" }
96
+ New-Item -ItemType Directory -Force -Path $root | Out-Null
97
97
  return Join-Path $root "tui-dock-host-$DockWindowHandle.json"
98
- }
99
-
98
+ }
99
+
100
100
  function Write-HudDockHostMarker {
101
101
  if ($DockWindowHandle -eq 0) { return }
102
102
  try {
@@ -118,67 +118,67 @@ function Write-HudDockHostMarker {
118
118
  [System.IO.File]::WriteAllText((Get-HudDockHostPath), $marker, [System.Text.UTF8Encoding]::new($false))
119
119
  } catch { }
120
120
  }
121
-
122
- function Remove-HudDockHostMarker {
123
- if ($DockWindowHandle -eq 0) { return }
124
- $path = Get-HudDockHostPath
125
- try {
126
- if (Test-Path -LiteralPath $path) {
127
- $marker = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json
128
- if ([int]$marker.pid -eq $PID) { Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue }
129
- }
130
- } catch { }
131
- }
132
-
133
- function Request-HudStop {
134
- $requestPath = Get-HudDockRequestPath
135
- try {
136
- $request = @{ stop = $true; at = [datetime]::UtcNow.ToString("o") } | ConvertTo-Json -Compress
137
- [System.IO.File]::WriteAllText($requestPath, $request, [System.Text.UTF8Encoding]::new($false))
138
- } catch {
139
- return
140
- }
141
-
142
- for ($wait = 0; $wait -lt 40; $wait += 1) {
143
- Start-Sleep -Milliseconds 150
144
- if (-not (Test-Path -LiteralPath $requestPath)) { return }
145
- }
146
- Remove-Item -LiteralPath $requestPath -Force -ErrorAction SilentlyContinue
147
- }
148
-
149
- if ($StopExisting) {
150
- Request-HudStop
151
- Start-Sleep -Milliseconds 400
152
- Stop-ExistingHudProcesses
153
- if (-not $Once) {
154
- exit 0
155
- }
156
- } elseif (-not $Once -and $DockWindowHandle -eq 0) {
157
- # Dock launches must never kill a running HUD: they hand the new dock
158
- # target to it via the request file below instead.
159
- Stop-ExistingHudProcesses
160
- }
161
-
162
- $script:singleInstanceMutex = $null
163
- if (-not $Once) {
164
- # A replaced instance we just stopped can hold the mutex handle for a
165
- # moment after Stop-Process returns; retry briefly before treating the
166
- # mutex owner as a genuinely running HUD.
167
- $createdNew = $false
168
- $mutexAttempts = if ($DockWindowHandle -ne 0) { 3 } else { 20 }
169
- for ($mutexAttempt = 0; $mutexAttempt -lt $mutexAttempts; $mutexAttempt += 1) {
121
+
122
+ function Remove-HudDockHostMarker {
123
+ if ($DockWindowHandle -eq 0) { return }
124
+ $path = Get-HudDockHostPath
125
+ try {
126
+ if (Test-Path -LiteralPath $path) {
127
+ $marker = Get-Content -LiteralPath $path -Raw | ConvertFrom-Json
128
+ if ([int]$marker.pid -eq $PID) { Remove-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue }
129
+ }
130
+ } catch { }
131
+ }
132
+
133
+ function Request-HudStop {
134
+ $requestPath = Get-HudDockRequestPath
135
+ try {
136
+ $request = @{ stop = $true; at = [datetime]::UtcNow.ToString("o") } | ConvertTo-Json -Compress
137
+ [System.IO.File]::WriteAllText($requestPath, $request, [System.Text.UTF8Encoding]::new($false))
138
+ } catch {
139
+ return
140
+ }
141
+
142
+ for ($wait = 0; $wait -lt 40; $wait += 1) {
143
+ Start-Sleep -Milliseconds 150
144
+ if (-not (Test-Path -LiteralPath $requestPath)) { return }
145
+ }
146
+ Remove-Item -LiteralPath $requestPath -Force -ErrorAction SilentlyContinue
147
+ }
148
+
149
+ if ($StopExisting) {
150
+ Request-HudStop
151
+ Start-Sleep -Milliseconds 400
152
+ Stop-ExistingHudProcesses
153
+ if (-not $Once) {
154
+ exit 0
155
+ }
156
+ } elseif (-not $Once -and $DockWindowHandle -eq 0) {
157
+ # Dock launches must never kill a running HUD: they hand the new dock
158
+ # target to it via the request file below instead.
159
+ Stop-ExistingHudProcesses
160
+ }
161
+
162
+ $script:singleInstanceMutex = $null
163
+ if (-not $Once) {
164
+ # A replaced instance we just stopped can hold the mutex handle for a
165
+ # moment after Stop-Process returns; retry briefly before treating the
166
+ # mutex owner as a genuinely running HUD.
167
+ $createdNew = $false
168
+ $mutexAttempts = if ($DockWindowHandle -ne 0) { 3 } else { 20 }
169
+ for ($mutexAttempt = 0; $mutexAttempt -lt $mutexAttempts; $mutexAttempt += 1) {
170
170
  $mutexName = if ($DockWindowHandle -ne 0) { "Local\AiBatteryTuiStatusline_$DockWindowHandle" } else { "Local\AiBatteryHud" }
171
- $script:singleInstanceMutex = [System.Threading.Mutex]::new($true, $mutexName, [ref]$createdNew)
172
- if ($createdNew) { break }
173
- $script:singleInstanceMutex.Dispose()
174
- $script:singleInstanceMutex = $null
175
- Start-Sleep -Milliseconds 150
176
- }
177
- if (-not $createdNew -and $DockWindowHandle -ne 0) {
178
- # A HUD is already running: ask it to adopt this dock target.
179
- $requestPath = Get-HudDockRequestPath
180
- $requestWritten = $false
181
- try {
171
+ $script:singleInstanceMutex = [System.Threading.Mutex]::new($true, $mutexName, [ref]$createdNew)
172
+ if ($createdNew) { break }
173
+ $script:singleInstanceMutex.Dispose()
174
+ $script:singleInstanceMutex = $null
175
+ Start-Sleep -Milliseconds 150
176
+ }
177
+ if (-not $createdNew -and $DockWindowHandle -ne 0) {
178
+ # A HUD is already running: ask it to adopt this dock target.
179
+ $requestPath = Get-HudDockRequestPath
180
+ $requestWritten = $false
181
+ try {
182
182
  $request = @{
183
183
  hwnd = [Int64]$DockWindowHandle
184
184
  placement = $DockPlacement
@@ -188,381 +188,381 @@ if (-not $Once) {
188
188
  markerPath = $DockMarkerPath
189
189
  at = [datetime]::UtcNow.ToString("o")
190
190
  } | ConvertTo-Json -Compress
191
- [System.IO.File]::WriteAllText($requestPath, $request, [System.Text.UTF8Encoding]::new($false))
192
- $requestWritten = $true
193
- } catch {
194
- # If the request cannot be written, fall through to the takeover check.
195
- }
196
-
197
- # A healthy HUD (docked or floating) consumes the request within a tick or
198
- # two. If it is still on disk the mutex owner is a zombie (e.g. an
199
- # orphaned instance from a killed session): replace it.
200
- $consumed = $false
201
- if ($requestWritten) {
202
- for ($wait = 0; $wait -lt 14; $wait += 1) {
203
- Start-Sleep -Milliseconds 150
204
- if (-not (Test-Path -LiteralPath $requestPath)) { $consumed = $true; break }
205
- }
206
- }
207
- if (-not $consumed) {
208
- Stop-ExistingHudProcesses $true
209
- Remove-Item -LiteralPath $requestPath -Force -ErrorAction SilentlyContinue
210
- for ($mutexAttempt = 0; $mutexAttempt -lt 20; $mutexAttempt += 1) {
211
- $script:singleInstanceMutex = [System.Threading.Mutex]::new($true, $mutexName, [ref]$createdNew)
212
- if ($createdNew) { break }
213
- $script:singleInstanceMutex.Dispose()
214
- $script:singleInstanceMutex = $null
215
- Start-Sleep -Milliseconds 150
216
- }
217
- }
218
- }
219
- if (-not $createdNew) {
220
- exit 0
221
- }
222
- }
223
-
224
- function Release-SingleInstance {
225
- if ($script:singleInstanceMutex) {
226
- try {
227
- $script:singleInstanceMutex.ReleaseMutex()
228
- } catch {
229
- # Already released.
230
- }
231
- $script:singleInstanceMutex.Dispose()
232
- $script:singleInstanceMutex = $null
233
- }
234
- }
235
-
236
- function Get-HudStatePath {
237
- $root = if ($env:LOCALAPPDATA) {
238
- Join-Path $env:LOCALAPPDATA "ai-battery"
239
- } else {
240
- Join-Path $env:TEMP "ai-battery"
241
- }
242
- New-Item -ItemType Directory -Force -Path $root | Out-Null
243
- return Join-Path $root "hud-position.json"
244
- }
245
-
246
- function Get-HudSourceId {
247
- if ($UseWsl) { return "wsl" }
248
- return "windows"
249
- }
250
-
251
- function Get-HudSnapshotPath {
252
- $root = if ($env:LOCALAPPDATA) {
253
- Join-Path $env:LOCALAPPDATA "ai-battery"
254
- } else {
255
- Join-Path $env:TEMP "ai-battery"
256
- }
257
- New-Item -ItemType Directory -Force -Path $root | Out-Null
258
- return Join-Path $root "hud-snapshot-$(Get-HudSourceId).json"
259
- }
260
-
261
- function Get-LegacyHudStatePath {
262
- $root = if ($env:LOCALAPPDATA) {
263
- Join-Path $env:LOCALAPPDATA "claudex-battery"
264
- } else {
265
- Join-Path $env:TEMP "claudex-battery"
266
- }
267
- return Join-Path $root "hud-position.json"
268
- }
269
-
270
- $script:hudAnchorX = "left"
271
- $script:hudAnchorY = "top"
272
- $script:codexRowVisible = $true
273
- $script:claudeRowVisible = $true
274
-
275
- function Signal-HudReady {
276
- if ([string]::IsNullOrWhiteSpace($ReadyPath)) { return }
277
- try {
278
- $dir = Split-Path -Parent $ReadyPath
279
- if ($dir) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
280
- @{
281
- Ready = $true
282
- Pid = $PID
283
- At = [datetime]::UtcNow.ToString("o")
284
- Mode = $Mode
285
- } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 -Path $ReadyPath
286
- } catch {
287
- # Readiness is diagnostic only.
288
- }
289
- }
290
-
291
- function Read-HudPlacement {
292
- foreach ($path in @((Get-HudStatePath), (Get-LegacyHudStatePath))) {
293
- try {
294
- if (-not (Test-Path $path)) { continue }
295
- $state = Get-Content $path -Raw | ConvertFrom-Json
296
- if ($null -ne $state.X -and $null -ne $state.Y) {
297
- return $state
298
- }
299
- } catch {
300
- # Try the next state path.
301
- }
302
- }
303
- return $null
304
- }
305
-
306
- function Read-HudPosition {
307
- $state = Read-HudPlacement
308
- if (-not $state) { return $null }
309
- return [System.Drawing.Point]::new([int]$state.X, [int]$state.Y)
310
- }
311
-
312
- function Write-HudPosition($Point) {
313
- try {
314
- $width = $null
315
- $height = $null
316
- if ($form -and -not $form.IsDisposed) {
317
- $width = [int]$form.Width
318
- $height = [int]$form.Height
319
- }
320
- @{
321
- X = [int]$Point.X
322
- Y = [int]$Point.Y
323
- Width = $width
324
- Height = $height
325
- } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 -Path (Get-HudStatePath)
326
- } catch {
327
- # Position persistence is helpful but not required for the HUD to run.
328
- }
329
- }
330
-
331
- function Get-SnapshotAgeSeconds($Snapshot) {
332
- if (-not $Snapshot -or -not $Snapshot.generatedAt) { return $null }
333
- try {
334
- return [math]::Max(0, [int](([datetime]::UtcNow - ([datetime]$Snapshot.generatedAt).ToUniversalTime()).TotalSeconds))
335
- } catch {
336
- return $null
337
- }
338
- }
339
-
340
- function Read-HudSnapshot {
341
- try {
342
- $path = Get-HudSnapshotPath
343
- if (-not (Test-Path $path)) { return $null }
344
- $snapshot = Get-Content $path -Raw | ConvertFrom-Json
345
- $age = Get-SnapshotAgeSeconds $snapshot
346
- $maxAge = if ($env:AI_BATTERY_HUD_CACHE_SECONDS) { [int]$env:AI_BATTERY_HUD_CACHE_SECONDS } else { 900 }
347
- if ($null -ne $age -and $age -le $maxAge) { return $snapshot }
348
- } catch {
349
- # Cached data is optional.
350
- }
351
- return $null
352
- }
353
-
354
- function Read-InitialHudSnapshot {
355
- if ([string]::IsNullOrWhiteSpace($InitialJsonBase64)) { return $null }
356
- try {
357
- $json = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($InitialJsonBase64))
358
- if ([string]::IsNullOrWhiteSpace($json)) { return $null }
359
- return $json | ConvertFrom-Json
360
- } catch {
361
- return $null
362
- }
363
- }
364
-
365
- function Write-HudSnapshot($Snapshot) {
366
- try {
367
- if (-not $Snapshot) { return }
368
- $Snapshot | Add-Member -NotePropertyName "hudSource" -NotePropertyValue (Get-HudSourceId) -Force
369
- $Snapshot | ConvertTo-Json -Depth 20 -Compress | Set-Content -Encoding UTF8 -Path (Get-HudSnapshotPath)
370
- } catch {
371
- # The HUD can still run without a warm-start cache.
372
- }
373
- }
374
-
375
- $script:initialHudSnapshot = Read-InitialHudSnapshot
376
-
377
- . (Join-Path $PSScriptRoot "native.ps1")
378
-
379
- . (Join-Path $PSScriptRoot "snapshot.ps1")
380
-
381
- if ($Once) {
382
- $texts = Get-Texts
383
- if ($texts.CodexVisible) { Write-Output "$($texts.Codex.Prefix)[battery]$($texts.Codex.Suffix)" }
384
- if ($texts.ClaudeVisible) { Write-Output "$($texts.Claude.Prefix)[battery]$($texts.Claude.Suffix)" }
385
- exit 0
386
- }
387
-
388
- Add-Type -AssemblyName System.Windows.Forms
389
- Add-Type -AssemblyName System.Drawing
390
- try {
391
- [System.Windows.Forms.Application]::SetHighDpiMode([System.Windows.Forms.HighDpiMode]::PerMonitorV2) | Out-Null
392
- } catch {
393
- # Windows PowerShell/.NET Framework does not expose SetHighDpiMode; the
394
- # native DPI awareness call above covers that runtime.
395
- }
396
- [System.Windows.Forms.Application]::EnableVisualStyles()
397
- try {
398
- [System.Windows.Forms.Application]::SetCompatibleTextRenderingDefault($false)
399
- } catch {
400
- # The default is already GDI text rendering on older WinForms.
401
- }
402
-
403
- . (Join-Path $PSScriptRoot "rendering.ps1")
404
-
405
- if ($Mode -eq "tray") {
406
- $context = [System.Windows.Forms.ApplicationContext]::new()
407
- $trayFont = [System.Drawing.Font]::new("Segoe UI", 9, [System.Drawing.FontStyle]::Regular)
408
- $menu = New-Object System.Windows.Forms.ContextMenuStrip
409
- $menu.Font = $trayFont
410
- $codexRow = New-StatusMenuRow $trayFont
411
- $claudeRow = New-StatusMenuRow $trayFont
412
- $menu.Items.Add($codexRow.Host) | Out-Null
413
- $menu.Items.Add($claudeRow.Host) | Out-Null
414
- $menu.Items.Add("-") | Out-Null
415
- $refreshItem = $menu.Items.Add("Refresh")
416
- $exitItem = $menu.Items.Add("Exit")
417
-
418
- $notifyIcon = New-Object System.Windows.Forms.NotifyIcon
419
- $notifyIcon.ContextMenuStrip = $menu
420
- $notifyIcon.Visible = $true
421
- $notifyIcon.Text = "AI Battery"
422
- $script:currentTrayIcon = $null
423
- $script:lastBalloonText = "AI Battery"
424
-
425
- function Set-SingleNotifyIcon($Texts) {
426
- $trayPercent = Select-TrayPercent $Texts
427
- $newIcon = New-SingleBatteryTrayIcon $trayPercent
428
- $oldIcon = $script:currentTrayIcon
429
- $notifyIcon.Icon = $newIcon
430
- $script:currentTrayIcon = $newIcon
431
- if ($oldIcon) { $oldIcon.Dispose() }
432
-
433
- $shortParts = @()
434
- if ($Texts.CodexVisible) {
435
- $shortParts += $(if ($null -ne $Texts.CodexResult.percentRemaining) { "Codex $($Texts.CodexResult.percentRemaining)%" } else { "Codex --%" })
436
- }
437
- if ($Texts.ClaudeVisible) {
438
- $shortParts += $(if ($null -ne $Texts.ClaudeResult.percentRemaining) { "Claude $($Texts.ClaudeResult.percentRemaining)%" } else { "Claude --%" })
439
- }
440
- $notifyIcon.Text = Limit-Text "AI Battery: $($shortParts -join ', ')" 63
441
- }
442
-
443
- function Update-Tray {
444
- try {
445
- $texts = Get-Texts
446
- $codexRow.Host.Visible = $texts.CodexVisible
447
- $claudeRow.Host.Visible = $texts.ClaudeVisible
448
- $codexLine = if ($texts.CodexVisible) { Get-LineText $texts.Codex } else { "" }
449
- $claudeLine = if ($texts.ClaudeVisible) { Get-LineText $texts.Claude } else { "" }
450
- if ($texts.CodexVisible) { Set-StatusMenuRow $codexRow $texts.Codex }
451
- if ($texts.ClaudeVisible) { Set-StatusMenuRow $claudeRow $texts.Claude }
452
-
453
- Set-SingleNotifyIcon $texts
454
- $script:lastBalloonText = (@($codexLine, $claudeLine) | Where-Object { $_ }) -join "`n"
455
- } catch {
456
- Set-StatusMenuRow $codexRow @{
457
- Prefix = "Codex "
458
- Percent = $null
459
- PercentText = "?"
460
- ResetText = ""
461
- WeekText = ""
462
- ExtraText = "unavailable"
463
- TextColor = [System.Drawing.Color]::FromArgb(255, 92, 92)
464
- }
465
- Set-StatusMenuRow $claudeRow @{
466
- Prefix = "Claude "
467
- Percent = $null
468
- PercentText = "?"
469
- ResetText = ""
470
- WeekText = ""
471
- ExtraText = ""
472
- TextColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
473
- }
474
- $newIcon = New-SingleBatteryTrayIcon $null
475
- $oldIcon = $script:currentTrayIcon
476
- $notifyIcon.Icon = $newIcon
477
- $script:currentTrayIcon = $newIcon
478
- if ($oldIcon) { $oldIcon.Dispose() }
479
- $notifyIcon.Text = "AI Battery unavailable"
480
- $script:lastBalloonText = "AI Battery unavailable"
481
- }
482
- }
483
-
484
- $refreshItem.add_Click({ Update-Tray })
485
- $exitItem.add_Click({
486
- $notifyIcon.Visible = $false
487
- Dispose-StatusMenuRow $codexRow
488
- Dispose-StatusMenuRow $claudeRow
489
- if ($notifyIcon.Icon) { $notifyIcon.Icon.Dispose() }
490
- $notifyIcon.Dispose()
491
- $trayFont.Dispose()
492
- Release-SingleInstance
493
- $context.ExitThread()
494
- })
495
- $openMenu = {
496
- param($sender, $event)
497
- if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
498
- Update-Tray
499
- $menu.Show([System.Windows.Forms.Cursor]::Position)
500
- }
501
- }
502
- $notifyIcon.add_MouseClick($openMenu)
503
-
504
- $timer = New-Object System.Windows.Forms.Timer
505
- $timer.Interval = [math]::Max(1, $Interval) * 1000
506
- $timer.add_Tick({ Update-Tray })
507
- Update-Tray
508
- $timer.Start()
509
- Signal-HudReady
510
- [System.Windows.Forms.Application]::Run($context)
511
- Release-SingleInstance
512
- exit 0
513
- }
514
-
515
- $script:dockTuiStatusline = ($DockWindowHandle -ne 0)
516
- $script:dockPlacementMode = $DockPlacement
517
- $script:dockStripHeight = if ($script:dockTuiStatusline) { Scale-HudValue 20 } else { 0 }
518
- $script:dockJoinOverlap = if ($script:dockTuiStatusline -and $script:dockPlacementMode -eq "bottom") { [math]::Max(1, (Scale-HudValue 8)) } else { 0 }
519
- $script:dockHorizontalInset = 0
520
- $script:dockLeftOpticalInset = 1
521
- $script:dockSquareCorners = $false
522
- $script:dockTuiResponsiveLayoutName = ""
523
- $script:dockTuiResponsiveThresholds = ""
191
+ [System.IO.File]::WriteAllText($requestPath, $request, [System.Text.UTF8Encoding]::new($false))
192
+ $requestWritten = $true
193
+ } catch {
194
+ # If the request cannot be written, fall through to the takeover check.
195
+ }
196
+
197
+ # A healthy HUD (docked or floating) consumes the request within a tick or
198
+ # two. If it is still on disk the mutex owner is a zombie (e.g. an
199
+ # orphaned instance from a killed session): replace it.
200
+ $consumed = $false
201
+ if ($requestWritten) {
202
+ for ($wait = 0; $wait -lt 14; $wait += 1) {
203
+ Start-Sleep -Milliseconds 150
204
+ if (-not (Test-Path -LiteralPath $requestPath)) { $consumed = $true; break }
205
+ }
206
+ }
207
+ if (-not $consumed) {
208
+ Stop-ExistingHudProcesses $true
209
+ Remove-Item -LiteralPath $requestPath -Force -ErrorAction SilentlyContinue
210
+ for ($mutexAttempt = 0; $mutexAttempt -lt 20; $mutexAttempt += 1) {
211
+ $script:singleInstanceMutex = [System.Threading.Mutex]::new($true, $mutexName, [ref]$createdNew)
212
+ if ($createdNew) { break }
213
+ $script:singleInstanceMutex.Dispose()
214
+ $script:singleInstanceMutex = $null
215
+ Start-Sleep -Milliseconds 150
216
+ }
217
+ }
218
+ }
219
+ if (-not $createdNew) {
220
+ exit 0
221
+ }
222
+ }
223
+
224
+ function Release-SingleInstance {
225
+ if ($script:singleInstanceMutex) {
226
+ try {
227
+ $script:singleInstanceMutex.ReleaseMutex()
228
+ } catch {
229
+ # Already released.
230
+ }
231
+ $script:singleInstanceMutex.Dispose()
232
+ $script:singleInstanceMutex = $null
233
+ }
234
+ }
235
+
236
+ function Get-HudStatePath {
237
+ $root = if ($env:LOCALAPPDATA) {
238
+ Join-Path $env:LOCALAPPDATA "ai-battery"
239
+ } else {
240
+ Join-Path $env:TEMP "ai-battery"
241
+ }
242
+ New-Item -ItemType Directory -Force -Path $root | Out-Null
243
+ return Join-Path $root "hud-position.json"
244
+ }
245
+
246
+ function Get-HudSourceId {
247
+ if ($UseWsl) { return "wsl" }
248
+ return "windows"
249
+ }
250
+
251
+ function Get-HudSnapshotPath {
252
+ $root = if ($env:LOCALAPPDATA) {
253
+ Join-Path $env:LOCALAPPDATA "ai-battery"
254
+ } else {
255
+ Join-Path $env:TEMP "ai-battery"
256
+ }
257
+ New-Item -ItemType Directory -Force -Path $root | Out-Null
258
+ return Join-Path $root "hud-snapshot-$(Get-HudSourceId).json"
259
+ }
260
+
261
+ function Get-LegacyHudStatePath {
262
+ $root = if ($env:LOCALAPPDATA) {
263
+ Join-Path $env:LOCALAPPDATA "claudex-battery"
264
+ } else {
265
+ Join-Path $env:TEMP "claudex-battery"
266
+ }
267
+ return Join-Path $root "hud-position.json"
268
+ }
269
+
270
+ $script:hudAnchorX = "left"
271
+ $script:hudAnchorY = "top"
272
+ $script:codexRowVisible = $true
273
+ $script:claudeRowVisible = $true
274
+
275
+ function Signal-HudReady {
276
+ if ([string]::IsNullOrWhiteSpace($ReadyPath)) { return }
277
+ try {
278
+ $dir = Split-Path -Parent $ReadyPath
279
+ if ($dir) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
280
+ @{
281
+ Ready = $true
282
+ Pid = $PID
283
+ At = [datetime]::UtcNow.ToString("o")
284
+ Mode = $Mode
285
+ } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 -Path $ReadyPath
286
+ } catch {
287
+ # Readiness is diagnostic only.
288
+ }
289
+ }
290
+
291
+ function Read-HudPlacement {
292
+ foreach ($path in @((Get-HudStatePath), (Get-LegacyHudStatePath))) {
293
+ try {
294
+ if (-not (Test-Path $path)) { continue }
295
+ $state = Get-Content $path -Raw | ConvertFrom-Json
296
+ if ($null -ne $state.X -and $null -ne $state.Y) {
297
+ return $state
298
+ }
299
+ } catch {
300
+ # Try the next state path.
301
+ }
302
+ }
303
+ return $null
304
+ }
305
+
306
+ function Read-HudPosition {
307
+ $state = Read-HudPlacement
308
+ if (-not $state) { return $null }
309
+ return [System.Drawing.Point]::new([int]$state.X, [int]$state.Y)
310
+ }
311
+
312
+ function Write-HudPosition($Point) {
313
+ try {
314
+ $width = $null
315
+ $height = $null
316
+ if ($form -and -not $form.IsDisposed) {
317
+ $width = [int]$form.Width
318
+ $height = [int]$form.Height
319
+ }
320
+ @{
321
+ X = [int]$Point.X
322
+ Y = [int]$Point.Y
323
+ Width = $width
324
+ Height = $height
325
+ } | ConvertTo-Json -Compress | Set-Content -Encoding UTF8 -Path (Get-HudStatePath)
326
+ } catch {
327
+ # Position persistence is helpful but not required for the HUD to run.
328
+ }
329
+ }
330
+
331
+ function Get-SnapshotAgeSeconds($Snapshot) {
332
+ if (-not $Snapshot -or -not $Snapshot.generatedAt) { return $null }
333
+ try {
334
+ return [math]::Max(0, [int](([datetime]::UtcNow - ([datetime]$Snapshot.generatedAt).ToUniversalTime()).TotalSeconds))
335
+ } catch {
336
+ return $null
337
+ }
338
+ }
339
+
340
+ function Read-HudSnapshot {
341
+ try {
342
+ $path = Get-HudSnapshotPath
343
+ if (-not (Test-Path $path)) { return $null }
344
+ $snapshot = Get-Content $path -Raw | ConvertFrom-Json
345
+ $age = Get-SnapshotAgeSeconds $snapshot
346
+ $maxAge = if ($env:AI_BATTERY_HUD_CACHE_SECONDS) { [int]$env:AI_BATTERY_HUD_CACHE_SECONDS } else { 900 }
347
+ if ($null -ne $age -and $age -le $maxAge) { return $snapshot }
348
+ } catch {
349
+ # Cached data is optional.
350
+ }
351
+ return $null
352
+ }
353
+
354
+ function Read-InitialHudSnapshot {
355
+ if ([string]::IsNullOrWhiteSpace($InitialJsonBase64)) { return $null }
356
+ try {
357
+ $json = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($InitialJsonBase64))
358
+ if ([string]::IsNullOrWhiteSpace($json)) { return $null }
359
+ return $json | ConvertFrom-Json
360
+ } catch {
361
+ return $null
362
+ }
363
+ }
364
+
365
+ function Write-HudSnapshot($Snapshot) {
366
+ try {
367
+ if (-not $Snapshot) { return }
368
+ $Snapshot | Add-Member -NotePropertyName "hudSource" -NotePropertyValue (Get-HudSourceId) -Force
369
+ $Snapshot | ConvertTo-Json -Depth 20 -Compress | Set-Content -Encoding UTF8 -Path (Get-HudSnapshotPath)
370
+ } catch {
371
+ # The HUD can still run without a warm-start cache.
372
+ }
373
+ }
374
+
375
+ $script:initialHudSnapshot = Read-InitialHudSnapshot
376
+
377
+ . (Join-Path $PSScriptRoot "native.ps1")
378
+
379
+ . (Join-Path $PSScriptRoot "snapshot.ps1")
380
+
381
+ if ($Once) {
382
+ $texts = Get-Texts
383
+ if ($texts.CodexVisible) { Write-Output "$($texts.Codex.Prefix)[battery]$($texts.Codex.Suffix)" }
384
+ if ($texts.ClaudeVisible) { Write-Output "$($texts.Claude.Prefix)[battery]$($texts.Claude.Suffix)" }
385
+ exit 0
386
+ }
387
+
388
+ Add-Type -AssemblyName System.Windows.Forms
389
+ Add-Type -AssemblyName System.Drawing
390
+ try {
391
+ [System.Windows.Forms.Application]::SetHighDpiMode([System.Windows.Forms.HighDpiMode]::PerMonitorV2) | Out-Null
392
+ } catch {
393
+ # Windows PowerShell/.NET Framework does not expose SetHighDpiMode; the
394
+ # native DPI awareness call above covers that runtime.
395
+ }
396
+ [System.Windows.Forms.Application]::EnableVisualStyles()
397
+ try {
398
+ [System.Windows.Forms.Application]::SetCompatibleTextRenderingDefault($false)
399
+ } catch {
400
+ # The default is already GDI text rendering on older WinForms.
401
+ }
402
+
403
+ . (Join-Path $PSScriptRoot "rendering.ps1")
404
+
405
+ if ($Mode -eq "tray") {
406
+ $context = [System.Windows.Forms.ApplicationContext]::new()
407
+ $trayFont = [System.Drawing.Font]::new("Segoe UI", 9, [System.Drawing.FontStyle]::Regular)
408
+ $menu = New-Object System.Windows.Forms.ContextMenuStrip
409
+ $menu.Font = $trayFont
410
+ $codexRow = New-StatusMenuRow $trayFont
411
+ $claudeRow = New-StatusMenuRow $trayFont
412
+ $menu.Items.Add($codexRow.Host) | Out-Null
413
+ $menu.Items.Add($claudeRow.Host) | Out-Null
414
+ $menu.Items.Add("-") | Out-Null
415
+ $refreshItem = $menu.Items.Add("Refresh")
416
+ $exitItem = $menu.Items.Add("Exit")
417
+
418
+ $notifyIcon = New-Object System.Windows.Forms.NotifyIcon
419
+ $notifyIcon.ContextMenuStrip = $menu
420
+ $notifyIcon.Visible = $true
421
+ $notifyIcon.Text = "AI Battery"
422
+ $script:currentTrayIcon = $null
423
+ $script:lastBalloonText = "AI Battery"
424
+
425
+ function Set-SingleNotifyIcon($Texts) {
426
+ $trayPercent = Select-TrayPercent $Texts
427
+ $newIcon = New-SingleBatteryTrayIcon $trayPercent
428
+ $oldIcon = $script:currentTrayIcon
429
+ $notifyIcon.Icon = $newIcon
430
+ $script:currentTrayIcon = $newIcon
431
+ if ($oldIcon) { $oldIcon.Dispose() }
432
+
433
+ $shortParts = @()
434
+ if ($Texts.CodexVisible) {
435
+ $shortParts += $(if ($null -ne $Texts.CodexResult.percentRemaining) { "Codex $($Texts.CodexResult.percentRemaining)%" } else { "Codex --%" })
436
+ }
437
+ if ($Texts.ClaudeVisible) {
438
+ $shortParts += $(if ($null -ne $Texts.ClaudeResult.percentRemaining) { "Claude $($Texts.ClaudeResult.percentRemaining)%" } else { "Claude --%" })
439
+ }
440
+ $notifyIcon.Text = Limit-Text "AI Battery: $($shortParts -join ', ')" 63
441
+ }
442
+
443
+ function Update-Tray {
444
+ try {
445
+ $texts = Get-Texts
446
+ $codexRow.Host.Visible = $texts.CodexVisible
447
+ $claudeRow.Host.Visible = $texts.ClaudeVisible
448
+ $codexLine = if ($texts.CodexVisible) { Get-LineText $texts.Codex } else { "" }
449
+ $claudeLine = if ($texts.ClaudeVisible) { Get-LineText $texts.Claude } else { "" }
450
+ if ($texts.CodexVisible) { Set-StatusMenuRow $codexRow $texts.Codex }
451
+ if ($texts.ClaudeVisible) { Set-StatusMenuRow $claudeRow $texts.Claude }
452
+
453
+ Set-SingleNotifyIcon $texts
454
+ $script:lastBalloonText = (@($codexLine, $claudeLine) | Where-Object { $_ }) -join "`n"
455
+ } catch {
456
+ Set-StatusMenuRow $codexRow @{
457
+ Prefix = "Codex "
458
+ Percent = $null
459
+ PercentText = "?"
460
+ ResetText = ""
461
+ WeekText = ""
462
+ ExtraText = "unavailable"
463
+ TextColor = [System.Drawing.Color]::FromArgb(255, 92, 92)
464
+ }
465
+ Set-StatusMenuRow $claudeRow @{
466
+ Prefix = "Claude "
467
+ Percent = $null
468
+ PercentText = "?"
469
+ ResetText = ""
470
+ WeekText = ""
471
+ ExtraText = ""
472
+ TextColor = [System.Drawing.Color]::FromArgb(145, 145, 145)
473
+ }
474
+ $newIcon = New-SingleBatteryTrayIcon $null
475
+ $oldIcon = $script:currentTrayIcon
476
+ $notifyIcon.Icon = $newIcon
477
+ $script:currentTrayIcon = $newIcon
478
+ if ($oldIcon) { $oldIcon.Dispose() }
479
+ $notifyIcon.Text = "AI Battery unavailable"
480
+ $script:lastBalloonText = "AI Battery unavailable"
481
+ }
482
+ }
483
+
484
+ $refreshItem.add_Click({ Update-Tray })
485
+ $exitItem.add_Click({
486
+ $notifyIcon.Visible = $false
487
+ Dispose-StatusMenuRow $codexRow
488
+ Dispose-StatusMenuRow $claudeRow
489
+ if ($notifyIcon.Icon) { $notifyIcon.Icon.Dispose() }
490
+ $notifyIcon.Dispose()
491
+ $trayFont.Dispose()
492
+ Release-SingleInstance
493
+ $context.ExitThread()
494
+ })
495
+ $openMenu = {
496
+ param($sender, $event)
497
+ if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
498
+ Update-Tray
499
+ $menu.Show([System.Windows.Forms.Cursor]::Position)
500
+ }
501
+ }
502
+ $notifyIcon.add_MouseClick($openMenu)
503
+
504
+ $timer = New-Object System.Windows.Forms.Timer
505
+ $timer.Interval = [math]::Max(1, $Interval) * 1000
506
+ $timer.add_Tick({ Update-Tray })
507
+ Update-Tray
508
+ $timer.Start()
509
+ Signal-HudReady
510
+ [System.Windows.Forms.Application]::Run($context)
511
+ Release-SingleInstance
512
+ exit 0
513
+ }
514
+
515
+ $script:dockTuiStatusline = ($DockWindowHandle -ne 0)
516
+ $script:dockPlacementMode = $DockPlacement
517
+ $script:dockStripHeight = if ($script:dockTuiStatusline) { Scale-HudValue 20 } else { 0 }
518
+ $script:dockJoinOverlap = if ($script:dockTuiStatusline -and $script:dockPlacementMode -eq "bottom") { [math]::Max(1, (Scale-HudValue 8)) } else { 0 }
519
+ $script:dockHorizontalInset = 0
520
+ $script:dockLeftOpticalInset = 1
521
+ $script:dockSquareCorners = $false
522
+ $script:dockTuiResponsiveLayoutName = ""
523
+ $script:dockTuiResponsiveThresholds = ""
524
524
  $script:dockOuterBorderColor = [System.Drawing.Color]::FromArgb(72, 72, 72)
525
525
  $form = New-Object System.Windows.Forms.Form
526
526
  $form.Text = "AI Battery"
527
527
  $form.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::None
528
528
  $form.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
529
- $form.Width = Scale-HudValue $Width
530
- $form.Height = if ($script:dockTuiStatusline) { $script:dockStripHeight + $script:dockJoinOverlap } elseif ($Mode -eq "floating") { Scale-HudValue 44 } elseif ($Mode -eq "statusline") { Scale-HudValue 44 } else { Scale-HudValue 54 }
531
- $script:hudTwoRowHeight = $form.Height
532
- $script:hudOneRowHeight = [math]::Max((Scale-HudValue 20), $form.Height - (Scale-HudValue 18))
533
- $form.TopMost = ($DockWindowHandle -eq 0)
534
- $form.ShowInTaskbar = $false
535
- $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
536
- $form.Padding = [System.Windows.Forms.Padding]::new(0)
537
- $script:hudTransparentSurface = if ($script:dockTuiStatusline) { $false } else { Test-HudTransparentSurface }
538
- $script:hudContrastBackdrop = Test-HudContrastBackdrop
539
- $script:hudChromeBackColor = if ($script:dockTuiStatusline) {
540
- [System.Drawing.Color]::FromArgb(12, 12, 12)
541
- } else {
542
- [System.Drawing.Color]::FromArgb(24, 24, 24)
543
- }
544
- if ($script:hudTransparentSurface) {
545
- $transparentBackColor = if ($script:hudDarkText -and (-not $script:hudContrastBackdrop)) {
546
- [System.Drawing.Color]::FromArgb(254, 254, 254)
547
- } else {
548
- [System.Drawing.Color]::FromArgb(18, 18, 18)
549
- }
550
- $form.BackColor = $transparentBackColor
551
- $form.TransparencyKey = $transparentBackColor
552
- } else {
553
- $form.BackColor = $script:hudChromeBackColor
554
- }
555
- $script:hudSurfaceBackColor = if ($script:hudContrastBackdrop -or (-not $script:hudTransparentSurface)) {
556
- $script:hudChromeBackColor
557
- } else {
558
- $form.BackColor
559
- }
560
- $form.Opacity = if ($script:dockTuiStatusline) {
561
- 1.0
562
- } else {
563
- [math]::Max(0.2, [math]::Min(1.0, $Opacity))
564
- }
565
-
529
+ $form.Width = Scale-HudValue $Width
530
+ $form.Height = if ($script:dockTuiStatusline) { $script:dockStripHeight + $script:dockJoinOverlap } elseif ($Mode -eq "floating") { Scale-HudValue 44 } elseif ($Mode -eq "statusline") { Scale-HudValue 44 } else { Scale-HudValue 54 }
531
+ $script:hudTwoRowHeight = $form.Height
532
+ $script:hudOneRowHeight = [math]::Max((Scale-HudValue 20), $form.Height - (Scale-HudValue 18))
533
+ $form.TopMost = ($DockWindowHandle -eq 0)
534
+ $form.ShowInTaskbar = $false
535
+ $form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
536
+ $form.Padding = [System.Windows.Forms.Padding]::new(0)
537
+ $script:hudTransparentSurface = if ($script:dockTuiStatusline) { $false } else { Test-HudTransparentSurface }
538
+ $script:hudContrastBackdrop = Test-HudContrastBackdrop
539
+ $script:hudChromeBackColor = if ($script:dockTuiStatusline) {
540
+ [System.Drawing.Color]::FromArgb(12, 12, 12)
541
+ } else {
542
+ [System.Drawing.Color]::FromArgb(24, 24, 24)
543
+ }
544
+ if ($script:hudTransparentSurface) {
545
+ $transparentBackColor = if ($script:hudDarkText -and (-not $script:hudContrastBackdrop)) {
546
+ [System.Drawing.Color]::FromArgb(254, 254, 254)
547
+ } else {
548
+ [System.Drawing.Color]::FromArgb(18, 18, 18)
549
+ }
550
+ $form.BackColor = $transparentBackColor
551
+ $form.TransparencyKey = $transparentBackColor
552
+ } else {
553
+ $form.BackColor = $script:hudChromeBackColor
554
+ }
555
+ $script:hudSurfaceBackColor = if ($script:hudContrastBackdrop -or (-not $script:hudTransparentSurface)) {
556
+ $script:hudChromeBackColor
557
+ } else {
558
+ $form.BackColor
559
+ }
560
+ $form.Opacity = if ($script:dockTuiStatusline) {
561
+ 1.0
562
+ } else {
563
+ [math]::Max(0.2, [math]::Min(1.0, $Opacity))
564
+ }
565
+
566
566
  function New-HudMainFont {
567
567
  if ($script:dockTuiStatusline) {
568
568
  # Use explicit physical pixels for the dock strip. Windows PowerShell's
@@ -591,245 +591,245 @@ function New-HudSymbolFont {
591
591
 
592
592
  $font = New-HudMainFont
593
593
  $symbolFont = New-HudSymbolFont
594
-
595
- $panel = New-Object System.Windows.Forms.TableLayoutPanel
596
- $panel.Dock = [System.Windows.Forms.DockStyle]::Fill
597
- $panel.RowCount = $(if ($script:dockTuiStatusline) { 1 } else { 2 })
598
- $panel.ColumnCount = 1
599
- $panel.GrowStyle = [System.Windows.Forms.TableLayoutPanelGrowStyle]::FixedSize
600
- $panel.Padding = if ($script:dockTuiStatusline) {
601
- New-HudPadding 8 2 2 2
602
- } elseif ($Mode -eq "floating" -or $Mode -eq "statusline") {
603
- New-HudPadding 6 4 2 3
604
- } else {
605
- New-HudPadding 10 7 10 6
606
- }
607
- $panel.BackColor = $script:hudSurfaceBackColor
608
- $panel.RowStyles.Add([System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, $(if ($script:dockTuiStatusline) { 100 } else { 50 }))) | Out-Null
609
- if (-not $script:dockTuiStatusline) {
610
- $panel.RowStyles.Add([System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)) | Out-Null
611
- }
612
- $panel.ColumnStyles.Add([System.Windows.Forms.ColumnStyle]::new([System.Windows.Forms.SizeType]::Percent, 100)) | Out-Null
613
-
614
- function New-HudRow {
615
- $row = New-Object System.Windows.Forms.FlowLayoutPanel
616
- $row.Dock = [System.Windows.Forms.DockStyle]::Fill
617
- $row.FlowDirection = [System.Windows.Forms.FlowDirection]::LeftToRight
618
- $row.WrapContents = $false
619
- $row.Margin = [System.Windows.Forms.Padding]::new(0)
620
- $row.Padding = [System.Windows.Forms.Padding]::new(0)
621
- $row.BackColor = $script:hudSurfaceBackColor
622
- return $row
623
- }
624
-
625
- function New-HudLabel([int]$RightMargin = 0) {
626
- $label = New-Object System.Windows.Forms.Label
627
- $label.AutoSize = $false
628
- $label.Width = 0
629
- $label.Height = Scale-HudValue 18
630
- $label.Font = $font
631
- $label.UseCompatibleTextRendering = $false
632
- $label.BackColor = $script:hudSurfaceBackColor
633
- $label.Margin = New-HudPadding 0 0 $RightMargin 0
634
- $label.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
635
- return $label
636
- }
637
-
638
- function New-HudIconBox {
639
- $box = New-Object System.Windows.Forms.PictureBox
640
- $box.Width = Scale-HudValue 40
641
- $box.Height = Scale-HudValue 18
642
- $box.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::Zoom
643
- $box.BackColor = $script:hudSurfaceBackColor
644
- $box.ForeColor = Get-HudBatteryTextColor $true
645
- $box.Margin = New-HudPadding 0 0 2 0
646
- $box.add_Paint({
647
- param($sender, $event)
648
- $text = [string]$sender.AccessibleName
649
- if ([string]::IsNullOrWhiteSpace($text)) { return }
650
-
651
- $drawFont = $null
652
- $disposeDrawFont = $false
653
- try {
654
- $drawFont = $font
655
- if (-not $drawFont) {
656
- $drawFont = [System.Drawing.Font]::new("Segoe UI", 9, [System.Drawing.FontStyle]::Regular)
657
- $disposeDrawFont = $true
658
- }
659
- $rect = [System.Drawing.Rectangle]::new(
660
- (Scale-HudValue 2),
661
- 0,
662
- [math]::Max(1, $sender.Width - (Scale-HudValue 4)),
663
- $sender.Height
664
- )
665
- $flags = [System.Windows.Forms.TextFormatFlags]::HorizontalCenter -bor
666
- [System.Windows.Forms.TextFormatFlags]::VerticalCenter -bor
667
- [System.Windows.Forms.TextFormatFlags]::SingleLine -bor
668
- [System.Windows.Forms.TextFormatFlags]::NoPadding
669
- [System.Windows.Forms.TextRenderer]::DrawText($event.Graphics, $text, $drawFont, $rect, $sender.ForeColor, $flags)
670
- } finally {
671
- if ($disposeDrawFont -and $drawFont) { $drawFont.Dispose() }
672
- }
673
- })
674
- return $box
675
- }
676
-
677
- function New-HudLineIconBox {
678
- $box = New-Object System.Windows.Forms.PictureBox
679
- $box.Width = Scale-HudValue 21
680
- $box.Height = Scale-HudValue 18
681
- $box.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
682
- $box.BackColor = $script:hudSurfaceBackColor
683
- $box.Margin = New-HudPadding 3 0 0 0
684
- return $box
685
- }
686
-
687
- function New-HudDivider {
688
- $divider = New-Object System.Windows.Forms.Panel
689
- $divider.AutoSize = $false
690
- $divider.Width = Scale-HudValue 1
691
- $divider.Height = Scale-HudValue 12
692
- $divider.BackColor = Get-DividerColor
693
- $divider.Margin = New-HudPadding 4 3 4 3
694
- return $divider
695
- }
696
-
697
- function Draw-TuiSegment($Graphics, [string]$Value, $Color, [ref]$X, [int]$Y, $DrawFont) {
698
- if ([string]::IsNullOrEmpty($Value)) { return }
699
- $flags = [System.Windows.Forms.TextFormatFlags]::NoPadding -bor
700
- [System.Windows.Forms.TextFormatFlags]::NoPrefix -bor
701
- [System.Windows.Forms.TextFormatFlags]::SingleLine
702
- [System.Windows.Forms.TextRenderer]::DrawText(
703
- $Graphics,
704
- $Value,
705
- $DrawFont,
706
- [System.Drawing.Point]::new([int]$X.Value, $Y),
707
- $Color,
708
- $flags
709
- )
710
- $size = [System.Windows.Forms.TextRenderer]::MeasureText(
711
- $Value,
712
- $DrawFont,
713
- [System.Drawing.Size]::new(4096, 64),
714
- $flags
715
- )
716
- $X.Value = [int]$X.Value + [int]$size.Width
717
- }
718
-
719
- function Get-TuiTextWidth([string]$Value, $DrawFont) {
720
- if ([string]::IsNullOrEmpty($Value)) { return 0 }
721
- $flags = [System.Windows.Forms.TextFormatFlags]::NoPadding -bor
722
- [System.Windows.Forms.TextFormatFlags]::NoPrefix -bor
723
- [System.Windows.Forms.TextFormatFlags]::SingleLine
724
- $size = [System.Windows.Forms.TextRenderer]::MeasureText(
725
- $Value,
726
- $DrawFont,
727
- [System.Drawing.Size]::new(4096, 64),
728
- $flags
729
- )
730
- return [int]$size.Width
731
- }
732
-
733
- function Get-TuiProviderDisplayValues($Result, [string]$Name, [int]$BarWidth, [bool]$ShowWindows) {
734
- $percent = if ($Result -and $Result.ok -and $null -ne $Result.percentRemaining) { [int]$Result.percentRemaining } else { $null }
735
- $values = [ordered]@{
736
- Prefix = $Name + " "
737
- Bar = ([string][char]0x275A) * $BarWidth
738
- Percent = $(if ($null -ne $percent) { " $percent%" } else { " --%" })
739
- Primary = ""
740
- Secondary = ""
741
- }
742
- if ($ShowWindows -and $Result -and $Result.primary) {
743
- $values.Primary = "$(Get-WindowText $Result.primary.windowMinutes) $(Get-ResetClock $Result.primary)"
744
- }
745
- if ($ShowWindows -and $Result -and $Result.secondary) {
746
- $values.Secondary = "$(Get-WindowText $Result.secondary.windowMinutes) $([int]$Result.secondary.remainingPercent)%"
747
- if ($Result.secondary.remainingPercent -le 10 -and -not $Result.secondary.resetPassed) {
748
- $values.Secondary += " $(Get-ResetClock $Result.secondary)"
749
- }
750
- }
751
- return [PSCustomObject]$values
752
- }
753
-
754
- function Get-TuiProviderDisplayWidth($Result, [string]$Name, $DrawFont, [int]$BarWidth, [bool]$ShowWindows) {
755
- $values = Get-TuiProviderDisplayValues $Result $Name $BarWidth $ShowWindows
756
- $width = (Get-TuiTextWidth $values.Prefix $DrawFont) +
757
- (Get-TuiTextWidth $values.Bar $DrawFont) +
758
- (Get-TuiTextWidth $values.Percent $DrawFont)
759
- $metricDivider = " $([char]0x2502) "
760
- if ($values.Primary) {
761
- $width += (Get-TuiTextWidth $metricDivider $DrawFont) + (Get-TuiTextWidth $values.Primary $DrawFont)
762
- }
763
- if ($values.Secondary) {
764
- $width += (Get-TuiTextWidth $metricDivider $DrawFont) + (Get-TuiTextWidth $values.Secondary $DrawFont)
765
- }
766
- return $width
767
- }
768
-
769
- function Get-DockedTuiResponsiveLayout($Codex, $Claude, $DrawFont, [int]$AvailableWidth) {
770
- # Preserve time-window information first, then trade bar length for it. Once
771
- # the windows no longer fit, return to a full ten-cell provider summary; that
772
- # summary still fits at Windows Terminal's minimum practical width.
773
- $candidates = @(
774
- [PSCustomObject]@{ Name = "full"; BarWidth = 10; ShowWindows = $true },
775
- [PSCustomObject]@{ Name = "metrics-half"; BarWidth = 5; ShowWindows = $true },
776
- [PSCustomObject]@{ Name = "summary-full"; BarWidth = 10; ShowWindows = $false }
777
- )
778
- $providerDividerWidth = if ($Codex -and $Claude) { Get-TuiTextWidth " $([char]0x2503) " $DrawFont } else { 0 }
779
- $requiredWidths = @()
780
- foreach ($candidate in $candidates) {
781
- $required = $providerDividerWidth
782
- if ($Codex) {
783
- $required += Get-TuiProviderDisplayWidth $Codex "Codex" $DrawFont $candidate.BarWidth $candidate.ShowWindows
784
- }
785
- if ($Claude) {
786
- $required += Get-TuiProviderDisplayWidth $Claude "Claude" $DrawFont $candidate.BarWidth $candidate.ShowWindows
787
- }
788
- $requiredWidths += $required
789
- }
790
-
791
- # The five-cell variants only save about 50 physical pixels for two
792
- # providers. Pure fit-based selection therefore makes those stages nearly
793
- # impossible to see while resizing. Give every density a useful interval,
794
- # while never selecting a layout below the width it actually requires.
795
- $fullThreshold = [int][math]::Ceiling($requiredWidths[0] * 1.08)
796
- $metricsHalfThreshold = [math]::Max($requiredWidths[1], [int][math]::Ceiling($requiredWidths[0] * 0.98))
797
- $script:dockTuiResponsiveThresholds = "$fullThreshold,$metricsHalfThreshold"
798
- if ($AvailableWidth -ge $fullThreshold) { return $candidates[0] }
799
- if ($AvailableWidth -ge $metricsHalfThreshold) { return $candidates[1] }
800
- return $candidates[2]
801
- }
802
-
594
+
595
+ $panel = New-Object System.Windows.Forms.TableLayoutPanel
596
+ $panel.Dock = [System.Windows.Forms.DockStyle]::Fill
597
+ $panel.RowCount = $(if ($script:dockTuiStatusline) { 1 } else { 2 })
598
+ $panel.ColumnCount = 1
599
+ $panel.GrowStyle = [System.Windows.Forms.TableLayoutPanelGrowStyle]::FixedSize
600
+ $panel.Padding = if ($script:dockTuiStatusline) {
601
+ New-HudPadding 8 2 2 2
602
+ } elseif ($Mode -eq "floating" -or $Mode -eq "statusline") {
603
+ New-HudPadding 6 4 2 3
604
+ } else {
605
+ New-HudPadding 10 7 10 6
606
+ }
607
+ $panel.BackColor = $script:hudSurfaceBackColor
608
+ $panel.RowStyles.Add([System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, $(if ($script:dockTuiStatusline) { 100 } else { 50 }))) | Out-Null
609
+ if (-not $script:dockTuiStatusline) {
610
+ $panel.RowStyles.Add([System.Windows.Forms.RowStyle]::new([System.Windows.Forms.SizeType]::Percent, 50)) | Out-Null
611
+ }
612
+ $panel.ColumnStyles.Add([System.Windows.Forms.ColumnStyle]::new([System.Windows.Forms.SizeType]::Percent, 100)) | Out-Null
613
+
614
+ function New-HudRow {
615
+ $row = New-Object System.Windows.Forms.FlowLayoutPanel
616
+ $row.Dock = [System.Windows.Forms.DockStyle]::Fill
617
+ $row.FlowDirection = [System.Windows.Forms.FlowDirection]::LeftToRight
618
+ $row.WrapContents = $false
619
+ $row.Margin = [System.Windows.Forms.Padding]::new(0)
620
+ $row.Padding = [System.Windows.Forms.Padding]::new(0)
621
+ $row.BackColor = $script:hudSurfaceBackColor
622
+ return $row
623
+ }
624
+
625
+ function New-HudLabel([int]$RightMargin = 0) {
626
+ $label = New-Object System.Windows.Forms.Label
627
+ $label.AutoSize = $false
628
+ $label.Width = 0
629
+ $label.Height = Scale-HudValue 18
630
+ $label.Font = $font
631
+ $label.UseCompatibleTextRendering = $false
632
+ $label.BackColor = $script:hudSurfaceBackColor
633
+ $label.Margin = New-HudPadding 0 0 $RightMargin 0
634
+ $label.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
635
+ return $label
636
+ }
637
+
638
+ function New-HudIconBox {
639
+ $box = New-Object System.Windows.Forms.PictureBox
640
+ $box.Width = Scale-HudValue 40
641
+ $box.Height = Scale-HudValue 18
642
+ $box.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::Zoom
643
+ $box.BackColor = $script:hudSurfaceBackColor
644
+ $box.ForeColor = Get-HudBatteryTextColor $true
645
+ $box.Margin = New-HudPadding 0 0 2 0
646
+ $box.add_Paint({
647
+ param($sender, $event)
648
+ $text = [string]$sender.AccessibleName
649
+ if ([string]::IsNullOrWhiteSpace($text)) { return }
650
+
651
+ $drawFont = $null
652
+ $disposeDrawFont = $false
653
+ try {
654
+ $drawFont = $font
655
+ if (-not $drawFont) {
656
+ $drawFont = [System.Drawing.Font]::new("Segoe UI", 9, [System.Drawing.FontStyle]::Regular)
657
+ $disposeDrawFont = $true
658
+ }
659
+ $rect = [System.Drawing.Rectangle]::new(
660
+ (Scale-HudValue 2),
661
+ 0,
662
+ [math]::Max(1, $sender.Width - (Scale-HudValue 4)),
663
+ $sender.Height
664
+ )
665
+ $flags = [System.Windows.Forms.TextFormatFlags]::HorizontalCenter -bor
666
+ [System.Windows.Forms.TextFormatFlags]::VerticalCenter -bor
667
+ [System.Windows.Forms.TextFormatFlags]::SingleLine -bor
668
+ [System.Windows.Forms.TextFormatFlags]::NoPadding
669
+ [System.Windows.Forms.TextRenderer]::DrawText($event.Graphics, $text, $drawFont, $rect, $sender.ForeColor, $flags)
670
+ } finally {
671
+ if ($disposeDrawFont -and $drawFont) { $drawFont.Dispose() }
672
+ }
673
+ })
674
+ return $box
675
+ }
676
+
677
+ function New-HudLineIconBox {
678
+ $box = New-Object System.Windows.Forms.PictureBox
679
+ $box.Width = Scale-HudValue 21
680
+ $box.Height = Scale-HudValue 18
681
+ $box.SizeMode = [System.Windows.Forms.PictureBoxSizeMode]::CenterImage
682
+ $box.BackColor = $script:hudSurfaceBackColor
683
+ $box.Margin = New-HudPadding 3 0 0 0
684
+ return $box
685
+ }
686
+
687
+ function New-HudDivider {
688
+ $divider = New-Object System.Windows.Forms.Panel
689
+ $divider.AutoSize = $false
690
+ $divider.Width = Scale-HudValue 1
691
+ $divider.Height = Scale-HudValue 12
692
+ $divider.BackColor = Get-DividerColor
693
+ $divider.Margin = New-HudPadding 4 3 4 3
694
+ return $divider
695
+ }
696
+
697
+ function Draw-TuiSegment($Graphics, [string]$Value, $Color, [ref]$X, [int]$Y, $DrawFont) {
698
+ if ([string]::IsNullOrEmpty($Value)) { return }
699
+ $flags = [System.Windows.Forms.TextFormatFlags]::NoPadding -bor
700
+ [System.Windows.Forms.TextFormatFlags]::NoPrefix -bor
701
+ [System.Windows.Forms.TextFormatFlags]::SingleLine
702
+ [System.Windows.Forms.TextRenderer]::DrawText(
703
+ $Graphics,
704
+ $Value,
705
+ $DrawFont,
706
+ [System.Drawing.Point]::new([int]$X.Value, $Y),
707
+ $Color,
708
+ $flags
709
+ )
710
+ $size = [System.Windows.Forms.TextRenderer]::MeasureText(
711
+ $Value,
712
+ $DrawFont,
713
+ [System.Drawing.Size]::new(4096, 64),
714
+ $flags
715
+ )
716
+ $X.Value = [int]$X.Value + [int]$size.Width
717
+ }
718
+
719
+ function Get-TuiTextWidth([string]$Value, $DrawFont) {
720
+ if ([string]::IsNullOrEmpty($Value)) { return 0 }
721
+ $flags = [System.Windows.Forms.TextFormatFlags]::NoPadding -bor
722
+ [System.Windows.Forms.TextFormatFlags]::NoPrefix -bor
723
+ [System.Windows.Forms.TextFormatFlags]::SingleLine
724
+ $size = [System.Windows.Forms.TextRenderer]::MeasureText(
725
+ $Value,
726
+ $DrawFont,
727
+ [System.Drawing.Size]::new(4096, 64),
728
+ $flags
729
+ )
730
+ return [int]$size.Width
731
+ }
732
+
733
+ function Get-TuiProviderDisplayValues($Result, [string]$Name, [int]$BarWidth, [bool]$ShowWindows) {
734
+ $percent = if ($Result -and $Result.ok -and $null -ne $Result.percentRemaining) { [int]$Result.percentRemaining } else { $null }
735
+ $values = [ordered]@{
736
+ Prefix = $Name + " "
737
+ Bar = ([string][char]0x275A) * $BarWidth
738
+ Percent = $(if ($null -ne $percent) { " $percent%" } else { " --%" })
739
+ Primary = ""
740
+ Secondary = ""
741
+ }
742
+ if ($ShowWindows -and $Result -and $Result.primary) {
743
+ $values.Primary = "$(Get-WindowText $Result.primary.windowMinutes) $(Get-ResetClock $Result.primary)"
744
+ }
745
+ if ($ShowWindows -and $Result -and $Result.secondary) {
746
+ $values.Secondary = "$(Get-WindowText $Result.secondary.windowMinutes) $([int]$Result.secondary.remainingPercent)%"
747
+ if ($Result.secondary.remainingPercent -le 10 -and -not $Result.secondary.resetPassed) {
748
+ $values.Secondary += " $(Get-ResetClock $Result.secondary)"
749
+ }
750
+ }
751
+ return [PSCustomObject]$values
752
+ }
753
+
754
+ function Get-TuiProviderDisplayWidth($Result, [string]$Name, $DrawFont, [int]$BarWidth, [bool]$ShowWindows) {
755
+ $values = Get-TuiProviderDisplayValues $Result $Name $BarWidth $ShowWindows
756
+ $width = (Get-TuiTextWidth $values.Prefix $DrawFont) +
757
+ (Get-TuiTextWidth $values.Bar $DrawFont) +
758
+ (Get-TuiTextWidth $values.Percent $DrawFont)
759
+ $metricDivider = " $([char]0x2502) "
760
+ if ($values.Primary) {
761
+ $width += (Get-TuiTextWidth $metricDivider $DrawFont) + (Get-TuiTextWidth $values.Primary $DrawFont)
762
+ }
763
+ if ($values.Secondary) {
764
+ $width += (Get-TuiTextWidth $metricDivider $DrawFont) + (Get-TuiTextWidth $values.Secondary $DrawFont)
765
+ }
766
+ return $width
767
+ }
768
+
769
+ function Get-DockedTuiResponsiveLayout($Codex, $Claude, $DrawFont, [int]$AvailableWidth) {
770
+ # Preserve time-window information first, then trade bar length for it. Once
771
+ # the windows no longer fit, return to a full ten-cell provider summary; that
772
+ # summary still fits at Windows Terminal's minimum practical width.
773
+ $candidates = @(
774
+ [PSCustomObject]@{ Name = "full"; BarWidth = 10; ShowWindows = $true },
775
+ [PSCustomObject]@{ Name = "metrics-half"; BarWidth = 5; ShowWindows = $true },
776
+ [PSCustomObject]@{ Name = "summary-full"; BarWidth = 10; ShowWindows = $false }
777
+ )
778
+ $providerDividerWidth = if ($Codex -and $Claude) { Get-TuiTextWidth " $([char]0x2503) " $DrawFont } else { 0 }
779
+ $requiredWidths = @()
780
+ foreach ($candidate in $candidates) {
781
+ $required = $providerDividerWidth
782
+ if ($Codex) {
783
+ $required += Get-TuiProviderDisplayWidth $Codex "Codex" $DrawFont $candidate.BarWidth $candidate.ShowWindows
784
+ }
785
+ if ($Claude) {
786
+ $required += Get-TuiProviderDisplayWidth $Claude "Claude" $DrawFont $candidate.BarWidth $candidate.ShowWindows
787
+ }
788
+ $requiredWidths += $required
789
+ }
790
+
791
+ # The five-cell variants only save about 50 physical pixels for two
792
+ # providers. Pure fit-based selection therefore makes those stages nearly
793
+ # impossible to see while resizing. Give every density a useful interval,
794
+ # while never selecting a layout below the width it actually requires.
795
+ $fullThreshold = [int][math]::Ceiling($requiredWidths[0] * 1.08)
796
+ $metricsHalfThreshold = [math]::Max($requiredWidths[1], [int][math]::Ceiling($requiredWidths[0] * 0.98))
797
+ $script:dockTuiResponsiveThresholds = "$fullThreshold,$metricsHalfThreshold"
798
+ if ($AvailableWidth -ge $fullThreshold) { return $candidates[0] }
799
+ if ($AvailableWidth -ge $metricsHalfThreshold) { return $candidates[1] }
800
+ return $candidates[2]
801
+ }
802
+
803
803
  function Draw-TuiProvider($Graphics, $Result, [string]$Name, [ref]$X, [int]$Y, $DrawFont, $Layout) {
804
804
  $running = Get-DockedTuiProviderRunning $Result $Name
805
- $textColor = if ($running) { [System.Drawing.Color]::FromArgb(255, 255, 255) } else { [System.Drawing.Color]::FromArgb(125, 125, 125) }
806
- $dividerColor = [System.Drawing.Color]::FromArgb(105, 105, 105)
807
- $percent = if ($Result -and $Result.ok -and $null -ne $Result.percentRemaining) { [int]$Result.percentRemaining } else { $null }
808
- $clamped = if ($null -ne $percent) { [math]::Max(0, [math]::Min(100, $percent)) } else { 0 }
809
- $barWidth = [math]::Max(1, [int]$Layout.BarWidth)
810
- $filled = if ($null -ne $percent) { [int][math]::Round(($clamped / 100.0) * $barWidth) } else { 0 }
811
- if ($clamped -gt 0 -and $filled -eq 0) { $filled = 1 }
812
- $barGlyph = [string][char]0x275A
813
- $values = Get-TuiProviderDisplayValues $Result $Name $barWidth ([bool]$Layout.ShowWindows)
814
-
815
- Draw-TuiSegment $Graphics $values.Prefix $textColor $X $Y $DrawFont
816
- $barStart = [int]$X.Value
817
- Draw-TuiSegment $Graphics $values.Bar ([System.Drawing.Color]::FromArgb(82, 82, 82)) $X $Y $DrawFont
818
- if ($filled -gt 0) {
819
- $overlayValue = $barStart
820
- $overlayX = [ref]$overlayValue
821
- Draw-TuiSegment $Graphics ($barGlyph * $filled) (Get-PercentColor $percent) $overlayX $Y $DrawFont
822
- }
823
- Draw-TuiSegment $Graphics $values.Percent $textColor $X $Y $DrawFont
824
-
825
- if ($values.Primary) {
826
- Draw-TuiSegment $Graphics " $([char]0x2502) " $dividerColor $X $Y $DrawFont
827
- Draw-TuiSegment $Graphics $values.Primary $textColor $X $Y $DrawFont
828
- }
829
- if ($values.Secondary) {
830
- Draw-TuiSegment $Graphics " $([char]0x2502) " $dividerColor $X $Y $DrawFont
831
- Draw-TuiSegment $Graphics $values.Secondary $textColor $X $Y $DrawFont
832
- }
805
+ $textColor = if ($running) { [System.Drawing.Color]::FromArgb(255, 255, 255) } else { [System.Drawing.Color]::FromArgb(125, 125, 125) }
806
+ $dividerColor = [System.Drawing.Color]::FromArgb(105, 105, 105)
807
+ $percent = if ($Result -and $Result.ok -and $null -ne $Result.percentRemaining) { [int]$Result.percentRemaining } else { $null }
808
+ $clamped = if ($null -ne $percent) { [math]::Max(0, [math]::Min(100, $percent)) } else { 0 }
809
+ $barWidth = [math]::Max(1, [int]$Layout.BarWidth)
810
+ $filled = if ($null -ne $percent) { [int][math]::Round(($clamped / 100.0) * $barWidth) } else { 0 }
811
+ if ($clamped -gt 0 -and $filled -eq 0) { $filled = 1 }
812
+ $barGlyph = [string][char]0x275A
813
+ $values = Get-TuiProviderDisplayValues $Result $Name $barWidth ([bool]$Layout.ShowWindows)
814
+
815
+ Draw-TuiSegment $Graphics $values.Prefix $textColor $X $Y $DrawFont
816
+ $barStart = [int]$X.Value
817
+ Draw-TuiSegment $Graphics $values.Bar ([System.Drawing.Color]::FromArgb(82, 82, 82)) $X $Y $DrawFont
818
+ if ($filled -gt 0) {
819
+ $overlayValue = $barStart
820
+ $overlayX = [ref]$overlayValue
821
+ Draw-TuiSegment $Graphics ($barGlyph * $filled) (Get-PercentColor $percent) $overlayX $Y $DrawFont
822
+ }
823
+ Draw-TuiSegment $Graphics $values.Percent $textColor $X $Y $DrawFont
824
+
825
+ if ($values.Primary) {
826
+ Draw-TuiSegment $Graphics " $([char]0x2502) " $dividerColor $X $Y $DrawFont
827
+ Draw-TuiSegment $Graphics $values.Primary $textColor $X $Y $DrawFont
828
+ }
829
+ if ($values.Secondary) {
830
+ Draw-TuiSegment $Graphics " $([char]0x2502) " $dividerColor $X $Y $DrawFont
831
+ Draw-TuiSegment $Graphics $values.Secondary $textColor $X $Y $DrawFont
832
+ }
833
833
  }
834
834
 
835
835
  function Get-DockedTuiProviderRunning($Result, [string]$Name) {
@@ -838,540 +838,540 @@ function Get-DockedTuiProviderRunning($Result, [string]$Name) {
838
838
  }
839
839
  return [bool]($Result -and $Result.running)
840
840
  }
841
-
842
- function Draw-DockedTuiStatusline($Graphics, [int]$Width, [int]$Height) {
843
- $snapshot = $script:latestSnapshot
844
- if (-not $snapshot -or -not $snapshot.results) { return }
845
- $codex = Get-Provider $snapshot "codex"
846
- $claude = Get-Provider $snapshot "claude"
847
- $xValue = Scale-HudValue 15
848
- $x = [ref]$xValue
849
- $rightPadding = Scale-HudValue 10
850
- $availableWidth = [math]::Max(1, $Width - $xValue - $rightPadding)
851
- $layout = Get-DockedTuiResponsiveLayout $codex $claude $font $availableWidth
852
- if ($script:dockTuiResponsiveLayoutName -ne $layout.Name) {
853
- $script:dockTuiResponsiveLayoutName = $layout.Name
854
- if (Get-Command Write-HudDockDebug -ErrorAction SilentlyContinue) {
855
- Write-HudDockDebug "dock responsive layout -> $($layout.Name) width=$availableWidth thresholds=$script:dockTuiResponsiveThresholds"
856
- }
857
- }
858
- $visibleTop = [math]::Max(0, [int]$script:dockJoinOverlap - (Scale-HudValue 2))
859
- $visibleHeight = [math]::Max(1, $Height - $visibleTop)
860
- $y = $visibleTop + [math]::Max(0, [int][math]::Floor(($visibleHeight - $font.Height) / 2) - 1)
861
- if ($codex) { Draw-TuiProvider $Graphics $codex "Codex" $x $y $font $layout }
862
- if ($codex -and $claude) {
863
- Draw-TuiSegment $Graphics " $([char]0x2503) " ([System.Drawing.Color]::FromArgb(150, 150, 150)) $x $y $font
864
- }
865
- if ($claude) { Draw-TuiProvider $Graphics $claude "Claude" $x $y $font $layout }
866
- }
867
-
868
- $script:dockTuiRenderKey = $null
869
-
870
- function Get-DockedTuiRenderKey($Snapshot) {
871
- if (-not $Snapshot -or -not $Snapshot.results) { return "empty" }
872
- $parts = @()
873
- foreach ($name in @("codex", "claude")) {
874
- $result = Get-Provider $Snapshot $name
875
- if (-not $result) { $parts += "$name`:missing"; continue }
876
- $primary = if ($result.primary) {
877
- "$(Get-WindowText $result.primary.windowMinutes):$(Get-ResetClock $result.primary)"
878
- } else { "" }
879
- $secondary = if ($result.secondary) {
880
- "$($result.secondary.windowMinutes):$($result.secondary.remainingPercent):$($result.secondary.resetPassed):$(Get-ResetClock $result.secondary)"
881
- } else { "" }
841
+
842
+ function Draw-DockedTuiStatusline($Graphics, [int]$Width, [int]$Height) {
843
+ $snapshot = $script:latestSnapshot
844
+ if (-not $snapshot -or -not $snapshot.results) { return }
845
+ $codex = Get-Provider $snapshot "codex"
846
+ $claude = Get-Provider $snapshot "claude"
847
+ $xValue = Scale-HudValue 15
848
+ $x = [ref]$xValue
849
+ $rightPadding = Scale-HudValue 10
850
+ $availableWidth = [math]::Max(1, $Width - $xValue - $rightPadding)
851
+ $layout = Get-DockedTuiResponsiveLayout $codex $claude $font $availableWidth
852
+ if ($script:dockTuiResponsiveLayoutName -ne $layout.Name) {
853
+ $script:dockTuiResponsiveLayoutName = $layout.Name
854
+ if (Get-Command Write-HudDockDebug -ErrorAction SilentlyContinue) {
855
+ Write-HudDockDebug "dock responsive layout -> $($layout.Name) width=$availableWidth thresholds=$script:dockTuiResponsiveThresholds"
856
+ }
857
+ }
858
+ $visibleTop = [math]::Max(0, [int]$script:dockJoinOverlap - (Scale-HudValue 2))
859
+ $visibleHeight = [math]::Max(1, $Height - $visibleTop)
860
+ $y = $visibleTop + [math]::Max(0, [int][math]::Floor(($visibleHeight - $font.Height) / 2) - 1)
861
+ if ($codex) { Draw-TuiProvider $Graphics $codex "Codex" $x $y $font $layout }
862
+ if ($codex -and $claude) {
863
+ Draw-TuiSegment $Graphics " $([char]0x2503) " ([System.Drawing.Color]::FromArgb(150, 150, 150)) $x $y $font
864
+ }
865
+ if ($claude) { Draw-TuiProvider $Graphics $claude "Claude" $x $y $font $layout }
866
+ }
867
+
868
+ $script:dockTuiRenderKey = $null
869
+
870
+ function Get-DockedTuiRenderKey($Snapshot) {
871
+ if (-not $Snapshot -or -not $Snapshot.results) { return "empty" }
872
+ $parts = @()
873
+ foreach ($name in @("codex", "claude")) {
874
+ $result = Get-Provider $Snapshot $name
875
+ if (-not $result) { $parts += "$name`:missing"; continue }
876
+ $primary = if ($result.primary) {
877
+ "$(Get-WindowText $result.primary.windowMinutes):$(Get-ResetClock $result.primary)"
878
+ } else { "" }
879
+ $secondary = if ($result.secondary) {
880
+ "$($result.secondary.windowMinutes):$($result.secondary.remainingPercent):$($result.secondary.resetPassed):$(Get-ResetClock $result.secondary)"
881
+ } else { "" }
882
882
  $running = Get-DockedTuiProviderRunning $result $name
883
883
  $parts += "$name`:$running`:$($result.ok):$($result.percentRemaining):$primary`:$secondary"
884
- }
885
- return $parts -join "|"
886
- }
887
-
888
- function Invalidate-DockedTuiIfChanged($Snapshot) {
889
- if (-not $script:dockTuiPaintPanel) { return }
890
- $nextKey = Get-DockedTuiRenderKey $Snapshot
891
- if ($script:dockTuiRenderKey -eq $nextKey) { return }
892
- $script:dockTuiRenderKey = $nextKey
893
- $script:dockTuiPaintPanel.Invalidate()
894
- }
895
-
896
- function Draw-DockedTuiOuterBorder($Graphics, [int]$Width, [int]$Height) {
897
- if (-not (Test-DockBottomPlacement) -or $Width -lt 4 -or $Height -lt 4) { return }
898
- $radius = [math]::Min((Scale-HudValue 8), [math]::Floor(($Height - 1) / 2))
899
- $left = [single]0.5
900
- $right = [single]($Width - 0.5)
901
- $bottom = [single]($Height - 0.5)
902
- $arcTop = [single]($Height - ($radius * 2) + 0.5)
903
- $arcDiameter = [single](($radius * 2) - 1)
904
- $rightArcLeft = [single]($Width - ($radius * 2) + 0.5)
905
- $path = [System.Drawing.Drawing2D.GraphicsPath]::new()
906
- $pen = [System.Drawing.Pen]::new($script:dockOuterBorderColor, 0.5)
907
- try {
908
- $pen.LineJoin = [System.Drawing.Drawing2D.LineJoin]::Round
909
- # The terminal covers the open top edge. Only the three exposed edges are
910
- # painted so the overlap cannot create a horizontal join line.
911
- $path.StartFigure()
912
- if ($script:dockSquareCorners) {
913
- $path.AddLine($left, [single]0, $left, $bottom)
914
- $path.AddLine($left, $bottom, $right, $bottom)
915
- $path.AddLine($right, $bottom, $right, [single]0)
916
- } else {
917
- $path.AddLine($left, [single]0, $left, [single]($Height - $radius))
918
- $path.AddArc($left, $arcTop, $arcDiameter, $arcDiameter, 180, -90)
919
- $path.AddLine([single]$radius, $bottom, [single]($Width - $radius), $bottom)
920
- $path.AddArc($rightArcLeft, $arcTop, $arcDiameter, $arcDiameter, 90, -90)
921
- $path.AddLine($right, [single]($Height - $radius), $right, [single]0)
922
- }
923
- $Graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
924
- $Graphics.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::GammaCorrected
925
- $Graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half
926
- $Graphics.DrawPath($pen, $path)
927
- } finally {
928
- $pen.Dispose()
929
- $path.Dispose()
930
- }
931
- }
932
-
933
- $codexRow = New-HudRow
934
- $claudeRow = New-HudRow
935
- $codexPrefixLabel = New-HudLabel
936
- $codexIconLabel = New-HudIconBox
937
- $codexDivider1 = New-HudDivider
938
- $codexResetLabel = New-HudLabel
939
- $codexDivider2 = New-HudDivider
940
- $codexWeekLabel = New-HudLabel
941
- $codexExtraLabel = New-HudLabel
942
- $claudePrefixLabel = New-HudLabel
943
- $claudeIconLabel = New-HudIconBox
944
- $claudeDivider1 = New-HudDivider
945
- $claudeResetLabel = New-HudLabel
946
- $claudeDivider2 = New-HudDivider
947
- $claudeWeekLabel = New-HudLabel
948
- $claudeExtraLabel = New-HudLabel
949
- $providerDivider = New-HudDivider
950
- $providerDivider.Margin = New-HudPadding 8 3 8 3
951
-
952
- foreach ($label in @($codexPrefixLabel, $claudePrefixLabel)) {
953
- $label.AutoSize = $false
954
- $label.Width = Scale-HudValue 48
955
- }
956
- foreach ($label in @($codexIconLabel, $claudeIconLabel)) {
957
- $label.Width = Scale-HudValue 42
958
- }
959
-
960
- $codexHudControls = @($codexPrefixLabel, $codexIconLabel, $codexDivider1, $codexResetLabel, $codexDivider2, $codexWeekLabel, $codexExtraLabel)
961
- $claudeHudControls = @($claudePrefixLabel, $claudeIconLabel, $claudeDivider1, $claudeResetLabel, $claudeDivider2, $claudeWeekLabel, $claudeExtraLabel)
962
-
963
- function Test-PointInBounds($Bounds, [System.Drawing.Point]$Point) {
964
- if (-not $Bounds) { return $false }
965
- return $Bounds.Contains($Point)
966
- }
967
-
968
- $menu = New-Object System.Windows.Forms.ContextMenuStrip
969
- $menu.Font = $font
970
- $menu.AutoClose = $true
971
- $script:hudMenuOpenedAt = [datetime]::UtcNow
972
- $script:hudMenuLastInsideAt = [datetime]::UtcNow
973
- $script:hudMenuReadyForOutsideClick = $false
974
- $exitItem = $menu.Items.Add("Exit")
975
- $exitItem.add_Click({ $form.Close() })
976
- $menu.add_Opened({
977
- $script:hudMenuOpenedAt = [datetime]::UtcNow
978
- $script:hudMenuLastInsideAt = [datetime]::UtcNow
979
- $script:hudMenuReadyForOutsideClick = $false
980
- })
981
- function Hide-HudMenu {
982
- if ($menu -and -not $menu.IsDisposed -and $menu.Visible) {
983
- $menu.Close([System.Windows.Forms.ToolStripDropDownCloseReason]::CloseCalled)
984
- }
985
- }
986
- $form.ContextMenuStrip = $menu
987
- $panel.ContextMenuStrip = $menu
988
-
989
- foreach ($label in $codexHudControls) {
990
- $label.ContextMenuStrip = $menu
991
- $codexRow.Controls.Add($label) | Out-Null
992
- }
993
- foreach ($label in $claudeHudControls) {
994
- $label.ContextMenuStrip = $menu
995
- $claudeRow.Controls.Add($label) | Out-Null
996
- }
997
- $codexRow.ContextMenuStrip = $menu
998
- $claudeRow.ContextMenuStrip = $menu
999
- $providerDivider.ContextMenuStrip = $menu
1000
- $script:dockCombinedRow = $null
1001
- $script:dockTuiPaintPanel = $null
1002
- if ($script:dockTuiStatusline) {
1003
- $script:dockTuiPaintPanel = New-Object System.Windows.Forms.Panel
1004
- $script:dockTuiPaintPanel.Dock = [System.Windows.Forms.DockStyle]::Fill
1005
- $script:dockTuiPaintPanel.Margin = [System.Windows.Forms.Padding]::new(0)
1006
- $script:dockTuiPaintPanel.BackColor = [System.Drawing.Color]::FromArgb(12, 12, 12)
1007
- $script:dockTuiPaintPanel.ContextMenuStrip = $menu
1008
- try {
1009
- $doubleBuffered = $script:dockTuiPaintPanel.GetType().GetProperty(
1010
- "DoubleBuffered",
1011
- ([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic)
1012
- )
1013
- if ($doubleBuffered) { $doubleBuffered.SetValue($script:dockTuiPaintPanel, $true, $null) }
1014
- } catch { }
1015
- $script:dockTuiPaintPanel.add_Paint({
1016
- param($sender, $event)
1017
- Draw-DockedTuiStatusline $event.Graphics $sender.Width $sender.Height
1018
- Draw-DockedTuiOuterBorder $event.Graphics $sender.Width $sender.Height
1019
- })
1020
- } else {
1021
- $panel.Controls.Add($codexRow, 0, 0) | Out-Null
1022
- $panel.Controls.Add($claudeRow, 0, 1) | Out-Null
1023
- }
1024
- if ($script:dockTuiStatusline) {
1025
- $form.Controls.Add($script:dockTuiPaintPanel)
1026
- } else {
1027
- $form.Controls.Add($panel)
1028
- }
1029
-
1030
- $hitForm = $null
884
+ }
885
+ return $parts -join "|"
886
+ }
887
+
888
+ function Invalidate-DockedTuiIfChanged($Snapshot) {
889
+ if (-not $script:dockTuiPaintPanel) { return }
890
+ $nextKey = Get-DockedTuiRenderKey $Snapshot
891
+ if ($script:dockTuiRenderKey -eq $nextKey) { return }
892
+ $script:dockTuiRenderKey = $nextKey
893
+ $script:dockTuiPaintPanel.Invalidate()
894
+ }
895
+
896
+ function Draw-DockedTuiOuterBorder($Graphics, [int]$Width, [int]$Height) {
897
+ if (-not (Test-DockBottomPlacement) -or $Width -lt 4 -or $Height -lt 4) { return }
898
+ $radius = [math]::Min((Scale-HudValue 8), [math]::Floor(($Height - 1) / 2))
899
+ $left = [single]0.5
900
+ $right = [single]($Width - 0.5)
901
+ $bottom = [single]($Height - 0.5)
902
+ $arcTop = [single]($Height - ($radius * 2) + 0.5)
903
+ $arcDiameter = [single](($radius * 2) - 1)
904
+ $rightArcLeft = [single]($Width - ($radius * 2) + 0.5)
905
+ $path = [System.Drawing.Drawing2D.GraphicsPath]::new()
906
+ $pen = [System.Drawing.Pen]::new($script:dockOuterBorderColor, 0.5)
907
+ try {
908
+ $pen.LineJoin = [System.Drawing.Drawing2D.LineJoin]::Round
909
+ # The terminal covers the open top edge. Only the three exposed edges are
910
+ # painted so the overlap cannot create a horizontal join line.
911
+ $path.StartFigure()
912
+ if ($script:dockSquareCorners) {
913
+ $path.AddLine($left, [single]0, $left, $bottom)
914
+ $path.AddLine($left, $bottom, $right, $bottom)
915
+ $path.AddLine($right, $bottom, $right, [single]0)
916
+ } else {
917
+ $path.AddLine($left, [single]0, $left, [single]($Height - $radius))
918
+ $path.AddArc($left, $arcTop, $arcDiameter, $arcDiameter, 180, -90)
919
+ $path.AddLine([single]$radius, $bottom, [single]($Width - $radius), $bottom)
920
+ $path.AddArc($rightArcLeft, $arcTop, $arcDiameter, $arcDiameter, 90, -90)
921
+ $path.AddLine($right, [single]($Height - $radius), $right, [single]0)
922
+ }
923
+ $Graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::HighQuality
924
+ $Graphics.CompositingQuality = [System.Drawing.Drawing2D.CompositingQuality]::GammaCorrected
925
+ $Graphics.PixelOffsetMode = [System.Drawing.Drawing2D.PixelOffsetMode]::Half
926
+ $Graphics.DrawPath($pen, $path)
927
+ } finally {
928
+ $pen.Dispose()
929
+ $path.Dispose()
930
+ }
931
+ }
932
+
933
+ $codexRow = New-HudRow
934
+ $claudeRow = New-HudRow
935
+ $codexPrefixLabel = New-HudLabel
936
+ $codexIconLabel = New-HudIconBox
937
+ $codexDivider1 = New-HudDivider
938
+ $codexResetLabel = New-HudLabel
939
+ $codexDivider2 = New-HudDivider
940
+ $codexWeekLabel = New-HudLabel
941
+ $codexExtraLabel = New-HudLabel
942
+ $claudePrefixLabel = New-HudLabel
943
+ $claudeIconLabel = New-HudIconBox
944
+ $claudeDivider1 = New-HudDivider
945
+ $claudeResetLabel = New-HudLabel
946
+ $claudeDivider2 = New-HudDivider
947
+ $claudeWeekLabel = New-HudLabel
948
+ $claudeExtraLabel = New-HudLabel
949
+ $providerDivider = New-HudDivider
950
+ $providerDivider.Margin = New-HudPadding 8 3 8 3
951
+
952
+ foreach ($label in @($codexPrefixLabel, $claudePrefixLabel)) {
953
+ $label.AutoSize = $false
954
+ $label.Width = Scale-HudValue 48
955
+ }
956
+ foreach ($label in @($codexIconLabel, $claudeIconLabel)) {
957
+ $label.Width = Scale-HudValue 42
958
+ }
959
+
960
+ $codexHudControls = @($codexPrefixLabel, $codexIconLabel, $codexDivider1, $codexResetLabel, $codexDivider2, $codexWeekLabel, $codexExtraLabel)
961
+ $claudeHudControls = @($claudePrefixLabel, $claudeIconLabel, $claudeDivider1, $claudeResetLabel, $claudeDivider2, $claudeWeekLabel, $claudeExtraLabel)
962
+
963
+ function Test-PointInBounds($Bounds, [System.Drawing.Point]$Point) {
964
+ if (-not $Bounds) { return $false }
965
+ return $Bounds.Contains($Point)
966
+ }
967
+
968
+ $menu = New-Object System.Windows.Forms.ContextMenuStrip
969
+ $menu.Font = $font
970
+ $menu.AutoClose = $true
971
+ $script:hudMenuOpenedAt = [datetime]::UtcNow
972
+ $script:hudMenuLastInsideAt = [datetime]::UtcNow
973
+ $script:hudMenuReadyForOutsideClick = $false
974
+ $exitItem = $menu.Items.Add("Exit")
975
+ $exitItem.add_Click({ $form.Close() })
976
+ $menu.add_Opened({
977
+ $script:hudMenuOpenedAt = [datetime]::UtcNow
978
+ $script:hudMenuLastInsideAt = [datetime]::UtcNow
979
+ $script:hudMenuReadyForOutsideClick = $false
980
+ })
981
+ function Hide-HudMenu {
982
+ if ($menu -and -not $menu.IsDisposed -and $menu.Visible) {
983
+ $menu.Close([System.Windows.Forms.ToolStripDropDownCloseReason]::CloseCalled)
984
+ }
985
+ }
986
+ $form.ContextMenuStrip = $menu
987
+ $panel.ContextMenuStrip = $menu
988
+
989
+ foreach ($label in $codexHudControls) {
990
+ $label.ContextMenuStrip = $menu
991
+ $codexRow.Controls.Add($label) | Out-Null
992
+ }
993
+ foreach ($label in $claudeHudControls) {
994
+ $label.ContextMenuStrip = $menu
995
+ $claudeRow.Controls.Add($label) | Out-Null
996
+ }
997
+ $codexRow.ContextMenuStrip = $menu
998
+ $claudeRow.ContextMenuStrip = $menu
999
+ $providerDivider.ContextMenuStrip = $menu
1000
+ $script:dockCombinedRow = $null
1001
+ $script:dockTuiPaintPanel = $null
1002
+ if ($script:dockTuiStatusline) {
1003
+ $script:dockTuiPaintPanel = New-Object System.Windows.Forms.Panel
1004
+ $script:dockTuiPaintPanel.Dock = [System.Windows.Forms.DockStyle]::Fill
1005
+ $script:dockTuiPaintPanel.Margin = [System.Windows.Forms.Padding]::new(0)
1006
+ $script:dockTuiPaintPanel.BackColor = [System.Drawing.Color]::FromArgb(12, 12, 12)
1007
+ $script:dockTuiPaintPanel.ContextMenuStrip = $menu
1008
+ try {
1009
+ $doubleBuffered = $script:dockTuiPaintPanel.GetType().GetProperty(
1010
+ "DoubleBuffered",
1011
+ ([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic)
1012
+ )
1013
+ if ($doubleBuffered) { $doubleBuffered.SetValue($script:dockTuiPaintPanel, $true, $null) }
1014
+ } catch { }
1015
+ $script:dockTuiPaintPanel.add_Paint({
1016
+ param($sender, $event)
1017
+ Draw-DockedTuiStatusline $event.Graphics $sender.Width $sender.Height
1018
+ Draw-DockedTuiOuterBorder $event.Graphics $sender.Width $sender.Height
1019
+ })
1020
+ } else {
1021
+ $panel.Controls.Add($codexRow, 0, 0) | Out-Null
1022
+ $panel.Controls.Add($claudeRow, 0, 1) | Out-Null
1023
+ }
1024
+ if ($script:dockTuiStatusline) {
1025
+ $form.Controls.Add($script:dockTuiPaintPanel)
1026
+ } else {
1027
+ $form.Controls.Add($panel)
1028
+ }
1029
+
1030
+ $hitForm = $null
1031
1031
  if ((-not $ClickThrough) -and $script:hudTransparentSurface) {
1032
1032
  $hitForm = New-Object System.Windows.Forms.Form
1033
1033
  $hitForm.Text = "AI Battery hit area"
1034
1034
  $hitForm.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::None
1035
1035
  $hitForm.Width = $form.Width
1036
- $hitForm.Height = $form.Height
1037
- $hitForm.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
1038
- $hitForm.ShowInTaskbar = $false
1039
- $hitForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
1040
- $hitForm.BackColor = [System.Drawing.Color]::Black
1041
- $hitForm.Opacity = 0.01
1042
- $hitForm.TopMost = ($DockWindowHandle -eq 0)
1043
- $hitForm.ContextMenuStrip = $menu
1044
- }
1045
-
1046
- function Sync-HitFormBounds {
1047
- if (-not $hitForm -or $hitForm.IsDisposed) { return }
1048
- $hitForm.Bounds = [System.Drawing.Rectangle]::new($form.Left, $form.Top, $form.Width, $form.Height)
1049
- }
1050
-
1051
- function Set-DockedTuiWindowRegion {
1052
- if (-not $script:dockTuiStatusline -or -not $form -or $form.IsDisposed) { return }
1053
- if ($form.Region) {
1054
- $oldRegion = $form.Region
1055
- $form.Region = $null
1056
- $oldRegion.Dispose()
1057
- }
1058
- $rounded = if (Test-DockBottomPlacement) { [AiBatteryNative]::DWMWCP_DONOTROUND } else { [AiBatteryNative]::DWMWCP_ROUND }
1059
- $ncRendering = if ($script:dockSquareCorners) { [AiBatteryNative]::DWMNCRP_DISABLED } else { [AiBatteryNative]::DWMNCRP_USEWINDOWSTYLE }
1060
- $noBorder = [AiBatteryNative]::DWMWA_COLOR_NONE
1061
- try {
1062
- [AiBatteryNative]::DwmSetWindowAttribute($form.Handle, [AiBatteryNative]::DWMWA_WINDOW_CORNER_PREFERENCE, [ref]$rounded, 4) | Out-Null
1063
- [AiBatteryNative]::DwmSetWindowAttribute($form.Handle, [AiBatteryNative]::DWMWA_BORDER_COLOR, [ref]$noBorder, 4) | Out-Null
1064
- [AiBatteryNative]::DwmSetWindowAttribute($form.Handle, [AiBatteryNative]::DWMWA_NCRENDERING_POLICY, [ref]$ncRendering, 4) | Out-Null
1065
- } catch { }
1066
- if (Test-DockBottomPlacement -and -not $script:dockSquareCorners) {
1067
- $radius = [math]::Min((Scale-HudValue 8), [math]::Floor($form.Height / 2))
1068
- $diameter = $radius * 2
1069
- $path = [System.Drawing.Drawing2D.GraphicsPath]::new()
1070
- try {
1071
- # A square top removes the sliver between the two HWNDs. The exposed
1072
- # bottom keeps the same rounded silhouette as Windows Terminal.
1073
- $path.StartFigure()
1074
- $path.AddLine(0, 0, $form.Width, 0)
1075
- $path.AddLine($form.Width, 0, $form.Width, ($form.Height - $radius))
1076
- $path.AddArc(($form.Width - $diameter), ($form.Height - $diameter), $diameter, $diameter, 0, 90)
1077
- $path.AddLine(($form.Width - $radius), $form.Height, $radius, $form.Height)
1078
- $path.AddArc(0, ($form.Height - $diameter), $diameter, $diameter, 90, 90)
1079
- $path.AddLine(0, ($form.Height - $radius), 0, 0)
1080
- $path.CloseFigure()
1081
- $form.Region = [System.Drawing.Region]::new($path)
1082
- } finally {
1083
- $path.Dispose()
1084
- }
1085
- }
1086
- }
1087
-
1088
- function Show-HitForm {
1089
- if (-not $hitForm -or $hitForm.IsDisposed) { return }
1090
- Sync-HitFormBounds
1091
- if (-not $hitForm.Visible) {
1092
- $hitForm.Show()
1093
- }
1094
- $style = [AiBatteryNative]::GetWindowLong($hitForm.Handle, [AiBatteryNative]::GWL_EXSTYLE)
1095
- $style = $style -bor [AiBatteryNative]::WS_EX_TOOLWINDOW -bor [AiBatteryNative]::WS_EX_NOACTIVATE
1096
- [AiBatteryNative]::SetWindowLong($hitForm.Handle, [AiBatteryNative]::GWL_EXSTYLE, $style) | Out-Null
1097
- }
1098
-
1099
- $dragging = $false
1100
- $dragOffset = [System.Drawing.Point]::new(0, 0)
1101
- $mouseDown = {
1102
- param($sender, $event)
1103
- if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
1104
- $script:dragging = $true
1105
- $screenPoint = $sender.PointToScreen([System.Drawing.Point]::new($event.X, $event.Y))
1106
- $script:dragOffset = [System.Drawing.Point]::new(
1107
- ($screenPoint.X - $form.Location.X),
1108
- ($screenPoint.Y - $form.Location.Y)
1109
- )
1110
- }
1111
- }
1112
- $mouseMove = {
1113
- param($sender, $event)
1114
- if ($script:dragging) {
1115
- $screenPoint = $sender.PointToScreen([System.Drawing.Point]::new($event.X, $event.Y))
1116
- $form.Location = [System.Drawing.Point]::new(($screenPoint.X - $script:dragOffset.X), ($screenPoint.Y - $script:dragOffset.Y))
1117
- Sync-HitFormBounds
1118
- }
1119
- }
1120
- $mouseUp = {
1121
- $script:dragging = $false
1122
- if ($canMove) {
1123
- Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1124
- Write-HudPosition $form.Location
1125
- Ensure-HudTopMost
1126
- }
1127
- }
1128
- # A docked HUD is glued to its terminal window; dragging and position saving
1129
- # are floating-mode concepts.
1130
- $canMove = ($DockWindowHandle -eq 0) -and ($Movable -or (($Mode -eq "floating") -and (-not $Locked)))
1131
- $script:positionSaveReady = $false
1132
- $script:hudHiddenForFullscreen = $false
1133
-
1134
- function Save-HudPositionIfReady {
1135
- if (-not $canMove -or -not $script:positionSaveReady) { return }
1136
- Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1137
- Write-HudPosition $form.Location
1138
- }
1139
-
1140
- if ($canMove) {
1141
- $dragControls = @($form, $panel, $codexRow, $claudeRow) + $codexHudControls + $claudeHudControls
1142
- if ($hitForm) { $dragControls += $hitForm }
1143
- foreach ($control in $dragControls) {
1144
- $control.add_MouseDown($mouseDown)
1145
- $control.add_MouseMove($mouseMove)
1146
- $control.add_MouseUp($mouseUp)
1147
- }
1148
- }
1149
-
1150
- . (Join-Path $PSScriptRoot "windowing.ps1")
1151
-
1152
- . (Join-Path $PSScriptRoot "dock.ps1")
1153
- Initialize-HudDockResizeGrip
1154
-
1155
- $script:fullscreenClearCount = 0
1156
-
1157
- function Update-HudVisibilityForFullscreen {
1158
- if (-not $form -or $form.IsDisposed) { return }
1159
- if ($script:dockTuiStatusline) {
1160
- # The docked strip is part of the terminal UI. Maximize/fullscreen/snap
1161
- # layouts are repaired by Update-HudDockPlacement instead of hiding it.
1162
- Set-HudHiddenForFullscreen $false
1163
- return
1164
- }
1165
- if (Test-FullscreenOnHudMonitor) {
1166
- $script:fullscreenClearCount = 0
1167
- Set-HudHiddenForFullscreen $true
1168
- return
1169
- }
1170
- if ($script:hudHiddenForFullscreen) {
1171
- $script:fullscreenClearCount += 1
1172
- if ($script:fullscreenClearCount -lt 2) { return }
1173
- }
1174
- $script:fullscreenClearCount = 0
1175
- Set-HudHiddenForFullscreen $false
1176
- Ensure-HudTopMost
1177
- }
1178
-
1179
- $script:fullscreenCheckPending = $false
1180
-
1181
- function Update-HudMenuAutoHide {
1182
- if (-not $menu -or $menu.IsDisposed -or -not $menu.Visible) { return }
1183
- $now = [datetime]::UtcNow
1184
- $point = [System.Windows.Forms.Cursor]::Position
1185
- $insideMenu = Test-PointInBounds $menu.Bounds $point
1186
- $insideHud = Test-PointInBounds $form.Bounds $point
1187
- if ($hitForm -and -not $hitForm.IsDisposed) {
1188
- $insideHud = $insideHud -or (Test-PointInBounds $hitForm.Bounds $point)
1189
- }
1190
-
1191
- if ($insideMenu -or $insideHud) {
1192
- $script:hudMenuLastInsideAt = $now
1193
- }
1194
-
1195
- $buttons = [System.Windows.Forms.Control]::MouseButtons
1196
- if (-not $script:hudMenuReadyForOutsideClick) {
1197
- if ($buttons -eq [System.Windows.Forms.MouseButtons]::None) {
1198
- $script:hudMenuReadyForOutsideClick = $true
1199
- }
1200
- return
1201
- }
1202
-
1203
- if ($buttons -ne [System.Windows.Forms.MouseButtons]::None -and -not $insideMenu) {
1204
- Hide-HudMenu
1205
- return
1206
- }
1207
-
1208
- if ((-not $insideMenu) -and (-not $insideHud) -and (($now - $script:hudMenuLastInsideAt).TotalMilliseconds -gt 1500)) {
1209
- Hide-HudMenu
1210
- }
1211
- }
1212
-
1213
- function Request-FullscreenCheck {
1214
- if (-not $form -or $form.IsDisposed) { return }
1215
- if ($form.InvokeRequired) {
1216
- if ($script:fullscreenCheckPending) { return }
1217
- $script:fullscreenCheckPending = $true
1218
- try {
1219
- $form.BeginInvoke([Action]{
1220
- $script:fullscreenCheckPending = $false
1221
- Apply-DockPendingMoveSizeState
1222
- Update-HudVisibilityForFullscreen
1223
- Update-HudDockPlacement
1224
- }) | Out-Null
1225
- } catch {
1226
- $script:fullscreenCheckPending = $false
1227
- }
1228
- return
1229
- }
1230
- Apply-DockPendingMoveSizeState
1231
- Update-HudVisibilityForFullscreen
1232
- Update-HudDockPlacement
1233
- }
1234
-
1235
- $script:fullscreenEventCallback = $null
1236
- $script:fullscreenEventHooks = @()
1237
-
1238
- function Start-FullscreenEventHooks {
1239
- if ($script:fullscreenEventCallback) { return }
1240
- $script:fullscreenEventCallback = [AiBatteryWinEventDelegate]{
1241
- param($hook, $eventType, $hwnd, $idObject, $idChild, $eventThread, $eventTime)
1242
- if ($script:dockTargetHandle -ne [IntPtr]::Zero) {
1243
- if (($eventType -eq [AiBatteryNative]::EVENT_SYSTEM_MOVESIZESTART -or
1244
- $eventType -eq [AiBatteryNative]::EVENT_SYSTEM_MOVESIZEEND) -and
1245
- $hwnd -eq $script:dockTargetHandle) {
1246
- Set-DockPendingMoveSizeState ($eventType -eq [AiBatteryNative]::EVENT_SYSTEM_MOVESIZESTART)
1247
- Request-FullscreenCheck
1248
- return
1249
- }
1250
- # Global reorder/location traffic is noisy and made the dock repeatedly
1251
- # show itself. The 150ms fallback still maintains relative Z-order.
1252
- if ($hwnd -ne $script:dockTargetHandle) { return }
1253
- }
1254
- if ($idObject -ne [AiBatteryNative]::OBJID_WINDOW) { return }
1255
- Request-FullscreenCheck
1256
- }
1257
-
1258
- $events = @(
1259
- [AiBatteryNative]::EVENT_SYSTEM_FOREGROUND,
1260
- [AiBatteryNative]::EVENT_SYSTEM_MOVESIZESTART,
1261
- [AiBatteryNative]::EVENT_SYSTEM_MOVESIZEEND,
1262
- [AiBatteryNative]::EVENT_OBJECT_SHOW,
1263
- [AiBatteryNative]::EVENT_OBJECT_HIDE,
1264
- [AiBatteryNative]::EVENT_OBJECT_REORDER,
1265
- [AiBatteryNative]::EVENT_OBJECT_LOCATIONCHANGE,
1266
- [AiBatteryNative]::EVENT_OBJECT_CLOAKED,
1267
- [AiBatteryNative]::EVENT_OBJECT_UNCLOAKED
1268
- )
1269
- $flags = [AiBatteryNative]::WINEVENT_OUTOFCONTEXT -bor [AiBatteryNative]::WINEVENT_SKIPOWNPROCESS
1270
- foreach ($eventId in $events) {
1271
- try {
1272
- $hook = [AiBatteryNative]::SetWinEventHook($eventId, $eventId, [IntPtr]::Zero, $script:fullscreenEventCallback, 0, 0, $flags)
1273
- if ($hook -ne [IntPtr]::Zero) {
1274
- $script:fullscreenEventHooks += $hook
1275
- }
1276
- } catch {
1277
- # Polling still covers older or restricted Windows environments.
1278
- }
1279
- }
1280
- }
1281
-
1282
- function Stop-FullscreenEventHooks {
1283
- foreach ($hook in $script:fullscreenEventHooks) {
1284
- try {
1285
- [AiBatteryNative]::UnhookWinEvent($hook) | Out-Null
1286
- } catch {
1287
- # The hook may already be gone during shutdown.
1288
- }
1289
- }
1290
- $script:fullscreenEventHooks = @()
1291
- $script:fullscreenEventCallback = $null
1292
- }
1293
-
1294
- . (Join-Path $PSScriptRoot "controls.ps1")
1295
-
1296
- $form.add_FormClosed({
1297
- Remove-HudDockHostMarker
1298
- try { Restore-DockTargetSpace } catch { }
1299
- if ($canMove) {
1300
- Write-HudPosition $form.Location
1301
- }
1302
- $timer.Stop()
1303
- $timer.Dispose()
1304
- $topMostTimer.Stop()
1305
- $topMostTimer.Dispose()
1306
- $menuAutoHideTimer.Stop()
1307
- $menuAutoHideTimer.Dispose()
1308
- Stop-FullscreenEventHooks
1309
- Stop-SnapshotFetch
1310
- foreach ($box in @($codexIconLabel, $claudeIconLabel)) {
1311
- if ($box.Image) {
1312
- $box.Image.Dispose()
1313
- $box.Image = $null
1314
- }
1315
- }
1316
- if ($menu -and -not $menu.IsDisposed) {
1317
- $menu.Dispose()
1318
- }
1319
- $font.Dispose()
1320
- $symbolFont.Dispose()
1321
- if ($hitForm -and -not $hitForm.IsDisposed) {
1322
- $hitForm.Close()
1323
- $hitForm.Dispose()
1324
- }
1325
- Release-SingleInstance
1326
- })
1327
-
1328
- $form.add_LocationChanged({
1329
- # No position save here: writing the state file on every drag pixel causes
1330
- # visible hitches. MouseUp and Resize-HudToContent persist the placement.
1331
- Sync-HitFormBounds
1332
- })
1333
- $form.add_SizeChanged({
1334
- Set-DockedTuiWindowRegion
1335
- Sync-HitFormBounds
1336
- })
1337
- $form.add_Shown({
1338
- Show-HitForm
1339
- Update-HudVisibilityForFullscreen
1340
- Update-HudDockPlacement
1341
- Signal-HudReady
1342
- })
1343
-
1344
- Set-Position
1345
- $script:positionSaveReady = $true
1346
-
1347
- $diskSnapshot = Read-HudSnapshot
1348
- if ($script:initialHudSnapshot) {
1349
- $script:latestSnapshot = Merge-HudSnapshot $script:initialHudSnapshot $diskSnapshot
1350
- $script:initialHudSnapshot = $null
1351
- Write-HudSnapshot $script:latestSnapshot
1352
- } else {
1353
- $script:latestSnapshot = $diskSnapshot
1354
- }
1355
- Update-HudFromSnapshot $script:latestSnapshot
1356
- Start-SnapshotFetch
1357
- $style = [AiBatteryNative]::GetWindowLong($form.Handle, [AiBatteryNative]::GWL_EXSTYLE)
1358
- $style = $style -bor [AiBatteryNative]::WS_EX_TOOLWINDOW -bor [AiBatteryNative]::WS_EX_NOACTIVATE
1359
- if ($ClickThrough) {
1360
- $style = $style -bor [AiBatteryNative]::WS_EX_TRANSPARENT
1361
- }
1362
- [AiBatteryNative]::SetWindowLong($form.Handle, [AiBatteryNative]::GWL_EXSTYLE, $style) | Out-Null
1363
- if ($script:dockTuiStatusline) {
1364
- $rounded = [AiBatteryNative]::DWMWCP_ROUND
1365
- try {
1366
- [AiBatteryNative]::DwmSetWindowAttribute($form.Handle, [AiBatteryNative]::DWMWA_WINDOW_CORNER_PREFERENCE, [ref]$rounded, 4) | Out-Null
1367
- } catch { }
1368
- Set-DockedTuiWindowRegion
1369
- }
1370
- $timer.Start()
1371
- Start-FullscreenEventHooks
1372
- $topMostTimer.Start()
1373
- $menuAutoHideTimer.Start()
1374
- Write-HudDockHostMarker
1375
- if ($env:AI_BATTERY_HUD_DEBUG_LOG) { Add-Content $env:AI_BATTERY_HUD_DEBUG_LOG "run dockTarget=$([Int64]$script:dockTargetHandle)" }
1376
- [System.Windows.Forms.Application]::Run($form)
1377
- if ($env:AI_BATTERY_HUD_DEBUG_LOG) { Add-Content $env:AI_BATTERY_HUD_DEBUG_LOG "run returned" }
1036
+ $hitForm.Height = $form.Height
1037
+ $hitForm.StartPosition = [System.Windows.Forms.FormStartPosition]::Manual
1038
+ $hitForm.ShowInTaskbar = $false
1039
+ $hitForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::None
1040
+ $hitForm.BackColor = [System.Drawing.Color]::Black
1041
+ $hitForm.Opacity = 0.01
1042
+ $hitForm.TopMost = ($DockWindowHandle -eq 0)
1043
+ $hitForm.ContextMenuStrip = $menu
1044
+ }
1045
+
1046
+ function Sync-HitFormBounds {
1047
+ if (-not $hitForm -or $hitForm.IsDisposed) { return }
1048
+ $hitForm.Bounds = [System.Drawing.Rectangle]::new($form.Left, $form.Top, $form.Width, $form.Height)
1049
+ }
1050
+
1051
+ function Set-DockedTuiWindowRegion {
1052
+ if (-not $script:dockTuiStatusline -or -not $form -or $form.IsDisposed) { return }
1053
+ if ($form.Region) {
1054
+ $oldRegion = $form.Region
1055
+ $form.Region = $null
1056
+ $oldRegion.Dispose()
1057
+ }
1058
+ $rounded = if (Test-DockBottomPlacement) { [AiBatteryNative]::DWMWCP_DONOTROUND } else { [AiBatteryNative]::DWMWCP_ROUND }
1059
+ $ncRendering = if ($script:dockSquareCorners) { [AiBatteryNative]::DWMNCRP_DISABLED } else { [AiBatteryNative]::DWMNCRP_USEWINDOWSTYLE }
1060
+ $noBorder = [AiBatteryNative]::DWMWA_COLOR_NONE
1061
+ try {
1062
+ [AiBatteryNative]::DwmSetWindowAttribute($form.Handle, [AiBatteryNative]::DWMWA_WINDOW_CORNER_PREFERENCE, [ref]$rounded, 4) | Out-Null
1063
+ [AiBatteryNative]::DwmSetWindowAttribute($form.Handle, [AiBatteryNative]::DWMWA_BORDER_COLOR, [ref]$noBorder, 4) | Out-Null
1064
+ [AiBatteryNative]::DwmSetWindowAttribute($form.Handle, [AiBatteryNative]::DWMWA_NCRENDERING_POLICY, [ref]$ncRendering, 4) | Out-Null
1065
+ } catch { }
1066
+ if (Test-DockBottomPlacement -and -not $script:dockSquareCorners) {
1067
+ $radius = [math]::Min((Scale-HudValue 8), [math]::Floor($form.Height / 2))
1068
+ $diameter = $radius * 2
1069
+ $path = [System.Drawing.Drawing2D.GraphicsPath]::new()
1070
+ try {
1071
+ # A square top removes the sliver between the two HWNDs. The exposed
1072
+ # bottom keeps the same rounded silhouette as Windows Terminal.
1073
+ $path.StartFigure()
1074
+ $path.AddLine(0, 0, $form.Width, 0)
1075
+ $path.AddLine($form.Width, 0, $form.Width, ($form.Height - $radius))
1076
+ $path.AddArc(($form.Width - $diameter), ($form.Height - $diameter), $diameter, $diameter, 0, 90)
1077
+ $path.AddLine(($form.Width - $radius), $form.Height, $radius, $form.Height)
1078
+ $path.AddArc(0, ($form.Height - $diameter), $diameter, $diameter, 90, 90)
1079
+ $path.AddLine(0, ($form.Height - $radius), 0, 0)
1080
+ $path.CloseFigure()
1081
+ $form.Region = [System.Drawing.Region]::new($path)
1082
+ } finally {
1083
+ $path.Dispose()
1084
+ }
1085
+ }
1086
+ }
1087
+
1088
+ function Show-HitForm {
1089
+ if (-not $hitForm -or $hitForm.IsDisposed) { return }
1090
+ Sync-HitFormBounds
1091
+ if (-not $hitForm.Visible) {
1092
+ $hitForm.Show()
1093
+ }
1094
+ $style = [AiBatteryNative]::GetWindowLong($hitForm.Handle, [AiBatteryNative]::GWL_EXSTYLE)
1095
+ $style = $style -bor [AiBatteryNative]::WS_EX_TOOLWINDOW -bor [AiBatteryNative]::WS_EX_NOACTIVATE
1096
+ [AiBatteryNative]::SetWindowLong($hitForm.Handle, [AiBatteryNative]::GWL_EXSTYLE, $style) | Out-Null
1097
+ }
1098
+
1099
+ $dragging = $false
1100
+ $dragOffset = [System.Drawing.Point]::new(0, 0)
1101
+ $mouseDown = {
1102
+ param($sender, $event)
1103
+ if ($event.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
1104
+ $script:dragging = $true
1105
+ $screenPoint = $sender.PointToScreen([System.Drawing.Point]::new($event.X, $event.Y))
1106
+ $script:dragOffset = [System.Drawing.Point]::new(
1107
+ ($screenPoint.X - $form.Location.X),
1108
+ ($screenPoint.Y - $form.Location.Y)
1109
+ )
1110
+ }
1111
+ }
1112
+ $mouseMove = {
1113
+ param($sender, $event)
1114
+ if ($script:dragging) {
1115
+ $screenPoint = $sender.PointToScreen([System.Drawing.Point]::new($event.X, $event.Y))
1116
+ $form.Location = [System.Drawing.Point]::new(($screenPoint.X - $script:dragOffset.X), ($screenPoint.Y - $script:dragOffset.Y))
1117
+ Sync-HitFormBounds
1118
+ }
1119
+ }
1120
+ $mouseUp = {
1121
+ $script:dragging = $false
1122
+ if ($canMove) {
1123
+ Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1124
+ Write-HudPosition $form.Location
1125
+ Ensure-HudTopMost
1126
+ }
1127
+ }
1128
+ # A docked HUD is glued to its terminal window; dragging and position saving
1129
+ # are floating-mode concepts.
1130
+ $canMove = ($DockWindowHandle -eq 0) -and ($Movable -or (($Mode -eq "floating") -and (-not $Locked)))
1131
+ $script:positionSaveReady = $false
1132
+ $script:hudHiddenForFullscreen = $false
1133
+
1134
+ function Save-HudPositionIfReady {
1135
+ if (-not $canMove -or -not $script:positionSaveReady) { return }
1136
+ Set-HudAnchorFromPlacement $form.Location ([Nullable[int]]$form.Width) ([Nullable[int]]$form.Height)
1137
+ Write-HudPosition $form.Location
1138
+ }
1139
+
1140
+ if ($canMove) {
1141
+ $dragControls = @($form, $panel, $codexRow, $claudeRow) + $codexHudControls + $claudeHudControls
1142
+ if ($hitForm) { $dragControls += $hitForm }
1143
+ foreach ($control in $dragControls) {
1144
+ $control.add_MouseDown($mouseDown)
1145
+ $control.add_MouseMove($mouseMove)
1146
+ $control.add_MouseUp($mouseUp)
1147
+ }
1148
+ }
1149
+
1150
+ . (Join-Path $PSScriptRoot "windowing.ps1")
1151
+
1152
+ . (Join-Path $PSScriptRoot "dock.ps1")
1153
+ Initialize-HudDockResizeGrip
1154
+
1155
+ $script:fullscreenClearCount = 0
1156
+
1157
+ function Update-HudVisibilityForFullscreen {
1158
+ if (-not $form -or $form.IsDisposed) { return }
1159
+ if ($script:dockTuiStatusline) {
1160
+ # The docked strip is part of the terminal UI. Maximize/fullscreen/snap
1161
+ # layouts are repaired by Update-HudDockPlacement instead of hiding it.
1162
+ Set-HudHiddenForFullscreen $false
1163
+ return
1164
+ }
1165
+ if (Test-FullscreenOnHudMonitor) {
1166
+ $script:fullscreenClearCount = 0
1167
+ Set-HudHiddenForFullscreen $true
1168
+ return
1169
+ }
1170
+ if ($script:hudHiddenForFullscreen) {
1171
+ $script:fullscreenClearCount += 1
1172
+ if ($script:fullscreenClearCount -lt 2) { return }
1173
+ }
1174
+ $script:fullscreenClearCount = 0
1175
+ Set-HudHiddenForFullscreen $false
1176
+ Ensure-HudTopMost
1177
+ }
1178
+
1179
+ $script:fullscreenCheckPending = $false
1180
+
1181
+ function Update-HudMenuAutoHide {
1182
+ if (-not $menu -or $menu.IsDisposed -or -not $menu.Visible) { return }
1183
+ $now = [datetime]::UtcNow
1184
+ $point = [System.Windows.Forms.Cursor]::Position
1185
+ $insideMenu = Test-PointInBounds $menu.Bounds $point
1186
+ $insideHud = Test-PointInBounds $form.Bounds $point
1187
+ if ($hitForm -and -not $hitForm.IsDisposed) {
1188
+ $insideHud = $insideHud -or (Test-PointInBounds $hitForm.Bounds $point)
1189
+ }
1190
+
1191
+ if ($insideMenu -or $insideHud) {
1192
+ $script:hudMenuLastInsideAt = $now
1193
+ }
1194
+
1195
+ $buttons = [System.Windows.Forms.Control]::MouseButtons
1196
+ if (-not $script:hudMenuReadyForOutsideClick) {
1197
+ if ($buttons -eq [System.Windows.Forms.MouseButtons]::None) {
1198
+ $script:hudMenuReadyForOutsideClick = $true
1199
+ }
1200
+ return
1201
+ }
1202
+
1203
+ if ($buttons -ne [System.Windows.Forms.MouseButtons]::None -and -not $insideMenu) {
1204
+ Hide-HudMenu
1205
+ return
1206
+ }
1207
+
1208
+ if ((-not $insideMenu) -and (-not $insideHud) -and (($now - $script:hudMenuLastInsideAt).TotalMilliseconds -gt 1500)) {
1209
+ Hide-HudMenu
1210
+ }
1211
+ }
1212
+
1213
+ function Request-FullscreenCheck {
1214
+ if (-not $form -or $form.IsDisposed) { return }
1215
+ if ($form.InvokeRequired) {
1216
+ if ($script:fullscreenCheckPending) { return }
1217
+ $script:fullscreenCheckPending = $true
1218
+ try {
1219
+ $form.BeginInvoke([Action]{
1220
+ $script:fullscreenCheckPending = $false
1221
+ Apply-DockPendingMoveSizeState
1222
+ Update-HudVisibilityForFullscreen
1223
+ Update-HudDockPlacement
1224
+ }) | Out-Null
1225
+ } catch {
1226
+ $script:fullscreenCheckPending = $false
1227
+ }
1228
+ return
1229
+ }
1230
+ Apply-DockPendingMoveSizeState
1231
+ Update-HudVisibilityForFullscreen
1232
+ Update-HudDockPlacement
1233
+ }
1234
+
1235
+ $script:fullscreenEventCallback = $null
1236
+ $script:fullscreenEventHooks = @()
1237
+
1238
+ function Start-FullscreenEventHooks {
1239
+ if ($script:fullscreenEventCallback) { return }
1240
+ $script:fullscreenEventCallback = [AiBatteryWinEventDelegate]{
1241
+ param($hook, $eventType, $hwnd, $idObject, $idChild, $eventThread, $eventTime)
1242
+ if ($script:dockTargetHandle -ne [IntPtr]::Zero) {
1243
+ if (($eventType -eq [AiBatteryNative]::EVENT_SYSTEM_MOVESIZESTART -or
1244
+ $eventType -eq [AiBatteryNative]::EVENT_SYSTEM_MOVESIZEEND) -and
1245
+ $hwnd -eq $script:dockTargetHandle) {
1246
+ Set-DockPendingMoveSizeState ($eventType -eq [AiBatteryNative]::EVENT_SYSTEM_MOVESIZESTART)
1247
+ Request-FullscreenCheck
1248
+ return
1249
+ }
1250
+ # Global reorder/location traffic is noisy and made the dock repeatedly
1251
+ # show itself. The 150ms fallback still maintains relative Z-order.
1252
+ if ($hwnd -ne $script:dockTargetHandle) { return }
1253
+ }
1254
+ if ($idObject -ne [AiBatteryNative]::OBJID_WINDOW) { return }
1255
+ Request-FullscreenCheck
1256
+ }
1257
+
1258
+ $events = @(
1259
+ [AiBatteryNative]::EVENT_SYSTEM_FOREGROUND,
1260
+ [AiBatteryNative]::EVENT_SYSTEM_MOVESIZESTART,
1261
+ [AiBatteryNative]::EVENT_SYSTEM_MOVESIZEEND,
1262
+ [AiBatteryNative]::EVENT_OBJECT_SHOW,
1263
+ [AiBatteryNative]::EVENT_OBJECT_HIDE,
1264
+ [AiBatteryNative]::EVENT_OBJECT_REORDER,
1265
+ [AiBatteryNative]::EVENT_OBJECT_LOCATIONCHANGE,
1266
+ [AiBatteryNative]::EVENT_OBJECT_CLOAKED,
1267
+ [AiBatteryNative]::EVENT_OBJECT_UNCLOAKED
1268
+ )
1269
+ $flags = [AiBatteryNative]::WINEVENT_OUTOFCONTEXT -bor [AiBatteryNative]::WINEVENT_SKIPOWNPROCESS
1270
+ foreach ($eventId in $events) {
1271
+ try {
1272
+ $hook = [AiBatteryNative]::SetWinEventHook($eventId, $eventId, [IntPtr]::Zero, $script:fullscreenEventCallback, 0, 0, $flags)
1273
+ if ($hook -ne [IntPtr]::Zero) {
1274
+ $script:fullscreenEventHooks += $hook
1275
+ }
1276
+ } catch {
1277
+ # Polling still covers older or restricted Windows environments.
1278
+ }
1279
+ }
1280
+ }
1281
+
1282
+ function Stop-FullscreenEventHooks {
1283
+ foreach ($hook in $script:fullscreenEventHooks) {
1284
+ try {
1285
+ [AiBatteryNative]::UnhookWinEvent($hook) | Out-Null
1286
+ } catch {
1287
+ # The hook may already be gone during shutdown.
1288
+ }
1289
+ }
1290
+ $script:fullscreenEventHooks = @()
1291
+ $script:fullscreenEventCallback = $null
1292
+ }
1293
+
1294
+ . (Join-Path $PSScriptRoot "controls.ps1")
1295
+
1296
+ $form.add_FormClosed({
1297
+ Remove-HudDockHostMarker
1298
+ try { Restore-DockTargetSpace } catch { }
1299
+ if ($canMove) {
1300
+ Write-HudPosition $form.Location
1301
+ }
1302
+ $timer.Stop()
1303
+ $timer.Dispose()
1304
+ $topMostTimer.Stop()
1305
+ $topMostTimer.Dispose()
1306
+ $menuAutoHideTimer.Stop()
1307
+ $menuAutoHideTimer.Dispose()
1308
+ Stop-FullscreenEventHooks
1309
+ Stop-SnapshotFetch
1310
+ foreach ($box in @($codexIconLabel, $claudeIconLabel)) {
1311
+ if ($box.Image) {
1312
+ $box.Image.Dispose()
1313
+ $box.Image = $null
1314
+ }
1315
+ }
1316
+ if ($menu -and -not $menu.IsDisposed) {
1317
+ $menu.Dispose()
1318
+ }
1319
+ $font.Dispose()
1320
+ $symbolFont.Dispose()
1321
+ if ($hitForm -and -not $hitForm.IsDisposed) {
1322
+ $hitForm.Close()
1323
+ $hitForm.Dispose()
1324
+ }
1325
+ Release-SingleInstance
1326
+ })
1327
+
1328
+ $form.add_LocationChanged({
1329
+ # No position save here: writing the state file on every drag pixel causes
1330
+ # visible hitches. MouseUp and Resize-HudToContent persist the placement.
1331
+ Sync-HitFormBounds
1332
+ })
1333
+ $form.add_SizeChanged({
1334
+ Set-DockedTuiWindowRegion
1335
+ Sync-HitFormBounds
1336
+ })
1337
+ $form.add_Shown({
1338
+ Show-HitForm
1339
+ Update-HudVisibilityForFullscreen
1340
+ Update-HudDockPlacement
1341
+ Signal-HudReady
1342
+ })
1343
+
1344
+ Set-Position
1345
+ $script:positionSaveReady = $true
1346
+
1347
+ $diskSnapshot = Read-HudSnapshot
1348
+ if ($script:initialHudSnapshot) {
1349
+ $script:latestSnapshot = Merge-HudSnapshot $script:initialHudSnapshot $diskSnapshot
1350
+ $script:initialHudSnapshot = $null
1351
+ Write-HudSnapshot $script:latestSnapshot
1352
+ } else {
1353
+ $script:latestSnapshot = $diskSnapshot
1354
+ }
1355
+ Update-HudFromSnapshot $script:latestSnapshot
1356
+ Start-SnapshotFetch
1357
+ $style = [AiBatteryNative]::GetWindowLong($form.Handle, [AiBatteryNative]::GWL_EXSTYLE)
1358
+ $style = $style -bor [AiBatteryNative]::WS_EX_TOOLWINDOW -bor [AiBatteryNative]::WS_EX_NOACTIVATE
1359
+ if ($ClickThrough) {
1360
+ $style = $style -bor [AiBatteryNative]::WS_EX_TRANSPARENT
1361
+ }
1362
+ [AiBatteryNative]::SetWindowLong($form.Handle, [AiBatteryNative]::GWL_EXSTYLE, $style) | Out-Null
1363
+ if ($script:dockTuiStatusline) {
1364
+ $rounded = [AiBatteryNative]::DWMWCP_ROUND
1365
+ try {
1366
+ [AiBatteryNative]::DwmSetWindowAttribute($form.Handle, [AiBatteryNative]::DWMWA_WINDOW_CORNER_PREFERENCE, [ref]$rounded, 4) | Out-Null
1367
+ } catch { }
1368
+ Set-DockedTuiWindowRegion
1369
+ }
1370
+ $timer.Start()
1371
+ Start-FullscreenEventHooks
1372
+ $topMostTimer.Start()
1373
+ $menuAutoHideTimer.Start()
1374
+ Write-HudDockHostMarker
1375
+ if ($env:AI_BATTERY_HUD_DEBUG_LOG) { Add-Content $env:AI_BATTERY_HUD_DEBUG_LOG "run dockTarget=$([Int64]$script:dockTargetHandle)" }
1376
+ [System.Windows.Forms.Application]::Run($form)
1377
+ if ($env:AI_BATTERY_HUD_DEBUG_LOG) { Add-Content $env:AI_BATTERY_HUD_DEBUG_LOG "run returned" }