Skip to main content

vs_engine_webkit/backend/
wpe.rs

1//! Linux backend — real `WebKitGTK 6` driven via `webkit6` + `glib`.
2//!
3//! # Threading model
4//!
5//! WebKitGTK is bound to the GLib main context of the thread that
6//! initialized GTK. Methods on [`WpeBackend`] must be called from that
7//! thread; the type is `!Send`. Production wiring (follow-up):
8//! `vs-cli::serve` on Linux must put GTK on the OS main thread and
9//! dispatch engine calls there via `MainContext::invoke`.
10//!
11//! # Status
12//!
13//! Real WebKitGTK-backed implementation of every primitive on the
14//! [`Engine`] trait: open / close / snapshot / act / wait / layout /
15//! set_viewport / save_auth / load_auth — plus inspector capture
16//! (console + network) wired through the `UserContentManager` script-
17//! message bridge. `capture` is the only outstanding piece (a TODO in
18//! a follow-up that calls `WebView::snapshot`).
19//!
20//! Verified on Linux CI with `libwebkitgtk-6.0-dev` + `libgtk-4-dev`
21//! installed; this file is not built on macOS.
22
23use std::cell::{Cell, RefCell};
24use std::collections::HashMap;
25use std::path::PathBuf;
26use std::rc::Rc;
27use std::time::Duration;
28
29use glib::prelude::*;
30// `gtk4` is a direct dep so we can enable its `v4_10` feature (webkit6
31// needs `gtk::Accessible`); alias it to `gtk` to keep the existing refs.
32use gtk4 as gtk;
33use webkit6::prelude::*;
34use webkit6::{LoadEvent, UserContentInjectedFrames, UserScript, UserScriptInjectionTime, WebView};
35
36use vs_protocol::{Ref, Tree};
37
38use crate::engine::{
39    ActTarget, Action, AuthBlob, CaptureScope, CursorOp, DataStore, Download, DownloadEntry,
40    DownloadSource, Engine, EngineCapabilities, EngineError, EngineResult, InputMode, LayoutBox,
41    OpenStart, PageHandle, Viewport, WaitCondition,
42};
43
44// =============================================================================
45// Per-page state
46// =============================================================================
47
48struct WpePage {
49    web_view: WebView,
50    /// Hidden host window that owns `web_view` as its single child.
51    /// Required so the WebView has a `GdkSurface` on the X display —
52    /// without it XTest's synthetic input has no window to land on.
53    /// Created in `open()`, dropped on `close()`.
54    window: gtk::Window,
55    inspector: super::inspector_bridge::InspectorSlots,
56    /// True if the inspector install path actually succeeded for this
57    /// page (script + handlers registered without bail). Read by
58    /// `Engine::capabilities()` and the daemon `vs_inspect` gate.
59    inspector_installed: bool,
60    cookie_baseline: std::cell::RefCell<Option<Vec<super::auth::CookieData>>>,
61    cookie_next_seq: std::cell::RefCell<u64>,
62    /// Last known cursor position in screen-absolute CSS px. Updated
63    /// after every `cursor_op` so the next humanized lead-in starts
64    /// where the previous one ended. Defaults to (0, 0) on `open`.
65    last_mouse: Cell<vs_humanize::Point>,
66    /// A new-window navigation (`target="_blank"`, `window.open()`)
67    /// the page asked for and we have not loaded yet. Set by the
68    /// `create` handler installed in `open`.
69    new_window: Rc<RefCell<Option<webkit6::URIRequest>>>,
70    /// Downloads this page's responses turned into.
71    downloads: SharedDownloads,
72    /// The shared network session's `download-started` handler for
73    /// this page. Disconnected on close.
74    download_hook: Option<(webkit6::NetworkSession, glib::SignalHandlerId)>,
75    /// HTTP response of the latest main-frame navigation. Kept by the
76    /// `load-changed` handler from `install_response_capture`.
77    main_response: Rc<RefCell<Option<crate::inspector::MainResponse>>>,
78    /// The page's session asked for real popups (`Engine::set_popups`):
79    /// a new window becomes a page, `window.close()` releases it, and
80    /// dialogs wait for an answer. Read by the view's signal handlers.
81    popups_on: Rc<Cell<bool>>,
82    /// The page's own handle, for those handlers (set once allocated).
83    me: Rc<Cell<Option<PageHandle>>>,
84    /// Subframe agents, for evaluating in one frame (`wpe_frames`).
85    frames: Option<super::wpe_frames::FrameAgents>,
86    /// Screen position of the host window's top-left corner: its tile
87    /// (see `WpeBackend::place`), or the origin.
88    origin: Cell<(f64, f64)>,
89}
90
91type Popups = super::wpe_popups::Popups<WpePage>;
92
93/// Size of the screen tile each page window gets when the display is
94/// large enough for several (see `WpeBackend::place`). Larger than any
95/// usual viewport, so a page's window stays inside its tile.
96const TILE_W: i32 = 1600;
97const TILE_H: i32 = 1000;
98
99// =============================================================================
100// Backend
101// =============================================================================
102
103/// Real WebKitGTK 6 backend. Construct on the GTK main thread; all
104/// subsequent calls must come from the same thread.
105pub struct WpeBackend {
106    pages: HashMap<PageHandle, WpePage>,
107    /// Popups and closed pages from the views' signal handlers, the
108    /// popup feed, and the page-handle counter.
109    popups: Popups,
110    captures_dir: Option<PathBuf>,
111    /// Ephemeral network sessions for isolated sessions, by key. One
112    /// per key so every page of the session shares cookies and storage.
113    isolated_sessions: HashMap<String, webkit6::NetworkSession>,
114    /// Which page holds which screen tile (see `place`).
115    tiles: HashMap<i32, PageHandle>,
116    /// Pages whose first load is still running, by ticket (see
117    /// `open_start`), and the next ticket.
118    opening: HashMap<u64, Opening>,
119    next_ticket: u64,
120}
121
122/// A page `open_start` began whose first load has not ended yet.
123struct Opening {
124    page: WpePage,
125    /// Set by the load-finished or load-failed handler.
126    slot: Rc<RefCell<Option<Result<(), String>>>>,
127    signals: Vec<glib::SignalHandlerId>,
128    deadline: std::time::Instant,
129    budget: Duration,
130}
131
132impl Default for WpeBackend {
133    fn default() -> Self {
134        Self::new()
135    }
136}
137
138impl WpeBackend {
139    /// Build a backend. Caller must already have initialized GTK on
140    /// this thread (via `gtk4::init()`); production wiring lives in
141    /// `vs-cli::serve` on Linux. Constructing on a non-GTK thread will
142    /// panic the first time a `WebView` operation runs.
143    #[must_use]
144    pub fn new() -> Self {
145        Self {
146            pages: HashMap::new(),
147            popups: Popups::default(),
148            captures_dir: None,
149            isolated_sessions: HashMap::new(),
150            tiles: HashMap::new(),
151            opening: HashMap::new(),
152            next_ticket: 0,
153        }
154    }
155
156    /// Pin the directory where `capture` writes PNGs. Defaults to a
157    /// system temp subdirectory.
158    #[must_use]
159    pub fn with_capture_dir(mut self, dir: impl Into<PathBuf>) -> Self {
160        self.captures_dir = Some(dir.into());
161        self
162    }
163
164    fn alloc_handle(&mut self) -> PageHandle {
165        self.popups.borrow_mut().alloc()
166    }
167
168    /// Take in the windows pages opened and release the pages that
169    /// closed themselves since the last call. Runs before any page
170    /// lookup, so a popup's handle works as soon as it is reported.
171    fn sync_popups(&mut self) {
172        let (born, closed) = {
173            let mut s = self.popups.borrow_mut();
174            (std::mem::take(&mut s.born), std::mem::take(&mut s.closed))
175        };
176        for b in born {
177            self.pages.insert(b.handle, b.page);
178            self.place(b.handle);
179        }
180        for h in closed {
181            let _ = self.close(h);
182        }
183    }
184
185    /// Give a new page's window a screen tile of its own, when the
186    /// display has room for several. XTest input goes by screen
187    /// position and X has one pointer and one stacking order, so with
188    /// windows stacked at one spot, pages took each other's clicks and
189    /// hover state; apart, the pointer over one page is over no other.
190    /// On a smaller display the windows stay at the origin and input
191    /// raises its window first. Then park the pointer off every window,
192    /// so the page does not open hovered.
193    ///
194    /// Tile 0, at the screen's origin, is where new windows show while
195    /// their first load runs (the engine serves other pages meanwhile),
196    /// so no page keeps it: a page there took clicks meant for it on
197    /// the window that opened on top.
198    fn place(&mut self, handle: PageHandle) {
199        let Ok(input) = super::wpe_input::dispatcher() else {
200            return;
201        };
202        let Some((width, height)) = input.screen_size() else {
203            return;
204        };
205        let (cols, rows) = (width / TILE_W, height / TILE_H);
206        let title = window_title(handle);
207        let free = (1..cols * rows).find(|i| !self.tiles.contains_key(i));
208        // Where to park the page's pointer: past its window inside its
209        // tile, or past every window at the screen's far corner.
210        let mut park = (width - 1, height - 1);
211        if let (true, Some(slot), Some(page)) = (cols * rows >= 2, free, self.pages.get(&handle)) {
212            let (left, top) = ((slot % cols) * TILE_W, (slot / cols) * TILE_H);
213            // GTK sends the title on its own connection; make sure the
214            // server has it before looking the window up by it.
215            gtk::prelude::WidgetExt::display(&page.window).sync();
216            if input.place_window(&title, left, top) {
217                page.origin.set((f64::from(left), f64::from(top)));
218                self.tiles.insert(slot, handle);
219                park = (left + TILE_W - 1, top + TILE_H - 1);
220            }
221        }
222        // The page's own pointer (where the display has several) starts
223        // off its window, so the page does not open hovered.
224        input.use_page_pointer(&title);
225        let _ = input.dispatch(super::wpe_input::InputEvent::Move(
226            super::wpe_input::ScreenPoint {
227                x: park.0,
228                y: park.1,
229            },
230        ));
231        park_core_pointer(input, (width, height));
232    }
233
234    fn page_mut(&mut self, h: PageHandle) -> EngineResult<&mut WpePage> {
235        self.sync_popups();
236        self.pages.get_mut(&h).ok_or(EngineError::NotFound {
237            kind: "page",
238            id: h.0.to_string(),
239        })
240    }
241}
242
243// =============================================================================
244// Run-loop helper: pump the GLib main context until a predicate fires
245// =============================================================================
246
247fn run_loop_until<F: FnMut() -> bool>(mut done: F, budget: Duration) -> bool {
248    let main_ctx = glib::MainContext::default();
249    let deadline = std::time::Instant::now() + budget;
250    loop {
251        let now = std::time::Instant::now();
252        if now >= deadline {
253            break;
254        }
255        if done() {
256            return true;
257        }
258        if main_ctx.iteration(false) {
259            continue;
260        }
261        // Nothing ready: block until a source fires or the slice ends.
262        // A fixed sleep here noticed every eval result and input event
263        // up to 10ms late.
264        let left = deadline.duration_since(now).min(Duration::from_millis(50));
265        let fired = std::rc::Rc::new(Cell::new(false));
266        let flag = fired.clone();
267        let timer = glib::timeout_add_local_once(left, move || flag.set(true));
268        main_ctx.iteration(true);
269        if !fired.get() {
270            timer.remove();
271        }
272    }
273    done()
274}
275
276// =============================================================================
277// Shared payloads + parsers
278// =============================================================================
279
280use super::common::{parse_snapshot, SNAPSHOT_DOM_WALKER_JS as SNAPSHOT_JS};
281use super::native_download::{
282    is_attachment, name_from_disposition, temp_path, SharedDownloads, MAX_BYTES,
283};
284
285// =============================================================================
286// Engine impl
287// =============================================================================
288
289impl Engine for WpeBackend {
290    fn open(&mut self, url: &str, store: &DataStore) -> EngineResult<PageHandle> {
291        let ticket = match self.open_start(url, store)? {
292            OpenStart::Done(page) => return Ok(page),
293            OpenStart::Pending(ticket) => ticket,
294        };
295        if let Some(slot) = self.opening.get(&ticket).map(|o| o.slot.clone()) {
296            let budget = super::common::nav_budget();
297            let _ = run_loop_until(move || slot.borrow().is_some(), budget);
298        }
299        loop {
300            if let Some(result) = self.open_poll(ticket) {
301                return result;
302            }
303            let _ = run_loop_until(|| false, Duration::from_millis(5));
304        }
305    }
306
307    fn open_start(&mut self, url: &str, store: &DataStore) -> EngineResult<OpenStart> {
308        // An isolated session's pages share one ephemeral (in-memory)
309        // network session; everyone else gets the default persistent
310        // one. The download hook below connects to whichever session
311        // the view ends up with.
312        //
313        // A proxied session's network session also sends every request
314        // through the daemon's proxy. The ignore list is empty, so
315        // loopback is proxied too.
316        let web_view = match store.key() {
317            None => WebView::new(),
318            Some(key) => {
319                let port = store.proxy_port();
320                let session = self
321                    .isolated_sessions
322                    .entry(key.to_string())
323                    .or_insert_with(|| {
324                        let s = webkit6::NetworkSession::new_ephemeral();
325                        if let Some(port) = port {
326                            let uri = format!("http://127.0.0.1:{port}");
327                            let settings = webkit6::NetworkProxySettings::new(Some(&uri), &[]);
328                            s.set_proxy_settings(
329                                webkit6::NetworkProxyMode::Custom,
330                                Some(&settings),
331                            );
332                            // The proxy answers TLS with leaves from the
333                            // daemon's CA, made per host, so they cannot
334                            // be allowed one by one up front. Every TLS
335                            // connection of this session ends at the
336                            // proxy, which verifies upstream itself, so
337                            // certificate errors are ignored here, for
338                            // this network session only.
339                            s.set_tls_errors_policy(webkit6::TLSErrorsPolicy::Ignore);
340                        }
341                        s
342                    });
343                WebView::builder().network_session(session).build()
344            }
345        };
346
347        // Hidden host window for the WebView. v0.1.11 added native
348        // input dispatch (XTest / libei) for the cursor primitives;
349        // both require the WebView to have a real `GdkSurface` on the
350        // display server so the synthetic event has somewhere to land.
351        // `WebView::new()` alone renders to an internal offscreen
352        // surface with no display-server window — XTest events would
353        // disappear into the void. Wrapping each WebView in a
354        // decorated-off `gtk::Window` and presenting it gives us that
355        // surface; under `xvfb` (CI) the window has no visual effect.
356        let page = host_page(&web_view, &self.popups);
357        web_view.load_uri(url);
358
359        // Wait for LoadEvent::Finished or LoadEvent::Failed via signal.
360        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
361        let slot_for_signal = slot.clone();
362        let signal_id = web_view.connect_load_changed(move |_view, event| {
363            if event == LoadEvent::Finished {
364                *slot_for_signal.borrow_mut() = Some(Ok(()));
365            }
366        });
367        let slot_fail = slot.clone();
368        let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
369            *slot_fail.borrow_mut() = Some(load_result(err));
370            // Stop event propagation: we have handled it.
371            true
372        });
373
374        // The load runs in the page's web process (a new one takes tens
375        // of milliseconds to start); `open_poll` finishes the open, and
376        // the engine thread serves other pages meanwhile.
377        let budget = super::common::nav_budget();
378        let ticket = self.next_ticket;
379        self.next_ticket += 1;
380        self.opening.insert(
381            ticket,
382            Opening {
383                page,
384                slot,
385                signals: vec![signal_id, fail_id],
386                deadline: std::time::Instant::now() + budget,
387                budget,
388            },
389        );
390        Ok(OpenStart::Pending(ticket))
391    }
392
393    fn open_poll(&mut self, ticket: u64) -> Option<EngineResult<PageHandle>> {
394        let Some(o) = self.opening.get(&ticket) else {
395            return Some(Err(EngineError::Other("no open is pending".into())));
396        };
397        if o.slot.borrow().is_none() && std::time::Instant::now() < o.deadline {
398            return None;
399        }
400        let o = self.opening.remove(&ticket)?;
401        // Disconnect the handlers: the WebView outlives the open.
402        for id in o.signals {
403            o.page.web_view.disconnect(id);
404        }
405        let outcome = o.slot.borrow_mut().take();
406        match outcome {
407            None => {
408                return Some(Err(EngineError::Timeout {
409                    budget: o.budget,
410                    primitive: "open",
411                    detail: "",
412                }))
413            }
414            Some(Err(msg)) => {
415                return Some(Err(EngineError::Other(format!("navigation failed: {msg}"))))
416            }
417            Some(Ok(())) => {}
418        }
419        let page = o.page;
420        let handle = self.alloc_handle();
421        page.me.set(Some(handle));
422        page.window.set_title(Some(&window_title(handle)));
423        self.pages.insert(handle, page);
424        self.place(handle);
425        Some(Ok(handle))
426    }
427
428    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()> {
429        // Same wait as `open`, on a WebView that already exists. The
430        // inspector bridge and download shim were installed at
431        // document-start and survive the navigation, so this only has
432        // to load and wait.
433        let web_view = self.page_mut(page)?.web_view.clone();
434        web_view.load_uri(url);
435        wait_for_load(&web_view, "navigate")
436    }
437
438    fn load_html(&mut self, page: PageHandle, url: &str, html: &str) -> EngineResult<()> {
439        let web_view = self.page_mut(page)?.web_view.clone();
440        web_view.load_html(html, Some(url));
441        wait_for_load(&web_view, "load_html")
442    }
443
444    fn add_init_script(&mut self, page: PageHandle, source: &str) -> EngineResult<()> {
445        let manager = self
446            .page_mut(page)?
447            .web_view
448            .user_content_manager()
449            .ok_or_else(|| EngineError::Other("WebView has no UserContentManager".into()))?;
450        manager.add_script(&UserScript::new(
451            source,
452            UserContentInjectedFrames::AllFrames,
453            UserScriptInjectionTime::Start,
454            &[],
455            &[],
456        ));
457        Ok(())
458    }
459
460    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
461        Err(EngineError::NotImplemented {
462            engine: "wpe",
463            primitive: "enable_webauthn",
464        })
465    }
466
467    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
468        self.tiles.retain(|_, h| *h != page);
469        if let Ok(input) = super::wpe_input::dispatcher() {
470            input.drop_page_pointer(&window_title(page));
471        }
472        if let Some(mut p) = self.pages.remove(&page) {
473            if let Some((session, id)) = p.download_hook.take() {
474                session.disconnect(id);
475            }
476            // Dismiss the hidden host window so its `GdkSurface` is
477            // unmapped from the display server. `close()` queues the
478            // destroy; the GLib main context completes it on the next
479            // iteration.
480            p.window.close();
481        }
482        Ok(())
483    }
484
485    fn drop_store(&mut self, key: &str) -> EngineResult<()> {
486        // The session lives on while a closed view still references it;
487        // dropping ours lets GLib free it with the last one.
488        self.isolated_sessions.remove(key);
489        Ok(())
490    }
491
492    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
493        let p = self.page_mut(page)?;
494        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
495        parse_snapshot(&json).map_err(EngineError::Other)
496    }
497
498    fn act(
499        &mut self,
500        page: PageHandle,
501        target: ActTarget,
502        action: Action,
503        _mode: InputMode,
504    ) -> EngineResult<()> {
505        self.forget_new_window(page)?;
506        let p = self.page_mut(page)?;
507        let web_view = p.web_view.clone();
508        super::common::run_act(
509            move |js, budget| eval_js_string(&web_view, js, budget),
510            &target,
511            &action,
512        )?;
513        self.follow_new_window(page, super::common::may_open_window(&action))
514    }
515
516    fn wait(
517        &mut self,
518        page: PageHandle,
519        cond: WaitCondition,
520        budget: Duration,
521    ) -> EngineResult<()> {
522        let p = self.page_mut(page)?;
523        let web_view = p.web_view.clone();
524        super::common::run_wait(
525            |js, budget| eval_js_string(&web_view, js, budget),
526            &cond,
527            budget,
528            || {
529                let _ = run_loop_until(|| false, Duration::from_millis(50));
530            },
531        )
532    }
533    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
534        let p = self.page_mut(page)?;
535        let web_view = p.web_view.clone();
536        super::common::run_layout(
537            move |js, budget| eval_js_string(&web_view, js, budget),
538            refs,
539        )
540    }
541
542    fn download(
543        &mut self,
544        page: PageHandle,
545        source: DownloadSource,
546        budget: Duration,
547    ) -> EngineResult<Download> {
548        let p = self.page_mut(page)?;
549        let web_view = p.web_view.clone();
550        let native = p.downloads.clone();
551        super::common::run_download(
552            |js, budget| eval_js_string(&web_view, js, budget),
553            || {
554                let _ = run_loop_until(|| false, Duration::from_millis(50));
555            },
556            &source,
557            budget,
558            &native,
559        )
560    }
561
562    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
563        let p = self.page_mut(page)?;
564        let web_view = p.web_view.clone();
565        let native = p.downloads.clone();
566        super::common::run_download_list(
567            move |js, budget| eval_js_string(&web_view, js, budget),
568            &native,
569        )
570    }
571    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
572        let p = self.page_mut(page)?;
573        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
574        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
575        // The host `gtk::Window` constrains its child WebView's
576        // allocation, so resizing the WebView via `set_size_request`
577        // alone is shadowed by the (1280x800) host. Resize both: the
578        // window's default size for the surface, and the WebView's
579        // size request so its render target matches the requested
580        // viewport.
581        p.window.set_default_size(w, h);
582        p.web_view.set_size_request(w, h);
583        // Pin the sized view to the window's top-left corner: a viewport
584        // smaller than the window must not be centered, or pointer input
585        // at page coordinates would miss by the gap. (Without a size
586        // request the view fills the window, so this is only set here.)
587        p.web_view.set_halign(gtk::Align::Start);
588        p.web_view.set_valign(gtk::Align::Start);
589        Ok(())
590    }
591
592    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
593        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
594        let _ = std::fs::create_dir_all(&captures_dir);
595        let path = captures_dir.join(format!("capture-{}.png", page.0));
596        let p = self.page_mut(page)?;
597        let web_view = p.web_view.clone();
598        let out_path = path.clone();
599
600        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
601        let slot_for_cb = slot.clone();
602        web_view.snapshot(
603            webkit6::SnapshotRegion::FullDocument,
604            webkit6::SnapshotOptions::NONE,
605            None::<&webkit6::gio::Cancellable>,
606            move |result| {
607                *slot_for_cb.borrow_mut() = Some(match result {
608                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
609                    Err(e) => Err(e.to_string()),
610                });
611            },
612        );
613
614        let slot_check = slot.clone();
615        let ok = run_loop_until(
616            move || slot_check.borrow().is_some(),
617            Duration::from_secs(10),
618        );
619        if !ok {
620            return Err(EngineError::Timeout {
621                budget: Duration::from_secs(10),
622                primitive: "capture",
623                detail: "",
624            });
625        }
626        let result = slot.borrow_mut().take();
627        match result {
628            Some(Ok(())) => Ok(path),
629            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
630            None => Err(EngineError::Other(
631                "capture completed without a result".into(),
632            )),
633        }
634    }
635
636    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
637        let p = self.page_mut(page)?;
638        let web_view = p.web_view.clone();
639        // Cookies: host-side via CookieManager so HttpOnly entries
640        // are captured. localStorage/sessionStorage: JS shim.
641        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
642        let storage = super::common::run_save_storage_only(
643            move |js, budget| eval_js_string(&web_view, js, budget),
644            || {
645                let _ = run_loop_until(|| false, Duration::from_millis(50));
646            },
647        )?;
648        let blob = super::auth::AuthBlobV2 {
649            version: 2,
650            url: storage.url,
651            origin: storage.origin,
652            cookies,
653            local_storage: storage.local_storage,
654            indexed_db: storage.indexed_db,
655            indexed_db_skipped: storage.indexed_db_skipped,
656            indexed_db_incomplete: storage.indexed_db_incomplete,
657            session_storage: storage.session_storage,
658        };
659        super::auth::encode(&blob)
660    }
661
662    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
663        let p = self.page_mut(page)?;
664        let web_view = p.web_view.clone();
665        let parsed = super::auth::decode(blob)?;
666        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
667        super::common::run_load_storage_only(
668            move |js, budget| eval_js_string(&web_view, js, budget),
669            &parsed.local_storage,
670            &parsed.session_storage,
671            &parsed.indexed_db,
672            || {
673                let _ = run_loop_until(|| false, Duration::from_millis(50));
674            },
675        )
676    }
677
678    fn console_entries(
679        &mut self,
680        page: PageHandle,
681    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
682        let p = self.page_mut(page)?;
683        Ok(p.inspector.console.borrow().snapshot())
684    }
685
686    fn network_entries(
687        &mut self,
688        page: PageHandle,
689    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
690        let p = self.page_mut(page)?;
691        Ok(p.inspector.network.borrow().snapshot())
692    }
693
694    fn request_detail(
695        &mut self,
696        page: PageHandle,
697        seq: u64,
698    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
699        let p = self.page_mut(page)?;
700        Ok(p.inspector.details.borrow().get(seq).cloned())
701    }
702
703    fn eval_js(
704        &mut self,
705        page: PageHandle,
706        expr: &str,
707    ) -> EngineResult<crate::inspector::EvalResult> {
708        let p = self.page_mut(page)?;
709        let web_view = p.web_view.clone();
710        super::common::run_eval(
711            move |js, budget| eval_js_string(&web_view, js, budget),
712            expr,
713        )
714    }
715
716    fn storage(
717        &mut self,
718        page: PageHandle,
719        scope: crate::inspector::StorageScope,
720    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
721        let p = self.page_mut(page)?;
722        let web_view = p.web_view.clone();
723        if matches!(scope, crate::inspector::StorageScope::Cookies) {
724            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
725            return Ok(cookies
726                .iter()
727                .map(super::common::cookie_to_storage_entry)
728                .collect());
729        }
730        super::common::run_storage(
731            move |js, budget| eval_js_string(&web_view, js, budget),
732            scope,
733        )
734    }
735
736    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
737        let p = self.page_mut(page)?;
738        let web_view = p.web_view.clone();
739        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
740    }
741
742    fn script_source(
743        &mut self,
744        page: PageHandle,
745        seq: u64,
746    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
747        let p = self.page_mut(page)?;
748        let web_view = p.web_view.clone();
749        super::common::run_script_source(
750            move |js, budget| eval_js_string(&web_view, js, budget),
751            seq,
752        )
753    }
754
755    fn dom(
756        &mut self,
757        page: PageHandle,
758        r: Ref,
759        extra_props: &[String],
760    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
761        let p = self.page_mut(page)?;
762        let web_view = p.web_view.clone();
763        super::common::run_dom(
764            move |js, budget| eval_js_string(&web_view, js, budget),
765            r,
766            extra_props,
767        )
768    }
769
770    fn performance(
771        &mut self,
772        page: PageHandle,
773    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
774        let p = self.page_mut(page)?;
775        let web_view = p.web_view.clone();
776        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
777    }
778
779    fn main_response(
780        &mut self,
781        page: PageHandle,
782    ) -> EngineResult<Option<crate::inspector::MainResponse>> {
783        Ok(self.page_mut(page)?.main_response.borrow().clone())
784    }
785
786    fn cookie_events(
787        &mut self,
788        page: PageHandle,
789    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
790        let p = self.page_mut(page)?;
791        let web_view = p.web_view.clone();
792        let current = wpe_cookies::get_all_cookies(&web_view)?;
793        let previous = p.cookie_baseline.borrow().clone();
794        let mut seq = p.cookie_next_seq.borrow_mut();
795        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
796        *p.cookie_baseline.borrow_mut() = Some(current);
797        Ok(events)
798    }
799
800    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
801        // Addressing the page validates it and keeps the error shape
802        // the same as every other page op, even though the keys go to
803        // whatever holds focus rather than to a page handle.
804        self.forget_new_window(page)?;
805        let (cursor, tile) = {
806            let p = self.page_mut(page)?;
807            (p.last_mouse.get(), p.origin.get())
808        };
809        let dispatcher = super::wpe_input::dispatcher()?;
810        let origin = input_origin(dispatcher, page, tile);
811        // Pump GLib rather than sleep: this runs on the main thread,
812        // so a plain sleep would stop WebKit processing the very keys
813        // we are sending.
814        let settle = |d: Duration| {
815            let _ = run_loop_until(|| false, d);
816        };
817        // Put the pointer where we believe it already is before asking
818        // for focus. X hands keys to the focused window, and a
819        // headless session has no window manager to focus anything, so
820        // the pointer is what we have to go on. The caller has
821        // normally just clicked to place the caret, which means the
822        // right window is already under it.
823        #[allow(clippy::cast_possible_truncation)]
824        let at = super::wpe_input::ScreenPoint {
825            x: (origin.0 + cursor.x) as i32,
826            y: (origin.1 + cursor.y) as i32,
827        };
828        dispatcher.raise_window(&window_title(page));
829        // Keys go through the core keyboard (toolkits take them from it
830        // only), focused on this page's window by the core pointer.
831        dispatcher.use_core_pointer();
832        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
833        let _ = dispatcher.flush();
834        dispatcher.focus_pointer_window();
835
836        let (base_delay, span) = match mode {
837            InputMode::Robotic => (0_u64, 0_u64),
838            InputMode::Careful => (120, 0),
839            // ±40% of base, so repeated typing is not metronomic.
840            InputMode::Human => (45, 18),
841        };
842        let mut jitter = text
843            .chars()
844            .map(|c| c as u64)
845            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
846            | 1;
847
848        let typed = (|| -> EngineResult<()> {
849            for ch in text.chars() {
850                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
851                dispatcher.key_down(ch, &settle)?;
852                settle(Duration::from_millis(hold.max(1)));
853                dispatcher.key_up(ch)?;
854                if base_delay > 0 {
855                    jitter ^= jitter << 13;
856                    jitter ^= jitter >> 7;
857                    jitter ^= jitter << 17;
858                    let extra = if span == 0 {
859                        0
860                    } else {
861                        jitter % (span * 2 + 1)
862                    };
863                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
864                    settle(Duration::from_millis(wait.max(1)));
865                } else {
866                    settle(Duration::from_millis(1));
867                }
868            }
869            Ok(())
870        })();
871
872        // Give the borrowed keycode back whether the run finished or
873        // failed halfway: a stray binding would change what the user's
874        // own keyboard does for the rest of the session.
875        let restored = dispatcher.end_typing();
876        typed?;
877        restored?;
878
879        // Let the last keyUp turn into beforeinput/input before the
880        // caller reads the page back.
881        let _ = run_loop_until(|| false, Duration::from_millis(150));
882        // The core pointer must not stay over this page (or end up over
883        // the next one placed here) once typing is done.
884        if let Some(size) = dispatcher.screen_size() {
885            park_core_pointer(dispatcher, size);
886        }
887        self.follow_new_window(page, false)
888    }
889
890    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
891        self.forget_new_window(page)?;
892        let p = self.page_mut(page)?;
893        let dispatcher = super::wpe_input::dispatcher()?;
894        let humanize_mode = match mode {
895            InputMode::Human => vs_humanize::InputMode::Human,
896            InputMode::Careful => vs_humanize::InputMode::Careful,
897            InputMode::Robotic => vs_humanize::InputMode::Robotic,
898        };
899        // Screen origin of the hidden host window. v0.1.11 assumes
900        // (0, 0) — true under `xvfb` (CI) and any session without a
901        // window manager. With a WM, the WM may have translated the
902        // window elsewhere; a follow-up PR will query
903        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
904        // real origin. Until then, page-local CSS px == screen px,
905        // which is fine for CI and most headless setups.
906        // The web view fills the window, or is pinned to its top-left
907        // once sized (set_viewport): page coordinates are window
908        // coordinates either way.
909        let (origin_x, origin_y) = input_origin(dispatcher, page, p.origin.get());
910        // Every page's window is at the origin; put this one on top so
911        // the input reaches it and not another page's.
912        dispatcher.raise_window(&window_title(page));
913        dispatcher.use_page_pointer(&window_title(page));
914        let start = p.last_mouse.get();
915        let seed = humanize_seed(op);
916        let landed = match op {
917            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
918                dispatcher,
919                start,
920                vs_humanize::Point { x, y },
921                (origin_x, origin_y),
922                humanize_mode,
923                seed,
924                false,
925            )?,
926            CursorOp::ClickAt { x, y } => {
927                let landed = cursor_move_along_path(
928                    dispatcher,
929                    start,
930                    vs_humanize::Point { x, y },
931                    (origin_x, origin_y),
932                    humanize_mode,
933                    seed,
934                    false,
935                )?;
936                cursor_press_release(dispatcher, landed, (origin_x, origin_y), humanize_mode)?;
937                landed
938            }
939            CursorOp::Drag { x1, y1, x2, y2 } => {
940                let start_pt = vs_humanize::Point { x: x1, y: y1 };
941                let target = vs_humanize::Point { x: x2, y: y2 };
942                let pre = cursor_move_along_path(
943                    dispatcher,
944                    start,
945                    start_pt,
946                    (origin_x, origin_y),
947                    humanize_mode,
948                    seed,
949                    false,
950                )?;
951                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
952                    super::wpe_input::Button::Left,
953                ))?;
954                std::thread::sleep(Duration::from_millis(15));
955                let landed = cursor_move_along_path(
956                    dispatcher,
957                    pre,
958                    target,
959                    (origin_x, origin_y),
960                    humanize_mode,
961                    seed,
962                    true,
963                )?;
964                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
965                    super::wpe_input::Button::Left,
966                ))?;
967                dispatcher.flush()?;
968                // After the OS-level drag, fire the HTML5 DragEvent
969                // chain in JS so react-dnd / React-Flow HTML5 targets
970                // observe the drop.
971                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
972                let web_view = p.web_view.clone();
973                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
974                landed
975            }
976        };
977        p.last_mouse.set(landed);
978        deliver_input(dispatcher, &p.window);
979        self.follow_new_window(page, matches!(op, CursorOp::ClickAt { .. }))
980    }
981
982    fn set_popups(&mut self, page: PageHandle, on: bool) -> EngineResult<()> {
983        self.page_mut(page)?.popups_on.set(on);
984        Ok(())
985    }
986
987    fn eval_js_in_frame(
988        &mut self,
989        page: PageHandle,
990        frame: &str,
991        expr: &str,
992    ) -> EngineResult<crate::inspector::EvalResult> {
993        let agents = self
994            .page_mut(page)?
995            .frames
996            .clone()
997            .ok_or(EngineError::Unsupported {
998                engine: "wpe",
999                primitive: "vs_inspect eval --frame",
1000            })?;
1001        let not_found = || EngineError::NotFound {
1002            kind: "frame",
1003            id: frame.to_string(),
1004        };
1005        // A frame still loading has no agent yet; give it a moment.
1006        let probe = agents.clone();
1007        let wanted = frame.to_string();
1008        if !run_loop_until(
1009            move || super::wpe_frames::has_agent(&probe, &wanted),
1010            Duration::from_millis(500),
1011        ) {
1012            return Err(not_found());
1013        }
1014        super::common::run_eval(
1015            |js, budget| {
1016                let id = super::wpe_frames::dispatch(&agents, frame, js).ok_or_else(not_found)?;
1017                let out: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
1018                let (sink, src) = (out.clone(), agents.clone());
1019                let done = run_loop_until(
1020                    move || {
1021                        if let Some(r) = super::wpe_frames::take_result(&src, id) {
1022                            *sink.borrow_mut() = Some(r);
1023                        }
1024                        sink.borrow().is_some()
1025                    },
1026                    budget,
1027                );
1028                if !done {
1029                    return Err(EngineError::Timeout {
1030                        budget,
1031                        primitive: "eval",
1032                        detail: "",
1033                    });
1034                }
1035                let result = out.borrow_mut().take();
1036                match result {
1037                    Some(Ok(v)) => Ok(v),
1038                    Some(Err(e)) => Err(EngineError::Other(e)),
1039                    None => Err(not_found()),
1040                }
1041            },
1042            expr,
1043        )
1044    }
1045
1046    fn popup_feed(&mut self) -> Option<std::sync::Arc<crate::engine::PopupFeed>> {
1047        Some(self.popups.borrow().feed.clone())
1048    }
1049
1050    fn capabilities(&self) -> EngineCapabilities {
1051        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
1052        EngineCapabilities {
1053            renders: true,
1054            honors_viewport: true,
1055            measures_layout: true,
1056            persists_auth: true,
1057            inspector_console: any_inspector,
1058            inspector_network: any_inspector,
1059            inspector_cookie_events: true,
1060            name: "wpe",
1061            version: "Linux WebKitGTK 6 (webkit6)",
1062        }
1063    }
1064}
1065
1066// =============================================================================
1067// JS evaluation helper
1068// =============================================================================
1069
1070// =============================================================================
1071// Cursor primitive helpers (XTest / libei input dispatch)
1072// =============================================================================
1073
1074/// Deterministic seed for the humanize Bezier path so the same
1075/// `cursor_op` invocation produces the same trajectory on every run.
1076fn humanize_seed(op: CursorOp) -> u64 {
1077    // Hash the op's coordinates into a u64. Trivial mixer; replays
1078    // need determinism, not cryptographic spread.
1079    let (a, b, c, d) = match op {
1080        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
1081            (x, y, 0.0, 0.0)
1082        }
1083        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
1084    };
1085    let bits = |v: f64| v.to_bits();
1086    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
1087        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
1088        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
1089        ^ bits(d)
1090}
1091
1092/// The X window title of a page's host window. XTest input goes by
1093/// screen position, so the input path finds a page's window by this
1094/// name to place it in its tile, raise it, and give it its own pointer.
1095fn window_title(page: PageHandle) -> String {
1096    // The daemon's pid, so two daemons on one display never share a
1097    // name (and `wpe_input` can tell a dead daemon's leftovers).
1098    format!("vs-page-{}-{}", std::process::id(), page.0)
1099}
1100
1101/// Hand the input just sent to WebKit before returning. XTest events go
1102/// from the server to GTK's own connection, and GTK handles them on a
1103/// later main-loop pass; a read of the page sent right after (an eval)
1104/// could reach the web process first and see the page from before the
1105/// click. A display sync makes sure GTK has received every event the
1106/// server generated so far; dispatching what is pending then passes the
1107/// events to WebKit, whose messages to the web process keep that order.
1108fn deliver_input(dispatcher: &dyn super::wpe_input::InputDispatcher, window: &gtk::Window) {
1109    let _ = dispatcher.flush();
1110    gtk::prelude::WidgetExt::display(window).sync();
1111    let ctx = glib::MainContext::default();
1112    for _ in 0..64 {
1113        if !ctx.iteration(false) {
1114            break;
1115        }
1116    }
1117}
1118
1119/// Move the display's core pointer to the screen's far corner, past
1120/// every page window and tile, and leave input routed through it.
1121fn park_core_pointer(dispatcher: &dyn super::wpe_input::InputDispatcher, size: (i32, i32)) {
1122    dispatcher.use_core_pointer();
1123    let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(
1124        super::wpe_input::ScreenPoint {
1125            x: size.0 - 1,
1126            y: size.1 - 1,
1127        },
1128    ));
1129    let _ = dispatcher.flush();
1130}
1131
1132/// The screen origin to add to page coordinates for input. GTK moves a
1133/// window back to where it thinks it is when it resizes (`vs viewport`),
1134/// so put a drifted window back into its tile first; otherwise trust
1135/// where X says the window is.
1136fn input_origin(
1137    dispatcher: &dyn super::wpe_input::InputDispatcher,
1138    page: PageHandle,
1139    home: (f64, f64),
1140) -> (f64, f64) {
1141    let title = window_title(page);
1142    let Some((x, y)) = dispatcher.window_origin(&title) else {
1143        return home;
1144    };
1145    let now = (f64::from(x), f64::from(y));
1146    #[allow(clippy::cast_possible_truncation)]
1147    let moved_back = home != (0.0, 0.0)
1148        && now != home
1149        && dispatcher.place_window(&title, home.0 as i32, home.1 as i32);
1150    if moved_back {
1151        home
1152    } else {
1153        now
1154    }
1155}
1156
1157/// Everything a web view needs to be a page: a host window on the X
1158/// display, the user agent, the inspector bridge, download and response
1159/// capture, and the new-window, close and dialog handlers. Used for
1160/// pages `open` creates and for windows a page opens (`create`), so a
1161/// popup is the same kind of page. The caller sets `me` and the window
1162/// title once the page has a handle.
1163fn host_page(web_view: &WebView, popups: &Popups) -> WpePage {
1164    // Hidden host window: XTest input needs a real surface on the
1165    // display server to land on (see `open`). It shows at the screen's
1166    // origin until `place` moves it; no placed page keeps that tile.
1167    let window = gtk::Window::new();
1168    window.set_decorated(false);
1169    window.set_default_size(1280, 800);
1170    window.set_child(Some(web_view));
1171    window.present();
1172
1173    // Pin the User-Agent to a current Safari string so anti-bot
1174    // fingerprinters don't flag the WebKitGTK default. See the commit
1175    // log for `crate::engine::DEFAULT_USER_AGENT` rationale.
1176    if let Some(settings) = WebViewExt::settings(web_view) {
1177        settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
1178        // Expose `navigator.mediaDevices`. WebKitGTK gates the
1179        // MediaDevices surface off by default, so the object is simply
1180        // absent and anything feature-detecting camera or mic support
1181        // sees a browser that cannot exist.
1182        settings.set_enable_media_stream(true);
1183        // `act click` on this engine is a JS click, not a user gesture,
1184        // so blank-target navigation has to be allowed without one.
1185        settings.set_javascript_can_open_windows_automatically(true);
1186    }
1187
1188    // Inspector capture wiring — install the user script and register
1189    // both message channels before any load, so the bridge is live by
1190    // document-start.
1191    let inspector =
1192        super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
1193    let inspector_installed = install_inspector(web_view, &inspector);
1194    install_download_shim(web_view);
1195    let frames = super::wpe_frames::install(web_view);
1196
1197    let popups_on = Rc::new(Cell::new(false));
1198    let me: Rc<Cell<Option<PageHandle>>> = Rc::new(Cell::new(None));
1199
1200    // A new window (`target="_blank"`, `window.open()`). With popups on
1201    // it becomes a page of its own, built on a related view (same
1202    // network session and web process, so `window.opener` works) and
1203    // reported on the feed. Otherwise there is no second window: park
1204    // the request, and the input primitive that caused it loads it in
1205    // this page (`follow_new_window`).
1206    let new_window: Rc<RefCell<Option<webkit6::URIRequest>>> = Rc::new(RefCell::new(None));
1207    {
1208        let parked = new_window.clone();
1209        let on = popups_on.clone();
1210        let me = me.clone();
1211        let popups = popups.clone();
1212        web_view.connect_create(move |view, action| {
1213            if !on.get() {
1214                *parked.borrow_mut() = action.request();
1215                return None;
1216            }
1217            let url = action
1218                .request()
1219                .and_then(|r| r.uri())
1220                .map(|u| u.to_string())
1221                .unwrap_or_default();
1222            let child = WebView::builder().related_view(view).build();
1223            let page = host_page(&child, &popups);
1224            page.popups_on.set(true);
1225            let mut s = popups.borrow_mut();
1226            let handle = s.alloc();
1227            page.me.set(Some(handle));
1228            page.window.set_title(Some(&window_title(handle)));
1229            s.born.push(super::wpe_popups::Born { handle, page });
1230            s.feed
1231                .push(crate::engine::PopupEvent::Opened(crate::engine::Popup {
1232                    opener: me.get(),
1233                    page: handle,
1234                    url,
1235                }));
1236            Some(child.upcast())
1237        });
1238    }
1239    // `window.close()`: with popups on, report it; the backend releases
1240    // the page on its next lookup.
1241    {
1242        let on = popups_on.clone();
1243        let me = me.clone();
1244        let popups = popups.clone();
1245        web_view.connect_close(move |_| {
1246            if let (true, Some(h)) = (on.get(), me.get()) {
1247                let mut s = popups.borrow_mut();
1248                s.closed.push(h);
1249                s.feed.push(crate::engine::PopupEvent::Closed(h));
1250            }
1251        });
1252    }
1253    // `alert`/`confirm`/`prompt`: with popups on, report and hold for
1254    // an answer; otherwise dismiss at once, as on macOS.
1255    {
1256        let on = popups_on.clone();
1257        let me = me.clone();
1258        let popups = popups.clone();
1259        web_view.connect_script_dialog(move |_, dialog| match (on.get(), me.get()) {
1260            (true, Some(h)) => {
1261                let feed = popups.borrow().feed.clone();
1262                super::wpe_popups::hold_dialog(&feed, h, dialog)
1263            }
1264            _ => super::wpe_popups::dismiss_dialog(dialog),
1265        });
1266    }
1267
1268    let downloads = SharedDownloads::default();
1269    let download_hook = install_download_capture(web_view, &downloads);
1270    let main_response = install_response_capture(web_view);
1271    WpePage {
1272        web_view: web_view.clone(),
1273        window,
1274        inspector,
1275        inspector_installed,
1276        cookie_baseline: std::cell::RefCell::new(None),
1277        cookie_next_seq: std::cell::RefCell::new(0),
1278        last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
1279        new_window,
1280        downloads,
1281        download_hook,
1282        main_response,
1283        popups_on,
1284        me,
1285        frames,
1286        origin: Cell::new((0.0, 0.0)),
1287    }
1288}
1289
1290/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
1291/// per step at the path's prescribed timing. Returns the final point.
1292/// The `button_down` flag is unused on Linux today (XTest doesn't
1293/// distinguish drag-move from plain-move — both are `MotionNotify`
1294/// events; the held button state is tracked at the X server). Kept
1295/// in the signature so drag callers stay symmetric with the macOS
1296/// `move_along_path`.
1297fn cursor_move_along_path(
1298    dispatcher: &dyn super::wpe_input::InputDispatcher,
1299    start: vs_humanize::Point,
1300    end: vs_humanize::Point,
1301    origin: (f64, f64),
1302    mode: vs_humanize::InputMode,
1303    seed: u64,
1304    _button_down: bool,
1305) -> EngineResult<vs_humanize::Point> {
1306    let path = vs_humanize::mouse_path(start, end, mode, seed);
1307    let mut prev_ms: u128 = 0;
1308    for step in &path {
1309        if step.kind != vs_humanize::MouseStepKind::Move {
1310            continue;
1311        }
1312        let screen = super::wpe_input::ScreenPoint {
1313            #[allow(clippy::cast_possible_truncation)]
1314            x: (origin.0 + step.point.x).round() as i32,
1315            #[allow(clippy::cast_possible_truncation)]
1316            y: (origin.1 + step.point.y).round() as i32,
1317        };
1318        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
1319        let dt = step.at.as_millis().saturating_sub(prev_ms);
1320        if dt > 0 {
1321            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
1322        }
1323        prev_ms = step.at.as_millis();
1324    }
1325    // Final settling move ending exactly at `end`.
1326    let final_pt = super::wpe_input::ScreenPoint {
1327        #[allow(clippy::cast_possible_truncation)]
1328        x: (origin.0 + end.x).round() as i32,
1329        #[allow(clippy::cast_possible_truncation)]
1330        y: (origin.1 + end.y).round() as i32,
1331    };
1332    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
1333    dispatcher.flush()?;
1334    Ok(end)
1335}
1336
1337/// Press-then-release left button at the current pointer position.
1338/// Same cadence as the macOS backend (robotic 2 ms / 6 ms, otherwise
1339/// 15 ms / 30 ms), so JS sees a coherent `click` event.
1340fn cursor_press_release(
1341    dispatcher: &dyn super::wpe_input::InputDispatcher,
1342    _at: vs_humanize::Point,
1343    _origin: (f64, f64),
1344    mode: vs_humanize::InputMode,
1345) -> EngineResult<()> {
1346    // Robotic input holds the button briefly, as on macOS; the other
1347    // modes keep a human press. The waits pump the main loop (a plain
1348    // sleep stalled GTK, which then saw the events only afterwards).
1349    let (down_ms, up_ms) = match mode {
1350        vs_humanize::InputMode::Robotic => (2, 6),
1351        _ => (15, 30),
1352    };
1353    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
1354        super::wpe_input::Button::Left,
1355    ))?;
1356    dispatcher.flush()?;
1357    let _ = run_loop_until(|| false, Duration::from_millis(down_ms));
1358    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
1359        super::wpe_input::Button::Left,
1360    ))?;
1361    dispatcher.flush()?;
1362    let _ = run_loop_until(|| false, Duration::from_millis(up_ms));
1363    Ok(())
1364}
1365
1366fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
1367    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
1368    let slot_for_cb = slot.clone();
1369
1370    let cancellable = webkit6::gio::Cancellable::new();
1371    web_view.evaluate_javascript(
1372        js,
1373        None,
1374        None,
1375        Some(&cancellable),
1376        move |result| match result {
1377            Ok(value) => {
1378                let s = value.to_string();
1379                *slot_for_cb.borrow_mut() = Some(Ok(s));
1380            }
1381            Err(err) => {
1382                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
1383            }
1384        },
1385    );
1386
1387    let slot_check = slot.clone();
1388    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
1389    if !ok {
1390        return Err(EngineError::Timeout {
1391            budget,
1392            primitive: "eval",
1393            detail: "",
1394        });
1395    }
1396    let result = slot.borrow_mut().take();
1397    match result {
1398        Some(Ok(s)) => Ok(s),
1399        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
1400        None => Err(EngineError::Other("eval completed without a result".into())),
1401    }
1402}
1403
1404// =============================================================================
1405// Inspector capture wiring
1406// =============================================================================
1407
1408/// Add the download-capture shim as a document-start script in every
1409/// frame. WebKitGTK does emit a `download-started` signal, but the
1410/// shim covers what that signal cannot see — an in-page `blob:` save
1411/// whose object URL is revoked a tick later — and keeps the capture
1412/// buffer identical across all three backends.
1413fn install_download_shim(web_view: &WebView) {
1414    let Some(manager) = web_view.user_content_manager() else {
1415        return;
1416    };
1417    manager.add_script(&UserScript::new(
1418        super::common::DOWNLOAD_SHIM_JS,
1419        UserContentInjectedFrames::AllFrames,
1420        UserScriptInjectionTime::Start,
1421        &[],
1422        &[],
1423    ));
1424    // No native drags (see NO_NATIVE_DRAG_JS).
1425    manager.add_script(&UserScript::new(
1426        super::common::NO_NATIVE_DRAG_JS,
1427        UserContentInjectedFrames::AllFrames,
1428        UserScriptInjectionTime::Start,
1429        &[],
1430        &[],
1431    ));
1432}
1433
1434fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
1435    use super::inspector_bridge::{
1436        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
1437    };
1438
1439    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
1440        return false;
1441    }
1442
1443    let manager = web_view.user_content_manager().expect(
1444        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
1445    );
1446
1447    let script = UserScript::new(
1448        inspector_bridge::SCRIPT,
1449        UserContentInjectedFrames::AllFrames,
1450        UserScriptInjectionTime::Start,
1451        &[],
1452        &[],
1453    );
1454    manager.add_script(&script);
1455
1456    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
1457        return false;
1458    }
1459    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
1460        return false;
1461    }
1462
1463    let console_slots: InspectorSlots = slots.clone();
1464    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
1465        let json = value.to_string();
1466        let mut buf = console_slots.console.borrow_mut();
1467        inspector_bridge::ingest_console(&mut buf, &json);
1468    });
1469    let network_slots: InspectorSlots = slots.clone();
1470    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
1471        let json = value.to_string();
1472        let mut entries = network_slots.network.borrow_mut();
1473        let mut details = network_slots.details.borrow_mut();
1474        let mut pending = network_slots.pending.borrow_mut();
1475        inspector_bridge::ingest_network(
1476            NetworkIngestSlot {
1477                entries: &mut entries,
1478                details: &mut details,
1479                pending: &mut pending,
1480            },
1481            &json,
1482        );
1483    });
1484    true
1485}
1486
1487// =============================================================================
1488// Host-side cookie save/load via WebKitCookieManager
1489// =============================================================================
1490//
1491// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
1492// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
1493// The v0.1.2 fix routes auth save/load through this path on every
1494// platform.
1495mod wpe_cookies {
1496    use std::cell::RefCell;
1497    use std::rc::Rc;
1498    use std::time::Duration;
1499
1500    use webkit6::gio;
1501    use webkit6::glib;
1502    use webkit6::prelude::*;
1503    use webkit6::soup;
1504    use webkit6::WebView;
1505
1506    use crate::backend::auth::CookieData;
1507    use crate::engine::{EngineError, EngineResult};
1508
1509    use super::run_loop_until;
1510
1511    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
1512
1513    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
1514        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
1515            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
1516        })?;
1517        session
1518            .cookie_manager()
1519            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
1520    }
1521
1522    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
1523        let manager = cookie_manager(web_view)?;
1524        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
1525        let slot_cb = slot.clone();
1526        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
1527            let cookies = match result {
1528                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
1529                Err(_) => Vec::new(),
1530            };
1531            *slot_cb.borrow_mut() = Some(cookies);
1532        });
1533        let check = slot.clone();
1534        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
1535        if !ok {
1536            return Err(EngineError::Timeout {
1537                budget: ASYNC_BUDGET,
1538                primitive: "save_auth (all_cookies)",
1539                detail: "",
1540            });
1541        }
1542        let result = slot.borrow_mut().take().unwrap_or_default();
1543        Ok(result)
1544    }
1545
1546    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
1547        let manager = cookie_manager(web_view)?;
1548        for c in cookies {
1549            if c.name.is_empty() || c.domain.is_empty() {
1550                continue;
1551            }
1552            let path = if c.path.is_empty() {
1553                "/"
1554            } else {
1555                c.path.as_str()
1556            };
1557            // max_age=-1: session cookie (no expiration). We set
1558            // expires explicitly below if the saved blob carried it.
1559            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
1560            cookie.set_secure(c.secure);
1561            cookie.set_http_only(c.http_only);
1562            if let Some(unix) = c.expires_unix {
1563                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
1564                    cookie.set_expires(&dt);
1565                }
1566            }
1567            if let Some(ss) = c.same_site.as_deref() {
1568                let policy = match ss {
1569                    "Strict" => soup::SameSitePolicy::Strict,
1570                    "None" => soup::SameSitePolicy::None,
1571                    _ => soup::SameSitePolicy::Lax,
1572                };
1573                cookie.set_same_site_policy(policy);
1574            }
1575
1576            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
1577            let done_cb = done.clone();
1578            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
1579                *done_cb.borrow_mut() = true;
1580            });
1581            let check = done.clone();
1582            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
1583            if !ok {
1584                return Err(EngineError::Timeout {
1585                    budget: ASYNC_BUDGET,
1586                    primitive: "load_auth (add_cookie)",
1587                    detail: "",
1588                });
1589            }
1590        }
1591        Ok(())
1592    }
1593
1594    fn serialize(c: &mut soup::Cookie) -> CookieData {
1595        CookieData {
1596            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
1597            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
1598            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
1599            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
1600            expires_unix: c.expires().map(|dt| dt.to_unix()),
1601            secure: c.is_secure(),
1602            http_only: c.is_http_only(),
1603            same_site: match c.same_site_policy() {
1604                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
1605                soup::SameSitePolicy::None => Some("None".to_string()),
1606                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
1607                _ => None,
1608            },
1609        }
1610    }
1611}
1612
1613/// A load that ended because its response became a download left the
1614/// page as it was and put the file in the download buffer. Not a
1615/// failure.
1616fn load_result(err: &glib::Error) -> Result<(), String> {
1617    if err.matches(webkit6::PolicyError::FrameLoadInterruptedByPolicyChange) {
1618        Ok(())
1619    } else {
1620        Err(err.message().to_string())
1621    }
1622}
1623
1624/// Keep the HTTP response of each main-frame navigation.
1625///
1626/// `load-changed` fires for the main frame only. The slot is cleared
1627/// when a load starts, so a failed or non-HTTP load reports nothing,
1628/// and filled at commit, when the main resource has its response.
1629fn install_response_capture(
1630    web_view: &WebView,
1631) -> Rc<RefCell<Option<crate::inspector::MainResponse>>> {
1632    let slot: Rc<RefCell<Option<crate::inspector::MainResponse>>> = Rc::new(RefCell::new(None));
1633    let sink = slot.clone();
1634    web_view.connect_load_changed(move |view, event| match event {
1635        LoadEvent::Started => {
1636            sink.borrow_mut().take();
1637        }
1638        LoadEvent::Committed => {
1639            *sink.borrow_mut() = view
1640                .main_resource()
1641                .and_then(|r| r.response())
1642                .and_then(|r| http_response(&r));
1643        }
1644        _ => {}
1645    });
1646    slot
1647}
1648
1649fn http_response(resp: &webkit6::URIResponse) -> Option<crate::inspector::MainResponse> {
1650    let url = resp.uri().map(|u| u.to_string()).unwrap_or_default();
1651    if !(url.starts_with("http:") || url.starts_with("https:")) {
1652        return None;
1653    }
1654    let status = u16::try_from(resp.status_code()).unwrap_or(0);
1655    if status == 0 {
1656        return None;
1657    }
1658    let mut headers = Vec::new();
1659    if let Some(h) = resp.http_headers() {
1660        h.foreach(|name, value| headers.push((name.to_ascii_lowercase(), value.to_string())));
1661    }
1662    Some(crate::inspector::MainResponse {
1663        url,
1664        status,
1665        status_text: crate::inspector::reason_phrase(status).to_string(),
1666        headers,
1667    })
1668}
1669
1670/// Save attachments instead of dropping them.
1671///
1672/// A `Content-Disposition: attachment` response (an export button, a
1673/// form POST answering with a file, a hidden-iframe download) never
1674/// reaches page script. Turn it into a WebKit download, write it to a
1675/// temp file, and move the bytes into `downloads` for `vs_download`.
1676/// The network session is shared by every page of the same store, so
1677/// the `download-started` handler checks the download belongs to this
1678/// one.
1679fn install_download_capture(
1680    web_view: &WebView,
1681    downloads: &SharedDownloads,
1682) -> Option<(webkit6::NetworkSession, glib::SignalHandlerId)> {
1683    web_view.connect_decide_policy(|_view, decision, ty| {
1684        if ty != webkit6::PolicyDecisionType::Response {
1685            return false;
1686        }
1687        let Some(rd) = decision.downcast_ref::<webkit6::ResponsePolicyDecision>() else {
1688            return false;
1689        };
1690        let Some(resp) = rd.response() else {
1691            return false;
1692        };
1693        let uri = resp.uri().map(|u| u.to_string()).unwrap_or_default();
1694        if !(uri.starts_with("http:") || uri.starts_with("https:")) {
1695            return false;
1696        }
1697        let cd = resp
1698            .http_headers()
1699            .and_then(|h| h.one("Content-Disposition"))
1700            .map(|v| v.to_string())
1701            .unwrap_or_default();
1702        if is_attachment(&cd) || !rd.is_mime_type_supported() {
1703            decision.download();
1704            return true;
1705        }
1706        false
1707    });
1708
1709    let session = WebViewExt::network_session(web_view)?;
1710    let weak = web_view.downgrade();
1711    let downloads = downloads.clone();
1712    let id = session.connect_download_started(move |_session, download| {
1713        let Some(view) = weak.upgrade() else { return };
1714        if download.web_view().as_ref() != Some(&view) {
1715            return;
1716        }
1717        let resp = download.response();
1718        let url = resp
1719            .as_ref()
1720            .and_then(webkit6::URIResponse::uri)
1721            .or_else(|| download.request().and_then(|r| r.uri()))
1722            .map(|u| u.to_string())
1723            .unwrap_or_default();
1724        let mime = resp
1725            .as_ref()
1726            .and_then(webkit6::URIResponse::mime_type)
1727            .map(|m| m.to_string())
1728            .unwrap_or_default();
1729        let name = resp
1730            .as_ref()
1731            .and_then(webkit6::URIResponse::http_headers)
1732            .and_then(|h| h.one("Content-Disposition"))
1733            .and_then(|cd| name_from_disposition(&cd))
1734            .unwrap_or_default();
1735        let Ok(id) = downloads.lock().map(|mut d| d.begin(&url, &name, &mime)) else {
1736            return;
1737        };
1738        let path = temp_path(id);
1739        let _ = std::fs::remove_file(&path);
1740
1741        let dl = downloads.clone();
1742        download.connect_decide_destination(move |download, suggested| {
1743            if let Ok(mut d) = dl.lock() {
1744                if name.is_empty() {
1745                    d.set_name(id, suggested);
1746                }
1747            }
1748            let expected = download.response().map_or(0, |r| r.content_length());
1749            if expected > MAX_BYTES {
1750                if let Ok(mut d) = dl.lock() {
1751                    d.finish(
1752                        id,
1753                        Err(format!("download exceeds {MAX_BYTES} bytes ({expected})")),
1754                    );
1755                }
1756                download.cancel();
1757                return true;
1758            }
1759            download.set_destination(&path.to_string_lossy());
1760            true
1761        });
1762        let dl = downloads.clone();
1763        download.connect_failed(move |_download, err| {
1764            if let Ok(mut d) = dl.lock() {
1765                d.finish(id, Err(err.message().to_string()));
1766            }
1767            let _ = std::fs::remove_file(temp_path(id));
1768        });
1769        let dl = downloads.clone();
1770        download.connect_finished(move |_download| {
1771            let path = temp_path(id);
1772            // `failed` is followed by `finished`; the first result wins.
1773            let bytes = std::fs::read(&path).map_err(|e| format!("read {}: {e}", path.display()));
1774            let _ = std::fs::remove_file(&path);
1775            if let Ok(mut d) = dl.lock() {
1776                d.finish(id, bytes);
1777            }
1778        });
1779    });
1780    Some((session, id))
1781}
1782
1783/// Wait for the load already started on `web_view` to finish or fail.
1784fn wait_for_load(web_view: &WebView, primitive: &'static str) -> EngineResult<()> {
1785    let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
1786    let slot_for_signal = slot.clone();
1787    let signal_id = web_view.connect_load_changed(move |_view, event| {
1788        if event == LoadEvent::Finished {
1789            *slot_for_signal.borrow_mut() = Some(Ok(()));
1790        }
1791    });
1792    let slot_fail = slot.clone();
1793    let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
1794        *slot_fail.borrow_mut() = Some(load_result(err));
1795        true
1796    });
1797
1798    let slot_check = slot.clone();
1799    let budget = super::common::nav_budget();
1800    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
1801
1802    web_view.disconnect(signal_id);
1803    web_view.disconnect(fail_id);
1804
1805    if !ok {
1806        return Err(EngineError::Timeout {
1807            budget,
1808            primitive,
1809            detail: "",
1810        });
1811    }
1812    // Taken out of the RefCell before the match, not inside it:
1813    // as the function's tail expression the borrow guard would
1814    // otherwise outlive `slot` itself.
1815    let result = slot.borrow_mut().take();
1816    match result {
1817        Some(Ok(())) => Ok(()),
1818        Some(Err(msg)) => Err(EngineError::Other(format!("navigation failed: {msg}"))),
1819        None => Err(EngineError::Other(
1820            "navigation completed without a result".into(),
1821        )),
1822    }
1823}
1824
1825impl WpeBackend {
1826    /// Drop a new-window request parked before this input primitive
1827    /// started (a popup the page fired on its own), so the primitive
1828    /// only follows what it caused.
1829    fn forget_new_window(&mut self, page: PageHandle) -> EngineResult<()> {
1830        let _ = self.page_mut(page)?.new_window.borrow_mut().take();
1831        let mut s = self.popups.borrow_mut();
1832        s.raised_at_input = s.feed.raised();
1833        Ok(())
1834    }
1835
1836    /// Load a new-window navigation the last input primitive caused, in
1837    /// this page, and wait for it like `goto`. The `create` signal can
1838    /// arrive after the click returns, so after a click (`settle`) pump
1839    /// for up to `NEW_WINDOW_SETTLE` first. No parked request: no-op.
1840    fn follow_new_window(&mut self, page: PageHandle, settle: bool) -> EngineResult<()> {
1841        let popups = self.popups.clone();
1842        let p = self.page_mut(page)?;
1843        if settle && p.new_window.borrow().is_none() {
1844            let hint = eval_js_string(
1845                &p.web_view,
1846                super::common::NEW_WINDOW_HINT_JS,
1847                Duration::from_secs(2),
1848            );
1849            if super::common::new_window_hinted(&hint) {
1850                if p.popups_on.get() {
1851                    // A real window: wait for WebKit to ask for it, so
1852                    // the popup exists when the click returns.
1853                    let (feed, before) = {
1854                        let s = popups.borrow();
1855                        (s.feed.clone(), s.raised_at_input)
1856                    };
1857                    let _ = run_loop_until(
1858                        move || feed.raised() > before,
1859                        super::common::NEW_WINDOW_SETTLE,
1860                    );
1861                    return Ok(());
1862                }
1863                let parked = p.new_window.clone();
1864                let _ = run_loop_until(
1865                    move || parked.borrow().is_some(),
1866                    super::common::NEW_WINDOW_SETTLE,
1867                );
1868            }
1869        }
1870        let Some(request) = p.new_window.borrow_mut().take() else {
1871            return Ok(());
1872        };
1873        let web_view = p.web_view.clone();
1874        web_view.load_request(&request);
1875        wait_for_load(&web_view, "act")
1876    }
1877}