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 close(&mut self, page: PageHandle) -> EngineResult<()> {
242        if let Some(p) = self.pages.remove(&page) {
243            // Dismiss the hidden host window so its `GdkSurface` is
244            // unmapped from the display server. `close()` queues the
245            // destroy; the GLib main context completes it on the next
246            // iteration.
247            p.window.close();
248        }
249        Ok(())
250    }
251
252    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
253        let p = self.page_mut(page)?;
254        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
255        parse_snapshot(&json).map_err(EngineError::Other)
256    }
257
258    fn act(&mut self, page: PageHandle, target: ActTarget, action: Action) -> EngineResult<()> {
259        let p = self.page_mut(page)?;
260        let web_view = p.web_view.clone();
261        super::common::run_act(
262            move |js, budget| eval_js_string(&web_view, js, budget),
263            &target,
264            &action,
265        )
266    }
267
268    fn wait(
269        &mut self,
270        page: PageHandle,
271        cond: WaitCondition,
272        budget: Duration,
273    ) -> EngineResult<()> {
274        let p = self.page_mut(page)?;
275        let web_view = p.web_view.clone();
276        super::common::run_wait(
277            |js, budget| eval_js_string(&web_view, js, budget),
278            &cond,
279            budget,
280            || {
281                let _ = run_loop_until(|| false, Duration::from_millis(50));
282            },
283        )
284    }
285    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
286        let p = self.page_mut(page)?;
287        let web_view = p.web_view.clone();
288        super::common::run_layout(
289            move |js, budget| eval_js_string(&web_view, js, budget),
290            refs,
291        )
292    }
293    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
294        let p = self.page_mut(page)?;
295        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
296        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
297        // The host `gtk::Window` constrains its child WebView's
298        // allocation, so resizing the WebView via `set_size_request`
299        // alone is shadowed by the (1280x800) host. Resize both: the
300        // window's default size for the surface, and the WebView's
301        // size request so its render target matches the requested
302        // viewport.
303        p.window.set_default_size(w, h);
304        p.web_view.set_size_request(w, h);
305        Ok(())
306    }
307
308    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
309        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
310        let _ = std::fs::create_dir_all(&captures_dir);
311        let path = captures_dir.join(format!("capture-{}.png", page.0));
312        let p = self.page_mut(page)?;
313        let web_view = p.web_view.clone();
314        let out_path = path.clone();
315
316        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
317        let slot_for_cb = slot.clone();
318        web_view.snapshot(
319            webkit6::SnapshotRegion::FullDocument,
320            webkit6::SnapshotOptions::NONE,
321            None::<&webkit6::gio::Cancellable>,
322            move |result| {
323                *slot_for_cb.borrow_mut() = Some(match result {
324                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
325                    Err(e) => Err(e.to_string()),
326                });
327            },
328        );
329
330        let slot_check = slot.clone();
331        let ok = run_loop_until(
332            move || slot_check.borrow().is_some(),
333            Duration::from_secs(10),
334        );
335        if !ok {
336            return Err(EngineError::Timeout {
337                budget: Duration::from_secs(10),
338                primitive: "capture",
339            });
340        }
341        let result = slot.borrow_mut().take();
342        match result {
343            Some(Ok(())) => Ok(path),
344            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
345            None => Err(EngineError::Other(
346                "capture completed without a result".into(),
347            )),
348        }
349    }
350
351    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
352        let p = self.page_mut(page)?;
353        let web_view = p.web_view.clone();
354        // Cookies: host-side via CookieManager so HttpOnly entries
355        // are captured. localStorage/sessionStorage: JS shim.
356        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
357        let storage = super::common::run_save_storage_only(move |js, budget| {
358            eval_js_string(&web_view, js, budget)
359        })?;
360        let blob = super::auth::AuthBlobV2 {
361            version: 2,
362            url: storage.url,
363            origin: storage.origin,
364            cookies,
365            local_storage: storage.local_storage,
366            session_storage: storage.session_storage,
367        };
368        super::auth::encode(&blob)
369    }
370
371    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
372        let p = self.page_mut(page)?;
373        let web_view = p.web_view.clone();
374        let parsed = super::auth::decode(blob)?;
375        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
376        super::common::run_load_storage_only(
377            move |js, budget| eval_js_string(&web_view, js, budget),
378            &parsed.local_storage,
379            &parsed.session_storage,
380        )
381    }
382
383    fn console_entries(
384        &mut self,
385        page: PageHandle,
386    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
387        let p = self.page_mut(page)?;
388        Ok(p.inspector.console.borrow().snapshot())
389    }
390
391    fn network_entries(
392        &mut self,
393        page: PageHandle,
394    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
395        let p = self.page_mut(page)?;
396        Ok(p.inspector.network.borrow().snapshot())
397    }
398
399    fn request_detail(
400        &mut self,
401        page: PageHandle,
402        seq: u64,
403    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
404        let p = self.page_mut(page)?;
405        Ok(p.inspector.details.borrow().get(seq).cloned())
406    }
407
408    fn eval_js(
409        &mut self,
410        page: PageHandle,
411        expr: &str,
412    ) -> EngineResult<crate::inspector::EvalResult> {
413        let p = self.page_mut(page)?;
414        let web_view = p.web_view.clone();
415        super::common::run_eval(
416            move |js, budget| eval_js_string(&web_view, js, budget),
417            expr,
418        )
419    }
420
421    fn storage(
422        &mut self,
423        page: PageHandle,
424        scope: crate::inspector::StorageScope,
425    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
426        let p = self.page_mut(page)?;
427        let web_view = p.web_view.clone();
428        if matches!(scope, crate::inspector::StorageScope::Cookies) {
429            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
430            return Ok(cookies
431                .iter()
432                .map(super::common::cookie_to_storage_entry)
433                .collect());
434        }
435        super::common::run_storage(
436            move |js, budget| eval_js_string(&web_view, js, budget),
437            scope,
438        )
439    }
440
441    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
442        let p = self.page_mut(page)?;
443        let web_view = p.web_view.clone();
444        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
445    }
446
447    fn script_source(
448        &mut self,
449        page: PageHandle,
450        seq: u64,
451    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
452        let p = self.page_mut(page)?;
453        let web_view = p.web_view.clone();
454        super::common::run_script_source(
455            move |js, budget| eval_js_string(&web_view, js, budget),
456            seq,
457        )
458    }
459
460    fn dom(
461        &mut self,
462        page: PageHandle,
463        r: Ref,
464        extra_props: &[String],
465    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
466        let p = self.page_mut(page)?;
467        let web_view = p.web_view.clone();
468        super::common::run_dom(
469            move |js, budget| eval_js_string(&web_view, js, budget),
470            r,
471            extra_props,
472        )
473    }
474
475    fn performance(
476        &mut self,
477        page: PageHandle,
478    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
479        let p = self.page_mut(page)?;
480        let web_view = p.web_view.clone();
481        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
482    }
483
484    fn cookie_events(
485        &mut self,
486        page: PageHandle,
487    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
488        let p = self.page_mut(page)?;
489        let web_view = p.web_view.clone();
490        let current = wpe_cookies::get_all_cookies(&web_view)?;
491        let previous = p.cookie_baseline.borrow().clone();
492        let mut seq = p.cookie_next_seq.borrow_mut();
493        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
494        *p.cookie_baseline.borrow_mut() = Some(current);
495        Ok(events)
496    }
497
498    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
499        let p = self.page_mut(page)?;
500        let dispatcher = super::wpe_input::dispatcher()?;
501        let humanize_mode = match mode {
502            InputMode::Human => vs_humanize::InputMode::Human,
503            InputMode::Careful => vs_humanize::InputMode::Careful,
504            InputMode::Robotic => vs_humanize::InputMode::Robotic,
505        };
506        // Screen origin of the hidden host window. v0.1.11 assumes
507        // (0, 0) — true under `xvfb` (CI) and any session without a
508        // window manager. With a WM, the WM may have translated the
509        // window elsewhere; a follow-up PR will query
510        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
511        // real origin. Until then, page-local CSS px == screen px,
512        // which is fine for CI and most headless setups.
513        let (origin_x, origin_y) = (0.0_f64, 0.0_f64);
514        let start = p.last_mouse.get();
515        let seed = humanize_seed(op);
516        let landed = match op {
517            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
518                dispatcher,
519                start,
520                vs_humanize::Point { x, y },
521                (origin_x, origin_y),
522                humanize_mode,
523                seed,
524                false,
525            )?,
526            CursorOp::ClickAt { x, y } => {
527                let landed = cursor_move_along_path(
528                    dispatcher,
529                    start,
530                    vs_humanize::Point { x, y },
531                    (origin_x, origin_y),
532                    humanize_mode,
533                    seed,
534                    false,
535                )?;
536                cursor_press_release(dispatcher, landed, (origin_x, origin_y))?;
537                landed
538            }
539            CursorOp::Drag { x1, y1, x2, y2 } => {
540                let start_pt = vs_humanize::Point { x: x1, y: y1 };
541                let target = vs_humanize::Point { x: x2, y: y2 };
542                let pre = cursor_move_along_path(
543                    dispatcher,
544                    start,
545                    start_pt,
546                    (origin_x, origin_y),
547                    humanize_mode,
548                    seed,
549                    false,
550                )?;
551                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
552                    super::wpe_input::Button::Left,
553                ))?;
554                std::thread::sleep(Duration::from_millis(15));
555                let landed = cursor_move_along_path(
556                    dispatcher,
557                    pre,
558                    target,
559                    (origin_x, origin_y),
560                    humanize_mode,
561                    seed,
562                    true,
563                )?;
564                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
565                    super::wpe_input::Button::Left,
566                ))?;
567                dispatcher.flush()?;
568                // After the OS-level drag, fire the HTML5 DragEvent
569                // chain in JS so react-dnd / React-Flow HTML5 targets
570                // observe the drop.
571                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
572                let web_view = p.web_view.clone();
573                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
574                landed
575            }
576        };
577        p.last_mouse.set(landed);
578        Ok(())
579    }
580
581    fn capabilities(&self) -> EngineCapabilities {
582        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
583        EngineCapabilities {
584            renders: true,
585            honors_viewport: true,
586            measures_layout: true,
587            persists_auth: true,
588            inspector_console: any_inspector,
589            inspector_network: any_inspector,
590            inspector_cookie_events: true,
591            name: "wpe",
592            version: "Linux WebKitGTK 6 (webkit6)",
593        }
594    }
595}
596
597// =============================================================================
598// JS evaluation helper
599// =============================================================================
600
601// =============================================================================
602// Cursor primitive helpers (XTest / libei input dispatch)
603// =============================================================================
604
605/// Deterministic seed for the humanize Bezier path so the same
606/// `cursor_op` invocation produces the same trajectory on every run.
607fn humanize_seed(op: CursorOp) -> u64 {
608    // Hash the op's coordinates into a u64. Trivial mixer; replays
609    // need determinism, not cryptographic spread.
610    let (a, b, c, d) = match op {
611        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
612            (x, y, 0.0, 0.0)
613        }
614        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
615    };
616    let bits = |v: f64| v.to_bits();
617    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
618        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
619        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
620        ^ bits(d)
621}
622
623/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
624/// per step at the path's prescribed timing. Returns the final point.
625/// The `button_down` flag is unused on Linux today (XTest doesn't
626/// distinguish drag-move from plain-move — both are `MotionNotify`
627/// events; the held button state is tracked at the X server). Kept
628/// in the signature so drag callers stay symmetric with the macOS
629/// `move_along_path`.
630fn cursor_move_along_path(
631    dispatcher: &dyn super::wpe_input::InputDispatcher,
632    start: vs_humanize::Point,
633    end: vs_humanize::Point,
634    origin: (f64, f64),
635    mode: vs_humanize::InputMode,
636    seed: u64,
637    _button_down: bool,
638) -> EngineResult<vs_humanize::Point> {
639    let path = vs_humanize::mouse_path(start, end, mode, seed);
640    let mut prev_ms: u128 = 0;
641    for step in &path {
642        if step.kind != vs_humanize::MouseStepKind::Move {
643            continue;
644        }
645        let screen = super::wpe_input::ScreenPoint {
646            #[allow(clippy::cast_possible_truncation)]
647            x: (origin.0 + step.point.x).round() as i32,
648            #[allow(clippy::cast_possible_truncation)]
649            y: (origin.1 + step.point.y).round() as i32,
650        };
651        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
652        let dt = step.at.as_millis().saturating_sub(prev_ms);
653        if dt > 0 {
654            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
655        }
656        prev_ms = step.at.as_millis();
657    }
658    // Final settling move ending exactly at `end`.
659    let final_pt = super::wpe_input::ScreenPoint {
660        #[allow(clippy::cast_possible_truncation)]
661        x: (origin.0 + end.x).round() as i32,
662        #[allow(clippy::cast_possible_truncation)]
663        y: (origin.1 + end.y).round() as i32,
664    };
665    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
666    dispatcher.flush()?;
667    Ok(end)
668}
669
670/// Press-then-release left button at the current pointer position.
671/// Matches the `mouseDown` / 15 ms / `mouseUp` cadence the macOS
672/// backend uses so JS sees a coherent `click` event.
673fn cursor_press_release(
674    dispatcher: &dyn super::wpe_input::InputDispatcher,
675    _at: vs_humanize::Point,
676    _origin: (f64, f64),
677) -> EngineResult<()> {
678    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
679        super::wpe_input::Button::Left,
680    ))?;
681    std::thread::sleep(Duration::from_millis(15));
682    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
683        super::wpe_input::Button::Left,
684    ))?;
685    dispatcher.flush()?;
686    std::thread::sleep(Duration::from_millis(30));
687    Ok(())
688}
689
690fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
691    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
692    let slot_for_cb = slot.clone();
693
694    let cancellable = webkit6::gio::Cancellable::new();
695    web_view.evaluate_javascript(
696        js,
697        None,
698        None,
699        Some(&cancellable),
700        move |result| match result {
701            Ok(value) => {
702                let s = value.to_string();
703                *slot_for_cb.borrow_mut() = Some(Ok(s));
704            }
705            Err(err) => {
706                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
707            }
708        },
709    );
710
711    let slot_check = slot.clone();
712    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
713    if !ok {
714        return Err(EngineError::Timeout {
715            budget,
716            primitive: "eval",
717        });
718    }
719    let result = slot.borrow_mut().take();
720    match result {
721        Some(Ok(s)) => Ok(s),
722        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
723        None => Err(EngineError::Other("eval completed without a result".into())),
724    }
725}
726
727// =============================================================================
728// Inspector capture wiring
729// =============================================================================
730
731fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
732    use super::inspector_bridge::{
733        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
734    };
735
736    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
737        return false;
738    }
739
740    let manager = web_view.user_content_manager().expect(
741        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
742    );
743
744    let script = UserScript::new(
745        inspector_bridge::SCRIPT,
746        UserContentInjectedFrames::AllFrames,
747        UserScriptInjectionTime::Start,
748        &[],
749        &[],
750    );
751    manager.add_script(&script);
752
753    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
754        return false;
755    }
756    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
757        return false;
758    }
759
760    let console_slots: InspectorSlots = slots.clone();
761    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
762        let json = value.to_string();
763        let mut buf = console_slots.console.borrow_mut();
764        inspector_bridge::ingest_console(&mut buf, &json);
765    });
766    let network_slots: InspectorSlots = slots.clone();
767    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
768        let json = value.to_string();
769        let mut entries = network_slots.network.borrow_mut();
770        let mut details = network_slots.details.borrow_mut();
771        let mut pending = network_slots.pending.borrow_mut();
772        inspector_bridge::ingest_network(
773            NetworkIngestSlot {
774                entries: &mut entries,
775                details: &mut details,
776                pending: &mut pending,
777            },
778            &json,
779        );
780    });
781    true
782}
783
784// =============================================================================
785// Host-side cookie save/load via WebKitCookieManager
786// =============================================================================
787//
788// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
789// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
790// The v0.1.2 fix routes auth save/load through this path on every
791// platform.
792mod wpe_cookies {
793    use std::cell::RefCell;
794    use std::rc::Rc;
795    use std::time::Duration;
796
797    use webkit6::gio;
798    use webkit6::glib;
799    use webkit6::prelude::*;
800    use webkit6::soup;
801    use webkit6::WebView;
802
803    use crate::backend::auth::CookieData;
804    use crate::engine::{EngineError, EngineResult};
805
806    use super::run_loop_until;
807
808    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
809
810    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
811        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
812            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
813        })?;
814        session
815            .cookie_manager()
816            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
817    }
818
819    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
820        let manager = cookie_manager(web_view)?;
821        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
822        let slot_cb = slot.clone();
823        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
824            let cookies = match result {
825                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
826                Err(_) => Vec::new(),
827            };
828            *slot_cb.borrow_mut() = Some(cookies);
829        });
830        let check = slot.clone();
831        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
832        if !ok {
833            return Err(EngineError::Timeout {
834                budget: ASYNC_BUDGET,
835                primitive: "save_auth (all_cookies)",
836            });
837        }
838        let result = slot.borrow_mut().take().unwrap_or_default();
839        Ok(result)
840    }
841
842    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
843        let manager = cookie_manager(web_view)?;
844        for c in cookies {
845            if c.name.is_empty() || c.domain.is_empty() {
846                continue;
847            }
848            let path = if c.path.is_empty() {
849                "/"
850            } else {
851                c.path.as_str()
852            };
853            // max_age=-1: session cookie (no expiration). We set
854            // expires explicitly below if the saved blob carried it.
855            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
856            cookie.set_secure(c.secure);
857            cookie.set_http_only(c.http_only);
858            if let Some(unix) = c.expires_unix {
859                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
860                    cookie.set_expires(&dt);
861                }
862            }
863            if let Some(ss) = c.same_site.as_deref() {
864                let policy = match ss {
865                    "Strict" => soup::SameSitePolicy::Strict,
866                    "None" => soup::SameSitePolicy::None,
867                    _ => soup::SameSitePolicy::Lax,
868                };
869                cookie.set_same_site_policy(policy);
870            }
871
872            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
873            let done_cb = done.clone();
874            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
875                *done_cb.borrow_mut() = true;
876            });
877            let check = done.clone();
878            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
879            if !ok {
880                return Err(EngineError::Timeout {
881                    budget: ASYNC_BUDGET,
882                    primitive: "load_auth (add_cookie)",
883                });
884            }
885        }
886        Ok(())
887    }
888
889    fn serialize(c: &mut soup::Cookie) -> CookieData {
890        CookieData {
891            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
892            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
893            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
894            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
895            expires_unix: c.expires().map(|dt| dt.to_unix()),
896            secure: c.is_secure(),
897            http_only: c.is_http_only(),
898            same_site: match c.same_site_policy() {
899                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
900                soup::SameSitePolicy::None => Some("None".to_string()),
901                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
902                _ => None,
903            },
904        }
905    }
906}