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    /// A new-window navigation (`target="_blank"`, `window.open()`)
67    /// the page asked for and we have not loaded yet. Set by the
68    /// `create` handler installed in `open`.
69    new_window: Rc<RefCell<Option<webkit6::URIRequest>>>,
70}
71
72// =============================================================================
73// Backend
74// =============================================================================
75
76/// Real WebKitGTK 6 backend. Construct on the GTK main thread; all
77/// subsequent calls must come from the same thread.
78pub struct WpeBackend {
79    pages: HashMap<PageHandle, WpePage>,
80    next_handle: u64,
81    captures_dir: Option<PathBuf>,
82}
83
84impl Default for WpeBackend {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90impl WpeBackend {
91    /// Build a backend. Caller must already have initialized GTK on
92    /// this thread (via `gtk4::init()`); production wiring lives in
93    /// `vs-cli::serve` on Linux. Constructing on a non-GTK thread will
94    /// panic the first time a `WebView` operation runs.
95    #[must_use]
96    pub fn new() -> Self {
97        Self {
98            pages: HashMap::new(),
99            next_handle: 1,
100            captures_dir: None,
101        }
102    }
103
104    /// Pin the directory where `capture` writes PNGs. Defaults to a
105    /// system temp subdirectory.
106    #[must_use]
107    pub fn with_capture_dir(mut self, dir: impl Into<PathBuf>) -> Self {
108        self.captures_dir = Some(dir.into());
109        self
110    }
111
112    fn alloc_handle(&mut self) -> PageHandle {
113        let h = PageHandle(self.next_handle);
114        self.next_handle += 1;
115        h
116    }
117
118    fn page_mut(&mut self, h: PageHandle) -> EngineResult<&mut WpePage> {
119        self.pages.get_mut(&h).ok_or(EngineError::NotFound {
120            kind: "page",
121            id: h.0.to_string(),
122        })
123    }
124}
125
126// =============================================================================
127// Run-loop helper: pump the GLib main context until a predicate fires
128// =============================================================================
129
130fn run_loop_until<F: FnMut() -> bool>(mut done: F, budget: Duration) -> bool {
131    let main_ctx = glib::MainContext::default();
132    let deadline = std::time::Instant::now() + budget;
133    while std::time::Instant::now() < deadline {
134        if done() {
135            return true;
136        }
137        // Iterate non-blocking; if no work, sleep briefly.
138        if !main_ctx.iteration(false) {
139            std::thread::sleep(Duration::from_millis(10));
140        }
141    }
142    done()
143}
144
145// =============================================================================
146// Shared payloads + parsers
147// =============================================================================
148
149use super::common::{parse_snapshot, SNAPSHOT_DOM_WALKER_JS as SNAPSHOT_JS};
150
151// =============================================================================
152// Engine impl
153// =============================================================================
154
155impl Engine for WpeBackend {
156    fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
157        let web_view = WebView::new();
158
159        // Hidden host window for the WebView. v0.1.11 added native
160        // input dispatch (XTest / libei) for the cursor primitives;
161        // both require the WebView to have a real `GdkSurface` on the
162        // display server so the synthetic event has somewhere to land.
163        // `WebView::new()` alone renders to an internal offscreen
164        // surface with no display-server window — XTest events would
165        // disappear into the void. Wrapping each WebView in a
166        // decorated-off `gtk::Window` and presenting it gives us that
167        // surface; under `xvfb` (CI) the window has no visual effect.
168        let window = gtk::Window::new();
169        window.set_decorated(false);
170        window.set_default_size(1280, 800);
171        window.set_child(Some(&web_view));
172        window.present();
173
174        // Pin the User-Agent to a current Safari string so anti-bot
175        // fingerprinters don't flag the WebKitGTK default. See the
176        // commit log for `crate::engine::DEFAULT_USER_AGENT` rationale.
177        if let Some(settings) = WebViewExt::settings(&web_view) {
178            settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
179            // Expose `navigator.mediaDevices`. WebKitGTK gates the
180            // MediaDevices surface off by default, so the object is
181            // simply absent and anything feature-detecting camera or
182            // mic support sees a browser that cannot exist. The macOS
183            // backend needed the same switch (there via a WKPreferences
184            // KVC key); here it is public API.
185            settings.set_enable_media_stream(true);
186        }
187
188        // Inspector capture wiring — install the user script + register
189        // both message channels BEFORE load_uri so the bridge is live
190        // by document-start.
191        let inspector =
192            super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
193        let inspector_installed = install_inspector(&web_view, &inspector);
194        install_download_shim(&web_view);
195        // A headless page has no second window. Without a `create`
196        // handler WebKitGTK drops a `target="_blank"` link or form, or
197        // `window.open()`, and the click does nothing. Park the request;
198        // the input primitive that caused it loads it in this page
199        // (`follow_new_window`). `act click` on this engine is a JS
200        // click, not a user gesture, so blank-target navigation also
201        // has to be allowed without one.
202        if let Some(settings) = WebViewExt::settings(&web_view) {
203            settings.set_javascript_can_open_windows_automatically(true);
204        }
205        let new_window: Rc<RefCell<Option<webkit6::URIRequest>>> = Rc::new(RefCell::new(None));
206        let parked = new_window.clone();
207        web_view.connect_create(move |_view, action| {
208            *parked.borrow_mut() = action.request();
209            None
210        });
211        web_view.load_uri(url);
212
213        // Wait for LoadEvent::Finished or LoadEvent::Failed via signal.
214        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
215        let slot_for_signal = slot.clone();
216        let signal_id = web_view.connect_load_changed(move |_view, event| {
217            if event == LoadEvent::Finished {
218                *slot_for_signal.borrow_mut() = Some(Ok(()));
219            }
220        });
221        let slot_fail = slot.clone();
222        let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
223            *slot_fail.borrow_mut() = Some(Err(err.message().to_string()));
224            // Stop event propagation: we have handled it.
225            true
226        });
227
228        let slot_check = slot.clone();
229        let budget = super::common::nav_budget();
230        let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
231
232        // Disconnect signal handlers — the WebView outlives this scope.
233        web_view.disconnect(signal_id);
234        web_view.disconnect(fail_id);
235
236        if !ok {
237            return Err(EngineError::Timeout {
238                budget,
239                primitive: "open",
240                detail: "",
241            });
242        }
243        match slot.borrow_mut().take() {
244            Some(Ok(())) => {}
245            Some(Err(msg)) => return Err(EngineError::Other(format!("navigation failed: {msg}"))),
246            None => {
247                return Err(EngineError::Other(
248                    "navigation completed without a result".into(),
249                ))
250            }
251        }
252
253        let handle = self.alloc_handle();
254        self.pages.insert(
255            handle,
256            WpePage {
257                web_view,
258                window,
259                inspector,
260                inspector_installed,
261                cookie_baseline: std::cell::RefCell::new(None),
262                cookie_next_seq: std::cell::RefCell::new(0),
263                last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
264                new_window,
265            },
266        );
267        Ok(handle)
268    }
269
270    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()> {
271        // Same wait as `open`, on a WebView that already exists. The
272        // inspector bridge and download shim were installed at
273        // document-start and survive the navigation, so this only has
274        // to load and wait.
275        let web_view = self.page_mut(page)?.web_view.clone();
276        web_view.load_uri(url);
277        wait_for_load(&web_view, "navigate")
278    }
279
280    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
281        Err(EngineError::NotImplemented {
282            engine: "wpe",
283            primitive: "enable_webauthn",
284        })
285    }
286
287    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
288        if let Some(p) = self.pages.remove(&page) {
289            // Dismiss the hidden host window so its `GdkSurface` is
290            // unmapped from the display server. `close()` queues the
291            // destroy; the GLib main context completes it on the next
292            // iteration.
293            p.window.close();
294        }
295        Ok(())
296    }
297
298    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
299        let p = self.page_mut(page)?;
300        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
301        parse_snapshot(&json).map_err(EngineError::Other)
302    }
303
304    fn act(
305        &mut self,
306        page: PageHandle,
307        target: ActTarget,
308        action: Action,
309        _mode: InputMode,
310    ) -> EngineResult<()> {
311        self.forget_new_window(page)?;
312        let p = self.page_mut(page)?;
313        let web_view = p.web_view.clone();
314        super::common::run_act(
315            move |js, budget| eval_js_string(&web_view, js, budget),
316            &target,
317            &action,
318        )?;
319        self.follow_new_window(page, super::common::may_open_window(&action))
320    }
321
322    fn wait(
323        &mut self,
324        page: PageHandle,
325        cond: WaitCondition,
326        budget: Duration,
327    ) -> EngineResult<()> {
328        let p = self.page_mut(page)?;
329        let web_view = p.web_view.clone();
330        super::common::run_wait(
331            |js, budget| eval_js_string(&web_view, js, budget),
332            &cond,
333            budget,
334            || {
335                let _ = run_loop_until(|| false, Duration::from_millis(50));
336            },
337        )
338    }
339    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
340        let p = self.page_mut(page)?;
341        let web_view = p.web_view.clone();
342        super::common::run_layout(
343            move |js, budget| eval_js_string(&web_view, js, budget),
344            refs,
345        )
346    }
347
348    fn download(
349        &mut self,
350        page: PageHandle,
351        source: DownloadSource,
352        budget: Duration,
353    ) -> EngineResult<Download> {
354        let p = self.page_mut(page)?;
355        let web_view = p.web_view.clone();
356        super::common::run_download(
357            |js, budget| eval_js_string(&web_view, js, budget),
358            || {
359                let _ = run_loop_until(|| false, Duration::from_millis(50));
360            },
361            &source,
362            budget,
363        )
364    }
365
366    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
367        let p = self.page_mut(page)?;
368        let web_view = p.web_view.clone();
369        super::common::run_download_list(move |js, budget| eval_js_string(&web_view, js, budget))
370    }
371    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
372        let p = self.page_mut(page)?;
373        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
374        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
375        // The host `gtk::Window` constrains its child WebView's
376        // allocation, so resizing the WebView via `set_size_request`
377        // alone is shadowed by the (1280x800) host. Resize both: the
378        // window's default size for the surface, and the WebView's
379        // size request so its render target matches the requested
380        // viewport.
381        p.window.set_default_size(w, h);
382        p.web_view.set_size_request(w, h);
383        Ok(())
384    }
385
386    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
387        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
388        let _ = std::fs::create_dir_all(&captures_dir);
389        let path = captures_dir.join(format!("capture-{}.png", page.0));
390        let p = self.page_mut(page)?;
391        let web_view = p.web_view.clone();
392        let out_path = path.clone();
393
394        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
395        let slot_for_cb = slot.clone();
396        web_view.snapshot(
397            webkit6::SnapshotRegion::FullDocument,
398            webkit6::SnapshotOptions::NONE,
399            None::<&webkit6::gio::Cancellable>,
400            move |result| {
401                *slot_for_cb.borrow_mut() = Some(match result {
402                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
403                    Err(e) => Err(e.to_string()),
404                });
405            },
406        );
407
408        let slot_check = slot.clone();
409        let ok = run_loop_until(
410            move || slot_check.borrow().is_some(),
411            Duration::from_secs(10),
412        );
413        if !ok {
414            return Err(EngineError::Timeout {
415                budget: Duration::from_secs(10),
416                primitive: "capture",
417                detail: "",
418            });
419        }
420        let result = slot.borrow_mut().take();
421        match result {
422            Some(Ok(())) => Ok(path),
423            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
424            None => Err(EngineError::Other(
425                "capture completed without a result".into(),
426            )),
427        }
428    }
429
430    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
431        let p = self.page_mut(page)?;
432        let web_view = p.web_view.clone();
433        // Cookies: host-side via CookieManager so HttpOnly entries
434        // are captured. localStorage/sessionStorage: JS shim.
435        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
436        let storage = super::common::run_save_storage_only(
437            move |js, budget| eval_js_string(&web_view, js, budget),
438            || {
439                let _ = run_loop_until(|| false, Duration::from_millis(50));
440            },
441        )?;
442        let blob = super::auth::AuthBlobV2 {
443            version: 2,
444            url: storage.url,
445            origin: storage.origin,
446            cookies,
447            local_storage: storage.local_storage,
448            indexed_db: storage.indexed_db,
449            indexed_db_skipped: storage.indexed_db_skipped,
450            indexed_db_incomplete: storage.indexed_db_incomplete,
451            session_storage: storage.session_storage,
452        };
453        super::auth::encode(&blob)
454    }
455
456    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
457        let p = self.page_mut(page)?;
458        let web_view = p.web_view.clone();
459        let parsed = super::auth::decode(blob)?;
460        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
461        super::common::run_load_storage_only(
462            move |js, budget| eval_js_string(&web_view, js, budget),
463            &parsed.local_storage,
464            &parsed.session_storage,
465            &parsed.indexed_db,
466            || {
467                let _ = run_loop_until(|| false, Duration::from_millis(50));
468            },
469        )
470    }
471
472    fn console_entries(
473        &mut self,
474        page: PageHandle,
475    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
476        let p = self.page_mut(page)?;
477        Ok(p.inspector.console.borrow().snapshot())
478    }
479
480    fn network_entries(
481        &mut self,
482        page: PageHandle,
483    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
484        let p = self.page_mut(page)?;
485        Ok(p.inspector.network.borrow().snapshot())
486    }
487
488    fn request_detail(
489        &mut self,
490        page: PageHandle,
491        seq: u64,
492    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
493        let p = self.page_mut(page)?;
494        Ok(p.inspector.details.borrow().get(seq).cloned())
495    }
496
497    fn eval_js(
498        &mut self,
499        page: PageHandle,
500        expr: &str,
501    ) -> EngineResult<crate::inspector::EvalResult> {
502        let p = self.page_mut(page)?;
503        let web_view = p.web_view.clone();
504        super::common::run_eval(
505            move |js, budget| eval_js_string(&web_view, js, budget),
506            expr,
507        )
508    }
509
510    fn storage(
511        &mut self,
512        page: PageHandle,
513        scope: crate::inspector::StorageScope,
514    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
515        let p = self.page_mut(page)?;
516        let web_view = p.web_view.clone();
517        if matches!(scope, crate::inspector::StorageScope::Cookies) {
518            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
519            return Ok(cookies
520                .iter()
521                .map(super::common::cookie_to_storage_entry)
522                .collect());
523        }
524        super::common::run_storage(
525            move |js, budget| eval_js_string(&web_view, js, budget),
526            scope,
527        )
528    }
529
530    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
531        let p = self.page_mut(page)?;
532        let web_view = p.web_view.clone();
533        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
534    }
535
536    fn script_source(
537        &mut self,
538        page: PageHandle,
539        seq: u64,
540    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
541        let p = self.page_mut(page)?;
542        let web_view = p.web_view.clone();
543        super::common::run_script_source(
544            move |js, budget| eval_js_string(&web_view, js, budget),
545            seq,
546        )
547    }
548
549    fn dom(
550        &mut self,
551        page: PageHandle,
552        r: Ref,
553        extra_props: &[String],
554    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
555        let p = self.page_mut(page)?;
556        let web_view = p.web_view.clone();
557        super::common::run_dom(
558            move |js, budget| eval_js_string(&web_view, js, budget),
559            r,
560            extra_props,
561        )
562    }
563
564    fn performance(
565        &mut self,
566        page: PageHandle,
567    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
568        let p = self.page_mut(page)?;
569        let web_view = p.web_view.clone();
570        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
571    }
572
573    fn cookie_events(
574        &mut self,
575        page: PageHandle,
576    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
577        let p = self.page_mut(page)?;
578        let web_view = p.web_view.clone();
579        let current = wpe_cookies::get_all_cookies(&web_view)?;
580        let previous = p.cookie_baseline.borrow().clone();
581        let mut seq = p.cookie_next_seq.borrow_mut();
582        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
583        *p.cookie_baseline.borrow_mut() = Some(current);
584        Ok(events)
585    }
586
587    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
588        // Addressing the page validates it and keeps the error shape
589        // the same as every other page op, even though the keys go to
590        // whatever holds focus rather than to a page handle.
591        self.forget_new_window(page)?;
592        let cursor = self.page_mut(page)?.last_mouse.get();
593        let dispatcher = super::wpe_input::dispatcher()?;
594        // Pump GLib rather than sleep: this runs on the main thread,
595        // so a plain sleep would stop WebKit processing the very keys
596        // we are sending.
597        let settle = |d: Duration| {
598            let _ = run_loop_until(|| false, d);
599        };
600        // Put the pointer where we believe it already is before asking
601        // for focus. X hands keys to the focused window, and a
602        // headless session has no window manager to focus anything, so
603        // the pointer is what we have to go on. The caller has
604        // normally just clicked to place the caret, which means the
605        // right window is already under it.
606        #[allow(clippy::cast_possible_truncation)]
607        let at = super::wpe_input::ScreenPoint {
608            x: cursor.x as i32,
609            y: cursor.y as i32,
610        };
611        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
612        let _ = dispatcher.flush();
613        dispatcher.focus_pointer_window();
614
615        let (base_delay, span) = match mode {
616            InputMode::Robotic => (0_u64, 0_u64),
617            InputMode::Careful => (120, 0),
618            // ±40% of base, so repeated typing is not metronomic.
619            InputMode::Human => (45, 18),
620        };
621        let mut jitter = text
622            .chars()
623            .map(|c| c as u64)
624            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
625            | 1;
626
627        let typed = (|| -> EngineResult<()> {
628            for ch in text.chars() {
629                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
630                dispatcher.key_down(ch, &settle)?;
631                settle(Duration::from_millis(hold.max(1)));
632                dispatcher.key_up(ch)?;
633                if base_delay > 0 {
634                    jitter ^= jitter << 13;
635                    jitter ^= jitter >> 7;
636                    jitter ^= jitter << 17;
637                    let extra = if span == 0 {
638                        0
639                    } else {
640                        jitter % (span * 2 + 1)
641                    };
642                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
643                    settle(Duration::from_millis(wait.max(1)));
644                } else {
645                    settle(Duration::from_millis(1));
646                }
647            }
648            Ok(())
649        })();
650
651        // Give the borrowed keycode back whether the run finished or
652        // failed halfway: a stray binding would change what the user's
653        // own keyboard does for the rest of the session.
654        let restored = dispatcher.end_typing();
655        typed?;
656        restored?;
657
658        // Let the last keyUp turn into beforeinput/input before the
659        // caller reads the page back.
660        let _ = run_loop_until(|| false, Duration::from_millis(150));
661        self.follow_new_window(page, false)
662    }
663
664    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
665        self.forget_new_window(page)?;
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        self.follow_new_window(page, matches!(op, CursorOp::ClickAt { .. }))
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            detail: "",
885        });
886    }
887    let result = slot.borrow_mut().take();
888    match result {
889        Some(Ok(s)) => Ok(s),
890        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
891        None => Err(EngineError::Other("eval completed without a result".into())),
892    }
893}
894
895// =============================================================================
896// Inspector capture wiring
897// =============================================================================
898
899/// Add the download-capture shim as a document-start script in every
900/// frame. WebKitGTK does emit a `download-started` signal, but the
901/// shim covers what that signal cannot see — an in-page `blob:` save
902/// whose object URL is revoked a tick later — and keeps the capture
903/// buffer identical across all three backends.
904fn install_download_shim(web_view: &WebView) {
905    let Some(manager) = web_view.user_content_manager() else {
906        return;
907    };
908    manager.add_script(&UserScript::new(
909        super::common::DOWNLOAD_SHIM_JS,
910        UserContentInjectedFrames::AllFrames,
911        UserScriptInjectionTime::Start,
912        &[],
913        &[],
914    ));
915}
916
917fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
918    use super::inspector_bridge::{
919        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
920    };
921
922    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
923        return false;
924    }
925
926    let manager = web_view.user_content_manager().expect(
927        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
928    );
929
930    let script = UserScript::new(
931        inspector_bridge::SCRIPT,
932        UserContentInjectedFrames::AllFrames,
933        UserScriptInjectionTime::Start,
934        &[],
935        &[],
936    );
937    manager.add_script(&script);
938
939    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
940        return false;
941    }
942    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
943        return false;
944    }
945
946    let console_slots: InspectorSlots = slots.clone();
947    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
948        let json = value.to_string();
949        let mut buf = console_slots.console.borrow_mut();
950        inspector_bridge::ingest_console(&mut buf, &json);
951    });
952    let network_slots: InspectorSlots = slots.clone();
953    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
954        let json = value.to_string();
955        let mut entries = network_slots.network.borrow_mut();
956        let mut details = network_slots.details.borrow_mut();
957        let mut pending = network_slots.pending.borrow_mut();
958        inspector_bridge::ingest_network(
959            NetworkIngestSlot {
960                entries: &mut entries,
961                details: &mut details,
962                pending: &mut pending,
963            },
964            &json,
965        );
966    });
967    true
968}
969
970// =============================================================================
971// Host-side cookie save/load via WebKitCookieManager
972// =============================================================================
973//
974// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
975// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
976// The v0.1.2 fix routes auth save/load through this path on every
977// platform.
978mod wpe_cookies {
979    use std::cell::RefCell;
980    use std::rc::Rc;
981    use std::time::Duration;
982
983    use webkit6::gio;
984    use webkit6::glib;
985    use webkit6::prelude::*;
986    use webkit6::soup;
987    use webkit6::WebView;
988
989    use crate::backend::auth::CookieData;
990    use crate::engine::{EngineError, EngineResult};
991
992    use super::run_loop_until;
993
994    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
995
996    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
997        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
998            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
999        })?;
1000        session
1001            .cookie_manager()
1002            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
1003    }
1004
1005    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
1006        let manager = cookie_manager(web_view)?;
1007        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
1008        let slot_cb = slot.clone();
1009        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
1010            let cookies = match result {
1011                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
1012                Err(_) => Vec::new(),
1013            };
1014            *slot_cb.borrow_mut() = Some(cookies);
1015        });
1016        let check = slot.clone();
1017        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
1018        if !ok {
1019            return Err(EngineError::Timeout {
1020                budget: ASYNC_BUDGET,
1021                primitive: "save_auth (all_cookies)",
1022                detail: "",
1023            });
1024        }
1025        let result = slot.borrow_mut().take().unwrap_or_default();
1026        Ok(result)
1027    }
1028
1029    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
1030        let manager = cookie_manager(web_view)?;
1031        for c in cookies {
1032            if c.name.is_empty() || c.domain.is_empty() {
1033                continue;
1034            }
1035            let path = if c.path.is_empty() {
1036                "/"
1037            } else {
1038                c.path.as_str()
1039            };
1040            // max_age=-1: session cookie (no expiration). We set
1041            // expires explicitly below if the saved blob carried it.
1042            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
1043            cookie.set_secure(c.secure);
1044            cookie.set_http_only(c.http_only);
1045            if let Some(unix) = c.expires_unix {
1046                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
1047                    cookie.set_expires(&dt);
1048                }
1049            }
1050            if let Some(ss) = c.same_site.as_deref() {
1051                let policy = match ss {
1052                    "Strict" => soup::SameSitePolicy::Strict,
1053                    "None" => soup::SameSitePolicy::None,
1054                    _ => soup::SameSitePolicy::Lax,
1055                };
1056                cookie.set_same_site_policy(policy);
1057            }
1058
1059            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
1060            let done_cb = done.clone();
1061            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
1062                *done_cb.borrow_mut() = true;
1063            });
1064            let check = done.clone();
1065            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
1066            if !ok {
1067                return Err(EngineError::Timeout {
1068                    budget: ASYNC_BUDGET,
1069                    primitive: "load_auth (add_cookie)",
1070                    detail: "",
1071                });
1072            }
1073        }
1074        Ok(())
1075    }
1076
1077    fn serialize(c: &mut soup::Cookie) -> CookieData {
1078        CookieData {
1079            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
1080            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
1081            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
1082            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
1083            expires_unix: c.expires().map(|dt| dt.to_unix()),
1084            secure: c.is_secure(),
1085            http_only: c.is_http_only(),
1086            same_site: match c.same_site_policy() {
1087                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
1088                soup::SameSitePolicy::None => Some("None".to_string()),
1089                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
1090                _ => None,
1091            },
1092        }
1093    }
1094}
1095
1096/// Wait for the load already started on `web_view` to finish or fail.
1097fn wait_for_load(web_view: &WebView, primitive: &'static str) -> EngineResult<()> {
1098    let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
1099    let slot_for_signal = slot.clone();
1100    let signal_id = web_view.connect_load_changed(move |_view, event| {
1101        if event == LoadEvent::Finished {
1102            *slot_for_signal.borrow_mut() = Some(Ok(()));
1103        }
1104    });
1105    let slot_fail = slot.clone();
1106    let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
1107        *slot_fail.borrow_mut() = Some(Err(err.message().to_string()));
1108        true
1109    });
1110
1111    let slot_check = slot.clone();
1112    let budget = super::common::nav_budget();
1113    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
1114
1115    web_view.disconnect(signal_id);
1116    web_view.disconnect(fail_id);
1117
1118    if !ok {
1119        return Err(EngineError::Timeout {
1120            budget,
1121            primitive,
1122            detail: "",
1123        });
1124    }
1125    // Taken out of the RefCell before the match, not inside it:
1126    // as the function's tail expression the borrow guard would
1127    // otherwise outlive `slot` itself.
1128    let result = slot.borrow_mut().take();
1129    match result {
1130        Some(Ok(())) => Ok(()),
1131        Some(Err(msg)) => Err(EngineError::Other(format!("navigation failed: {msg}"))),
1132        None => Err(EngineError::Other(
1133            "navigation completed without a result".into(),
1134        )),
1135    }
1136}
1137
1138impl WpeBackend {
1139    /// Drop a new-window request parked before this input primitive
1140    /// started (a popup the page fired on its own), so the primitive
1141    /// only follows what it caused.
1142    fn forget_new_window(&mut self, page: PageHandle) -> EngineResult<()> {
1143        let _ = self.page_mut(page)?.new_window.borrow_mut().take();
1144        Ok(())
1145    }
1146
1147    /// Load a new-window navigation the last input primitive caused, in
1148    /// this page, and wait for it like `goto`. The `create` signal can
1149    /// arrive after the click returns, so after a click (`settle`) pump
1150    /// for up to `NEW_WINDOW_SETTLE` first. No parked request: no-op.
1151    fn follow_new_window(&mut self, page: PageHandle, settle: bool) -> EngineResult<()> {
1152        let p = self.page_mut(page)?;
1153        if settle {
1154            let parked = p.new_window.clone();
1155            let _ = run_loop_until(
1156                move || parked.borrow().is_some(),
1157                super::common::NEW_WINDOW_SETTLE,
1158            );
1159        }
1160        let Some(request) = p.new_window.borrow_mut().take() else {
1161            return Ok(());
1162        };
1163        let web_view = p.web_view.clone();
1164        web_view.load_request(&request);
1165        wait_for_load(&web_view, "act")
1166    }
1167}