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 budget = super::common::nav_budget();
210        let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
211
212        // Disconnect signal handlers — the WebView outlives this scope.
213        web_view.disconnect(signal_id);
214        web_view.disconnect(fail_id);
215
216        if !ok {
217            return Err(EngineError::Timeout {
218                budget,
219                primitive: "open",
220            });
221        }
222        match slot.borrow_mut().take() {
223            Some(Ok(())) => {}
224            Some(Err(msg)) => return Err(EngineError::Other(format!("navigation failed: {msg}"))),
225            None => {
226                return Err(EngineError::Other(
227                    "navigation completed without a result".into(),
228                ))
229            }
230        }
231
232        let handle = self.alloc_handle();
233        self.pages.insert(
234            handle,
235            WpePage {
236                web_view,
237                window,
238                inspector,
239                inspector_installed,
240                cookie_baseline: std::cell::RefCell::new(None),
241                cookie_next_seq: std::cell::RefCell::new(0),
242                last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
243            },
244        );
245        Ok(handle)
246    }
247
248    fn navigate(&mut self, _page: PageHandle, _url: &str) -> EngineResult<()> {
249        Err(EngineError::NotImplemented {
250            engine: "wpe",
251            primitive: "navigate",
252        })
253    }
254
255    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
256        Err(EngineError::NotImplemented {
257            engine: "wpe",
258            primitive: "enable_webauthn",
259        })
260    }
261
262    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
263        if let Some(p) = self.pages.remove(&page) {
264            // Dismiss the hidden host window so its `GdkSurface` is
265            // unmapped from the display server. `close()` queues the
266            // destroy; the GLib main context completes it on the next
267            // iteration.
268            p.window.close();
269        }
270        Ok(())
271    }
272
273    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
274        let p = self.page_mut(page)?;
275        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
276        parse_snapshot(&json).map_err(EngineError::Other)
277    }
278
279    fn act(
280        &mut self,
281        page: PageHandle,
282        target: ActTarget,
283        action: Action,
284        _mode: InputMode,
285    ) -> EngineResult<()> {
286        let p = self.page_mut(page)?;
287        let web_view = p.web_view.clone();
288        super::common::run_act(
289            move |js, budget| eval_js_string(&web_view, js, budget),
290            &target,
291            &action,
292        )
293    }
294
295    fn wait(
296        &mut self,
297        page: PageHandle,
298        cond: WaitCondition,
299        budget: Duration,
300    ) -> EngineResult<()> {
301        let p = self.page_mut(page)?;
302        let web_view = p.web_view.clone();
303        super::common::run_wait(
304            |js, budget| eval_js_string(&web_view, js, budget),
305            &cond,
306            budget,
307            || {
308                let _ = run_loop_until(|| false, Duration::from_millis(50));
309            },
310        )
311    }
312    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
313        let p = self.page_mut(page)?;
314        let web_view = p.web_view.clone();
315        super::common::run_layout(
316            move |js, budget| eval_js_string(&web_view, js, budget),
317            refs,
318        )
319    }
320
321    fn download(
322        &mut self,
323        page: PageHandle,
324        source: DownloadSource,
325        budget: Duration,
326    ) -> EngineResult<Download> {
327        let p = self.page_mut(page)?;
328        let web_view = p.web_view.clone();
329        super::common::run_download(
330            |js, budget| eval_js_string(&web_view, js, budget),
331            || {
332                let _ = run_loop_until(|| false, Duration::from_millis(50));
333            },
334            &source,
335            budget,
336        )
337    }
338
339    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
340        let p = self.page_mut(page)?;
341        let web_view = p.web_view.clone();
342        super::common::run_download_list(move |js, budget| eval_js_string(&web_view, js, budget))
343    }
344    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
345        let p = self.page_mut(page)?;
346        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
347        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
348        // The host `gtk::Window` constrains its child WebView's
349        // allocation, so resizing the WebView via `set_size_request`
350        // alone is shadowed by the (1280x800) host. Resize both: the
351        // window's default size for the surface, and the WebView's
352        // size request so its render target matches the requested
353        // viewport.
354        p.window.set_default_size(w, h);
355        p.web_view.set_size_request(w, h);
356        Ok(())
357    }
358
359    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
360        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
361        let _ = std::fs::create_dir_all(&captures_dir);
362        let path = captures_dir.join(format!("capture-{}.png", page.0));
363        let p = self.page_mut(page)?;
364        let web_view = p.web_view.clone();
365        let out_path = path.clone();
366
367        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
368        let slot_for_cb = slot.clone();
369        web_view.snapshot(
370            webkit6::SnapshotRegion::FullDocument,
371            webkit6::SnapshotOptions::NONE,
372            None::<&webkit6::gio::Cancellable>,
373            move |result| {
374                *slot_for_cb.borrow_mut() = Some(match result {
375                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
376                    Err(e) => Err(e.to_string()),
377                });
378            },
379        );
380
381        let slot_check = slot.clone();
382        let ok = run_loop_until(
383            move || slot_check.borrow().is_some(),
384            Duration::from_secs(10),
385        );
386        if !ok {
387            return Err(EngineError::Timeout {
388                budget: Duration::from_secs(10),
389                primitive: "capture",
390            });
391        }
392        let result = slot.borrow_mut().take();
393        match result {
394            Some(Ok(())) => Ok(path),
395            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
396            None => Err(EngineError::Other(
397                "capture completed without a result".into(),
398            )),
399        }
400    }
401
402    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
403        let p = self.page_mut(page)?;
404        let web_view = p.web_view.clone();
405        // Cookies: host-side via CookieManager so HttpOnly entries
406        // are captured. localStorage/sessionStorage: JS shim.
407        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
408        let storage = super::common::run_save_storage_only(move |js, budget| {
409            eval_js_string(&web_view, js, budget)
410        })?;
411        let blob = super::auth::AuthBlobV2 {
412            version: 2,
413            url: storage.url,
414            origin: storage.origin,
415            cookies,
416            local_storage: storage.local_storage,
417            session_storage: storage.session_storage,
418        };
419        super::auth::encode(&blob)
420    }
421
422    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
423        let p = self.page_mut(page)?;
424        let web_view = p.web_view.clone();
425        let parsed = super::auth::decode(blob)?;
426        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
427        super::common::run_load_storage_only(
428            move |js, budget| eval_js_string(&web_view, js, budget),
429            &parsed.local_storage,
430            &parsed.session_storage,
431        )
432    }
433
434    fn console_entries(
435        &mut self,
436        page: PageHandle,
437    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
438        let p = self.page_mut(page)?;
439        Ok(p.inspector.console.borrow().snapshot())
440    }
441
442    fn network_entries(
443        &mut self,
444        page: PageHandle,
445    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
446        let p = self.page_mut(page)?;
447        Ok(p.inspector.network.borrow().snapshot())
448    }
449
450    fn request_detail(
451        &mut self,
452        page: PageHandle,
453        seq: u64,
454    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
455        let p = self.page_mut(page)?;
456        Ok(p.inspector.details.borrow().get(seq).cloned())
457    }
458
459    fn eval_js(
460        &mut self,
461        page: PageHandle,
462        expr: &str,
463    ) -> EngineResult<crate::inspector::EvalResult> {
464        let p = self.page_mut(page)?;
465        let web_view = p.web_view.clone();
466        super::common::run_eval(
467            move |js, budget| eval_js_string(&web_view, js, budget),
468            expr,
469        )
470    }
471
472    fn storage(
473        &mut self,
474        page: PageHandle,
475        scope: crate::inspector::StorageScope,
476    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
477        let p = self.page_mut(page)?;
478        let web_view = p.web_view.clone();
479        if matches!(scope, crate::inspector::StorageScope::Cookies) {
480            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
481            return Ok(cookies
482                .iter()
483                .map(super::common::cookie_to_storage_entry)
484                .collect());
485        }
486        super::common::run_storage(
487            move |js, budget| eval_js_string(&web_view, js, budget),
488            scope,
489        )
490    }
491
492    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
493        let p = self.page_mut(page)?;
494        let web_view = p.web_view.clone();
495        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
496    }
497
498    fn script_source(
499        &mut self,
500        page: PageHandle,
501        seq: u64,
502    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
503        let p = self.page_mut(page)?;
504        let web_view = p.web_view.clone();
505        super::common::run_script_source(
506            move |js, budget| eval_js_string(&web_view, js, budget),
507            seq,
508        )
509    }
510
511    fn dom(
512        &mut self,
513        page: PageHandle,
514        r: Ref,
515        extra_props: &[String],
516    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
517        let p = self.page_mut(page)?;
518        let web_view = p.web_view.clone();
519        super::common::run_dom(
520            move |js, budget| eval_js_string(&web_view, js, budget),
521            r,
522            extra_props,
523        )
524    }
525
526    fn performance(
527        &mut self,
528        page: PageHandle,
529    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
530        let p = self.page_mut(page)?;
531        let web_view = p.web_view.clone();
532        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
533    }
534
535    fn cookie_events(
536        &mut self,
537        page: PageHandle,
538    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
539        let p = self.page_mut(page)?;
540        let web_view = p.web_view.clone();
541        let current = wpe_cookies::get_all_cookies(&web_view)?;
542        let previous = p.cookie_baseline.borrow().clone();
543        let mut seq = p.cookie_next_seq.borrow_mut();
544        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
545        *p.cookie_baseline.borrow_mut() = Some(current);
546        Ok(events)
547    }
548
549    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
550        // Addressing the page validates it and keeps the error shape
551        // the same as every other page op, even though the keys go to
552        // whatever holds focus rather than to a page handle.
553        let cursor = self.page_mut(page)?.last_mouse.get();
554        let dispatcher = super::wpe_input::dispatcher()?;
555        // Pump GLib rather than sleep: this runs on the main thread,
556        // so a plain sleep would stop WebKit processing the very keys
557        // we are sending.
558        let settle = |d: Duration| {
559            let _ = run_loop_until(|| false, d);
560        };
561        // Put the pointer where we believe it already is before asking
562        // for focus. X hands keys to the focused window, and a
563        // headless session has no window manager to focus anything, so
564        // the pointer is what we have to go on. The caller has
565        // normally just clicked to place the caret, which means the
566        // right window is already under it.
567        #[allow(clippy::cast_possible_truncation)]
568        let at = super::wpe_input::ScreenPoint {
569            x: cursor.x as i32,
570            y: cursor.y as i32,
571        };
572        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
573        let _ = dispatcher.flush();
574        dispatcher.focus_pointer_window();
575
576        let (base_delay, span) = match mode {
577            InputMode::Robotic => (0_u64, 0_u64),
578            InputMode::Careful => (120, 0),
579            // ±40% of base, so repeated typing is not metronomic.
580            InputMode::Human => (45, 18),
581        };
582        let mut jitter = text
583            .chars()
584            .map(|c| c as u64)
585            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
586            | 1;
587
588        let typed = (|| -> EngineResult<()> {
589            for ch in text.chars() {
590                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
591                dispatcher.key_down(ch, &settle)?;
592                settle(Duration::from_millis(hold.max(1)));
593                dispatcher.key_up(ch)?;
594                if base_delay > 0 {
595                    jitter ^= jitter << 13;
596                    jitter ^= jitter >> 7;
597                    jitter ^= jitter << 17;
598                    let extra = if span == 0 {
599                        0
600                    } else {
601                        jitter % (span * 2 + 1)
602                    };
603                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
604                    settle(Duration::from_millis(wait.max(1)));
605                } else {
606                    settle(Duration::from_millis(1));
607                }
608            }
609            Ok(())
610        })();
611
612        // Give the borrowed keycode back whether the run finished or
613        // failed halfway: a stray binding would change what the user's
614        // own keyboard does for the rest of the session.
615        let restored = dispatcher.end_typing();
616        typed?;
617        restored?;
618
619        // Let the last keyUp turn into beforeinput/input before the
620        // caller reads the page back.
621        let _ = run_loop_until(|| false, Duration::from_millis(150));
622        Ok(())
623    }
624
625    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
626        let p = self.page_mut(page)?;
627        let dispatcher = super::wpe_input::dispatcher()?;
628        let humanize_mode = match mode {
629            InputMode::Human => vs_humanize::InputMode::Human,
630            InputMode::Careful => vs_humanize::InputMode::Careful,
631            InputMode::Robotic => vs_humanize::InputMode::Robotic,
632        };
633        // Screen origin of the hidden host window. v0.1.11 assumes
634        // (0, 0) — true under `xvfb` (CI) and any session without a
635        // window manager. With a WM, the WM may have translated the
636        // window elsewhere; a follow-up PR will query
637        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
638        // real origin. Until then, page-local CSS px == screen px,
639        // which is fine for CI and most headless setups.
640        let (origin_x, origin_y) = (0.0_f64, 0.0_f64);
641        let start = p.last_mouse.get();
642        let seed = humanize_seed(op);
643        let landed = match op {
644            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
645                dispatcher,
646                start,
647                vs_humanize::Point { x, y },
648                (origin_x, origin_y),
649                humanize_mode,
650                seed,
651                false,
652            )?,
653            CursorOp::ClickAt { x, y } => {
654                let landed = cursor_move_along_path(
655                    dispatcher,
656                    start,
657                    vs_humanize::Point { x, y },
658                    (origin_x, origin_y),
659                    humanize_mode,
660                    seed,
661                    false,
662                )?;
663                cursor_press_release(dispatcher, landed, (origin_x, origin_y))?;
664                landed
665            }
666            CursorOp::Drag { x1, y1, x2, y2 } => {
667                let start_pt = vs_humanize::Point { x: x1, y: y1 };
668                let target = vs_humanize::Point { x: x2, y: y2 };
669                let pre = cursor_move_along_path(
670                    dispatcher,
671                    start,
672                    start_pt,
673                    (origin_x, origin_y),
674                    humanize_mode,
675                    seed,
676                    false,
677                )?;
678                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
679                    super::wpe_input::Button::Left,
680                ))?;
681                std::thread::sleep(Duration::from_millis(15));
682                let landed = cursor_move_along_path(
683                    dispatcher,
684                    pre,
685                    target,
686                    (origin_x, origin_y),
687                    humanize_mode,
688                    seed,
689                    true,
690                )?;
691                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
692                    super::wpe_input::Button::Left,
693                ))?;
694                dispatcher.flush()?;
695                // After the OS-level drag, fire the HTML5 DragEvent
696                // chain in JS so react-dnd / React-Flow HTML5 targets
697                // observe the drop.
698                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
699                let web_view = p.web_view.clone();
700                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
701                landed
702            }
703        };
704        p.last_mouse.set(landed);
705        Ok(())
706    }
707
708    fn capabilities(&self) -> EngineCapabilities {
709        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
710        EngineCapabilities {
711            renders: true,
712            honors_viewport: true,
713            measures_layout: true,
714            persists_auth: true,
715            inspector_console: any_inspector,
716            inspector_network: any_inspector,
717            inspector_cookie_events: true,
718            name: "wpe",
719            version: "Linux WebKitGTK 6 (webkit6)",
720        }
721    }
722}
723
724// =============================================================================
725// JS evaluation helper
726// =============================================================================
727
728// =============================================================================
729// Cursor primitive helpers (XTest / libei input dispatch)
730// =============================================================================
731
732/// Deterministic seed for the humanize Bezier path so the same
733/// `cursor_op` invocation produces the same trajectory on every run.
734fn humanize_seed(op: CursorOp) -> u64 {
735    // Hash the op's coordinates into a u64. Trivial mixer; replays
736    // need determinism, not cryptographic spread.
737    let (a, b, c, d) = match op {
738        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
739            (x, y, 0.0, 0.0)
740        }
741        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
742    };
743    let bits = |v: f64| v.to_bits();
744    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
745        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
746        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
747        ^ bits(d)
748}
749
750/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
751/// per step at the path's prescribed timing. Returns the final point.
752/// The `button_down` flag is unused on Linux today (XTest doesn't
753/// distinguish drag-move from plain-move — both are `MotionNotify`
754/// events; the held button state is tracked at the X server). Kept
755/// in the signature so drag callers stay symmetric with the macOS
756/// `move_along_path`.
757fn cursor_move_along_path(
758    dispatcher: &dyn super::wpe_input::InputDispatcher,
759    start: vs_humanize::Point,
760    end: vs_humanize::Point,
761    origin: (f64, f64),
762    mode: vs_humanize::InputMode,
763    seed: u64,
764    _button_down: bool,
765) -> EngineResult<vs_humanize::Point> {
766    let path = vs_humanize::mouse_path(start, end, mode, seed);
767    let mut prev_ms: u128 = 0;
768    for step in &path {
769        if step.kind != vs_humanize::MouseStepKind::Move {
770            continue;
771        }
772        let screen = super::wpe_input::ScreenPoint {
773            #[allow(clippy::cast_possible_truncation)]
774            x: (origin.0 + step.point.x).round() as i32,
775            #[allow(clippy::cast_possible_truncation)]
776            y: (origin.1 + step.point.y).round() as i32,
777        };
778        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
779        let dt = step.at.as_millis().saturating_sub(prev_ms);
780        if dt > 0 {
781            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
782        }
783        prev_ms = step.at.as_millis();
784    }
785    // Final settling move ending exactly at `end`.
786    let final_pt = super::wpe_input::ScreenPoint {
787        #[allow(clippy::cast_possible_truncation)]
788        x: (origin.0 + end.x).round() as i32,
789        #[allow(clippy::cast_possible_truncation)]
790        y: (origin.1 + end.y).round() as i32,
791    };
792    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
793    dispatcher.flush()?;
794    Ok(end)
795}
796
797/// Press-then-release left button at the current pointer position.
798/// Matches the `mouseDown` / 15 ms / `mouseUp` cadence the macOS
799/// backend uses so JS sees a coherent `click` event.
800fn cursor_press_release(
801    dispatcher: &dyn super::wpe_input::InputDispatcher,
802    _at: vs_humanize::Point,
803    _origin: (f64, f64),
804) -> EngineResult<()> {
805    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
806        super::wpe_input::Button::Left,
807    ))?;
808    std::thread::sleep(Duration::from_millis(15));
809    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
810        super::wpe_input::Button::Left,
811    ))?;
812    dispatcher.flush()?;
813    std::thread::sleep(Duration::from_millis(30));
814    Ok(())
815}
816
817fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
818    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
819    let slot_for_cb = slot.clone();
820
821    let cancellable = webkit6::gio::Cancellable::new();
822    web_view.evaluate_javascript(
823        js,
824        None,
825        None,
826        Some(&cancellable),
827        move |result| match result {
828            Ok(value) => {
829                let s = value.to_string();
830                *slot_for_cb.borrow_mut() = Some(Ok(s));
831            }
832            Err(err) => {
833                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
834            }
835        },
836    );
837
838    let slot_check = slot.clone();
839    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
840    if !ok {
841        return Err(EngineError::Timeout {
842            budget,
843            primitive: "eval",
844        });
845    }
846    let result = slot.borrow_mut().take();
847    match result {
848        Some(Ok(s)) => Ok(s),
849        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
850        None => Err(EngineError::Other("eval completed without a result".into())),
851    }
852}
853
854// =============================================================================
855// Inspector capture wiring
856// =============================================================================
857
858/// Add the download-capture shim as a document-start script in every
859/// frame. WebKitGTK does emit a `download-started` signal, but the
860/// shim covers what that signal cannot see — an in-page `blob:` save
861/// whose object URL is revoked a tick later — and keeps the capture
862/// buffer identical across all three backends.
863fn install_download_shim(web_view: &WebView) {
864    let Some(manager) = web_view.user_content_manager() else {
865        return;
866    };
867    manager.add_script(&UserScript::new(
868        super::common::DOWNLOAD_SHIM_JS,
869        UserContentInjectedFrames::AllFrames,
870        UserScriptInjectionTime::Start,
871        &[],
872        &[],
873    ));
874}
875
876fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
877    use super::inspector_bridge::{
878        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
879    };
880
881    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
882        return false;
883    }
884
885    let manager = web_view.user_content_manager().expect(
886        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
887    );
888
889    let script = UserScript::new(
890        inspector_bridge::SCRIPT,
891        UserContentInjectedFrames::AllFrames,
892        UserScriptInjectionTime::Start,
893        &[],
894        &[],
895    );
896    manager.add_script(&script);
897
898    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
899        return false;
900    }
901    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
902        return false;
903    }
904
905    let console_slots: InspectorSlots = slots.clone();
906    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
907        let json = value.to_string();
908        let mut buf = console_slots.console.borrow_mut();
909        inspector_bridge::ingest_console(&mut buf, &json);
910    });
911    let network_slots: InspectorSlots = slots.clone();
912    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
913        let json = value.to_string();
914        let mut entries = network_slots.network.borrow_mut();
915        let mut details = network_slots.details.borrow_mut();
916        let mut pending = network_slots.pending.borrow_mut();
917        inspector_bridge::ingest_network(
918            NetworkIngestSlot {
919                entries: &mut entries,
920                details: &mut details,
921                pending: &mut pending,
922            },
923            &json,
924        );
925    });
926    true
927}
928
929// =============================================================================
930// Host-side cookie save/load via WebKitCookieManager
931// =============================================================================
932//
933// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
934// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
935// The v0.1.2 fix routes auth save/load through this path on every
936// platform.
937mod wpe_cookies {
938    use std::cell::RefCell;
939    use std::rc::Rc;
940    use std::time::Duration;
941
942    use webkit6::gio;
943    use webkit6::glib;
944    use webkit6::prelude::*;
945    use webkit6::soup;
946    use webkit6::WebView;
947
948    use crate::backend::auth::CookieData;
949    use crate::engine::{EngineError, EngineResult};
950
951    use super::run_loop_until;
952
953    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
954
955    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
956        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
957            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
958        })?;
959        session
960            .cookie_manager()
961            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
962    }
963
964    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
965        let manager = cookie_manager(web_view)?;
966        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
967        let slot_cb = slot.clone();
968        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
969            let cookies = match result {
970                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
971                Err(_) => Vec::new(),
972            };
973            *slot_cb.borrow_mut() = Some(cookies);
974        });
975        let check = slot.clone();
976        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
977        if !ok {
978            return Err(EngineError::Timeout {
979                budget: ASYNC_BUDGET,
980                primitive: "save_auth (all_cookies)",
981            });
982        }
983        let result = slot.borrow_mut().take().unwrap_or_default();
984        Ok(result)
985    }
986
987    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
988        let manager = cookie_manager(web_view)?;
989        for c in cookies {
990            if c.name.is_empty() || c.domain.is_empty() {
991                continue;
992            }
993            let path = if c.path.is_empty() {
994                "/"
995            } else {
996                c.path.as_str()
997            };
998            // max_age=-1: session cookie (no expiration). We set
999            // expires explicitly below if the saved blob carried it.
1000            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
1001            cookie.set_secure(c.secure);
1002            cookie.set_http_only(c.http_only);
1003            if let Some(unix) = c.expires_unix {
1004                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
1005                    cookie.set_expires(&dt);
1006                }
1007            }
1008            if let Some(ss) = c.same_site.as_deref() {
1009                let policy = match ss {
1010                    "Strict" => soup::SameSitePolicy::Strict,
1011                    "None" => soup::SameSitePolicy::None,
1012                    _ => soup::SameSitePolicy::Lax,
1013                };
1014                cookie.set_same_site_policy(policy);
1015            }
1016
1017            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
1018            let done_cb = done.clone();
1019            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
1020                *done_cb.borrow_mut() = true;
1021            });
1022            let check = done.clone();
1023            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
1024            if !ok {
1025                return Err(EngineError::Timeout {
1026                    budget: ASYNC_BUDGET,
1027                    primitive: "load_auth (add_cookie)",
1028                });
1029            }
1030        }
1031        Ok(())
1032    }
1033
1034    fn serialize(c: &mut soup::Cookie) -> CookieData {
1035        CookieData {
1036            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
1037            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
1038            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
1039            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
1040            expires_unix: c.expires().map(|dt| dt.to_unix()),
1041            secure: c.is_secure(),
1042            http_only: c.is_http_only(),
1043            same_site: match c.same_site_policy() {
1044                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
1045                soup::SameSitePolicy::None => Some("None".to_string()),
1046                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
1047                _ => None,
1048            },
1049        }
1050    }
1051}