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, LayoutDamage, LayoutElementType,
13    LayoutNodeType as ScriptLayoutNodeType, 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, RestyleDamage};
23
24use crate::cell::ArcRefCell;
25use crate::flexbox::FlexLevelBox;
26use crate::flow::BlockLevelBox;
27use crate::flow::inline::{InlineItem, SharedInlineStyles};
28use crate::fragment_tree::Fragment;
29use crate::geom::PhysicalSize;
30use crate::layout_box_base::LayoutBoxBase;
31use crate::replaced::CanvasInfo;
32use crate::table::TableLevelBox;
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            .map(|layout_box| layout_box.with_base_flat(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 clear_fragment_layout_cache(&self) {
98        if let Some(data) = self.self_box.borrow().as_ref() {
99            data.clear_fragment_layout_cache();
100        }
101        for pseudo_layout_data in self.pseudo_boxes.iter() {
102            pseudo_layout_data
103                .data
104                .borrow()
105                .clear_fragment_layout_cache();
106        }
107    }
108}
109
110/// A box that is stored in one of the `DOMLayoutData` slots.
111#[derive(MallocSizeOf)]
112pub(super) enum LayoutBox {
113    DisplayContents(SharedInlineStyles),
114    BlockLevel(ArcRefCell<BlockLevelBox>),
115    InlineLevel(Vec<ArcRefCell<InlineItem>>),
116    FlexLevel(ArcRefCell<FlexLevelBox>),
117    TableLevelBox(TableLevelBox),
118    TaffyItemBox(ArcRefCell<TaffyItemBox>),
119}
120
121impl LayoutBox {
122    fn clear_fragment_layout_cache(&self) {
123        match self {
124            LayoutBox::DisplayContents(..) => {},
125            LayoutBox::BlockLevel(block_level_box) => {
126                block_level_box.borrow().clear_fragment_layout_cache()
127            },
128            LayoutBox::InlineLevel(inline_items) => {
129                for inline_item in inline_items.iter() {
130                    inline_item.borrow().clear_fragment_layout_cache()
131                }
132            },
133            LayoutBox::FlexLevel(flex_level_box) => {
134                flex_level_box.borrow().clear_fragment_layout_cache()
135            },
136            LayoutBox::TaffyItemBox(taffy_item_box) => {
137                taffy_item_box.borrow_mut().clear_fragment_layout_cache()
138            },
139            LayoutBox::TableLevelBox(table_box) => table_box.clear_fragment_layout_cache(),
140        }
141    }
142
143    pub(crate) fn with_first_base<T>(
144        &self,
145        callback: impl FnOnce(&LayoutBoxBase) -> T,
146    ) -> Option<T> {
147        Some(match self {
148            LayoutBox::DisplayContents(..) => return None,
149            LayoutBox::BlockLevel(block_level_box) => block_level_box.borrow().with_base(callback),
150            LayoutBox::InlineLevel(inline_items) => {
151                inline_items.first()?.borrow().with_base(callback)
152            },
153            LayoutBox::FlexLevel(flex_level_box) => flex_level_box.borrow().with_base(callback),
154            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box.borrow().with_base(callback),
155            LayoutBox::TableLevelBox(table_box) => table_box.with_base(callback),
156        })
157    }
158
159    pub(crate) fn with_base_flat<T>(&self, callback: impl Fn(&LayoutBoxBase) -> Vec<T>) -> Vec<T> {
160        match self {
161            LayoutBox::DisplayContents(..) => vec![],
162            LayoutBox::BlockLevel(block_level_box) => block_level_box.borrow().with_base(callback),
163            LayoutBox::InlineLevel(inline_items) => inline_items
164                .iter()
165                .flat_map(|inline_item| inline_item.borrow().with_base(&callback))
166                .collect(),
167            LayoutBox::FlexLevel(flex_level_box) => flex_level_box.borrow().with_base(callback),
168            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box.borrow().with_base(callback),
169            LayoutBox::TableLevelBox(table_box) => table_box.with_base(callback),
170        }
171    }
172
173    pub(crate) fn with_base_mut(&mut self, callback: impl Fn(&mut LayoutBoxBase)) {
174        match self {
175            LayoutBox::DisplayContents(..) => {},
176            LayoutBox::BlockLevel(block_level_box) => {
177                block_level_box.borrow_mut().with_base_mut(callback);
178            },
179            LayoutBox::InlineLevel(inline_items) => {
180                for inline_item in inline_items {
181                    inline_item.borrow_mut().with_base_mut(&callback);
182                }
183            },
184            LayoutBox::FlexLevel(flex_level_box) => {
185                flex_level_box.borrow_mut().with_base_mut(callback)
186            },
187            LayoutBox::TableLevelBox(table_level_box) => table_level_box.with_base_mut(callback),
188            LayoutBox::TaffyItemBox(taffy_item_box) => {
189                taffy_item_box.borrow_mut().with_base_mut(callback)
190            },
191        }
192    }
193
194    fn repair_style(
195        &self,
196        context: &SharedStyleContext,
197        node: &ServoThreadSafeLayoutNode,
198        new_style: &ServoArc<ComputedValues>,
199    ) {
200        match self {
201            LayoutBox::DisplayContents(inline_shared_styles) => {
202                *inline_shared_styles.style.borrow_mut() = new_style.clone();
203                *inline_shared_styles.selected.borrow_mut() = node.selected_style();
204            },
205            LayoutBox::BlockLevel(block_level_box) => {
206                block_level_box
207                    .borrow_mut()
208                    .repair_style(context, node, new_style);
209            },
210            LayoutBox::InlineLevel(inline_items) => {
211                for inline_item in inline_items {
212                    inline_item
213                        .borrow_mut()
214                        .repair_style(context, node, new_style);
215                }
216            },
217            LayoutBox::FlexLevel(flex_level_box) => flex_level_box
218                .borrow_mut()
219                .repair_style(context, node, new_style),
220            LayoutBox::TableLevelBox(table_level_box) => {
221                table_level_box.repair_style(context, node, new_style)
222            },
223            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box
224                .borrow_mut()
225                .repair_style(context, node, new_style),
226        }
227    }
228
229    /// If this [`LayoutBox`] represents an unsplit (due to inline-block splits) inline
230    /// level item, unwrap and return it. If not, return `None`.
231    pub(crate) fn unsplit_inline_level_layout_box(self) -> Option<ArcRefCell<InlineItem>> {
232        let LayoutBox::InlineLevel(inline_level_boxes) = self else {
233            return None;
234        };
235        // If this element box has been subject to inline-block splitting, ignore it. It's
236        // not useful currently for incremental box tree construction.
237        if inline_level_boxes.len() != 1 {
238            return None;
239        }
240        inline_level_boxes.into_iter().next()
241    }
242}
243
244/// A wrapper for [`InnerDOMLayoutData`]. This is necessary to give the entire data
245/// structure interior mutability, as we will need to mutate the layout data of
246/// non-mutable DOM nodes.
247#[derive(Default, MallocSizeOf)]
248pub struct DOMLayoutData(AtomicRefCell<InnerDOMLayoutData>);
249
250// The implementation of this trait allows the data to be stored in the DOM.
251impl LayoutDataTrait for DOMLayoutData {}
252impl GenericLayoutDataTrait for DOMLayoutData {
253    fn as_any(&self) -> &dyn std::any::Any {
254        self
255    }
256}
257
258pub struct BoxSlot<'dom> {
259    pub(crate) slot: Option<ArcRefCell<Option<LayoutBox>>>,
260    pub(crate) marker: PhantomData<&'dom ()>,
261}
262
263impl From<ArcRefCell<Option<LayoutBox>>> for BoxSlot<'_> {
264    fn from(layout_box_slot: ArcRefCell<Option<LayoutBox>>) -> Self {
265        let slot = Some(layout_box_slot);
266        Self {
267            slot,
268            marker: PhantomData,
269        }
270    }
271}
272
273/// A mutable reference to a `LayoutBox` stored in a DOM element.
274impl BoxSlot<'_> {
275    pub(crate) fn set(mut self, box_: LayoutBox) {
276        if let Some(slot) = &mut self.slot {
277            *slot.borrow_mut() = Some(box_);
278        }
279    }
280
281    pub(crate) fn take_layout_box_if_undamaged(&self, damage: LayoutDamage) -> Option<LayoutBox> {
282        if damage.has_box_damage() {
283            return None;
284        }
285        self.slot.as_ref().and_then(|slot| slot.borrow_mut().take())
286    }
287}
288
289impl Drop for BoxSlot<'_> {
290    fn drop(&mut self) {
291        if !std::thread::panicking() {
292            if let Some(slot) = &mut self.slot {
293                assert!(slot.borrow().is_some(), "failed to set a layout box");
294            }
295        }
296    }
297}
298
299pub(crate) trait NodeExt<'dom> {
300    /// Returns the image if it’s loaded, and its size in image pixels
301    /// adjusted for `image_density`.
302    fn as_image(&self) -> Option<(Option<Image>, PhysicalSize<f64>)>;
303    fn as_canvas(&self) -> Option<(CanvasInfo, PhysicalSize<f64>)>;
304    fn as_iframe(&self) -> Option<(PipelineId, BrowsingContextId)>;
305    fn as_video(&self) -> Option<(Option<webrender_api::ImageKey>, Option<PhysicalSize<f64>>)>;
306    fn as_svg(&self) -> Option<SVGElementData>;
307    fn as_typeless_object_with_data_attribute(&self) -> Option<String>;
308
309    fn ensure_inner_layout_data(&self) -> AtomicRefMut<'dom, InnerDOMLayoutData>;
310    fn inner_layout_data(&self) -> Option<AtomicRef<'dom, InnerDOMLayoutData>>;
311    fn box_slot(&self) -> BoxSlot<'dom>;
312
313    /// Remove boxes for the element itself, and all of its pseudo-element boxes.
314    fn unset_all_boxes(&self);
315
316    /// Remove all pseudo-element boxes for this element.
317    fn unset_all_pseudo_boxes(&self);
318
319    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment>;
320    fn clear_fragment_layout_cache(&self);
321
322    fn repair_style(&self, context: &SharedStyleContext);
323    fn take_restyle_damage(&self) -> LayoutDamage;
324}
325
326impl<'dom> NodeExt<'dom> for ServoThreadSafeLayoutNode<'dom> {
327    fn as_image(&self) -> Option<(Option<Image>, PhysicalSize<f64>)> {
328        let (resource, metadata) = self.image_data()?;
329        let (width, height) = resource
330            .as_ref()
331            .map(|image| {
332                let image_metadata = image.metadata();
333                (image_metadata.width, image_metadata.height)
334            })
335            .or_else(|| metadata.map(|metadata| (metadata.width, metadata.height)))
336            .unwrap_or((0, 0));
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> {
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.source;
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 unset_all_pseudo_boxes(&self) {
465        self.ensure_inner_layout_data().pseudo_boxes.clear();
466    }
467
468    fn clear_fragment_layout_cache(&self) {
469        if let Some(inner_layout_data) = self.inner_layout_data() {
470            inner_layout_data.clear_fragment_layout_cache();
471        }
472    }
473
474    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment> {
475        let Some(layout_data) = self.inner_layout_data() else {
476            return vec![];
477        };
478        match pseudo_element {
479            Some(pseudo_element) => layout_data
480                .pseudo_layout_data(pseudo_element)
481                .map(|pseudo_layout_data| pseudo_layout_data.borrow().fragments())
482                .unwrap_or_default(),
483            None => layout_data.fragments(),
484        }
485    }
486
487    fn repair_style(&self, context: &SharedStyleContext) {
488        if let Some(layout_data) = self.inner_layout_data() {
489            layout_data.repair_style(self, context);
490        }
491    }
492
493    fn take_restyle_damage(&self) -> LayoutDamage {
494        let damage = self
495            .style_data()
496            .map(|style_data| std::mem::take(&mut style_data.element_data.borrow_mut().damage))
497            .unwrap_or_else(RestyleDamage::reconstruct);
498        LayoutDamage::from_bits_retain(damage.bits())
499    }
500}