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, Download, DownloadEntry, DownloadSource,
40    Engine, EngineCapabilities, EngineError, EngineResult, InputMode, LayoutBox, PageHandle,
41    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}
67
68// =============================================================================
69// Backend
70// =============================================================================
71
72/// Real WebKitGTK 6 backend. Construct on the GTK main thread; all
73/// subsequent calls must come from the same thread.
74pub struct WpeBackend {
75    pages: HashMap<PageHandle, WpePage>,
76    next_handle: u64,
77    captures_dir: Option<PathBuf>,
78}
79
80impl Default for WpeBackend {
81    fn default() -> Self {
82        Self::new()
83    }
84}
85
86impl WpeBackend {
87    /// Build a backend. Caller must already have initialized GTK on
88    /// this thread (via `gtk4::init()`); production wiring lives in
89    /// `vs-cli::serve` on Linux. Constructing on a non-GTK thread will
90    /// panic the first time a `WebView` operation runs.
91    #[must_use]
92    pub fn new() -> Self {
93        Self {
94            pages: HashMap::new(),
95            next_handle: 1,
96            captures_dir: None,
97        }
98    }
99
100    /// Pin the directory where `capture` writes PNGs. Defaults to a
101    /// system temp subdirectory.
102    #[must_use]
103    pub fn with_capture_dir(mut self, dir: impl Into<PathBuf>) -> Self {
104        self.captures_dir = Some(dir.into());
105        self
106    }
107
108    fn alloc_handle(&mut self) -> PageHandle {
109        let h = PageHandle(self.next_handle);
110        self.next_handle += 1;
111        h
112    }
113
114    fn page_mut(&mut self, h: PageHandle) -> EngineResult<&mut WpePage> {
115        self.pages.get_mut(&h).ok_or(EngineError::NotFound {
116            kind: "page",
117            id: h.0.to_string(),
118        })
119    }
120}
121
122// =============================================================================
123// Run-loop helper: pump the GLib main context until a predicate fires
124// =============================================================================
125
126fn run_loop_until<F: FnMut() -> bool>(mut done: F, budget: Duration) -> bool {
127    let main_ctx = glib::MainContext::default();
128    let deadline = std::time::Instant::now() + budget;
129    while std::time::Instant::now() < deadline {
130        if done() {
131            return true;
132        }
133        // Iterate non-blocking; if no work, sleep briefly.
134        if !main_ctx.iteration(false) {
135            std::thread::sleep(Duration::from_millis(10));
136        }
137    }
138    done()
139}
140
141// =============================================================================
142// Shared payloads + parsers
143// =============================================================================
144
145use super::common::{parse_snapshot, SNAPSHOT_DOM_WALKER_JS as SNAPSHOT_JS};
146
147// =============================================================================
148// Engine impl
149// =============================================================================
150
151impl Engine for WpeBackend {
152    fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
153        let web_view = WebView::new();
154
155        // Hidden host window for the WebView. v0.1.11 added native
156        // input dispatch (XTest / libei) for the cursor primitives;
157        // both require the WebView to have a real `GdkSurface` on the
158        // display server so the synthetic event has somewhere to land.
159        // `WebView::new()` alone renders to an internal offscreen
160        // surface with no display-server window — XTest events would
161        // disappear into the void. Wrapping each WebView in a
162        // decorated-off `gtk::Window` and presenting it gives us that
163        // surface; under `xvfb` (CI) the window has no visual effect.
164        let window = gtk::Window::new();
165        window.set_decorated(false);
166        window.set_default_size(1280, 800);
167        window.set_child(Some(&web_view));
168        window.present();
169
170        // Pin the User-Agent to a current Safari string so anti-bot
171        // fingerprinters don't flag the WebKitGTK default. See the
172        // commit log for `crate::engine::DEFAULT_USER_AGENT` rationale.
173        if let Some(settings) = WebViewExt::settings(&web_view) {
174            settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
175            // Expose `navigator.mediaDevices`. WebKitGTK gates the
176            // MediaDevices surface off by default, so the object is
177            // simply absent and anything feature-detecting camera or
178            // mic support sees a browser that cannot exist. The macOS
179            // backend needed the same switch (there via a WKPreferences
180            // KVC key); here it is public API.
181            settings.set_enable_media_stream(true);
182        }
183
184        // Inspector capture wiring — install the user script + register
185        // both message channels BEFORE load_uri so the bridge is live
186        // by document-start.
187        let inspector =
188            super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
189        let inspector_installed = install_inspector(&web_view, &inspector);
190        install_download_shim(&web_view);
191        web_view.load_uri(url);
192
193        // Wait for LoadEvent::Finished or LoadEvent::Failed via signal.
194        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
195        let slot_for_signal = slot.clone();
196        let signal_id = web_view.connect_load_changed(move |_view, event| {
197            if event == LoadEvent::Finished {
198                *slot_for_signal.borrow_mut() = Some(Ok(()));
199            }
200        });
201        let slot_fail = slot.clone();
202        let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
203            *slot_fail.borrow_mut() = Some(Err(err.message().to_string()));
204            // Stop event propagation: we have handled it.
205            true
206        });
207
208        let slot_check = slot.clone();
209        let ok = run_loop_until(
210            move || slot_check.borrow().is_some(),
211            Duration::from_secs(15),
212        );
213
214        // Disconnect signal handlers — the WebView outlives this scope.
215        web_view.disconnect(signal_id);
216        web_view.disconnect(fail_id);
217
218        if !ok {
219            return Err(EngineError::Timeout {
220                budget: Duration::from_secs(15),
221                primitive: "open",
222            });
223        }
224        match slot.borrow_mut().take() {
225            Some(Ok(())) => {}
226            Some(Err(msg)) => return Err(EngineError::Other(format!("navigation failed: {msg}"))),
227            None => {
228                return Err(EngineError::Other(
229                    "navigation completed without a result".into(),
230                ))
231            }
232        }
233
234        let handle = self.alloc_handle();
235        self.pages.insert(
236            handle,
237            WpePage {
238                web_view,
239                window,
240                inspector,
241                inspector_installed,
242                cookie_baseline: std::cell::RefCell::new(None),
243                cookie_next_seq: std::cell::RefCell::new(0),
244                last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
245            },
246        );
247        Ok(handle)
248    }
249
250    fn navigate(&mut self, _page: PageHandle, _url: &str) -> EngineResult<()> {
251        Err(EngineError::NotImplemented {
252            engine: "wpe",
253            primitive: "navigate",
254        })
255    }
256
257    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
258        Err(EngineError::NotImplemented {
259            engine: "wpe",
260            primitive: "enable_webauthn",
261        })
262    }
263
264    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
265        if let Some(p) = self.pages.remove(&page) {
266            // Dismiss the hidden host window so its `GdkSurface` is
267            // unmapped from the display server. `close()` queues the
268            // destroy; the GLib main context completes it on the next
269            // iteration.
270            p.window.close();
271        }
272        Ok(())
273    }
274
275    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
276        let p = self.page_mut(page)?;
277        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
278        parse_snapshot(&json).map_err(EngineError::Other)
279    }
280
281    fn act(
282        &mut self,
283        page: PageHandle,
284        target: ActTarget,
285        action: Action,
286        _mode: InputMode,
287    ) -> EngineResult<()> {
288        let p = self.page_mut(page)?;
289        let web_view = p.web_view.clone();
290        super::common::run_act(
291            move |js, budget| eval_js_string(&web_view, js, budget),
292            &target,
293            &action,
294        )
295    }
296
297    fn wait(
298        &mut self,
299        page: PageHandle,
300        cond: WaitCondition,
301        budget: Duration,
302    ) -> EngineResult<()> {
303        let p = self.page_mut(page)?;
304        let web_view = p.web_view.clone();
305        super::common::run_wait(
306            |js, budget| eval_js_string(&web_view, js, budget),
307            &cond,
308            budget,
309            || {
310                let _ = run_loop_until(|| false, Duration::from_millis(50));
311            },
312        )
313    }
314    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
315        let p = self.page_mut(page)?;
316        let web_view = p.web_view.clone();
317        super::common::run_layout(
318            move |js, budget| eval_js_string(&web_view, js, budget),
319            refs,
320        )
321    }
322
323    fn download(
324        &mut self,
325        page: PageHandle,
326        source: DownloadSource,
327        budget: Duration,
328    ) -> EngineResult<Download> {
329        let p = self.page_mut(page)?;
330        let web_view = p.web_view.clone();
331        super::common::run_download(
332            |js, budget| eval_js_string(&web_view, js, budget),
333            || {
334                let _ = run_loop_until(|| false, Duration::from_millis(50));
335            },
336            &source,
337            budget,
338        )
339    }
340
341    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
342        let p = self.page_mut(page)?;
343        let web_view = p.web_view.clone();
344        super::common::run_download_list(move |js, budget| eval_js_string(&web_view, js, budget))
345    }
346    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
347        let p = self.page_mut(page)?;
348        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
349        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
350        // The host `gtk::Window` constrains its child WebView's
351        // allocation, so resizing the WebView via `set_size_request`
352        // alone is shadowed by the (1280x800) host. Resize both: the
353        // window's default size for the surface, and the WebView's
354        // size request so its render target matches the requested
355        // viewport.
356        p.window.set_default_size(w, h);
357        p.web_view.set_size_request(w, h);
358        Ok(())
359    }
360
361    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
362        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
363        let _ = std::fs::create_dir_all(&captures_dir);
364        let path = captures_dir.join(format!("capture-{}.png", page.0));
365        let p = self.page_mut(page)?;
366        let web_view = p.web_view.clone();
367        let out_path = path.clone();
368
369        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
370        let slot_for_cb = slot.clone();
371        web_view.snapshot(
372            webkit6::SnapshotRegion::FullDocument,
373            webkit6::SnapshotOptions::NONE,
374            None::<&webkit6::gio::Cancellable>,
375            move |result| {
376                *slot_for_cb.borrow_mut() = Some(match result {
377                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
378                    Err(e) => Err(e.to_string()),
379                });
380            },
381        );
382
383        let slot_check = slot.clone();
384        let ok = run_loop_until(
385            move || slot_check.borrow().is_some(),
386            Duration::from_secs(10),
387        );
388        if !ok {
389            return Err(EngineError::Timeout {
390                budget: Duration::from_secs(10),
391                primitive: "capture",
392            });
393        }
394        let result = slot.borrow_mut().take();
395        match result {
396            Some(Ok(())) => Ok(path),
397            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
398            None => Err(EngineError::Other(
399                "capture completed without a result".into(),
400            )),
401        }
402    }
403
404    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
405        let p = self.page_mut(page)?;
406        let web_view = p.web_view.clone();
407        // Cookies: host-side via CookieManager so HttpOnly entries
408        // are captured. localStorage/sessionStorage: JS shim.
409        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
410        let storage = super::common::run_save_storage_only(move |js, budget| {
411            eval_js_string(&web_view, js, budget)
412        })?;
413        let blob = super::auth::AuthBlobV2 {
414            version: 2,
415            url: storage.url,
416            origin: storage.origin,
417            cookies,
418            local_storage: storage.local_storage,
419            session_storage: storage.session_storage,
420        };
421        super::auth::encode(&blob)
422    }
423
424    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
425        let p = self.page_mut(page)?;
426        let web_view = p.web_view.clone();
427        let parsed = super::auth::decode(blob)?;
428        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
429        super::common::run_load_storage_only(
430            move |js, budget| eval_js_string(&web_view, js, budget),
431            &parsed.local_storage,
432            &parsed.session_storage,
433        )
434    }
435
436    fn console_entries(
437        &mut self,
438        page: PageHandle,
439    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
440        let p = self.page_mut(page)?;
441        Ok(p.inspector.console.borrow().snapshot())
442    }
443
444    fn network_entries(
445        &mut self,
446        page: PageHandle,
447    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
448        let p = self.page_mut(page)?;
449        Ok(p.inspector.network.borrow().snapshot())
450    }
451
452    fn request_detail(
453        &mut self,
454        page: PageHandle,
455        seq: u64,
456    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
457        let p = self.page_mut(page)?;
458        Ok(p.inspector.details.borrow().get(seq).cloned())
459    }
460
461    fn eval_js(
462        &mut self,
463        page: PageHandle,
464        expr: &str,
465    ) -> EngineResult<crate::inspector::EvalResult> {
466        let p = self.page_mut(page)?;
467        let web_view = p.web_view.clone();
468        super::common::run_eval(
469            move |js, budget| eval_js_string(&web_view, js, budget),
470            expr,
471        )
472    }
473
474    fn storage(
475        &mut self,
476        page: PageHandle,
477        scope: crate::inspector::StorageScope,
478    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
479        let p = self.page_mut(page)?;
480        let web_view = p.web_view.clone();
481        if matches!(scope, crate::inspector::StorageScope::Cookies) {
482            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
483            return Ok(cookies
484                .iter()
485                .map(super::common::cookie_to_storage_entry)
486                .collect());
487        }
488        super::common::run_storage(
489            move |js, budget| eval_js_string(&web_view, js, budget),
490            scope,
491        )
492    }
493
494    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
495        let p = self.page_mut(page)?;
496        let web_view = p.web_view.clone();
497        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
498    }
499
500    fn script_source(
501        &mut self,
502        page: PageHandle,
503        seq: u64,
504    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
505        let p = self.page_mut(page)?;
506        let web_view = p.web_view.clone();
507        super::common::run_script_source(
508            move |js, budget| eval_js_string(&web_view, js, budget),
509            seq,
510        )
511    }
512
513    fn dom(
514        &mut self,
515        page: PageHandle,
516        r: Ref,
517        extra_props: &[String],
518    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
519        let p = self.page_mut(page)?;
520        let web_view = p.web_view.clone();
521        super::common::run_dom(
522            move |js, budget| eval_js_string(&web_view, js, budget),
523            r,
524            extra_props,
525        )
526    }
527
528    fn performance(
529        &mut self,
530        page: PageHandle,
531    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
532        let p = self.page_mut(page)?;
533        let web_view = p.web_view.clone();
534        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
535    }
536
537    fn cookie_events(
538        &mut self,
539        page: PageHandle,
540    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
541        let p = self.page_mut(page)?;
542        let web_view = p.web_view.clone();
543        let current = wpe_cookies::get_all_cookies(&web_view)?;
544        let previous = p.cookie_baseline.borrow().clone();
545        let mut seq = p.cookie_next_seq.borrow_mut();
546        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
547        *p.cookie_baseline.borrow_mut() = Some(current);
548        Ok(events)
549    }
550
551    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
552        let p = self.page_mut(page)?;
553        let dispatcher = super::wpe_input::dispatcher()?;
554        let humanize_mode = match mode {
555            InputMode::Human => vs_humanize::InputMode::Human,
556            InputMode::Careful => vs_humanize::InputMode::Careful,
557            InputMode::Robotic => vs_humanize::InputMode::Robotic,
558        };
559        // Screen origin of the hidden host window. v0.1.11 assumes
560        // (0, 0) — true under `xvfb` (CI) and any session without a
561        // window manager. With a WM, the WM may have translated the
562        // window elsewhere; a follow-up PR will query
563        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
564        // real origin. Until then, page-local CSS px == screen px,
565        // which is fine for CI and most headless setups.
566        let (origin_x, origin_y) = (0.0_f64, 0.0_f64);
567        let start = p.last_mouse.get();
568        let seed = humanize_seed(op);
569        let landed = match op {
570            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
571                dispatcher,
572                start,
573                vs_humanize::Point { x, y },
574                (origin_x, origin_y),
575                humanize_mode,
576                seed,
577                false,
578            )?,
579            CursorOp::ClickAt { x, y } => {
580                let landed = cursor_move_along_path(
581                    dispatcher,
582                    start,
583                    vs_humanize::Point { x, y },
584                    (origin_x, origin_y),
585                    humanize_mode,
586                    seed,
587                    false,
588                )?;
589                cursor_press_release(dispatcher, landed, (origin_x, origin_y))?;
590                landed
591            }
592            CursorOp::Drag { x1, y1, x2, y2 } => {
593                let start_pt = vs_humanize::Point { x: x1, y: y1 };
594                let target = vs_humanize::Point { x: x2, y: y2 };
595                let pre = cursor_move_along_path(
596                    dispatcher,
597                    start,
598                    start_pt,
599                    (origin_x, origin_y),
600                    humanize_mode,
601                    seed,
602                    false,
603                )?;
604                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
605                    super::wpe_input::Button::Left,
606                ))?;
607                std::thread::sleep(Duration::from_millis(15));
608                let landed = cursor_move_along_path(
609                    dispatcher,
610                    pre,
611                    target,
612                    (origin_x, origin_y),
613                    humanize_mode,
614                    seed,
615                    true,
616                )?;
617                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
618                    super::wpe_input::Button::Left,
619                ))?;
620                dispatcher.flush()?;
621                // After the OS-level drag, fire the HTML5 DragEvent
622                // chain in JS so react-dnd / React-Flow HTML5 targets
623                // observe the drop.
624                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
625                let web_view = p.web_view.clone();
626                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
627                landed
628            }
629        };
630        p.last_mouse.set(landed);
631        Ok(())
632    }
633
634    fn capabilities(&self) -> EngineCapabilities {
635        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
636        EngineCapabilities {
637            renders: true,
638            honors_viewport: true,
639            measures_layout: true,
640            persists_auth: true,
641            inspector_console: any_inspector,
642            inspector_network: any_inspector,
643            inspector_cookie_events: true,
644            name: "wpe",
645            version: "Linux WebKitGTK 6 (webkit6)",
646        }
647    }
648}
649
650// =============================================================================
651// JS evaluation helper
652// =============================================================================
653
654// =============================================================================
655// Cursor primitive helpers (XTest / libei input dispatch)
656// =============================================================================
657
658/// Deterministic seed for the humanize Bezier path so the same
659/// `cursor_op` invocation produces the same trajectory on every run.
660fn humanize_seed(op: CursorOp) -> u64 {
661    // Hash the op's coordinates into a u64. Trivial mixer; replays
662    // need determinism, not cryptographic spread.
663    let (a, b, c, d) = match op {
664        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
665            (x, y, 0.0, 0.0)
666        }
667        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
668    };
669    let bits = |v: f64| v.to_bits();
670    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
671        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
672        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
673        ^ bits(d)
674}
675
676/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
677/// per step at the path's prescribed timing. Returns the final point.
678/// The `button_down` flag is unused on Linux today (XTest doesn't
679/// distinguish drag-move from plain-move — both are `MotionNotify`
680/// events; the held button state is tracked at the X server). Kept
681/// in the signature so drag callers stay symmetric with the macOS
682/// `move_along_path`.
683fn cursor_move_along_path(
684    dispatcher: &dyn super::wpe_input::InputDispatcher,
685    start: vs_humanize::Point,
686    end: vs_humanize::Point,
687    origin: (f64, f64),
688    mode: vs_humanize::InputMode,
689    seed: u64,
690    _button_down: bool,
691) -> EngineResult<vs_humanize::Point> {
692    let path = vs_humanize::mouse_path(start, end, mode, seed);
693    let mut prev_ms: u128 = 0;
694    for step in &path {
695        if step.kind != vs_humanize::MouseStepKind::Move {
696            continue;
697        }
698        let screen = super::wpe_input::ScreenPoint {
699            #[allow(clippy::cast_possible_truncation)]
700            x: (origin.0 + step.point.x).round() as i32,
701            #[allow(clippy::cast_possible_truncation)]
702            y: (origin.1 + step.point.y).round() as i32,
703        };
704        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
705        let dt = step.at.as_millis().saturating_sub(prev_ms);
706        if dt > 0 {
707            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
708        }
709        prev_ms = step.at.as_millis();
710    }
711    // Final settling move ending exactly at `end`.
712    let final_pt = super::wpe_input::ScreenPoint {
713        #[allow(clippy::cast_possible_truncation)]
714        x: (origin.0 + end.x).round() as i32,
715        #[allow(clippy::cast_possible_truncation)]
716        y: (origin.1 + end.y).round() as i32,
717    };
718    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
719    dispatcher.flush()?;
720    Ok(end)
721}
722
723/// Press-then-release left button at the current pointer position.
724/// Matches the `mouseDown` / 15 ms / `mouseUp` cadence the macOS
725/// backend uses so JS sees a coherent `click` event.
726fn cursor_press_release(
727    dispatcher: &dyn super::wpe_input::InputDispatcher,
728    _at: vs_humanize::Point,
729    _origin: (f64, f64),
730) -> EngineResult<()> {
731    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
732        super::wpe_input::Button::Left,
733    ))?;
734    std::thread::sleep(Duration::from_millis(15));
735    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
736        super::wpe_input::Button::Left,
737    ))?;
738    dispatcher.flush()?;
739    std::thread::sleep(Duration::from_millis(30));
740    Ok(())
741}
742
743fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
744    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
745    let slot_for_cb = slot.clone();
746
747    let cancellable = webkit6::gio::Cancellable::new();
748    web_view.evaluate_javascript(
749        js,
750        None,
751        None,
752        Some(&cancellable),
753        move |result| match result {
754            Ok(value) => {
755                let s = value.to_string();
756                *slot_for_cb.borrow_mut() = Some(Ok(s));
757            }
758            Err(err) => {
759                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
760            }
761        },
762    );
763
764    let slot_check = slot.clone();
765    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
766    if !ok {
767        return Err(EngineError::Timeout {
768            budget,
769            primitive: "eval",
770        });
771    }
772    let result = slot.borrow_mut().take();
773    match result {
774        Some(Ok(s)) => Ok(s),
775        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
776        None => Err(EngineError::Other("eval completed without a result".into())),
777    }
778}
779
780// =============================================================================
781// Inspector capture wiring
782// =============================================================================
783
784/// Add the download-capture shim as a document-start script in every
785/// frame. WebKitGTK does emit a `download-started` signal, but the
786/// shim covers what that signal cannot see — an in-page `blob:` save
787/// whose object URL is revoked a tick later — and keeps the capture
788/// buffer identical across all three backends.
789fn install_download_shim(web_view: &WebView) {
790    let Some(manager) = web_view.user_content_manager() else {
791        return;
792    };
793    manager.add_script(&UserScript::new(
794        super::common::DOWNLOAD_SHIM_JS,
795        UserContentInjectedFrames::AllFrames,
796        UserScriptInjectionTime::Start,
797        &[],
798        &[],
799    ));
800}
801
802fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
803    use super::inspector_bridge::{
804        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
805    };
806
807    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
808        return false;
809    }
810
811    let manager = web_view.user_content_manager().expect(
812        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
813    );
814
815    let script = UserScript::new(
816        inspector_bridge::SCRIPT,
817        UserContentInjectedFrames::AllFrames,
818        UserScriptInjectionTime::Start,
819        &[],
820        &[],
821    );
822    manager.add_script(&script);
823
824    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
825        return false;
826    }
827    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
828        return false;
829    }
830
831    let console_slots: InspectorSlots = slots.clone();
832    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
833        let json = value.to_string();
834        let mut buf = console_slots.console.borrow_mut();
835        inspector_bridge::ingest_console(&mut buf, &json);
836    });
837    let network_slots: InspectorSlots = slots.clone();
838    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
839        let json = value.to_string();
840        let mut entries = network_slots.network.borrow_mut();
841        let mut details = network_slots.details.borrow_mut();
842        let mut pending = network_slots.pending.borrow_mut();
843        inspector_bridge::ingest_network(
844            NetworkIngestSlot {
845                entries: &mut entries,
846                details: &mut details,
847                pending: &mut pending,
848            },
849            &json,
850        );
851    });
852    true
853}
854
855// =============================================================================
856// Host-side cookie save/load via WebKitCookieManager
857// =============================================================================
858//
859// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
860// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
861// The v0.1.2 fix routes auth save/load through this path on every
862// platform.
863mod wpe_cookies {
864    use std::cell::RefCell;
865    use std::rc::Rc;
866    use std::time::Duration;
867
868    use webkit6::gio;
869    use webkit6::glib;
870    use webkit6::prelude::*;
871    use webkit6::soup;
872    use webkit6::WebView;
873
874    use crate::backend::auth::CookieData;
875    use crate::engine::{EngineError, EngineResult};
876
877    use super::run_loop_until;
878
879    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
880
881    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
882        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
883            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
884        })?;
885        session
886            .cookie_manager()
887            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
888    }
889
890    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
891        let manager = cookie_manager(web_view)?;
892        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
893        let slot_cb = slot.clone();
894        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
895            let cookies = match result {
896                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
897                Err(_) => Vec::new(),
898            };
899            *slot_cb.borrow_mut() = Some(cookies);
900        });
901        let check = slot.clone();
902        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
903        if !ok {
904            return Err(EngineError::Timeout {
905                budget: ASYNC_BUDGET,
906                primitive: "save_auth (all_cookies)",
907            });
908        }
909        let result = slot.borrow_mut().take().unwrap_or_default();
910        Ok(result)
911    }
912
913    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
914        let manager = cookie_manager(web_view)?;
915        for c in cookies {
916            if c.name.is_empty() || c.domain.is_empty() {
917                continue;
918            }
919            let path = if c.path.is_empty() {
920                "/"
921            } else {
922                c.path.as_str()
923            };
924            // max_age=-1: session cookie (no expiration). We set
925            // expires explicitly below if the saved blob carried it.
926            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
927            cookie.set_secure(c.secure);
928            cookie.set_http_only(c.http_only);
929            if let Some(unix) = c.expires_unix {
930                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
931                    cookie.set_expires(&dt);
932                }
933            }
934            if let Some(ss) = c.same_site.as_deref() {
935                let policy = match ss {
936                    "Strict" => soup::SameSitePolicy::Strict,
937                    "None" => soup::SameSitePolicy::None,
938                    _ => soup::SameSitePolicy::Lax,
939                };
940                cookie.set_same_site_policy(policy);
941            }
942
943            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
944            let done_cb = done.clone();
945            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
946                *done_cb.borrow_mut() = true;
947            });
948            let check = done.clone();
949            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
950            if !ok {
951                return Err(EngineError::Timeout {
952                    budget: ASYNC_BUDGET,
953                    primitive: "load_auth (add_cookie)",
954                });
955            }
956        }
957        Ok(())
958    }
959
960    fn serialize(c: &mut soup::Cookie) -> CookieData {
961        CookieData {
962            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
963            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
964            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
965            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
966            expires_unix: c.expires().map(|dt| dt.to_unix()),
967            secure: c.is_secure(),
968            http_only: c.is_http_only(),
969            same_site: match c.same_site_policy() {
970                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
971                soup::SameSitePolicy::None => Some("None".to_string()),
972                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
973                _ => None,
974            },
975        }
976    }
977}