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 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            },
110            MixedMessage::FromScript(inner_msg) => match inner_msg {
111                MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, _, pipeline_id, _)) => {
112                    *pipeline_id
113                },
114                MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(_)) => None,
115                MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
116                    pipeline_id,
117                    _,
118                )) => Some(*pipeline_id),
119                MainThreadScriptMsg::NavigationResponse { pipeline_id, .. } => Some(*pipeline_id),
120                MainThreadScriptMsg::WorkletLoaded(pipeline_id) => Some(*pipeline_id),
121                MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id, .. } => Some(*pipeline_id),
122                MainThreadScriptMsg::Inactive => None,
123                MainThreadScriptMsg::WakeUp => None,
124                MainThreadScriptMsg::ForwardEmbedderControlResponseFromFileManager(
125                    control_id,
126                    ..,
127                ) => Some(control_id.pipeline_id),
128            },
129            MixedMessage::FromImageCache(response) => match response {
130                ImageCacheResponseMessage::NotifyPendingImageLoadStatus(response) => {
131                    Some(response.pipeline_id)
132                },
133                ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
134                    Some(response.pipeline_id)
135                },
136            },
137            MixedMessage::FromDevtools(_) | MixedMessage::TimerFired => None,
138            #[cfg(feature = "webgpu")]
139            MixedMessage::FromWebGPUServer(..) => None,
140        }
141    }
142}
143
144/// Messages used to control the script event loop.
145#[derive(Debug)]
146pub(crate) enum MainThreadScriptMsg {
147    /// Common variants associated with the script messages
148    Common(CommonScriptMsg),
149    /// Notifies the script thread that a new worklet has been loaded, and thus the page should be
150    /// reflowed.
151    WorkletLoaded(PipelineId),
152    NavigationResponse {
153        pipeline_id: PipelineId,
154        message: Box<FetchResponseMsg>,
155    },
156    /// Notifies the script thread that a new paint worklet has been registered.
157    RegisterPaintWorklet {
158        pipeline_id: PipelineId,
159        name: Atom,
160        properties: Vec<Atom>,
161        painter: Box<dyn Painter>,
162    },
163    /// A task related to a not fully-active document has been throttled.
164    Inactive,
165    /// Wake-up call from the task queue.
166    WakeUp,
167    /// The `FileManagerThread` has finished selecting files is forwarding the response to
168    /// the main thread of this `ScriptThread`.
169    ForwardEmbedderControlResponseFromFileManager(EmbedderControlId, EmbedderControlResponse),
170}
171
172/// Common messages used to control the event loops in both the script and the worker
173pub(crate) enum CommonScriptMsg {
174    /// Requests that the script thread measure its memory usage. The results are sent back via the
175    /// supplied channel.
176    CollectReports(ReportsChan),
177    /// Generic message that encapsulates event handling.
178    Task(
179        ScriptThreadEventCategory,
180        Box<dyn TaskBox>,
181        Option<PipelineId>,
182        TaskSourceName,
183    ),
184    /// Report CSP violations in the script
185    ReportCspViolations(PipelineId, Vec<Violation>),
186}
187
188impl fmt::Debug for CommonScriptMsg {
189    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
190        match *self {
191            CommonScriptMsg::CollectReports(_) => write!(f, "CollectReports(...)"),
192            CommonScriptMsg::Task(ref category, ref task, _, _) => {
193                f.debug_tuple("Task").field(category).field(task).finish()
194            },
195            CommonScriptMsg::ReportCspViolations(..) => write!(f, "ReportCspViolations(...)"),
196        }
197    }
198}
199
200/// A wrapper around various types of `Sender`s that send messages back to the event loop
201/// of a script context event loop. This will either target the main `ScriptThread` event
202/// loop or that of a worker.
203#[derive(Clone, JSTraceable, MallocSizeOf)]
204pub(crate) enum ScriptEventLoopSender {
205    /// A sender that sends to the main `ScriptThread` event loop.
206    MainThread(Sender<MainThreadScriptMsg>),
207    /// A sender that sends to a `ServiceWorker` event loop.
208    ServiceWorker(Sender<ServiceWorkerScriptMsg>),
209    /// A sender that sends to a dedicated worker (such as a generic Web Worker) event loop.
210    /// Note that this sender keeps the main thread Worker DOM object alive as long as it or
211    /// or any message it sends is not dropped.
212    DedicatedWorker {
213        sender: Sender<DedicatedWorkerScriptMsg>,
214        main_thread_worker: TrustedWorkerAddress,
215    },
216}
217
218impl ScriptEventLoopSender {
219    /// Send a message to the event loop, which might be a main thread event loop or a worker event loop.
220    pub(crate) fn send(&self, message: CommonScriptMsg) -> Result<(), SendError<()>> {
221        match self {
222            Self::MainThread(sender) => sender
223                .send(MainThreadScriptMsg::Common(message))
224                .map_err(|_| SendError(())),
225            Self::ServiceWorker(sender) => sender
226                .send(ServiceWorkerScriptMsg::CommonWorker(
227                    WorkerScriptMsg::Common(message),
228                ))
229                .map_err(|_| SendError(())),
230            Self::DedicatedWorker {
231                sender,
232                main_thread_worker,
233            } => {
234                let common_message = WorkerScriptMsg::Common(message);
235                sender
236                    .send(DedicatedWorkerScriptMsg::CommonWorker(
237                        main_thread_worker.clone(),
238                        common_message,
239                    ))
240                    .map_err(|_| SendError(()))
241            },
242        }
243    }
244}
245
246/// A wrapper around various types of `Receiver`s that receive event loop messages. Used for
247/// synchronous DOM APIs that need to abstract over multiple kinds of event loops (worker/main
248/// thread) with different Receiver interfaces.
249pub(crate) enum ScriptEventLoopReceiver {
250    /// A receiver that receives messages to the main `ScriptThread` event loop.
251    MainThread(Receiver<MainThreadScriptMsg>),
252    /// A receiver that receives messages to dedicated workers (such as a generic Web Worker) event loop.
253    DedicatedWorker(Receiver<DedicatedWorkerScriptMsg>),
254}
255
256impl ScriptEventLoopReceiver {
257    pub(crate) fn recv(&self) -> Result<CommonScriptMsg, ()> {
258        match self {
259            Self::MainThread(receiver) => match receiver.recv() {
260                Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg),
261                Ok(_) => panic!("unexpected main thread event message!"),
262                Err(_) => Err(()),
263            },
264            Self::DedicatedWorker(receiver) => match receiver.recv() {
265                Ok(DedicatedWorkerScriptMsg::CommonWorker(_, WorkerScriptMsg::Common(message))) => {
266                    Ok(message)
267                },
268                Ok(_) => panic!("unexpected worker event message!"),
269                Err(_) => Err(()),
270            },
271        }
272    }
273}
274
275impl QueuedTaskConversion for MainThreadScriptMsg {
276    fn task_source_name(&self) -> Option<&TaskSourceName> {
277        let script_msg = match self {
278            MainThreadScriptMsg::Common(script_msg) => script_msg,
279            _ => return None,
280        };
281        match script_msg {
282            CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => {
283                Some(task_source)
284            },
285            _ => None,
286        }
287    }
288
289    fn pipeline_id(&self) -> Option<PipelineId> {
290        let script_msg = match self {
291            MainThreadScriptMsg::Common(script_msg) => script_msg,
292            _ => return None,
293        };
294        match script_msg {
295            CommonScriptMsg::Task(_category, _boxed, pipeline_id, _task_source) => *pipeline_id,
296            _ => None,
297        }
298    }
299
300    fn into_queued_task(self) -> Option<QueuedTask> {
301        let script_msg = match self {
302            MainThreadScriptMsg::Common(script_msg) => script_msg,
303            _ => return None,
304        };
305        let (category, boxed, pipeline_id, task_source) = match script_msg {
306            CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => {
307                (category, boxed, pipeline_id, task_source)
308            },
309            _ => return None,
310        };
311        Some((None, category, boxed, pipeline_id, task_source))
312    }
313
314    fn from_queued_task(queued_task: QueuedTask) -> Self {
315        let (_worker, category, boxed, pipeline_id, task_source) = queued_task;
316        let script_msg = CommonScriptMsg::Task(category, boxed, pipeline_id, task_source);
317        MainThreadScriptMsg::Common(script_msg)
318    }
319
320    fn inactive_msg() -> Self {
321        MainThreadScriptMsg::Inactive
322    }
323
324    fn wake_up_msg() -> Self {
325        MainThreadScriptMsg::WakeUp
326    }
327
328    fn is_wake_up(&self) -> bool {
329        matches!(self, MainThreadScriptMsg::WakeUp)
330    }
331}
332
333impl OpaqueSender<CommonScriptMsg> for ScriptEventLoopSender {
334    fn send(&self, message: CommonScriptMsg) {
335        self.send(message).unwrap()
336    }
337}
338
339#[derive(Clone, JSTraceable)]
340pub(crate) struct ScriptThreadSenders {
341    /// A channel to hand out to script thread-based entities that need to be able to enqueue
342    /// events in the event queue.
343    pub(crate) self_sender: Sender<MainThreadScriptMsg>,
344
345    /// A handle to the bluetooth thread.
346    #[no_trace]
347    #[cfg(feature = "bluetooth")]
348    pub(crate) bluetooth_sender: GenericSender<BluetoothRequest>,
349
350    /// A [`Sender`] that sends messages to the `Constellation`.
351    #[no_trace]
352    pub(crate) constellation_sender: GenericSender<ScriptThreadMessage>,
353
354    /// A [`Sender`] that sends messages to the `Constellation` associated with
355    /// particular pipelines.
356    #[no_trace]
357    pub(crate) pipeline_to_constellation_sender:
358        GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
359
360    /// A channel to send messages to the Embedder.
361    #[no_trace]
362    pub(crate) pipeline_to_embedder_sender: ScriptToEmbedderChan,
363
364    /// The shared [`Sender`] which is sent to the `ImageCache` when requesting an image.
365    /// Messages on this channel are sent to [`ScriptThreadReceivers::image_cache_receiver`].
366    #[no_trace]
367    pub(crate) image_cache_sender: Sender<ImageCacheResponseMessage>,
368
369    /// For providing contact with the time profiler.
370    #[no_trace]
371    pub(crate) time_profiler_sender: profile_time::ProfilerChan,
372
373    /// For providing contact with the memory profiler.
374    #[no_trace]
375    pub(crate) memory_profiler_sender: profile_mem::ProfilerChan,
376
377    /// For providing instructions to an optional devtools server.
378    #[no_trace]
379    pub(crate) devtools_server_sender: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
380
381    #[no_trace]
382    pub(crate) devtools_client_to_script_thread_sender: GenericSender<DevtoolScriptControlMsg>,
383}
384
385#[derive(JSTraceable)]
386pub(crate) struct ScriptThreadReceivers {
387    /// A [`Receiver`] that receives messages from the constellation.
388    #[no_trace]
389    pub(crate) constellation_receiver: RoutedReceiver<ScriptThreadMessage>,
390
391    /// The [`Receiver`] which receives incoming messages from the `ImageCache`.
392    #[no_trace]
393    pub(crate) image_cache_receiver: Receiver<ImageCacheResponseMessage>,
394
395    /// For receiving commands from an optional devtools server. Will be ignored if no such server
396    /// exists. When devtools are not active this will be [`crossbeam_channel::never()`].
397    #[no_trace]
398    pub(crate) devtools_server_receiver: RoutedReceiver<DevtoolScriptControlMsg>,
399
400    /// Receiver to receive commands from optional WebGPU server. When there is no active
401    /// WebGPU context, this will be [`crossbeam_channel::never()`].
402    #[no_trace]
403    #[cfg(feature = "webgpu")]
404    pub(crate) webgpu_receiver: RefCell<RoutedReceiver<WebGPUMsg>>,
405}
406
407impl ScriptThreadReceivers {
408    /// Block until a message is received by any of the receivers of this [`ScriptThreadReceivers`]
409    /// or the given [`TaskQueue`] or [`TimerScheduler`]. Return the first message received.
410    pub(crate) fn recv(
411        &self,
412        task_queue: &TaskQueue<MainThreadScriptMsg>,
413        timer_scheduler: &TimerScheduler,
414        fully_active: &FxHashSet<PipelineId>,
415    ) -> MixedMessage {
416        select! {
417            recv(task_queue.select()) -> msg => {
418                task_queue.take_tasks(msg.unwrap(), fully_active);
419                let event = task_queue
420                    .recv()
421                    .expect("Spurious wake-up of the event-loop, task-queue has no tasks available");
422                MixedMessage::FromScript(event)
423            },
424            recv(self.constellation_receiver) -> msg => MixedMessage::FromConstellation(msg.unwrap().unwrap()),
425            recv(self.devtools_server_receiver) -> msg => MixedMessage::FromDevtools(msg.unwrap().unwrap()),
426            recv(self.image_cache_receiver) -> msg => MixedMessage::FromImageCache(msg.unwrap()),
427            recv(timer_scheduler.wait_channel()) -> _ => MixedMessage::TimerFired,
428            recv({
429                #[cfg(feature = "webgpu")]
430                {
431                    self.webgpu_receiver.borrow()
432                }
433                #[cfg(not(feature = "webgpu"))]
434                {
435                    crossbeam_channel::never::<()>()
436                }
437            }) -> msg => {
438                #[cfg(feature = "webgpu")]
439                {
440                    MixedMessage::FromWebGPUServer(msg.unwrap().unwrap())
441                }
442                #[cfg(not(feature = "webgpu"))]
443                {
444                    unreachable!("This should never be hit when webgpu is disabled ({msg:?})");
445                }
446            }
447        }
448    }
449
450    /// Try to receive a from any of the receivers of this [`ScriptThreadReceivers`] or the given
451    /// [`TaskQueue`]. Return `None` if no messages are ready to be received.
452    pub(crate) fn try_recv(
453        &self,
454        task_queue: &TaskQueue<MainThreadScriptMsg>,
455        fully_active: &FxHashSet<PipelineId>,
456    ) -> Option<MixedMessage> {
457        if let Ok(message) = self.constellation_receiver.try_recv() {
458            let message = message
459                .inspect_err(|e| {
460                    log::warn!(
461                        "ScriptThreadReceivers IPC error on constellation_receiver: {:?}",
462                        e
463                    );
464                })
465                .ok()?;
466            return MixedMessage::FromConstellation(message).into();
467        }
468        if let Ok(message) = task_queue.take_tasks_and_recv(fully_active) {
469            return MixedMessage::FromScript(message).into();
470        }
471        if let Ok(message) = self.devtools_server_receiver.try_recv() {
472            return MixedMessage::FromDevtools(message.unwrap()).into();
473        }
474        if let Ok(message) = self.image_cache_receiver.try_recv() {
475            return MixedMessage::FromImageCache(message).into();
476        }
477        #[cfg(feature = "webgpu")]
478        if let Ok(message) = self.webgpu_receiver.borrow().try_recv() {
479            return MixedMessage::FromWebGPUServer(message.unwrap()).into();
480        }
481        None
482    }
483}