taskbar-focus 0.6.0

A tiny Pomodoro/focus timer that lives in the Windows tray and toggles Do Not Disturb
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
//! The application window, tray icon and message pump.

use std::ffi::c_void;

use windows::core::PCWSTR;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::System::DataExchange::COPYDATASTRUCT;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::SystemInformation::GetTickCount64;
use windows::Win32::UI::Input::KeyboardAndMouse::EnableWindow;
use windows::Win32::UI::WindowsAndMessaging::*;

use crate::cli::Command;
use crate::config::Config;
use crate::lock::settings::Day;
use crate::lock::{Action, Card, Status};
use crate::orchestrator::{Orchestrator, UiEvent};
use crate::os::dnd::worker::DndWorker;
use crate::os::localtime::format_when;
use crate::os::sound;
use crate::session;
use crate::timer::{Phase, Timer};
use crate::ui::hotkeys::{self, Hotkeys};
use crate::ui::icon::{self, OwnedIcon, Visual};
use crate::ui::lock_card::{self, Content, WM_LOCK_CARD};
use crate::ui::shortcuts;
use crate::ui::tray::Tray;
use crate::ui::wide;

/// A debug build uses its own names, so it can neither command an installed
/// copy nor be mistaken for it.
pub const CLASS_MAIN: &str = if cfg!(debug_assertions) {
    "TaskbarFocusDevMainWindow"
} else {
    "TaskbarFocusMainWindow"
};
pub const MUTEX_NAME: &str = if cfg!(debug_assertions) {
    "Local\\TaskbarFocusDevSingleInstance"
} else {
    "Local\\TaskbarFocusSingleInstance"
};

const WM_TRAY: u32 = WM_APP + 1;
const WM_DND_REPORT: u32 = WM_APP + 2;
/// A command forwarded by another instance is waiting in `App::forwarded`.
const WM_FORWARDED: u32 = WM_APP + 5;

/// Notification-area icon ids. The muted mark is a second icon rather than
/// part of the first so it can sit beside the clock on its own, which is where
/// Windows would have put its own indicator.
///
/// It is an indicator, not a control, so any click on it opens the menu rather
/// than starting or pausing a session the way the timer icon does.
const TRAY_ID: u32 = 1;
const MUTE_TRAY_ID: u32 = 2;

const TIMER_ID: usize = 1;
/// Twice a second: the countdown stays honest without burning power.
const TICK_MS: u32 = 500;

const HOTKEY_TOGGLE: i32 = 1;
const HOTKEY_SKIP: i32 = 2;

const ID_TOGGLE: usize = 1001;
const ID_START_FOCUS: usize = 1002;
const ID_START_BREAK: usize = 1003;
const ID_STOP: usize = 1004;
const ID_SKIP: usize = 1005;
const ID_SETTINGS: usize = 1006;
const ID_EXIT: usize = 1007;
const ID_HIDE_MINI: usize = 1008;
const ID_RESET_MINI: usize = 1009;
const ID_LOCK_POSTPONE: usize = 1010;
const ID_LOCK_SKIP: usize = 1011;
const ID_LOCK_SKIP_LATE: usize = 1012;
const ID_LOCK_END: usize = 1013;
/// The menu's first line, which names the app and its state. It is not
/// disabled, because Windows would then grey out the app icon beside it, and
/// choosing it does nothing.
const ID_HEADING: usize = 1014;
const ID_PRESET_BASE: usize = 2000;

/// How long a due lock waits for a menu or dialog to close before it happens
/// anyway, in ms.
const LOCK_PATIENCE: u64 = 2_000;

/// The application icon, as embedded in the executable by `build.rs`.
///
/// Loaded once and never destroyed: it lives as long as the window classes do,
/// which is the life of the process. Falls back to a drawn ring if the resource
/// is missing, so the app never shows the generic Windows placeholder.
pub fn shared_icon() -> HICON {
    use std::sync::OnceLock;
    static ICON: OnceLock<isize> = OnceLock::new();
    let raw = *ICON.get_or_init(|| unsafe {
        let instance = GetModuleHandleW(None).unwrap_or_default();
        if let Ok(h) = LoadIconW(Some(instance.into()), PCWSTR(1 as *const u16)) {
            if !h.is_invalid() {
                return h.0 as isize;
            }
        }
        let v = Visual {
            rgb: (0xE8, 0x56, 0x3F),
            progress: 1.0,
            paused: false,
            idle: false,
            alpha: 1.0,
        };
        match icon::render(v, 32) {
            Some(ic) => {
                let h = ic.handle().0 as isize;
                std::mem::forget(ic);
                h
            }
            None => 0,
        }
    });
    HICON(raw as *mut c_void)
}

pub struct App {
    hwnd: HWND,
    mini_hwnd: Option<HWND>,
    pub orch: Orchestrator,
    tray: Tray,
    /// Kept alive because the shell keeps using the handle we hand it.
    current_icon: Option<OwnedIcon>,
    last_visual: Option<Visual>,
    last_tooltip: String,
    hotkeys: Hotkeys,
    taskbar_created_msg: u32,
    settings_hwnd: Option<HWND>,
    /// The standalone muted mark beside the clock, shown only while muted.
    mute_tray: Tray,
    mute_icon: Option<OwnedIcon>,
    /// Centre alert card, if one is showing.
    alert_hwnd: Option<HWND>,
    /// Short-lived per-monitor flash windows, if any are showing.
    flash_hwnds: Vec<HWND>,
    /// True when the dismiss-wait overlay paused a running timer.
    alert_paused_timer: bool,
    /// Bumped each time an alert is shown or dropped, so a delayed close
    /// message from a destroyed HWND cannot resume a replacement card.
    alert_generation: u32,
    /// The lock the open tray menu offers to postpone or skip.
    menu_lock_day: Option<Day>,
    /// The tray menu is open. The compact timer then stops putting itself back
    /// on top every tick, which would otherwise cover part of the menu when
    /// the menu opens over it.
    menu_open: bool,
    /// While the tray menu is open: each menu, a key, and the position of the
    /// line that key chooses in that menu.
    menu_keys: Vec<(isize, char, u32)>,
    /// Commands from other instances, so that their sender is never kept waiting.
    forwarded: std::collections::VecDeque<Command>,
    /// When a lock became due, until it is carried out.
    lock_due: Option<u64>,
    /// The PC lock card on screen, and what it stands for.
    lock_card: Option<(HWND, LockCard)>,
    /// Messages about PC locks not yet dismissed, oldest first.
    notices: std::collections::VecDeque<(String, String)>,
}

/// What the PC lock card on screen stands for.
#[derive(Clone, PartialEq)]
enum LockCard {
    Lock(Card),
    Notice(String, String),
}

impl LockCard {
    /// Whether `other` only needs new text in the same window.
    fn same_window(&self, other: &LockCard) -> bool {
        match (self, other) {
            (LockCard::Lock(a), LockCard::Lock(b)) => {
                a.kind == b.kind && a.day == b.day && a.actions == b.actions
            }
            (a, b) => a == b,
        }
    }
}

/// Entry point for the UI. Blocks until the user exits.
///
/// `first_run` makes the initial launch visibly announce itself; see
/// [`crate::config::is_first_run`].
pub fn run(
    config: Config,
    config_lost: bool,
    timer: Timer,
    initial: Command,
    first_run: bool,
) -> windows::core::Result<()> {
    unsafe {
        let icc = windows::Win32::UI::Controls::INITCOMMONCONTROLSEX {
            dwSize: std::mem::size_of::<windows::Win32::UI::Controls::INITCOMMONCONTROLSEX>()
                as u32,
            dwICC: windows::Win32::UI::Controls::ICC_STANDARD_CLASSES
                | windows::Win32::UI::Controls::ICC_TAB_CLASSES,
        };
        let _ = windows::Win32::UI::Controls::InitCommonControlsEx(&icc);

        let instance = GetModuleHandleW(None)?;
        let class = wide(CLASS_MAIN);

        let wc = WNDCLASSW {
            lpfnWndProc: Some(wndproc),
            hInstance: instance.into(),
            lpszClassName: class.as_pcwstr(),
            hCursor: LoadCursorW(None, IDC_ARROW)?,
            hIcon: shared_icon(),
            ..Default::default()
        };
        RegisterClassW(&wc);

        let title = wide(crate::APP_NAME);

        let hwnd = CreateWindowExW(
            WS_EX_TOOLWINDOW,
            class.as_pcwstr(),
            title.as_pcwstr(),
            WS_OVERLAPPED,
            0,
            0,
            0,
            0,
            None,
            None,
            Some(instance.into()),
            None,
        )?;

        let hwnd_bits = hwnd.0 as isize;
        let dnd = DndWorker::spawn(move || {
            let _ = PostMessageW(
                Some(HWND(hwnd_bits as *mut c_void)),
                WM_DND_REPORT,
                WPARAM(0),
                LPARAM(0),
            );
        });

        let taskbar_created_msg = RegisterWindowMessageW(wide("TaskbarCreated").as_pcwstr());

        let registered = crate::os::lock::register(hwnd);
        if !registered {
            crate::audit::log("lock: Windows does not report locks yet; trying again");
        }

        let mut app = Box::new(App {
            hwnd,
            mini_hwnd: None,
            orch: Orchestrator::new(config, config_lost, timer, dnd),
            tray: Tray::new(hwnd, TRAY_ID, WM_TRAY),
            current_icon: None,
            last_visual: None,
            last_tooltip: String::new(),
            hotkeys: Hotkeys::new(hwnd),
            taskbar_created_msg,
            settings_hwnd: None,
            mute_tray: Tray::new(hwnd, MUTE_TRAY_ID, WM_TRAY),
            mute_icon: None,
            alert_hwnd: None,
            flash_hwnds: Vec::new(),
            alert_paused_timer: false,
            alert_generation: 0,
            menu_lock_day: None,
            menu_open: false,
            menu_keys: Vec::new(),
            forwarded: Default::default(),
            lock_due: None,
            lock_card: None,
            notices: Default::default(),
        });

        app.orch.set_lock_reports(registered);
        app.register_hotkeys();
        let ptr = Box::into_raw(app);
        SetWindowLongPtrW(hwnd, GWLP_USERDATA, ptr as isize);

        let app = &mut *ptr;

        app.sync_mini_window();
        app.refresh();

        if first_run {
            app.tray.notify(
                &format!("{} is running", crate::APP_NAME),
                "Look for the ring icon in the notification area - click the ^ arrow \
                 and drag it onto the taskbar to keep it visible. Left-click starts a \
                 focus session; right-click opens the menu.",
            );
            let _ = app.orch.config.save();
            app.open_settings();
        }

        if initial.is_remote_control() {
            app.handle_command(&initial);
        }

        SetTimer(Some(hwnd), TIMER_ID, TICK_MS, None);

        let mut msg = MSG::default();
        while GetMessageW(&mut msg, None, 0, 0).as_bool() {
            let settings = (*ptr).settings_hwnd;
            let handled = settings.is_some_and(|s| {
                let keys = matches!(msg.message, WM_KEYDOWN | WM_SYSKEYDOWN)
                    .then(|| (*ptr).orch.config.shortcuts.clone());
                crate::ui::settings::box_key(s, &msg)
                    || keys.is_some_and(|k| crate::ui::settings::shortcut(s, &msg, &k))
                    || IsDialogMessageW(s, &msg).as_bool()
            });
            if !handled {
                let _ = TranslateMessage(&msg);
                DispatchMessageW(&msg);
            }
            (*ptr).perform_due_lock();
        }

        drop(Box::from_raw(ptr));
        Ok(())
    }
}

impl App {
    fn register_hotkeys(&mut self) {
        self.hotkeys.unregister_all();
        if !self.orch.config.hotkeys.enabled {
            return;
        }
        let mut failed = Vec::new();
        if let Some(a) = hotkeys::parse(&self.orch.config.hotkeys.toggle) {
            if !self.hotkeys.register(HOTKEY_TOGGLE, a) {
                failed.push(self.orch.config.hotkeys.toggle.clone());
            }
        }
        if let Some(a) = hotkeys::parse(&self.orch.config.hotkeys.skip) {
            if !self.hotkeys.register(HOTKEY_SKIP, a) {
                failed.push(self.orch.config.hotkeys.skip.clone());
            }
        }
        if !failed.is_empty() {
            self.tray.notify(
                "Hotkey unavailable",
                &format!("Another application already uses {}.", failed.join(" and ")),
            );
        }
    }

    /// Create or destroy the compact timer window to match settings.
    fn sync_mini_window(&mut self) {
        let want = self.orch.config.display.mini_window;
        let topmost = self.orch.config.display.always_on_top;
        match (want, self.mini_hwnd) {
            (true, None) => {
                let geo = self.orch.config.display.mini_geometry;
                self.mini_hwnd = crate::ui::mini::open(self as *mut App, geo, topmost);
            }
            (true, Some(h)) => crate::ui::mini::set_topmost(h, topmost),
            (false, Some(h)) => {
                unsafe {
                    let _ = DestroyWindow(h);
                }
                self.mini_hwnd = None;
            }
            (false, None) => {}
        }
    }

    /// Clicking the compact window body behaves like the tray icon.
    pub fn mini_clicked(&mut self) {
        self.handle_command(&Command::Toggle);
    }

    /// Forget the saved size and position, putting the window back to the
    /// default strip. Recreated rather than resized so it also returns to the
    /// default placement.
    fn reset_mini_window(&mut self) {
        self.orch.config.display.mini_geometry = None;
        let _ = self.orch.config.save();
        if let Some(h) = self.mini_hwnd.take() {
            unsafe {
                let _ = DestroyWindow(h);
            }
        }
        self.sync_mini_window();
        self.refresh();
    }

    /// The user moved or resized it; remember where.
    pub fn mini_geometry_changed(&mut self) {
        if let Some(h) = self.mini_hwnd {
            if let Some(g) = crate::ui::mini::geometry(h) {
                self.orch.config.display.mini_geometry = Some(g);
                let _ = self.orch.config.save();
            }
        }
    }

    /// Closing it switches the setting off, rather than leaving a checkbox
    /// insisting the window is shown when it plainly is not.
    pub fn mini_closed_by_user(&mut self) {
        self.mini_geometry_changed();
        self.orch.config.display.mini_window = false;
        let _ = self.orch.config.save();
        if let Some(h) = self.mini_hwnd.take() {
            unsafe {
                let _ = DestroyWindow(h);
            }
        }
    }

    /// Repaint the tray icon, tooltip and taskbar title if anything changed.
    ///
    /// Everything here is guarded on "did it actually change?". Pushing an
    /// unchanged icon or tooltip to the shell twice a second is what makes a
    /// tray icon shimmer.
    fn refresh(&mut self) {
        let muted = self.orch.dnd_active();
        let visual = Visual::from_state(self.orch.timer.state());
        let tooltip = format!("{}\n{}", crate::APP_NAME, self.orch.tooltip());
        let icon_changed = self.last_visual != Some(visual) || self.current_icon.is_none();
        let tip_changed = tooltip != self.last_tooltip;

        if icon_changed {
            if let Some(ic) = icon::render(visual, icon::tray_icon_size()) {
                self.tray.set(ic.handle(), &tooltip);

                self.current_icon = Some(ic);
                self.last_visual = Some(visual);
                self.last_tooltip = tooltip.clone();
            }
        } else if tip_changed {
            if let Some(ic) = &self.current_icon {
                self.tray.set(ic.handle(), &tooltip);
            }
            self.last_tooltip = tooltip;
        }

        self.sync_mute_tray(muted);

        if let Some(s) = self.settings_hwnd {
            crate::ui::settings::refresh_status(s);
        }
        if let Some(m) = self.mini_hwnd {
            let topmost = self.orch.config.display.always_on_top && !self.menu_open;
            crate::ui::mini::refresh(m, topmost);
        }
    }

    /// Add or remove the standalone muted mark in the notification area.
    ///
    /// It only exists while notifications are muted: an indicator that is
    /// always there says nothing. Windows 11 files new tray icons into the
    /// overflow, so the first time it appears the user may have to drag it out
    /// - which is also true of the timer icon itself.
    fn sync_mute_tray(&mut self, muted: bool) {
        let want = muted && self.orch.config.dnd.mute_tray_icon;
        if want == self.mute_icon.is_some() {
            return;
        }
        if !want {
            self.mute_tray.remove();
            self.mute_icon = None;
            return;
        }
        if let Some(icon) = icon::render_mute_icon(icon::tray_icon_size()) {
            self.mute_tray.set(
                icon.handle(),
                &format!("{}\nNotifications are muted", crate::APP_NAME),
            );
            self.mute_icon = Some(icon);
        }
    }

    fn apply_events(&mut self, events: Vec<UiEvent>) {
        let mut notification_sent = false;
        let mut visual_alerts = Vec::new();
        for event in events {
            match event {
                UiEvent::Notify { title, body } => {
                    notification_sent |= self.tray.notify(&title, &body);
                }
                UiEvent::Sound(_) => sound::play(),
                UiEvent::Alert { title, body, event } => visual_alerts.push((title, body, event)),
                UiEvent::Refresh => {}
                UiEvent::Warn(message) => {
                    notification_sent |= self.tray.notify(crate::APP_NAME, &message);
                }
                UiEvent::Notice { title, body } => {
                    let notice = (title, body);
                    if !self.notices.contains(&notice) {
                        self.notices.push_back(notice);
                    }
                }
                UiEvent::CloseAlert => self.drop_alert(),
                UiEvent::LockDue => self.lock_is_due(),
            }
        }
        for (title, body, event) in visual_alerts {
            self.show_alert(&title, &body, event);
        }
        self.sync_lock_card();
        self.refresh();
        self.orch.ui_events_applied(notification_sent);
    }

    /// Clear anything modal out of the way of a lock, which then happens from
    /// the main loop.
    fn lock_is_due(&mut self) {
        self.lock_due = Some(unsafe { GetTickCount64() });
        crate::ui::confirm::cancel();
        unsafe {
            let _ = EndMenu();
            if let Some(settings) = self.settings_hwnd {
                if let Ok(popup) = GetWindow(settings, GW_ENABLEDPOPUP) {
                    if popup != settings {
                        let _ = PostMessageW(Some(popup), WM_CLOSE, WPARAM(0), LPARAM(0));
                    }
                }
                let _ = PostMessageW(Some(settings), WM_CANCELMODE, WPARAM(0), LPARAM(0));
            }
            if let Some(mini) = self.mini_hwnd {
                let _ = PostMessageW(Some(mini), WM_CANCELMODE, WPARAM(0), LPARAM(0));
            }
        }
    }

    fn perform_due_lock(&mut self) {
        if self.lock_due.take().is_none() {
            return;
        }
        let events = self.orch.perform_lock();
        self.apply_events(events);
    }

    /// Lock from inside a nested loop that did not close when asked to.
    fn perform_overdue_lock(&mut self) {
        let now = unsafe { GetTickCount64() };
        if self.lock_due.is_some_and(|t| now - t >= LOCK_PATIENCE) {
            self.perform_due_lock();
        }
    }

    /// Show, update or close the PC lock card. A countdown comes before
    /// a message, and a message before any other card.
    fn sync_lock_card(&mut self) {
        let card = self.orch.lock_card();
        let notice = self.notices.front().cloned();
        let wanted = match (card, notice) {
            (Some(c), _) if c.seconds.is_some() => Some(LockCard::Lock(c)),
            (_, Some((title, body))) => Some(LockCard::Notice(title, body)),
            (Some(c), None) => Some(LockCard::Lock(c)),
            (None, None) => None,
        };
        let now = crate::os::lock::moment().wall;
        let content = wanted.as_ref().map(|w| match w {
            LockCard::Lock(card) => Content::of(card, now),
            LockCard::Notice(title, body) => Content::notice(title, body),
        });
        match (self.lock_card.take(), wanted, content) {
            (Some((hwnd, shown)), Some(wanted), Some(content)) if shown.same_window(&wanted) => {
                lock_card::update(hwnd, content);
                self.lock_card = Some((hwnd, wanted));
            }
            (old, wanted, content) => {
                if let Some((hwnd, _)) = old {
                    lock_card::close(hwnd);
                }
                let countdown = matches!(&wanted, Some(LockCard::Lock(c)) if c.seconds.is_some());
                if crate::ui::confirm::is_open() && !countdown {
                    return;
                }
                if let (Some(wanted), Some(content)) = (wanted, content) {
                    let shown = lock_card::show(self.hwnd, self.alert_anchor(), content);
                    self.lock_card = shown.map(|hwnd| (hwnd, wanted));
                }
            }
        }
    }

    /// A button on the PC lock card was clicked.
    fn lock_card_clicked(&mut self, index: usize, hwnd: HWND) {
        let Some((_, shown)) = self.lock_card.clone().filter(|(h, _)| *h == hwnd) else {
            return;
        };
        match shown {
            LockCard::Notice(..) => {
                self.notices.pop_front();
            }
            LockCard::Lock(card) => {
                let day = Some(card.day);
                match card.actions.get(index) {
                    Some(Action::Dismiss) => self.orch.dismiss_lock_card(&card),
                    _ if crate::ui::confirm::is_open() => return,
                    Some(Action::Postpone) => return self.run_lock_action(ID_LOCK_POSTPONE, day),
                    Some(Action::SkipLate) => return self.run_lock_action(ID_LOCK_SKIP_LATE, day),
                    Some(Action::EndPeriod) => return self.run_lock_action(ID_LOCK_END, day),
                    None => {}
                }
            }
        }
        self.sync_lock_card();
    }

    /// Carry out a PC lock action from the menu or a card, on the lock it showed.
    fn run_lock_action(&mut self, id: usize, day: Option<Day>) {
        let events = match id {
            ID_LOCK_POSTPONE => self.orch.postpone_lock(day),
            ID_LOCK_SKIP if !self.confirm_skip_lock() => return,
            ID_LOCK_SKIP => self.orch.skip_lock(day),
            ID_LOCK_SKIP_LATE => self.orch.skip_late_lock(),
            ID_LOCK_END if !self.confirm_end_period() => return,
            ID_LOCK_END => self.orch.end_locked_period(),
            _ => return,
        };
        self.apply_events(events);
    }

    /// Skipping a strict lock is confirmed first.
    fn confirm_skip_lock(&mut self) -> bool {
        let Status::Open {
            lock, strict: true, ..
        } = self.orch.lock_status()
        else {
            return true;
        };
        let at = format_when(lock, crate::os::lock::moment().wall);
        self.ask(&crate::ui::confirm::Question {
            eyebrow: "STRICT LOCK",
            title: "Skip this lock?",
            body: &format!("The PC will not lock at {at}."),
            keep: "Keep the lock",
            action: "Skip",
        })
    }

    fn confirm_end_period(&mut self) -> bool {
        if !self.orch.hold_lock_countdown() {
            return false;
        }
        self.sync_lock_card();
        let accepted = self.ask(&crate::ui::confirm::Question {
            eyebrow: "PC LOCK",
            title: "End the locked period?",
            body: "The PC will not be locked again for this lock.",
            keep: "Keep it",
            action: "End locked period",
        });
        self.orch.release_lock_countdown();
        self.sync_lock_card();
        accepted
    }

    /// Ask a question, keeping everything else out of reach meanwhile.
    fn ask(&mut self, question: &crate::ui::confirm::Question) -> bool {
        self.set_interactive(false);
        let accepted = crate::ui::confirm::ask(self.hwnd, question);
        self.set_interactive(true);
        accepted
    }

    /// Close the app, unless a strict lock refuses it.
    fn request_exit(&mut self) {
        match self.orch.exit_refusal() {
            Some(refusal) => self.apply_events(vec![refusal]),
            None => unsafe {
                let _ = DestroyWindow(self.hwnd);
            },
        }
    }

    fn run_forwarded(&mut self) {
        match self.forwarded.pop_front() {
            Some(Command::Quit) => self.request_exit(),
            Some(cmd) => self.handle_command(&cmd),
            None => {}
        }
    }

    /// The tray menu's PC lock lines.
    unsafe fn append_lock_menu(&mut self, lines: &mut MenuLines) {
        self.menu_lock_day = None;
        let now = crate::os::lock::moment().wall;
        let when = |at: i64| format_when(at, now);
        let keys = &self.orch.config.shortcuts;
        let letter = |value: &String| shortcuts::menu_letter(keys, value);
        let info = MF_STRING | MF_DISABLED;
        let status = self.orch.lock_status();
        if status == Status::Hidden {
            return;
        }
        lines.separator();
        match status {
            Status::Hidden => {}
            Status::Open {
                day,
                lock,
                cutoff,
                left,
                today,
                postpone_minutes,
                ..
            } => {
                self.menu_lock_day = Some(day);
                let text = format!(
                    "PC locks at {}  \u{00B7}  cutoff {}",
                    when(lock),
                    when(cutoff)
                );
                lines.line(info, 0, &text, glyph::LOCK, None);
                let flags = if left > 0 {
                    MF_STRING
                } else {
                    MF_STRING | MF_GRAYED
                };
                lines.line(
                    flags,
                    ID_LOCK_POSTPONE,
                    &format!("Postpone {postpone_minutes} min ({left} left)"),
                    glyph::POSTPONE,
                    letter(&keys.menu.postpone_lock),
                );
                let skip = match today {
                    true => "Skip today's lock".to_string(),
                    false => format!("Skip the {} lock", when(lock)),
                };
                lines.line(
                    MF_STRING,
                    ID_LOCK_SKIP,
                    &skip,
                    glyph::SKIP_LOCK,
                    letter(&keys.menu.skip_lock),
                );
            }
            Status::CutoffPassed { lock } => {
                let text = format!("PC locks at {} (cutoff passed)", when(lock));
                lines.line(info, 0, &text, glyph::LOCK, None);
            }
            Status::Next { lock } => {
                let text = format!("Next PC lock {}", when(lock));
                lines.line(info, 0, &text, glyph::LOCK, None);
            }
            Status::Skipped { next: Some(lock) } => {
                let text = format!("PC lock skipped, next {}", when(lock));
                lines.line(info, 0, &text, glyph::LOCK, None);
            }
            Status::Skipped { next: None } => {
                lines.line(info, 0, "PC lock skipped", glyph::LOCK, None);
            }
            Status::Late { can_skip } => {
                lines.line(info, 0, "Lock time passed, locking soon", glyph::LOCK, None);
                if can_skip {
                    lines.line(
                        MF_STRING,
                        ID_LOCK_SKIP_LATE,
                        "Skip today's lock",
                        glyph::SKIP_LOCK,
                        letter(&keys.menu.skip_lock),
                    );
                }
            }
            Status::LockedUntil { end, can_end } => {
                let text = format!("Locked until {}", when(end));
                lines.line(info, 0, &text, glyph::LOCK, None);
                if can_end {
                    lines.line(
                        MF_STRING,
                        ID_LOCK_END,
                        "End locked period...",
                        glyph::UNLOCK,
                        letter(&keys.menu.end_lock),
                    );
                }
            }
        }
    }

    /// Anchor visual alerts on the compact timer if shown, otherwise the
    /// foreground window's monitor, else the main window.
    fn alert_anchor(&self) -> HWND {
        if let Some(mini) = self.mini_hwnd {
            return mini;
        }
        let fg = unsafe { GetForegroundWindow() };
        if fg.is_invalid() {
            self.hwnd
        } else {
            fg
        }
    }

    fn show_alert(&mut self, title: &str, body: &str, event: crate::orchestrator::Event) {
        let settings = self.orch.config.alerts.clone();
        let anchor = self.alert_anchor();
        self.alert_generation = self.alert_generation.wrapping_add(1);
        let generation = self.alert_generation;
        if settings.require_dismiss && settings.overlay {
            self.pause_for_alert();
        }
        if settings.flash {
            for old in self.flash_hwnds.drain(..) {
                crate::ui::alert::close(old);
            }
            self.flash_hwnds = crate::ui::alert::show_flash(
                self.hwnd,
                anchor,
                event,
                generation,
                settings.flash_length,
            );
        }
        if settings.overlay {
            if let Some(old) = self.alert_hwnd.take() {
                crate::ui::alert::close(old);
            }
            self.alert_hwnd = crate::ui::alert::show_overlay(
                self.hwnd, anchor, title, body, event, &settings, generation,
            );
            if settings.require_dismiss && self.alert_hwnd.is_none() {
                self.resume_after_alert();
            }
        }
    }

    fn pause_for_alert(&mut self) {
        if self.alert_paused_timer || !self.orch.timer.state().is_running() {
            return;
        }
        self.alert_paused_timer = true;
        let _ = self.orch.dispatch(&Command::Pause);
        self.refresh();
    }

    fn resume_after_alert(&mut self) {
        if !self.alert_paused_timer {
            return;
        }
        self.alert_paused_timer = false;
        let _ = self.orch.dispatch(&Command::Resume);
        self.refresh();
    }

    /// Close overlay/flash without resuming: a user command will set the timer.
    fn drop_alert(&mut self) {
        if self.alert_hwnd.is_none() && self.flash_hwnds.is_empty() {
            return;
        }
        self.alert_generation = self.alert_generation.wrapping_add(1);
        if let Some(h) = self.alert_hwnd.take() {
            crate::ui::alert::close(h);
        }
        for h in self.flash_hwnds.drain(..) {
            crate::ui::alert::close(h);
        }
        self.alert_paused_timer = false;
    }

    /// Forget an overlay or flash HWND after it destroys itself.
    pub fn alert_closed(&mut self, hwnd: HWND, generation: u32) {
        if generation != self.alert_generation {
            return;
        }
        if self.alert_hwnd == Some(hwnd) {
            self.alert_hwnd = None;
            self.resume_after_alert();
        }
        if let Some(i) = self.flash_hwnds.iter().position(|&h| h == hwnd) {
            self.flash_hwnds.remove(i);
        }
    }

    /// Run a command, applying the "strict focus" guard where it applies.
    fn handle_command(&mut self, cmd: &Command) {
        if crate::ui::confirm::is_open() {
            return;
        }
        if self.needs_confirmation(cmd) && !self.confirm(cmd) {
            return;
        }
        if matches!(
            cmd,
            Command::Stop
                | Command::Skip
                | Command::StartFocus
                | Command::StartBreak
                | Command::Toggle
        ) {
            self.drop_alert();
        }
        let events = self.orch.dispatch(cmd);
        self.apply_events(events);
    }

    /// In strict mode, abandoning a *running* focus session needs a deliberate
    /// answer - the whole point is to defeat an absent-minded click.
    fn needs_confirmation(&self, cmd: &Command) -> bool {
        if !self.orch.config.behavior.strict_focus {
            return false;
        }
        if !matches!(cmd, Command::Stop | Command::Skip) {
            return false;
        }
        self.orch.timer.state().is_running()
            && self.orch.timer.state().phase() == Some(Phase::Focus)
    }

    fn confirm(&mut self, cmd: &Command) -> bool {
        let (title, action) = if matches!(cmd, Command::Skip) {
            ("Skip this focus session?", "Skip")
        } else {
            ("Stop this focus session?", "Stop")
        };
        let body = match self
            .orch
            .timer
            .state()
            .remaining()
            .map(crate::orchestrator::human_duration)
        {
            Some(remaining) => {
                format!("You still have {remaining} on the clock. A stray click shouldn't end it.")
            }
            None => "A stray click shouldn't end a running focus session.".into(),
        };
        self.ask(&crate::ui::confirm::Question {
            eyebrow: "STRICT FOCUS",
            title,
            body: &body,
            keep: "Keep going",
            action,
        })
    }

    /// Disable the compact timer and settings so they cannot change the
    /// session while [`Self::confirm`] is waiting for an answer.
    fn set_interactive(&self, enabled: bool) {
        unsafe {
            if let Some(h) = self.mini_hwnd {
                let _ = EnableWindow(h, enabled);
            }
            if let Some(h) = self.settings_hwnd {
                let _ = EnableWindow(h, enabled);
            }
        }
    }

    /// Build and show the tray menu.
    ///
    /// Menus put anything after a tab in the column on the right, which is
    /// where a shortcut belongs. A global hotkey is shown only while hotkeys
    /// are on and it parses, so the menu never advertises one that does
    /// nothing. Each line's own key, set on the Hotkeys page, is shown there
    /// too and handled in [`Self::menu_key`].
    pub fn show_menu(&mut self) {
        if crate::ui::confirm::is_open() {
            return;
        }
        unsafe {
            let Ok(menu) = CreatePopupMenu() else { return };
            let mut lines = MenuLines::new(menu);
            let running = self.orch.timer.state().is_running();
            let active = self.orch.timer.state().phase().is_some();
            let keys = self.orch.config.shortcuts.clone();
            let letter = |value: &String| shortcuts::menu_letter(&keys, value);

            let heading = format!("{} - {}", crate::APP_NAME, self.orch.tooltip());
            let _ = AppendMenuW(
                menu,
                MF_STRING,
                ID_HEADING,
                wide(&keyless(&plain(&heading))).as_pcwstr(),
            );
            let _ = SetMenuDefaultItem(menu, 0, 1);
            set_menu_bitmap(menu, 0, crate::ui::menu_icon());
            lines.separator();

            let shortcut = |configured: &str| -> String {
                if self.orch.config.hotkeys.enabled && hotkeys::parse(configured).is_some() {
                    configured.trim().to_string()
                } else {
                    String::new()
                }
            };
            let toggle_hotkey = shortcut(&self.orch.config.hotkeys.toggle);
            let skip_hotkey = shortcut(&self.orch.config.hotkeys.skip);

            let (toggle_verb, toggle_glyph, toggle_key) = match (active, running) {
                (false, _) => ("Start focus", glyph::PLAY, &keys.menu.start_focus),
                (true, true) => ("Pause", glyph::PAUSE, &keys.menu.pause),
                (true, false) => ("Resume", glyph::PLAY, &keys.menu.pause),
            };
            let toggle_label = if toggle_hotkey.is_empty() {
                format!("{toggle_verb}\tClick")
            } else {
                format!("{toggle_verb}\tClick  \u{2022}  {toggle_hotkey}")
            };
            lines.line(
                MF_STRING,
                ID_TOGGLE,
                &toggle_label,
                toggle_glyph,
                letter(toggle_key),
            );
            if active {
                let skip_label = if skip_hotkey.is_empty() {
                    "Skip to next".to_string()
                } else {
                    format!("Skip to next\t{skip_hotkey}")
                };
                lines.line(
                    MF_STRING,
                    ID_SKIP,
                    &skip_label,
                    glyph::NEXT,
                    letter(&keys.menu.skip),
                );
                lines.line(
                    MF_STRING,
                    ID_STOP,
                    "Stop",
                    glyph::STOP,
                    letter(&keys.menu.stop),
                );
                lines.separator();
                lines.line(
                    MF_STRING,
                    ID_START_FOCUS,
                    "Start focus",
                    glyph::FOCUS,
                    letter(&keys.menu.start_focus),
                );
            }
            lines.line(
                MF_STRING,
                ID_START_BREAK,
                "Start break",
                glyph::BREAK,
                letter(&keys.menu.start_break),
            );

            lines.separator();
            let mut preset_lines = None;
            if let Ok(sub) = CreatePopupMenu() {
                let mut sub_lines = MenuLines::new(sub);
                let active_name = self.orch.config.preset().name;
                for (i, p) in self.orch.config.presets.iter().enumerate() {
                    let mut flags = MF_STRING;
                    if p.name == active_name {
                        flags |= MF_CHECKED;
                    }
                    let digit =
                        char::from_digit(i as u32 + 1, 10).filter(|_| keys.enabled && i < 9);
                    let label = match digit {
                        Some(d) => format!("{d}  {}", plain(&p.name)),
                        None => plain(&p.name),
                    };
                    let _ = AppendMenuW(
                        sub,
                        flags,
                        ID_PRESET_BASE + i,
                        wide(&keyless(&label)).as_pcwstr(),
                    );
                    if let Some(d) = digit {
                        sub_lines.keys.push((d, i as u32));
                    }
                }
                lines.line(
                    MF_POPUP,
                    sub.0 as usize,
                    &format!("Preset: {}", plain(&active_name)),
                    glyph::PRESET,
                    letter(&keys.menu.preset),
                );
                preset_lines = Some(sub_lines);
            }

            let status = match self.orch.dnd_note() {
                Some(note) => note.to_string(),
                None => {
                    let s = self.orch.dnd_status();
                    let mut c = s.chars();
                    match c.next() {
                        Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
                        None => s.to_string(),
                    }
                }
            };
            lines.line(
                MF_STRING | MF_DISABLED,
                0,
                &plain(&status),
                glyph::QUIET,
                None,
            );
            self.append_lock_menu(&mut lines);

            lines.separator();
            let mini_label = if self.mini_hwnd.is_some() {
                "Hide timer window"
            } else {
                "Show timer window"
            };
            lines.line(
                MF_STRING,
                ID_HIDE_MINI,
                mini_label,
                glyph::WINDOW,
                letter(&keys.menu.timer_window),
            );
            if self.mini_hwnd.is_some() {
                lines.line(
                    MF_STRING,
                    ID_RESET_MINI,
                    "Reset window size",
                    glyph::RESET,
                    letter(&keys.menu.reset_window),
                );
            }
            lines.line(
                MF_STRING,
                ID_SETTINGS,
                "Settings...",
                glyph::SETTINGS,
                letter(&keys.menu.settings),
            );
            lines.line(
                MF_STRING,
                ID_EXIT,
                "Exit",
                glyph::EXIT,
                letter(&keys.menu.exit),
            );

            self.menu_keys = lines.keys_of_menu();
            if let Some(sub_lines) = preset_lines {
                self.menu_keys.extend(sub_lines.keys_of_menu());
            }

            let mut pt = Default::default();
            let _ = GetCursorPos(&mut pt);

            let _ = SetForegroundWindow(self.hwnd);
            self.menu_open = true;
            let _ = TrackPopupMenu(
                menu,
                TPM_RIGHTBUTTON | TPM_BOTTOMALIGN,
                pt.x,
                pt.y,
                None,
                self.hwnd,
                None,
            );
            self.menu_open = false;
            self.menu_keys.clear();
            let _ = PostMessageW(Some(self.hwnd), WM_NULL, WPARAM(0), LPARAM(0));
            let _ = DestroyMenu(menu);
        }
    }

    /// The tray menu line chosen by a key pressed while the menu is open, as
    /// the answer `WM_MENUCHAR` expects, or `None` if no line has that key.
    ///
    /// The menu's lines carry no `&` of their own: Windows would underline
    /// such a letter only when the menu was opened from the keyboard, and it
    /// would tie each line to a letter of its text.
    fn menu_key(&self, wparam: WPARAM, lparam: LPARAM) -> Option<LRESULT> {
        let typed = char::from_u32((wparam.0 & 0xFFFF) as u32)?.to_ascii_uppercase();
        let (_, _, position) = self
            .menu_keys
            .iter()
            .find(|(menu, key, _)| *menu == lparam.0 && *key == typed)?;
        Some(LRESULT(((MNC_EXECUTE as isize) << 16) | *position as isize))
    }

    /// A key pressed in the compact timer window. Returns whether it was the
    /// window's start and pause shortcut.
    pub fn mini_key(&mut self, vk: u32) -> bool {
        let keys = &self.orch.config.shortcuts;
        if !shortcuts::pressed(keys, &keys.timer_window.start_pause, vk) {
            return false;
        }
        self.mini_clicked();
        true
    }

    fn on_menu(&mut self, id: usize) {
        if crate::ui::confirm::is_open() {
            return;
        }
        match id {
            ID_TOGGLE => self.handle_command(&Command::Toggle),
            ID_START_FOCUS => self.handle_command(&Command::StartFocus),
            ID_START_BREAK => self.handle_command(&Command::StartBreak),
            ID_STOP => self.handle_command(&Command::Stop),
            ID_SKIP => self.handle_command(&Command::Skip),
            ID_HIDE_MINI => {
                self.orch.config.display.mini_window = !self.orch.config.display.mini_window;
                let _ = self.orch.config.save();
                self.sync_mini_window();
            }
            ID_RESET_MINI => self.reset_mini_window(),
            ID_SETTINGS => self.open_settings(),
            ID_EXIT => self.request_exit(),
            ID_LOCK_POSTPONE | ID_LOCK_SKIP | ID_LOCK_SKIP_LATE | ID_LOCK_END => {
                self.run_lock_action(id, self.menu_lock_day)
            }
            n if n >= ID_PRESET_BASE => {
                let i = n - ID_PRESET_BASE;
                if let Some(p) = self.orch.config.presets.get(i) {
                    let name = p.name.clone();
                    self.handle_command(&Command::Preset(name));
                }
            }
            _ => {}
        }
    }

    fn open_settings(&mut self) {
        if crate::ui::confirm::is_open() {
            return;
        }
        if let Some(h) = self.settings_hwnd {
            unsafe {
                let _ = SetForegroundWindow(h);
            }
            return;
        }
        self.settings_hwnd = crate::ui::settings::open(self.hwnd, self as *mut App);
        self.refresh();
    }

    /// Called by the settings window when the user saves.
    pub fn apply_config(&mut self, new: Config) {
        if self.orch.replace_config(new) {
            self.notices.push_back((
                "Saved, but not for the coming lock".into(),
                "Its cutoff has passed, so some lock changes start with a later lock. \
                 Everything else applies now."
                    .into(),
            ));
        }
        let _ = self.orch.config.save();
        self.register_hotkeys();
        self.sync_mini_window();
        self.last_visual = None;
        self.refresh();
    }

    pub fn config(&self) -> &Config {
        &self.orch.config
    }

    pub fn on_settings_closed(&mut self) {
        self.settings_hwnd = None;
    }
}

unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    let ptr = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *mut App;
    if ptr.is_null() {
        return DefWindowProcW(hwnd, msg, wparam, lparam);
    }
    let app = &mut *ptr;

    if msg == app.taskbar_created_msg {
        app.tray.forget();
        app.mute_tray.forget();
        app.mute_icon = None;
        app.last_visual = None;
        app.refresh();
        return LRESULT(0);
    }

    match msg {
        WM_TRAY => {
            let indicator = wparam.0 as u32 == MUTE_TRAY_ID;
            match lparam.0 as u32 {
                WM_LBUTTONUP if indicator => app.show_menu(),
                WM_LBUTTONUP => app.handle_command(&Command::Toggle),
                WM_RBUTTONUP | WM_CONTEXTMENU => app.show_menu(),
                WM_LBUTTONDBLCLK => app.open_settings(),
                _ => {}
            }
            LRESULT(0)
        }

        WM_COMMAND => {
            app.on_menu(wparam.0 & 0xFFFF);
            LRESULT(0)
        }

        WM_TIMER => {
            if wparam.0 == TIMER_ID {
                if !app.orch.has_lock_reports() {
                    app.orch.set_lock_reports(crate::os::lock::register(hwnd));
                }
                let events = app.orch.tick();
                app.apply_events(events);
                app.perform_overdue_lock();
            }
            LRESULT(0)
        }

        WM_MENUCHAR => match app.menu_key(wparam, lparam) {
            Some(chosen) => chosen,
            None => DefWindowProcW(hwnd, msg, wparam, lparam),
        },

        WM_HOTKEY
            if app
                .settings_hwnd
                .is_some_and(|s| crate::ui::settings::record_hotkey(s, lparam)) =>
        {
            LRESULT(0)
        }
        WM_HOTKEY => {
            match wparam.0 as i32 {
                HOTKEY_TOGGLE => app.handle_command(&Command::Toggle),
                HOTKEY_SKIP => app.handle_command(&Command::Skip),
                _ => {}
            }
            LRESULT(0)
        }

        WM_DND_REPORT => {
            let events = app.orch.collect_dnd_reports();
            app.apply_events(events);
            LRESULT(0)
        }

        msg if msg == crate::ui::alert::WM_ALERT_CLOSED => {
            app.alert_closed(HWND(wparam.0 as *mut std::ffi::c_void), lparam.0 as u32);
            LRESULT(0)
        }

        WM_LOCK_CARD => {
            app.lock_card_clicked(wparam.0, HWND(lparam.0 as *mut c_void));
            LRESULT(0)
        }

        WM_FORWARDED => {
            app.run_forwarded();
            LRESULT(0)
        }

        WM_WTSSESSION_CHANGE => {
            let events = app.orch.note_session(wparam.0 as u32, lparam.0 as u32);
            app.apply_events(events);
            LRESULT(0)
        }

        WM_TIMECHANGE => {
            app.orch.note_time_change();
            LRESULT(0)
        }

        WM_POWERBROADCAST => {
            let ev = wparam.0 as u32;
            if ev == PBT_APMRESUMEAUTOMATIC || ev == PBT_APMRESUMESUSPEND {
                app.orch.refresh_session();
                let events = app.orch.tick();
                app.apply_events(events);
            }
            LRESULT(1)
        }

        WM_COPYDATA => {
            let cds = lparam.0 as *const COPYDATASTRUCT;
            if !cds.is_null() && !(*cds).lpData.is_null() {
                let bytes =
                    std::slice::from_raw_parts((*cds).lpData as *const u8, (*cds).cbData as usize);
                if let Ok(text) = std::str::from_utf8(bytes) {
                    if let Some(cmd) = Command::decode(text) {
                        app.forwarded.push_back(cmd);
                        let _ = PostMessageW(Some(hwnd), WM_FORWARDED, WPARAM(0), LPARAM(0));
                    }
                }
            }
            LRESULT(1)
        }

        WM_DESTROY => {
            crate::os::lock::unregister(hwnd);
            app.mini_geometry_changed();
            session::save(&app.orch.timer);
            app.orch.save_lock();
            crate::audit::log_stop();
            app.tray.remove();
            app.mute_tray.remove();
            PostQuitMessage(0);
            LRESULT(0)
        }

        _ => DefWindowProcW(hwnd, msg, wparam, lparam),
    }
}

/// The icon-font glyphs shown beside the tray menu's lines. They match the
/// icons of the settings window where the two show the same thing.
mod glyph {
    pub const PLAY: &str = "\u{E768}";
    pub const PAUSE: &str = "\u{E769}";
    pub const NEXT: &str = "\u{E893}";
    pub const STOP: &str = "\u{E71A}";
    pub const FOCUS: &str = "\u{E916}";
    pub const BREAK: &str = "\u{EC32}";
    pub const PRESET: &str = "\u{E8FD}";
    pub const QUIET: &str = "\u{E708}";
    pub const LOCK: &str = "\u{E72E}";
    pub const UNLOCK: &str = "\u{E785}";
    pub const POSTPONE: &str = "\u{E823}";
    pub const SKIP_LOCK: &str = "\u{E711}";
    pub const WINDOW: &str = "\u{E7F4}";
    pub const RESET: &str = "\u{E72C}";
    pub const SETTINGS: &str = "\u{E713}";
    pub const EXIT: &str = "\u{E7E8}";
}

/// Colour of the glyphs beside lines that cannot be chosen, matching the grey
/// Windows draws their text in.
const MENU_INFO: u32 = 0x6D6D6D;

/// A menu being filled, with the key that chooses each of its lines while it
/// is open.
struct MenuLines {
    menu: HMENU,
    /// A key and the position of the line it chooses.
    keys: Vec<(char, u32)>,
}

impl MenuLines {
    fn new(menu: HMENU) -> Self {
        MenuLines {
            menu,
            keys: Vec::new(),
        }
    }

    /// Add a line with `glyph` in the icon column. Lines that cannot be chosen
    /// get a grey glyph to go with their grey text, and no key. A line's key
    /// is shown first in the shortcut column, before anything already after a
    /// tab in `text`.
    unsafe fn line(
        &mut self,
        flags: MENU_ITEM_FLAGS,
        id: usize,
        text: &str,
        glyph: &str,
        key: Option<char>,
    ) {
        let inert = flags.0 & (MF_GRAYED.0 | MF_DISABLED.0) != 0;
        let key = key.filter(|_| !inert);
        let text = match key {
            Some(key) => match text.split_once('\t') {
                Some((label, shortcuts)) => format!("{label}\t{key}  \u{2022}  {shortcuts}"),
                None => format!("{text}\t{key}"),
            },
            None => text.to_string(),
        };
        let _ = AppendMenuW(self.menu, flags, id, wide(&keyless(&text)).as_pcwstr());
        let position = GetMenuItemCount(Some(self.menu)) - 1;
        if position < 0 {
            return;
        }
        if let Some(key) = key {
            self.keys.push((key, position as u32));
        }
        let colour = if inert {
            MENU_INFO
        } else {
            crate::ui::fluent::TEXT
        };
        set_menu_bitmap(
            self.menu,
            position as u32,
            crate::ui::fluent::glyph_bitmap(glyph, colour),
        );
    }

    unsafe fn separator(&self) {
        let _ = AppendMenuW(self.menu, MF_SEPARATOR, 0, PCWSTR::null());
    }

    /// The keys of this menu, labelled with the menu they belong to, the way
    /// `WM_MENUCHAR` names it.
    fn keys_of_menu(&self) -> Vec<(isize, char, u32)> {
        let menu = self.menu.0 as isize;
        self.keys.iter().map(|&(k, p)| (menu, k, p)).collect()
    }
}

/// `text` as a menu shows it, without an `&` turning the next letter into
/// the line's access key.
fn plain(text: &str) -> String {
    text.replace('&', "&&")
}

/// `text` with an invisible access key that no key can type.
///
/// A menu line without an access key is chosen by its first letter, which
/// would make removed or changed shortcuts still work. With this, every key
/// pressed in the menu reaches `WM_MENUCHAR`, where only the configured ones
/// are honoured.
fn keyless(text: &str) -> String {
    format!("&\u{200B}{text}")
}

/// Put `bitmap` in the icon column of the menu line at `position`.
unsafe fn set_menu_bitmap(
    menu: HMENU,
    position: u32,
    bitmap: windows::Win32::Graphics::Gdi::HBITMAP,
) {
    let info = MENUITEMINFOW {
        cbSize: std::mem::size_of::<MENUITEMINFOW>() as u32,
        fMask: MIIM_BITMAP,
        hbmpItem: bitmap,
        ..Default::default()
    };
    let _ = SetMenuItemInfoW(menu, position, true, &info);
}