Skip to main content

servo_constellation/
pipeline.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::rc::Rc;
6
7use embedder_traits::{AnimationState, FocusSequenceNumber};
8use layout_api::ScriptThreadFactory;
9use log::{debug, error, warn};
10use paint_api::{CompositionPipeline, PaintMessage, PaintProxy};
11use rustc_hash::FxHashSet;
12use script_traits::{
13    DiscardBrowsingContext, DocumentActivity, NewPipelineInfo, ScriptThreadMessage,
14};
15use servo_base::generic_channel::SendError;
16use servo_base::id::{BrowsingContextId, HistoryStateId, PipelineId, WebViewId, WorkerId};
17use servo_constellation_traits::{LoadData, ServiceWorkerManagerFactory};
18use servo_url::ServoUrl;
19
20use crate::Constellation;
21use crate::event_loop::EventLoop;
22
23/// A `Pipeline` is the constellation's view of a `Window`. Each pipeline has an event loop
24/// (executed by a script thread). A script thread may be responsible for many pipelines.
25pub struct Pipeline {
26    /// The ID of the pipeline.
27    pub id: PipelineId,
28
29    /// The ID of the browsing context that contains this Pipeline.
30    pub browsing_context_id: BrowsingContextId,
31
32    /// The [`WebViewId`] of the `WebView` that contains this Pipeline.
33    pub webview_id: WebViewId,
34
35    pub opener: Option<BrowsingContextId>,
36
37    /// The event loop handling this pipeline.
38    pub event_loop: Rc<EventLoop>,
39
40    /// A channel to `Paint`.
41    pub paint_proxy: PaintProxy,
42
43    /// The most recently loaded URL in this pipeline.
44    /// Note that this URL can change, for example if the page navigates
45    /// to a hash URL.
46    pub url: ServoUrl,
47
48    /// Whether this pipeline is currently running animations. Pipelines that are running
49    /// animations cause composites to be continually scheduled.
50    pub animation_state: AnimationState,
51
52    /// Whether the document for this pipeline has active animation frame callbacks.
53    pub document_callbacks_active: bool,
54
55    /// Workers in this pipeline with active animation frame callbacks.
56    pub worker_callbacks_active: FxHashSet<WorkerId>,
57
58    /// The last aggregate animation-callback state sent to Paint.
59    pub last_callbacks_active_sent_to_paint: bool,
60
61    /// The child browsing contexts of this pipeline (these are iframes in the document).
62    pub children: Vec<BrowsingContextId>,
63
64    /// The Load Data used to create this pipeline.
65    pub load_data: LoadData,
66
67    /// The active history state for this pipeline.
68    pub history_state_id: Option<HistoryStateId>,
69
70    /// Has this pipeline received a notification that it is completely loaded?
71    pub completely_loaded: bool,
72
73    /// Has this pipeline reported the end of its load? (No matter aborted or not)
74    pub load_finished: bool,
75
76    /// The title of this pipeline's document.
77    pub title: String,
78
79    /// The [`FocusSequenceNumber`] of this [`Pipeline`].
80    pub focus_sequence: FocusSequenceNumber,
81
82    /// Whether or not this [`Pipeline`] has an actively loading/loaded document. When there is
83    /// no active document, the [`Pipeline`] will never be unthrottled. Throttled pipelines do
84    /// not update animations and their timers are slowed.
85    has_active_document: bool,
86}
87
88impl Pipeline {
89    /// Possibly starts a script thread, in a new process if requested.
90    pub(crate) fn spawn<STF: ScriptThreadFactory, SWF: ServiceWorkerManagerFactory>(
91        new_pipeline_info: NewPipelineInfo,
92        event_loop: Rc<EventLoop>,
93        constellation: &Constellation<STF, SWF>,
94        webview_hidden: bool,
95    ) -> Result<Self, SendError> {
96        if let Err(error) = event_loop.send(ScriptThreadMessage::SpawnPipeline(
97            new_pipeline_info.clone(),
98        )) {
99            error!("Could not spawn Pipeline in EventLoop: {error}");
100            return Err(error);
101        }
102
103        Ok(Self::new_already_spawned(
104            new_pipeline_info.new_pipeline_id,
105            new_pipeline_info.browsing_context_id,
106            new_pipeline_info.webview_state.id,
107            new_pipeline_info.opener,
108            event_loop,
109            constellation.paint_proxy.clone(),
110            webview_hidden,
111            new_pipeline_info.load_data,
112        ))
113    }
114
115    /// Creates a new `Pipeline`, after it has been spawned in its [`EventLoop`].
116    #[expect(clippy::too_many_arguments)]
117    pub fn new_already_spawned(
118        id: PipelineId,
119        browsing_context_id: BrowsingContextId,
120        webview_id: WebViewId,
121        opener: Option<BrowsingContextId>,
122        event_loop: Rc<EventLoop>,
123        paint_proxy: PaintProxy,
124        webview_hidden: bool,
125        load_data: LoadData,
126    ) -> Self {
127        let pipeline = Self {
128            id,
129            browsing_context_id,
130            webview_id,
131            opener,
132            event_loop,
133            paint_proxy,
134            url: load_data.url.clone(),
135            children: vec![],
136            animation_state: AnimationState::NoAnimationsPresent,
137            document_callbacks_active: false,
138            worker_callbacks_active: FxHashSet::default(),
139            last_callbacks_active_sent_to_paint: false,
140            load_data,
141            history_state_id: None,
142            completely_loaded: false,
143            load_finished: false,
144            title: String::new(),
145            focus_sequence: FocusSequenceNumber::default(),
146            // Assume that every new Pipeline has an active document until told otherwise.
147            has_active_document: true,
148        };
149
150        if webview_hidden {
151            pipeline.send_throttle_messages(true);
152        }
153
154        pipeline
155    }
156
157    /// Let the `ScriptThread` for this [`Pipeline`] know that it has exited. If the `ScriptThread` hasn't
158    /// panicked and is still alive, it will send a `PipelineExited` message back to the `Constellation`
159    /// when it finishes cleaning up.
160    ///
161    /// Returns `true` if the channel is still alive or `false` otherwise.
162    pub fn send_exit_message_to_script(&self, discard_bc: DiscardBrowsingContext) -> bool {
163        debug!("{:?} Sending exit message to script", self.id);
164
165        // Script thread handles shutting down layout, and layout handles shutting down the painter.
166        // For now, if the script thread has failed, we give up on clean shutdown.
167        let result = self
168            .event_loop
169            .send(ScriptThreadMessage::ExitPipeline(
170                self.webview_id,
171                self.id,
172                discard_bc,
173            ))
174            .inspect_err(|error| warn!("Sending script exit message failed ({error})."));
175        !matches!(result, Err(SendError::Disconnected))
176    }
177
178    /// Notify this pipeline of its activity.
179    pub fn set_activity(&self, activity: DocumentActivity) {
180        let msg = ScriptThreadMessage::SetDocumentActivity(self.id, activity);
181        if let Err(e) = self.event_loop.send(msg) {
182            warn!("Sending activity message failed ({}).", e);
183        }
184    }
185
186    /// `Paint`'s view of a pipeline.
187    pub fn to_sendable(&self) -> CompositionPipeline {
188        CompositionPipeline {
189            id: self.id,
190            webview_id: self.webview_id,
191        }
192    }
193
194    /// Add a new child browsing context.
195    pub fn add_child(&mut self, browsing_context_id: BrowsingContextId) {
196        self.children.push(browsing_context_id);
197    }
198
199    /// Remove a child browsing context.
200    pub fn remove_child(&mut self, browsing_context_id: BrowsingContextId) {
201        match self
202            .children
203            .iter()
204            .position(|id| *id == browsing_context_id)
205        {
206            None => {
207                warn!(
208                    "Pipeline remove child already removed ({:?}).",
209                    browsing_context_id
210                )
211            },
212            Some(index) => {
213                self.children.remove(index);
214            },
215        }
216    }
217
218    /// Set whether or not this [`Pipeline`] has an active document.
219    pub(crate) fn set_has_active_document(&mut self, has_active_document: bool) {
220        if self.has_active_document == has_active_document {
221            return;
222        }
223
224        self.has_active_document = has_active_document;
225
226        // If the active document has gone away, throttle the WebView.
227        if !self.has_active_document {
228            self.send_throttle_messages(true);
229        }
230    }
231
232    /// Set whether this [`Pipeline`] is throttled or unthrottled. If the Pipeline
233    /// does not have an active Document, it will not be unthrottled until it does.
234    pub(crate) fn send_throttle_messages(&self, throttled: bool) {
235        // Never unthrottle Pipelines that do not have an active Document.
236        let throttled = !self.has_active_document || throttled;
237
238        if let Err(error) = self
239            .event_loop
240            .send(ScriptThreadMessage::SetThrottled(self.id, throttled))
241        {
242            warn!("Sending SetThrottled to script failed ({error}).");
243        }
244        self.paint_proxy.send(PaintMessage::SetThrottled(
245            self.webview_id,
246            self.id,
247            throttled,
248        ));
249    }
250}