script/
document_collection.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::collections::hash_map;
6
7use base::id::{BrowsingContextId, PipelineId};
8use rustc_hash::{FxBuildHasher, FxHashMap};
9
10use crate::dom::bindings::inheritance::Castable;
11use crate::dom::bindings::root::{Dom, DomRoot};
12use crate::dom::bindings::trace::HashMapTracedValues;
13use crate::dom::document::Document;
14use crate::dom::globalscope::GlobalScope;
15use crate::dom::html::htmliframeelement::HTMLIFrameElement;
16use crate::dom::window::Window;
17
18/// The collection of all [`Document`]s managed by the [`crate::script_thread::ScriptThread`].
19/// This is stored as a mapping of [`PipelineId`] to [`Document`], but for updating the
20/// rendering, [`Document`]s should be processed in order via [`Self::documents_in_order`].
21#[derive(JSTraceable)]
22#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
23pub(crate) struct DocumentCollection {
24    map: HashMapTracedValues<PipelineId, Dom<Document>, FxBuildHasher>,
25}
26
27impl DocumentCollection {
28    pub(crate) fn insert(&mut self, pipeline_id: PipelineId, doc: &Document) {
29        self.map.insert(pipeline_id, Dom::from_ref(doc));
30    }
31
32    pub(crate) fn remove(&mut self, pipeline_id: PipelineId) -> Option<DomRoot<Document>> {
33        self.map
34            .remove(&pipeline_id)
35            .map(|ref doc| DomRoot::from_ref(&**doc))
36    }
37
38    pub(crate) fn find_document(&self, pipeline_id: PipelineId) -> Option<DomRoot<Document>> {
39        self.map
40            .get(&pipeline_id)
41            .map(|doc| DomRoot::from_ref(&**doc))
42    }
43
44    pub(crate) fn find_window(&self, pipeline_id: PipelineId) -> Option<DomRoot<Window>> {
45        self.find_document(pipeline_id)
46            .map(|doc| DomRoot::from_ref(doc.window()))
47    }
48
49    pub(crate) fn find_global(&self, pipeline_id: PipelineId) -> Option<DomRoot<GlobalScope>> {
50        self.find_window(pipeline_id)
51            .map(|window| DomRoot::from_ref(window.upcast()))
52    }
53
54    pub(crate) fn find_iframe(
55        &self,
56        pipeline_id: PipelineId,
57        browsing_context_id: BrowsingContextId,
58    ) -> Option<DomRoot<HTMLIFrameElement>> {
59        self.find_document(pipeline_id).and_then(|document| {
60            document
61                .iframes()
62                .get(browsing_context_id)
63                .map(|iframe| iframe.element.as_rooted())
64        })
65    }
66
67    pub(crate) fn iter(&self) -> DocumentsIter<'_> {
68        DocumentsIter {
69            iter: self.map.iter(),
70        }
71    }
72
73    /// Return the documents managed by this [`crate::script_thread::ScriptThread`] in the
74    /// order specified by the *[update the rendering][update-the-rendering]* step of the
75    /// HTML specification:
76    ///
77    /// > Let docs be all fully active Document objects whose relevant agent's event loop is
78    /// > eventLoop, sorted arbitrarily except that the following conditions must be met:
79    /// >
80    /// > Any Document B whose container document is A must be listed after A in the list.
81    /// >
82    /// > If there are two documents A and B that both have the same non-null container
83    /// > document C, then the order of A and B in the list must match the shadow-including
84    /// > tree order of their respective navigable containers in C's node tree.
85    /// >
86    /// > In the steps below that iterate over docs, each Document must be processed in the
87    /// > order it is found in the list.
88    ///
89    /// [update-the-rendering]: https://html.spec.whatwg.org/multipage/#update-the-rendering
90    pub(crate) fn documents_in_order(&self) -> Vec<PipelineId> {
91        DocumentTree::new(self).documents_in_order()
92    }
93}
94
95impl Default for DocumentCollection {
96    fn default() -> Self {
97        Self {
98            map: HashMapTracedValues::new_fx(),
99        }
100    }
101}
102
103pub(crate) struct DocumentsIter<'a> {
104    iter: hash_map::Iter<'a, PipelineId, Dom<Document>>,
105}
106
107impl Iterator for DocumentsIter<'_> {
108    type Item = (PipelineId, DomRoot<Document>);
109
110    fn next(&mut self) -> Option<(PipelineId, DomRoot<Document>)> {
111        self.iter
112            .next()
113            .map(|(id, doc)| (*id, DomRoot::from_ref(&**doc)))
114    }
115}
116
117#[derive(Default)]
118struct DocumentTreeNode {
119    parent: Option<PipelineId>,
120    children: Vec<PipelineId>,
121}
122
123/// A tree representation of [`Document`]s managed by the [`ScriptThread`][st], which is used
124/// to generate an ordered set of [`Document`]s for the *update the rendering* step of the
125/// HTML5 specification.
126///
127/// FIXME: The [`ScriptThread`][st] only has a view of [`Document`]s managed by itself,
128/// so if there are interceding iframes managed by other `ScriptThread`s, then the
129/// order of the [`Document`]s may not be correct. Perhaps the Constellation could
130/// ensure that every [`ScriptThread`][st] has the full view of the frame tree.
131///
132/// [st]: crate::script_thread::ScriptThread
133#[derive(Default)]
134struct DocumentTree {
135    tree: FxHashMap<PipelineId, DocumentTreeNode>,
136}
137
138impl DocumentTree {
139    fn new(documents: &DocumentCollection) -> Self {
140        let mut tree = DocumentTree::default();
141        for (id, document) in documents.iter() {
142            let children: Vec<PipelineId> = document
143                .iframes()
144                .iter()
145                .filter_map(|iframe| iframe.pipeline_id())
146                .filter(|iframe_pipeline_id| documents.find_document(*iframe_pipeline_id).is_some())
147                .collect();
148            for child in &children {
149                tree.tree.entry(*child).or_default().parent = Some(id);
150            }
151            tree.tree.entry(id).or_default().children = children;
152        }
153        tree
154    }
155
156    fn documents_in_order(&self) -> Vec<PipelineId> {
157        let mut list = Vec::new();
158        for (id, node) in self.tree.iter() {
159            if node.parent.is_none() {
160                self.process_node_for_documents_in_order(*id, &mut list);
161            }
162        }
163        list
164    }
165
166    fn process_node_for_documents_in_order(&self, id: PipelineId, list: &mut Vec<PipelineId>) {
167        list.push(id);
168        for child in self
169            .tree
170            .get(&id)
171            .expect("Should have found child node")
172            .children
173            .iter()
174        {
175            self.process_node_for_documents_in_order(*child, list);
176        }
177    }
178}