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                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/// Messages used to control the script event loop.
146#[derive(Debug)]
147pub(crate) enum MainThreadScriptMsg {
148    /// Common variants associated with the script messages
149    Common(CommonScriptMsg),
150    /// Notifies the script thread that a new worklet has been loaded, and thus the page should be
151    /// reflowed.
152    WorkletLoaded(PipelineId),
153    NavigationResponse {
154        pipeline_id: PipelineId,
155        message: Box<FetchResponseMsg>,
156    },
157    /// Notifies the script thread that a new paint worklet has been registered.
158    RegisterPaintWorklet {
159        pipeline_id: PipelineId,
160        name: Atom,
161        properties: Vec<Atom>,
162        painter: Box<dyn Painter>,
163    },
164    /// A task related to a not fully-active document has been throttled.
165    Inactive,
166    /// Wake-up call from the task queue.
167    WakeUp,
168    /// The `FileManagerThread` has finished selecting files is forwarding the response to
169    /// the main thread of this `ScriptThread`.
170    ForwardEmbedderControlResponseFromFileManager(EmbedderControlId, EmbedderControlResponse),
171}
172
173/// Common messages used to control the event loops in both the script and the worker
174pub(crate) enum CommonScriptMsg {
175    /// Requests that the script thread measure its memory usage. The results are sent back via the
176    /// supplied channel.
177    CollectReports(ReportsChan),
178    /// Generic message that encapsulates event handling.
179    Task(
180        ScriptThreadEventCategory,
181        Box<dyn TaskBox>,
182        Option<PipelineId>,
183        TaskSourceName,
184    ),
185    /// Report CSP violations in the script
186    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/// A wrapper around various types of `Sender`s that send messages back to the event loop
202/// of a script context event loop. This will either target the main `ScriptThread` event
203/// loop or that of a worker.
204#[derive(Clone, JSTraceable, MallocSizeOf)]
205pub(crate) enum ScriptEventLoopSender {
206    /// A sender that sends to the main `ScriptThread` event loop.
207    MainThread(Sender<MainThreadScriptMsg>),
208    /// A sender that sends to a `ServiceWorker` event loop.
209    ServiceWorker(Sender<ServiceWorkerScriptMsg>),
210    /// A sender that sends to a dedicated worker (such as a generic Web Worker) event loop.
211    /// Note that this sender keeps the main thread Worker DOM object alive as long as it or
212    /// or any message it sends is not dropped.
213    DedicatedWorker {
214        sender: Sender<DedicatedWorkerScriptMsg>,
215        main_thread_worker: TrustedWorkerAddress,
216    },
217}
218
219impl ScriptEventLoopSender {
220    /// Send a message to the event loop, which might be a main thread event loop or a worker event loop.
221    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
247/// A wrapper around various types of `Receiver`s that receive event loop messages. Used for
248/// synchronous DOM APIs that need to abstract over multiple kinds of event loops (worker/main
249/// thread) with different Receiver interfaces.
250pub(crate) enum ScriptEventLoopReceiver {
251    /// A receiver that receives messages to the main `ScriptThread` event loop.
252    MainThread(Receiver<MainThreadScriptMsg>),
253    /// A receiver that receives messages to dedicated workers (such as a generic Web Worker) event loop.
254    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    /// A channel to hand out to script thread-based entities that need to be able to enqueue
353    /// events in the event queue.
354    pub(crate) self_sender: Sender<MainThreadScriptMsg>,
355
356    /// A handle to the bluetooth thread.
357    #[no_trace]
358    #[cfg(feature = "bluetooth")]
359    pub(crate) bluetooth_sender: GenericSender<BluetoothRequest>,
360
361    /// A [`Sender`] that sends messages to the `Constellation`.
362    #[no_trace]
363    pub(crate) constellation_sender: GenericSender<ScriptThreadMessage>,
364
365    /// A [`Sender`] that sends messages to the `Constellation` associated with
366    /// particular pipelines.
367    #[no_trace]
368    pub(crate) pipeline_to_constellation_sender:
369        GenericSender<(WebViewId, PipelineId, ScriptToConstellationMessage)>,
370
371    /// A channel to send messages to the Embedder.
372    #[no_trace]
373    pub(crate) pipeline_to_embedder_sender: ScriptToEmbedderChan,
374
375    /// The shared [`Sender`] which is sent to the `ImageCache` when requesting an image.
376    /// Messages on this channel are sent to [`ScriptThreadReceivers::image_cache_receiver`].
377    #[no_trace]
378    pub(crate) image_cache_sender: Sender<ImageCacheResponseMessage>,
379
380    /// For providing contact with the time profiler.
381    #[no_trace]
382    pub(crate) time_profiler_sender: profile_time::ProfilerChan,
383
384    /// For providing contact with the memory profiler.
385    #[no_trace]
386    pub(crate) memory_profiler_sender: profile_mem::ProfilerChan,
387
388    /// For providing instructions to an optional devtools server.
389    #[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    /// A [`Receiver`] that receives messages from the constellation.
399    #[no_trace]
400    pub(crate) constellation_receiver: RoutedReceiver<ScriptThreadMessage>,
401
402    /// The [`Receiver`] which receives incoming messages from the `ImageCache`.
403    #[no_trace]
404    pub(crate) image_cache_receiver: Receiver<ImageCacheResponseMessage>,
405
406    /// For receiving commands from an optional devtools server. Will be ignored if no such server
407    /// exists. When devtools are not active this will be [`crossbeam_channel::never()`].
408    #[no_trace]
409    pub(crate) devtools_server_receiver: RoutedReceiver<DevtoolScriptControlMsg>,
410
411    /// Receiver to receive commands from optional WebGPU server. When there is no active
412    /// WebGPU context, this will be [`crossbeam_channel::never()`].
413    #[no_trace]
414    #[cfg(feature = "webgpu")]
415    pub(crate) webgpu_receiver: RefCell<RoutedReceiver<WebGPUMsg>>,
416}
417
418impl ScriptThreadReceivers {
419    /// Block until a message is received by any of the receivers of this [`ScriptThreadReceivers`]
420    /// or the given [`TaskQueue`] or [`TimerScheduler`]. Return the first message received.
421    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    /// Try to receive a from any of the receivers of this [`ScriptThreadReceivers`] or the given
462    /// [`TaskQueue`]. Return `None` if no messages are ready to be received.
463    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}