1use core::fmt;
6#[cfg(feature = "webgpu")]
7use std::cell::RefCell;
8use std::option::Option;
9use std::result::Result;
10
11use crossbeam_channel::{Receiver, Select, SelectedOperation, SendError, Sender};
12use devtools_traits::{DevtoolScriptControlMsg, ScriptToDevtoolsControlMsg};
13use embedder_traits::{EmbedderControlId, EmbedderControlResponse, ScriptToEmbedderChan};
14use net_traits::FetchResponseMsg;
15use net_traits::image_cache::ImageCacheResponseMessage;
16use profile_traits::mem::{self as profile_mem, OpaqueSender, ReportsChan};
17use profile_traits::time::{self as profile_time};
18use rustc_hash::FxHashSet;
19use script_traits::{Painter, ScriptThreadMessage};
20use servo_base::generic_channel::{GenericCallback, GenericSender, RoutedReceiver};
21use servo_base::id::{PipelineId, WebViewId};
22#[cfg(feature = "bluetooth")]
23use servo_bluetooth_traits::BluetoothRequest;
24use servo_constellation_traits::ScriptToConstellationMessage;
25use stylo_atoms::Atom;
26use timers::TimerScheduler;
27#[cfg(feature = "webgpu")]
28use webgpu_traits::WebGPUMsg;
29
30use crate::dom::abstractworker::WorkerScriptMsg;
31use crate::dom::bindings::trace::CustomTraceable;
32use crate::dom::csp::Violation;
33use crate::dom::dedicatedworkerglobalscope::DedicatedWorkerScriptMsg;
34use crate::dom::serviceworkerglobalscope::ServiceWorkerScriptMsg;
35use crate::dom::sharedworkerglobalscope::SharedWorkerScriptMsg;
36use crate::dom::worker::TrustedWorkerAddress;
37use crate::dom::{WorkletControl, WorkletExecutor};
38use crate::script_runtime::ScriptThreadEventCategory;
39use crate::tasks::task::TaskBox;
40use crate::tasks::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue};
41use crate::tasks::task_source::TaskSourceName;
42
43#[expect(clippy::large_enum_variant)]
44#[derive(Debug)]
45pub(crate) enum MixedMessage {
46 FromConstellation(ScriptThreadMessage),
47 FromScript(MainThreadScriptMsg),
48 FromDevtools(DevtoolScriptControlMsg),
49 FromImageCache(ImageCacheResponseMessage),
50 #[cfg(feature = "webgpu")]
51 FromWebGPUServer(WebGPUMsg),
52 TimerFired,
53}
54
55impl MixedMessage {
56 pub(crate) fn pipeline_id(&self) -> Option<PipelineId> {
57 match self {
58 MixedMessage::FromConstellation(inner_msg) => match inner_msg {
59 ScriptThreadMessage::StopDelayingLoadEventsMode(id) => Some(*id),
60 ScriptThreadMessage::SpawnPipeline(new_pipeline_info) => new_pipeline_info
61 .parent_info
62 .or(Some(new_pipeline_info.new_pipeline_id)),
63 ScriptThreadMessage::Resize(id, ..) => Some(*id),
64 ScriptThreadMessage::ThemeChange(id, ..) => Some(*id),
65 ScriptThreadMessage::ResizeInactive(id, ..) => Some(*id),
66 ScriptThreadMessage::UnloadDocument(id) => Some(*id),
67 ScriptThreadMessage::ExitPipeline(_webview_id, id, ..) => Some(*id),
68 ScriptThreadMessage::ExitScriptThread => None,
69 ScriptThreadMessage::SendInputEvent(_, id, _) => Some(*id),
70 ScriptThreadMessage::RefreshCursor(id, ..) => Some(*id),
71 ScriptThreadMessage::GetTitle(id) => Some(*id),
72 ScriptThreadMessage::GetDocumentOrigin(id, _) => Some(*id),
73 ScriptThreadMessage::SetDocumentActivity(id, ..) => Some(*id),
74 ScriptThreadMessage::SetThrottled(_, id, ..) => Some(*id),
75 ScriptThreadMessage::SetThrottledInContainingIframe(_, id, ..) => Some(*id),
76 ScriptThreadMessage::NavigateIframe(id, ..) => Some(*id),
77 ScriptThreadMessage::PostMessage { target: id, .. } => Some(*id),
78 ScriptThreadMessage::UpdatePipelineId(_, _, _, id, _) => Some(*id),
79 ScriptThreadMessage::UpdateHistoryState(id, ..) => Some(*id),
80 ScriptThreadMessage::RemoveHistoryStates(id, ..) => Some(*id),
81
82 ScriptThreadMessage::FocusDocumentAsPartOfFocusingSteps(id, ..) => Some(*id),
83 ScriptThreadMessage::UnfocusDocumentAsPartOfFocusingSteps(id, ..) => Some(*id),
84 ScriptThreadMessage::FocusDocument(id, ..) => Some(*id),
85 ScriptThreadMessage::WebDriverScriptCommand(id, ..) => Some(*id),
86 ScriptThreadMessage::TickAllAnimations(..) => None,
87 ScriptThreadMessage::WebFontLoadFinished(id, ..) => Some(*id),
88 ScriptThreadMessage::DispatchIFrameLoadEvent {
89 target: _,
90 parent: id,
91 child: _,
92 } => Some(*id),
93 ScriptThreadMessage::DispatchStorageEvent(id, ..) => Some(*id),
94 ScriptThreadMessage::ReportCSSError(id, ..) => Some(*id),
95 ScriptThreadMessage::Reload(id, ..) => Some(*id),
96 ScriptThreadMessage::PaintMetric(id, ..) => Some(*id),
97 ScriptThreadMessage::ExitFullScreen(id, ..) => Some(*id),
98 ScriptThreadMessage::MediaSessionAction(..) => None,
99 #[cfg(feature = "webgpu")]
100 ScriptThreadMessage::SetWebGPUPort(..) => None,
101 ScriptThreadMessage::SetScrollStates(id, ..) => Some(*id),
102 ScriptThreadMessage::EvaluateJavaScript(_, id, _, _) => Some(*id),
103 ScriptThreadMessage::SendImageKeysBatch(..) => None,
104 ScriptThreadMessage::PreferencesUpdated(..) => None,
105 ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(_) => None,
106 ScriptThreadMessage::ForwardKeyboardScroll(id, _) => Some(*id),
107 ScriptThreadMessage::RequestScreenshotReadiness(_, id) => Some(*id),
108 ScriptThreadMessage::EmbedderControlResponse(id, _) => Some(id.pipeline_id),
109 ScriptThreadMessage::SetUserContents(..) => None,
110 ScriptThreadMessage::DestroyUserContentManager(..) => None,
111 ScriptThreadMessage::UpdatePinchZoomInfos(id, _) => Some(*id),
112 ScriptThreadMessage::SetAccessibilityActive(..) => None,
113 ScriptThreadMessage::TriggerGarbageCollection => None,
114 },
115 MixedMessage::FromScript(inner_msg) => match inner_msg {
116 MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, _, pipeline_id, _)) => {
117 *pipeline_id
118 },
119 MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(_)) => None,
120 MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
121 pipeline_id,
122 _,
123 )) => Some(*pipeline_id),
124 MainThreadScriptMsg::NavigationResponse { pipeline_id, .. } => Some(*pipeline_id),
125 MainThreadScriptMsg::WorkletLoaded(pipeline_id) => Some(*pipeline_id),
126 MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id, .. } => Some(*pipeline_id),
127 MainThreadScriptMsg::Inactive => None,
128 MainThreadScriptMsg::WakeUp => None,
129 MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
130 control_id,
131 ..,
132 ) => Some(control_id.pipeline_id),
133 },
134 MixedMessage::FromImageCache(response) => match response {
135 ImageCacheResponseMessage::NotifyPendingImageLoadStatus(response) => {
136 Some(response.pipeline_id)
137 },
138 ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
139 Some(response.pipeline_id)
140 },
141 },
142 MixedMessage::FromDevtools(_) | MixedMessage::TimerFired => None,
143 #[cfg(feature = "webgpu")]
144 MixedMessage::FromWebGPUServer(..) => None,
145 }
146 }
147}
148
149#[derive(Debug)]
151pub(crate) enum MainThreadScriptMsg {
152 Common(CommonScriptMsg),
154 WorkletLoaded(PipelineId),
157 NavigationResponse {
158 pipeline_id: PipelineId,
159 message: Box<FetchResponseMsg>,
160 },
161 RegisterPaintWorklet {
163 pipeline_id: PipelineId,
164 name: Atom,
165 properties: Vec<Atom>,
166 painter: Box<dyn Painter>,
167 },
168 Inactive,
170 WakeUp,
172 ForwardEmbedderControlResponseFromFileManager(EmbedderControlId, EmbedderControlResponse),
175}
176
177pub(crate) enum CommonScriptMsg {
180 CollectReports(ReportsChan),
183 Task(
185 ScriptThreadEventCategory,
186 Box<dyn TaskBox>,
187 Option<PipelineId>,
188 TaskSourceName,
189 ),
190 ReportCspViolations(PipelineId, Vec<Violation>),
192}
193
194impl fmt::Debug for CommonScriptMsg {
195 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
196 match *self {
197 CommonScriptMsg::CollectReports(_) => write!(f, "CollectReports(...)"),
198 CommonScriptMsg::Task(ref category, ref task, _, _) => {
199 f.debug_tuple("Task").field(category).field(task).finish()
200 },
201 CommonScriptMsg::ReportCspViolations(..) => write!(f, "ReportCspViolations(...)"),
202 }
203 }
204}
205
206#[derive(Clone, JSTraceable, MallocSizeOf)]
210pub(crate) enum ScriptEventLoopSender {
211 MainThread(Sender<MainThreadScriptMsg>),
213 SharedWorker(Sender<SharedWorkerScriptMsg>),
215 ServiceWorker(Sender<ServiceWorkerScriptMsg>),
217 Worklet(WorkletExecutor),
219 DedicatedWorker {
223 sender: Sender<DedicatedWorkerScriptMsg>,
224 main_thread_worker: TrustedWorkerAddress,
225 },
226}
227
228impl ScriptEventLoopSender {
229 pub(crate) fn send(&self, message: CommonScriptMsg) -> Result<(), SendError<()>> {
231 match self {
232 Self::MainThread(sender) => sender
233 .send(MainThreadScriptMsg::Common(message))
234 .map_err(|_| SendError(())),
235 Self::SharedWorker(sender) => sender
236 .send(SharedWorkerScriptMsg::CommonWorker(
237 WorkerScriptMsg::Common(message),
238 ))
239 .map_err(|_| SendError(())),
240 Self::ServiceWorker(sender) => sender
241 .send(ServiceWorkerScriptMsg::CommonWorker(
242 WorkerScriptMsg::Common(message),
243 ))
244 .map_err(|_| SendError(())),
245 Self::DedicatedWorker {
246 sender,
247 main_thread_worker,
248 } => {
249 let common_message = WorkerScriptMsg::Common(message);
250 sender
251 .send(DedicatedWorkerScriptMsg::CommonWorker(
252 main_thread_worker.clone(),
253 common_message,
254 ))
255 .map_err(|_| SendError(()))
256 },
257 Self::Worklet(executor) => {
258 executor.send_control_message(WorkletControl::Common(message))
259 },
260 }
261 }
262}
263
264pub(crate) enum ScriptEventLoopReceiver {
268 MainThread(Receiver<MainThreadScriptMsg>),
270 SharedWorker(Receiver<SharedWorkerScriptMsg>),
272 DedicatedWorker(Receiver<DedicatedWorkerScriptMsg>),
274}
275
276impl ScriptEventLoopReceiver {
277 pub(crate) fn recv(&self) -> Result<CommonScriptMsg, ()> {
278 match self {
279 Self::MainThread(receiver) => match receiver.recv() {
280 Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg),
281 Ok(_) => panic!("unexpected main thread event message!"),
282 Err(_) => Err(()),
283 },
284 Self::SharedWorker(receiver) => match receiver.recv() {
285 Ok(SharedWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(message))) => {
286 Ok(message)
287 },
288 Ok(_) => panic!("unexpected shared worker event message!"),
289 Err(_) => Err(()),
290 },
291 Self::DedicatedWorker(receiver) => match receiver.recv() {
292 Ok(DedicatedWorkerScriptMsg::CommonWorker(_, WorkerScriptMsg::Common(message))) => {
293 Ok(message)
294 },
295 Ok(_) => panic!("unexpected worker event message!"),
296 Err(_) => Err(()),
297 },
298 }
299 }
300}
301
302impl QueuedTaskConversion for MainThreadScriptMsg {
303 fn task_source_name(&self) -> Option<&TaskSourceName> {
304 let script_msg = match self {
305 MainThreadScriptMsg::Common(script_msg) => script_msg,
306 _ => return None,
307 };
308 match script_msg {
309 CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => {
310 Some(task_source)
311 },
312 _ => None,
313 }
314 }
315
316 fn pipeline_id(&self) -> Option<PipelineId> {
317 let script_msg = match self {
318 MainThreadScriptMsg::Common(script_msg) => script_msg,
319 _ => return None,
320 };
321 match script_msg {
322 CommonScriptMsg::Task(_category, _boxed, pipeline_id, _task_source) => *pipeline_id,
323 _ => None,
324 }
325 }
326
327 fn into_queued_task(self) -> Option<QueuedTask> {
328 let script_msg = match self {
329 MainThreadScriptMsg::Common(script_msg) => script_msg,
330 _ => return None,
331 };
332 let (event_category, task, pipeline_id, task_source) = match script_msg {
333 CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => {
334 (category, boxed, pipeline_id, task_source)
335 },
336 _ => return None,
337 };
338 Some(QueuedTask {
339 worker: None,
340 event_category,
341 task,
342 pipeline_id,
343 task_source,
344 })
345 }
346
347 fn from_queued_task(queued_task: QueuedTask) -> Self {
348 let script_msg = CommonScriptMsg::Task(
349 queued_task.event_category,
350 queued_task.task,
351 queued_task.pipeline_id,
352 queued_task.task_source,
353 );
354 MainThreadScriptMsg::Common(script_msg)
355 }
356
357 fn inactive_msg() -> Self {
358 MainThreadScriptMsg::Inactive
359 }
360
361 fn wake_up_msg() -> Self {
362 MainThreadScriptMsg::WakeUp
363 }
364
365 fn is_wake_up(&self) -> bool {
366 matches!(self, MainThreadScriptMsg::WakeUp)
367 }
368}
369
370impl OpaqueSender<CommonScriptMsg> for ScriptEventLoopSender {
371 fn send(&self, message: CommonScriptMsg) {
372 self.send(message).unwrap()
373 }
374}
375
376#[derive(Clone, JSTraceable)]
377pub(crate) struct ScriptThreadSenders {
378 pub(crate) self_sender: Sender<MainThreadScriptMsg>,
381
382 #[no_trace]
384 #[cfg(feature = "bluetooth")]
385 pub(crate) bluetooth_sender: GenericSender<BluetoothRequest>,
386
387 #[no_trace]
389 pub(crate) constellation_sender: GenericSender<ScriptThreadMessage>,
390
391 #[no_trace]
394 pub(crate) pipeline_to_constellation_sender:
395 GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
396
397 #[no_trace]
399 pub(crate) pipeline_to_embedder_sender: ScriptToEmbedderChan,
400
401 #[no_trace]
404 pub(crate) image_cache_sender: Sender<ImageCacheResponseMessage>,
405
406 #[no_trace]
408 pub(crate) time_profiler_sender: profile_time::ProfilerChan,
409
410 #[no_trace]
412 pub(crate) memory_profiler_sender: profile_mem::ProfilerChan,
413
414 #[no_trace]
416 pub(crate) devtools_server_sender: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
417
418 #[no_trace]
419 pub(crate) devtools_client_to_script_thread_sender: GenericSender<DevtoolScriptControlMsg>,
420}
421
422#[derive(JSTraceable)]
423pub(crate) struct ScriptThreadReceivers {
424 #[no_trace]
426 pub(crate) constellation_receiver: RoutedReceiver<ScriptThreadMessage>,
427
428 #[no_trace]
430 pub(crate) image_cache_receiver: Receiver<ImageCacheResponseMessage>,
431
432 #[no_trace]
435 pub(crate) devtools_server_receiver: RoutedReceiver<DevtoolScriptControlMsg>,
436
437 #[no_trace]
440 #[cfg(feature = "webgpu")]
441 pub(crate) webgpu_receiver: RefCell<RoutedReceiver<WebGPUMsg>>,
442}
443
444impl ScriptThreadReceivers {
445 pub(crate) fn recv(
448 &self,
449 task_queue: &TaskQueue<MainThreadScriptMsg>,
450 timer_scheduler: &TimerScheduler,
451 fully_active: &FxHashSet<PipelineId>,
452 ) -> MixedMessage {
453 let mut select = Select::new();
454
455 let task_recv = task_queue.select();
456 let task_index = select.recv(task_recv);
457 let constellation_index = select.recv(&self.constellation_receiver);
458 let devtools_index = select.recv(&self.devtools_server_receiver);
459 let image_cache_index = select.recv(&self.image_cache_receiver);
460
461 #[cfg(feature = "webgpu")]
462 let webgpu_receiver = self.webgpu_receiver.borrow();
463 #[cfg(feature = "webgpu")]
464 let webgpu_index = select.recv(&*webgpu_receiver);
465
466 let message_from_operation = |operation: SelectedOperation| {
467 let index = operation.index();
468 if index == task_index {
469 let msg = operation.recv(task_recv).unwrap();
470 task_queue.take_tasks(msg, fully_active);
471 let event = task_queue.recv().expect(
472 "Spurious wake-up of the event-loop, task-queue has no tasks available",
473 );
474 MixedMessage::FromScript(event)
475 } else if index == constellation_index {
476 MixedMessage::FromConstellation(
477 operation
478 .recv(&self.constellation_receiver)
479 .unwrap()
480 .unwrap(),
481 )
482 } else if index == devtools_index {
483 MixedMessage::FromDevtools(
484 operation
485 .recv(&self.devtools_server_receiver)
486 .unwrap()
487 .unwrap(),
488 )
489 } else if index == image_cache_index {
490 MixedMessage::FromImageCache(operation.recv(&self.image_cache_receiver).unwrap())
491 } else {
492 #[cfg(feature = "webgpu")]
493 {
494 debug_assert_eq!(index, webgpu_index);
495 MixedMessage::FromWebGPUServer(
496 operation.recv(&*webgpu_receiver).unwrap().unwrap(),
497 )
498 }
499 #[cfg(not(feature = "webgpu"))]
500 unreachable!("select returned an unknown index {index}")
501 }
502 };
503
504 if let Some(deadline) = timer_scheduler.next_deadline() {
505 select
506 .select_deadline(deadline)
507 .map(message_from_operation)
508 .unwrap_or(MixedMessage::TimerFired)
509 } else {
510 message_from_operation(select.select())
511 }
512 }
513
514 pub(crate) fn try_recv(
517 &self,
518 task_queue: &TaskQueue<MainThreadScriptMsg>,
519 fully_active: &FxHashSet<PipelineId>,
520 ) -> Option<MixedMessage> {
521 if let Ok(message) = self.constellation_receiver.try_recv() {
522 let message = message
523 .inspect_err(|e| {
524 log::warn!(
525 "ScriptThreadReceivers IPC error on constellation_receiver: {:?}",
526 e
527 );
528 })
529 .ok()?;
530 return MixedMessage::FromConstellation(message).into();
531 }
532 if let Ok(message) = task_queue.take_tasks_and_recv(fully_active) {
533 return MixedMessage::FromScript(message).into();
534 }
535 if let Ok(message) = self.devtools_server_receiver.try_recv() {
536 return MixedMessage::FromDevtools(message.unwrap()).into();
537 }
538 if let Ok(message) = self.image_cache_receiver.try_recv() {
539 return MixedMessage::FromImageCache(message).into();
540 }
541 #[cfg(feature = "webgpu")]
542 if let Ok(message) = self.webgpu_receiver.borrow().try_recv() {
543 return MixedMessage::FromWebGPUServer(message.unwrap()).into();
544 }
545 None
546 }
547}