Skip to main content

servo_constellation/
constellation_webview.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::cell::{Cell, RefCell};
6use std::collections::{HashMap, VecDeque};
7use std::rc::Rc;
8
9use embedder_traits::user_contents::UserContentManagerId;
10use embedder_traits::{InputEvent, MouseLeftViewportEvent, Theme, ViewportDetails};
11use euclid::Size2D;
12use log::{debug, warn};
13use paint_api::{PaintMessage, PaintProxy};
14use rustc_hash::{FxHashMap, FxHashSet};
15use script_traits::{ConstellationInputEvent, ScriptThreadMessage, WebViewState};
16use servo_base::Epoch;
17use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
18use servo_constellation_traits::{ScreenshotReadinessResponse, SessionHistoryTraversalRequest};
19
20use crate::browsingcontext::{BrowsingContext, FullyActiveBrowsingContextsIterator};
21use crate::constellation::BrowsingContextGroup;
22use crate::pipeline::Pipeline;
23use crate::screenshot_readiness_request::{ScreenshotReadinessRequest, ScreenshotRequestState};
24use crate::session_history::{JointSessionHistory, SessionHistoryChange};
25
26/// The `Constellation`'s view of a `WebView` in the embedding layer. This tracks all of the
27/// `Constellation` state for this `WebView`.
28pub(crate) struct ConstellationWebView {
29    /// The [`WebViewId`] of this [`ConstellationWebView`].
30    webview_id: WebViewId,
31
32    /// The [`PipelineId`] of the currently active pipeline at the top level of this WebView.
33    pub active_top_level_pipeline_id: Option<PipelineId>,
34
35    /// A counter for changes to [`Self::active_top_level_pipeline_id`].
36    pub active_top_level_pipeline_epoch: Epoch,
37
38    /// When a navigation is performed, we do not immediately update
39    /// the session history, instead we ask the event loop to begin loading
40    /// the new document, and do not update the browsing context until the
41    /// document is active. Between starting the load and it activating,
42    /// we store a `SessionHistoryChange` object for the navigation in progress.
43    pub pending_changes: Vec<SessionHistoryChange>,
44
45    /// The [`BrowsingContextGroup`] associated with this [`ConstellationWebView`]. Every
46    /// `WebView` has a single [`BrowsingContextGroup`], but that group may be shared amongst
47    /// multiple `WebView`s in the case of `window.open()`.
48    browsing_context_group: Rc<RefCell<BrowsingContextGroup>>,
49
50    /// The currently focused browsing context in this webview for key events.
51    /// The focused pipeline is the current entry of the focused browsing
52    /// context.
53    pub focused_browsing_context_id: BrowsingContextId,
54
55    /// The [`BrowsingContextId`] of the currently hovered browsing context, to use for
56    /// knowing which frame is currently receiving cursor events.
57    pub hovered_browsing_context_id: Option<BrowsingContextId>,
58
59    /// The joint session history for this webview.
60    pub session_history: JointSessionHistory,
61
62    /// <https://html.spec.whatwg.org/multipage/#tn-session-history-traversal-queue>
63    ///
64    /// A queue of traversals that should be applied sequentially. The next item from
65    /// the queue is applied once [`Self::ongoing_history_traversal_request`] has finished.
66    pub session_history_traversal_request_queue: VecDeque<SessionHistoryTraversalRequest>,
67
68    /// The currently running session history traversal. This will be completed once all
69    /// `Pipeline`s in a traversal become active or their load fails for some other reason.
70    pub ongoing_history_traversal_request: Option<OngoingHistoryTraversalRequest>,
71
72    /// Pending viewport changes for browsing contexts that are not
73    /// yet known to the constellation.
74    pending_viewport_details: HashMap<BrowsingContextId, ViewportDetails>,
75
76    /// The [`UserContentManagerId`] for all pipelines in this `WebView`. This is `Some`
77    /// if the embedder has set a `UserContentManager` using the WebViewBuilder API and
78    /// it is `None` otherwise.
79    pub user_content_manager_id: Option<UserContentManagerId>,
80
81    /// The [`Theme`] that this [`ConstellationWebView`] uses. This is communicated to all
82    /// `ScriptThread`s so that they know how to render the contents of a particular `WebView.
83    theme: Theme,
84
85    /// Whether or not this entire [`ConstellationWebView`] is hidden. `WebView`s that
86    /// are hidden will be throttled.
87    hidden: bool,
88
89    /// Whether or not this [`ConstellationWebView`] has system focus. This is
90    /// a distinct piece of state from [`Self::focused_browsing_context_id`] which
91    /// tracks the frame with focus regardless of system focus state.
92    has_system_focus: bool,
93
94    /// Whether accessibility is active for this webview.
95    ///
96    /// Set by [`crate::Constellation::set_accessibility_active()`], and forwarded to the
97    /// webview’s *active* pipelines (of those that represent documents) at any given moment
98    /// via [`ScriptThreadMessage::SetAccessibilityActive`] in `set_accessibility_active()`
99    /// and [`crate::Constellation::set_frame_tree_for_webview()`].
100    pub accessibility_active: bool,
101
102    /// Pending screenshot readiness requests. These are collected until the screenshot is
103    /// ready to take place, at which point the Constellation informs the renderer that it
104    /// can start the process of taking the screenshot.
105    screenshot_readiness_requests: Vec<ScreenshotReadinessRequest>,
106}
107
108impl ConstellationWebView {
109    pub(crate) fn new(
110        webview_id: WebViewId,
111        browsing_context_group: Rc<RefCell<BrowsingContextGroup>>,
112        focused_browsing_context_id: BrowsingContextId,
113        user_content_manager_id: Option<UserContentManagerId>,
114    ) -> Self {
115        Self {
116            webview_id,
117            user_content_manager_id,
118            active_top_level_pipeline_id: None,
119            active_top_level_pipeline_epoch: Epoch::default(),
120            pending_changes: Default::default(),
121            browsing_context_group,
122            focused_browsing_context_id,
123            hovered_browsing_context_id: None,
124            session_history: JointSessionHistory::new(),
125            session_history_traversal_request_queue: Default::default(),
126            ongoing_history_traversal_request: None,
127            pending_viewport_details: Default::default(),
128            theme: Theme::Light,
129            hidden: false,
130            has_system_focus: true,
131            accessibility_active: false,
132            screenshot_readiness_requests: Default::default(),
133        }
134    }
135
136    pub(crate) fn browsing_context_group(&self) -> Rc<RefCell<BrowsingContextGroup>> {
137        self.browsing_context_group.clone()
138    }
139
140    /// Set the [`Theme`] on this [`ConstellationWebView`] returning true if the theme changed.
141    pub(crate) fn set_theme(&mut self, new_theme: Theme) -> bool {
142        let old_theme = std::mem::replace(&mut self.theme, new_theme);
143        old_theme != self.theme
144    }
145
146    /// Get the [`Theme`] of this [`ConstellationWebView`].
147    pub(crate) fn theme(&self) -> Theme {
148        self.theme
149    }
150
151    /// Whether or not the [`ConstellationWebView`] is hidden.
152    pub(crate) fn hidden(&self) -> bool {
153        self.hidden
154    }
155
156    /// Create a [`WebViewState`] for this [`ConstellationWebView`] to pass during pipeline
157    /// creation.
158    pub(crate) fn state(&self) -> WebViewState {
159        WebViewState {
160            id: self.webview_id,
161            theme: Cell::new(self.theme),
162            has_system_focus: Cell::new(self.has_system_focus),
163        }
164    }
165
166    /// Set whether or not this [`ConstellationWebView`] is hidden, returning true if the
167    /// value changed.
168    pub(crate) fn set_hidden(&mut self, hidden: bool) -> bool {
169        let old_hidden = std::mem::replace(&mut self.hidden, hidden);
170        old_hidden != self.hidden
171    }
172
173    /// Set whether or not this [`ConstellationWebView`] has system focus, returning true
174    /// if the value changed.
175    pub(crate) fn set_has_system_focus(&mut self, has_system_focus: bool) -> bool {
176        let old_has_system_focus = std::mem::replace(&mut self.has_system_focus, has_system_focus);
177        old_has_system_focus != self.has_system_focus
178    }
179
180    fn target_pipeline_id_for_input_event(
181        &self,
182        event: &ConstellationInputEvent,
183        browsing_contexts: &FxHashMap<BrowsingContextId, BrowsingContext>,
184    ) -> Option<PipelineId> {
185        if let Some(hit_test_result) = &event.hit_test_result {
186            return Some(hit_test_result.pipeline_id);
187        }
188
189        // If there's no hit test, send the event to either the hovered or focused browsing context,
190        // depending on the event type.
191        let browsing_context_id = if matches!(event.event.event, InputEvent::MouseLeftViewport(_)) {
192            self.hovered_browsing_context_id
193                .unwrap_or(self.focused_browsing_context_id)
194        } else {
195            self.focused_browsing_context_id
196        };
197
198        Some(browsing_contexts.get(&browsing_context_id)?.pipeline_id)
199    }
200
201    /// Forward the [`InputEvent`] to this [`ConstellationWebView`]. Returns false if
202    /// the event could not be forwarded or true otherwise.
203    pub(crate) fn forward_input_event(
204        &mut self,
205        event: ConstellationInputEvent,
206        pipelines: &FxHashMap<PipelineId, Pipeline>,
207        browsing_contexts: &FxHashMap<BrowsingContextId, BrowsingContext>,
208    ) -> bool {
209        let Some(pipeline_id) = self.target_pipeline_id_for_input_event(&event, browsing_contexts)
210        else {
211            warn!("Unknown pipeline for input event. Ignoring.");
212            return false;
213        };
214        let Some(pipeline) = pipelines.get(&pipeline_id) else {
215            warn!("Unknown pipeline id {pipeline_id:?} for input event. Ignoring.");
216            return false;
217        };
218
219        let mut update_hovered_browsing_context =
220            |newly_hovered_browsing_context_id, focus_moving_to_another_iframe: bool| {
221                let old_hovered_context_id = std::mem::replace(
222                    &mut self.hovered_browsing_context_id,
223                    newly_hovered_browsing_context_id,
224                );
225                if old_hovered_context_id == newly_hovered_browsing_context_id {
226                    return;
227                }
228                let Some(old_hovered_context_id) = old_hovered_context_id else {
229                    return;
230                };
231                let Some(pipeline) = browsing_contexts
232                    .get(&old_hovered_context_id)
233                    .and_then(|browsing_context| pipelines.get(&browsing_context.pipeline_id))
234                else {
235                    return;
236                };
237
238                let mut synthetic_mouse_leave_event = event.clone();
239                synthetic_mouse_leave_event.event.event =
240                    InputEvent::MouseLeftViewport(MouseLeftViewportEvent {
241                        focus_moving_to_another_iframe,
242                    });
243
244                let _ = pipeline
245                    .event_loop
246                    .send(ScriptThreadMessage::SendInputEvent(
247                        self.webview_id,
248                        pipeline.id,
249                        synthetic_mouse_leave_event,
250                    ));
251            };
252
253        if let InputEvent::MouseLeftViewport(_) = &event.event.event {
254            update_hovered_browsing_context(None, false);
255            return true;
256        }
257
258        if let InputEvent::MouseMove(_) = &event.event.event {
259            update_hovered_browsing_context(Some(pipeline.browsing_context_id), true);
260        }
261
262        let _ = pipeline
263            .event_loop
264            .send(ScriptThreadMessage::SendInputEvent(
265                self.webview_id,
266                pipeline.id,
267                event,
268            ));
269        true
270    }
271
272    pub(crate) fn close_browsing_context(&mut self, browsing_context_id: BrowsingContextId) {
273        self.take_pending_viewport_details(&browsing_context_id);
274        self.session_history
275            .remove_entries_for_browsing_context(browsing_context_id);
276    }
277
278    /// If there is an ongoing history traversal request that is waiting on documents to
279    /// reload, check to see if none of its pipelines are awaiting activation. If that's the
280    /// case unset the ongoing request and return it.
281    pub(crate) fn maybe_finish_ongoing_session_history_traversal_request(
282        &mut self,
283    ) -> Option<SessionHistoryTraversalRequest> {
284        let ongoing_history_traversal_request = self.ongoing_history_traversal_request.as_mut()?;
285
286        let pipelines_with_pending_changes = self
287            .pending_changes
288            .iter()
289            .map(|change| change.new_pipeline_id)
290            .collect::<FxHashSet<_>>();
291        ongoing_history_traversal_request
292            .pipelines_awaiting_activation
293            .retain(|pipeline_id| pipelines_with_pending_changes.contains(pipeline_id));
294
295        if !ongoing_history_traversal_request
296            .pipelines_awaiting_activation
297            .is_empty()
298        {
299            return None;
300        }
301        Some(
302            self.ongoing_history_traversal_request
303                .take()
304                .expect("Guaranteed above")
305                .traversal_request,
306        )
307    }
308
309    pub(crate) fn has_pending_change(&self) -> bool {
310        !self.pending_changes.is_empty()
311    }
312
313    /// Whether a navigation is in flight in this [`ConstellationWebView`] that will
314    /// report its own end: a queued or ongoing history traversal,
315    /// or a `top_level_pipeline` has not finished loading,
316    /// or a top-level pending change.
317    pub(crate) fn is_navigating(&self, top_level_pipeline: Option<&Pipeline>) -> bool {
318        let top_level_browsing_context_id = BrowsingContextId::from(self.webview_id);
319        !self.session_history_traversal_request_queue.is_empty() ||
320            self.ongoing_history_traversal_request.is_some() ||
321            top_level_pipeline.is_some_and(|pipeline| !pipeline.load_finished) ||
322            self.pending_changes
323                .iter()
324                .any(|change| change.browsing_context_id == top_level_browsing_context_id)
325    }
326
327    pub(crate) fn pipeline_is_pending(&self, pipeline_id: PipelineId) -> bool {
328        self.pending_changes
329            .iter()
330            .any(|pending_change| pending_change.new_pipeline_id == pipeline_id)
331    }
332
333    pub(crate) fn add_pending_change(&mut self, change: SessionHistoryChange) {
334        debug!(
335            "adding pending session history change with {}",
336            if change.replace.is_some() {
337                "replacement"
338            } else {
339                "no replacement"
340            },
341        );
342        self.pending_changes.push(change);
343    }
344
345    pub(crate) fn remove_pending_change_for_pipeline(
346        &mut self,
347        pipeline_id: PipelineId,
348    ) -> Option<SessionHistoryChange> {
349        let pending_index = self
350            .pending_changes
351            .iter()
352            .rposition(|change| change.new_pipeline_id == pipeline_id)?;
353        Some(self.pending_changes.swap_remove(pending_index))
354    }
355
356    pub(crate) fn remove_pending_changes_for_browsing_context_id(
357        &mut self,
358        browsing_context_id: BrowsingContextId,
359    ) -> Vec<SessionHistoryChange> {
360        self.pending_changes
361            .extract_if(.., |change| {
362                change.browsing_context_id == browsing_context_id
363            })
364            .collect()
365    }
366
367    #[servo_tracing::instrument(skip_all)]
368    pub(crate) fn handle_screenshot_readiness_request(
369        &mut self,
370        browsing_contexts: &FxHashMap<BrowsingContextId, BrowsingContext>,
371        pipelines: &FxHashMap<PipelineId, Pipeline>,
372    ) {
373        self.screenshot_readiness_requests
374            .push(ScreenshotReadinessRequest {
375                pipeline_states: Default::default(),
376                state: Default::default(),
377            });
378        self.send_screenshot_readiness_requests_to_pipelines(browsing_contexts, pipelines);
379    }
380
381    pub(crate) fn send_screenshot_readiness_requests_to_pipelines(
382        &mut self,
383        browsing_contexts: &FxHashMap<BrowsingContextId, BrowsingContext>,
384        pipelines: &FxHashMap<PipelineId, Pipeline>,
385    ) {
386        // If there are pending loads, wait for those to complete.
387        if self.has_pending_change() {
388            return;
389        }
390
391        for screenshot_request in self.screenshot_readiness_requests.iter_mut() {
392            // Ignore this request if it is not pending.
393            if screenshot_request.state != ScreenshotRequestState::Pending {
394                continue;
395            }
396
397            screenshot_request.pipeline_states = FullyActiveBrowsingContextsIterator::new(
398                self.webview_id.into(),
399                browsing_contexts,
400                pipelines,
401            )
402            .filter_map(|browsing_context| {
403                let pipeline_id = browsing_context.pipeline_id;
404                let Some(pipeline) = pipelines.get(&pipeline_id) else {
405                    // This can happen while Servo is shutting down, so just ignore it for now.
406                    return None;
407                };
408                // If the rectangle for this BrowsingContext is zero, it will never be
409                // painted. In this case, don't query screenshot readiness as it won't
410                // contribute to the final output image.
411                if browsing_context.viewport_details.size == Size2D::zero() {
412                    return None;
413                }
414                let _ = pipeline
415                    .event_loop
416                    .send(ScriptThreadMessage::RequestScreenshotReadiness(
417                        pipeline.webview_id,
418                        pipeline_id,
419                    ));
420                Some((pipeline_id, None))
421            })
422            .collect();
423            screenshot_request.state = ScreenshotRequestState::WaitingOnScript;
424        }
425    }
426
427    #[servo_tracing::instrument(skip_all)]
428    pub(crate) fn handle_screenshot_readiness_response(
429        &mut self,
430        updated_pipeline_id: PipelineId,
431        response: ScreenshotReadinessResponse,
432        paint_proxy: &PaintProxy,
433    ) {
434        if self.screenshot_readiness_requests.is_empty() {
435            return;
436        }
437
438        self.screenshot_readiness_requests
439            .retain_mut(|screenshot_request| {
440                if screenshot_request.state != ScreenshotRequestState::WaitingOnScript {
441                    return true;
442                }
443
444                let mut has_pending_pipeline = false;
445                screenshot_request
446                    .pipeline_states
447                    .retain(|pipeline_id, state| {
448                        if *pipeline_id != updated_pipeline_id {
449                            has_pending_pipeline |= state.is_none();
450                            return true;
451                        }
452                        match response {
453                            ScreenshotReadinessResponse::Ready(epoch) => {
454                                *state = Some(epoch);
455                                true
456                            },
457                            ScreenshotReadinessResponse::NoLongerActive => false,
458                        }
459                    });
460
461                if has_pending_pipeline {
462                    return true;
463                }
464
465                let pipelines_and_epochs = screenshot_request
466                    .pipeline_states
467                    .iter()
468                    .map(|(pipeline_id, epoch)| {
469                        (
470                            *pipeline_id,
471                            epoch.expect("Should have an epoch when pipeline is ready."),
472                        )
473                    })
474                    .collect();
475                paint_proxy.send(PaintMessage::ScreenshotReadinessReponse(
476                    self.webview_id,
477                    pipelines_and_epochs,
478                ));
479
480                false
481            });
482    }
483
484    pub(crate) fn add_viewport_details(
485        &mut self,
486        browsing_context_id: BrowsingContextId,
487        viewport_details: ViewportDetails,
488    ) {
489        self.pending_viewport_details
490            .insert(browsing_context_id, viewport_details);
491    }
492
493    pub(crate) fn take_pending_viewport_details(
494        &mut self,
495        browsing_context_id: &BrowsingContextId,
496    ) -> Option<ViewportDetails> {
497        self.pending_viewport_details.remove(browsing_context_id)
498    }
499}
500
501/// A [`HistoryTraversalRequest`] that is in progress because it is waiting
502/// for documents that need reloading.
503pub(crate) struct OngoingHistoryTraversalRequest {
504    /// The [`HistoryTraversalRequest`] that spawned this series of navigations.
505    pub traversal_request: SessionHistoryTraversalRequest,
506    /// The ids of all the `Pipeline`s that needed reloading for this traversal.
507    /// Multiple pipelines can be traversed if the top-level document contained
508    /// `<iframe>`s / browsing contexts. The traversal is only done when all of
509    /// the pipelines are ready or have failed to load.
510    pub pipelines_awaiting_activation: FxHashSet<PipelineId>,
511}