Skip to main content

servo_constellation/
event_loop.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//! This module contains the `EventLoop` type, which is the constellation's
6//! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread`
7//! message is sent to the script thread, asking it to shut down.
8
9use std::hash::Hash;
10use std::marker::PhantomData;
11use std::rc::Rc;
12
13use background_hang_monitor_api::{BackgroundHangMonitorControlMsg, HangAlert};
14use embedder_traits::ScriptToEmbedderChan;
15use ipc_channel::IpcError;
16use layout_api::ScriptThreadFactory;
17use log::error;
18use media::WindowGLContext;
19use script_traits::{InitialScriptState, ScriptThreadMessage};
20use serde::{Deserialize, Serialize};
21use servo_base::generic_channel::{self, GenericReceiver, GenericSender, SendError};
22use servo_base::id::ScriptEventLoopId;
23use servo_config::opts::{self, Opts};
24use servo_config::prefs::{self, Preferences};
25use servo_constellation_traits::ServiceWorkerManagerFactory;
26
27use crate::sandboxing::spawn_multiprocess;
28use crate::{Constellation, UnprivilegedContent};
29
30/// <https://html.spec.whatwg.org/multipage/#event-loop>
31pub struct EventLoop {
32    script_chan: GenericSender<ScriptThreadMessage>,
33    id: ScriptEventLoopId,
34    /// When running in another process, this is an `IpcSender` to the BackgroundHangMonitor
35    /// on the other side of the process boundary. When running in the same process, the
36    /// BackgroundHangMonitor is shared among all [`EventLoop`]s so this will be `None`.
37    background_hang_monitor_sender: Option<GenericSender<BackgroundHangMonitorControlMsg>>,
38    dont_send_or_sync: PhantomData<Rc<()>>,
39}
40
41impl PartialEq for EventLoop {
42    fn eq(&self, other: &Self) -> bool {
43        self.id == other.id
44    }
45}
46
47impl Eq for EventLoop {}
48
49impl Hash for EventLoop {
50    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
51        self.id.hash(state);
52    }
53}
54
55impl Drop for EventLoop {
56    fn drop(&mut self) {
57        self.send_message_to_background_hang_monitor(&BackgroundHangMonitorControlMsg::Exit);
58
59        if let Err(error) = self.script_chan.send(ScriptThreadMessage::ExitScriptThread) {
60            error!("Did not successfully request EventLoop exit: {error}");
61        }
62    }
63}
64
65impl EventLoop {
66    pub(crate) fn spawn<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
67        constellation: &mut Constellation<STF, SWF>,
68        is_private: bool,
69    ) -> Result<Rc<Self>, IpcError> {
70        let (script_chan, script_port) =
71            servo_base::generic_channel::channel().expect("Pipeline script chan");
72
73        let embedder_chan = constellation.embedder_proxy.sender.clone();
74        let eventloop_waker = constellation.embedder_proxy.event_loop_waker.clone();
75        let script_to_embedder_sender = ScriptToEmbedderChan::new(embedder_chan, eventloop_waker);
76
77        let resource_threads = if is_private {
78            constellation.private_resource_threads.clone()
79        } else {
80            constellation.public_resource_threads.clone()
81        };
82        let storage_threads = if is_private {
83            constellation.private_storage_threads.clone()
84        } else {
85            constellation.public_storage_threads.clone()
86        };
87
88        let event_loop_id = ScriptEventLoopId::new();
89        let initial_script_state = InitialScriptState {
90            id: event_loop_id,
91            script_to_constellation_sender: constellation.script_sender.clone(),
92            script_to_embedder_sender,
93            namespace_request_sender: constellation.namespace_ipc_sender.clone(),
94            devtools_server_sender: constellation.script_to_devtools_callback(),
95            #[cfg(feature = "bluetooth")]
96            bluetooth_sender: constellation.bluetooth_ipc_sender.clone(),
97            system_font_service: constellation.system_font_service.to_sender(),
98            resource_threads,
99            storage_threads,
100            time_profiler_sender: constellation.time_profiler_chan.clone(),
101            memory_profiler_sender: constellation.mem_profiler_chan.clone(),
102            constellation_to_script_sender: script_chan,
103            constellation_to_script_receiver: script_port,
104            pipeline_namespace_id: constellation.next_pipeline_namespace_id(),
105            cross_process_paint_api: constellation.paint_proxy.cross_process_paint_api.clone(),
106            #[cfg(feature = "webgl")]
107            webgl_chan: constellation
108                .webgl_threads
109                .as_ref()
110                .map(|threads| threads.pipeline()),
111            webxr_registry: constellation.webxr_registry.clone(),
112            player_context: WindowGLContext::get(),
113            privileged_urls: constellation.privileged_urls.clone(),
114            user_contents_for_manager_id: constellation.user_contents_for_manager_id.clone(),
115        };
116
117        let event_loop = if opts::get().multiprocess {
118            Self::spawn_in_process(constellation, initial_script_state)?
119        } else {
120            Self::spawn_in_thread(constellation, initial_script_state)
121        };
122
123        let event_loop = Rc::new(event_loop);
124        constellation.add_event_loop(&event_loop);
125        Ok(event_loop)
126    }
127
128    fn spawn_in_thread<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
129        constellation: &mut Constellation<STF, SWF>,
130        initial_script_state: InitialScriptState,
131    ) -> Self {
132        let script_chan = initial_script_state.constellation_to_script_sender.clone();
133        let id = initial_script_state.id;
134        let background_hang_monitor_register = constellation
135            .background_monitor_register
136            .clone()
137            .expect("Couldn't start content, no background monitor has been initiated");
138        let join_handle = STF::create(
139            initial_script_state,
140            constellation.layout_factory.clone(),
141            constellation.image_cache_factory.clone(),
142            background_hang_monitor_register,
143        );
144        constellation.add_event_loop_join_handle(join_handle);
145
146        Self {
147            script_chan,
148            id,
149            background_hang_monitor_sender: None,
150            dont_send_or_sync: PhantomData,
151        }
152    }
153
154    fn spawn_in_process<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
155        constellation: &mut Constellation<STF, SWF>,
156        initial_script_state: InitialScriptState,
157    ) -> Result<Self, IpcError> {
158        let script_chan = initial_script_state.constellation_to_script_sender.clone();
159        let id = initial_script_state.id;
160
161        let (background_hand_monitor_sender, backgrond_hand_monitor_receiver) =
162            generic_channel::channel().expect("Sampler chan");
163        let (lifeline_sender, lifeline_receiver) =
164            generic_channel::channel().expect("Failed to create lifeline channel");
165
166        let process = spawn_multiprocess(UnprivilegedContent::ScriptEventLoop(
167            NewScriptEventLoopProcessInfo {
168                initial_script_state,
169                constellation_to_bhm_receiver: backgrond_hand_monitor_receiver,
170                bhm_to_constellation_sender: constellation.background_hang_monitor_sender.clone(),
171                lifeline_sender,
172                opts: (*opts::get()).clone(),
173                prefs: Box::new(prefs::get().clone()),
174                broken_image_icon_data: constellation.broken_image_icon_data.clone(),
175            },
176        ))?;
177
178        let crossbeam_receiver = lifeline_receiver.route_preserving_errors();
179        constellation
180            .process_manager
181            .add(crossbeam_receiver, process);
182
183        Ok(Self {
184            script_chan,
185            id,
186            background_hang_monitor_sender: Some(background_hand_monitor_sender),
187            dont_send_or_sync: PhantomData,
188        })
189    }
190
191    pub(crate) fn id(&self) -> ScriptEventLoopId {
192        self.id
193    }
194
195    /// Send a message to the event loop.
196    pub fn send(&self, msg: ScriptThreadMessage) -> Result<(), SendError> {
197        self.script_chan.send(msg)
198    }
199
200    /// If this is [`EventLoop`] is in another process, send a message to its `BackgroundHangMonitor`,
201    /// otherwise do nothing.
202    pub(crate) fn send_message_to_background_hang_monitor(
203        &self,
204        message: &BackgroundHangMonitorControlMsg,
205    ) {
206        if let Some(background_hang_monitor_sender) = &self.background_hang_monitor_sender &&
207            let Err(error) = background_hang_monitor_sender.send(message.clone())
208        {
209            error!("Could not send message ({message:?}) to BHM: {error}");
210        }
211    }
212}
213
214/// All of the information necessary to create a new script [`EventLoop`] in a new process.
215#[derive(Deserialize, Serialize)]
216pub struct NewScriptEventLoopProcessInfo {
217    pub initial_script_state: InitialScriptState,
218    pub constellation_to_bhm_receiver: GenericReceiver<BackgroundHangMonitorControlMsg>,
219    pub bhm_to_constellation_sender: GenericSender<HangAlert>,
220    pub lifeline_sender: GenericSender<()>,
221    pub opts: Opts,
222    pub prefs: Box<Preferences>,
223    /// The broken image icon data that is used to create an image to show in place of broken images.
224    pub broken_image_icon_data: Vec<u8>,
225}