1use std::marker::PhantomData;
10use std::rc::Rc;
11
12use background_hang_monitor_api::{BackgroundHangMonitorControlMsg, HangAlert};
13use embedder_traits::ScriptToEmbedderChan;
14#[cfg(feature = "multiprocess")]
15use embedder_traits::resources::ResourceBytes;
16use layout_api::ScriptThreadFactory;
17use log::error;
18use media::WindowGLContext;
19use script_traits::{InitialScriptState, ScriptThreadMessage};
20use serde::{Deserialize, Serialize};
21use servo_base::generic_channel::{GenericReceiver, GenericSender, SendError};
22use servo_base::id::ScriptEventLoopId;
23#[cfg(feature = "multiprocess")]
24use servo_config::opts::{self, Opts};
25#[cfg(feature = "multiprocess")]
26use servo_config::prefs::{self, Preferences};
27use servo_constellation_traits::ServiceWorkerManagerFactory;
28
29use crate::Constellation;
30
31pub struct EventLoop {
33 script_chan: GenericSender<ScriptThreadMessage>,
34 id: ScriptEventLoopId,
35 background_hang_monitor_sender: Option<GenericSender<BackgroundHangMonitorControlMsg>>,
39 dont_send_or_sync: PhantomData<Rc<()>>,
40}
41
42impl Drop for EventLoop {
43 fn drop(&mut self) {
44 self.send_message_to_background_hang_monitor(&BackgroundHangMonitorControlMsg::Exit);
45
46 if let Err(error) = self.script_chan.send(ScriptThreadMessage::ExitScriptThread) {
47 error!("Did not successfully request EventLoop exit: {error}");
48 }
49 }
50}
51
52impl EventLoop {
53 pub(crate) fn spawn<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
54 constellation: &mut Constellation<STF, SWF>,
55 is_private: bool,
56 ) -> Result<Rc<Self>, SendError> {
57 let (script_chan, script_port) =
58 servo_base::generic_channel::channel().expect("Pipeline script chan");
59
60 let embedder_chan = constellation.embedder_proxy.sender.clone();
61 let eventloop_waker = constellation.embedder_proxy.event_loop_waker.clone();
62 let script_to_embedder_sender = ScriptToEmbedderChan::new(embedder_chan, eventloop_waker);
63
64 let resource_threads = if is_private {
65 constellation.private_resource_threads.clone()
66 } else {
67 constellation.public_resource_threads.clone()
68 };
69 let storage_threads = if is_private {
70 constellation.private_storage_threads.clone()
71 } else {
72 constellation.public_storage_threads.clone()
73 };
74
75 let event_loop_id = ScriptEventLoopId::new();
76 let initial_script_state = InitialScriptState {
77 id: event_loop_id,
78 script_to_constellation_sender: constellation.script_sender.clone(),
79 script_to_embedder_sender,
80 namespace_request_sender: constellation.namespace_ipc_sender.clone(),
81 #[cfg(feature = "devtools")]
82 devtools_server_sender: constellation.script_to_devtools_callback(),
83 #[cfg(feature = "bluetooth")]
84 bluetooth_sender: constellation.bluetooth_ipc_sender.clone(),
85 system_font_service: constellation.system_font_service.to_sender(),
86 resource_threads,
87 storage_threads,
88 time_profiler_sender: constellation.time_profiler_chan.clone(),
89 memory_profiler_sender: constellation.mem_profiler_chan.clone(),
90 constellation_to_script_sender: script_chan,
91 constellation_to_script_receiver: script_port,
92 pipeline_namespace_id: constellation.next_pipeline_namespace_id(),
93 cross_process_paint_api: constellation.paint_proxy.cross_process_paint_api.clone(),
94 #[cfg(feature = "webgl")]
95 webgl_chan: constellation
96 .webgl_threads
97 .as_ref()
98 .map(|threads| threads.pipeline()),
99 webxr_registry: constellation.webxr_registry.clone(),
100 player_context: WindowGLContext::get(),
101 privileged_urls: constellation.privileged_urls.clone(),
102 user_contents_for_manager_id: constellation.user_contents_for_manager_id.clone(),
103 online: constellation.online(),
104 };
105
106 #[cfg(feature = "multiprocess")]
107 let event_loop = if opts::get().multiprocess {
108 Self::spawn_in_process(constellation, initial_script_state)?
109 } else {
110 Self::spawn_in_thread(constellation, initial_script_state)
111 };
112 #[cfg(not(feature = "multiprocess"))]
113 let event_loop = Self::spawn_in_thread(constellation, initial_script_state);
114
115 let event_loop = Rc::new(event_loop);
116 constellation.add_event_loop(&event_loop);
117 Ok(event_loop)
118 }
119
120 fn spawn_in_thread<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
121 constellation: &mut Constellation<STF, SWF>,
122 initial_script_state: InitialScriptState,
123 ) -> Self {
124 let script_chan = initial_script_state.constellation_to_script_sender.clone();
125 let id = initial_script_state.id;
126 let background_hang_monitor_register = constellation
127 .background_monitor_register
128 .clone()
129 .expect("Couldn't start content, no background monitor has been initiated");
130 let join_handle = STF::create(
131 initial_script_state,
132 constellation.layout_factory.clone(),
133 constellation.image_cache_factory.clone(),
134 background_hang_monitor_register,
135 );
136 constellation.add_event_loop_join_handle(join_handle);
137
138 Self {
139 script_chan,
140 id,
141 background_hang_monitor_sender: None,
142 dont_send_or_sync: PhantomData,
143 }
144 }
145
146 #[cfg(feature = "multiprocess")]
147 fn spawn_in_process<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
148 constellation: &mut Constellation<STF, SWF>,
149 initial_script_state: InitialScriptState,
150 ) -> Result<Self, SendError> {
151 let script_chan = initial_script_state.constellation_to_script_sender.clone();
152 let id = initial_script_state.id;
153
154 let (background_hand_monitor_sender, backgrond_hand_monitor_receiver) =
155 servo_base::generic_channel::channel().expect("Sampler chan");
156 let (lifeline_sender, lifeline_receiver) =
157 servo_base::generic_channel::channel().expect("Failed to create lifeline channel");
158
159 let process = crate::sandboxing::spawn_multiprocess(
160 crate::UnprivilegedContent::ScriptEventLoop(NewScriptEventLoopProcessInfo {
161 initial_script_state,
162 constellation_to_bhm_receiver: backgrond_hand_monitor_receiver,
163 bhm_to_constellation_sender: constellation.background_hang_monitor_sender.clone(),
164 lifeline_sender,
165 opts: (*opts::get()).clone(),
166 prefs: Box::new(prefs::get().clone()),
167 broken_image_icon_data: constellation.broken_image_icon_data.clone(),
168 }),
169 )?;
170
171 let crossbeam_receiver = lifeline_receiver.route_preserving_errors();
172 constellation
173 .process_manager
174 .add(crossbeam_receiver, process);
175
176 Ok(Self {
177 script_chan,
178 id,
179 background_hang_monitor_sender: Some(background_hand_monitor_sender),
180 dont_send_or_sync: PhantomData,
181 })
182 }
183
184 pub(crate) fn id(&self) -> ScriptEventLoopId {
185 self.id
186 }
187
188 pub fn send(&self, msg: ScriptThreadMessage) -> Result<(), SendError> {
190 self.script_chan.send(msg)
191 }
192
193 pub(crate) fn send_message_to_background_hang_monitor(
196 &self,
197 message: &BackgroundHangMonitorControlMsg,
198 ) {
199 if let Some(background_hang_monitor_sender) = &self.background_hang_monitor_sender &&
200 let Err(error) = background_hang_monitor_sender.send(message.clone())
201 {
202 error!("Could not send message ({message:?}) to BHM: {error}");
203 }
204 }
205}
206
207#[derive(Deserialize, Serialize)]
209#[cfg(feature = "multiprocess")]
210pub struct NewScriptEventLoopProcessInfo {
211 pub initial_script_state: InitialScriptState,
212 pub constellation_to_bhm_receiver: GenericReceiver<BackgroundHangMonitorControlMsg>,
213 pub bhm_to_constellation_sender: GenericSender<HangAlert>,
214 pub lifeline_sender: GenericSender<()>,
215 pub opts: Opts,
216 pub prefs: Box<Preferences>,
217 pub broken_image_icon_data: ResourceBytes,
219}