native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
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
//! `WebView`: web content shown by the platform's own browser engine.
//!
//! The widget is hosted inside an ordinary [`WidgetKind::Container`], so it
//! takes part in layout like any other widget. The engine is the one the
//! operating system provides; nothing is bundled:
//!
//! | Backend | Engine | Notes |
//! |---|---|---|
//! | Win32 | Microsoft Edge WebView2 | Needs the WebView2 Runtime (preinstalled on current Windows 10 and 11). [`Ui::webview_engine`] reports [`WebViewError::RuntimeUnavailable`] when it is missing. |
//! | Cocoa | `WKWebView` | Part of macOS. |
//! | GTK | WebKitGTK 6 | The `webkitgtk-6.0` library is LGPL-2.1 and is linked dynamically; building needs its development package (`libwebkitgtk-6.0-dev` on Debian and Ubuntu). |
//! | Mock | in-memory | Records calls and replays deterministic events for tests. |
//!
//! # Loading and navigation
//!
//! [`Ui::webview_load_url`] and [`Ui::webview_load_html`] start a load; the
//! engine then reports [`UiEvent::WebViewLoadStarted`] and either
//! [`UiEvent::WebViewLoadFinished`] or [`UiEvent::WebViewLoadFailed`].
//! Loads started by the application are always allowed. Navigations started
//! by the page (a link, a form, a script changing `location`) are checked
//! against [`WebViewOptions::allow_navigation`]: with no prefixes every
//! navigation is allowed, otherwise only URLs that start with one of them.
//! A refused navigation is reported as [`UiEvent::WebViewNavigationBlocked`].
//! Requests to open a new window are always refused and reported the same
//! way.
//!
//! # Scripts
//!
//! [`Ui::webview_evaluate_script`] runs JavaScript in the page and returns an
//! [`OperationId`]. The outcome arrives later as
//! [`UiEvent::WebViewScriptResult`] carrying the value as JSON text, or the
//! message of the exception the script threw. The script is evaluated the way
//! `eval` would, so the value of its last expression is the result; a page
//! whose content security policy forbids `eval` will report an error.
//!
//! # Messages between the page and the application
//!
//! Every page gets a small `window.nativeGui` object:
//!
//! ```js
//! window.nativeGui.postMessage("saved");            // to the application
//! window.nativeGui.addEventListener("message", e => console.log(e.data));
//! ```
//!
//! `postMessage` arrives as [`UiEvent::WebViewMessage`];
//! [`Ui::webview_post_message`] delivers a string to the page's `message`
//! listeners (and to `window.nativeGui.onmessage` if it is set). Treat page
//! messages as untrusted input: any script running in the page can send them.

use std::collections::HashSet;
use std::fmt;

use crate::advanced::{EngineInfo, OperationId};
use crate::error::{GuiError, GuiResult};
use crate::events::UiEvent;
use crate::ui::{Backend, Ui};
use crate::widgets::WidgetKind;
use crate::WidgetId;

/// Why a WebView operation did not happen.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebViewError {
    /// The browser engine is not installed or could not be started. The
    /// text says what is missing and how to install it.
    RuntimeUnavailable(String),
    /// The URL is empty, has no scheme, or contains whitespace or NUL.
    InvalidUrl(String),
    /// The widget is not a WebView.
    NotAWebView(WidgetId),
    /// The engine refused or failed the request.
    Engine(String),
}

impl fmt::Display for WebViewError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WebViewError::RuntimeUnavailable(detail) => {
                write!(f, "web engine unavailable: {detail}")
            }
            WebViewError::InvalidUrl(url) => write!(f, "invalid URL: {url:?}"),
            WebViewError::NotAWebView(widget) => write!(f, "widget {} is not a WebView", widget.0),
            WebViewError::Engine(detail) => write!(f, "web engine error: {detail}"),
        }
    }
}

impl std::error::Error for WebViewError {}

impl From<WebViewError> for GuiError {
    fn from(error: WebViewError) -> Self {
        GuiError::WebView(error)
    }
}

/// Settings fixed when a WebView is created.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WebViewOptions {
    /// Allow the engine's developer tools (inspector, context menu entry).
    pub devtools: bool,
    /// URL prefixes that page-started navigations may go to. Empty allows
    /// every navigation.
    pub allowed_navigation: Vec<String>,
    /// Replaces the engine's user agent string.
    pub user_agent: Option<String>,
}

impl WebViewOptions {
    /// Default options: no developer tools, every navigation allowed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Turns the engine's developer tools on or off.
    pub fn devtools(mut self, enabled: bool) -> Self {
        self.devtools = enabled;
        self
    }

    /// Allows page-started navigations to URLs starting with `prefix`. Once
    /// any prefix is set, navigations to other URLs are blocked.
    pub fn allow_navigation(mut self, prefix: impl Into<String>) -> Self {
        self.allowed_navigation.push(prefix.into());
        self
    }

    /// Sets the user agent string the engine sends.
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = Some(user_agent.into());
        self
    }

    /// Whether a page-started navigation to `url` is allowed.
    pub fn allows(&self, url: &str) -> bool {
        self.allowed_navigation.is_empty()
            || self
                .allowed_navigation
                .iter()
                .any(|prefix| url.starts_with(prefix.as_str()))
    }
}

/// What a WebView should show.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebViewContent {
    /// Load a URL.
    Url(String),
    /// Show an HTML document. Relative links resolve against `base_url`,
    /// which is also the page's URL and origin when given.
    Html {
        /// The document.
        html: String,
        /// The URL the document is shown at.
        base_url: Option<String>,
    },
}

/// History and loading commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebViewCommand {
    /// Load the current page again.
    Reload,
    /// Stop the current load.
    Stop,
    /// Go back one history entry.
    GoBack,
    /// Go forward one history entry.
    GoForward,
}

/// What a WebView is showing right now.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct WebViewState {
    /// The current URL, once a load has started.
    pub url: Option<String>,
    /// The document title, when the page has one.
    pub title: Option<String>,
    /// A load is in progress.
    pub loading: bool,
    /// [`WebViewCommand::GoBack`] would move.
    pub can_go_back: bool,
    /// [`WebViewCommand::GoForward`] would move.
    pub can_go_forward: bool,
}

/// Backend contract for the WebView family.
///
/// A backend creates the engine's view inside the host container, keeps it
/// sized to the container, and reports engine callbacks as the `WebView*`
/// [`UiEvent`]s through its normal event queue. Calls made before the engine
/// is ready (WebView2 starts asynchronously) are queued and run in order once
/// it is.
pub trait WebViewBackend: Backend {
    /// Checks that the engine can run and reports its name and version.
    fn webview_engine(&mut self) -> GuiResult<EngineInfo>;
    /// Creates a web view filling the container `host`.
    fn create_webview(&mut self, host: WidgetId, options: &WebViewOptions) -> GuiResult<()>;
    /// Starts loading `content`.
    fn webview_load(&mut self, host: WidgetId, content: &WebViewContent) -> GuiResult<()>;
    /// Runs a history or loading command; a command that cannot move (back
    /// with no history) does nothing.
    fn webview_command(&mut self, host: WidgetId, command: WebViewCommand) -> GuiResult<()>;
    /// Reports the current URL, title and history state.
    fn webview_state(&self, host: WidgetId) -> GuiResult<WebViewState>;
    /// Runs `script`, already wrapped by [`wrap_script`], and later reports
    /// [`UiEvent::WebViewScriptResult`] for `operation` with the result
    /// decoded by [`decode_script_result`].
    fn webview_evaluate(
        &mut self,
        host: WidgetId,
        operation: OperationId,
        script: &str,
    ) -> GuiResult<()>;
    /// Delivers `message` to the page's `window.nativeGui` listeners.
    fn webview_post_message(&mut self, host: WidgetId, message: &str) -> GuiResult<()>;
}

/// Encodes `text` as a JavaScript (and JSON) string literal, quotes
/// included. Line and paragraph separators are escaped too, so the literal
/// is safe inside any script.
pub fn json_string(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for ch in text.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{2028}' => out.push_str("\\u2028"),
            '\u{2029}' => out.push_str("\\u2029"),
            ch if (ch as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", ch as u32)),
            ch => out.push(ch),
        }
    }
    out.push('"');
    out
}

/// Decodes one JSON string literal (the whole input, surrounding whitespace
/// allowed). Returns `None` when `literal` is not exactly one string.
pub fn decode_json_string(literal: &str) -> Option<String> {
    let body = literal.trim().strip_prefix('"')?.strip_suffix('"')?;
    let mut out = String::with_capacity(body.len());
    let mut chars = body.chars();
    while let Some(ch) = chars.next() {
        match ch {
            '"' => return None,
            '\\' => match chars.next()? {
                '"' => out.push('"'),
                '\\' => out.push('\\'),
                '/' => out.push('/'),
                'b' => out.push('\u{8}'),
                'f' => out.push('\u{c}'),
                'n' => out.push('\n'),
                'r' => out.push('\r'),
                't' => out.push('\t'),
                'u' => {
                    let unit = read_hex4(&mut chars)?;
                    if (0xD800..0xDC00).contains(&unit) {
                        if chars.next()? != '\\' || chars.next()? != 'u' {
                            return None;
                        }
                        let low = read_hex4(&mut chars)?;
                        if !(0xDC00..0xE000).contains(&low) {
                            return None;
                        }
                        let code = 0x10000 + ((unit - 0xD800) << 10) + (low - 0xDC00);
                        out.push(char::from_u32(code)?);
                    } else {
                        out.push(char::from_u32(unit)?);
                    }
                }
                _ => return None,
            },
            ch => out.push(ch),
        }
    }
    Some(out)
}

fn read_hex4(chars: &mut std::str::Chars<'_>) -> Option<u32> {
    let mut value = 0;
    for _ in 0..4 {
        value = value * 16 + chars.next()?.to_digit(16)?;
    }
    Some(value)
}

/// Wraps `script` so every engine returns the same thing: a string that is
/// `o` followed by the JSON of the script's value, or `e` followed by the
/// message of the exception it threw. [`decode_script_result`] reads it.
pub fn wrap_script(script: &str) -> String {
    format!(
        "(function(){{try{{var v=(0,eval)({});var j=JSON.stringify(v);\
         return 'o'+(j===undefined?'null':j);}}catch(e){{\
         return 'e'+String(e&&e.message!==undefined?e.message:e);}}}})()",
        json_string(script)
    )
}

/// Reads the string returned by a [`wrap_script`] script: `Ok` with the
/// value as JSON text, or `Err` with the exception message.
pub fn decode_script_result(raw: &str) -> Result<String, String> {
    if let Some(json) = raw.strip_prefix('o') {
        Ok(json.to_owned())
    } else if let Some(message) = raw.strip_prefix('e') {
        Err(message.to_owned())
    } else {
        Err(format!("unexpected script result: {raw}"))
    }
}

/// The script every page gets at document start. It defines
/// `window.nativeGui`; `native_post` is a JavaScript function expression
/// that takes one string and hands it to the engine's message channel, and
/// `native_subscribe` is a statement that may call `deliver(data)` for
/// messages the engine pushes into the page (empty when the backend delivers
/// by evaluating `window.nativeGui.__deliver(...)` instead).
pub fn bridge_script(native_post: &str, native_subscribe: &str) -> String {
    format!(
        "(function(){{if(window.nativeGui){{return;}}var post={native_post};var listeners=[];\
         function report(e){{setTimeout(function(){{throw e;}});}}\
         var bridge={{postMessage:function(m){{post(String(m));}},\
         addEventListener:function(t,l){{if(t==='message'&&typeof l==='function'){{listeners.push(l);}}}},\
         removeEventListener:function(t,l){{var i=listeners.indexOf(l);if(i>=0){{listeners.splice(i,1);}}}},\
         onmessage:null}};\
         function deliver(data){{var ev={{data:String(data)}};\
         if(typeof bridge.onmessage==='function'){{try{{bridge.onmessage(ev);}}catch(e){{report(e);}}}}\
         listeners.slice().forEach(function(l){{try{{l(ev);}}catch(e){{report(e);}}}});}}\
         Object.defineProperty(bridge,'__deliver',{{value:deliver}});\
         Object.defineProperty(window,'nativeGui',{{value:bridge}});{native_subscribe}}})();"
    )
}

/// The script a backend evaluates to deliver `message` to the page when it
/// has no native push channel.
pub fn deliver_script(message: &str) -> String {
    format!(
        "window.nativeGui&&window.nativeGui.__deliver({});",
        json_string(message)
    )
}

/// Reports whether `url` is the navigation an application load asked for.
///
/// Engines may add or drop a trailing slash when they build the request, so
/// that difference is ignored. Backends use this to let application loads
/// past the navigation policy, which only applies to page navigations.
pub fn matches_app_target(target: &str, url: &str) -> bool {
    target.trim_end_matches('/') == url.trim_end_matches('/')
}

/// Checks that `url` looks like an absolute URL: a scheme, no whitespace and
/// no NUL.
pub fn validate_url(url: &str) -> Result<(), WebViewError> {
    let scheme_ok = url
        .split_once(':')
        .map(|(scheme, _)| {
            !scheme.is_empty()
                && scheme
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_ascii_alphabetic())
                && scheme
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
        })
        .unwrap_or(false);
    if !scheme_ok || url.chars().any(|c| c.is_whitespace() || c == '\0') {
        return Err(WebViewError::InvalidUrl(url.to_owned()));
    }
    Ok(())
}

/// WebViews created by [`Ui::create_webview`].
#[derive(Debug, Default)]
pub(crate) struct WebViewRegistry {
    views: HashSet<WidgetId>,
}

impl WebViewRegistry {
    pub(crate) fn forget(&mut self, widget: WidgetId) {
        self.views.remove(&widget);
    }
}

impl<B: Backend> Ui<B> {
    /// Whether `widget` is a WebView created by [`Ui::create_webview`].
    pub fn is_webview(&self, widget: WidgetId) -> bool {
        self.webviews.views.contains(&widget)
    }

    fn require_webview(&self, widget: WidgetId) -> GuiResult<()> {
        if self.widget(widget).is_none() {
            return Err(GuiError::WidgetNotFound(widget.0));
        }
        if !self.webviews.views.contains(&widget) {
            return Err(WebViewError::NotAWebView(widget).into());
        }
        Ok(())
    }

    /// Completes the operation of a script result so
    /// [`Ui::operation_pending`] reports it as done.
    pub(crate) fn observe_webview_event(&mut self, event: &UiEvent) {
        if let UiEvent::WebViewScriptResult { operation, .. } = event {
            self.complete_operation(*operation);
        }
    }
}

impl<B: Backend + WebViewBackend> Ui<B> {
    /// Checks that the browser engine can run here and reports its name and
    /// version. On Windows this is the place to find out that the WebView2
    /// Runtime is missing ([`WebViewError::RuntimeUnavailable`]).
    pub fn webview_engine(&mut self) -> GuiResult<EngineInfo> {
        self.backend_mut().webview_engine()
    }

    /// Creates a WebView. It is a container widget: attach it, size it and
    /// give it flex grow like any other widget. Nothing is loaded yet.
    pub fn create_webview(&mut self, options: WebViewOptions) -> GuiResult<WidgetId> {
        if let Some(agent) = &options.user_agent {
            if agent.contains('\0') {
                return Err(WebViewError::Engine("user agent contains NUL".into()).into());
            }
        }
        let host = self.create(WidgetKind::Container, None)?;
        if let Err(error) = self.backend_mut().create_webview(host, &options) {
            let _ = self.remove(host);
            return Err(error);
        }
        self.webviews.views.insert(host);
        Ok(host)
    }

    /// Starts loading `url`.
    pub fn webview_load_url(&mut self, widget: WidgetId, url: &str) -> GuiResult<()> {
        self.require_webview(widget)?;
        validate_url(url)?;
        self.backend_mut()
            .webview_load(widget, &WebViewContent::Url(url.to_owned()))
    }

    /// Shows an HTML document. With `base_url`, relative links resolve
    /// against it and it becomes the page's URL and origin.
    pub fn webview_load_html(
        &mut self,
        widget: WidgetId,
        html: &str,
        base_url: Option<&str>,
    ) -> GuiResult<()> {
        self.require_webview(widget)?;
        if let Some(base) = base_url {
            validate_url(base)?;
        }
        self.backend_mut().webview_load(
            widget,
            &WebViewContent::Html {
                html: html.to_owned(),
                base_url: base_url.map(str::to_owned),
            },
        )
    }

    /// Loads the current page again.
    pub fn webview_reload(&mut self, widget: WidgetId) -> GuiResult<()> {
        self.webview_command(widget, WebViewCommand::Reload)
    }

    /// Stops the current load.
    pub fn webview_stop(&mut self, widget: WidgetId) -> GuiResult<()> {
        self.webview_command(widget, WebViewCommand::Stop)
    }

    /// Goes back one history entry, if there is one.
    pub fn webview_go_back(&mut self, widget: WidgetId) -> GuiResult<()> {
        self.webview_command(widget, WebViewCommand::GoBack)
    }

    /// Goes forward one history entry, if there is one.
    pub fn webview_go_forward(&mut self, widget: WidgetId) -> GuiResult<()> {
        self.webview_command(widget, WebViewCommand::GoForward)
    }

    fn webview_command(&mut self, widget: WidgetId, command: WebViewCommand) -> GuiResult<()> {
        self.require_webview(widget)?;
        self.backend_mut().webview_command(widget, command)
    }

    /// The current URL, title and history state.
    pub fn webview_state(&self, widget: WidgetId) -> GuiResult<WebViewState> {
        self.require_webview(widget)?;
        self.backend().webview_state(widget)
    }

    /// Runs JavaScript in the page. The result arrives as
    /// [`UiEvent::WebViewScriptResult`] with the returned id.
    pub fn webview_evaluate_script(
        &mut self,
        widget: WidgetId,
        script: &str,
    ) -> GuiResult<OperationId> {
        self.require_webview(widget)?;
        let operation = self.allocate_operation_id();
        let wrapped = wrap_script(script);
        if let Err(error) = self
            .backend_mut()
            .webview_evaluate(widget, operation, &wrapped)
        {
            self.complete_operation(operation);
            return Err(error);
        }
        Ok(operation)
    }

    /// Sends `message` to the page's `window.nativeGui` message listeners.
    pub fn webview_post_message(&mut self, widget: WidgetId, message: &str) -> GuiResult<()> {
        self.require_webview(widget)?;
        self.backend_mut().webview_post_message(widget, message)
    }
}

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

    #[test]
    fn app_target_ignores_trailing_slash() {
        assert!(matches_app_target(
            "https://a.example",
            "https://a.example/"
        ));
        assert!(!matches_app_target(
            "https://a.example/",
            "https://b.example/"
        ));
    }

    #[test]
    fn json_string_round_trips() {
        for text in [
            "",
            "plain",
            "quote \" and backslash \\",
            "lines\nand\ttabs\r",
            "\u{1}\u{1f}",
            "separators \u{2028}\u{2029}",
            "emoji 🙂 and ünïcode",
        ] {
            let literal = json_string(text);
            assert!(!literal.contains('\n'));
            assert!(!literal.contains('\u{2028}'));
            assert_eq!(
                decode_json_string(&literal).as_deref(),
                Some(text),
                "{text:?}"
            );
        }
    }

    #[test]
    fn decode_json_string_reads_surrogate_pairs_and_rejects_junk() {
        assert_eq!(
            decode_json_string(r#""\ud83d\ude42 \u00e9""#).as_deref(),
            Some("🙂 é")
        );
        assert_eq!(decode_json_string(" \"x\" ").as_deref(), Some("x"));
        assert_eq!(decode_json_string("x"), None);
        assert_eq!(decode_json_string("\"a\"b\""), None);
        assert_eq!(decode_json_string(r#""\q""#), None);
        assert_eq!(decode_json_string(r#""\ud83d""#), None);
    }

    #[test]
    fn script_results_decode() {
        assert_eq!(decode_script_result("o3"), Ok("3".to_owned()));
        assert_eq!(decode_script_result("o\"hi\""), Ok("\"hi\"".to_owned()));
        assert_eq!(decode_script_result("eboom"), Err("boom".to_owned()));
        assert!(decode_script_result("").is_err());
        let wrapped = wrap_script("document.title\n// \"quoted\"");
        assert!(wrapped.starts_with("(function(){"));
        assert!(wrapped.contains(r#"(0,eval)("document.title\n// \"quoted\"")"#));
    }

    #[test]
    fn bridge_and_delivery_scripts_embed_their_parts() {
        let bridge = bridge_script("function(m){native(m);}", "subscribe(deliver);");
        assert!(bridge.contains("var post=function(m){native(m);};"));
        assert!(bridge.ends_with("subscribe(deliver);})();"));
        assert!(bridge.contains("Object.defineProperty(window,'nativeGui'"));
        assert_eq!(
            deliver_script("a\"b"),
            "window.nativeGui&&window.nativeGui.__deliver(\"a\\\"b\");"
        );
    }

    #[test]
    fn urls_are_checked() {
        for good in [
            "https://example.com/",
            "about:blank",
            "data:text/html,hi",
            "file:///tmp/a.html",
            "app+local://x",
        ] {
            assert_eq!(validate_url(good), Ok(()), "{good}");
        }
        for bad in [
            "",
            "example.com",
            "://x",
            "1http://x",
            "https://a b",
            "https://a\0",
        ] {
            assert!(validate_url(bad).is_err(), "{bad:?}");
        }
    }

    #[test]
    fn navigation_prefixes() {
        let open = WebViewOptions::new();
        assert!(open.allows("https://anything.example/"));
        let limited = WebViewOptions::new()
            .allow_navigation("https://app.example/")
            .allow_navigation("about:");
        assert!(limited.allows("https://app.example/page"));
        assert!(limited.allows("about:blank"));
        assert!(!limited.allows("https://other.example/"));
        assert!(!limited.allows("https://app.example.evil/"));
    }

    #[test]
    fn errors_display() {
        let error: GuiError = WebViewError::RuntimeUnavailable("install it".into()).into();
        assert_eq!(
            error.to_string(),
            "WebView error: web engine unavailable: install it"
        );
        assert_eq!(
            WebViewError::NotAWebView(WidgetId(4)).to_string(),
            "widget 4 is not a WebView"
        );
    }
}