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, Engine, EngineCapabilities, EngineError,
40    EngineResult, InputMode, LayoutBox, PageHandle, Viewport, WaitCondition,
41};
42
43// =============================================================================
44// Per-page state
45// =============================================================================
46
47struct WpePage {
48    web_view: WebView,
49    /// Hidden host window that owns `web_view` as its single child.
50    /// Required so the WebView has a `GdkSurface` on the X display —
51    /// without it XTest's synthetic input has no window to land on.
52    /// Created in `open()`, dropped on `close()`.
53    window: gtk::Window,
54    inspector: super::inspector_bridge::InspectorSlots,
55    /// True if the inspector install path actually succeeded for this
56    /// page (script + handlers registered without bail). Read by
57    /// `Engine::capabilities()` and the daemon `vs_inspect` gate.
58    inspector_installed: bool,
59    cookie_baseline: std::cell::RefCell<Option<Vec<super::auth::CookieData>>>,
60    cookie_next_seq: std::cell::RefCell<u64>,
61    /// Last known cursor position in screen-absolute CSS px. Updated
62    /// after every `cursor_op` so the next humanized lead-in starts
63    /// where the previous one ended. Defaults to (0, 0) on `open`.
64    last_mouse: Cell<vs_humanize::Point>,
65}
66
67// =============================================================================
68// Backend
69// =============================================================================
70
71/// Real WebKitGTK 6 backend. Construct on the GTK main thread; all
72/// subsequent calls must come from the same thread.
73pub struct WpeBackend {
74    pages: HashMap<PageHandle, WpePage>,
75    next_handle: u64,
76    captures_dir: Option<PathBuf>,
77}
78
79impl Default for WpeBackend {
80    fn default() -> Self {
81        Self::new()
82    }
83}
84
85impl WpeBackend {
86    /// Build a backend. Caller must already have initialized GTK on
87    /// this thread (via `gtk4::init()`); production wiring lives in
88    /// `vs-cli::serve` on Linux. Constructing on a non-GTK thread will
89    /// panic the first time a `WebView` operation runs.
90    #[must_use]
91    pub fn new() -> Self {
92        Self {
93            pages: HashMap::new(),
94            next_handle: 1,
95            captures_dir: None,
96        }
97    }
98
99    /// Pin the directory where `capture` writes PNGs. Defaults to a
100    /// system temp subdirectory.
101    #[must_use]
102    pub fn with_capture_dir(mut self, dir: impl Into<PathBuf>) -> Self {
103        self.captures_dir = Some(dir.into());
104        self
105    }
106
107    fn alloc_handle(&mut self) -> PageHandle {
108        let h = PageHandle(self.next_handle);
109        self.next_handle += 1;
110        h
111    }
112
113    fn page_mut(&mut self, h: PageHandle) -> EngineResult<&mut WpePage> {
114        self.pages.get_mut(&h).ok_or(EngineError::NotFound {
115            kind: "page",
116            id: h.0.to_string(),
117        })
118    }
119}
120
121// =============================================================================
122// Run-loop helper: pump the GLib main context until a predicate fires
123// =============================================================================
124
125fn run_loop_until<F: FnMut() -> bool>(mut done: F, budget: Duration) -> bool {
126    let main_ctx = glib::MainContext::default();
127    let deadline = std::time::Instant::now() + budget;
128    while std::time::Instant::now() < deadline {
129        if done() {
130            return true;
131        }
132        // Iterate non-blocking; if no work, sleep briefly.
133        if !main_ctx.iteration(false) {
134            std::thread::sleep(Duration::from_millis(10));
135        }
136    }
137    done()
138}
139
140// =============================================================================
141// Shared payloads + parsers
142// =============================================================================
143
144use super::common::{parse_snapshot, SNAPSHOT_DOM_WALKER_JS as SNAPSHOT_JS};
145
146// =============================================================================
147// Engine impl
148// =============================================================================
149
150impl Engine for WpeBackend {
151    fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
152        let web_view = WebView::new();
153
154        // Hidden host window for the WebView. v0.1.11 added native
155        // input dispatch (XTest / libei) for the cursor primitives;
156        // both require the WebView to have a real `GdkSurface` on the
157        // display server so the synthetic event has somewhere to land.
158        // `WebView::new()` alone renders to an internal offscreen
159        // surface with no display-server window — XTest events would
160        // disappear into the void. Wrapping each WebView in a
161        // decorated-off `gtk::Window` and presenting it gives us that
162        // surface; under `xvfb` (CI) the window has no visual effect.
163        let window = gtk::Window::new();
164        window.set_decorated(false);
165        window.set_default_size(1280, 800);
166        window.set_child(Some(&web_view));
167        window.present();
168
169        // Pin the User-Agent to a current Safari string so anti-bot
170        // fingerprinters don't flag the WebKitGTK default. See the
171        // commit log for `crate::engine::DEFAULT_USER_AGENT` rationale.
172        if let Some(settings) = WebViewExt::settings(&web_view) {
173            settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
174        }
175
176        // Inspector capture wiring — install the user script + register
177        // both message channels BEFORE load_uri so the bridge is live
178        // by document-start.
179        let inspector =
180            super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
181        let inspector_installed = install_inspector(&web_view, &inspector);
182        web_view.load_uri(url);
183
184        // Wait for LoadEvent::Finished or LoadEvent::Failed via signal.
185        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
186        let slot_for_signal = slot.clone();
187        let signal_id = web_view.connect_load_changed(move |_view, event| {
188            if event == LoadEvent::Finished {
189                *slot_for_signal.borrow_mut() = Some(Ok(()));
190            }
191        });
192        let slot_fail = slot.clone();
193        let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
194            *slot_fail.borrow_mut() = Some(Err(err.message().to_string()));
195            // Stop event propagation: we have handled it.
196            true
197        });
198
199        let slot_check = slot.clone();
200        let ok = run_loop_until(
201            move || slot_check.borrow().is_some(),
202            Duration::from_secs(15),
203        );
204
205        // Disconnect signal handlers — the WebView outlives this scope.
206        web_view.disconnect(signal_id);
207        web_view.disconnect(fail_id);
208
209        if !ok {
210            return Err(EngineError::Timeout {
211                budget: Duration::from_secs(15),
212                primitive: "open",
213            });
214        }
215        match slot.borrow_mut().take() {
216            Some(Ok(())) => {}
217            Some(Err(msg)) => return Err(EngineError::Other(format!("navigation failed: {msg}"))),
218            None => {
219                return Err(EngineError::Other(
220                    "navigation completed without a result".into(),
221                ))
222            }
223        }
224
225        let handle = self.alloc_handle();
226        self.pages.insert(
227            handle,
228            WpePage {
229                web_view,
230                window,
231                inspector,
232                inspector_installed,
233                cookie_baseline: std::cell::RefCell::new(None),
234                cookie_next_seq: std::cell::RefCell::new(0),
235                last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
236            },
237        );
238        Ok(handle)
239    }
240
241    fn navigate(&mut self, _page: PageHandle, _url: &str) -> EngineResult<()> {
242        Err(EngineError::NotImplemented {
243            engine: "wpe",
244            primitive: "navigate",
245        })
246    }
247
248    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
249        Err(EngineError::NotImplemented {
250            engine: "wpe",
251            primitive: "enable_webauthn",
252        })
253    }
254
255    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
256        if let Some(p) = self.pages.remove(&page) {
257            // Dismiss the hidden host window so its `GdkSurface` is
258            // unmapped from the display server. `close()` queues the
259            // destroy; the GLib main context completes it on the next
260            // iteration.
261            p.window.close();
262        }
263        Ok(())
264    }
265
266    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
267        let p = self.page_mut(page)?;
268        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
269        parse_snapshot(&json).map_err(EngineError::Other)
270    }
271
272    fn act(
273        &mut self,
274        page: PageHandle,
275        target: ActTarget,
276        action: Action,
277        _mode: InputMode,
278    ) -> EngineResult<()> {
279        let p = self.page_mut(page)?;
280        let web_view = p.web_view.clone();
281        super::common::run_act(
282            move |js, budget| eval_js_string(&web_view, js, budget),
283            &target,
284            &action,
285        )
286    }
287
288    fn wait(
289        &mut self,
290        page: PageHandle,
291        cond: WaitCondition,
292        budget: Duration,
293    ) -> EngineResult<()> {
294        let p = self.page_mut(page)?;
295        let web_view = p.web_view.clone();
296        super::common::run_wait(
297            |js, budget| eval_js_string(&web_view, js, budget),
298            &cond,
299            budget,
300            || {
301                let _ = run_loop_until(|| false, Duration::from_millis(50));
302            },
303        )
304    }
305    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
306        let p = self.page_mut(page)?;
307        let web_view = p.web_view.clone();
308        super::common::run_layout(
309            move |js, budget| eval_js_string(&web_view, js, budget),
310            refs,
311        )
312    }
313    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
314        let p = self.page_mut(page)?;
315        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
316        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
317        // The host `gtk::Window` constrains its child WebView's
318        // allocation, so resizing the WebView via `set_size_request`
319        // alone is shadowed by the (1280x800) host. Resize both: the
320        // window's default size for the surface, and the WebView's
321        // size request so its render target matches the requested
322        // viewport.
323        p.window.set_default_size(w, h);
324        p.web_view.set_size_request(w, h);
325        Ok(())
326    }
327
328    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
329        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
330        let _ = std::fs::create_dir_all(&captures_dir);
331        let path = captures_dir.join(format!("capture-{}.png", page.0));
332        let p = self.page_mut(page)?;
333        let web_view = p.web_view.clone();
334        let out_path = path.clone();
335
336        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
337        let slot_for_cb = slot.clone();
338        web_view.snapshot(
339            webkit6::SnapshotRegion::FullDocument,
340            webkit6::SnapshotOptions::NONE,
341            None::<&webkit6::gio::Cancellable>,
342            move |result| {
343                *slot_for_cb.borrow_mut() = Some(match result {
344                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
345                    Err(e) => Err(e.to_string()),
346                });
347            },
348        );
349
350        let slot_check = slot.clone();
351        let ok = run_loop_until(
352            move || slot_check.borrow().is_some(),
353            Duration::from_secs(10),
354        );
355        if !ok {
356            return Err(EngineError::Timeout {
357                budget: Duration::from_secs(10),
358                primitive: "capture",
359            });
360        }
361        let result = slot.borrow_mut().take();
362        match result {
363            Some(Ok(())) => Ok(path),
364            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
365            None => Err(EngineError::Other(
366                "capture completed without a result".into(),
367            )),
368        }
369    }
370
371    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
372        let p = self.page_mut(page)?;
373        let web_view = p.web_view.clone();
374        // Cookies: host-side via CookieManager so HttpOnly entries
375        // are captured. localStorage/sessionStorage: JS shim.
376        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
377        let storage = super::common::run_save_storage_only(move |js, budget| {
378            eval_js_string(&web_view, js, budget)
379        })?;
380        let blob = super::auth::AuthBlobV2 {
381            version: 2,
382            url: storage.url,
383            origin: storage.origin,
384            cookies,
385            local_storage: storage.local_storage,
386            session_storage: storage.session_storage,
387        };
388        super::auth::encode(&blob)
389    }
390
391    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
392        let p = self.page_mut(page)?;
393        let web_view = p.web_view.clone();
394        let parsed = super::auth::decode(blob)?;
395        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
396        super::common::run_load_storage_only(
397            move |js, budget| eval_js_string(&web_view, js, budget),
398            &parsed.local_storage,
399            &parsed.session_storage,
400        )
401    }
402
403    fn console_entries(
404        &mut self,
405        page: PageHandle,
406    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
407        let p = self.page_mut(page)?;
408        Ok(p.inspector.console.borrow().snapshot())
409    }
410
411    fn network_entries(
412        &mut self,
413        page: PageHandle,
414    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
415        let p = self.page_mut(page)?;
416        Ok(p.inspector.network.borrow().snapshot())
417    }
418
419    fn request_detail(
420        &mut self,
421        page: PageHandle,
422        seq: u64,
423    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
424        let p = self.page_mut(page)?;
425        Ok(p.inspector.details.borrow().get(seq).cloned())
426    }
427
428    fn eval_js(
429        &mut self,
430        page: PageHandle,
431        expr: &str,
432    ) -> EngineResult<crate::inspector::EvalResult> {
433        let p = self.page_mut(page)?;
434        let web_view = p.web_view.clone();
435        super::common::run_eval(
436            move |js, budget| eval_js_string(&web_view, js, budget),
437            expr,
438        )
439    }
440
441    fn storage(
442        &mut self,
443        page: PageHandle,
444        scope: crate::inspector::StorageScope,
445    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
446        let p = self.page_mut(page)?;
447        let web_view = p.web_view.clone();
448        if matches!(scope, crate::inspector::StorageScope::Cookies) {
449            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
450            return Ok(cookies
451                .iter()
452                .map(super::common::cookie_to_storage_entry)
453                .collect());
454        }
455        super::common::run_storage(
456            move |js, budget| eval_js_string(&web_view, js, budget),
457            scope,
458        )
459    }
460
461    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
462        let p = self.page_mut(page)?;
463        let web_view = p.web_view.clone();
464        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
465    }
466
467    fn script_source(
468        &mut self,
469        page: PageHandle,
470        seq: u64,
471    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
472        let p = self.page_mut(page)?;
473        let web_view = p.web_view.clone();
474        super::common::run_script_source(
475            move |js, budget| eval_js_string(&web_view, js, budget),
476            seq,
477        )
478    }
479
480    fn dom(
481        &mut self,
482        page: PageHandle,
483        r: Ref,
484        extra_props: &[String],
485    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
486        let p = self.page_mut(page)?;
487        let web_view = p.web_view.clone();
488        super::common::run_dom(
489            move |js, budget| eval_js_string(&web_view, js, budget),
490            r,
491            extra_props,
492        )
493    }
494
495    fn performance(
496        &mut self,
497        page: PageHandle,
498    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
499        let p = self.page_mut(page)?;
500        let web_view = p.web_view.clone();
501        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
502    }
503
504    fn cookie_events(
505        &mut self,
506        page: PageHandle,
507    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
508        let p = self.page_mut(page)?;
509        let web_view = p.web_view.clone();
510        let current = wpe_cookies::get_all_cookies(&web_view)?;
511        let previous = p.cookie_baseline.borrow().clone();
512        let mut seq = p.cookie_next_seq.borrow_mut();
513        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
514        *p.cookie_baseline.borrow_mut() = Some(current);
515        Ok(events)
516    }
517
518    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
519        let p = self.page_mut(page)?;
520        let dispatcher = super::wpe_input::dispatcher()?;
521        let humanize_mode = match mode {
522            InputMode::Human => vs_humanize::InputMode::Human,
523            InputMode::Careful => vs_humanize::InputMode::Careful,
524            InputMode::Robotic => vs_humanize::InputMode::Robotic,
525        };
526        // Screen origin of the hidden host window. v0.1.11 assumes
527        // (0, 0) — true under `xvfb` (CI) and any session without a
528        // window manager. With a WM, the WM may have translated the
529        // window elsewhere; a follow-up PR will query
530        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
531        // real origin. Until then, page-local CSS px == screen px,
532        // which is fine for CI and most headless setups.
533        let (origin_x, origin_y) = (0.0_f64, 0.0_f64);
534        let start = p.last_mouse.get();
535        let seed = humanize_seed(op);
536        let landed = match op {
537            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
538                dispatcher,
539                start,
540                vs_humanize::Point { x, y },
541                (origin_x, origin_y),
542                humanize_mode,
543                seed,
544                false,
545            )?,
546            CursorOp::ClickAt { x, y } => {
547                let landed = cursor_move_along_path(
548                    dispatcher,
549                    start,
550                    vs_humanize::Point { x, y },
551                    (origin_x, origin_y),
552                    humanize_mode,
553                    seed,
554                    false,
555                )?;
556                cursor_press_release(dispatcher, landed, (origin_x, origin_y))?;
557                landed
558            }
559            CursorOp::Drag { x1, y1, x2, y2 } => {
560                let start_pt = vs_humanize::Point { x: x1, y: y1 };
561                let target = vs_humanize::Point { x: x2, y: y2 };
562                let pre = cursor_move_along_path(
563                    dispatcher,
564                    start,
565                    start_pt,
566                    (origin_x, origin_y),
567                    humanize_mode,
568                    seed,
569                    false,
570                )?;
571                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
572                    super::wpe_input::Button::Left,
573                ))?;
574                std::thread::sleep(Duration::from_millis(15));
575                let landed = cursor_move_along_path(
576                    dispatcher,
577                    pre,
578                    target,
579                    (origin_x, origin_y),
580                    humanize_mode,
581                    seed,
582                    true,
583                )?;
584                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
585                    super::wpe_input::Button::Left,
586                ))?;
587                dispatcher.flush()?;
588                // After the OS-level drag, fire the HTML5 DragEvent
589                // chain in JS so react-dnd / React-Flow HTML5 targets
590                // observe the drop.
591                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
592                let web_view = p.web_view.clone();
593                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
594                landed
595            }
596        };
597        p.last_mouse.set(landed);
598        Ok(())
599    }
600
601    fn capabilities(&self) -> EngineCapabilities {
602        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
603        EngineCapabilities {
604            renders: true,
605            honors_viewport: true,
606            measures_layout: true,
607            persists_auth: true,
608            inspector_console: any_inspector,
609            inspector_network: any_inspector,
610            inspector_cookie_events: true,
611            name: "wpe",
612            version: "Linux WebKitGTK 6 (webkit6)",
613        }
614    }
615}
616
617// =============================================================================
618// JS evaluation helper
619// =============================================================================
620
621// =============================================================================
622// Cursor primitive helpers (XTest / libei input dispatch)
623// =============================================================================
624
625/// Deterministic seed for the humanize Bezier path so the same
626/// `cursor_op` invocation produces the same trajectory on every run.
627fn humanize_seed(op: CursorOp) -> u64 {
628    // Hash the op's coordinates into a u64. Trivial mixer; replays
629    // need determinism, not cryptographic spread.
630    let (a, b, c, d) = match op {
631        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
632            (x, y, 0.0, 0.0)
633        }
634        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
635    };
636    let bits = |v: f64| v.to_bits();
637    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
638        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
639        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
640        ^ bits(d)
641}
642
643/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
644/// per step at the path's prescribed timing. Returns the final point.
645/// The `button_down` flag is unused on Linux today (XTest doesn't
646/// distinguish drag-move from plain-move — both are `MotionNotify`
647/// events; the held button state is tracked at the X server). Kept
648/// in the signature so drag callers stay symmetric with the macOS
649/// `move_along_path`.
650fn cursor_move_along_path(
651    dispatcher: &dyn super::wpe_input::InputDispatcher,
652    start: vs_humanize::Point,
653    end: vs_humanize::Point,
654    origin: (f64, f64),
655    mode: vs_humanize::InputMode,
656    seed: u64,
657    _button_down: bool,
658) -> EngineResult<vs_humanize::Point> {
659    let path = vs_humanize::mouse_path(start, end, mode, seed);
660    let mut prev_ms: u128 = 0;
661    for step in &path {
662        if step.kind != vs_humanize::MouseStepKind::Move {
663            continue;
664        }
665        let screen = super::wpe_input::ScreenPoint {
666            #[allow(clippy::cast_possible_truncation)]
667            x: (origin.0 + step.point.x).round() as i32,
668            #[allow(clippy::cast_possible_truncation)]
669            y: (origin.1 + step.point.y).round() as i32,
670        };
671        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
672        let dt = step.at.as_millis().saturating_sub(prev_ms);
673        if dt > 0 {
674            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
675        }
676        prev_ms = step.at.as_millis();
677    }
678    // Final settling move ending exactly at `end`.
679    let final_pt = super::wpe_input::ScreenPoint {
680        #[allow(clippy::cast_possible_truncation)]
681        x: (origin.0 + end.x).round() as i32,
682        #[allow(clippy::cast_possible_truncation)]
683        y: (origin.1 + end.y).round() as i32,
684    };
685    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
686    dispatcher.flush()?;
687    Ok(end)
688}
689
690/// Press-then-release left button at the current pointer position.
691/// Matches the `mouseDown` / 15 ms / `mouseUp` cadence the macOS
692/// backend uses so JS sees a coherent `click` event.
693fn cursor_press_release(
694    dispatcher: &dyn super::wpe_input::InputDispatcher,
695    _at: vs_humanize::Point,
696    _origin: (f64, f64),
697) -> EngineResult<()> {
698    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
699        super::wpe_input::Button::Left,
700    ))?;
701    std::thread::sleep(Duration::from_millis(15));
702    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
703        super::wpe_input::Button::Left,
704    ))?;
705    dispatcher.flush()?;
706    std::thread::sleep(Duration::from_millis(30));
707    Ok(())
708}
709
710fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
711    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
712    let slot_for_cb = slot.clone();
713
714    let cancellable = webkit6::gio::Cancellable::new();
715    web_view.evaluate_javascript(
716        js,
717        None,
718        None,
719        Some(&cancellable),
720        move |result| match result {
721            Ok(value) => {
722                let s = value.to_string();
723                *slot_for_cb.borrow_mut() = Some(Ok(s));
724            }
725            Err(err) => {
726                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
727            }
728        },
729    );
730
731    let slot_check = slot.clone();
732    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
733    if !ok {
734        return Err(EngineError::Timeout {
735            budget,
736            primitive: "eval",
737        });
738    }
739    let result = slot.borrow_mut().take();
740    match result {
741        Some(Ok(s)) => Ok(s),
742        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
743        None => Err(EngineError::Other("eval completed without a result".into())),
744    }
745}
746
747// =============================================================================
748// Inspector capture wiring
749// =============================================================================
750
751fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
752    use super::inspector_bridge::{
753        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
754    };
755
756    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
757        return false;
758    }
759
760    let manager = web_view.user_content_manager().expect(
761        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
762    );
763
764    let script = UserScript::new(
765        inspector_bridge::SCRIPT,
766        UserContentInjectedFrames::AllFrames,
767        UserScriptInjectionTime::Start,
768        &[],
769        &[],
770    );
771    manager.add_script(&script);
772
773    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
774        return false;
775    }
776    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
777        return false;
778    }
779
780    let console_slots: InspectorSlots = slots.clone();
781    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
782        let json = value.to_string();
783        let mut buf = console_slots.console.borrow_mut();
784        inspector_bridge::ingest_console(&mut buf, &json);
785    });
786    let network_slots: InspectorSlots = slots.clone();
787    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
788        let json = value.to_string();
789        let mut entries = network_slots.network.borrow_mut();
790        let mut details = network_slots.details.borrow_mut();
791        let mut pending = network_slots.pending.borrow_mut();
792        inspector_bridge::ingest_network(
793            NetworkIngestSlot {
794                entries: &mut entries,
795                details: &mut details,
796                pending: &mut pending,
797            },
798            &json,
799        );
800    });
801    true
802}
803
804// =============================================================================
805// Host-side cookie save/load via WebKitCookieManager
806// =============================================================================
807//
808// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
809// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
810// The v0.1.2 fix routes auth save/load through this path on every
811// platform.
812mod wpe_cookies {
813    use std::cell::RefCell;
814    use std::rc::Rc;
815    use std::time::Duration;
816
817    use webkit6::gio;
818    use webkit6::glib;
819    use webkit6::prelude::*;
820    use webkit6::soup;
821    use webkit6::WebView;
822
823    use crate::backend::auth::CookieData;
824    use crate::engine::{EngineError, EngineResult};
825
826    use super::run_loop_until;
827
828    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
829
830    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
831        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
832            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
833        })?;
834        session
835            .cookie_manager()
836            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
837    }
838
839    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
840        let manager = cookie_manager(web_view)?;
841        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
842        let slot_cb = slot.clone();
843        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
844            let cookies = match result {
845                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
846                Err(_) => Vec::new(),
847            };
848            *slot_cb.borrow_mut() = Some(cookies);
849        });
850        let check = slot.clone();
851        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
852        if !ok {
853            return Err(EngineError::Timeout {
854                budget: ASYNC_BUDGET,
855                primitive: "save_auth (all_cookies)",
856            });
857        }
858        let result = slot.borrow_mut().take().unwrap_or_default();
859        Ok(result)
860    }
861
862    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
863        let manager = cookie_manager(web_view)?;
864        for c in cookies {
865            if c.name.is_empty() || c.domain.is_empty() {
866                continue;
867            }
868            let path = if c.path.is_empty() {
869                "/"
870            } else {
871                c.path.as_str()
872            };
873            // max_age=-1: session cookie (no expiration). We set
874            // expires explicitly below if the saved blob carried it.
875            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
876            cookie.set_secure(c.secure);
877            cookie.set_http_only(c.http_only);
878            if let Some(unix) = c.expires_unix {
879                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
880                    cookie.set_expires(&dt);
881                }
882            }
883            if let Some(ss) = c.same_site.as_deref() {
884                let policy = match ss {
885                    "Strict" => soup::SameSitePolicy::Strict,
886                    "None" => soup::SameSitePolicy::None,
887                    _ => soup::SameSitePolicy::Lax,
888                };
889                cookie.set_same_site_policy(policy);
890            }
891
892            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
893            let done_cb = done.clone();
894            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
895                *done_cb.borrow_mut() = true;
896            });
897            let check = done.clone();
898            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
899            if !ok {
900                return Err(EngineError::Timeout {
901                    budget: ASYNC_BUDGET,
902                    primitive: "load_auth (add_cookie)",
903                });
904            }
905        }
906        Ok(())
907    }
908
909    fn serialize(c: &mut soup::Cookie) -> CookieData {
910        CookieData {
911            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
912            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
913            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
914            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
915            expires_unix: c.expires().map(|dt| dt.to_unix()),
916            secure: c.is_secure(),
917            http_only: c.is_http_only(),
918            same_site: match c.same_site_policy() {
919                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
920                soup::SameSitePolicy::None => Some("None".to_string()),
921                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
922                _ => None,
923            },
924        }
925    }
926}