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::runtime::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::GetInternalAncestorOriginObjectsList(id, _) => Some(*id),
74 ScriptThreadMessage::SetDocumentActivity(id, ..) => Some(*id),
75 ScriptThreadMessage::SetThrottled(_, id, ..) => Some(*id),
76 ScriptThreadMessage::SetThrottledInContainingIframe(_, id, ..) => Some(*id),
77 ScriptThreadMessage::NavigateIframe(id, ..) => Some(*id),
78 ScriptThreadMessage::PostMessage { target: id, .. } => Some(*id),
79 ScriptThreadMessage::UpdatePipelineId(_, _, _, id, _) => Some(*id),
80 ScriptThreadMessage::UpdateHistoryState(id, ..) => Some(*id),
81 ScriptThreadMessage::RemoveHistoryStates(id, ..) => Some(*id),
82
83 ScriptThreadMessage::FocusDocumentAsPartOfFocusingSteps(id, ..) => Some(*id),
84 ScriptThreadMessage::UnfocusDocumentAsPartOfFocusingSteps(id, ..) => Some(*id),
85 ScriptThreadMessage::FocusDocument(id, ..) => Some(*id),
86 ScriptThreadMessage::WebDriverScriptCommand(id, ..) => Some(*id),
87 ScriptThreadMessage::TickAllAnimations(..) => None,
88 ScriptThreadMessage::WebFontLoadFinished(id, ..) => Some(*id),
89 ScriptThreadMessage::DispatchIFrameLoadEvent {
90 target: _,
91 parent: id,
92 child: _,
93 } => Some(*id),
94 ScriptThreadMessage::DispatchStorageEvent(id, ..) => Some(*id),
95 ScriptThreadMessage::ReportCSSError(id, ..) => Some(*id),
96 ScriptThreadMessage::Reload(id, ..) => Some(*id),
97 ScriptThreadMessage::PaintMetric(id, ..) => Some(*id),
98 ScriptThreadMessage::ExitFullScreen(id, ..) => Some(*id),
99 ScriptThreadMessage::MediaSessionAction(..) => None,
100 #[cfg(feature = "webgpu")]
101 ScriptThreadMessage::SetWebGPUPort(..) => None,
102 ScriptThreadMessage::SetScrollStates(id, ..) => Some(*id),
103 ScriptThreadMessage::EvaluateJavaScript(_, id, _, _) => Some(*id),
104 ScriptThreadMessage::SendImageKeysBatch(..) => None,
105 ScriptThreadMessage::PreferencesUpdated(..) => None,
106 ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(_) => None,
107 ScriptThreadMessage::ForwardKeyboardScroll(id, _) => Some(*id),
108 ScriptThreadMessage::RequestScreenshotReadiness(_, id) => Some(*id),
109 ScriptThreadMessage::EmbedderControlResponse(id, _) => Some(id.pipeline_id),
110 ScriptThreadMessage::SetUserContents(..) => None,
111 ScriptThreadMessage::DestroyUserContentManager(..) => None,
112 ScriptThreadMessage::UpdatePinchZoomInfos(id, _) => Some(*id),
113 ScriptThreadMessage::SetAccessibilityActive(..) => None,
114 ScriptThreadMessage::TriggerGarbageCollection => None,
115 },
116 MixedMessage::FromScript(inner_msg) => match inner_msg {
117 MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, _, pipeline_id, _)) => {
118 *pipeline_id
119 },
120 MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(_)) => None,
121 MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
122 pipeline_id,
123 _,
124 )) => Some(*pipeline_id),
125 MainThreadScriptMsg::NavigationResponse { pipeline_id, .. } => Some(*pipeline_id),
126 MainThreadScriptMsg::WorkletLoaded(pipeline_id) => Some(*pipeline_id),
127 MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id, .. } => Some(*pipeline_id),
128 MainThreadScriptMsg::Inactive => None,
129 MainThreadScriptMsg::WakeUp => None,
130 MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
131 control_id,
132 ..,
133 ) => Some(control_id.pipeline_id),
134 },
135 MixedMessage::FromImageCache(response) => match response {
136 ImageCacheResponseMessage::NotifyPendingImageLoadStatus(response) => {
137 Some(response.pipeline_id)
138 },
139 ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
140 Some(response.pipeline_id)
141 },
142 },
143 MixedMessage::FromDevtools(_) | MixedMessage::TimerFired => None,
144 #[cfg(feature = "webgpu")]
145 MixedMessage::FromWebGPUServer(..) => None,
146 }
147 }
148}
149
150#[derive(Debug)]
152pub(crate) enum MainThreadScriptMsg {
153 Common(CommonScriptMsg),
155 WorkletLoaded(PipelineId),
158 NavigationResponse {
159 pipeline_id: PipelineId,
160 message: Box<FetchResponseMsg>,
161 },
162 RegisterPaintWorklet {
164 pipeline_id: PipelineId,
165 name: Atom,
166 properties: Vec<Atom>,
167 painter: Box<dyn Painter>,
168 },
169 Inactive,
171 WakeUp,
173 ForwardEmbedderControlResponseFromFileManager(EmbedderControlId, EmbedderControlResponse),
176}
177
178pub(crate) enum CommonScriptMsg {
181 CollectReports(ReportsChan),
184 Task(
186 ScriptThreadEventCategory,
187 Box<dyn TaskBox>,
188 Option<PipelineId>,
189 TaskSourceName,
190 ),
191 ReportCspViolations(PipelineId, Vec<Violation>),
193}
194
195impl fmt::Debug for CommonScriptMsg {
196 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
197 match *self {
198 CommonScriptMsg::CollectReports(_) => write!(f, "CollectReports(...)"),
199 CommonScriptMsg::Task(ref category, ref task, _, _) => {
200 f.debug_tuple("Task").field(category).field(task).finish()
201 },
202 CommonScriptMsg::ReportCspViolations(..) => write!(f, "ReportCspViolations(...)"),
203 }
204 }
205}
206
207#[derive(Clone, JSTraceable, MallocSizeOf)]
211pub(crate) enum ScriptEventLoopSender {
212 MainThread(Sender<MainThreadScriptMsg>),
214 SharedWorker(Sender<SharedWorkerScriptMsg>),
216 ServiceWorker(Sender<ServiceWorkerScriptMsg>),
218 Worklet(WorkletExecutor),
220 DedicatedWorker {
224 sender: Sender<DedicatedWorkerScriptMsg>,
225 main_thread_worker: TrustedWorkerAddress,
226 },
227}
228
229impl ScriptEventLoopSender {
230 pub(crate) fn send(&self, message: CommonScriptMsg) -> Result<(), SendError<()>> {
232 match self {
233 Self::MainThread(sender) => sender
234 .send(MainThreadScriptMsg::Common(message))
235 .map_err(|_| SendError(())),
236 Self::SharedWorker(sender) => sender
237 .send(SharedWorkerScriptMsg::CommonWorker(
238 WorkerScriptMsg::Common(message),
239 ))
240 .map_err(|_| SendError(())),
241 Self::ServiceWorker(sender) => sender
242 .send(ServiceWorkerScriptMsg::CommonWorker(
243 WorkerScriptMsg::Common(message),
244 ))
245 .map_err(|_| SendError(())),
246 Self::DedicatedWorker {
247 sender,
248 main_thread_worker,
249 } => {
250 let common_message = WorkerScriptMsg::Common(message);
251 sender
252 .send(DedicatedWorkerScriptMsg::CommonWorker(
253 main_thread_worker.clone(),
254 common_message,
255 ))
256 .map_err(|_| SendError(()))
257 },
258 Self::Worklet(executor) => {
259 executor.send_control_message(WorkletControl::Common(message))
260 },
261 }
262 }
263}
264
265pub(crate) enum ScriptEventLoopReceiver {
269 MainThread(Receiver<MainThreadScriptMsg>),
271 SharedWorker(Receiver<SharedWorkerScriptMsg>),
273 DedicatedWorker(Receiver<DedicatedWorkerScriptMsg>),
275}
276
277impl ScriptEventLoopReceiver {
278 pub(crate) fn recv(&self) -> Result<CommonScriptMsg, ()> {
279 match self {
280 Self::MainThread(receiver) => match receiver.recv() {
281 Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg),
282 Ok(_) => panic!("unexpected main thread event message!"),
283 Err(_) => Err(()),
284 },
285 Self::SharedWorker(receiver) => match receiver.recv() {
286 Ok(SharedWorkerScriptMsg::CommonWorker(WorkerScriptMsg::Common(message))) => {
287 Ok(message)
288 },
289 Ok(_) => panic!("unexpected shared worker event message!"),
290 Err(_) => Err(()),
291 },
292 Self::DedicatedWorker(receiver) => match receiver.recv() {
293 Ok(DedicatedWorkerScriptMsg::CommonWorker(_, WorkerScriptMsg::Common(message))) => {
294 Ok(message)
295 },
296 Ok(_) => panic!("unexpected worker event message!"),
297 Err(_) => Err(()),
298 },
299 }
300 }
301}
302
303impl QueuedTaskConversion for MainThreadScriptMsg {
304 fn task_source_name(&self) -> Option<&TaskSourceName> {
305 let script_msg = match self {
306 MainThreadScriptMsg::Common(script_msg) => script_msg,
307 _ => return None,
308 };
309 match script_msg {
310 CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => {
311 Some(task_source)
312 },
313 _ => None,
314 }
315 }
316
317 fn pipeline_id(&self) -> Option<PipelineId> {
318 let script_msg = match self {
319 MainThreadScriptMsg::Common(script_msg) => script_msg,
320 _ => return None,
321 };
322 match script_msg {
323 CommonScriptMsg::Task(_category, _boxed, pipeline_id, _task_source) => *pipeline_id,
324 _ => None,
325 }
326 }
327
328 fn into_queued_task(self) -> Option<QueuedTask> {
329 let script_msg = match self {
330 MainThreadScriptMsg::Common(script_msg) => script_msg,
331 _ => return None,
332 };
333 let (event_category, task, pipeline_id, task_source) = match script_msg {
334 CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => {
335 (category, boxed, pipeline_id, task_source)
336 },
337 _ => return None,
338 };
339 Some(QueuedTask {
340 worker: None,
341 event_category,
342 task,
343 pipeline_id,
344 task_source,
345 })
346 }
347
348 fn from_queued_task(queued_task: QueuedTask) -> Self {
349 let script_msg = CommonScriptMsg::Task(
350 queued_task.event_category,
351 queued_task.task,
352 queued_task.pipeline_id,
353 queued_task.task_source,
354 );
355 MainThreadScriptMsg::Common(script_msg)
356 }
357
358 fn inactive_msg() -> Self {
359 MainThreadScriptMsg::Inactive
360 }
361
362 fn wake_up_msg() -> Self {
363 MainThreadScriptMsg::WakeUp
364 }
365
366 fn is_wake_up(&self) -> bool {
367 matches!(self, MainThreadScriptMsg::WakeUp)
368 }
369}
370
371impl OpaqueSender<CommonScriptMsg> for ScriptEventLoopSender {
372 fn send(&self, message: CommonScriptMsg) {
373 if self.send(message).is_err() {
374 log::warn!("Error communicating with the target thread from the profiler");
375 }
376 }
377}
378
379#[derive(Clone, JSTraceable)]
380pub(crate) struct ScriptThreadSenders {
381 pub(crate) self_sender: Sender<MainThreadScriptMsg>,
384
385 #[no_trace]
387 #[cfg(feature = "bluetooth")]
388 pub(crate) bluetooth_sender: GenericSender<BluetoothRequest>,
389
390 #[no_trace]
392 pub(crate) constellation_sender: GenericSender<ScriptThreadMessage>,
393
394 #[no_trace]
397 pub(crate) pipeline_to_constellation_sender:
398 GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
399
400 #[no_trace]
402 pub(crate) pipeline_to_embedder_sender: ScriptToEmbedderChan,
403
404 #[no_trace]
407 pub(crate) image_cache_sender: Sender<ImageCacheResponseMessage>,
408
409 #[no_trace]
411 pub(crate) time_profiler_sender: profile_time::ProfilerChan,
412
413 #[no_trace]
415 pub(crate) memory_profiler_sender: profile_mem::ProfilerChan,
416
417 #[no_trace]
419 pub(crate) devtools_server_sender: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
420
421 #[no_trace]
422 pub(crate) devtools_client_to_script_thread_sender: GenericSender<DevtoolScriptControlMsg>,
423}
424
425#[derive(JSTraceable)]
426pub(crate) struct ScriptThreadReceivers {
427 #[no_trace]
429 pub(crate) constellation_receiver: RoutedReceiver<ScriptThreadMessage>,
430
431 #[no_trace]
433 pub(crate) image_cache_receiver: Receiver<ImageCacheResponseMessage>,
434
435 #[no_trace]
438 pub(crate) devtools_server_receiver: RoutedReceiver<DevtoolScriptControlMsg>,
439
440 #[no_trace]
443 #[cfg(feature = "webgpu")]
444 pub(crate) webgpu_receiver: RefCell<RoutedReceiver<WebGPUMsg>>,
445}
446
447impl ScriptThreadReceivers {
448 pub(crate) fn recv(
451 &self,
452 task_queue: &TaskQueue<MainThreadScriptMsg>,
453 timer_scheduler: &TimerScheduler,
454 fully_active: &FxHashSet<PipelineId>,
455 ) -> MixedMessage {
456 let mut select = Select::new();
457
458 let task_recv = task_queue.select();
459 let task_index = select.recv(task_recv);
460 let constellation_index = select.recv(&self.constellation_receiver);
461 let devtools_index = select.recv(&self.devtools_server_receiver);
462 let image_cache_index = select.recv(&self.image_cache_receiver);
463
464 #[cfg(feature = "webgpu")]
465 let webgpu_receiver = self.webgpu_receiver.borrow();
466 #[cfg(feature = "webgpu")]
467 let webgpu_index = select.recv(&*webgpu_receiver);
468
469 let message_from_operation = |operation: SelectedOperation| {
470 let index = operation.index();
471 if index == task_index {
472 let msg = operation.recv(task_recv).unwrap();
473 task_queue.take_tasks(msg, fully_active);
474 let event = task_queue.recv().expect(
475 "Spurious wake-up of the event-loop, task-queue has no tasks available",
476 );
477 MixedMessage::FromScript(event)
478 } else if index == constellation_index {
479 MixedMessage::FromConstellation(
480 operation
481 .recv(&self.constellation_receiver)
482 .unwrap()
483 .unwrap(),
484 )
485 } else if index == devtools_index {
486 MixedMessage::FromDevtools(
487 operation
488 .recv(&self.devtools_server_receiver)
489 .unwrap()
490 .unwrap(),
491 )
492 } else if index == image_cache_index {
493 MixedMessage::FromImageCache(operation.recv(&self.image_cache_receiver).unwrap())
494 } else {
495 #[cfg(feature = "webgpu")]
496 {
497 debug_assert_eq!(index, webgpu_index);
498 MixedMessage::FromWebGPUServer(
499 operation.recv(&*webgpu_receiver).unwrap().unwrap(),
500 )
501 }
502 #[cfg(not(feature = "webgpu"))]
503 unreachable!("select returned an unknown index {index}")
504 }
505 };
506
507 if let Some(deadline) = timer_scheduler.next_deadline() {
508 select
509 .select_deadline(deadline)
510 .map(message_from_operation)
511 .unwrap_or(MixedMessage::TimerFired)
512 } else {
513 message_from_operation(select.select())
514 }
515 }
516
517 pub(crate) fn try_recv(
520 &self,
521 task_queue: &TaskQueue<MainThreadScriptMsg>,
522 fully_active: &FxHashSet<PipelineId>,
523 ) -> Option<MixedMessage> {
524 if let Ok(message) = self.constellation_receiver.try_recv() {
525 let message = message
526 .inspect_err(|e| {
527 log::warn!(
528 "ScriptThreadReceivers IPC error on constellation_receiver: {:?}",
529 e
530 );
531 })
532 .ok()?;
533 return MixedMessage::FromConstellation(message).into();
534 }
535 if let Ok(message) = task_queue.take_tasks_and_recv(fully_active) {
536 return MixedMessage::FromScript(message).into();
537 }
538 if let Ok(message) = self.devtools_server_receiver.try_recv() {
539 return MixedMessage::FromDevtools(message.unwrap()).into();
540 }
541 if let Ok(message) = self.image_cache_receiver.try_recv() {
542 return MixedMessage::FromImageCache(message).into();
543 }
544 #[cfg(feature = "webgpu")]
545 if let Ok(message) = self.webgpu_receiver.borrow().try_recv() {
546 return MixedMessage::FromWebGPUServer(message.unwrap()).into();
547 }
548 None
549 }
550}