Skip to main content

day_piece_webview/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-piece-webview, an external Day Piece (DESIGN.md §15) wrapping each toolkit's native web
5//! view: `WKWebView` on AppKit/UIKit, `QWebEngineView` on Qt, `android.webkit.WebView` on Android. One
6//! Rust API registered link-time into each backend's renderer slice without touching day. Alongside
7//! the picker it's a reference for pieces that carry both a front-end and their own native backend,
8//! here including an Android manifest permission contribution (INTERNET), see docs/extending.md.
9//!
10//! The view is a growing leaf that fills its space. Navigation is imperative and modeled with
11//! `Copy` `Trigger`s (`.go()` loads the bound URL, `.back()`/`.forward()`/`.stop()`/`.reload()`
12//! drive history), each `watch`ed to a `WebPatch`. The bound URL is two-way: `.go()` loads it, and
13//! native navigation reports the current URL back so a bound text field follows along.
14
15#[cfg(feature = "dom")]
16mod browser;
17
18use std::cell::{Cell, RefCell};
19use std::collections::HashMap;
20use std::future::Future;
21use std::pin::Pin;
22use std::rc::Rc;
23use std::sync::Arc;
24use std::task::Poll;
25
26use day_core::{BuildCx, Flex, Piece, RNode};
27use day_pieces::{Decorated, IntoReactive, IntoText, Reactive};
28use day_reactive::{AnyBinding, Binding, Signal, Trigger, bind_seeded, watch};
29use day_spec::Event;
30
31mod browsing;
32mod content;
33pub mod renderer;
34mod resources;
35pub use browsing::{
36    AuthRequest, AuthResponder, BrowseProps, DialogKind, DialogRequest, DialogResponder,
37    DownloadEvent, DownloadRequest, DownloadResponder, LoadError, LoadErrorKind, RendererGone,
38    UserAgent, cancel_download, download_support, host_trusted, open_download, present_dialog,
39    remove_download, sanitize_file_name, trust_host, unused_path,
40};
41pub use content::{
42    BlockedLoad, ContentRuleList, ContentRulesError, Frames, InjectAt, MediaRequest, PageContent,
43    RequestDecision, RequestFilter, RequestHooks, RequestInfo, ResourceKind, ScriptMessage,
44    UserScript, blocked_report_support, content_rules_support, request_filter_support,
45    script_message_support, user_script_support,
46};
47pub use resources::{ResourceProvider, ResourceRequest, ResourceResponse};
48
49#[cfg(all(
50    any(target_os = "macos", target_os = "ios"),
51    any(feature = "appkit", feature = "uikit", feature = "gtk")
52))]
53mod resources_apple;
54
55#[cfg(all(feature = "arkui", target_env = "ohos"))]
56mod resources_arkui;
57
58#[cfg(any(test, all(feature = "arkui", target_env = "ohos")))]
59mod resource_content_type;
60
61/// Ordinary documents opt in through `on_external_link`. Loading a document, reloading,
62/// fragment navigation, and embedded frames must not be mistaken for an outbound click.
63#[cfg(any(
64    test,
65    all(
66        any(target_os = "macos", target_os = "ios"),
67        any(feature = "appkit", feature = "uikit", feature = "gtk")
68    )
69))]
70fn external_document_link(
71    current: Option<&str>,
72    target: &str,
73    activated: bool,
74    new_window: bool,
75    subframe: bool,
76) -> bool {
77    if subframe || target.is_empty() || target == "about:blank" || !(activated || new_window) {
78        return false;
79    }
80    let without_fragment = |url: &str| url.split('#').next().unwrap_or("").to_owned();
81    current.is_none_or(|url| without_fragment(url) != without_fragment(target))
82}
83
84pub const KIND: &str = "day.piece.webview";
85
86/// Storage shared by independent views. A private profile never shares persistent data.
87/// Configure before creating views. Directory is honored where the engine exposes a public
88/// storage-path API; Apple uses an identifier-backed, system-managed location instead.
89#[derive(Clone, Debug, Default, PartialEq, Eq)]
90#[must_use]
91pub struct WebProfile {
92    pub name: String,
93    pub directory: Option<String>,
94    pub private: bool,
95}
96impl WebProfile {
97    pub fn persistent(name: impl Into<String>) -> Self {
98        Self {
99            name: name.into(),
100            ..Self::default()
101        }
102    }
103    pub fn private(name: impl Into<String>) -> Self {
104        Self {
105            name: name.into(),
106            private: true,
107            directory: None,
108        }
109    }
110    pub fn directory(mut self, path: impl Into<String>) -> Self {
111        self.directory = Some(path.into());
112        self
113    }
114    /// Stable, filesystem-safe identity. Includes privacy mode and requested directory.
115    pub fn storage_key(&self) -> String {
116        let text = format!("{}:{:?}:{}", self.name, self.directory, self.private);
117        let hash = text.bytes().fold(14_695_981_039_346_656_037_u64, |h, b| {
118            (h ^ u64::from(b)).wrapping_mul(1_099_511_628_211)
119        });
120        format!("day-{hash:016x}")
121    }
122}
123/// Whether an engine can guarantee an ephemeral, isolated data store. Unsupported private
124/// requests are blocked before loading anything; deleting data afterward is not private mode.
125pub fn private_browsing_support() -> day_spec::Support {
126    if cfg!(any(
127        all(feature = "material", target_os = "android"),
128        all(feature = "dom", target_arch = "wasm32")
129    )) {
130        day_spec::Support::Unsupported
131    } else {
132        support()
133    }
134}
135/// Native cookie URL filtering, shared by engines that expose a whole cookie jar.
136#[allow(
137    dead_code,
138    reason = "the Apple cookie store (storage_apple.rs) is its only caller"
139)]
140pub(crate) fn cookie_matches(url: &str, domain: &str, path: &str, secure: bool) -> bool {
141    let Ok(url) = url::Url::parse(url) else {
142        return false;
143    };
144    if !matches!(url.scheme(), "http" | "https") || (secure && url.scheme() != "https") {
145        return false;
146    }
147    let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
148    let domain = domain.to_ascii_lowercase();
149    let bare = domain.trim_start_matches('.');
150    let domain_match =
151        host == bare || (domain.starts_with('.') && host.ends_with(&format!(".{bare}")));
152    let path = if path.is_empty() { "/" } else { path };
153    domain_match
154        && (url.path() == path
155            || (url.path().starts_with(path)
156                && (path.ends_with('/') || url.path().as_bytes().get(path.len()) == Some(&b'/'))))
157}
158/// Validate the response origin before native APIs (some accept arbitrary cookie domains).
159fn cookie_source_valid(source: &str, header: &str) -> bool {
160    if header.contains(['\r', '\n']) {
161        return false;
162    }
163    let Ok(url) = url::Url::parse(source) else {
164        return false;
165    };
166    if !matches!(url.scheme(), "http" | "https") {
167        return false;
168    }
169    let host = url.host_str().unwrap_or_default().to_ascii_lowercase();
170    let mut fields = header.split(';');
171    let Some((name, _)) = fields.next().and_then(|field| field.trim().split_once('=')) else {
172        return false;
173    };
174    let mut secure = false;
175    let mut domain_set = false;
176    let mut root_path = false;
177    for field in fields {
178        let (key, value) = field.trim().split_once('=').unwrap_or((field.trim(), ""));
179        if key.eq_ignore_ascii_case("domain") {
180            domain_set = true;
181            let domain = value.trim().trim_start_matches('.').to_ascii_lowercase();
182            if psl::suffix(domain.as_bytes())
183                .is_some_and(|suffix| suffix.is_known() && suffix.as_bytes() == domain.as_bytes())
184            {
185                return false;
186            }
187            if domain.is_empty()
188                || !(host == domain
189                    || (url::Host::parse(&host).is_ok_and(|h| matches!(h, url::Host::Domain(_)))
190                        && host.ends_with(&format!(".{domain}"))))
191            {
192                return false;
193            }
194        } else if key.eq_ignore_ascii_case("secure") {
195            secure = true;
196        } else if key.eq_ignore_ascii_case("path") {
197            root_path = value.trim() == "/";
198        }
199    }
200    if secure && url.scheme() != "https" {
201        return false;
202    }
203    if name.starts_with("__Secure-") && !secure {
204        return false;
205    }
206    if name.starts_with("__Host-") && (!secure || domain_set || !root_path) {
207        return false;
208    }
209    true
210}
211#[cfg(any(
212    all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
213    all(feature = "uikit", target_os = "ios")
214))]
215mod browsing_apple;
216#[cfg(any(
217    all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
218    all(feature = "uikit", target_os = "ios")
219))]
220mod content_apple;
221#[cfg(any(
222    all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
223    all(feature = "uikit", target_os = "ios")
224))]
225mod storage_apple;
226/// For `tests/content-rules-macos.rs` only: WebKit content rule lists on a real view.
227#[cfg(all(any(feature = "appkit", feature = "gtk"), target_os = "macos"))]
228#[doc(hidden)]
229pub use content_apple::probe as __webkit_content_probe;
230/// Named profile isolation. ArkWeb exposes app-wide stores only; its default and private
231/// contexts share data by origin, but do not implement independent named profiles.
232pub fn profile_support() -> day_spec::Support {
233    #[cfg(all(feature = "material", target_os = "android"))]
234    let result = android_impl::capability("supportsProfiles");
235    #[cfg(not(all(feature = "material", target_os = "android")))]
236    let result = {
237        #[cfg(any(
238            all(any(feature = "appkit", feature = "gtk"), target_os = "macos"),
239            all(feature = "uikit", target_os = "ios")
240        ))]
241        if !storage_apple::named_profiles_available() {
242            return day_spec::Support::Emulated;
243        }
244        if cfg!(all(feature = "arkui", target_env = "ohos")) {
245            day_spec::Support::Emulated
246        } else if cfg!(all(feature = "dom", target_arch = "wasm32")) {
247            day_spec::Support::Unsupported
248        } else {
249            support()
250        }
251    };
252    result
253}
254/// Complete deletion of a profile's cookie, cache and persistent site data.
255pub fn clear_data_support() -> day_spec::Support {
256    #[cfg(all(feature = "material", target_os = "android"))]
257    let result = android_impl::capability("supportsDataClearing");
258    #[cfg(not(all(feature = "material", target_os = "android")))]
259    let result = if cfg!(any(
260        all(feature = "arkui", target_env = "ohos"),
261        all(feature = "dom", target_arch = "wasm32")
262    )) {
263        day_spec::Support::Unsupported
264    } else {
265        support()
266    };
267    result
268}
269
270const DATA_REQUEST: &str = "day-web-data:";
271
272/// Full props (realize). The initial `url` is loaded when the native view is created.
273#[derive(Clone, Debug, Default, PartialEq)]
274pub struct WebProps {
275    pub renderer: WebRenderer,
276    pub profile: WebProfile,
277    pub resources: Option<ResourceProvider>,
278    /// The view shows the provider's own site ([`web_view_resources`]): a main-frame navigation
279    /// that leaves `resources`' base is cancelled and reported (`LINK_REPORT`), like an inline
280    /// site's. `false` with a provider ([`WebView::resources`]) registers the namespace and
281    /// otherwise browses like any remote view.
282    pub resource_site: bool,
283    /// On Apple backends, report user-activated links in ordinary documents as well.
284    pub external_links: bool,
285    pub tabs: Option<TabLinkLabels>,
286    pub url: String,
287    /// The [`WebSession`] this view belongs to, or `0` for none. A non-zero id asks the backend to
288    /// hand back the session's existing native view instead of creating one, so the loaded page
289    /// survives being navigated away from (docs/webview.md).
290    pub session: u64,
291    /// Inline mode (docs/webview.md): the `/`-relative `resource/assets/` path of the bundled
292    /// site's root directory, or `""` for remote mode. The arm resolves it to its native
293    /// browsable base, loads `<base>/<inline_start>`, and cancels+reports navigations that
294    /// leave the site (`Event::Custom` with `num` = the link-report tag).
295    pub inline_root: String,
296    /// The start page within `inline_root` (`"index.html"` unless overridden), which may carry a
297    /// query or fragment (`"player.html?src=hello"`). Empty in remote mode.
298    pub inline_start: String,
299    /// Inline mode: the page may read the app's whole `resource/assets/` tree rather than only
300    /// the site's own directory ([`WebView::app_assets`]). Backends whose browsable base is the
301    /// asset tree already (Qt's qrc, Android's `file:///android_asset/`, WebView2's virtual host,
302    /// the deployed `assets/data/` on web-dom) read the same either way; it is WebKit's file-URL
303    /// read access and the GTK cache extraction that narrow to the site without it.
304    pub inline_assets: bool,
305    /// Draw no background of the view's own, so a page whose own background is transparent shows
306    /// the app behind it ([`WebView::transparent`]). A view normally paints white under the page.
307    pub transparent: bool,
308    /// Report the page's scroll position as it moves ([`WebView::scroll_state`]). Off unless the
309    /// view has a binding for it, so no view sends a report per frame of scrolling for nothing.
310    pub scroll_reports: bool,
311    /// Page zoom, desktop-site requests and page scripts, as they stand when the view is
312    /// created ([`WebView::zoom`], [`WebView::desktop_mode`], [`WebView::javascript`]). Later
313    /// changes arrive as [`WebPatch::Zoom`], [`WebPatch::DesktopMode`] and
314    /// [`WebPatch::JavaScript`].
315    pub settings: WebSettings,
316    /// Request filtering, content rule lists, user scripts and styles, and page message
317    /// handlers ([`WebView::request_filter`], [`WebView::content_rules`],
318    /// [`WebView::user_script`], [`WebView::on_script_message`]). Rule list changes arrive as
319    /// [`WebPatch::ContentRules`].
320    pub content: PageContent,
321    /// Which browser duties the app takes on, and edge-swipe navigation
322    /// ([`WebView::on_auth`], [`WebView::on_download`], [`WebView::on_renderer_gone`],
323    /// [`WebView::swipe_navigation`]).
324    pub browse: BrowseProps,
325    /// What the view tells sites it is ([`WebView::user_agent`]), fixed when the view is
326    /// created.
327    pub user_agent: UserAgent,
328}
329
330/// Per-view browsing settings: what [`WebView::zoom`], [`WebView::desktop_mode`] and
331/// [`WebView::javascript`] bind. The default is what a view does without them: 100%, the
332/// engine's choice of site layout, and page scripts on.
333#[derive(Clone, Copy, Debug, PartialEq)]
334pub struct WebSettings {
335    /// Page zoom factor, `1.0` for 100%, within [`WebSettings::ZOOM_RANGE`]. The backend keeps it
336    /// across navigations.
337    pub zoom: f64,
338    /// Ask sites for the layout they serve a desktop browser.
339    pub desktop_mode: bool,
340    /// Scripts that pages load or contain run.
341    pub javascript: bool,
342}
343
344impl WebSettings {
345    /// The zoom factors every engine accepts: QtWebEngine and WebView2 both stop at 25% and
346    /// 500%. Safari's steps run from 50% to 300%.
347    pub const ZOOM_RANGE: std::ops::RangeInclusive<f64> = 0.25..=5.0;
348
349    /// `zoom` within [`WebSettings::ZOOM_RANGE`]; `1.0` for a value that is not a positive
350    /// number.
351    pub fn clamp_zoom(zoom: f64) -> f64 {
352        if zoom.is_finite() && zoom > 0.0 {
353            zoom.clamp(*Self::ZOOM_RANGE.start(), *Self::ZOOM_RANGE.end())
354        } else {
355            1.0
356        }
357    }
358}
359
360impl Default for WebSettings {
361    fn default() -> Self {
362        WebSettings {
363            zoom: 1.0,
364            desktop_mode: false,
365            javascript: true,
366        }
367    }
368}
369
370/// A desktop browser's user agent for a Chromium engine (Android `WebView`, ArkWeb) whose user
371/// agent is `mobile`: Chrome's "Request desktop site" string, at the engine's major version.
372/// The Java (`DayWebView.desktopAgent`) and ArkTS (`desktopAgent`) arms compose this text
373/// themselves; this is the reference their format is pinned against.
374#[cfg(test)]
375pub(crate) fn desktop_user_agent(mobile: &str) -> String {
376    let major = mobile
377        .split_once("Chrome/")
378        .map(|(_, rest)| {
379            rest.chars()
380                .take_while(char::is_ascii_digit)
381                .collect::<String>()
382        })
383        .filter(|major| !major.is_empty())
384        .unwrap_or_else(|| "120".into());
385    format!(
386        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
387         Chrome/{major}.0.0.0 Safari/537.36"
388    )
389}
390
391/// A retained browsing session: the thing that outlives the view showing it.
392///
393/// Day rebuilds a page's whole subtree on every navigation, so a plain `web_view` gets a brand-new
394/// native view each visit and reloads from scratch. A session moves the *engine* out of that
395/// lifetime: the piece keeps the native web view alive against this id, and a later `web_view`
396/// bound to the same session re-attaches it with its page, scroll position, history and JavaScript
397/// context intact.
398///
399/// This is the shape Apple settled on for the same problem (`WebPage` holds the session and
400/// `WebView` renders it), and the reason it works is the same: a web view's content lives in the
401/// object and its content process, not in its attachment to a parent view.
402///
403/// Sessions are keyed by a `&'static str`, so [`WebSession::global`] is idempotent and safe to
404/// call from a page function that runs again on every navigation. There is no way to mint an
405/// anonymous one: an id that changed per build would retain a new view each visit and leak them
406/// all.
407///
408/// The retained view is never freed: one session is one live web view for the process's lifetime.
409/// Use them for pages a user returns to, not per-item.
410#[derive(Clone, Copy, PartialEq, Eq, Debug)]
411pub struct WebSession(u64);
412
413impl WebSession {
414    /// The session named `key`, created on first use. Calling this repeatedly with the same key
415    /// returns the same session.
416    pub fn global(key: &'static str) -> WebSession {
417        day_core::tls_group! {
418            static KEYS: RefCell<HashMap<&'static str, u64>> = RefCell::new(HashMap::new());
419            static NEXT: Cell<u64> = const { Cell::new(1) };
420        }
421        WebSession(KEYS.with(|m| {
422            *m.borrow_mut().entry(key).or_insert_with(|| {
423                NEXT.with(|c| {
424                    let v = c.get();
425                    c.set(v + 1);
426                    v
427                })
428            })
429        }))
430    }
431
432    /// The raw id, as it reaches a backend arm through [`WebProps::session`].
433    pub fn id(self) -> u64 {
434        self.0
435    }
436}
437
438// ---------------------------------------------------------------------------
439// Inline (app-embedded) sites (docs/webview.md). A directory under `resource/assets/` ships a
440// whole site (html/css/js/images, structure preserved, §18.5); the view loads it through the
441// backend's own local-content channel (a file URL into the bundle on Apple,
442// `file:///android_asset/` on Android, the same-origin `assets/data/` URL on web-dom), so the
443// page's relative references resolve natively. Navigations that leave the site are cancelled
444// in-view and dispatched per [`LinkPolicy`], the system browser by default.
445// ---------------------------------------------------------------------------
446
447/// The `num` the arms tag an external-link report with on the shared `Event::Custom` channel:
448/// navigation reports are `0`, eval replies are `≥ 1`, link reports are this.
449const LINK_REPORT: f64 = -1.0;
450
451/// What to do with a navigation that leaves an inline site: the answer an
452/// [`WebView::on_external_link`] handler returns. Without a handler, every external link is
453/// [`LinkPolicy::OpenSystem`].
454#[derive(Clone, Copy, Debug, PartialEq, Eq)]
455pub enum LinkPolicy {
456    /// Hand the URL to the operating system (`day`'s `open_url`): the default browser for
457    /// `https://`, the mail client for `mailto:`, whatever the OS maps the scheme to.
458    OpenSystem,
459    /// Let the navigation proceed inside the web view after all.
460    InView,
461    /// Swallow it. The handler has already done whatever the link means in-app (navigate the
462    /// day app, record it, show UI).
463    Ignore,
464}
465
466/// Split a start page into its path and the query/fragment behind it (`"player.html?src=hello"`
467/// → `("player.html", "?src=hello")`). The arms that browse a site by URL keep the page whole;
468/// the two that build a file URL from a path need the tail back, because `fileURLWithPath:`
469/// would percent-encode `?` and `#` into the file name.
470// Only the two file-URL arms call this; the test below covers it in every build.
471#[allow(
472    dead_code,
473    reason = "only the AppKit and UIKit arms load bundled pages through it"
474)]
475pub(crate) fn split_page(page: &str) -> (&str, &str) {
476    match page.find(['?', '#']) {
477        Some(i) => page.split_at(i),
478        None => (page, ""),
479    }
480}
481
482/// A bundled site ready for [`web_view_inline`], the marker [`AssetDirSiteExt::prepare_site`]
483/// resolves to (or an unchecked one via `From`-style [`IntoInlineSite`] on the raw directory).
484#[derive(Clone, Debug, PartialEq, Eq)]
485pub struct InlineSite {
486    root: String,
487}
488
489impl InlineSite {
490    /// The site root's `/`-relative path under `resource/assets/`.
491    pub fn root(&self) -> &str {
492        &self.root
493    }
494}
495
496/// Why [`AssetDirSiteExt::prepare_site`] declined the directory.
497#[derive(Clone, Debug, PartialEq, Eq)]
498pub enum PrepareError {
499    /// `<root>/index.html` is not among the bundled assets.
500    MissingIndex(String),
501    /// A backend that serves inline sites from extracted files (GTK today) failed to extract
502    /// the tree to the platform cache.
503    Extract(String),
504}
505
506impl std::fmt::Display for PrepareError {
507    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
508        match self {
509            PrepareError::MissingIndex(root) => {
510                write!(f, "no index.html under resource/assets/{root}")
511            }
512            PrepareError::Extract(e) => write!(f, "extracting the inline site: {e}"),
513        }
514    }
515}
516
517/// The future [`AssetDirSiteExt::prepare_site`] returns. Today every v1 backend serves the site
518/// from where it already lives, so this resolves on first poll; the shape is a future because
519/// backends whose engine cannot read embedded stores in place (GTK's `GResource`, HarmonyOS
520/// rawfile) will extract to the platform cache here, and a large site should not block the UI
521/// thread when they land.
522pub struct PrepareSite {
523    result: Option<Result<InlineSite, PrepareError>>,
524}
525
526impl Future for PrepareSite {
527    type Output = Result<InlineSite, PrepareError>;
528    fn poll(mut self: Pin<&mut Self>, _cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
529        match self.result.take() {
530            Some(r) => Poll::Ready(r),
531            // Fused: polled again after completion (which day's task runner never does).
532            None => Poll::Pending,
533        }
534    }
535}
536
537/// `res::assets::<dir>.prepare_site()`: validate and prepare a bundled directory as an inline
538/// site (docs/webview.md).
539pub trait AssetDirSiteExt {
540    fn prepare_site(self) -> PrepareSite;
541}
542
543impl AssetDirSiteExt for day_core::AssetDir {
544    fn prepare_site(self) -> PrepareSite {
545        let root = self.as_str().trim_matches('/').to_string();
546        // web-dom has no resource opener (the browser fetches the served tree directly), so the
547        // index probe is skipped there and a missing index surfaces as the frame's own 404.
548        #[cfg(target_arch = "wasm32")]
549        let result = Ok(InlineSite { root });
550        #[cfg(not(target_arch = "wasm32"))]
551        let result = {
552            let index = day_spec::AssetName::dynamic(format!("{root}/index.html"));
553            match day_spec::resource(index) {
554                Some(_) => prepare_backend(root),
555                None => Err(PrepareError::MissingIndex(root)),
556            }
557        };
558        PrepareSite {
559            result: Some(result),
560        }
561    }
562}
563
564/// The per-backend half of `prepare_site`: where a backend whose engine cannot read the
565/// embedded store in place gets the site onto loose files ahead of the view (docs/webview.md).
566#[cfg(not(target_arch = "wasm32"))]
567#[allow(
568    clippy::unnecessary_wraps,
569    reason = "the Linux GTK arm returns an error when extraction fails"
570)]
571fn prepare_backend(root: String) -> Result<InlineSite, PrepareError> {
572    // GTK: the assets live in a GResource blob WebKitGTK cannot browse; extract to the user
573    // cache now so `make` finds it warm. The lazy `web_view_inline(dir)` route extracts at
574    // realize instead.
575    #[cfg(all(feature = "gtk", not(target_os = "macos"), not(windows)))]
576    if let Err(e) = gtk_impl::extract_site(&root) {
577        return Err(PrepareError::Extract(e));
578    }
579    Ok(InlineSite { root })
580}
581
582/// What [`web_view_inline`] accepts: a prepared [`InlineSite`], or the raw generated
583/// `res::assets::…` directory constant for the lazy path (no ahead-of-time index check; a
584/// missing page surfaces in the view itself).
585pub trait IntoInlineSite {
586    fn into_inline_site(self) -> InlineSite;
587}
588
589impl IntoInlineSite for InlineSite {
590    fn into_inline_site(self) -> InlineSite {
591        self
592    }
593}
594
595impl IntoInlineSite for day_core::AssetDir {
596    fn into_inline_site(self) -> InlineSite {
597        InlineSite {
598            root: self.as_str().trim_matches('/').to_string(),
599        }
600    }
601}
602
603/// Whether this backend can show an inline (app-embedded) site. A separate axis from
604/// [`support`]: web-dom's iframe is `Emulated` for remote browsing but fully capable here:
605/// the bundled site is same-origin, so loading, relative navigation and the link policy all
606/// work. `Unsupported` means no renderer is compiled for this target.
607pub fn inline_support() -> day_spec::Support {
608    if cfg!(any(
609        all(
610            any(feature = "appkit", feature = "gtk"),
611            target_os = "macos"
612        ),
613        all(feature = "uikit", target_os = "ios"),
614        all(feature = "material", target_os = "android"),
615        // QWebEngine reads qrc assets.
616        feature = "qt",
617        // WebView2 browses the exe-relative assets tree through a virtual-host mapping
618        // (degrades to the URL label when the WebView2 Runtime is absent, like `support()`).
619        all(feature = "xaml", windows),
620        // GTK hosts extract the bundled site before navigation.
621        all(feature = "gtk", not(target_os = "macos")),
622        // ArkWeb browses the rawfile-staged tree through `resource://rawfile/` URLs.
623        all(feature = "arkui", target_env = "ohos"),
624        // The deployed `assets/data/` tree is same-origin with the host page: the browser
625        // resolves the site natively and the shim's click hook polices leaving links.
626        all(feature = "dom", target_arch = "wasm32"),
627    )) {
628        day_spec::Support::Native
629    } else {
630        day_spec::Support::Unsupported
631    }
632}
633
634/// Native cache-bypassing reload. Cross-origin iframe hosts cannot force cache policy.
635pub fn force_reload_support() -> day_spec::Support {
636    if cfg!(all(feature = "dom", target_arch = "wasm32")) {
637        day_spec::Support::Unsupported
638    } else {
639        support()
640    }
641}
642
643/// Whether [`WebView::zoom`] scales the page. `Native` uses the engine's own page zoom (text
644/// zoom on Android and ArkWeb, see docs/webview.md). `Emulated` sets CSS `zoom` on each page
645/// instead: web-dom's iframe can only do that for same-origin pages, and the WinUI WebView2
646/// control does not expose the engine's zoom factor.
647pub fn zoom_support() -> day_spec::Support {
648    if cfg!(any(
649        all(feature = "dom", target_arch = "wasm32"),
650        all(feature = "winui", windows)
651    )) {
652        day_spec::Support::Emulated
653    } else {
654        support()
655    }
656}
657
658/// Whether [`WebView::desktop_mode`] is honored. Engines on phones and tablets switch to a
659/// desktop user agent and layout; desktop engines already present themselves as desktop
660/// browsers and accept the setting as it is. web-dom's iframe cannot change what the host
661/// browser sends.
662pub fn desktop_mode_support() -> day_spec::Support {
663    if cfg!(all(feature = "dom", target_arch = "wasm32")) {
664        day_spec::Support::Unsupported
665    } else {
666        support()
667    }
668}
669
670/// Whether [`WebView::javascript`] can stop page scripts. `Emulated` on web-dom, which sandboxes
671/// the iframe without `allow-scripts` and so also blocks the app's own evaluation in the frame.
672pub fn javascript_support() -> day_spec::Support {
673    if cfg!(all(feature = "dom", target_arch = "wasm32")) {
674        day_spec::Support::Emulated
675    } else {
676        support()
677    }
678}
679
680/// Sparse imperative commands sent to the native view after creation.
681#[derive(Clone, Debug, PartialEq)]
682pub enum WebPatch {
683    /// Load a URL (from `.go()`).
684    Load(String),
685    /// History back / forward.
686    Back,
687    Forward,
688    /// Stop the in-flight load (the demo's "cancel").
689    Stop,
690    /// Reload the current page.
691    Reload,
692    /// Reload while bypassing the engine resource cache (never clears cookies or site data).
693    ForceReload,
694    /// Evaluate `script` (already wrapped by [`wrap_script`]) and report the result back as an
695    /// `Event::Custom` whose `num` is `req`. See docs/webview-eval.md.
696    Eval {
697        req: u64,
698        script: String,
699    },
700    /// Report the page state now, even when it has not changed since the last report. Sent once,
701    /// a turn after the view is built, so a node re-attaching a retained session learns where
702    /// the settled page stands. A report made while the view was being created would reach a
703    /// node whose handler is not installed yet and be lost. Renderers that never retain a view
704    /// ignore it: a fresh view reports as its first load proceeds.
705    ReportState,
706    /// Zoom the page to this factor ([`WebView::zoom`]), already within
707    /// [`WebSettings::ZOOM_RANGE`]. Applies at once and to later pages.
708    Zoom(f64),
709    /// Ask for desktop (`true`) or the engine's default layout ([`WebView::desktop_mode`]). The
710    /// backend reloads the current page so the site can answer.
711    DesktopMode(bool),
712    /// Let page scripts run, or stop them ([`WebView::javascript`]). The backend reloads the
713    /// current page, since a page's scripts cannot be turned on or off while it runs.
714    JavaScript(bool),
715    /// Replace the view's content rule lists ([`WebView::content_rules`]). The backend compiles
716    /// what it has not compiled before, off the UI thread, and swaps the lists once all are ready.
717    ContentRules(Vec<ContentRuleList>),
718    /// Answer the page message the backend reported under `id` (`SCRIPT_MESSAGE`): the
719    /// handler's reply, or `None` for none. The page's `dayMessage` promise resolves with it.
720    ScriptReply {
721        id: u64,
722        reply: Option<String>,
723    },
724    /// Answer the camera and microphone request the backend reported under `id`
725    /// (`MEDIA_REPORT`) with what the app allows ([`WebView::on_media_request`]).
726    MediaDecision {
727        id: u64,
728        allow: bool,
729    },
730    /// Answer the question the backend reported under `id` (`PAGE_PROMPT`): a script dialog, a
731    /// sign-in, a file choice or a download's destination. `answer` is the JSON of the
732    /// crate's `browsing::Answer`.
733    PromptAnswer {
734        id: u64,
735        answer: String,
736    },
737}
738
739// ---------------------------------------------------------------------------
740// JavaScript evaluation (docs/webview-eval.md)
741// ---------------------------------------------------------------------------
742
743/// Field separator inside an evaluation reply. A raw 0x1F can never appear inside JSON text
744/// (`JSON.stringify` escapes control characters as the six ASCII chars `\u001f`), so splitting on
745/// it is unambiguous and needs no JSON parser on the Rust side.
746const SEP: char = '\u{1f}';
747
748/// Why an evaluation did not produce a value.
749#[derive(Clone, Debug, PartialEq, Eq)]
750pub enum EvalError {
751    /// This backend has no engine to evaluate in (web-dom's `<iframe>`, or no renderer at all).
752    Unsupported,
753    /// The script threw. `name`/`message` come from the caught exception; a cyclic value that
754    /// `JSON.stringify` refuses arrives here too, as a `TypeError`.
755    Threw { name: String, message: String },
756    /// The web view was never realized, or went away before the reply arrived.
757    ViewGone,
758    /// The engine ran but the reply did not decode; the raw payload is included.
759    Engine(String),
760}
761
762impl std::fmt::Display for EvalError {
763    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
764        match self {
765            EvalError::Unsupported => write!(f, "javascript evaluation is unsupported here"),
766            EvalError::Threw { name, message } => write!(f, "{name}: {message}"),
767            EvalError::ViewGone => write!(f, "the web view is gone"),
768            EvalError::Engine(raw) => write!(f, "undecodable reply: {raw}"),
769        }
770    }
771}
772
773/// Escape `s` into a JavaScript string literal, quotes included.
774///
775/// U+2028 and U+2029 get named escapes because they are literal line terminators in JS source and
776/// would end the string; everything below U+0020 goes to `\uXXXX` because a raw control character
777/// is not legal inside a literal either.
778fn js_string_literal(s: &str) -> String {
779    use std::fmt::Write as _;
780    let mut out = String::with_capacity(s.len() + 2);
781    out.push('"');
782    for c in s.chars() {
783        match c {
784            '"' => out.push_str("\\\""),
785            '\\' => out.push_str("\\\\"),
786            '\n' => out.push_str("\\n"),
787            '\r' => out.push_str("\\r"),
788            '\t' => out.push_str("\\t"),
789            '\u{2028}' => out.push_str("\\u2028"),
790            '\u{2029}' => out.push_str("\\u2029"),
791            c if (c as u32) < 0x20 => {
792                let _ = write!(out, "\\u{:04x}", c as u32);
793            }
794            c => out.push(c),
795        }
796    }
797    out.push('"');
798    out
799}
800
801/// Wrap a user script so every backend reports errors the same way.
802///
803/// Qt and Android have no error channel at all (a throw, a syntax error and a `null` result all
804/// arrive identically), so the channel is built in JavaScript instead, and every backend then
805/// behaves like the ones with real errors. The reply is `1␟<json>` or `0␟<name>␟<message>`.
806///
807/// The script is passed to `eval` as a **string literal** rather than spliced in as source. That
808/// costs one escape pass and buys three things splicing cannot:
809///
810/// - **Syntax errors become catchable.** Spliced in, the wrapper and the script compile as one
811///   unit, so a bad script kills the wrapper too and the backend reports its uninformative
812///   "no result". `eval` compiles at run time, inside the `try`.
813/// - **Statements work.** `throw new Error("x")` and `var a = 1; a + 1` are statements, so
814///   `v = (…)` around them is itself a syntax error. `eval` takes a program and yields its
815///   completion value, which is the behavior a console user expects.
816/// - **No lexical hazards.** A trailing `//` comment or an unbalanced brace in the script cannot
817///   reach the wrapper's own tokens.
818///
819/// The cost is that a page whose Content-Security-Policy omits `unsafe-eval` refuses to run it;
820/// that surfaces as a caught `EvalError`, which is at least legible.
821///
822/// Two `try` blocks, not one: the second catches `JSON.stringify` refusing a cyclic value, which is
823/// a different failure from the script throwing.
824fn wrap_script(script: &str) -> String {
825    let src = js_string_literal(script);
826    // A page that refuses `eval` refuses every string, so a harmless one is tried first: its
827    // failure is the refusal, reported under a name no script throws ([`EVAL_REFUSED`]) and
828    // retried in the second form. The script itself then reaches `eval` exactly as written
829    // (a leading directive, its completion value and its own names are all its own), and
830    // whatever it throws, even an `EvalError`, is its error from its one run.
831    format!(
832        "(function(){{var v;\
833         try{{eval(\"0\");}}\
834         catch(e){{return \"0\\u001f{EVAL_REFUSED}\\u001f\"+((e&&e.message)||String(e));}}\
835         try{{v=eval({src});}}\
836         catch(e){{return \"0\\u001f\"+((e&&e.name)||\"Error\")+\"\\u001f\"+((e&&e.message)||String(e));}}\
837         try{{var s=JSON.stringify(v);return \"1\\u001f\"+(s===undefined?\"null\":s);}}\
838         catch(e){{return \"0\\u001f\"+((e&&e.name)||\"TypeError\")+\"\\u001f\"+((e&&e.message)||String(e));}}\
839         }})()"
840    )
841}
842
843/// The error name [`wrap_script`] reports when the page refused `eval` before the script ran.
844const EVAL_REFUSED: &str = "DayEvalRefused";
845
846/// Build a reply an arm can send when the engine failed rather than the script: a dead content
847/// process, a missing web view, a reply of the wrong type. Shaped like the wrapper's own error arm
848/// so [`decode`] needs only one format.
849// Used by the per-backend arms, each of which is `#[cfg]`-gated to one toolkit, so on any single
850// build all but one caller is compiled out, and on a build whose backend has no eval arm yet there
851// are none. Which callers exist is a build-configuration accident, not a sign this is unused.
852pub(crate) fn engine_error(name: &str, message: &str) -> String {
853    format!("0{SEP}{name}{SEP}{message}")
854}
855
856/// Decode one reply produced by [`wrap_script`]. `undefined` and values `JSON.stringify` drops
857/// (a function, a symbol) both arrive as `null`; the wrapper normalizes them so the payload is
858/// always valid JSON.
859/// The wrapper for a page that refuses `eval`: the script is part of the wrapper's own source,
860/// as the expression it then has to be. A page's Content Security Policy without `unsafe-eval`,
861/// or with Trusted Types required, stops `eval(text)` inside the page even though the engine
862/// runs the wrapper itself; such a page answers [`wrap_script`]'s form with [`EVAL_REFUSED`],
863/// and the request is sent once more in this form ([`resolve`]). A script that is a list of
864/// statements cannot be written this way and fails to parse, which is the error the caller
865/// then sees. The line breaks keep a trailing `//` comment from swallowing the wrapper.
866fn wrap_expression(script: &str) -> String {
867    format!(
868        "(function(){{var v;\
869         try{{v=(\n{script}\n);}}\
870         catch(e){{return \"0\\u001f\"+((e&&e.name)||\"Error\")+\"\\u001f\"+((e&&e.message)||String(e));}}\
871         try{{var s=JSON.stringify(v);return \"1\\u001f\"+(s===undefined?\"null\":s);}}\
872         catch(e){{return \"0\\u001f\"+((e&&e.name)||\"TypeError\")+\"\\u001f\"+((e&&e.message)||String(e));}}\
873         }})()"
874    )
875}
876
877fn decode(payload: &str) -> Result<String, EvalError> {
878    match payload.split_once(SEP) {
879        Some(("1", json)) => Ok(json.to_string()),
880        Some(("0", rest)) => {
881            let (name, message) = rest.split_once(SEP).unwrap_or(("Error", rest));
882            Err(EvalError::Threw {
883                name: name.to_string(),
884                message: message.to_string(),
885            })
886        }
887        _ => Err(EvalError::Engine(payload.to_string())),
888    }
889}
890
891struct EvalShared {
892    result: RefCell<Option<Result<String, EvalError>>>,
893    waker: RefCell<Option<std::task::Waker>>,
894}
895
896day_core::tls_group! {
897    /// Request ids start at 1 so 0 stays free for the URL report, which shares this channel.
898    static PRIVATE_BLOCKED_NODES: RefCell<std::collections::HashSet<RNode>> = RefCell::new(std::collections::HashSet::new());
899    static REQUEST_NODES: RefCell<HashMap<u64, RNode>> = RefCell::new(HashMap::new());
900    static NEXT_REQ: Cell<u64> = const { Cell::new(1) };
901    static PENDING: RefCell<HashMap<u64, Rc<EvalShared>>> = RefCell::new(HashMap::new());
902    /// Callback-shaped requests (the dayscript `web_eval` step, via day-core's
903    /// `register_piece_operation`): same req space and reply channel as the futures above,
904    /// different completion shape.
905    static PENDING_CB: RefCell<HashMap<u64, day_core::PieceOperationDone>> =
906        RefCell::new(HashMap::new());
907    /// Each request's second form ([`wrap_expression`]), kept until its first answer.
908    static FALLBACKS: RefCell<HashMap<u64, String>> = RefCell::new(HashMap::new());
909}
910
911/// Deliver a reply to whichever request is waiting on `req`: an awaited [`EvalFuture`] or a
912/// `web_eval` step callback. A reply for a dropped future finds nothing pending and is
913/// discarded.
914fn resolve(req: u64, payload: &str) {
915    // A page that refuses `eval` gets the request once more with the script as source.
916    let fallback = FALLBACKS.with(|f| f.borrow_mut().remove(&req));
917    let refused =
918        matches!(decode(payload), Err(EvalError::Threw { ref name, .. }) if name == EVAL_REFUSED);
919    if refused
920        && let Some(script) = fallback
921        && let Some(node) = REQUEST_NODES.with(|p| p.borrow().get(&req).copied())
922    {
923        renderer::send_patch(node, WebPatch::Eval { req, script });
924        return;
925    }
926    // Refused, with no second form left: the caller hears it under the engine's own name.
927    let renamed;
928    let payload = if refused {
929        renamed = payload.replacen(EVAL_REFUSED, "EvalError", 1);
930        renamed.as_str()
931    } else {
932        payload
933    };
934    REQUEST_NODES.with(|p| p.borrow_mut().remove(&req));
935    if let Some(done) = PENDING_CB.with(|p| p.borrow_mut().remove(&req)) {
936        done(decode(payload).map_err(|e| e.to_string()));
937        return;
938    }
939    let Some(shared) = PENDING.with(|p| p.borrow_mut().remove(&req)) else {
940        return;
941    };
942    *shared.result.borrow_mut() = Some(decode(payload));
943    if let Some(waker) = shared.waker.borrow_mut().take() {
944        waker.wake();
945    }
946}
947
948/// Register this piece's evaluator with day-core, for the dayscript `web_eval` step
949/// (docs/webview-eval.md). Called from the constructors; idempotent, and an app that never
950/// builds a web view never registers, which the step then reports. The provider applies
951/// the same [`wrap_script`] envelope and reply channel as [`JsHandle::eval`]; on a backend
952/// whose arm answers `eval_support() != Native` it fails the callback immediately rather
953/// than letting the step wait out its retry window.
954fn register_script_eval() {
955    let handler: day_core::PieceOperationFn = std::rc::Rc::new(|node, script, done| {
956        if PRIVATE_BLOCKED_NODES.with(|nodes| nodes.borrow().contains(&node))
957            || (!renderer::surface::owns(node) && eval_support() != day_spec::Support::Native)
958        {
959            done(Err(EvalError::Unsupported.to_string()));
960            return;
961        }
962        let req = NEXT_REQ.with(|c| {
963            let v = c.get();
964            c.set(v + 1);
965            v
966        });
967        let wrapped = wrap_script(script);
968        REQUEST_NODES.with(|p| p.borrow_mut().insert(req, node));
969        FALLBACKS.with(|f| f.borrow_mut().insert(req, wrap_expression(script)));
970        PENDING_CB.with(|p| p.borrow_mut().insert(req, done));
971        renderer::send_patch(
972            node,
973            WebPatch::Eval {
974                req,
975                script: wrapped,
976            },
977        );
978    });
979    day_core::register_piece_operation(KIND, "day.webview.eval", handler.clone());
980    day_core::register_piece_operation(
981        renderer::surface::KIND,
982        "day.webview.eval",
983        Rc::new(move |node, script, done| {
984            if renderer::surface::owns(node) {
985                handler(node, script, done);
986            } else {
987                done(Err(EvalError::Unsupported.to_string()));
988            }
989        }),
990    );
991}
992
993/// A native snapshot of the current browser page and session history.
994/// Query after navigation or periodically while visible; no script or network request runs.
995#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Deserialize)]
996pub struct NavigationState {
997    pub url: String,
998    pub title: String,
999    pub can_go_back: bool,
1000    pub can_go_forward: bool,
1001    pub loading: bool,
1002}
1003
1004/// The live state of the page a view shows, kept current by the engine's own notifications
1005/// ([`WebView::page_state`]). Unlike [`JsHandle::navigation_state`] nothing is polled: each
1006/// backend reports a change when its engine announces one.
1007#[derive(Clone, Debug, Default, PartialEq)]
1008pub struct PageState {
1009    /// The engine's current URL, including same-document changes (`history.pushState`, a
1010    /// fragment). A provider-served page reports its provider URL.
1011    pub url: String,
1012    /// The document title, or empty before the page sets one.
1013    pub title: String,
1014    /// A main-frame load is in progress.
1015    pub loading: bool,
1016    /// Estimated load progress from `0.0` to `1.0`, in hundredths. It reaches `1.0` when a load
1017    /// finishes. Engines without a progress estimate step through fixed points (docs/webview.md).
1018    pub progress: f64,
1019    /// Session history has an entry behind the current one.
1020    pub can_go_back: bool,
1021    /// Session history has an entry ahead of the current one.
1022    pub can_go_forward: bool,
1023}
1024
1025/// The `num` that tags a page-state report on the shared `Event::Custom` channel.
1026const PAGE_STATE_REPORT: f64 = -5.0;
1027
1028/// Encode a page-state report: `<loading><back><forward>␟<progress>␟<url>␟<title>`, each flag a
1029/// `0`/`1` digit and the progress a decimal fraction. The title goes last so that a title holding
1030/// the separator still decodes; a URL never holds a raw control character. Java, C++ and ArkTS
1031/// compose the same text, so the format stays this plain.
1032// The Rust arms call this; a build whose arm composes the text natively compiles it out.
1033pub(crate) fn encode_page_state(state: &PageState) -> String {
1034    let flag = |b: bool| if b { '1' } else { '0' };
1035    format!(
1036        "{}{}{}{SEP}{:.2}{SEP}{}{SEP}{}",
1037        flag(state.loading),
1038        flag(state.can_go_back),
1039        flag(state.can_go_forward),
1040        state.progress.clamp(0.0, 1.0),
1041        state.url,
1042        state.title
1043    )
1044}
1045
1046/// A page-state report as an event, for the arms that emit from Rust.
1047pub(crate) fn page_state_event(state: &PageState) -> Event {
1048    Event::Custom {
1049        tag: "webview:state",
1050        num: PAGE_STATE_REPORT,
1051        text: encode_page_state(state),
1052    }
1053}
1054
1055/// Where the page is scrolled, kept current as it moves ([`WebView::scroll_state`]): what a
1056/// browser's chrome reads to slide its bars away while the user scrolls down a page, as Safari
1057/// and Chrome do, and back when they scroll up or reach either end.
1058#[derive(Clone, Copy, Debug, Default, PartialEq)]
1059pub struct ScrollState {
1060    /// How far the page is scrolled down, in points from its top: `0` at the top. It can go
1061    /// below `0` or past the end while the platform's scroll bounces.
1062    pub offset: f64,
1063    /// The page's full height, in points.
1064    pub content_height: f64,
1065    /// The height of the part of the page the view shows, in points.
1066    pub viewport_height: f64,
1067    /// The user's finger is on the page (a drag, not a fling or a programmatic scroll).
1068    pub dragging: bool,
1069}
1070
1071impl ScrollState {
1072    /// The page is at its top, or bounced above it.
1073    pub fn at_top(&self) -> bool {
1074        self.offset <= 0.5
1075    }
1076
1077    /// The page is scrolled to its end, or bounced past it.
1078    pub fn at_bottom(&self) -> bool {
1079        self.content_height > self.viewport_height
1080            && self.offset + self.viewport_height >= self.content_height - 0.5
1081    }
1082}
1083
1084/// The `num` that tags a scroll report on the shared `Event::Custom` channel.
1085const SCROLL_REPORT: f64 = -6.0;
1086
1087/// The `num` that tags a blocked-load report: a JSON array of [`BlockedLoad`]s (or one).
1088const BLOCKED_REPORT: f64 = -7.0;
1089/// The `num` that tags a page message: a JSON [`content::MessageReport`].
1090const SCRIPT_MESSAGE: f64 = -8.0;
1091/// The `num` that tags a content rule list that failed to compile: a JSON [`ContentRulesError`].
1092const CONTENT_RULES_ERROR: f64 = -9.0;
1093/// The `num` that tags a camera or microphone request: a JSON [`content::MediaReport`].
1094const MEDIA_REPORT: f64 = -10.0;
1095
1096/// A blocked-load report as an event, for arms that report through the event channel.
1097pub(crate) fn blocked_event(loads: &[BlockedLoad]) -> Event {
1098    Event::Custom {
1099        tag: "webview:blocked",
1100        num: BLOCKED_REPORT,
1101        text: serde_json::to_string(loads).unwrap_or_default(),
1102    }
1103}
1104
1105/// A page message as an event: its reply goes back as [`WebPatch::ScriptReply`] with `id`.
1106pub(crate) fn script_message_event(id: u64, message: ScriptMessage) -> Event {
1107    Event::Custom {
1108        tag: "webview:message",
1109        num: SCRIPT_MESSAGE,
1110        text: serde_json::to_string(&content::MessageReport { id, message }).unwrap_or_default(),
1111    }
1112}
1113
1114/// A content rule list compile failure as an event.
1115pub(crate) fn content_rules_error_event(id: &str, message: &str) -> Event {
1116    Event::Custom {
1117        tag: "webview:rules",
1118        num: CONTENT_RULES_ERROR,
1119        text: serde_json::to_string(&ContentRulesError {
1120            id: id.to_owned(),
1121            message: message.to_owned(),
1122        })
1123        .unwrap_or_default(),
1124    }
1125}
1126
1127/// A camera or microphone request as an event: the answer goes back as
1128/// [`WebPatch::MediaDecision`] with `id`.
1129pub(crate) fn media_event(id: u64, request: MediaRequest) -> Event {
1130    Event::Custom {
1131        tag: "webview:media",
1132        num: MEDIA_REPORT,
1133        text: serde_json::to_string(&content::MediaReport { id, request }).unwrap_or_default(),
1134    }
1135}
1136
1137/// Encode a scroll report: `<offset>␟<content height>␟<viewport height>␟<dragging>`, in points
1138/// rounded to tenths, the flag a `0`/`1` digit. Java composes the same text.
1139#[allow(dead_code, reason = "only the UIKit arm reports its scroll position")]
1140pub(crate) fn encode_scroll_state(state: &ScrollState) -> String {
1141    format!(
1142        "{:.1}{SEP}{:.1}{SEP}{:.1}{SEP}{}",
1143        state.offset,
1144        state.content_height,
1145        state.viewport_height,
1146        if state.dragging { '1' } else { '0' }
1147    )
1148}
1149
1150/// A scroll report as an event, for the arms that emit from Rust.
1151#[allow(dead_code, reason = "only the UIKit arm reports its scroll position")]
1152pub(crate) fn scroll_state_event(state: &ScrollState) -> Event {
1153    Event::Custom {
1154        tag: "webview:scroll",
1155        num: SCROLL_REPORT,
1156        text: encode_scroll_state(state),
1157    }
1158}
1159
1160fn decode_scroll_state(text: &str) -> Option<ScrollState> {
1161    let mut fields = text.split(SEP);
1162    let mut number = || -> Option<f64> {
1163        let v: f64 = fields.next()?.trim().parse().ok()?;
1164        v.is_finite().then_some(v)
1165    };
1166    let (offset, content_height, viewport_height) = (number()?, number()?, number()?);
1167    let dragging = match fields.next()? {
1168        "1" => true,
1169        "0" => false,
1170        _ => return None,
1171    };
1172    Some(ScrollState {
1173        offset,
1174        content_height,
1175        viewport_height,
1176        dragging,
1177    })
1178}
1179
1180/// Decode [`encode_page_state`]'s text. Progress is rounded to hundredths, so a stream of tiny
1181/// estimate changes collapses into equal states that the front-end does not re-publish.
1182fn decode_page_state(text: &str) -> Option<PageState> {
1183    let mut fields = text.splitn(4, SEP);
1184    let flags = fields.next()?.as_bytes();
1185    let progress: f64 = fields.next()?.trim().parse().ok()?;
1186    let url = fields.next()?.to_owned();
1187    let title = fields.next().unwrap_or_default().to_owned();
1188    if flags.len() != 3 || !progress.is_finite() {
1189        return None;
1190    }
1191    Some(PageState {
1192        url,
1193        title,
1194        loading: flags[0] == b'1',
1195        progress: (progress.clamp(0.0, 1.0) * 100.0).round() / 100.0,
1196        can_go_back: flags[1] == b'1',
1197        can_go_forward: flags[2] == b'1',
1198    })
1199}
1200
1201/// Decode standard base64 (with or without padding; whitespace ignored), as every engine's
1202/// snapshot reply encodes its PNG. `None` on any other character.
1203fn base64_decode(text: &str) -> Option<Vec<u8>> {
1204    let mut out = Vec::with_capacity(text.len() / 4 * 3);
1205    let (mut acc, mut bits) = (0u32, 0u32);
1206    for c in text.bytes() {
1207        let v = match c {
1208            b'A'..=b'Z' => c - b'A',
1209            b'a'..=b'z' => c - b'a' + 26,
1210            b'0'..=b'9' => c - b'0' + 52,
1211            b'+' | b'-' => 62,
1212            b'/' | b'_' => 63,
1213            b'=' | b'\r' | b'\n' | b' ' => continue,
1214            _ => return None,
1215        };
1216        acc = (acc << 6) | u32::from(v);
1217        bits += 6;
1218        if bits >= 8 {
1219            bits -= 8;
1220            out.push((acc >> bits) as u8);
1221            acc &= (1 << bits) - 1;
1222        }
1223    }
1224    Some(out)
1225}
1226
1227/// A handle for running JavaScript in a web view. `Copy`, like `Trigger`, so it can be captured by
1228/// several closures. Bind it with [`WebView::js`]; evaluating before the view is realized fails
1229/// with [`EvalError::ViewGone`].
1230#[derive(Clone, Copy)]
1231pub struct JsHandle {
1232    node: Signal<Option<RNode>>,
1233    blocked: Signal<bool>,
1234    renderer: Signal<WebRenderer>,
1235}
1236
1237impl Default for JsHandle {
1238    fn default() -> Self {
1239        Self::new()
1240    }
1241}
1242
1243impl JsHandle {
1244    /// Engine currently attached to this handle.
1245    pub fn renderer(&self) -> WebRenderer {
1246        self.renderer.get_untracked()
1247    }
1248    #[track_caller]
1249    pub fn new() -> Self {
1250        JsHandle {
1251            node: Signal::new(None),
1252            blocked: Signal::new(false),
1253            renderer: Signal::new(WebRenderer::default()),
1254        }
1255    }
1256
1257    fn data_request(&self, operation: &str, url: &str, cookie: &str) -> EvalFuture {
1258        self.data_request_value(
1259            &serde_json::json!({"operation":operation,"url":url,"cookie":cookie}),
1260        )
1261    }
1262    fn data_request_value(&self, request: &serde_json::Value) -> EvalFuture {
1263        let mut future = self.eval("");
1264        future.script = Some(format!("{DATA_REQUEST}{request}"));
1265        // A request to the backend is no page script and has no second form.
1266        future.fallback = None;
1267        future
1268    }
1269    /// Capture the visible page as PNG bytes, at most `max_width_px` physical pixels wide (the
1270    /// height follows the view's aspect ratio). Meant for thumbnails such as a tab overview.
1271    ///
1272    /// The capture is the engine's own rendering of what the view shows, not a re-render of the
1273    /// document. A view that is not on screen (a background tab) may capture blank or fail with
1274    /// [`EvalError::Threw`], depending on the engine. Engines without a capture API (ArkWeb,
1275    /// web-dom's iframe) fail with [`EvalError::Unsupported`]; see docs/webview.md.
1276    ///
1277    /// # Errors
1278    ///
1279    /// Returns [`EvalError::Unsupported`] on an engine without a capture API, [`EvalError::Threw`]
1280    /// when the engine cannot capture the view, and [`EvalError::Engine`] when its reply is not PNG
1281    /// data.
1282    pub async fn snapshot(&self, max_width_px: u32) -> Result<Vec<u8>, EvalError> {
1283        let reply = self
1284            .data_request_value(&serde_json::json!({"operation":"snapshot","width":max_width_px}))
1285            .await
1286            .map_err(|error| match error {
1287                EvalError::Threw { name, .. } if name == "Unsupported" => EvalError::Unsupported,
1288                error => error,
1289            })?;
1290        let encoded: String =
1291            serde_json::from_str(&reply).map_err(|_| EvalError::Engine(reply.clone()))?;
1292        base64_decode(&encoded).ok_or(EvalError::Engine(reply))
1293    }
1294    /// Read URL, title, loading status and actual native history availability.
1295    /// Emulated iframe hosts return Unsupported rather than guessing browser history.
1296    ///
1297    /// # Errors
1298    ///
1299    /// Returns [`EvalError::Unsupported`] on an emulated iframe host, or the error of the request
1300    /// to the backend.
1301    pub async fn navigation_state(&self) -> Result<NavigationState, EvalError> {
1302        let reply = self.data_request("navigation", "", "").await?;
1303        serde_json::from_str(&reply).map_err(|_| EvalError::Unsupported)
1304    }
1305    /// Read cookies (including `HttpOnly`) eligible for this URL from the bound view's profile.
1306    /// Treat the returned header as a credential; never log it or send it to a different origin.
1307    ///
1308    /// # Errors
1309    ///
1310    /// Returns [`EvalError::Unsupported`] when `url` is not an HTTP or HTTPS URL or the backend
1311    /// cannot read cookies, or the error of the request to the backend.
1312    pub async fn cookie_header(&self, url: &str) -> Result<String, EvalError> {
1313        if !url::Url::parse(url).is_ok_and(|url| matches!(url.scheme(), "http" | "https")) {
1314            return Err(EvalError::Unsupported);
1315        }
1316        let reply = self.data_request("cookies", url, "").await?;
1317        serde_json::from_str(&reply).map_err(|_| EvalError::Unsupported)
1318    }
1319    /// Store an HTTP Set-Cookie response in the browser's own jar.
1320    pub fn set_cookie(&self, url: &str, cookie: &str) -> EvalFuture {
1321        let future = self.data_request("set-cookie", url, cookie);
1322        if !cookie_source_valid(url, cookie) {
1323            *future.shared.result.borrow_mut() = Some(Err(EvalError::Unsupported));
1324        }
1325        future
1326    }
1327    /// Clear all browser data in this profile. Use a dedicated site profile to forget one site.
1328    /// Await completion before reusing its cookies or allowing another request to that site.
1329    pub fn clear_data(&self) -> EvalFuture {
1330        self.data_request("clear", "", "")
1331    }
1332
1333    /// Evaluate `script` and resolve with its result as JSON text.
1334    ///
1335    /// Nothing is dispatched until the future is polled. Dropping it deregisters the request, so a
1336    /// late reply is discarded, but the script keeps running: no backend can cancel one.
1337    pub fn eval(&self, script: impl AsRef<str>) -> EvalFuture {
1338        EvalFuture {
1339            req: NEXT_REQ.with(|c| {
1340                let v = c.get();
1341                c.set(v + 1);
1342                v
1343            }),
1344            node: self.node,
1345            blocked: self.blocked,
1346            script: Some(wrap_script(script.as_ref())),
1347            fallback: Some(wrap_expression(script.as_ref())),
1348            shared: Rc::new(EvalShared {
1349                result: RefCell::new(None),
1350                waker: RefCell::new(None),
1351            }),
1352            sent: false,
1353        }
1354    }
1355}
1356
1357/// The pending result of [`JsHandle::eval`].
1358pub struct EvalFuture {
1359    blocked: Signal<bool>,
1360    req: u64,
1361    node: Signal<Option<RNode>>,
1362    script: Option<String>,
1363    /// The script in [`wrap_expression`]'s form, for a page that refuses `eval`.
1364    fallback: Option<String>,
1365    shared: Rc<EvalShared>,
1366    sent: bool,
1367}
1368
1369impl Future for EvalFuture {
1370    type Output = Result<String, EvalError>;
1371
1372    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1373        if let Some(result) = self.shared.result.borrow_mut().take() {
1374            return Poll::Ready(result);
1375        }
1376        let Some(blocked) = day_reactive::untrack(|| self.blocked.try_get()) else {
1377            return Poll::Ready(Err(EvalError::ViewGone));
1378        };
1379        if blocked {
1380            return Poll::Ready(Err(EvalError::Unsupported));
1381        }
1382        // Dispatch on first poll, not at construction, so an eval that is never awaited never runs.
1383        if !self.sent {
1384            self.sent = true;
1385            let Some(node) = day_reactive::untrack(|| self.node.try_get()).flatten() else {
1386                return Poll::Ready(Err(EvalError::ViewGone));
1387            };
1388            if !renderer::surface::owns(node) && eval_support() != day_spec::Support::Native {
1389                return Poll::Ready(Err(EvalError::Unsupported));
1390            }
1391            let (req, script) = (self.req, self.script.take().unwrap_or_default());
1392            REQUEST_NODES.with(|p| p.borrow_mut().insert(req, node));
1393            if let Some(fallback) = self.fallback.take() {
1394                FALLBACKS.with(|f| f.borrow_mut().insert(req, fallback));
1395            }
1396            PENDING.with(|p| p.borrow_mut().insert(req, self.shared.clone()));
1397            renderer::send_patch(node, WebPatch::Eval { req, script });
1398            // An arm that fails a request without reaching the engine replies from inside that
1399            // patch — before this poll has a waker to wake, so `resolve` found none and left the
1400            // answer here. Take it now: nothing will ever wake this future on its behalf.
1401            // (The XAML arm does exactly this while WebView2 is still starting up.)
1402            if let Some(result) = self.shared.result.borrow_mut().take() {
1403                return Poll::Ready(result);
1404            }
1405        }
1406        *self.shared.waker.borrow_mut() = Some(cx.waker().clone());
1407        Poll::Pending
1408    }
1409}
1410
1411impl Drop for EvalFuture {
1412    fn drop(&mut self) {
1413        REQUEST_NODES.with(|p| p.borrow_mut().remove(&self.req));
1414        PENDING.with(|p| p.borrow_mut().remove(&self.req));
1415        FALLBACKS.with(|f| f.borrow_mut().remove(&self.req));
1416    }
1417}
1418
1419/// Whether this backend can evaluate JavaScript. A separate axis from [`support`]: web-dom loads
1420/// pages but can evaluate only same-origin frames.
1421pub fn eval_support() -> day_spec::Support {
1422    if cfg!(any(
1423        all(
1424            any(feature = "appkit", feature = "gtk"),
1425            target_os = "macos"
1426        ),
1427        all(feature = "uikit", target_os = "ios"),
1428        feature = "qt",
1429        all(feature = "dom", target_arch = "wasm32"),
1430        all(feature = "gtk", not(target_os = "macos")),
1431        all(feature = "xaml", target_os = "windows"),
1432        // `evaluateJavascript` in DayWebView.evalJs, with the outer-JSON unquote and the
1433        // null/empty→engine-error mapping (docs/webview-eval.md).
1434        all(feature = "material", target_os = "android"),
1435        // `runJavaScript` in the ArkTS component, replying on `pieceEvent`'s num slot.
1436        all(feature = "arkui", target_env = "ohos"),
1437    )) {
1438        day_spec::Support::Native
1439    } else {
1440        // No renderer with a JavaScript engine on this platform.
1441        day_spec::Support::Unsupported
1442    }
1443}
1444
1445/// A native web view bound to `url`. Attach command triggers with `.go()/.back()/.forward()/
1446/// .stop()/.reload()`; fire them (`Trigger::notify`) from buttons.
1447/// A request from a link, modifier click, or a new-window navigation. The source
1448/// remains alive; the application creates a separately owned browsing context.
1449#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
1450pub struct NewTabRequest {
1451    pub url: String,
1452    pub background: bool,
1453}
1454/// App-localized labels for native link menus.
1455#[derive(Clone, Debug, PartialEq, Eq)]
1456pub struct TabLinkLabels {
1457    pub foreground: String,
1458    pub background: String,
1459}
1460const NEW_TAB_REPORT: f64 = -4.0;
1461fn new_tab_event(url: String, background: bool) -> Event {
1462    Event::Custom {
1463        tag: "webview:new-tab",
1464        num: NEW_TAB_REPORT,
1465        text: serde_json::to_string(&NewTabRequest { url, background }).unwrap_or_default(),
1466    }
1467}
1468
1469// A document-start fallback for engines that don't expose pointer modifiers in
1470// navigation requests. It carries only link intent; normal navigation remains native.
1471#[cfg(all(target_os = "ios", feature = "uikit"))]
1472const TAB_MODIFIER_SCRIPT: &str = r"(() => {
1473  const click = e => {
1474    const a = e.composedPath().find(n => n?.tagName === 'A' && n.href);
1475    if (!a || !(e.metaKey || e.ctrlKey || e.button === 1)) return;
1476    e.preventDefault(); e.stopImmediatePropagation();
1477    location.href = 'day-tab://open?url=' + encodeURIComponent(a.href) + '&background=' + (e.shiftKey ? '0' : '1');
1478  };
1479  addEventListener('click', click, true); addEventListener('auxclick', click, true);
1480})();";
1481#[cfg(all(target_os = "ios", feature = "uikit"))]
1482fn tab_scheme_request(input: &str) -> Option<NewTabRequest> {
1483    let url = url::Url::parse(input).ok()?;
1484    if url.scheme() != "day-tab" {
1485        return None;
1486    }
1487    let pairs: HashMap<_, _> = url.query_pairs().into_owned().collect();
1488    Some(NewTabRequest {
1489        url: pairs.get("url")?.clone(),
1490        background: pairs.get("background").is_some_and(|v| v == "1"),
1491    })
1492}
1493
1494/// What `.on_link(…)` stores: decides what a navigation to a URL should do.
1495type LinkDecider = Rc<dyn Fn(&str) -> LinkPolicy>;
1496type NewTabHandler = (TabLinkLabels, Rc<dyn Fn(&NewTabRequest)>);
1497type MessageHandler = Rc<dyn Fn(ScriptMessage) -> Option<String>>;
1498type RulesErrorHandler = Rc<dyn Fn(&ContentRulesError)>;
1499type MediaHandler = Rc<dyn Fn(&MediaRequest) -> bool>;
1500
1501#[must_use]
1502pub struct WebView {
1503    renderer: WebRenderer,
1504    profile: WebProfile,
1505    resources: Option<ResourceProvider>,
1506    resource_site: bool,
1507    page_state: Option<AnyBinding<PageState>>,
1508    scroll_state: Option<AnyBinding<ScrollState>>,
1509    url: AnyBinding<String>,
1510    go: Option<Trigger>,
1511    back: Option<Trigger>,
1512    forward: Option<Trigger>,
1513    stop: Option<Trigger>,
1514    reload: Option<Trigger>,
1515    force_reload: Option<Trigger>,
1516    js: Option<JsHandle>,
1517    session: Option<WebSession>,
1518    inline: Option<InlineSite>,
1519    inline_start: String,
1520    inline_assets: bool,
1521    transparent: bool,
1522    on_link: Option<LinkDecider>,
1523    tabs: Option<NewTabHandler>,
1524    on_load: Option<Rc<dyn Fn()>>,
1525    zoom: Option<Reactive<f64>>,
1526    desktop_mode: Option<Reactive<bool>>,
1527    javascript: Option<Reactive<bool>>,
1528    request_filter: Option<Arc<dyn RequestFilter>>,
1529    content_rules: Option<Reactive<Vec<ContentRuleList>>>,
1530    user_scripts: Vec<UserScript>,
1531    user_styles: Vec<Arc<str>>,
1532    messages: Vec<(String, MessageHandler)>,
1533    on_blocked: Option<content::BlockedCallback>,
1534    on_rules_error: Option<RulesErrorHandler>,
1535    on_media: Option<MediaHandler>,
1536    on_app_link: Option<LinkDecider>,
1537    browse: browsing::Handlers,
1538    swipe_navigation: bool,
1539    user_agent: UserAgent,
1540}
1541
1542/// `web_view(url)`: a native web view showing `url`. The initial value loads on creation; call
1543/// `.go(trigger)` and fire the trigger to (re)load whatever `url` currently holds.
1544pub fn web_view(url: impl Binding<String>) -> WebView {
1545    // Self-register the web renderer. wasm has no link-time renderer slice, and a constructor is
1546    // the earliest point the piece is known to be in play, always before its node is realized.
1547    #[cfg(all(feature = "dom", target_arch = "wasm32"))]
1548    dom_impl::register();
1549    // Same earliest-point reasoning for the dayscript `web_eval` registration: a step can only
1550    // target a webview some constructor built, so registration here is always in time.
1551    register_script_eval();
1552    WebView {
1553        renderer: WebRenderer::default(),
1554        profile: WebProfile::default(),
1555        url: AnyBinding::new(url),
1556        go: None,
1557        back: None,
1558        forward: None,
1559        stop: None,
1560        reload: None,
1561        force_reload: None,
1562        js: None,
1563        session: None,
1564        inline: None,
1565        inline_start: String::new(),
1566        inline_assets: false,
1567        transparent: false,
1568        on_link: None,
1569        tabs: None,
1570        on_load: None,
1571        resources: None,
1572        resource_site: false,
1573        page_state: None,
1574        scroll_state: None,
1575        zoom: None,
1576        desktop_mode: None,
1577        javascript: None,
1578        request_filter: None,
1579        content_rules: None,
1580        user_scripts: Vec::new(),
1581        user_styles: Vec::new(),
1582        messages: Vec::new(),
1583        on_blocked: None,
1584        on_rules_error: None,
1585        on_media: None,
1586        on_app_link: None,
1587        browse: browsing::Handlers::default(),
1588        swipe_navigation: false,
1589        user_agent: UserAgent::Engine,
1590    }
1591}
1592
1593/// `web_view_inline(site)`: a web view showing a site bundled inside the app
1594/// (docs/webview.md): a directory under `resource/assets/`, shipped whole. Relative references
1595/// within the site resolve natively; navigations that leave it are cancelled and dispatched
1596/// per [`LinkPolicy`], the system browser unless [`WebView::on_external_link`] says otherwise.
1597///
1598/// Takes a prepared [`InlineSite`] (`res::assets::<dir>.prepare_site().await?`, the checked
1599/// route) or the raw `res::assets::<dir>` constant (lazy; a missing page surfaces in the view).
1600/// Gate on [`inline_support`].
1601pub fn web_view_inline(site: impl IntoInlineSite) -> WebView {
1602    let mut v = web_view(Signal::new(String::new()));
1603    v.inline = Some(site.into_inline_site());
1604    v.inline_start = "index.html".into();
1605    v
1606}
1607
1608/// Display an application-provided resource tree. Relative references are resolved by the engine.
1609pub fn web_view_resources(provider: ResourceProvider, page: &str) -> WebView {
1610    let mut view = web_view(Signal::new(provider.url(page)));
1611    view.resources = Some(provider);
1612    view.resource_site = true;
1613    view
1614}
1615
1616#[day_pieces::builder(WebViewBuilder)]
1617impl WebView {
1618    /// Select an engine for this context, failing instead of falling back silently.
1619    /// Rebuild the piece at its current URL to switch an existing page's renderer.
1620    ///
1621    /// # Errors
1622    ///
1623    /// Returns [`RendererUnavailable`] when this build does not include `renderer`.
1624    pub fn renderer(mut self, renderer: WebRenderer) -> Result<Self, RendererUnavailable> {
1625        if !renderer.available() {
1626            return Err(RendererUnavailable(renderer));
1627        }
1628        self.renderer = renderer;
1629        Ok(self)
1630    }
1631    /// Share cookies, local storage, cache and engine site data with other views using this profile.
1632    pub fn profile(mut self, profile: WebProfile) -> Self {
1633        self.profile = profile;
1634        self
1635    }
1636    /// Bind the actual page URL, including native navigation reports, to application state.
1637    /// Useful for an address bar on bundled/resource views. Notify `.go()` to load the value.
1638    pub fn url_binding(mut self, url: impl Binding<String>) -> Self {
1639        let url = AnyBinding::new(url);
1640        if url.get_untracked().is_empty() {
1641            url.set(self.url.get_untracked());
1642        }
1643        self.url = url;
1644        self
1645    }
1646    /// Keep `state` current with the page's URL, title, load progress and history, as the
1647    /// engine reports them (see [`PageState`]). The view writes the binding; the app reads it to
1648    /// drive a title, a progress line, or Back/Forward buttons.
1649    ///
1650    /// Reports are pushed by the engine's own notifications, not polled, and those arriving
1651    /// within one frame (a burst of progress estimates) are coalesced into one write. The
1652    /// binding is only written when the state changed. web-dom's iframe reports only the URL and
1653    /// title of same-origin frames after each load.
1654    pub fn page_state(mut self, state: impl Binding<PageState>) -> Self {
1655        self.page_state = Some(AnyBinding::new(state));
1656        self
1657    }
1658    /// Keep `state` current with where the page is scrolled (see [`ScrollState`]): what a
1659    /// browser's chrome reads to slide its bars away as the user scrolls down, the way Safari
1660    /// and Chrome do on a phone. Reports arriving within one frame are coalesced into one write.
1661    ///
1662    /// Reported on iOS (the web view's scroll view) and Android (the view's scroll listener),
1663    /// the platforms whose browsers hide their bars; elsewhere the binding keeps its value.
1664    pub fn scroll_state(mut self, state: impl Binding<ScrollState>) -> Self {
1665        self.scroll_state = Some(AnyBinding::new(state));
1666        self
1667    }
1668    /// Serve `provider`'s namespace in this view, which otherwise browses like any remote view:
1669    /// it navigates anywhere, reports URLs, opens new tabs, and keeps its history across
1670    /// provider pages and remote ones. Pages are reached at [`ResourceProvider::url`] (or under
1671    /// [`ResourceProvider::base_url`]); a query reaches the handler as
1672    /// [`ResourceRequest::query`].
1673    ///
1674    /// [`web_view_resources`] is the other shape: a view confined to the provider's site, whose
1675    /// links out of it go through [`WebView::on_external_link`]. A provider given here replaces
1676    /// any provider the view already had.
1677    pub fn resources(mut self, provider: ResourceProvider) -> Self {
1678        self.resources = Some(provider);
1679        self
1680    }
1681    /// Called on the UI thread after the backend reports a completed navigation. Useful for
1682    /// applying the latest presentation state through `JsHandle`, including same-URL reloads.
1683    /// Available on native backends that report navigation; not on emulated iframe hosts.
1684    pub fn on_load(mut self, callback: impl Fn() + 'static) -> Self {
1685        self.on_load = Some(Rc::new(callback));
1686        self
1687    }
1688    /// Load the current value of the bound `url` whenever `trigger` fires.
1689    pub fn go(mut self, trigger: Trigger) -> Self {
1690        self.go = Some(trigger);
1691        self
1692    }
1693    /// Navigate back in history whenever `trigger` fires.
1694    pub fn back(mut self, trigger: Trigger) -> Self {
1695        self.back = Some(trigger);
1696        self
1697    }
1698    /// Navigate forward in history whenever `trigger` fires.
1699    pub fn forward(mut self, trigger: Trigger) -> Self {
1700        self.forward = Some(trigger);
1701        self
1702    }
1703    /// Stop the current load whenever `trigger` fires.
1704    pub fn stop(mut self, trigger: Trigger) -> Self {
1705        self.stop = Some(trigger);
1706        self
1707    }
1708    /// Reload the current page whenever `trigger` fires.
1709    pub fn reload(mut self, trigger: Trigger) -> Self {
1710        self.reload = Some(trigger);
1711        self
1712    }
1713    /// Reload from the server, bypassing cached resources. Check [`force_reload_support`].
1714    pub fn force_reload(mut self, trigger: Trigger) -> Self {
1715        self.force_reload = Some(trigger);
1716        self
1717    }
1718    /// Bind a [`JsHandle`] so `handle.eval(…)` runs in this view (docs/webview-eval.md).
1719    pub fn js(mut self, handle: JsHandle) -> Self {
1720        self.js = Some(handle);
1721        self
1722    }
1723    /// Show a retained [`WebSession`], so the loaded page survives navigating away and back.
1724    pub fn session(mut self, session: WebSession) -> Self {
1725        self.session = Some(session);
1726        self
1727    }
1728    /// Inline mode only: the page within the site to open first, instead of `index.html`. A
1729    /// query or fragment is part of the page (`"player.html?src=hello"`), and the site reads it
1730    /// back through `location.search` / `location.hash` as it would on a server.
1731    pub fn start_page(mut self, page: impl Into<String>) -> Self {
1732        self.inline_start = page.into();
1733        self
1734    }
1735    /// Inline mode only: let the site read the app's whole `resource/assets/` tree, not just its
1736    /// own directory.
1737    ///
1738    /// A self-contained site needs nothing here. Ask for it when the page's job is to show the
1739    /// app's own files — a player, a viewer, a renderer — because those files live in the app's
1740    /// asset namespace and the site's relative URLs have to reach them
1741    /// (`day-piece-lottie`'s player is this: one page, any of the app's animations).
1742    pub fn app_assets(mut self) -> Self {
1743        self.inline_assets = true;
1744        self
1745    }
1746    /// Draw no background of the view's own: where the page's own background is transparent, the
1747    /// app shows through, the way an image with an alpha channel sits on whatever is behind it.
1748    ///
1749    /// What a web view is for here is content that belongs to the app's own surface (an
1750    /// animation player, a rendered diagram, a badge), where the view's usual white sheet reads as
1751    /// a hole in the window. A page that sets a background of its own still draws it. Every arm
1752    /// honors it (docs/webview.md "A transparent view").
1753    pub fn transparent(mut self) -> Self {
1754        self.transparent = true;
1755        self
1756    }
1757    /// Zoom the page by `factor`, `1.0` being 100%: a constant, a signal or a closure. The engine
1758    /// keeps the factor as the view navigates, the way a browser's zoom control does, and a
1759    /// change applies to the page on screen at once. Factors are clamped to
1760    /// [`WebSettings::ZOOM_RANGE`]. Check [`zoom_support`]: Android and ArkWeb scale text, and
1761    /// web-dom zooms same-origin pages only (docs/webview.md).
1762    pub fn zoom<M>(mut self, factor: impl IntoReactive<f64, M>) -> Self {
1763        self.zoom = Some(factor.into_reactive());
1764        self
1765    }
1766    /// Ask sites for the layout they serve a desktop browser, like Safari's "Request Desktop
1767    /// Website" and Chrome's "Desktop site". When the value changes, the view reloads its page so
1768    /// the site can answer. `false` leaves the engine's choice, which is already the desktop
1769    /// layout on a Mac, an iPad and every desktop toolkit. Check [`desktop_mode_support`].
1770    pub fn desktop_mode<M>(mut self, desktop: impl IntoReactive<bool, M>) -> Self {
1771        self.desktop_mode = Some(desktop.into_reactive());
1772        self
1773    }
1774    /// Let pages run their scripts (`true`, the default) or stop them. When the value changes,
1775    /// the view reloads its page, because a page cannot lose or gain its scripts while it runs.
1776    ///
1777    /// The app's own evaluation ([`JsHandle::eval`]) keeps working with page scripts off on the
1778    /// WebKit, WebKitGTK, Qt, WebView2 and ArkWeb engines. Android `WebView` and web-dom have no
1779    /// such split: there, evaluation fails until scripts are on again. Check
1780    /// [`javascript_support`] and docs/webview.md.
1781    pub fn javascript<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
1782        self.javascript = Some(enabled.into_reactive());
1783        self
1784    }
1785    /// Ask `filter` about every request the view's pages make, before it leaves the device
1786    /// (docs/webview.md, "Content blocking and page scripts"). A [`RequestDecision::Block`]
1787    /// fails the request; [`WebView::on_blocked`] hears about it.
1788    ///
1789    /// Runs on the engine's own thread: a `WebView` worker on Android, the UI thread on WebView2
1790    /// and Qt, ArkWeb's IO thread. Check [`request_filter_support`]: WebKit engines have no
1791    /// per-request hook and take [`WebView::content_rules`] instead.
1792    pub fn request_filter(mut self, filter: Arc<dyn RequestFilter>) -> Self {
1793        self.request_filter = Some(filter);
1794        self
1795    }
1796    /// Hear about the requests [`WebView::request_filter`] blocked, on the UI thread, in
1797    /// batches: at most one call every 100 ms, holding every load blocked since the last one.
1798    pub fn on_blocked(mut self, f: impl Fn(&[BlockedLoad]) + 'static) -> Self {
1799        self.on_blocked = Some(Rc::new(f));
1800        self
1801    }
1802    /// Block and hide content with WebKit content rule lists: a constant, a signal or a
1803    /// closure. Each list is compiled once, off the UI thread, and kept compiled across launches
1804    /// under its id and version; a change swaps the view's lists once the new ones are ready.
1805    /// A view built with lists holds its first page until they are attached. Check
1806    /// [`content_rules_support`]: only the WebKit engines apply them.
1807    pub fn content_rules<M>(mut self, lists: impl IntoReactive<Vec<ContentRuleList>, M>) -> Self {
1808        self.content_rules = Some(lists.into_reactive());
1809        self
1810    }
1811    /// Hear about a content rule list that failed to compile (it is also logged). The other
1812    /// lists still apply.
1813    pub fn on_content_rules_error(mut self, f: impl Fn(&ContentRulesError) + 'static) -> Self {
1814        self.on_rules_error = Some(Rc::new(f));
1815        self
1816    }
1817    /// Run `script` in every page the view loads, in the page's own JavaScript world. Call it
1818    /// again for more; they run in the order added. Check [`user_script_support`].
1819    pub fn user_script(mut self, script: UserScript) -> Self {
1820        self.user_scripts.push(script);
1821        self
1822    }
1823    /// Apply `css` to every page and frame the view loads, as a user style sheet where the engine
1824    /// has one (WebKitGTK) and as a `<style>` element added at document start elsewhere.
1825    pub fn user_style(mut self, css: impl Into<Arc<str>>) -> Self {
1826        self.user_styles.push(css.into());
1827        self
1828    }
1829    /// Answer page messages posted to `name`: a page calls `window.dayMessage(name, text)` and
1830    /// gets a promise of the handler's reply (`null` for `None`). The handler runs on the UI
1831    /// thread. Any frame can post, third-party ones included: treat [`ScriptMessage::payload`]
1832    /// as untrusted input. Check [`script_message_support`].
1833    pub fn on_script_message(
1834        mut self,
1835        name: impl Into<String>,
1836        handler: impl Fn(ScriptMessage) -> Option<String> + 'static,
1837    ) -> Self {
1838        let name = name.into();
1839        self.messages.retain(|(known, _)| *known != name);
1840        self.messages.push((name, Rc::new(handler)));
1841        self
1842    }
1843    /// Decide whether a page may use the camera or microphone (`getUserMedia`). Android only
1844    /// asks this: without it, a page gets what the app itself may use, the system asking the
1845    /// user once for a permission the app declares but does not hold yet. The other engines
1846    /// ask the user themselves.
1847    pub fn on_media_request(mut self, f: impl Fn(&MediaRequest) -> bool + 'static) -> Self {
1848        self.on_media = Some(Rc::new(f));
1849        self
1850    }
1851    /// Decide what happens to a navigation that leaves an inline/resource site. On Apple
1852    /// backends, also opts ordinary documents into reporting user-activated links and new
1853    /// windows; initial loads, subframes and same-document fragments stay in view. Runs on the
1854    /// main thread with the target URL; without it every external link is
1855    /// [`LinkPolicy::OpenSystem`]. The closure may do arbitrary in-app work (navigate the day
1856    /// app, log) and return [`LinkPolicy::Ignore`].
1857    /// Handle a request for a separate tab without replacing the source document.
1858    /// Labels must be localized by the application. Background requests preserve focus.
1859    pub fn on_new_tab<M1, M2>(
1860        mut self,
1861        foreground_label: impl IntoText<M1>,
1862        background_label: impl IntoText<M2>,
1863        f: impl Fn(&NewTabRequest) + 'static,
1864    ) -> Self {
1865        self.tabs = Some((
1866            TabLinkLabels {
1867                foreground: foreground_label.into_text().initial(),
1868                background: background_label.into_text().initial(),
1869            },
1870            Rc::new(f),
1871        ));
1872        self
1873    }
1874    pub fn on_external_link(mut self, f: impl Fn(&str) -> LinkPolicy + 'static) -> Self {
1875        self.on_link = Some(Rc::new(f));
1876        self
1877    }
1878    /// Decide what happens to a navigation whose address another program opens: `mailto:`,
1879    /// `tel:`, an app's own scheme, Android's `intent:`. The view never loads such an address;
1880    /// without this (and without [`WebView::on_external_link`]) each goes to the system, which
1881    /// is [`LinkPolicy::OpenSystem`]. A browser asks the user here before an unfamiliar scheme
1882    /// leaves for another app. [`LinkPolicy::InView`] is treated as [`LinkPolicy::Ignore`].
1883    pub fn on_app_link(mut self, f: impl Fn(&str) -> LinkPolicy + 'static) -> Self {
1884        self.on_app_link = Some(Rc::new(f));
1885        self
1886    }
1887    /// Answer a page's `alert()`, `confirm()` and `prompt()`. The page's script waits for the
1888    /// responder. Without this the view presents Day's own dialogs, titled with the site that
1889    /// asked.
1890    pub fn on_dialog(mut self, f: impl Fn(DialogRequest, DialogResponder) + 'static) -> Self {
1891        self.browse.dialog = Some(Rc::new(f));
1892        self
1893    }
1894    /// Answer a server's or proxy's request for a name and password (HTTP Basic, Digest, NTLM).
1895    /// Without this the sign-in is canceled and the server's "unauthorized" page loads.
1896    pub fn on_auth(mut self, f: impl Fn(AuthRequest, AuthResponder) + 'static) -> Self {
1897        self.browse.auth = Some(Rc::new(f));
1898        self
1899    }
1900    /// Take the files the engine offers to save rather than show. The handler names where a
1901    /// file goes ([`DownloadResponder::save_to`]) or declines it; without a handler nothing is
1902    /// downloaded. See [`download_support`].
1903    pub fn on_download(mut self, f: impl Fn(DownloadRequest, DownloadResponder) + 'static) -> Self {
1904        self.browse.download = Some(Rc::new(f));
1905        self
1906    }
1907    /// Hear that a page did not load: no connection, no such server, an untrusted certificate.
1908    /// The view is left on whatever the engine shows for a failed load, so a browser covers it
1909    /// with its own error page until the next load starts.
1910    pub fn on_load_error(mut self, f: impl Fn(&LoadError) + 'static) -> Self {
1911        self.browse.load_error = Some(Rc::new(f));
1912        self
1913    }
1914    /// Hear that the process running this view's page is gone. On Android the view is dead from
1915    /// then on and ignores every command: build a new one in its place. On Apple platforms the
1916    /// view survives and a reload brings the page back; without this handler WebKit views
1917    /// reload themselves.
1918    pub fn on_renderer_gone(mut self, f: impl Fn(&RendererGone) + 'static) -> Self {
1919        self.browse.renderer_gone = Some(Rc::new(f));
1920        self
1921    }
1922    /// What the view tells sites it is: the engine's own string (the default), the platform
1923    /// browser's ([`UserAgent::Browser`], which a browser wants), or a string of the app's.
1924    /// It is read when the view is created; build a new view to change it. WebKit and Android
1925    /// honor it, and a view in [`WebView::desktop_mode`] sends the desktop string instead.
1926    pub fn user_agent(mut self, user_agent: UserAgent) -> Self {
1927        self.user_agent = user_agent;
1928        self
1929    }
1930    /// Swiping in from a screen edge goes back and forward through the view's history (WebKit).
1931    /// Off unless asked for, since an app's own navigation may own those edges.
1932    pub fn swipe_navigation(mut self, on: bool) -> Self {
1933        self.swipe_navigation = on;
1934        self
1935    }
1936}
1937
1938/// Hand an address no engine loads to the program that opens it: `mailto:`, `tel:`, an app's
1939/// own scheme. Android's `intent:` addresses name an app, a package to install it from and a
1940/// web page to fall back to; the backend starts whichever applies, and the fallback page comes
1941/// back here for the caller to load. This is what [`LinkPolicy::OpenSystem`] does, for an app
1942/// that answers [`WebView::on_app_link`] later than the handler's return (after asking the
1943/// user).
1944pub fn open_app_link(url: &str) -> Option<String> {
1945    #[cfg(all(target_os = "android", feature = "material"))]
1946    if url.starts_with("intent:") {
1947        return android_impl::open_intent(url);
1948    }
1949    day_core::open_url(url);
1950    None
1951}
1952
1953/// [`LinkPolicy::OpenSystem`]: hand `url` to the system, and load an `intent:` address's
1954/// fallback page in the view through `send`.
1955fn open_system(url: &str, send: &impl Fn(WebPatch)) {
1956    if let Some(fallback) = open_app_link(url) {
1957        send(WebPatch::Load(fallback));
1958    }
1959}
1960
1961/// What this backend realizes. `Native` is a real embedded browser engine with the full command
1962/// set; `Emulated` loads pages but cannot drive history or report navigation back (web-dom's
1963/// `<iframe>`, see docs/webview.md); `Unsupported` renders day's placeholder leaf.
1964///
1965/// Gate history controls on this: `.back()`, `.forward()` and `.stop()` are no-ops below `Native`,
1966/// so an app should disable those buttons rather than offer ones that do nothing.
1967pub fn support() -> day_spec::Support {
1968    // Browser frames retain remote-navigation restrictions. Native hosts supply an engine.
1969    if cfg!(all(feature = "dom", target_arch = "wasm32")) {
1970        day_spec::Support::Emulated
1971    } else if cfg!(any(
1972        all(
1973            any(feature = "appkit", feature = "gtk"),
1974            target_os = "macos"
1975        ),
1976        all(feature = "uikit", target_os = "ios"),
1977        all(feature = "material", target_os = "android"),
1978        all(feature = "gtk", not(target_os = "macos")),
1979        feature = "qt",
1980        all(feature = "xaml", windows),
1981        all(feature = "arkui", target_env = "ohos"),
1982    )) {
1983        day_spec::Support::Native
1984    } else {
1985        day_spec::Support::Unsupported
1986    }
1987}
1988
1989/// The front-end half of [`WebView::page_state`] and [`WebView::scroll_state`]: the latest
1990/// unpublished report and the timer that publishes it.
1991struct LatestSink<T: Clone + PartialEq + 'static> {
1992    binding: AnyBinding<T>,
1993    pending: RefCell<Option<T>>,
1994    flush: Cell<Option<day_core::TaskHandle>>,
1995}
1996
1997impl<T: Clone + PartialEq + 'static> LatestSink<T> {
1998    /// A sink writing `binding`, whose pending publish is cancelled with the current scope.
1999    fn new(binding: AnyBinding<T>) -> Rc<Self> {
2000        let sink = Rc::new(LatestSink {
2001            binding,
2002            pending: RefCell::new(None),
2003            flush: Cell::new(None),
2004        });
2005        let cleanup = sink.clone();
2006        day_reactive::Scope::current().on_cleanup(move || {
2007            if let Some(flush) = cleanup.flush.take() {
2008                flush.abort();
2009            }
2010        });
2011        sink
2012    }
2013
2014    /// Keep `state` as the latest report and publish it on the next frame, unless a publish is
2015    /// already due: the reports arriving before it are superseded, never queued.
2016    fn report(self: &Rc<Self>, state: T) {
2017        *self.pending.borrow_mut() = Some(state);
2018        if let Some(flush) = self.flush.get()
2019            && !flush.is_finished()
2020        {
2021            return;
2022        }
2023        let sink = self.clone();
2024        self.flush.set(Some(day_core::task(async move {
2025            day_core::sleep(16).await;
2026            if let Some(state) = sink.pending.borrow_mut().take()
2027                && sink.binding.get_untracked() != state
2028            {
2029                sink.binding.set(state);
2030            }
2031        })));
2032    }
2033}
2034
2035impl Piece for WebView {
2036    fn build(self, cx: &mut BuildCx) -> RNode {
2037        let WebView {
2038            renderer,
2039            profile,
2040            url,
2041            go,
2042            back,
2043            forward,
2044            stop,
2045            reload,
2046            force_reload,
2047            js,
2048            session,
2049            inline,
2050            inline_start,
2051            inline_assets,
2052            transparent,
2053            on_link,
2054            tabs,
2055            on_load,
2056            mut resources,
2057            resource_site,
2058            page_state,
2059            scroll_state,
2060            zoom,
2061            desktop_mode,
2062            javascript,
2063            request_filter,
2064            content_rules,
2065            user_scripts,
2066            user_styles,
2067            messages,
2068            on_blocked,
2069            on_rules_error,
2070            on_media,
2071            on_app_link,
2072            browse,
2073            swipe_navigation,
2074            user_agent,
2075        } = self;
2076        let settings = WebSettings {
2077            zoom: zoom
2078                .as_ref()
2079                .map_or(1.0, |zoom| WebSettings::clamp_zoom(zoom.get_untracked())),
2080            desktop_mode: desktop_mode
2081                .as_ref()
2082                .is_some_and(day_pieces::Reactive::get_untracked),
2083            javascript: javascript
2084                .as_ref()
2085                .is_none_or(day_pieces::Reactive::get_untracked),
2086        };
2087        // Blocked loads reach `on_blocked` through this sink, from whichever thread the engine
2088        // filters on (`RequestHooks::decide`) or from the event channel (`BLOCKED_REPORT`).
2089        let blocked_sink = on_blocked
2090            .as_ref()
2091            .map(|_| Arc::new(content::BlockedSink::default()));
2092        let content = PageContent {
2093            // A provider's own site and a bundled site are the app's: the filter never sees them.
2094            // A view that only borrows a provider for some pages filters those like any other.
2095            requests: request_filter.map(|filter| {
2096                RequestHooks::new(
2097                    filter,
2098                    blocked_sink.clone(),
2099                    resource_site || inline.is_some(),
2100                )
2101            }),
2102            rules: content_rules
2103                .as_ref()
2104                .map_or_default(day_pieces::Reactive::get_untracked),
2105            scripts: user_scripts,
2106            styles: user_styles,
2107            messages: messages.iter().map(|(name, _)| name.clone()).collect(),
2108            media_handler: on_media.is_some(),
2109        };
2110        let session_id = session.map_or(0, WebSession::id);
2111        let session_id = if session_id == 0 || profile == WebProfile::default() {
2112            session_id
2113        } else {
2114            profile.storage_key().bytes().fold(session_id, |h, b| {
2115                (h ^ u64::from(b)).wrapping_mul(1_099_511_628_211)
2116            })
2117        };
2118        let mut initial_url = url.get_untracked();
2119        if let (Some(_session), Some(provider)) = (session, &resources) {
2120            // A retained engine still needs its original namespace while detached. Like the
2121            // retained page itself, the first provider wins until process shutdown.
2122            day_core::tls_group! {
2123                static SESSION_RESOURCES: RefCell<HashMap<(WebRenderer, u64), (ResourceProvider, String)>> = RefCell::new(HashMap::new());
2124            }
2125            let retained = SESSION_RESOURCES.with(|m| {
2126                m.borrow_mut()
2127                    .entry((renderer, session_id))
2128                    .or_insert_with(|| (provider.clone(), initial_url.clone()))
2129                    .clone()
2130            });
2131            resources = Some(retained.0);
2132            initial_url = retained.1;
2133            url.set(initial_url.clone());
2134        }
2135        let blocked_private = (profile.private
2136            && renderer.private_browsing_support() == day_spec::Support::Unsupported)
2137            || (renderer != WebRenderer::WebView
2138                && renderer.profile_support() == day_spec::Support::Unsupported
2139                && profile != WebProfile::default());
2140        let initial = WebProps {
2141            renderer,
2142            profile,
2143            resources: if blocked_private {
2144                None
2145            } else {
2146                resources.clone()
2147            },
2148            resource_site: resource_site && resources.is_some() && !blocked_private,
2149            external_links: on_link.is_some(),
2150            tabs: tabs.as_ref().map(|(labels, _)| labels.clone()),
2151            url: if blocked_private {
2152                "about:blank".into()
2153            } else {
2154                initial_url
2155            },
2156            session: session_id,
2157            inline_root: if blocked_private {
2158                String::new()
2159            } else {
2160                inline.as_ref().map_or_default(|s| s.root.clone())
2161            },
2162            inline_start: if inline.is_some() {
2163                inline_start
2164            } else {
2165                String::new()
2166            },
2167            inline_assets: inline.is_some() && inline_assets,
2168            transparent,
2169            scroll_reports: scroll_state.is_some(),
2170            settings,
2171            content: if blocked_private {
2172                PageContent::default()
2173            } else {
2174                content
2175            },
2176            browse: browse.props(swipe_navigation),
2177            user_agent,
2178        };
2179        // A web view has no intrinsic size; it fills whatever space its container offers.
2180        let surface = renderer::surface::get(renderer);
2181        let flex = Flex {
2182            grow_w: true,
2183            grow_h: true,
2184            ..Default::default()
2185        };
2186        let node = if surface.is_some() {
2187            cx.leaf(
2188                renderer::surface::KIND,
2189                &day_spec::props::CanvasProps::default(),
2190                flex,
2191            )
2192        } else {
2193            cx.leaf(KIND, &initial, flex)
2194        };
2195
2196        if let Some(host) = surface {
2197            renderer::surface::attach(host, cx, node, &initial);
2198        }
2199
2200        day_reactive::Scope::current().on_cleanup(move || {
2201            let requests = REQUEST_NODES.with(|p| {
2202                p.borrow()
2203                    .iter()
2204                    .filter_map(|(req, owner)| (*owner == node).then_some(*req))
2205                    .collect::<Vec<_>>()
2206            });
2207            for req in requests {
2208                REQUEST_NODES.with(|p| p.borrow_mut().remove(&req));
2209                if let Some(done) = PENDING_CB.with(|p| p.borrow_mut().remove(&req)) {
2210                    done(Err(EvalError::ViewGone.to_string()));
2211                }
2212                if let Some(shared) = PENDING.with(|p| p.borrow_mut().remove(&req)) {
2213                    *shared.result.borrow_mut() = Some(Err(EvalError::ViewGone));
2214                    if let Some(waker) = shared.waker.borrow_mut().take() {
2215                        waker.wake();
2216                    }
2217                }
2218            }
2219        });
2220        if blocked_private {
2221            PRIVATE_BLOCKED_NODES.with(|nodes| nodes.borrow_mut().insert(node));
2222            day_reactive::Scope::current().on_cleanup(move || {
2223                PRIVATE_BLOCKED_NODES.with(|nodes| nodes.borrow_mut().remove(&node));
2224            });
2225        }
2226        let send = move |patch: WebPatch| {
2227            if blocked_private {
2228                if let WebPatch::Eval { req, .. } = patch {
2229                    resolve(
2230                        req,
2231                        &engine_error("Unsupported", "private browsing unavailable"),
2232                    );
2233                }
2234                return;
2235            }
2236            renderer::send_patch(node, patch);
2237        };
2238
2239        // Each command trigger → one patch. `watch` never fires for the initial value, so wiring
2240        // these does not issue a spurious command at build time (the initial URL loads via props).
2241        if let Some(go) = go {
2242            watch(
2243                move || go.track(),
2244                move |(), _| send(WebPatch::Load(url.get_untracked())),
2245            );
2246        }
2247        if let Some(back) = back {
2248            watch(move || back.track(), move |(), _| send(WebPatch::Back));
2249        }
2250        if let Some(forward) = forward {
2251            watch(
2252                move || forward.track(),
2253                move |(), _| send(WebPatch::Forward),
2254            );
2255        }
2256        if let Some(stop) = stop {
2257            watch(move || stop.track(), move |(), _| send(WebPatch::Stop));
2258        }
2259        if let Some(reload) = reload {
2260            watch(move || reload.track(), move |(), _| send(WebPatch::Reload));
2261        }
2262
2263        if let Some(force_reload) = force_reload {
2264            watch(
2265                move || force_reload.track(),
2266                move |(), _| send(WebPatch::ForceReload),
2267            );
2268        }
2269
2270        // Settings: seeded with what the props already carried, so a binding sends a patch only
2271        // when its value changes from the one the view has, and never at build time.
2272        if let Some(zoom) = zoom {
2273            bind_seeded(
2274                settings.zoom,
2275                move || WebSettings::clamp_zoom(zoom.get()),
2276                move |zoom: &f64| send(WebPatch::Zoom(*zoom)),
2277            );
2278        }
2279        if let Some(desktop) = desktop_mode {
2280            bind_seeded(
2281                settings.desktop_mode,
2282                move || desktop.get(),
2283                move |desktop: &bool| send(WebPatch::DesktopMode(*desktop)),
2284            );
2285        }
2286        if let Some(javascript) = javascript {
2287            bind_seeded(
2288                settings.javascript,
2289                move || javascript.get(),
2290                move |enabled: &bool| send(WebPatch::JavaScript(*enabled)),
2291            );
2292        }
2293        if let Some(rules) = content_rules {
2294            bind_seeded(
2295                initial.content.rules.clone(),
2296                move || rules.get(),
2297                move |rules: &Vec<ContentRuleList>| send(WebPatch::ContentRules(rules.clone())),
2298            );
2299        }
2300        if let (Some(sink), Some(callback)) = (&blocked_sink, on_blocked) {
2301            let delivery = content::deliver_blocked(sink.clone(), callback);
2302            day_reactive::Scope::current().on_cleanup(move || delivery.abort());
2303        }
2304
2305        // Bind the eval handle to the realized node so `handle.eval(…)` knows where to send.
2306        if let Some(js) = js {
2307            js.renderer.set(renderer);
2308            js.blocked.set(blocked_private);
2309            js.node.set(Some(node));
2310            day_reactive::Scope::current().on_cleanup(move || {
2311                if js.node.try_get() == Some(Some(node)) {
2312                    js.node.set(None);
2313                }
2314            });
2315        }
2316
2317        // Page-state reports (`PAGE_STATE_REPORT`) land in `pending` and are published at most
2318        // once a frame: an engine announces each progress estimate, title and history change
2319        // separately, and the app only needs the state they settle on.
2320        let has_page_state = page_state.is_some();
2321        let page_states = page_state.map(LatestSink::new);
2322        // Scroll reports (`SCROLL_REPORT`) arrive once per frame of scrolling, coalesced alike.
2323        let scroll_states = scroll_state.map(LatestSink::new);
2324        // Several kinds of report share this node's `Event::Custom` channel, told apart by `num`:
2325        // 0 is navigation (the URL, so a bound text field follows along), positive is an
2326        // evaluation reply keyed by its request id, and the negative tags are the link, new-tab
2327        // and page-state reports. In-process backends also tag them, but a
2328        // cross-boundary Custom (JNI, C-ABI) carries only `num`/`text`, so `num` is the
2329        // discriminator that works everywhere (§8.2's opened event channel).
2330        #[cfg(all(feature = "arkui", target_env = "ohos"))]
2331        let registration = RefCell::new(None);
2332        #[cfg(all(feature = "arkui", target_env = "ohos"))]
2333        let resource_start = initial.url.clone();
2334        // Backends reach the request hooks by token through Java or C, and the token registry
2335        // holds them weakly: this handler keeps them alive exactly as long as the node.
2336        let keep_hooks = initial.content.requests.clone();
2337        cx.on(node, move |ev| {
2338            let _keep_resources_alive = &resources;
2339            let _keep_hooks_alive = &keep_hooks;
2340            if let Event::Custom { num, text, .. } = ev {
2341                #[cfg(all(feature = "arkui", target_env = "ohos"))]
2342                #[expect(clippy::float_cmp, reason = "report codes are small integers carried in a float")]
2343                if *num == -3.0 {
2344                    // The controller is attached: install the scheme handler that serves the
2345                    // provider and asks the request filter, then load the first page, which
2346                    // waited for it.
2347                    let provider = resources.as_ref().map_or(0, ResourceProvider::id);
2348                    *registration.borrow_mut() =
2349                        resources_arkui::install(provider, keep_hooks.clone(), text);
2350                    if provider != 0 {
2351                        if registration.borrow().is_some() {
2352                            send(WebPatch::Load(resource_start.clone()));
2353                        }
2354                    } else if keep_hooks.is_some() {
2355                        if registration.borrow().is_none() {
2356                            log::warn!("day-piece-webview: ArkWeb scheme handler unavailable; the request filter is off");
2357                        }
2358                        // The ArkTS half loads its own first page for an empty URL.
2359                        send(WebPatch::Load(String::new()));
2360                    }
2361                    return;
2362                }
2363                if *num >= 1.0 {
2364                    resolve(*num as u64, text);
2365                } else if *num == PAGE_STATE_REPORT {
2366                    if let (Some(sink), Some(state)) = (&page_states, decode_page_state(text)) {
2367                        sink.report(state);
2368                    }
2369                } else if *num == SCROLL_REPORT {
2370                    if let (Some(sink), Some(state)) = (&scroll_states, decode_scroll_state(text)) {
2371                        sink.report(state);
2372                    }
2373                } else if *num == BLOCKED_REPORT {
2374                    if let Some(sink) = &blocked_sink {
2375                        match serde_json::from_str::<Vec<BlockedLoad>>(text) {
2376                            Ok(loads) => sink.extend(loads),
2377                            Err(_) => {
2378                                if let Ok(load) = serde_json::from_str::<BlockedLoad>(text) {
2379                                    sink.push(load);
2380                                }
2381                            }
2382                        }
2383                    }
2384                } else if *num == SCRIPT_MESSAGE {
2385                    if let Ok(report) = serde_json::from_str::<content::MessageReport>(text) {
2386                        let reply = messages
2387                            .iter()
2388                            .find(|(name, _)| *name == report.message.name)
2389                            .and_then(|(_, handler)| handler(report.message));
2390                        send(WebPatch::ScriptReply {
2391                            id: report.id,
2392                            reply,
2393                        });
2394                    }
2395                } else if *num == CONTENT_RULES_ERROR {
2396                    if let (Some(callback), Ok(error)) = (
2397                        &on_rules_error,
2398                        serde_json::from_str::<ContentRulesError>(text),
2399                    ) {
2400                        callback(&error);
2401                    }
2402                } else if *num == MEDIA_REPORT {
2403                    if let Ok(report) = serde_json::from_str::<content::MediaReport>(text) {
2404                        let allow = on_media.as_ref().is_some_and(|f| f(&report.request));
2405                        send(WebPatch::MediaDecision {
2406                            id: report.id,
2407                            allow,
2408                        });
2409                    }
2410                } else if *num == browsing::PAGE_PROMPT {
2411                    browse.prompt(text, move |id, answer| {
2412                        send(WebPatch::PromptAnswer {
2413                            id,
2414                            answer: serde_json::to_string(&answer).unwrap_or_default(),
2415                        });
2416                    });
2417                } else if *num == browsing::PAGE_NOTICE {
2418                    browse.notice(text);
2419                } else if *num == NEW_TAB_REPORT {
2420                    if let Some((_, callback)) = &tabs
2421                        && let Ok(request) = serde_json::from_str::<NewTabRequest>(text)
2422                    {
2423                        callback(&request);
2424                    }
2425                } else if *num == LINK_REPORT {
2426                    // An inline site's navigation left the site: the arm already canceled it
2427                    // (§8.3 events are enqueue-only, so the native side can't ask), and the
2428                    // policy runs here. `InView` re-issues the load as a command.
2429                    // An address no engine loads (`mailto:`, an app's scheme) is reported from
2430                    // any page, and `on_app_link` decides it where the app set one.
2431                    let app_link = !browsing::engine_scheme(text);
2432                    let policy = on_app_link
2433                        .as_ref()
2434                        .filter(|_| app_link)
2435                        .or(on_link.as_ref())
2436                        .map_or(LinkPolicy::OpenSystem, |f| f(text));
2437                    match policy {
2438                        LinkPolicy::OpenSystem => open_system(text, &send),
2439                        LinkPolicy::InView if !app_link => {
2440                            send(WebPatch::Load(text.clone()));
2441                        }
2442                        LinkPolicy::InView | LinkPolicy::Ignore => {}
2443                    }
2444                } else if *num == 0.0 {
2445                    url.set(text.clone());
2446                    if let Some(callback) = &on_load {
2447                        callback();
2448                    }
2449                }
2450            }
2451        });
2452        // A retained session re-attached to this node has a settled page and no reason to
2453        // report again: ask for its state once the handler above exists and the node is realized.
2454        if has_page_state {
2455            let ask = day_core::task(async move {
2456                day_core::sleep(0).await;
2457                send(WebPatch::ReportState);
2458            });
2459            day_reactive::Scope::current().on_cleanup(move || ask.abort());
2460        }
2461        node
2462    }
2463}
2464
2465// ---------------------------------------------------------------------------
2466// Per-toolkit native renderers, one file per backend (this crate is a reference implementation,
2467// so each toolkit is split out for clarity). Each module registers a `Renderer` link-time into its
2468// backend's `RENDERERS` slice; `#[cfg]` gates each to its feature + target, and `#[path]` keeps the
2469// files grouped next to lib.rs.
2470// ---------------------------------------------------------------------------
2471
2472#[cfg(all(target_os = "macos", feature = "gtk"))]
2473mod gtk_assets;
2474#[cfg(all(target_os = "macos", feature = "gtk"))]
2475#[path = "lib-gtk-macos.rs"]
2476mod gtk_macos;
2477#[cfg(all(target_os = "macos", any(feature = "appkit", feature = "gtk")))]
2478mod macos_web;
2479
2480day_pieces::glue_modules!(appkit, qt, uikit, material, xaml, arkui, dom);
2481
2482#[cfg(any(test, all(feature = "xaml", windows)))]
2483mod xaml_path;
2484
2485// Linux GTK uses WebKitGTK; the other GTK hosts are registered above.
2486#[cfg(all(feature = "gtk", not(target_os = "macos"), not(windows)))]
2487#[path = "lib-gtk.rs"]
2488mod gtk_impl;
2489
2490/// Rendering engine selected independently for each view.
2491#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2492pub enum WebRenderer {
2493    /// The toolkit's embedded browser; the default.
2494    #[default]
2495    WebView,
2496    /// Experimental engine supplied by the separately registered `day-piece-webview-servo` package.
2497    Servo,
2498}
2499impl WebRenderer {
2500    /// Whether this build can create this renderer, without initializing an engine.
2501    pub fn available(self) -> bool {
2502        match self {
2503            Self::WebView => support() != day_spec::Support::Unsupported,
2504            Self::Servo => renderer::capabilities(self).is_some(),
2505        }
2506    }
2507    /// Whether isolated private browsing contexts are supported.
2508    pub fn private_browsing_support(self) -> day_spec::Support {
2509        match self {
2510            Self::WebView => private_browsing_support(),
2511            Self::Servo => renderer::capabilities(self)
2512                .map_or(day_spec::Support::Unsupported, |caps| caps.private_browsing),
2513        }
2514    }
2515    /// Whether named storage profiles are supported.
2516    pub fn profile_support(self) -> day_spec::Support {
2517        match self {
2518            Self::WebView => profile_support(),
2519            Self::Servo => renderer::capabilities(self)
2520                .map_or(day_spec::Support::Unsupported, |caps| caps.profiles),
2521        }
2522    }
2523    /// Whether all data in a profile can be deleted.
2524    pub fn clear_data_support(self) -> day_spec::Support {
2525        match self {
2526            Self::WebView => clear_data_support(),
2527            Self::Servo => renderer::capabilities(self)
2528                .map_or(day_spec::Support::Unsupported, |caps| caps.clear_data),
2529        }
2530    }
2531    /// Whether [`WebView::zoom`] scales the page. The Servo adapter sets Servo's page zoom.
2532    pub fn zoom_support(self) -> day_spec::Support {
2533        match self {
2534            Self::WebView => zoom_support(),
2535            Self::Servo => renderer::capabilities(self)
2536                .map_or(day_spec::Support::Unsupported, |_| {
2537                    day_spec::Support::Native
2538                }),
2539        }
2540    }
2541    /// Whether [`WebView::desktop_mode`] is honored. Servo 0.6 has no per-view user agent.
2542    pub fn desktop_mode_support(self) -> day_spec::Support {
2543        match self {
2544            Self::WebView => desktop_mode_support(),
2545            Self::Servo => day_spec::Support::Unsupported,
2546        }
2547    }
2548    /// Whether [`WebView::request_filter`] runs. The Servo adapter filters each request it is
2549    /// asked to load.
2550    pub fn request_filter_support(self) -> day_spec::Support {
2551        match self {
2552            Self::WebView => request_filter_support(),
2553            Self::Servo => renderer::capabilities(self)
2554                .map_or(day_spec::Support::Unsupported, |_| {
2555                    day_spec::Support::Native
2556                }),
2557        }
2558    }
2559    /// Whether [`WebView::javascript`] can stop page scripts. Servo 0.6 has no per-view switch.
2560    pub fn javascript_support(self) -> day_spec::Support {
2561        match self {
2562            Self::WebView => javascript_support(),
2563            Self::Servo => day_spec::Support::Unsupported,
2564        }
2565    }
2566}
2567/// An explicitly selected renderer is unavailable in this build.
2568#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2569pub struct RendererUnavailable(pub WebRenderer);
2570impl std::fmt::Display for RendererUnavailable {
2571    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2572        write!(f, "{:?} renderer is unavailable in this build", self.0)
2573    }
2574}
2575impl std::error::Error for RendererUnavailable {}
2576
2577#[cfg(test)]
2578mod tests {
2579    #[test]
2580    fn the_expression_form_carries_the_script_as_source() {
2581        let wrapped = wrap_expression("document.title // the title");
2582        assert!(wrapped.contains("v=(\ndocument.title // the title\n);"));
2583        assert!(!wrapped.contains("eval("));
2584        // The first form evaluates text, which a page's policy can refuse.
2585        assert!(wrap_script("document.title").contains("eval("));
2586    }
2587
2588    /// The wrapper, run for real (with `node`, skipped without it). A script that throws its
2589    /// own `EvalError` after a side effect ran once and is reported as thrown, so it is never
2590    /// sent again. An `eval` that refuses before anything ran is reported as the refusal.
2591    #[test]
2592    fn only_a_refused_eval_is_reported_as_one() {
2593        let throws = "globalThis.count=(globalThis.count||0)+1; throw new EvalError('mine')";
2594        let program = format!(
2595            "var first={};\
2596             var refused=(function(eval){{return {}}})(function(){{throw new EvalError('refused')}});\
2597             console.log(JSON.stringify([first,globalThis.count,refused,globalThis.touched===undefined,{}]))",
2598            wrap_script(throws),
2599            wrap_script("globalThis.touched=1"),
2600            wrap_expression("1+1")
2601        );
2602        let output = match std::process::Command::new("node")
2603            .arg("-e")
2604            .arg(&program)
2605            .output()
2606        {
2607            Ok(output) if output.status.success() => output,
2608            _ => {
2609                eprintln!("node did not run; skipping");
2610                return;
2611            }
2612        };
2613        let text = String::from_utf8_lossy(&output.stdout);
2614        let values: Vec<serde_json::Value> = serde_json::from_str(text.trim()).unwrap();
2615        assert_eq!(values[0], format!("0{SEP}EvalError{SEP}mine"));
2616        assert_eq!(values[1], 1, "the script ran once");
2617        assert_eq!(values[2], format!("0{SEP}{EVAL_REFUSED}{SEP}refused"));
2618        assert_eq!(values[3], true, "a refused script did not run");
2619        assert_eq!(values[4], format!("1{SEP}2"));
2620    }
2621
2622    /// The wrapper leaves the script's meaning alone (with `node`, skipped without it): a
2623    /// leading `"use strict"` still governs it, a script with no value reports null, and the
2624    /// script may use any name, the wrapper's own included.
2625    #[test]
2626    fn the_wrapper_runs_the_script_as_written() {
2627        let scripts = [
2628            "'use strict'; (function(){ return this === undefined; })()",
2629            "",
2630            "var declared = 1;",
2631            "let ran = 2, v = 3, e = 4, s = 5; ran + v + e + s",
2632            "document = undefined; typeof eval",
2633        ];
2634        let wrapped: Vec<String> = scripts.iter().map(|s| wrap_script(s)).collect();
2635        let program = format!("console.log(JSON.stringify([{}]))", wrapped.join(","));
2636        let output = match std::process::Command::new("node")
2637            .arg("-e")
2638            .arg(&program)
2639            .output()
2640        {
2641            Ok(output) if output.status.success() => output,
2642            _ => {
2643                eprintln!("node did not run; skipping");
2644                return;
2645            }
2646        };
2647        let text = String::from_utf8_lossy(&output.stdout);
2648        let values: Vec<String> = serde_json::from_str(text.trim()).unwrap();
2649        assert_eq!(values[0], format!("1{SEP}true"), "strict mode kept");
2650        assert_eq!(values[1], format!("1{SEP}null"));
2651        assert_eq!(values[2], format!("1{SEP}null"));
2652        assert_eq!(values[3], format!("1{SEP}14"));
2653        assert_eq!(values[4], format!("1{SEP}\"function\""));
2654    }
2655
2656    #[test]
2657    fn servo_selection_is_explicit_and_does_not_claim_native_profiles() {
2658        assert_eq!(super::WebRenderer::default(), super::WebRenderer::WebView);
2659        assert!(!super::WebRenderer::Servo.available());
2660        assert_eq!(
2661            super::WebRenderer::Servo.private_browsing_support(),
2662            day_spec::Support::Unsupported
2663        );
2664        assert_eq!(
2665            super::WebRenderer::Servo.profile_support(),
2666            day_spec::Support::Unsupported
2667        );
2668    }
2669
2670    use super::*;
2671
2672    #[test]
2673    fn an_unpolled_evaluation_survives_its_tab_being_closed() {
2674        let scope = day_reactive::Scope::child();
2675        let mut future = scope.enter(|| JsHandle::new().eval("1 + 1"));
2676        scope.dispose();
2677        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
2678        std::assert_matches!(
2679            Pin::new(&mut future).poll(&mut context),
2680            Poll::Ready(Err(EvalError::ViewGone))
2681        );
2682    }
2683
2684    #[test]
2685    fn profiles_keep_identity_and_privacy_separate() {
2686        let profile = WebProfile::persistent("publication");
2687        assert_eq!(
2688            profile.storage_key(),
2689            WebProfile::persistent("publication").storage_key()
2690        );
2691        assert_ne!(
2692            profile.storage_key(),
2693            WebProfile::private("publication").storage_key()
2694        );
2695        assert_ne!(
2696            profile.storage_key(),
2697            WebProfile::persistent("other").storage_key()
2698        );
2699        assert_ne!(
2700            profile.clone().directory("/fixture/a").storage_key(),
2701            profile.directory("/fixture/b").storage_key()
2702        );
2703    }
2704    #[test]
2705    fn response_cookies_cannot_impersonate_another_origin() {
2706        assert!(cookie_source_valid(
2707            "https://news.example.com/story",
2708            "session=fixture; Domain=.example.com; Secure; HttpOnly"
2709        ));
2710        assert!(!cookie_source_valid(
2711            "https://news.example.co.uk/",
2712            "session=fixture; Domain=co.uk"
2713        ));
2714        assert!(!cookie_source_valid(
2715            "https://project.github.io/",
2716            "session=fixture; Domain=github.io"
2717        ));
2718        assert!(!cookie_source_valid(
2719            "https://unrelated.test/",
2720            "session=fixture; Domain=example.com"
2721        ));
2722        assert!(!cookie_source_valid(
2723            "https://example.com/",
2724            "session=fixture\r\nInjected: header"
2725        ));
2726        assert!(!cookie_source_valid(
2727            "http://example.com/",
2728            "session=fixture; Secure"
2729        ));
2730        assert!(!cookie_source_valid(
2731            "https://example.com/",
2732            "__Host-session=fixture; Secure; Domain=example.com; Path=/"
2733        ));
2734        assert!(cookie_source_valid(
2735            "https://example.com/",
2736            "__Host-session=fixture; Secure; Path=/"
2737        ));
2738    }
2739    #[test]
2740    fn cookie_credentials_respect_host_path_and_transport_boundaries() {
2741        assert!(cookie_matches(
2742            "https://news.example.com/account/page",
2743            ".example.com",
2744            "/account",
2745            true
2746        ));
2747        assert!(!cookie_matches(
2748            "http://news.example.com/account",
2749            ".example.com",
2750            "/account",
2751            true
2752        ));
2753        assert!(!cookie_matches(
2754            "https://evil-example.com/account",
2755            ".example.com",
2756            "/account",
2757            false
2758        ));
2759        assert!(!cookie_matches(
2760            "https://news.example.com/accounting",
2761            ".example.com",
2762            "/account",
2763            false
2764        ));
2765        assert!(!cookie_matches(
2766            "https://news.example.com/",
2767            "example.com",
2768            "/",
2769            false
2770        ));
2771        assert!(!cookie_matches(
2772            "file:///account",
2773            ".example.com",
2774            "/",
2775            false
2776        ));
2777        assert!(cookie_matches(
2778            "https://EXAMPLE.com/",
2779            "example.com",
2780            "",
2781            false
2782        ));
2783    }
2784
2785    /// Build a reply the way an arm would, without a literal control char in the test source.
2786    fn reply(parts: &[&str]) -> String {
2787        parts.join(&SEP.to_string())
2788    }
2789
2790    #[test]
2791    fn decodes_a_value() {
2792        assert_eq!(decode(&reply(&["1", "2"])), Ok("2".into()));
2793        assert_eq!(decode(&reply(&["1", "null"])), Ok("null".into()));
2794        let obj = r#"{"a":1,"b":"x"}"#;
2795        assert_eq!(decode(&reply(&["1", obj])), Ok(obj.into()));
2796    }
2797
2798    #[test]
2799    fn decodes_a_throw() {
2800        assert_eq!(
2801            decode(&reply(&["0", "TypeError", "boom"])),
2802            Err(EvalError::Threw {
2803                name: "TypeError".into(),
2804                message: "boom".into(),
2805            })
2806        );
2807    }
2808
2809    /// Only the first separator splits the name off, so a message carrying more stays intact.
2810    #[test]
2811    fn a_message_may_contain_the_separator() {
2812        assert_eq!(
2813            decode(&reply(&["0", "Error", "a", "b"])),
2814            Err(EvalError::Threw {
2815                name: "Error".into(),
2816                message: reply(&["a", "b"]),
2817            })
2818        );
2819    }
2820
2821    /// JSON text can never hold a raw separator (`JSON.stringify` escapes control characters as
2822    /// six ASCII chars), so splitting on it cannot corrupt a value. This pins that.
2823    #[test]
2824    fn an_escaped_separator_inside_json_survives() {
2825        let json = r#""a\u001fb""#;
2826        assert_eq!(decode(&reply(&["1", json])), Ok(json.into()));
2827    }
2828
2829    #[test]
2830    fn an_undecodable_reply_is_an_engine_error() {
2831        assert_eq!(decode(""), Err(EvalError::Engine(String::new())));
2832        // What a backend reports when the wrapper never ran at all.
2833        assert_eq!(decode("null"), Err(EvalError::Engine("null".into())));
2834    }
2835
2836    /// The arms build engine failures with `engine_error`; it must decode like any other throw.
2837    #[test]
2838    fn engine_errors_round_trip() {
2839        assert_eq!(
2840            decode(&engine_error("WebKitError", "process gone")),
2841            Err(EvalError::Threw {
2842                name: "WebKitError".into(),
2843                message: "process gone".into(),
2844            })
2845        );
2846    }
2847
2848    /// The script rides inside a string literal, so nothing in it can reach the wrapper's own
2849    /// tokens: a trailing line comment, an unbalanced brace, a quote, a newline.
2850    #[test]
2851    fn the_wrapper_is_lexically_sealed() {
2852        for hostile in [
2853            "1 + 1 // add",
2854            "\"unterminated",
2855            "}}})(){{{",
2856            "a\nb",
2857            "x\\y",
2858        ] {
2859            let js = wrap_script(hostile);
2860            assert!(
2861                js.trim_end().ends_with("})()"),
2862                "wrapper not closed for {hostile:?}: {js}"
2863            );
2864            assert!(
2865                !js.contains('\n'),
2866                "raw newline leaked for {hostile:?}: {js}"
2867            );
2868        }
2869    }
2870
2871    #[test]
2872    fn scroll_reports_round_trip_and_reject_garbage() {
2873        let state = ScrollState {
2874            offset: 1234.5,
2875            content_height: 8000.0,
2876            viewport_height: 700.0,
2877            dragging: true,
2878        };
2879        assert_eq!(
2880            decode_scroll_state(&encode_scroll_state(&state)),
2881            Some(state)
2882        );
2883        // Java's `%.1f` under Locale.ROOT, and a bounce above the top.
2884        let java = decode_scroll_state("-12.0\u{1f}900.0\u{1f}700.0\u{1f}0").unwrap();
2885        assert!(java.at_top() && !java.dragging);
2886        assert!(!java.at_bottom());
2887        let end = ScrollState {
2888            offset: 200.0,
2889            content_height: 900.0,
2890            viewport_height: 700.0,
2891            dragging: false,
2892        };
2893        assert!(end.at_bottom());
2894        assert_eq!(decode_scroll_state("1,5\u{1f}900\u{1f}700\u{1f}0"), None);
2895        assert_eq!(decode_scroll_state("1\u{1f}NaN\u{1f}700\u{1f}0"), None);
2896        assert_eq!(decode_scroll_state("1\u{1f}2\u{1f}3\u{1f}yes"), None);
2897        assert_eq!(decode_scroll_state("1\u{1f}2"), None);
2898    }
2899
2900    #[test]
2901    fn page_state_reports_round_trip_with_a_separator_in_the_title() {
2902        let state = PageState {
2903            url: "https://example.test/a?b=c#d".into(),
2904            title: reply(&["two", "parts"]),
2905            loading: true,
2906            progress: 0.4567,
2907            can_go_back: true,
2908            can_go_forward: false,
2909        };
2910        let decoded = decode_page_state(&encode_page_state(&state)).unwrap();
2911        assert_eq!(decoded.title, state.title);
2912        assert_eq!(decoded.url, state.url);
2913        assert!(decoded.loading && decoded.can_go_back && !decoded.can_go_forward);
2914        assert_eq!(decoded.progress, 0.46);
2915        // What the Java, C++ and ArkTS arms compose by hand.
2916        let native = decode_page_state(&reply(&["011", "1", "about:blank", ""])).unwrap();
2917        assert_eq!(native.progress, 1.0);
2918        assert!(!native.loading && native.can_go_back && native.can_go_forward);
2919        assert_eq!(decode_page_state(&reply(&["01", "1", "x", ""])), None);
2920        assert_eq!(decode_page_state(&reply(&["000", "NaN", "x", ""])), None);
2921        assert_eq!(
2922            decode_page_state(&reply(&["000", "7", "x", "t"]))
2923                .unwrap()
2924                .progress,
2925            1.0
2926        );
2927    }
2928
2929    #[test]
2930    fn zoom_factors_clamp_to_what_every_engine_accepts() {
2931        assert_eq!(WebSettings::clamp_zoom(1.25), 1.25);
2932        assert_eq!(WebSettings::clamp_zoom(0.1), 0.25);
2933        assert_eq!(WebSettings::clamp_zoom(12.0), 5.0);
2934        for nonsense in [0.0, -2.0, f64::NAN, f64::INFINITY] {
2935            assert_eq!(WebSettings::clamp_zoom(nonsense), 1.0, "{nonsense}");
2936        }
2937    }
2938
2939    /// The Java (`DayWebView.desktopAgent`) and ArkTS (`desktopAgent`) arms compose this text too.
2940    #[test]
2941    fn desktop_agents_keep_the_engine_major_version() {
2942        let android = "Mozilla/5.0 (Linux; Android 14; Pixel 7 Build/UQ1A; wv) AppleWebKit/537.36 \
2943                       (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.135 Mobile Safari/537.36";
2944        assert_eq!(
2945            desktop_user_agent(android),
2946            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) \
2947             Chrome/131.0.0.0 Safari/537.36"
2948        );
2949        assert!(desktop_user_agent("ArkWeb/4.1 Mobile").contains(" Chrome/120.0.0.0 "));
2950    }
2951
2952    #[test]
2953    fn snapshot_replies_decode_base64() {
2954        assert_eq!(base64_decode("iVBORw0KGgo=").unwrap(), b"\x89PNG\r\n\x1a\n");
2955        assert_eq!(base64_decode("aGVsbG8").unwrap(), b"hello");
2956        assert_eq!(base64_decode("aGVs\nbG8=").unwrap(), b"hello");
2957        assert_eq!(base64_decode(""), Some(Vec::new()));
2958        assert_eq!(base64_decode("a*b"), None);
2959    }
2960
2961    #[test]
2962    fn a_start_page_keeps_its_query_out_of_the_path() {
2963        assert_eq!(split_page("index.html"), ("index.html", ""));
2964        assert_eq!(
2965            split_page("player.html?src=hello&loop=1"),
2966            ("player.html", "?src=hello&loop=1")
2967        );
2968        assert_eq!(
2969            split_page("docs/index.html#top"),
2970            ("docs/index.html", "#top")
2971        );
2972    }
2973
2974    #[test]
2975    fn escapes_a_script_into_a_literal() {
2976        assert_eq!(js_string_literal("a"), "\"a\"");
2977        assert_eq!(js_string_literal("a\"b"), "\"a\\\"b\"");
2978        assert_eq!(js_string_literal("a\\b"), "\"a\\\\b\"");
2979        assert_eq!(js_string_literal("a\nb"), "\"a\\nb\"");
2980        // A literal line terminator would end the string mid-source.
2981        assert_eq!(js_string_literal("a\u{2028}b"), "\"a\\u2028b\"");
2982        assert_eq!(js_string_literal("a\u{1}b"), "\"a\\u0001b\"");
2983    }
2984}
2985
2986#[cfg(test)]
2987mod external_link_tests {
2988    use super::external_document_link as external;
2989    #[test]
2990    fn user_navigation_leaves_reader_but_loading_and_anchors_do_not() {
2991        let page = Some("file:///tmp/fixture.html");
2992        assert!(external(
2993            page,
2994            "https://example.test/story",
2995            true,
2996            false,
2997            false
2998        ));
2999        assert!(external(
3000            page,
3001            "https://example.test/story",
3002            true,
3003            true,
3004            false
3005        ));
3006        assert!(external(
3007            page,
3008            "https://example.test/story",
3009            false,
3010            true,
3011            false
3012        ));
3013        assert!(!external(
3014            page,
3015            "file:///tmp/fixture.html#note",
3016            true,
3017            false,
3018            false
3019        ));
3020        assert!(!external(
3021            page,
3022            "file:///tmp/next.html",
3023            false,
3024            false,
3025            false
3026        ));
3027        assert!(!external(
3028            page,
3029            "https://example.test/frame",
3030            true,
3031            false,
3032            true
3033        ));
3034        assert!(!external(page, "about:blank", false, true, false));
3035        assert!(external(
3036            Some("https://example.test/story?a=1#x"),
3037            "https://example.test/story?a=2",
3038            true,
3039            false,
3040            false
3041        ));
3042    }
3043}