Skip to main content

script/
messaging.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use 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/// Messages used to control the script event loop.
150#[derive(Debug)]
151pub(crate) enum MainThreadScriptMsg {
152    /// Common variants associated with the script messages
153    Common(CommonScriptMsg),
154    /// Notifies the script thread that a new worklet has been loaded, and thus the page should be
155    /// reflowed.
156    WorkletLoaded(PipelineId),
157    NavigationResponse {
158        pipeline_id: PipelineId,
159        message: Box<FetchResponseMsg>,
160    },
161    /// Notifies the script thread that a new paint worklet has been registered.
162    RegisterPaintWorklet {
163        pipeline_id: PipelineId,
164        name: Atom,
165        properties: Vec<Atom>,
166        painter: Box<dyn Painter>,
167    },
168    /// A task related to a not fully-active document has been throttled.
169    Inactive,
170    /// Wake-up call from the task queue.
171    WakeUp,
172    /// The `FileManagerThread` has finished selecting files is forwarding the response to
173    /// the main thread of this `ScriptThread`.
174    ForwardEmbedderControlResponseFromFileManager(EmbedderControlId, EmbedderControlResponse),
175}
176
177/// Common messages used to control the event loops in both the script, the worker, and the
178/// worklet
179pub(crate) enum CommonScriptMsg {
180    /// Requests that the script thread measure its memory usage. The results are sent back via the
181    /// supplied channel.
182    CollectReports(ReportsChan),
183    /// Generic message that encapsulates event handling.
184    Task(
185        ScriptThreadEventCategory,
186        Box<dyn TaskBox>,
187        Option<PipelineId>,
188        TaskSourceName,
189    ),
190    /// Report CSP violations in the script
191    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/// A wrapper around various types of `Sender`s that send messages back to the event loop
207/// of a script context event loop. This will either target the main `ScriptThread` event
208/// loop or that of a worker.
209#[derive(Clone, JSTraceable, MallocSizeOf)]
210pub(crate) enum ScriptEventLoopSender {
211    /// A sender that sends to the main `ScriptThread` event loop.
212    MainThread(Sender<MainThreadScriptMsg>),
213    /// A sender that sends to a `SharedWorker` event loop.
214    SharedWorker(Sender<SharedWorkerScriptMsg>),
215    /// A sender that sends to a `ServiceWorker` event loop.
216    ServiceWorker(Sender<ServiceWorkerScriptMsg>),
217    /// A wrapper that sends to the event loops of all threads belonging to a `Worklet`
218    Worklet(WorkletExecutor),
219    /// A sender that sends to a dedicated worker (such as a generic Web Worker) event loop.
220    /// Note that this sender keeps the main thread Worker DOM object alive as long as it or
221    /// or any message it sends is not dropped.
222    DedicatedWorker {
223        sender: Sender<DedicatedWorkerScriptMsg>,
224        main_thread_worker: TrustedWorkerAddress,
225    },
226}
227
228impl ScriptEventLoopSender {
229    /// Send a message to the event loop, which might be a main thread event loop or a worker event loop.
230    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
264/// A wrapper around various types of `Receiver`s that receive event loop messages. Used for
265/// synchronous DOM APIs that need to abstract over multiple kinds of event loops (worker/main
266/// thread) with different Receiver interfaces.
267pub(crate) enum ScriptEventLoopReceiver {
268    /// A receiver that receives messages to the main `ScriptThread` event loop.
269    MainThread(Receiver<MainThreadScriptMsg>),
270    /// A receiver that receives messages to shared worker event loops.
271    SharedWorker(Receiver<SharedWorkerScriptMsg>),
272    /// A receiver that receives messages to dedicated workers (such as a generic Web Worker) event loop.
273    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    /// A channel to hand out to script thread-based entities that need to be able to enqueue
379    /// events in the event queue.
380    pub(crate) self_sender: Sender<MainThreadScriptMsg>,
381
382    /// A handle to the bluetooth thread.
383    #[no_trace]
384    #[cfg(feature = "bluetooth")]
385    pub(crate) bluetooth_sender: GenericSender<BluetoothRequest>,
386
387    /// A [`Sender`] that sends messages to the `ScriptThread`.
388    #[no_trace]
389    pub(crate) constellation_sender: GenericSender<ScriptThreadMessage>,
390
391    /// A [`Sender`] that sends messages to the `Constellation` associated with
392    /// particular pipelines.
393    #[no_trace]
394    pub(crate) pipeline_to_constellation_sender:
395        GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
396
397    /// A channel to send messages to the Embedder.
398    #[no_trace]
399    pub(crate) pipeline_to_embedder_sender: ScriptToEmbedderChan,
400
401    /// The shared [`Sender`] which is sent to the `ImageCache` when requesting an image.
402    /// Messages on this channel are sent to [`ScriptThreadReceivers::image_cache_receiver`].
403    #[no_trace]
404    pub(crate) image_cache_sender: Sender<ImageCacheResponseMessage>,
405
406    /// For providing contact with the time profiler.
407    #[no_trace]
408    pub(crate) time_profiler_sender: profile_time::ProfilerChan,
409
410    /// For providing contact with the memory profiler.
411    #[no_trace]
412    pub(crate) memory_profiler_sender: profile_mem::ProfilerChan,
413
414    /// For providing instructions to an optional devtools server.
415    #[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    /// A [`Receiver`] that receives messages from the constellation.
425    #[no_trace]
426    pub(crate) constellation_receiver: RoutedReceiver<ScriptThreadMessage>,
427
428    /// The [`Receiver`] which receives incoming messages from the `ImageCache`.
429    #[no_trace]
430    pub(crate) image_cache_receiver: Receiver<ImageCacheResponseMessage>,
431
432    /// For receiving commands from an optional devtools server. Will be ignored if no such server
433    /// exists. When devtools are not active this will be [`crossbeam_channel::never()`].
434    #[no_trace]
435    pub(crate) devtools_server_receiver: RoutedReceiver<DevtoolScriptControlMsg>,
436
437    /// Receiver to receive commands from optional WebGPU server. When there is no active
438    /// WebGPU context, this will be [`crossbeam_channel::never()`].
439    #[no_trace]
440    #[cfg(feature = "webgpu")]
441    pub(crate) webgpu_receiver: RefCell<RoutedReceiver<WebGPUMsg>>,
442}
443
444impl ScriptThreadReceivers {
445    /// Block until a message is received by any of the receivers of this [`ScriptThreadReceivers`]
446    /// or the given [`TaskQueue`] or [`TimerScheduler`]. Return the first message received.
447    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    /// Try to receive a from any of the receivers of this [`ScriptThreadReceivers`] or the given
515    /// [`TaskQueue`]. Return `None` if no messages are ready to be received.
516    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}