script/
task_source.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 std::fmt;
6
7use base::id::PipelineId;
8use malloc_size_of_derive::MallocSizeOf;
9use strum_macros::VariantArray;
10use stylo_atoms::Atom;
11
12use crate::dom::bindings::refcounted::Trusted;
13use crate::dom::event::{EventBubbles, EventCancelable, EventTask, SimpleEventTask};
14use crate::dom::eventtarget::EventTarget;
15use crate::messaging::{CommonScriptMsg, ScriptEventLoopSender};
16use crate::script_runtime::ScriptThreadEventCategory;
17use crate::task::{TaskCanceller, TaskOnce};
18use crate::task_manager::TaskManager;
19
20/// The names of all task sources, used to differentiate TaskCancellers. Note: When adding a task
21/// source, update this enum. Note: The HistoryTraversalTaskSource is not part of this, because it
22/// doesn't implement TaskSource.
23#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, MallocSizeOf, PartialEq, VariantArray)]
24pub(crate) enum TaskSourceName {
25    /// <https://html.spec.whatwg.org/multipage/#bitmap-task-source>
26    Bitmap,
27    Canvas,
28    Clipboard,
29    /// <https://w3c.github.io/webcrypto/#dfn-crypto-task-source-0>
30    Crypto,
31    DatabaseAccess,
32    /// <https://fetch.spec.whatwg.org/#deferred-fetch-task-source>
33    DeferredFetch,
34    DOMManipulation,
35    FileReading,
36    /// <https://drafts.csswg.org/css-font-loading/#task-source>
37    FontLoading,
38    HistoryTraversal,
39    Networking,
40    PerformanceTimeline,
41    PortMessage,
42    UserInteraction,
43    RemoteEvent,
44    /// <https://html.spec.whatwg.org/multipage/#rendering-task-source>
45    Rendering,
46    MediaElement,
47    WebSocket,
48    Timer,
49    /// <https://www.w3.org/TR/gamepad/#dfn-gamepad-task-source>
50    Gamepad,
51    /// <https://www.w3.org/TR/geolocation/#dfn-geolocation-task-source>
52    Geolocation,
53    /// <https://w3c.github.io/IntersectionObserver/#intersectionobserver-task-source>
54    IntersectionObserver,
55    /// <https://www.w3.org/TR/webgpu/#-webgpu-task-source>
56    WebGPU,
57}
58
59impl From<TaskSourceName> for ScriptThreadEventCategory {
60    fn from(value: TaskSourceName) -> Self {
61        match value {
62            TaskSourceName::Bitmap => ScriptThreadEventCategory::ScriptEvent,
63            TaskSourceName::Canvas => ScriptThreadEventCategory::ScriptEvent,
64            TaskSourceName::Clipboard => ScriptThreadEventCategory::ScriptEvent,
65            TaskSourceName::Crypto => ScriptThreadEventCategory::ScriptEvent,
66            TaskSourceName::DatabaseAccess => ScriptThreadEventCategory::ScriptEvent,
67            TaskSourceName::DeferredFetch => ScriptThreadEventCategory::NetworkEvent,
68            TaskSourceName::DOMManipulation => ScriptThreadEventCategory::ScriptEvent,
69            TaskSourceName::FileReading => ScriptThreadEventCategory::FileRead,
70            TaskSourceName::FontLoading => ScriptThreadEventCategory::FontLoading,
71            TaskSourceName::Geolocation => ScriptThreadEventCategory::GeolocationEvent,
72            TaskSourceName::HistoryTraversal => ScriptThreadEventCategory::HistoryEvent,
73            TaskSourceName::Networking => ScriptThreadEventCategory::NetworkEvent,
74            TaskSourceName::PerformanceTimeline => {
75                ScriptThreadEventCategory::PerformanceTimelineTask
76            },
77            TaskSourceName::PortMessage => ScriptThreadEventCategory::PortMessage,
78            TaskSourceName::UserInteraction => ScriptThreadEventCategory::InputEvent,
79            TaskSourceName::RemoteEvent => ScriptThreadEventCategory::NetworkEvent,
80            TaskSourceName::Rendering => ScriptThreadEventCategory::Rendering,
81            TaskSourceName::MediaElement => ScriptThreadEventCategory::ScriptEvent,
82            TaskSourceName::WebSocket => ScriptThreadEventCategory::WebSocketEvent,
83            TaskSourceName::Timer => ScriptThreadEventCategory::TimerEvent,
84            TaskSourceName::Gamepad => ScriptThreadEventCategory::InputEvent,
85            TaskSourceName::IntersectionObserver => ScriptThreadEventCategory::ScriptEvent,
86            TaskSourceName::WebGPU => ScriptThreadEventCategory::ScriptEvent,
87        }
88    }
89}
90
91pub(crate) struct TaskSource<'task_manager> {
92    pub(crate) task_manager: &'task_manager TaskManager,
93    pub(crate) name: TaskSourceName,
94}
95
96impl TaskSource<'_> {
97    /// Queue a task with the default canceller for this [`TaskSource`].
98    pub(crate) fn queue(&self, task: impl TaskOnce + 'static) {
99        let canceller = self.task_manager.canceller(self.name);
100        if canceller.cancelled() {
101            return;
102        }
103
104        self.queue_unconditionally(canceller.wrap_task(task))
105    }
106
107    /// This queues a task that will not be cancelled when its associated global scope gets destroyed.
108    pub(crate) fn queue_unconditionally(&self, task: impl TaskOnce + 'static) {
109        let sender = self.task_manager.sender();
110        sender
111            .as_ref()
112            .expect("Tried to enqueue task for DedicatedWorker while not handling a message.")
113            .send(CommonScriptMsg::Task(
114                self.name.into(),
115                Box::new(task),
116                Some(self.task_manager.pipeline_id()),
117                self.name,
118            ))
119            .expect("Tried to send a task on a task queue after shutdown.");
120    }
121
122    pub(crate) fn queue_simple_event(&self, target: &EventTarget, name: Atom) {
123        let target = Trusted::new(target);
124        self.queue(SimpleEventTask { target, name });
125    }
126
127    pub(crate) fn queue_event(
128        &self,
129        target: &EventTarget,
130        name: Atom,
131        bubbles: EventBubbles,
132        cancelable: EventCancelable,
133    ) {
134        let target = Trusted::new(target);
135        self.queue(EventTask {
136            target,
137            name,
138            bubbles,
139            cancelable,
140        });
141    }
142
143    /// Convert this [`TaskSource`] into a [`SendableTaskSource`] suitable for sending
144    /// to different threads.
145    pub(crate) fn to_sendable(&self) -> SendableTaskSource {
146        let sender = self.task_manager.sender();
147        let sender = sender
148            .as_ref()
149            .expect("Tried to enqueue task for DedicatedWorker while not handling a message.")
150            .clone();
151        SendableTaskSource {
152            sender,
153            pipeline_id: self.task_manager.pipeline_id(),
154            name: self.name,
155            canceller: self.task_manager.canceller(self.name),
156        }
157    }
158}
159
160impl<'task_manager> From<TaskSource<'task_manager>> for SendableTaskSource {
161    fn from(task_source: TaskSource<'task_manager>) -> Self {
162        task_source.to_sendable()
163    }
164}
165
166#[derive(JSTraceable, MallocSizeOf)]
167pub(crate) struct SendableTaskSource {
168    pub(crate) sender: ScriptEventLoopSender,
169    #[no_trace]
170    pub(crate) pipeline_id: PipelineId,
171    pub(crate) name: TaskSourceName,
172    pub(crate) canceller: TaskCanceller,
173}
174
175impl SendableTaskSource {
176    pub(crate) fn queue(&self, task: impl TaskOnce + 'static) {
177        if !self.canceller.cancelled() {
178            self.queue_unconditionally(self.canceller.wrap_task(task))
179        }
180    }
181
182    /// This queues a task that will not be cancelled when its associated global scope gets destroyed.
183    pub(crate) fn queue_unconditionally(&self, task: impl TaskOnce + 'static) {
184        if self
185            .sender
186            .send(CommonScriptMsg::Task(
187                self.name.into(),
188                Box::new(task),
189                Some(self.pipeline_id),
190                self.name,
191            ))
192            .is_err()
193        {
194            warn!(
195                "Could not queue non-main-thread task {:?}. Likely tried to queue during shutdown.",
196                self.name
197            );
198        }
199    }
200}
201
202impl Clone for SendableTaskSource {
203    fn clone(&self) -> Self {
204        Self {
205            sender: self.sender.clone(),
206            pipeline_id: self.pipeline_id,
207            name: self.name,
208            canceller: self.canceller.clone(),
209        }
210    }
211}
212
213impl fmt::Debug for SendableTaskSource {
214    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
215        write!(f, "{:?}(...)", self.name)
216    }
217}