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_fold<T>(
174        &mut self,
175        init: T,
176        callback: impl Fn(T, &mut LayoutBoxBase) -> T,
177    ) -> T {
178        match self {
179            LayoutBox::DisplayContents(..) => init,
180            LayoutBox::BlockLevel(block_level_box) => block_level_box
181                .borrow_mut()
182                .with_base_mut(|base| callback(init, base)),
183            LayoutBox::InlineLevel(inline_items) => inline_items.iter().fold(init, |acc, item| {
184                item.borrow_mut().with_base_mut(|base| callback(acc, base))
185            }),
186            LayoutBox::FlexLevel(flex_level_box) => flex_level_box
187                .borrow_mut()
188                .with_base_mut(|base| callback(init, base)),
189            LayoutBox::TableLevelBox(table_level_box) => {
190                table_level_box.with_base_mut(|base| callback(init, base))
191            },
192            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box
193                .borrow_mut()
194                .with_base_mut(|base| callback(init, base)),
195        }
196    }
197
198    fn repair_style(
199        &self,
200        context: &SharedStyleContext,
201        node: &ServoThreadSafeLayoutNode,
202        new_style: &ServoArc<ComputedValues>,
203    ) {
204        match self {
205            LayoutBox::DisplayContents(inline_shared_styles) => {
206                *inline_shared_styles.style.borrow_mut() = new_style.clone();
207                *inline_shared_styles.selected.borrow_mut() = node.selected_style();
208            },
209            LayoutBox::BlockLevel(block_level_box) => {
210                block_level_box
211                    .borrow_mut()
212                    .repair_style(context, node, new_style);
213            },
214            LayoutBox::InlineLevel(inline_items) => {
215                for inline_item in inline_items {
216                    inline_item
217                        .borrow_mut()
218                        .repair_style(context, node, new_style);
219                }
220            },
221            LayoutBox::FlexLevel(flex_level_box) => flex_level_box
222                .borrow_mut()
223                .repair_style(context, node, new_style),
224            LayoutBox::TableLevelBox(table_level_box) => {
225                table_level_box.repair_style(context, node, new_style)
226            },
227            LayoutBox::TaffyItemBox(taffy_item_box) => taffy_item_box
228                .borrow_mut()
229                .repair_style(context, node, new_style),
230        }
231    }
232
233    /// If this [`LayoutBox`] represents an unsplit (due to inline-block splits) inline
234    /// level item, unwrap and return it. If not, return `None`.
235    pub(crate) fn unsplit_inline_level_layout_box(self) -> Option<ArcRefCell<InlineItem>> {
236        let LayoutBox::InlineLevel(inline_level_boxes) = self else {
237            return None;
238        };
239        // If this element box has been subject to inline-block splitting, ignore it. It's
240        // not useful currently for incremental box tree construction.
241        if inline_level_boxes.len() != 1 {
242            return None;
243        }
244        inline_level_boxes.into_iter().next()
245    }
246}
247
248/// A wrapper for [`InnerDOMLayoutData`]. This is necessary to give the entire data
249/// structure interior mutability, as we will need to mutate the layout data of
250/// non-mutable DOM nodes.
251#[derive(Default, MallocSizeOf)]
252pub struct DOMLayoutData(AtomicRefCell<InnerDOMLayoutData>);
253
254// The implementation of this trait allows the data to be stored in the DOM.
255impl LayoutDataTrait for DOMLayoutData {}
256impl GenericLayoutDataTrait for DOMLayoutData {
257    fn as_any(&self) -> &dyn std::any::Any {
258        self
259    }
260}
261
262pub struct BoxSlot<'dom> {
263    pub(crate) slot: Option<ArcRefCell<Option<LayoutBox>>>,
264    pub(crate) marker: PhantomData<&'dom ()>,
265}
266
267impl From<ArcRefCell<Option<LayoutBox>>> for BoxSlot<'_> {
268    fn from(layout_box_slot: ArcRefCell<Option<LayoutBox>>) -> Self {
269        let slot = Some(layout_box_slot);
270        Self {
271            slot,
272            marker: PhantomData,
273        }
274    }
275}
276
277/// A mutable reference to a `LayoutBox` stored in a DOM element.
278impl BoxSlot<'_> {
279    pub(crate) fn set(mut self, box_: LayoutBox) {
280        if let Some(slot) = &mut self.slot {
281            *slot.borrow_mut() = Some(box_);
282        }
283    }
284
285    pub(crate) fn take_layout_box_if_undamaged(&self, damage: LayoutDamage) -> Option<LayoutBox> {
286        if damage.has_box_damage() {
287            return None;
288        }
289        self.slot.as_ref().and_then(|slot| slot.borrow_mut().take())
290    }
291}
292
293impl Drop for BoxSlot<'_> {
294    fn drop(&mut self) {
295        if !std::thread::panicking() {
296            if let Some(slot) = &mut self.slot {
297                assert!(slot.borrow().is_some(), "failed to set a layout box");
298            }
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>;
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    /// Remove all pseudo-element boxes for this element.
321    fn unset_all_pseudo_boxes(&self);
322
323    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment>;
324    fn clear_fragment_layout_cache(&self);
325
326    fn repair_style(&self, context: &SharedStyleContext);
327    fn take_restyle_damage(&self) -> LayoutDamage;
328}
329
330impl<'dom> NodeExt<'dom> for ServoThreadSafeLayoutNode<'dom> {
331    fn as_image(&self) -> Option<(Option<Image>, PhysicalSize<f64>)> {
332        let (resource, metadata) = self.image_data()?;
333        let (width, height) = resource
334            .as_ref()
335            .map(|image| {
336                let image_metadata = image.metadata();
337                (image_metadata.width, image_metadata.height)
338            })
339            .or_else(|| metadata.map(|metadata| (metadata.width, metadata.height)))
340            .unwrap_or((0, 0));
341        let (mut width, mut height) = (width as f64, height as f64);
342        if let Some(density) = self.image_density().filter(|density| *density != 1.) {
343            width /= density;
344            height /= density;
345        }
346        Some((resource, PhysicalSize::new(width, height)))
347    }
348
349    fn as_svg(&self) -> Option<SVGElementData> {
350        self.svg_data()
351    }
352
353    fn as_video(&self) -> Option<(Option<webrender_api::ImageKey>, Option<PhysicalSize<f64>>)> {
354        let data = self.media_data()?;
355        let natural_size = if let Some(frame) = data.current_frame {
356            Some(PhysicalSize::new(frame.width.into(), frame.height.into()))
357        } else {
358            data.metadata
359                .map(|meta| PhysicalSize::new(meta.width.into(), meta.height.into()))
360        };
361        Some((
362            data.current_frame.map(|frame| frame.image_key),
363            natural_size,
364        ))
365    }
366
367    fn as_canvas(&self) -> Option<(CanvasInfo, PhysicalSize<f64>)> {
368        let canvas_data = self.canvas_data()?;
369        let source = canvas_data.source;
370        Some((
371            CanvasInfo { source },
372            PhysicalSize::new(canvas_data.width.into(), canvas_data.height.into()),
373        ))
374    }
375
376    fn as_iframe(&self) -> Option<(PipelineId, BrowsingContextId)> {
377        match (self.iframe_pipeline_id(), self.iframe_browsing_context_id()) {
378            (Some(pipeline_id), Some(browsing_context_id)) => {
379                Some((pipeline_id, browsing_context_id))
380            },
381            _ => None,
382        }
383    }
384
385    fn as_typeless_object_with_data_attribute(&self) -> Option<String> {
386        if self.type_id() !=
387            Some(ScriptLayoutNodeType::Element(
388                LayoutElementType::HTMLObjectElement,
389            ))
390        {
391            return None;
392        }
393
394        // TODO: This is the what the legacy layout system did, but really if Servo
395        // supports any `<object>` that's an image, it should support those with URLs
396        // and `type` attributes with image mime types.
397        let element = self.as_element()?;
398        if element.get_attr(&ns!(), &local_name!("type")).is_some() {
399            return None;
400        }
401        element
402            .get_attr(&ns!(), &local_name!("data"))
403            .map(|string| string.to_owned())
404    }
405
406    fn ensure_inner_layout_data(&self) -> AtomicRefMut<'dom, InnerDOMLayoutData> {
407        if self.layout_data().is_none() {
408            self.initialize_layout_data::<DOMLayoutData>();
409        }
410        self.layout_data()
411            .unwrap()
412            .as_any()
413            .downcast_ref::<DOMLayoutData>()
414            .unwrap()
415            .0
416            .borrow_mut()
417    }
418
419    fn inner_layout_data(&self) -> Option<AtomicRef<'dom, InnerDOMLayoutData>> {
420        self.layout_data().map(|data| {
421            data.as_any()
422                .downcast_ref::<DOMLayoutData>()
423                .unwrap()
424                .0
425                .borrow()
426        })
427    }
428
429    fn box_slot(&self) -> BoxSlot<'dom> {
430        let pseudo_element_chain = self.pseudo_element_chain();
431        let Some(primary) = pseudo_element_chain.primary else {
432            return self.ensure_inner_layout_data().self_box.clone().into();
433        };
434
435        let Some(secondary) = pseudo_element_chain.secondary else {
436            let primary_layout_data = self
437                .ensure_inner_layout_data()
438                .create_pseudo_layout_data(primary);
439            return primary_layout_data.borrow().self_box.clone().into();
440        };
441
442        // It's *very* important that this not borrow the element's main
443        // `InnerLayoutData`. Primary pseudo-elements are processed at the same recursion
444        // level as the main data, so the `BoxSlot` is created sequentially with other
445        // primary pseudo-elements and the element itself. The secondary pseudo-element is
446        // one level deep, so could be happening in parallel with the primary
447        // pseudo-elements or main element layout.
448        let primary_layout_data = self
449            .inner_layout_data()
450            .expect("Should already have element InnerLayoutData here.")
451            .pseudo_layout_data(primary)
452            .expect("Should already have primary pseudo-element InnerLayoutData here");
453        let secondary_layout_data = primary_layout_data
454            .borrow_mut()
455            .create_pseudo_layout_data(secondary);
456        secondary_layout_data.borrow().self_box.clone().into()
457    }
458
459    fn unset_all_boxes(&self) {
460        let mut layout_data = self.ensure_inner_layout_data();
461        *layout_data.self_box.borrow_mut() = None;
462        layout_data.pseudo_boxes.clear();
463
464        // Stylo already takes care of removing all layout data
465        // for DOM descendants of elements with `display: none`.
466    }
467
468    fn unset_all_pseudo_boxes(&self) {
469        self.ensure_inner_layout_data().pseudo_boxes.clear();
470    }
471
472    fn clear_fragment_layout_cache(&self) {
473        if let Some(inner_layout_data) = self.inner_layout_data() {
474            inner_layout_data.clear_fragment_layout_cache();
475        }
476    }
477
478    fn fragments_for_pseudo(&self, pseudo_element: Option<PseudoElement>) -> Vec<Fragment> {
479        let Some(layout_data) = self.inner_layout_data() else {
480            return vec![];
481        };
482        match pseudo_element {
483            Some(pseudo_element) => layout_data
484                .pseudo_layout_data(pseudo_element)
485                .map(|pseudo_layout_data| pseudo_layout_data.borrow().fragments())
486                .unwrap_or_default(),
487            None => layout_data.fragments(),
488        }
489    }
490
491    fn repair_style(&self, context: &SharedStyleContext) {
492        if let Some(layout_data) = self.inner_layout_data() {
493            layout_data.repair_style(self, context);
494        }
495    }
496
497    fn take_restyle_damage(&self) -> LayoutDamage {
498        let damage = self
499            .style_data()
500            .map(|style_data| std::mem::take(&mut style_data.element_data.borrow_mut().damage))
501            .unwrap_or_else(RestyleDamage::reconstruct);
502        LayoutDamage::from_bits_retain(damage.bits())
503    }
504}