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