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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Windows desktop backend built on Win32 and the WebView2 runtime.
//!
//! The backend keeps platform code in one place behind the cross-platform
//! [`crate::DesktopFrame`] contract:
//!
//! * [`create`] builds the native window, styles, and initial geometry.
//! * [`message`] owns the window procedure, custom frame, and lifecycle events.
//! * [`command`] executes queued window commands on the UI thread.
//! * [`state`] stores per-window state and persisted geometry.
//! * [`webview`] configures WebView2, navigation policy, and script bridges.
//! * [`bridge`] receives window controls and typed application IPC.
//! * [`protocol`] serves app resources through native request interception.

mod app_sdk;
mod bridge;
#[cfg(feature = "native-capture")]
pub(crate) mod capture;
#[cfg(feature = "native-clipboard")]
pub(crate) mod clipboard;
mod command;
mod create;
#[cfg(feature = "native-dialogs")]
pub(crate) mod dialogs;
mod event;
#[cfg(feature = "application-ipc")]
mod ipc;
#[cfg(feature = "application-ipc")]
mod ipc_body;
#[cfg(feature = "application-ipc")]
mod ipc_control;
#[cfg(feature = "application-ipc")]
mod ipc_deadline;
#[cfg(feature = "application-ipc")]
mod ipc_http;
#[cfg(feature = "application-ipc")]
mod ipc_policy;
#[cfg(feature = "local-server")]
mod local_controls;
mod message;
mod native_frame;
mod nonclient;
#[cfg(feature = "native-picker")]
pub(crate) mod picker;
mod protocol;
mod request;
mod startup;
mod state;
mod wakeup;
mod webview;

use std::cell::Cell;
#[cfg(feature = "application-ipc")]
use std::rc::Rc;
#[cfg(feature = "local-server")]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

use crate::{DesktopEvent, DesktopRuntime, WindowId, WindowOptions, WindowStateStore};
use anyhow::{Context, Result};
use windows::core::w;
use windows::core::PCWSTR;
use windows::Win32::Foundation::{E_ACCESSDENIED, LPARAM, WPARAM};
use windows::Win32::Graphics::Gdi;
use windows::Win32::System::Com::{CoInitializeEx, CoUninitialize, COINIT_APARTMENTTHREADED};
use windows::Win32::UI::HiDpi;
use windows::Win32::UI::WindowsAndMessaging;

use crate::DesktopFrame;
use create::FrameWindow;
use state::FrameState;

/// Origin served to web content by the resource interceptor.
pub(super) const APP_ORIGIN: &str = "https://app.webui.localhost";
/// WebView2 normalizes HTTP URLs to include the authority's trailing slash.
pub(super) const APP_REQUEST_FILTER: PCWSTR = w!("https://app.webui.localhost/*");
/// Private message used to wake the UI thread for queued commands.
pub(super) const WAKE_MESSAGE: u32 = WindowsAndMessaging::WM_APP + 1;
pub(super) const APP_WAKE_MESSAGE: u32 = WindowsAndMessaging::WM_APP + 3;
/// UI-only owner-loss wake, independent of the bounded window-command queue.
#[cfg(feature = "local-server")]
pub(super) const OWNER_LOST_MESSAGE: u32 = WindowsAndMessaging::WM_APP + 4;
#[cfg(feature = "local-server")]
static NEXT_OWNER_CLOSE_COOKIE: AtomicUsize = AtomicUsize::new(1);

#[cfg(feature = "local-server")]
fn next_owner_close_cookie() -> Result<usize> {
    NEXT_OWNER_CLOSE_COOKIE
        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |next| next.checked_add(1))
        .map_err(|_| anyhow::anyhow!("native window generation exhausted; restart the desktop host before opening another local-server frame"))
}

#[cfg(feature = "local-server")]
pub(super) fn post_owner_lost(
    hwnd: windows::Win32::Foundation::HWND,
    cookie: usize,
) -> std::result::Result<(), crate::HostCloseError> {
    // SAFETY: PostMessageW is thread-safe and never waits for the UI loop.
    // The receiver checks both its window generation and weak lifetime.
    unsafe {
        WindowsAndMessaging::PostMessageW(Some(hwnd), OWNER_LOST_MESSAGE, WPARAM(cookie), LPARAM(0))
    }
    .map_err(|error| crate::HostCloseError::WakeFailed {
        message: error.to_string(),
    })
}
mod tasks;
/// Coalesced, payload-free native IPC completion/control wake.
#[cfg(feature = "application-ipc")]
pub(super) const IPC_WAKE_MESSAGE: u32 = WindowsAndMessaging::WM_APP + 2;
/// Identity of the single window owned by this backend.
pub(super) const WINDOW_ID: WindowId = WindowId::PRIMARY;

/// Run a packaged WebUI desktop app on Windows using WebView2.
///
/// # Errors
///
/// Returns an error if packaged resources cannot be located or WebView2 cannot initialize.
pub fn run_packaged_app() -> Result<()> {
    crate::run_packaged_app().map_err(Into::into)
}

/// Run a prebuilt desktop runtime in a Windows WebView2 window.
///
/// # Errors
///
/// Returns an error if WebView2 cannot initialize.
pub fn run_runtime(runtime: Arc<DesktopRuntime>, window: WindowOptions) -> Result<()> {
    crate::run_runtime(runtime, window).map_err(Into::into)
}

/// Run a desktop frame until the native window closes.
///
/// # Errors
///
/// Returns an error if COM, the native window, or WebView2 cannot initialize.
pub(crate) fn run_frame(frame: DesktopFrame) -> Result<()> {
    run_content(FrameContent::Bundle(frame))
}

#[cfg(feature = "local-server")]
pub(crate) fn run_local_server_frame(frame: crate::LocalServerFrame) -> Result<()> {
    run_content(FrameContent::Local(frame))
}

enum FrameContent {
    Bundle(DesktopFrame),
    #[cfg(feature = "local-server")]
    Local(crate::LocalServerFrame),
}

impl FrameContent {
    fn window(&self) -> &WindowOptions {
        match self {
            Self::Bundle(frame) => &frame.window,
            #[cfg(feature = "local-server")]
            Self::Local(frame) => &frame.window,
        }
    }
    fn app_id(&self) -> Option<&str> {
        match self {
            Self::Bundle(frame) => frame.app_id.as_deref(),
            #[cfg(feature = "local-server")]
            Self::Local(frame) => frame.app_id.as_deref(),
        }
    }
    fn events(&self) -> &crate::EventRegistry {
        match self {
            Self::Bundle(frame) => &frame.events,
            #[cfg(feature = "local-server")]
            Self::Local(frame) => &frame.events,
        }
    }
    fn window_handle(&self) -> &crate::WindowHandle {
        match self {
            Self::Bundle(frame) => &frame.window_handle,
            #[cfg(feature = "local-server")]
            Self::Local(frame) => &frame.window_handle,
        }
    }
    fn background(&self) -> Arc<crate::window::LiveBackground> {
        match self {
            Self::Bundle(frame) => frame.runtime.live_background(),
            #[cfg(feature = "local-server")]
            Self::Local(frame) => Arc::clone(&frame.live_background),
        }
    }
}

fn run_content(frame: FrameContent) -> Result<()> {
    let trace = startup::StartupTrace::begin();
    #[cfg(feature = "local-server")]
    if let FrameContent::Local(local) = &frame {
        local.lifetime().require_active()?;
    }
    #[cfg(feature = "local-server")]
    let owner_close_cookie = match &frame {
        FrameContent::Bundle(_) => None,
        FrameContent::Local(_) => Some(next_owner_close_cookie()?),
    };
    let store = WindowStateStore::for_window(frame.window().remember_state, frame.app_id())?;
    trace.mark("store");
    let _com = initialize_com()?;
    configure_dpi_awareness()?;
    trace.mark("com_dpi");
    let runtime = if native_frame::enabled(frame.window()) {
        None
    } else {
        Some(app_sdk::Runtime::initialize()?)
    };
    trace.mark("app_sdk_runtime");

    let saved = state::load_saved_state(store.as_ref());
    let window_frame = FrameWindow::new(frame.window(), saved.as_ref())?;
    trace.mark("window_created");
    let early_overlay = !frame.window().fullscreen
        && matches!(
            frame.window().titlebar,
            crate::TitlebarStyle::Overlay { .. } | crate::TitlebarStyle::HiddenInset
        );
    if native_frame::enabled(frame.window()) {
        native_frame::prepare_startup_window(window_frame.hwnd, frame.window(), saved.is_some())?;
    }
    if early_overlay {
        if !native_frame::enabled(frame.window()) {
            nonclient::prepare_overlay_startup(window_frame.hwnd)?;
        }
        window_frame.show()?;
        trace.mark("early_overlay_visible");
    }
    let profile = webview::browser_profile(frame.app_id())?;
    trace.mark("environment_started");
    let environment = webview::create_environment(&profile.path).with_context(|| {
        "Failed to initialize WebView2; install the Microsoft Edge WebView2 Runtime or use a Windows image that includes it"
    })?;
    trace.mark("environment_created");
    let native_window = if runtime.is_none() {
        Some(native_frame::WindowFrame::attach(
            None,
            window_frame.hwnd,
            frame.window(),
        )?)
    } else {
        None
    };
    let browser_frame = native_frame::enabled(frame.window())
        .then(|| native_frame::BrowserWindow::new(window_frame.hwnd))
        .transpose()?;
    let content = browser_frame
        .as_ref()
        .map_or(window_frame.hwnd, |browser| browser.hwnd);
    if browser_frame.is_some() {
        native_frame::resize_browser(window_frame.hwnd, content)?;
    }
    let pending_controller = webview::begin_create_controller(&environment, content)?;
    trace.mark("controller_started");
    let app_window = if let Some(native) = native_window {
        native
    } else {
        native_frame::WindowFrame::attach(runtime.as_ref(), window_frame.hwnd, frame.window())?
    };
    if early_overlay && !native_frame::enabled(frame.window()) {
        nonclient::finish_overlay_startup(window_frame.hwnd)?;
    }
    if browser_frame.is_some() {
        native_frame::resize_browser(window_frame.hwnd, content)?;
    }
    trace.mark("app_window_attached");
    window_frame.show()?;
    let controller = pending_controller.finish()?;
    trace.mark("controller_created");
    webview::configure_controller_background(&controller, frame.window().background)?;
    webview::configure_window_effect(window_frame.hwnd, frame.window().effect);
    message::set_controller_bounds(&controller, content)?;
    // SAFETY: The live controller contains only its initial blank document;
    // app navigation still waits for all security and resource handlers.
    unsafe { controller.SetIsVisible(true)? };
    webview::focus_controller_from_frame(window_frame.hwnd, &controller)
        .context("Failed to transfer native keyboard focus into WebView2")?;
    trace.mark("controller_visible");
    // SAFETY: The controller was created successfully, so it owns a WebView2.
    let webview = unsafe { controller.CoreWebView2()? };
    webview::configure_settings(&webview, frame.window().devtools)?;
    trace.mark("webview_configured");
    #[cfg(feature = "native-picker")]
    let picker_services = match &frame {
        FrameContent::Bundle(_) => None,
        FrameContent::Local(local) => Some(local.native_services()?),
    };
    #[cfg(feature = "native-picker")]
    if let Some(services) = &picker_services {
        let cookie = owner_close_cookie.ok_or_else(|| {
            anyhow::anyhow!("local-server picker has no exact owning window generation")
        })?;
        services.attach_picker(window_frame.hwnd.0 as usize, cookie);
    }
    #[cfg(feature = "native-dialogs")]
    let dialog_services = match &frame {
        FrameContent::Bundle(_) => None,
        FrameContent::Local(local) => Some(local.native_services()?),
    };
    #[cfg(feature = "native-dialogs")]
    if let Some(services) = &dialog_services {
        services.attach_dialogs(window_frame.hwnd.0 as usize);
    }
    #[cfg(feature = "local-server")]
    let local_controls = match &frame {
        FrameContent::Local(local)
            if !matches!(frame.window().titlebar, crate::TitlebarStyle::Native) =>
        {
            Some(local_controls::LocalControls::new(
                local.origin().clone(),
                local.lifetime().clone(),
            ))
        }
        _ => None,
    };
    #[cfg(feature = "native-capture")]
    let capture_services = match &frame {
        FrameContent::Bundle(_) => None,
        FrameContent::Local(local) => Some(local.native_services()?),
    };
    #[cfg(feature = "native-capture")]
    let capture_registration = capture_services
        .as_ref()
        .map(|services| capture::install(&services.capture_for_revoke(), window_frame.hwnd))
        .transpose()?;
    #[cfg(feature = "native-clipboard")]
    if let Some(services) = &capture_services {
        services.attach_clipboard(window_frame.hwnd.0 as usize);
    }
    #[cfg(feature = "application-ipc")]
    let ipc = match &frame {
        FrameContent::Bundle(bundle) => Some(ipc::WindowsIpc::new(
            bundle.ipc_bridge(),
            &webview,
            window_frame.hwnd,
        )?),
        #[cfg(feature = "local-server")]
        FrameContent::Local(local) => local
            .ipc_bridge()
            .map(|bridge| {
                ipc::WindowsIpc::new_local(
                    bridge,
                    &webview,
                    window_frame.hwnd,
                    local.origin().clone(),
                    local.lifetime().clone(),
                )
            })
            .transpose()?,
    };
    #[cfg(feature = "application-ipc")]
    let _ipc_shutdown = ipc.as_ref().map(|ipc| ipc::Shutdown(Rc::clone(ipc)));

    let navigation_starting = webview::register_navigation_guard(
        &webview,
        frame.events().clone(),
        webview::NavigationGuardContext {
            #[cfg(feature = "native-capture")]
            capture: capture_services.clone(),
            #[cfg(feature = "local-server")]
            controls: local_controls.clone(),
            #[cfg(feature = "local-server")]
            origin: match &frame {
                FrameContent::Bundle(_) => None,
                FrameContent::Local(local) => Some(local.origin().clone()),
            },
            #[cfg(feature = "local-server")]
            lifetime: match &frame {
                FrameContent::Bundle(_) => None,
                FrameContent::Local(local) => Some(local.lifetime().clone()),
            },
        },
    )?;
    trace.mark("navigation_guard");
    #[cfg(feature = "local-server")]
    let local_navigation = match (&frame, owner_close_cookie) {
        (FrameContent::Bundle(_), _) => None,
        (FrameContent::Local(local), Some(cookie)) => Some(webview::register_local_frame_guards(
            &webview,
            window_frame.hwnd,
            local.lifetime().clone(),
            cookie,
            Arc::clone(&local.frame_policy),
        )?),
        (FrameContent::Local(_), None) => {
            return Err(anyhow::anyhow!(
                "local-server window generation is missing; restart the desktop host"
            ));
        }
    };
    let navigation_completed = webview::register_navigation_completed(
        &webview,
        frame.events().clone(),
        window_frame.hwnd,
        frame.background(),
        webview::CompletionOwner {
            #[cfg(feature = "native-capture")]
            capture: capture_services.clone(),
            #[cfg(feature = "local-server")]
            controls: local_controls.clone(),
            #[cfg(feature = "local-server")]
            lifetime: owner_close_cookie.and_then(|cookie| match &frame {
                FrameContent::Bundle(_) => None,
                FrameContent::Local(local) => Some((local.lifetime().clone(), cookie)),
            }),
        },
    )?;
    trace.mark("navigation_completed");
    if matches!(&frame, FrameContent::Bundle(_)) {
        let metrics = app_window.metrics_script();
        webview::inject_bundle_script(&webview, metrics.as_deref())?;
    }
    trace.mark("bundle_script");
    // Local-server controls are a separate, document-nonce-bound host bridge,
    // never the packaged app's unconditional native command path.
    let controls = matches!(&frame, FrameContent::Bundle(_));
    let needs_message_handler = controls;
    #[cfg(feature = "local-server")]
    let needs_message_handler = needs_message_handler || local_controls.is_some();
    #[cfg(feature = "application-ipc")]
    let needs_message_handler = needs_message_handler || ipc.is_some();
    let web_message_received = if needs_message_handler {
        Some(bridge::register_message_handler(
            &webview,
            window_frame.hwnd,
            controls,
            #[cfg(feature = "local-server")]
            local_controls.clone(),
            #[cfg(feature = "application-ipc")]
            ipc.as_ref().map(Rc::downgrade).unwrap_or_default(),
        )?)
    } else {
        None
    };
    trace.mark("message_handler");
    let application_tasks = tasks::ApplicationTasks::new(window_frame.hwnd);
    let web_resource_requested = match &frame {
        FrameContent::Bundle(bundle) => Some(protocol::register_runtime_handler(
            &environment,
            &webview,
            bundle,
            protocol::RuntimeHandlerOptions {
                tasks: std::rc::Rc::downgrade(&application_tasks),
                trace,
                #[cfg(feature = "application-ipc")]
                ipc: ipc.as_ref().map(Rc::downgrade).unwrap_or_default(),
            },
        )?),
        #[cfg(feature = "local-server")]
        FrameContent::Local(_) => None,
    };
    trace.mark("resource_handler");
    #[cfg(feature = "local-server")]
    let owner_close_registration = match (&frame, owner_close_cookie) {
        (FrameContent::Bundle(_), _) => None,
        (FrameContent::Local(local), Some(cookie)) => {
            let handle = window_frame.hwnd.0 as usize;
            #[cfg(feature = "native-capture")]
            let capture = capture_services
                .as_ref()
                .map(|services| services.capture_for_revoke());
            #[cfg(feature = "native-clipboard")]
            let clipboard = capture_services
                .as_ref()
                .map(|services| services.clipboard_for_revoke());
            #[cfg(feature = "native-dialogs")]
            let dialogs = dialog_services
                .as_ref()
                .map(|services| services.dialogs_for_revoke());
            #[cfg(feature = "native-picker")]
            let picker = picker_services.clone();
            Some(local.lifetime().register_close_fallible(Arc::new(move || {
                #[cfg(feature = "native-capture")]
                if let Some(capture) = &capture {
                    // Retire bytes synchronously on owner revocation, before
                    // the asynchronous close wake and without waking Futures
                    // under HostLifetime's close lock.
                    capture.close();
                }
                #[cfg(feature = "native-clipboard")]
                if let Some(clipboard) = &clipboard {
                    // No future wake under HostLifetime's close lock.
                    clipboard.close_silent();
                }
                #[cfg(feature = "native-dialogs")]
                if let Some(dialogs) = &dialogs {
                    dialogs.close_silent();
                }
                #[cfg(feature = "native-picker")]
                if let Some(picker) = &picker {
                    // Retire synchronously, post cancellation to its own STA;
                    // no arbitrary Future waker runs under the host lock.
                    picker.picker_close_silent();
                }
                let hwnd = windows::Win32::Foundation::HWND(handle as *mut std::ffi::c_void);
                post_owner_lost(hwnd, cookie)
            }))?)
        }
        (FrameContent::Local(_), None) => {
            return Err(anyhow::anyhow!(
                "local-server window generation is missing; restart the desktop host"
            ));
        }
    };
    let state = Box::new(FrameState {
        app_window,
        content,
        application_tasks,
        #[cfg(feature = "application-ipc")]
        ipc: ipc.as_ref().map(Rc::clone),
        controller,
        #[cfg(feature = "native-picker")]
        picker: picker_services,
        #[cfg(feature = "native-dialogs")]
        dialogs: dialog_services
            .as_ref()
            .map(|services| services.dialogs_for_revoke()),
        #[cfg(feature = "native-clipboard")]
        clipboard: capture_services
            .as_ref()
            .map(|services| services.clipboard_for_revoke()),
        #[cfg(feature = "local-server")]
        local_controls,
        #[cfg(feature = "native-capture")]
        capture_registration,
        _navigation_starting: navigation_starting,
        #[cfg(feature = "local-server")]
        _local_navigation: local_navigation,
        #[cfg(feature = "local-server")]
        _owner_close_registration: owner_close_registration,
        #[cfg(feature = "local-server")]
        local_lifetime: match &frame {
            FrameContent::Bundle(_) => None,
            FrameContent::Local(local) => Some(local.lifetime().clone()),
        },
        #[cfg(feature = "local-server")]
        owner_close_cookie,
        _navigation_completed: navigation_completed,
        _web_message_received: web_message_received,
        _web_resource_requested: web_resource_requested,
        events: frame.events().clone(),
        window_handle: frame.window_handle().clone(),
        options: frame.window().clone(),
        webview: webview.clone(),
        store,
        fullscreen: Cell::new(false),
        window_state: Cell::new(state::initial_window_size_state(window_frame.hwnd)),
    });
    state::set_window_state(window_frame.hwnd, Some(state));
    // Installing a wakeup flushes an existing backlog. WebView2 initialization
    // pumps messages, so the native receiver must exist before attachment.
    install_wakeup(window_frame.hwnd)?;
    trace.mark("state_installed");
    #[cfg(feature = "application-ipc")]
    if let Some(ipc) = &ipc {
        let script = if ipc.is_local() {
            #[cfg(feature = "local-server")]
            {
                crate::ipc_assets::LOCAL_NATIVE_BOOTSTRAP_SCRIPT
            }
            #[cfg(not(feature = "local-server"))]
            {
                crate::ipc_assets::NATIVE_BOOTSTRAP_SCRIPT
            }
        } else {
            crate::ipc_assets::NATIVE_BOOTSTRAP_SCRIPT
        };
        ipc.install(script)?;
    }
    #[cfg(feature = "local-server")]
    if let FrameContent::Local(local) = &frame {
        local.lifetime().require_active()?;
    }

    if frame.window().fullscreen {
        state::with_window_state(window_frame.hwnd, |state| {
            command::set_fullscreen(window_frame.hwnd, state, true);
        });
    }

    if nonclient::mark_startup_ready(window_frame.hwnd) {
        // SAFETY: Startup is complete and the deferred close can now run
        // through the normal state-aware destruction path.
        unsafe { WindowsAndMessaging::DestroyWindow(window_frame.hwnd)? };
        let _ = frame.events().dispatch(&DesktopEvent::Exiting);
        return Ok(());
    }
    window_frame.show()?;
    trace.mark("final_show");
    message::refresh_frame(window_frame.hwnd);
    trace.mark("frame_refreshed");
    // SAFETY: `window_frame.hwnd` is a live window owned by this thread.
    unsafe {
        let _ = Gdi::UpdateWindow(window_frame.hwnd);
    }
    window_frame.focus_after_startup();
    message::publish(window_frame.hwnd, &DesktopEvent::Ready);
    trace.mark("ready_published");
    match &frame {
        FrameContent::Bundle(_) => webview::navigate_to_startup_url(&webview)?,
        #[cfg(feature = "local-server")]
        FrameContent::Local(local) => {
            local.lifetime().require_active()?;
            webview::navigate_to_url(&webview, &local.options.url())?;
        }
    }
    trace.mark("navigation_started");
    let message_loop_result = message::message_loop();
    let _ = frame.events().dispatch(&DesktopEvent::Exiting);
    message_loop_result
}

/// Wake the message pump whenever another thread queues a window command.
fn install_wakeup(hwnd: windows::Win32::Foundation::HWND) -> Result<()> {
    let receiver = state::with_window_state_result(hwnd, |state| state.window_handle.clone());
    // `HWND` is a raw pointer, so it is moved into the callback as an integer
    // and rebuilt on use, keeping the closure `Send + Sync` as the API requires.
    let handle = hwnd.0 as usize;
    wakeup::attach(receiver, move || {
        let hwnd = windows::Win32::Foundation::HWND(handle as *mut std::ffi::c_void);
        // SAFETY: `PostMessageW` is thread-safe by design. The window lives for
        // the whole message loop, and a stale handle after shutdown only makes
        // the post fail, which is ignored.
        let _ = unsafe {
            WindowsAndMessaging::PostMessageW(Some(hwnd), WAKE_MESSAGE, WPARAM(0), LPARAM(0))
        };
    })
}

/// COM apartment guard for the UI thread.
struct ComApartment;

impl Drop for ComApartment {
    fn drop(&mut self) {
        // SAFETY: `initialize_com` successfully initialized COM on this thread.
        unsafe { CoUninitialize() };
    }
}

/// Initialize a single-threaded COM apartment for WebView2.
fn initialize_com() -> Result<ComApartment> {
    // SAFETY: Called once at the start of the UI thread before WebView2 COM APIs.
    unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok()? };
    Ok(ComApartment)
}

/// Opt the process into per-monitor DPI awareness.
fn configure_dpi_awareness() -> Result<()> {
    // SAFETY: Process-wide DPI awareness is configured before any window is created.
    match unsafe { HiDpi::SetProcessDpiAwareness(HiDpi::PROCESS_PER_MONITOR_DPI_AWARE) } {
        Ok(()) => Ok(()),
        Err(error) if error.code() == E_ACCESSDENIED => Ok(()),
        Err(error) => Err(error.into()),
    }
}