Skip to main content

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
5use std::marker::PhantomData;
6use std::sync::atomic::Ordering;
7
8use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
9use layout_api::{
10    GenericLayoutDataTrait, LayoutDataTrait, LayoutElement, LayoutElementType, LayoutNode,
11    LayoutNodeType as ScriptLayoutNodeType, NodeRenderingType, SVGElementData,
12};
13use malloc_size_of_derive::MallocSizeOf;
14use script::layout_dom::ServoLayoutNode;
15use servo_arc::Arc as ServoArc;
16use servo_base::text::{AssumeUnder4GB, RangeAny, Utf32CodeUnits};
17use smallvec::SmallVec;
18use style::context::SharedStyleContext;
19use style::properties::ComputedValues;
20use style::selector_parser::PseudoElement;
21use style::values::specified::box_::DisplayOutside as StyloDisplayOutside;
22use web_atoms::{local_name, ns};
23
24use crate::BoxTree;
25use crate::cell::{ArcRefCell, WeakRefCell};
26use crate::context::LayoutContext;
27use crate::dom_traversal::{Contents, NodeAndStyleInfo};
28use crate::flexbox::FlexLevelBox;
29use crate::flow::inline::text_run::TextRun;
30use crate::flow::inline::{
31    InlineFormattingContext, InlineItem, SharedInlineStyles, WeakInlineItem,
32};
33use crate::flow::{BlockLevelBox, BlockLevelCreator};
34use crate::formatting_contexts::IndependentFormattingContext;
35use crate::fragment_tree::{Fragment, FragmentFlags};
36use crate::geom::PhysicalSize;
37use crate::layout_box_base::LayoutBoxBase;
38use crate::replaced::{CanvasInfo, IFrameInfo, ImageInfo, VideoInfo};
39use crate::style_ext::{
40    ComputedValuesExt, Display, DisplayGeneratingBox, DisplayLayoutInternal, DisplayOutside,
41};
42use crate::table::{TableLevelBox, WeakTableLevelBox};
43use crate::taffy::{TaffyItemBox, TaffyItemBoxInner};
44
45#[derive(MallocSizeOf)]
46pub struct PseudoLayoutData {
47    pseudo: PseudoElement,
48    data: ArcRefCell<InnerDOMLayoutData>,
49}
50
51/// The data that is stored in each DOM node that is used by layout.
52#[derive(Default, MallocSizeOf)]
53pub struct InnerDOMLayoutData {
54    pub(super) self_box: ArcRefCell<Option<LayoutBox>>,
55    pub(super) pseudo_boxes: SmallVec<[PseudoLayoutData; 2]>,
56}
57
58impl InnerDOMLayoutData {
59    fn pseudo_layout_data(
60        &self,
61        pseudo_element: PseudoElement,
62    ) -> Option<ArcRefCell<InnerDOMLayoutData>> {
63        for pseudo_layout_data in self.pseudo_boxes.iter() {
64            if pseudo_element == pseudo_layout_data.pseudo {
65                return Some(pseudo_layout_data.data.clone());
66            }
67        }
68        None
69    }
70
71    fn create_pseudo_layout_data(
72        &mut self,
73        pseudo_element: PseudoElement,
74    ) -> ArcRefCell<InnerDOMLayoutData> {
75        let data: ArcRefCell<InnerDOMLayoutData> = Default::default();
76        self.pseudo_boxes.push(PseudoLayoutData {
77            pseudo: pseudo_element,
78            data: data.clone(),
79        });
80        data
81    }
82
83    fn fragments(&self) -> Vec<Fragment> {
84        self.with_fragments(<[Fragment]>::to_vec)
85            .unwrap_or_default()
86    }
87
88    /// Run `callback` on the fragments without cloning them. Returns `None` if the node has no box.
89    fn with_fragments<T>(&self, callback: impl FnOnce(&[Fragment]) -> T) -> Option<T> {
90        let self_box = self.self_box.borrow();
91        let layout_box = self_box.as_ref()?;
92        layout_box.with_base(|base| callback(&base.fragments()))
93    }
94
95    fn repair_style(&self, node: &ServoLayoutNode, context: &SharedStyleContext) {
96        if let Some(layout_object) = &*self.self_box.borrow() {
97            let new_style = node.style(context);
98            let style = if node.as_element().is_some_and(|element| element.is_root()) {
99                BoxTree::style_with_writing_mode_source_style(
100                    new_style,
101                    &BoxTree::writing_mode_source_style(context, *node),
102                )
103            } else {
104                new_style
105            };
106
107            layout_object.repair_style(context, node, &style);
108        }
109
110        for pseudo_layout_data in self.pseudo_boxes.iter() {
111            let Some(node_with_pseudo) = node.with_pseudo(pseudo_layout_data.pseudo) else {
112                continue;
113            };
114            pseudo_layout_data
115                .data
116                .borrow()
117                .repair_style(&node_with_pseudo, context);
118        }
119    }
120
121    fn with_layout_box_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> Option<T> {
122        self.self_box
123            .borrow()
124            .as_ref()
125            .and_then(|data| data.with_base(callback))
126    }
127
128    fn with_layout_box_base_including_pseudos(&self, mut callback: impl FnMut(&LayoutBoxBase)) {
129        self.with_layout_box_base(&mut callback);
130        for pseudo_layout_data in self.pseudo_boxes.iter() {
131            pseudo_layout_data
132                .data
133                .borrow()
134                .with_layout_box_base(&mut callback);
135        }
136    }
137}
138
139/// A box that is stored in one of the `DOMLayoutData` slots.
140#[derive(Debug, MallocSizeOf)]
141pub(super) enum LayoutBox {
142    DisplayContents(SharedInlineStyles),
143    BlockLevel(ArcRefCell<BlockLevelBox>),
144    InlineLevel(InlineItem),
145    FlexLevel(ArcRefCell<FlexLevelBox>),
146    TableLevelBox(TableLevelBox),
147    TaffyItemBox(ArcRefCell<TaffyItemBox>),
148    Text(ArcRefCell<TextRun>),
149    Widget(ArcRefCell<IndependentFormattingContext>),
150}
151
152impl LayoutBox {
153    fn parent(&self) -> Option<LayoutBox> {
154        match self {
155            LayoutBox::Text(text_run) => text_run
156                .borrow()
157                .parent_box
158                .as_ref()
159                .and_then(WeakLayoutBox::upgrade),
160            _ => self.with_base(|base| base.parent_box()).flatten(),
161        }
162    }
163
164    pub(crate) fn with_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> Option<T> {
165        Some(match self {
166            LayoutBox::DisplayContents(..) | LayoutBox::Text(..) => return None,
167            LayoutBox::BlockLevel(block_level_box) => block_level_box.borrow().with_base(callback),
168            LayoutBox::InlineLevel(inline_item) => inline_item.with_base(callback),
169            LayoutBox::FlexLevel(flex_level_box) => flex_level_box.borrow().with_base(callback),
170            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box.borrow().with_base(callback),
171            LayoutBox::TableLevelBox(table_box) => table_box.with_base(callback),
172            LayoutBox::Widget(widget_context) => callback(&widget_context.borrow().base),
173        })
174    }
175
176    pub(crate) fn with_base_mut<T>(
177        &mut self,
178        callback: impl FnOnce(&mut LayoutBoxBase) -> T,
179    ) -> Option<T> {
180        Some(match self {
181            LayoutBox::DisplayContents(..) | LayoutBox::Text(..) => return None,
182            LayoutBox::BlockLevel(block_level_box) => {
183                block_level_box.borrow_mut().with_base_mut(callback)
184            },
185            LayoutBox::InlineLevel(inline_item) => inline_item.with_base_mut(callback),
186            LayoutBox::FlexLevel(flex_level_box) => {
187                flex_level_box.borrow_mut().with_base_mut(callback)
188            },
189            LayoutBox::TaffyItemBox(taffy_item_box) => {
190                taffy_item_box.borrow_mut().with_base_mut(callback)
191            },
192            LayoutBox::TableLevelBox(table_box) => table_box.with_base_mut(callback),
193            LayoutBox::Widget(widget_context) => callback(&mut widget_context.borrow_mut().base),
194        })
195    }
196
197    fn repair_style(
198        &self,
199        context: &SharedStyleContext,
200        node: &ServoLayoutNode,
201        new_style: &ServoArc<ComputedValues>,
202    ) {
203        match self {
204            LayoutBox::DisplayContents(inline_shared_styles) => {
205                *inline_shared_styles.style.borrow_mut() = new_style.clone();
206                *inline_shared_styles.selected.borrow_mut() = node.selected_style(context);
207            },
208            LayoutBox::BlockLevel(block_level_box) => {
209                block_level_box
210                    .borrow_mut()
211                    .repair_style(context, node, new_style);
212            },
213            LayoutBox::InlineLevel(inline_item) => {
214                inline_item.repair_style(context, node, new_style);
215            },
216            LayoutBox::FlexLevel(flex_level_box) => flex_level_box
217                .borrow_mut()
218                .repair_style(context, node, new_style),
219            LayoutBox::TableLevelBox(table_level_box) => {
220                table_level_box.repair_style(context, node, new_style)
221            },
222            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box
223                .borrow_mut()
224                .repair_style(context, node, new_style),
225            LayoutBox::Text(..) => {
226                // There is nothing to update in this case.
227            },
228            LayoutBox::Widget(widget_context) => widget_context
229                .borrow_mut()
230                .repair_style(context, node, new_style),
231        }
232    }
233
234    fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
235        match self {
236            Self::DisplayContents(_) => {
237                // This box can't have children, its contents get reparented to its parent.
238                // Therefore, no need to do anything.
239            },
240            Self::BlockLevel(block_level_box) => {
241                block_level_box.borrow().attached_to_tree(layout_box)
242            },
243            Self::InlineLevel(inline_item) => inline_item.attached_to_tree(layout_box),
244            Self::FlexLevel(flex_level_box) => flex_level_box.borrow().attached_to_tree(layout_box),
245            Self::TableLevelBox(table_level_box) => table_level_box.attached_to_tree(layout_box),
246            Self::TaffyItemBox(taffy_item_box) => {
247                taffy_item_box.borrow().attached_to_tree(layout_box)
248            },
249            Self::Text(..) => {
250                // This kind of box cannot have children, so no need to do anything.
251            },
252            LayoutBox::Widget(widget_context) => {
253                widget_context.borrow().attached_to_tree(layout_box)
254            },
255        }
256    }
257
258    fn downgrade(&self) -> WeakLayoutBox {
259        match self {
260            Self::DisplayContents(inline_shared_styles) => {
261                WeakLayoutBox::DisplayContents(inline_shared_styles.clone())
262            },
263            Self::BlockLevel(block_level_box) => {
264                WeakLayoutBox::BlockLevel(block_level_box.downgrade())
265            },
266            Self::InlineLevel(inline_item) => WeakLayoutBox::InlineLevel(inline_item.downgrade()),
267            Self::FlexLevel(flex_level_box) => WeakLayoutBox::FlexLevel(flex_level_box.downgrade()),
268            Self::TableLevelBox(table_level_box) => {
269                WeakLayoutBox::TableLevelBox(table_level_box.downgrade())
270            },
271            Self::TaffyItemBox(taffy_item_box) => {
272                WeakLayoutBox::TaffyItemBox(taffy_item_box.downgrade())
273            },
274            Self::Text(text_run) => WeakLayoutBox::Text(text_run.downgrade()),
275            Self::Widget(widget_context) => WeakLayoutBox::Widget(widget_context.downgrade()),
276        }
277    }
278
279    fn with_independent_formatting_context<T>(
280        &self,
281        callback: impl FnOnce(&IndependentFormattingContext) -> Option<T>,
282    ) -> Option<T> {
283        match self {
284            LayoutBox::DisplayContents(..) => None,
285            LayoutBox::BlockLevel(block_level_box) => match &*block_level_box.borrow() {
286                BlockLevelBox::Independent(independent_formatting_context) => {
287                    callback(independent_formatting_context)
288                },
289                BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(positioned) => {
290                    callback(&positioned.borrow().context)
291                },
292                BlockLevelBox::OutOfFlowFloatBox(float) => callback(&float.contents),
293                BlockLevelBox::OutsideMarker(..) |
294                BlockLevelBox::SameFormattingContextBlock(..) => None,
295            },
296            LayoutBox::InlineLevel(inline_item) => match inline_item {
297                InlineItem::Atomic(atomic_item, ..) => callback(&atomic_item.borrow()),
298                InlineItem::OutOfFlowFloatBox(float) => callback(&float.borrow().contents),
299                InlineItem::OutOfFlowAbsolutelyPositionedBox(absolute, ..) => {
300                    callback(&absolute.borrow().context)
301                },
302                InlineItem::StartInlineBox(..) |
303                InlineItem::EndInlineBox(..) |
304                InlineItem::TextRun(..) |
305                InlineItem::BlockLevel(..) => None,
306            },
307            LayoutBox::FlexLevel(flex_level_box) => match &*flex_level_box.borrow() {
308                FlexLevelBox::FlexItem(flex_item) => {
309                    callback(&flex_item.independent_formatting_context)
310                },
311                FlexLevelBox::OutOfFlowAbsolutelyPositionedBox(absolute) => {
312                    callback(&absolute.borrow().context)
313                },
314            },
315            LayoutBox::TableLevelBox(table_level_box) => match table_level_box {
316                TableLevelBox::Caption(caption) => callback(&caption.borrow().context),
317                TableLevelBox::Cell(cell) => callback(&cell.borrow().context),
318                TableLevelBox::TrackGroup(..) | TableLevelBox::Track(..) => None,
319            },
320            LayoutBox::TaffyItemBox(taffy_item_box) => {
321                match &taffy_item_box.borrow().taffy_level_box {
322                    TaffyItemBoxInner::InFlowBox(independent_formatting_context) => {
323                        callback(independent_formatting_context)
324                    },
325                    TaffyItemBoxInner::OutOfFlowAbsolutelyPositionedBox(absolute) => {
326                        callback(&absolute.borrow().context)
327                    },
328                }
329            },
330            LayoutBox::Text(..) => None,
331            LayoutBox::Widget(widget_context) => callback(&widget_context.borrow()),
332        }
333    }
334
335    pub(crate) fn with_inline_formatting_context<T>(
336        &self,
337        callback: impl FnOnce(&InlineFormattingContext) -> Option<T>,
338    ) -> Option<T> {
339        if let LayoutBox::BlockLevel(block_level_box) = self &&
340            let BlockLevelBox::SameFormattingContextBlock(same_formatting_context_block) =
341                &*block_level_box.borrow() &&
342            let Some(inline_formatting_context) = same_formatting_context_block
343                .contents
344                .inline_formatting_context()
345        {
346            return callback(inline_formatting_context);
347        }
348
349        self.with_independent_formatting_context(|independent_formatting_context| {
350            independent_formatting_context
351                .inline_formatting_context()
352                .and_then(callback)
353        })
354    }
355
356    pub(crate) fn layout_box_for_containing_inline_formatting_context(&self) -> Option<LayoutBox> {
357        let mut current = self.parent()?;
358        while let LayoutBox::InlineLevel(InlineItem::StartInlineBox(..)) = current {
359            current = current.parent()?;
360        }
361        Some(current)
362    }
363}
364
365#[derive(Clone, Debug, MallocSizeOf)]
366pub(super) enum WeakLayoutBox {
367    DisplayContents(SharedInlineStyles),
368    BlockLevel(WeakRefCell<BlockLevelBox>),
369    InlineLevel(WeakInlineItem),
370    FlexLevel(WeakRefCell<FlexLevelBox>),
371    TableLevelBox(WeakTableLevelBox),
372    TaffyItemBox(WeakRefCell<TaffyItemBox>),
373    Text(WeakRefCell<TextRun>),
374    Widget(WeakRefCell<IndependentFormattingContext>),
375}
376
377impl WeakLayoutBox {
378    pub(crate) fn upgrade(&self) -> Option<LayoutBox> {
379        Some(match self {
380            Self::DisplayContents(inline_shared_styles) => {
381                LayoutBox::DisplayContents(inline_shared_styles.clone())
382            },
383            Self::BlockLevel(block_level_box) => LayoutBox::BlockLevel(block_level_box.upgrade()?),
384            Self::InlineLevel(inline_item) => LayoutBox::InlineLevel(inline_item.upgrade()?),
385            Self::FlexLevel(flex_level_box) => LayoutBox::FlexLevel(flex_level_box.upgrade()?),
386            Self::TableLevelBox(table_level_box) => {
387                LayoutBox::TableLevelBox(table_level_box.upgrade()?)
388            },
389            Self::TaffyItemBox(taffy_item_box) => {
390                LayoutBox::TaffyItemBox(taffy_item_box.upgrade()?)
391            },
392            Self::Text(text_run) => LayoutBox::Text(text_run.upgrade()?),
393            Self::Widget(widget_context) => LayoutBox::Widget(widget_context.upgrade()?),
394        })
395    }
396}
397
398/// A wrapper for [`InnerDOMLayoutData`]. This is necessary to give the entire data
399/// structure interior mutability, as we will need to mutate the layout data of
400/// non-mutable DOM nodes.
401#[derive(Default, MallocSizeOf)]
402pub struct DOMLayoutData(AtomicRefCell<InnerDOMLayoutData>);
403
404// The implementation of this trait allows the data to be stored in the DOM.
405impl LayoutDataTrait for DOMLayoutData {}
406impl GenericLayoutDataTrait for DOMLayoutData {
407    fn as_any(&self) -> &dyn std::any::Any {
408        self
409    }
410
411    fn set_text_run_selection(
412        &self,
413        new_range: Option<RangeAny<Utf32CodeUnits>>,
414        new_paints_caret: bool,
415    ) -> bool {
416        let inner = self.0.borrow();
417        // When `::first-letter` is used, one DOM text node can generate multiple text runs
418        // so there isn’t a single place to set the new range
419        if inner
420            .pseudo_boxes
421            .iter()
422            .any(|pseudo_box| matches!(pseudo_box.pseudo, PseudoElement::FirstLetter))
423        {
424            return false;
425        }
426        if let Some(LayoutBox::Text(text_run)) = &*inner.self_box.borrow() {
427            *text_run.borrow().run_data.selection.borrow_mut() = new_range;
428            text_run
429                .borrow()
430                .run_data
431                .paints_caret
432                .store(new_paints_caret, Ordering::Relaxed);
433            true
434        } else {
435            false
436        }
437    }
438
439    fn set_element_selection(&self, selected: bool) -> bool {
440        let inner = self.0.borrow();
441        let inner_box = inner.self_box.borrow();
442        let Some(inner_box) = &*inner_box else {
443            return false;
444        };
445        inner_box
446            .with_independent_formatting_context(|independent_formatting_context| {
447                Some(independent_formatting_context.set_selection(selected))
448            })
449            .unwrap_or(false)
450    }
451
452    fn rendered_text(&self, range: RangeAny<Utf32CodeUnits>) -> Option<String> {
453        let inner = self.0.borrow();
454        let self_box = inner.self_box.borrow();
455
456        let Some(LayoutBox::Text(text_run)) = self_box.as_ref() else {
457            return None;
458        };
459
460        let text_run = text_run.borrow();
461        let range_in_text_run = text_run.run_data.map_dom_range_to_transformed_range(range);
462        let start_in_ifc = text_run.run_data.character_range_in_ifc_text.start;
463
464        let string = text_run.run_data.text_content.get()?;
465        let start =
466            (range_in_text_run.start + start_in_ifc).to_utf8_code_units_in(AssumeUnder4GB, string);
467        let end =
468            (range_in_text_run.end + start_in_ifc).to_utf8_code_units_in(AssumeUnder4GB, string);
469        Some(string[start.0 as usize..end.0 as usize].to_owned())
470    }
471}
472
473pub struct BoxSlot<'dom> {
474    pub(crate) slot: ArcRefCell<Option<LayoutBox>>,
475    pub(crate) marker: PhantomData<&'dom ()>,
476}
477
478impl From<ArcRefCell<Option<LayoutBox>>> for BoxSlot<'_> {
479    fn from(slot: ArcRefCell<Option<LayoutBox>>) -> Self {
480        Self {
481            slot,
482            marker: PhantomData,
483        }
484    }
485}
486
487/// A mutable reference to a `LayoutBox` stored in a DOM element.
488impl BoxSlot<'_> {
489    pub(crate) fn set(self, layout_box: LayoutBox) {
490        layout_box.attached_to_tree(layout_box.downgrade());
491        *self.slot.borrow_mut() = Some(layout_box);
492    }
493
494    pub(crate) fn take_layout_box(&self) -> Option<LayoutBox> {
495        self.slot.borrow_mut().take()
496    }
497
498    /// Call [`Self::take_layout_box`] and try to unwrap it into a [`TextRun`], returning `None` if
499    /// the slot is empty or it does not contain a [`TextRun`]. Note that this will *always* clear
500    /// the [`BoxSlot`].
501    pub(crate) fn take_layout_box_as_text_run(&self) -> Option<ArcRefCell<TextRun>> {
502        match self.take_layout_box()? {
503            LayoutBox::Text(old_text_run) => Some(old_text_run),
504            _ => None,
505        }
506    }
507}
508
509impl Drop for BoxSlot<'_> {
510    fn drop(&mut self) {
511        if !std::thread::panicking() {
512            assert!(self.slot.borrow().is_some(), "failed to set a layout box");
513        }
514    }
515}
516
517pub(crate) trait NodeExt<'dom> {
518    /// Return true if the element is an HTML `<br>` element.
519    fn is_html_br_element(&self) -> bool;
520    /// Return true if the element is an HTML `<wbr>` element.
521    fn is_html_wbr_element(&self) -> bool;
522    /// Returns the relevant data wrapping into respective struct and its size in pixels.
523    fn as_image(&self) -> Option<(ImageInfo, PhysicalSize<f64>)>;
524    fn as_canvas(&self) -> Option<(CanvasInfo, PhysicalSize<f64>)>;
525    fn as_iframe(&self) -> Option<IFrameInfo>;
526    fn as_video(&self) -> Option<(VideoInfo, Option<PhysicalSize<f64>>)>;
527    fn as_svg(&self) -> Option<SVGElementData<'dom>>;
528    fn as_typeless_object_with_data_attribute(&self) -> Option<String>;
529
530    fn ensure_inner_layout_data(&self) -> AtomicRefMut<'dom, InnerDOMLayoutData>;
531    fn inner_layout_data(&self) -> Option<AtomicRef<'dom, InnerDOMLayoutData>>;
532    fn inner_layout_data_mut(&self) -> Option<AtomicRefMut<'dom, InnerDOMLayoutData>>;
533    fn box_slot(&self) -> BoxSlot<'dom>;
534
535    /// Remove boxes for the element itself, and all of its pseudo-element boxes.
536    fn unset_all_boxes(&self);
537
538    /// Clear laid out `Fragment`s and dirty `Fragment` caches for all of this node's boxes,
539    /// ensuring that the next `FragmentTree` layout that happens at this node is complete.
540    fn clear_fragments_and_dirty_fragment_caches(&self);
541
542    /// Clear laid out `Fragment`s and dirty `Fragment` caches for all this node's boxes and
543    /// descendant's boxes, ensuring that the next `FragmentTree` layout that happens at and
544    /// below this node is complete.
545    fn clear_fragments_and_dirty_fragment_caches_recursively(&self);
546
547    /// Clear laid out `Fragment`s and dirty `Fragment` caches for all this node's descendant's
548    /// boxes.
549    fn clear_fragments_and_dirty_fragment_caches_of_descendants(&self);
550
551    /// Returns the [`NodeRenderingType`] for this [`LayoutNode`] which describes whether
552    /// the node is being rendered, delegating rendering, or not being rendered at all
553    /// based on whether it has a [`LayoutBox`] and what kind.
554    fn rendering_type(&self) -> NodeRenderingType;
555
556    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment>;
557
558    /// Run `callback` on the fragments without cloning them. Returns `None` if the node has no box.
559    fn with_fragments<T>(&self, callback: impl FnOnce(&[Fragment]) -> T) -> Option<T>;
560    /// Run `callback` on the `LayoutBoxBase` of this node's box or the box of its pseudo-element.
561    /// Returns `None` if there is no such box.
562    fn with_layout_box_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> Option<T>;
563    fn with_layout_box_base_including_pseudos(&self, callback: impl FnMut(&LayoutBoxBase));
564
565    fn repair_style(&self, context: &SharedStyleContext);
566
567    /// Whether or not this node isolates downward flowing box tree rebuild damage and
568    /// fragment tree layout cache damage. Roughly, this corresponds to independent
569    /// formatting context boundaries.
570    ///
571    /// - The node's boxes themselves will be rebuilt, but not the descendant node's
572    ///   boxes.
573    /// - The node's fragment tree layout will be rebuilt, not the descendent node's
574    ///   fragment tree layout cache.
575    ///
576    /// When this node has no box yet, `false` is returned.
577    fn isolates_damage_for_damage_propagation(&self) -> bool;
578
579    /// Try to re-run box tree reconstruction from this point. This can succeed if the
580    /// node itself is still valid and isolates box tree damage from ancestors (for
581    /// instance, if it starts an independent formatting context). **Note:** This assumes
582    /// that no ancestors have box damage.
583    ///
584    /// Returns `true` if box tree reconstruction was sucessful and `false` otherwise.
585    fn rebuild_box_tree_from_independent_formatting_context(
586        &self,
587        layout_context: &LayoutContext,
588    ) -> bool;
589
590    /// Whether or not the style of this node indicates that it should be absolutely
591    /// positioned.
592    fn is_absolutely_positioned(&self) -> bool;
593}
594
595impl<'dom> NodeExt<'dom> for ServoLayoutNode<'dom> {
596    fn is_html_br_element(&self) -> bool {
597        self.as_html_element()
598            .is_some_and(|element| element.local_name() == &local_name!("br"))
599    }
600
601    fn is_html_wbr_element(&self) -> bool {
602        self.as_html_element()
603            .is_some_and(|element| element.local_name() == &local_name!("wbr"))
604    }
605
606    fn as_image(&self) -> Option<(ImageInfo, PhysicalSize<f64>)> {
607        let (resource, metadata) = self.image_data()?;
608        let width = metadata.map(|metadata| metadata.width).unwrap_or_default();
609        let height = metadata.map(|metadata| metadata.height).unwrap_or_default();
610        let (mut width, mut height) = (width as f64, height as f64);
611        // Take `image_density` into account for calculating the size in pixels for images.
612        if let Some(density) = self.image_density().filter(|density| *density != 1.) {
613            width /= density;
614            height /= density;
615        }
616        Some((
617            ImageInfo {
618                load_time: self.load_time(),
619                image: resource,
620                showing_broken_image_icon: self.showing_broken_image_icon(),
621                url: self.image_url(),
622            },
623            PhysicalSize::new(width, height),
624        ))
625    }
626
627    fn as_svg(&self) -> Option<SVGElementData<'dom>> {
628        self.svg_data()
629    }
630
631    fn as_video(&self) -> Option<(VideoInfo, Option<PhysicalSize<f64>>)> {
632        let data = self.media_data()?;
633        let natural_size = if let Some(frame) = data.current_frame {
634            Some(PhysicalSize::new(frame.width.into(), frame.height.into()))
635        } else {
636            data.metadata
637                .map(|meta| PhysicalSize::new(meta.width.into(), meta.height.into()))
638        };
639        Some((
640            VideoInfo {
641                image_key: data.current_frame.map(|frame| frame.image_key),
642                poster_or_src_url: data.poster_or_src_url,
643            },
644            natural_size,
645        ))
646    }
647
648    fn as_canvas(&self) -> Option<(CanvasInfo, PhysicalSize<f64>)> {
649        let canvas_data = self.canvas_data()?;
650        let source = canvas_data.image_key;
651        Some((
652            CanvasInfo { source },
653            PhysicalSize::new(canvas_data.width.into(), canvas_data.height.into()),
654        ))
655    }
656
657    fn as_iframe(&self) -> Option<IFrameInfo> {
658        match (self.iframe_pipeline_id(), self.iframe_browsing_context_id()) {
659            (Some(pipeline_id), Some(browsing_context_id)) => Some(IFrameInfo {
660                pipeline_id,
661                browsing_context_id,
662            }),
663            _ => None,
664        }
665    }
666
667    fn as_typeless_object_with_data_attribute(&self) -> Option<String> {
668        if self.type_id() !=
669            Some(ScriptLayoutNodeType::Element(
670                LayoutElementType::HTMLObjectElement,
671            ))
672        {
673            return None;
674        }
675
676        // TODO: This is the what the legacy layout system did, but really if Servo
677        // supports any `<object>` that's an image, it should support those with URLs
678        // and `type` attributes with image mime types.
679        let element = self.as_element()?;
680        if element.attribute(&ns!(), &local_name!("type")).is_some() {
681            return None;
682        }
683        element
684            .attribute_as_str(&ns!(), &local_name!("data"))
685            .map(|string| string.to_owned())
686    }
687
688    fn ensure_inner_layout_data(&self) -> AtomicRefMut<'dom, InnerDOMLayoutData> {
689        if self.layout_data().is_none() {
690            self.initialize_layout_data::<DOMLayoutData>();
691        }
692        self.layout_data()
693            .unwrap()
694            .as_any()
695            .downcast_ref::<DOMLayoutData>()
696            .unwrap()
697            .0
698            .borrow_mut()
699    }
700
701    fn inner_layout_data(&self) -> Option<AtomicRef<'dom, InnerDOMLayoutData>> {
702        self.layout_data().map(|data| {
703            data.as_any()
704                .downcast_ref::<DOMLayoutData>()
705                .unwrap()
706                .0
707                .borrow()
708        })
709    }
710
711    fn inner_layout_data_mut(&self) -> Option<AtomicRefMut<'dom, InnerDOMLayoutData>> {
712        self.layout_data().map(|data| {
713            data.as_any()
714                .downcast_ref::<DOMLayoutData>()
715                .unwrap()
716                .0
717                .borrow_mut()
718        })
719    }
720
721    fn box_slot(&self) -> BoxSlot<'dom> {
722        let pseudo_element_chain = self.pseudo_element_chain();
723        let Some(primary) = pseudo_element_chain.primary else {
724            return self.ensure_inner_layout_data().self_box.clone().into();
725        };
726
727        let Some(secondary) = pseudo_element_chain.secondary else {
728            let primary_layout_data = self
729                .ensure_inner_layout_data()
730                .create_pseudo_layout_data(primary);
731            return primary_layout_data.borrow().self_box.clone().into();
732        };
733
734        // It's *very* important that this not borrow the element's main
735        // `InnerLayoutData`. Primary pseudo-elements are processed at the same recursion
736        // level as the main data, so the `BoxSlot` is created sequentially with other
737        // primary pseudo-elements and the element itself. The secondary pseudo-element is
738        // one level deep, so could be happening in parallel with the primary
739        // pseudo-elements or main element layout.
740        let primary_layout_data = self
741            .inner_layout_data()
742            .expect("Should already have element InnerLayoutData here.")
743            .pseudo_layout_data(primary)
744            .expect("Should already have primary pseudo-element InnerLayoutData here");
745        let secondary_layout_data = primary_layout_data
746            .borrow_mut()
747            .create_pseudo_layout_data(secondary);
748        secondary_layout_data.borrow().self_box.clone().into()
749    }
750
751    fn unset_all_boxes(&self) {
752        let mut layout_data = self.ensure_inner_layout_data();
753        *layout_data.self_box.borrow_mut() = None;
754        layout_data.pseudo_boxes.clear();
755
756        // Stylo already takes care of removing all layout data
757        // for DOM descendants of elements with `display: none`.
758    }
759
760    fn clear_fragments_and_dirty_fragment_caches_recursively(&self) {
761        self.clear_fragments_and_dirty_fragment_caches();
762        self.clear_fragments_and_dirty_fragment_caches_of_descendants();
763    }
764
765    fn clear_fragments_and_dirty_fragment_caches(&self) {
766        self.with_layout_box_base_including_pseudos(|base| {
767            base.clear_fragments_and_dirty_fragment_cache()
768        });
769    }
770
771    fn clear_fragments_and_dirty_fragment_caches_of_descendants(&self) {
772        for child in self.flat_tree_children() {
773            child.clear_fragments_and_dirty_fragment_caches_recursively();
774        }
775    }
776
777    fn rendering_type(&self) -> NodeRenderingType {
778        let Some(layout_data) = self.inner_layout_data() else {
779            return NodeRenderingType::NotRendered;
780        };
781        match &*layout_data.self_box.borrow() {
782            Some(LayoutBox::DisplayContents(..)) => NodeRenderingType::DelegatesRendering,
783            Some(..) => NodeRenderingType::Rendered,
784            None => NodeRenderingType::NotRendered,
785        }
786    }
787
788    fn with_layout_box_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> Option<T> {
789        let pseudo_element_chain = self.pseudo_element_chain();
790        let inner_layout_data = self.inner_layout_data()?;
791        let Some(primary) = pseudo_element_chain.primary else {
792            return inner_layout_data.with_layout_box_base(callback);
793        };
794
795        let primary_data = inner_layout_data.pseudo_layout_data(primary)?;
796        drop(inner_layout_data);
797        let Some(secondary) = pseudo_element_chain.secondary else {
798            return primary_data.borrow().with_layout_box_base(callback);
799        };
800
801        primary_data
802            .borrow()
803            .pseudo_layout_data(secondary)?
804            .borrow()
805            .with_layout_box_base(callback)
806    }
807
808    fn with_layout_box_base_including_pseudos(&self, callback: impl FnMut(&LayoutBoxBase)) {
809        if let Some(inner_layout_data) = self.inner_layout_data() {
810            inner_layout_data.with_layout_box_base_including_pseudos(callback);
811        }
812    }
813
814    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment> {
815        let Some(layout_data) = self.inner_layout_data() else {
816            return vec![];
817        };
818        match pseudo_element {
819            Some(pseudo_element) => layout_data
820                .pseudo_layout_data(pseudo_element)
821                .map(|pseudo_layout_data| pseudo_layout_data.borrow().fragments())
822                .unwrap_or_default(),
823            None => layout_data.fragments(),
824        }
825    }
826
827    fn with_fragments<T>(&self, callback: impl FnOnce(&[Fragment]) -> T) -> Option<T> {
828        self.inner_layout_data()?.with_fragments(callback)
829    }
830
831    fn repair_style(&self, context: &SharedStyleContext) {
832        if let Some(layout_data) = self.inner_layout_data() {
833            layout_data.repair_style(self, context);
834        }
835    }
836
837    fn isolates_damage_for_damage_propagation(&self) -> bool {
838        // Do not run incremental box and fragment tree layout at the `<body>` or root element as
839        // there is some special processing that must happen for these elements and it currently
840        // only happens when doing a full box tree construction traversal.
841        if self.as_element().is_some_and(|element| {
842            element.is_body_element_of_html_element_root() || element.is_root()
843        }) {
844            return false;
845        }
846
847        let Some(inner_layout_data) = self.inner_layout_data() else {
848            return false;
849        };
850        let self_box = inner_layout_data.self_box.borrow();
851        let Some(self_box) = &*self_box else {
852            return false;
853        };
854
855        match self_box {
856            LayoutBox::DisplayContents(..) => false,
857            LayoutBox::BlockLevel(block_level) => matches!(
858                &*block_level.borrow(),
859                BlockLevelBox::Independent(..) |
860                    BlockLevelBox::OutOfFlowFloatBox(..) |
861                    BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(..)
862            ),
863            LayoutBox::InlineLevel(inline_level) => matches!(
864                inline_level,
865                InlineItem::OutOfFlowAbsolutelyPositionedBox(..) | InlineItem::Atomic(..)
866            ),
867            LayoutBox::FlexLevel(..) => true,
868            LayoutBox::TableLevelBox(table_level_box) => matches!(
869                table_level_box,
870                TableLevelBox::Cell(..) | TableLevelBox::Caption(..),
871            ),
872            LayoutBox::TaffyItemBox(..) => true,
873            LayoutBox::Text(..) => unreachable!("An element should never be a text node"),
874            LayoutBox::Widget(..) => unreachable!("Widgets are always pseudo-elements."),
875        }
876    }
877
878    fn rebuild_box_tree_from_independent_formatting_context(
879        &self,
880        layout_context: &LayoutContext,
881    ) -> bool {
882        // Do not run incremental box tree layout at the `<body>` or root element as there
883        // is some special processing that must happen for these elements and it currently
884        // only happens when doing a full box tree construction traversal.
885        if self.as_element().is_some_and(|element| {
886            element.is_body_element_of_html_element_root() || element.is_root()
887        }) {
888            return false;
889        }
890
891        let layout_box = {
892            let Some(mut inner_layout_data) = self.inner_layout_data_mut() else {
893                return false;
894            };
895            inner_layout_data.pseudo_boxes.clear();
896            inner_layout_data.self_box.clone()
897        };
898
899        let layout_box = layout_box.borrow();
900        let Some(layout_box) = &*layout_box else {
901            return false;
902        };
903
904        let info = NodeAndStyleInfo::new(*self, self.style(&layout_context.style_context));
905        let box_style = info.style.get_box();
906        let Display::GeneratingBox(display) = box_style.display.into() else {
907            return false;
908        };
909        let contents = || {
910            assert!(
911                self.pseudo_element_chain().is_empty(),
912                "Shouldn't try to rebuild box tree from a pseudo-element"
913            );
914            Contents::for_element(info.node, layout_context)
915        };
916        match layout_box {
917            LayoutBox::DisplayContents(..) => false,
918            LayoutBox::BlockLevel(block_level) => {
919                let mut block_level = block_level.borrow_mut();
920                match &mut *block_level {
921                    BlockLevelBox::Independent(independent_formatting_context) => {
922                        if box_style.position.is_absolutely_positioned() ||
923                            box_style.float.is_floating()
924                        {
925                            return false;
926                        }
927                        let DisplayGeneratingBox::OutsideInside {
928                            outside: DisplayOutside::Block,
929                            inside: display_inside,
930                        } = display
931                        else {
932                            return false;
933                        };
934                        if !matches!(
935                            BlockLevelCreator::new_for_inflow_block_level_element(
936                                &info,
937                                display_inside,
938                                contents(),
939                                independent_formatting_context.propagated_data,
940                            ),
941                            BlockLevelCreator::Independent { .. }
942                        ) {
943                            return false;
944                        }
945                        independent_formatting_context.rebuild(layout_context, &info);
946                        true
947                    },
948                    BlockLevelBox::OutOfFlowFloatBox(float_box) => {
949                        if !info.style.get_float().is_floating() {
950                            return false;
951                        }
952                        float_box.contents.rebuild(layout_context, &info);
953                        true
954                    },
955                    BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(positioned_box) => {
956                        // Even if absolute positioning blockifies the outer display type, if the
957                        // original display was inline-level, then the box needs to be handled as
958                        // an inline-level in order to compute the static position correctly.
959                        // See `BlockContainerBuilder::handle_absolutely_positioned_element()`.
960                        if !info.style.get_box().position.is_absolutely_positioned() ||
961                            box_style.original_display.outside() != StyloDisplayOutside::Block
962                        {
963                            return false;
964                        }
965                        positioned_box
966                            .borrow_mut()
967                            .context
968                            .rebuild(layout_context, &info);
969                        true
970                    },
971                    _ => false,
972                }
973            },
974            LayoutBox::InlineLevel(inline_level) => match inline_level {
975                InlineItem::OutOfFlowAbsolutelyPositionedBox(positioned_box, ..) => {
976                    if !info.style.get_box().position.is_absolutely_positioned() {
977                        return false;
978                    }
979                    positioned_box
980                        .borrow_mut()
981                        .context
982                        .rebuild(layout_context, &info);
983                    true
984                },
985                InlineItem::Atomic(atomic_box, _, _) => {
986                    let flags = match contents() {
987                        Contents::NonReplaced(_) => FragmentFlags::empty(),
988                        Contents::Replaced(_) => FragmentFlags::IS_REPLACED,
989                        Contents::Widget(_) => FragmentFlags::IS_WIDGET,
990                    };
991                    if !info.style.is_atomic_inline_level(flags) {
992                        return false;
993                    }
994                    atomic_box.borrow_mut().rebuild(layout_context, &info);
995                    true
996                },
997                _ => false,
998            },
999            LayoutBox::FlexLevel(flex_level_box) => {
1000                let mut flex_level_box = flex_level_box.borrow_mut();
1001                match &mut *flex_level_box {
1002                    FlexLevelBox::FlexItem(flex_item_box) => {
1003                        if info.style.get_box().position.is_absolutely_positioned() ||
1004                            !flex_item_box.style().order_equals(&info.style)
1005                        {
1006                            return false;
1007                        }
1008                        flex_item_box
1009                            .independent_formatting_context
1010                            .rebuild(layout_context, &info)
1011                    },
1012                    FlexLevelBox::OutOfFlowAbsolutelyPositionedBox(positioned_box) => {
1013                        if !info.style.get_box().position.is_absolutely_positioned() {
1014                            return false;
1015                        }
1016                        positioned_box
1017                            .borrow_mut()
1018                            .context
1019                            .rebuild(layout_context, &info);
1020                    },
1021                }
1022                true
1023            },
1024            LayoutBox::TableLevelBox(table_level_box) => match table_level_box {
1025                TableLevelBox::Caption(caption) => {
1026                    if display !=
1027                        DisplayGeneratingBox::LayoutInternal(DisplayLayoutInternal::TableCaption)
1028                    {
1029                        return false;
1030                    }
1031                    caption.borrow_mut().context.rebuild(layout_context, &info);
1032                    true
1033                },
1034                TableLevelBox::Cell(table_cell) => {
1035                    if display !=
1036                        DisplayGeneratingBox::LayoutInternal(DisplayLayoutInternal::TableCell)
1037                    {
1038                        return false;
1039                    }
1040                    table_cell
1041                        .borrow_mut()
1042                        .context
1043                        .rebuild(layout_context, &info);
1044                    true
1045                },
1046                _ => false,
1047            },
1048            LayoutBox::TaffyItemBox(..) => false,
1049            LayoutBox::Text(..) => unreachable!("An element should never be a text node"),
1050            LayoutBox::Widget(..) => unreachable!("Widgets are always pseudo-elements."),
1051        }
1052    }
1053
1054    fn is_absolutely_positioned(&self) -> bool {
1055        self.as_element().is_some_and(|element| {
1056            element
1057                .element_data()
1058                .styles
1059                .primary()
1060                .get_box()
1061                .position
1062                .is_absolutely_positioned()
1063        })
1064    }
1065}