microsoft-webui-desktop 0.0.30

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

//! WebView2 environment, controller, navigation policy, and script bridges.

use std::path::PathBuf;
use std::sync::{mpsc, Arc};

use crate::window::LiveBackground;
use crate::{
    DesktopEvent, DesktopHostMessage, EventRegistry, EventResponse, Rgba, WindowEffect,
    DRAG_REGION_SCRIPT,
};
use anyhow::{Context, Result};
use webview2_com::Microsoft::Web::WebView2::Win32::{
    CreateCoreWebView2EnvironmentWithOptions, ICoreWebView2, ICoreWebView2Controller,
    ICoreWebView2Controller2, ICoreWebView2Environment, ICoreWebView2EnvironmentOptions,
    ICoreWebView2NavigationCompletedEventHandler, ICoreWebView2NavigationStartingEventHandler,
    ICoreWebView2WebMessageReceivedEventArgs, COREWEBVIEW2_COLOR,
};
use webview2_com::{
    AddScriptToExecuteOnDocumentCreatedCompletedHandler, CoTaskMemPWSTR,
    CoreWebView2EnvironmentOptions, CreateCoreWebView2ControllerCompletedHandler,
    CreateCoreWebView2EnvironmentCompletedHandler, ExecuteScriptCompletedHandler,
    NavigationCompletedEventHandler, NavigationStartingEventHandler,
};
use windows::core::{Error as WindowsError, Interface, Result as WindowsResult, PCWSTR};
use windows::Win32::Foundation::{E_FAIL, HWND};
use windows::Win32::Graphics::Dwm::{
    DwmSetWindowAttribute, DWMSBT_MAINWINDOW, DWMSBT_TRANSIENTWINDOW, DWMWA_SYSTEMBACKDROP_TYPE,
    DWMWA_USE_IMMERSIVE_DARK_MODE,
};

use super::command::execute_host_message;
use super::message::system_dark;
use super::protocol::read_pwstr;
use super::{APP_ORIGIN, WINDOW_ID};

/// Byte size of the 32-bit values passed to `DwmSetWindowAttribute`.
const DWM_ATTRIBUTE_SIZE: u32 = 4;

/// Host bridge exposed to web content.
///
/// `DRAG_REGION_SCRIPT` calls `window.webuiHostPostMessage` with an already
/// serialized JSON string. WebView2 wraps that string once more when it is read
/// back through `WebMessageAsJson`, which [`handle_host_message`] unwraps.
const HOST_BRIDGE_SCRIPT: &str = "(()=>{if(!window.chrome?.webview)return;\
window.webuiHostPostMessage=m=>window.chrome.webview.postMessage(String(m));})();";

/// Create the shared WebView2 environment backed by a per-app data folder.
pub(super) fn create_environment(
    user_data_folder: &std::path::Path,
) -> Result<ICoreWebView2Environment> {
    let user_data_folder = user_data_folder.to_string_lossy();
    let user_data_folder = CoTaskMemPWSTR::from(user_data_folder.as_ref());
    let options = webview_environment_options();
    let (tx, rx) = mpsc::channel();
    CreateCoreWebView2EnvironmentCompletedHandler::wait_for_async_operation(
        Box::new(move |handler| {
            // SAFETY: The folder buffer and options outlive this call, and the
            // handler is owned by the WebView2 loader for the async operation.
            unsafe {
                CreateCoreWebView2EnvironmentWithOptions(
                    PCWSTR::null(),
                    *user_data_folder.as_ref().as_pcwstr(),
                    &options,
                    &handler,
                )
                .map_err(webview2_com::Error::WindowsError)
            }
        }),
        Box::new(
            move |error_code, environment: Option<ICoreWebView2Environment>| {
                error_code?;
                tx.send(environment.ok_or_else(|| WindowsError::from(E_FAIL)))
                    .map_err(|_| WindowsError::from(E_FAIL))?;
                Ok(())
            },
        ),
    )?;
    rx.recv()
        .map_err(|_| anyhow::anyhow!("WebView2 environment creation was cancelled"))?
        .map_err(Into::into)
}

/// Resolve the first URL loaded into the window.
fn startup_url() -> String {
    let path = std::env::var("WEBUI_DESKTOP_START_PATH").unwrap_or_else(|_| "/".to_string());
    startup_url_for_path(&path)
}

/// Build an app-origin URL for the supplied path.
fn startup_url_for_path(path: &str) -> String {
    let path = if path.starts_with('/') {
        path.to_string()
    } else {
        format!("/{path}")
    };
    let mut url = String::with_capacity(APP_ORIGIN.len() + path.len());
    url.push_str(APP_ORIGIN);
    url.push_str(&path);
    url
}

/// Default WebView2 environment options.
fn webview_environment_options() -> ICoreWebView2EnvironmentOptions {
    let options = CoreWebView2EnvironmentOptions::default();
    options.into()
}

/// Locate (and create) the per-app WebView2 user data folder.
pub(super) fn browser_profile(
    app_id: Option<&str>,
) -> Result<crate::browser_profile::BrowserProfile> {
    let base = std::env::var_os("LOCALAPPDATA")
        .map(PathBuf::from)
        .unwrap_or_else(std::env::temp_dir);
    let dir = base.join("Microsoft").join("WebUI").join("Desktop");
    crate::browser_profile::BrowserProfile::create(&dir, app_id).with_context(|| {
        format!(
            "Failed to create WebView2 user data folder {}",
            dir.display()
        )
    })
}

/// Create the WebView2 controller hosted inside the native window.
pub(super) fn create_controller(
    environment: &ICoreWebView2Environment,
    hwnd: HWND,
) -> Result<ICoreWebView2Controller> {
    let (tx, rx) = mpsc::channel();
    let environment = environment.clone();
    CreateCoreWebView2ControllerCompletedHandler::wait_for_async_operation(
        Box::new(move |handler| {
            // SAFETY: `hwnd` is a live window owned by this thread and the
            // environment reference stays alive for the async operation.
            unsafe {
                environment
                    .CreateCoreWebView2Controller(hwnd, &handler)
                    .map_err(webview2_com::Error::WindowsError)
            }
        }),
        Box::new(
            move |error_code, controller: Option<ICoreWebView2Controller>| {
                error_code?;
                tx.send(controller.ok_or_else(|| WindowsError::from(E_FAIL)))
                    .map_err(|_| WindowsError::from(E_FAIL))?;
                Ok(())
            },
        ),
    )?;
    rx.recv()
        .map_err(|_| anyhow::anyhow!("WebView2 controller creation was cancelled"))?
        .map_err(Into::into)
}

/// Apply the developer-tools policy to the WebView2 settings.
pub(super) fn configure_settings(webview: &ICoreWebView2, devtools: bool) -> Result<()> {
    // SAFETY: `webview` is a live COM interface owned by the caller.
    unsafe {
        let settings = webview.Settings()?;
        settings.SetAreDevToolsEnabled(devtools)?;
        settings.SetAreDefaultContextMenusEnabled(devtools)?;
    }
    Ok(())
}

/// Route navigations through the app event registry while keeping the
/// app-origin allowlist as the final, non-overridable authority.
pub(super) fn register_navigation_guard(
    webview: &ICoreWebView2,
    events: EventRegistry,
) -> Result<ICoreWebView2NavigationStartingEventHandler> {
    let webview_for_events = webview.clone();
    let handler = NavigationStartingEventHandler::create(Box::new(move |_sender, args| {
        if let Some(args) = args {
            // SAFETY: WebView2 passes a live args interface for the callback's
            // duration; the URL is copied out before the callback returns.
            let uri = read_pwstr(|out| unsafe { args.Uri(out) })?;
            let event = DesktopEvent::NavigationRequested {
                window_id: WINDOW_ID,
                url: uri.clone(),
            };
            let prevented = events.dispatch(&event) == EventResponse::PreventDefault;
            mirror_event(&webview_for_events, &event);
            if prevented || !is_allowed_navigation_url(&uri) {
                // SAFETY: Same live args interface as above.
                unsafe { args.SetCancel(true)? };
            }
        }
        Ok(())
    }));
    let mut token = 0_i64;
    // SAFETY: `webview` is live and the handler is kept alive by the caller,
    // which stores it in the window state for the lifetime of the window.
    unsafe { webview.add_NavigationStarting(&handler, &mut token)? };
    Ok(handler)
}

/// Apply the requested backdrop effect, degrading silently on older Windows.
///
/// `Vibrancy` resolves to acrylic, the closest Windows equivalent, matching the
/// [`WindowEffect`] contract's "or closest equivalent" wording. `Tabbed` never
/// reaches here: it is not in the Windows `supported_effects` list, so
/// `validate_frame_capabilities` rejects it at startup.
pub(super) fn configure_window_effect(hwnd: HWND, effect: WindowEffect) {
    let backdrop = match effect {
        WindowEffect::Acrylic | WindowEffect::Vibrancy => DWMSBT_TRANSIENTWINDOW.0,
        WindowEffect::Mica => DWMSBT_MAINWINDOW.0,
        WindowEffect::None | WindowEffect::Tabbed => return,
    };
    // SAFETY: `hwnd` is a live top-level window and the pointer refers to an
    // initialized `i32` whose length matches `DWM_ATTRIBUTE_SIZE`. DWM reports
    // an error on Windows versions without backdrop support, which is ignored
    // so the window degrades to an opaque frame instead of failing to start.
    let _ = unsafe {
        DwmSetWindowAttribute(
            hwnd,
            DWMWA_SYSTEMBACKDROP_TYPE,
            std::ptr::from_ref(&backdrop).cast(),
            DWM_ATTRIBUTE_SIZE,
        )
    };
    let dark = i32::from(system_dark());
    // SAFETY: Same live window; the pointer refers to an initialized `i32`
    // holding a `BOOL`-shaped value of the declared length.
    let _ = unsafe {
        DwmSetWindowAttribute(
            hwnd,
            DWMWA_USE_IMMERSIVE_DARK_MODE,
            std::ptr::from_ref(&dark).cast(),
            DWM_ATTRIBUTE_SIZE,
        )
    };
}

/// Paint the WebView2 surface with the manifest background so the window does
/// not flash white before the first frame is rendered.
pub(super) fn configure_controller_background(
    controller: &ICoreWebView2Controller,
    background: Option<Rgba>,
) -> Result<()> {
    let Some(color) = background else {
        return Ok(());
    };
    // `ICoreWebView2Controller2` is unavailable on very old runtimes; a failed
    // cast simply leaves the default background in place.
    let Ok(controller) = controller.cast::<ICoreWebView2Controller2>() else {
        return Ok(());
    };
    let color = COREWEBVIEW2_COLOR {
        A: color.a,
        R: color.r,
        G: color.g,
        B: color.b,
    };
    // SAFETY: The controller is a live COM interface and `color` is passed by
    // value as an initialized plain-old-data struct.
    unsafe {
        controller.SetDefaultBackgroundColor(color)?;
    }
    Ok(())
}

pub(super) fn update_background(
    controller: &ICoreWebView2Controller,
    webview: &ICoreWebView2,
    color: Rgba,
) -> Result<()> {
    let controller = controller
        .cast::<ICoreWebView2Controller2>()
        .context("live background updates require a newer WebView2 Runtime; update WebView2")?;
    let native = COREWEBVIEW2_COLOR {
        A: color.a,
        R: color.r,
        G: color.g,
        B: color.b,
    };
    // SAFETY: The UI thread owns the controller and the color is initialized POD.
    unsafe { controller.SetDefaultBackgroundColor(native)? };

    update_document_background(webview, color)
}

pub(super) fn update_document_background(webview: &ICoreWebView2, color: Rgba) -> Result<()> {
    let script = CoTaskMemPWSTR::from(crate::window::live_background_script(color).as_str());
    let completion = ExecuteScriptCompletedHandler::create(Box::new(|result, _| {
        if let Err(error) = result {
            eprintln!("WebUI: failed to update the current document background: {error}");
        }
        Ok(())
    }));
    // SAFETY: The live WebView2 interface retains the completion callback;
    // the script buffer stays valid for the synchronous call that queues it.
    unsafe { webview.ExecuteScript(*script.as_ref().as_pcwstr(), &completion)? };
    Ok(())
}

/// Install the host bridge and drag-region helper script on every document.
pub(super) fn inject_drag_script(webview: &ICoreWebView2) -> Result<()> {
    add_document_script(webview, HOST_BRIDGE_SCRIPT)?;
    add_document_script(webview, DRAG_REGION_SCRIPT)
}

/// Register a script that runs before any page script on every document.
pub(super) fn add_document_script(webview: &ICoreWebView2, source: &str) -> Result<()> {
    let webview = webview.clone();
    let script = CoTaskMemPWSTR::from(source);
    AddScriptToExecuteOnDocumentCreatedCompletedHandler::wait_for_async_operation(
        Box::new(move |handler| {
            // SAFETY: `webview` is live and the script buffer outlives the call.
            unsafe {
                webview
                    .AddScriptToExecuteOnDocumentCreated(*script.as_ref().as_pcwstr(), &handler)
                    .map_err(webview2_com::Error::WindowsError)
            }
        }),
        Box::new(|result, _| {
            result?;
            Ok(())
        }),
    )?;
    Ok(())
}

/// Mirror a native event into web content as a DOM event.
pub(super) fn mirror_event(webview: &ICoreWebView2, event: &DesktopEvent) {
    let Ok(script) = event.to_javascript() else {
        return;
    };
    let script = CoTaskMemPWSTR::from(script.as_str());
    let handler = ExecuteScriptCompletedHandler::create(Box::new(|_result, _| Ok(())));
    // SAFETY: `webview` is a live COM interface and the script buffer stays
    // alive for the duration of this call. The completion handler is reference
    // counted by WebView2, so it remains valid until the script finishes.
    let _ = unsafe { webview.ExecuteScript(*script.as_ref().as_pcwstr(), &handler) };
}

/// Handle a window-control message posted by web content.
///
/// Returns `true` when the message was a host command.
pub(super) fn handle_host_message(
    hwnd: HWND,
    args: &ICoreWebView2WebMessageReceivedEventArgs,
) -> WindowsResult<bool> {
    // SAFETY: WebView2 passes a live args interface for the callback's
    // duration; the JSON is copied out before the callback returns.
    let raw = read_pwstr(|out| unsafe { args.WebMessageAsJson(out) })?;
    let Some(message) = decode_host_message(&raw) else {
        return Ok(false);
    };
    // Host commands arrive on the UI thread, so they run directly instead of
    // being queued through the command channel.
    execute_host_message(hwnd, message);
    Ok(true)
}

/// Decode a `WebMessageAsJson` payload into a host command.
///
/// Host commands are posted as strings, so WebView2 reports them as a JSON
/// string wrapping the message's own JSON text. Typed IPC records are objects
/// and fail the first decode.
fn decode_host_message(raw: &str) -> Option<DesktopHostMessage> {
    let payload = serde_json::from_str::<String>(raw).ok()?;
    DesktopHostMessage::from_json(&payload).ok()
}

/// Report completed navigations to app handlers and web content.
pub(super) fn register_navigation_completed(
    webview: &ICoreWebView2,
    events: EventRegistry,
    hwnd: HWND,
    live_background: Arc<LiveBackground>,
) -> Result<ICoreWebView2NavigationCompletedEventHandler> {
    let webview_for_uri = webview.clone();
    let handler = NavigationCompletedEventHandler::create(Box::new(move |_sender, _args| {
        super::state::with_window_state(hwnd, |state| {
            if let Err(error) = state.app_window.publish_metrics(&state.webview) {
                eprintln!("WebUI: failed to publish native titlebar measurements: {error}");
            }
        });
        // SAFETY: The cloned interface is live for as long as the handler is
        // registered, and the source URL is copied out immediately.
        let url = read_pwstr(|out| unsafe { webview_for_uri.Source(out) })?;
        let event = DesktopEvent::NavigationCompleted {
            window_id: WINDOW_ID,
            url,
        };
        let _ = events.dispatch(&event);
        mirror_event(&webview_for_uri, &event);
        if let Some(color) = live_background.current() {
            if let Err(error) = update_document_background(&webview_for_uri, color) {
                eprintln!("WebUI: failed to restore document background after navigation: {error}");
            }
        }
        Ok(())
    }));
    let mut token = 0_i64;
    // SAFETY: `webview` is live and the handler is kept alive by the caller.
    unsafe { webview.add_NavigationCompleted(&handler, &mut token)? };
    Ok(handler)
}

/// Report whether a URL belongs to the app origin allowlist.
/// Delegate to the shared cross-backend navigation policy.
fn is_allowed_navigation_url(url: &str) -> bool {
    crate::is_allowed_navigation_url(url, APP_ORIGIN)
}

/// Navigate the window to its configured startup URL.
///
/// Source and packaged content must both use WebResourceRequested. A virtual
/// host folder mapping bypasses that event, including authenticated IPC routes
/// and dynamic app routes; packaged assets are already served by the runtime.
pub(super) fn navigate_to_startup_url(webview: &ICoreWebView2) -> Result<()> {
    let url = startup_url();
    let url = CoTaskMemPWSTR::from(url.as_str());
    // SAFETY: `webview` is live and the URL buffer outlives this call.
    unsafe { webview.Navigate(*url.as_ref().as_pcwstr())? };
    Ok(())
}

#[cfg(test)]
#[allow(clippy::disallowed_methods)]
mod tests {
    use super::*;

    #[test]
    fn startup_url_normalizes_paths() {
        assert_eq!(
            startup_url_for_path("/contacts"),
            "https://app.webui.localhost/contacts"
        );
        assert_eq!(
            startup_url_for_path("contacts"),
            "https://app.webui.localhost/contacts"
        );
    }

    #[test]
    fn navigation_allowlist_accepts_only_the_app_origin() {
        assert!(is_allowed_navigation_url("about:blank"));
        assert!(is_allowed_navigation_url("https://app.webui.localhost"));
        assert!(is_allowed_navigation_url(
            "https://app.webui.localhost/contacts?view=all"
        ));
        assert!(!is_allowed_navigation_url("https://example.com"));
        assert!(!is_allowed_navigation_url(
            "https://app.webui.localhost.evil.com/"
        ));
    }

    #[test]
    fn host_messages_decode_through_the_webview_json_wrapper() {
        // `webuiHostPostMessage` posts the already-serialized JSON text, which
        // WebView2 reports wrapped in one more layer of JSON string quoting.
        assert_eq!(
            decode_host_message("\"\\\"start-drag\\\"\""),
            Some(DesktopHostMessage::StartDrag)
        );
        assert_eq!(
            decode_host_message("\"\\\"toggle-maximize\\\"\""),
            Some(DesktopHostMessage::ToggleMaximize)
        );
        // Typed application IPC must not be decoded as a window control.
        assert_eq!(decode_host_message("{\"kind\":\"hello\"}"), None);
        assert_eq!(decode_host_message("\"\\\"nope\\\"\""), None);
    }

    #[test]
    fn host_bridge_script_defines_the_documented_global() {
        assert!(HOST_BRIDGE_SCRIPT.contains("window.webuiHostPostMessage"));
        assert!(DRAG_REGION_SCRIPT.contains("window.webuiHostPostMessage"));
    }
}