1use core::fmt;
6#[cfg(feature = "webgpu")]
7use std::cell::RefCell;
8use std::option::Option;
9use std::result::Result;
10
11use base::generic_channel::{GenericCallback, GenericSender, RoutedReceiver};
12use base::id::{PipelineId, WebViewId};
13#[cfg(feature = "bluetooth")]
14use bluetooth_traits::BluetoothRequest;
15use constellation_traits::ScriptToConstellationMessage;
16use crossbeam_channel::{Receiver, SendError, Sender, select};
17use devtools_traits::{DevtoolScriptControlMsg, ScriptToDevtoolsControlMsg};
18use embedder_traits::{EmbedderControlId, EmbedderControlResponse, ScriptToEmbedderChan};
19use net_traits::FetchResponseMsg;
20use net_traits::image_cache::ImageCacheResponseMessage;
21use profile_traits::mem::{self as profile_mem, OpaqueSender, ReportsChan};
22use profile_traits::time::{self as profile_time};
23use rustc_hash::FxHashSet;
24use script_traits::{Painter, ScriptThreadMessage};
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::worker::TrustedWorkerAddress;
36use crate::script_runtime::ScriptThreadEventCategory;
37use crate::task::TaskBox;
38use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue};
39use crate::task_source::TaskSourceName;
40
41#[expect(clippy::large_enum_variant)]
42#[derive(Debug)]
43pub(crate) enum MixedMessage {
44 FromConstellation(ScriptThreadMessage),
45 FromScript(MainThreadScriptMsg),
46 FromDevtools(DevtoolScriptControlMsg),
47 FromImageCache(ImageCacheResponseMessage),
48 #[cfg(feature = "webgpu")]
49 FromWebGPUServer(WebGPUMsg),
50 TimerFired,
51}
52
53impl MixedMessage {
54 pub(crate) fn pipeline_id(&self) -> Option<PipelineId> {
55 match self {
56 MixedMessage::FromConstellation(inner_msg) => match inner_msg {
57 ScriptThreadMessage::StopDelayingLoadEventsMode(id) => Some(*id),
58 ScriptThreadMessage::SpawnPipeline(new_pipeline_info) => new_pipeline_info
59 .parent_info
60 .or(Some(new_pipeline_info.new_pipeline_id)),
61 ScriptThreadMessage::Resize(id, ..) => Some(*id),
62 ScriptThreadMessage::ThemeChange(id, ..) => Some(*id),
63 ScriptThreadMessage::ResizeInactive(id, ..) => Some(*id),
64 ScriptThreadMessage::UnloadDocument(id) => Some(*id),
65 ScriptThreadMessage::ExitPipeline(_webview_id, id, ..) => Some(*id),
66 ScriptThreadMessage::ExitScriptThread => None,
67 ScriptThreadMessage::SendInputEvent(_, id, _) => Some(*id),
68 ScriptThreadMessage::RefreshCursor(id, ..) => Some(*id),
69 ScriptThreadMessage::GetTitle(id) => Some(*id),
70 ScriptThreadMessage::SetDocumentActivity(id, ..) => Some(*id),
71 ScriptThreadMessage::SetThrottled(_, id, ..) => Some(*id),
72 ScriptThreadMessage::SetThrottledInContainingIframe(_, id, ..) => Some(*id),
73 ScriptThreadMessage::NavigateIframe(id, ..) => Some(*id),
74 ScriptThreadMessage::PostMessage { target: id, .. } => Some(*id),
75 ScriptThreadMessage::UpdatePipelineId(_, _, _, id, _) => Some(*id),
76 ScriptThreadMessage::UpdateHistoryState(id, ..) => Some(*id),
77 ScriptThreadMessage::RemoveHistoryStates(id, ..) => Some(*id),
78 ScriptThreadMessage::FocusIFrame(id, ..) => Some(*id),
79 ScriptThreadMessage::FocusDocument(id, ..) => Some(*id),
80 ScriptThreadMessage::Unfocus(id, ..) => Some(*id),
81 ScriptThreadMessage::WebDriverScriptCommand(id, ..) => Some(*id),
82 ScriptThreadMessage::TickAllAnimations(..) => None,
83 ScriptThreadMessage::WebFontLoaded(id, ..) => Some(*id),
84 ScriptThreadMessage::DispatchIFrameLoadEvent {
85 target: _,
86 parent: id,
87 child: _,
88 } => Some(*id),
89 ScriptThreadMessage::DispatchStorageEvent(id, ..) => Some(*id),
90 ScriptThreadMessage::ReportCSSError(id, ..) => Some(*id),
91 ScriptThreadMessage::Reload(id, ..) => Some(*id),
92 ScriptThreadMessage::PaintMetric(id, ..) => Some(*id),
93 ScriptThreadMessage::ExitFullScreen(id, ..) => Some(*id),
94 ScriptThreadMessage::MediaSessionAction(..) => None,
95 #[cfg(feature = "webgpu")]
96 ScriptThreadMessage::SetWebGPUPort(..) => None,
97 ScriptThreadMessage::SetScrollStates(id, ..) => Some(*id),
98 ScriptThreadMessage::EvaluateJavaScript(_, id, _, _) => Some(*id),
99 ScriptThreadMessage::SendImageKeysBatch(..) => None,
100 ScriptThreadMessage::PreferencesUpdated(..) => None,
101 ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(_) => None,
102 ScriptThreadMessage::ForwardKeyboardScroll(id, _) => Some(*id),
103 ScriptThreadMessage::RequestScreenshotReadiness(_, id) => Some(*id),
104 ScriptThreadMessage::EmbedderControlResponse(id, _) => Some(id.pipeline_id),
105 ScriptThreadMessage::SetUserContents(..) => None,
106 ScriptThreadMessage::DestroyUserContentManager(..) => None,
107 ScriptThreadMessage::AccessibilityTreeUpdate(..) => None,
108 ScriptThreadMessage::UpdatePinchZoomInfos(id, _) => Some(*id),
109 ScriptThreadMessage::SetAccessibilityActive(..) => None,
110 },
111 MixedMessage::FromScript(inner_msg) => match inner_msg {
112 MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, _, pipeline_id, _)) => {
113 *pipeline_id
114 },
115 MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(_)) => None,
116 MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
117 pipeline_id,
118 _,
119 )) => Some(*pipeline_id),
120 MainThreadScriptMsg::NavigationResponse { pipeline_id, .. } => Some(*pipeline_id),
121 MainThreadScriptMsg::WorkletLoaded(pipeline_id) => Some(*pipeline_id),
122 MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id, .. } => Some(*pipeline_id),
123 MainThreadScriptMsg::Inactive => None,
124 MainThreadScriptMsg::WakeUp => None,
125 MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
126 control_id,
127 ..,
128 ) => Some(control_id.pipeline_id),
129 },
130 MixedMessage::FromImageCache(response) => match response {
131 ImageCacheResponseMessage::NotifyPendingImageLoadStatus(response) => {
132 Some(response.pipeline_id)
133 },
134 ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
135 Some(response.pipeline_id)
136 },
137 },
138 MixedMessage::FromDevtools(_) | MixedMessage::TimerFired => None,
139 #[cfg(feature = "webgpu")]
140 MixedMessage::FromWebGPUServer(..) => None,
141 }
142 }
143}
144
145#[derive(Debug)]
147pub(crate) enum MainThreadScriptMsg {
148 Common(CommonScriptMsg),
150 WorkletLoaded(PipelineId),
153 NavigationResponse {
154 pipeline_id: PipelineId,
155 message: Box<FetchResponseMsg>,
156 },
157 RegisterPaintWorklet {
159 pipeline_id: PipelineId,
160 name: Atom,
161 properties: Vec<Atom>,
162 painter: Box<dyn Painter>,
163 },
164 Inactive,
166 WakeUp,
168 ForwardEmbedderControlResponseFromFileManager(EmbedderControlId, EmbedderControlResponse),
171}
172
173pub(crate) enum CommonScriptMsg {
175 CollectReports(ReportsChan),
178 Task(
180 ScriptThreadEventCategory,
181 Box<dyn TaskBox>,
182 Option<PipelineId>,
183 TaskSourceName,
184 ),
185 ReportCspViolations(PipelineId, Vec<Violation>),
187}
188
189impl fmt::Debug for CommonScriptMsg {
190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
191 match *self {
192 CommonScriptMsg::CollectReports(_) => write!(f, "CollectReports(...)"),
193 CommonScriptMsg::Task(ref category, ref task, _, _) => {
194 f.debug_tuple("Task").field(category).field(task).finish()
195 },
196 CommonScriptMsg::ReportCspViolations(..) => write!(f, "ReportCspViolations(...)"),
197 }
198 }
199}
200
201#[derive(Clone, JSTraceable, MallocSizeOf)]
205pub(crate) enum ScriptEventLoopSender {
206 MainThread(Sender<MainThreadScriptMsg>),
208 ServiceWorker(Sender<ServiceWorkerScriptMsg>),
210 DedicatedWorker {
214 sender: Sender<DedicatedWorkerScriptMsg>,
215 main_thread_worker: TrustedWorkerAddress,
216 },
217}
218
219impl ScriptEventLoopSender {
220 pub(crate) fn send(&self, message: CommonScriptMsg) -> Result<(), SendError<()>> {
222 match self {
223 Self::MainThread(sender) => sender
224 .send(MainThreadScriptMsg::Common(message))
225 .map_err(|_| SendError(())),
226 Self::ServiceWorker(sender) => sender
227 .send(ServiceWorkerScriptMsg::CommonWorker(
228 WorkerScriptMsg::Common(message),
229 ))
230 .map_err(|_| SendError(())),
231 Self::DedicatedWorker {
232 sender,
233 main_thread_worker,
234 } => {
235 let common_message = WorkerScriptMsg::Common(message);
236 sender
237 .send(DedicatedWorkerScriptMsg::CommonWorker(
238 main_thread_worker.clone(),
239 common_message,
240 ))
241 .map_err(|_| SendError(()))
242 },
243 }
244 }
245}
246
247pub(crate) enum ScriptEventLoopReceiver {
251 MainThread(Receiver<MainThreadScriptMsg>),
253 DedicatedWorker(Receiver<DedicatedWorkerScriptMsg>),
255}
256
257impl ScriptEventLoopReceiver {
258 pub(crate) fn recv(&self) -> Result<CommonScriptMsg, ()> {
259 match self {
260 Self::MainThread(receiver) => match receiver.recv() {
261 Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg),
262 Ok(_) => panic!("unexpected main thread event message!"),
263 Err(_) => Err(()),
264 },
265 Self::DedicatedWorker(receiver) => match receiver.recv() {
266 Ok(DedicatedWorkerScriptMsg::CommonWorker(_, WorkerScriptMsg::Common(message))) => {
267 Ok(message)
268 },
269 Ok(_) => panic!("unexpected worker event message!"),
270 Err(_) => Err(()),
271 },
272 }
273 }
274}
275
276impl QueuedTaskConversion for MainThreadScriptMsg {
277 fn task_source_name(&self) -> Option<&TaskSourceName> {
278 let script_msg = match self {
279 MainThreadScriptMsg::Common(script_msg) => script_msg,
280 _ => return None,
281 };
282 match script_msg {
283 CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => {
284 Some(task_source)
285 },
286 _ => None,
287 }
288 }
289
290 fn pipeline_id(&self) -> Option<PipelineId> {
291 let script_msg = match self {
292 MainThreadScriptMsg::Common(script_msg) => script_msg,
293 _ => return None,
294 };
295 match script_msg {
296 CommonScriptMsg::Task(_category, _boxed, pipeline_id, _task_source) => *pipeline_id,
297 _ => None,
298 }
299 }
300
301 fn into_queued_task(self) -> Option<QueuedTask> {
302 let script_msg = match self {
303 MainThreadScriptMsg::Common(script_msg) => script_msg,
304 _ => return None,
305 };
306 let (event_category, task, pipeline_id, task_source) = match script_msg {
307 CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => {
308 (category, boxed, pipeline_id, task_source)
309 },
310 _ => return None,
311 };
312 Some(QueuedTask {
313 worker: None,
314 event_category,
315 task,
316 pipeline_id,
317 task_source,
318 })
319 }
320
321 fn from_queued_task(queued_task: QueuedTask) -> Self {
322 let script_msg = CommonScriptMsg::Task(
323 queued_task.event_category,
324 queued_task.task,
325 queued_task.pipeline_id,
326 queued_task.task_source,
327 );
328 MainThreadScriptMsg::Common(script_msg)
329 }
330
331 fn inactive_msg() -> Self {
332 MainThreadScriptMsg::Inactive
333 }
334
335 fn wake_up_msg() -> Self {
336 MainThreadScriptMsg::WakeUp
337 }
338
339 fn is_wake_up(&self) -> bool {
340 matches!(self, MainThreadScriptMsg::WakeUp)
341 }
342}
343
344impl OpaqueSender<CommonScriptMsg> for ScriptEventLoopSender {
345 fn send(&self, message: CommonScriptMsg) {
346 self.send(message).unwrap()
347 }
348}
349
350#[derive(Clone, JSTraceable)]
351pub(crate) struct ScriptThreadSenders {
352 pub(crate) self_sender: Sender<MainThreadScriptMsg>,
355
356 #[no_trace]
358 #[cfg(feature = "bluetooth")]
359 pub(crate) bluetooth_sender: GenericSender<BluetoothRequest>,
360
361 #[no_trace]
363 pub(crate) constellation_sender: GenericSender<ScriptThreadMessage>,
364
365 #[no_trace]
368 pub(crate) pipeline_to_constellation_sender:
369 GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
370
371 #[no_trace]
373 pub(crate) pipeline_to_embedder_sender: ScriptToEmbedderChan,
374
375 #[no_trace]
378 pub(crate) image_cache_sender: Sender<ImageCacheResponseMessage>,
379
380 #[no_trace]
382 pub(crate) time_profiler_sender: profile_time::ProfilerChan,
383
384 #[no_trace]
386 pub(crate) memory_profiler_sender: profile_mem::ProfilerChan,
387
388 #[no_trace]
390 pub(crate) devtools_server_sender: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
391
392 #[no_trace]
393 pub(crate) devtools_client_to_script_thread_sender: GenericSender<DevtoolScriptControlMsg>,
394}
395
396#[derive(JSTraceable)]
397pub(crate) struct ScriptThreadReceivers {
398 #[no_trace]
400 pub(crate) constellation_receiver: RoutedReceiver<ScriptThreadMessage>,
401
402 #[no_trace]
404 pub(crate) image_cache_receiver: Receiver<ImageCacheResponseMessage>,
405
406 #[no_trace]
409 pub(crate) devtools_server_receiver: RoutedReceiver<DevtoolScriptControlMsg>,
410
411 #[no_trace]
414 #[cfg(feature = "webgpu")]
415 pub(crate) webgpu_receiver: RefCell<RoutedReceiver<WebGPUMsg>>,
416}
417
418impl ScriptThreadReceivers {
419 pub(crate) fn recv(
422 &self,
423 task_queue: &TaskQueue<MainThreadScriptMsg>,
424 timer_scheduler: &TimerScheduler,
425 fully_active: &FxHashSet<PipelineId>,
426 ) -> MixedMessage {
427 select! {
428 recv(task_queue.select()) -> msg => {
429 task_queue.take_tasks(msg.unwrap(), fully_active);
430 let event = task_queue
431 .recv()
432 .expect("Spurious wake-up of the event-loop, task-queue has no tasks available");
433 MixedMessage::FromScript(event)
434 },
435 recv(self.constellation_receiver) -> msg => MixedMessage::FromConstellation(msg.unwrap().unwrap()),
436 recv(self.devtools_server_receiver) -> msg => MixedMessage::FromDevtools(msg.unwrap().unwrap()),
437 recv(self.image_cache_receiver) -> msg => MixedMessage::FromImageCache(msg.unwrap()),
438 recv(timer_scheduler.wait_channel()) -> _ => MixedMessage::TimerFired,
439 recv({
440 #[cfg(feature = "webgpu")]
441 {
442 self.webgpu_receiver.borrow()
443 }
444 #[cfg(not(feature = "webgpu"))]
445 {
446 crossbeam_channel::never::<()>()
447 }
448 }) -> msg => {
449 #[cfg(feature = "webgpu")]
450 {
451 MixedMessage::FromWebGPUServer(msg.unwrap().unwrap())
452 }
453 #[cfg(not(feature = "webgpu"))]
454 {
455 unreachable!("This should never be hit when webgpu is disabled ({msg:?})");
456 }
457 }
458 }
459 }
460
461 pub(crate) fn try_recv(
464 &self,
465 task_queue: &TaskQueue<MainThreadScriptMsg>,
466 fully_active: &FxHashSet<PipelineId>,
467 ) -> Option<MixedMessage> {
468 if let Ok(message) = self.constellation_receiver.try_recv() {
469 let message = message
470 .inspect_err(|e| {
471 log::warn!(
472 "ScriptThreadReceivers IPC error on constellation_receiver: {:?}",
473 e
474 );
475 })
476 .ok()?;
477 return MixedMessage::FromConstellation(message).into();
478 }
479 if let Ok(message) = task_queue.take_tasks_and_recv(fully_active) {
480 return MixedMessage::FromScript(message).into();
481 }
482 if let Ok(message) = self.devtools_server_receiver.try_recv() {
483 return MixedMessage::FromDevtools(message.unwrap()).into();
484 }
485 if let Ok(message) = self.image_cache_receiver.try_recv() {
486 return MixedMessage::FromImageCache(message).into();
487 }
488 #[cfg(feature = "webgpu")]
489 if let Ok(message) = self.webgpu_receiver.borrow().try_recv() {
490 return MixedMessage::FromWebGPUServer(message.unwrap()).into();
491 }
492 None
493 }
494}