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