microsoft-webui-desktop 3.0.2

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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;

use crate::{
    DesktopEvent, DesktopHostMessage, DesktopRuntime, DisplayBounds, EventResponse, Rgba,
    TitlebarStyle, WindowCommand, WindowEffect, WindowHandle, WindowId, WindowState,
    WindowStateStore, DRAG_REGION_SCRIPT,
};
use anyhow::Result;
use gtk4::{gdk, gio, glib, prelude::*, Application, ApplicationWindow, HeaderBar};
use webkit6::{
    prelude::*, LoadEvent, PolicyDecisionType, UserContentInjectedFrames, UserContentManager,
    UserScript, UserScriptInjectionTime, WebContext, WebView,
};

use super::protocol::{handle_scheme_request, startup_url};
use crate::DesktopFrame;

const WINDOW_ID: WindowId = WindowId::PRIMARY;
const SCRIPT_HANDLER: &str = "webuiHost";

/// Host bridge exposed to web content.
///
/// WebKitGTK exposes a registered handler as
/// `window.webkit.messageHandlers.<name>`, so [`DRAG_REGION_SCRIPT`] cannot
/// reach it until this alias is defined. Without the alias every drag,
/// minimize, maximize, and close message from page JavaScript is silently
/// dropped.
const HOST_BRIDGE_SCRIPT: &str = "(()=>{if(!window.webkit?.messageHandlers?.webuiHost)return;\
window.webuiHostPostMessage=m=>window.webkit.messageHandlers.webuiHost.postMessage(String(m));})();";

/// Run a packaged WebUI desktop app on Linux using GTK4 and WebKitGTK 6.
///
/// # Errors
///
/// Returns an error when packaged resources cannot be located or GTK cannot run.
pub fn run_packaged_app() -> Result<()> {
    crate::run_packaged_app().map_err(Into::into)
}

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

pub(crate) fn run_frame(frame: DesktopFrame) -> Result<()> {
    let state_store =
        WindowStateStore::for_window(frame.window.remember_state, frame.app_id.as_deref())?;
    let application = match frame
        .app_id
        .as_deref()
        .filter(|id| gio::Application::id_is_valid(id))
    {
        Some(id) => Application::builder().application_id(id),
        // An absent/non-D-Bus identity must not make unrelated apps share a
        // fixed GApplication id. Persistence still uses the explicit frame id.
        None => Application::builder().flags(gio::ApplicationFlags::NON_UNIQUE),
    };
    let frame = Rc::new(frame);
    let app = application.build();
    #[cfg(feature = "application-ipc")]
    let ipc_owner = Rc::new(RefCell::new(None));
    #[cfg(feature = "application-ipc")]
    let ipc_for_activation = Rc::clone(&ipc_owner);
    let startup_error = Rc::new(RefCell::new(None));
    let error_for_activation = Rc::clone(&startup_error);
    let activation_frame = Rc::clone(&frame);
    let activation = app.connect_activate(move |app| {
        if let Err(error) = build_window(
            app,
            &activation_frame,
            state_store.clone(),
            #[cfg(feature = "application-ipc")]
            &ipc_for_activation,
        ) {
            *error_for_activation.borrow_mut() = Some(error);
            app.quit();
        }
    });
    let exit = run_application(&app);
    // Disconnect before dropping the session owner, even if GTK retains the app.
    app.disconnect(activation);
    #[cfg(feature = "application-ipc")]
    {
        let ipc = ipc_owner.borrow_mut().take();
        if let Some(ipc) = ipc {
            ipc.close();
        }
    }
    let context = COMMAND_CONTEXT.with(|slot| slot.borrow_mut().take());
    drop(context);
    let _ = frame.events.dispatch(&DesktopEvent::Exiting);
    if let Some(error) = startup_error.borrow_mut().take() {
        return Err(error);
    }
    if exit != glib::ExitCode::SUCCESS {
        anyhow::bail!("GTK application exited with {exit:?}; check the native startup diagnostics");
    }
    Ok(())
}

pub(super) fn run_application(app: &impl IsA<gio::Application>) -> glib::ExitCode {
    // The embedding host has already parsed its arguments. Passing them to
    // GApplication makes positional arguments look like files to open.
    app.run_with_args::<&str>(&[])
}

fn build_window(
    app: &Application,
    frame: &DesktopFrame,
    state_store: Option<WindowStateStore>,
    #[cfg(feature = "application-ipc")] ipc_owner: &Rc<RefCell<Option<Rc<super::ipc::GtkIpc>>>>,
) -> Result<()> {
    #[cfg(feature = "application-ipc")]
    if ipc_owner.borrow().is_some() {
        return Ok(());
    }
    let context = WebContext::new();
    let runtime = Arc::clone(&frame.runtime);
    let executor = Arc::clone(&frame.executor);
    #[cfg(feature = "application-ipc")]
    let ipc_enabled = frame.ipc_bridge().is_enabled();
    #[cfg(feature = "application-ipc")]
    let ipc_for_scheme = Rc::downgrade(ipc_owner);
    context.register_uri_scheme("webui", move |request| {
        #[cfg(feature = "application-ipc")]
        {
            let ipc = ipc_for_scheme
                .upgrade()
                .and_then(|slot| slot.borrow().clone());
            let handled = match ipc {
                Some(ipc) => super::ipc_scheme::handle(&ipc, request),
                None if ipc_enabled => super::ipc_scheme::reject_unavailable(request),
                None => false,
            };
            if handled {
                return;
            }
        }
        handle_scheme_request(request, &runtime, &executor);
    });

    let manager = UserContentManager::new();
    let mut source = String::with_capacity(HOST_BRIDGE_SCRIPT.len() + DRAG_REGION_SCRIPT.len());
    source.push_str(HOST_BRIDGE_SCRIPT);
    source.push_str(DRAG_REGION_SCRIPT);
    // TopFrame keeps the `webuiHostPostMessage` convenience alias out of
    // embedded iframes. This is a partial mitigation, not a structural one:
    // see the SECURITY note on `connect_message_handler` below for why
    // WebKitGTK cannot fully close this off the way macOS and Windows do.
    let script = UserScript::new(
        &source,
        UserContentInjectedFrames::TopFrame,
        UserScriptInjectionTime::Start,
        &[],
        &[],
    );
    manager.add_script(&script);
    let _ = manager.register_script_message_handler(SCRIPT_HANDLER, None);

    let webview = WebView::builder()
        .web_context(&context)
        .user_content_manager(&manager)
        .build();
    #[cfg(feature = "application-ipc")]
    let ipc = if frame.ipc_bridge().is_enabled() {
        Some(super::ipc::GtkIpc::install(
            frame.ipc_bridge(),
            &webview,
            &manager,
        )?)
    } else {
        None
    };
    #[cfg(feature = "application-ipc")]
    {
        *ipc_owner.borrow_mut() = ipc.clone();
    }
    if let Some(color) = frame.window.background {
        webview.set_background_color(&to_gdk_rgba(color));
    } else if frame.window.effect != WindowEffect::None {
        webview.set_background_color(&to_gdk_rgba(Rgba {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
        }));
    }

    let window = ApplicationWindow::builder()
        .application(app)
        .title(&frame.window.title)
        .default_width(safe_dimension(frame.window.width, 1200))
        .default_height(safe_dimension(frame.window.height, 800))
        .resizable(frame.window.resizable)
        .build();
    configure_constraints(&window, &frame.window);
    configure_titlebar(&window, &webview, &frame.window.titlebar);
    if matches!(frame.window.titlebar, TitlebarStyle::Native) {
        window.set_child(Some(&webview));
    }

    restore_state(&window, state_store.as_ref());
    install_events(&window, &webview, &manager, frame, state_store);
    #[cfg(feature = "application-ipc")]
    if let Some(ipc) = ipc {
        let weak = Rc::downgrade(&ipc);
        // GTK stops this signal at the earlier handler if the application
        // prevents closing. Only an accepted close reaches this callback.
        window.connect_close_request(move |_| {
            if let Some(ipc) = weak.upgrade() {
                ipc.close();
            }
            glib::Propagation::Proceed
        });
        let weak = Rc::downgrade(&ipc);
        window.connect_destroy(move |_| {
            if let Some(ipc) = weak.upgrade() {
                ipc.close();
            }
        });
    }
    install_wakeup(&window, &webview, frame);

    if frame.window.maximized {
        window.maximize();
    }
    if frame.window.fullscreen {
        window.fullscreen();
    }
    if frame.window.always_on_top {
        eprintln!("WebUI: always_on_top is unavailable on Wayland and best-effort on X11");
    }
    if frame.window.center {
        eprintln!("WebUI: centering is compositor-controlled on Wayland");
    }
    report_effect_limit(frame.window.effect);
    window.present();
    webview.load_uri(&startup_url());
    let ready = DesktopEvent::Ready;
    dispatch_event(&frame.events, &webview, &ready);
    Ok(())
}

pub(super) fn configure_constraints(window: &ApplicationWindow, options: &crate::WindowOptions) {
    let min_width = options
        .min_width
        .map_or(-1, |value| safe_dimension(value, -1));
    let min_height = options
        .min_height
        .map_or(-1, |value| safe_dimension(value, -1));
    if min_width >= 0 || min_height >= 0 {
        window.set_size_request(min_width, min_height);
    }
    if options.max_width.is_some() || options.max_height.is_some() {
        eprintln!(
            "WebUI: GTK4 has no portable hard maximum window size; max dimensions are ignored"
        );
    }
}

fn configure_titlebar(window: &ApplicationWindow, webview: &WebView, style: &TitlebarStyle) {
    match style {
        TitlebarStyle::Native => {}
        TitlebarStyle::HiddenInset | TitlebarStyle::Overlay { .. } => {
            window.set_decorated(false);
            let header = HeaderBar::new();
            header.set_show_title_buttons(true);
            if let TitlebarStyle::Overlay { height } = style {
                header.set_size_request(-1, safe_dimension(*height, 28));
            }
            window.set_titlebar(Some(&header));
            window.set_child(Some(webview));
        }
        TitlebarStyle::None => {
            window.set_decorated(false);
            window.set_child(Some(webview));
        }
    }
}

/// UI-thread handles used to run queued window commands.
///
/// `WindowHandle::set_wakeup` requires a `Send + Sync` callback, but GTK
/// objects are neither. The handles therefore stay in thread-local storage
/// owned by the UI thread, and the wakeup callback captures nothing but a
/// request to visit it there.
#[derive(Clone)]
struct CommandContext {
    window: ApplicationWindow,
    webview: WebView,
    handle: WindowHandle,
    events: crate::EventRegistry,
}

thread_local! {
    static COMMAND_CONTEXT: RefCell<Option<CommandContext>> = const { RefCell::new(None) };
}

fn install_wakeup(window: &ApplicationWindow, webview: &WebView, frame: &DesktopFrame) {
    COMMAND_CONTEXT.with(|slot| {
        *slot.borrow_mut() = Some(CommandContext {
            window: window.clone(),
            webview: webview.clone(),
            handle: frame.window_handle.clone(),
            events: frame.events.clone(),
        });
    });
    frame.window_handle.set_wakeup(|| {
        // Captures nothing, so it stays `Send + Sync`. `idle_add_once` hops to
        // the default main context, which the UI thread owns, so the
        // thread-local context below is always the one installed above.
        glib::idle_add_once(|| {
            let context = COMMAND_CONTEXT.with(|slot| slot.borrow().clone());
            if let Some(context) = context {
                execute_commands(
                    &context.window,
                    &context.webview,
                    &context.handle,
                    &context.events,
                );
            }
        });
    });
}

fn execute_commands(
    window: &ApplicationWindow,
    webview: &WebView,
    handle: &crate::WindowHandle,
    events: &crate::EventRegistry,
) {
    for command in handle.drain_commands() {
        match command {
            WindowCommand::SetTitle(title) => window.set_title(Some(&title)),
            WindowCommand::SetBackground(color) => {
                webview.set_background_color(&to_gdk_rgba(color));
                update_document_background(webview, color);
            }
            WindowCommand::SetSize { width, height } => {
                window.set_default_size(safe_dimension(width, 1200), safe_dimension(height, 800))
            }
            WindowCommand::Minimize => minimize_window(window),
            WindowCommand::Maximize => window.maximize(),
            WindowCommand::Unmaximize => window.unmaximize(),
            WindowCommand::SetFullscreen(value) => {
                if value {
                    window.fullscreen();
                } else {
                    window.unfullscreen();
                }
            }
            WindowCommand::Center => {
                eprintln!("WebUI: centering is compositor-controlled on Wayland")
            }
            WindowCommand::Focus => window.present(),
            WindowCommand::Close => window.close(),
            WindowCommand::StartDrag => begin_native_drag(window),
            WindowCommand::SetAlwaysOnTop(value) => {
                if value {
                    eprintln!("WebUI: always_on_top is not portable in GTK4/Wayland");
                }
            }
        }
    }
    let _ = events;
}

fn install_events(
    window: &ApplicationWindow,
    webview: &WebView,
    manager: &UserContentManager,
    frame: &DesktopFrame,
    state_store: Option<WindowStateStore>,
) {
    let events = frame.events.clone();
    let webview_for_close = webview.clone();
    window.connect_close_request(move |_| {
        let event = DesktopEvent::WindowCloseRequested {
            window_id: WINDOW_ID,
        };
        let response = dispatch_event(&events, &webview_for_close, &event);
        if response == EventResponse::PreventDefault {
            glib::Propagation::Stop
        } else {
            let closed = DesktopEvent::WindowClosed {
                window_id: WINDOW_ID,
            };
            dispatch_event(&events, &webview_for_close, &closed);
            glib::Propagation::Proceed
        }
    });

    let events = frame.events.clone();
    let webview_for_size = webview.clone();
    let width_state = state_store.clone();
    window.connect_notify_local(Some("width"), move |window, _| {
        dispatch_size_event(window, &webview_for_size, &events, width_state.as_ref());
    });
    let events = frame.events.clone();
    let webview_for_size = webview.clone();
    let height_state = state_store.clone();
    window.connect_notify_local(Some("height"), move |window, _| {
        dispatch_size_event(window, &webview_for_size, &events, height_state.as_ref());
    });

    connect_window_state_events(window, webview, &frame.events, state_store);
    super::state::connect_toplevel_state_events(window, webview, &frame.events);
    connect_webview_events(webview, &frame.events, frame.runtime.live_background());
    connect_theme_events(webview, &frame.events);
    connect_message_handler(manager, window, webview, &frame.events);
}

fn connect_window_state_events(
    window: &ApplicationWindow,
    webview: &WebView,
    events: &crate::EventRegistry,
    state_store: Option<WindowStateStore>,
) {
    // `DesktopEvent::WindowMaximized`/`WindowUnmaximized` and the fullscreen
    // pair are emitted from a single consolidated path in
    // `state::connect_toplevel_state_events`, driven by `gdk::Toplevel`'s
    // `state` property; this handler only persists window state, which the
    // GTK-level `maximized` property notification tracks independently of
    // the GDK toplevel state bits.
    window.connect_maximized_notify(move |window| {
        persist_state(window, state_store.as_ref());
    });
    let events_focus = events.clone();
    let webview_focus = webview.clone();
    window.connect_is_active_notify(move |window| {
        let event = if window.is_active() {
            DesktopEvent::WindowFocused {
                window_id: WINDOW_ID,
            }
        } else {
            DesktopEvent::WindowBlurred {
                window_id: WINDOW_ID,
            }
        };
        dispatch_event(&events_focus, &webview_focus, &event);
    });
    let events_scale = events.clone();
    let webview_scale = webview.clone();
    window.connect_scale_factor_notify(move |window| {
        let event = DesktopEvent::ScaleFactorChanged {
            scale: f64::from(window.scale_factor()),
        };
        dispatch_event(&events_scale, &webview_scale, &event);
    });
}

fn connect_theme_events(webview: &WebView, events: &crate::EventRegistry) {
    let Some(settings) = gtk4::Settings::default() else {
        return;
    };
    let webview = webview.clone();
    let events = events.clone();
    settings.connect_gtk_application_prefer_dark_theme_notify(move |settings| {
        let event = DesktopEvent::ThemeChanged {
            dark: settings.is_gtk_application_prefer_dark_theme(),
        };
        dispatch_event(&events, &webview, &event);
    });
}

fn connect_webview_events(
    webview: &WebView,
    events: &crate::EventRegistry,
    live_background: Arc<crate::window::LiveBackground>,
) {
    let load_events = events.clone();
    webview.connect_load_changed(move |webview, load_event| {
        if load_event == LoadEvent::Finished {
            if let Some(uri) = webview.uri() {
                let event = DesktopEvent::NavigationCompleted {
                    window_id: WINDOW_ID,
                    url: uri.to_string(),
                };
                dispatch_event(&load_events, webview, &event);
                if let Some(color) = live_background.current() {
                    update_document_background(webview, color);
                }
            }
        }
    });
    let events = events.clone();
    webview.connect_decide_policy(move |webview, decision, decision_type| {
        if decision_type != PolicyDecisionType::NavigationAction {
            return false;
        }
        let Some(action) = decision.downcast_ref::<webkit6::NavigationPolicyDecision>() else {
            decision.ignore();
            return true;
        };
        let Some(request) = action
            .navigation_action()
            .and_then(|action| action.request())
        else {
            decision.ignore();
            return true;
        };
        let Some(uri) = request.uri() else {
            decision.ignore();
            return true;
        };
        let event = DesktopEvent::NavigationRequested {
            window_id: WINDOW_ID,
            url: uri.to_string(),
        };
        let allowed = is_allowed_navigation_url(uri.as_str())
            && dispatch_event(&events, webview, &event) == EventResponse::Continue;
        if allowed {
            decision.use_();
        } else {
            decision.ignore();
        }
        true
    });
}

fn update_document_background(webview: &WebView, color: Rgba) {
    webview.evaluate_javascript(
        &crate::window::live_background_script(color),
        None,
        None,
        None::<&gio::Cancellable>,
        |result| {
            if let Err(error) = result {
                eprintln!("WebUI: failed to update the current document background: {error}");
            }
        },
    );
}

/// SECURITY: WebKitGTK 6 (webkit6 0.6.1) exposes a registered message handler
/// as `window.webkit.messageHandlers.<name>` to every frame on the page,
/// including cross-origin iframes, regardless of the `UserContentInjectedFrames`
/// setting used above. `UserContentManager::register_script_message_handler`
/// has no `forMainFrameOnly` equivalent, and `script-message-received` does
/// not report the sending frame, unlike WKWebView's `WKScriptMessage.frameInfo`
/// (`macos/ipc_message.rs::trusted_message`) or WebView2's top-level-only
/// `WebMessageReceived` (`windows/ipc_control.rs`, which deliberately avoids
/// `ICoreWebView2Frame::add_WebMessageReceived`). Restricting script
/// injection to `TopFrame` (above) stops the convenience
/// `window.webuiHostPostMessage` alias from being defined in subframes, but a
/// subframe can still reach the handler directly via
/// `window.webkit.messageHandlers.webuiHost.postMessage(...)`. Apps that
/// embed untrusted third-party iframe content on Linux must not rely on this
/// bridge being frame-scoped until the webkit6 crate exposes per-message
/// frame identity.
fn connect_message_handler(
    manager: &UserContentManager,
    window: &ApplicationWindow,
    webview: &WebView,
    events: &crate::EventRegistry,
) {
    let window = window.clone();
    let webview = webview.clone();
    let events = events.clone();
    manager.connect_script_message_received(Some(SCRIPT_HANDLER), move |_, value| {
        let message = value.to_str();
        let Ok(message) = DesktopHostMessage::from_json(message.as_str()) else {
            return;
        };
        match message {
            DesktopHostMessage::StartDrag => begin_native_drag(&window),
            DesktopHostMessage::Minimize => minimize_window(&window),
            DesktopHostMessage::ToggleMaximize => {
                if window.is_maximized() {
                    window.unmaximize();
                } else {
                    window.maximize();
                }
            }
            DesktopHostMessage::Close => {
                let event = DesktopEvent::WindowCloseRequested {
                    window_id: WINDOW_ID,
                };
                if dispatch_event(&events, &webview, &event) == EventResponse::Continue {
                    window.close();
                }
            }
        }
    });
}

fn begin_native_drag(window: &ApplicationWindow) {
    let Some(surface) = window.surface() else {
        return;
    };
    let display = surface.display();
    let Some(device) = display.default_seat().and_then(|seat| seat.pointer()) else {
        return;
    };
    let Some(toplevel) = surface.downcast_ref::<gdk::Toplevel>() else {
        return;
    };
    let (x, y, _) =
        surface
            .device_position(&device)
            .unwrap_or((0.0, 0.0, gdk::ModifierType::empty()));
    toplevel.begin_move(&device, 1, x, y, 0);
}

fn minimize_window(window: &ApplicationWindow) {
    if let Some(surface) = window.surface() {
        if let Some(toplevel) = surface.downcast_ref::<gdk::Toplevel>() {
            let _ = toplevel.minimize();
        }
    }
}

fn dispatch_size_event(
    window: &ApplicationWindow,
    webview: &WebView,
    events: &crate::EventRegistry,
    state_store: Option<&WindowStateStore>,
) {
    let width = u32::try_from(window.width()).unwrap_or(0);
    let height = u32::try_from(window.height()).unwrap_or(0);
    let event = DesktopEvent::WindowResized {
        window_id: WINDOW_ID,
        width,
        height,
    };
    dispatch_event(events, webview, &event);
    persist_state(window, state_store);
}

pub(super) fn dispatch_event(
    events: &crate::EventRegistry,
    webview: &WebView,
    event: &DesktopEvent,
) -> EventResponse {
    let response = events.dispatch(event);
    match event.to_javascript() {
        Ok(script) => {
            webview.evaluate_javascript(&script, None, None, None::<&gio::Cancellable>, |_| {})
        }
        Err(error) => eprintln!("WebUI: failed to mirror desktop event: {error}"),
    }
    response
}

pub(super) fn restore_state(window: &ApplicationWindow, store: Option<&WindowStateStore>) {
    let Some(store) = store else {
        return;
    };
    let displays = display_bounds(window);
    match store.load_valid(&displays) {
        Ok(Some(state)) => {
            window.set_default_size(
                safe_dimension(state.width, 1200),
                safe_dimension(state.height, 800),
            );
            if state.maximized {
                window.maximize();
            }
            if state.x != 0 || state.y != 0 {
                eprintln!("WebUI: GTK4 cannot restore window position on Wayland");
            }
        }
        Ok(None) => {}
        Err(error) => eprintln!("WebUI: failed to restore window state: {error}"),
    }
}

pub(super) fn persist_state(window: &ApplicationWindow, store: Option<&WindowStateStore>) {
    let Some(store) = store else {
        return;
    };
    let state = WindowState {
        x: 0,
        y: 0,
        width: u32::try_from(window.width()).unwrap_or(0),
        height: u32::try_from(window.height()).unwrap_or(0),
        maximized: window.is_maximized(),
    };
    if let Err(error) = store.save(&state) {
        eprintln!("WebUI: failed to persist window state: {error}");
    }
}

fn display_bounds(window: &ApplicationWindow) -> Vec<DisplayBounds> {
    // Both `RootExt` and `WidgetExt` expose `display()`, so name the trait.
    let display = gtk4::prelude::WidgetExt::display(window);
    let monitors = display.monitors();
    let mut bounds = Vec::with_capacity(monitors.n_items() as usize);
    for index in 0..monitors.n_items() {
        let Some(monitor) = monitors
            .item(index)
            .and_then(|object| object.downcast::<gdk::Monitor>().ok())
        else {
            continue;
        };
        let geometry = monitor.geometry();
        bounds.push(DisplayBounds {
            x: geometry.x(),
            y: geometry.y(),
            width: u32::try_from(geometry.width()).unwrap_or(0),
            height: u32::try_from(geometry.height()).unwrap_or(0),
        });
    }
    bounds
}

pub(super) fn to_gdk_rgba(color: Rgba) -> gdk::RGBA {
    gdk::RGBA::new(
        f32::from(color.r) / 255.0,
        f32::from(color.g) / 255.0,
        f32::from(color.b) / 255.0,
        f32::from(color.a) / 255.0,
    )
}

fn report_effect_limit(effect: WindowEffect) {
    if effect != WindowEffect::None {
        eprintln!("WebUI: Linux has no portable blur-behind effect; requested {effect:?} is degraded to the configured background");
    }
}

pub(super) fn safe_dimension(value: u32, fallback: i32) -> i32 {
    i32::try_from(value).unwrap_or(fallback).max(1)
}

/// Delegate to the shared cross-backend navigation policy.
fn is_allowed_navigation_url(url: &str) -> bool {
    crate::is_allowed_navigation_url(url, super::APP_ORIGIN)
}

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

    #[test]
    fn application_activation_does_not_parse_the_host_command_line() {
        let app = gio::Application::new(None, gio::ApplicationFlags::NON_UNIQUE);
        let activated = Rc::new(std::cell::Cell::new(false));
        let observed = Rc::clone(&activated);
        app.connect_activate(move |app| {
            observed.set(true);
            app.quit();
        });
        assert_eq!(run_application(&app), glib::ExitCode::SUCCESS);
        assert!(activated.get());
    }

    #[test]
    fn navigation_allowlist_rejects_external_origins() {
        assert!(is_allowed_navigation_url("webui://app"));
        assert!(is_allowed_navigation_url("webui://app/settings"));
        assert!(!is_allowed_navigation_url("https://webui://app/"));
        assert!(!is_allowed_navigation_url("webui://application/"));
        assert!(!is_allowed_navigation_url("webui://app.evil/"));
    }

    #[test]
    fn dimensions_are_positive_and_bounded_to_native_int() {
        assert_eq!(safe_dimension(0, 1200), 1);
        assert_eq!(safe_dimension(u32::MAX, 1200), 1200);
        assert_eq!(safe_dimension(640, 1200), 640);
    }
}