glasskit 0.6.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
// Copyright (c) 2026 John Law
// SPDX-License-Identifier: MIT

//! The main loop of an app: one loop for all trays, popups, and dialogs of a thread.
//!
//! [`EventLoop::next`] handles the window messages of the thread, and returns when there is
//! something for the app: a menu command, the end of a popup, a change in a dialog, a deadline,
//! an unlock of the session, a wake from another thread, or a quit. Popups and dialogs that show do not stop the loop, so
//! a dialog can stay open while popups come and go.

use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use windows::Win32::Foundation::{
    CloseHandle, HANDLE, HWND, LPARAM, LRESULT, WAIT_OBJECT_0, WPARAM,
};
use windows::Win32::System::RemoteDesktop::{
    NOTIFY_FOR_THIS_SESSION, WTSRegisterSessionNotification, WTSUnRegisterSessionNotification,
};
use windows::Win32::System::Threading::{
    CancelWaitableTimer, CreateEventW, CreateWaitableTimerExW, INFINITE, ResetEvent, SetEvent,
    SetWaitableTimer, TIMER_ALL_ACCESS, WaitForSingleObject,
};
use windows::Win32::UI::WindowsAndMessaging::{
    DefWindowProcW, IDC_ARROW, MWMO_INPUTAVAILABLE, MsgWaitForMultipleObjectsEx, QS_ALLINPUT,
    WM_WTSSESSION_CHANGE, WTS_SESSION_UNLOCK,
};
use windows::core::{PCWSTR, w};

use crate::Ui;
use crate::error::{Call, Result};
use crate::native::{self, NativeWindow};
use crate::ui::Notice;

const CLASS_NAME: PCWSTR = w!("GlasskitEvents");
/// Ticks of 100 ns from 1601-01-01 (FILETIME) to 1970-01-01 (Unix).
const UNIX_EPOCH_AS_FILETIME: i64 = 116_444_736_000_000_000;

/// The id of a [`ChoicePopup`](crate::popup::ChoicePopup), as [`Event::Popup`] gives it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PopupId(pub(crate) u32);

/// The id of a [`Dialog`](crate::dialog::Dialog), as [`Event::Dialog`] gives it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DialogId(pub(crate) u32);

/// The id of a [`Window`](crate::window::Window), as [`Event::Window`] gives it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WindowId(pub(crate) u32);

/// Something for the app. `C` is the command type of the trays.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event<C> {
    /// The user picked a command item of a tray menu.
    Command(C),
    /// A popup has ended: call [`ChoicePopup::take_reply`](crate::popup::ChoicePopup::take_reply)
    /// on the popup with this id.
    Popup(PopupId),
    /// A dialog has events: call [`Dialog::next_event`](crate::dialog::Dialog::next_event) on
    /// the dialog with this id until it gives `None`.
    Dialog(DialogId),
    /// A window has events: call [`Window::next_event`](crate::window::Window::next_event) on
    /// the window with this id until it gives `None`.
    Window(WindowId),
    /// The time given to [`EventLoop::next`] came.
    Deadline,
    /// The user unlocked the session: someone is at the screen again.
    SessionUnlocked,
    /// Another thread called [`Waker::wake`]. Many calls can give one event.
    Wake,
    /// The user picked the quit item of a tray menu, or the thread got `WM_QUIT`.
    Quit,
}

/// Something that gives commands to the loop, such as a tray.
pub(crate) trait Source<C> {
    fn take_command(&self) -> Option<C>;
}

/// What the loop gives, apart from a command.
enum Ready {
    Popup(PopupId),
    Dialog(DialogId),
    Window(WindowId),
    SessionUnlocked,
    Wake,
    Deadline,
}

impl<C> From<Ready> for Event<C> {
    fn from(ready: Ready) -> Self {
        match ready {
            Ready::Popup(id) => Event::Popup(id),
            Ready::Dialog(id) => Event::Dialog(id),
            Ready::Window(id) => Event::Window(id),
            Ready::SessionUnlocked => Event::SessionUnlocked,
            Ready::Wake => Event::Wake,
            Ready::Deadline => Event::Deadline,
        }
    }
}

/// The main loop of the thread. `C` is the command type of the trays.
///
/// Make it with a [`Ui`], then give it to [`Tray::new`](crate::tray::Tray::new).
pub struct EventLoop<C> {
    waiter: Waiter,
    sources: RefCell<Vec<Weak<dyn Source<C>>>>,
}

impl<C> EventLoop<C> {
    /// A loop for the windows of this thread.
    pub fn new(ui: &Ui) -> Result<Self> {
        Ok(Self {
            waiter: Waiter::new(ui)?,
            sources: RefCell::new(Vec::new()),
        })
    }

    /// The setup of the thread that the loop serves.
    pub fn ui(&self) -> &Ui {
        &self.waiter.ui
    }

    /// A handle that wakes this loop from another thread.
    pub fn waker(&self) -> Waker {
        Waker(Arc::clone(&self.waiter.signal))
    }

    pub(crate) fn add_source(&self, source: Weak<dyn Source<C>>) {
        self.sources.borrow_mut().push(source);
    }

    /// Handle the window messages until there is something for the app. With `until`, it
    /// also returns [`Event::Deadline`] at that clock time. The deadline stays exact after
    /// sleep or a clock change. While it waits, the thread uses no CPU.
    pub fn next(&mut self, until: Option<SystemTime>) -> Result<Event<C>> {
        if until.is_none() {
            self.waiter.timer.cancel();
        }
        loop {
            if self.waiter.ui.pump_pending() {
                return Ok(Event::Quit);
            }
            if let Some(command) = self.take_command() {
                return Ok(Event::Command(command));
            }
            if let Some(ready) = self.waiter.poll(until)? {
                return Ok(ready.into());
            }
        }
    }

    fn take_command(&mut self) -> Option<C> {
        let sources = self.sources.get_mut();
        sources.retain(|s| s.strong_count() > 0);
        sources
            .iter()
            .find_map(|s| s.upgrade().and_then(|s| s.take_command()))
    }
}

/// The part of the loop that does not depend on the command type.
struct Waiter {
    ui: Ui,
    timer: DeadlineTimer,
    signal: Arc<Signal>,
    window: NativeWindow<Cell<bool>>,
}

impl Waiter {
    fn new(ui: &Ui) -> Result<Self> {
        let timer = DeadlineTimer::new()?;
        let signal = Arc::new(Signal::new()?);
        let hinstance = ui.hinstance();
        native::register_class(CLASS_NAME, Some(wndproc), hinstance, IDC_ARROW)?;
        let hwnd = native::create_hidden(CLASS_NAME, hinstance)?;
        let window = NativeWindow::attach(hwnd, Rc::new(Cell::new(false)));
        unsafe {
            let _ = WTSRegisterSessionNotification(hwnd, NOTIFY_FOR_THIS_SESSION);
        }
        Ok(Self {
            ui: ui.clone(),
            timer,
            signal,
            window,
        })
    }

    /// Give what is ready now. If nothing is, wait for a message or the deadline and give
    /// `None`.
    fn poll(&mut self, until: Option<SystemTime>) -> Result<Option<Ready>> {
        match self.ui.take_notice() {
            Some(Notice::Popup(id)) => return Ok(Some(Ready::Popup(PopupId(id)))),
            Some(Notice::Dialog(id)) => return Ok(Some(Ready::Dialog(DialogId(id)))),
            Some(Notice::Window(id)) => return Ok(Some(Ready::Window(WindowId(id)))),
            None => {}
        }
        if self.window.state().replace(false) {
            return Ok(Some(Ready::SessionUnlocked));
        }
        if self.signal.take() {
            return Ok(Some(Ready::Wake));
        }
        if let Some(t) = until {
            if SystemTime::now() >= t {
                return Ok(Some(Ready::Deadline));
            }
            self.timer.set(t)?;
        }
        unsafe {
            MsgWaitForMultipleObjectsEx(
                Some(&[self.timer.0, self.signal.0]),
                INFINITE,
                QS_ALLINPUT,
                MWMO_INPUTAVAILABLE,
            );
        }
        Ok(None)
    }
}

impl Drop for Waiter {
    fn drop(&mut self) {
        unsafe {
            let _ = WTSUnRegisterSessionNotification(self.window.hwnd());
        }
    }
}

extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    unsafe {
        if let (WM_WTSSESSION_CHANGE, Some(unlocked)) = (msg, native::state_of::<Cell<bool>>(hwnd))
        {
            if wparam.0 == WTS_SESSION_UNLOCK as usize {
                unlocked.set(true);
            }
            return LRESULT(0);
        }
        DefWindowProcW(hwnd, msg, wparam, lparam)
    }
}

/// Wakes an [`EventLoop`] from another thread: the loop then gives [`Event::Wake`].
///
/// Get it from [`EventLoop::waker`], and give it or a clone of it to the other thread. A
/// wake after the end of the loop does nothing.
///
/// ```no_run
/// use glasskit::Ui;
/// use glasskit::events::{Event, EventLoop};
///
/// fn main() -> glasskit::Result<()> {
///     let ui = Ui::new()?;
///     let mut events: EventLoop<()> = EventLoop::new(&ui)?;
///     let waker = events.waker();
///     let work = std::thread::spawn(move || {
///         // Slow work, then:
///         waker.wake();
///     });
///     loop {
///         match events.next(None)? {
///             Event::Wake => break,
///             Event::Quit => break,
///             _ => {}
///         }
///     }
///     work.join().expect("the work thread does not panic");
///     Ok(())
/// }
/// ```
#[derive(Clone)]
pub struct Waker(Arc<Signal>);

impl Waker {
    /// Make the loop give [`Event::Wake`]. Calls before the loop gives the event count as one.
    pub fn wake(&self) {
        self.0.set();
    }
}

impl std::fmt::Debug for Waker {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Waker").finish_non_exhaustive()
    }
}

/// An event object that stays set until [`Signal::take`]. Thus a wait that ends on it does
/// not use it up.
struct Signal(HANDLE);

// SAFETY: all threads can use the handle of an event object, and the handle lives as long
// as the value.
unsafe impl Send for Signal {}
unsafe impl Sync for Signal {}

impl Signal {
    fn new() -> Result<Self> {
        let handle =
            unsafe { CreateEventW(None, true, false, PCWSTR::null()).call("CreateEventW")? };
        Ok(Self(handle))
    }

    fn set(&self) {
        unsafe {
            let _ = SetEvent(self.0);
        }
    }

    /// Give true if the signal was set, and reset it.
    fn take(&self) -> bool {
        unsafe {
            let set = WaitForSingleObject(self.0, 0) == WAIT_OBJECT_0;
            if set {
                let _ = ResetEvent(self.0);
            }
            set
        }
    }
}

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

/// For `SetWaitableTimer`, a positive due time is absolute and a negative one is relative.
/// The value must stay positive. It saturates at the maximum and does not wrap.
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)
}

/// An absolute timer fires at the right clock time after sleep or a clock change. The wait
/// need not 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);
        }
    }
}

#[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 a_deadline_in_the_past_returns_at_once() {
        let ui = Ui::new().unwrap();
        let mut events: EventLoop<()> = EventLoop::new(&ui).unwrap();
        let past = SystemTime::now() - Duration::from_secs(1);
        assert_eq!(events.next(Some(past)).unwrap(), Event::Deadline);
    }

    #[test]
    fn a_wake_from_another_thread_gives_one_event() {
        let ui = Ui::new().unwrap();
        let mut events: EventLoop<()> = EventLoop::new(&ui).unwrap();
        let waker = events.waker();
        std::thread::spawn(move || {
            waker.wake();
            waker.wake();
        })
        .join()
        .unwrap();
        assert_eq!(events.next(None).unwrap(), Event::Wake);
        let soon = SystemTime::now() + Duration::from_millis(20);
        assert_eq!(events.next(Some(soon)).unwrap(), Event::Deadline);
    }

    #[test]
    fn a_wake_ends_a_wait() {
        let ui = Ui::new().unwrap();
        let mut events: EventLoop<()> = EventLoop::new(&ui).unwrap();
        let waker = events.waker();
        let thread = std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(50));
            waker.wake();
        });
        assert_eq!(events.next(None).unwrap(), Event::Wake);
        thread.join().unwrap();
    }

    #[test]
    fn a_wake_after_the_loop_does_nothing() {
        let ui = Ui::new().unwrap();
        let events: EventLoop<()> = EventLoop::new(&ui).unwrap();
        let waker = events.waker();
        drop(events);
        waker.wake();
    }

    #[test]
    fn a_notice_wakes_the_loop() {
        let ui = Ui::new().unwrap();
        let mut events: EventLoop<()> = EventLoop::new(&ui).unwrap();
        crate::ui::notify(Notice::Popup(7));
        assert_eq!(events.next(None).unwrap(), Event::Popup(PopupId(7)));
    }
}