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