microsoft-webui-desktop 3.0.3

Configurable native desktop SDK for WebUI applications
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Native window creation, style selection, and initial geometry.

use crate::{TitlebarStyle, WindowOptions, WindowState};
use anyhow::{Context, Result};
use webview2_com::CoTaskMemPWSTR;
use windows::core::{w, PCWSTR};
use windows::Win32::Foundation::{HINSTANCE, HWND};
use windows::Win32::System::LibraryLoader;
use windows::Win32::UI::WindowsAndMessaging::{
    self, WNDCLASSW, WS_MAXIMIZEBOX, WS_OVERLAPPEDWINDOW, WS_THICKFRAME,
};

use super::command::center_window;
use super::message::window_proc;
use super::nonclient::CUSTOM_FRAME_BYTES;

/// Owner of the native top-level window handle.
pub(super) struct FrameWindow {
    /// Handle to the created top-level window.
    pub(super) hwnd: HWND,
}

impl FrameWindow {
    /// Create the native window, applying saved geometry when available.
    pub(super) fn new(window: &WindowOptions, saved: Option<&WindowState>) -> Result<Self> {
        let title = CoTaskMemPWSTR::from(window.title.as_str());
        let (x, y, width, height) = initial_geometry(window, saved)?;
        let mut style = window_style(window);
        if window.maximized || saved.is_some_and(|state| state.maximized) {
            style |= WindowsAndMessaging::WS_MAXIMIZE;
        }
        // SAFETY: The executable module remains loaded for the lifetime of the
        // window; Win32 treats this low pointer value as resource ID 1, not an
        // address to dereference. The resource is optional for custom runners.
        let instance = unsafe { HINSTANCE(LibraryLoader::GetModuleHandleW(None)?.0) };
        let icon = unsafe {
            WindowsAndMessaging::LoadIconW(
                Some(instance),
                PCWSTR::from_raw(std::ptr::without_provenance(1)),
            )
            .unwrap_or_default()
        };
        // SAFETY: The class name, window title, and module handle are valid for
        // this call, and `window_proc` has the required `WNDPROC` signature.
        let hwnd = unsafe {
            let class = WNDCLASSW {
                lpfnWndProc: Some(window_proc),
                lpszClassName: w!("WebUIDesktopWindow"),
                cbWndExtra: CUSTOM_FRAME_BYTES,
                hInstance: instance,
                hIcon: icon,
                hCursor: WindowsAndMessaging::LoadCursorW(None, WindowsAndMessaging::IDC_ARROW)
                    .unwrap_or_default(),
                ..Default::default()
            };
            WindowsAndMessaging::RegisterClassW(&class);
            WindowsAndMessaging::CreateWindowExW(
                Default::default(),
                w!("WebUIDesktopWindow"),
                *title.as_ref().as_pcwstr(),
                style,
                x,
                y,
                width,
                height,
                None,
                None,
                Some(instance),
                Some(std::ptr::from_ref(window).cast()),
            )?
        };
        let frame = Self { hwnd };
        frame.apply_custom_frame(window);
        frame.apply_initial_placement(window, saved);
        Ok(frame)
    }

    pub(super) fn show(&self) -> Result<()> {
        if super::nonclient::startup_close_requested(self.hwnd) {
            return Ok(());
        }
        // SAFETY: The owner retains this live HWND on the calling thread.
        if unsafe { WindowsAndMessaging::IsWindowVisible(self.hwnd) }.as_bool() {
            return Ok(());
        }
        // The first ShowWindow call can restore a maximized window according to
        // the launcher's STARTUPINFO. Publish the configured frame unchanged.
        // SAFETY: The window is live; only visibility and frame layout change.
        unsafe {
            WindowsAndMessaging::SetWindowPos(
                self.hwnd,
                None,
                0,
                0,
                0,
                0,
                WindowsAndMessaging::SWP_NOMOVE
                    | WindowsAndMessaging::SWP_NOSIZE
                    | WindowsAndMessaging::SWP_NOZORDER
                    | WindowsAndMessaging::SWP_SHOWWINDOW
                    | WindowsAndMessaging::SWP_FRAMECHANGED,
            )?;
        }
        Ok(())
    }

    pub(super) fn focus_after_startup(&self) {
        use windows::Win32::UI::Input::KeyboardAndMouse;
        // SAFETY: The owner retains this live HWND on its creating UI thread.
        unsafe {
            let focused = KeyboardAndMouse::GetFocus();
            if focused != self.hwnd && !WindowsAndMessaging::IsChild(self.hwnd, focused).as_bool() {
                let _ = KeyboardAndMouse::SetFocus(Some(self.hwnd));
            }
        }
    }

    /// Keep DWM's shadow and system-managed corners for custom frames.
    fn apply_custom_frame(&self, window: &WindowOptions) {
        if !matches!(window.titlebar, TitlebarStyle::None) {
            return;
        }
        if let Err(error) = extend_frameless_frame(self.hwnd) {
            eprintln!("WebUI: failed to extend the desktop frame: {error}");
        }

        // SAFETY: The window is live; the reposition only forces the frame to
        // be recalculated so `WM_NCCALCSIZE` runs with the new styles.
        unsafe {
            if let Err(error) = WindowsAndMessaging::SetWindowPos(
                self.hwnd,
                None,
                0,
                0,
                0,
                0,
                WindowsAndMessaging::SWP_NOMOVE
                    | WindowsAndMessaging::SWP_NOSIZE
                    | WindowsAndMessaging::SWP_NOZORDER
                    | WindowsAndMessaging::SWP_FRAMECHANGED,
            ) {
                eprintln!("WebUI: failed to refresh the desktop frame: {error}");
            }
        }
    }

    /// Apply initial placement without making the window visible.
    fn apply_initial_placement(&self, window: &WindowOptions, saved: Option<&WindowState>) {
        if saved.is_none() && window.center && !window.maximized {
            center_window(self.hwnd);
        }
        if window.always_on_top {
            // SAFETY: The window is live and only its z-order changes.
            unsafe {
                let _ = WindowsAndMessaging::SetWindowPos(
                    self.hwnd,
                    Some(WindowsAndMessaging::HWND_TOPMOST),
                    0,
                    0,
                    0,
                    0,
                    WindowsAndMessaging::SWP_NOMOVE | WindowsAndMessaging::SWP_NOSIZE,
                );
            }
        }
    }
}

impl Drop for FrameWindow {
    fn drop(&mut self) {
        // SAFETY: This owner is dropped on the creating thread before runtime
        // shutdown, including when setup fails before the window is shown.
        unsafe {
            if WindowsAndMessaging::IsWindow(Some(self.hwnd)).as_bool() {
                if let Err(error) = WindowsAndMessaging::DestroyWindow(self.hwnd) {
                    eprintln!("WebUI: failed to destroy the desktop window: {error}");
                }
            }
        }
    }
}

pub(super) fn extend_frameless_frame(hwnd: HWND) -> windows::core::Result<()> {
    // SAFETY: A one-pixel DWM margin preserves the live frameless HWND's
    // shadow/corners without taking ownership of AppWindow overlay frames.
    unsafe {
        windows::Win32::Graphics::Dwm::DwmExtendFrameIntoClientArea(
            hwnd,
            &windows::Win32::UI::Controls::MARGINS {
                cxLeftWidth: 1,
                cxRightWidth: 1,
                cyTopHeight: 1,
                cyBottomHeight: 1,
            },
        )
    }
}

/// Resolve the creation rectangle from saved state or manifest options.
fn initial_geometry(
    window: &WindowOptions,
    saved: Option<&WindowState>,
) -> Result<(i32, i32, i32, i32)> {
    if let Some(saved) = saved {
        let width = i32::try_from(saved.width).context("saved window width exceeds Win32 range")?;
        let height =
            i32::try_from(saved.height).context("saved window height exceeds Win32 range")?;
        return Ok((saved.x, saved.y, width, height));
    }
    let width = i32::try_from(window.width).context("window width exceeds Win32 range")?;
    let height = i32::try_from(window.height).context("window height exceeds Win32 range")?;
    Ok((
        WindowsAndMessaging::CW_USEDEFAULT,
        WindowsAndMessaging::CW_USEDEFAULT,
        width,
        height,
    ))
}

/// Select the window style bits implied by the manifest options.
pub(super) fn window_style(window: &WindowOptions) -> WindowsAndMessaging::WINDOW_STYLE {
    let mut style = WS_OVERLAPPEDWINDOW;
    if !window.resizable {
        style &= !WS_THICKFRAME;
        style &= !WS_MAXIMIZEBOX;
    }
    // Hide the caption in WM_NCCALCSIZE, not in the native capability bits.
    style
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)]
mod tests {
    use super::*;
    use windows::Win32::Foundation::{LPARAM, RECT, WPARAM};
    use windows::Win32::UI::WindowsAndMessaging::WS_CAPTION;

    std::thread_local! {
        static FRAME_CALCULATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    }

    extern "system" fn count_frame_calculations(
        hwnd: HWND,
        message: u32,
        w_param: WPARAM,
        l_param: LPARAM,
    ) -> windows::Win32::Foundation::LRESULT {
        if message == WindowsAndMessaging::WM_NCCALCSIZE {
            FRAME_CALCULATIONS.set(FRAME_CALCULATIONS.get() + 1);
        }
        super::super::message::window_proc(hwnd, message, w_param, l_param)
    }

    #[test]
    fn showing_a_visible_startup_frame_does_not_recalculate_its_native_caption() {
        let frame = FrameWindow::new(
            &WindowOptions {
                center: false,
                ..Default::default()
            },
            None,
        )
        .unwrap();
        // SAFETY: The test owns the window and replaces its known procedure
        // with a same-thread counter which forwards every message to it.
        unsafe {
            assert_ne!(
                WindowsAndMessaging::SetWindowLongPtrW(
                    frame.hwnd,
                    WindowsAndMessaging::GWLP_WNDPROC,
                    count_frame_calculations as *const () as isize,
                ),
                0
            );
        }
        FRAME_CALCULATIONS.set(0);
        frame.show().unwrap();
        let first = FRAME_CALCULATIONS.get();
        assert!(first > 0);
        frame.show().unwrap();
        assert_eq!(FRAME_CALCULATIONS.get(), first);
    }

    #[test]
    fn a_deferred_startup_close_is_not_undone_by_later_show_calls() {
        let frame = FrameWindow::new(
            &WindowOptions {
                center: false,
                ..Default::default()
            },
            None,
        )
        .unwrap();
        frame.show().unwrap();
        super::super::nonclient::defer_startup_close(frame.hwnd);
        frame.show().unwrap();
        // SAFETY: The fixture owns this live window on the calling thread.
        assert!(!unsafe { WindowsAndMessaging::IsWindowVisible(frame.hwnd) }.as_bool());
        assert!(super::super::nonclient::mark_startup_ready(frame.hwnd));
    }

    struct TestFrame(FrameWindow);

    impl Drop for TestFrame {
        fn drop(&mut self) {
            // SAFETY: The test owns this window and destroys it on its UI thread.
            if let Err(error) = unsafe { WindowsAndMessaging::DestroyWindow(self.0.hwnd) } {
                eprintln!("Failed to destroy test window: {error}");
            }
        }
    }

    fn frame_rectangles(frame: &TestFrame) -> (RECT, RECT) {
        let mut outer = RECT::default();
        let mut client = RECT::default();
        // SAFETY: The test window is live and both rectangles are writable.
        unsafe {
            WindowsAndMessaging::GetWindowRect(frame.0.hwnd, &mut outer).unwrap();
            WindowsAndMessaging::GetClientRect(frame.0.hwnd, &mut client).unwrap();
        }
        (outer, client)
    }

    #[test]
    fn startup_custom_frame_reserves_only_native_resize_borders() {
        {
            let titlebar = TitlebarStyle::None;
            let options = WindowOptions {
                titlebar,
                center: false,
                width: 600,
                height: 400,
                ..WindowOptions::default()
            };
            let frame = TestFrame(FrameWindow::new(&options, None).unwrap());
            let (outer, client) = frame_rectangles(&frame);
            let (border_x, border_y) = if matches!(options.titlebar, TitlebarStyle::None) {
                // SAFETY: These calls only read the test window's DPI and metrics.
                unsafe {
                    let dpi = windows::Win32::UI::HiDpi::GetDpiForWindow(frame.0.hwnd);
                    let metric =
                        |index| windows::Win32::UI::HiDpi::GetSystemMetricsForDpi(index, dpi);
                    let padded = metric(WindowsAndMessaging::SM_CXPADDEDBORDER);
                    (
                        metric(WindowsAndMessaging::SM_CXFRAME) + padded,
                        metric(WindowsAndMessaging::SM_CYFRAME) + padded,
                    )
                }
            } else {
                (0, 0)
            };

            assert_eq!(
                (client.right - client.left, client.bottom - client.top),
                (
                    outer.right - outer.left - 2 * border_x,
                    outer.bottom - outer.top - 2 * border_y
                ),
                "hide the caption without letting WebView2 cover resize borders: {:?}",
                options.titlebar
            );
            // SAFETY: The test window is live; this only reads visibility.
            assert!(!unsafe { WindowsAndMessaging::IsWindowVisible(frame.0.hwnd) }.as_bool());
        }
    }

    #[test]
    fn startup_native_frame_retains_system_chrome() {
        let frame = TestFrame(
            FrameWindow::new(
                &WindowOptions {
                    center: false,
                    ..WindowOptions::default()
                },
                None,
            )
            .unwrap(),
        );
        let (outer, client) = frame_rectangles(&frame);

        assert!(client.bottom - client.top < outer.bottom - outer.top);
    }

    #[test]
    fn finishing_startup_does_not_replace_focus_already_inside_the_window() {
        use windows::Win32::UI::Input::KeyboardAndMouse;
        let frame = TestFrame(
            FrameWindow::new(
                &WindowOptions {
                    center: false,
                    ..WindowOptions::default()
                },
                None,
            )
            .unwrap(),
        );
        frame.0.show().unwrap();
        // SAFETY: The fixture owns the parent and child on this UI thread.
        let child = unsafe {
            WindowsAndMessaging::CreateWindowExW(
                Default::default(),
                w!("BUTTON"),
                None,
                WindowsAndMessaging::WS_CHILD | WindowsAndMessaging::WS_VISIBLE,
                0,
                0,
                40,
                20,
                Some(frame.0.hwnd),
                None,
                None,
                None,
            )
            .unwrap()
        };
        // SAFETY: Both focus operations target this thread's live test windows.
        unsafe {
            let _ = KeyboardAndMouse::SetFocus(Some(child));
            assert_eq!(KeyboardAndMouse::GetFocus(), child);
            frame.0.focus_after_startup();
            assert_eq!(KeyboardAndMouse::GetFocus(), child);
            let _ = KeyboardAndMouse::SetFocus(None);
            frame.0.focus_after_startup();
            assert_eq!(KeyboardAndMouse::GetFocus(), frame.0.hwnd);
        }
    }

    #[test]
    fn startup_custom_frame_handles_both_non_client_geometry_messages() {
        let frame = TestFrame(
            FrameWindow::new(
                &WindowOptions {
                    titlebar: TitlebarStyle::None,
                    resizable: false,
                    center: false,
                    ..WindowOptions::default()
                },
                None,
            )
            .unwrap(),
        );
        let expected = RECT {
            left: 10,
            top: 20,
            right: 610,
            bottom: 420,
        };
        let mut rect = expected;
        let mut params = WindowsAndMessaging::NCCALCSIZE_PARAMS {
            rgrc: [expected; 3],
            ..Default::default()
        };
        // SAFETY: Both messages synchronously borrow the corresponding writable
        // Win32 geometry type. No pointer escapes SendMessageW.
        unsafe {
            WindowsAndMessaging::SendMessageW(
                frame.0.hwnd,
                WindowsAndMessaging::WM_NCCALCSIZE,
                Some(WPARAM(0)),
                Some(LPARAM(std::ptr::from_mut(&mut rect) as isize)),
            );
            WindowsAndMessaging::SendMessageW(
                frame.0.hwnd,
                WindowsAndMessaging::WM_NCCALCSIZE,
                Some(WPARAM(1)),
                Some(LPARAM(std::ptr::from_mut(&mut params) as isize)),
            );
        }
        assert_eq!(rect, expected);
        assert_eq!(params.rgrc[0], expected);
    }

    #[test]
    fn startup_maximized_frame_stays_hidden_until_ready() {
        let saved = WindowState {
            x: 30,
            y: 40,
            width: 900,
            height: 700,
            maximized: true,
        };
        for (maximized, saved) in [(true, None), (false, Some(&saved))] {
            let frame = TestFrame(
                FrameWindow::new(
                    &WindowOptions {
                        titlebar: TitlebarStyle::None,
                        maximized,
                        center: false,
                        ..WindowOptions::default()
                    },
                    saved,
                )
                .unwrap(),
            );

            // SAFETY: The test window is live; these only read native state.
            unsafe {
                assert!(WindowsAndMessaging::IsZoomed(frame.0.hwnd).as_bool());
                assert!(
                    !WindowsAndMessaging::IsWindowVisible(frame.0.hwnd).as_bool(),
                    "restoring maximized geometry must not show an uninitialized window"
                );
            }
            let (_, client) = frame_rectangles(&frame);
            let work_area = super::super::command::monitor_rect(frame.0.hwnd, true).unwrap();
            assert_eq!(
                (client.right - client.left, client.bottom - client.top),
                (
                    work_area.right - work_area.left,
                    work_area.bottom - work_area.top
                ),
                "maximized custom content must fill, but not exceed, the monitor work area"
            );
            frame.0.show().unwrap();
            // SAFETY: The test owns the live window; these calls only read state.
            unsafe {
                assert!(WindowsAndMessaging::IsWindowVisible(frame.0.hwnd).as_bool());
                assert!(WindowsAndMessaging::IsZoomed(frame.0.hwnd).as_bool());
            }
            assert_eq!(frame_rectangles(&frame).1, client);
        }
    }

    #[test]
    fn frameless_style_preserves_native_frame_capabilities() {
        let style = window_style(&WindowOptions {
            titlebar: TitlebarStyle::None,
            ..WindowOptions::default()
        });

        assert_eq!(style & WS_CAPTION, WS_CAPTION);
        assert_eq!(style & WS_THICKFRAME, WS_THICKFRAME);
    }

    #[test]
    fn non_resizable_style_drops_resize_affordances() {
        let style = window_style(&WindowOptions {
            resizable: false,
            ..WindowOptions::default()
        });

        assert_eq!(style & WS_THICKFRAME, WindowsAndMessaging::WINDOW_STYLE(0));
        assert_eq!(style & WS_MAXIMIZEBOX, WindowsAndMessaging::WINDOW_STYLE(0));
        assert_eq!(style & WS_CAPTION, WS_CAPTION);
    }

    #[test]
    fn saved_geometry_overrides_manifest_size() {
        let saved = WindowState {
            x: 30,
            y: 40,
            width: 900,
            height: 700,
            maximized: false,
        };

        let geometry = initial_geometry(&WindowOptions::default(), Some(&saved)).unwrap();

        assert_eq!(geometry, (30, 40, 900, 700));
    }

    #[test]
    fn default_geometry_uses_system_placement() {
        let geometry = initial_geometry(&WindowOptions::default(), None).unwrap();

        assert_eq!(
            geometry,
            (
                WindowsAndMessaging::CW_USEDEFAULT,
                WindowsAndMessaging::CW_USEDEFAULT,
                1200,
                800
            )
        );
    }
}