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::{GenericSender, RoutedReceiver};
12use base::id::PipelineId;
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::ScriptToEmbedderChan;
19use ipc_channel::ipc::IpcSender;
20use net_traits::FetchResponseMsg;
21use net_traits::image_cache::ImageCacheResponseMessage;
22use profile_traits::mem::{self as profile_mem, OpaqueSender, ReportsChan};
23use profile_traits::time::{self as profile_time};
24use rustc_hash::FxHashSet;
25use script_traits::{Painter, ScriptThreadMessage};
26use stylo_atoms::Atom;
27use timers::TimerScheduler;
28#[cfg(feature = "webgpu")]
29use webgpu_traits::WebGPUMsg;
30
31use crate::dom::abstractworker::WorkerScriptMsg;
32use crate::dom::bindings::trace::CustomTraceable;
33use crate::dom::csp::Violation;
34use crate::dom::dedicatedworkerglobalscope::DedicatedWorkerScriptMsg;
35use crate::dom::serviceworkerglobalscope::ServiceWorkerScriptMsg;
36use crate::dom::worker::TrustedWorkerAddress;
37use crate::script_runtime::ScriptThreadEventCategory;
38use crate::task::TaskBox;
39use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue};
40use crate::task_source::TaskSourceName;
41
42#[allow(clippy::large_enum_variant)]
43#[derive(Debug)]
44pub(crate) enum MixedMessage {
45    FromConstellation(ScriptThreadMessage),
46    FromScript(MainThreadScriptMsg),
47    FromDevtools(DevtoolScriptControlMsg),
48    FromImageCache(ImageCacheResponseMessage),
49    #[cfg(feature = "webgpu")]
50    FromWebGPUServer(WebGPUMsg),
51    TimerFired,
52}
53
54impl MixedMessage {
55    pub(crate) fn pipeline_id(&self) -> Option<PipelineId> {
56        match self {
57            MixedMessage::FromConstellation(inner_msg) => match inner_msg {
58                ScriptThreadMessage::StopDelayingLoadEventsMode(id) => Some(*id),
59                ScriptThreadMessage::AttachLayout(new_layout_info) => new_layout_info
60                    .parent_info
61                    .or(Some(new_layout_info.new_pipeline_id)),
62                ScriptThreadMessage::Resize(id, ..) => Some(*id),
63                ScriptThreadMessage::ThemeChange(id, ..) => Some(*id),
64                ScriptThreadMessage::ResizeInactive(id, ..) => Some(*id),
65                ScriptThreadMessage::UnloadDocument(id) => Some(*id),
66                ScriptThreadMessage::ExitPipeline(_webview_id, id, ..) => Some(*id),
67                ScriptThreadMessage::ExitScriptThread => None,
68                ScriptThreadMessage::SendInputEvent(_, id, _) => Some(*id),
69                ScriptThreadMessage::RefreshCursor(id, ..) => Some(*id),
70                ScriptThreadMessage::Viewport(id, ..) => Some(*id),
71                ScriptThreadMessage::GetTitle(id) => Some(*id),
72                ScriptThreadMessage::SetDocumentActivity(id, ..) => Some(*id),
73                ScriptThreadMessage::SetThrottled(id, ..) => Some(*id),
74                ScriptThreadMessage::SetThrottledInContainingIframe(id, ..) => Some(*id),
75                ScriptThreadMessage::NavigateIframe(id, ..) => Some(*id),
76                ScriptThreadMessage::PostMessage { target: id, .. } => Some(*id),
77                ScriptThreadMessage::UpdatePipelineId(_, _, _, id, _) => Some(*id),
78                ScriptThreadMessage::UpdateHistoryState(id, ..) => Some(*id),
79                ScriptThreadMessage::RemoveHistoryStates(id, ..) => Some(*id),
80                ScriptThreadMessage::FocusIFrame(id, ..) => Some(*id),
81                ScriptThreadMessage::FocusDocument(id, ..) => Some(*id),
82                ScriptThreadMessage::Unfocus(id, ..) => Some(*id),
83                ScriptThreadMessage::WebDriverScriptCommand(id, ..) => Some(*id),
84                ScriptThreadMessage::TickAllAnimations(..) => None,
85                ScriptThreadMessage::WebFontLoaded(id, ..) => Some(*id),
86                ScriptThreadMessage::DispatchIFrameLoadEvent {
87                    target: _,
88                    parent: id,
89                    child: _,
90                } => Some(*id),
91                ScriptThreadMessage::DispatchStorageEvent(id, ..) => Some(*id),
92                ScriptThreadMessage::ReportCSSError(id, ..) => Some(*id),
93                ScriptThreadMessage::Reload(id, ..) => Some(*id),
94                ScriptThreadMessage::PaintMetric(id, ..) => Some(*id),
95                ScriptThreadMessage::ExitFullScreen(id, ..) => Some(*id),
96                ScriptThreadMessage::MediaSessionAction(..) => None,
97                #[cfg(feature = "webgpu")]
98                ScriptThreadMessage::SetWebGPUPort(..) => None,
99                ScriptThreadMessage::SetScrollStates(id, ..) => Some(*id),
100                ScriptThreadMessage::EvaluateJavaScript(id, _, _) => Some(*id),
101                ScriptThreadMessage::SendImageKeysBatch(..) => None,
102                ScriptThreadMessage::PreferencesUpdated(..) => None,
103                ScriptThreadMessage::NoLongerWaitingOnAsychronousImageUpdates(_) => None,
104                ScriptThreadMessage::ForwardKeyboardScroll(id, _) => Some(*id),
105                ScriptThreadMessage::RequestScreenshotReadiness(id) => Some(*id),
106                ScriptThreadMessage::EmbedderControlResponse(id, _) => Some(id.pipeline_id),
107            },
108            MixedMessage::FromScript(inner_msg) => match inner_msg {
109                MainThreadScriptMsg::Common(CommonScriptMsg::Task(_, _, pipeline_id, _)) => {
110                    *pipeline_id
111                },
112                MainThreadScriptMsg::Common(CommonScriptMsg::CollectReports(_)) => None,
113                MainThreadScriptMsg::Common(CommonScriptMsg::ReportCspViolations(
114                    pipeline_id,
115                    _,
116                )) => Some(*pipeline_id),
117                MainThreadScriptMsg::NavigationResponse { pipeline_id, .. } => Some(*pipeline_id),
118                MainThreadScriptMsg::WorkletLoaded(pipeline_id) => Some(*pipeline_id),
119                MainThreadScriptMsg::RegisterPaintWorklet { pipeline_id, .. } => Some(*pipeline_id),
120                MainThreadScriptMsg::Inactive => None,
121                MainThreadScriptMsg::WakeUp => None,
122            },
123            MixedMessage::FromImageCache(response) => match response {
124                ImageCacheResponseMessage::NotifyPendingImageLoadStatus(response) => {
125                    Some(response.pipeline_id)
126                },
127                ImageCacheResponseMessage::VectorImageRasterizationComplete(response) => {
128                    Some(response.pipeline_id)
129                },
130            },
131            MixedMessage::FromDevtools(_) | MixedMessage::TimerFired => None,
132            #[cfg(feature = "webgpu")]
133            MixedMessage::FromWebGPUServer(..) => None,
134        }
135    }
136}
137
138/// Messages used to control the script event loop.
139#[derive(Debug)]
140pub(crate) enum MainThreadScriptMsg {
141    /// Common variants associated with the script messages
142    Common(CommonScriptMsg),
143    /// Notifies the script thread that a new worklet has been loaded, and thus the page should be
144    /// reflowed.
145    WorkletLoaded(PipelineId),
146    NavigationResponse {
147        pipeline_id: PipelineId,
148        message: Box<FetchResponseMsg>,
149    },
150    /// Notifies the script thread that a new paint worklet has been registered.
151    RegisterPaintWorklet {
152        pipeline_id: PipelineId,
153        name: Atom,
154        properties: Vec<Atom>,
155        painter: Box<dyn Painter>,
156    },
157    /// A task related to a not fully-active document has been throttled.
158    Inactive,
159    /// Wake-up call from the task queue.
160    WakeUp,
161}
162
163/// Common messages used to control the event loops in both the script and the worker
164pub(crate) enum CommonScriptMsg {
165    /// Requests that the script thread measure its memory usage. The results are sent back via the
166    /// supplied channel.
167    CollectReports(ReportsChan),
168    /// Generic message that encapsulates event handling.
169    Task(
170        ScriptThreadEventCategory,
171        Box<dyn TaskBox>,
172        Option<PipelineId>,
173        TaskSourceName,
174    ),
175    /// Report CSP violations in the script
176    ReportCspViolations(PipelineId, Vec<Violation>),
177}
178
179impl fmt::Debug for CommonScriptMsg {
180    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
181        match *self {
182            CommonScriptMsg::CollectReports(_) => write!(f, "CollectReports(...)"),
183            CommonScriptMsg::Task(ref category, ref task, _, _) => {
184                f.debug_tuple("Task").field(category).field(task).finish()
185            },
186            CommonScriptMsg::ReportCspViolations(..) => write!(f, "ReportCspViolations(...)"),
187        }
188    }
189}
190
191/// A wrapper around various types of `Sender`s that send messages back to the event loop
192/// of a script context event loop. This will either target the main `ScriptThread` event
193/// loop or that of a worker.
194#[derive(Clone, JSTraceable, MallocSizeOf)]
195pub(crate) enum ScriptEventLoopSender {
196    /// A sender that sends to the main `ScriptThread` event loop.
197    MainThread(Sender<MainThreadScriptMsg>),
198    /// A sender that sends to a `ServiceWorker` event loop.
199    ServiceWorker(Sender<ServiceWorkerScriptMsg>),
200    /// A sender that sends to a dedicated worker (such as a generic Web Worker) event loop.
201    /// Note that this sender keeps the main thread Worker DOM object alive as long as it or
202    /// or any message it sends is not dropped.
203    DedicatedWorker {
204        sender: Sender<DedicatedWorkerScriptMsg>,
205        main_thread_worker: TrustedWorkerAddress,
206    },
207}
208
209impl ScriptEventLoopSender {
210    /// Send a message to the event loop, which might be a main thread event loop or a worker event loop.
211    pub(crate) fn send(&self, message: CommonScriptMsg) -> Result<(), SendError<()>> {
212        match self {
213            Self::MainThread(sender) => sender
214                .send(MainThreadScriptMsg::Common(message))
215                .map_err(|_| SendError(())),
216            Self::ServiceWorker(sender) => sender
217                .send(ServiceWorkerScriptMsg::CommonWorker(
218                    WorkerScriptMsg::Common(message),
219                ))
220                .map_err(|_| SendError(())),
221            Self::DedicatedWorker {
222                sender,
223                main_thread_worker,
224            } => {
225                let common_message = WorkerScriptMsg::Common(message);
226                sender
227                    .send(DedicatedWorkerScriptMsg::CommonWorker(
228                        main_thread_worker.clone(),
229                        common_message,
230                    ))
231                    .map_err(|_| SendError(()))
232            },
233        }
234    }
235}
236
237/// A wrapper around various types of `Receiver`s that receive event loop messages. Used for
238/// synchronous DOM APIs that need to abstract over multiple kinds of event loops (worker/main
239/// thread) with different Receiver interfaces.
240pub(crate) enum ScriptEventLoopReceiver {
241    /// A receiver that receives messages to the main `ScriptThread` event loop.
242    MainThread(Receiver<MainThreadScriptMsg>),
243    /// A receiver that receives messages to dedicated workers (such as a generic Web Worker) event loop.
244    DedicatedWorker(Receiver<DedicatedWorkerScriptMsg>),
245}
246
247impl ScriptEventLoopReceiver {
248    pub(crate) fn recv(&self) -> Result<CommonScriptMsg, ()> {
249        match self {
250            Self::MainThread(receiver) => match receiver.recv() {
251                Ok(MainThreadScriptMsg::Common(script_msg)) => Ok(script_msg),
252                Ok(_) => panic!("unexpected main thread event message!"),
253                Err(_) => Err(()),
254            },
255            Self::DedicatedWorker(receiver) => match receiver.recv() {
256                Ok(DedicatedWorkerScriptMsg::CommonWorker(_, WorkerScriptMsg::Common(message))) => {
257                    Ok(message)
258                },
259                Ok(_) => panic!("unexpected worker event message!"),
260                Err(_) => Err(()),
261            },
262        }
263    }
264}
265
266impl QueuedTaskConversion for MainThreadScriptMsg {
267    fn task_source_name(&self) -> Option<&TaskSourceName> {
268        let script_msg = match self {
269            MainThreadScriptMsg::Common(script_msg) => script_msg,
270            _ => return None,
271        };
272        match script_msg {
273            CommonScriptMsg::Task(_category, _boxed, _pipeline_id, task_source) => {
274                Some(task_source)
275            },
276            _ => None,
277        }
278    }
279
280    fn pipeline_id(&self) -> Option<PipelineId> {
281        let script_msg = match self {
282            MainThreadScriptMsg::Common(script_msg) => script_msg,
283            _ => return None,
284        };
285        match script_msg {
286            CommonScriptMsg::Task(_category, _boxed, pipeline_id, _task_source) => *pipeline_id,
287            _ => None,
288        }
289    }
290
291    fn into_queued_task(self) -> Option<QueuedTask> {
292        let script_msg = match self {
293            MainThreadScriptMsg::Common(script_msg) => script_msg,
294            _ => return None,
295        };
296        let (category, boxed, pipeline_id, task_source) = match script_msg {
297            CommonScriptMsg::Task(category, boxed, pipeline_id, task_source) => {
298                (category, boxed, pipeline_id, task_source)
299            },
300            _ => return None,
301        };
302        Some((None, category, boxed, pipeline_id, task_source))
303    }
304
305    fn from_queued_task(queued_task: QueuedTask) -> Self {
306        let (_worker, category, boxed, pipeline_id, task_source) = queued_task;
307        let script_msg = CommonScriptMsg::Task(category, boxed, pipeline_id, task_source);
308        MainThreadScriptMsg::Common(script_msg)
309    }
310
311    fn inactive_msg() -> Self {
312        MainThreadScriptMsg::Inactive
313    }
314
315    fn wake_up_msg() -> Self {
316        MainThreadScriptMsg::WakeUp
317    }
318
319    fn is_wake_up(&self) -> bool {
320        matches!(self, MainThreadScriptMsg::WakeUp)
321    }
322}
323
324impl OpaqueSender<CommonScriptMsg> for ScriptEventLoopSender {
325    fn send(&self, message: CommonScriptMsg) {
326        self.send(message).unwrap()
327    }
328}
329
330#[derive(Clone, JSTraceable)]
331pub(crate) struct ScriptThreadSenders {
332    /// A channel to hand out to script thread-based entities that need to be able to enqueue
333    /// events in the event queue.
334    pub(crate) self_sender: Sender<MainThreadScriptMsg>,
335
336    /// A handle to the bluetooth thread.
337    #[no_trace]
338    #[cfg(feature = "bluetooth")]
339    pub(crate) bluetooth_sender: IpcSender<BluetoothRequest>,
340
341    /// A [`Sender`] that sends messages to the `Constellation`.
342    #[no_trace]
343    pub(crate) constellation_sender: GenericSender<ScriptThreadMessage>,
344
345    /// A [`Sender`] that sends messages to the `Constellation` associated with
346    /// particular pipelines.
347    #[no_trace]
348    pub(crate) pipeline_to_constellation_sender:
349        GenericSender<(PipelineId, ScriptToConstellationMessage)>,
350
351    /// A channel to send messages to the Embedder.
352    #[no_trace]
353    pub(crate) pipeline_to_embedder_sender: ScriptToEmbedderChan,
354
355    /// The shared [`IpcSender`] which is sent to the `ImageCache` when requesting an image. The
356    /// messages on this channel are routed to crossbeam [`Sender`] on the router thread, which
357    /// in turn sends messages to [`ScriptThreadReceivers::image_cache_receiver`].
358    #[no_trace]
359    pub(crate) image_cache_sender: IpcSender<ImageCacheResponseMessage>,
360
361    /// For providing contact with the time profiler.
362    #[no_trace]
363    pub(crate) time_profiler_sender: profile_time::ProfilerChan,
364
365    /// For providing contact with the memory profiler.
366    #[no_trace]
367    pub(crate) memory_profiler_sender: profile_mem::ProfilerChan,
368
369    /// For providing instructions to an optional devtools server.
370    #[no_trace]
371    pub(crate) devtools_server_sender: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
372
373    #[no_trace]
374    pub(crate) devtools_client_to_script_thread_sender: IpcSender<DevtoolScriptControlMsg>,
375
376    #[no_trace]
377    pub(crate) content_process_shutdown_sender: Sender<()>,
378}
379
380#[derive(JSTraceable)]
381pub(crate) struct ScriptThreadReceivers {
382    /// A [`Receiver`] that receives messages from the constellation.
383    #[no_trace]
384    pub(crate) constellation_receiver: RoutedReceiver<ScriptThreadMessage>,
385
386    /// The [`Receiver`] which receives incoming messages from the `ImageCache`.
387    #[no_trace]
388    pub(crate) image_cache_receiver: Receiver<ImageCacheResponseMessage>,
389
390    /// For receiving commands from an optional devtools server. Will be ignored if no such server
391    /// exists. When devtools are not active this will be [`crossbeam_channel::never()`].
392    #[no_trace]
393    pub(crate) devtools_server_receiver: Receiver<DevtoolScriptControlMsg>,
394
395    /// Receiver to receive commands from optional WebGPU server. When there is no active
396    /// WebGPU context, this will be [`crossbeam_channel::never()`].
397    #[no_trace]
398    #[cfg(feature = "webgpu")]
399    pub(crate) webgpu_receiver: RefCell<Receiver<WebGPUMsg>>,
400}
401
402impl ScriptThreadReceivers {
403    /// Block until a message is received by any of the receivers of this [`ScriptThreadReceivers`]
404    /// or the given [`TaskQueue`] or [`TimerScheduler`]. Return the first message received.
405    pub(crate) fn recv(
406        &self,
407        task_queue: &TaskQueue<MainThreadScriptMsg>,
408        timer_scheduler: &TimerScheduler,
409        fully_active: &FxHashSet<PipelineId>,
410    ) -> MixedMessage {
411        select! {
412            recv(task_queue.select()) -> msg => {
413                task_queue.take_tasks(msg.unwrap(), fully_active);
414                let event = task_queue
415                    .recv()
416                    .expect("Spurious wake-up of the event-loop, task-queue has no tasks available");
417                MixedMessage::FromScript(event)
418            },
419            recv(self.constellation_receiver) -> msg => MixedMessage::FromConstellation(msg.unwrap().unwrap()),
420            recv(self.devtools_server_receiver) -> msg => MixedMessage::FromDevtools(msg.unwrap()),
421            recv(self.image_cache_receiver) -> msg => MixedMessage::FromImageCache(msg.unwrap()),
422            recv(timer_scheduler.wait_channel()) -> _ => MixedMessage::TimerFired,
423            recv({
424                #[cfg(feature = "webgpu")]
425                {
426                    self.webgpu_receiver.borrow()
427                }
428                #[cfg(not(feature = "webgpu"))]
429                {
430                    crossbeam_channel::never::<()>()
431                }
432            }) -> msg => {
433                #[cfg(feature = "webgpu")]
434                {
435                    MixedMessage::FromWebGPUServer(msg.unwrap())
436                }
437                #[cfg(not(feature = "webgpu"))]
438                {
439                    unreachable!("This should never be hit when webgpu is disabled ({msg:?})");
440                }
441            }
442        }
443    }
444
445    /// Try to receive a from any of the receivers of this [`ScriptThreadReceivers`] or the given
446    /// [`TaskQueue`]. Return `None` if no messages are ready to be received.
447    pub(crate) fn try_recv(
448        &self,
449        task_queue: &TaskQueue<MainThreadScriptMsg>,
450        fully_active: &FxHashSet<PipelineId>,
451    ) -> Option<MixedMessage> {
452        if let Ok(message) = self.constellation_receiver.try_recv() {
453            let message = message
454                .inspect_err(|e| {
455                    log::warn!(
456                        "ScriptThreadReceivers IPC error on constellation_receiver: {:?}",
457                        e
458                    );
459                })
460                .ok()?;
461            return MixedMessage::FromConstellation(message).into();
462        }
463        if let Ok(message) = task_queue.take_tasks_and_recv(fully_active) {
464            return MixedMessage::FromScript(message).into();
465        }
466        if let Ok(message) = self.devtools_server_receiver.try_recv() {
467            return MixedMessage::FromDevtools(message).into();
468        }
469        if let Ok(message) = self.image_cache_receiver.try_recv() {
470            return MixedMessage::FromImageCache(message).into();
471        }
472        #[cfg(feature = "webgpu")]
473        if let Ok(message) = self.webgpu_receiver.borrow().try_recv() {
474            return MixedMessage::FromWebGPUServer(message).into();
475        }
476        None
477    }
478}