glasskit 0.1.0

Native Windows UI with a glass look: tray icon and menu, glass popup, themed dialogs, and helpers for tray apps.
Documentation
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
// Copyright (c) 2026 John Law
// SPDX-License-Identifier: MIT

//! A notification-area (tray) icon with a menu, and the wait loop of a tray app.
//!
//! [`Tray::wait`] is the main loop of the app: it handles the window messages of the thread and
//! returns when the user picks a menu command, when a deadline comes, or when the user quits.

use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::ffi::c_void;
use std::time::{SystemTime, UNIX_EPOCH};

use windows::Win32::Foundation::{CloseHandle, HANDLE, HWND, LPARAM, LRESULT, POINT, TRUE, WPARAM};
use windows::Win32::Graphics::Gdi::{
    BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateBitmap, CreateDIBSection, DIB_RGB_COLORS,
    DeleteObject,
};
use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW};
use windows::Win32::System::RemoteDesktop::{
    NOTIFY_FOR_THIS_SESSION, WTSRegisterSessionNotification, WTSUnRegisterSessionNotification,
};
use windows::Win32::System::Threading::{
    CancelWaitableTimer, CreateWaitableTimerExW, INFINITE, SetWaitableTimer, TIMER_ALL_ACCESS,
};
use windows::Win32::UI::Shell::{
    NIF_ICON, NIF_MESSAGE, NIF_TIP, NIM_ADD, NIM_DELETE, NIM_MODIFY, NOTIFYICONDATAW,
    Shell_NotifyIconW,
};
use windows::Win32::UI::WindowsAndMessaging::{
    AppendMenuW, CreateIconIndirect, CreatePopupMenu, CreateWindowExW, DefWindowProcW, DestroyIcon,
    DestroyMenu, DestroyWindow, DispatchMessageW, GWLP_USERDATA, GetCursorPos, GetSystemMetrics,
    GetWindowLongPtrW, HICON, HMENU, ICONINFO, MENU_ITEM_FLAGS, MF_CHECKED, MF_GRAYED, MF_POPUP,
    MF_SEPARATOR, MF_STRING, MSG, MWMO_INPUTAVAILABLE, MsgWaitForMultipleObjectsEx, PM_REMOVE,
    PeekMessageW, PostMessageW, PostQuitMessage, QS_ALLINPUT, RegisterWindowMessageW, SM_CXSMICON,
    SetForegroundWindow, SetWindowLongPtrW, TPM_BOTTOMALIGN, TPM_NONOTIFY, TPM_RETURNCMD,
    TPM_RIGHTALIGN, TPM_RIGHTBUTTON, TrackPopupMenu, TranslateMessage, WM_APP, WM_LBUTTONUP,
    WM_NCDESTROY, WM_NULL, WM_QUIT, WM_RBUTTONUP, WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_POPUP,
};
use windows::core::{BOOL, HSTRING, PCSTR, PCWSTR, w};

use crate::Ui;
use crate::error::{Call, Error, Result};

const CLASS_NAME: PCWSTR = w!("GlasskitTray");
const WM_WTSSESSION_CHANGE: u32 = 0x02B1;
const WTS_SESSION_UNLOCK: usize = 0x8;
/// The numbers of the uxtheme.dll exports for dark menus. They have no names.
const SET_PREFERRED_APP_MODE: u16 = 135;
const ALLOW_DARK_MODE_FOR_WINDOW: u16 = 133;
const FLUSH_MENU_THEMES: u16 = 136;
/// The app mode that follows the Windows light or dark setting.
const APP_MODE_ALLOW_DARK: i32 = 1;
const WM_TRAY: u32 = WM_APP + 1;
const ICON_ID: u32 = 1;
/// Menu item ids start here. 0 means that the user closed the menu without a choice.
const FIRST_ID: usize = 1;
/// The number of 100 ns intervals from 1601-01-01 (FILETIME start) to 1970-01-01 (Unix start).
const UNIX_EPOCH_AS_FILETIME: i64 = 116_444_736_000_000_000;

/// A positive due time is absolute for `SetWaitableTimer`, and a negative one is relative.
/// Thus the value must stay positive: it saturates and never wraps.
fn absolute_due_time(at: SystemTime) -> i64 {
    let since_unix = at.duration_since(UNIX_EPOCH).unwrap_or_default();
    i64::try_from(since_unix.as_nanos().div_ceil(100))
        .unwrap_or(i64::MAX)
        .saturating_add(UNIX_EPOCH_AS_FILETIME)
}

/// One item of the tray menu. `C` is the command type of the app.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MenuItem<C> {
    /// An item that the user can pick. [`Tray::wait`] then returns [`Wake::Command`].
    Command {
        /// The command that [`Tray::wait`] returns.
        command: C,
        /// The text of the item.
        label: String,
        /// A disabled item shows in gray, and the user cannot pick it.
        enabled: bool,
        /// A checked item shows a check mark.
        checked: bool,
    },
    /// A gray text that the user cannot pick, for example a status line.
    Label(String),
    /// A line between groups of items.
    Separator,
    /// An item that opens more items.
    Submenu {
        /// The text of the item.
        label: String,
        /// The items of the submenu.
        items: Vec<MenuItem<C>>,
    },
    /// The item that ends the app. [`Tray::wait`] then returns [`Wake::Quit`]. If a popup or a
    /// dialog shows at that time, it closes first and gives its own quit result.
    Quit(String),
}

impl<C> MenuItem<C> {
    /// An enabled, unchecked command item.
    pub fn command(command: C, label: impl Into<String>) -> Self {
        MenuItem::Command {
            command,
            label: label.into(),
            enabled: true,
            checked: false,
        }
    }

    /// Enable or disable a command item. Other items do not change.
    #[must_use]
    pub fn enabled(mut self, on: bool) -> Self {
        if let MenuItem::Command { enabled, .. } = &mut self {
            *enabled = on;
        }
        self
    }

    /// Set or clear the check mark of a command item. Other items do not change.
    #[must_use]
    pub fn checked(mut self, on: bool) -> Self {
        if let MenuItem::Command { checked, .. } = &mut self {
            *checked = on;
        }
        self
    }
}

/// Why [`Tray::wait`] returned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wake<C> {
    /// The time given to [`Tray::wait`] came.
    Deadline,
    /// The user unlocked the session: someone is at the screen again.
    SessionUnlocked,
    /// The user picked a command item.
    Command(C),
    /// The user picked the [`MenuItem::Quit`] item, or the thread got `WM_QUIT`.
    Quit,
}

/// The picture of a tray icon.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Icon {
    size: u32,
    pixels: Vec<u32>,
}

impl Icon {
    /// The size in pixels that Windows uses for tray icons now. It changes with the display
    /// scale, so make the icon at this size just before [`Tray::new`].
    pub fn tray_size() -> u32 {
        unsafe { GetSystemMetrics(SM_CXSMICON).max(16) as u32 }
    }

    /// A square icon of `size` by `size` pixels. `pixels` go row by row from the top-left
    /// corner. Each pixel is `0xAARRGGBB` with straight (not premultiplied) alpha.
    pub fn from_argb(size: u32, pixels: Vec<u32>) -> Result<Self> {
        if pixels.len() as u64 != u64::from(size) * u64::from(size) {
            return Err(Error::InvalidIcon {
                size,
                pixels: pixels.len(),
            });
        }
        Ok(Self { size, pixels })
    }

    /// The width and height in pixels.
    pub fn size(&self) -> u32 {
        self.size
    }
}

/// A menu item as the window procedure keeps it: commands are numbers in the action list.
#[derive(Debug, Clone)]
enum Entry {
    Action {
        index: usize,
        label: String,
        enabled: bool,
        checked: bool,
    },
    Label(String),
    Separator,
    Submenu {
        label: String,
        entries: Vec<Entry>,
    },
    Quit(String),
}

/// The state that the window procedure uses. It has no type parameter, so one window class
/// serves all command types.
struct Shared {
    entries: RefCell<Vec<Entry>>,
    /// It changes with each new menu. A choice from an older menu is not used.
    generation: Cell<u64>,
    chosen: RefCell<VecDeque<(u64, usize)>>,
    icon_data: RefCell<NOTIFYICONDATAW>,
    taskbar_created: u32,
    unlocked: Cell<bool>,
}

/// A tray icon and its menu. `C` is the command type of the app, for example an enum.
///
/// Create it with a [`Ui`] on the thread that runs [`Tray::wait`].
pub struct Tray<C> {
    _ui: Ui,
    hwnd: HWND,
    icon: HICON,
    timer: DeadlineTimer,
    shared: *const Shared,
    commands: Vec<C>,
}

impl<C: Clone> Tray<C> {
    /// Add an icon with this tooltip to the notification area. The menu is empty until
    /// [`Tray::set_menu`].
    pub fn new(ui: &Ui, tooltip: &str, icon: &Icon) -> Result<Self> {
        let timer = DeadlineTimer::new()?;
        let hinstance = ui.hinstance();
        crate::register_class(&WNDCLASSEXW {
            cbSize: size_of::<WNDCLASSEXW>() as u32,
            lpfnWndProc: Some(wndproc),
            hInstance: hinstance,
            lpszClassName: CLASS_NAME,
            ..Default::default()
        })?;
        unsafe {
            // Use a hidden top-level window, not a message-only window.
            // Only a top-level window gets the TaskbarCreated message when Explorer restarts.
            let hwnd = CreateWindowExW(
                WS_EX_TOOLWINDOW,
                CLASS_NAME,
                CLASS_NAME,
                WS_POPUP,
                0,
                0,
                0,
                0,
                None,
                None,
                Some(hinstance),
                None,
            )
            .call("CreateWindowExW")?;
            let icon = match create_icon(icon) {
                Ok(icon) => icon,
                Err(err) => {
                    let _ = DestroyWindow(hwnd);
                    return Err(err);
                }
            };
            let mut data = NOTIFYICONDATAW {
                cbSize: size_of::<NOTIFYICONDATAW>() as u32,
                hWnd: hwnd,
                uID: ICON_ID,
                uFlags: NIF_ICON | NIF_MESSAGE | NIF_TIP,
                uCallbackMessage: WM_TRAY,
                hIcon: icon,
                ..Default::default()
            };
            set_tip(&mut data, tooltip);
            let shared = Box::into_raw(Box::new(Shared {
                entries: RefCell::new(Vec::new()),
                generation: Cell::new(0),
                chosen: RefCell::new(VecDeque::new()),
                icon_data: RefCell::new(data),
                taskbar_created: RegisterWindowMessageW(w!("TaskbarCreated")),
                unlocked: Cell::new(false),
            }));
            SetWindowLongPtrW(hwnd, GWLP_USERDATA, shared as isize);
            allow_dark_menus(hwnd);
            // Without it, the tray does not know when the user unlocks. Then a held popup waits
            // for its next check.
            let _ = WTSRegisterSessionNotification(hwnd, NOTIFY_FOR_THIS_SESSION);

            let tray = Self {
                _ui: ui.clone(),
                hwnd,
                icon,
                timer,
                shared,
                commands: Vec::new(),
            };
            if !Shell_NotifyIconW(NIM_ADD, &data).as_bool() {
                return Err(Error::TrayIconNotAdded);
            }
            Ok(tray)
        }
    }

    fn shared(&self) -> &Shared {
        unsafe { &*self.shared }
    }

    /// Replace the menu. A choice that the user made in the old menu and that [`Tray::wait`]
    /// did not return yet is dropped.
    pub fn set_menu(&mut self, items: &[MenuItem<C>]) {
        self.commands.clear();
        let entries = to_entries(items, &mut self.commands);
        let shared = self.shared();
        shared.entries.replace(entries);
        shared.generation.set(shared.generation.get() + 1);
    }

    /// Change the text that shows when the pointer is on the icon. Windows shows up to 127
    /// characters.
    pub fn set_tooltip(&self, tooltip: &str) {
        let mut data = self.shared().icon_data.borrow_mut();
        set_tip(&mut data, tooltip);
        unsafe {
            let _ = Shell_NotifyIconW(NIM_MODIFY, &*data);
        }
    }

    /// Handle the window messages of the thread until there is something for the app: a menu
    /// command, the time `until` (if given), an unlock of the session, or a quit.
    ///
    /// The deadline is a clock time. It stays correct after sleep, hibernation, or a change of
    /// the clock. While it waits, the thread uses no CPU.
    pub fn wait(&self, until: Option<SystemTime>) -> Result<Wake<C>> {
        if until.is_none() {
            self.timer.cancel();
        }
        let shared = self.shared();
        loop {
            unsafe {
                let mut msg = MSG::default();
                while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {
                    if msg.message == WM_QUIT {
                        return Ok(Wake::Quit);
                    }
                    let _ = TranslateMessage(&msg);
                    DispatchMessageW(&msg);
                }
            }
            loop {
                let chosen = shared.chosen.borrow_mut().pop_front();
                let Some((generation, index)) = chosen else {
                    break;
                };
                if generation == shared.generation.get()
                    && let Some(command) = self.commands.get(index)
                {
                    return Ok(Wake::Command(command.clone()));
                }
            }
            if shared.unlocked.replace(false) {
                return Ok(Wake::SessionUnlocked);
            }
            if let Some(t) = until {
                if SystemTime::now() >= t {
                    return Ok(Wake::Deadline);
                }
                self.timer.set(t)?;
            }
            unsafe {
                MsgWaitForMultipleObjectsEx(
                    Some(&[self.timer.0]),
                    INFINITE,
                    QS_ALLINPUT,
                    MWMO_INPUTAVAILABLE,
                );
            }
        }
    }
}

impl<C> Drop for Tray<C> {
    fn drop(&mut self) {
        unsafe {
            let data = (*self.shared).icon_data.borrow();
            let _ = Shell_NotifyIconW(NIM_DELETE, &*data);
            drop(data);
            let _ = DestroyIcon(self.icon);
            let _ = WTSUnRegisterSessionNotification(self.hwnd);
            let _ = DestroyWindow(self.hwnd);
            drop(Box::from_raw(self.shared as *mut Shared));
        }
    }
}

fn to_entries<C: Clone>(items: &[MenuItem<C>], commands: &mut Vec<C>) -> Vec<Entry> {
    items
        .iter()
        .map(|item| match item {
            MenuItem::Command {
                command,
                label,
                enabled,
                checked,
            } => {
                commands.push(command.clone());
                Entry::Action {
                    index: commands.len() - 1,
                    label: label.clone(),
                    enabled: *enabled,
                    checked: *checked,
                }
            }
            MenuItem::Label(label) => Entry::Label(label.clone()),
            MenuItem::Separator => Entry::Separator,
            MenuItem::Submenu { label, items } => Entry::Submenu {
                label: label.clone(),
                entries: to_entries(items, commands),
            },
            MenuItem::Quit(label) => Entry::Quit(label.clone()),
        })
        .collect()
}

fn set_tip(data: &mut NOTIFYICONDATAW, tip: &str) {
    let max = data.szTip.len() - 1;
    let wide: Vec<u16> = tip.encode_utf16().take(max).collect();
    data.szTip = [0; 128];
    data.szTip[..wide.len()].copy_from_slice(&wide);
}

/// An absolute timer fires at the correct clock time after sleep, hibernation, or a clock change.
/// Thus the wait does not have to wake up to check the clock.
struct DeadlineTimer(HANDLE);

impl DeadlineTimer {
    fn new() -> Result<Self> {
        let handle = unsafe {
            CreateWaitableTimerExW(None, PCWSTR::null(), 0, TIMER_ALL_ACCESS.0)
                .call("CreateWaitableTimerExW")?
        };
        Ok(Self(handle))
    }

    fn set(&self, at: SystemTime) -> Result<()> {
        let due = absolute_due_time(at);
        unsafe { SetWaitableTimer(self.0, &due, 0, None, None, false).call("SetWaitableTimer") }
    }

    fn cancel(&self) {
        unsafe {
            let _ = CancelWaitableTimer(self.0);
        }
    }
}

impl Drop for DeadlineTimer {
    fn drop(&mut self) {
        unsafe {
            let _ = CloseHandle(self.0);
        }
    }
}

extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    unsafe {
        let shared = GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *const Shared;
        if shared.is_null() {
            return DefWindowProcW(hwnd, msg, wparam, lparam);
        }
        let shared = &*shared;
        match msg {
            WM_TRAY => {
                let event = (lparam.0 & 0xFFFF) as u32;
                if event == WM_LBUTTONUP || event == WM_RBUTTONUP {
                    show_menu(hwnd, shared);
                }
                LRESULT(0)
            }
            WM_WTSSESSION_CHANGE => {
                if wparam.0 == WTS_SESSION_UNLOCK {
                    shared.unlocked.set(true);
                }
                LRESULT(0)
            }
            m if m != 0 && m == shared.taskbar_created => {
                let data = *shared.icon_data.borrow();
                let _ = Shell_NotifyIconW(NIM_ADD, &data);
                LRESULT(0)
            }
            WM_NCDESTROY => {
                SetWindowLongPtrW(hwnd, GWLP_USERDATA, 0);
                DefWindowProcW(hwnd, msg, wparam, lparam)
            }
            _ => DefWindowProcW(hwnd, msg, wparam, lparam),
        }
    }
}

#[derive(Clone, Copy)]
enum Choice {
    Action(usize),
    Quit,
}

fn add_choice(choices: &mut Vec<Choice>, choice: Choice) -> usize {
    choices.push(choice);
    FIRST_ID + choices.len() - 1
}

fn append_entries(menu: HMENU, entries: &[Entry], choices: &mut Vec<Choice>) {
    let flag = |on: bool, f: MENU_ITEM_FLAGS| if on { f } else { MENU_ITEM_FLAGS(0) };
    unsafe {
        for entry in entries {
            match entry {
                Entry::Action {
                    index,
                    label,
                    enabled,
                    checked,
                } => {
                    let _ = AppendMenuW(
                        menu,
                        MF_STRING | flag(!enabled, MF_GRAYED) | flag(*checked, MF_CHECKED),
                        add_choice(choices, Choice::Action(*index)),
                        &HSTRING::from(label),
                    );
                }
                Entry::Label(label) => {
                    let _ = AppendMenuW(menu, MF_STRING | MF_GRAYED, 0, &HSTRING::from(label));
                }
                Entry::Separator => {
                    let _ = AppendMenuW(menu, MF_SEPARATOR, 0, PCWSTR::null());
                }
                Entry::Submenu { label, entries } => {
                    if let Ok(sub) = CreatePopupMenu() {
                        append_entries(sub, entries, choices);
                        let _ = AppendMenuW(menu, MF_POPUP, sub.0 as usize, &HSTRING::from(label));
                    }
                }
                Entry::Quit(label) => {
                    let _ = AppendMenuW(
                        menu,
                        MF_STRING,
                        add_choice(choices, Choice::Quit),
                        &HSTRING::from(label),
                    );
                }
            }
        }
    }
}

fn show_menu(hwnd: HWND, shared: &Shared) {
    let entries = shared.entries.borrow().clone();
    let generation = shared.generation.get();
    unsafe {
        let Ok(menu) = CreatePopupMenu() else {
            return;
        };
        let mut choices = Vec::new();
        append_entries(menu, &entries, &mut choices);

        let mut pt = POINT::default();
        let _ = GetCursorPos(&mut pt);
        // This is necessary. Without it, the menu does not close when the user clicks outside it.
        let _ = SetForegroundWindow(hwnd);
        let chosen = TrackPopupMenu(
            menu,
            TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON | TPM_BOTTOMALIGN | TPM_RIGHTALIGN,
            pt.x,
            pt.y,
            None,
            hwnd,
            None,
        );
        let _ = PostMessageW(Some(hwnd), WM_NULL, WPARAM(0), LPARAM(0));
        let _ = DestroyMenu(menu);

        let index = (chosen.0 as usize).wrapping_sub(FIRST_ID);
        match choices.get(index) {
            Some(Choice::Action(action)) => {
                shared.chosen.borrow_mut().push_back((generation, *action));
            }
            Some(Choice::Quit) => PostQuitMessage(0),
            None => {}
        }
    }
}

fn create_icon(image: &Icon) -> Result<HICON> {
    let size = image.size as i32;
    unsafe {
        let info = BITMAPINFO {
            bmiHeader: BITMAPINFOHEADER {
                biSize: size_of::<BITMAPINFOHEADER>() as u32,
                biWidth: size,
                biHeight: -size,
                biPlanes: 1,
                biBitCount: 32,
                biCompression: BI_RGB.0,
                ..Default::default()
            },
            ..Default::default()
        };
        let mut bits: *mut c_void = std::ptr::null_mut();
        let color = CreateDIBSection(None, &info, DIB_RGB_COLORS, &mut bits, None, 0)
            .call("CreateDIBSection")?;
        std::slice::from_raw_parts_mut(bits as *mut u32, image.pixels.len())
            .copy_from_slice(&image.pixels);

        let stride = ((size + 15) / 16 * 2) as usize;
        let mask_bits = vec![0u8; stride * size as usize];
        let mask = CreateBitmap(size, size, 1, 1, Some(mask_bits.as_ptr().cast()));
        let icon = CreateIconIndirect(&ICONINFO {
            fIcon: TRUE,
            xHotspot: 0,
            yHotspot: 0,
            hbmMask: mask,
            hbmColor: color,
        });
        let _ = DeleteObject(color.into());
        let _ = DeleteObject(mask.into());
        icon.call("CreateIconIndirect")
    }
}

/// Make the menus follow the Windows dark mode, as the menus of File Explorer do.
/// Windows has no public API for this. uxtheme.dll exports the functions only by number, since
/// Windows 10 version 1903. If a function is missing, the menus stay light.
fn allow_dark_menus(hwnd: HWND) {
    unsafe {
        let Ok(uxtheme) = LoadLibraryW(w!("uxtheme.dll")) else {
            return;
        };
        let export = |number: u16| GetProcAddress(uxtheme, PCSTR(number as usize as *const u8));
        if let Some(f) = export(SET_PREFERRED_APP_MODE) {
            let set: unsafe extern "system" fn(i32) -> i32 = std::mem::transmute(f);
            set(APP_MODE_ALLOW_DARK);
        }
        if let Some(f) = export(ALLOW_DARK_MODE_FOR_WINDOW) {
            let allow: unsafe extern "system" fn(HWND, BOOL) -> BOOL = std::mem::transmute(f);
            let _ = allow(hwnd, TRUE);
        }
        if let Some(f) = export(FLUSH_MENU_THEMES) {
            let flush: unsafe extern "system" fn() = std::mem::transmute(f);
            flush();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;

    #[test]
    fn due_time_counts_from_1601() {
        assert_eq!(absolute_due_time(UNIX_EPOCH), UNIX_EPOCH_AS_FILETIME);
        let one_second = UNIX_EPOCH + Duration::from_secs(1);
        assert_eq!(
            absolute_due_time(one_second),
            UNIX_EPOCH_AS_FILETIME + 10_000_000
        );
    }

    #[test]
    fn due_time_stays_positive_far_in_the_future() {
        const YEAR: u64 = 365 * 24 * 60 * 60;
        let far = UNIX_EPOCH
            .checked_add(Duration::from_secs(20_000 * YEAR))
            .expect("SystemTime holds 20000 years");
        assert!(absolute_due_time(far) > UNIX_EPOCH_AS_FILETIME);
    }

    #[test]
    fn due_time_before_1970_is_1970() {
        let before = UNIX_EPOCH - Duration::from_secs(60);
        assert_eq!(absolute_due_time(before), UNIX_EPOCH_AS_FILETIME);
    }

    #[test]
    fn icon_needs_one_pixel_per_cell() {
        assert!(Icon::from_argb(2, vec![0; 4]).is_ok());
        assert!(matches!(
            Icon::from_argb(2, vec![0; 3]),
            Err(Error::InvalidIcon { size: 2, pixels: 3 })
        ));
    }

    #[test]
    fn builders_change_only_command_items() {
        let item = MenuItem::command('a', "A").enabled(false).checked(true);
        assert_eq!(
            item,
            MenuItem::Command {
                command: 'a',
                label: "A".into(),
                enabled: false,
                checked: true,
            }
        );
        assert_eq!(
            MenuItem::<char>::Separator.checked(true),
            MenuItem::Separator
        );
    }

    #[test]
    fn entries_number_the_commands_in_order() {
        let items = vec![
            MenuItem::Label("status".into()),
            MenuItem::command(10, "a"),
            MenuItem::Submenu {
                label: "more".into(),
                items: vec![MenuItem::command(20, "b"), MenuItem::Separator],
            },
            MenuItem::Quit("quit".into()),
        ];
        let mut commands = Vec::new();
        let entries = to_entries(&items, &mut commands);
        assert_eq!(commands, [10, 20]);
        assert!(matches!(entries[1], Entry::Action { index: 0, .. }));
        let Entry::Submenu { entries: sub, .. } = &entries[2] else {
            panic!("expected a submenu");
        };
        assert!(matches!(sub[0], Entry::Action { index: 1, .. }));
        assert!(matches!(entries[3], Entry::Quit(_)));
    }
}