layout_api/
layout_node.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#![expect(unsafe_code)]
6#![deny(missing_docs)]
7
8use std::borrow::Cow;
9use std::fmt::Debug;
10
11use net_traits::image_cache::Image;
12use pixels::ImageMetadata;
13use servo_arc::Arc;
14use servo_base::id::{BrowsingContextId, PipelineId};
15use servo_url::ServoUrl;
16use style::context::SharedStyleContext;
17use style::dom::{LayoutIterator, NodeInfo, OpaqueNode, TNode};
18use style::properties::ComputedValues;
19use style::selector_parser::PseudoElement;
20
21use crate::layout_element::{DangerousStyleElement, LayoutElement};
22use crate::pseudo_element_chain::PseudoElementChain;
23use crate::{
24    GenericLayoutData, HTMLCanvasData, HTMLMediaData, LayoutDataTrait, LayoutNodeType,
25    SVGElementData, SharedSelection,
26};
27
28/// A trait that exposes a DOM nodes to layout. Implementors of this trait must abide by certain
29/// safety requirements. Layout will only ever access and mutate each node from a single thread
30/// at a time, though children may be used in parallel from other threads. That is why this trait
31/// does not allow access to parent nodes, as it would make it easy to cause race conditions and
32/// memory errors.
33///
34/// Note that the related [`DangerousStyleNode`] trait *may* access parent nodes, which is why
35/// that API is marked as `unsafe` here. In general [`DangerousStyleNode`] should only be used
36/// when interfacing with the `stylo` and `selectors`.
37pub trait LayoutNode<'dom>: Copy + Debug + NodeInfo + Send + Sync {
38    /// The concrete implementation of [`DangerousStyleNode`] implemented in `script`.
39    type ConcreteDangerousStyleNode: DangerousStyleNode<'dom>;
40    /// The concrete implementation of [`DangerousStyleElement`] implemented in `script`.
41    type ConcreteDangerousStyleElement: DangerousStyleElement<'dom>;
42    /// The concrete implementation of [`ConcreteLayoutElement`] implemented in `script`.
43    type ConcreteLayoutElement: LayoutElement<'dom>;
44    /// The concrete implementation of [`ChildIterator`] implemented in `script`.
45    type ChildIterator: Iterator<Item = Self> + Sized;
46
47    /// Creates a new `LayoutNode` for the same `LayoutNode` with a different pseudo-element type.
48    ///
49    /// Returns `None` if this pseudo doesn't apply to the given element for one of
50    /// the following reasons:
51    ///
52    ///  1. This node is not an element.
53    ///  2. `pseudo` is eager and is not defined in the stylesheet. In this case, there
54    ///     is not reason to process the pseudo element at all.
55    ///  3. `pseudo` is for `::servo-details-content` and
56    ///     it doesn't apply to this element, either because it isn't a details or is
57    ///     in the wrong state.
58    fn with_pseudo(&self, pseudo_element_type: PseudoElement) -> Option<Self>;
59
60    /// Returns the [`PseudoElementChain`] for this [`LayoutElement`].
61    fn pseudo_element_chain(&self) -> PseudoElementChain;
62
63    /// Returns access to a version of this LayoutNode that can be used by stylo
64    /// and selectors. This is dangerous as it allows more access to ancestors nodes
65    /// than LayoutNode. This should *only* be used when handing a node to stylo
66    /// or selectors.
67    ///
68    /// # Safety
69    ///
70    /// This should only ever be called from the main script thread. It is never
71    /// okay to explicitly create a node for style while any layout worker threads
72    /// are running.
73    unsafe fn dangerous_style_node(self) -> Self::ConcreteDangerousStyleNode;
74
75    /// Returns access to the DOM parent node of this node. This *does not* take
76    /// into account shadow tree children and slottables. For that use
77    /// [`Self::dangerous_flat_tree_parent`].
78    ///
79    /// # Safety
80    ///
81    /// This should only ever be called from the main script thread. It is never
82    /// okay to explicitly access the parent node while any layout worker threads
83    /// are running.
84    unsafe fn dangerous_dom_parent(self) -> Option<Self>;
85
86    /// Returns access to the flat tree parent node of this node. This takes
87    /// into account shadow tree children and slottables. For that use
88    /// [`Self::dangerous_flat_tree_parent`].
89    ///
90    /// # Safety
91    ///
92    /// This should only ever be called from the main script thread. It is never
93    /// okay to explicitly access the parent node while any layout worker threads
94    /// are running.
95    unsafe fn dangerous_flat_tree_parent(self) -> Option<Self>;
96
97    /// Get the layout data of this node, attempting to downcast it to the desired type.
98    /// Returns None if there is no layout data or it isn't of the desired type.
99    fn layout_data(&self) -> Option<&'dom GenericLayoutData>;
100
101    /// Returns whether the node is connected.
102    fn is_connected(&self) -> bool;
103
104    /// Converts self into an `OpaqueNode`.
105    fn opaque(&self) -> OpaqueNode;
106
107    /// Returns the type ID of this node. Returns `None` if this is a pseudo-element; otherwise,
108    /// returns `Some`.
109    fn type_id(&self) -> Option<LayoutNodeType>;
110
111    /// Initialize this node with empty opaque layout data.
112    fn initialize_layout_data<RequestedLayoutDataType: LayoutDataTrait>(&self);
113
114    /// Returns an iterator over this node's children in the [flat tree]. This
115    /// takes into account shadow tree children and slottables.
116    ///
117    /// [flat tree]: https://drafts.csswg.org/css-shadow-1/#flat-tree
118    fn flat_tree_children(&self) -> LayoutIterator<Self::ChildIterator>;
119
120    /// Returns an iterator over this node's children in the DOM. This
121    /// *does not* take shadow roots and assigned slottables into account.
122    /// For that use [`Self::flat_tree_children`].
123    fn dom_children(&self) -> LayoutIterator<Self::ChildIterator>;
124
125    /// Returns a [`LayoutElement`] if this is an element in the HTML namespace, None otherwise.
126    fn as_html_element(&self) -> Option<Self::ConcreteLayoutElement>;
127
128    /// Returns a [`LayoutElement`] if this is an element.
129    fn as_element(&self) -> Option<Self::ConcreteLayoutElement>;
130
131    /// Returns the computed style for the given node, properly handling pseudo-elements. For
132    /// elements this returns their style and for other nodes, this returns the style of the parent
133    /// element, if one exists.
134    ///
135    /// # Panics
136    ///
137    /// - Calling this method will panic it is an element has no style data, whether because
138    ///   styling has not run yet or was not run for this element.
139    /// - Calling this method will panic if it is a non-element node without a parent element.
140    fn style(&self, context: &SharedStyleContext) -> Arc<ComputedValues>;
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    /// # Safety
146    ///
147    /// Note that this does require accessing the parent, which this interface
148    /// technically forbids. But accessing the parent is only unsafe insofar as
149    /// it can be used to reach siblings and cousins. A simple immutable borrow
150    /// of the parent data is fine, since the bottom-up traversal will not process
151    /// the parent until all the children have been processed.
152    ///
153    /// # Panics
154    ///
155    /// - Calling this method will panic if the parent element has no style data, whether
156    ///   because styling has not run yet or was not run for this element.
157    /// - Calling this method will panic if it is a non-element node without a parent element.
158    fn parent_style(&self, context: &SharedStyleContext) -> Arc<ComputedValues>;
159
160    /// Returns the computed `:selected` style for the given node, properly handling
161    /// pseudo-elements. For elements this returns their style and for other nodes, this
162    /// returns the style of the parent element, if one exists.
163    ///
164    /// # Panics
165    ///
166    /// - Calling this method will panic it is an element has no style data, whether because
167    ///   styling has not run yet or was not run for this element.
168    /// - Calling this method will panic if it is a non-element node without a parent element.
169    fn selected_style(&self, context: &SharedStyleContext) -> Arc<ComputedValues>;
170
171    /// Get the text content of this node, if it is a text node.
172    ///
173    /// # Panics
174    ///
175    /// This method will panic if called on a node that is not a DOM text node.
176    fn text_content(self) -> Cow<'dom, str>;
177
178    /// If this node manages a selection, this returns the shared selection for the node.
179    fn selection(&self) -> Option<SharedSelection>;
180
181    /// If this is an image element, returns its URL. If this is not an image element, fails.
182    fn image_url(&self) -> Option<ServoUrl>;
183
184    /// If this is an image element, returns its current-pixel-density. If this is not an image element, fails.
185    fn image_density(&self) -> Option<f64>;
186
187    /// If this is an image element, returns its image data. Otherwise, returns `None`.
188    fn image_data(&self) -> Option<(Option<Image>, Option<ImageMetadata>)>;
189
190    /// Whether or not this is an image element that is showing a broken image icon.
191    fn showing_broken_image_icon(&self) -> bool;
192
193    /// Return the [`HTMLCanvas`] data for this node, if it is a canvas.
194    fn canvas_data(&self) -> Option<HTMLCanvasData>;
195
196    /// Return the [`SVGElementData`] for this node, if it is an SVG subtree.
197    fn svg_data(&self) -> Option<SVGElementData<'dom>>;
198
199    /// Return the [`HTMLMediaData`] for this node, if it is a media element.
200    fn media_data(&self) -> Option<HTMLMediaData>;
201
202    /// If this node is an iframe element, returns its browsing context ID. If this node is
203    /// not an iframe element, fails. Returns None if there is no nested browsing context.
204    fn iframe_browsing_context_id(&self) -> Option<BrowsingContextId>;
205
206    /// If this node is an iframe element, returns its pipeline ID. If this node is
207    /// not an iframe element, fails. Returns None if there is no nested browsing context.
208    fn iframe_pipeline_id(&self) -> Option<PipelineId>;
209
210    /// Return the table span property if it is an element that supports it.
211    fn table_span(&self) -> Option<u32>;
212
213    /// Return the table colspan property if it is an element that supports it.
214    fn table_colspan(&self) -> Option<u32>;
215
216    /// Return the table rowspan property if it is an element that supports it.
217    fn table_rowspan(&self) -> Option<u32>;
218
219    /// Whether this is a container for the text within a single-line text input. This
220    /// is used to solve the special case of line height for a text entry widget.
221    /// <https://html.spec.whatwg.org/multipage/#the-input-element-as-a-text-entry-widget>
222    fn is_single_line_text_input(&self) -> bool;
223
224    /// Whether or not this [`LayoutNode`] is in a user agent widget shadow DOM.
225    fn is_root_of_user_agent_widget(&self) -> bool;
226
227    /// Set whether or not this node has an active pseudo-element style with a `content`
228    /// attribute that uses `attr`.
229    fn set_uses_content_attribute_with_attr(&self, _uses_content_attribute_with_attr: bool);
230}
231
232/// A node that can be passed to `stylo` and `selectors` that allows accessing the
233/// parent node. We consider this to be too dangerous for normal layout, so it is
234/// reserved only for using `stylo` and `selectors`.
235///
236/// If you are not interfacing with `stylo` and `selectors` you *should not* use this
237/// type, unless you know what you are doing.
238pub trait DangerousStyleNode<'dom>: TNode + Sized + NodeInfo + Send + Sync {
239    /// The concrete implementation of [`LayoutNode`] implemented in `script`.
240    type ConcreteLayoutNode: LayoutNode<'dom>;
241    /// Get a handle to the original "safe" version of this node, a [`LayoutNode`] implementation.
242    fn layout_node(&self) -> Self::ConcreteLayoutNode;
243}