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        // A click on a ref is a native one (isTrusted), as on macOS,
509        // where the input path is available; else the JS path below.
510        if let (ActTarget::Ref(r), Action::Click) = (&target, &action) {
511            if super::wpe_input::dispatcher().is_ok() {
512                let at = super::common::ref_click_point(
513                    |js, budget| eval_js_string(&web_view, js, budget),
514                    *r,
515                )?;
516                if let Some((x, y)) = at {
517                    return self.cursor_op(page, CursorOp::ClickAt { x, y }, mode);
518                }
519            }
520        }
521        super::common::run_act(
522            move |js, budget| eval_js_string(&web_view, js, budget),
523            &target,
524            &action,
525        )?;
526        self.follow_new_window(page, super::common::may_open_window(&action))
527    }
528
529    fn wait(
530        &mut self,
531        page: PageHandle,
532        cond: WaitCondition,
533        budget: Duration,
534    ) -> EngineResult<()> {
535        let p = self.page_mut(page)?;
536        let web_view = p.web_view.clone();
537        super::common::run_wait(
538            |js, budget| eval_js_string(&web_view, js, budget),
539            &cond,
540            budget,
541            || {
542                let _ = run_loop_until(|| false, Duration::from_millis(50));
543            },
544        )
545    }
546    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
547        let p = self.page_mut(page)?;
548        let web_view = p.web_view.clone();
549        super::common::run_layout(
550            move |js, budget| eval_js_string(&web_view, js, budget),
551            refs,
552        )
553    }
554
555    fn download(
556        &mut self,
557        page: PageHandle,
558        source: DownloadSource,
559        budget: Duration,
560    ) -> EngineResult<Download> {
561        let p = self.page_mut(page)?;
562        let web_view = p.web_view.clone();
563        let native = p.downloads.clone();
564        super::common::run_download(
565            |js, budget| eval_js_string(&web_view, js, budget),
566            || {
567                let _ = run_loop_until(|| false, Duration::from_millis(50));
568            },
569            &source,
570            budget,
571            &native,
572        )
573    }
574
575    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
576        let p = self.page_mut(page)?;
577        let web_view = p.web_view.clone();
578        let native = p.downloads.clone();
579        super::common::run_download_list(
580            move |js, budget| eval_js_string(&web_view, js, budget),
581            &native,
582        )
583    }
584    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
585        let p = self.page_mut(page)?;
586        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
587        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
588        // The host `gtk::Window` constrains its child WebView's
589        // allocation, so resizing the WebView via `set_size_request`
590        // alone is shadowed by the (1280x800) host. Resize both: the
591        // window's default size for the surface, and the WebView's
592        // size request so its render target matches the requested
593        // viewport.
594        p.window.set_default_size(w, h);
595        p.web_view.set_size_request(w, h);
596        // Pin the sized view to the window's top-left corner: a viewport
597        // smaller than the window must not be centered, or pointer input
598        // at page coordinates would miss by the gap. (Without a size
599        // request the view fills the window, so this is only set here.)
600        p.web_view.set_halign(gtk::Align::Start);
601        p.web_view.set_valign(gtk::Align::Start);
602        Ok(())
603    }
604
605    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
606        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
607        let _ = std::fs::create_dir_all(&captures_dir);
608        let path = captures_dir.join(format!("capture-{}.png", page.0));
609        let p = self.page_mut(page)?;
610        let web_view = p.web_view.clone();
611        let out_path = path.clone();
612
613        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
614        let slot_for_cb = slot.clone();
615        web_view.snapshot(
616            webkit6::SnapshotRegion::FullDocument,
617            webkit6::SnapshotOptions::NONE,
618            None::<&webkit6::gio::Cancellable>,
619            move |result| {
620                *slot_for_cb.borrow_mut() = Some(match result {
621                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
622                    Err(e) => Err(e.to_string()),
623                });
624            },
625        );
626
627        let slot_check = slot.clone();
628        let ok = run_loop_until(
629            move || slot_check.borrow().is_some(),
630            Duration::from_secs(10),
631        );
632        if !ok {
633            return Err(EngineError::Timeout {
634                budget: Duration::from_secs(10),
635                primitive: "capture",
636                detail: "",
637            });
638        }
639        let result = slot.borrow_mut().take();
640        match result {
641            Some(Ok(())) => Ok(path),
642            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
643            None => Err(EngineError::Other(
644                "capture completed without a result".into(),
645            )),
646        }
647    }
648
649    fn crash(&mut self, page: PageHandle) -> EngineResult<()> {
650        let p = self.page_mut(page)?;
651        p.web_view.terminate_web_process();
652        let _ = run_loop_until(|| false, Duration::from_millis(200));
653        Ok(())
654    }
655
656    fn drop_data(
657        &mut self,
658        page: PageHandle,
659        x: f64,
660        y: f64,
661        data: &crate::engine::DropData,
662    ) -> EngineResult<bool> {
663        self.forget_new_window(page)?;
664        let dispatcher = super::wpe_input::dispatcher()?;
665        let (web_view, home) = {
666            let p = self.page_mut(page)?;
667            (p.web_view.clone(), p.origin.get())
668        };
669        let title = window_title(page);
670        // XDND needs an X11 window; a pure Wayland session has no
671        // protocol for an outside drag, so the drop arrives by script.
672        let Some(target) = dispatcher.x11_window(&title) else {
673            return Err(EngineError::Unsupported {
674                engine: "webkitgtk-wayland",
675                primitive: "drop",
676            });
677        };
678        let (ox, oy) = input_origin(dispatcher, page, home);
679        dispatcher.raise_window(&title);
680        if let Some(js) = super::drop_shim::install_js(data) {
681            eval_js_string(&web_view, &js, Duration::from_secs(2))?;
682        }
683        let accepted = super::wpe_xdnd::drop_data(target, ox + x, oy + y, data, |d| {
684            let _ = run_loop_until(|| false, d);
685        });
686        let accepted = accepted?;
687        self.follow_new_window(page, false)?;
688        Ok(accepted)
689    }
690
691    fn set_zoom(&mut self, page: PageHandle, zoom: f64) -> EngineResult<()> {
692        let p = self.page_mut(page)?;
693        p.web_view.set_zoom_level(zoom);
694        Ok(())
695    }
696
697    fn cookies(
698        &mut self,
699        page: PageHandle,
700        op: crate::engine::CookieOp,
701    ) -> EngineResult<Vec<crate::engine::CookieData>> {
702        let web_view = self.page_mut(page)?.web_view.clone();
703        match op {
704            crate::engine::CookieOp::List => {}
705            crate::engine::CookieOp::Set(list) => wpe_cookies::set_cookies(&web_view, &list)?,
706            crate::engine::CookieOp::Clear => wpe_cookies::delete_all(&web_view)?,
707        }
708        wpe_cookies::get_all_cookies(&web_view)
709    }
710
711    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
712        let p = self.page_mut(page)?;
713        let web_view = p.web_view.clone();
714        // Cookies: host-side via CookieManager so HttpOnly entries
715        // are captured. localStorage/sessionStorage: JS shim.
716        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
717        let storage = super::common::run_save_storage_only(
718            move |js, budget| eval_js_string(&web_view, js, budget),
719            || {
720                let _ = run_loop_until(|| false, Duration::from_millis(50));
721            },
722        )?;
723        let blob = super::auth::AuthBlobV2 {
724            version: 2,
725            url: storage.url,
726            origin: storage.origin,
727            cookies,
728            local_storage: storage.local_storage,
729            indexed_db: storage.indexed_db,
730            indexed_db_skipped: storage.indexed_db_skipped,
731            indexed_db_incomplete: storage.indexed_db_incomplete,
732            session_storage: storage.session_storage,
733        };
734        super::auth::encode(&blob)
735    }
736
737    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
738        let p = self.page_mut(page)?;
739        let web_view = p.web_view.clone();
740        let parsed = super::auth::decode(blob)?;
741        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
742        super::common::run_load_storage_only(
743            move |js, budget| eval_js_string(&web_view, js, budget),
744            &parsed.local_storage,
745            &parsed.session_storage,
746            &parsed.indexed_db,
747            || {
748                let _ = run_loop_until(|| false, Duration::from_millis(50));
749            },
750        )
751    }
752
753    fn console_entries(
754        &mut self,
755        page: PageHandle,
756    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
757        let p = self.page_mut(page)?;
758        Ok(p.inspector.console.borrow().snapshot())
759    }
760
761    fn network_entries(
762        &mut self,
763        page: PageHandle,
764    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
765        let p = self.page_mut(page)?;
766        Ok(p.inspector.network.borrow().snapshot())
767    }
768
769    fn request_detail(
770        &mut self,
771        page: PageHandle,
772        seq: u64,
773    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
774        let p = self.page_mut(page)?;
775        Ok(p.inspector.details.borrow().get(seq).cloned())
776    }
777
778    fn eval_js(
779        &mut self,
780        page: PageHandle,
781        expr: &str,
782    ) -> EngineResult<crate::inspector::EvalResult> {
783        let p = self.page_mut(page)?;
784        let web_view = p.web_view.clone();
785        super::common::run_eval(
786            move |js, budget| eval_js_string(&web_view, js, budget),
787            expr,
788        )
789    }
790
791    fn storage(
792        &mut self,
793        page: PageHandle,
794        scope: crate::inspector::StorageScope,
795    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
796        let p = self.page_mut(page)?;
797        let web_view = p.web_view.clone();
798        if matches!(scope, crate::inspector::StorageScope::Cookies) {
799            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
800            return Ok(cookies
801                .iter()
802                .map(super::common::cookie_to_storage_entry)
803                .collect());
804        }
805        super::common::run_storage(
806            move |js, budget| eval_js_string(&web_view, js, budget),
807            scope,
808        )
809    }
810
811    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
812        let p = self.page_mut(page)?;
813        let web_view = p.web_view.clone();
814        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
815    }
816
817    fn script_source(
818        &mut self,
819        page: PageHandle,
820        seq: u64,
821    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
822        let p = self.page_mut(page)?;
823        let web_view = p.web_view.clone();
824        super::common::run_script_source(
825            move |js, budget| eval_js_string(&web_view, js, budget),
826            seq,
827        )
828    }
829
830    fn dom(
831        &mut self,
832        page: PageHandle,
833        r: Ref,
834        extra_props: &[String],
835    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
836        let p = self.page_mut(page)?;
837        let web_view = p.web_view.clone();
838        super::common::run_dom(
839            move |js, budget| eval_js_string(&web_view, js, budget),
840            r,
841            extra_props,
842        )
843    }
844
845    fn performance(
846        &mut self,
847        page: PageHandle,
848    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
849        let p = self.page_mut(page)?;
850        let web_view = p.web_view.clone();
851        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
852    }
853
854    fn main_response(
855        &mut self,
856        page: PageHandle,
857    ) -> EngineResult<Option<crate::inspector::MainResponse>> {
858        Ok(self.page_mut(page)?.main_response.borrow().clone())
859    }
860
861    fn cookie_events(
862        &mut self,
863        page: PageHandle,
864    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
865        let p = self.page_mut(page)?;
866        let web_view = p.web_view.clone();
867        let current = wpe_cookies::get_all_cookies(&web_view)?;
868        let previous = p.cookie_baseline.borrow().clone();
869        let mut seq = p.cookie_next_seq.borrow_mut();
870        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
871        *p.cookie_baseline.borrow_mut() = Some(current);
872        Ok(events)
873    }
874
875    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
876        // Addressing the page validates it and keeps the error shape
877        // the same as every other page op, even though the keys go to
878        // whatever holds focus rather than to a page handle.
879        self.forget_new_window(page)?;
880        let (cursor, tile) = {
881            let p = self.page_mut(page)?;
882            (p.last_mouse.get(), p.origin.get())
883        };
884        let dispatcher = super::wpe_input::dispatcher()?;
885        let origin = input_origin(dispatcher, page, tile);
886        // Pump GLib rather than sleep: this runs on the main thread,
887        // so a plain sleep would stop WebKit processing the very keys
888        // we are sending.
889        let settle = |d: Duration| {
890            let _ = run_loop_until(|| false, d);
891        };
892        // Put the pointer where we believe it already is before asking
893        // for focus. X hands keys to the focused window, and a
894        // headless session has no window manager to focus anything, so
895        // the pointer is what we have to go on. The caller has
896        // normally just clicked to place the caret, which means the
897        // right window is already under it.
898        #[allow(clippy::cast_possible_truncation)]
899        let at = super::wpe_input::ScreenPoint {
900            x: (origin.0 + cursor.x) as i32,
901            y: (origin.1 + cursor.y) as i32,
902        };
903        dispatcher.raise_window(&window_title(page));
904        // Keys go through the core keyboard (toolkits take them from it
905        // only), focused on this page's window by the core pointer.
906        dispatcher.use_core_pointer();
907        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
908        let _ = dispatcher.flush();
909        dispatcher.focus_pointer_window();
910
911        let (base_delay, span) = match mode {
912            InputMode::Robotic => (0_u64, 0_u64),
913            InputMode::Careful => (120, 0),
914            // ±40% of base, so repeated typing is not metronomic.
915            InputMode::Human => (45, 18),
916        };
917        let mut jitter = text
918            .chars()
919            .map(|c| c as u64)
920            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
921            | 1;
922
923        let typed = (|| -> EngineResult<()> {
924            for ch in text.chars() {
925                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
926                dispatcher.key_down(ch, &settle)?;
927                settle(Duration::from_millis(hold.max(1)));
928                dispatcher.key_up(ch)?;
929                if base_delay > 0 {
930                    jitter ^= jitter << 13;
931                    jitter ^= jitter >> 7;
932                    jitter ^= jitter << 17;
933                    let extra = if span == 0 {
934                        0
935                    } else {
936                        jitter % (span * 2 + 1)
937                    };
938                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
939                    settle(Duration::from_millis(wait.max(1)));
940                } else {
941                    settle(Duration::from_millis(1));
942                }
943            }
944            Ok(())
945        })();
946
947        // Give the borrowed keycode back whether the run finished or
948        // failed halfway: a stray binding would change what the user's
949        // own keyboard does for the rest of the session.
950        let restored = dispatcher.end_typing();
951        typed?;
952        restored?;
953
954        // Let the last keyUp turn into beforeinput/input before the
955        // caller reads the page back.
956        let _ = run_loop_until(|| false, Duration::from_millis(150));
957        // The core pointer must not stay over this page (or end up over
958        // the next one placed here) once typing is done.
959        if let Some(size) = dispatcher.screen_size() {
960            park_core_pointer(dispatcher, size);
961        }
962        self.follow_new_window(page, false)
963    }
964
965    #[allow(clippy::too_many_lines)]
966    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
967        self.forget_new_window(page)?;
968        let p = self.page_mut(page)?;
969        let dispatcher = super::wpe_input::dispatcher()?;
970        let humanize_mode = match mode {
971            InputMode::Human => vs_humanize::InputMode::Human,
972            InputMode::Careful => vs_humanize::InputMode::Careful,
973            InputMode::Robotic => vs_humanize::InputMode::Robotic,
974        };
975        // Screen origin of the hidden host window. v0.1.11 assumes
976        // (0, 0) — true under `xvfb` (CI) and any session without a
977        // window manager. With a WM, the WM may have translated the
978        // window elsewhere; a follow-up PR will query
979        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
980        // real origin. Until then, page-local CSS px == screen px,
981        // which is fine for CI and most headless setups.
982        // The web view fills the window, or is pinned to its top-left
983        // once sized (set_viewport): page coordinates are window
984        // coordinates either way.
985        let (origin_x, origin_y) = input_origin(dispatcher, page, p.origin.get());
986        // Every page's window is at the origin; put this one on top so
987        // the input reaches it and not another page's.
988        dispatcher.raise_window(&window_title(page));
989        dispatcher.use_page_pointer(&window_title(page));
990        let start = p.last_mouse.get();
991        let seed = humanize_seed(op);
992        let landed = match op {
993            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
994                dispatcher,
995                start,
996                vs_humanize::Point { x, y },
997                (origin_x, origin_y),
998                humanize_mode,
999                seed,
1000                false,
1001            )?,
1002            CursorOp::ClickAt { x, y } => {
1003                let landed = cursor_move_along_path(
1004                    dispatcher,
1005                    start,
1006                    vs_humanize::Point { x, y },
1007                    (origin_x, origin_y),
1008                    humanize_mode,
1009                    seed,
1010                    false,
1011                )?;
1012                cursor_press_release(dispatcher, landed, (origin_x, origin_y), humanize_mode)?;
1013                landed
1014            }
1015            CursorOp::Drag { x1, y1, x2, y2 } => {
1016                let start_pt = vs_humanize::Point { x: x1, y: y1 };
1017                let target = vs_humanize::Point { x: x2, y: y2 };
1018                let pre = cursor_move_along_path(
1019                    dispatcher,
1020                    start,
1021                    start_pt,
1022                    (origin_x, origin_y),
1023                    humanize_mode,
1024                    seed,
1025                    false,
1026                )?;
1027                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
1028                    super::wpe_input::Button::Left,
1029                ))?;
1030                std::thread::sleep(Duration::from_millis(15));
1031                let landed = cursor_move_along_path(
1032                    dispatcher,
1033                    pre,
1034                    target,
1035                    (origin_x, origin_y),
1036                    humanize_mode,
1037                    seed,
1038                    true,
1039                )?;
1040                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
1041                    super::wpe_input::Button::Left,
1042                ))?;
1043                dispatcher.flush()?;
1044                // After the OS-level drag, fire the HTML5 DragEvent
1045                // chain in JS so react-dnd / React-Flow HTML5 targets
1046                // observe the drop.
1047                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
1048                let web_view = p.web_view.clone();
1049                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
1050                landed
1051            }
1052            CursorOp::Click { x, y, opts } => {
1053                let landed = cursor_move_along_path(
1054                    dispatcher,
1055                    start,
1056                    vs_humanize::Point { x, y },
1057                    (origin_x, origin_y),
1058                    humanize_mode,
1059                    seed,
1060                    false,
1061                )?;
1062                click_with(dispatcher, opts)?;
1063                landed
1064            }
1065            CursorOp::Wheel { x, y, dx, dy } => {
1066                let landed = cursor_move_along_path(
1067                    dispatcher,
1068                    start,
1069                    vs_humanize::Point { x, y },
1070                    (origin_x, origin_y),
1071                    humanize_mode,
1072                    seed,
1073                    false,
1074                )?;
1075                // One click that WebKit's handler takes as the exact
1076                // turn (see wpe_wheel); the XTest step stays the
1077                // fallback when that hook is not in place.
1078                // The portal's axis events are exact already.
1079                if dispatcher.backend_name() == "xtest" {
1080                    super::wpe_wheel::arm(dx, dy, (p.web_view.width(), p.web_view.height()));
1081                    dispatcher.dispatch(super::wpe_input::InputEvent::Wheel {
1082                        dx: if dy == 0.0 { dx.signum() } else { 0.0 },
1083                        dy: dy.signum(),
1084                        step: (1.0, 1.0),
1085                    })?;
1086                } else {
1087                    dispatcher.dispatch(super::wpe_input::InputEvent::Wheel {
1088                        dx,
1089                        dy,
1090                        step: (1.0, 1.0),
1091                    })?;
1092                }
1093                dispatcher.flush()?;
1094                deliver_input(dispatcher, &p.window);
1095                super::wpe_wheel::disarm();
1096                landed
1097            }
1098        };
1099        p.last_mouse.set(landed);
1100        deliver_input(dispatcher, &p.window);
1101        self.follow_new_window(
1102            page,
1103            matches!(op, CursorOp::ClickAt { .. } | CursorOp::Click { .. }),
1104        )
1105    }
1106
1107    fn set_popups(&mut self, page: PageHandle, on: bool) -> EngineResult<()> {
1108        self.page_mut(page)?.popups_on.set(on);
1109        Ok(())
1110    }
1111
1112    fn eval_js_in_frame(
1113        &mut self,
1114        page: PageHandle,
1115        frame: &str,
1116        expr: &str,
1117    ) -> EngineResult<crate::inspector::EvalResult> {
1118        let agents = self
1119            .page_mut(page)?
1120            .frames
1121            .clone()
1122            .ok_or(EngineError::Unsupported {
1123                engine: "wpe",
1124                primitive: "vs_inspect eval --frame",
1125            })?;
1126        let not_found = || EngineError::NotFound {
1127            kind: "frame",
1128            id: frame.to_string(),
1129        };
1130        // A frame still loading has no agent yet; give it a moment.
1131        let probe = agents.clone();
1132        let wanted = frame.to_string();
1133        if !run_loop_until(
1134            move || super::wpe_frames::has_agent(&probe, &wanted),
1135            Duration::from_millis(500),
1136        ) {
1137            return Err(not_found());
1138        }
1139        super::common::run_eval(
1140            |js, budget| {
1141                let id = super::wpe_frames::dispatch(&agents, frame, js).ok_or_else(not_found)?;
1142                let out: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
1143                let (sink, src) = (out.clone(), agents.clone());
1144                let done = run_loop_until(
1145                    move || {
1146                        if let Some(r) = super::wpe_frames::take_result(&src, id) {
1147                            *sink.borrow_mut() = Some(r);
1148                        }
1149                        sink.borrow().is_some()
1150                    },
1151                    budget,
1152                );
1153                if !done {
1154                    return Err(EngineError::Timeout {
1155                        budget,
1156                        primitive: "eval",
1157                        detail: "",
1158                    });
1159                }
1160                let result = out.borrow_mut().take();
1161                match result {
1162                    Some(Ok(v)) => Ok(v),
1163                    Some(Err(e)) => Err(EngineError::Other(e)),
1164                    None => Err(not_found()),
1165                }
1166            },
1167            expr,
1168        )
1169    }
1170
1171    fn popup_feed(&mut self) -> Option<std::sync::Arc<crate::engine::PopupFeed>> {
1172        Some(self.popups.borrow().feed.clone())
1173    }
1174
1175    fn capabilities(&self) -> EngineCapabilities {
1176        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
1177        EngineCapabilities {
1178            renders: true,
1179            honors_viewport: true,
1180            measures_layout: true,
1181            persists_auth: true,
1182            inspector_console: any_inspector,
1183            inspector_network: any_inspector,
1184            inspector_cookie_events: true,
1185            name: "wpe",
1186            version: "Linux WebKitGTK 6 (webkit6)",
1187        }
1188    }
1189}
1190
1191// =============================================================================
1192// JS evaluation helper
1193// =============================================================================
1194
1195// =============================================================================
1196// Cursor primitive helpers (XTest / libei input dispatch)
1197// =============================================================================
1198
1199/// Deterministic seed for the humanize Bezier path so the same
1200/// `cursor_op` invocation produces the same trajectory on every run.
1201/// Press and release `opts.button` `opts.count` times at the pointer,
1202/// with the modifier keys held around the clicks. Clicks this close
1203/// together are one double (or triple) click to GTK.
1204fn click_with(
1205    dispatcher: &dyn super::wpe_input::InputDispatcher,
1206    opts: crate::engine::ClickOpts,
1207) -> EngineResult<()> {
1208    use super::wpe_input::{Button, InputEvent};
1209    use crate::engine::MouseButton;
1210    // Shift_L, Control_L, Alt_L, Super_L.
1211    let held: Vec<u32> = [
1212        (opts.modifiers.shift, 0xffe1),
1213        (opts.modifiers.ctrl, 0xffe3),
1214        (opts.modifiers.alt, 0xffe9),
1215        (opts.modifiers.meta, 0xffeb),
1216    ]
1217    .into_iter()
1218    .filter_map(|(on, k)| on.then_some(k))
1219    .collect();
1220    for &k in &held {
1221        dispatcher.modifier(k, true)?;
1222    }
1223    let button = match opts.button {
1224        MouseButton::Left => Button::Left,
1225        MouseButton::Right => Button::Right,
1226        MouseButton::Middle => Button::Middle,
1227    };
1228    for _ in 0..opts.count.max(1) {
1229        dispatcher.dispatch(InputEvent::Press(button))?;
1230        dispatcher.dispatch(InputEvent::Release(button))?;
1231    }
1232    for &k in held.iter().rev() {
1233        dispatcher.modifier(k, false)?;
1234    }
1235    dispatcher.flush()
1236}
1237
1238fn humanize_seed(op: CursorOp) -> u64 {
1239    // Hash the op's coordinates into a u64. Trivial mixer; replays
1240    // need determinism, not cryptographic spread.
1241    let (a, b, c, d) = match op {
1242        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
1243            (x, y, 0.0, 0.0)
1244        }
1245        CursorOp::Wheel { x, y, dx, dy } => (x, y, dx, dy),
1246        CursorOp::Click { x, y, .. } => (x, y, 0.0, 0.0),
1247        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
1248    };
1249    let bits = |v: f64| v.to_bits();
1250    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
1251        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
1252        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
1253        ^ bits(d)
1254}
1255
1256/// The X window title of a page's host window. XTest input goes by
1257/// screen position, so the input path finds a page's window by this
1258/// name to place it in its tile, raise it, and give it its own pointer.
1259fn window_title(page: PageHandle) -> String {
1260    // The daemon's pid, so two daemons on one display never share a
1261    // name (and `wpe_input` can tell a dead daemon's leftovers).
1262    format!("vs-page-{}-{}", std::process::id(), page.0)
1263}
1264
1265/// Hand the input just sent to WebKit before returning. XTest events go
1266/// from the server to GTK's own connection, and GTK handles them on a
1267/// later main-loop pass; a read of the page sent right after (an eval)
1268/// could reach the web process first and see the page from before the
1269/// click. A display sync makes sure GTK has received every event the
1270/// server generated so far; dispatching what is pending then passes the
1271/// events to WebKit, whose messages to the web process keep that order.
1272fn deliver_input(dispatcher: &dyn super::wpe_input::InputDispatcher, window: &gtk::Window) {
1273    let _ = dispatcher.flush();
1274    gtk::prelude::WidgetExt::display(window).sync();
1275    let ctx = glib::MainContext::default();
1276    for _ in 0..64 {
1277        if !ctx.iteration(false) {
1278            break;
1279        }
1280    }
1281}
1282
1283/// Move the display's core pointer to the screen's far corner, past
1284/// every page window and tile, and leave input routed through it.
1285fn park_core_pointer(dispatcher: &dyn super::wpe_input::InputDispatcher, size: (i32, i32)) {
1286    dispatcher.use_core_pointer();
1287    let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(
1288        super::wpe_input::ScreenPoint {
1289            x: size.0 - 1,
1290            y: size.1 - 1,
1291        },
1292    ));
1293    let _ = dispatcher.flush();
1294}
1295
1296/// The screen origin to add to page coordinates for input. GTK moves a
1297/// window back to where it thinks it is when it resizes (`vs viewport`),
1298/// so put a drifted window back into its tile first; otherwise trust
1299/// where X says the window is.
1300fn input_origin(
1301    dispatcher: &dyn super::wpe_input::InputDispatcher,
1302    page: PageHandle,
1303    home: (f64, f64),
1304) -> (f64, f64) {
1305    let title = window_title(page);
1306    let Some((x, y)) = dispatcher.window_origin(&title) else {
1307        return home;
1308    };
1309    let now = (f64::from(x), f64::from(y));
1310    #[allow(clippy::cast_possible_truncation)]
1311    let moved_back = home != (0.0, 0.0)
1312        && now != home
1313        && dispatcher.place_window(&title, home.0 as i32, home.1 as i32);
1314    if moved_back {
1315        home
1316    } else {
1317        now
1318    }
1319}
1320
1321/// Everything a web view needs to be a page: a host window on the X
1322/// display, the user agent, the inspector bridge, download and response
1323/// capture, and the new-window, close and dialog handlers. Used for
1324/// pages `open` creates and for windows a page opens (`create`), so a
1325/// popup is the same kind of page. The caller sets `me` and the window
1326/// title once the page has a handle.
1327#[allow(clippy::too_many_lines)]
1328fn host_page(web_view: &WebView, popups: &Popups) -> WpePage {
1329    // No native context menu: the page still gets its contextmenu
1330    // event, and no menu stays open to take the next click.
1331    web_view.connect_context_menu(|_, _, _| true);
1332    super::wpe_wheel::install(web_view);
1333    // Hidden host window: XTest input needs a real surface on the
1334    // display server to land on (see `open`). It shows at the screen's
1335    // origin until `place` moves it; no placed page keeps that tile.
1336    let window = gtk::Window::new();
1337    window.set_decorated(false);
1338    window.set_default_size(1280, 800);
1339    window.set_child(Some(web_view));
1340    window.present();
1341
1342    // Pin the User-Agent to a current Safari string so anti-bot
1343    // fingerprinters don't flag the WebKitGTK default. See the commit
1344    // log for `crate::engine::DEFAULT_USER_AGENT` rationale.
1345    if let Some(settings) = WebViewExt::settings(web_view) {
1346        settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
1347        // Expose `navigator.mediaDevices`. WebKitGTK gates the
1348        // MediaDevices surface off by default, so the object is simply
1349        // absent and anything feature-detecting camera or mic support
1350        // sees a browser that cannot exist.
1351        settings.set_enable_media_stream(true);
1352        // `act click` on this engine is a JS click, not a user gesture,
1353        // so blank-target navigation has to be allowed without one.
1354        settings.set_javascript_can_open_windows_automatically(true);
1355    }
1356
1357    // Inspector capture wiring — install the user script and register
1358    // both message channels before any load, so the bridge is live by
1359    // document-start.
1360    let inspector =
1361        super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
1362    let inspector_installed = install_inspector(web_view, &inspector);
1363    install_download_shim(web_view);
1364    let frames = super::wpe_frames::install(web_view);
1365
1366    let popups_on = Rc::new(Cell::new(false));
1367    let me: Rc<Cell<Option<PageHandle>>> = Rc::new(Cell::new(None));
1368
1369    // A new window (`target="_blank"`, `window.open()`). With popups on
1370    // it becomes a page of its own, built on a related view (same
1371    // network session and web process, so `window.opener` works) and
1372    // reported on the feed. Otherwise there is no second window: park
1373    // the request, and the input primitive that caused it loads it in
1374    // this page (`follow_new_window`).
1375    let new_window: Rc<RefCell<Option<webkit6::URIRequest>>> = Rc::new(RefCell::new(None));
1376    {
1377        let parked = new_window.clone();
1378        let on = popups_on.clone();
1379        let me = me.clone();
1380        let popups = popups.clone();
1381        web_view.connect_create(move |view, action| {
1382            if !on.get() {
1383                *parked.borrow_mut() = action.request();
1384                return None;
1385            }
1386            let url = action
1387                .request()
1388                .and_then(|r| r.uri())
1389                .map(|u| u.to_string())
1390                .unwrap_or_default();
1391            let child = WebView::builder().related_view(view).build();
1392            let page = host_page(&child, &popups);
1393            page.popups_on.set(true);
1394            let mut s = popups.borrow_mut();
1395            let handle = s.alloc();
1396            page.me.set(Some(handle));
1397            page.window.set_title(Some(&window_title(handle)));
1398            s.born.push(super::wpe_popups::Born { handle, page });
1399            s.feed
1400                .push(crate::engine::PopupEvent::Opened(crate::engine::Popup {
1401                    opener: me.get(),
1402                    page: handle,
1403                    url,
1404                }));
1405            Some(child.upcast())
1406        });
1407    }
1408    // `window.close()`: with popups on, report it; the backend releases
1409    // the page on its next lookup.
1410    {
1411        let on = popups_on.clone();
1412        let me = me.clone();
1413        let popups = popups.clone();
1414        web_view.connect_close(move |_| {
1415            if let (true, Some(h)) = (on.get(), me.get()) {
1416                let mut s = popups.borrow_mut();
1417                s.closed.push(h);
1418                s.feed.push(crate::engine::PopupEvent::Closed(h));
1419            }
1420        });
1421    }
1422    // The web process died: report it.
1423    {
1424        let on = popups_on.clone();
1425        let me = me.clone();
1426        let popups = popups.clone();
1427        web_view.connect_web_process_terminated(move |_, _| {
1428            if let (true, Some(h)) = (on.get(), me.get()) {
1429                popups
1430                    .borrow_mut()
1431                    .feed
1432                    .push(crate::engine::PopupEvent::Crashed(h));
1433            }
1434        });
1435    }
1436    // `alert`/`confirm`/`prompt`: with popups on, report and hold for
1437    // an answer; otherwise dismiss at once, as on macOS.
1438    {
1439        let on = popups_on.clone();
1440        let me = me.clone();
1441        let popups = popups.clone();
1442        web_view.connect_script_dialog(move |_, dialog| match (on.get(), me.get()) {
1443            (true, Some(h)) => {
1444                let feed = popups.borrow().feed.clone();
1445                super::wpe_popups::hold_dialog(&feed, h, dialog)
1446            }
1447            _ => super::wpe_popups::dismiss_dialog(dialog),
1448        });
1449    }
1450
1451    let downloads = SharedDownloads::default();
1452    let download_hook = install_download_capture(web_view, &downloads);
1453    let main_response = install_response_capture(web_view);
1454    WpePage {
1455        web_view: web_view.clone(),
1456        window,
1457        inspector,
1458        inspector_installed,
1459        cookie_baseline: std::cell::RefCell::new(None),
1460        cookie_next_seq: std::cell::RefCell::new(0),
1461        last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
1462        new_window,
1463        downloads,
1464        download_hook,
1465        main_response,
1466        popups_on,
1467        me,
1468        frames,
1469        origin: Cell::new((0.0, 0.0)),
1470    }
1471}
1472
1473/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
1474/// per step at the path's prescribed timing. Returns the final point.
1475/// The `button_down` flag is unused on Linux today (XTest doesn't
1476/// distinguish drag-move from plain-move — both are `MotionNotify`
1477/// events; the held button state is tracked at the X server). Kept
1478/// in the signature so drag callers stay symmetric with the macOS
1479/// `move_along_path`.
1480fn cursor_move_along_path(
1481    dispatcher: &dyn super::wpe_input::InputDispatcher,
1482    start: vs_humanize::Point,
1483    end: vs_humanize::Point,
1484    origin: (f64, f64),
1485    mode: vs_humanize::InputMode,
1486    seed: u64,
1487    _button_down: bool,
1488) -> EngineResult<vs_humanize::Point> {
1489    let path = vs_humanize::mouse_path(start, end, mode, seed);
1490    let mut prev_ms: u128 = 0;
1491    for step in &path {
1492        if step.kind != vs_humanize::MouseStepKind::Move {
1493            continue;
1494        }
1495        let screen = super::wpe_input::ScreenPoint {
1496            #[allow(clippy::cast_possible_truncation)]
1497            x: (origin.0 + step.point.x).round() as i32,
1498            #[allow(clippy::cast_possible_truncation)]
1499            y: (origin.1 + step.point.y).round() as i32,
1500        };
1501        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
1502        let dt = step.at.as_millis().saturating_sub(prev_ms);
1503        if dt > 0 {
1504            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
1505        }
1506        prev_ms = step.at.as_millis();
1507    }
1508    // Final settling move ending exactly at `end`.
1509    let final_pt = super::wpe_input::ScreenPoint {
1510        #[allow(clippy::cast_possible_truncation)]
1511        x: (origin.0 + end.x).round() as i32,
1512        #[allow(clippy::cast_possible_truncation)]
1513        y: (origin.1 + end.y).round() as i32,
1514    };
1515    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
1516    dispatcher.flush()?;
1517    Ok(end)
1518}
1519
1520/// Press-then-release left button at the current pointer position.
1521/// Same cadence as the macOS backend (robotic 2 ms / 6 ms, otherwise
1522/// 15 ms / 30 ms), so JS sees a coherent `click` event.
1523fn cursor_press_release(
1524    dispatcher: &dyn super::wpe_input::InputDispatcher,
1525    _at: vs_humanize::Point,
1526    _origin: (f64, f64),
1527    mode: vs_humanize::InputMode,
1528) -> EngineResult<()> {
1529    // Robotic input holds the button briefly, as on macOS; the other
1530    // modes keep a human press. The waits pump the main loop (a plain
1531    // sleep stalled GTK, which then saw the events only afterwards).
1532    let (down_ms, up_ms) = match mode {
1533        vs_humanize::InputMode::Robotic => (2, 6),
1534        _ => (15, 30),
1535    };
1536    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
1537        super::wpe_input::Button::Left,
1538    ))?;
1539    dispatcher.flush()?;
1540    let _ = run_loop_until(|| false, Duration::from_millis(down_ms));
1541    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
1542        super::wpe_input::Button::Left,
1543    ))?;
1544    dispatcher.flush()?;
1545    let _ = run_loop_until(|| false, Duration::from_millis(up_ms));
1546    Ok(())
1547}
1548
1549fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
1550    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
1551    let slot_for_cb = slot.clone();
1552
1553    let cancellable = webkit6::gio::Cancellable::new();
1554    web_view.evaluate_javascript(
1555        js,
1556        None,
1557        None,
1558        Some(&cancellable),
1559        move |result| match result {
1560            Ok(value) => {
1561                let s = value.to_string();
1562                *slot_for_cb.borrow_mut() = Some(Ok(s));
1563            }
1564            Err(err) => {
1565                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
1566            }
1567        },
1568    );
1569
1570    let slot_check = slot.clone();
1571    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
1572    if !ok {
1573        return Err(EngineError::Timeout {
1574            budget,
1575            primitive: "eval",
1576            detail: "",
1577        });
1578    }
1579    let result = slot.borrow_mut().take();
1580    match result {
1581        Some(Ok(s)) => Ok(s),
1582        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
1583        None => Err(EngineError::Other("eval completed without a result".into())),
1584    }
1585}
1586
1587// =============================================================================
1588// Inspector capture wiring
1589// =============================================================================
1590
1591/// Add the download-capture shim as a document-start script in every
1592/// frame. WebKitGTK does emit a `download-started` signal, but the
1593/// shim covers what that signal cannot see — an in-page `blob:` save
1594/// whose object URL is revoked a tick later — and keeps the capture
1595/// buffer identical across all three backends.
1596fn install_download_shim(web_view: &WebView) {
1597    let Some(manager) = web_view.user_content_manager() else {
1598        return;
1599    };
1600    manager.add_script(&UserScript::new(
1601        super::common::DOWNLOAD_SHIM_JS,
1602        UserContentInjectedFrames::AllFrames,
1603        UserScriptInjectionTime::Start,
1604        &[],
1605        &[],
1606    ));
1607    // No native drags (see NO_NATIVE_DRAG_JS).
1608    manager.add_script(&UserScript::new(
1609        super::common::NO_NATIVE_DRAG_JS,
1610        UserContentInjectedFrames::AllFrames,
1611        UserScriptInjectionTime::Start,
1612        &[],
1613        &[],
1614    ));
1615}
1616
1617fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
1618    use super::inspector_bridge::{
1619        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
1620    };
1621
1622    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
1623        return false;
1624    }
1625
1626    let manager = web_view.user_content_manager().expect(
1627        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
1628    );
1629
1630    let script = UserScript::new(
1631        inspector_bridge::SCRIPT,
1632        UserContentInjectedFrames::AllFrames,
1633        UserScriptInjectionTime::Start,
1634        &[],
1635        &[],
1636    );
1637    manager.add_script(&script);
1638
1639    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
1640        return false;
1641    }
1642    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
1643        return false;
1644    }
1645
1646    let console_slots: InspectorSlots = slots.clone();
1647    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
1648        let json = value.to_string();
1649        let mut buf = console_slots.console.borrow_mut();
1650        inspector_bridge::ingest_console(&mut buf, &json);
1651    });
1652    let network_slots: InspectorSlots = slots.clone();
1653    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
1654        let json = value.to_string();
1655        let mut entries = network_slots.network.borrow_mut();
1656        let mut details = network_slots.details.borrow_mut();
1657        let mut pending = network_slots.pending.borrow_mut();
1658        inspector_bridge::ingest_network(
1659            NetworkIngestSlot {
1660                entries: &mut entries,
1661                details: &mut details,
1662                pending: &mut pending,
1663            },
1664            &json,
1665        );
1666    });
1667    true
1668}
1669
1670// =============================================================================
1671// Host-side cookie save/load via WebKitCookieManager
1672// =============================================================================
1673//
1674// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
1675// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
1676// The v0.1.2 fix routes auth save/load through this path on every
1677// platform.
1678mod wpe_cookies {
1679    use std::cell::RefCell;
1680    use std::rc::Rc;
1681    use std::time::Duration;
1682
1683    use webkit6::gio;
1684    use webkit6::glib;
1685    use webkit6::prelude::*;
1686    use webkit6::soup;
1687    use webkit6::WebView;
1688
1689    use crate::backend::auth::CookieData;
1690    use crate::engine::{EngineError, EngineResult};
1691
1692    use super::run_loop_until;
1693
1694    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
1695
1696    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
1697        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
1698            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
1699        })?;
1700        session
1701            .cookie_manager()
1702            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
1703    }
1704
1705    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
1706        let manager = cookie_manager(web_view)?;
1707        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
1708        let slot_cb = slot.clone();
1709        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
1710            let cookies = match result {
1711                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
1712                Err(_) => Vec::new(),
1713            };
1714            *slot_cb.borrow_mut() = Some(cookies);
1715        });
1716        let check = slot.clone();
1717        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
1718        if !ok {
1719            return Err(EngineError::Timeout {
1720                budget: ASYNC_BUDGET,
1721                primitive: "save_auth (all_cookies)",
1722                detail: "",
1723            });
1724        }
1725        let result = slot.borrow_mut().take().unwrap_or_default();
1726        Ok(result)
1727    }
1728
1729    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
1730        let manager = cookie_manager(web_view)?;
1731        for c in cookies {
1732            if c.name.is_empty() || c.domain.is_empty() {
1733                continue;
1734            }
1735            let path = if c.path.is_empty() {
1736                "/"
1737            } else {
1738                c.path.as_str()
1739            };
1740            // max_age=-1: session cookie (no expiration). We set
1741            // expires explicitly below if the saved blob carried it.
1742            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
1743            cookie.set_secure(c.secure);
1744            cookie.set_http_only(c.http_only);
1745            if let Some(unix) = c.expires_unix {
1746                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
1747                    cookie.set_expires(&dt);
1748                }
1749            }
1750            if let Some(ss) = c.same_site.as_deref() {
1751                let policy = match ss {
1752                    "Strict" => soup::SameSitePolicy::Strict,
1753                    "None" => soup::SameSitePolicy::None,
1754                    _ => soup::SameSitePolicy::Lax,
1755                };
1756                cookie.set_same_site_policy(policy);
1757            }
1758
1759            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
1760            let done_cb = done.clone();
1761            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
1762                *done_cb.borrow_mut() = true;
1763            });
1764            let check = done.clone();
1765            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
1766            if !ok {
1767                return Err(EngineError::Timeout {
1768                    budget: ASYNC_BUDGET,
1769                    primitive: "load_auth (add_cookie)",
1770                    detail: "",
1771                });
1772            }
1773        }
1774        Ok(())
1775    }
1776
1777    /// Delete every cookie of the web view's network session.
1778    pub(super) fn delete_all(web_view: &WebView) -> EngineResult<()> {
1779        let manager = cookie_manager(web_view)?;
1780        let slot: Rc<RefCell<Option<Vec<soup::Cookie>>>> = Rc::new(RefCell::new(None));
1781        let slot_cb = slot.clone();
1782        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
1783            *slot_cb.borrow_mut() = Some(result.unwrap_or_default());
1784        });
1785        let check = slot.clone();
1786        if !run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET) {
1787            return Err(EngineError::Timeout {
1788                budget: ASYNC_BUDGET,
1789                primitive: "cookies clear (all_cookies)",
1790                detail: "",
1791            });
1792        }
1793        let all = slot.borrow_mut().take().unwrap_or_default();
1794        let left = Rc::new(RefCell::new(all.len()));
1795        for c in &all {
1796            let left_cb = left.clone();
1797            manager.delete_cookie(c, None::<&gio::Cancellable>, move |_| {
1798                *left_cb.borrow_mut() -= 1;
1799            });
1800        }
1801        let check = left.clone();
1802        if !run_loop_until(move || *check.borrow() == 0, ASYNC_BUDGET) {
1803            return Err(EngineError::Timeout {
1804                budget: ASYNC_BUDGET,
1805                primitive: "cookies clear (delete_cookie)",
1806                detail: "",
1807            });
1808        }
1809        Ok(())
1810    }
1811
1812    fn serialize(c: &mut soup::Cookie) -> CookieData {
1813        CookieData {
1814            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
1815            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
1816            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
1817            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
1818            expires_unix: c.expires().map(|dt| dt.to_unix()),
1819            secure: c.is_secure(),
1820            http_only: c.is_http_only(),
1821            same_site: match c.same_site_policy() {
1822                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
1823                soup::SameSitePolicy::None => Some("None".to_string()),
1824                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
1825                _ => None,
1826            },
1827        }
1828    }
1829}
1830
1831/// A load that ended because its response became a download left the
1832/// page as it was and put the file in the download buffer. Not a
1833/// failure.
1834fn load_result(err: &glib::Error) -> Result<(), String> {
1835    if err.matches(webkit6::PolicyError::FrameLoadInterruptedByPolicyChange) {
1836        Ok(())
1837    } else {
1838        Err(err.message().to_string())
1839    }
1840}
1841
1842/// Keep the HTTP response of each main-frame navigation.
1843///
1844/// `load-changed` fires for the main frame only. The slot is cleared
1845/// when a load starts, so a failed or non-HTTP load reports nothing,
1846/// and filled at commit, when the main resource has its response.
1847fn install_response_capture(
1848    web_view: &WebView,
1849) -> Rc<RefCell<Option<crate::inspector::MainResponse>>> {
1850    let slot: Rc<RefCell<Option<crate::inspector::MainResponse>>> = Rc::new(RefCell::new(None));
1851    let sink = slot.clone();
1852    web_view.connect_load_changed(move |view, event| match event {
1853        LoadEvent::Started => {
1854            sink.borrow_mut().take();
1855        }
1856        LoadEvent::Committed => {
1857            *sink.borrow_mut() = view
1858                .main_resource()
1859                .and_then(|r| r.response())
1860                .and_then(|r| http_response(&r));
1861        }
1862        _ => {}
1863    });
1864    slot
1865}
1866
1867fn http_response(resp: &webkit6::URIResponse) -> Option<crate::inspector::MainResponse> {
1868    let url = resp.uri().map(|u| u.to_string()).unwrap_or_default();
1869    if !(url.starts_with("http:") || url.starts_with("https:")) {
1870        return None;
1871    }
1872    let status = u16::try_from(resp.status_code()).unwrap_or(0);
1873    if status == 0 {
1874        return None;
1875    }
1876    let mut headers = Vec::new();
1877    if let Some(h) = resp.http_headers() {
1878        h.foreach(|name, value| headers.push((name.to_ascii_lowercase(), value.to_string())));
1879    }
1880    Some(crate::inspector::MainResponse {
1881        url,
1882        status,
1883        status_text: crate::inspector::reason_phrase(status).to_string(),
1884        headers,
1885    })
1886}
1887
1888/// Save attachments instead of dropping them.
1889///
1890/// A `Content-Disposition: attachment` response (an export button, a
1891/// form POST answering with a file, a hidden-iframe download) never
1892/// reaches page script. Turn it into a WebKit download, write it to a
1893/// temp file, and move the bytes into `downloads` for `vs_download`.
1894/// The network session is shared by every page of the same store, so
1895/// the `download-started` handler checks the download belongs to this
1896/// one.
1897fn install_download_capture(
1898    web_view: &WebView,
1899    downloads: &SharedDownloads,
1900) -> Option<(webkit6::NetworkSession, glib::SignalHandlerId)> {
1901    web_view.connect_decide_policy(|_view, decision, ty| {
1902        if ty != webkit6::PolicyDecisionType::Response {
1903            return false;
1904        }
1905        let Some(rd) = decision.downcast_ref::<webkit6::ResponsePolicyDecision>() else {
1906            return false;
1907        };
1908        let Some(resp) = rd.response() else {
1909            return false;
1910        };
1911        let uri = resp.uri().map(|u| u.to_string()).unwrap_or_default();
1912        if !(uri.starts_with("http:") || uri.starts_with("https:")) {
1913            return false;
1914        }
1915        let cd = resp
1916            .http_headers()
1917            .and_then(|h| h.one("Content-Disposition"))
1918            .map(|v| v.to_string())
1919            .unwrap_or_default();
1920        if is_attachment(&cd) || !rd.is_mime_type_supported() {
1921            decision.download();
1922            return true;
1923        }
1924        false
1925    });
1926
1927    let session = WebViewExt::network_session(web_view)?;
1928    let weak = web_view.downgrade();
1929    let downloads = downloads.clone();
1930    let id = session.connect_download_started(move |_session, download| {
1931        let Some(view) = weak.upgrade() else { return };
1932        if download.web_view().as_ref() != Some(&view) {
1933            return;
1934        }
1935        let resp = download.response();
1936        let url = resp
1937            .as_ref()
1938            .and_then(webkit6::URIResponse::uri)
1939            .or_else(|| download.request().and_then(|r| r.uri()))
1940            .map(|u| u.to_string())
1941            .unwrap_or_default();
1942        let mime = resp
1943            .as_ref()
1944            .and_then(webkit6::URIResponse::mime_type)
1945            .map(|m| m.to_string())
1946            .unwrap_or_default();
1947        let name = resp
1948            .as_ref()
1949            .and_then(webkit6::URIResponse::http_headers)
1950            .and_then(|h| h.one("Content-Disposition"))
1951            .and_then(|cd| name_from_disposition(&cd))
1952            .unwrap_or_default();
1953        let Ok(id) = downloads.lock().map(|mut d| d.begin(&url, &name, &mime)) else {
1954            return;
1955        };
1956        let path = temp_path(id);
1957        let _ = std::fs::remove_file(&path);
1958
1959        let dl = downloads.clone();
1960        download.connect_decide_destination(move |download, suggested| {
1961            if let Ok(mut d) = dl.lock() {
1962                if name.is_empty() {
1963                    d.set_name(id, suggested);
1964                }
1965            }
1966            let expected = download.response().map_or(0, |r| r.content_length());
1967            if expected > MAX_BYTES {
1968                if let Ok(mut d) = dl.lock() {
1969                    d.finish(
1970                        id,
1971                        Err(format!("download exceeds {MAX_BYTES} bytes ({expected})")),
1972                    );
1973                }
1974                download.cancel();
1975                return true;
1976            }
1977            download.set_destination(&path.to_string_lossy());
1978            true
1979        });
1980        let dl = downloads.clone();
1981        download.connect_failed(move |_download, err| {
1982            if let Ok(mut d) = dl.lock() {
1983                d.finish(id, Err(err.message().to_string()));
1984            }
1985            let _ = std::fs::remove_file(temp_path(id));
1986        });
1987        let dl = downloads.clone();
1988        download.connect_finished(move |_download| {
1989            let path = temp_path(id);
1990            // `failed` is followed by `finished`; the first result wins.
1991            let bytes = std::fs::read(&path).map_err(|e| format!("read {}: {e}", path.display()));
1992            let _ = std::fs::remove_file(&path);
1993            if let Ok(mut d) = dl.lock() {
1994                d.finish(id, bytes);
1995            }
1996        });
1997    });
1998    Some((session, id))
1999}
2000
2001/// Wait for the load already started on `web_view` to finish or fail.
2002fn wait_for_load(web_view: &WebView, primitive: &'static str) -> EngineResult<()> {
2003    let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
2004    let slot_for_signal = slot.clone();
2005    let signal_id = web_view.connect_load_changed(move |_view, event| {
2006        if event == LoadEvent::Finished {
2007            *slot_for_signal.borrow_mut() = Some(Ok(()));
2008        }
2009    });
2010    let slot_fail = slot.clone();
2011    let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
2012        *slot_fail.borrow_mut() = Some(load_result(err));
2013        true
2014    });
2015
2016    let slot_check = slot.clone();
2017    let budget = super::common::nav_budget();
2018    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
2019
2020    web_view.disconnect(signal_id);
2021    web_view.disconnect(fail_id);
2022
2023    if !ok {
2024        return Err(EngineError::Timeout {
2025            budget,
2026            primitive,
2027            detail: "",
2028        });
2029    }
2030    // Taken out of the RefCell before the match, not inside it:
2031    // as the function's tail expression the borrow guard would
2032    // otherwise outlive `slot` itself.
2033    let result = slot.borrow_mut().take();
2034    match result {
2035        Some(Ok(())) => Ok(()),
2036        Some(Err(msg)) => Err(EngineError::Other(format!("navigation failed: {msg}"))),
2037        None => Err(EngineError::Other(
2038            "navigation completed without a result".into(),
2039        )),
2040    }
2041}
2042
2043impl WpeBackend {
2044    /// Drop a new-window request parked before this input primitive
2045    /// started (a popup the page fired on its own), so the primitive
2046    /// only follows what it caused.
2047    fn forget_new_window(&mut self, page: PageHandle) -> EngineResult<()> {
2048        let _ = self.page_mut(page)?.new_window.borrow_mut().take();
2049        let mut s = self.popups.borrow_mut();
2050        s.raised_at_input = s.feed.raised();
2051        Ok(())
2052    }
2053
2054    /// Load a new-window navigation the last input primitive caused, in
2055    /// this page, and wait for it like `goto`. The `create` signal can
2056    /// arrive after the click returns, so after a click (`settle`) pump
2057    /// for up to `NEW_WINDOW_SETTLE` first. No parked request: no-op.
2058    fn follow_new_window(&mut self, page: PageHandle, settle: bool) -> EngineResult<()> {
2059        let popups = self.popups.clone();
2060        let p = self.page_mut(page)?;
2061        if settle && p.new_window.borrow().is_none() {
2062            let hint = eval_js_string(
2063                &p.web_view,
2064                super::common::NEW_WINDOW_HINT_JS,
2065                Duration::from_secs(2),
2066            );
2067            if super::common::new_window_hinted(&hint) {
2068                if p.popups_on.get() {
2069                    // A real window: wait for WebKit to ask for it, so
2070                    // the popup exists when the click returns.
2071                    let (feed, before) = {
2072                        let s = popups.borrow();
2073                        (s.feed.clone(), s.raised_at_input)
2074                    };
2075                    let _ = run_loop_until(
2076                        move || feed.raised() > before,
2077                        super::common::NEW_WINDOW_SETTLE,
2078                    );
2079                    return Ok(());
2080                }
2081                let parked = p.new_window.clone();
2082                let _ = run_loop_until(
2083                    move || parked.borrow().is_some(),
2084                    super::common::NEW_WINDOW_SETTLE,
2085                );
2086            }
2087        }
2088        let Some(request) = p.new_window.borrow_mut().take() else {
2089            return Ok(());
2090        };
2091        let web_view = p.web_view.clone();
2092        web_view.load_request(&request);
2093        wait_for_load(&web_view, "act")
2094    }
2095}