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