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;
6
7use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
8use base::id::{BrowsingContextId, PipelineId};
9use html5ever::{local_name, ns};
10use layout_api::wrapper_traits::{LayoutDataTrait, ThreadSafeLayoutElement, ThreadSafeLayoutNode};
11use layout_api::{
12    GenericLayoutDataTrait, LayoutElementType, LayoutNodeType as ScriptLayoutNodeType,
13    SVGElementData,
14};
15use malloc_size_of_derive::MallocSizeOf;
16use net_traits::image_cache::Image;
17use script::layout_dom::ServoThreadSafeLayoutNode;
18use servo_arc::Arc as ServoArc;
19use smallvec::SmallVec;
20use style::context::SharedStyleContext;
21use style::properties::ComputedValues;
22use style::selector_parser::PseudoElement;
23
24use crate::cell::{ArcRefCell, WeakRefCell};
25use crate::flexbox::FlexLevelBox;
26use crate::flow::BlockLevelBox;
27use crate::flow::inline::{InlineItem, SharedInlineStyles, WeakInlineItem};
28use crate::fragment_tree::Fragment;
29use crate::geom::PhysicalSize;
30use crate::layout_box_base::LayoutBoxBase;
31use crate::replaced::CanvasInfo;
32use crate::table::{TableLevelBox, WeakTableLevelBox};
33use crate::taffy::TaffyItemBox;
34
35#[derive(MallocSizeOf)]
36pub struct PseudoLayoutData {
37    pseudo: PseudoElement,
38    data: ArcRefCell<InnerDOMLayoutData>,
39}
40
41/// The data that is stored in each DOM node that is used by layout.
42#[derive(Default, MallocSizeOf)]
43pub struct InnerDOMLayoutData {
44    pub(super) self_box: ArcRefCell<Option<LayoutBox>>,
45    pub(super) pseudo_boxes: SmallVec<[PseudoLayoutData; 2]>,
46}
47
48impl InnerDOMLayoutData {
49    fn pseudo_layout_data(
50        &self,
51        pseudo_element: PseudoElement,
52    ) -> Option<ArcRefCell<InnerDOMLayoutData>> {
53        for pseudo_layout_data in self.pseudo_boxes.iter() {
54            if pseudo_element == pseudo_layout_data.pseudo {
55                return Some(pseudo_layout_data.data.clone());
56            }
57        }
58        None
59    }
60
61    fn create_pseudo_layout_data(
62        &mut self,
63        pseudo_element: PseudoElement,
64    ) -> ArcRefCell<InnerDOMLayoutData> {
65        let data: ArcRefCell<InnerDOMLayoutData> = Default::default();
66        self.pseudo_boxes.push(PseudoLayoutData {
67            pseudo: pseudo_element,
68            data: data.clone(),
69        });
70        data
71    }
72
73    fn fragments(&self) -> Vec<Fragment> {
74        self.self_box
75            .borrow()
76            .as_ref()
77            .and_then(|layout_box| layout_box.with_base(LayoutBoxBase::fragments))
78            .unwrap_or_default()
79    }
80
81    fn repair_style(&self, node: &ServoThreadSafeLayoutNode, context: &SharedStyleContext) {
82        if let Some(layout_object) = &*self.self_box.borrow() {
83            layout_object.repair_style(context, node, &node.style(context));
84        }
85
86        for pseudo_layout_data in self.pseudo_boxes.iter() {
87            let Some(node_with_pseudo) = node.with_pseudo(pseudo_layout_data.pseudo) else {
88                continue;
89            };
90            pseudo_layout_data
91                .data
92                .borrow()
93                .repair_style(&node_with_pseudo, context);
94        }
95    }
96
97    fn with_layout_box_base(&self, callback: impl Fn(&LayoutBoxBase)) {
98        if let Some(data) = self.self_box.borrow().as_ref() {
99            data.with_base(callback);
100        }
101    }
102
103    fn with_layout_box_base_including_pseudos(&self, callback: impl Fn(&LayoutBoxBase)) {
104        self.with_layout_box_base(&callback);
105        for pseudo_layout_data in self.pseudo_boxes.iter() {
106            pseudo_layout_data
107                .data
108                .borrow()
109                .with_layout_box_base(&callback);
110        }
111    }
112}
113
114/// A box that is stored in one of the `DOMLayoutData` slots.
115#[derive(Debug, MallocSizeOf)]
116pub(super) enum LayoutBox {
117    DisplayContents(SharedInlineStyles),
118    BlockLevel(ArcRefCell<BlockLevelBox>),
119    InlineLevel(InlineItem),
120    FlexLevel(ArcRefCell<FlexLevelBox>),
121    TableLevelBox(TableLevelBox),
122    TaffyItemBox(ArcRefCell<TaffyItemBox>),
123}
124
125impl LayoutBox {
126    pub(crate) fn with_base<T>(&self, callback: impl FnOnce(&LayoutBoxBase) -> T) -> Option<T> {
127        Some(match self {
128            LayoutBox::DisplayContents(..) => return None,
129            LayoutBox::BlockLevel(block_level_box) => block_level_box.borrow().with_base(callback),
130            LayoutBox::InlineLevel(inline_item) => inline_item.with_base(callback),
131            LayoutBox::FlexLevel(flex_level_box) => flex_level_box.borrow().with_base(callback),
132            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box.borrow().with_base(callback),
133            LayoutBox::TableLevelBox(table_box) => table_box.with_base(callback),
134        })
135    }
136
137    pub(crate) fn with_base_mut<T>(
138        &mut self,
139        callback: impl FnOnce(&mut LayoutBoxBase) -> T,
140    ) -> Option<T> {
141        Some(match self {
142            LayoutBox::DisplayContents(..) => return None,
143            LayoutBox::BlockLevel(block_level_box) => {
144                block_level_box.borrow_mut().with_base_mut(callback)
145            },
146            LayoutBox::InlineLevel(inline_item) => inline_item.with_base_mut(callback),
147            LayoutBox::FlexLevel(flex_level_box) => {
148                flex_level_box.borrow_mut().with_base_mut(callback)
149            },
150            LayoutBox::TaffyItemBox(taffy_item_box) => {
151                taffy_item_box.borrow_mut().with_base_mut(callback)
152            },
153            LayoutBox::TableLevelBox(table_box) => table_box.with_base_mut(callback),
154        })
155    }
156
157    fn repair_style(
158        &self,
159        context: &SharedStyleContext,
160        node: &ServoThreadSafeLayoutNode,
161        new_style: &ServoArc<ComputedValues>,
162    ) {
163        match self {
164            LayoutBox::DisplayContents(inline_shared_styles) => {
165                *inline_shared_styles.style.borrow_mut() = new_style.clone();
166                *inline_shared_styles.selected.borrow_mut() = node.selected_style();
167            },
168            LayoutBox::BlockLevel(block_level_box) => {
169                block_level_box
170                    .borrow_mut()
171                    .repair_style(context, node, new_style);
172            },
173            LayoutBox::InlineLevel(inline_item) => {
174                inline_item.repair_style(context, node, new_style);
175            },
176            LayoutBox::FlexLevel(flex_level_box) => flex_level_box
177                .borrow_mut()
178                .repair_style(context, node, new_style),
179            LayoutBox::TableLevelBox(table_level_box) => {
180                table_level_box.repair_style(context, node, new_style)
181            },
182            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box
183                .borrow_mut()
184                .repair_style(context, node, new_style),
185        }
186    }
187
188    fn attached_to_tree(&self, layout_box: WeakLayoutBox) {
189        match self {
190            Self::DisplayContents(_) => {
191                // This box can't have children, its contents get reparented to its parent.
192                // Therefore, no need to do anything.
193            },
194            Self::BlockLevel(block_level_box) => {
195                block_level_box.borrow().attached_to_tree(layout_box)
196            },
197            Self::InlineLevel(inline_item) => inline_item.attached_to_tree(layout_box),
198            Self::FlexLevel(flex_level_box) => flex_level_box.borrow().attached_to_tree(layout_box),
199            Self::TableLevelBox(table_level_box) => table_level_box.attached_to_tree(layout_box),
200            Self::TaffyItemBox(taffy_item_box) => {
201                taffy_item_box.borrow().attached_to_tree(layout_box)
202            },
203        }
204    }
205
206    fn downgrade(&self) -> WeakLayoutBox {
207        match self {
208            Self::DisplayContents(inline_shared_styles) => {
209                WeakLayoutBox::DisplayContents(inline_shared_styles.clone())
210            },
211            Self::BlockLevel(block_level_box) => {
212                WeakLayoutBox::BlockLevel(block_level_box.downgrade())
213            },
214            Self::InlineLevel(inline_item) => WeakLayoutBox::InlineLevel(inline_item.downgrade()),
215            Self::FlexLevel(flex_level_box) => WeakLayoutBox::FlexLevel(flex_level_box.downgrade()),
216            Self::TableLevelBox(table_level_box) => {
217                WeakLayoutBox::TableLevelBox(table_level_box.downgrade())
218            },
219            Self::TaffyItemBox(taffy_item_box) => {
220                WeakLayoutBox::TaffyItemBox(taffy_item_box.downgrade())
221            },
222        }
223    }
224}
225
226#[derive(Clone, Debug, MallocSizeOf)]
227pub(super) enum WeakLayoutBox {
228    DisplayContents(SharedInlineStyles),
229    BlockLevel(WeakRefCell<BlockLevelBox>),
230    InlineLevel(WeakInlineItem),
231    FlexLevel(WeakRefCell<FlexLevelBox>),
232    TableLevelBox(WeakTableLevelBox),
233    TaffyItemBox(WeakRefCell<TaffyItemBox>),
234}
235
236impl WeakLayoutBox {
237    pub(crate) fn upgrade(&self) -> Option<LayoutBox> {
238        Some(match self {
239            Self::DisplayContents(inline_shared_styles) => {
240                LayoutBox::DisplayContents(inline_shared_styles.clone())
241            },
242            Self::BlockLevel(block_level_box) => LayoutBox::BlockLevel(block_level_box.upgrade()?),
243            Self::InlineLevel(inline_item) => LayoutBox::InlineLevel(inline_item.upgrade()?),
244            Self::FlexLevel(flex_level_box) => LayoutBox::FlexLevel(flex_level_box.upgrade()?),
245            Self::TableLevelBox(table_level_box) => {
246                LayoutBox::TableLevelBox(table_level_box.upgrade()?)
247            },
248            Self::TaffyItemBox(taffy_item_box) => {
249                LayoutBox::TaffyItemBox(taffy_item_box.upgrade()?)
250            },
251        })
252    }
253}
254
255/// A wrapper for [`InnerDOMLayoutData`]. This is necessary to give the entire data
256/// structure interior mutability, as we will need to mutate the layout data of
257/// non-mutable DOM nodes.
258#[derive(Default, MallocSizeOf)]
259pub struct DOMLayoutData(AtomicRefCell<InnerDOMLayoutData>);
260
261// The implementation of this trait allows the data to be stored in the DOM.
262impl LayoutDataTrait for DOMLayoutData {}
263impl GenericLayoutDataTrait for DOMLayoutData {
264    fn as_any(&self) -> &dyn std::any::Any {
265        self
266    }
267}
268
269pub struct BoxSlot<'dom> {
270    pub(crate) slot: ArcRefCell<Option<LayoutBox>>,
271    pub(crate) marker: PhantomData<&'dom ()>,
272}
273
274impl From<ArcRefCell<Option<LayoutBox>>> for BoxSlot<'_> {
275    fn from(slot: ArcRefCell<Option<LayoutBox>>) -> Self {
276        Self {
277            slot,
278            marker: PhantomData,
279        }
280    }
281}
282
283/// A mutable reference to a `LayoutBox` stored in a DOM element.
284impl BoxSlot<'_> {
285    pub(crate) fn set(self, layout_box: LayoutBox) {
286        layout_box.attached_to_tree(layout_box.downgrade());
287        *self.slot.borrow_mut() = Some(layout_box);
288    }
289
290    pub(crate) fn take_layout_box(&self) -> Option<LayoutBox> {
291        self.slot.borrow_mut().take()
292    }
293}
294
295impl Drop for BoxSlot<'_> {
296    fn drop(&mut self) {
297        if !std::thread::panicking() {
298            assert!(self.slot.borrow().is_some(), "failed to set a layout box");
299        }
300    }
301}
302
303pub(crate) trait NodeExt<'dom> {
304    /// Returns the image if it’s loaded, and its size in image pixels
305    /// adjusted for `image_density`.
306    fn as_image(&self) -> Option<(Option<Image>, PhysicalSize<f64>)>;
307    fn as_canvas(&self) -> Option<(CanvasInfo, PhysicalSize<f64>)>;
308    fn as_iframe(&self) -> Option<(PipelineId, BrowsingContextId)>;
309    fn as_video(&self) -> Option<(Option<webrender_api::ImageKey>, Option<PhysicalSize<f64>>)>;
310    fn as_svg(&self) -> Option<SVGElementData<'dom>>;
311    fn as_typeless_object_with_data_attribute(&self) -> Option<String>;
312
313    fn ensure_inner_layout_data(&self) -> AtomicRefMut<'dom, InnerDOMLayoutData>;
314    fn inner_layout_data(&self) -> Option<AtomicRef<'dom, InnerDOMLayoutData>>;
315    fn box_slot(&self) -> BoxSlot<'dom>;
316
317    /// Remove boxes for the element itself, and all of its pseudo-element boxes.
318    fn unset_all_boxes(&self);
319
320    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment>;
321    fn with_layout_box_base_including_pseudos(&self, callback: impl Fn(&LayoutBoxBase));
322
323    fn repair_style(&self, context: &SharedStyleContext);
324
325    /// Whether or not this node isolates downward flowing box tree rebuild damage. Roughly,
326    /// this corresponds to independent formatting context boundaries. The node's boxes
327    /// themselves will be rebuilt, but not the descendant node's boxes. When this node
328    /// has no box yet, `false` is returned.
329    fn isolates_box_tree_rebuild_damage(&self) -> bool;
330}
331
332impl<'dom> NodeExt<'dom> for ServoThreadSafeLayoutNode<'dom> {
333    fn as_image(&self) -> Option<(Option<Image>, PhysicalSize<f64>)> {
334        let (resource, metadata) = self.image_data()?;
335        let width = metadata.map(|metadata| metadata.width).unwrap_or_default();
336        let height = metadata.map(|metadata| metadata.height).unwrap_or_default();
337        let (mut width, mut height) = (width as f64, height as f64);
338        if let Some(density) = self.image_density().filter(|density| *density != 1.) {
339            width /= density;
340            height /= density;
341        }
342        Some((resource, PhysicalSize::new(width, height)))
343    }
344
345    fn as_svg(&self) -> Option<SVGElementData<'dom>> {
346        self.svg_data()
347    }
348
349    fn as_video(&self) -> Option<(Option<webrender_api::ImageKey>, Option<PhysicalSize<f64>>)> {
350        let data = self.media_data()?;
351        let natural_size = if let Some(frame) = data.current_frame {
352            Some(PhysicalSize::new(frame.width.into(), frame.height.into()))
353        } else {
354            data.metadata
355                .map(|meta| PhysicalSize::new(meta.width.into(), meta.height.into()))
356        };
357        Some((
358            data.current_frame.map(|frame| frame.image_key),
359            natural_size,
360        ))
361    }
362
363    fn as_canvas(&self) -> Option<(CanvasInfo, PhysicalSize<f64>)> {
364        let canvas_data = self.canvas_data()?;
365        let source = canvas_data.image_key;
366        Some((
367            CanvasInfo { source },
368            PhysicalSize::new(canvas_data.width.into(), canvas_data.height.into()),
369        ))
370    }
371
372    fn as_iframe(&self) -> Option<(PipelineId, BrowsingContextId)> {
373        match (self.iframe_pipeline_id(), self.iframe_browsing_context_id()) {
374            (Some(pipeline_id), Some(browsing_context_id)) => {
375                Some((pipeline_id, browsing_context_id))
376            },
377            _ => None,
378        }
379    }
380
381    fn as_typeless_object_with_data_attribute(&self) -> Option<String> {
382        if self.type_id() !=
383            Some(ScriptLayoutNodeType::Element(
384                LayoutElementType::HTMLObjectElement,
385            ))
386        {
387            return None;
388        }
389
390        // TODO: This is the what the legacy layout system did, but really if Servo
391        // supports any `<object>` that's an image, it should support those with URLs
392        // and `type` attributes with image mime types.
393        let element = self.as_element()?;
394        if element.get_attr(&ns!(), &local_name!("type")).is_some() {
395            return None;
396        }
397        element
398            .get_attr(&ns!(), &local_name!("data"))
399            .map(|string| string.to_owned())
400    }
401
402    fn ensure_inner_layout_data(&self) -> AtomicRefMut<'dom, InnerDOMLayoutData> {
403        if self.layout_data().is_none() {
404            self.initialize_layout_data::<DOMLayoutData>();
405        }
406        self.layout_data()
407            .unwrap()
408            .as_any()
409            .downcast_ref::<DOMLayoutData>()
410            .unwrap()
411            .0
412            .borrow_mut()
413    }
414
415    fn inner_layout_data(&self) -> Option<AtomicRef<'dom, InnerDOMLayoutData>> {
416        self.layout_data().map(|data| {
417            data.as_any()
418                .downcast_ref::<DOMLayoutData>()
419                .unwrap()
420                .0
421                .borrow()
422        })
423    }
424
425    fn box_slot(&self) -> BoxSlot<'dom> {
426        let pseudo_element_chain = self.pseudo_element_chain();
427        let Some(primary) = pseudo_element_chain.primary else {
428            return self.ensure_inner_layout_data().self_box.clone().into();
429        };
430
431        let Some(secondary) = pseudo_element_chain.secondary else {
432            let primary_layout_data = self
433                .ensure_inner_layout_data()
434                .create_pseudo_layout_data(primary);
435            return primary_layout_data.borrow().self_box.clone().into();
436        };
437
438        // It's *very* important that this not borrow the element's main
439        // `InnerLayoutData`. Primary pseudo-elements are processed at the same recursion
440        // level as the main data, so the `BoxSlot` is created sequentially with other
441        // primary pseudo-elements and the element itself. The secondary pseudo-element is
442        // one level deep, so could be happening in parallel with the primary
443        // pseudo-elements or main element layout.
444        let primary_layout_data = self
445            .inner_layout_data()
446            .expect("Should already have element InnerLayoutData here.")
447            .pseudo_layout_data(primary)
448            .expect("Should already have primary pseudo-element InnerLayoutData here");
449        let secondary_layout_data = primary_layout_data
450            .borrow_mut()
451            .create_pseudo_layout_data(secondary);
452        secondary_layout_data.borrow().self_box.clone().into()
453    }
454
455    fn unset_all_boxes(&self) {
456        let mut layout_data = self.ensure_inner_layout_data();
457        *layout_data.self_box.borrow_mut() = None;
458        layout_data.pseudo_boxes.clear();
459
460        // Stylo already takes care of removing all layout data
461        // for DOM descendants of elements with `display: none`.
462    }
463
464    fn with_layout_box_base_including_pseudos(&self, callback: impl Fn(&LayoutBoxBase)) {
465        if let Some(inner_layout_data) = self.inner_layout_data() {
466            inner_layout_data.with_layout_box_base_including_pseudos(callback);
467        }
468    }
469
470    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment> {
471        let Some(layout_data) = self.inner_layout_data() else {
472            return vec![];
473        };
474        match pseudo_element {
475            Some(pseudo_element) => layout_data
476                .pseudo_layout_data(pseudo_element)
477                .map(|pseudo_layout_data| pseudo_layout_data.borrow().fragments())
478                .unwrap_or_default(),
479            None => layout_data.fragments(),
480        }
481    }
482
483    fn repair_style(&self, context: &SharedStyleContext) {
484        if let Some(layout_data) = self.inner_layout_data() {
485            layout_data.repair_style(self, context);
486        }
487    }
488
489    fn isolates_box_tree_rebuild_damage(&self) -> bool {
490        let Some(inner_layout_data) = self.inner_layout_data() else {
491            return false;
492        };
493        let self_box = inner_layout_data.self_box.borrow();
494        let Some(self_box) = &*self_box else {
495            return false;
496        };
497
498        match self_box {
499            LayoutBox::DisplayContents(..) => false,
500            LayoutBox::BlockLevel(block_level) => matches!(
501                &*block_level.borrow(),
502                BlockLevelBox::Independent(..) |
503                    BlockLevelBox::OutOfFlowAbsolutelyPositionedBox(..)
504            ),
505            LayoutBox::InlineLevel(inline_level) => matches!(
506                inline_level,
507                InlineItem::OutOfFlowAbsolutelyPositionedBox(..) | InlineItem::Atomic(..)
508            ),
509            LayoutBox::FlexLevel(..) => true,
510            LayoutBox::TableLevelBox(..) => false,
511            LayoutBox::TaffyItemBox(..) => true,
512        }
513    }
514}