1use std::hash::Hash;
10use std::marker::PhantomData;
11use std::rc::Rc;
12
13use background_hang_monitor_api::{BackgroundHangMonitorControlMsg, HangAlert};
14use embedder_traits::ScriptToEmbedderChan;
15use layout_api::ScriptThreadFactory;
16use log::error;
17use media::WindowGLContext;
18use script_traits::{InitialScriptState, ScriptThreadMessage};
19use serde::{Deserialize, Serialize};
20use servo_base::generic_channel::{GenericReceiver, GenericSender, SendError};
21use servo_base::id::ScriptEventLoopId;
22#[cfg(feature = "multiprocess")]
23use servo_config::opts::{self, Opts};
24#[cfg(feature = "multiprocess")]
25use servo_config::prefs::{self, Preferences};
26use servo_constellation_traits::ServiceWorkerManagerFactory;
27
28use crate::Constellation;
29
30pub struct EventLoop {
32 script_chan: GenericSender<ScriptThreadMessage>,
33 id: ScriptEventLoopId,
34 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>, SendError> {
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 #[cfg(feature = "multiprocess")]
118 let event_loop = if opts::get().multiprocess {
119 Self::spawn_in_process(constellation, initial_script_state)?
120 } else {
121 Self::spawn_in_thread(constellation, initial_script_state)
122 };
123 #[cfg(not(feature = "multiprocess"))]
124 let event_loop = Self::spawn_in_thread(constellation, initial_script_state);
125
126 let event_loop = Rc::new(event_loop);
127 constellation.add_event_loop(&event_loop);
128 Ok(event_loop)
129 }
130
131 fn spawn_in_thread<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
132 constellation: &mut Constellation<STF, SWF>,
133 initial_script_state: InitialScriptState,
134 ) -> Self {
135 let script_chan = initial_script_state.constellation_to_script_sender.clone();
136 let id = initial_script_state.id;
137 let background_hang_monitor_register = constellation
138 .background_monitor_register
139 .clone()
140 .expect("Couldn't start content, no background monitor has been initiated");
141 let join_handle = STF::create(
142 initial_script_state,
143 constellation.layout_factory.clone(),
144 constellation.image_cache_factory.clone(),
145 background_hang_monitor_register,
146 );
147 constellation.add_event_loop_join_handle(join_handle);
148
149 Self {
150 script_chan,
151 id,
152 background_hang_monitor_sender: None,
153 dont_send_or_sync: PhantomData,
154 }
155 }
156
157 #[cfg(feature = "multiprocess")]
158 fn spawn_in_process<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
159 constellation: &mut Constellation<STF, SWF>,
160 initial_script_state: InitialScriptState,
161 ) -> Result<Self, SendError> {
162 let script_chan = initial_script_state.constellation_to_script_sender.clone();
163 let id = initial_script_state.id;
164
165 let (background_hand_monitor_sender, backgrond_hand_monitor_receiver) =
166 servo_base::generic_channel::channel().expect("Sampler chan");
167 let (lifeline_sender, lifeline_receiver) =
168 servo_base::generic_channel::channel().expect("Failed to create lifeline channel");
169
170 let process = crate::sandboxing::spawn_multiprocess(
171 crate::UnprivilegedContent::ScriptEventLoop(NewScriptEventLoopProcessInfo {
172 initial_script_state,
173 constellation_to_bhm_receiver: backgrond_hand_monitor_receiver,
174 bhm_to_constellation_sender: constellation.background_hang_monitor_sender.clone(),
175 lifeline_sender,
176 opts: (*opts::get()).clone(),
177 prefs: Box::new(prefs::get().clone()),
178 broken_image_icon_data: constellation.broken_image_icon_data.clone(),
179 }),
180 )?;
181
182 let crossbeam_receiver = lifeline_receiver.route_preserving_errors();
183 constellation
184 .process_manager
185 .add(crossbeam_receiver, process);
186
187 Ok(Self {
188 script_chan,
189 id,
190 background_hang_monitor_sender: Some(background_hand_monitor_sender),
191 dont_send_or_sync: PhantomData,
192 })
193 }
194
195 pub(crate) fn id(&self) -> ScriptEventLoopId {
196 self.id
197 }
198
199 pub fn send(&self, msg: ScriptThreadMessage) -> Result<(), SendError> {
201 self.script_chan.send(msg)
202 }
203
204 pub(crate) fn send_message_to_background_hang_monitor(
207 &self,
208 message: &BackgroundHangMonitorControlMsg,
209 ) {
210 if let Some(background_hang_monitor_sender) = &self.background_hang_monitor_sender &&
211 let Err(error) = background_hang_monitor_sender.send(message.clone())
212 {
213 error!("Could not send message ({message:?}) to BHM: {error}");
214 }
215 }
216}
217
218#[derive(Deserialize, Serialize)]
220#[cfg(feature = "multiprocess")]
221pub struct NewScriptEventLoopProcessInfo {
222 pub initial_script_state: InitialScriptState,
223 pub constellation_to_bhm_receiver: GenericReceiver<BackgroundHangMonitorControlMsg>,
224 pub bhm_to_constellation_sender: GenericSender<HangAlert>,
225 pub lifeline_sender: GenericSender<()>,
226 pub opts: Opts,
227 pub prefs: Box<Preferences>,
228 pub broken_image_icon_data: Vec<u8>,
230}