Skip to main content

script/dom/node/
layout_dom.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//! Methods for layout of node
6
7use std::borrow::Cow;
8
9use layout_api::{
10    GenericLayoutData, HTMLCanvasData, HTMLMediaData, LayoutElementType, LayoutNodeType,
11    SVGElementData, SharedSelection,
12};
13use net_traits::image_cache::Image;
14use pixels::ImageMetadata;
15use script_bindings::codegen::InheritTypes::{
16    ElementTypeId, HTMLElementTypeId, SVGElementTypeId, SVGGraphicsElementTypeId,
17};
18use servo_base::id::{BrowsingContextId, PipelineId};
19use servo_url::ServoUrl;
20use style::dom::OpaqueNode;
21use style::selector_parser::PseudoElement;
22
23use crate::dom::bindings::inheritance::{CharacterDataTypeId, NodeTypeId};
24use crate::dom::bindings::root::{LayoutDom, ToLayout, ToLayoutOptional};
25use crate::dom::document::Document;
26use crate::dom::element::Element;
27use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
28use crate::dom::html::htmlcanvaselement::HTMLCanvasElement;
29use crate::dom::html::htmliframeelement::HTMLIFrameElement;
30use crate::dom::html::htmlimageelement::HTMLImageElement;
31use crate::dom::html::htmlslotelement::HTMLSlotElement;
32use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
33use crate::dom::html::htmlvideoelement::HTMLVideoElement;
34use crate::dom::shadowroot::ShadowRoot;
35use crate::dom::svg::svgsvgelement::SVGSVGElement;
36use crate::dom::text::Text;
37use crate::dom::{Node, NodeFlags};
38
39impl<'dom> LayoutDom<'dom, Node> {
40    #[inline]
41    #[expect(unsafe_code)]
42    pub(crate) fn parent_node_ref(self) -> Option<LayoutDom<'dom, Node>> {
43        unsafe { self.unsafe_get().parent_node().to_layout() }
44    }
45
46    #[inline]
47    pub(crate) fn type_id_for_layout(self) -> NodeTypeId {
48        self.unsafe_get().type_id()
49    }
50
51    #[inline]
52    pub(crate) fn is_element_for_layout(&self) -> bool {
53        (*self).is::<Element>()
54    }
55
56    pub(crate) fn is_text_node_for_layout(&self) -> bool {
57        matches!(
58            self.type_id_for_layout(),
59            NodeTypeId::CharacterData(CharacterDataTypeId::Text(..))
60        )
61    }
62
63    #[inline]
64    pub(crate) fn composed_parent_node_ref(self) -> Option<LayoutDom<'dom, Node>> {
65        let parent = self.parent_node_ref();
66        if let Some(parent) = parent &&
67            let Some(shadow_root) = parent.downcast::<ShadowRoot>()
68        {
69            return Some(shadow_root.get_host_for_layout().upcast());
70        }
71        parent
72    }
73
74    #[inline]
75    pub(crate) fn traversal_parent(self) -> Option<LayoutDom<'dom, Element>> {
76        if let Some(assigned_slot) = self.assigned_slot_for_layout() {
77            return Some(assigned_slot.upcast());
78        }
79        let parent = self.parent_node_ref()?;
80        if let Some(shadow) = parent.downcast::<ShadowRoot>() {
81            return Some(shadow.get_host_for_layout());
82        };
83        parent.downcast()
84    }
85
86    #[inline]
87    #[expect(unsafe_code)]
88    pub(crate) fn first_child_ref(self) -> Option<LayoutDom<'dom, Node>> {
89        unsafe { self.unsafe_get().first_child().to_layout() }
90    }
91
92    #[inline]
93    #[expect(unsafe_code)]
94    pub(crate) fn last_child_ref(self) -> Option<LayoutDom<'dom, Node>> {
95        unsafe { self.unsafe_get().last_child().to_layout() }
96    }
97
98    #[inline]
99    #[expect(unsafe_code)]
100    pub(crate) fn prev_sibling_ref(self) -> Option<LayoutDom<'dom, Node>> {
101        unsafe { self.unsafe_get().prev_sibling().to_layout() }
102    }
103
104    #[inline]
105    #[expect(unsafe_code)]
106    pub(crate) fn next_sibling_ref(self) -> Option<LayoutDom<'dom, Node>> {
107        unsafe { self.unsafe_get().next_sibling().to_layout() }
108    }
109
110    #[inline]
111    #[expect(unsafe_code)]
112    pub(crate) fn owner_doc_for_layout(self) -> LayoutDom<'dom, Document> {
113        unsafe { self.unsafe_get().get_owner_doc().to_layout().unwrap() }
114    }
115
116    #[inline]
117    #[expect(unsafe_code)]
118    pub(crate) fn containing_shadow_root_for_layout(self) -> Option<LayoutDom<'dom, ShadowRoot>> {
119        unsafe {
120            self.unsafe_get()
121                .get_rare_data()
122                .borrow_for_layout()
123                .as_ref()?
124                .containing_shadow_root
125                .as_ref()
126                .map(|sr| sr.to_layout())
127        }
128    }
129
130    #[inline]
131    #[expect(unsafe_code)]
132    pub(crate) fn assigned_slot_for_layout(self) -> Option<LayoutDom<'dom, HTMLSlotElement>> {
133        unsafe {
134            self.unsafe_get()
135                .get_rare_data()
136                .borrow_for_layout()
137                .as_ref()?
138                .slottable_data
139                .assigned_slot
140                .as_ref()
141                .map(|assigned_slot| assigned_slot.to_layout())
142        }
143    }
144
145    // FIXME(nox): get_flag/set_flag (especially the latter) are not safe because
146    // they mutate stuff while values of this type can be used from multiple
147    // threads at once, this should be revisited.
148
149    #[inline]
150    #[expect(unsafe_code)]
151    pub(crate) unsafe fn get_flag(self, flag: NodeFlags) -> bool {
152        (self.unsafe_get()).flags().get().contains(flag)
153    }
154
155    #[inline]
156    #[expect(unsafe_code)]
157    pub(crate) unsafe fn set_flag(self, flag: NodeFlags, value: bool) {
158        let this = self.unsafe_get();
159        let mut flags = (this).flags().get();
160
161        if value {
162            flags.insert(flag);
163        } else {
164            flags.remove(flag);
165        }
166
167        (this).flags().set(flags);
168    }
169
170    #[inline]
171    #[expect(unsafe_code)]
172    pub(crate) fn layout_data(self) -> Option<&'dom GenericLayoutData> {
173        unsafe {
174            self.unsafe_get()
175                .layout_data()
176                .borrow_for_layout()
177                .as_deref()
178        }
179    }
180
181    /// Initialize the style data of this node.
182    ///
183    /// # Safety
184    ///
185    /// This method is unsafe because it modifies the given node during
186    /// layout. Callers should ensure that no other layout thread is
187    /// attempting to read or modify the opaque layout data of this node.
188    #[inline]
189    #[expect(unsafe_code)]
190    pub(crate) unsafe fn initialize_layout_data(self, new_data: Box<GenericLayoutData>) {
191        let data = unsafe { self.unsafe_get().layout_data().borrow_mut_for_layout() };
192        debug_assert!(data.is_none());
193        *data = Some(new_data);
194    }
195
196    /// Clear the style and opaque layout data of this node.
197    ///
198    /// # Safety
199    ///
200    /// This method is unsafe because it modifies the given node during
201    /// layout. Callers should ensure that no other layout thread is
202    /// attempting to read or modify the opaque layout data of this node.
203    #[inline]
204    #[expect(unsafe_code)]
205    pub(crate) unsafe fn clear_layout_data(self) {
206        unsafe {
207            self.unsafe_get()
208                .layout_data()
209                .borrow_mut_for_layout()
210                .take();
211        }
212    }
213
214    /// Whether this element serve as a container of editable text for a text input
215    /// that is implemented as an UA widget.
216    pub(crate) fn is_single_line_text_inner_editor(&self) -> bool {
217        matches!(
218            self.implemented_pseudo_element(),
219            Some(PseudoElement::ServoTextControlInnerEditor)
220        )
221    }
222
223    /// Whether this element serve as a container of any text inside a text input
224    /// that is implemented as an UA widget.
225    pub(crate) fn is_text_container_of_single_line_input(&self) -> bool {
226        let is_single_line_text_inner_placeholder = matches!(
227            self.implemented_pseudo_element(),
228            Some(PseudoElement::Placeholder)
229        );
230        // Currently `::placeholder` is only implemented for single line text input element.
231        debug_assert!(
232            !is_single_line_text_inner_placeholder ||
233                self.containing_shadow_root_for_layout()
234                    .map(|root| root.get_host_for_layout())
235                    .map(|host| host.downcast::<HTMLInputElement>())
236                    .is_some()
237        );
238
239        self.is_single_line_text_inner_editor() || is_single_line_text_inner_placeholder
240    }
241
242    pub(crate) fn text_content(self) -> Cow<'dom, str> {
243        self.downcast::<Text>()
244            .expect("Called LayoutDom::text_content on non-Text node!")
245            .upcast()
246            .data_for_layout()
247            .into()
248    }
249
250    /// Get the selection for the given node. This only works for text nodes that are in
251    /// the shadow DOM of user agent widgets for form controls, specifically for `<input>`
252    /// and `<textarea>`.
253    ///
254    /// As we want to expose the selection on the inner text node of the widget's shadow
255    /// DOM, we must find the shadow root and then access the containing element itself.
256    pub(crate) fn selection(self) -> Option<SharedSelection> {
257        if let Some(input) = self.downcast::<HTMLInputElement>() {
258            return input.selection_for_layout();
259        }
260        if let Some(textarea) = self.downcast::<HTMLTextAreaElement>() {
261            return Some(textarea.selection_for_layout());
262        }
263
264        let shadow_root = self
265            .containing_shadow_root_for_layout()?
266            .get_host_for_layout();
267        if let Some(input) = shadow_root.downcast::<HTMLInputElement>() {
268            return input.selection_for_layout();
269        }
270        shadow_root
271            .downcast::<HTMLTextAreaElement>()
272            .map(|textarea| textarea.selection_for_layout())
273    }
274
275    pub(crate) fn image_url(self) -> Option<ServoUrl> {
276        self.downcast::<HTMLImageElement>()
277            .expect("not an image!")
278            .image_url()
279    }
280
281    pub(crate) fn image_data(self) -> Option<(Option<Image>, Option<ImageMetadata>)> {
282        self.downcast::<HTMLImageElement>().map(|e| e.image_data())
283    }
284
285    pub(crate) fn image_density(self) -> Option<f64> {
286        self.downcast::<HTMLImageElement>()
287            .expect("not an image!")
288            .image_density()
289    }
290
291    pub(crate) fn showing_broken_image_icon(self) -> bool {
292        self.downcast::<HTMLImageElement>()
293            .map(|image_element| image_element.showing_broken_image_icon())
294            .unwrap_or_default()
295    }
296
297    pub(crate) fn canvas_data(self) -> Option<HTMLCanvasData> {
298        self.downcast::<HTMLCanvasElement>()
299            .map(|canvas| canvas.data())
300    }
301
302    pub(crate) fn media_data(self) -> Option<HTMLMediaData> {
303        self.downcast::<HTMLVideoElement>()
304            .map(|media| media.data())
305    }
306
307    pub(crate) fn svg_data(self) -> Option<SVGElementData<'dom>> {
308        self.downcast::<SVGSVGElement>().map(|svg| svg.data())
309    }
310
311    pub(crate) fn iframe_browsing_context_id(self) -> Option<BrowsingContextId> {
312        self.downcast::<HTMLIFrameElement>()
313            .and_then(|iframe_element| iframe_element.browsing_context_id())
314    }
315
316    pub(crate) fn iframe_pipeline_id(self) -> Option<PipelineId> {
317        self.downcast::<HTMLIFrameElement>()
318            .and_then(|iframe_element| iframe_element.pipeline_id())
319    }
320
321    #[expect(unsafe_code)]
322    pub(crate) fn opaque(self) -> OpaqueNode {
323        unsafe { OpaqueNode(self.get_jsobject() as usize) }
324    }
325
326    #[expect(unsafe_code)]
327    pub(crate) fn implemented_pseudo_element(&self) -> Option<PseudoElement> {
328        unsafe {
329            self.unsafe_get()
330                .get_rare_data()
331                .borrow_for_layout()
332                .as_ref()
333                .and_then(|rare_data| rare_data.implemented_pseudo_element)
334        }
335    }
336
337    pub(crate) fn is_in_ua_widget(&self) -> bool {
338        self.unsafe_get().is_in_ua_widget()
339    }
340
341    pub(crate) fn is_root_of_user_agent_widget(&self) -> bool {
342        self.downcast::<Element>().is_some_and(|element| {
343            element
344                .get_shadow_root_for_layout()
345                .is_some_and(|shadow_root| shadow_root.is_user_agent_widget())
346        })
347    }
348
349    pub(crate) fn children_count(&self) -> u32 {
350        self.unsafe_get().children_count()
351    }
352}
353
354pub(crate) struct NodeTypeIdWrapper(pub(crate) NodeTypeId);
355
356impl From<NodeTypeIdWrapper> for LayoutNodeType {
357    #[inline(always)]
358    fn from(node_type: NodeTypeIdWrapper) -> LayoutNodeType {
359        match node_type.0 {
360            NodeTypeId::Element(e) => LayoutNodeType::Element(ElementTypeIdWrapper(e).into()),
361            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => LayoutNodeType::Text,
362            x => unreachable!("Layout should not traverse nodes of type {:?}", x),
363        }
364    }
365}
366
367struct ElementTypeIdWrapper(ElementTypeId);
368
369impl From<ElementTypeIdWrapper> for LayoutElementType {
370    #[inline(always)]
371    fn from(element_type: ElementTypeIdWrapper) -> LayoutElementType {
372        match element_type.0 {
373            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBodyElement) => {
374                LayoutElementType::HTMLBodyElement
375            },
376            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLButtonElement) => {
377                LayoutElementType::HTMLButtonElement
378            },
379            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLBRElement) => {
380                LayoutElementType::HTMLBRElement
381            },
382            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLCanvasElement) => {
383                LayoutElementType::HTMLCanvasElement
384            },
385            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLHtmlElement) => {
386                LayoutElementType::HTMLHtmlElement
387            },
388            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLIFrameElement) => {
389                LayoutElementType::HTMLIFrameElement
390            },
391            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLImageElement) => {
392                LayoutElementType::HTMLImageElement
393            },
394            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLMediaElement(_)) => {
395                LayoutElementType::HTMLMediaElement
396            },
397            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement) => {
398                LayoutElementType::HTMLInputElement
399            },
400            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptGroupElement) => {
401                LayoutElementType::HTMLOptGroupElement
402            },
403            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLOptionElement) => {
404                LayoutElementType::HTMLOptionElement
405            },
406            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLObjectElement) => {
407                LayoutElementType::HTMLObjectElement
408            },
409            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLParagraphElement) => {
410                LayoutElementType::HTMLParagraphElement
411            },
412            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLPreElement) => {
413                LayoutElementType::HTMLPreElement
414            },
415            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLSelectElement) => {
416                LayoutElementType::HTMLSelectElement
417            },
418            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableCellElement) => {
419                LayoutElementType::HTMLTableCellElement
420            },
421            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableColElement) => {
422                LayoutElementType::HTMLTableColElement
423            },
424            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableElement) => {
425                LayoutElementType::HTMLTableElement
426            },
427            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableRowElement) => {
428                LayoutElementType::HTMLTableRowElement
429            },
430            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTableSectionElement) => {
431                LayoutElementType::HTMLTableSectionElement
432            },
433            ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTextAreaElement) => {
434                LayoutElementType::HTMLTextAreaElement
435            },
436            ElementTypeId::SVGElement(SVGElementTypeId::SVGGraphicsElement(
437                SVGGraphicsElementTypeId::SVGImageElement,
438            )) => LayoutElementType::SVGImageElement,
439            ElementTypeId::SVGElement(SVGElementTypeId::SVGGraphicsElement(
440                SVGGraphicsElementTypeId::SVGSVGElement,
441            )) => LayoutElementType::SVGSVGElement,
442            _ => LayoutElementType::Element,
443        }
444    }
445}