Skip to main content

teksilo_webview/
backend.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! Backend abstraction for [`WebView`](crate::WebView).
5//!
6//! An engine shows its page in one of two ways, and a backend says which with
7//! [`WebViewBackend::rendering`]:
8//!
9//! - [`WebViewRendering::NativeSubview`]: the engine owns a native OS view
10//!   placed *on top of* the wgpu pass (WKWebView, WebView2 and WebKitGTK, all
11//!   through wry). The OS delivers its input; the widget positions, clips and
12//!   hides it.
13//! - [`WebViewRendering::Surface`]: the engine renders offscreen and writes each
14//!   frame into the [`LiveImageWriter`] the widget hands
15//!   [`WebViewBackend::open`]. The widget draws the picture in the wgpu pass
16//!   like any other content and forwards input with
17//!   [`WebViewHandle::send_input`].
18//!
19//! This module mirrors the established platform-backend pattern
20//! (`FileDialogBackend` / `ExternalDndBackend`): a swappable
21//! [`WebViewBackend`] trait creates an engine-specific [`WebViewHandle`], and a
22//! per-app [`WebViewRegistry`] (registered in app-state) owns the backend and
23//! routes JS→Rust / browser-lifecycle events back into the originating widget
24//! tree.
25//!
26//! The default build ships only the [`MemoryWebViewBackend`] (headless,
27//! deterministic). The native `wry` / `servo` backends live behind the
28//! `wry-backend` / `servo-backend` features.
29
30use std::cell::{Cell, RefCell};
31use std::collections::HashMap;
32use std::path::PathBuf;
33use std::rc::Rc;
34use std::sync::Arc;
35use std::sync::atomic::{AtomicU64, Ordering};
36
37use teksilo_canvas::live_image::LiveImageWriter;
38use teksilo_canvas::{ImageOrientation, Point, Rect};
39use teksilo_core::AppEventPoster;
40use teksilo_core::event::{Key, Modifiers, PointerButton, ScrollDelta};
41use teksilo_core::pointer::PointerId;
42use teksilo_core::raw_handle::ParentHandle;
43use teksilo_core::widget::CursorIcon;
44
45use crate::controls::{WebViewControl, WebViewControlAnswer};
46use crate::page_a11y::PageAccessibilityUpdate;
47use teksilo_core::widget::EventContext;
48use teksilo_core::window::TeksiloWindowId;
49
50/// Process-unique identity for a single web view instance. Allocated once at
51/// `WebView` construction and stable across rebuilds, so backend events route
52/// to the correct widget. Same shape as `MenuItemId`.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54pub struct WebViewId(u64);
55
56impl WebViewId {
57    /// Allocate the next process-unique id.
58    pub fn next() -> Self {
59        static COUNTER: AtomicU64 = AtomicU64::new(1);
60        Self(COUNTER.fetch_add(1, Ordering::Relaxed))
61    }
62
63    /// The raw numeric value (diagnostics / map keys).
64    pub fn raw(self) -> u64 {
65        self.0
66    }
67}
68
69/// What a web view should initially display.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub enum WebSource {
72    /// Navigate to a URL.
73    Url(String),
74    /// Load an inline HTML string, with an optional base URL for relative
75    /// asset resolution.
76    Html {
77        html: String,
78        base_url: Option<String>,
79    },
80}
81
82/// Severity of a [`WebViewEvent::ConsoleMessage`].
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum ConsoleLevel {
85    Log,
86    Warn,
87    Error,
88}
89
90/// Engine configuration accumulated by the [`WebView`](crate::WebView)
91/// builders and handed to [`WebViewBackend::open`].
92#[derive(Debug, Clone, Default)]
93pub struct WebViewAttributes {
94    /// Initial content. `None` means "blank page".
95    pub source: Option<WebSource>,
96    /// Override the engine's `User-Agent`.
97    pub user_agent: Option<String>,
98    /// Transparent engine background (compose over Teksilo content).
99    pub transparent: bool,
100    /// Enable the engine's devtools (debug builds only by convention).
101    pub devtools: bool,
102    /// Custom-protocol scheme names the app wants to serve (`app` → `app://`).
103    /// The dispatch closures live app-side; the backend only needs the names
104    /// at open time to register the schemes.
105    pub custom_protocols: Vec<String>,
106}
107
108/// How an engine shows its page, as its backend reports through
109/// [`WebViewBackend::rendering`].
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub enum WebViewRendering {
112    /// A native OS view placed over the host window. The OS delivers its
113    /// input, and the widget keeps it positioned, clipped to its visible
114    /// part and hidden when dormant or covered by an overlay.
115    NativeSubview,
116    /// Offscreen rendering into the [`LiveImageWriter`] the widget passes to
117    /// [`WebViewBackend::open`]. The widget draws the picture inside the wgpu
118    /// pass, so clipping, overlays and dormancy need no help from the engine,
119    /// and it forwards input through [`WebViewHandle::send_input`].
120    Surface {
121        /// How the engine's rows lie in the picture:
122        /// [`ImageOrientation::FlipVertical`] for an engine that writes its
123        /// frame bottom row first, as an OpenGL readback does, so the widget
124        /// turns it upright when drawing instead of the engine copying every
125        /// row in reverse.
126        orientation: ImageOrientation,
127    },
128}
129
130/// The phase of a touch contact in [`WebViewInputEvent::Touch`].
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum WebViewTouchPhase {
133    /// The contact landed.
134    Down,
135    /// The contact moved.
136    Move,
137    /// The contact lifted.
138    Up,
139    /// The contact was taken away (palm rejection, a gesture claimed it, the
140    /// window lost it). Nothing may activate from it.
141    Cancel,
142}
143
144/// A clipboard command the page should carry out on its own selection or
145/// focused field, sent as [`WebViewInputEvent::Edit`].
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum WebViewEditCommand {
148    /// Copy the selection.
149    Copy,
150    /// Cut the selection.
151    Cut,
152    /// Paste at the caret.
153    Paste,
154}
155
156/// Input the widget forwards to a [`WebViewRendering::Surface`] engine.
157///
158/// A surface engine has no native view for the OS to deliver input to, so the
159/// widget receives it like any other widget and passes it on. Every position
160/// is in **page pixels**: the pixels of the frame the engine last wrote into
161/// its [`LiveImageWriter`], as displayed, with the origin at the page's
162/// top-left whatever orientation the rows were written in. The widget converts
163/// from its own coordinates with the same placement it painted the frame
164/// with, so a click lands on the pixel the user saw, even while a resize is
165/// still on its way to the engine.
166#[derive(Debug, Clone, PartialEq)]
167#[non_exhaustive]
168pub enum WebViewInputEvent {
169    /// A mouse, or a pen hovering, moved over the page.
170    PointerMove {
171        /// Where the pointer is.
172        position: Point,
173    },
174    /// A mouse or pen button went down or up.
175    PointerButton {
176        /// Where the pointer is.
177        position: Point,
178        /// Which button.
179        button: PointerButton,
180        /// `true` on press, `false` on release.
181        pressed: bool,
182    },
183    /// The pointer left the page.
184    PointerLeave,
185    /// A finger, or a pen in contact with the screen.
186    Touch {
187        /// Identifies the contact from `Down` to `Up` or `Cancel`.
188        contact: PointerId,
189        /// What happened to it.
190        phase: WebViewTouchPhase,
191        /// Where it is.
192        position: Point,
193        /// Whether the contact is a pen rather than a finger.
194        pen: bool,
195    },
196    /// A wheel or trackpad scroll, as Teksilo reports it.
197    Scroll {
198        /// Where the pointer is.
199        position: Point,
200        /// How far, in lines or in logical pixels.
201        delta: ScrollDelta,
202        /// The modifiers held during the scroll.
203        modifiers: Modifiers,
204    },
205    /// A key went down or up while the page held the keyboard.
206    Key {
207        /// The logical key.
208        key: Key,
209        /// The modifiers held.
210        modifiers: Modifiers,
211        /// `true` on press, `false` on release.
212        pressed: bool,
213        /// The text the key produces, on a press that produces any.
214        text: Option<String>,
215    },
216    /// An input method updated its composition.
217    ImeComposition {
218        /// The text being composed.
219        text: String,
220        /// The caret or selection inside it, in bytes.
221        cursor: Option<std::ops::Range<usize>>,
222    },
223    /// An input method committed text.
224    ImeCommit {
225        /// The committed text.
226        text: String,
227    },
228    /// A clipboard command, from the application's standard edit shortcuts.
229    Edit(WebViewEditCommand),
230}
231
232/// A live engine view. Dropping the handle tears it down (RAII, same contract
233/// as `ExternalDndGuard`).
234///
235/// All methods are `&self` — the handle is cheaply shareable and the engine
236/// state lives behind the platform's own interior mutability.
237pub trait WebViewHandle: 'static {
238    /// Reposition / resize the native subview within its parent window.
239    /// `bounds` is in **logical** pixels (Teksilo's coordinate system);
240    /// `scale_factor` is the host window's HiDPI scale. Most engines position
241    /// in logical units, but some need device pixels (`bounds × scale_factor`)
242    /// because their own toolkit runs at a different scale than the wgpu
243    /// surface — notably WebKitGTK on X11/XWayland, which uses integer GDK
244    /// scaling and ignores fractional factors. Issued whenever the widget's
245    /// layout bounds or the window scale change.
246    fn set_bounds(&self, bounds: Rect, scale_factor: f32);
247    /// Navigate to a URL.
248    fn load_url(&self, url: &str);
249    /// Load inline HTML.
250    fn load_html(&self, html: &str, base_url: Option<&str>);
251    /// Evaluate JavaScript in the page.
252    fn eval(&self, script: &str);
253    /// Rust → JS: dispatch a `teksilo-message` `MessageEvent` carrying `msg`.
254    fn post_message(&self, msg: &str);
255    /// Reload the current page.
256    fn reload(&self);
257    /// Navigate back in history.
258    fn go_back(&self);
259    /// Navigate forward in history.
260    fn go_forward(&self);
261    /// Stop the current load.
262    fn stop(&self);
263    /// Show / hide the native subview. **Load-bearing**: a native subview
264    /// lives outside the wgpu pass, so framework dormancy (a `Switcher`
265    /// parking the page) does NOT hide it — the `WebView` widget bridges
266    /// its activation signal to this call. See `WebView`'s rustdoc.
267    fn set_visible(&self, visible: bool);
268    /// Give the engine subview keyboard focus.
269    fn set_focus(&self);
270    /// Ask the engine to stop taking pointer input over its own rectangle, so
271    /// the OS delivers those events to the host window and Teksilo routes them
272    /// — the engine half of [`WebViewInput::Transparent`].
273    ///
274    /// **Not every engine can do this** — the call needs control over the
275    /// native surface's hit region, which the embedding API may simply not
276    /// expose — and one that cannot must say so through
277    /// [`WebViewEvent::ConsoleMessage`] — the channel this crate
278    /// already reserves for reporting an unsupported operation — rather than
279    /// accept the call and change nothing. There is deliberately no return
280    /// value and no default implementation: an answer invented here would be
281    /// an answer for an engine nobody asked.
282    ///
283    /// [`WebViewInput::Transparent`]: crate::WebViewInput::Transparent
284    fn set_input_passthrough(&self, passthrough: bool);
285    /// Open the engine's developer tools (no-op on backends that don't
286    /// expose them — Servo's embedding API has no clean devtools hook today).
287    fn open_devtools(&self) {}
288    /// Close the engine's developer tools (no-op where unsupported).
289    fn close_devtools(&self) {}
290    /// Take the keyboard away from the page: the frame lost Teksilo's focus.
291    /// Only a [`WebViewRendering::Surface`] engine needs telling; a native
292    /// subview loses the OS focus with the frame.
293    fn blur(&self) {}
294    /// Answer the control [`WebViewEvent::ControlRequested`] carried `key`
295    /// for. A key answered already, or one the page has since closed, is
296    /// ignored.
297    fn answer_control(&self, _key: u64, _answer: WebViewControlAnswer) {}
298    /// Pass input to the page. Only a [`WebViewRendering::Surface`] engine
299    /// receives this: a native subview gets its input from the OS. See
300    /// [`WebViewInputEvent`] for the coordinate space.
301    fn send_input(&self, _event: &WebViewInputEvent) {}
302}
303
304/// A browser lifecycle / JS→Rust event surfaced by a backend.
305#[derive(Debug, Clone)]
306pub enum WebViewEvent {
307    /// A navigation is starting. `can_cancel` is true on backends that
308    /// support pre-navigation veto.
309    NavigationStarted { url: String, can_cancel: bool },
310    /// A navigation finished (or failed).
311    NavigationFinished { url: String, success: bool },
312    /// The page began loading resources.
313    PageLoadStarted,
314    /// The page finished loading.
315    PageLoadFinished,
316    /// The document title changed.
317    TitleChanged(String),
318    /// `window.ipc.postMessage(payload)` fired in the page.
319    Message(String),
320    /// A download began.
321    DownloadStarted {
322        url: String,
323        suggested_path: PathBuf,
324    },
325    /// A download finished (or failed).
326    DownloadFinished { path: PathBuf, success: bool },
327    /// A console message (forwarded in debug builds / by best-effort
328    /// backends to report unsupported operations).
329    ConsoleMessage { level: ConsoleLevel, text: String },
330    /// The engine's own keyboard focus changed: `true` when the page took the
331    /// keyboard, `false` when it gave it up.
332    ///
333    /// A web view has two disjoint focus rings — the toolkit's and the
334    /// engine's platform tree — and the engine's is the one Teksilo cannot
335    /// see. Without this event a tap inside the page moves the OS focus while
336    /// Teksilo goes on believing a text field elsewhere still owns it, caret
337    /// blinking. The `WebView` widget follows the event with
338    /// `EventContext::request_focus` on its own frame, so the toolkit's focus
339    /// agrees with the OS.
340    EngineFocusChanged(bool),
341    /// The page wants this cursor over itself. Sent by a
342    /// [`WebViewRendering::Surface`] engine; a native subview sets the OS
343    /// cursor itself.
344    CursorChanged(CursorIcon),
345    /// Where the page's text caret is, in page pixels, while an editable
346    /// element in it has focus (`None` once none has), so the input method's
347    /// candidate window opens beside it. Sent by a surface engine.
348    InputMethodArea(Option<Rect>),
349    /// The page opened a dialog or a picker for the application to present
350    /// (see [`crate::controls`]). Answer it with
351    /// [`WebViewHandle::answer_control`] and the same `key`. A `Select`'s
352    /// `area` is in page pixels here; the widget maps it to the window.
353    ControlRequested { key: u64, control: WebViewControl },
354    /// An update of the page's accessibility tree, from an engine that hands
355    /// it to its embedder instead of publishing it to the OS (Servo). The
356    /// widget mirrors it under its own node.
357    PageAccessibility(PageAccessibilityUpdate),
358}
359
360/// Boxed inside `AppEvent::External` when a backend produces an event.
361/// `teksilo-app`'s app-event handler downcasts to this type and routes to
362/// [`WebViewRegistry::deliver`]. Mirrors `FileDialogEventPayload`.
363pub struct WebViewEventPayload {
364    /// The window the web view lives in — routes delivery to the right tree.
365    pub window_id_owner: TeksiloWindowId,
366    /// Which web view the event belongs to.
367    pub web_view_id: WebViewId,
368    /// The event itself.
369    pub event: WebViewEvent,
370}
371
372/// Boxed inside `AppEvent::External` when a [`WebViewRendering::Surface`]
373/// engine asks to run. `teksilo-app` answers it on the main thread with
374/// [`WebViewRegistry::pump`].
375///
376/// A surface engine works on threads of its own and needs its embedder to call
377/// back on the thread that owns it, which is the UI thread. Posting this
378/// payload is how it asks; a backend coalesces its requests so that one
379/// payload is in flight at a time.
380#[derive(Debug, Default)]
381pub struct WebViewPumpPayload;
382
383/// Ask the UI loop to call [`WebViewRegistry::pump`], if a poster is available.
384#[allow(dead_code)] // used only by the feature-gated engine backends
385pub(crate) fn post_pump(poster: &Option<Arc<dyn AppEventPoster>>) {
386    if let Some(poster) = poster {
387        poster.post_external(Box::new(WebViewPumpPayload) as Box<dyn std::any::Any + Send>);
388    }
389}
390
391/// Post a [`WebViewEvent`] back to the UI loop, if a poster is available.
392/// Shared by every engine backend so the emit path lives in one place.
393#[allow(dead_code)] // used only by the feature-gated engine backends
394pub(crate) fn post_event(
395    poster: &Option<Arc<dyn AppEventPoster>>,
396    window_id: TeksiloWindowId,
397    web_view_id: WebViewId,
398    event: WebViewEvent,
399) {
400    if let Some(poster) = poster {
401        let payload = WebViewEventPayload {
402            window_id_owner: window_id,
403            web_view_id,
404            event,
405        };
406        poster.post_external(Box::new(payload) as Box<dyn std::any::Any + Send>);
407    }
408}
409
410/// Encode `s` as a JavaScript string literal (double-quoted, fully escaped) so
411/// it can be safely interpolated into an `evaluate_script` body. Lives in the
412/// shared backend module (not in one engine's file) so every JS-executing
413/// backend uses the same audited escaper — an incomplete escape is a JS
414/// injection / silent-SyntaxError hazard.
415///
416/// Escapes the JS-significant characters: `"`, `\`, the C0 controls (incl.
417/// `\n` / `\r` / `\t`), and U+2028 / U+2029 (LINE / PARAGRAPH SEPARATOR — these
418/// are line terminators *inside* JS string literals pre-ES2019 and silently
419/// break the literal otherwise).
420#[allow(dead_code)] // used only by the feature-gated engine backends
421pub(crate) fn js_string(s: &str) -> String {
422    let mut out = String::with_capacity(s.len() + 2);
423    out.push('"');
424    for c in s.chars() {
425        match c {
426            '"' => out.push_str("\\\""),
427            '\\' => out.push_str("\\\\"),
428            '\n' => out.push_str("\\n"),
429            '\r' => out.push_str("\\r"),
430            '\t' => out.push_str("\\t"),
431            '\u{2028}' => out.push_str("\\u2028"),
432            '\u{2029}' => out.push_str("\\u2029"),
433            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
434            c => out.push(c),
435        }
436    }
437    out.push('"');
438    out
439}
440
441/// Swappable web-view engine backend.
442///
443/// The real backends (`WryBackend` / `ServoBackend`, behind their features)
444/// open an engine for the host window. The test backend
445/// ([`MemoryWebViewBackend`]) records calls and synthesizes events.
446pub trait WebViewBackend {
447    /// How this backend's engines show their page. The widget asks before it
448    /// opens anything, so it knows whether to make a picture for the engine
449    /// to draw into.
450    fn rendering(&self) -> WebViewRendering;
451
452    /// Open an engine view for `web_view_id` in `window_id`'s OS window. The
453    /// backend MUST deliver browser events by calling
454    /// [`AppEventPoster::post_external`] on `poster` with a boxed
455    /// [`WebViewEventPayload`] whose `web_view_id` / `window_id_owner` match.
456    ///
457    /// `parent` is `None` when the host context can't surface an OS handle
458    /// (headless tests). A native backend cannot open without one and reports
459    /// the failure through the events above.
460    ///
461    /// `surface` is `Some` exactly when [`rendering`](Self::rendering) is
462    /// [`WebViewRendering::Surface`]: the picture the widget draws, for the
463    /// engine to write its frames into.
464    fn open(
465        &mut self,
466        web_view_id: WebViewId,
467        window_id: TeksiloWindowId,
468        parent: Option<ParentHandle>,
469        attrs: WebViewAttributes,
470        poster: Option<Arc<dyn AppEventPoster>>,
471        surface: Option<LiveImageWriter>,
472    ) -> Box<dyn WebViewHandle>;
473
474    /// Let the engine run, on the UI thread. Called by
475    /// [`WebViewRegistry::pump`] when a [`WebViewPumpPayload`] arrives; a
476    /// backend whose engine never posts one has nothing to do here.
477    fn pump(&mut self) {}
478}
479
480// ============================================================
481// WebViewRegistry — per-app service (app-state)
482// ============================================================
483
484/// Callback the `WebView` widget installs to receive its own backend events.
485type EventCallback = Box<dyn FnMut(WebViewEvent, &mut EventContext)>;
486
487struct Registered {
488    window_id: TeksiloWindowId,
489    callback: EventCallback,
490}
491
492struct RegistryState {
493    backend: RefCell<Box<dyn WebViewBackend>>,
494    callbacks: RefCell<HashMap<WebViewId, Registered>>,
495    /// Bumped per `open`, purely for diagnostics.
496    open_count: Cell<u64>,
497    /// The `(web_view_id, window)` of the delivery currently in flight, if any
498    /// (`deliver` removes the callback, runs it, then reinserts). If a
499    /// re-entrant `unregister`/`purge_window` hits this id/window while the
500    /// callback runs, `delivery_aborted` is set and `deliver` skips the
501    /// reinsert — so a since-purged callback is never resurrected even if
502    /// widget teardown becomes synchronous. `deliver` is not itself re-entrant
503    /// (backend events are posted, not delivered inline), so a single slot
504    /// suffices.
505    delivering: Cell<Option<(WebViewId, TeksiloWindowId)>>,
506    delivery_aborted: Cell<bool>,
507}
508
509/// Per-app web-view service. Registered in app-state by
510/// `TeksiloAppBuilderWebViewExt::install_web_view` (in the `teksilo` umbrella
511/// crate); reachable from any `build()` / handler via
512/// `ctx.app_state::<WebViewRegistry>()`. Cloneable; clones share the same
513/// backend and event-callback map.
514#[derive(Clone)]
515pub struct WebViewRegistry {
516    inner: Rc<RegistryState>,
517}
518
519impl WebViewRegistry {
520    /// Build a registry wrapping `backend`.
521    pub fn new<B: WebViewBackend + 'static>(backend: B) -> Self {
522        Self {
523            inner: Rc::new(RegistryState {
524                backend: RefCell::new(Box::new(backend)),
525                callbacks: RefCell::new(HashMap::new()),
526                open_count: Cell::new(0),
527                delivering: Cell::new(None),
528                delivery_aborted: Cell::new(false),
529            }),
530        }
531    }
532
533    /// How the installed backend's engines show their page.
534    pub fn rendering(&self) -> WebViewRendering {
535        self.inner.backend.borrow().rendering()
536    }
537
538    /// Let the installed backend's engine run. Called by `teksilo-app` on the
539    /// UI thread when a [`WebViewPumpPayload`] arrives.
540    pub fn pump(&self) {
541        self.inner.backend.borrow_mut().pump();
542    }
543
544    /// Open an engine view and register the widget's event callback in one
545    /// step. Returns the live [`WebViewHandle`] (dropped on widget removal).
546    /// `surface` follows the rule of [`WebViewBackend::open`].
547    #[allow(clippy::too_many_arguments)]
548    pub fn open(
549        &self,
550        web_view_id: WebViewId,
551        window_id: TeksiloWindowId,
552        parent: Option<ParentHandle>,
553        attrs: WebViewAttributes,
554        poster: Option<Arc<dyn AppEventPoster>>,
555        surface: Option<LiveImageWriter>,
556        on_event: impl FnMut(WebViewEvent, &mut EventContext) + 'static,
557    ) -> Box<dyn WebViewHandle> {
558        self.inner
559            .open_count
560            .set(self.inner.open_count.get().wrapping_add(1));
561        self.inner.callbacks.borrow_mut().insert(
562            web_view_id,
563            Registered {
564                window_id,
565                callback: Box::new(on_event),
566            },
567        );
568        self.inner
569            .backend
570            .borrow_mut()
571            .open(web_view_id, window_id, parent, attrs, poster, surface)
572    }
573
574    /// Route a backend-produced payload to its registered widget callback.
575    /// Called by `teksilo-app` from the `AppEvent::External` arm. Dropped
576    /// silently if the callback was already purged (window/widget gone).
577    pub fn deliver(&self, payload: WebViewEventPayload, ctx: &mut EventContext) {
578        // Take the callback out so the map borrow isn't held while the
579        // (re-entrant-capable) callback runs — it may itself open another web
580        // view, which inserts. Then put it back via `or_insert`, so a *newer*
581        // registration created during the callback wins and is not clobbered.
582        //
583        // The `delivering` slot guards the one remaining hazard: if the
584        // callback synchronously tears the widget/window down (a re-entrant
585        // `unregister` / `purge_window` for this id/window), we must NOT
586        // resurrect the dead callback. That marks `delivery_aborted`, and we
587        // skip the reinsert below. (Today teardown is deferred so this never
588        // fires, but the guard makes the invariant hold unconditionally.)
589        let entry = self
590            .inner
591            .callbacks
592            .borrow_mut()
593            .remove(&payload.web_view_id);
594        let Some(mut reg) = entry else {
595            return;
596        };
597        if reg.window_id != payload.window_id_owner {
598            // Stale routing — drop, don't reinsert.
599            return;
600        }
601        self.inner
602            .delivering
603            .set(Some((payload.web_view_id, reg.window_id)));
604        self.inner.delivery_aborted.set(false);
605
606        (reg.callback)(payload.event, ctx);
607
608        self.inner.delivering.set(None);
609        if !self.inner.delivery_aborted.get() {
610            self.inner
611                .callbacks
612                .borrow_mut()
613                .entry(payload.web_view_id)
614                .or_insert(reg);
615        }
616    }
617
618    /// Drop the registration for a single web view (widget removed).
619    pub fn unregister(&self, web_view_id: WebViewId) {
620        self.inner.callbacks.borrow_mut().remove(&web_view_id);
621        if matches!(self.inner.delivering.get(), Some((id, _)) if id == web_view_id) {
622            self.inner.delivery_aborted.set(true);
623        }
624    }
625
626    /// Drop every registration owned by `window_id`. Called by
627    /// `teksilo-app`'s window-close path so callbacks capturing widget state
628    /// cannot fire into a torn-down tree. Mirrors
629    /// `FileDialogHandle::purge_window`.
630    pub fn purge_window(&self, window_id: TeksiloWindowId) {
631        self.inner
632            .callbacks
633            .borrow_mut()
634            .retain(|_, r| r.window_id != window_id);
635        if matches!(self.inner.delivering.get(), Some((_, win)) if win == window_id) {
636            self.inner.delivery_aborted.set(true);
637        }
638    }
639
640    /// Number of registered web views. Test helper.
641    pub fn registered_count(&self) -> usize {
642        self.inner.callbacks.borrow().len()
643    }
644}
645
646impl std::fmt::Debug for WebViewRegistry {
647    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
648        f.debug_struct("WebViewRegistry")
649            .field("registered", &self.inner.callbacks.borrow().len())
650            .field("opens", &self.inner.open_count.get())
651            .finish_non_exhaustive()
652    }
653}
654
655// ============================================================
656// MemoryWebViewBackend (headless test backend)
657// ============================================================
658
659/// One recorded backend operation. Lets tests assert the exact call sequence
660/// (open → set_bounds → set_visible(false) → set_visible(true) → …) without a
661/// real engine, window, or GPU.
662#[derive(Debug, Clone, PartialEq)]
663pub enum WebViewOp {
664    Open {
665        web_view_id: WebViewId,
666        /// Whether the widget handed the backend a picture to draw into.
667        surface: bool,
668    },
669    SetBounds {
670        web_view_id: WebViewId,
671        bounds: Rect,
672    },
673    LoadUrl {
674        web_view_id: WebViewId,
675        url: String,
676    },
677    LoadHtml {
678        web_view_id: WebViewId,
679    },
680    Eval {
681        web_view_id: WebViewId,
682        script: String,
683    },
684    PostMessage {
685        web_view_id: WebViewId,
686        msg: String,
687    },
688    Reload {
689        web_view_id: WebViewId,
690    },
691    GoBack {
692        web_view_id: WebViewId,
693    },
694    GoForward {
695        web_view_id: WebViewId,
696    },
697    Stop {
698        web_view_id: WebViewId,
699    },
700    SetVisible {
701        web_view_id: WebViewId,
702        visible: bool,
703    },
704    SetFocus {
705        web_view_id: WebViewId,
706    },
707    SetInputPassthrough {
708        web_view_id: WebViewId,
709        passthrough: bool,
710    },
711    OpenDevtools {
712        web_view_id: WebViewId,
713    },
714    CloseDevtools {
715        web_view_id: WebViewId,
716    },
717    Blur {
718        web_view_id: WebViewId,
719    },
720    AnswerControl {
721        web_view_id: WebViewId,
722        key: u64,
723        answer: WebViewControlAnswer,
724    },
725    /// Input forwarded with [`WebViewHandle::send_input`].
726    Input {
727        web_view_id: WebViewId,
728        event: WebViewInputEvent,
729    },
730    Dropped {
731        web_view_id: WebViewId,
732    },
733}
734
735/// Shared, cloneable recorder. Both the backend and the test hold a clone, so
736/// the test can read the op log after driving the tree.
737#[derive(Clone, Default)]
738pub struct MemoryWebViewRecords {
739    ops: Rc<RefCell<Vec<WebViewOp>>>,
740    /// The scale factor of each `set_bounds`, beside its op: kept apart so
741    /// `WebViewOp::SetBounds` stays scale-independent.
742    scales: Rc<RefCell<Vec<(WebViewId, f32)>>>,
743}
744
745impl MemoryWebViewRecords {
746    /// All recorded ops, in order.
747    pub fn ops(&self) -> Vec<WebViewOp> {
748        self.ops.borrow().clone()
749    }
750
751    /// Every op for a given web view.
752    pub fn ops_for(&self, id: WebViewId) -> Vec<WebViewOp> {
753        self.ops
754            .borrow()
755            .iter()
756            .filter(|op| op_web_view_id(op) == id)
757            .cloned()
758            .collect()
759    }
760
761    /// The ordered `set_visible` booleans for a web view — the headline
762    /// dormancy assertion (`[false, true]` across a tab-away / tab-back).
763    pub fn visibility_log(&self, id: WebViewId) -> Vec<bool> {
764        self.ops
765            .borrow()
766            .iter()
767            .filter_map(|op| match op {
768                WebViewOp::SetVisible {
769                    web_view_id,
770                    visible,
771                } if *web_view_id == id => Some(*visible),
772                _ => None,
773            })
774            .collect()
775    }
776
777    /// The input forwarded to a web view, in order.
778    pub fn input_log(&self, id: WebViewId) -> Vec<WebViewInputEvent> {
779        self.ops
780            .borrow()
781            .iter()
782            .filter_map(|op| match op {
783                WebViewOp::Input { web_view_id, event } if *web_view_id == id => {
784                    Some(event.clone())
785                }
786                _ => None,
787            })
788            .collect()
789    }
790
791    /// The ordered scale factors the `set_bounds` of a web view were given,
792    /// one per [`WebViewOp::SetBounds`]: what an engine that positions in
793    /// device pixels converts the logical bounds with.
794    pub fn scale_log(&self, id: WebViewId) -> Vec<f32> {
795        self.scales
796            .borrow()
797            .iter()
798            .filter(|(web_view_id, _)| *web_view_id == id)
799            .map(|(_, scale)| *scale)
800            .collect()
801    }
802
803    fn push(&self, op: WebViewOp) {
804        self.ops.borrow_mut().push(op);
805    }
806}
807
808fn op_web_view_id(op: &WebViewOp) -> WebViewId {
809    match op {
810        WebViewOp::Open { web_view_id, .. }
811        | WebViewOp::SetBounds { web_view_id, .. }
812        | WebViewOp::LoadUrl { web_view_id, .. }
813        | WebViewOp::LoadHtml { web_view_id }
814        | WebViewOp::Eval { web_view_id, .. }
815        | WebViewOp::PostMessage { web_view_id, .. }
816        | WebViewOp::Reload { web_view_id }
817        | WebViewOp::GoBack { web_view_id }
818        | WebViewOp::GoForward { web_view_id }
819        | WebViewOp::Stop { web_view_id }
820        | WebViewOp::SetVisible { web_view_id, .. }
821        | WebViewOp::SetFocus { web_view_id }
822        | WebViewOp::SetInputPassthrough { web_view_id, .. }
823        | WebViewOp::OpenDevtools { web_view_id }
824        | WebViewOp::CloseDevtools { web_view_id }
825        | WebViewOp::Blur { web_view_id }
826        | WebViewOp::AnswerControl { web_view_id, .. }
827        | WebViewOp::Input { web_view_id, .. }
828        | WebViewOp::Dropped { web_view_id } => *web_view_id,
829    }
830}
831
832/// In-memory deterministic backend for headless tests. Records every op into a
833/// shared [`MemoryWebViewRecords`]. Mirrors `MemoryFileDialog`.
834///
835/// [`new`](Self::new) behaves as a [`WebViewRendering::NativeSubview`] engine
836/// and draws nothing. [`surface`](Self::surface) behaves as a
837/// [`WebViewRendering::Surface`] engine: each `set_bounds` commits one opaque
838/// frame of the bounds' device-pixel size, the way an engine answers a resize,
839/// so a test can lay the widget out against a frame and check where input
840/// lands.
841pub struct MemoryWebViewBackend {
842    records: MemoryWebViewRecords,
843    surface: bool,
844}
845
846/// The colour of every frame a surface [`MemoryWebViewBackend`] commits:
847/// opaque, and neither black nor white, so it is told apart from a cleared
848/// buffer.
849pub const MEMORY_SURFACE_COLOUR: [u8; 4] = [0x33, 0x66, 0x99, 0xff];
850
851impl MemoryWebViewBackend {
852    /// A native-subview backend plus its shared recorder; clone the returned
853    /// records before moving the backend into a [`WebViewRegistry`].
854    pub fn new() -> (Self, MemoryWebViewRecords) {
855        let records = MemoryWebViewRecords::default();
856        (
857            Self {
858                records: records.clone(),
859                surface: false,
860            },
861            records,
862        )
863    }
864
865    /// A surface backend plus its shared recorder.
866    pub fn surface() -> (Self, MemoryWebViewRecords) {
867        let (mut backend, records) = Self::new();
868        backend.surface = true;
869        (backend, records)
870    }
871}
872
873struct MemoryWebViewHandle {
874    web_view_id: WebViewId,
875    records: MemoryWebViewRecords,
876    surface: Option<LiveImageWriter>,
877}
878
879impl WebViewHandle for MemoryWebViewHandle {
880    fn set_bounds(&self, bounds: Rect, scale_factor: f32) {
881        // Record logical bounds (scale-independent) so test assertions stay
882        // resolution-agnostic; the scale goes to its own log.
883        self.records.push(WebViewOp::SetBounds {
884            web_view_id: self.web_view_id,
885            bounds,
886        });
887        self.records
888            .scales
889            .borrow_mut()
890            .push((self.web_view_id, scale_factor));
891        if let Some(writer) = &self.surface {
892            let width = (bounds.width * scale_factor).round().max(1.0) as u32;
893            let height = (bounds.height * scale_factor).round().max(1.0) as u32;
894            let frame: Vec<u8> = MEMORY_SURFACE_COLOUR
895                .iter()
896                .copied()
897                .cycle()
898                .take(width as usize * height as usize * 4)
899                .collect();
900            let _ = writer.write_frame(width, height, &frame, width as usize * 4);
901        }
902    }
903    fn load_url(&self, url: &str) {
904        self.records.push(WebViewOp::LoadUrl {
905            web_view_id: self.web_view_id,
906            url: url.to_string(),
907        });
908    }
909    fn load_html(&self, _html: &str, _base_url: Option<&str>) {
910        self.records.push(WebViewOp::LoadHtml {
911            web_view_id: self.web_view_id,
912        });
913    }
914    fn eval(&self, script: &str) {
915        self.records.push(WebViewOp::Eval {
916            web_view_id: self.web_view_id,
917            script: script.to_string(),
918        });
919    }
920    fn post_message(&self, msg: &str) {
921        self.records.push(WebViewOp::PostMessage {
922            web_view_id: self.web_view_id,
923            msg: msg.to_string(),
924        });
925    }
926    fn reload(&self) {
927        self.records.push(WebViewOp::Reload {
928            web_view_id: self.web_view_id,
929        });
930    }
931    fn go_back(&self) {
932        self.records.push(WebViewOp::GoBack {
933            web_view_id: self.web_view_id,
934        });
935    }
936    fn go_forward(&self) {
937        self.records.push(WebViewOp::GoForward {
938            web_view_id: self.web_view_id,
939        });
940    }
941    fn stop(&self) {
942        self.records.push(WebViewOp::Stop {
943            web_view_id: self.web_view_id,
944        });
945    }
946    fn set_visible(&self, visible: bool) {
947        self.records.push(WebViewOp::SetVisible {
948            web_view_id: self.web_view_id,
949            visible,
950        });
951    }
952    fn set_focus(&self) {
953        self.records.push(WebViewOp::SetFocus {
954            web_view_id: self.web_view_id,
955        });
956    }
957    fn set_input_passthrough(&self, passthrough: bool) {
958        self.records.push(WebViewOp::SetInputPassthrough {
959            web_view_id: self.web_view_id,
960            passthrough,
961        });
962    }
963    fn open_devtools(&self) {
964        self.records.push(WebViewOp::OpenDevtools {
965            web_view_id: self.web_view_id,
966        });
967    }
968    fn close_devtools(&self) {
969        self.records.push(WebViewOp::CloseDevtools {
970            web_view_id: self.web_view_id,
971        });
972    }
973    fn blur(&self) {
974        self.records.push(WebViewOp::Blur {
975            web_view_id: self.web_view_id,
976        });
977    }
978    fn answer_control(&self, key: u64, answer: WebViewControlAnswer) {
979        self.records.push(WebViewOp::AnswerControl {
980            web_view_id: self.web_view_id,
981            key,
982            answer,
983        });
984    }
985    fn send_input(&self, event: &WebViewInputEvent) {
986        self.records.push(WebViewOp::Input {
987            web_view_id: self.web_view_id,
988            event: event.clone(),
989        });
990    }
991}
992
993impl Drop for MemoryWebViewHandle {
994    fn drop(&mut self) {
995        self.records.push(WebViewOp::Dropped {
996            web_view_id: self.web_view_id,
997        });
998    }
999}
1000
1001impl WebViewBackend for MemoryWebViewBackend {
1002    fn rendering(&self) -> WebViewRendering {
1003        if self.surface {
1004            WebViewRendering::Surface {
1005                orientation: ImageOrientation::Normal,
1006            }
1007        } else {
1008            WebViewRendering::NativeSubview
1009        }
1010    }
1011
1012    fn open(
1013        &mut self,
1014        web_view_id: WebViewId,
1015        _window_id: TeksiloWindowId,
1016        _parent: Option<ParentHandle>,
1017        attrs: WebViewAttributes,
1018        _poster: Option<Arc<dyn AppEventPoster>>,
1019        surface: Option<LiveImageWriter>,
1020    ) -> Box<dyn WebViewHandle> {
1021        self.records.push(WebViewOp::Open {
1022            web_view_id,
1023            surface: surface.is_some(),
1024        });
1025        // Replay the initial source as the corresponding load op so tests can
1026        // see what the widget asked to display.
1027        match attrs.source {
1028            Some(WebSource::Url(url)) => self.records.push(WebViewOp::LoadUrl { web_view_id, url }),
1029            Some(WebSource::Html { .. }) => self.records.push(WebViewOp::LoadHtml { web_view_id }),
1030            None => {}
1031        }
1032        Box::new(MemoryWebViewHandle {
1033            web_view_id,
1034            records: self.records.clone(),
1035            surface,
1036        })
1037    }
1038}
1039
1040/// Convenience: a registry backed by a fresh [`MemoryWebViewBackend`], plus
1041/// its shared recorder. The one-liner headless-test setup.
1042pub fn memory_registry() -> (WebViewRegistry, MemoryWebViewRecords) {
1043    let (backend, records) = MemoryWebViewBackend::new();
1044    (WebViewRegistry::new(backend), records)
1045}
1046
1047/// The same with a surface backend ([`MemoryWebViewBackend::surface`]).
1048pub fn memory_surface_registry() -> (WebViewRegistry, MemoryWebViewRecords) {
1049    let (backend, records) = MemoryWebViewBackend::surface();
1050    (WebViewRegistry::new(backend), records)
1051}
1052
1053/// A backend that renders nothing and records nothing — every call is a no-op.
1054///
1055/// Unlike [`MemoryWebViewBackend`] (which accumulates an unbounded op log for
1056/// test assertions), this is safe to install in a long-running app as the
1057/// placeholder default until a native engine backend is wired. Used by
1058/// `install_web_view_default`.
1059#[derive(Debug, Default)]
1060pub struct NoopWebViewBackend;
1061
1062/// A [`WebViewHandle`] whose every method is a no-op. Returned by
1063/// [`NoopWebViewBackend`], and by the `WryBackend` / `ServoBackend` engine
1064/// backends on their failure paths (no parent handle, engine-init error) so a
1065/// failed open still yields a live, harmless handle. Defined once so a method
1066/// added to the trait is implemented in exactly one place. `pub(crate)` —
1067/// backends return it boxed; apps never name it.
1068pub(crate) struct NoopWebViewHandle;
1069
1070impl WebViewHandle for NoopWebViewHandle {
1071    fn set_bounds(&self, _bounds: Rect, _scale_factor: f32) {}
1072    fn load_url(&self, _url: &str) {}
1073    fn load_html(&self, _html: &str, _base_url: Option<&str>) {}
1074    fn eval(&self, _script: &str) {}
1075    fn post_message(&self, _msg: &str) {}
1076    fn reload(&self) {}
1077    fn go_back(&self) {}
1078    fn go_forward(&self) {}
1079    fn stop(&self) {}
1080    fn set_visible(&self, _visible: bool) {}
1081    fn set_focus(&self) {}
1082    fn set_input_passthrough(&self, _passthrough: bool) {
1083        // No surface, so nothing to make transparent.
1084    }
1085}
1086
1087impl WebViewBackend for NoopWebViewBackend {
1088    fn rendering(&self) -> WebViewRendering {
1089        WebViewRendering::NativeSubview
1090    }
1091
1092    fn open(
1093        &mut self,
1094        _web_view_id: WebViewId,
1095        _window_id: TeksiloWindowId,
1096        _parent: Option<ParentHandle>,
1097        _attrs: WebViewAttributes,
1098        _poster: Option<Arc<dyn AppEventPoster>>,
1099        _surface: Option<LiveImageWriter>,
1100    ) -> Box<dyn WebViewHandle> {
1101        Box::new(NoopWebViewHandle)
1102    }
1103}
1104
1105#[cfg(test)]
1106mod tests {
1107    use super::*;
1108
1109    /// A surface backend that counts the pumps it is given.
1110    struct CountingSurfaceBackend(Rc<Cell<u32>>);
1111
1112    impl WebViewBackend for CountingSurfaceBackend {
1113        fn rendering(&self) -> WebViewRendering {
1114            WebViewRendering::Surface {
1115                orientation: ImageOrientation::FlipVertical,
1116            }
1117        }
1118        fn open(
1119            &mut self,
1120            _web_view_id: WebViewId,
1121            _window_id: TeksiloWindowId,
1122            _parent: Option<ParentHandle>,
1123            _attrs: WebViewAttributes,
1124            _poster: Option<Arc<dyn AppEventPoster>>,
1125            _surface: Option<LiveImageWriter>,
1126        ) -> Box<dyn WebViewHandle> {
1127            Box::new(NoopWebViewHandle)
1128        }
1129        fn pump(&mut self) {
1130            self.0.set(self.0.get() + 1);
1131        }
1132    }
1133
1134    #[test]
1135    fn the_registry_answers_for_its_backend_and_passes_pumps_on() {
1136        let pumps = Rc::new(Cell::new(0));
1137        let registry = WebViewRegistry::new(CountingSurfaceBackend(pumps.clone()));
1138        assert_eq!(
1139            registry.rendering(),
1140            WebViewRendering::Surface {
1141                orientation: ImageOrientation::FlipVertical
1142            }
1143        );
1144        registry.pump();
1145        registry.pump();
1146        assert_eq!(pumps.get(), 2);
1147        assert_eq!(
1148            WebViewRegistry::new(NoopWebViewBackend).rendering(),
1149            WebViewRendering::NativeSubview
1150        );
1151    }
1152}