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(
449            move |js, budget| eval_js_string(&web_view, js, budget),
450            || {
451                let _ = run_loop_until(|| false, Duration::from_millis(50));
452            },
453        )?;
454        let blob = super::auth::AuthBlobV2 {
455            version: 2,
456            url: storage.url,
457            origin: storage.origin,
458            cookies,
459            local_storage: storage.local_storage,
460            indexed_db: storage.indexed_db,
461            indexed_db_skipped: storage.indexed_db_skipped,
462            indexed_db_incomplete: storage.indexed_db_incomplete,
463            session_storage: storage.session_storage,
464        };
465        super::auth::encode(&blob)
466    }
467
468    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
469        let p = self.page_mut(page)?;
470        let web_view = p.web_view.clone();
471        let parsed = super::auth::decode(blob)?;
472        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
473        super::common::run_load_storage_only(
474            move |js, budget| eval_js_string(&web_view, js, budget),
475            &parsed.local_storage,
476            &parsed.session_storage,
477            &parsed.indexed_db,
478            || {
479                let _ = run_loop_until(|| false, Duration::from_millis(50));
480            },
481        )
482    }
483
484    fn console_entries(
485        &mut self,
486        page: PageHandle,
487    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
488        let p = self.page_mut(page)?;
489        Ok(p.inspector.console.borrow().snapshot())
490    }
491
492    fn network_entries(
493        &mut self,
494        page: PageHandle,
495    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
496        let p = self.page_mut(page)?;
497        Ok(p.inspector.network.borrow().snapshot())
498    }
499
500    fn request_detail(
501        &mut self,
502        page: PageHandle,
503        seq: u64,
504    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
505        let p = self.page_mut(page)?;
506        Ok(p.inspector.details.borrow().get(seq).cloned())
507    }
508
509    fn eval_js(
510        &mut self,
511        page: PageHandle,
512        expr: &str,
513    ) -> EngineResult<crate::inspector::EvalResult> {
514        let p = self.page_mut(page)?;
515        let web_view = p.web_view.clone();
516        super::common::run_eval(
517            move |js, budget| eval_js_string(&web_view, js, budget),
518            expr,
519        )
520    }
521
522    fn storage(
523        &mut self,
524        page: PageHandle,
525        scope: crate::inspector::StorageScope,
526    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
527        let p = self.page_mut(page)?;
528        let web_view = p.web_view.clone();
529        if matches!(scope, crate::inspector::StorageScope::Cookies) {
530            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
531            return Ok(cookies
532                .iter()
533                .map(super::common::cookie_to_storage_entry)
534                .collect());
535        }
536        super::common::run_storage(
537            move |js, budget| eval_js_string(&web_view, js, budget),
538            scope,
539        )
540    }
541
542    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
543        let p = self.page_mut(page)?;
544        let web_view = p.web_view.clone();
545        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
546    }
547
548    fn script_source(
549        &mut self,
550        page: PageHandle,
551        seq: u64,
552    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
553        let p = self.page_mut(page)?;
554        let web_view = p.web_view.clone();
555        super::common::run_script_source(
556            move |js, budget| eval_js_string(&web_view, js, budget),
557            seq,
558        )
559    }
560
561    fn dom(
562        &mut self,
563        page: PageHandle,
564        r: Ref,
565        extra_props: &[String],
566    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
567        let p = self.page_mut(page)?;
568        let web_view = p.web_view.clone();
569        super::common::run_dom(
570            move |js, budget| eval_js_string(&web_view, js, budget),
571            r,
572            extra_props,
573        )
574    }
575
576    fn performance(
577        &mut self,
578        page: PageHandle,
579    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
580        let p = self.page_mut(page)?;
581        let web_view = p.web_view.clone();
582        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
583    }
584
585    fn cookie_events(
586        &mut self,
587        page: PageHandle,
588    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
589        let p = self.page_mut(page)?;
590        let web_view = p.web_view.clone();
591        let current = wpe_cookies::get_all_cookies(&web_view)?;
592        let previous = p.cookie_baseline.borrow().clone();
593        let mut seq = p.cookie_next_seq.borrow_mut();
594        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
595        *p.cookie_baseline.borrow_mut() = Some(current);
596        Ok(events)
597    }
598
599    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
600        // Addressing the page validates it and keeps the error shape
601        // the same as every other page op, even though the keys go to
602        // whatever holds focus rather than to a page handle.
603        let cursor = self.page_mut(page)?.last_mouse.get();
604        let dispatcher = super::wpe_input::dispatcher()?;
605        // Pump GLib rather than sleep: this runs on the main thread,
606        // so a plain sleep would stop WebKit processing the very keys
607        // we are sending.
608        let settle = |d: Duration| {
609            let _ = run_loop_until(|| false, d);
610        };
611        // Put the pointer where we believe it already is before asking
612        // for focus. X hands keys to the focused window, and a
613        // headless session has no window manager to focus anything, so
614        // the pointer is what we have to go on. The caller has
615        // normally just clicked to place the caret, which means the
616        // right window is already under it.
617        #[allow(clippy::cast_possible_truncation)]
618        let at = super::wpe_input::ScreenPoint {
619            x: cursor.x as i32,
620            y: cursor.y as i32,
621        };
622        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
623        let _ = dispatcher.flush();
624        dispatcher.focus_pointer_window();
625
626        let (base_delay, span) = match mode {
627            InputMode::Robotic => (0_u64, 0_u64),
628            InputMode::Careful => (120, 0),
629            // ±40% of base, so repeated typing is not metronomic.
630            InputMode::Human => (45, 18),
631        };
632        let mut jitter = text
633            .chars()
634            .map(|c| c as u64)
635            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
636            | 1;
637
638        let typed = (|| -> EngineResult<()> {
639            for ch in text.chars() {
640                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
641                dispatcher.key_down(ch, &settle)?;
642                settle(Duration::from_millis(hold.max(1)));
643                dispatcher.key_up(ch)?;
644                if base_delay > 0 {
645                    jitter ^= jitter << 13;
646                    jitter ^= jitter >> 7;
647                    jitter ^= jitter << 17;
648                    let extra = if span == 0 {
649                        0
650                    } else {
651                        jitter % (span * 2 + 1)
652                    };
653                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
654                    settle(Duration::from_millis(wait.max(1)));
655                } else {
656                    settle(Duration::from_millis(1));
657                }
658            }
659            Ok(())
660        })();
661
662        // Give the borrowed keycode back whether the run finished or
663        // failed halfway: a stray binding would change what the user's
664        // own keyboard does for the rest of the session.
665        let restored = dispatcher.end_typing();
666        typed?;
667        restored?;
668
669        // Let the last keyUp turn into beforeinput/input before the
670        // caller reads the page back.
671        let _ = run_loop_until(|| false, Duration::from_millis(150));
672        Ok(())
673    }
674
675    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
676        let p = self.page_mut(page)?;
677        let dispatcher = super::wpe_input::dispatcher()?;
678        let humanize_mode = match mode {
679            InputMode::Human => vs_humanize::InputMode::Human,
680            InputMode::Careful => vs_humanize::InputMode::Careful,
681            InputMode::Robotic => vs_humanize::InputMode::Robotic,
682        };
683        // Screen origin of the hidden host window. v0.1.11 assumes
684        // (0, 0) — true under `xvfb` (CI) and any session without a
685        // window manager. With a WM, the WM may have translated the
686        // window elsewhere; a follow-up PR will query
687        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
688        // real origin. Until then, page-local CSS px == screen px,
689        // which is fine for CI and most headless setups.
690        let (origin_x, origin_y) = (0.0_f64, 0.0_f64);
691        let start = p.last_mouse.get();
692        let seed = humanize_seed(op);
693        let landed = match op {
694            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => 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            CursorOp::ClickAt { x, y } => {
704                let landed = cursor_move_along_path(
705                    dispatcher,
706                    start,
707                    vs_humanize::Point { x, y },
708                    (origin_x, origin_y),
709                    humanize_mode,
710                    seed,
711                    false,
712                )?;
713                cursor_press_release(dispatcher, landed, (origin_x, origin_y))?;
714                landed
715            }
716            CursorOp::Drag { x1, y1, x2, y2 } => {
717                let start_pt = vs_humanize::Point { x: x1, y: y1 };
718                let target = vs_humanize::Point { x: x2, y: y2 };
719                let pre = cursor_move_along_path(
720                    dispatcher,
721                    start,
722                    start_pt,
723                    (origin_x, origin_y),
724                    humanize_mode,
725                    seed,
726                    false,
727                )?;
728                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
729                    super::wpe_input::Button::Left,
730                ))?;
731                std::thread::sleep(Duration::from_millis(15));
732                let landed = cursor_move_along_path(
733                    dispatcher,
734                    pre,
735                    target,
736                    (origin_x, origin_y),
737                    humanize_mode,
738                    seed,
739                    true,
740                )?;
741                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
742                    super::wpe_input::Button::Left,
743                ))?;
744                dispatcher.flush()?;
745                // After the OS-level drag, fire the HTML5 DragEvent
746                // chain in JS so react-dnd / React-Flow HTML5 targets
747                // observe the drop.
748                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
749                let web_view = p.web_view.clone();
750                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
751                landed
752            }
753        };
754        p.last_mouse.set(landed);
755        Ok(())
756    }
757
758    fn capabilities(&self) -> EngineCapabilities {
759        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
760        EngineCapabilities {
761            renders: true,
762            honors_viewport: true,
763            measures_layout: true,
764            persists_auth: true,
765            inspector_console: any_inspector,
766            inspector_network: any_inspector,
767            inspector_cookie_events: true,
768            name: "wpe",
769            version: "Linux WebKitGTK 6 (webkit6)",
770        }
771    }
772}
773
774// =============================================================================
775// JS evaluation helper
776// =============================================================================
777
778// =============================================================================
779// Cursor primitive helpers (XTest / libei input dispatch)
780// =============================================================================
781
782/// Deterministic seed for the humanize Bezier path so the same
783/// `cursor_op` invocation produces the same trajectory on every run.
784fn humanize_seed(op: CursorOp) -> u64 {
785    // Hash the op's coordinates into a u64. Trivial mixer; replays
786    // need determinism, not cryptographic spread.
787    let (a, b, c, d) = match op {
788        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
789            (x, y, 0.0, 0.0)
790        }
791        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
792    };
793    let bits = |v: f64| v.to_bits();
794    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
795        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
796        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
797        ^ bits(d)
798}
799
800/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
801/// per step at the path's prescribed timing. Returns the final point.
802/// The `button_down` flag is unused on Linux today (XTest doesn't
803/// distinguish drag-move from plain-move — both are `MotionNotify`
804/// events; the held button state is tracked at the X server). Kept
805/// in the signature so drag callers stay symmetric with the macOS
806/// `move_along_path`.
807fn cursor_move_along_path(
808    dispatcher: &dyn super::wpe_input::InputDispatcher,
809    start: vs_humanize::Point,
810    end: vs_humanize::Point,
811    origin: (f64, f64),
812    mode: vs_humanize::InputMode,
813    seed: u64,
814    _button_down: bool,
815) -> EngineResult<vs_humanize::Point> {
816    let path = vs_humanize::mouse_path(start, end, mode, seed);
817    let mut prev_ms: u128 = 0;
818    for step in &path {
819        if step.kind != vs_humanize::MouseStepKind::Move {
820            continue;
821        }
822        let screen = super::wpe_input::ScreenPoint {
823            #[allow(clippy::cast_possible_truncation)]
824            x: (origin.0 + step.point.x).round() as i32,
825            #[allow(clippy::cast_possible_truncation)]
826            y: (origin.1 + step.point.y).round() as i32,
827        };
828        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
829        let dt = step.at.as_millis().saturating_sub(prev_ms);
830        if dt > 0 {
831            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
832        }
833        prev_ms = step.at.as_millis();
834    }
835    // Final settling move ending exactly at `end`.
836    let final_pt = super::wpe_input::ScreenPoint {
837        #[allow(clippy::cast_possible_truncation)]
838        x: (origin.0 + end.x).round() as i32,
839        #[allow(clippy::cast_possible_truncation)]
840        y: (origin.1 + end.y).round() as i32,
841    };
842    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
843    dispatcher.flush()?;
844    Ok(end)
845}
846
847/// Press-then-release left button at the current pointer position.
848/// Matches the `mouseDown` / 15 ms / `mouseUp` cadence the macOS
849/// backend uses so JS sees a coherent `click` event.
850fn cursor_press_release(
851    dispatcher: &dyn super::wpe_input::InputDispatcher,
852    _at: vs_humanize::Point,
853    _origin: (f64, f64),
854) -> EngineResult<()> {
855    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
856        super::wpe_input::Button::Left,
857    ))?;
858    std::thread::sleep(Duration::from_millis(15));
859    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
860        super::wpe_input::Button::Left,
861    ))?;
862    dispatcher.flush()?;
863    std::thread::sleep(Duration::from_millis(30));
864    Ok(())
865}
866
867fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
868    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
869    let slot_for_cb = slot.clone();
870
871    let cancellable = webkit6::gio::Cancellable::new();
872    web_view.evaluate_javascript(
873        js,
874        None,
875        None,
876        Some(&cancellable),
877        move |result| match result {
878            Ok(value) => {
879                let s = value.to_string();
880                *slot_for_cb.borrow_mut() = Some(Ok(s));
881            }
882            Err(err) => {
883                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
884            }
885        },
886    );
887
888    let slot_check = slot.clone();
889    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
890    if !ok {
891        return Err(EngineError::Timeout {
892            budget,
893            primitive: "eval",
894        });
895    }
896    let result = slot.borrow_mut().take();
897    match result {
898        Some(Ok(s)) => Ok(s),
899        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
900        None => Err(EngineError::Other("eval completed without a result".into())),
901    }
902}
903
904// =============================================================================
905// Inspector capture wiring
906// =============================================================================
907
908/// Add the download-capture shim as a document-start script in every
909/// frame. WebKitGTK does emit a `download-started` signal, but the
910/// shim covers what that signal cannot see — an in-page `blob:` save
911/// whose object URL is revoked a tick later — and keeps the capture
912/// buffer identical across all three backends.
913fn install_download_shim(web_view: &WebView) {
914    let Some(manager) = web_view.user_content_manager() else {
915        return;
916    };
917    manager.add_script(&UserScript::new(
918        super::common::DOWNLOAD_SHIM_JS,
919        UserContentInjectedFrames::AllFrames,
920        UserScriptInjectionTime::Start,
921        &[],
922        &[],
923    ));
924}
925
926fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
927    use super::inspector_bridge::{
928        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
929    };
930
931    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
932        return false;
933    }
934
935    let manager = web_view.user_content_manager().expect(
936        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
937    );
938
939    let script = UserScript::new(
940        inspector_bridge::SCRIPT,
941        UserContentInjectedFrames::AllFrames,
942        UserScriptInjectionTime::Start,
943        &[],
944        &[],
945    );
946    manager.add_script(&script);
947
948    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
949        return false;
950    }
951    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
952        return false;
953    }
954
955    let console_slots: InspectorSlots = slots.clone();
956    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
957        let json = value.to_string();
958        let mut buf = console_slots.console.borrow_mut();
959        inspector_bridge::ingest_console(&mut buf, &json);
960    });
961    let network_slots: InspectorSlots = slots.clone();
962    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
963        let json = value.to_string();
964        let mut entries = network_slots.network.borrow_mut();
965        let mut details = network_slots.details.borrow_mut();
966        let mut pending = network_slots.pending.borrow_mut();
967        inspector_bridge::ingest_network(
968            NetworkIngestSlot {
969                entries: &mut entries,
970                details: &mut details,
971                pending: &mut pending,
972            },
973            &json,
974        );
975    });
976    true
977}
978
979// =============================================================================
980// Host-side cookie save/load via WebKitCookieManager
981// =============================================================================
982//
983// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
984// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
985// The v0.1.2 fix routes auth save/load through this path on every
986// platform.
987mod wpe_cookies {
988    use std::cell::RefCell;
989    use std::rc::Rc;
990    use std::time::Duration;
991
992    use webkit6::gio;
993    use webkit6::glib;
994    use webkit6::prelude::*;
995    use webkit6::soup;
996    use webkit6::WebView;
997
998    use crate::backend::auth::CookieData;
999    use crate::engine::{EngineError, EngineResult};
1000
1001    use super::run_loop_until;
1002
1003    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
1004
1005    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
1006        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
1007            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
1008        })?;
1009        session
1010            .cookie_manager()
1011            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
1012    }
1013
1014    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
1015        let manager = cookie_manager(web_view)?;
1016        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
1017        let slot_cb = slot.clone();
1018        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
1019            let cookies = match result {
1020                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
1021                Err(_) => Vec::new(),
1022            };
1023            *slot_cb.borrow_mut() = Some(cookies);
1024        });
1025        let check = slot.clone();
1026        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
1027        if !ok {
1028            return Err(EngineError::Timeout {
1029                budget: ASYNC_BUDGET,
1030                primitive: "save_auth (all_cookies)",
1031            });
1032        }
1033        let result = slot.borrow_mut().take().unwrap_or_default();
1034        Ok(result)
1035    }
1036
1037    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
1038        let manager = cookie_manager(web_view)?;
1039        for c in cookies {
1040            if c.name.is_empty() || c.domain.is_empty() {
1041                continue;
1042            }
1043            let path = if c.path.is_empty() {
1044                "/"
1045            } else {
1046                c.path.as_str()
1047            };
1048            // max_age=-1: session cookie (no expiration). We set
1049            // expires explicitly below if the saved blob carried it.
1050            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
1051            cookie.set_secure(c.secure);
1052            cookie.set_http_only(c.http_only);
1053            if let Some(unix) = c.expires_unix {
1054                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
1055                    cookie.set_expires(&dt);
1056                }
1057            }
1058            if let Some(ss) = c.same_site.as_deref() {
1059                let policy = match ss {
1060                    "Strict" => soup::SameSitePolicy::Strict,
1061                    "None" => soup::SameSitePolicy::None,
1062                    _ => soup::SameSitePolicy::Lax,
1063                };
1064                cookie.set_same_site_policy(policy);
1065            }
1066
1067            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
1068            let done_cb = done.clone();
1069            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
1070                *done_cb.borrow_mut() = true;
1071            });
1072            let check = done.clone();
1073            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
1074            if !ok {
1075                return Err(EngineError::Timeout {
1076                    budget: ASYNC_BUDGET,
1077                    primitive: "load_auth (add_cookie)",
1078                });
1079            }
1080        }
1081        Ok(())
1082    }
1083
1084    fn serialize(c: &mut soup::Cookie) -> CookieData {
1085        CookieData {
1086            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
1087            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
1088            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
1089            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
1090            expires_unix: c.expires().map(|dt| dt.to_unix()),
1091            secure: c.is_secure(),
1092            http_only: c.is_http_only(),
1093            same_site: match c.same_site_policy() {
1094                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
1095                soup::SameSitePolicy::None => Some("None".to_string()),
1096                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
1097                _ => None,
1098            },
1099        }
1100    }
1101}