Skip to main content

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