Skip to main content

vs_engine_webkit/backend/
wpe.rs

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