layout_api/
wrapper_traits.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
5#![allow(unsafe_code)]
6
7use std::borrow::Cow;
8use std::fmt::Debug;
9
10use atomic_refcell::AtomicRef;
11use base::id::{BrowsingContextId, PipelineId};
12use fonts_traits::ByteIndex;
13use html5ever::{LocalName, Namespace};
14use malloc_size_of_derive::MallocSizeOf;
15use net_traits::image_cache::Image;
16use pixels::ImageMetadata;
17use range::Range;
18use servo_arc::Arc;
19use servo_url::ServoUrl;
20use style::attr::AttrValue;
21use style::context::SharedStyleContext;
22use style::data::ElementData;
23use style::dom::{LayoutIterator, NodeInfo, OpaqueNode, TElement, TNode};
24use style::properties::ComputedValues;
25use style::selector_parser::{PseudoElement, PseudoElementCascadeType, SelectorImpl};
26use style::stylist::RuleInclusion;
27
28use crate::{
29    GenericLayoutData, GenericLayoutDataTrait, HTMLCanvasData, HTMLMediaData, LayoutNodeType,
30    SVGElementData, StyleData,
31};
32
33pub trait LayoutDataTrait: GenericLayoutDataTrait + Default + Send + Sync + 'static {}
34
35/// A wrapper so that layout can access only the methods that it should have access to. Layout must
36/// only ever see these and must never see instances of `LayoutDom`.
37/// FIXME(mrobinson): `Send + Sync` is required here for Layout 2020, but eventually it
38/// should stop sending LayoutNodes to other threads and rely on ThreadSafeLayoutNode
39/// or some other mechanism to ensure thread safety.
40pub trait LayoutNode<'dom>: Copy + Debug + TNode + Send + Sync {
41    type ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode<'dom>;
42    fn to_threadsafe(&self) -> Self::ConcreteThreadSafeLayoutNode;
43
44    /// Returns the type ID of this node.
45    fn type_id(&self) -> LayoutNodeType;
46
47    /// Initialize this node with empty style and opaque layout data.
48    ///
49    /// # Safety
50    ///
51    /// This method is unsafe because it modifies the given node during
52    /// layout. Callers should ensure that no other layout thread is
53    /// attempting to read or modify the opaque layout data of this node.
54    unsafe fn initialize_style_and_layout_data<RequestedLayoutDataType: LayoutDataTrait>(&self);
55
56    /// Get the [`StyleData`] for this node. Returns None if the node is unstyled.
57    fn style_data(&self) -> Option<&'dom StyleData>;
58
59    /// Get the layout data of this node, attempting to downcast it to the desired type.
60    /// Returns None if there is no layout data or it isn't of the desired type.
61    fn layout_data(&self) -> Option<&'dom GenericLayoutData>;
62
63    fn rev_children(self) -> LayoutIterator<ReverseChildrenIterator<Self>> {
64        LayoutIterator(ReverseChildrenIterator {
65            current: self.last_child(),
66        })
67    }
68
69    fn traverse_preorder(self) -> TreeIterator<Self> {
70        TreeIterator::new(self)
71    }
72
73    /// Returns whether the node is connected.
74    fn is_connected(&self) -> bool;
75}
76
77pub struct ReverseChildrenIterator<ConcreteNode> {
78    current: Option<ConcreteNode>,
79}
80
81impl<'dom, ConcreteNode> Iterator for ReverseChildrenIterator<ConcreteNode>
82where
83    ConcreteNode: LayoutNode<'dom>,
84{
85    type Item = ConcreteNode;
86    fn next(&mut self) -> Option<ConcreteNode> {
87        let node = self.current;
88        self.current = node.and_then(|node| node.prev_sibling());
89        node
90    }
91}
92
93pub struct TreeIterator<ConcreteNode> {
94    stack: Vec<ConcreteNode>,
95}
96
97impl<'dom, ConcreteNode> TreeIterator<ConcreteNode>
98where
99    ConcreteNode: LayoutNode<'dom>,
100{
101    fn new(root: ConcreteNode) -> TreeIterator<ConcreteNode> {
102        let stack = vec![root];
103        TreeIterator { stack }
104    }
105
106    pub fn next_skipping_children(&mut self) -> Option<ConcreteNode> {
107        self.stack.pop()
108    }
109}
110
111impl<'dom, ConcreteNode> Iterator for TreeIterator<ConcreteNode>
112where
113    ConcreteNode: LayoutNode<'dom>,
114{
115    type Item = ConcreteNode;
116    fn next(&mut self) -> Option<ConcreteNode> {
117        let ret = self.stack.pop();
118        if let Some(node) = ret {
119            self.stack.extend(node.rev_children())
120        }
121        ret
122    }
123}
124
125/// A thread-safe version of `LayoutNode`, used during flow construction. This type of layout
126/// node does not allow any parents or siblings of nodes to be accessed, to avoid races.
127pub trait ThreadSafeLayoutNode<'dom>: Clone + Copy + Debug + NodeInfo + PartialEq + Sized {
128    type ConcreteNode: LayoutNode<'dom, ConcreteThreadSafeLayoutNode = Self>;
129    type ConcreteElement: TElement;
130
131    type ConcreteThreadSafeLayoutElement: ThreadSafeLayoutElement<'dom, ConcreteThreadSafeLayoutNode = Self>
132        + ::selectors::Element<Impl = SelectorImpl>;
133    type ChildrenIterator: Iterator<Item = Self> + Sized;
134
135    /// Converts self into an `OpaqueNode`.
136    fn opaque(&self) -> OpaqueNode;
137
138    /// Returns the type ID of this node.
139    /// Returns `None` if this is a pseudo-element; otherwise, returns `Some`.
140    fn type_id(&self) -> Option<LayoutNodeType>;
141
142    /// Returns the style for a text node. This is computed on the fly from the
143    /// parent style to avoid traversing text nodes in the style system.
144    ///
145    /// Note that this does require accessing the parent, which this interface
146    /// technically forbids. But accessing the parent is only unsafe insofar as
147    /// it can be used to reach siblings and cousins. A simple immutable borrow
148    /// of the parent data is fine, since the bottom-up traversal will not process
149    /// the parent until all the children have been processed.
150    fn parent_style(&self) -> Arc<ComputedValues>;
151
152    /// Initialize this node with empty opaque layout data.
153    ///
154    /// # Safety
155    ///
156    /// This method is unsafe because it modifies the given node during
157    /// layout. Callers should ensure that no other layout thread is
158    /// attempting to read or modify the opaque layout data of this node.
159    fn initialize_layout_data<RequestedLayoutDataType: LayoutDataTrait>(&self);
160
161    fn debug_id(self) -> usize;
162
163    /// Returns an iterator over this node's children.
164    fn children(&self) -> LayoutIterator<Self::ChildrenIterator>;
165
166    /// Returns a ThreadSafeLayoutElement if this is an element, None otherwise.
167    fn as_element(&self) -> Option<Self::ConcreteThreadSafeLayoutElement>;
168
169    /// Returns a ThreadSafeLayoutElement if this is an element in an HTML namespace, None otherwise.
170    fn as_html_element(&self) -> Option<Self::ConcreteThreadSafeLayoutElement>;
171
172    /// Get the [`StyleData`] for this node. Returns None if the node is unstyled.
173    fn style_data(&self) -> Option<&'dom StyleData>;
174
175    /// Get the layout data of this node, attempting to downcast it to the desired type.
176    /// Returns None if there is no layout data or it isn't of the desired type.
177    fn layout_data(&self) -> Option<&'dom GenericLayoutData>;
178
179    fn style(&self, context: &SharedStyleContext) -> Arc<ComputedValues> {
180        if let Some(el) = self.as_element() {
181            el.style(context)
182        } else {
183            // Text nodes are not styled during traversal,instead we simply
184            // return parent style here and do cascading during layout.
185            debug_assert!(self.is_text_node());
186            self.parent_style()
187        }
188    }
189
190    /// Returns true if this node contributes content. This is used in the implementation of
191    /// `empty_cells` per CSS 2.1 ยง 17.6.1.1.
192    fn is_content(&self) -> bool {
193        self.type_id().is_some()
194    }
195
196    /// Returns access to the underlying LayoutNode. This is breaks the abstraction
197    /// barrier of ThreadSafeLayout wrapper layer, and can lead to races if not used
198    /// carefully.
199    ///
200    /// We need this because the implementation of some methods need to access the layout
201    /// data flags, and we have this annoying trait separation between script and layout :-(
202    fn unsafe_get(self) -> Self::ConcreteNode;
203
204    fn node_text_content(self) -> Cow<'dom, str>;
205
206    /// If selection intersects this node, return it. Otherwise, returns `None`.
207    fn selection(&self) -> Option<Range<ByteIndex>>;
208
209    /// If this is an image element, returns its URL. If this is not an image element, fails.
210    fn image_url(&self) -> Option<ServoUrl>;
211
212    /// If this is an image element, returns its current-pixel-density. If this is not an image element, fails.
213    fn image_density(&self) -> Option<f64>;
214
215    /// If this is an image element, returns its image data. Otherwise, returns `None`.
216    fn image_data(&self) -> Option<(Option<Image>, Option<ImageMetadata>)>;
217
218    fn canvas_data(&self) -> Option<HTMLCanvasData>;
219
220    fn svg_data(&self) -> Option<SVGElementData>;
221
222    fn media_data(&self) -> Option<HTMLMediaData>;
223
224    /// If this node is an iframe element, returns its browsing context ID. If this node is
225    /// not an iframe element, fails. Returns None if there is no nested browsing context.
226    fn iframe_browsing_context_id(&self) -> Option<BrowsingContextId>;
227
228    /// If this node is an iframe element, returns its pipeline ID. If this node is
229    /// not an iframe element, fails. Returns None if there is no nested browsing context.
230    fn iframe_pipeline_id(&self) -> Option<PipelineId>;
231
232    fn get_span(&self) -> Option<u32>;
233    fn get_colspan(&self) -> Option<u32>;
234    fn get_rowspan(&self) -> Option<u32>;
235
236    fn pseudo_element_chain(&self) -> PseudoElementChain;
237
238    fn with_pseudo(&self, pseudo_element_type: PseudoElement) -> Option<Self> {
239        self.as_element()
240            .and_then(|element| element.with_pseudo(pseudo_element_type))
241            .as_ref()
242            .map(ThreadSafeLayoutElement::as_node)
243    }
244
245    fn with_pseudo_element_chain(&self, pseudo_element_chain: PseudoElementChain) -> Self;
246}
247
248pub trait ThreadSafeLayoutElement<'dom>:
249    Clone + Copy + Sized + Debug + ::selectors::Element<Impl = SelectorImpl>
250{
251    type ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode<'dom, ConcreteThreadSafeLayoutElement = Self>;
252
253    /// This type alias is just a work-around to avoid writing
254    ///
255    ///   <Self::ConcreteThreadSafeLayoutNode as ThreadSafeLayoutNode>::ConcreteElement
256    ///
257    type ConcreteElement: TElement;
258
259    fn as_node(&self) -> Self::ConcreteThreadSafeLayoutNode;
260
261    /// Creates a new `ThreadSafeLayoutElement` for the same `LayoutElement`
262    /// with a different pseudo-element type.
263    ///
264    /// Returns `None` if this pseudo doesn't apply to the given element for one of
265    /// the following reasons:
266    ///
267    ///  1. `pseudo` is eager and is not defined in the stylesheet. In this case, there
268    ///     is not reason to process the pseudo element at all.
269    ///  2. `pseudo` is for `::servo-details-summary` or `::servo-details-content` and
270    ///     it doesn't apply to this element, either because it isn't a details or is
271    ///     in the wrong state.
272    fn with_pseudo(&self, pseudo: PseudoElement) -> Option<Self>;
273
274    /// Returns the type ID of this node.
275    /// Returns `None` if this is a pseudo-element; otherwise, returns `Some`.
276    fn type_id(&self) -> Option<LayoutNodeType>;
277
278    /// Returns access to the underlying TElement. This is breaks the abstraction
279    /// barrier of ThreadSafeLayout wrapper layer, and can lead to races if not used
280    /// carefully.
281    ///
282    /// We need this so that the functions defined on this trait can call
283    /// lazily_compute_pseudo_element_style, which operates on TElement.
284    fn unsafe_get(self) -> Self::ConcreteElement;
285
286    /// Get the local name of this element. See
287    /// <https://dom.spec.whatwg.org/#concept-element-local-name>.
288    fn get_local_name(&self) -> &LocalName;
289
290    fn get_attr(&self, namespace: &Namespace, name: &LocalName) -> Option<&str>;
291
292    fn get_attr_enum(&self, namespace: &Namespace, name: &LocalName) -> Option<&AttrValue>;
293
294    fn style_data(&self) -> AtomicRef<'_, ElementData>;
295
296    fn pseudo_element_chain(&self) -> PseudoElementChain;
297
298    /// Returns the style results for the given node. If CSS selector matching
299    /// has not yet been performed, fails.
300    ///
301    /// Unlike the version on TNode, this handles pseudo-elements.
302    #[inline]
303    fn style(&self, context: &SharedStyleContext) -> Arc<ComputedValues> {
304        let get_style_for_pseudo_element =
305            |base_style: &Arc<ComputedValues>, pseudo_element: PseudoElement| {
306                // Precompute non-eagerly-cascaded pseudo-element styles if not
307                // cached before.
308                match pseudo_element.cascade_type() {
309                    // Already computed during the cascade.
310                    PseudoElementCascadeType::Eager => self
311                        .style_data()
312                        .styles
313                        .pseudos
314                        .get(&pseudo_element)
315                        .unwrap()
316                        .clone(),
317                    PseudoElementCascadeType::Precomputed => context
318                        .stylist
319                        .precomputed_values_for_pseudo::<Self::ConcreteElement>(
320                            &context.guards,
321                            &pseudo_element,
322                            Some(base_style),
323                        ),
324                    PseudoElementCascadeType::Lazy => {
325                        context
326                            .stylist
327                            .lazily_compute_pseudo_element_style(
328                                &context.guards,
329                                self.unsafe_get(),
330                                &pseudo_element,
331                                RuleInclusion::All,
332                                base_style,
333                                /* is_probe = */ false,
334                                /* matching_func = */ None,
335                            )
336                            .unwrap()
337                    },
338                }
339            };
340
341        let data = self.style_data();
342        let element_style = data.styles.primary();
343        let pseudo_element_chain = self.pseudo_element_chain();
344
345        let primary_pseudo_style = match pseudo_element_chain.primary {
346            Some(pseudo_element) => get_style_for_pseudo_element(element_style, pseudo_element),
347            None => return element_style.clone(),
348        };
349        match pseudo_element_chain.secondary {
350            Some(pseudo_element) => {
351                get_style_for_pseudo_element(&primary_pseudo_style, pseudo_element)
352            },
353            None => primary_pseudo_style,
354        }
355    }
356
357    fn is_shadow_host(&self) -> bool;
358
359    /// Returns whether this node is a body element of an html element root
360    /// in an HTML element document.
361    ///
362    /// Note that this does require accessing the parent, which this interface
363    /// technically forbids. But accessing the parent is only unsafe insofar as
364    /// it can be used to reach siblings and cousins. A simple immutable borrow
365    /// of the parent data is fine, since the bottom-up traversal will not process
366    /// the parent until all the children have been processed.
367    fn is_body_element_of_html_element_root(&self) -> bool;
368
369    /// Returns whether this node is the root element in an HTML document element.
370    ///
371    /// Note that, like `Self::is_body_element_of_html_element_root`, this accesses the parent.
372    /// As in that case, since this is an immutable borrow, we do not violate thread safety.
373    fn is_root(&self) -> bool;
374}
375
376/// A chain of pseudo-elements up to two levels deep. This is used to represent cases
377/// where a pseudo-element has its own child pseudo element (for instance
378/// `.div::after::marker`). If both [`Self::primary`] and [`Self::secondary`] are `None`,
379/// then this chain represents the element itself. Not all combinations of pseudo-elements
380/// are possible and we may not be able to calculate a style for all
381/// [`PseudoElementChain`]s.
382#[derive(Clone, Copy, Debug, Default, Eq, Hash, MallocSizeOf, PartialEq)]
383pub struct PseudoElementChain {
384    pub primary: Option<PseudoElement>,
385    pub secondary: Option<PseudoElement>,
386}
387
388impl PseudoElementChain {
389    pub fn unnested(pseudo_element: PseudoElement) -> Self {
390        Self {
391            primary: Some(pseudo_element),
392            secondary: None,
393        }
394    }
395
396    pub fn innermost(&self) -> Option<PseudoElement> {
397        self.secondary.or(self.primary)
398    }
399
400    /// Return a possibly nested [`PseudoElementChain`]. Currently only `::before` and
401    /// `::after` only support nesting. If the primary [`PseudoElement`] on the chain is
402    /// not `::before` or `::after` a single element chain is returned for the given
403    /// [`PseudoElement`].
404    pub fn with_pseudo(&self, pseudo_element: PseudoElement) -> Self {
405        match self.primary {
406            Some(primary) if primary.is_before_or_after() => Self {
407                primary: self.primary,
408                secondary: Some(pseudo_element),
409            },
410            _ => {
411                assert!(self.secondary.is_none());
412                Self::unnested(pseudo_element)
413            },
414        }
415    }
416
417    pub fn is_empty(&self) -> bool {
418        self.primary.is_none()
419    }
420}