Skip to main content

servoshell/
running_app_state.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Shared state and methods for desktop and EGL implementations.
6
7use std::cell::{Cell, Ref, RefCell};
8use std::collections::HashMap;
9use std::rc::Rc;
10
11use crossbeam_channel::{Receiver, Sender, unbounded};
12use euclid::Rect;
13#[cfg(all(
14    feature = "gamepad",
15    not(any(target_os = "android", target_env = "ohos"))
16))]
17use gilrs::Event;
18use image::{DynamicImage, ImageFormat, RgbaImage};
19#[cfg(all(
20    any(coverage, llvm_pgo),
21    any(target_os = "android", target_env = "ohos")
22))]
23use libc::c_char;
24use log::{error, info, warn};
25#[cfg(all(
26    feature = "gamepad",
27    not(any(target_os = "android", target_env = "ohos"))
28))]
29use servo::GamepadIndex;
30use servo::{
31    AllowOrDenyRequest, AuthenticationRequest, BluetoothDeviceSelectionRequest, CSSPixel,
32    ConsoleLogLevel, CreateNewWebViewRequest, DeviceIntPoint, DeviceIntSize, EmbedderControl,
33    EmbedderControlId, EventLoopWaker, GenericSender, InputEvent, InputEventId, InputEventResult,
34    JSValue, LoadStatus, PermissionRequest, PrefValue, Preferences, ScreenshotCaptureError, Servo,
35    ServoDelegate, ServoError, UserContentManager, WebDriverCommandMsg, WebDriverJSResult,
36    WebDriverLoadStatus, WebDriverLoadStatusMessage, WebDriverScriptCommand, WebDriverSenders,
37    WebView, WebViewDelegate, WebViewId,
38};
39use url::Url;
40
41#[cfg(all(
42    feature = "gamepad",
43    not(any(target_os = "android", target_env = "ohos"))
44))]
45pub(crate) use crate::desktop::gamepad::ServoshellGamepadDelegate;
46use crate::prefs::{EXPERIMENTAL_PREFS, ServoShellPreferences};
47use crate::webdriver::WebDriverEmbedderControls;
48use crate::window::{
49    PlatformWindow, ServoShellWindow, ServoShellWindowId, TopLevelWebViewCreationRequest,
50};
51
52#[cfg(all(
53    any(coverage, llvm_pgo),
54    any(target_os = "android", target_env = "ohos")
55))]
56unsafe extern "C" {
57    fn __llvm_profile_set_filename(file: *const c_char);
58    fn __llvm_profile_write_file();
59}
60
61#[derive(Default)]
62pub struct WebViewCollection {
63    /// List of top-level browsing contexts.
64    /// Modified by EmbedderMsg::WebViewOpened and EmbedderMsg::WebViewClosed,
65    /// and we exit if it ever becomes empty.
66    webviews: HashMap<WebViewId, WebView>,
67
68    /// The order in which the webviews were created.
69    pub(crate) creation_order: Vec<WebViewId>,
70
71    /// The [`WebView`] that is currently active. This is the [`WebView`] that is shown and has
72    /// input focus.
73    active_webview_id: Option<WebViewId>,
74
75    /// Whether or not the active WebView in this collection has system focus.
76    has_system_focus: bool,
77}
78
79impl WebViewCollection {
80    pub fn add(&mut self, webview: WebView) {
81        let id = webview.id();
82        self.creation_order.push(id);
83        self.webviews.insert(id, webview);
84    }
85
86    /// Removes a webview from the collection by [`WebViewId`]. If the removed [`WebView`] was the active
87    /// [`WebView`] then the next newest [`WebView`] will be activated.
88    pub fn remove(&mut self, id: WebViewId) -> Option<WebView> {
89        self.creation_order.retain(|&webview_id| webview_id != id);
90        let removed_webview = self.webviews.remove(&id);
91
92        if self.active_webview_id == Some(id) {
93            self.active_webview_id = None;
94            if let Some(newest) = self.creation_order.last() {
95                self.activate_webview(*newest);
96            }
97        }
98
99        removed_webview
100    }
101
102    pub fn get(&self, id: WebViewId) -> Option<&WebView> {
103        self.webviews.get(&id)
104    }
105
106    pub fn active(&self) -> Option<&WebView> {
107        self.active_webview_id.and_then(|id| self.webviews.get(&id))
108    }
109
110    pub fn active_id(&self) -> Option<WebViewId> {
111        self.active_webview_id
112    }
113
114    /// Gets a reference to the most recently created webview, if any.
115    pub fn newest(&self) -> Option<&WebView> {
116        self.creation_order
117            .last()
118            .and_then(|id| self.webviews.get(id))
119    }
120
121    pub fn all_in_creation_order(&self) -> impl Iterator<Item = (WebViewId, &WebView)> {
122        self.creation_order
123            .iter()
124            .filter_map(move |id| self.webviews.get(id).map(|webview| (*id, webview)))
125    }
126
127    /// Returns an iterator over all webview references (in arbitrary order).
128    pub fn values(&self) -> impl Iterator<Item = &WebView> {
129        self.webviews.values()
130    }
131
132    /// Returns true if the collection contains no webviews.
133    pub fn is_empty(&self) -> bool {
134        self.webviews.is_empty()
135    }
136
137    pub(crate) fn activate_webview(&mut self, id_to_activate: WebViewId) {
138        assert!(self.creation_order.contains(&id_to_activate));
139
140        self.active_webview_id = Some(id_to_activate);
141        for (webview_id, webview) in self.all_in_creation_order() {
142            if id_to_activate == webview_id {
143                if self.has_system_focus {
144                    webview.set_focused(true);
145                }
146                webview.show();
147            } else {
148                if self.has_system_focus {
149                    webview.set_focused(false);
150                }
151                webview.hide();
152            }
153        }
154    }
155
156    pub(crate) fn activate_webview_by_index(&mut self, index: usize) {
157        let Some(webview_id) = self.creation_order.get(index) else {
158            // Just ignore requests to activate unknown WebViews. This can happen by pressing
159            // keyboard shortcuts in the interface.
160            return;
161        };
162        self.activate_webview(*webview_id);
163    }
164
165    pub(crate) fn set_focused(&mut self, focused: bool) {
166        self.has_system_focus = focused;
167        if let Some(active) = self.active() {
168            active.set_focused(focused);
169        }
170    }
171}
172
173/// A command received via the user interacting with the user interface.
174#[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
175pub(crate) enum UserInterfaceCommand {
176    Go(String),
177    Back,
178    Forward,
179    Reload,
180    ReloadAll,
181    NewWebView,
182    CloseWebView(WebViewId),
183    NewWindow(TopLevelWebViewCreationRequest),
184}
185
186pub(crate) struct RunningAppState {
187    /// The gamepad provider, used for handling gamepad events and set on each WebView.
188    /// May be `None` if gamepad support is disabled or failed to initialize.
189    #[cfg(all(
190        feature = "gamepad",
191        not(any(target_os = "android", target_env = "ohos"))
192    ))]
193    gamepad_delegate: Option<Rc<ServoshellGamepadDelegate>>,
194
195    /// The [`WebDriverSenders`] used to reply to pending WebDriver requests.
196    pub(crate) webdriver_senders: RefCell<WebDriverSenders>,
197
198    /// When running in WebDriver mode, [`WebDriverEmbedderControls`] is a virtual container
199    /// for all embedder controls. This overrides the normal behavior where these controls
200    /// are shown in the GUI or not processed at all in headless mode.
201    pub(crate) webdriver_embedder_controls: WebDriverEmbedderControls,
202
203    /// A [`HashMap`] of pending WebDriver events. It is the WebDriver embedder's responsibility
204    /// to inform the WebDriver server when the event has been fully handled. This map is used
205    /// to report back to WebDriver when that happens.
206    pub(crate) pending_webdriver_events: RefCell<HashMap<InputEventId, (WebViewId, Sender<()>)>>,
207
208    /// A [`Receiver`] for receiving commands from a running WebDriver server, if WebDriver
209    /// was enabled.
210    pub(crate) webdriver_receiver: Option<Receiver<WebDriverCommandMsg>>,
211
212    /// servoshell specific preferences created during startup of the application.
213    pub(crate) servoshell_preferences: ServoShellPreferences,
214
215    /// A handle to the Servo instance.
216    pub(crate) servo: Servo,
217
218    /// Whether or not the application has achieved stable image output. This is used
219    /// for the `exit_after_stable_image` option.
220    pub(crate) achieved_stable_image: Rc<Cell<bool>>,
221
222    /// The [`UserContentManager`] for all `WebView`s created.
223    pub(crate) user_content_manager: Rc<UserContentManager>,
224
225    /// Whether or not program exit has been triggered. This means that all windows
226    /// will be destroyed and shutdown will start at the end of the current event loop.
227    exit_scheduled: Cell<bool>,
228
229    /// Whether the user has enabled experimental preferences.
230    experimental_preferences_enabled: Cell<bool>,
231
232    /// The set of [`ServoShellWindow`]s that currently exist for this instance of servoshell.
233    ///
234    /// These are stored in creation order to ensure consistent focus behavior.
235    // This is the last field of the struct to ensure that windows are dropped *after* all
236    // other references to the relevant rendering contexts have been destroyed.
237    // See https://github.com/servo/servo/issues/36711.
238    windows: RefCell<Vec<Rc<ServoShellWindow>>>,
239
240    /// The currently focused [`ServoShellWindow`], if one is focused.
241    focused_window: RefCell<Option<Rc<ServoShellWindow>>>,
242
243    /// Whether accessibility is active in servoshell.
244    ///
245    /// Set by the platform via AccessKit, and forwarded to existing and new WebViews via
246    /// [`WebView::set_accessibility_active()`], in [`Self::set_accessibility_active()`] and
247    /// and [`ServoShellWindow::create_toplevel_webview()`].
248    accessibility_active: Cell<bool>,
249}
250
251impl RunningAppState {
252    pub(crate) fn new(
253        servo: Servo,
254        servoshell_preferences: ServoShellPreferences,
255        event_loop_waker: Box<dyn EventLoopWaker>,
256        user_content_manager: Rc<UserContentManager>,
257        default_preferences: Preferences,
258        #[cfg(all(
259            feature = "gamepad",
260            not(any(target_os = "android", target_env = "ohos"))
261        ))]
262        gamepad_delegate: Option<Rc<ServoshellGamepadDelegate>>,
263    ) -> Self {
264        servo.set_delegate(Rc::new(ServoShellServoDelegate));
265
266        let webdriver_receiver = servoshell_preferences.webdriver_port.get().map(|port| {
267            let (embedder_sender, embedder_receiver) = unbounded();
268            webdriver_server::start_server(
269                port,
270                embedder_sender,
271                event_loop_waker,
272                default_preferences,
273            );
274            embedder_receiver
275        });
276
277        let experimental_preferences_enabled =
278            Cell::new(servoshell_preferences.experimental_preferences_enabled);
279
280        Self {
281            windows: Default::default(),
282            focused_window: Default::default(),
283            #[cfg(all(
284                feature = "gamepad",
285                not(any(target_os = "android", target_env = "ohos"))
286            ))]
287            gamepad_delegate,
288            webdriver_senders: RefCell::default(),
289            webdriver_embedder_controls: Default::default(),
290            pending_webdriver_events: Default::default(),
291            webdriver_receiver,
292            servoshell_preferences,
293            servo,
294            achieved_stable_image: Default::default(),
295            exit_scheduled: Default::default(),
296            user_content_manager,
297            experimental_preferences_enabled,
298            accessibility_active: Cell::new(false),
299        }
300    }
301
302    pub(crate) fn open_window(
303        self: &Rc<Self>,
304        platform_window: Rc<dyn PlatformWindow>,
305        creation_request: TopLevelWebViewCreationRequest,
306    ) -> Rc<ServoShellWindow> {
307        let window = Rc::new(ServoShellWindow::new(platform_window.clone()));
308        self.windows.borrow_mut().push(window.clone());
309        window.create_and_activate_toplevel_webview(self.clone(), creation_request);
310
311        // If the window already has platform focus, mark it as focused in our application state.
312        if platform_window.has_platform_focus() {
313            self.set_window_has_focus(window.clone(), true);
314        }
315
316        window
317    }
318
319    pub(crate) fn windows<'a>(&'a self) -> Ref<'a, Vec<Rc<ServoShellWindow>>> {
320        self.windows.borrow()
321    }
322
323    pub(crate) fn focused_window(&self) -> Option<Rc<ServoShellWindow>> {
324        self.focused_window.borrow().clone()
325    }
326
327    pub(crate) fn set_window_has_focus(&self, window: Rc<ServoShellWindow>, has_focus: bool) {
328        let mut focused_window = self.focused_window.borrow_mut();
329
330        // If another window had focus before and this new window is gaining it, then
331        // ensure that the old window is explicitly unfocused.
332        if let Some(previously_focused_window) = &*focused_window &&
333            !Rc::ptr_eq(previously_focused_window, &window) &&
334            has_focus
335        {
336            previously_focused_window
337                .webview_collection_mut()
338                .set_focused(false);
339        }
340
341        window.webview_collection_mut().set_focused(has_focus);
342
343        if let Some(previously_focused_window) = &*focused_window &&
344            Rc::ptr_eq(previously_focused_window, &window) &&
345            !has_focus
346        {
347            *focused_window = None;
348        } else if has_focus {
349            *focused_window = Some(window);
350        }
351    }
352
353    pub(crate) fn window(&self, id: ServoShellWindowId) -> Option<Rc<ServoShellWindow>> {
354        self.windows
355            .borrow()
356            .iter()
357            .find(|window| window.id() == id)
358            .cloned()
359    }
360
361    pub(crate) fn webview_by_id(&self, webview_id: WebViewId) -> Option<WebView> {
362        self.windows()
363            .iter()
364            .find_map(|window| window.webview_by_id(webview_id))
365    }
366
367    pub(crate) fn webdriver_receiver(&self) -> Option<&Receiver<WebDriverCommandMsg>> {
368        self.webdriver_receiver.as_ref()
369    }
370
371    pub(crate) fn servo(&self) -> &Servo {
372        &self.servo
373    }
374
375    #[cfg(all(
376        feature = "gamepad",
377        not(any(target_os = "android", target_env = "ohos"))
378    ))]
379    pub(crate) fn gamepad_delegate(&self) -> Option<Rc<ServoshellGamepadDelegate>> {
380        self.gamepad_delegate.clone()
381    }
382
383    pub(crate) fn schedule_exit(&self) {
384        // When explicitly required to shutdown, unset webdriver port
385        // which allows normal shutdown.
386        // Note that when not explicitly required to shutdown, we still keep Servo alive
387        // when all tabs are closed when `webdriver_port` enabled, which is necessary
388        // to run wpt test using servodriver.
389        self.servoshell_preferences.webdriver_port.set(None);
390        self.exit_scheduled.set(true);
391
392        #[cfg(all(
393            any(coverage, llvm_pgo),
394            any(target_os = "android", target_env = "ohos")
395        ))]
396        {
397            use std::ffi::CString;
398
399            use crate::prefs::default_config_dir;
400
401            let mut profile_path = default_config_dir().expect("Need a config dir");
402            profile_path.push("profiles/");
403            let filename = format!(
404                "{}/profile-%h-%p.profraw",
405                profile_path.to_str().expect("Should be unicode")
406            );
407            let c_filename = CString::new(filename).expect("Need a valid cstring");
408            unsafe {
409                __llvm_profile_set_filename(c_filename.as_ptr() as *const c_char);
410                __llvm_profile_write_file()
411            }
412        }
413    }
414
415    #[cfg_attr(any(target_os = "android", target_env = "ohos"), expect(dead_code))]
416    pub(crate) fn experimental_preferences_enabled(&self) -> bool {
417        self.experimental_preferences_enabled.get()
418    }
419
420    #[cfg_attr(target_env = "ohos", expect(dead_code))]
421    pub(crate) fn set_experimental_preferences_enabled(&self, new_value: bool) {
422        let old_value = self.experimental_preferences_enabled.replace(new_value);
423        if old_value == new_value {
424            return;
425        }
426        for pref in EXPERIMENTAL_PREFS {
427            self.servo.set_preference(pref, PrefValue::Bool(new_value));
428        }
429    }
430
431    /// Close any [`ServoShellWindow`] that doesn't have an open [`WebView`].
432    fn close_empty_windows(&self) {
433        let mut move_focus = false;
434        self.windows.borrow_mut().retain(|window| {
435            if !self.exit_scheduled.get() && !window.should_close() {
436                return true;
437            }
438
439            if let Some(focused_window) = self.focused_window() &&
440                Rc::ptr_eq(window, &focused_window)
441            {
442                *self.focused_window.borrow_mut() = None;
443                move_focus = !focused_window.platform_window().platform_manages_focus();
444            }
445            false
446        });
447
448        // If the platform doesn't manage focus, then focus the most recently opened
449        // window.
450        if move_focus &&
451            let Some(newly_focused_window) = self
452                .windows()
453                .iter()
454                .rev()
455                .find(|window| !window.platform_window().platform_manages_focus())
456                .cloned()
457        {
458            self.set_window_has_focus(newly_focused_window, true);
459        }
460    }
461
462    /// Spins the internal application event loop.
463    ///
464    /// - Notifies Servo about incoming gamepad events
465    /// - Spin the Servo event loop, which will update Servo's embedding layer and trigger
466    ///   delegate methods.
467    ///
468    /// Returns true if the event loop should continue spinning and false if it should exit.
469    pub(crate) fn spin_event_loop(
470        self: &Rc<Self>,
471        create_platform_window: Option<&dyn Fn(Url) -> Rc<dyn PlatformWindow>>,
472    ) -> bool {
473        self.handle_webdriver_messages(create_platform_window);
474
475        self.servo.spin_event_loop();
476
477        for window in self.windows.borrow().iter() {
478            window.update_and_request_repaint_if_necessary(self);
479        }
480
481        // We clone here to avoid a double borrow. User interface commands can update the list of windows.
482        let windows: Vec<_> = self.windows.borrow().iter().cloned().collect();
483        for window in windows {
484            window.handle_interface_commands(self, create_platform_window);
485        }
486
487        if self.servoshell_preferences.exit_after_stable_image && self.achieved_stable_image.get() {
488            self.schedule_exit();
489        }
490
491        self.close_empty_windows();
492
493        // When no more windows are open, exit the application. Do not do this when
494        // running WebDriver, which expects to keep running with no WebView open.
495        if self.servoshell_preferences.webdriver_port.get().is_none() &&
496            self.windows.borrow().is_empty()
497        {
498            self.schedule_exit()
499        }
500
501        !self.exit_scheduled.get()
502    }
503
504    fn maybe_window_for_webview(&self, webview: &WebView) -> Option<Rc<ServoShellWindow>> {
505        // Look up the ServoShellWindow by RenderingContext. This method can be called while a
506        // WebView is being constructed, which means that it may not fully be associated with a
507        // ServoShellWindow yet.
508        let rendering_context = webview.rendering_context();
509        self.windows()
510            .iter()
511            .find(|window| {
512                Rc::ptr_eq(
513                    &window.platform_window().rendering_context(),
514                    &rendering_context,
515                )
516            })
517            .cloned()
518    }
519
520    pub(crate) fn window_for_webview(&self, webview: &WebView) -> Rc<ServoShellWindow> {
521        self.maybe_window_for_webview(webview)
522            .unwrap_or_else(|| panic!("Looking for unexpected WebView: {:?}", webview.id()))
523    }
524
525    pub(crate) fn platform_window_for_webview(&self, webview: &WebView) -> Rc<dyn PlatformWindow> {
526        self.window_for_webview(webview).platform_window()
527    }
528
529    /// If we are exiting after achieving a stable image or we want to save the display of the
530    /// [`WebView`] to an image file, request a screenshot of the [`WebView`].
531    fn maybe_request_screenshot(&self, webview: WebView) {
532        let output_path = self.servoshell_preferences.output_image_path.clone();
533        if !self.servoshell_preferences.exit_after_stable_image && output_path.is_none() {
534            return;
535        }
536
537        // Never request more than a single screenshot for now.
538        let achieved_stable_image = self.achieved_stable_image.clone();
539        if achieved_stable_image.get() {
540            return;
541        }
542
543        webview.take_screenshot(None, move |image| {
544            achieved_stable_image.set(true);
545
546            let Some(output_path) = output_path else {
547                return;
548            };
549
550            let image = match image {
551                Ok(image) => image,
552                Err(error) => {
553                    error!("Could not take screenshot: {error:?}");
554                    return;
555                },
556            };
557
558            let image_format = ImageFormat::from_path(&output_path).unwrap_or(ImageFormat::Png);
559            if let Err(error) =
560                DynamicImage::ImageRgba8(image).save_with_format(output_path, image_format)
561            {
562                error!("Failed to save screenshot: {error}.");
563            }
564        });
565    }
566
567    pub(crate) fn set_load_status_sender(
568        &self,
569        webview_id: WebViewId,
570        sender: GenericSender<WebDriverLoadStatusMessage>,
571    ) {
572        self.webdriver_senders
573            .borrow_mut()
574            .load_status_senders
575            .insert(webview_id, sender);
576    }
577
578    pub(crate) fn remove_load_status_sender(&self, webview_id: WebViewId) {
579        self.webdriver_senders
580            .borrow_mut()
581            .load_status_senders
582            .remove(&webview_id);
583    }
584
585    fn set_script_command_interrupt_sender(
586        &self,
587        sender: Option<GenericSender<WebDriverJSResult>>,
588    ) {
589        self.webdriver_senders
590            .borrow_mut()
591            .script_evaluation_interrupt_sender = sender;
592    }
593
594    pub(crate) fn handle_webdriver_input_event(
595        &self,
596        webview_id: WebViewId,
597        input_event: InputEvent,
598        response_sender: Option<Sender<()>>,
599    ) {
600        if let Some(webview) = self.webview_by_id(webview_id) {
601            let event_id = webview.notify_input_event(input_event);
602            if let Some(response_sender) = response_sender {
603                self.pending_webdriver_events
604                    .borrow_mut()
605                    .insert(event_id, (webview_id, response_sender));
606            }
607        } else {
608            error!("Could not find WebView ({webview_id:?}) for WebDriver event: {input_event:?}");
609        };
610    }
611
612    pub(crate) fn handle_webdriver_screenshot(
613        &self,
614        webview_id: WebViewId,
615        rect: Option<Rect<f32, CSSPixel>>,
616        result_sender: Sender<Result<RgbaImage, ScreenshotCaptureError>>,
617    ) {
618        if let Some(webview) = self.webview_by_id(webview_id) {
619            let rect = rect.map(|rect| rect.to_box2d().into());
620            webview.take_screenshot(rect, move |result| {
621                if let Err(error) = result_sender.send(result) {
622                    warn!("Failed to send response to TakeScreenshot: {error}");
623                }
624            });
625        } else if let Err(error) =
626            result_sender.send(Err(ScreenshotCaptureError::WebViewDoesNotExist))
627        {
628            error!("Failed to send response to TakeScreenshot: {error}");
629        }
630    }
631
632    pub(crate) fn handle_webdriver_script_command(&self, script_command: &WebDriverScriptCommand) {
633        match script_command {
634            WebDriverScriptCommand::ExecuteScriptWithCallback(_webview_id, response_sender) => {
635                // Give embedder a chance to interrupt the script command.
636                // Webdriver only handles 1 script command at a time, so we can
637                // safely set a new interrupt sender and remove the previous one here.
638                self.set_script_command_interrupt_sender(Some(response_sender.clone()));
639            },
640            _ => {
641                self.set_script_command_interrupt_sender(None);
642            },
643        }
644    }
645
646    pub(crate) fn handle_webdriver_load_url(&self, webview_id: WebViewId, url: Url) {
647        let Some(webview) = self.webview_by_id(webview_id) else {
648            return;
649        };
650
651        self.platform_window_for_webview(&webview)
652            .dismiss_embedder_controls_for_webview(webview_id);
653
654        info!("Loading URL in webview {}: {}", webview_id, url);
655        webview.load(url);
656    }
657
658    #[cfg(all(
659        feature = "gamepad",
660        not(any(target_os = "android", target_env = "ohos"))
661    ))]
662    pub(crate) fn handle_gamepad_events(
663        &self,
664        event: Event,
665        gamepad_name: String,
666        gamepad_index: GamepadIndex,
667    ) {
668        let Some(gamepad_delegate) = self.gamepad_delegate.as_ref() else {
669            return;
670        };
671        let Some(active_webview) = self
672            .focused_window()
673            .and_then(|window| window.active_webview())
674        else {
675            return;
676        };
677        gamepad_delegate.handle_gamepad_events(event, gamepad_name, gamepad_index, active_webview);
678    }
679
680    /// Interrupt any ongoing WebDriver-based script evaluation.
681    ///
682    /// From <https://w3c.github.io/webdriver/#dfn-execute-a-function-body>:
683    /// > The rules to execute a function body are as follows. The algorithm returns
684    /// > an ECMAScript completion record.
685    /// >
686    /// > If at any point during the algorithm a user prompt appears, immediately return
687    /// > Completion { Type: normal, Value: null, Target: empty }, but continue to run the
688    /// >  other steps of this algorithm in parallel.
689    fn interrupt_webdriver_script_evaluation(&self) {
690        if let Some(sender) = &self
691            .webdriver_senders
692            .borrow()
693            .script_evaluation_interrupt_sender
694        {
695            sender.send(Ok(JSValue::Null)).unwrap_or_else(|err| {
696                info!(
697                    "Notify dialog appear failed. Maybe the channel to webdriver is closed: {err}"
698                );
699            });
700        }
701    }
702
703    #[cfg(not(any(target_os = "android", target_env = "ohos")))]
704    pub(crate) fn set_accessibility_active(&self, active: bool) {
705        let was_active = self.accessibility_active.replace(active);
706        if active == was_active {
707            return;
708        }
709
710        for window in self.windows().iter() {
711            window.set_accessibility_active(active);
712        }
713    }
714
715    pub(crate) fn accessibility_active(&self) -> bool {
716        self.accessibility_active.get()
717    }
718}
719
720impl WebViewDelegate for RunningAppState {
721    fn screen_geometry(&self, webview: WebView) -> Option<servo::ScreenGeometry> {
722        Some(self.platform_window_for_webview(&webview).screen_geometry())
723    }
724
725    fn notify_status_text_changed(&self, webview: WebView, _status: Option<String>) {
726        self.window_for_webview(&webview).set_needs_update();
727    }
728
729    fn notify_history_changed(&self, webview: WebView, _entries: Vec<Url>, _current: usize) {
730        self.window_for_webview(&webview).set_needs_update();
731    }
732
733    fn notify_page_title_changed(&self, webview: WebView, _: Option<String>) {
734        self.window_for_webview(&webview).set_needs_update();
735    }
736
737    fn request_move_to(&self, webview: WebView, new_position: DeviceIntPoint) {
738        self.platform_window_for_webview(&webview)
739            .set_position(new_position);
740    }
741
742    fn request_resize_to(&self, webview: WebView, requested_outer_size: DeviceIntSize) {
743        self.platform_window_for_webview(&webview)
744            .request_resize(&webview, requested_outer_size);
745    }
746
747    fn request_authentication(
748        &self,
749        webview: WebView,
750        authentication_request: AuthenticationRequest,
751    ) {
752        self.platform_window_for_webview(&webview)
753            .show_http_authentication_dialog(webview.id(), authentication_request);
754    }
755
756    fn request_create_new(&self, parent_webview: WebView, request: CreateNewWebViewRequest) {
757        let window = self.window_for_webview(&parent_webview);
758
759        // When WebDriver wants to open a new WebView, do this in a new window. Normally, servoshell
760        // throttles WebViews that are hidden, but WebDriver expects all opened WebViews to stay
761        // active. Using a separate window ensures this.
762        if self.servoshell_preferences.webdriver_port.get().is_some() {
763            window.queue_user_interface_command(UserInterfaceCommand::NewWindow(
764                TopLevelWebViewCreationRequest::WithCreateRequest(request),
765            ));
766            return;
767        }
768
769        let platform_window = window.platform_window();
770        let webview = request
771            .builder(platform_window.rendering_context())
772            .hidpi_scale_factor(platform_window.hidpi_scale_factor())
773            .delegate(parent_webview.delegate())
774            .build();
775
776        window.add_webview(webview.clone());
777        window.activate_webview(webview.id());
778    }
779
780    fn notify_closed(&self, webview: WebView) {
781        let webview_id = webview.id();
782        self.pending_webdriver_events
783            .borrow_mut()
784            .retain(|_, (pending_webview_id, _)| *pending_webview_id != webview_id);
785        self.window_for_webview(&webview).close_webview(webview_id)
786    }
787
788    fn notify_input_event_handled(
789        &self,
790        webview: WebView,
791        id: InputEventId,
792        result: InputEventResult,
793    ) {
794        self.platform_window_for_webview(&webview)
795            .notify_input_event_handled(&webview, id, result);
796
797        self.pending_webdriver_events.borrow_mut().remove(&id);
798    }
799
800    fn notify_cursor_changed(&self, webview: WebView, cursor: servo::Cursor) {
801        self.platform_window_for_webview(&webview)
802            .set_cursor(cursor);
803    }
804
805    fn notify_load_status_changed(&self, webview: WebView, status: LoadStatus) {
806        self.window_for_webview(&webview).set_needs_update();
807
808        if matches!(status, LoadStatus::Complete | LoadStatus::Stopped) {
809            self.maybe_request_screenshot(webview);
810        }
811    }
812
813    fn notify_fullscreen_state_changed(&self, webview: WebView, fullscreen_state: bool) {
814        self.platform_window_for_webview(&webview)
815            .set_fullscreen(fullscreen_state);
816    }
817
818    fn show_bluetooth_device_dialog(
819        &self,
820        webview: WebView,
821        request: BluetoothDeviceSelectionRequest,
822    ) {
823        self.platform_window_for_webview(&webview)
824            .show_bluetooth_device_dialog(webview.id(), request);
825    }
826
827    fn request_permission(&self, webview: WebView, permission_request: PermissionRequest) {
828        self.platform_window_for_webview(&webview)
829            .show_permission_dialog(webview.id(), permission_request);
830    }
831
832    fn notify_new_frame_ready(&self, webview: WebView) {
833        self.window_for_webview(&webview).set_needs_repaint();
834    }
835
836    fn show_embedder_control(&self, webview: WebView, embedder_control: EmbedderControl) {
837        if self.servoshell_preferences.webdriver_port.get().is_some() {
838            if matches!(&embedder_control, EmbedderControl::SimpleDialog(..)) {
839                self.interrupt_webdriver_script_evaluation();
840
841                // Dialogs block the page load, so need need to notify WebDriver
842                if let Some(sender) = self
843                    .webdriver_senders
844                    .borrow_mut()
845                    .load_status_senders
846                    .get(&webview.id())
847                {
848                    let _ = sender.send(WebDriverLoadStatusMessage {
849                        webview_id: webview.id(),
850                        status: WebDriverLoadStatus::Blocked,
851                    });
852                };
853            }
854
855            self.webdriver_embedder_controls
856                .show_embedder_control(webview.id(), embedder_control);
857            return;
858        }
859
860        self.window_for_webview(&webview)
861            .show_embedder_control(webview, embedder_control);
862    }
863
864    fn hide_embedder_control(&self, webview: WebView, embedder_control_id: EmbedderControlId) {
865        if self.servoshell_preferences.webdriver_port.get().is_some() {
866            self.webdriver_embedder_controls
867                .hide_embedder_control(webview.id(), embedder_control_id);
868            return;
869        }
870
871        self.window_for_webview(&webview)
872            .hide_embedder_control(webview, embedder_control_id);
873    }
874
875    fn notify_favicon_changed(&self, webview: WebView) {
876        self.window_for_webview(&webview)
877            .notify_favicon_changed(webview);
878    }
879
880    fn notify_crashed(&self, webview: WebView, reason: String, backtrace: Option<String>) {
881        self.platform_window_for_webview(&webview)
882            .notify_crashed(webview, reason, backtrace);
883    }
884
885    fn show_console_message(&self, webview: WebView, level: ConsoleLogLevel, message: String) {
886        self.platform_window_for_webview(&webview)
887            .show_console_message(level, &message);
888    }
889
890    fn notify_accessibility_tree_update(
891        &self,
892        webview: WebView,
893        tree_update: accesskit::TreeUpdate,
894    ) {
895        self.platform_window_for_webview(&webview)
896            .notify_accessibility_tree_update(webview, tree_update);
897    }
898}
899
900struct ServoShellServoDelegate;
901impl ServoDelegate for ServoShellServoDelegate {
902    fn notify_devtools_server_started(&self, port: u16, _token: String) {
903        info!("Devtools Server running on port {port}");
904    }
905
906    fn request_devtools_connection(&self, request: AllowOrDenyRequest) {
907        request.allow();
908    }
909
910    fn notify_error(&self, error: ServoError) {
911        error!("Saw Servo error: {error:?}!");
912    }
913
914    fn show_console_message(&self, level: ConsoleLogLevel, message: String) {
915        // For messages without a WebView context, apply platform-specific behavior
916        #[cfg(not(any(target_os = "android", target_env = "ohos")))]
917        println!("{message}");
918        log::log!(level.into(), "{message}");
919    }
920}