Skip to main content

vs_engine_webkit/backend/
wpe.rs

1//! Linux backend — real `WebKitGTK 6` driven via `webkit6` + `glib`.
2//!
3//! # Threading model
4//!
5//! WebKitGTK is bound to the GLib main context of the thread that
6//! initialized GTK. Methods on [`WpeBackend`] must be called from that
7//! thread; the type is `!Send`. Production wiring (follow-up):
8//! `vs-cli::serve` on Linux must put GTK on the OS main thread and
9//! dispatch engine calls there via `MainContext::invoke`.
10//!
11//! # Status
12//!
13//! Real WebKitGTK-backed implementation of every primitive on the
14//! [`Engine`] trait: open / close / snapshot / act / wait / layout /
15//! set_viewport / save_auth / load_auth — plus inspector capture
16//! (console + network) wired through the `UserContentManager` script-
17//! message bridge. `capture` is the only outstanding piece (a TODO in
18//! a follow-up that calls `WebView::snapshot`).
19//!
20//! Verified on Linux CI with `libwebkitgtk-6.0-dev` + `libgtk-4-dev`
21//! installed; this file is not built on macOS.
22
23use std::cell::{Cell, RefCell};
24use std::collections::HashMap;
25use std::path::PathBuf;
26use std::rc::Rc;
27use std::time::Duration;
28
29use glib::prelude::*;
30// `gtk4` is a direct dep so we can enable its `v4_10` feature (webkit6
31// needs `gtk::Accessible`); alias it to `gtk` to keep the existing refs.
32use gtk4 as gtk;
33use webkit6::prelude::*;
34use webkit6::{LoadEvent, UserContentInjectedFrames, UserScript, UserScriptInjectionTime, WebView};
35
36use vs_protocol::{Ref, Tree};
37
38use crate::engine::{
39    ActTarget, Action, AuthBlob, CaptureScope, CursorOp, Download, DownloadEntry, DownloadSource,
40    Engine, EngineCapabilities, EngineError, EngineResult, InputMode, LayoutBox, PageHandle,
41    Viewport, WaitCondition,
42};
43
44// =============================================================================
45// Per-page state
46// =============================================================================
47
48struct WpePage {
49    web_view: WebView,
50    /// Hidden host window that owns `web_view` as its single child.
51    /// Required so the WebView has a `GdkSurface` on the X display —
52    /// without it XTest's synthetic input has no window to land on.
53    /// Created in `open()`, dropped on `close()`.
54    window: gtk::Window,
55    inspector: super::inspector_bridge::InspectorSlots,
56    /// True if the inspector install path actually succeeded for this
57    /// page (script + handlers registered without bail). Read by
58    /// `Engine::capabilities()` and the daemon `vs_inspect` gate.
59    inspector_installed: bool,
60    cookie_baseline: std::cell::RefCell<Option<Vec<super::auth::CookieData>>>,
61    cookie_next_seq: std::cell::RefCell<u64>,
62    /// Last known cursor position in screen-absolute CSS px. Updated
63    /// after every `cursor_op` so the next humanized lead-in starts
64    /// where the previous one ended. Defaults to (0, 0) on `open`.
65    last_mouse: Cell<vs_humanize::Point>,
66    /// A new-window navigation (`target="_blank"`, `window.open()`)
67    /// the page asked for and we have not loaded yet. Set by the
68    /// `create` handler installed in `open`.
69    new_window: Rc<RefCell<Option<webkit6::URIRequest>>>,
70    /// Downloads this page's responses turned into.
71    downloads: SharedDownloads,
72    /// The shared network session's `download-started` handler for
73    /// this page. Disconnected on close.
74    download_hook: Option<(webkit6::NetworkSession, glib::SignalHandlerId)>,
75}
76
77// =============================================================================
78// Backend
79// =============================================================================
80
81/// Real WebKitGTK 6 backend. Construct on the GTK main thread; all
82/// subsequent calls must come from the same thread.
83pub struct WpeBackend {
84    pages: HashMap<PageHandle, WpePage>,
85    next_handle: u64,
86    captures_dir: Option<PathBuf>,
87}
88
89impl Default for WpeBackend {
90    fn default() -> Self {
91        Self::new()
92    }
93}
94
95impl WpeBackend {
96    /// Build a backend. Caller must already have initialized GTK on
97    /// this thread (via `gtk4::init()`); production wiring lives in
98    /// `vs-cli::serve` on Linux. Constructing on a non-GTK thread will
99    /// panic the first time a `WebView` operation runs.
100    #[must_use]
101    pub fn new() -> Self {
102        Self {
103            pages: HashMap::new(),
104            next_handle: 1,
105            captures_dir: None,
106        }
107    }
108
109    /// Pin the directory where `capture` writes PNGs. Defaults to a
110    /// system temp subdirectory.
111    #[must_use]
112    pub fn with_capture_dir(mut self, dir: impl Into<PathBuf>) -> Self {
113        self.captures_dir = Some(dir.into());
114        self
115    }
116
117    fn alloc_handle(&mut self) -> PageHandle {
118        let h = PageHandle(self.next_handle);
119        self.next_handle += 1;
120        h
121    }
122
123    fn page_mut(&mut self, h: PageHandle) -> EngineResult<&mut WpePage> {
124        self.pages.get_mut(&h).ok_or(EngineError::NotFound {
125            kind: "page",
126            id: h.0.to_string(),
127        })
128    }
129}
130
131// =============================================================================
132// Run-loop helper: pump the GLib main context until a predicate fires
133// =============================================================================
134
135fn run_loop_until<F: FnMut() -> bool>(mut done: F, budget: Duration) -> bool {
136    let main_ctx = glib::MainContext::default();
137    let deadline = std::time::Instant::now() + budget;
138    while std::time::Instant::now() < deadline {
139        if done() {
140            return true;
141        }
142        // Iterate non-blocking; if no work, sleep briefly.
143        if !main_ctx.iteration(false) {
144            std::thread::sleep(Duration::from_millis(10));
145        }
146    }
147    done()
148}
149
150// =============================================================================
151// Shared payloads + parsers
152// =============================================================================
153
154use super::common::{parse_snapshot, SNAPSHOT_DOM_WALKER_JS as SNAPSHOT_JS};
155use super::native_download::{
156    is_attachment, name_from_disposition, temp_path, SharedDownloads, MAX_BYTES,
157};
158
159// =============================================================================
160// Engine impl
161// =============================================================================
162
163impl Engine for WpeBackend {
164    fn open(&mut self, url: &str) -> EngineResult<PageHandle> {
165        let web_view = WebView::new();
166
167        // Hidden host window for the WebView. v0.1.11 added native
168        // input dispatch (XTest / libei) for the cursor primitives;
169        // both require the WebView to have a real `GdkSurface` on the
170        // display server so the synthetic event has somewhere to land.
171        // `WebView::new()` alone renders to an internal offscreen
172        // surface with no display-server window — XTest events would
173        // disappear into the void. Wrapping each WebView in a
174        // decorated-off `gtk::Window` and presenting it gives us that
175        // surface; under `xvfb` (CI) the window has no visual effect.
176        let window = gtk::Window::new();
177        window.set_decorated(false);
178        window.set_default_size(1280, 800);
179        window.set_child(Some(&web_view));
180        window.present();
181
182        // Pin the User-Agent to a current Safari string so anti-bot
183        // fingerprinters don't flag the WebKitGTK default. See the
184        // commit log for `crate::engine::DEFAULT_USER_AGENT` rationale.
185        if let Some(settings) = WebViewExt::settings(&web_view) {
186            settings.set_user_agent(Some(crate::engine::DEFAULT_USER_AGENT));
187            // Expose `navigator.mediaDevices`. WebKitGTK gates the
188            // MediaDevices surface off by default, so the object is
189            // simply absent and anything feature-detecting camera or
190            // mic support sees a browser that cannot exist. The macOS
191            // backend needed the same switch (there via a WKPreferences
192            // KVC key); here it is public API.
193            settings.set_enable_media_stream(true);
194        }
195
196        // Inspector capture wiring — install the user script + register
197        // both message channels BEFORE load_uri so the bridge is live
198        // by document-start.
199        let inspector =
200            super::inspector_bridge::InspectorSlots::new(crate::inspector::DEFAULT_BUFFER_CAPACITY);
201        let inspector_installed = install_inspector(&web_view, &inspector);
202        install_download_shim(&web_view);
203        // A headless page has no second window. Without a `create`
204        // handler WebKitGTK drops a `target="_blank"` link or form, or
205        // `window.open()`, and the click does nothing. Park the request;
206        // the input primitive that caused it loads it in this page
207        // (`follow_new_window`). `act click` on this engine is a JS
208        // click, not a user gesture, so blank-target navigation also
209        // has to be allowed without one.
210        if let Some(settings) = WebViewExt::settings(&web_view) {
211            settings.set_javascript_can_open_windows_automatically(true);
212        }
213        let new_window: Rc<RefCell<Option<webkit6::URIRequest>>> = Rc::new(RefCell::new(None));
214        let parked = new_window.clone();
215        web_view.connect_create(move |_view, action| {
216            *parked.borrow_mut() = action.request();
217            None
218        });
219        let downloads = SharedDownloads::default();
220        let download_hook = install_download_capture(&web_view, &downloads);
221        web_view.load_uri(url);
222
223        // Wait for LoadEvent::Finished or LoadEvent::Failed via signal.
224        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
225        let slot_for_signal = slot.clone();
226        let signal_id = web_view.connect_load_changed(move |_view, event| {
227            if event == LoadEvent::Finished {
228                *slot_for_signal.borrow_mut() = Some(Ok(()));
229            }
230        });
231        let slot_fail = slot.clone();
232        let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
233            *slot_fail.borrow_mut() = Some(load_result(err));
234            // Stop event propagation: we have handled it.
235            true
236        });
237
238        let slot_check = slot.clone();
239        let budget = super::common::nav_budget();
240        let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
241
242        // Disconnect signal handlers — the WebView outlives this scope.
243        web_view.disconnect(signal_id);
244        web_view.disconnect(fail_id);
245
246        if !ok {
247            return Err(EngineError::Timeout {
248                budget,
249                primitive: "open",
250                detail: "",
251            });
252        }
253        match slot.borrow_mut().take() {
254            Some(Ok(())) => {}
255            Some(Err(msg)) => return Err(EngineError::Other(format!("navigation failed: {msg}"))),
256            None => {
257                return Err(EngineError::Other(
258                    "navigation completed without a result".into(),
259                ))
260            }
261        }
262
263        let handle = self.alloc_handle();
264        self.pages.insert(
265            handle,
266            WpePage {
267                web_view,
268                window,
269                inspector,
270                inspector_installed,
271                cookie_baseline: std::cell::RefCell::new(None),
272                cookie_next_seq: std::cell::RefCell::new(0),
273                last_mouse: Cell::new(vs_humanize::Point { x: 0.0, y: 0.0 }),
274                new_window,
275                downloads,
276                download_hook,
277            },
278        );
279        Ok(handle)
280    }
281
282    fn navigate(&mut self, page: PageHandle, url: &str) -> EngineResult<()> {
283        // Same wait as `open`, on a WebView that already exists. The
284        // inspector bridge and download shim were installed at
285        // document-start and survive the navigation, so this only has
286        // to load and wait.
287        let web_view = self.page_mut(page)?.web_view.clone();
288        web_view.load_uri(url);
289        wait_for_load(&web_view, "navigate")
290    }
291
292    fn add_init_script(&mut self, page: PageHandle, source: &str) -> EngineResult<()> {
293        let manager = self
294            .page_mut(page)?
295            .web_view
296            .user_content_manager()
297            .ok_or_else(|| EngineError::Other("WebView has no UserContentManager".into()))?;
298        manager.add_script(&UserScript::new(
299            source,
300            UserContentInjectedFrames::AllFrames,
301            UserScriptInjectionTime::Start,
302            &[],
303            &[],
304        ));
305        Ok(())
306    }
307
308    fn enable_webauthn(&mut self, _page: PageHandle) -> EngineResult<()> {
309        Err(EngineError::NotImplemented {
310            engine: "wpe",
311            primitive: "enable_webauthn",
312        })
313    }
314
315    fn close(&mut self, page: PageHandle) -> EngineResult<()> {
316        if let Some(mut p) = self.pages.remove(&page) {
317            if let Some((session, id)) = p.download_hook.take() {
318                session.disconnect(id);
319            }
320            // Dismiss the hidden host window so its `GdkSurface` is
321            // unmapped from the display server. `close()` queues the
322            // destroy; the GLib main context completes it on the next
323            // iteration.
324            p.window.close();
325        }
326        Ok(())
327    }
328
329    fn snapshot(&mut self, page: PageHandle) -> EngineResult<Tree> {
330        let p = self.page_mut(page)?;
331        let json = eval_js_string(&p.web_view, SNAPSHOT_JS, Duration::from_secs(5))?;
332        parse_snapshot(&json).map_err(EngineError::Other)
333    }
334
335    fn act(
336        &mut self,
337        page: PageHandle,
338        target: ActTarget,
339        action: Action,
340        _mode: InputMode,
341    ) -> EngineResult<()> {
342        self.forget_new_window(page)?;
343        let p = self.page_mut(page)?;
344        let web_view = p.web_view.clone();
345        super::common::run_act(
346            move |js, budget| eval_js_string(&web_view, js, budget),
347            &target,
348            &action,
349        )?;
350        self.follow_new_window(page, super::common::may_open_window(&action))
351    }
352
353    fn wait(
354        &mut self,
355        page: PageHandle,
356        cond: WaitCondition,
357        budget: Duration,
358    ) -> EngineResult<()> {
359        let p = self.page_mut(page)?;
360        let web_view = p.web_view.clone();
361        super::common::run_wait(
362            |js, budget| eval_js_string(&web_view, js, budget),
363            &cond,
364            budget,
365            || {
366                let _ = run_loop_until(|| false, Duration::from_millis(50));
367            },
368        )
369    }
370    fn layout(&mut self, page: PageHandle, refs: &[Ref]) -> EngineResult<Vec<LayoutBox>> {
371        let p = self.page_mut(page)?;
372        let web_view = p.web_view.clone();
373        super::common::run_layout(
374            move |js, budget| eval_js_string(&web_view, js, budget),
375            refs,
376        )
377    }
378
379    fn download(
380        &mut self,
381        page: PageHandle,
382        source: DownloadSource,
383        budget: Duration,
384    ) -> EngineResult<Download> {
385        let p = self.page_mut(page)?;
386        let web_view = p.web_view.clone();
387        let native = p.downloads.clone();
388        super::common::run_download(
389            |js, budget| eval_js_string(&web_view, js, budget),
390            || {
391                let _ = run_loop_until(|| false, Duration::from_millis(50));
392            },
393            &source,
394            budget,
395            &native,
396        )
397    }
398
399    fn download_list(&mut self, page: PageHandle) -> EngineResult<Vec<DownloadEntry>> {
400        let p = self.page_mut(page)?;
401        let web_view = p.web_view.clone();
402        let native = p.downloads.clone();
403        super::common::run_download_list(
404            move |js, budget| eval_js_string(&web_view, js, budget),
405            &native,
406        )
407    }
408    fn set_viewport(&mut self, page: PageHandle, viewport: Viewport) -> EngineResult<()> {
409        let p = self.page_mut(page)?;
410        let w = i32::try_from(viewport.width).unwrap_or(i32::MAX);
411        let h = i32::try_from(viewport.height).unwrap_or(i32::MAX);
412        // The host `gtk::Window` constrains its child WebView's
413        // allocation, so resizing the WebView via `set_size_request`
414        // alone is shadowed by the (1280x800) host. Resize both: the
415        // window's default size for the surface, and the WebView's
416        // size request so its render target matches the requested
417        // viewport.
418        p.window.set_default_size(w, h);
419        p.web_view.set_size_request(w, h);
420        Ok(())
421    }
422
423    fn capture(&mut self, page: PageHandle, _scope: CaptureScope) -> EngineResult<PathBuf> {
424        let captures_dir = self.captures_dir.clone().unwrap_or_else(std::env::temp_dir);
425        let _ = std::fs::create_dir_all(&captures_dir);
426        let path = captures_dir.join(format!("capture-{}.png", page.0));
427        let p = self.page_mut(page)?;
428        let web_view = p.web_view.clone();
429        let out_path = path.clone();
430
431        let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
432        let slot_for_cb = slot.clone();
433        web_view.snapshot(
434            webkit6::SnapshotRegion::FullDocument,
435            webkit6::SnapshotOptions::NONE,
436            None::<&webkit6::gio::Cancellable>,
437            move |result| {
438                *slot_for_cb.borrow_mut() = Some(match result {
439                    Ok(texture) => texture.save_to_png(&out_path).map_err(|e| e.to_string()),
440                    Err(e) => Err(e.to_string()),
441                });
442            },
443        );
444
445        let slot_check = slot.clone();
446        let ok = run_loop_until(
447            move || slot_check.borrow().is_some(),
448            Duration::from_secs(10),
449        );
450        if !ok {
451            return Err(EngineError::Timeout {
452                budget: Duration::from_secs(10),
453                primitive: "capture",
454                detail: "",
455            });
456        }
457        let result = slot.borrow_mut().take();
458        match result {
459            Some(Ok(())) => Ok(path),
460            Some(Err(msg)) => Err(EngineError::Other(format!("capture: {msg}"))),
461            None => Err(EngineError::Other(
462                "capture completed without a result".into(),
463            )),
464        }
465    }
466
467    fn save_auth(&mut self, page: PageHandle) -> EngineResult<AuthBlob> {
468        let p = self.page_mut(page)?;
469        let web_view = p.web_view.clone();
470        // Cookies: host-side via CookieManager so HttpOnly entries
471        // are captured. localStorage/sessionStorage: JS shim.
472        let cookies = wpe_cookies::get_all_cookies(&web_view)?;
473        let storage = super::common::run_save_storage_only(
474            move |js, budget| eval_js_string(&web_view, js, budget),
475            || {
476                let _ = run_loop_until(|| false, Duration::from_millis(50));
477            },
478        )?;
479        let blob = super::auth::AuthBlobV2 {
480            version: 2,
481            url: storage.url,
482            origin: storage.origin,
483            cookies,
484            local_storage: storage.local_storage,
485            indexed_db: storage.indexed_db,
486            indexed_db_skipped: storage.indexed_db_skipped,
487            indexed_db_incomplete: storage.indexed_db_incomplete,
488            session_storage: storage.session_storage,
489        };
490        super::auth::encode(&blob)
491    }
492
493    fn load_auth(&mut self, page: PageHandle, blob: &AuthBlob) -> EngineResult<()> {
494        let p = self.page_mut(page)?;
495        let web_view = p.web_view.clone();
496        let parsed = super::auth::decode(blob)?;
497        wpe_cookies::set_cookies(&web_view, &parsed.cookies)?;
498        super::common::run_load_storage_only(
499            move |js, budget| eval_js_string(&web_view, js, budget),
500            &parsed.local_storage,
501            &parsed.session_storage,
502            &parsed.indexed_db,
503            || {
504                let _ = run_loop_until(|| false, Duration::from_millis(50));
505            },
506        )
507    }
508
509    fn console_entries(
510        &mut self,
511        page: PageHandle,
512    ) -> EngineResult<Vec<crate::inspector::ConsoleEntry>> {
513        let p = self.page_mut(page)?;
514        Ok(p.inspector.console.borrow().snapshot())
515    }
516
517    fn network_entries(
518        &mut self,
519        page: PageHandle,
520    ) -> EngineResult<Vec<crate::inspector::NetworkEntry>> {
521        let p = self.page_mut(page)?;
522        Ok(p.inspector.network.borrow().snapshot())
523    }
524
525    fn request_detail(
526        &mut self,
527        page: PageHandle,
528        seq: u64,
529    ) -> EngineResult<Option<crate::inspector::RequestDetail>> {
530        let p = self.page_mut(page)?;
531        Ok(p.inspector.details.borrow().get(seq).cloned())
532    }
533
534    fn eval_js(
535        &mut self,
536        page: PageHandle,
537        expr: &str,
538    ) -> EngineResult<crate::inspector::EvalResult> {
539        let p = self.page_mut(page)?;
540        let web_view = p.web_view.clone();
541        super::common::run_eval(
542            move |js, budget| eval_js_string(&web_view, js, budget),
543            expr,
544        )
545    }
546
547    fn storage(
548        &mut self,
549        page: PageHandle,
550        scope: crate::inspector::StorageScope,
551    ) -> EngineResult<Vec<crate::inspector::StorageEntry>> {
552        let p = self.page_mut(page)?;
553        let web_view = p.web_view.clone();
554        if matches!(scope, crate::inspector::StorageScope::Cookies) {
555            let cookies = wpe_cookies::get_all_cookies(&web_view)?;
556            return Ok(cookies
557                .iter()
558                .map(super::common::cookie_to_storage_entry)
559                .collect());
560        }
561        super::common::run_storage(
562            move |js, budget| eval_js_string(&web_view, js, budget),
563            scope,
564        )
565    }
566
567    fn scripts(&mut self, page: PageHandle) -> EngineResult<Vec<crate::inspector::ScriptEntry>> {
568        let p = self.page_mut(page)?;
569        let web_view = p.web_view.clone();
570        super::common::run_scripts(move |js, budget| eval_js_string(&web_view, js, budget))
571    }
572
573    fn script_source(
574        &mut self,
575        page: PageHandle,
576        seq: u64,
577    ) -> EngineResult<Option<crate::inspector::ScriptSource>> {
578        let p = self.page_mut(page)?;
579        let web_view = p.web_view.clone();
580        super::common::run_script_source(
581            move |js, budget| eval_js_string(&web_view, js, budget),
582            seq,
583        )
584    }
585
586    fn dom(
587        &mut self,
588        page: PageHandle,
589        r: Ref,
590        extra_props: &[String],
591    ) -> EngineResult<Option<crate::inspector::DomDetail>> {
592        let p = self.page_mut(page)?;
593        let web_view = p.web_view.clone();
594        super::common::run_dom(
595            move |js, budget| eval_js_string(&web_view, js, budget),
596            r,
597            extra_props,
598        )
599    }
600
601    fn performance(
602        &mut self,
603        page: PageHandle,
604    ) -> EngineResult<crate::inspector::PerformanceMetrics> {
605        let p = self.page_mut(page)?;
606        let web_view = p.web_view.clone();
607        super::common::run_performance(move |js, budget| eval_js_string(&web_view, js, budget))
608    }
609
610    fn cookie_events(
611        &mut self,
612        page: PageHandle,
613    ) -> EngineResult<Vec<crate::inspector::CookieEvent>> {
614        let p = self.page_mut(page)?;
615        let web_view = p.web_view.clone();
616        let current = wpe_cookies::get_all_cookies(&web_view)?;
617        let previous = p.cookie_baseline.borrow().clone();
618        let mut seq = p.cookie_next_seq.borrow_mut();
619        let events = super::common::diff_cookies(previous.as_deref(), &current, &mut seq);
620        *p.cookie_baseline.borrow_mut() = Some(current);
621        Ok(events)
622    }
623
624    fn type_text(&mut self, page: PageHandle, text: &str, mode: InputMode) -> EngineResult<()> {
625        // Addressing the page validates it and keeps the error shape
626        // the same as every other page op, even though the keys go to
627        // whatever holds focus rather than to a page handle.
628        self.forget_new_window(page)?;
629        let cursor = self.page_mut(page)?.last_mouse.get();
630        let dispatcher = super::wpe_input::dispatcher()?;
631        // Pump GLib rather than sleep: this runs on the main thread,
632        // so a plain sleep would stop WebKit processing the very keys
633        // we are sending.
634        let settle = |d: Duration| {
635            let _ = run_loop_until(|| false, d);
636        };
637        // Put the pointer where we believe it already is before asking
638        // for focus. X hands keys to the focused window, and a
639        // headless session has no window manager to focus anything, so
640        // the pointer is what we have to go on. The caller has
641        // normally just clicked to place the caret, which means the
642        // right window is already under it.
643        #[allow(clippy::cast_possible_truncation)]
644        let at = super::wpe_input::ScreenPoint {
645            x: cursor.x as i32,
646            y: cursor.y as i32,
647        };
648        let _ = dispatcher.dispatch(super::wpe_input::InputEvent::Move(at));
649        let _ = dispatcher.flush();
650        dispatcher.focus_pointer_window();
651
652        let (base_delay, span) = match mode {
653            InputMode::Robotic => (0_u64, 0_u64),
654            InputMode::Careful => (120, 0),
655            // ±40% of base, so repeated typing is not metronomic.
656            InputMode::Human => (45, 18),
657        };
658        let mut jitter = text
659            .chars()
660            .map(|c| c as u64)
661            .fold(0x9e37_79b9_u64, |a, c| a.wrapping_mul(31).wrapping_add(c))
662            | 1;
663
664        let typed = (|| -> EngineResult<()> {
665            for ch in text.chars() {
666                let hold = if base_delay == 0 { 1 } else { base_delay / 3 };
667                dispatcher.key_down(ch, &settle)?;
668                settle(Duration::from_millis(hold.max(1)));
669                dispatcher.key_up(ch)?;
670                if base_delay > 0 {
671                    jitter ^= jitter << 13;
672                    jitter ^= jitter >> 7;
673                    jitter ^= jitter << 17;
674                    let extra = if span == 0 {
675                        0
676                    } else {
677                        jitter % (span * 2 + 1)
678                    };
679                    let wait = base_delay.saturating_sub(span).saturating_add(extra);
680                    settle(Duration::from_millis(wait.max(1)));
681                } else {
682                    settle(Duration::from_millis(1));
683                }
684            }
685            Ok(())
686        })();
687
688        // Give the borrowed keycode back whether the run finished or
689        // failed halfway: a stray binding would change what the user's
690        // own keyboard does for the rest of the session.
691        let restored = dispatcher.end_typing();
692        typed?;
693        restored?;
694
695        // Let the last keyUp turn into beforeinput/input before the
696        // caller reads the page back.
697        let _ = run_loop_until(|| false, Duration::from_millis(150));
698        self.follow_new_window(page, false)
699    }
700
701    fn cursor_op(&mut self, page: PageHandle, op: CursorOp, mode: InputMode) -> EngineResult<()> {
702        self.forget_new_window(page)?;
703        let p = self.page_mut(page)?;
704        let dispatcher = super::wpe_input::dispatcher()?;
705        let humanize_mode = match mode {
706            InputMode::Human => vs_humanize::InputMode::Human,
707            InputMode::Careful => vs_humanize::InputMode::Careful,
708            InputMode::Robotic => vs_humanize::InputMode::Robotic,
709        };
710        // Screen origin of the hidden host window. v0.1.11 assumes
711        // (0, 0) — true under `xvfb` (CI) and any session without a
712        // window manager. With a WM, the WM may have translated the
713        // window elsewhere; a follow-up PR will query
714        // `GdkX11Surface::xid()` + `XTranslateCoordinates` to read the
715        // real origin. Until then, page-local CSS px == screen px,
716        // which is fine for CI and most headless setups.
717        let (origin_x, origin_y) = (0.0_f64, 0.0_f64);
718        let start = p.last_mouse.get();
719        let seed = humanize_seed(op);
720        let landed = match op {
721            CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } => cursor_move_along_path(
722                dispatcher,
723                start,
724                vs_humanize::Point { x, y },
725                (origin_x, origin_y),
726                humanize_mode,
727                seed,
728                false,
729            )?,
730            CursorOp::ClickAt { x, y } => {
731                let landed = cursor_move_along_path(
732                    dispatcher,
733                    start,
734                    vs_humanize::Point { x, y },
735                    (origin_x, origin_y),
736                    humanize_mode,
737                    seed,
738                    false,
739                )?;
740                cursor_press_release(dispatcher, landed, (origin_x, origin_y))?;
741                landed
742            }
743            CursorOp::Drag { x1, y1, x2, y2 } => {
744                let start_pt = vs_humanize::Point { x: x1, y: y1 };
745                let target = vs_humanize::Point { x: x2, y: y2 };
746                let pre = cursor_move_along_path(
747                    dispatcher,
748                    start,
749                    start_pt,
750                    (origin_x, origin_y),
751                    humanize_mode,
752                    seed,
753                    false,
754                )?;
755                dispatcher.dispatch(super::wpe_input::InputEvent::Press(
756                    super::wpe_input::Button::Left,
757                ))?;
758                std::thread::sleep(Duration::from_millis(15));
759                let landed = cursor_move_along_path(
760                    dispatcher,
761                    pre,
762                    target,
763                    (origin_x, origin_y),
764                    humanize_mode,
765                    seed,
766                    true,
767                )?;
768                dispatcher.dispatch(super::wpe_input::InputEvent::Release(
769                    super::wpe_input::Button::Left,
770                ))?;
771                dispatcher.flush()?;
772                // After the OS-level drag, fire the HTML5 DragEvent
773                // chain in JS so react-dnd / React-Flow HTML5 targets
774                // observe the drop.
775                let html5_js = super::common::build_html5_drag_js(x1, y1, x2, y2);
776                let web_view = p.web_view.clone();
777                let _ = eval_js_string(&web_view, &html5_js, Duration::from_secs(2));
778                landed
779            }
780        };
781        p.last_mouse.set(landed);
782        self.follow_new_window(page, matches!(op, CursorOp::ClickAt { .. }))
783    }
784
785    fn capabilities(&self) -> EngineCapabilities {
786        let any_inspector = self.pages.values().any(|p| p.inspector_installed);
787        EngineCapabilities {
788            renders: true,
789            honors_viewport: true,
790            measures_layout: true,
791            persists_auth: true,
792            inspector_console: any_inspector,
793            inspector_network: any_inspector,
794            inspector_cookie_events: true,
795            name: "wpe",
796            version: "Linux WebKitGTK 6 (webkit6)",
797        }
798    }
799}
800
801// =============================================================================
802// JS evaluation helper
803// =============================================================================
804
805// =============================================================================
806// Cursor primitive helpers (XTest / libei input dispatch)
807// =============================================================================
808
809/// Deterministic seed for the humanize Bezier path so the same
810/// `cursor_op` invocation produces the same trajectory on every run.
811fn humanize_seed(op: CursorOp) -> u64 {
812    // Hash the op's coordinates into a u64. Trivial mixer; replays
813    // need determinism, not cryptographic spread.
814    let (a, b, c, d) = match op {
815        CursorOp::MoveTo { x, y } | CursorOp::HoverAt { x, y } | CursorOp::ClickAt { x, y } => {
816            (x, y, 0.0, 0.0)
817        }
818        CursorOp::Drag { x1, y1, x2, y2 } => (x1, y1, x2, y2),
819    };
820    let bits = |v: f64| v.to_bits();
821    bits(a).wrapping_mul(0x9E37_79B9_7F4A_7C15)
822        ^ bits(b).wrapping_mul(0xBF58_476D_1CE4_E5B9)
823        ^ bits(c).wrapping_mul(0x94D0_49BB_1331_11EB)
824        ^ bits(d)
825}
826
827/// Walk a Bezier path from `start` to `end`, dispatching one `Move`
828/// per step at the path's prescribed timing. Returns the final point.
829/// The `button_down` flag is unused on Linux today (XTest doesn't
830/// distinguish drag-move from plain-move — both are `MotionNotify`
831/// events; the held button state is tracked at the X server). Kept
832/// in the signature so drag callers stay symmetric with the macOS
833/// `move_along_path`.
834fn cursor_move_along_path(
835    dispatcher: &dyn super::wpe_input::InputDispatcher,
836    start: vs_humanize::Point,
837    end: vs_humanize::Point,
838    origin: (f64, f64),
839    mode: vs_humanize::InputMode,
840    seed: u64,
841    _button_down: bool,
842) -> EngineResult<vs_humanize::Point> {
843    let path = vs_humanize::mouse_path(start, end, mode, seed);
844    let mut prev_ms: u128 = 0;
845    for step in &path {
846        if step.kind != vs_humanize::MouseStepKind::Move {
847            continue;
848        }
849        let screen = super::wpe_input::ScreenPoint {
850            #[allow(clippy::cast_possible_truncation)]
851            x: (origin.0 + step.point.x).round() as i32,
852            #[allow(clippy::cast_possible_truncation)]
853            y: (origin.1 + step.point.y).round() as i32,
854        };
855        dispatcher.dispatch(super::wpe_input::InputEvent::Move(screen))?;
856        let dt = step.at.as_millis().saturating_sub(prev_ms);
857        if dt > 0 {
858            std::thread::sleep(Duration::from_millis(u64::try_from(dt).unwrap_or(0)));
859        }
860        prev_ms = step.at.as_millis();
861    }
862    // Final settling move ending exactly at `end`.
863    let final_pt = super::wpe_input::ScreenPoint {
864        #[allow(clippy::cast_possible_truncation)]
865        x: (origin.0 + end.x).round() as i32,
866        #[allow(clippy::cast_possible_truncation)]
867        y: (origin.1 + end.y).round() as i32,
868    };
869    dispatcher.dispatch(super::wpe_input::InputEvent::Move(final_pt))?;
870    dispatcher.flush()?;
871    Ok(end)
872}
873
874/// Press-then-release left button at the current pointer position.
875/// Matches the `mouseDown` / 15 ms / `mouseUp` cadence the macOS
876/// backend uses so JS sees a coherent `click` event.
877fn cursor_press_release(
878    dispatcher: &dyn super::wpe_input::InputDispatcher,
879    _at: vs_humanize::Point,
880    _origin: (f64, f64),
881) -> EngineResult<()> {
882    dispatcher.dispatch(super::wpe_input::InputEvent::Press(
883        super::wpe_input::Button::Left,
884    ))?;
885    std::thread::sleep(Duration::from_millis(15));
886    dispatcher.dispatch(super::wpe_input::InputEvent::Release(
887        super::wpe_input::Button::Left,
888    ))?;
889    dispatcher.flush()?;
890    std::thread::sleep(Duration::from_millis(30));
891    Ok(())
892}
893
894fn eval_js_string(web_view: &WebView, js: &str, budget: Duration) -> EngineResult<String> {
895    let slot: Rc<RefCell<Option<Result<String, String>>>> = Rc::new(RefCell::new(None));
896    let slot_for_cb = slot.clone();
897
898    let cancellable = webkit6::gio::Cancellable::new();
899    web_view.evaluate_javascript(
900        js,
901        None,
902        None,
903        Some(&cancellable),
904        move |result| match result {
905            Ok(value) => {
906                let s = value.to_string();
907                *slot_for_cb.borrow_mut() = Some(Ok(s));
908            }
909            Err(err) => {
910                *slot_for_cb.borrow_mut() = Some(Err(err.to_string()));
911            }
912        },
913    );
914
915    let slot_check = slot.clone();
916    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
917    if !ok {
918        return Err(EngineError::Timeout {
919            budget,
920            primitive: "eval",
921            detail: "",
922        });
923    }
924    let result = slot.borrow_mut().take();
925    match result {
926        Some(Ok(s)) => Ok(s),
927        Some(Err(msg)) => Err(EngineError::Other(format!("eval failed: {msg}"))),
928        None => Err(EngineError::Other("eval completed without a result".into())),
929    }
930}
931
932// =============================================================================
933// Inspector capture wiring
934// =============================================================================
935
936/// Add the download-capture shim as a document-start script in every
937/// frame. WebKitGTK does emit a `download-started` signal, but the
938/// shim covers what that signal cannot see — an in-page `blob:` save
939/// whose object URL is revoked a tick later — and keeps the capture
940/// buffer identical across all three backends.
941fn install_download_shim(web_view: &WebView) {
942    let Some(manager) = web_view.user_content_manager() else {
943        return;
944    };
945    manager.add_script(&UserScript::new(
946        super::common::DOWNLOAD_SHIM_JS,
947        UserContentInjectedFrames::AllFrames,
948        UserScriptInjectionTime::Start,
949        &[],
950        &[],
951    ));
952}
953
954fn install_inspector(web_view: &WebView, slots: &super::inspector_bridge::InspectorSlots) -> bool {
955    use super::inspector_bridge::{
956        self, InspectorSlots, NetworkIngestSlot, CONSOLE_HANDLER, NETWORK_HANDLER,
957    };
958
959    if std::env::var_os("VS_DISABLE_INSPECTOR").is_some() {
960        return false;
961    }
962
963    let manager = web_view.user_content_manager().expect(
964        "WebKitGTK WebView is missing a UserContentManager — should not happen on a default WebView",
965    );
966
967    let script = UserScript::new(
968        inspector_bridge::SCRIPT,
969        UserContentInjectedFrames::AllFrames,
970        UserScriptInjectionTime::Start,
971        &[],
972        &[],
973    );
974    manager.add_script(&script);
975
976    if !manager.register_script_message_handler(CONSOLE_HANDLER, None) {
977        return false;
978    }
979    if !manager.register_script_message_handler(NETWORK_HANDLER, None) {
980        return false;
981    }
982
983    let console_slots: InspectorSlots = slots.clone();
984    manager.connect_script_message_received(Some(CONSOLE_HANDLER), move |_, value| {
985        let json = value.to_string();
986        let mut buf = console_slots.console.borrow_mut();
987        inspector_bridge::ingest_console(&mut buf, &json);
988    });
989    let network_slots: InspectorSlots = slots.clone();
990    manager.connect_script_message_received(Some(NETWORK_HANDLER), move |_, value| {
991        let json = value.to_string();
992        let mut entries = network_slots.network.borrow_mut();
993        let mut details = network_slots.details.borrow_mut();
994        let mut pending = network_slots.pending.borrow_mut();
995        inspector_bridge::ingest_network(
996            NetworkIngestSlot {
997                entries: &mut entries,
998                details: &mut details,
999                pending: &mut pending,
1000            },
1001            &json,
1002        );
1003    });
1004    true
1005}
1006
1007// =============================================================================
1008// Host-side cookie save/load via WebKitCookieManager
1009// =============================================================================
1010//
1011// Mirror of the macOS `webkit::cookie_store` module. `document.cookie`
1012// can't see or write `HttpOnly` cookies; `WebKitCookieManager` can.
1013// The v0.1.2 fix routes auth save/load through this path on every
1014// platform.
1015mod wpe_cookies {
1016    use std::cell::RefCell;
1017    use std::rc::Rc;
1018    use std::time::Duration;
1019
1020    use webkit6::gio;
1021    use webkit6::glib;
1022    use webkit6::prelude::*;
1023    use webkit6::soup;
1024    use webkit6::WebView;
1025
1026    use crate::backend::auth::CookieData;
1027    use crate::engine::{EngineError, EngineResult};
1028
1029    use super::run_loop_until;
1030
1031    const ASYNC_BUDGET: Duration = Duration::from_secs(5);
1032
1033    fn cookie_manager(web_view: &WebView) -> EngineResult<webkit6::CookieManager> {
1034        let session = WebViewExt::network_session(web_view).ok_or_else(|| {
1035            EngineError::Other("WebView has no NetworkSession; cookies unavailable".into())
1036        })?;
1037        session
1038            .cookie_manager()
1039            .ok_or_else(|| EngineError::Other("NetworkSession has no CookieManager".into()))
1040    }
1041
1042    pub(super) fn get_all_cookies(web_view: &WebView) -> EngineResult<Vec<CookieData>> {
1043        let manager = cookie_manager(web_view)?;
1044        let slot: Rc<RefCell<Option<Vec<CookieData>>>> = Rc::new(RefCell::new(None));
1045        let slot_cb = slot.clone();
1046        manager.all_cookies(None::<&gio::Cancellable>, move |result| {
1047            let cookies = match result {
1048                Ok(v) => v.into_iter().map(|mut c| serialize(&mut c)).collect(),
1049                Err(_) => Vec::new(),
1050            };
1051            *slot_cb.borrow_mut() = Some(cookies);
1052        });
1053        let check = slot.clone();
1054        let ok = run_loop_until(move || check.borrow().is_some(), ASYNC_BUDGET);
1055        if !ok {
1056            return Err(EngineError::Timeout {
1057                budget: ASYNC_BUDGET,
1058                primitive: "save_auth (all_cookies)",
1059                detail: "",
1060            });
1061        }
1062        let result = slot.borrow_mut().take().unwrap_or_default();
1063        Ok(result)
1064    }
1065
1066    pub(super) fn set_cookies(web_view: &WebView, cookies: &[CookieData]) -> EngineResult<()> {
1067        let manager = cookie_manager(web_view)?;
1068        for c in cookies {
1069            if c.name.is_empty() || c.domain.is_empty() {
1070                continue;
1071            }
1072            let path = if c.path.is_empty() {
1073                "/"
1074            } else {
1075                c.path.as_str()
1076            };
1077            // max_age=-1: session cookie (no expiration). We set
1078            // expires explicitly below if the saved blob carried it.
1079            let mut cookie = soup::Cookie::new(&c.name, &c.value, &c.domain, path, -1);
1080            cookie.set_secure(c.secure);
1081            cookie.set_http_only(c.http_only);
1082            if let Some(unix) = c.expires_unix {
1083                if let Ok(dt) = glib::DateTime::from_unix_utc(unix) {
1084                    cookie.set_expires(&dt);
1085                }
1086            }
1087            if let Some(ss) = c.same_site.as_deref() {
1088                let policy = match ss {
1089                    "Strict" => soup::SameSitePolicy::Strict,
1090                    "None" => soup::SameSitePolicy::None,
1091                    _ => soup::SameSitePolicy::Lax,
1092                };
1093                cookie.set_same_site_policy(policy);
1094            }
1095
1096            let done: Rc<RefCell<bool>> = Rc::new(RefCell::new(false));
1097            let done_cb = done.clone();
1098            manager.add_cookie(&cookie, None::<&gio::Cancellable>, move |_| {
1099                *done_cb.borrow_mut() = true;
1100            });
1101            let check = done.clone();
1102            let ok = run_loop_until(move || *check.borrow(), ASYNC_BUDGET);
1103            if !ok {
1104                return Err(EngineError::Timeout {
1105                    budget: ASYNC_BUDGET,
1106                    primitive: "load_auth (add_cookie)",
1107                    detail: "",
1108                });
1109            }
1110        }
1111        Ok(())
1112    }
1113
1114    fn serialize(c: &mut soup::Cookie) -> CookieData {
1115        CookieData {
1116            name: c.name().map(|s| s.to_string()).unwrap_or_default(),
1117            value: c.value().map(|s| s.to_string()).unwrap_or_default(),
1118            domain: c.domain().map(|s| s.to_string()).unwrap_or_default(),
1119            path: c.path().map(|s| s.to_string()).unwrap_or_default(),
1120            expires_unix: c.expires().map(|dt| dt.to_unix()),
1121            secure: c.is_secure(),
1122            http_only: c.is_http_only(),
1123            same_site: match c.same_site_policy() {
1124                soup::SameSitePolicy::Strict => Some("Strict".to_string()),
1125                soup::SameSitePolicy::None => Some("None".to_string()),
1126                soup::SameSitePolicy::Lax => Some("Lax".to_string()),
1127                _ => None,
1128            },
1129        }
1130    }
1131}
1132
1133/// A load that ended because its response became a download left the
1134/// page as it was and put the file in the download buffer. Not a
1135/// failure.
1136fn load_result(err: &glib::Error) -> Result<(), String> {
1137    if err.matches(webkit6::PolicyError::FrameLoadInterruptedByPolicyChange) {
1138        Ok(())
1139    } else {
1140        Err(err.message().to_string())
1141    }
1142}
1143
1144/// Save attachments instead of dropping them.
1145///
1146/// A `Content-Disposition: attachment` response (an export button, a
1147/// form POST answering with a file, a hidden-iframe download) never
1148/// reaches page script. Turn it into a WebKit download, write it to a
1149/// temp file, and move the bytes into `downloads` for `vs_download`.
1150/// The network session is shared by every page, so the
1151/// `download-started` handler checks the download belongs to this one.
1152fn install_download_capture(
1153    web_view: &WebView,
1154    downloads: &SharedDownloads,
1155) -> Option<(webkit6::NetworkSession, glib::SignalHandlerId)> {
1156    web_view.connect_decide_policy(|_view, decision, ty| {
1157        if ty != webkit6::PolicyDecisionType::Response {
1158            return false;
1159        }
1160        let Some(rd) = decision.downcast_ref::<webkit6::ResponsePolicyDecision>() else {
1161            return false;
1162        };
1163        let Some(resp) = rd.response() else {
1164            return false;
1165        };
1166        let uri = resp.uri().map(|u| u.to_string()).unwrap_or_default();
1167        if !(uri.starts_with("http:") || uri.starts_with("https:")) {
1168            return false;
1169        }
1170        let cd = resp
1171            .http_headers()
1172            .and_then(|h| h.one("Content-Disposition"))
1173            .map(|v| v.to_string())
1174            .unwrap_or_default();
1175        if is_attachment(&cd) || !rd.is_mime_type_supported() {
1176            decision.download();
1177            return true;
1178        }
1179        false
1180    });
1181
1182    let session = WebViewExt::network_session(web_view)?;
1183    let weak = web_view.downgrade();
1184    let downloads = downloads.clone();
1185    let id = session.connect_download_started(move |_session, download| {
1186        let Some(view) = weak.upgrade() else { return };
1187        if download.web_view().as_ref() != Some(&view) {
1188            return;
1189        }
1190        let resp = download.response();
1191        let url = resp
1192            .as_ref()
1193            .and_then(webkit6::URIResponse::uri)
1194            .or_else(|| download.request().and_then(|r| r.uri()))
1195            .map(|u| u.to_string())
1196            .unwrap_or_default();
1197        let mime = resp
1198            .as_ref()
1199            .and_then(webkit6::URIResponse::mime_type)
1200            .map(|m| m.to_string())
1201            .unwrap_or_default();
1202        let name = resp
1203            .as_ref()
1204            .and_then(webkit6::URIResponse::http_headers)
1205            .and_then(|h| h.one("Content-Disposition"))
1206            .and_then(|cd| name_from_disposition(&cd))
1207            .unwrap_or_default();
1208        let Ok(id) = downloads.lock().map(|mut d| d.begin(&url, &name, &mime)) else {
1209            return;
1210        };
1211        let path = temp_path(id);
1212        let _ = std::fs::remove_file(&path);
1213
1214        let dl = downloads.clone();
1215        download.connect_decide_destination(move |download, suggested| {
1216            if let Ok(mut d) = dl.lock() {
1217                if name.is_empty() {
1218                    d.set_name(id, suggested);
1219                }
1220            }
1221            let expected = download.response().map_or(0, |r| r.content_length());
1222            if expected > MAX_BYTES {
1223                if let Ok(mut d) = dl.lock() {
1224                    d.finish(
1225                        id,
1226                        Err(format!("download exceeds {MAX_BYTES} bytes ({expected})")),
1227                    );
1228                }
1229                download.cancel();
1230                return true;
1231            }
1232            download.set_destination(&path.to_string_lossy());
1233            true
1234        });
1235        let dl = downloads.clone();
1236        download.connect_failed(move |_download, err| {
1237            if let Ok(mut d) = dl.lock() {
1238                d.finish(id, Err(err.message().to_string()));
1239            }
1240            let _ = std::fs::remove_file(temp_path(id));
1241        });
1242        let dl = downloads.clone();
1243        download.connect_finished(move |_download| {
1244            let path = temp_path(id);
1245            // `failed` is followed by `finished`; the first result wins.
1246            let bytes = std::fs::read(&path).map_err(|e| format!("read {}: {e}", path.display()));
1247            let _ = std::fs::remove_file(&path);
1248            if let Ok(mut d) = dl.lock() {
1249                d.finish(id, bytes);
1250            }
1251        });
1252    });
1253    Some((session, id))
1254}
1255
1256/// Wait for the load already started on `web_view` to finish or fail.
1257fn wait_for_load(web_view: &WebView, primitive: &'static str) -> EngineResult<()> {
1258    let slot: Rc<RefCell<Option<Result<(), String>>>> = Rc::new(RefCell::new(None));
1259    let slot_for_signal = slot.clone();
1260    let signal_id = web_view.connect_load_changed(move |_view, event| {
1261        if event == LoadEvent::Finished {
1262            *slot_for_signal.borrow_mut() = Some(Ok(()));
1263        }
1264    });
1265    let slot_fail = slot.clone();
1266    let fail_id = web_view.connect_load_failed(move |_view, _event, _uri, err| {
1267        *slot_fail.borrow_mut() = Some(load_result(err));
1268        true
1269    });
1270
1271    let slot_check = slot.clone();
1272    let budget = super::common::nav_budget();
1273    let ok = run_loop_until(move || slot_check.borrow().is_some(), budget);
1274
1275    web_view.disconnect(signal_id);
1276    web_view.disconnect(fail_id);
1277
1278    if !ok {
1279        return Err(EngineError::Timeout {
1280            budget,
1281            primitive,
1282            detail: "",
1283        });
1284    }
1285    // Taken out of the RefCell before the match, not inside it:
1286    // as the function's tail expression the borrow guard would
1287    // otherwise outlive `slot` itself.
1288    let result = slot.borrow_mut().take();
1289    match result {
1290        Some(Ok(())) => Ok(()),
1291        Some(Err(msg)) => Err(EngineError::Other(format!("navigation failed: {msg}"))),
1292        None => Err(EngineError::Other(
1293            "navigation completed without a result".into(),
1294        )),
1295    }
1296}
1297
1298impl WpeBackend {
1299    /// Drop a new-window request parked before this input primitive
1300    /// started (a popup the page fired on its own), so the primitive
1301    /// only follows what it caused.
1302    fn forget_new_window(&mut self, page: PageHandle) -> EngineResult<()> {
1303        let _ = self.page_mut(page)?.new_window.borrow_mut().take();
1304        Ok(())
1305    }
1306
1307    /// Load a new-window navigation the last input primitive caused, in
1308    /// this page, and wait for it like `goto`. The `create` signal can
1309    /// arrive after the click returns, so after a click (`settle`) pump
1310    /// for up to `NEW_WINDOW_SETTLE` first. No parked request: no-op.
1311    fn follow_new_window(&mut self, page: PageHandle, settle: bool) -> EngineResult<()> {
1312        let p = self.page_mut(page)?;
1313        if settle && p.new_window.borrow().is_none() {
1314            let hint = eval_js_string(
1315                &p.web_view,
1316                super::common::NEW_WINDOW_HINT_JS,
1317                Duration::from_secs(2),
1318            );
1319            if super::common::new_window_hinted(&hint) {
1320                let parked = p.new_window.clone();
1321                let _ = run_loop_until(
1322                    move || parked.borrow().is_some(),
1323                    super::common::NEW_WINDOW_SETTLE,
1324                );
1325            }
1326        }
1327        let Some(request) = p.new_window.borrow_mut().take() else {
1328            return Ok(());
1329        };
1330        let web_view = p.web_view.clone();
1331        web_view.load_request(&request);
1332        wait_for_load(&web_view, "act")
1333    }
1334}