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