Skip to main content

layout/fragment_tree/
fragment.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::ops::Range;
6use std::sync::Arc;
7use std::sync::atomic::AtomicBool;
8
9use app_units::Au;
10use atomic_refcell::AtomicRef;
11use euclid::{Point2D, Rect, Size2D};
12use fonts::{FontMetrics, ShapedTextSlice};
13use itertools::Either;
14use layout_api::BoxAreaType;
15use malloc_size_of_derive::MallocSizeOf;
16use servo_arc::Arc as ServoArc;
17use servo_base::cross_process_instant::CrossProcessInstant;
18use servo_base::id::{PipelineId, ScrollTreeNodeId};
19use servo_base::print_tree::PrintTree;
20use servo_base::text::Utf32CodeUnits;
21use servo_url::ServoUrl;
22use style::Zero;
23use style::logical_geometry::WritingMode;
24use style::properties::ComputedValues;
25use style_traits::CSSPixel;
26use webrender_api::{FontInstanceKey, ImageKey};
27
28use super::{BaseFragment, BoxFragment, HoistedSharedFragment, PositioningFragment, Tag};
29use crate::SharedStyle;
30use crate::cell::{ArcRefCell, RefOrAtomicRef};
31use crate::flow::inline::text_run::SharedTextRunData;
32use crate::fragment_tree::FragmentStatus;
33use crate::geom::{LogicalRect, LogicalSides, LogicalVec2, PhysicalPoint, PhysicalRect};
34use crate::layout_impl::LayoutThread;
35
36#[derive(Clone, MallocSizeOf)]
37pub(crate) enum Fragment {
38    LayoutRoot(LayoutRootFragment),
39    Box(#[conditional_malloc_size_of] Arc<BoxFragment>),
40    /// Floating content. A floated fragment is very similar to a normal
41    /// [BoxFragment] but it isn't positioned using normal in block flow
42    /// positioning rules (margin collapse, etc). Instead, they are laid
43    /// out by the [crate::flow::float::SequentialLayoutState] of their
44    /// float containing block formatting context.
45    Float(#[conditional_malloc_size_of] Arc<BoxFragment>),
46    Positioning(#[conditional_malloc_size_of] Arc<PositioningFragment>),
47    /// Absolute and fixed position fragments are hoisted up so that they are children of the
48    /// BoxFragment that establishes their containing blocks, so that they can be laid out properly.
49    /// When this happens an `AbsoluteOrFixedPositionedPlaceholder` fragment is left at the original
50    /// tree position. This allows these hoisted fragments to be painted with regard to their
51    /// original tree order during stacking context tree / display list construction.
52    AbsoluteOrFixedPositionedPlaceholder(ArcRefCell<HoistedSharedFragment>),
53    Text(#[conditional_malloc_size_of] Arc<TextFragment>),
54    Image(#[conditional_malloc_size_of] Arc<ImageFragment>),
55    IFrame(#[conditional_malloc_size_of] Arc<IFrameFragment>),
56}
57
58/// A combination of a [`Fragment`] and its logical rectangle, which is used to keep
59/// a list of fragment children in order to later convert their logical rectangle
60/// into a physical rectangle when the size of the parent fragment is known.
61#[derive(Clone, MallocSizeOf)]
62pub(crate) struct FragmentAndLogicalRect {
63    pub fragment: Fragment,
64    /// The logical rectangle of the fragment relative to its parent's box. This logical rectangle
65    /// will be converted into a physical one, and the Fragment's `content_rect` will be updated
66    /// once the parent box's final size is known.
67    pub logical_rect: LogicalRect<Au>,
68}
69
70impl FragmentAndLogicalRect {
71    pub(crate) fn new(fragment: Fragment, logical_rect: LogicalRect<Au>) -> Self {
72        Self {
73            fragment,
74            logical_rect,
75        }
76    }
77}
78
79#[derive(Clone, MallocSizeOf)]
80pub(crate) struct CollapsedBlockMargins {
81    pub collapsed_through: bool,
82    pub start: CollapsedMargin,
83    pub end: CollapsedMargin,
84}
85
86#[derive(Clone, Copy, Debug, MallocSizeOf)]
87pub(crate) struct CollapsedMargin {
88    max_positive: Au,
89    min_negative: Au,
90}
91
92#[derive(Clone, MallocSizeOf)]
93pub(crate) struct LayoutRootFragment {
94    pub fragment: ArcRefCell<HoistedSharedFragment>,
95}
96
97impl LayoutRootFragment {
98    pub(crate) fn inner(&self) -> AtomicRef<'_, Fragment> {
99        AtomicRef::map(self.fragment.borrow(), |fragment| {
100            fragment
101                .fragment
102                .as_ref()
103                .expect("Should never create LayoutRoot without a Fragment")
104        })
105    }
106
107    pub(crate) fn inner_box_fragment(&self) -> AtomicRef<'_, Arc<BoxFragment>> {
108        AtomicRef::map(self.inner(), |fragment| match fragment {
109            Fragment::Box(box_fragment) => box_fragment,
110            _ => unreachable!("Layout root should always contain box fragment"),
111        })
112    }
113}
114
115#[derive(MallocSizeOf)]
116pub(crate) struct TextFragment {
117    pub base: BaseFragment,
118    #[conditional_malloc_size_of]
119    pub run_data: Arc<SharedTextRunData>,
120    #[conditional_malloc_size_of]
121    pub font_metrics: Arc<FontMetrics>,
122    pub font_key: FontInstanceKey,
123    #[conditional_malloc_size_of]
124    pub glyphs: Vec<Arc<ShapedTextSlice>>,
125    /// Extra space to add for each justification opportunity.
126    pub justification_adjustment: Au,
127    /// The range of characters this [`TextFragment`] represents within the text of its
128    /// original DOM node (modified by text transformation).
129    pub character_range_in_dom_node: Range<Utf32CodeUnits>,
130    /// Whether or not this [`TextFragment`] is an empty fragment added for the
131    /// benefit of placing a text cursor on an otherwise empty editable line.
132    pub is_empty_for_text_cursor: bool,
133}
134
135#[derive(MallocSizeOf)]
136pub(crate) struct ImageFragment {
137    pub base: BaseFragment,
138    pub style: SharedStyle,
139    /// The style to use for the selection overlay if this [`ImageFragment`] is
140    /// selected.
141    pub selected_style: SharedStyle,
142    pub clip: PhysicalRect<Au>,
143    pub image_key: Option<ImageKey>,
144    pub showing_broken_image_icon: bool,
145    pub url: Option<ServoUrl>,
146    pub load_time: Option<CrossProcessInstant>,
147    /// The intrinsic (natural) width of the image, if known.
148    pub natural_width: Option<Au>,
149    /// The intrinsic (natural) height of the image, if known.
150    pub natural_height: Option<Au>,
151    /// Whether or not this image is selected.
152    #[conditional_malloc_size_of]
153    pub selected: Arc<AtomicBool>,
154}
155
156#[derive(MallocSizeOf)]
157pub(crate) struct IFrameFragment {
158    pub base: BaseFragment,
159    pub style: SharedStyle,
160    pub pipeline_id: PipelineId,
161}
162
163impl Fragment {
164    pub fn base(&self) -> Option<RefOrAtomicRef<'_, BaseFragment>> {
165        Some(match self {
166            Fragment::LayoutRoot(fragment) => RefOrAtomicRef::AtomicRef(AtomicRef::map(
167                fragment.inner_box_fragment(),
168                |box_fragment| &box_fragment.base,
169            )),
170            Fragment::Box(fragment) => RefOrAtomicRef::Ref(&fragment.base),
171            Fragment::Text(fragment) => RefOrAtomicRef::Ref(&fragment.base),
172            Fragment::AbsoluteOrFixedPositionedPlaceholder(_) => return None,
173            Fragment::Positioning(fragment) => RefOrAtomicRef::Ref(&fragment.base),
174            Fragment::Image(fragment) => RefOrAtomicRef::Ref(&fragment.base),
175            Fragment::IFrame(fragment) => RefOrAtomicRef::Ref(&fragment.base),
176            Fragment::Float(fragment) => RefOrAtomicRef::Ref(&fragment.base),
177        })
178    }
179
180    pub(crate) fn set_cumulative_content_rect(&self, content_rect: &PhysicalRect<Au>) {
181        match self {
182            Fragment::LayoutRoot(layout_root_fragment) => layout_root_fragment
183                .inner()
184                .set_cumulative_content_rect(content_rect),
185            Fragment::Box(box_fragment) | Fragment::Float(box_fragment) => {
186                box_fragment.set_cumulative_content_rect(content_rect)
187            },
188            Fragment::Positioning(positioning_fragment) => {
189                positioning_fragment.set_cumulative_content_rect(content_rect)
190            },
191            Fragment::AbsoluteOrFixedPositionedPlaceholder(..) |
192            Fragment::Text(..) |
193            Fragment::Image(..) |
194            Fragment::IFrame(..) => {},
195        }
196    }
197
198    pub fn tag(&self) -> Option<Tag> {
199        self.base().and_then(|base| base.tag)
200    }
201
202    pub fn print(&self, tree: &mut PrintTree) {
203        match self {
204            Fragment::LayoutRoot(layout_root_fragment) => layout_root_fragment.inner().print(tree),
205            Fragment::Box(fragment) => fragment.print(tree),
206            Fragment::Float(fragment) => {
207                tree.new_level("Float".to_string());
208                fragment.print(tree);
209                tree.end_level();
210            },
211            Fragment::AbsoluteOrFixedPositionedPlaceholder(_) => {
212                tree.add_item("AbsoluteOrFixedPositioned".to_string());
213            },
214            Fragment::Positioning(fragment) => fragment.print(tree),
215            Fragment::Text(fragment) => fragment.print(tree),
216            Fragment::Image(fragment) => fragment.print(tree),
217            Fragment::IFrame(fragment) => fragment.print(tree),
218        }
219    }
220
221    pub(crate) fn scrolling_area(&self, layout_thread: &LayoutThread) -> PhysicalRect<Au> {
222        self.retrieve_box_fragment().map_or_else(
223            || self.scrollable_overflow_for_parent(),
224            |box_fragment| {
225                box_fragment.offset_by_cumulative_content_offset(
226                    &box_fragment.with_style().scrollable_overflow(),
227                    layout_thread.into(),
228                )
229            },
230        )
231    }
232
233    /// Clear the scrollable overflow on this [`Fragment`]. This is called during damage
234    /// propagation when a fragment is preserved, itself or one of its descendants has
235    /// scrollable overflow damage.
236    pub(crate) fn clear_scrollable_overflow(&self) {
237        match self {
238            Fragment::LayoutRoot(fragment) => {
239                fragment.inner_box_fragment().clear_scrollable_overflow()
240            },
241            Fragment::Box(fragment) | Fragment::Float(fragment) => {
242                fragment.clear_scrollable_overflow()
243            },
244            Fragment::Positioning(fragment) => fragment.clear_scrollable_overflow(),
245            _ => {},
246        }
247    }
248
249    pub(crate) fn scrollable_overflow_for_parent(&self) -> PhysicalRect<Au> {
250        match self {
251            Fragment::LayoutRoot(layout_root) => {
252                layout_root.inner().scrollable_overflow_for_parent()
253            },
254            Fragment::Box(fragment) | Fragment::Float(fragment) => {
255                fragment.with_style().scrollable_overflow_for_parent()
256            },
257            Fragment::Positioning(fragment) => fragment.scrollable_overflow_for_parent(),
258            Fragment::Text(fragment) => fragment.scrollable_overflow_for_parent(),
259            Fragment::AbsoluteOrFixedPositionedPlaceholder(_) |
260            Fragment::Image(..) |
261            Fragment::IFrame(..) => self.base().map(|base| base.rect()).unwrap_or_default(),
262        }
263    }
264
265    fn set_rect(&self, rect: PhysicalRect<Au>) {
266        if let Some(base) = self.base() {
267            base.set_rect(rect);
268        }
269    }
270
271    /// From <https://drafts.csswg.org/css-overflow-3/#scrollable>:
272    /// > This padding represents, within the scrollable overflow rectangle, the box’s own padding
273    /// > so that when its content is scrolled to its end, there is padding between the edge of its
274    /// > in-flow (or floated) content and the border edge of the box. It typically ends up being
275    /// > exactly the same size as the box’s own padding, except in a few cases—​such as when an
276    /// > out-of-flow positioned element, or the visible overflow of a descendent, has already
277    /// > increased the size of the scrollable overflow rectangle outside the conceptual “content
278    /// > edge” of the scroll container’s content.
279    pub(crate) fn scrollable_overflow_padding_contribution_for_parent(
280        &self,
281    ) -> Option<PhysicalRect<Au>> {
282        match self {
283            // TODO: This should consider the box in pre-relative-adjusted position state.
284            Fragment::Box(fragment) | Fragment::Float(fragment)
285                if !fragment
286                    .style()
287                    .get_box()
288                    .position
289                    .is_absolutely_positioned() =>
290            {
291                Some(fragment.margin_rect())
292            },
293            // Layout roots and absolutely positioned elements do not affect scrollable overflow
294            // for parents.
295            Fragment::Box(..) | Fragment::Float(..) | Fragment::LayoutRoot(..) => None,
296            // TODO: This rectangle does not include extra size from overflowing inline items. As
297            // this measurement is concerned with the actual fragments, it's quite likely that this
298            // rectangle should include that.
299            Fragment::Positioning(fragment) => Some(fragment.base.rect()),
300            Fragment::AbsoluteOrFixedPositionedPlaceholder(_) => None,
301            Fragment::Text(..) | Fragment::Image(..) | Fragment::IFrame(..) => {
302                Some(self.base()?.rect())
303            },
304        }
305    }
306
307    pub(crate) fn cumulative_box_area_rect(
308        &self,
309        area: BoxAreaType,
310        cumulative_content_rect_calculation: CumulativeContentRectCalculation<'_>,
311    ) -> Option<PhysicalRect<Au>> {
312        match self {
313            Fragment::LayoutRoot(layout_root_fragment) => layout_root_fragment
314                .inner()
315                .cumulative_box_area_rect(area, cumulative_content_rect_calculation),
316            Fragment::Box(fragment) | Fragment::Float(fragment) => Some(match area {
317                BoxAreaType::Content => {
318                    fragment.cumulative_content_box_rect(cumulative_content_rect_calculation)
319                },
320                BoxAreaType::Padding => {
321                    fragment.cumulative_padding_box_rect(cumulative_content_rect_calculation)
322                },
323                BoxAreaType::Border => {
324                    fragment.cumulative_border_box_rect(cumulative_content_rect_calculation)
325                },
326            }),
327            Fragment::Positioning(fragment) => Some(fragment.offset_by_containing_block(
328                &fragment.base.rect(),
329                cumulative_content_rect_calculation,
330            )),
331            Fragment::Text(_) |
332            Fragment::AbsoluteOrFixedPositionedPlaceholder(_) |
333            Fragment::Image(_) |
334            Fragment::IFrame(_) => None,
335        }
336    }
337
338    pub(crate) fn client_rect(&self) -> Rect<i32, CSSPixel> {
339        let Some(fragment) = self.retrieve_box_fragment() else {
340            return Rect::zero();
341        };
342        let fragment = fragment.with_style();
343
344        // https://drafts.csswg.org/cssom-view/#dom-element-clienttop
345        // " If the element has no associated CSS layout box or if the
346        //   CSS layout box is inline, return zero." For this check we
347        // also explicitly ignore the list item portion of the display
348        // style.
349        if fragment.is_inline_box() {
350            return Rect::zero();
351        }
352
353        let rect = if fragment.is_table_wrapper() {
354            // For tables the border actually belongs to the table grid box,
355            // so we need to include it in the dimension of the table wrapper box.
356            let mut rect = fragment.border_rect();
357            rect.origin = PhysicalPoint::zero();
358            rect
359        } else {
360            let mut rect = fragment.padding_rect();
361            rect.origin = PhysicalPoint::new(fragment.border.left, fragment.border.top);
362            rect
363        };
364
365        let rect = Rect::new(
366            Point2D::new(rect.origin.x.to_f32_px(), rect.origin.y.to_f32_px()),
367            Size2D::new(rect.size.width.to_f32_px(), rect.size.height.to_f32_px()),
368        );
369        rect.round().to_i32()
370    }
371
372    pub(crate) fn children(&self) -> Option<RefOrAtomicRef<'_, Vec<Fragment>>> {
373        match self {
374            Fragment::LayoutRoot(fragment) => Some(RefOrAtomicRef::AtomicRef(AtomicRef::map(
375                fragment.inner_box_fragment(),
376                |fragment| &fragment.children,
377            ))),
378            Fragment::Box(fragment) | Fragment::Float(fragment) => {
379                Some(RefOrAtomicRef::Ref(&fragment.children))
380            },
381            Fragment::Positioning(fragment) => Some(RefOrAtomicRef::Ref(&fragment.children)),
382            _ => None,
383        }
384    }
385
386    pub(crate) fn find<T>(
387        &self,
388        parent_content_rect: &PhysicalRect<Au>,
389        level: usize,
390        process_func: &mut impl FnMut(&Fragment, usize, &PhysicalRect<Au>) -> Option<T>,
391    ) -> Option<T> {
392        if let Some(result) = process_func(self, level, parent_content_rect) {
393            return Some(result);
394        }
395
396        match self {
397            Fragment::LayoutRoot(layout_root_fragment) => {
398                layout_root_fragment
399                    .inner()
400                    .find(parent_content_rect, level, process_func)
401            },
402            Fragment::Box(fragment) | Fragment::Float(fragment) => {
403                let content_rect_for_descendants = fragment
404                    .content_rect()
405                    .translate(parent_content_rect.origin.to_vector());
406                fragment.children.iter().find_map(|child| {
407                    child.find(&content_rect_for_descendants, level + 1, process_func)
408                })
409            },
410            Fragment::Positioning(fragment) => {
411                let content_rect_for_descendants = fragment
412                    .base
413                    .rect()
414                    .translate(parent_content_rect.origin.to_vector());
415                fragment.children.iter().find_map(|child| {
416                    child.find(&content_rect_for_descendants, level + 1, process_func)
417                })
418            },
419            _ => None,
420        }
421    }
422
423    pub(crate) fn repair_style(&self, new_style: &ServoArc<ComputedValues>) {
424        if let Some(base) = self.base() {
425            base.set_status(FragmentStatus::StyleChanged);
426        }
427
428        let inner_box_fragment;
429        let shared_style = match self {
430            Fragment::LayoutRoot(fragment) => {
431                inner_box_fragment = fragment.inner_box_fragment();
432                &inner_box_fragment.style
433            },
434            Fragment::Box(fragment) => &fragment.style,
435            Fragment::Text(fragment) => &fragment.run_data.inline_styles.style,
436            Fragment::AbsoluteOrFixedPositionedPlaceholder(_) => return,
437            Fragment::Positioning(fragment) => &fragment.style,
438            Fragment::Image(fragment) => &fragment.style,
439            Fragment::IFrame(fragment) => &fragment.style,
440            Fragment::Float(fragment) => &fragment.style,
441        };
442        *shared_style.borrow_mut() = new_style.clone();
443    }
444
445    pub(crate) fn retrieve_box_fragment(&self) -> Option<RefOrAtomicRef<'_, Arc<BoxFragment>>> {
446        match self {
447            Fragment::LayoutRoot(layout_root_fragment) => Some(RefOrAtomicRef::AtomicRef(
448                layout_root_fragment.inner_box_fragment(),
449            )),
450            Fragment::Box(box_fragment) | Fragment::Float(box_fragment) => {
451                Some(RefOrAtomicRef::Ref(box_fragment))
452            },
453            _ => None,
454        }
455    }
456
457    pub(crate) fn is_box_fragment(&self, box_fragment: &BoxFragment) -> bool {
458        self.retrieve_box_fragment()
459            .is_some_and(|this_box_fragment| std::ptr::eq(&**this_box_fragment, box_fragment))
460    }
461
462    pub(crate) fn spatial_tree_node(&self) -> Option<ScrollTreeNodeId> {
463        if let Fragment::Positioning(positioning_fragment) = self {
464            return positioning_fragment.spatial_tree_node.get();
465        };
466        self.retrieve_box_fragment()?.spatial_tree_node()
467    }
468}
469
470impl TextFragment {
471    pub(crate) fn style<'a>(&'a self) -> AtomicRef<'a, ServoArc<ComputedValues>> {
472        self.run_data.inline_styles.style.borrow()
473    }
474
475    pub(crate) fn selected_style<'a>(&'a self) -> AtomicRef<'a, ServoArc<ComputedValues>> {
476        self.run_data.inline_styles.selected.borrow()
477    }
478
479    pub fn print(&self, tree: &mut PrintTree) {
480        tree.add_item(format!(
481            "Text num_glyphs={} box={:?}",
482            self.glyphs
483                .iter()
484                .map(|shaped_text_slice| shaped_text_slice.glyph_count())
485                .sum::<usize>(),
486            self.base.rect()
487        ));
488    }
489
490    /// Whether or not the given point is within the vertical boundaries of this
491    /// [`TextFragment`].
492    pub(crate) fn point_is_within_vertical_boundaries(
493        &self,
494        point_in_fragment: Point2D<Au, CSSPixel>,
495    ) -> bool {
496        let rect = &self.base.rect();
497        rect.min_y() <= point_in_fragment.y && rect.max_y() >= point_in_fragment.y
498    }
499
500    /// Find the distance between for point relative to a [`TextFragment`] for the
501    /// purposes of finding a glyph offset. This is used to identify the most relevant
502    /// fragment for glyph offset queries during click handling.
503    pub(crate) fn distance_to_point_for_glyph_offset(
504        &self,
505        point_in_fragment: Point2D<Au, CSSPixel>,
506    ) -> Au {
507        // point_in_fragment is alerady in a coordinate space where the fragment origin is (0, 0)
508        let rect = Rect::new(Point2D::origin(), self.base.rect().size);
509
510        // This is the distance between the closest point on the edge of the rectangle and
511        // the point. From <https://stackoverflow.com/a/18157551>.
512        let dx = (rect.min_x() - point_in_fragment.x)
513            .max(Au::zero())
514            .max(point_in_fragment.x - rect.max_x());
515        let dy = (rect.min_y() - point_in_fragment.y)
516            .max(Au::zero())
517            .max(point_in_fragment.y - rect.max_y());
518        Au::from_f64_px(dx.to_f64_px().hypot(dy.to_f64_px()))
519    }
520
521    /// Given a point relative to this [`TextFragment`], find the most appropriate
522    /// character offset.
523    ///
524    /// Note that the given point may be outside the [`TextFragment`]'s content rect:
525    ///
526    ///  - If the point is vertically above the [`TextFragment`] the first offset will be returned.
527    ///  - If the point is vertically below the [`TextFragment`], `None` will be returned.
528    pub(crate) fn character_offset(
529        &self,
530        point_in_fragment: Point2D<Au, CSSPixel>,
531    ) -> Option<Utf32CodeUnits> {
532        self.unmapped_character_offset(point_in_fragment)
533            .map(|character_offset| {
534                self.run_data
535                    .map_transformed_offset_to_dom_offset(character_offset)
536            })
537    }
538
539    /// Like [`Self::character_offset`], but returning the character offset in layout text (after
540    /// applying white space collapse and the `text-transform` property), instead of the original DOM
541    /// text.
542    fn unmapped_character_offset(
543        &self,
544        point_in_fragment: Point2D<Au, CSSPixel>,
545    ) -> Option<Utf32CodeUnits> {
546        // If the click was far enough above the top of the fragment, then pick the first index.
547        let max_vertical_offset = self.base.rect().height().scale_by(0.25);
548        if point_in_fragment.y < -max_vertical_offset {
549            return Some(self.character_range_in_dom_node.start);
550        }
551
552        // If the click was below the fragment, return `None`, which will cause the
553        // caller to move the cursor to the end.
554        //
555        // TODO: It would be nice to just return the last offset here, but <textarea>
556        // does not currently make a fragment for all selection indices.
557        if point_in_fragment.y > self.base.rect().max_y() + max_vertical_offset {
558            return None;
559        }
560
561        let mut current_character = self.character_range_in_dom_node.start;
562        let mut current_offset = Au::zero();
563        for glyph_store in &self.glyphs {
564            for glyph in glyph_store.glyphs() {
565                let mut advance = glyph.advance();
566                if glyph.char_is_word_separator() {
567                    advance += self.justification_adjustment;
568                }
569                if current_offset + advance.scale_by(0.5) >= point_in_fragment.x {
570                    return Some(current_character);
571                }
572                current_offset += advance;
573                current_character += glyph.character_count();
574            }
575        }
576
577        Some(current_character)
578    }
579
580    fn scrollable_overflow_for_parent(&self) -> PhysicalRect<Au> {
581        let rect = self.base.rect();
582        let mut hanging_advance = Au::zero();
583        for slice in self.glyphs.iter().rev() {
584            hanging_advance += slice.hangable_advance();
585            if slice.has_non_hangable_non_removable_content() {
586                break;
587            }
588        }
589
590        let writing_mode = self.writing_mode();
591        let size = LogicalVec2::from_physical_size(&rect.size, writing_mode);
592        LogicalRect {
593            start_corner: LogicalVec2::zero(),
594            size: LogicalVec2 {
595                inline: size.inline - hanging_advance,
596                block: size.block,
597            },
598        }
599        .as_physical(writing_mode, size)
600        .translate(rect.origin.to_vector())
601    }
602
603    fn writing_mode(&self) -> WritingMode {
604        let mut writing_mode = self.style().writing_mode;
605        let is_rtl = self
606            .glyphs
607            .first()
608            .is_some_and(|shaped_text| shaped_text.is_rtl());
609
610        // If the directionality of the run is different from the parent writing mode then,
611        // invert the RTL-related bits.
612        if is_rtl == writing_mode.is_bidi_ltr() {
613            writing_mode ^= WritingMode::RTL | WritingMode::INLINE_REVERSED;
614        }
615
616        writing_mode
617    }
618}
619
620impl ImageFragment {
621    pub fn print(&self, tree: &mut PrintTree) {
622        tree.add_item(format!(
623            "Image\
624                \nrect={:?}",
625            self.base.rect()
626        ));
627    }
628}
629
630impl IFrameFragment {
631    pub fn print(&self, tree: &mut PrintTree) {
632        tree.add_item(format!(
633            "IFrame\
634                \npipeline={:?} rect={:?}",
635            self.pipeline_id,
636            self.base.rect()
637        ));
638    }
639}
640
641impl CollapsedBlockMargins {
642    pub fn from_margin(margin: &LogicalSides<Au>) -> Self {
643        Self {
644            collapsed_through: false,
645            start: CollapsedMargin::new(margin.block_start),
646            end: CollapsedMargin::new(margin.block_end),
647        }
648    }
649
650    pub fn zero() -> Self {
651        Self {
652            collapsed_through: false,
653            start: CollapsedMargin::zero(),
654            end: CollapsedMargin::zero(),
655        }
656    }
657}
658
659impl CollapsedMargin {
660    pub fn zero() -> Self {
661        Self {
662            max_positive: Au::zero(),
663            min_negative: Au::zero(),
664        }
665    }
666
667    pub fn new(margin: Au) -> Self {
668        Self {
669            max_positive: margin.max(Au::zero()),
670            min_negative: margin.min(Au::zero()),
671        }
672    }
673
674    pub fn adjoin(&self, other: &Self) -> Self {
675        Self {
676            max_positive: self.max_positive.max(other.max_positive),
677            min_negative: self.min_negative.min(other.min_negative),
678        }
679    }
680
681    pub fn adjoin_assign(&mut self, other: &Self) {
682        *self = self.adjoin(other);
683    }
684
685    pub fn solve(&self) -> Au {
686        self.max_positive + self.min_negative
687    }
688}
689
690/// A token which ensures the calculation and assignment of cumulative containing
691/// blocks to fragments in the fragment tree. This is used because these cumulative
692/// containing block offsets are set during stacking context tree construction, but
693/// some queries might need them beforehand. If the query is executed before stacking
694/// context tree construction, a quick traversal is performed to calculate them for
695/// the purpose of the query.
696pub(crate) enum CumulativeContentRectCalculation<'a> {
697    /// This token variant is for the purpose of a layout query. In this case, if stacking
698    /// context tree construction has not yet taken place, a cumulative containing block
699    /// calculation traversal will be performed.
700    Lazy { layout_thread: &'a LayoutThread },
701    /// This token variant is used when the code can guarantee that stacking context
702    /// tree construction has already taken place.
703    ///
704    /// Note: Using this before stacking context tree construction can lead
705    /// to incorrect layout or layout query results!
706    AlreadyDoneWithStackingContextTree,
707}
708
709impl CumulativeContentRectCalculation<'_> {
710    pub(crate) fn ensure(&self) {
711        match self {
712            Self::Lazy { layout_thread } => layout_thread.ensure_containing_block_calculation(),
713            Self::AlreadyDoneWithStackingContextTree => {},
714        }
715    }
716}
717
718impl<'a> From<&'a LayoutThread> for CumulativeContentRectCalculation<'a> {
719    fn from(layout_thread: &'a LayoutThread) -> Self {
720        Self::Lazy { layout_thread }
721    }
722}
723
724/// A temporary data structure to contain fragments that are meant to be
725/// children of another fragment.
726#[derive(Clone, MallocSizeOf)]
727pub(crate) enum FragmentChildren {
728    PhysicalDeprecated(Vec<Fragment>),
729    Logical(Vec<FragmentAndLogicalRect>),
730}
731
732impl Default for FragmentChildren {
733    fn default() -> Self {
734        Self::Logical(Default::default())
735    }
736}
737
738impl FragmentChildren {
739    pub(crate) fn fragments(&self) -> impl Iterator<Item = &Fragment> {
740        match self {
741            FragmentChildren::PhysicalDeprecated(fragments) => Either::Left(fragments.iter()),
742            FragmentChildren::Logical(fragment_and_logical_rects) => Either::Right(
743                fragment_and_logical_rects
744                    .iter()
745                    .map(|fragment_and_logical_rect| &fragment_and_logical_rect.fragment),
746            ),
747        }
748    }
749
750    pub(crate) fn is_empty(&self) -> bool {
751        match self {
752            FragmentChildren::PhysicalDeprecated(fragments) => fragments.is_empty(),
753            FragmentChildren::Logical(fragment_and_logical_rects) => {
754                fragment_and_logical_rects.is_empty()
755            },
756        }
757    }
758
759    pub(crate) fn len(&self) -> usize {
760        match self {
761            FragmentChildren::PhysicalDeprecated(fragments) => fragments.len(),
762            FragmentChildren::Logical(fragment_and_logical_rects) => {
763                fragment_and_logical_rects.len()
764            },
765        }
766    }
767
768    pub(crate) fn into_physical_fragments(
769        self,
770        writing_mode: WritingMode,
771        container_size: LogicalVec2<Au>,
772    ) -> Vec<Fragment> {
773        match self {
774            FragmentChildren::PhysicalDeprecated(fragments) => fragments,
775            FragmentChildren::Logical(fragment_and_logical_rects) => fragment_and_logical_rects
776                .into_iter()
777                .map(|fragment_and_logical_rect| {
778                    fragment_and_logical_rect.fragment.set_rect(
779                        fragment_and_logical_rect
780                            .logical_rect
781                            .as_physical(writing_mode, container_size),
782                    );
783                    fragment_and_logical_rect.fragment
784                })
785                .collect(),
786        }
787    }
788
789    pub(crate) fn append(
790        &mut self,
791        mut other: Self,
792        writing_mode: WritingMode,
793        container_size: LogicalVec2<Au>,
794    ) {
795        match (self, &mut other) {
796            (Self::PhysicalDeprecated(fragments), _) => {
797                fragments.append(&mut other.into_physical_fragments(writing_mode, container_size))
798            },
799            (Self::Logical(fragments), Self::PhysicalDeprecated(other_fragments)) => {
800                // FIXME: This is wrong. The calculated logical rectangle here might be incorrect,
801                // but this is a graceful degradation of behavior until `PhysicalDeprecated` is
802                // removed entirely.
803                fragments.extend(other_fragments.drain(..).map(|fragment| {
804                    let logical_rect = fragment
805                        .base()
806                        .map(|base| {
807                            LogicalRect::from_physical(base.rect(), writing_mode, container_size)
808                        })
809                        .unwrap_or_else(LogicalRect::zero);
810                    FragmentAndLogicalRect {
811                        fragment,
812                        logical_rect,
813                    }
814                }));
815            },
816            (Self::Logical(fragments), Self::Logical(other_fragments)) => {
817                fragments.append(other_fragments)
818            },
819        }
820    }
821}