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    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}
79
80// =============================================================================
81// Backend
82// =============================================================================
83
84/// Real WebKitGTK 6 backend. Construct on the GTK main thread; all
85/// subsequent calls must come from the same thread.
86pub struct WpeBackend {
87    pages: HashMap<PageHandle, WpePage>,
88    next_handle: u64,
89    captures_dir: Option<PathBuf>,
90    /// Ephemeral network sessions for isolated sessions, by key. One
91    /// per key so every page of the session shares cookies and storage.
92    isolated_sessions: HashMap<String, webkit6::NetworkSession>,
93}
94
95impl Default for WpeBackend {
96    fn default() -> Self {
97        Self::new()
98    }
99}
100
101impl WpeBackend {
102    /// Build a backend. Caller must already have initialized GTK on
103    /// this thread (via `gtk4::init()`); production wiring lives in
104    /// `vs-cli::serve` on Linux. Constructing on a non-GTK thread will
105    /// panic the first time a `WebView` operation runs.
106    #[must_use]
107    pub fn new() -> Self {
108        Self {
109            pages: HashMap::new(),
110            next_handle: 1,
111            captures_dir: None,
112            isolated_sessions: HashMap::new(),
113        }
114    }
115
116    /// Pin the directory where `capture` writes PNGs. Defaults to a
117    /// system temp subdirectory.
118    #[must_use]
119    pub fn with_capture_dir(mut self, dir: impl Into<PathBuf>) -> Self {
120        self.captures_dir = Some(dir.into());
121        self
122    }
123
124    fn alloc_handle(&mut self) -> PageHandle {
125        let h = PageHandle(self.next_handle);
126        self.next_handle += 1;
127        h
128    }
129
130    fn page_mut(&mut self, h: PageHandle) -> EngineResult<&mut WpePage> {
131        self.pages.get_mut(&h).ok_or(EngineError::NotFound {
132            kind: "page",
133            id: h.0.to_string(),
134        })
135    }
136}
137
138// =============================================================================
139// Run-loop helper: pump the GLib main context until a predicate fires
140// =============================================================================
141
142fn run_loop_until<F: FnMut() -> bool>(mut done: F, budget: Duration) -> bool {
143    let main_ctx = glib::MainContext::default();
144    let deadline = std::time::Instant::now() + budget;
145    while std::time::Instant::now() < deadline {
146        if done() {
147            return true;
148        }
149        // Iterate non-blocking; if no work, sleep briefly.
150        if !main_ctx.iteration(false) {
151            std::thread::sleep(Duration::from_millis(10));
152        }
153    }
154    done()
155}
156
157// =============================================================================
158// Shared payloads + parsers
159// =============================================================================
160
161use super::common::{parse_snapshot, SNAPSHOT_DOM_WALKER_JS as SNAPSHOT_JS};
162use super::native_download::{
163    is_attachment, name_from_disposition, temp_path, SharedDownloads, MAX_BYTES,
164};
165
166// =============================================================================
167// Engine impl
168// =============================================================================
169
170impl Engine for WpeBackend {
171    fn open(&mut self, url: &str, store: &DataStore) -> EngineResult<PageHandle> {
172        // An isolated session's pages share one ephemeral (in-memory)
173        // network session; everyone else gets the default persistent
174        // one. The download hook below connects to whichever session
175        // the view ends up with.
176        //
177        // A proxied session's network session also sends every request
178        // through the daemon's proxy. The ignore list is empty, so
179        // loopback is proxied too.
180        let web_view = match store.key() {
181            None => WebView::new(),
182            Some(key) => {
183                let port = store.proxy_port();
184                let session = self
185                    .isolated_sessions
186                    .entry(key.to_string())
187                    .or_insert_with(|| {
188                        let s = webkit6::NetworkSession::new_ephemeral();
189                        if let Some(port) = port {
190                            let uri = format!("http://127.0.0.1:{port}");
191                            let settings = webkit6::NetworkProxySettings::new(Some(&uri), &[]);
192                            s.set_proxy_settings(
193                                webkit6::NetworkProxyMode::Custom,
194                                Some(&settings),
195                            );
196                            // The proxy answers TLS with leaves from the
197                            // daemon's CA, made per host, so they cannot
198                            // be allowed one by one up front. Every TLS
199                            // connection of this session ends at the
200                            // proxy, which verifies upstream itself, so
201                            // certificate errors are ignored here, for
202                            // this network session only.
203                            s.set_tls_errors_policy(webkit6::TLSErrorsPolicy::Ignore);
204                        }
205                        s
206                    });
207                WebView::builder().network_session(session).build()
208            }
209        };
210
211        // Hidden host window for the WebView. v0.1.11 added native
212        // input dispatch (XTest / libei) for the cursor primitives;
213        // both require the WebView to have a real `GdkSurface` on the
214        // display server so the synthetic event has somewhere to land.
215        // `WebView::new()` alone renders to an internal offscreen
216        // surface with no display-server window — XTest events would
217        // disappear into the void. Wrapping each WebView in a
218        // decorated-off `gtk::Window` and presenting it gives us that
219        // surface; under `xvfb` (CI) the window has no visual effect.
220        let window = gtk::Window::new();
221        window.set_decorated(false);
222        window.set_default_size(1280, 800);
223        window.set_child(Some(&web_view));
224        window.present();
225
226        // Pin the User-Agent to a current Safari string so anti-bot
227        // fingerprinters don't flag the WebKitGTK default. See the
228        // commit log for `crate::engine::DEFAULT_USER_AGENT` rationale.
229        if let Some(settings) = WebViewExt::settings(&web_view) {
230            settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
231            // Expose `navigator.mediaDevices`. WebKitGTK gates the
232            // MediaDevices surface off by default, so the object is
233            // simply absent and anything feature-detecting camera or
234            // mic support sees a browser that cannot exist. The macOS
235            // backend needed the same switch (there via a WKPreferences
236            // KVC key); here it is public API.
237            settings.set_enable_media_stream(true);
238        }
239
240        // Inspector capture wiring — install the user script + register
241        // both message channels BEFORE load_uri so the bridge is live
242        // by document-start.
243        let inspector =
244            super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
245        let inspector_installed = install_inspector(&web_view, &inspector);
246        install_download_shim(&web_view);
247        // A headless page has no second window. Without a `create`
248        // handler WebKitGTK drops a `target="_blank"` link or form, or
249        // `window.open()`, and the click does nothing. Park the request;
250        // the input primitive that caused it loads it in this page
251        // (`follow_new_window`). `act click` on this engine is a JS
252        // click, not a user gesture, so blank-target navigation also
253        // has to be allowed without one.
254        if let Some(settings) = WebViewExt::settings(&web_view) {
255            settings.set_javascript_can_open_windows_automatically(true);
256        }
257        let new_window: Rc<RefCell<Option<webkit6::URIRequest>>> = Rc::new(RefCell::new(None));
258        let parked = new_window.clone();
259        web_view.connect_create(move |_view, action| {
260            *parked.borrow_mut() = action.request();
261            None
262        });
263        let downloads = SharedDownloads::default();
264        let download_hook = install_download_capture(&web_view, &downloads);
265        let main_response = install_response_capture(&web_view);
266        web_view.load_uri(url);
267
268        // Wait for LoadEvent::Finished or LoadEvent::Failed via signal.
269        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
270        let slot_for_signal = slot.clone();
271        let signal_id = web_view.connect_load_changed(move |_view, event| {
272            if event == LoadEvent::Finished {
273                *slot_for_signal.borrow_mut() = Some(Ok(()));
274            }
275        });
276        let slot_fail = slot.clone();
277        let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
278            *slot_fail.borrow_mut() = Some(load_result(err));
279            // Stop event propagation: we have handled it.
280            true
281        });
282
283        let slot_check = slot.clone();
284        let budget = super::common::nav_budget();
285        let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
286
287        // Disconnect signal handlers — the WebView outlives this scope.
288        web_view.disconnect(signal_id);
289        web_view.disconnect(fail_id);
290
291        if !ok {
292            return Err(EngineError::Timeout {
293                budget,
294                primitive: "open",
295                detail: "",
296            });
297        }
298        match slot.borrow_mut().take() {
299            Some(Ok(())) => {}
300            Some(Err(msg)) => return Err(EngineError::Other(format!("navigation failed: {msg}"))),
301            None => {
302                return Err(EngineError::Other(
303                    "navigation completed without a result".into(),
304                ))
305            }
306        }
307
308        let handle = self.alloc_handle();
309        self.pages.insert(
310            handle,
311            WpePage {
312                web_view,
313                window: titled(window, handle),
314                inspector,
315                inspector_installed,
316                cookie_baseline: std::cell::RefCell::new(None),
317                cookie_next_seq: std::cell::RefCell::new(0),
318                last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
319                new_window,
320                downloads,
321                download_hook,
322                main_response,
323            },
324        );
325        Ok(handle)
326    }
327
328    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()> {
329        // Same wait as `open`, on a WebView that already exists. The
330        // inspector bridge and download shim were installed at
331        // document-start and survive the navigation, so this only has
332        // to load and wait.
333        let web_view = self.page_mut(page)?.web_view.clone();
334        web_view.load_uri(url);
335        wait_for_load(&web_view, "navigate")
336    }
337
338    fn load_html(&mut self, page: PageHandle, url: &str, html: &str) -> EngineResult<()> {
339        let web_view = self.page_mut(page)?.web_view.clone();
340        web_view.load_html(html, Some(url));
341        wait_for_load(&web_view, "load_html")
342    }
343
344    fn add_init_script(&mut self, page: PageHandle, source: &str) -> EngineResult<()> {
345        let manager = self
346            .page_mut(page)?
347            .web_view
348            .user_content_manager()
349            .ok_or_else(|| EngineError::Other("WebView has no UserContentManager".into()))?;
350        manager.add_script(&UserScript::new(
351            source,
352            UserContentInjectedFrames::AllFrames,
353            UserScriptInjectionTime::Start,
354            &[],
355            &[],
356        ));
357        Ok(())
358    }
359
360    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
361        Err(EngineError::NotImplemented {
362            engine: "wpe",
363            primitive: "enable_webauthn",
364        })
365    }
366
367    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
368        if let Some(mut p) = self.pages.remove(&page) {
369            if let Some((session, id)) = p.download_hook.take() {
370                session.disconnect(id);
371            }
372            // Dismiss the hidden host window so its `GdkSurface` is
373            // unmapped from the display server. `close()` queues the
374            // destroy; the GLib main context completes it on the next
375            // iteration.
376            p.window.close();
377        }
378        Ok(())
379    }
380
381    fn drop_store(&mut self, key: &str) -> EngineResult<()> {
382        // The session lives on while a closed view still references it;
383        // dropping ours lets GLib free it with the last one.
384        self.isolated_sessions.remove(key);
385        Ok(())
386    }
387
388    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
389        let p = self.page_mut(page)?;
390        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
391        parse_snapshot(&json).map_err(EngineError::Other)
392    }
393
394    fn act(
395        &mut self,
396        page: PageHandle,
397        target: ActTarget,
398        action: Action,
399        _mode: InputMode,
400    ) -> EngineResult<()> {
401        self.forget_new_window(page)?;
402        let p = self.page_mut(page)?;
403        let web_view = p.web_view.clone();
404        super::common::run_act(
405            move |js, budget| eval_js_string(&web_view, js, budget),
406            &target,
407            &action,
408        )?;
409        self.follow_new_window(page, super::common::may_open_window(&action))
410    }
411
412    fn wait(
413        &mut self,
414        page: PageHandle,
415        cond: WaitCondition,
416        budget: Duration,
417    ) -> EngineResult<()> {
418        let p = self.page_mut(page)?;
419        let web_view = p.web_view.clone();
420        super::common::run_wait(
421            |js, budget| eval_js_string(&web_view, js, budget),
422            &cond,
423            budget,
424            || {
425                let _ = run_loop_until(|| false, Duration::from_millis(50));
426            },
427        )
428    }
429    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
430        let p = self.page_mut(page)?;
431        let web_view = p.web_view.clone();
432        super::common::run_layout(
433            move |js, budget| eval_js_string(&web_view, js, budget),
434            refs,
435        )
436    }
437
438    fn download(
439        &mut self,
440        page: PageHandle,
441        source: DownloadSource,
442        budget: Duration,
443    ) -> EngineResult<Download> {
444        let p = self.page_mut(page)?;
445        let web_view = p.web_view.clone();
446        let native = p.downloads.clone();
447        super::common::run_download(
448            |js, budget| eval_js_string(&web_view, js, budget),
449            || {
450                let _ = run_loop_until(|| false, Duration::from_millis(50));
451            },
452            &source,
453            budget,
454            &native,
455        )
456    }
457
458    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
459        let p = self.page_mut(page)?;
460        let web_view = p.web_view.clone();
461        let native = p.downloads.clone();
462        super::common::run_download_list(
463            move |js, budget| eval_js_string(&web_view, js, budget),
464            &native,
465        )
466    }
467    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
468        let p = self.page_mut(page)?;
469        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
470        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
471        // The host `gtk::Window` constrains its child WebView's
472        // allocation, so resizing the WebView via `set_size_request`
473        // alone is shadowed by the (1280x800) host. Resize both: the
474        // window's default size for the surface, and the WebView's
475        // size request so its render target matches the requested
476        // viewport.
477        p.window.set_default_size(w, h);
478        p.web_view.set_size_request(w, h);
479        // Pin the sized view to the window's top-left corner: a viewport
480        // smaller than the window must not be centered, or pointer input
481        // at page coordinates would miss by the gap. (Without a size
482        // request the view fills the window, so this is only set here.)
483        p.web_view.set_halign(gtk::Align::Start);
484        p.web_view.set_valign(gtk::Align::Start);
485        Ok(())
486    }
487
488    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
489        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
490        let _ = std::fs::create_dir_all(&captures_dir);
491        let path = captures_dir.join(format!("capture-{}.png", page.0));
492        let p = self.page_mut(page)?;
493        let web_view = p.web_view.clone();
494        let out_path = path.clone();
495
496        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
497        let slot_for_cb = slot.clone();
498        web_view.snapshot(
499            webkit6::SnapshotRegion::FullDocument,
500            webkit6::SnapshotOptions::NONE,
501            None::<&webkit6::gio::Cancellable>,
502            move |result| {
503                *slot_for_cb.borrow_mut() = Some(match result {
504                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
505                    Err(e) => Err(e.to_string()),
506                });
507            },
508        );
509
510        let slot_check = slot.clone();
511        let ok = run_loop_until(
512            move || slot_check.borrow().is_some(),
513            Duration::from_secs(10),
514        );
515        if !ok {
516            return Err(EngineError::Timeout {
517                budget: Duration::from_secs(10),
518                primitive: "capture",
519                detail: "",
520            });
521        }
522        let result = slot.borrow_mut().take();
523        match result {
524            Some(Ok(())) => Ok(path),
525            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
526            None => Err(EngineError::Other(
527                "capture completed without a result".into(),
528            )),
529        }
530    }
531
532    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
533        let p = self.page_mut(page)?;
534        let web_view = p.web_view.clone();
535        // Cookies: host-side via CookieManager so HttpOnly entries
536        // are captured. localStorage/sessionStorage: JS shim.
537        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
538        let storage = super::common::run_save_storage_only(
539            move |js, budget| eval_js_string(&web_view, js, budget),
540            || {
541                let _ = run_loop_until(|| false, Duration::from_millis(50));
542            },
543        )?;
544        let blob = super::auth::AuthBlobV2 {
545            version: 2,
546            url: storage.url,
547            origin: storage.origin,
548            cookies,
549            local_storage: storage.local_storage,
550            indexed_db: storage.indexed_db,
551            indexed_db_skipped: storage.indexed_db_skipped,
552            indexed_db_incomplete: storage.indexed_db_incomplete,
553            session_storage: storage.session_storage,
554        };
555        super::auth::encode(&blob)
556    }
557
558    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
559        let p = self.page_mut(page)?;
560        let web_view = p.web_view.clone();
561        let parsed = super::auth::decode(blob)?;
562        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
563        super::common::run_load_storage_only(
564            move |js, budget| eval_js_string(&web_view, js, budget),
565            &parsed.local_storage,
566            &parsed.session_storage,
567            &parsed.indexed_db,
568            || {
569                let _ = run_loop_until(|| false, Duration::from_millis(50));
570            },
571        )
572    }
573
574    fn console_entries(
575        &mut self,
576        page: PageHandle,
577    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
578        let p = self.page_mut(page)?;
579        Ok(p.inspector.console.borrow().snapshot())
580    }
581
582    fn network_entries(
583        &mut self,
584        page: PageHandle,
585    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
586        let p = self.page_mut(page)?;
587        Ok(p.inspector.network.borrow().snapshot())
588    }
589
590    fn request_detail(
591        &mut self,
592        page: PageHandle,
593        seq: u64,
594    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
595        let p = self.page_mut(page)?;
596        Ok(p.inspector.details.borrow().get(seq).cloned())
597    }
598
599    fn eval_js(
600        &mut self,
601        page: PageHandle,
602        expr: &str,
603    ) -> EngineResult<crate::inspector::EvalResult> {
604        let p = self.page_mut(page)?;
605        let web_view = p.web_view.clone();
606        super::common::run_eval(
607            move |js, budget| eval_js_string(&web_view, js, budget),
608            expr,
609        )
610    }
611
612    fn storage(
613        &mut self,
614        page: PageHandle,
615        scope: crate::inspector::StorageScope,
616    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
617        let p = self.page_mut(page)?;
618        let web_view = p.web_view.clone();
619        if matches!(scope, crate::inspector::StorageScope::Cookies) {
620            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
621            return Ok(cookies
622                .iter()
623                .map(super::common::cookie_to_storage_entry)
624                .collect());
625        }
626        super::common::run_storage(
627            move |js, budget| eval_js_string(&web_view, js, budget),
628            scope,
629        )
630    }
631
632    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
633        let p = self.page_mut(page)?;
634        let web_view = p.web_view.clone();
635        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
636    }
637
638    fn script_source(
639        &mut self,
640        page: PageHandle,
641        seq: u64,
642    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
643        let p = self.page_mut(page)?;
644        let web_view = p.web_view.clone();
645        super::common::run_script_source(
646            move |js, budget| eval_js_string(&web_view, js, budget),
647            seq,
648        )
649    }
650
651    fn dom(
652        &mut self,
653        page: PageHandle,
654        r: Ref,
655        extra_props: &[String],
656    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
657        let p = self.page_mut(page)?;
658        let web_view = p.web_view.clone();
659        super::common::run_dom(
660            move |js, budget| eval_js_string(&web_view, js, budget),
661            r,
662            extra_props,
663        )
664    }
665
666    fn performance(
667        &mut self,
668        page: PageHandle,
669    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
670        let p = self.page_mut(page)?;
671        let web_view = p.web_view.clone();
672        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
673    }
674
675    fn main_response(
676        &mut self,
677        page: PageHandle,
678    ) -> EngineResult<Option<crate::inspector::MainResponse>> {
679        Ok(self.page_mut(page)?.main_response.borrow().clone())
680    }
681
682    fn cookie_events(
683        &mut self,
684        page: PageHandle,
685    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
686        let p = self.page_mut(page)?;
687        let web_view = p.web_view.clone();
688        let current = wpe_cookies::get_all_cookies(&web_view)?;
689        let previous = p.cookie_baseline.borrow().clone();
690        let mut seq = p.cookie_next_seq.borrow_mut();
691        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
692        *p.cookie_baseline.borrow_mut() = Some(current);
693        Ok(events)
694    }
695
696    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
697        // Addressing the page validates it and keeps the error shape
698        // the same as every other page op, even though the keys go to
699        // whatever holds focus rather than to a page handle.
700        self.forget_new_window(page)?;
701        let cursor = self.page_mut(page)?.last_mouse.get();
702        let dispatcher = super::wpe_input::dispatcher()?;
703        // Pump GLib rather than sleep: this runs on the main thread,
704        // so a plain sleep would stop WebKit processing the very keys
705        // we are sending.
706        let settle = |d: Duration| {
707            let _ = run_loop_until(|| false, d);
708        };
709        // Put the pointer where we believe it already is before asking
710        // for focus. X hands keys to the focused window, and a
711        // headless session has no window manager to focus anything, so
712        // the pointer is what we have to go on. The caller has
713        // normally just clicked to place the caret, which means the
714        // right window is already under it.
715        #[allow(clippy::cast_possible_truncation)]
716        let at = super::wpe_input::ScreenPoint {
717            x: cursor.x as i32,
718            y: cursor.y as i32,
719        };
720        dispatcher.raise_window(&window_title(page));
721        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
722        let _ = dispatcher.flush();
723        dispatcher.focus_pointer_window();
724
725        let (base_delay, span) = match mode {
726            InputMode::Robotic => (0_u64, 0_u64),
727            InputMode::Careful => (120, 0),
728            // ±40% of base, so repeated typing is not metronomic.
729            InputMode::Human => (45, 18),
730        };
731        let mut jitter = text
732            .chars()
733            .map(|c| c as u64)
734            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
735            | 1;
736
737        let typed = (|| -> EngineResult<()> {
738            for ch in text.chars() {
739                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
740                dispatcher.key_down(ch, &settle)?;
741                settle(Duration::from_millis(hold.max(1)));
742                dispatcher.key_up(ch)?;
743                if base_delay > 0 {
744                    jitter ^= jitter << 13;
745                    jitter ^= jitter >> 7;
746                    jitter ^= jitter << 17;
747                    let extra = if span == 0 {
748                        0
749                    } else {
750                        jitter % (span * 2 + 1)
751                    };
752                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
753                    settle(Duration::from_millis(wait.max(1)));
754                } else {
755                    settle(Duration::from_millis(1));
756                }
757            }
758            Ok(())
759        })();
760
761        // Give the borrowed keycode back whether the run finished or
762        // failed halfway: a stray binding would change what the user's
763        // own keyboard does for the rest of the session.
764        let restored = dispatcher.end_typing();
765        typed?;
766        restored?;
767
768        // Let the last keyUp turn into beforeinput/input before the
769        // caller reads the page back.
770        let _ = run_loop_until(|| false, Duration::from_millis(150));
771        self.follow_new_window(page, false)
772    }
773
774    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
775        self.forget_new_window(page)?;
776        let p = self.page_mut(page)?;
777        let dispatcher = super::wpe_input::dispatcher()?;
778        let humanize_mode = match mode {
779            InputMode::Human => vs_humanize::InputMode::Human,
780            InputMode::Careful => vs_humanize::InputMode::Careful,
781            InputMode::Robotic => vs_humanize::InputMode::Robotic,
782        };
783        // Screen origin of the hidden host window. v0.1.11 assumes
784        // (0, 0) — true under `xvfb` (CI) and any session without a
785        // window manager. With a WM, the WM may have translated the
786        // window elsewhere; a follow-up PR will query
787        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
788        // real origin. Until then, page-local CSS px == screen px,
789        // which is fine for CI and most headless setups.
790        // The web view fills the window, or is pinned to its top-left
791        // once sized (set_viewport): page coordinates are window
792        // coordinates either way.
793        let (origin_x, origin_y) = (0.0_f64, 0.0_f64);
794        // Every page's window is at the origin; put this one on top so
795        // the input reaches it and not another page's.
796        dispatcher.raise_window(&window_title(page));
797        let start = p.last_mouse.get();
798        let seed = humanize_seed(op);
799        let landed = match op {
800            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
801                dispatcher,
802                start,
803                vs_humanize::Point { x, y },
804                (origin_x, origin_y),
805                humanize_mode,
806                seed,
807                false,
808            )?,
809            CursorOp::ClickAt { x, y } => {
810                let landed = cursor_move_along_path(
811                    dispatcher,
812                    start,
813                    vs_humanize::Point { x, y },
814                    (origin_x, origin_y),
815                    humanize_mode,
816                    seed,
817                    false,
818                )?;
819                cursor_press_release(dispatcher, landed, (origin_x, origin_y))?;
820                landed
821            }
822            CursorOp::Drag { x1, y1, x2, y2 } => {
823                let start_pt = vs_humanize::Point { x: x1, y: y1 };
824                let target = vs_humanize::Point { x: x2, y: y2 };
825                let pre = cursor_move_along_path(
826                    dispatcher,
827                    start,
828                    start_pt,
829                    (origin_x, origin_y),
830                    humanize_mode,
831                    seed,
832                    false,
833                )?;
834                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
835                    super::wpe_input::Button::Left,
836                ))?;
837                std::thread::sleep(Duration::from_millis(15));
838                let landed = cursor_move_along_path(
839                    dispatcher,
840                    pre,
841                    target,
842                    (origin_x, origin_y),
843                    humanize_mode,
844                    seed,
845                    true,
846                )?;
847                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
848                    super::wpe_input::Button::Left,
849                ))?;
850                dispatcher.flush()?;
851                // After the OS-level drag, fire the HTML5 DragEvent
852                // chain in JS so react-dnd / React-Flow HTML5 targets
853                // observe the drop.
854                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
855                let web_view = p.web_view.clone();
856                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
857                landed
858            }
859        };
860        p.last_mouse.set(landed);
861        self.follow_new_window(page, matches!(op, CursorOp::ClickAt { .. }))
862    }
863
864    fn capabilities(&self) -> EngineCapabilities {
865        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
866        EngineCapabilities {
867            renders: true,
868            honors_viewport: true,
869            measures_layout: true,
870            persists_auth: true,
871            inspector_console: any_inspector,
872            inspector_network: any_inspector,
873            inspector_cookie_events: true,
874            name: "wpe",
875            version: "Linux WebKitGTK 6 (webkit6)",
876        }
877    }
878}
879
880// =============================================================================
881// JS evaluation helper
882// =============================================================================
883
884// =============================================================================
885// Cursor primitive helpers (XTest / libei input dispatch)
886// =============================================================================
887
888/// Deterministic seed for the humanize Bezier path so the same
889/// `cursor_op` invocation produces the same trajectory on every run.
890fn humanize_seed(op: CursorOp) -> u64 {
891    // Hash the op's coordinates into a u64. Trivial mixer; replays
892    // need determinism, not cryptographic spread.
893    let (a, b, c, d) = match op {
894        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
895            (x, y, 0.0, 0.0)
896        }
897        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
898    };
899    let bits = |v: f64| v.to_bits();
900    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
901        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
902        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
903        ^ bits(d)
904}
905
906/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
907/// per step at the path's prescribed timing. Returns the final point.
908/// The `button_down` flag is unused on Linux today (XTest doesn't
909/// distinguish drag-move from plain-move — both are `MotionNotify`
910/// events; the held button state is tracked at the X server). Kept
911/// in the signature so drag callers stay symmetric with the macOS
912/// `move_along_path`.
913/// The X window title of a page's host window. Every host window sits
914/// at the screen origin and XTest input goes to whichever is on top, so
915/// the input path finds a page's window by this name and raises it.
916fn window_title(page: PageHandle) -> String {
917    format!("vs-page-{}", page.0)
918}
919
920fn titled(window: gtk::Window, page: PageHandle) -> gtk::Window {
921    window.set_title(Some(&window_title(page)));
922    window
923}
924
925fn cursor_move_along_path(
926    dispatcher: &dyn super::wpe_input::InputDispatcher,
927    start: vs_humanize::Point,
928    end: vs_humanize::Point,
929    origin: (f64, f64),
930    mode: vs_humanize::InputMode,
931    seed: u64,
932    _button_down: bool,
933) -> EngineResult<vs_humanize::Point> {
934    let path = vs_humanize::mouse_path(start, end, mode, seed);
935    let mut prev_ms: u128 = 0;
936    for step in &path {
937        if step.kind != vs_humanize::MouseStepKind::Move {
938            continue;
939        }
940        let screen = super::wpe_input::ScreenPoint {
941            #[allow(clippy::cast_possible_truncation)]
942            x: (origin.0 + step.point.x).round() as i32,
943            #[allow(clippy::cast_possible_truncation)]
944            y: (origin.1 + step.point.y).round() as i32,
945        };
946        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
947        let dt = step.at.as_millis().saturating_sub(prev_ms);
948        if dt > 0 {
949            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
950        }
951        prev_ms = step.at.as_millis();
952    }
953    // Final settling move ending exactly at `end`.
954    let final_pt = super::wpe_input::ScreenPoint {
955        #[allow(clippy::cast_possible_truncation)]
956        x: (origin.0 + end.x).round() as i32,
957        #[allow(clippy::cast_possible_truncation)]
958        y: (origin.1 + end.y).round() as i32,
959    };
960    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
961    dispatcher.flush()?;
962    Ok(end)
963}
964
965/// Press-then-release left button at the current pointer position.
966/// Matches the `mouseDown` / 15 ms / `mouseUp` cadence the macOS
967/// backend uses so JS sees a coherent `click` event.
968fn cursor_press_release(
969    dispatcher: &dyn super::wpe_input::InputDispatcher,
970    _at: vs_humanize::Point,
971    _origin: (f64, f64),
972) -> EngineResult<()> {
973    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
974        super::wpe_input::Button::Left,
975    ))?;
976    std::thread::sleep(Duration::from_millis(15));
977    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
978        super::wpe_input::Button::Left,
979    ))?;
980    dispatcher.flush()?;
981    std::thread::sleep(Duration::from_millis(30));
982    Ok(())
983}
984
985fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
986    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
987    let slot_for_cb = slot.clone();
988
989    let cancellable = webkit6::gio::Cancellable::new();
990    web_view.evaluate_javascript(
991        js,
992        None,
993        None,
994        Some(&cancellable),
995        move |result| match result {
996            Ok(value) => {
997                let s = value.to_string();
998                *slot_for_cb.borrow_mut() = Some(Ok(s));
999            }
1000            Err(err) => {
1001                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
1002            }
1003        },
1004    );
1005
1006    let slot_check = slot.clone();
1007    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
1008    if !ok {
1009        return Err(EngineError::Timeout {
1010            budget,
1011            primitive: "eval",
1012            detail: "",
1013        });
1014    }
1015    let result = slot.borrow_mut().take();
1016    match result {
1017        Some(Ok(s)) => Ok(s),
1018        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
1019        None => Err(EngineError::Other("eval completed without a result".into())),
1020    }
1021}
1022
1023// =============================================================================
1024// Inspector capture wiring
1025// =============================================================================
1026
1027/// Add the download-capture shim as a document-start script in every
1028/// frame. WebKitGTK does emit a `download-started` signal, but the
1029/// shim covers what that signal cannot see — an in-page `blob:` save
1030/// whose object URL is revoked a tick later — and keeps the capture
1031/// buffer identical across all three backends.
1032fn install_download_shim(web_view: &WebView) {
1033    let Some(manager) = web_view.user_content_manager() else {
1034        return;
1035    };
1036    manager.add_script(&UserScript::new(
1037        super::common::DOWNLOAD_SHIM_JS,
1038        UserContentInjectedFrames::AllFrames,
1039        UserScriptInjectionTime::Start,
1040        &[],
1041        &[],
1042    ));
1043}
1044
1045fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
1046    use super::inspector_bridge::{
1047        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
1048    };
1049
1050    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
1051        return false;
1052    }
1053
1054    let manager = web_view.user_content_manager().expect(
1055        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
1056    );
1057
1058    let script = UserScript::new(
1059        inspector_bridge::SCRIPT,
1060        UserContentInjectedFrames::AllFrames,
1061        UserScriptInjectionTime::Start,
1062        &[],
1063        &[],
1064    );
1065    manager.add_script(&script);
1066
1067    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
1068        return false;
1069    }
1070    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
1071        return false;
1072    }
1073
1074    let console_slots: InspectorSlots = slots.clone();
1075    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
1076        let json = value.to_string();
1077        let mut buf = console_slots.console.borrow_mut();
1078        inspector_bridge::ingest_console(&mut buf, &json);
1079    });
1080    let network_slots: InspectorSlots = slots.clone();
1081    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
1082        let json = value.to_string();
1083        let mut entries = network_slots.network.borrow_mut();
1084        let mut details = network_slots.details.borrow_mut();
1085        let mut pending = network_slots.pending.borrow_mut();
1086        inspector_bridge::ingest_network(
1087            NetworkIngestSlot {
1088                entries: &mut entries,
1089                details: &mut details,
1090                pending: &mut pending,
1091            },
1092            &json,
1093        );
1094    });
1095    true
1096}
1097
1098// =============================================================================
1099// Host-side cookie save/load via WebKitCookieManager
1100// =============================================================================
1101//
1102// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
1103// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
1104// The v0.1.2 fix routes auth save/load through this path on every
1105// platform.
1106mod wpe_cookies {
1107    use std::cell::RefCell;
1108    use std::rc::Rc;
1109    use std::time::Duration;
1110
1111    use webkit6::gio;
1112    use webkit6::glib;
1113    use webkit6::prelude::*;
1114    use webkit6::soup;
1115    use webkit6::WebView;
1116
1117    use crate::backend::auth::CookieData;
1118    use crate::engine::{EngineError, EngineResult};
1119
1120    use super::run_loop_until;
1121
1122    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
1123
1124    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
1125        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
1126            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
1127        })?;
1128        session
1129            .cookie_manager()
1130            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
1131    }
1132
1133    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
1134        let manager = cookie_manager(web_view)?;
1135        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
1136        let slot_cb = slot.clone();
1137        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
1138            let cookies = match result {
1139                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
1140                Err(_) => Vec::new(),
1141            };
1142            *slot_cb.borrow_mut() = Some(cookies);
1143        });
1144        let check = slot.clone();
1145        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
1146        if !ok {
1147            return Err(EngineError::Timeout {
1148                budget: ASYNC_BUDGET,
1149                primitive: "save_auth (all_cookies)",
1150                detail: "",
1151            });
1152        }
1153        let result = slot.borrow_mut().take().unwrap_or_default();
1154        Ok(result)
1155    }
1156
1157    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
1158        let manager = cookie_manager(web_view)?;
1159        for c in cookies {
1160            if c.name.is_empty() || c.domain.is_empty() {
1161                continue;
1162            }
1163            let path = if c.path.is_empty() {
1164                "/"
1165            } else {
1166                c.path.as_str()
1167            };
1168            // max_age=-1: session cookie (no expiration). We set
1169            // expires explicitly below if the saved blob carried it.
1170            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
1171            cookie.set_secure(c.secure);
1172            cookie.set_http_only(c.http_only);
1173            if let Some(unix) = c.expires_unix {
1174                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
1175                    cookie.set_expires(&dt);
1176                }
1177            }
1178            if let Some(ss) = c.same_site.as_deref() {
1179                let policy = match ss {
1180                    "Strict" => soup::SameSitePolicy::Strict,
1181                    "None" => soup::SameSitePolicy::None,
1182                    _ => soup::SameSitePolicy::Lax,
1183                };
1184                cookie.set_same_site_policy(policy);
1185            }
1186
1187            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
1188            let done_cb = done.clone();
1189            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
1190                *done_cb.borrow_mut() = true;
1191            });
1192            let check = done.clone();
1193            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
1194            if !ok {
1195                return Err(EngineError::Timeout {
1196                    budget: ASYNC_BUDGET,
1197                    primitive: "load_auth (add_cookie)",
1198                    detail: "",
1199                });
1200            }
1201        }
1202        Ok(())
1203    }
1204
1205    fn serialize(c: &mut soup::Cookie) -> CookieData {
1206        CookieData {
1207            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
1208            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
1209            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
1210            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
1211            expires_unix: c.expires().map(|dt| dt.to_unix()),
1212            secure: c.is_secure(),
1213            http_only: c.is_http_only(),
1214            same_site: match c.same_site_policy() {
1215                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
1216                soup::SameSitePolicy::None => Some("None".to_string()),
1217                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
1218                _ => None,
1219            },
1220        }
1221    }
1222}
1223
1224/// A load that ended because its response became a download left the
1225/// page as it was and put the file in the download buffer. Not a
1226/// failure.
1227fn load_result(err: &glib::Error) -> Result<(), String> {
1228    if err.matches(webkit6::PolicyError::FrameLoadInterruptedByPolicyChange) {
1229        Ok(())
1230    } else {
1231        Err(err.message().to_string())
1232    }
1233}
1234
1235/// Keep the HTTP response of each main-frame navigation.
1236///
1237/// `load-changed` fires for the main frame only. The slot is cleared
1238/// when a load starts, so a failed or non-HTTP load reports nothing,
1239/// and filled at commit, when the main resource has its response.
1240fn install_response_capture(
1241    web_view: &WebView,
1242) -> Rc<RefCell<Option<crate::inspector::MainResponse>>> {
1243    let slot: Rc<RefCell<Option<crate::inspector::MainResponse>>> = Rc::new(RefCell::new(None));
1244    let sink = slot.clone();
1245    web_view.connect_load_changed(move |view, event| match event {
1246        LoadEvent::Started => {
1247            sink.borrow_mut().take();
1248        }
1249        LoadEvent::Committed => {
1250            *sink.borrow_mut() = view
1251                .main_resource()
1252                .and_then(|r| r.response())
1253                .and_then(|r| http_response(&r));
1254        }
1255        _ => {}
1256    });
1257    slot
1258}
1259
1260fn http_response(resp: &webkit6::URIResponse) -> Option<crate::inspector::MainResponse> {
1261    let url = resp.uri().map(|u| u.to_string()).unwrap_or_default();
1262    if !(url.starts_with("http:") || url.starts_with("https:")) {
1263        return None;
1264    }
1265    let status = u16::try_from(resp.status_code()).unwrap_or(0);
1266    if status == 0 {
1267        return None;
1268    }
1269    let mut headers = Vec::new();
1270    if let Some(h) = resp.http_headers() {
1271        h.foreach(|name, value| headers.push((name.to_ascii_lowercase(), value.to_string())));
1272    }
1273    Some(crate::inspector::MainResponse {
1274        url,
1275        status,
1276        status_text: crate::inspector::reason_phrase(status).to_string(),
1277        headers,
1278    })
1279}
1280
1281/// Save attachments instead of dropping them.
1282///
1283/// A `Content-Disposition: attachment` response (an export button, a
1284/// form POST answering with a file, a hidden-iframe download) never
1285/// reaches page script. Turn it into a WebKit download, write it to a
1286/// temp file, and move the bytes into `downloads` for `vs_download`.
1287/// The network session is shared by every page of the same store, so
1288/// the `download-started` handler checks the download belongs to this
1289/// one.
1290fn install_download_capture(
1291    web_view: &WebView,
1292    downloads: &SharedDownloads,
1293) -> Option<(webkit6::NetworkSession, glib::SignalHandlerId)> {
1294    web_view.connect_decide_policy(|_view, decision, ty| {
1295        if ty != webkit6::PolicyDecisionType::Response {
1296            return false;
1297        }
1298        let Some(rd) = decision.downcast_ref::<webkit6::ResponsePolicyDecision>() else {
1299            return false;
1300        };
1301        let Some(resp) = rd.response() else {
1302            return false;
1303        };
1304        let uri = resp.uri().map(|u| u.to_string()).unwrap_or_default();
1305        if !(uri.starts_with("http:") || uri.starts_with("https:")) {
1306            return false;
1307        }
1308        let cd = resp
1309            .http_headers()
1310            .and_then(|h| h.one("Content-Disposition"))
1311            .map(|v| v.to_string())
1312            .unwrap_or_default();
1313        if is_attachment(&cd) || !rd.is_mime_type_supported() {
1314            decision.download();
1315            return true;
1316        }
1317        false
1318    });
1319
1320    let session = WebViewExt::network_session(web_view)?;
1321    let weak = web_view.downgrade();
1322    let downloads = downloads.clone();
1323    let id = session.connect_download_started(move |_session, download| {
1324        let Some(view) = weak.upgrade() else { return };
1325        if download.web_view().as_ref() != Some(&view) {
1326            return;
1327        }
1328        let resp = download.response();
1329        let url = resp
1330            .as_ref()
1331            .and_then(webkit6::URIResponse::uri)
1332            .or_else(|| download.request().and_then(|r| r.uri()))
1333            .map(|u| u.to_string())
1334            .unwrap_or_default();
1335        let mime = resp
1336            .as_ref()
1337            .and_then(webkit6::URIResponse::mime_type)
1338            .map(|m| m.to_string())
1339            .unwrap_or_default();
1340        let name = resp
1341            .as_ref()
1342            .and_then(webkit6::URIResponse::http_headers)
1343            .and_then(|h| h.one("Content-Disposition"))
1344            .and_then(|cd| name_from_disposition(&cd))
1345            .unwrap_or_default();
1346        let Ok(id) = downloads.lock().map(|mut d| d.begin(&url, &name, &mime)) else {
1347            return;
1348        };
1349        let path = temp_path(id);
1350        let _ = std::fs::remove_file(&path);
1351
1352        let dl = downloads.clone();
1353        download.connect_decide_destination(move |download, suggested| {
1354            if let Ok(mut d) = dl.lock() {
1355                if name.is_empty() {
1356                    d.set_name(id, suggested);
1357                }
1358            }
1359            let expected = download.response().map_or(0, |r| r.content_length());
1360            if expected > MAX_BYTES {
1361                if let Ok(mut d) = dl.lock() {
1362                    d.finish(
1363                        id,
1364                        Err(format!("download exceeds {MAX_BYTES} bytes ({expected})")),
1365                    );
1366                }
1367                download.cancel();
1368                return true;
1369            }
1370            download.set_destination(&path.to_string_lossy());
1371            true
1372        });
1373        let dl = downloads.clone();
1374        download.connect_failed(move |_download, err| {
1375            if let Ok(mut d) = dl.lock() {
1376                d.finish(id, Err(err.message().to_string()));
1377            }
1378            let _ = std::fs::remove_file(temp_path(id));
1379        });
1380        let dl = downloads.clone();
1381        download.connect_finished(move |_download| {
1382            let path = temp_path(id);
1383            // `failed` is followed by `finished`; the first result wins.
1384            let bytes = std::fs::read(&path).map_err(|e| format!("read {}: {e}", path.display()));
1385            let _ = std::fs::remove_file(&path);
1386            if let Ok(mut d) = dl.lock() {
1387                d.finish(id, bytes);
1388            }
1389        });
1390    });
1391    Some((session, id))
1392}
1393
1394/// Wait for the load already started on `web_view` to finish or fail.
1395fn wait_for_load(web_view: &WebView, primitive: &'static str) -> EngineResult<()> {
1396    let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
1397    let slot_for_signal = slot.clone();
1398    let signal_id = web_view.connect_load_changed(move |_view, event| {
1399        if event == LoadEvent::Finished {
1400            *slot_for_signal.borrow_mut() = Some(Ok(()));
1401        }
1402    });
1403    let slot_fail = slot.clone();
1404    let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
1405        *slot_fail.borrow_mut() = Some(load_result(err));
1406        true
1407    });
1408
1409    let slot_check = slot.clone();
1410    let budget = super::common::nav_budget();
1411    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
1412
1413    web_view.disconnect(signal_id);
1414    web_view.disconnect(fail_id);
1415
1416    if !ok {
1417        return Err(EngineError::Timeout {
1418            budget,
1419            primitive,
1420            detail: "",
1421        });
1422    }
1423    // Taken out of the RefCell before the match, not inside it:
1424    // as the function's tail expression the borrow guard would
1425    // otherwise outlive `slot` itself.
1426    let result = slot.borrow_mut().take();
1427    match result {
1428        Some(Ok(())) => Ok(()),
1429        Some(Err(msg)) => Err(EngineError::Other(format!("navigation failed: {msg}"))),
1430        None => Err(EngineError::Other(
1431            "navigation completed without a result".into(),
1432        )),
1433    }
1434}
1435
1436impl WpeBackend {
1437    /// Drop a new-window request parked before this input primitive
1438    /// started (a popup the page fired on its own), so the primitive
1439    /// only follows what it caused.
1440    fn forget_new_window(&mut self, page: PageHandle) -> EngineResult<()> {
1441        let _ = self.page_mut(page)?.new_window.borrow_mut().take();
1442        Ok(())
1443    }
1444
1445    /// Load a new-window navigation the last input primitive caused, in
1446    /// this page, and wait for it like `goto`. The `create` signal can
1447    /// arrive after the click returns, so after a click (`settle`) pump
1448    /// for up to `NEW_WINDOW_SETTLE` first. No parked request: no-op.
1449    fn follow_new_window(&mut self, page: PageHandle, settle: bool) -> EngineResult<()> {
1450        let p = self.page_mut(page)?;
1451        if settle && p.new_window.borrow().is_none() {
1452            let hint = eval_js_string(
1453                &p.web_view,
1454                super::common::NEW_WINDOW_HINT_JS,
1455                Duration::from_secs(2),
1456            );
1457            if super::common::new_window_hinted(&hint) {
1458                let parked = p.new_window.clone();
1459                let _ = run_loop_until(
1460                    move || parked.borrow().is_some(),
1461                    super::common::NEW_WINDOW_SETTLE,
1462                );
1463            }
1464        }
1465        let Some(request) = p.new_window.borrow_mut().take() else {
1466            return Ok(());
1467        };
1468        let web_view = p.web_view.clone();
1469        web_view.load_request(&request);
1470        wait_for_load(&web_view, "act")
1471    }
1472}