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

//! The state of a prompt window: its mouse and timer handling, and its drawing.

use std::cell::{Cell, RefCell};
use std::time::{Duration, Instant, SystemTime};

use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::Graphics::Direct2D::Common::{
    D2D_RECT_F, D2D_SIZE_U, D2D1_ALPHA_MODE_PREMULTIPLIED, D2D1_PIXEL_FORMAT,
};
use windows::Win32::Graphics::Direct2D::{
    D2D1_BITMAP_OPTIONS_NONE, D2D1_BITMAP_PROPERTIES1, D2D1_DRAW_TEXT_OPTIONS_NONE,
    D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC, D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE,
    ID2D1DeviceContext,
};
use windows::Win32::Graphics::DirectWrite::DWRITE_MEASURING_MODE_NATURAL;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use windows::Win32::UI::Controls::WM_MOUSELEAVE;
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture};
use windows::Win32::UI::WindowsAndMessaging::{
    DefWindowProcW, HWND_TOPMOST, IDC_HAND, KillTimer, LoadCursorW, MA_ACTIVATE, MA_NOACTIVATE,
    SW_SHOWNOACTIVATE, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SetCursor, SetTimer, SetWindowPos,
    ShowWindow, WM_CHAR, WM_DESTROY, WM_KEYDOWN, WM_KILLFOCUS, WM_LBUTTONDOWN, WM_LBUTTONUP,
    WM_MOUSEACTIVATE, WM_MOUSEMOVE, WM_SETCURSOR, WM_SETFOCUS, WM_TIMER,
};
use windows_numerics::Vector2;

use super::countdown::{self, Countdown};
use super::glass::Scene;
use super::input::{Frame, TextBox};
use super::layout::{Fonts, Layout};
use super::{Image, Mark, PopupStyle, Prompt, Reply, Response};
use crate::error::{Call, Result};
use crate::native::{self, state_of};
use crate::render;
use crate::theme::Theme;
use crate::ui::Notice;

/// The window closes this long after the fade-out, so the last frame shows.
const FADE_OUT_EXTRA: Duration = Duration::from_millis(50);
const TIMER_COUNTDOWN: usize = 1;
const TIMER_FADE_OUT: usize = 2;
const TIMER_FEEDBACK: usize = 3;
const BACKSPACE: u16 = 0x08;
const ENTER: u16 = 0x0D;
/// Ctrl+V.
const PASTE: u16 = 0x16;
const ESCAPE: u16 = 0x1B;

/// The window procedure can run again inside a call that it makes. For example,
/// `ReleaseCapture` sends `WM_CAPTURECHANGED`. Thus the state is shared and changes only in
/// `Cell` and `RefCell`. Handlers do not destroy the window. They set `response`, and the
/// loop in `ChoicePopup::ask` destroys the window.
pub(super) struct WindowState {
    pub(super) id: u32,
    pub(super) style: PopupStyle,
    pub(super) layout: RefCell<Layout>,
    pub(super) scene: Scene,
    pub(super) theme: Theme,
    pub(super) fonts: Fonts,
    hover: Cell<Option<usize>>,
    pressed: Cell<Option<usize>>,
    pointer_inside: Cell<bool>,
    dismiss: String,
    countdown: RefCell<Option<Countdown>>,
    marks: Option<Vec<Vec<(usize, Mark)>>>,
    image: Option<Image>,
    input: Option<RefCell<TextBox>>,
    selected: Cell<Option<usize>>,
    /// True from the start of the feedback or the fade-out. Then the popup ignores the mouse.
    closing: Cell<bool>,
    /// The response to give when the fade-out is complete.
    pending: RefCell<Option<Response>>,
    decided_at: Cell<Option<SystemTime>>,
    response: RefCell<Option<Response>>,
}

impl WindowState {
    pub(super) fn new(
        id: u32,
        style: PopupStyle,
        layout: Layout,
        scene: Scene,
        theme: Theme,
        fonts: Fonts,
        request: &Prompt,
    ) -> Self {
        Self {
            id,
            style,
            layout: RefCell::new(layout),
            scene,
            theme,
            fonts,
            hover: Cell::new(None),
            pressed: Cell::new(None),
            pointer_inside: Cell::new(false),
            dismiss: request.dismiss.to_string(),
            countdown: RefCell::new(request.auto_dismiss.map(Countdown::new)),
            marks: request.marks.clone(),
            image: request.image.clone(),
            input: request.input.clone().map(|p| RefCell::new(TextBox::new(p))),
            selected: Cell::new(None),
            closing: Cell::new(false),
            pending: RefCell::new(None),
            decided_at: Cell::new(None),
            response: RefCell::new(None),
        }
    }

    /// The reply, once the prompt has ended.
    pub(super) fn reply(&self) -> Option<Reply> {
        let response = self.response.borrow().clone()?;
        let at = self.decided_at.get().unwrap_or_else(SystemTime::now);
        Some(Reply { response, at })
    }

    /// Draw the first frame, show the window, and start the fade-in and the countdown.
    pub(super) fn open(&self, hwnd: HWND) -> Result<()> {
        self.draw()?;
        unsafe {
            let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
            SetWindowPos(
                hwnd,
                Some(HWND_TOPMOST),
                0,
                0,
                0,
                0,
                SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
            )
            .call("SetWindowPos")?;
        }
        self.scene.fade(0.0, 1.0, self.style.fade)?;
        self.resume_countdown(hwnd);
        Ok(())
    }

    /// End the prompt with this response, and wake the event loop. A later response is
    /// ignored.
    fn finish(&self, response: Response) {
        if self.response.borrow().is_none() {
            *self.response.borrow_mut() = Some(response);
            crate::ui::notify(Notice::Popup(self.id));
        }
    }

    /// Called when the timer of the countdown fires. It updates the label, if the whole
    /// seconds changed, and sets the next timer.
    fn tick(&self, hwnd: HWND) {
        let (left, label, running) = {
            let mut countdown = self.countdown.borrow_mut();
            let Some(c) = countdown.as_mut() else {
                return;
            };
            let left = c.remaining(Instant::now());
            let seconds = countdown::whole_seconds(left);
            let mut label = None;
            if seconds != c.shown {
                c.shown = seconds;
                label = Some(countdown::label(&self.dismiss, seconds));
            }
            (left, label, c.is_running())
        };
        if left.is_zero() {
            self.decide();
            self.fade_out(hwnd, Response::TimedOut);
            return;
        }
        if let Some(label) = label {
            if let Some(b) = self.layout.borrow_mut().buttons.last_mut() {
                b.label = label.encode_utf16().collect();
            }
            self.redraw();
        }
        if running {
            self.arm_countdown(hwnd, left);
        }
    }

    /// Let the countdown run from its time left, and wake up at its next whole second.
    fn resume_countdown(&self, hwnd: HWND) {
        let now = Instant::now();
        let left = self.countdown.borrow_mut().as_mut().map(|c| {
            c.resume(now);
            c.remaining(now)
        });
        if let Some(left) = left {
            self.arm_countdown(hwnd, left);
        }
    }

    /// Stop the countdown while the pointer is on the popup. It keeps the time left.
    fn pause_countdown(&self, hwnd: HWND) {
        if let Some(c) = self.countdown.borrow_mut().as_mut() {
            c.pause(Instant::now());
        }
        unsafe {
            let _ = KillTimer(Some(hwnd), TIMER_COUNTDOWN);
        }
    }

    fn arm_countdown(&self, hwnd: HWND, left: Duration) {
        let delay = countdown::until_next_second(left);
        unsafe {
            SetTimer(Some(hwnd), TIMER_COUNTDOWN, delay.as_millis() as u32, None);
        }
    }

    fn decide(&self) {
        if self.decided_at.get().is_none() {
            self.decided_at.set(Some(SystemTime::now()));
        }
    }

    /// Stop the countdown and ignore the mouse from now on.
    fn close_input(&self, hwnd: HWND) {
        self.countdown.replace(None);
        self.closing.set(true);
        self.hover.set(None);
        unsafe {
            let _ = KillTimer(Some(hwnd), TIMER_COUNTDOWN);
            if self.pressed.take().is_some() {
                let _ = ReleaseCapture();
            }
        }
    }

    fn show_feedback(&self, hwnd: HWND, selected: usize) {
        self.close_input(hwnd);
        self.selected.set(Some(selected));
        self.redraw();
        let held = unsafe {
            SetTimer(
                Some(hwnd),
                TIMER_FEEDBACK,
                self.style.hold.as_millis() as u32,
                None,
            ) != 0
        };
        if !held {
            self.fade_out(hwnd, Response::Choice(selected));
        }
    }

    fn fade_out(&self, hwnd: HWND, response: Response) {
        self.close_input(hwnd);
        *self.pending.borrow_mut() = Some(response.clone());
        unsafe {
            let started = match self.scene.fade(1.0, 0.0, self.style.fade) {
                Ok(()) => {
                    SetTimer(
                        Some(hwnd),
                        TIMER_FADE_OUT,
                        (self.style.fade + FADE_OUT_EXTRA).as_millis() as u32,
                        None,
                    ) != 0
                }
                // Without the animation, the popup closes at once.
                Err(_) => false,
            };
            if !started {
                self.finish(response);
            }
        }
    }

    /// Stop the countdown for good, and show the plain dismiss label.
    fn stop_countdown(&self, hwnd: HWND) {
        if self.countdown.replace(None).is_some() {
            unsafe {
                let _ = KillTimer(Some(hwnd), TIMER_COUNTDOWN);
            }
            if let Some(b) = self.layout.borrow_mut().buttons.last_mut() {
                b.label = self.dismiss.encode_utf16().collect();
            }
        }
    }

    /// Handle one `WM_CHAR` for the input box.
    fn type_char(&self, hwnd: HWND, unit: u16) {
        let Some(input) = &self.input else {
            return;
        };
        let changed = match unit {
            ENTER => {
                let text = input.borrow().text().trim().to_string();
                if !text.is_empty() {
                    self.decide();
                    self.close_input(hwnd);
                    self.finish(Response::Text(text));
                }
                return;
            }
            ESCAPE => {
                self.decide();
                self.close_input(hwnd);
                self.finish(Response::Dismissed);
                return;
            }
            BACKSPACE => input.borrow_mut().backspace(),
            PASTE => match crate::clipboard::text(hwnd) {
                Some(text) => input.borrow_mut().insert(&text),
                None => false,
            },
            unit if unit < 0x20 || unit == 0x7F => false,
            unit => input.borrow_mut().type_unit(unit),
        };
        if changed {
            self.stop_countdown(hwnd);
            self.redraw();
        }
    }

    /// Handle a key that moves the caret or deletes. It gives false for other keys.
    fn move_caret(&self, key: u16) -> bool {
        let Some(input) = &self.input else {
            return false;
        };
        let Some(changed) = input.borrow_mut().press(key) else {
            return false;
        };
        if changed {
            self.redraw();
        }
        true
    }

    fn hit(&self, lparam: LPARAM) -> Option<usize> {
        let (x, y) = native::point(lparam);
        let (x, y) = (x as f32, y as f32);
        self.layout.borrow().buttons.iter().position(|b| {
            x >= b.rect.left && x < b.rect.right && y >= b.rect.top && y < b.rect.bottom
        })
    }

    fn draw(&self) -> Result<()> {
        let t = &self.theme;
        let l = &*self.layout.borrow();
        let (hover, pressed) = (self.hover.get(), self.pressed.get());
        let shown: &[(usize, Mark)] = match (self.selected.get(), &self.marks) {
            (Some(clicked), Some(marks)) => &marks[clicked],
            _ => &[],
        };
        self.scene.draw(|dc: &ID2D1DeviceContext| unsafe {
            dc.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
            let frame = render::rounded(
                render::rect(0.0, 0.0, l.width, l.height),
                0.5,
                l.window_radius,
            );
            let window_border = dc.CreateSolidColorBrush(&t.window_border, None)?;
            dc.DrawRoundedRectangle(&frame, &window_border, 1.0, None);

            let text = dc.CreateSolidColorBrush(&t.text, None)?;
            dc.DrawTextLayout(
                Vector2 { X: l.pad, Y: l.pad },
                &l.prompt,
                &text,
                D2D1_DRAW_TEXT_OPTIONS_NONE,
            );
            if let (Some(rect), Some(image)) = (l.image, &self.image) {
                draw_image(dc, image, rect)?;
            }
            if let (Some(rect), Some(input)) = (l.input, &self.input) {
                let frame = Frame {
                    rect,
                    radius: l.radius,
                    padding: l.input_padding,
                };
                input.borrow().draw(dc, frame, &self.theme, &self.fonts)?;
            }

            for (i, b) in l.buttons.iter().enumerate() {
                let mark = shown
                    .iter()
                    .find(|&&(index, _)| index == i)
                    .map(|&(_, m)| m);
                let fill = match mark {
                    Some(Mark::Good) => t.good,
                    Some(Mark::Bad) => t.bad,
                    _ if pressed == Some(i) && hover == Some(i) => t.button_pressed,
                    _ if hover == Some(i) => t.button_hover,
                    _ => t.button,
                };
                render::panel(dc, b.rect, l.radius, &fill, &t.button_border)?;
                dc.DrawText(
                    &b.label,
                    &self.fonts.button,
                    &b.rect,
                    &text,
                    D2D1_DRAW_TEXT_OPTIONS_NONE,
                    DWRITE_MEASURING_MODE_NATURAL,
                );
            }
            Ok(())
        })
    }

    /// A failed redraw keeps the last frame. The next redraw tries again.
    fn redraw(&self) {
        let _ = self.draw();
    }
}

/// Draw the image into `rect`. The popup redraws only when something changes, so it makes
/// the bitmap again each time and keeps no GPU resource between frames.
fn draw_image(
    dc: &ID2D1DeviceContext,
    image: &Image,
    rect: D2D_RECT_F,
) -> windows::core::Result<()> {
    unsafe {
        let bitmap = dc.CreateBitmap(
            D2D_SIZE_U {
                width: image.width,
                height: image.height,
            },
            Some(image.pixels.as_ptr().cast()),
            image.width * 4,
            &D2D1_BITMAP_PROPERTIES1 {
                pixelFormat: D2D1_PIXEL_FORMAT {
                    format: DXGI_FORMAT_B8G8R8A8_UNORM,
                    alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED,
                },
                dpiX: 96.0,
                dpiY: 96.0,
                bitmapOptions: D2D1_BITMAP_OPTIONS_NONE,
                colorContext: std::mem::ManuallyDrop::new(None),
            },
        )?;
        dc.DrawBitmap(
            &bitmap,
            Some(&rect),
            1.0,
            D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC,
            None,
            None,
        );
    }
    Ok(())
}

pub(super) extern "system" fn wndproc(
    hwnd: HWND,
    msg: u32,
    wparam: WPARAM,
    lparam: LPARAM,
) -> LRESULT {
    unsafe {
        let Some(state) = state_of::<WindowState>(hwnd) else {
            return DefWindowProcW(hwnd, msg, wparam, lparam);
        };

        match msg {
            WM_MOUSEACTIVATE if state.input.is_some() && !state.closing.get() => {
                LRESULT(MA_ACTIVATE as isize)
            }
            WM_MOUSEACTIVATE => LRESULT(MA_NOACTIVATE as isize),
            WM_SETFOCUS | WM_KILLFOCUS => {
                if let Some(input) = &state.input {
                    input.borrow_mut().focused = msg == WM_SETFOCUS;
                    state.redraw();
                }
                LRESULT(0)
            }
            // A posted WM_CHAR also counts, so a test can type without the focus.
            WM_CHAR if state.input.is_some() && !state.closing.get() => {
                state.type_char(hwnd, wparam.0 as u16);
                LRESULT(0)
            }
            WM_KEYDOWN if state.input.is_some() && !state.closing.get() => {
                if state.move_caret(wparam.0 as u16) {
                    LRESULT(0)
                } else {
                    DefWindowProcW(hwnd, msg, wparam, lparam)
                }
            }
            WM_TIMER => {
                match wparam.0 {
                    TIMER_COUNTDOWN => state.tick(hwnd),
                    TIMER_FEEDBACK => {
                        let _ = KillTimer(Some(hwnd), TIMER_FEEDBACK);
                        if let Some(selected) = state.selected.get() {
                            state.fade_out(hwnd, Response::Choice(selected));
                        }
                    }
                    TIMER_FADE_OUT => {
                        let pending = state.pending.borrow_mut().take();
                        if let Some(response) = pending {
                            state.finish(response);
                        }
                    }
                    _ => {}
                }
                LRESULT(0)
            }
            WM_MOUSEMOVE | WM_LBUTTONDOWN | WM_LBUTTONUP if state.closing.get() => LRESULT(0),
            WM_MOUSEMOVE => {
                if !state.pointer_inside.get() && native::track_leave(hwnd) {
                    state.pointer_inside.set(true);
                    state.pause_countdown(hwnd);
                }
                let hit = state.hit(lparam);
                if hit != state.hover.get() {
                    state.hover.set(hit);
                    state.redraw();
                }
                LRESULT(0)
            }
            WM_MOUSELEAVE => {
                state.pointer_inside.set(false);
                state.resume_countdown(hwnd);
                state.hover.set(None);
                state.redraw();
                LRESULT(0)
            }
            WM_SETCURSOR if state.hover.get().is_some() => {
                if let Ok(hand) = LoadCursorW(None, IDC_HAND) {
                    SetCursor(Some(hand));
                }
                LRESULT(1)
            }
            WM_LBUTTONDOWN => {
                let hit = state.hit(lparam);
                state.pressed.set(hit);
                if hit.is_some() {
                    SetCapture(hwnd);
                    state.redraw();
                }
                LRESULT(0)
            }
            WM_LBUTTONUP => {
                let pressed = state.pressed.take();
                let _ = ReleaseCapture();
                let hit = state.hit(lparam);
                match pressed {
                    Some(i) if hit == Some(i) => {
                        state.decide();
                        let response = state.layout.borrow().buttons[i].response.clone();
                        match response {
                            Response::Choice(choice) if state.marks.is_some() => {
                                state.show_feedback(hwnd, choice);
                            }
                            _ => state.finish(response),
                        }
                    }
                    Some(_) => {
                        state.hover.set(hit);
                        state.redraw();
                    }
                    None => {}
                }
                LRESULT(0)
            }
            WM_DESTROY => {
                state.finish(Response::Dismissed);
                LRESULT(0)
            }
            _ => DefWindowProcW(hwnd, msg, wparam, lparam),
        }
    }
}