Skip to main content

script/layout_dom/
servo_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;
10
11use layout_api::{
12    GenericLayoutData, HTMLCanvasData, HTMLMediaData, LayoutDataTrait, LayoutElement, LayoutNode,
13    LayoutNodeType, PseudoElementChain, SVGElementData, SharedSelection, TrustedNodeAddress,
14};
15use net_traits::image_cache::Image;
16use pixels::ImageMetadata;
17use servo_arc::Arc;
18use servo_base::id::{BrowsingContextId, PipelineId};
19use servo_url::ServoUrl;
20use style;
21use style::context::SharedStyleContext;
22use style::dom::{LayoutIterator, NodeInfo};
23use style::properties::ComputedValues;
24use style::selector_parser::PseudoElement;
25
26use super::ServoLayoutElement;
27use crate::dom::bindings::root::LayoutDom;
28use crate::dom::element::Element;
29use crate::dom::node::{Node, NodeFlags, NodeTypeIdWrapper};
30use crate::layout_dom::{
31    ServoDangerousStyleNode, ServoLayoutDomTypeBundle, ServoLayoutNodeChildrenIterator,
32};
33
34impl fmt::Debug for LayoutDom<'_, Node> {
35    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
36        if let Some(element) = self.downcast::<Element>() {
37            element.fmt(f)
38        } else if self.is_text_node_for_layout() {
39            write!(f, "<text node> ({:#x})", self.opaque().0)
40        } else {
41            write!(f, "<non-text node> ({:#x})", self.opaque().0)
42        }
43    }
44}
45
46/// A wrapper around a `LayoutDom<Node>` which provides a safe interface that
47/// can be used during layout. This implements the `LayoutNode` trait.
48#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
49pub struct ServoLayoutNode<'dom> {
50    /// The wrapped private DOM node.
51    pub(super) node: LayoutDom<'dom, Node>,
52    /// The possibly nested [`PseudoElementChain`] for this node.
53    pub(super) pseudo_element_chain: PseudoElementChain,
54}
55
56/// Those are supposed to be sound, but they aren't because the entire system
57/// between script and layout so far has been designed to work around their
58/// absence. Switching the entire thing to the inert crate infra will help.
59unsafe impl Send for ServoLayoutNode<'_> {}
60unsafe impl Sync for ServoLayoutNode<'_> {}
61
62impl<'dom> ServoLayoutNode<'dom> {
63    /// Create a new [`ServoLayoutNode`] for this given [`TrustedNodeAddress`].
64    ///
65    /// # Safety
66    ///
67    /// The address pointed to by `address` should point to a valid node in memory.
68    pub unsafe fn new(address: &TrustedNodeAddress) -> Self {
69        unsafe { LayoutDom::from_trusted_node_address(*address) }.into()
70    }
71
72    /// Get the first child of this node.
73    ///
74    /// # Safety
75    ///
76    /// This node should never be exposed directly to the layout interface, as that may allow
77    /// mutating a node that is being laid out in another thread. Thus, this should *never* be
78    /// made public or exposed in the `LayoutNode` trait.
79    pub(super) unsafe fn dangerous_first_child(&self) -> Option<Self> {
80        self.node.first_child_ref().map(Into::into)
81    }
82
83    /// Get the next sibling of this node.
84    ///
85    /// # Safety
86    ///
87    /// This node should never be exposed directly to the layout interface, as that may allow
88    /// mutating a node that is being laid out in another thread. Thus, this should *never* be
89    /// made public or exposed in the `LayoutNode` trait.
90    pub(super) unsafe fn dangerous_next_sibling(&self) -> Option<Self> {
91        self.node.next_sibling_ref().map(Into::into)
92    }
93
94    /// Get the previous sibling of this node.
95    ///
96    /// # Safety
97    ///
98    /// This node should never be exposed directly to the layout interface, as that may allow
99    /// mutating a node that is being laid out in another thread. Thus, this should *never* be
100    /// made public or exposed in the `LayoutNode` trait.
101    pub(super) unsafe fn dangerous_previous_sibling(&self) -> Option<Self> {
102        self.node.prev_sibling_ref().map(Into::into)
103    }
104}
105
106impl<'dom> From<LayoutDom<'dom, Node>> for ServoLayoutNode<'dom> {
107    fn from(node: LayoutDom<'dom, Node>) -> Self {
108        Self {
109            node,
110            pseudo_element_chain: Default::default(),
111        }
112    }
113}
114
115impl<'dom> LayoutNode<'dom> for ServoLayoutNode<'dom> {
116    type ConcreteTypeBundle = ServoLayoutDomTypeBundle<'dom>;
117
118    fn with_pseudo(&self, pseudo_element_type: PseudoElement) -> Option<Self> {
119        Some(
120            self.as_element()?
121                .with_pseudo(pseudo_element_type)?
122                .as_node(),
123        )
124    }
125
126    unsafe fn dangerous_style_node(self) -> ServoDangerousStyleNode<'dom> {
127        self.node.into()
128    }
129
130    unsafe fn dangerous_dom_parent(self) -> Option<Self> {
131        self.node.parent_node_ref().map(Into::into)
132    }
133
134    unsafe fn dangerous_flat_tree_parent(self) -> Option<Self> {
135        self.node
136            .traversal_parent()
137            .map(|parent_element| parent_element.upcast().into())
138    }
139
140    fn is_connected(&self) -> bool {
141        unsafe { self.node.get_flag(NodeFlags::IS_CONNECTED) }
142    }
143
144    fn layout_data(&self) -> Option<&'dom GenericLayoutData> {
145        self.node.layout_data()
146    }
147
148    fn opaque(&self) -> style::dom::OpaqueNode {
149        self.node.opaque()
150    }
151
152    fn pseudo_element_chain(&self) -> PseudoElementChain {
153        self.pseudo_element_chain
154    }
155
156    fn type_id(&self) -> Option<LayoutNodeType> {
157        if self.pseudo_element_chain.is_empty() {
158            Some(NodeTypeIdWrapper(self.node.type_id_for_layout()).into())
159        } else {
160            None
161        }
162    }
163
164    fn style(&self, context: &SharedStyleContext) -> Arc<ComputedValues> {
165        if let Some(element) = self.as_element() {
166            element.style(context)
167        } else {
168            // Text nodes are not styled during traversal,instead we simply
169            // return parent style here and do cascading during layout.
170            debug_assert!(self.is_text_node());
171            self.parent_style(context)
172        }
173    }
174
175    fn parent_style(&self, context: &SharedStyleContext) -> Arc<ComputedValues> {
176        if let Some(chain) = self.pseudo_element_chain.without_innermost() {
177            let mut parent = *self;
178            parent.pseudo_element_chain = chain;
179            return parent.style(context);
180        }
181        unsafe { self.dangerous_flat_tree_parent() }
182            .unwrap()
183            .style(context)
184    }
185
186    fn selected_style(&self, context: &SharedStyleContext) -> Arc<ComputedValues> {
187        let Some(element) = self.as_element() else {
188            // TODO(stshine): What should the selected style be for text?
189            debug_assert!(self.is_text_node());
190            return self.parent_style(context);
191        };
192
193        let style_data = &element.element_data().styles;
194        let get_selected_style = || {
195            // This is a workaround for handling the `::selection` pseudos where it would not
196            // propagate to the children and Shadow DOM elements. For this case, UA widget
197            // inner elements should follow the originating element in terms of selection.
198            if self.node.is_in_ua_widget() {
199                return Some(
200                    Self::from(
201                        self.node
202                            .containing_shadow_root_for_layout()?
203                            .get_host_for_layout()
204                            .upcast(),
205                    )
206                    .selected_style(context),
207                );
208            }
209            style_data.pseudos.get(&PseudoElement::Selection).cloned()
210        };
211
212        get_selected_style().unwrap_or_else(|| style_data.primary().clone())
213    }
214
215    fn initialize_layout_data<RequestedLayoutDataType: LayoutDataTrait>(&self) {
216        if self.node.layout_data().is_none() {
217            unsafe {
218                self.node
219                    .initialize_layout_data(Box::<RequestedLayoutDataType>::default());
220            }
221        }
222    }
223
224    fn flat_tree_children(&self) -> impl Iterator<Item = Self> {
225        LayoutIterator(ServoLayoutNodeChildrenIterator::new_for_flat_tree(*self))
226    }
227
228    fn dom_children(&self) -> impl Iterator<Item = Self> {
229        LayoutIterator(ServoLayoutNodeChildrenIterator::new_for_dom_tree(*self))
230    }
231
232    fn as_element(&self) -> Option<ServoLayoutElement<'dom>> {
233        self.node.downcast().map(|element| ServoLayoutElement {
234            element,
235            pseudo_element_chain: self.pseudo_element_chain,
236        })
237    }
238
239    fn as_html_element(&self) -> Option<ServoLayoutElement<'dom>> {
240        self.as_element()
241            .filter(|element| element.is_html_element())
242    }
243
244    fn text_content(self) -> Cow<'dom, str> {
245        self.node.text_content()
246    }
247
248    fn selection(&self) -> Option<SharedSelection> {
249        self.node.selection()
250    }
251
252    fn image_url(&self) -> Option<ServoUrl> {
253        self.node.image_url()
254    }
255
256    fn image_density(&self) -> Option<f64> {
257        self.node.image_density()
258    }
259
260    fn showing_broken_image_icon(&self) -> bool {
261        self.node.showing_broken_image_icon()
262    }
263
264    fn image_data(&self) -> Option<(Option<Image>, Option<ImageMetadata>)> {
265        self.node.image_data()
266    }
267
268    fn canvas_data(&self) -> Option<HTMLCanvasData> {
269        self.node.canvas_data()
270    }
271
272    fn media_data(&self) -> Option<HTMLMediaData> {
273        self.node.media_data()
274    }
275
276    fn svg_data(&self) -> Option<SVGElementData<'dom>> {
277        self.node.svg_data()
278    }
279
280    fn iframe_browsing_context_id(&self) -> Option<BrowsingContextId> {
281        self.node.iframe_browsing_context_id()
282    }
283
284    fn iframe_pipeline_id(&self) -> Option<PipelineId> {
285        self.node.iframe_pipeline_id()
286    }
287
288    fn table_span(&self) -> Option<u32> {
289        self.node
290            .downcast::<Element>()
291            .and_then(|element| element.get_span())
292    }
293
294    fn table_colspan(&self) -> Option<u32> {
295        self.node
296            .downcast::<Element>()
297            .and_then(|element| element.get_colspan())
298    }
299
300    fn table_rowspan(&self) -> Option<u32> {
301        self.node
302            .downcast::<Element>()
303            .and_then(|element| element.get_rowspan())
304    }
305
306    fn set_uses_content_attribute_with_attr(&self, uses_content_attribute_with_attr: bool) {
307        unsafe {
308            self.node.set_flag(
309                NodeFlags::USES_ATTR_IN_CONTENT_ATTRIBUTE,
310                uses_content_attribute_with_attr,
311            )
312        }
313    }
314
315    fn is_single_line_text_input(&self) -> bool {
316        self.pseudo_element_chain.is_empty() && self.node.is_text_container_of_single_line_input()
317    }
318
319    fn is_root_of_user_agent_widget(&self) -> bool {
320        self.node.is_root_of_user_agent_widget()
321    }
322}
323
324impl NodeInfo for ServoLayoutNode<'_> {
325    fn is_element(&self) -> bool {
326        self.node.is_element_for_layout()
327    }
328
329    fn is_text_node(&self) -> bool {
330        self.node.is_text_node_for_layout()
331    }
332}