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://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::NavigationAndTraversal => {
73                ScriptThreadEventCategory::NavigationAndTraversalEvent
74            },
75            TaskSourceName::Networking => ScriptThreadEventCategory::NetworkEvent,
76            TaskSourceName::PerformanceTimeline => {
77                ScriptThreadEventCategory::PerformanceTimelineTask
78            },
79            TaskSourceName::PortMessage => ScriptThreadEventCategory::PortMessage,
80            TaskSourceName::UserInteraction => ScriptThreadEventCategory::InputEvent,
81            TaskSourceName::RemoteEvent => ScriptThreadEventCategory::NetworkEvent,
82            TaskSourceName::Rendering => ScriptThreadEventCategory::Rendering,
83            TaskSourceName::MediaElement => ScriptThreadEventCategory::ScriptEvent,
84            TaskSourceName::WebSocket => ScriptThreadEventCategory::WebSocketEvent,
85            TaskSourceName::Timer => ScriptThreadEventCategory::TimerEvent,
86            TaskSourceName::Gamepad => ScriptThreadEventCategory::InputEvent,
87            TaskSourceName::IntersectionObserver => ScriptThreadEventCategory::ScriptEvent,
88            TaskSourceName::WebGPU => ScriptThreadEventCategory::ScriptEvent,
89        }
90    }
91}
92
93pub(crate) struct TaskSource<'task_manager> {
94    pub(crate) task_manager: &'task_manager TaskManager,
95    pub(crate) name: TaskSourceName,
96}
97
98impl TaskSource<'_> {
99    /// Queue a task with the default canceller for this [`TaskSource`].
100    pub(crate) fn queue(&self, task: impl TaskOnce + 'static) {
101        let canceller = self.task_manager.canceller(self.name);
102        if canceller.cancelled() {
103            return;
104        }
105
106        self.queue_unconditionally(canceller.wrap_task(task))
107    }
108
109    /// This queues a task that will not be cancelled when its associated global scope gets destroyed.
110    pub(crate) fn queue_unconditionally(&self, task: impl TaskOnce + 'static) {
111        let sender = self.task_manager.sender();
112        sender
113            .as_ref()
114            .expect("Tried to enqueue task for DedicatedWorker while not handling a message.")
115            .send(CommonScriptMsg::Task(
116                self.name.into(),
117                Box::new(task),
118                Some(self.task_manager.pipeline_id()),
119                self.name,
120            ))
121            .expect("Tried to send a task on a task queue after shutdown.");
122    }
123
124    pub(crate) fn queue_simple_event(&self, target: &EventTarget, name: Atom) {
125        let target = Trusted::new(target);
126        self.queue(SimpleEventTask { target, name });
127    }
128
129    pub(crate) fn queue_event(
130        &self,
131        target: &EventTarget,
132        name: Atom,
133        bubbles: EventBubbles,
134        cancelable: EventCancelable,
135    ) {
136        let target = Trusted::new(target);
137        self.queue(EventTask {
138            target,
139            name,
140            bubbles,
141            cancelable,
142        });
143    }
144
145    /// Convert this [`TaskSource`] into a [`SendableTaskSource`] suitable for sending
146    /// to different threads.
147    pub(crate) fn to_sendable(&self) -> SendableTaskSource {
148        let sender = self.task_manager.sender();
149        let sender = sender
150            .as_ref()
151            .expect("Tried to enqueue task for DedicatedWorker while not handling a message.")
152            .clone();
153        SendableTaskSource {
154            sender,
155            pipeline_id: self.task_manager.pipeline_id(),
156            name: self.name,
157            canceller: self.task_manager.canceller(self.name),
158        }
159    }
160}
161
162impl<'task_manager> From<TaskSource<'task_manager>> for SendableTaskSource {
163    fn from(task_source: TaskSource<'task_manager>) -> Self {
164        task_source.to_sendable()
165    }
166}
167
168#[derive(JSTraceable, MallocSizeOf)]
169pub(crate) struct SendableTaskSource {
170    pub(crate) sender: ScriptEventLoopSender,
171    #[no_trace]
172    pub(crate) pipeline_id: PipelineId,
173    pub(crate) name: TaskSourceName,
174    pub(crate) canceller: TaskCanceller,
175}
176
177impl SendableTaskSource {
178    pub(crate) fn queue(&self, task: impl TaskOnce + 'static) {
179        if !self.canceller.cancelled() {
180            self.queue_unconditionally(self.canceller.wrap_task(task))
181        }
182    }
183
184    /// This queues a task that will not be cancelled when its associated global scope gets destroyed.
185    pub(crate) fn queue_unconditionally(&self, task: impl TaskOnce + 'static) {
186        if self
187            .sender
188            .send(CommonScriptMsg::Task(
189                self.name.into(),
190                Box::new(task),
191                Some(self.pipeline_id),
192                self.name,
193            ))
194            .is_err()
195        {
196            warn!(
197                "Could not queue non-main-thread task {:?}. Likely tried to queue during shutdown.",
198                self.name
199            );
200        }
201    }
202}
203
204impl Clone for SendableTaskSource {
205    fn clone(&self) -> Self {
206        Self {
207            sender: self.sender.clone(),
208            pipeline_id: self.pipeline_id,
209            name: self.name,
210            canceller: self.canceller.clone(),
211        }
212    }
213}
214
215impl fmt::Debug for SendableTaskSource {
216    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
217        write!(f, "{:?}(...)", self.name)
218    }
219}