Skip to main content

servo/
servo.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
5use std::cell::{Cell, Ref, RefCell, RefMut};
6use std::cmp::max;
7use std::rc::{Rc, Weak};
8use std::sync::Arc;
9use std::time::Duration;
10
11use accesskit::ActionRequest;
12use crossbeam_channel::{Receiver, Sender, unbounded};
13pub use embedder_traits::*;
14use env_logger::Builder as EnvLoggerBuilder;
15use fonts::{SystemFontService, SystemFontServiceProxy};
16#[cfg(all(
17    feature = "multiprocess",
18    not(target_os = "windows"),
19    not(target_os = "ios"),
20    not(target_os = "android"),
21    not(target_arch = "arm"),
22    not(target_arch = "aarch64"),
23    not(target_arch = "riscv32"),
24    not(target_arch = "riscv64"),
25    not(target_env = "ohos"),
26))]
27use gaol::sandbox::{ChildSandbox, ChildSandboxMethods};
28#[cfg(feature = "multiprocess")]
29use ipc_channel::ipc::{self, IpcSender};
30use layout::LayoutFactoryImpl;
31#[cfg(feature = "multiprocess")]
32use layout_api::ScriptThreadFactory;
33use log::{Log, Metadata, Record, debug, warn};
34use media::{GlApi, NativeDisplay, WindowGLContext};
35use net::embedder::NetToEmbedderMsg;
36#[cfg(feature = "multiprocess")]
37use net::image_cache::ImageCacheFactoryImpl;
38use net::protocols::ProtocolRegistry;
39use net::resource_thread::new_resource_threads;
40#[cfg(feature = "multiprocess")]
41use net_traits::FetchThread;
42use net_traits::ResourceThreads;
43use paint::{InitialPaintState, Paint};
44pub use paint_api::rendering_context::RenderingContext;
45use paint_api::{CrossProcessPaintApi, PaintMessage, PaintProxy};
46use profile::{mem as profile_mem, time as profile_time};
47use profile_traits::mem::MemoryReportResult;
48#[cfg(feature = "multiprocess")]
49use profile_traits::mem::{ProfilerMsg, Reporter};
50use profile_traits::{mem, time};
51use rustc_hash::FxHashMap;
52use script::JSEngineSetup;
53#[cfg(feature = "multiprocess")]
54use script::ServiceWorkerManager;
55#[cfg(feature = "multiprocess")]
56use servo_background_hang_monitor::HangMonitorRegister;
57#[cfg(feature = "bluetooth")]
58use servo_base::generic_channel::GenericSender;
59use servo_base::generic_channel::{GenericCallback, RoutedReceiver, SendError};
60pub use servo_base::id::WebViewId;
61use servo_base::id::{EMBEDDER_PIPELINE_NAMESPACE_ID, PipelineId, PipelineNamespace};
62#[cfg(feature = "bluetooth")]
63use servo_bluetooth::BluetoothThreadFactory;
64#[cfg(feature = "bluetooth")]
65use servo_bluetooth_traits::BluetoothRequest;
66use servo_config::opts::{DiagnosticsLoggingOption, Opts};
67use servo_config::prefs::{PrefValue, Preferences};
68use servo_config::{opts, pref, prefs};
69#[cfg(feature = "multiprocess")]
70use servo_constellation::UnprivilegedContent;
71#[cfg(all(
72    feature = "multiprocess",
73    not(target_os = "windows"),
74    not(target_os = "ios"),
75    not(target_os = "android"),
76    not(target_arch = "arm"),
77    not(target_arch = "aarch64"),
78    not(target_arch = "riscv32"),
79    not(target_arch = "riscv64"),
80    not(target_env = "ohos"),
81))]
82use servo_constellation::content_process_sandbox_profile;
83use servo_constellation::{
84    Constellation, ConstellationToEmbedderMsg, FromEmbedderLogger, InitialConstellationState,
85};
86#[cfg(feature = "multiprocess")]
87use servo_constellation::{FromScriptLogger, NewScriptEventLoopProcessInfo};
88use servo_constellation_traits::EmbedderToConstellationMessage;
89#[cfg(feature = "multiprocess")]
90use servo_constellation_traits::ScriptToConstellationSender;
91use servo_geometry::{
92    DeviceIndependentIntRect, convert_rect_to_css_pixel, convert_size_to_css_pixel,
93};
94use servo_media::ServoMedia;
95use servo_media::player::context::GlContext;
96use servo_wakelock::DefaultWakeLockDelegate;
97use storage::new_storage_threads;
98use storage_traits::StorageThreads;
99#[cfg(feature = "multiprocess")]
100use style::global_style_data::StyleThreadPool;
101#[cfg(feature = "webxr")]
102use webxr::WebXrRegistry;
103
104use crate::clipboard_delegate::StringRequest;
105#[cfg(feature = "gamepad")]
106use crate::gamepad_delegate::{GamepadHapticEffectRequest, GamepadHapticEffectRequestType};
107use crate::geolocation_delegate::{PositionRequest, PositionWatch};
108use crate::javascript_evaluator::JavaScriptEvaluator;
109use crate::network_manager::NetworkManager;
110use crate::proxies::ConstellationProxy;
111use crate::responders::ServoErrorChannel;
112use crate::servo_delegate::{DefaultServoDelegate, ServoDelegate, ServoError};
113use crate::site_data_manager::{CookieOperationResponse, SiteDataManager};
114use crate::webview::{MINIMUM_WEBVIEW_SIZE, WebView, WebViewInner};
115use crate::webview_delegate::{
116    AllowOrDenyRequest, AuthenticationRequest, BluetoothDeviceSelectionRequest, EmbedderControl,
117    FilePicker, NavigationRequest, PermissionRequest, ProtocolHandlerRegistration, WebResourceLoad,
118};
119
120#[cfg(all(
121    feature = "media-gstreamer",
122    not(any(target_os = "android", target_env = "ohos"))
123))]
124mod media_platform {
125    use servo_media_gstreamer::GStreamerBackend;
126
127    use super::ServoMedia;
128
129    #[cfg(any(windows, target_os = "macos"))]
130    pub fn init() {
131        ServoMedia::init_with_backend(|| {
132            use servo_media::BackendInit;
133
134            let mut plugin_dir = std::env::current_exe().unwrap();
135            plugin_dir.pop();
136
137            if cfg!(target_os = "macos") {
138                plugin_dir.push("lib");
139            }
140
141            let plugin_list = crate::gstreamer_plugins::gstreamer_plugins();
142            match GStreamerBackend::init_with_plugins(plugin_dir, &plugin_list) {
143                Ok(backend) => return backend,
144                Err(error) => {
145                    log::warn!(
146                        "Error initializing GStreamer: {error:?}. \
147                        Trying fallback initialization."
148                    );
149                },
150            }
151
152            GStreamerBackend::init()
153        });
154    }
155
156    #[cfg(not(any(windows, target_os = "macos")))]
157    pub fn init() {
158        ServoMedia::init::<GStreamerBackend>();
159    }
160}
161
162#[cfg(target_env = "ohos")]
163mod media_platform {
164    use servo_media_ohos::OhosBackend;
165
166    use super::ServoMedia;
167    pub fn init() {
168        ServoMedia::init::<OhosBackend>();
169    }
170}
171
172#[cfg(all(
173    not(target_env = "ohos"),
174    not(all(feature = "media-gstreamer", not(target_os = "android")))
175))]
176mod media_platform {
177    use super::ServoMedia;
178    pub fn init() {
179        ServoMedia::init::<servo_media_dummy::DummyBackend>();
180    }
181}
182
183#[allow(clippy::enum_variant_names)]
184enum Message {
185    FromNet(NetToEmbedderMsg),
186    FromConstellation(ConstellationToEmbedderMsg),
187    FromUnknown(EmbedderMsg),
188}
189
190/// Holds a prebuilt `crossbeam_channel::Select` over the crossbeam
191/// receivers so our [`spin_event_loop`] loop doesn't rebuild it on every
192/// iteration.
193///
194/// [`spin_event_loop`]: ServoInner::spin_event_loop
195struct EmbedderMessageSelector<'a> {
196    select: crossbeam_channel::Select<'a>,
197    receivers: (
198        &'a Receiver<EmbedderMsg>,
199        &'a Receiver<NetToEmbedderMsg>,
200        &'a Receiver<ConstellationToEmbedderMsg>,
201    ),
202}
203
204impl<'a> EmbedderMessageSelector<'a> {
205    fn new(
206        embedder_receiver: &'a Receiver<EmbedderMsg>,
207        net_embedder_receiver: &'a Receiver<NetToEmbedderMsg>,
208        constellation_embedder_receiver: &'a Receiver<ConstellationToEmbedderMsg>,
209    ) -> Self {
210        let mut select = crossbeam_channel::Select::new();
211        // The order of `.recv()` calls **must** match the order of fields in `receivers`.
212        // In `try_recv()` we assume the `select` index matches the order of receivers in the tuple.
213        let embedder_index = select.recv(embedder_receiver);
214        debug_assert_eq!(embedder_index, 0);
215        let net_embedder_index = select.recv(net_embedder_receiver);
216        debug_assert_eq!(net_embedder_index, 1);
217        let constellation_embedder_index = select.recv(constellation_embedder_receiver);
218        debug_assert_eq!(constellation_embedder_index, 2);
219        Self {
220            select,
221            receivers: (
222                embedder_receiver,
223                net_embedder_receiver,
224                constellation_embedder_receiver,
225            ),
226        }
227    }
228
229    #[servo_tracing::instrument(
230        level = "debug",
231        name = "EmbedderMessageSelector::try_recv_one_message",
232        skip_all
233    )]
234    fn try_recv_one_message(&mut self) -> Option<Message> {
235        let operation = self.select.try_select().ok()?;
236        let index = operation.index();
237        if index == 0 {
238            let message = operation.recv(self.receivers.0).ok()?;
239            Some(Message::FromUnknown(message))
240        } else if index == 1 {
241            let message = operation.recv(self.receivers.1).ok()?;
242            Some(Message::FromNet(message))
243        } else if index == 2 {
244            let message = operation.recv(self.receivers.2).ok()?;
245            Some(Message::FromConstellation(message))
246        } else {
247            log::error!("No select operation registered for {index:?}");
248            None
249        }
250    }
251}
252
253pub struct PendingHandledInputEvent {
254    pub event_id: InputEventId,
255    pub webview_id: WebViewId,
256}
257
258struct ServoInner {
259    delegate: RefCell<Rc<dyn ServoDelegate>>,
260    paint: Rc<RefCell<Paint>>,
261    constellation_proxy: ConstellationProxy,
262    embedder_receiver: Receiver<EmbedderMsg>,
263    net_embedder_receiver: Receiver<NetToEmbedderMsg>,
264    constellation_embedder_receiver: Receiver<ConstellationToEmbedderMsg>,
265    network_manager: Rc<RefCell<NetworkManager>>,
266    site_data_manager: SiteDataManager,
267    /// A struct that tracks ongoing JavaScript evaluations and is responsible for
268    /// calling the callback when the evaluation is complete.
269    javascript_evaluator: Rc<RefCell<JavaScriptEvaluator>>,
270    /// Tracks whether we are in the process of shutting down, or have shut down.
271    /// This is shared with `WebView`s and the `ServoRenderer`.
272    shutdown_state: Rc<Cell<ShutdownState>>,
273    /// A map  [`WebView`]s that are managed by this [`Servo`] instance. These are stored
274    /// as `Weak` references so that the embedding application can control their lifetime.
275    /// When accessed, `Servo` will be reponsible for cleaning up the invalid `Weak`
276    /// references.
277    webviews: RefCell<FxHashMap<WebViewId, Weak<RefCell<WebViewInner>>>>,
278    servo_errors: ServoErrorChannel,
279    /// For single-process Servo instances, this field controls the initialization
280    /// and deinitialization of the JS Engine. Multiprocess Servo instances have their
281    /// own instance that exists in the content process instead.
282    _js_engine_setup: Option<JSEngineSetup>,
283    /// [`InputEventId`]s that have been handled, but for which the embedder has
284    /// not been notified yet.
285    pending_handled_input_events: RefCell<Vec<PendingHandledInputEvent>>,
286    /// An [`EventLoopWaker`] used to wake up the main embedder event loop.
287    event_loop_waker: Box<dyn EventLoopWaker>,
288    /// Geolocation watches that have been handed to a GeolocationDelegate grouped by the pipeline
289    /// that asked for them.
290    geolocation_watches: RefCell<FxHashMap<PipelineId, Vec<GeolocationWatchId>>>,
291}
292
293impl ServoInner {
294    fn get_webview_handle(&self, id: WebViewId) -> Option<WebView> {
295        self.webviews
296            .borrow()
297            .get(&id)
298            .and_then(WebView::from_weak_handle)
299    }
300
301    /// Forget a geolocation watch, returning whether we were still tracking it.
302    fn untrack_geolocation_watch(&self, watch_id: &GeolocationWatchId) -> bool {
303        let mut watches = self.geolocation_watches.borrow_mut();
304        let Some(pipeline_watches) = watches.get_mut(&watch_id.pipeline_id) else {
305            return false;
306        };
307        let Some(index) = pipeline_watches.iter().position(|id| id == watch_id) else {
308            return false;
309        };
310        pipeline_watches.swap_remove(index);
311        if pipeline_watches.is_empty() {
312            watches.remove(&watch_id.pipeline_id);
313        }
314        true
315    }
316
317    /// Tell the GeolocationDelegate to stop a watch, if we still believe it to be running.
318    fn stop_geolocation_watch(&self, watch_id: &GeolocationWatchId) {
319        if !self.untrack_geolocation_watch(watch_id) {
320            return;
321        }
322        if let Some(webview) = self.get_webview_handle(watch_id.webview_id) {
323            webview
324                .geolocation_delegate()
325                .stop_watch(webview.clone(), watch_id);
326        }
327    }
328
329    #[servo_tracing::instrument(level = "debug", skip_all)]
330    fn spin_event_loop(&self) -> bool {
331        if self.shutdown_state.get() == ShutdownState::FinishedShuttingDown {
332            return false;
333        }
334
335        {
336            let paint = self.paint.borrow();
337            let mut messages = Vec::new();
338            while let Ok(message) = paint.receiver().try_recv() {
339                match message {
340                    Ok(message) => messages.push(message),
341                    Err(error) => {
342                        warn!("Router deserialization error: {error}. Ignoring this PaintMessage.")
343                    },
344                }
345            }
346            paint.handle_messages(messages);
347        }
348
349        let mut selector = EmbedderMessageSelector::new(
350            &self.embedder_receiver,
351            &self.net_embedder_receiver,
352            &self.constellation_embedder_receiver,
353        );
354        // Only handle incoming embedder messages if `Paint` hasn't already started shutting down.
355        while let Some(message) = selector.try_recv_one_message() {
356            match message {
357                Message::FromUnknown(message) => self.handle_embedder_message(message),
358                Message::FromNet(message) => self.handle_net_embedder_message(message),
359                Message::FromConstellation(message) => {
360                    self.handle_constellation_embedder_message(message)
361                },
362            }
363            if self.shutdown_state.get() == ShutdownState::FinishedShuttingDown {
364                break;
365            }
366        }
367        let pending_handled_input_events =
368            std::mem::take(&mut *self.pending_handled_input_events.borrow_mut());
369        for PendingHandledInputEvent {
370            event_id,
371            webview_id,
372        } in pending_handled_input_events
373        {
374            self.paint.borrow_mut().notify_input_event_handled(
375                webview_id,
376                event_id,
377                InputEventResult::DispatchFailed,
378            );
379            if let Some(webview) = self.get_webview_handle(webview_id) {
380                webview.delegate().notify_input_event_handled(
381                    webview,
382                    event_id,
383                    InputEventResult::DispatchFailed,
384                );
385            }
386        }
387
388        if self.constellation_proxy.disconnected() {
389            self.delegate
390                .borrow()
391                .notify_error(ServoError::LostConnectionWithBackend);
392        }
393
394        self.paint.borrow_mut().perform_updates();
395        self.resend_accessibility_root_nodes_for_viewport_changes();
396        self.send_new_frame_ready_messages();
397        self.handle_delegate_errors();
398        self.clean_up_destroyed_webview_handles();
399
400        if self.shutdown_state.get() == ShutdownState::FinishedShuttingDown {
401            return false;
402        }
403
404        true
405    }
406
407    /// Resend the root accessibility node for any [`WebView`] whose viewport geometry changed
408    /// post-last-spin (see [`WebView::note_accessibility_viewport_changed()`]). This runs
409    /// after `perform_updates` so the paint `RefCell` is no longer borrowed, and our
410    /// embedder-facing methods calling into the [`WebViewDelegate`] avoid re-entrant
411    /// borrows within the embedder!
412    fn resend_accessibility_root_nodes_for_viewport_changes(&self) {
413        // Collect handles first so the `webviews` borrow is released before we call into the
414        // WebViewDelegate, which the embedder may re-enter.
415        let webviews: Vec<WebView> = self
416            .webviews
417            .borrow()
418            .values()
419            .filter_map(WebView::from_weak_handle)
420            .collect();
421        for webview in webviews {
422            if webview.take_accessibility_viewport_changed() {
423                webview.send_accessibility_root_node();
424            }
425        }
426    }
427
428    fn send_new_frame_ready_messages(&self) {
429        let webviews_needing_repaint = self.paint.borrow().webviews_needing_repaint();
430
431        for webview in webviews_needing_repaint
432            .iter()
433            .filter_map(|webview_id| self.get_webview_handle(*webview_id))
434        {
435            webview.delegate().notify_new_frame_ready(webview);
436        }
437    }
438
439    fn handle_delegate_errors(&self) {
440        while let Some(error) = self.servo_errors.try_recv() {
441            self.delegate.borrow().notify_error(error);
442        }
443    }
444
445    fn clean_up_destroyed_webview_handles(&self) {
446        // Remove any webview handles that have been destroyed and would not be upgradable.
447        // Note that `retain` is O(capacity) because it visits empty buckets, so it may be worth
448        // calling `shrink_to_fit` at some point to deal with cases where a long-running Servo
449        // instance goes from many open webviews to only a few.
450        self.webviews
451            .borrow_mut()
452            .retain(|_webview_id, webview| webview.strong_count() > 0);
453    }
454
455    fn finish_shutting_down(&self) {
456        debug!("Servo received message that Constellation shutdown is complete");
457        self.shutdown_state.set(ShutdownState::FinishedShuttingDown);
458        self.paint.borrow_mut().finish_shutting_down();
459    }
460
461    fn handle_net_embedder_message(&self, message: NetToEmbedderMsg) {
462        match message {
463            NetToEmbedderMsg::SelectFiles(control_id, file_picker_request, response_sender) => {
464                if file_picker_request.accept_current_paths_for_testing {
465                    let _ = response_sender.send(Some(file_picker_request.current_paths));
466                    return;
467                }
468                if let Some(webview) = self.get_webview_handle(control_id.webview_id) {
469                    webview.delegate().show_embedder_control(
470                        webview,
471                        EmbedderControl::FilePicker(FilePicker {
472                            id: control_id,
473                            file_picker_request,
474                            response_sender: Some(response_sender),
475                        }),
476                    );
477                }
478            },
479            NetToEmbedderMsg::WebResourceRequested(
480                webview_id,
481                web_resource_request,
482                response_sender,
483            ) => {
484                if let Some(webview) =
485                    webview_id.and_then(|webview_id| self.get_webview_handle(webview_id))
486                {
487                    let web_resource_load = WebResourceLoad::new(
488                        web_resource_request,
489                        response_sender,
490                        self.servo_errors.sender(),
491                    );
492                    webview
493                        .delegate()
494                        .load_web_resource(webview, web_resource_load);
495                } else {
496                    let web_resource_load = WebResourceLoad::new(
497                        web_resource_request,
498                        response_sender,
499                        self.servo_errors.sender(),
500                    );
501                    self.delegate.borrow().load_web_resource(web_resource_load);
502                }
503            },
504            NetToEmbedderMsg::RequestAuthentication(
505                webview_id,
506                url,
507                for_proxy,
508                response_sender,
509            ) => {
510                if let Some(webview) = self.get_webview_handle(webview_id) {
511                    let authentication_request = AuthenticationRequest::new(
512                        url.into_url(),
513                        for_proxy,
514                        response_sender,
515                        self.servo_errors.sender(),
516                    );
517                    webview
518                        .delegate()
519                        .request_authentication(webview, authentication_request);
520                }
521            },
522            NetToEmbedderMsg::EmbedderCookieOperationResponseWithCookies(operation_id, cookies) => {
523                self.site_data_manager.handle_cookie_response(
524                    operation_id,
525                    CookieOperationResponse::Cookies(cookies),
526                );
527            },
528            NetToEmbedderMsg::EmbedderCookieOperationResponse(operation_id) => {
529                self.site_data_manager
530                    .handle_cookie_response(operation_id, CookieOperationResponse::Done);
531            },
532        }
533    }
534
535    fn handle_embedder_message(&self, message: EmbedderMsg) {
536        match message {
537            EmbedderMsg::Status(webview_id, status_text) => {
538                if let Some(webview) = self.get_webview_handle(webview_id) {
539                    webview.set_status_text(status_text);
540                }
541            },
542            EmbedderMsg::ChangePageTitle(webview_id, title) => {
543                if let Some(webview) = self.get_webview_handle(webview_id) {
544                    webview.set_page_title(title);
545                }
546            },
547            EmbedderMsg::MoveTo(webview_id, position) => {
548                if let Some(webview) = self.get_webview_handle(webview_id) {
549                    webview.delegate().request_move_to(webview, position);
550                }
551            },
552            EmbedderMsg::ResizeTo(webview_id, size) => {
553                if let Some(webview) = self.get_webview_handle(webview_id) {
554                    webview
555                        .delegate()
556                        .request_resize_to(webview, size.max(MINIMUM_WEBVIEW_SIZE));
557                }
558            },
559            EmbedderMsg::ShowSimpleDialog(webview_id, simple_dialog) => {
560                if let Some(webview) = self.get_webview_handle(webview_id) {
561                    webview.delegate().show_embedder_control(
562                        webview,
563                        EmbedderControl::SimpleDialog(simple_dialog.into()),
564                    );
565                }
566            },
567            EmbedderMsg::AllowProtocolHandlerRequest(
568                webview_id,
569                registration_update,
570                response_sender,
571            ) => {
572                if let Some(webview) = self.get_webview_handle(webview_id) {
573                    let ProtocolHandlerUpdateRegistration {
574                        scheme,
575                        url,
576                        register_or_unregister,
577                    } = registration_update;
578                    let protocol_handler_registration = ProtocolHandlerRegistration {
579                        scheme,
580                        url: url.into_url(),
581                        register_or_unregister,
582                    };
583                    let allow_deny_request = AllowOrDenyRequest::new(
584                        response_sender,
585                        AllowOrDeny::Deny,
586                        self.servo_errors.sender(),
587                    );
588                    webview.delegate().request_protocol_handler(
589                        webview,
590                        protocol_handler_registration,
591                        allow_deny_request,
592                    );
593                }
594            },
595            EmbedderMsg::AllowUnload(webview_id, response_sender) => {
596                if let Some(webview) = self.get_webview_handle(webview_id) {
597                    let request = AllowOrDenyRequest::new(
598                        response_sender,
599                        AllowOrDeny::Allow,
600                        self.servo_errors.sender(),
601                    );
602                    webview.delegate().request_unload(webview, request);
603                }
604            },
605            EmbedderMsg::InputEventsHandled(webview_id, event_outcomes) => {
606                let webview = self.get_webview_handle(webview_id);
607                for InputEventOutcome {
608                    id: input_event_id,
609                    result,
610                } in event_outcomes
611                {
612                    self.paint.borrow_mut().notify_input_event_handled(
613                        webview_id,
614                        input_event_id,
615                        result,
616                    );
617                    if let Some(ref webview) = webview {
618                        webview.delegate().notify_input_event_handled(
619                            webview.clone(),
620                            input_event_id,
621                            result,
622                        );
623                    }
624                }
625            },
626            EmbedderMsg::ClearClipboard(webview_id) => {
627                if let Some(webview) = self.get_webview_handle(webview_id) {
628                    webview.clipboard_delegate().clear(webview);
629                }
630            },
631            EmbedderMsg::GetClipboardText(webview_id, result_sender) => {
632                if let Some(webview) = self.get_webview_handle(webview_id) {
633                    webview
634                        .clipboard_delegate()
635                        .get_text(webview, StringRequest::from(result_sender));
636                }
637            },
638            EmbedderMsg::SetClipboardText(webview_id, string) => {
639                if let Some(webview) = self.get_webview_handle(webview_id) {
640                    webview.clipboard_delegate().set_text(webview, string);
641                }
642            },
643            EmbedderMsg::SetCursor(webview_id, cursor) => {
644                if let Some(webview) = self.get_webview_handle(webview_id) {
645                    webview.set_cursor(cursor);
646                }
647            },
648            EmbedderMsg::SetFavicon(webview_id, image) => {
649                if let Some(webview) = self.get_webview_handle(webview_id) {
650                    webview.set_favicon(image);
651                }
652            },
653            EmbedderMsg::NotifyLoadStatusChanged(webview_id, load_status) => {
654                if let Some(webview) = self.get_webview_handle(webview_id) {
655                    webview.set_load_status(load_status);
656                }
657            },
658            EmbedderMsg::NotifyFullscreenStateChanged(webview_id, fullscreen) => {
659                if let Some(webview) = self.get_webview_handle(webview_id) {
660                    webview
661                        .delegate()
662                        .notify_fullscreen_state_changed(webview, fullscreen);
663                }
664            },
665            EmbedderMsg::GetSelectedBluetoothDevice(webview_id, items, response_sender) => {
666                if let Some(webview) = self.get_webview_handle(webview_id) {
667                    webview.delegate().show_bluetooth_device_dialog(
668                        webview,
669                        BluetoothDeviceSelectionRequest::new(items, response_sender),
670                    );
671                }
672            },
673            EmbedderMsg::PromptPermission(webview_id, requested_feature, response_sender) => {
674                if let Some(webview) = self.get_webview_handle(webview_id) {
675                    let permission_request = PermissionRequest {
676                        requested_feature,
677                        allow_deny_request: AllowOrDenyRequest::new(
678                            response_sender,
679                            AllowOrDeny::Deny,
680                            self.servo_errors.sender(),
681                        ),
682                    };
683                    webview
684                        .delegate()
685                        .request_permission(webview, permission_request);
686                }
687            },
688            EmbedderMsg::RequestPermission(webview_id, requested_feature, callback) => {
689                if let Some(webview) = self.get_webview_handle(webview_id) {
690                    let permission_request = PermissionRequest {
691                        requested_feature,
692                        allow_deny_request: AllowOrDenyRequest::new_from_callback(
693                            callback,
694                            AllowOrDeny::Deny,
695                            self.servo_errors.sender(),
696                        ),
697                    };
698                    webview
699                        .delegate()
700                        .request_permission(webview, permission_request);
701                }
702            },
703            EmbedderMsg::RequestGeolocationPosition(webview_id, options, result_sender) => {
704                if let Some(webview) = self.get_webview_handle(webview_id) {
705                    webview.geolocation_delegate().request_position(
706                        webview.clone(),
707                        PositionRequest::new(result_sender, options),
708                    );
709                }
710            },
711            EmbedderMsg::StartGeolocationWatch(watch_id, options, result_sender) => {
712                if let Some(webview) = self.get_webview_handle(watch_id.webview_id) {
713                    self.geolocation_watches
714                        .borrow_mut()
715                        .entry(watch_id.pipeline_id)
716                        .or_default()
717                        .push(watch_id.clone());
718                    webview.geolocation_delegate().start_watch(
719                        webview.clone(),
720                        PositionWatch::new(watch_id, result_sender, options),
721                    );
722                }
723            },
724            EmbedderMsg::StopGeolocationWatch(watch_id) => {
725                self.stop_geolocation_watch(&watch_id);
726            },
727            EmbedderMsg::OnDevtoolsStarted(port, token) => match port {
728                Ok(port) => self
729                    .delegate
730                    .borrow()
731                    .notify_devtools_server_started(port, token),
732                Err(()) => self
733                    .delegate
734                    .borrow()
735                    .notify_error(ServoError::DevtoolsFailedToStart),
736            },
737            EmbedderMsg::RequestDevtoolsConnection(response_sender) => {
738                self.delegate
739                    .borrow()
740                    .request_devtools_connection(AllowOrDenyRequest::new(
741                        response_sender,
742                        AllowOrDeny::Deny,
743                        self.servo_errors.sender(),
744                    ));
745            },
746            #[cfg(feature = "gamepad")]
747            EmbedderMsg::PlayGamepadHapticEffect(
748                webview_id,
749                gamepad_index,
750                gamepad_haptic_effect_type,
751                callback,
752            ) => {
753                if let Some(webview) = self.get_webview_handle(webview_id) {
754                    let request = GamepadHapticEffectRequest::new(
755                        gamepad_index,
756                        GamepadHapticEffectRequestType::Play(gamepad_haptic_effect_type),
757                        Box::new(move |success| {
758                            callback
759                                .send(success)
760                                .expect("Could not send message via callback")
761                        }),
762                    );
763                    webview
764                        .gamepad_delegate()
765                        .handle_haptic_effect_request(request);
766                }
767            },
768            #[cfg(feature = "gamepad")]
769            EmbedderMsg::StopGamepadHapticEffect(webview_id, gamepad_index, callback) => {
770                if let Some(webview) = self.get_webview_handle(webview_id) {
771                    let request = GamepadHapticEffectRequest::new(
772                        gamepad_index,
773                        GamepadHapticEffectRequestType::Stop,
774                        Box::new(move |success| {
775                            callback
776                                .send(success)
777                                .expect("Could not send message via callback")
778                        }),
779                    );
780                    webview
781                        .gamepad_delegate()
782                        .handle_haptic_effect_request(request);
783                }
784            },
785            EmbedderMsg::ShowNotification(webview_id, notification) => {
786                match webview_id.and_then(|webview_id| self.get_webview_handle(webview_id)) {
787                    Some(webview) => webview.delegate().show_notification(webview, notification),
788                    None => self.delegate.borrow().show_notification(notification),
789                }
790            },
791            EmbedderMsg::ShowConsoleApiMessage(webview_id, level, message) => {
792                match webview_id.and_then(|webview_id| self.get_webview_handle(webview_id)) {
793                    Some(webview) => webview
794                        .delegate()
795                        .show_console_message(webview, level, message),
796                    None => self.delegate.borrow().show_console_message(level, message),
797                }
798            },
799            EmbedderMsg::ShowEmbedderControl(control_id, rect, embedder_control_request) => {
800                if let Some(webview) = self.get_webview_handle(control_id.webview_id) {
801                    let device_rect = self
802                        .paint
803                        .borrow()
804                        .map_pipeline_rect_to_device_rect(control_id.webview_id, rect)
805                        .unwrap_or_default();
806                    webview.show_embedder_control(
807                        control_id,
808                        device_rect.to_i32(),
809                        embedder_control_request,
810                    );
811                }
812            },
813            EmbedderMsg::HideEmbedderControl(control_id) => {
814                if let Some(webview) = self.get_webview_handle(control_id.webview_id) {
815                    webview
816                        .delegate()
817                        .hide_embedder_control(webview, control_id);
818                }
819            },
820            EmbedderMsg::GetWindowRect(webview_id, response_sender) => {
821                let window_rect = || {
822                    let Some(webview) = self.get_webview_handle(webview_id) else {
823                        return DeviceIndependentIntRect::default();
824                    };
825                    let hidpi_scale_factor = webview.hidpi_scale_factor();
826                    let Some(screen_geometry) = webview.delegate().screen_geometry(webview) else {
827                        return DeviceIndependentIntRect::default();
828                    };
829
830                    convert_rect_to_css_pixel(screen_geometry.window_rect, hidpi_scale_factor)
831                };
832
833                if let Err(error) = response_sender.send(window_rect()) {
834                    warn!("Failed to respond to GetWindowRect: {error}");
835                }
836            },
837            EmbedderMsg::GetScreenMetrics(webview_id, response_sender) => {
838                let screen_metrics = || {
839                    let Some(webview) = self.get_webview_handle(webview_id) else {
840                        return ScreenMetrics::default();
841                    };
842                    let hidpi_scale_factor = webview.hidpi_scale_factor();
843                    let Some(screen_geometry) = webview.delegate().screen_geometry(webview) else {
844                        return ScreenMetrics::default();
845                    };
846
847                    ScreenMetrics {
848                        screen_size: convert_size_to_css_pixel(
849                            screen_geometry.size,
850                            hidpi_scale_factor,
851                        ),
852                        available_size: convert_size_to_css_pixel(
853                            screen_geometry.available_size,
854                            hidpi_scale_factor,
855                        ),
856                    }
857                };
858                if let Err(error) = response_sender.send(screen_metrics()) {
859                    warn!("Failed to respond to GetScreenMetrics: {error}");
860                }
861            },
862            EmbedderMsg::AccessibilityTreeUpdate(webview_id, tree_update, epoch) => {
863                if let Some(webview) = self.get_webview_handle(webview_id) {
864                    webview.process_accessibility_tree_update(tree_update, epoch);
865                }
866            },
867        }
868    }
869
870    fn handle_constellation_embedder_message(&self, message: ConstellationToEmbedderMsg) {
871        match message {
872            ConstellationToEmbedderMsg::ShutdownComplete => self.finish_shutting_down(),
873            ConstellationToEmbedderMsg::AllowNavigationRequest(
874                webview_id,
875                pipeline_id,
876                servo_url,
877            ) => {
878                if let Some(webview) = self.get_webview_handle(webview_id) {
879                    let request = NavigationRequest {
880                        url: servo_url.into_url(),
881                        pipeline_id,
882                        constellation_proxy: self.constellation_proxy.clone(),
883                        response_sent: false,
884                    };
885                    webview.delegate().request_navigation(webview, request);
886                }
887            },
888            ConstellationToEmbedderMsg::AllowOpeningWebView(webview_id, response_sender) => {
889                if let Some(webview) = self.get_webview_handle(webview_id) {
890                    webview.request_create_new(response_sender);
891                }
892            },
893            ConstellationToEmbedderMsg::WebViewClosed(webview_id) => {
894                if let Some(webview) = self.get_webview_handle(webview_id) {
895                    webview.delegate().notify_closed(webview);
896                }
897            },
898            ConstellationToEmbedderMsg::FinishJavaScriptEvaluation(evaluation_id, result) => {
899                self.javascript_evaluator
900                    .borrow_mut()
901                    .finish_evaluation(evaluation_id, result);
902            },
903            ConstellationToEmbedderMsg::InputEventsHandled(webview_id, event_outcomes) => {
904                let webview = self.get_webview_handle(webview_id);
905                for InputEventOutcome {
906                    id: input_event_id,
907                    result,
908                } in event_outcomes
909                {
910                    self.paint.borrow_mut().notify_input_event_handled(
911                        webview_id,
912                        input_event_id,
913                        result,
914                    );
915                    if let Some(ref webview) = webview {
916                        webview.delegate().notify_input_event_handled(
917                            webview.clone(),
918                            input_event_id,
919                            result,
920                        );
921                    }
922                }
923            },
924            ConstellationToEmbedderMsg::HistoryTraversalComplete(webview_id, traversal_id) => {
925                if let Some(webview) = self.get_webview_handle(webview_id) {
926                    webview
927                        .delegate()
928                        .notify_traversal_complete(webview.clone(), traversal_id);
929                }
930            },
931            ConstellationToEmbedderMsg::HistoryChanged(
932                webview_id,
933                new_back_forward_list,
934                current_list_index,
935            ) => {
936                if let Some(webview) = self.get_webview_handle(webview_id) {
937                    webview.set_history(new_back_forward_list, current_list_index);
938                }
939            },
940            ConstellationToEmbedderMsg::Panic(webview_id, reason, backtrace) => {
941                if let Some(webview) = self.get_webview_handle(webview_id) {
942                    webview
943                        .delegate()
944                        .notify_crashed(webview, reason, backtrace);
945                }
946            },
947            ConstellationToEmbedderMsg::PipelineExited(pipeline_id) => {
948                let orphaned = self
949                    .geolocation_watches
950                    .borrow()
951                    .get(&pipeline_id)
952                    .cloned()
953                    .unwrap_or_default();
954                for watch_id in orphaned {
955                    self.stop_geolocation_watch(&watch_id);
956                }
957            },
958            ConstellationToEmbedderMsg::MediaSessionEvent(webview_id, media_session_event) => {
959                if let Some(webview) = self.get_webview_handle(webview_id) {
960                    webview
961                        .delegate()
962                        .notify_media_session_event(webview, media_session_event);
963                }
964            },
965        }
966    }
967}
968
969impl Drop for ServoInner {
970    fn drop(&mut self) {
971        self.constellation_proxy
972            .send(EmbedderToConstellationMessage::Exit);
973        self.shutdown_state.set(ShutdownState::ShuttingDown);
974        while self.spin_event_loop() {
975            std::thread::sleep(Duration::from_micros(500));
976        }
977    }
978}
979
980#[cfg(feature = "devtools")]
981type DevtoolsMessage = devtools_traits::DevtoolsControlMsg;
982
983#[cfg(not(feature = "devtools"))]
984type DevtoolsMessage = ();
985
986/// An in-process handle to a `Servo` instance. Cloning the handle does not create a new instance
987/// of `Servo`.
988///
989/// A `Servo` instance does everything necessary to render the web, primarily orchestrating the
990/// interaction between JavaScript, CSS layout, rendering, and the client window.
991///
992/// Clients create an event loop to pump messages between the embedding
993/// application and various browser components.
994#[derive(Clone)]
995pub struct Servo(Rc<ServoInner>);
996
997impl Servo {
998    #[servo_tracing::instrument(name = "Servo::new", skip(builder))]
999    fn new(builder: ServoBuilder) -> Self {
1000        // Global configuration options, parsed from the command line.
1001        let opts = builder.opts.map(|opts| *opts).unwrap_or_default();
1002        opts::initialize_options(opts);
1003        let opts = opts::get();
1004
1005        // Set the preferences globally.
1006        // TODO: It would be better to make these private to a particular Servo instance.
1007        let preferences = builder.preferences.map(|opts| *opts);
1008        servo_config::prefs::set(preferences.unwrap_or_default());
1009
1010        use std::sync::atomic::Ordering;
1011
1012        style::context::DEFAULT_DISABLE_STYLE_SHARING_CACHE.store(
1013            !pref!(layout_style_sharing_cache_enabled),
1014            Ordering::Relaxed,
1015        );
1016        style::context::DEFAULT_DUMP_STYLE_STATISTICS.store(
1017            opts.debug
1018                .is_enabled(DiagnosticsLoggingOption::StyleStatistics),
1019            Ordering::Relaxed,
1020        );
1021
1022        if !opts.multiprocess {
1023            media_platform::init();
1024        }
1025
1026        // Reserving a namespace to create WebViewId.
1027        PipelineNamespace::install(EMBEDDER_PIPELINE_NAMESPACE_ID);
1028
1029        // Get both endpoints of a special channel for communication between
1030        // the client window and `Paint`. This channel is unique because
1031        // messages to client may need to pump a platform-specific event loop
1032        // to deliver the message.
1033        let event_loop_waker = builder.event_loop_waker;
1034        let (paint_proxy, paint_receiver) = create_paint_channel(event_loop_waker.clone());
1035        let (constellation_proxy, embedder_to_constellation_receiver) = ConstellationProxy::new();
1036        let (embedder_proxy, embedder_receiver) = create_embedder_channel(event_loop_waker.clone());
1037        let (net_embedder_proxy, net_embedder_receiver) =
1038            create_generic_embedder_channel::<NetToEmbedderMsg>(event_loop_waker.clone());
1039        let (constellation_embedder_proxy, constellation_embedder_receiver) =
1040            create_generic_embedder_channel::<ConstellationToEmbedderMsg>(event_loop_waker.clone());
1041        let time_profiler_chan = profile_time::Profiler::create(
1042            &opts.time_profiling,
1043            opts.time_profiler_trace_path.clone(),
1044        );
1045        let mem_profiler_chan = profile_mem::Profiler::create();
1046
1047        let mut devtools_sender: Option<Sender<DevtoolsMessage>> = None;
1048        #[cfg(feature = "devtools")]
1049        if pref!(devtools_server_enabled) {
1050            devtools_sender = Some(devtools::start_server(
1051                embedder_proxy.clone(),
1052                mem_profiler_chan.clone(),
1053            ))
1054        }
1055
1056        // Important that this call is done in a single-threaded fashion, we
1057        // can't defer it after `create_constellation` has started.
1058        let js_engine_setup = if !opts.multiprocess {
1059            Some(script::init())
1060        } else {
1061            None
1062        };
1063
1064        // Create the constellation, which maintains the engine pipelines, including script and
1065        // layout, as well as the navigation context.
1066        let mut protocols = ProtocolRegistry::with_internal_protocols();
1067        protocols.merge(builder.protocol_registry);
1068
1069        // The `Paint` coordinates with the client window to create the final
1070        // rendered page and display it somewhere.
1071        let shutdown_state = Rc::new(Cell::new(ShutdownState::NotShuttingDown));
1072        let paint = Paint::new(InitialPaintState {
1073            paint_proxy: paint_proxy.clone(),
1074            receiver: paint_receiver,
1075            embedder_to_constellation_sender: constellation_proxy.sender(),
1076            time_profiler_chan: time_profiler_chan.clone(),
1077            mem_profiler_chan: mem_profiler_chan.clone(),
1078            shutdown_state: shutdown_state.clone(),
1079            event_loop_waker: event_loop_waker.clone(),
1080        });
1081
1082        let protocols = Arc::new(protocols);
1083        let (public_resource_threads, private_resource_threads, async_runtime) =
1084            new_resource_threads(
1085                devtools_sender.clone(),
1086                time_profiler_chan.clone(),
1087                mem_profiler_chan.clone(),
1088                net_embedder_proxy,
1089                opts.config_dir.clone(),
1090                opts.certificate_path.clone(),
1091                opts.ignore_certificate_errors,
1092                protocols.clone(),
1093            );
1094
1095        let (private_storage_threads, public_storage_threads) = new_storage_threads(
1096            mem_profiler_chan.clone(),
1097            opts.config_dir.clone(),
1098            opts.temporary_storage,
1099        );
1100
1101        create_constellation(
1102            embedder_to_constellation_receiver,
1103            &paint.borrow(),
1104            embedder_proxy,
1105            constellation_embedder_proxy,
1106            paint_proxy,
1107            time_profiler_chan,
1108            mem_profiler_chan,
1109            #[cfg(feature = "devtools")]
1110            devtools_sender,
1111            protocols,
1112            public_resource_threads.clone(),
1113            private_resource_threads.clone(),
1114            async_runtime,
1115            public_storage_threads.clone(),
1116            private_storage_threads.clone(),
1117        );
1118
1119        net::connector::prewarm_tls();
1120
1121        #[cfg(feature = "multiprocess")]
1122        if opts::get().multiprocess {
1123            prefs::add_observer(Box::new(constellation_proxy.clone()));
1124        }
1125
1126        Servo(Rc::new(ServoInner {
1127            delegate: RefCell::new(Rc::new(DefaultServoDelegate)),
1128            paint,
1129            network_manager: Rc::new(RefCell::new(NetworkManager::new(
1130                public_resource_threads.clone(),
1131                private_resource_threads.clone(),
1132                constellation_proxy.clone(),
1133            ))),
1134            site_data_manager: SiteDataManager::new(
1135                public_resource_threads,
1136                private_resource_threads,
1137                public_storage_threads,
1138                private_storage_threads,
1139            ),
1140            javascript_evaluator: Rc::new(RefCell::new(JavaScriptEvaluator::new(
1141                constellation_proxy.clone(),
1142            ))),
1143            constellation_proxy,
1144            embedder_receiver,
1145            net_embedder_receiver,
1146            constellation_embedder_receiver,
1147            shutdown_state,
1148            webviews: Default::default(),
1149            servo_errors: ServoErrorChannel::default(),
1150            _js_engine_setup: js_engine_setup,
1151            pending_handled_input_events: Default::default(),
1152            event_loop_waker,
1153            geolocation_watches: Default::default(),
1154        }))
1155    }
1156
1157    pub fn delegate(&self) -> Rc<dyn ServoDelegate> {
1158        self.0.delegate.borrow().clone()
1159    }
1160
1161    pub fn set_delegate(&self, delegate: Rc<dyn ServoDelegate>) {
1162        *self.0.delegate.borrow_mut() = delegate;
1163    }
1164
1165    /// **EXPERIMENTAL:** Intialize GL accelerated media playback. This currently only works on a limited number
1166    /// of platforms. This should be run *before* creating [`Servo`] and its first [`WebView`].
1167    pub fn initialize_gl_accelerated_media(display: NativeDisplay, api: GlApi, context: GlContext) {
1168        WindowGLContext::initialize(display, api, context)
1169    }
1170
1171    /// Spin the Servo event loop, which:
1172    ///
1173    ///   - Performs updates in `Paint`, such as queued pinch zoom events
1174    ///   - Runs delegate methods on all `WebView`s and `Servo` itself
1175    ///   - Maybe update the rendered `Paint` output, but *without* swapping buffers.
1176    pub fn spin_event_loop(&self) {
1177        self.0.spin_event_loop();
1178    }
1179
1180    pub fn setup_logging(&self) {
1181        let constellation_chan = self.0.constellation_proxy.sender();
1182        let env = env_logger::Env::default();
1183        let env_logger = EnvLoggerBuilder::from_env(env).build();
1184        let con_logger = FromEmbedderLogger::new(constellation_chan);
1185
1186        let filter = max(env_logger.filter(), con_logger.filter());
1187        let logger = BothLogger(env_logger, con_logger);
1188
1189        log::set_boxed_logger(Box::new(logger)).expect("Failed to set logger.");
1190        log::set_max_level(filter);
1191    }
1192
1193    pub fn create_memory_report(&self, snd: GenericCallback<MemoryReportResult>) {
1194        self.0
1195            .constellation_proxy
1196            .send(EmbedderToConstellationMessage::CreateMemoryReport(snd));
1197    }
1198
1199    pub fn execute_webdriver_command(&self, command: WebDriverCommandMsg) {
1200        self.0
1201            .constellation_proxy
1202            .send(EmbedderToConstellationMessage::WebDriverCommand(command));
1203    }
1204
1205    pub fn set_preference(&self, name: &str, value: PrefValue) {
1206        let mut preferences = prefs::get().clone();
1207        preferences.set_value(name, value);
1208        prefs::set(preferences);
1209    }
1210
1211    pub fn network_manager<'a>(&'a self) -> Ref<'a, NetworkManager> {
1212        self.0.network_manager.borrow()
1213    }
1214
1215    pub fn site_data_manager(&self) -> &SiteDataManager {
1216        &self.0.site_data_manager
1217    }
1218
1219    /// When an [`ActionRequest`] is received from AccessKit, forward it to the appropriate document
1220    /// to fulfill the action in the request.
1221    ///
1222    /// For example, if an AccessKit adapter sends a request for an [`accesskit::Action::Click`]
1223    /// with a particular [`accesskit::TreeId`] and [`accesskit::NodeId`], determine which document
1224    /// contains the tree matching the [`accesskit::TreeId`] and forward the [`ActionRequest`]
1225    /// there, so that it can find the appropriate node to take the click action on.
1226    pub fn forward_accessibility_action(&self, action_request: ActionRequest) {
1227        self.0.constellation_proxy.send(
1228            EmbedderToConstellationMessage::ForwardAccessibilityAction(action_request),
1229        );
1230    }
1231
1232    pub(crate) fn paint<'a>(&'a self) -> Ref<'a, Paint> {
1233        self.0.paint.borrow()
1234    }
1235
1236    pub(crate) fn paint_mut<'a>(&'a self) -> RefMut<'a, Paint> {
1237        self.0.paint.borrow_mut()
1238    }
1239
1240    pub(crate) fn event_loop_waker(&self) -> &dyn EventLoopWaker {
1241        &*self.0.event_loop_waker
1242    }
1243
1244    pub(crate) fn webviews_mut<'a>(
1245        &'a self,
1246    ) -> RefMut<'a, FxHashMap<WebViewId, Weak<RefCell<WebViewInner>>>> {
1247        self.0.webviews.borrow_mut()
1248    }
1249
1250    pub(crate) fn constellation_proxy(&self) -> &ConstellationProxy {
1251        &self.0.constellation_proxy
1252    }
1253
1254    pub(crate) fn javascript_evaluator_mut<'a>(&'a self) -> RefMut<'a, JavaScriptEvaluator> {
1255        self.0.javascript_evaluator.borrow_mut()
1256    }
1257
1258    pub(crate) fn add_pending_handled_input_event(&self, residue_event: PendingHandledInputEvent) {
1259        self.0
1260            .pending_handled_input_events
1261            .borrow_mut()
1262            .push(residue_event);
1263    }
1264
1265    #[cfg(feature = "webxr")]
1266    /// Registers a [`WebXrRegistry`]
1267    pub fn register_webxr_registry(&self, registry: Box<dyn WebXrRegistry>) {
1268        self.0.paint.borrow().register_webxr_registry(registry);
1269    }
1270}
1271
1272fn create_embedder_channel(
1273    event_loop_waker: Box<dyn EventLoopWaker>,
1274) -> (EmbedderProxy, Receiver<EmbedderMsg>) {
1275    let (sender, receiver) = unbounded();
1276    (
1277        EmbedderProxy {
1278            sender,
1279            event_loop_waker,
1280        },
1281        receiver,
1282    )
1283}
1284
1285fn create_generic_embedder_channel<T>(
1286    event_loop_waker: Box<dyn EventLoopWaker>,
1287) -> (GenericEmbedderProxy<T>, Receiver<T>) {
1288    let (sender, receiver) = unbounded();
1289    (
1290        GenericEmbedderProxy {
1291            sender,
1292            event_loop_waker,
1293        },
1294        receiver,
1295    )
1296}
1297
1298fn create_paint_channel(
1299    event_loop_waker: Box<dyn EventLoopWaker>,
1300) -> (PaintProxy, RoutedReceiver<PaintMessage>) {
1301    let (sender, receiver) = unbounded();
1302    let sender_clone = sender.clone();
1303    let event_loop_waker_clone = event_loop_waker.clone();
1304    // This callback is equivalent to `PaintProxy::send`
1305    let result_callback = move |msg: Result<PaintMessage, SendError>| {
1306        if let Err(err) = sender_clone.send(msg) {
1307            warn!("Failed to send response ({:?}).", err);
1308        }
1309        event_loop_waker_clone.wake();
1310    };
1311
1312    let generic_callback =
1313        GenericCallback::new(result_callback).expect("Failed to create callback");
1314    let cross_process_paint_api = CrossProcessPaintApi::new(generic_callback);
1315    let paint_proxy = PaintProxy {
1316        sender,
1317        cross_process_paint_api,
1318        event_loop_waker,
1319    };
1320
1321    (paint_proxy, receiver)
1322}
1323
1324#[expect(clippy::too_many_arguments)]
1325fn create_constellation(
1326    embedder_to_constellation_receiver: Receiver<EmbedderToConstellationMessage>,
1327    paint: &Paint,
1328    embedder_proxy: EmbedderProxy,
1329    constellation_to_embedder_proxy: GenericEmbedderProxy<ConstellationToEmbedderMsg>,
1330    paint_proxy: PaintProxy,
1331    time_profiler_chan: time::ProfilerChan,
1332    mem_profiler_chan: mem::ProfilerChan,
1333    #[cfg(feature = "devtools")] devtools_sender: Option<
1334        Sender<devtools_traits::DevtoolsControlMsg>,
1335    >,
1336    protocols: Arc<ProtocolRegistry>,
1337    public_resource_threads: ResourceThreads,
1338    private_resource_threads: ResourceThreads,
1339    async_runtime: Box<dyn net_traits::AsyncRuntime>,
1340    public_storage_threads: StorageThreads,
1341    private_storage_threads: StorageThreads,
1342) {
1343    // Global configuration options, parsed from the command line.
1344    let opts = opts::get();
1345
1346    #[cfg(feature = "bluetooth")]
1347    let bluetooth_thread: GenericSender<BluetoothRequest> =
1348        BluetoothThreadFactory::new(embedder_proxy.clone());
1349
1350    let privileged_urls = protocols.privileged_urls();
1351
1352    let system_font_service = SystemFontServiceProxy::new(&SystemFontService::spawn(
1353        paint_proxy.cross_process_paint_api.clone(),
1354        mem_profiler_chan.clone(),
1355    ));
1356
1357    let initial_state = InitialConstellationState {
1358        paint_proxy,
1359        embedder_proxy,
1360        constellation_to_embedder_proxy,
1361        #[cfg(feature = "devtools")]
1362        devtools_sender,
1363        #[cfg(feature = "bluetooth")]
1364        bluetooth_thread,
1365        system_font_service,
1366        public_resource_threads,
1367        private_resource_threads,
1368        public_storage_threads,
1369        private_storage_threads,
1370        time_profiler_chan,
1371        mem_profiler_chan,
1372        #[cfg(feature = "webxr")]
1373        webxr_registry: Some(paint.webxr_main_thread_registry()),
1374        #[cfg(not(feature = "webxr"))]
1375        webxr_registry: None,
1376        #[cfg(feature = "webgl")]
1377        webgl_threads: Some(paint.webgl_threads()),
1378        webrender_external_image_id_manager: paint.webrender_external_image_id_manager(),
1379        #[cfg(feature = "webgpu")]
1380        wgpu_image_map: paint.webgpu_image_map(),
1381        async_runtime,
1382        privileged_urls,
1383        wake_lock_provider: Box::new(DefaultWakeLockDelegate),
1384    };
1385
1386    let layout_factory = Arc::new(LayoutFactoryImpl());
1387
1388    Constellation::<script::ScriptThread, script::ServiceWorkerManager>::start(
1389        embedder_to_constellation_receiver,
1390        initial_state,
1391        layout_factory,
1392        opts.random_pipeline_closure_probability,
1393        opts.random_pipeline_closure_seed,
1394        opts.hard_fail,
1395    );
1396}
1397
1398// A logger that logs to two downstream loggers.
1399// This should probably be in the log crate.
1400struct BothLogger<Log1, Log2>(Log1, Log2);
1401
1402impl<Log1, Log2> Log for BothLogger<Log1, Log2>
1403where
1404    Log1: Log,
1405    Log2: Log,
1406{
1407    fn enabled(&self, metadata: &Metadata) -> bool {
1408        self.0.enabled(metadata) || self.1.enabled(metadata)
1409    }
1410
1411    fn log(&self, record: &Record) {
1412        self.0.log(record);
1413        self.1.log(record);
1414    }
1415
1416    fn flush(&self) {
1417        self.0.flush();
1418        self.1.flush();
1419    }
1420}
1421
1422#[cfg(feature = "multiprocess")]
1423fn set_logger(script_to_constellation_sender: ScriptToConstellationSender) {
1424    let con_logger = FromScriptLogger::new(script_to_constellation_sender);
1425    let env = env_logger::Env::default();
1426    let env_logger = EnvLoggerBuilder::from_env(env).build();
1427
1428    let filter = max(env_logger.filter(), con_logger.filter());
1429    let logger = BothLogger(env_logger, con_logger);
1430
1431    log::set_boxed_logger(Box::new(logger)).expect("Failed to set logger.");
1432    log::set_max_level(filter);
1433}
1434
1435/// Content process entry point.
1436#[cfg(feature = "multiprocess")]
1437pub fn run_content_process(token: String) {
1438    let (unprivileged_content_sender, unprivileged_content_receiver) =
1439        ipc::channel::<UnprivilegedContent>().unwrap();
1440    let connection_bootstrap: IpcSender<IpcSender<UnprivilegedContent>> =
1441        IpcSender::connect(token).unwrap();
1442    connection_bootstrap
1443        .send(unprivileged_content_sender)
1444        .unwrap();
1445
1446    let unprivileged_content = unprivileged_content_receiver.recv().unwrap();
1447    opts::initialize_options(unprivileged_content.opts());
1448    prefs::set(unprivileged_content.prefs().clone());
1449
1450    // Enter the sandbox if necessary.
1451    if opts::get().sandbox {
1452        create_sandbox();
1453    }
1454
1455    let _js_engine_setup = script::init();
1456
1457    match unprivileged_content {
1458        UnprivilegedContent::ScriptEventLoop(new_event_loop_info) => {
1459            media_platform::init();
1460
1461            set_logger(
1462                new_event_loop_info
1463                    .initial_script_state
1464                    .script_to_constellation_sender
1465                    .clone(),
1466            );
1467
1468            register_system_memory_reporter_for_event_loop(&new_event_loop_info);
1469
1470            let (background_hang_monitor_register, background_hang_monitor_join_handle) =
1471                HangMonitorRegister::init(
1472                    new_event_loop_info.bhm_to_constellation_sender.clone(),
1473                    new_event_loop_info.constellation_to_bhm_receiver,
1474                    opts::get().background_hang_monitor,
1475                );
1476
1477            let layout_factory = Arc::new(LayoutFactoryImpl());
1478            let script_join_handle = script::ScriptThread::create(
1479                new_event_loop_info.initial_script_state,
1480                layout_factory,
1481                Arc::new(ImageCacheFactoryImpl::new(
1482                    new_event_loop_info.broken_image_icon_data,
1483                )),
1484                background_hang_monitor_register,
1485            );
1486
1487            script_join_handle
1488                .join()
1489                .expect("Failed to join on the script thread.");
1490            background_hang_monitor_join_handle
1491                .join()
1492                .expect("Failed to join on the BHM background thread.");
1493
1494            StyleThreadPool::shutdown();
1495
1496            // Shut down the `FetchThread` if it had been started in the course of execution.
1497            FetchThread::exit();
1498        },
1499        UnprivilegedContent::ServiceWorker(content) => {
1500            content.start::<ServiceWorkerManager>();
1501        },
1502        UnprivilegedContent::SharedWorker(content) => {
1503            media_platform::init();
1504            content
1505                .start::<script::ScriptThread>(Arc::new(ImageCacheFactoryImpl::new(
1506                    resources::read_bytes(resources::Resource::BrokenImageIcon),
1507                )))
1508                .join()
1509                .expect("Failed to join on the shared worker manager thread.");
1510            FetchThread::exit();
1511        },
1512    }
1513}
1514
1515#[cfg(all(
1516    feature = "multiprocess",
1517    not(target_os = "windows"),
1518    not(target_os = "ios"),
1519    not(target_os = "android"),
1520    not(target_arch = "arm"),
1521    not(target_arch = "aarch64"),
1522    not(target_arch = "riscv32"),
1523    not(target_arch = "riscv64"),
1524    not(target_env = "ohos"),
1525))]
1526fn create_sandbox() {
1527    ChildSandbox::new(content_process_sandbox_profile())
1528        .activate()
1529        .expect("Failed to activate sandbox!");
1530}
1531
1532#[cfg(any(
1533    target_os = "windows",
1534    target_os = "ios",
1535    target_os = "android",
1536    target_arch = "arm",
1537    target_arch = "aarch64",
1538    target_arch = "riscv32",
1539    target_arch = "riscv64",
1540    target_env = "ohos",
1541))]
1542fn create_sandbox() {
1543    panic!("Sandboxing is not supported on Windows, iOS, ARM, RISC-V targets and android.");
1544}
1545
1546struct DefaultEventLoopWaker;
1547
1548impl EventLoopWaker for DefaultEventLoopWaker {
1549    fn clone_box(&self) -> Box<dyn EventLoopWaker> {
1550        Box::new(DefaultEventLoopWaker)
1551    }
1552
1553    fn wake(&self) {}
1554}
1555
1556/// Builder for [`Servo`].
1557pub struct ServoBuilder {
1558    opts: Option<Box<Opts>>,
1559    preferences: Option<Box<Preferences>>,
1560    event_loop_waker: Box<dyn EventLoopWaker>,
1561    protocol_registry: ProtocolRegistry,
1562}
1563
1564impl Default for ServoBuilder {
1565    fn default() -> Self {
1566        Self {
1567            opts: Default::default(),
1568            preferences: Default::default(),
1569            event_loop_waker: Box::new(DefaultEventLoopWaker),
1570            protocol_registry: Default::default(),
1571        }
1572    }
1573}
1574
1575impl ServoBuilder {
1576    pub fn build(self) -> Servo {
1577        Servo::new(self)
1578    }
1579
1580    pub fn opts(mut self, opts: Opts) -> Self {
1581        self.opts = Some(Box::new(opts));
1582        self
1583    }
1584
1585    pub fn preferences(mut self, preferences: Preferences) -> Self {
1586        self.preferences = Some(Box::new(preferences));
1587        self
1588    }
1589
1590    pub fn event_loop_waker(mut self, event_loop_waker: Box<dyn EventLoopWaker>) -> Self {
1591        self.event_loop_waker = event_loop_waker;
1592        self
1593    }
1594
1595    pub fn protocol_registry(mut self, protocol_registry: ProtocolRegistry) -> Self {
1596        self.protocol_registry = protocol_registry;
1597        self
1598    }
1599}
1600
1601#[cfg(feature = "multiprocess")]
1602fn register_system_memory_reporter_for_event_loop(
1603    new_event_loop_info: &NewScriptEventLoopProcessInfo,
1604) {
1605    // Register the system memory reporter, which will run on its own thread. It never needs to
1606    // be unregistered, because as long as the memory profiler is running the system memory
1607    // reporter can make measurements.
1608    let callback = GenericCallback::new(|message| {
1609        if let Ok(request) = message {
1610            profile::system_reporter::collect_reports(request);
1611        }
1612    })
1613    .expect("Could not create memory reporter callback");
1614    new_event_loop_info
1615        .initial_script_state
1616        .memory_profiler_sender
1617        .send(ProfilerMsg::RegisterReporter(
1618            format!("system-content-{}", std::process::id()),
1619            Reporter(callback),
1620        ));
1621}