-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathwindow.rs
More file actions
2286 lines (2076 loc) · 72.5 KB
/
window.rs
File metadata and controls
2286 lines (2076 loc) · 72.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::path::PathBuf;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use windows::core::PCWSTR;
use windows::Win32::Foundation::*;
use windows::Win32::Graphics::Gdi::*;
use windows::Win32::System::LibraryLoader::{GetModuleFileNameW, GetModuleHandleW};
use windows::Win32::System::Registry::*;
use windows::Win32::System::Threading::CreateMutexW;
use windows::Win32::UI::Accessibility::HWINEVENTHOOK;
use windows::Win32::UI::HiDpi::*;
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture};
use windows::Win32::UI::Shell::ExtractIconExW;
use windows::Win32::UI::WindowsAndMessaging::*;
use crate::diagnose;
use crate::localization::{self, LanguageId, Strings};
use crate::models::UsageData;
use crate::native_interop::{
self, Color, TIMER_COUNTDOWN, TIMER_POLL, TIMER_RESET_POLL, TIMER_UPDATE_CHECK,
WM_APP_TRAY, WM_APP_USAGE_UPDATED,
};
use crate::tray_icon;
use crate::poller;
use crate::theme;
use crate::updater::{self, InstallChannel, ReleaseDescriptor, UpdateCheckResult};
/// Wrapper to make HWND sendable across threads (safe for PostMessage usage)
#[derive(Clone, Copy)]
struct SendHwnd(isize);
unsafe impl Send for SendHwnd {}
impl SendHwnd {
fn from_hwnd(hwnd: HWND) -> Self {
Self(hwnd.0 as isize)
}
fn to_hwnd(self) -> HWND {
HWND(self.0 as *mut _)
}
}
/// Shared application state
struct AppState {
hwnd: SendHwnd,
taskbar_hwnd: Option<HWND>,
tray_notify_hwnd: Option<HWND>,
win_event_hook: Option<HWINEVENTHOOK>,
is_dark: bool,
embedded: bool,
language_override: Option<LanguageId>,
language: LanguageId,
install_channel: InstallChannel,
session_percent: f64,
session_text: String,
weekly_percent: f64,
weekly_text: String,
data: Option<UsageData>,
poll_interval_ms: u32,
retry_count: u32,
last_poll_ok: bool,
update_status: UpdateStatus,
last_update_check_unix: Option<u64>,
tray_offset: i32,
dragging: bool,
drag_start_mouse_x: i32,
drag_start_offset: i32,
show_decimals: bool,
widget_visible: bool,
}
#[derive(Clone, Debug)]
enum UpdateStatus {
Idle,
Checking,
Applying,
UpToDate,
Available(ReleaseDescriptor),
}
const RETRY_BASE_MS: u32 = 30_000; // 30 seconds
const POLL_1_MIN: u32 = 60_000;
const POLL_5_MIN: u32 = 300_000;
const POLL_15_MIN: u32 = 900_000;
const POLL_1_HOUR: u32 = 3_600_000;
// Menu item IDs for update frequency
const IDM_FREQ_1MIN: u16 = 10;
const IDM_FREQ_5MIN: u16 = 11;
const IDM_FREQ_15MIN: u16 = 12;
const IDM_FREQ_1HOUR: u16 = 13;
const IDM_START_WITH_WINDOWS: u16 = 20;
const IDM_RESET_POSITION: u16 = 30;
const IDM_VERSION_ACTION: u16 = 31;
const IDM_LANG_SYSTEM: u16 = 40;
const IDM_LANG_ENGLISH: u16 = 41;
const IDM_LANG_SPANISH: u16 = 42;
const IDM_LANG_FRENCH: u16 = 43;
const IDM_LANG_GERMAN: u16 = 44;
const IDM_LANG_JAPANESE: u16 = 45;
const IDM_SHOW_DECIMALS: u16 = 50;
const DIVIDER_HIT_ZONE: i32 = 13; // LEFT_DIVIDER_W + DIVIDER_RIGHT_MARGIN
const WM_DPICHANGED_MSG: u32 = 0x02E0;
const WM_APP_UPDATE_CHECK_COMPLETE: u32 = WM_APP + 2;
/// Current system DPI (96 = 100% scaling, 144 = 150%, 192 = 200%, etc.)
static CURRENT_DPI: AtomicU32 = AtomicU32::new(96);
/// Scale a base pixel value (designed at 96 DPI) to the current DPI.
fn sc(px: i32) -> i32 {
let dpi = CURRENT_DPI.load(Ordering::Relaxed);
(px as f64 * dpi as f64 / 96.0).round() as i32
}
/// Re-query the monitor DPI for our window and update the cached value.
/// Uses GetDpiForWindow which returns the live DPI (unlike GetDpiForSystem
/// which is cached at process startup and never changes).
fn refresh_dpi() {
let hwnd = {
let state = lock_state();
state.as_ref().map(|s| s.hwnd.to_hwnd())
};
if let Some(hwnd) = hwnd {
let dpi = unsafe { GetDpiForWindow(hwnd) };
if dpi > 0 {
CURRENT_DPI.store(dpi, Ordering::Relaxed);
}
}
}
fn load_embedded_app_icons() -> (HICON, HICON) {
unsafe {
let mut exe_buf = [0u16; 260];
let len = GetModuleFileNameW(None, &mut exe_buf) as usize;
if len == 0 {
return (HICON::default(), HICON::default());
}
let mut large_icon = HICON::default();
let mut small_icon = HICON::default();
let extracted = ExtractIconExW(
PCWSTR::from_raw(exe_buf.as_ptr()),
0,
Some(&mut large_icon),
Some(&mut small_icon),
1,
);
if extracted == 0 {
(HICON::default(), HICON::default())
} else {
(large_icon, small_icon)
}
}
}
unsafe impl Send for AppState {}
static STATE: Mutex<Option<AppState>> = Mutex::new(None);
/// Lock STATE safely, recovering from poisoned mutex
fn lock_state() -> MutexGuard<'static, Option<AppState>> {
STATE.lock().unwrap_or_else(|e| e.into_inner())
}
fn settings_path() -> PathBuf {
let appdata = std::env::var("APPDATA").unwrap_or_else(|_| ".".to_string());
PathBuf::from(appdata)
.join("ClaudeCodeUsageMonitor")
.join("settings.json")
}
#[derive(Debug, Serialize, Deserialize)]
struct SettingsFile {
#[serde(default)]
tray_offset: i32,
#[serde(default = "default_poll_interval")]
poll_interval_ms: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
language: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
last_update_check_unix: Option<u64>,
#[serde(default)]
show_decimals: bool,
#[serde(default = "default_widget_visible")]
widget_visible: bool,
}
impl Default for SettingsFile {
fn default() -> Self {
Self {
tray_offset: 0,
poll_interval_ms: default_poll_interval(),
language: None,
last_update_check_unix: None,
show_decimals: true,
widget_visible: true,
}
}
}
fn default_poll_interval() -> u32 {
POLL_15_MIN
}
fn default_widget_visible() -> bool {
true
}
fn load_settings() -> SettingsFile {
let content = match std::fs::read_to_string(settings_path()) {
Ok(c) => c,
Err(_) => return SettingsFile::default(),
};
serde_json::from_str(&content).unwrap_or_default()
}
fn save_settings(settings: &SettingsFile) {
let path = settings_path();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(json) = serde_json::to_string_pretty(settings) {
let _ = std::fs::write(path, json);
}
}
fn save_state_settings() {
let state = lock_state();
if let Some(s) = state.as_ref() {
save_settings(&SettingsFile {
tray_offset: s.tray_offset,
poll_interval_ms: s.poll_interval_ms,
language: s
.language_override
.map(|language| language.code().to_string()),
last_update_check_unix: s.last_update_check_unix,
show_decimals: s.show_decimals,
widget_visible: s.widget_visible,
});
}
}
fn tray_icon_data_from_state() -> (Option<f64>, String) {
let state = lock_state();
match state.as_ref() {
Some(s) if s.last_poll_ok => {
let tooltip = format!("5h: {} | 7d: {}", s.session_text, s.weekly_text);
(Some(s.session_percent), tooltip)
}
_ => (None, "Claude Code Usage Monitor".to_string()),
}
}
fn toggle_widget_visibility(hwnd: HWND) {
let new_visible = {
let mut state = lock_state();
if let Some(s) = state.as_mut() {
s.widget_visible = !s.widget_visible;
s.widget_visible
} else {
return;
}
};
save_state_settings();
unsafe {
if new_visible {
position_at_taskbar();
let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
render_layered();
} else {
let _ = ShowWindow(hwnd, SW_HIDE);
}
}
}
fn now_unix_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn update_check_interval() -> Duration {
Duration::from_secs(24 * 60 * 60)
}
fn auto_update_check_due(last_update_check_unix: Option<u64>) -> bool {
let Some(last_update_check_unix) = last_update_check_unix else {
return true;
};
now_unix_secs().saturating_sub(last_update_check_unix) >= update_check_interval().as_secs()
}
fn schedule_auto_update_check(hwnd: HWND) {
let delay_ms = {
let state = lock_state();
let Some(s) = state.as_ref() else {
return;
};
if auto_update_check_due(s.last_update_check_unix) {
None
} else {
let elapsed = now_unix_secs().saturating_sub(s.last_update_check_unix.unwrap_or(0));
let remaining_secs = update_check_interval().as_secs().saturating_sub(elapsed);
Some((remaining_secs.saturating_mul(1000)).min(u32::MAX as u64) as u32)
}
};
unsafe {
let _ = KillTimer(hwnd, TIMER_UPDATE_CHECK);
if let Some(delay_ms) = delay_ms {
SetTimer(hwnd, TIMER_UPDATE_CHECK, delay_ms.max(1), None);
}
}
}
fn refresh_usage_texts(state: &mut AppState) {
if !state.last_poll_ok {
return;
}
let strings = state.language.strings();
let Some((session_text, weekly_text)) = state.data.as_ref().map(|data| {
(
poller::format_line(&data.session, strings, state.show_decimals),
poller::format_line(&data.weekly, strings, state.show_decimals),
)
}) else {
return;
};
state.session_text = session_text;
state.weekly_text = weekly_text;
}
fn set_window_title(hwnd: HWND, strings: Strings) {
unsafe {
let title = native_interop::wide_str(strings.window_title);
let _ = SetWindowTextW(hwnd, PCWSTR::from_raw(title.as_ptr()));
}
}
fn show_info_message(hwnd: HWND, title: &str, message: &str) {
unsafe {
let title_wide = native_interop::wide_str(title);
let message_wide = native_interop::wide_str(message);
let _ = MessageBoxW(
hwnd,
PCWSTR::from_raw(message_wide.as_ptr()),
PCWSTR::from_raw(title_wide.as_ptr()),
MB_OK | MB_ICONINFORMATION,
);
}
}
fn show_error_message(hwnd: HWND, title: &str, message: &str) {
unsafe {
let title_wide = native_interop::wide_str(title);
let message_wide = native_interop::wide_str(message);
let _ = MessageBoxW(
hwnd,
PCWSTR::from_raw(message_wide.as_ptr()),
PCWSTR::from_raw(title_wide.as_ptr()),
MB_OK | MB_ICONERROR,
);
}
}
fn show_update_prompt(hwnd: HWND, strings: Strings, release: &ReleaseDescriptor) -> bool {
let message = strings
.update_prompt_now
.replace("{version}", &release.latest_version);
unsafe {
let title_wide = native_interop::wide_str(strings.update_available);
let message_wide = native_interop::wide_str(&message);
MessageBoxW(
hwnd,
PCWSTR::from_raw(message_wide.as_ptr()),
PCWSTR::from_raw(title_wide.as_ptr()),
MB_YESNO | MB_ICONQUESTION,
) == IDYES
}
}
fn apply_language_to_state(state: &mut AppState, language_override: Option<LanguageId>) {
state.language_override = language_override;
state.language = localization::resolve_language(language_override);
set_window_title(state.hwnd.to_hwnd(), state.language.strings());
refresh_usage_texts(state);
}
fn update_language_change() -> bool {
let mut state = lock_state();
let Some(app_state) = state.as_mut() else {
return false;
};
if app_state.language_override.is_some() {
return false;
}
let new_language = localization::detect_system_language();
if new_language == app_state.language {
return false;
}
apply_language_to_state(app_state, None);
true
}
fn version_action_label(
strings: Strings,
language: LanguageId,
install_channel: InstallChannel,
status: &UpdateStatus,
) -> String {
let current = env!("CARGO_PKG_VERSION");
match status {
UpdateStatus::Idle => format!("v{current} - {}", strings.check_for_updates),
UpdateStatus::Checking => format!("v{current} - {}", strings.checking_for_updates),
UpdateStatus::Applying => format!("v{current} - {}", strings.applying_update),
UpdateStatus::UpToDate => format!("v{current} - {}", strings.up_to_date_short),
UpdateStatus::Available(release) => match install_channel {
InstallChannel::Portable => {
format!(
"v{current} - {} v{}",
strings.update_to, release.latest_version
)
}
InstallChannel::Winget => format!(
"v{current} - {} v{}",
localization::update_via_winget(language),
release.latest_version
),
},
}
}
fn begin_update_check(hwnd: HWND, interactive: bool) {
let send_hwnd = SendHwnd::from_hwnd(hwnd);
let (strings, install_channel) = {
let mut state = lock_state();
let Some(app_state) = state.as_mut() else {
return;
};
if matches!(
app_state.update_status,
UpdateStatus::Checking | UpdateStatus::Applying
) {
if interactive {
show_info_message(
hwnd,
app_state.language.strings().updates,
app_state.language.strings().update_in_progress,
);
}
return;
}
app_state.update_status = UpdateStatus::Checking;
(app_state.language.strings(), app_state.install_channel)
};
std::thread::spawn(move || {
let hwnd = send_hwnd.to_hwnd();
let checked_at = now_unix_secs();
match updater::check_for_updates() {
Ok(UpdateCheckResult::UpToDate) => {
{
let mut state = lock_state();
if let Some(s) = state.as_mut() {
s.update_status = UpdateStatus::UpToDate;
s.last_update_check_unix = Some(checked_at);
}
}
save_state_settings();
if interactive {
show_info_message(hwnd, strings.updates, strings.up_to_date);
}
unsafe {
let _ = PostMessageW(hwnd, WM_APP_UPDATE_CHECK_COMPLETE, WPARAM(0), LPARAM(0));
}
}
Ok(UpdateCheckResult::Available(release)) => {
{
let mut state = lock_state();
if let Some(s) = state.as_mut() {
s.update_status = UpdateStatus::Available(release.clone());
s.last_update_check_unix = Some(checked_at);
}
}
save_state_settings();
if interactive && show_update_prompt(hwnd, strings, &release) {
match install_channel {
InstallChannel::Portable => begin_update_apply(hwnd, release),
InstallChannel::Winget => begin_winget_update(hwnd),
}
}
unsafe {
let _ = PostMessageW(hwnd, WM_APP_UPDATE_CHECK_COMPLETE, WPARAM(0), LPARAM(0));
}
}
Err(error) => {
{
let mut state = lock_state();
if let Some(s) = state.as_mut() {
s.update_status = UpdateStatus::Idle;
s.last_update_check_unix = Some(checked_at);
}
}
save_state_settings();
if interactive {
let message = format!("{}.\n\n{}", strings.update_failed, error);
show_error_message(hwnd, strings.updates, &message);
}
unsafe {
let _ = PostMessageW(hwnd, WM_APP_UPDATE_CHECK_COMPLETE, WPARAM(0), LPARAM(0));
}
}
}
});
}
fn begin_update_apply(hwnd: HWND, release: ReleaseDescriptor) {
let send_hwnd = SendHwnd::from_hwnd(hwnd);
let strings = {
let mut state = lock_state();
let Some(app_state) = state.as_mut() else {
return;
};
if matches!(
app_state.update_status,
UpdateStatus::Checking | UpdateStatus::Applying
) {
show_info_message(
hwnd,
app_state.language.strings().updates,
app_state.language.strings().update_in_progress,
);
return;
}
app_state.update_status = UpdateStatus::Applying;
app_state.language.strings()
};
std::thread::spawn(move || {
let hwnd = send_hwnd.to_hwnd();
match updater::begin_self_update(&release) {
Ok(()) => unsafe {
let _ = PostMessageW(hwnd, WM_CLOSE, WPARAM(0), LPARAM(0));
},
Err(error) => {
{
let mut state = lock_state();
if let Some(s) = state.as_mut() {
s.update_status = UpdateStatus::Available(release);
}
}
let message = format!("{}.\n\n{}", strings.update_failed, error);
show_error_message(hwnd, strings.updates, &message);
unsafe {
let _ = PostMessageW(hwnd, WM_APP_UPDATE_CHECK_COMPLETE, WPARAM(0), LPARAM(0));
}
}
}
});
}
fn begin_winget_update(hwnd: HWND) {
let strings = {
let state = lock_state();
state.as_ref().map(|s| s.language.strings())
}
.unwrap_or(LanguageId::English.strings());
match updater::begin_winget_update() {
Ok(()) => unsafe {
let _ = PostMessageW(hwnd, WM_CLOSE, WPARAM(0), LPARAM(0));
},
Err(error) => {
let message = format!("{}.\n\n{}", strings.update_failed, error);
show_error_message(hwnd, strings.updates, &message);
}
}
}
const STARTUP_REGISTRY_PATH: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
const STARTUP_REGISTRY_KEY: &str = "ClaudeCodeUsageMonitor";
/// Returns true only if the startup registry value points to this executable.
fn is_startup_enabled() -> bool {
unsafe {
let path = native_interop::wide_str(STARTUP_REGISTRY_PATH);
let key_name = native_interop::wide_str(STARTUP_REGISTRY_KEY);
let mut hkey = HKEY::default();
let result = RegOpenKeyExW(
HKEY_CURRENT_USER,
PCWSTR::from_raw(path.as_ptr()),
0,
KEY_READ,
&mut hkey,
);
if result.is_err() {
return false;
}
// Query the size of the value
let mut data_size: u32 = 0;
let result = RegQueryValueExW(
hkey,
PCWSTR::from_raw(key_name.as_ptr()),
None,
None,
None,
Some(&mut data_size),
);
if result.is_err() || data_size == 0 {
let _ = RegCloseKey(hkey);
return false;
}
// Read the value
let mut buf = vec![0u8; data_size as usize];
let result = RegQueryValueExW(
hkey,
PCWSTR::from_raw(key_name.as_ptr()),
None,
None,
Some(buf.as_mut_ptr()),
Some(&mut data_size),
);
let _ = RegCloseKey(hkey);
if result.is_err() {
return false;
}
// Convert the registry value (UTF-16) to a string
let wide_slice =
std::slice::from_raw_parts(buf.as_ptr() as *const u16, data_size as usize / 2);
let reg_value = String::from_utf16_lossy(wide_slice)
.trim_end_matches('\0')
.to_string();
// Get the current executable path
let mut exe_buf = [0u16; 260];
let len = GetModuleFileNameW(None, &mut exe_buf) as usize;
if len == 0 {
return false;
}
let current_exe = String::from_utf16_lossy(&exe_buf[..len]);
// Case-insensitive comparison (Windows paths are case-insensitive)
reg_value.eq_ignore_ascii_case(¤t_exe)
}
}
fn set_startup_enabled(enable: bool) {
unsafe {
let path = native_interop::wide_str(STARTUP_REGISTRY_PATH);
let mut hkey = HKEY::default();
let result = RegOpenKeyExW(
HKEY_CURRENT_USER,
PCWSTR::from_raw(path.as_ptr()),
0,
KEY_SET_VALUE,
&mut hkey,
);
if result.is_err() {
return;
}
let key_name = native_interop::wide_str(STARTUP_REGISTRY_KEY);
if enable {
let mut exe_buf = [0u16; 260];
let len = GetModuleFileNameW(None, &mut exe_buf) as usize;
if len > 0 {
// Write the wide string including null terminator
let byte_len = ((len + 1) * 2) as u32;
let _ = RegSetValueExW(
hkey,
PCWSTR::from_raw(key_name.as_ptr()),
0,
REG_SZ,
Some(std::slice::from_raw_parts(
exe_buf.as_ptr() as *const u8,
byte_len as usize,
)),
);
}
} else {
let _ = RegDeleteValueW(hkey, PCWSTR::from_raw(key_name.as_ptr()));
}
let _ = RegCloseKey(hkey);
}
}
// Dimensions matching the C# version
const SEGMENT_W: i32 = 10;
const SEGMENT_H: i32 = 13;
const SEGMENT_GAP: i32 = 1;
const SEGMENT_COUNT: i32 = 10;
const CORNER_RADIUS: i32 = 2;
const LEFT_DIVIDER_W: i32 = 3;
const DIVIDER_RIGHT_MARGIN: i32 = 10;
const LABEL_WIDTH: i32 = 18;
const LABEL_RIGHT_MARGIN: i32 = 10;
const BAR_RIGHT_MARGIN: i32 = 4;
const TEXT_WIDTH: i32 = 80;
const RIGHT_MARGIN: i32 = 1;
const WIDGET_HEIGHT: i32 = 46;
fn total_widget_width() -> i32 {
sc(LEFT_DIVIDER_W)
+ sc(DIVIDER_RIGHT_MARGIN)
+ sc(LABEL_WIDTH)
+ sc(LABEL_RIGHT_MARGIN)
+ (sc(SEGMENT_W) + sc(SEGMENT_GAP)) * SEGMENT_COUNT
- sc(SEGMENT_GAP)
+ sc(BAR_RIGHT_MARGIN)
+ sc(TEXT_WIDTH)
+ sc(RIGHT_MARGIN)
}
pub fn run() {
// Enable Per-Monitor DPI Awareness V2 for crisp rendering at any scale factor
unsafe {
let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
CURRENT_DPI.store(GetDpiForSystem(), Ordering::Relaxed);
}
diagnose::log("window::run started");
// Single-instance guard: silently exit if another instance is running
let mutex_name = native_interop::wide_str("Global\\ClaudeCodeUsageMonitor");
let _mutex = unsafe {
let handle = CreateMutexW(None, false, PCWSTR::from_raw(mutex_name.as_ptr()));
match handle {
Ok(h) => {
if GetLastError() == ERROR_ALREADY_EXISTS {
diagnose::log("startup aborted: another instance is already running");
return;
}
h
}
Err(error) => {
diagnose::log_error("startup aborted: unable to create single-instance mutex", error);
return;
}
}
};
let class_name = native_interop::wide_str("ClaudeCodeUsageMonitor");
unsafe {
let hinstance = GetModuleHandleW(PCWSTR::null()).unwrap();
let (large_icon, small_icon) = load_embedded_app_icons();
let wc = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
style: CS_HREDRAW | CS_VREDRAW,
lpfnWndProc: Some(wnd_proc),
hInstance: HINSTANCE(hinstance.0),
hIcon: large_icon,
hIconSm: small_icon,
hCursor: LoadCursorW(HINSTANCE::default(), IDC_ARROW).unwrap_or_default(),
hbrBackground: HBRUSH(std::ptr::null_mut()),
lpszClassName: PCWSTR::from_raw(class_name.as_ptr()),
..Default::default()
};
let atom = RegisterClassExW(&wc);
if atom == 0 {
diagnose::log("RegisterClassExW returned 0");
}
let settings = load_settings();
let language_override = settings.language.as_deref().and_then(LanguageId::from_code);
let language = localization::resolve_language(language_override);
let install_channel = updater::current_install_channel();
// Create as layered popup (will be reparented into taskbar)
let title = native_interop::wide_str(language.strings().window_title);
let hwnd = CreateWindowExW(
WS_EX_TOOLWINDOW | WS_EX_LAYERED | WS_EX_NOACTIVATE,
PCWSTR::from_raw(class_name.as_ptr()),
PCWSTR::from_raw(title.as_ptr()),
WS_POPUP,
0,
0,
total_widget_width(),
sc(WIDGET_HEIGHT),
HWND::default(),
HMENU::default(),
hinstance,
None,
)
.unwrap();
if !large_icon.is_invalid() {
let _ = SendMessageW(
hwnd,
WM_SETICON,
WPARAM(ICON_BIG as usize),
LPARAM(large_icon.0 as isize),
);
}
if !small_icon.is_invalid() {
let _ = SendMessageW(
hwnd,
WM_SETICON,
WPARAM(ICON_SMALL as usize),
LPARAM(small_icon.0 as isize),
);
}
diagnose::log(format!("main window created hwnd={:?}", hwnd));
let is_dark = theme::is_dark_mode();
let mut embedded = false;
{
let mut state = lock_state();
*state = Some(AppState {
hwnd: SendHwnd::from_hwnd(hwnd),
taskbar_hwnd: None,
tray_notify_hwnd: None,
win_event_hook: None,
is_dark,
embedded: false,
language_override,
language,
install_channel,
session_percent: 0.0,
session_text: "--".to_string(),
weekly_percent: 0.0,
weekly_text: "--".to_string(),
data: None,
poll_interval_ms: settings.poll_interval_ms,
retry_count: 0,
last_poll_ok: false,
update_status: UpdateStatus::Idle,
last_update_check_unix: settings.last_update_check_unix,
tray_offset: settings.tray_offset,
dragging: false,
drag_start_mouse_x: 0,
drag_start_offset: 0,
show_decimals: settings.show_decimals,
widget_visible: settings.widget_visible,
});
}
// Try to embed in taskbar
if let Some(taskbar_hwnd) = native_interop::find_taskbar() {
diagnose::log(format!("taskbar found hwnd={:?}", taskbar_hwnd));
native_interop::embed_in_taskbar(hwnd, taskbar_hwnd);
embedded = true;
let mut state = lock_state();
let s = state.as_mut().unwrap();
s.taskbar_hwnd = Some(taskbar_hwnd);
s.embedded = true;
let tray_notify = native_interop::find_child_window(taskbar_hwnd, "TrayNotifyWnd");
s.tray_notify_hwnd = tray_notify;
if tray_notify.is_some() {
diagnose::log("TrayNotifyWnd found");
} else {
diagnose::log("TrayNotifyWnd not found");
}
if let Some(tray_hwnd) = tray_notify {
let thread_id = native_interop::get_window_thread_id(tray_hwnd);
let hook = native_interop::set_tray_event_hook(thread_id, on_tray_location_changed);
s.win_event_hook = hook;
if hook.is_some() {
diagnose::log("tray event hook installed");
} else {
diagnose::log("tray event hook could not be installed");
}
}
} else {
diagnose::log("taskbar not found; using fallback popup window");
}
// If not embedded, fall back to topmost popup with SetLayeredWindowAttributes
if !embedded {
let _ = SetLayeredWindowAttributes(hwnd, COLORREF(0), 255, LWA_ALPHA);
let _ = SetWindowPos(
hwnd,
HWND_TOPMOST,
0,
0,
0,
0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
);
}
// Register system tray icon
let (tray_pct, tray_tooltip) = tray_icon_data_from_state();
tray_icon::add(hwnd, tray_pct, &tray_tooltip);
// Position and show (only if widget_visible preference is true)
position_at_taskbar();
if settings.widget_visible {
let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
}
diagnose::log("window shown");
// Initial render via UpdateLayeredWindow (for embedded) or InvalidateRect (fallback)
render_layered();
// Poll timer: 15 minutes
let initial_poll_ms = {
let state = lock_state();
state
.as_ref()
.map(|s| s.poll_interval_ms)
.unwrap_or(POLL_15_MIN)
};
SetTimer(hwnd, TIMER_POLL, initial_poll_ms, None);
// Initial poll
let send_hwnd = SendHwnd::from_hwnd(hwnd);
std::thread::spawn(move || {
diagnose::log("initial poll thread started");
do_poll(send_hwnd);
});
schedule_auto_update_check(hwnd);
let should_check_updates = {
let state = lock_state();
state
.as_ref()
.map(|s| auto_update_check_due(s.last_update_check_unix))
.unwrap_or(false)
};
if should_check_updates {
begin_update_check(hwnd, false);
}
// Initial theme check
check_theme_change();
// Message loop
let mut msg = MSG::default();
while GetMessageW(&mut msg, HWND::default(), 0, 0).as_bool() {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}
/// Render widget content and push to the layered window via UpdateLayeredWindow.
/// Renders fully opaque with the actual taskbar background colour so that
/// ClearType sub-pixel font rendering can be used for crisp, OS-native text.
fn render_layered() {
refresh_dpi();
let (hwnd_val, is_dark, embedded, strings, session_pct, session_text, weekly_pct, weekly_text) = {
let state = lock_state();
match state.as_ref() {
Some(s) => (
s.hwnd,
s.is_dark,
s.embedded,
s.language.strings(),
s.session_percent,
s.session_text.clone(),
s.weekly_percent,
s.weekly_text.clone(),
),
None => return,
}
};
let hwnd = hwnd_val.to_hwnd();
// For non-embedded fallback, just invalidate and let WM_PAINT handle it