Skip to main content

layout/
style_ext.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 app_units::Au;
6use layout_api::{AxesOverflow, LayoutElementType, LayoutNode, LayoutNodeType};
7use malloc_size_of_derive::MallocSizeOf;
8use style::Zero;
9use style::color::AbsoluteColor;
10use style::computed_values::direction::T as Direction;
11use style::computed_values::isolation::T as ComputedIsolation;
12use style::computed_values::mix_blend_mode::T as ComputedMixBlendMode;
13use style::computed_values::position::T as ComputedPosition;
14use style::computed_values::transform_style::T as ComputedTransformStyle;
15use style::computed_values::unicode_bidi::T as UnicodeBidi;
16use style::logical_geometry::{LogicalAxis, PhysicalSide, WritingMode};
17use style::properties::ComputedValues;
18use style::properties::longhands::backface_visibility::computed_value::T as BackfaceVisiblity;
19use style::properties::longhands::box_sizing::computed_value::T as BoxSizing;
20use style::properties::longhands::column_span::computed_value::T as ColumnSpan;
21use style::servo::selector_parser::PseudoElement;
22use style::values::CSSFloat;
23use style::values::computed::basic_shape::ClipPath;
24use style::values::computed::image::Image as ComputedImageLayer;
25use style::values::computed::{
26    BorderSideWidth, BorderStyle, Inset, ItemPlacement, LengthPercentage, Margin, SelfAlignment,
27    TextWrapMode, WhiteSpaceCollapse,
28};
29use style::values::generics::box_::Perspective;
30use style::values::generics::position::{GenericAspectRatio, PreferredRatio};
31use style::values::generics::transform::{GenericRotate, GenericScale, GenericTranslate};
32use style::values::specified::align::AlignFlags;
33use style::values::specified::{Overflow, WillChangeBits, box_ as stylo};
34use unicode_bidi::Level;
35use webrender_api as wr;
36use webrender_api::units::LayoutTransform;
37
38use crate::containing_block::{ContainingBlock, IndefiniteContainingBlock};
39use crate::dom_traversal::{Contents, NodeAndStyleInfo};
40use crate::fragment_tree::FragmentFlags;
41use crate::geom::{
42    AuOrAuto, LengthPercentageOrAuto, LogicalSides, LogicalSides1D, LogicalVec2, PhysicalSides,
43    PhysicalSize,
44};
45use crate::sizing::{Size, Sizes};
46use crate::table::TableLayoutStyle;
47
48#[derive(Clone, Copy, Eq, PartialEq)]
49pub(crate) enum Display {
50    None,
51    Contents,
52    GeneratingBox(DisplayGeneratingBox),
53}
54
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub(crate) enum DisplayGeneratingBox {
57    OutsideInside {
58        outside: DisplayOutside,
59        inside: DisplayInside,
60    },
61    /// <https://drafts.csswg.org/css-display-3/#layout-specific-display>
62    LayoutInternal(DisplayLayoutInternal),
63}
64impl DisplayGeneratingBox {
65    pub(crate) fn display_inside(&self) -> DisplayInside {
66        match *self {
67            DisplayGeneratingBox::OutsideInside { inside, .. } => inside,
68            DisplayGeneratingBox::LayoutInternal(layout_internal) => {
69                layout_internal.display_inside()
70            },
71        }
72    }
73
74    pub(crate) fn used_value_for_contents(
75        &self,
76        contents: &Contents,
77        info: &NodeAndStyleInfo,
78    ) -> Self {
79        if matches!(contents, Contents::NonReplaced(_)) {
80            return *self;
81        }
82        // The spec quotes below only mention replaced elements, but browsers agree
83        // that they also apply to widgets.
84        match self {
85            // From <https://www.w3.org/TR/css-display-3/#layout-specific-display>:
86            // > When the `display` property of a replaced element computes to one of
87            // > the layout-internal values, it is handled as having a used value of
88            // > `inline`.
89            // Note that `inline` actually behaves as `inline-block` (see below).
90            Self::LayoutInternal(_) => Self::OutsideInside {
91                outside: DisplayOutside::Inline,
92                inside: DisplayInside::FlowRoot {
93                    is_list_item: false,
94                },
95            },
96            // From <https://www.w3.org/TR/css-display-3/#replaced-element>:
97            // > Replaced elements always establish an independent formatting context.
98            // Therefore, replace a `flow` inner display type with `flow-root`,
99            // or just use `flow-root` unconditionally, depending on the element.
100            // Also, prevent it from being a list item, like Blink and WebKit, but
101            // unlike Gecko. See <https://github.com/w3c/csswg-drafts/issues/14187>
102            Self::OutsideInside { outside, inside }
103                if matches!(
104                    inside,
105                    DisplayInside::Flow { .. } | DisplayInside::FlowRoot { .. }
106                ) || info.node.type_id() !=
107                    Some(LayoutNodeType::Element(
108                        LayoutElementType::HTMLButtonElement,
109                    )) =>
110            {
111                DisplayGeneratingBox::OutsideInside {
112                    outside: *outside,
113                    inside: DisplayInside::FlowRoot {
114                        is_list_item: false,
115                    },
116                }
117            },
118            _ => *self,
119        }
120    }
121}
122
123#[derive(Clone, Copy, Debug, Eq, PartialEq)]
124pub(crate) enum DisplayOutside {
125    Block,
126    Inline,
127}
128
129#[derive(Clone, Copy, Debug, Eq, PartialEq)]
130pub(crate) enum DisplayInside {
131    // “list-items are limited to the Flow Layout display types”
132    // <https://drafts.csswg.org/css-display/#list-items>
133    Flow { is_list_item: bool },
134    FlowRoot { is_list_item: bool },
135    Flex,
136    Grid,
137    Table,
138}
139
140#[derive(Clone, Copy, Debug, Eq, PartialEq)]
141#[expect(clippy::enum_variant_names)]
142/// <https://drafts.csswg.org/css-display-3/#layout-specific-display>
143pub(crate) enum DisplayLayoutInternal {
144    TableCaption,
145    TableCell,
146    TableColumn,
147    TableColumnGroup,
148    TableFooterGroup,
149    TableHeaderGroup,
150    TableRow,
151    TableRowGroup,
152}
153
154impl DisplayLayoutInternal {
155    /// <https://drafts.csswg.org/css-display-3/#layout-specific-displa>
156    pub(crate) fn display_inside(&self) -> DisplayInside {
157        // When we add ruby, the display_inside of ruby must be Flow.
158        // TODO: this should be unreachable for everything but
159        // table cell and caption, once we have box tree fixups.
160        DisplayInside::FlowRoot {
161            is_list_item: false,
162        }
163    }
164}
165
166/// Percentages resolved but not `auto` margins
167#[derive(Clone, Debug)]
168pub(crate) struct PaddingBorderMargin {
169    pub padding: LogicalSides<Au>,
170    pub border: LogicalSides<Au>,
171    pub margin: LogicalSides<AuOrAuto>,
172
173    /// Pre-computed sums in each axis
174    pub padding_border_sums: LogicalVec2<Au>,
175}
176
177impl PaddingBorderMargin {
178    pub(crate) fn zero() -> Self {
179        Self {
180            padding: LogicalSides::zero(),
181            border: LogicalSides::zero(),
182            margin: LogicalSides::zero(),
183            padding_border_sums: LogicalVec2::zero(),
184        }
185    }
186
187    pub(crate) fn sums_auto_is_zero(
188        &self,
189        ignore_block_margins: LogicalSides1D<bool>,
190    ) -> LogicalVec2<Au> {
191        let margin = self.margin.auto_is(Au::zero);
192        let mut sums = self.padding_border_sums;
193        sums.inline += margin.inline_sum();
194        if !ignore_block_margins.start {
195            sums.block += margin.block_start;
196        }
197        if !ignore_block_margins.end {
198            sums.block += margin.block_end;
199        }
200        sums
201    }
202}
203
204/// Resolved `aspect-ratio` property with respect to a specific element. Depends
205/// on that element's `box-sizing` (and padding and border, if that `box-sizing`
206/// is `border-box`).
207#[derive(Clone, Copy, Debug)]
208pub(crate) struct AspectRatio {
209    /// If the element that this aspect ratio belongs to uses box-sizing:
210    /// border-box, and the aspect-ratio property does not contain "auto", then
211    /// the aspect ratio is in respect to the border box. This will then contain
212    /// the summed sizes of the padding and border. Otherwise, it's 0.
213    box_sizing_adjustment: LogicalVec2<Au>,
214    /// The ratio itself (inline over block).
215    i_over_b: CSSFloat,
216}
217
218impl AspectRatio {
219    /// Given one side length, compute the other one.
220    pub(crate) fn compute_dependent_size(
221        &self,
222        ratio_dependent_axis: LogicalAxis,
223        ratio_determining_size: Au,
224    ) -> Au {
225        match ratio_dependent_axis {
226            // Calculate the inline size from the block size
227            LogicalAxis::Inline => {
228                (ratio_determining_size + self.box_sizing_adjustment.block).scale_by(self.i_over_b) -
229                    self.box_sizing_adjustment.inline
230            },
231            // Calculate the block size from the inline size
232            LogicalAxis::Block => {
233                (ratio_determining_size + self.box_sizing_adjustment.inline)
234                    .scale_by(1.0 / self.i_over_b) -
235                    self.box_sizing_adjustment.block
236            },
237        }
238    }
239
240    pub(crate) fn from_logical_content_ratio(i_over_b: CSSFloat) -> Self {
241        Self {
242            box_sizing_adjustment: LogicalVec2::zero(),
243            i_over_b,
244        }
245    }
246}
247
248#[derive(Clone)]
249pub(crate) struct ContentBoxSizesAndPBM {
250    pub content_box_sizes: LogicalVec2<Sizes>,
251    pub pbm: PaddingBorderMargin,
252    pub depends_on_block_constraints: bool,
253    pub preferred_size_computes_to_auto: LogicalVec2<bool>,
254}
255
256#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
257pub(crate) struct BorderStyleColor {
258    pub style: BorderStyle,
259    pub color: AbsoluteColor,
260}
261
262impl BorderStyleColor {
263    pub(crate) fn new(style: BorderStyle, color: AbsoluteColor) -> Self {
264        Self { style, color }
265    }
266
267    pub(crate) fn from_style(style: &ComputedValues) -> PhysicalSides<Self> {
268        let border = style.get_border();
269        PhysicalSides::<Self>::new(
270            Self::new(
271                border.border_top_style,
272                style.resolve_color(&border.border_top_color),
273            ),
274            Self::new(
275                border.border_right_style,
276                style.resolve_color(&border.border_right_color),
277            ),
278            Self::new(
279                border.border_bottom_style,
280                style.resolve_color(&border.border_bottom_color),
281            ),
282            Self::new(
283                border.border_left_style,
284                style.resolve_color(&border.border_left_color),
285            ),
286        )
287    }
288
289    pub(crate) fn hidden() -> Self {
290        Self::new(BorderStyle::Hidden, AbsoluteColor::TRANSPARENT_BLACK)
291    }
292}
293
294impl Default for BorderStyleColor {
295    fn default() -> Self {
296        Self::new(BorderStyle::None, AbsoluteColor::TRANSPARENT_BLACK)
297    }
298}
299
300/// <https://drafts.csswg.org/cssom-view/#overflow-directions>
301/// > A scrolling box of a viewport or element has two overflow directions,
302/// > which are the block-end and inline-end directions for that viewport or element.
303pub(crate) struct OverflowDirection {
304    /// Whether block-end or inline-end direction is [PhysicalSide::Right].
305    pub rightward: bool,
306    /// Whether block-end or inline-end direction is [PhysicalSide::Bottom].
307    pub downward: bool,
308}
309
310pub(crate) trait ComputedValuesExt {
311    fn physical_box_offsets(&self) -> PhysicalSides<LengthPercentageOrAuto<'_>>;
312    fn box_offsets(&self, writing_mode: WritingMode) -> LogicalSides<LengthPercentageOrAuto<'_>>;
313    fn box_size(
314        &self,
315        containing_block_writing_mode: WritingMode,
316    ) -> LogicalVec2<Size<LengthPercentage>>;
317    fn min_box_size(
318        &self,
319        containing_block_writing_mode: WritingMode,
320    ) -> LogicalVec2<Size<LengthPercentage>>;
321    fn max_box_size(
322        &self,
323        containing_block_writing_mode: WritingMode,
324    ) -> LogicalVec2<Size<LengthPercentage>>;
325    fn content_box_size_for_box_size(
326        &self,
327        box_size: LogicalVec2<Size<Au>>,
328        pbm: &PaddingBorderMargin,
329    ) -> LogicalVec2<Size<Au>>;
330    fn content_min_box_size_for_min_size(
331        &self,
332        box_size: LogicalVec2<Size<Au>>,
333        pbm: &PaddingBorderMargin,
334    ) -> LogicalVec2<Size<Au>>;
335    fn content_max_box_size_for_max_size(
336        &self,
337        box_size: LogicalVec2<Size<Au>>,
338        pbm: &PaddingBorderMargin,
339    ) -> LogicalVec2<Size<Au>>;
340    fn border_style_color(
341        &self,
342        containing_block_writing_mode: WritingMode,
343    ) -> LogicalSides<BorderStyleColor>;
344    fn physical_margin(&self) -> PhysicalSides<LengthPercentageOrAuto<'_>>;
345    fn margin(
346        &self,
347        containing_block_writing_mode: WritingMode,
348    ) -> LogicalSides<LengthPercentageOrAuto<'_>>;
349    fn is_transformable(&self, fragment_flags: FragmentFlags) -> bool;
350    fn has_transform_or_perspective_style(&self) -> bool;
351    fn has_transform_style(&self) -> bool;
352    fn has_effective_transform(&self, fragment_flags: FragmentFlags) -> bool;
353    fn has_effective_transform_or_perspective(&self, fragment_flags: FragmentFlags) -> bool;
354    fn z_index_applies(&self, fragment_flags: FragmentFlags) -> bool;
355    fn effective_z_index(&self, fragment_flags: FragmentFlags) -> i32;
356    fn effective_overflow(&self, fragment_flags: FragmentFlags) -> AxesOverflow;
357    fn used_transform_style(&self, fragment_flags: FragmentFlags) -> ComputedTransformStyle;
358    fn establishes_block_formatting_context(&self, fragment_flags: FragmentFlags) -> bool;
359    fn establishes_stacking_context(&self, fragment_flags: FragmentFlags) -> bool;
360    fn establishes_scroll_container(&self, fragment_flags: FragmentFlags) -> bool;
361    fn establishes_or_extends_3d_rendering_context(&self, fragment_flags: FragmentFlags) -> bool;
362    fn establishes_containing_block_for_absolute_descendants(
363        &self,
364        fragment_flags: FragmentFlags,
365    ) -> bool;
366    fn establishes_containing_block_for_all_descendants(
367        &self,
368        fragment_flags: FragmentFlags,
369    ) -> bool;
370    fn preferred_aspect_ratio(
371        &self,
372        natural_aspect_ratio: Option<CSSFloat>,
373        padding_border_sums: &LogicalVec2<Au>,
374    ) -> Option<AspectRatio>;
375    fn background_is_transparent(&self) -> bool;
376    fn webrender_primitive_flags(&self) -> wr::PrimitiveFlags;
377    fn bidi_control_chars(&self) -> (&'static str, &'static str);
378    fn resolve_align_self(
379        &self,
380        resolved_auto_value: ItemPlacement,
381        resolved_normal_value: AlignFlags,
382    ) -> SelfAlignment;
383    fn depends_on_block_constraints_due_to_relative_positioning(
384        &self,
385        writing_mode: WritingMode,
386    ) -> bool;
387    fn is_inline_box(&self, fragment_flags: FragmentFlags) -> bool;
388    fn is_atomic_inline_level(&self, fragment_flags: FragmentFlags) -> bool;
389    fn overflow_direction(&self) -> OverflowDirection;
390    fn to_bidi_level(&self) -> Level;
391    /// Whether or not this style causes conditional hanging in inline layout
392    /// i.e. if it is `white-space-collapse: preserve` and `text-wrap-mode: wrap`.
393    fn white_space_may_hang_conditionally(&self) -> bool;
394}
395
396impl ComputedValuesExt for ComputedValues {
397    fn physical_box_offsets(&self) -> PhysicalSides<LengthPercentageOrAuto<'_>> {
398        fn convert(inset: &Inset) -> LengthPercentageOrAuto<'_> {
399            match inset {
400                Inset::LengthPercentage(v) => LengthPercentageOrAuto::LengthPercentage(v),
401                Inset::Auto => LengthPercentageOrAuto::Auto,
402                Inset::AnchorFunction(_) => unreachable!("anchor() should be disabled"),
403                Inset::AnchorSizeFunction(_) => unreachable!("anchor-size() should be disabled"),
404                Inset::AnchorContainingCalcFunction(_) => {
405                    unreachable!("anchor() and anchor-size() should be disabled")
406                },
407            }
408        }
409        let position = self.get_position();
410        PhysicalSides::new(
411            convert(&position.top),
412            convert(&position.right),
413            convert(&position.bottom),
414            convert(&position.left),
415        )
416    }
417
418    fn box_offsets(&self, writing_mode: WritingMode) -> LogicalSides<LengthPercentageOrAuto<'_>> {
419        LogicalSides::from_physical(&self.physical_box_offsets(), writing_mode)
420    }
421
422    fn box_size(
423        &self,
424        containing_block_writing_mode: WritingMode,
425    ) -> LogicalVec2<Size<LengthPercentage>> {
426        let position = self.get_position();
427        LogicalVec2::from_physical_size(
428            &PhysicalSize::new(position.get_width().into(), position.get_height().into()),
429            containing_block_writing_mode,
430        )
431    }
432
433    fn min_box_size(
434        &self,
435        containing_block_writing_mode: WritingMode,
436    ) -> LogicalVec2<Size<LengthPercentage>> {
437        let position = self.get_position();
438        LogicalVec2::from_physical_size(
439            &PhysicalSize::new(
440                position.get_min_width().into(),
441                position.get_min_height().into(),
442            ),
443            containing_block_writing_mode,
444        )
445    }
446
447    fn max_box_size(
448        &self,
449        containing_block_writing_mode: WritingMode,
450    ) -> LogicalVec2<Size<LengthPercentage>> {
451        let position = self.get_position();
452        LogicalVec2::from_physical_size(
453            &PhysicalSize::new(
454                position.get_max_width().into(),
455                position.get_max_height().into(),
456            ),
457            containing_block_writing_mode,
458        )
459    }
460
461    fn content_box_size_for_box_size(
462        &self,
463        box_size: LogicalVec2<Size<Au>>,
464        pbm: &PaddingBorderMargin,
465    ) -> LogicalVec2<Size<Au>> {
466        match self.get_position().box_sizing {
467            BoxSizing::ContentBox => box_size,
468            // These may be negative, but will later be clamped by `min-width`/`min-height`
469            // which is clamped to zero.
470            BoxSizing::BorderBox => box_size.map_inline_and_block_sizes(
471                |value| value - pbm.padding_border_sums.inline,
472                |value| value - pbm.padding_border_sums.block,
473            ),
474        }
475    }
476
477    fn content_min_box_size_for_min_size(
478        &self,
479        min_box_size: LogicalVec2<Size<Au>>,
480        pbm: &PaddingBorderMargin,
481    ) -> LogicalVec2<Size<Au>> {
482        match self.get_position().box_sizing {
483            BoxSizing::ContentBox => min_box_size,
484            // Clamp to zero to make sure the used size components are non-negative
485            BoxSizing::BorderBox => min_box_size.map_inline_and_block_sizes(
486                |value| Au::zero().max(value - pbm.padding_border_sums.inline),
487                |value| Au::zero().max(value - pbm.padding_border_sums.block),
488            ),
489        }
490    }
491
492    fn content_max_box_size_for_max_size(
493        &self,
494        max_box_size: LogicalVec2<Size<Au>>,
495        pbm: &PaddingBorderMargin,
496    ) -> LogicalVec2<Size<Au>> {
497        match self.get_position().box_sizing {
498            BoxSizing::ContentBox => max_box_size,
499            // This may be negative, but will later be clamped by `min-width`
500            // which itself is clamped to zero.
501            BoxSizing::BorderBox => max_box_size.map_inline_and_block_sizes(
502                |value| value - pbm.padding_border_sums.inline,
503                |value| value - pbm.padding_border_sums.block,
504            ),
505        }
506    }
507
508    fn border_style_color(
509        &self,
510        containing_block_writing_mode: WritingMode,
511    ) -> LogicalSides<BorderStyleColor> {
512        LogicalSides::from_physical(
513            &BorderStyleColor::from_style(self),
514            containing_block_writing_mode,
515        )
516    }
517
518    fn physical_margin(&self) -> PhysicalSides<LengthPercentageOrAuto<'_>> {
519        fn convert(inset: &Margin) -> LengthPercentageOrAuto<'_> {
520            match inset {
521                Margin::LengthPercentage(v) => LengthPercentageOrAuto::LengthPercentage(v),
522                Margin::Auto => LengthPercentageOrAuto::Auto,
523                Margin::AnchorSizeFunction(_) | Margin::AnchorContainingCalcFunction(_) => {
524                    unreachable!("anchor-size() should be disabled")
525                },
526            }
527        }
528        let margin = self.get_margin();
529        PhysicalSides::new(
530            convert(&margin.margin_top),
531            convert(&margin.margin_right),
532            convert(&margin.margin_bottom),
533            convert(&margin.margin_left),
534        )
535    }
536
537    fn margin(
538        &self,
539        containing_block_writing_mode: WritingMode,
540    ) -> LogicalSides<LengthPercentageOrAuto<'_>> {
541        LogicalSides::from_physical(&self.physical_margin(), containing_block_writing_mode)
542    }
543
544    fn is_inline_box(&self, fragment_flags: FragmentFlags) -> bool {
545        (self.get_box().display.is_inline_flow() &&
546            !fragment_flags.intersects(
547                FragmentFlags::IS_REPLACED |
548                    FragmentFlags::IS_WIDGET |
549                    FragmentFlags::IS_FLEX_OR_GRID_ITEM,
550            )) ||
551            matches!(self.pseudo(), Some(PseudoElement::FirstLetter))
552    }
553
554    fn is_atomic_inline_level(&self, fragment_flags: FragmentFlags) -> bool {
555        self.get_box().display.outside() == stylo::DisplayOutside::Inline &&
556            !self.is_inline_box(fragment_flags) &&
557            !fragment_flags.intersects(FragmentFlags::IS_FLEX_OR_GRID_ITEM)
558    }
559
560    /// Returns true if this is a transformable element.
561    fn is_transformable(&self, fragment_flags: FragmentFlags) -> bool {
562        // "A transformable element is an element in one of these categories:
563        //   * all elements whose layout is governed by the CSS box model except for
564        //     non-replaced inline boxes, table-column boxes, and table-column-group
565        //     boxes,
566        //   * all SVG paint server elements, the clipPath element  and SVG renderable
567        //     elements with the exception of any descendant element of text content
568        //     elements."
569        // <https://drafts.csswg.org/css-transforms/#transformable-element>
570        // TODO: check for all cases listed in the above spec.
571        !self.is_inline_box(fragment_flags)
572    }
573
574    /// Returns true if this style has a transform or perspective property set.
575    fn has_transform_or_perspective_style(&self) -> bool {
576        self.has_transform_style() || self.get_box().perspective != Perspective::None
577    }
578
579    /// Returns true if this style has a transform property set.
580    fn has_transform_style(&self) -> bool {
581        !self.get_box().transform.0.is_empty() ||
582            self.get_box().scale != GenericScale::None ||
583            self.get_box().rotate != GenericRotate::None ||
584            self.get_box().translate != GenericTranslate::None
585    }
586
587    /// Returns true if this style has a transform or perspective property set, and
588    /// it applies to this element.
589    #[inline]
590    fn has_effective_transform_or_perspective(&self, fragment_flags: FragmentFlags) -> bool {
591        self.is_transformable(fragment_flags) && self.has_transform_or_perspective_style()
592    }
593
594    /// Returns true if this style has the transform property set, and it applies to this
595    /// element.
596    #[inline]
597    fn has_effective_transform(&self, fragment_flags: FragmentFlags) -> bool {
598        self.is_transformable(fragment_flags) && self.has_transform_style()
599    }
600
601    /// Whether the `z-index` property applies to this fragment.
602    fn z_index_applies(&self, fragment_flags: FragmentFlags) -> bool {
603        // As per CSS 2 § 9.9.1, `z-index` applies to positioned elements.
604        // <http://www.w3.org/TR/CSS2/visuren.html#z-index>
605        if self.get_box().position != ComputedPosition::Static {
606            return true;
607        }
608        // More modern specs also apply it to flex and grid items.
609        // - From <https://www.w3.org/TR/css-flexbox-1/#painting>:
610        //   > Flex items paint exactly the same as inline blocks [CSS2], except that order-modified
611        //   > document order is used in place of raw document order, and z-index values other than auto
612        //   > create a stacking context even if position is static (behaving exactly as if position
613        //   > were relative).
614        // - From <https://drafts.csswg.org/css-flexbox/#painting>:
615        //   > The painting order of grid items is exactly the same as inline blocks [CSS2], except that
616        //   > order-modified document order is used in place of raw document order, and z-index values
617        //   > other than auto create a stacking context even if position is static (behaving exactly
618        //   > as if position were relative).
619        fragment_flags.contains(FragmentFlags::IS_FLEX_OR_GRID_ITEM)
620    }
621
622    /// Get the effective z-index of this fragment. Z-indices only apply to positioned elements
623    /// per CSS 2 9.9.1 (<http://www.w3.org/TR/CSS2/visuren.html#z-index>), so this value may differ
624    /// from the value specified in the style.
625    fn effective_z_index(&self, fragment_flags: FragmentFlags) -> i32 {
626        if self.z_index_applies(fragment_flags) {
627            self.get_position().z_index.integer_or(0)
628        } else {
629            0
630        }
631    }
632
633    /// Get the effective overflow of this box. The property only applies to block containers,
634    /// flex containers, and grid containers. And some box types only accept a few values.
635    /// <https://www.w3.org/TR/css-overflow-3/#overflow-control>
636    fn effective_overflow(&self, fragment_flags: FragmentFlags) -> AxesOverflow {
637        // https://www.w3.org/TR/css-overflow-3/#overflow-propagation
638        // The element from which the value is propagated must then have a used overflow value of visible.
639        if fragment_flags.contains(FragmentFlags::PROPAGATED_OVERFLOW_TO_VIEWPORT) {
640            return AxesOverflow::default();
641        }
642
643        let mut overflow = AxesOverflow::from(self);
644
645        // From <https://www.w3.org/TR/css-overflow-4/#overflow-control>:
646        // "On replaced elements, the used values of all computed values other than visible is clip."
647        if fragment_flags.contains(FragmentFlags::IS_REPLACED) {
648            if overflow.x != Overflow::Visible {
649                overflow.x = Overflow::Clip;
650            }
651            if overflow.y != Overflow::Visible {
652                overflow.y = Overflow::Clip;
653            }
654            return overflow;
655        }
656
657        let ignores_overflow = match self.get_box().display.inside() {
658            // <https://drafts.csswg.org/css-overflow-3/#overflow-control>
659            // `overflow` doesn't apply to inline boxes.
660            stylo::DisplayInside::Flow => self.is_inline_box(fragment_flags),
661
662            // According to <https://drafts.csswg.org/css-tables/#global-style-overrides>,
663            // - overflow applies to table-wrapper boxes and not to table grid boxes.
664            //   That's what Blink and WebKit do, however Firefox matches a CSSWG resolution that says
665            //   the opposite: <https://lists.w3.org/Archives/Public/www-style/2012Aug/0298.html>
666            //   Due to the way that we implement table-wrapper boxes, it's easier to align with Firefox.
667            // - Tables ignore overflow values different than visible, clip and hidden.
668            //   This affects both axes, to ensure they have the same scrollability.
669            stylo::DisplayInside::Table => {
670                !matches!(self.pseudo(), Some(PseudoElement::ServoTableGrid)) ||
671                    matches!(overflow.x, Overflow::Auto | Overflow::Scroll) ||
672                    matches!(overflow.y, Overflow::Auto | Overflow::Scroll)
673            },
674
675            // <https://drafts.csswg.org/css-tables/#global-style-overrides>
676            // Table-track and table-track-group boxes ignore overflow.
677            stylo::DisplayInside::TableColumn |
678            stylo::DisplayInside::TableColumnGroup |
679            stylo::DisplayInside::TableRow |
680            stylo::DisplayInside::TableRowGroup |
681            stylo::DisplayInside::TableHeaderGroup |
682            stylo::DisplayInside::TableFooterGroup => true,
683
684            _ => false,
685        };
686        if ignores_overflow {
687            return AxesOverflow::default();
688        }
689
690        overflow
691    }
692
693    /// Get the used `transform-style` value according to the the rules in
694    /// <https://drafts.csswg.org/css-transforms/#grouping-property-values>.
695    fn used_transform_style(&self, fragment_flags: FragmentFlags) -> ComputedTransformStyle {
696        // The check for flat here is to avoid having to check all of the properties below when
697        // possible.
698        let box_style = self.get_box();
699        if box_style.transform_style == ComputedTransformStyle::Flat {
700            return ComputedTransformStyle::Flat;
701        }
702
703        // https://drafts.csswg.org/css-transforms-2/#grouping-property-values
704        //  * overflow: any value other than visible or clip.
705        //  * opacity: any value less than 1.
706        //  * filter: any value other than none.
707        //  * clip: any value other than auto.
708        //  * clip-path: any value other than none.
709        //  * isolation: used value of isolate.
710        //  * mask-image: any value other than none.
711        //  * mask-border-source: any value other than none.
712        //  * mix-blend-mode: any value other than normal.
713        //  * contain: paint and any other property/value combination that causes
714        //    paint containment. Note: this includes any property that affect the
715        //    used value of the contain property, such as content-visibility:
716        //    hidden.
717        //
718        // TODO: Support `mask-image`, `mask-border-source`, and `contain`.
719        let effects = self.get_effects();
720        let overflow = self.effective_overflow(fragment_flags);
721        if !matches!(overflow.x, Overflow::Visible | Overflow::Clip) ||
722            !matches!(overflow.y, Overflow::Visible | Overflow::Clip) ||
723            effects.opacity < 1.0 ||
724            !effects.filter.0.is_empty() ||
725            !effects.clip.is_auto() ||
726            self.get_svg().clip_path != ClipPath::None ||
727            self.get_box().isolation == ComputedIsolation::Isolate ||
728            effects.mix_blend_mode != ComputedMixBlendMode::Normal
729        {
730            return ComputedTransformStyle::Flat;
731        }
732
733        // Return the computed value if not overridden by the above exceptions
734        box_style.transform_style
735    }
736
737    /// Return true if this style is a normal block and establishes
738    /// a new block formatting context.
739    ///
740    /// NOTE: This should be kept in sync with the checks in `impl
741    /// TElement::compute_layout_damage` for `ServoLayoutElement` in
742    /// `components/script/layout_dom/element.rs`.
743    fn establishes_block_formatting_context(&self, fragment_flags: FragmentFlags) -> bool {
744        if self.establishes_scroll_container(fragment_flags) {
745            return true;
746        }
747
748        if self.get_column().is_multicol() {
749            return true;
750        }
751
752        if self.get_column().column_span == ColumnSpan::All {
753            return true;
754        }
755
756        // Per <https://drafts.csswg.org/css-align/#distribution-block>:
757        // Block containers with an `align-content` value that is not `normal` should
758        // form an independent block formatting context. This should really only happen
759        // for block containers, but we do not support subgrid containers yet which is the
760        // only other case.
761        if self.get_position().align_content.primary() != AlignFlags::NORMAL {
762            return true;
763        }
764
765        // TODO: We need to handle CSS Contain here.
766        false
767    }
768
769    /// Whether or not the `overflow` value of this style establishes a scroll container.
770    fn establishes_scroll_container(&self, fragment_flags: FragmentFlags) -> bool {
771        self.effective_overflow(fragment_flags)
772            .establishes_scroll_container()
773    }
774
775    /// Returns true if this fragment establishes or extends a 3D rendering context.
776    fn establishes_or_extends_3d_rendering_context(&self, fragment_flags: FragmentFlags) -> bool {
777        // > A 3D rendering context is established by a transformable element whose used
778        // > value for transform-style is preserve-3d and which itself is not part of a 3D
779        // > rendering context. An element that establishes a 3D rendering context also
780        // > participates in that context.
781        self.is_transformable(fragment_flags) &&
782            self.used_transform_style(fragment_flags) == ComputedTransformStyle::Preserve3d
783    }
784
785    /// Returns true if this fragment establishes a new stacking context and false otherwise.
786    fn establishes_stacking_context(&self, fragment_flags: FragmentFlags) -> bool {
787        // From <https://www.w3.org/TR/css-will-change/#valdef-will-change-custom-ident>:
788        // > If any non-initial value of a property would create a stacking context on the element,
789        // > specifying that property in will-change must create a stacking context on the element.
790        let will_change_bits = self.get_will_change().bits;
791        if will_change_bits
792            .intersects(WillChangeBits::STACKING_CONTEXT_UNCONDITIONAL | WillChangeBits::OPACITY)
793        {
794            return true;
795        }
796
797        // From <https://www.w3.org/TR/CSS2/visuren.html#z-index>, values different than `auto`
798        // make the box establish a stacking context.
799        if self.z_index_applies(fragment_flags) &&
800            (!self.get_position().z_index.is_auto() ||
801                will_change_bits.intersects(WillChangeBits::Z_INDEX))
802        {
803            return true;
804        }
805
806        // Fixed position and sticky position always create stacking contexts.
807        // Note `will-change: position` is handled above by `STACKING_CONTEXT_UNCONDITIONAL`.
808        if matches!(
809            self.get_box().position,
810            ComputedPosition::Fixed | ComputedPosition::Sticky
811        ) {
812            return true;
813        }
814
815        // From <https://www.w3.org/TR/css-transforms-1/#transform-rendering>
816        // > For elements whose layout is governed by the CSS box model, any value other than
817        // > `none` for the `transform` property results in the creation of a stacking context.
818        //
819        // From <https://www.w3.org/TR/css-transforms-2/#individual-transforms>
820        // > all other values […] create a stacking context and containing block for all
821        // > descendants, per usual for transforms.
822        //
823        // From <https://www.w3.org/TR/css-transforms-2/#perspective-property>
824        // > any value other than none establishes a stacking context.
825        //
826        // From <https://www.w3.org/TR/css-transforms-2/#transform-style-property>
827        // > A computed value of `preserve-3d` for `transform-style` on a transformable element
828        // > establishes both a stacking context and a containing block for all descendants.
829        if self.is_transformable(fragment_flags) &&
830            (self.has_transform_or_perspective_style() ||
831                self.used_transform_style(fragment_flags) ==
832                    ComputedTransformStyle::Preserve3d ||
833                will_change_bits
834                    .intersects(WillChangeBits::TRANSFORM | WillChangeBits::PERSPECTIVE))
835        {
836            return true;
837        }
838
839        // From <https://www.w3.org/TR/css-color-3/#transparency>
840        // > implementations must create a new stacking context for any element with opacity less than 1.
841        // Note `will-change: opacity` is handled above by `WillChangeBits::OPACITY`.
842        let effects = self.get_effects();
843        if effects.opacity != 1.0 {
844            return true;
845        }
846
847        // From <https://www.w3.org/TR/filter-effects-1/#FilterProperty>
848        // > A computed value of other than `none` results in the creation of a stacking context
849        // Note `will-change: filter` is handled above by `STACKING_CONTEXT_UNCONDITIONAL`.
850        if !effects.filter.0.is_empty() {
851            return true;
852        }
853
854        // From <https://drafts.fxtf.org/filter-effects-2/#BackdropFilterProperty>
855        // > A computed value of other than none results in the creation of
856        // > both a stacking context [CSS21] and a Containing Block for
857        // > absolute and fixed position descendants, unless the element it
858        // > applies to is a document root element in the current browsing
859        // > context.
860        // Note `will-change: backdrop-filter` is handled above by
861        // `WillChangeBits::STACKING_CONTEXT_UNCONDITIONAL`.
862        if !effects.backdrop_filter.0.is_empty() &&
863            !fragment_flags.contains(FragmentFlags::IS_ROOT_ELEMENT)
864        {
865            return true;
866        }
867
868        // From <https://www.w3.org/TR/compositing-1/#mix-blend-mode>
869        // > Applying a blendmode other than `normal` to the element must establish a new stacking context
870        // Note `will-change: mix-blend-mode` is handled above by `STACKING_CONTEXT_UNCONDITIONAL`.
871        if effects.mix_blend_mode != ComputedMixBlendMode::Normal {
872            return true;
873        }
874
875        // From <https://www.w3.org/TR/css-masking-1/#the-clip-path>
876        // > A computed value of other than `none` results in the creation of a stacking context.
877        // Note `will-change: clip-path` is handled above by `STACKING_CONTEXT_UNCONDITIONAL`.
878        if self.get_svg().clip_path != ClipPath::None {
879            return true;
880        }
881
882        // From <https://www.w3.org/TR/compositing-1/#isolation>
883        // > For CSS, setting `isolation` to `isolate` will turn the element into a stacking context.
884        // Note `will-change: isolation` is handled above by `STACKING_CONTEXT_UNCONDITIONAL`.
885        if self.get_box().isolation == ComputedIsolation::Isolate {
886            return true;
887        }
888
889        // From https://www.w3.org/TR/CSS22/visuren.html#z-index:
890        // > The root element forms the root stacking context.
891        if fragment_flags.contains(FragmentFlags::IS_ROOT_ELEMENT) {
892            return true;
893        }
894
895        // TODO: We need to handle CSS Contain here.
896        false
897    }
898
899    /// Returns true if this style establishes a containing block for absolute
900    /// descendants (`position: absolute`). If this style happens to establish a
901    /// containing block for “all descendants” (ie including `position: fixed`
902    /// descendants) this method will return true, but a true return value does
903    /// not imply that the style establishes a containing block for all descendants.
904    /// Use `establishes_containing_block_for_all_descendants()` instead.
905    fn establishes_containing_block_for_absolute_descendants(
906        &self,
907        fragment_flags: FragmentFlags,
908    ) -> bool {
909        if self.establishes_containing_block_for_all_descendants(fragment_flags) {
910            return true;
911        }
912
913        // From <https://www.w3.org/TR/css-will-change/#valdef-will-change-custom-ident>:
914        // > If any non-initial value of a property would cause the element to
915        // > generate a containing block for absolutely positioned elements, specifying that property in
916        // > will-change must cause the element to generate a containing block for absolutely positioned elements.
917        if self
918            .get_will_change()
919            .bits
920            .intersects(WillChangeBits::POSITION)
921        {
922            return true;
923        }
924
925        self.get_box().position != ComputedPosition::Static
926    }
927
928    /// Returns true if this style establishes a containing block for
929    /// all descendants, including fixed descendants (`position: fixed`).
930    /// Note that this also implies that it establishes a containing block
931    /// for absolute descendants (`position: absolute`).
932    fn establishes_containing_block_for_all_descendants(
933        &self,
934        fragment_flags: FragmentFlags,
935    ) -> bool {
936        // From <https://www.w3.org/TR/css-will-change/#valdef-will-change-custom-ident>:
937        // > If any non-initial value of a property would cause the element to generate a
938        // > containing block for fixed positioned elements, specifying that property in will-change
939        // > must cause the element to generate a containing block for fixed positioned elements.
940        let will_change_bits = self.get_will_change().bits;
941
942        // From <https://drafts.csswg.org/css-transforms-1/#transform-rendering>:
943        // > any value other than `none` for the `transform` property also causes the element
944        // > to establish a containing block for all descendants.
945        //
946        // From <https://www.w3.org/TR/css-transforms-2/#individual-transforms>
947        // > all other values […] create a stacking context and containing block for all
948        // > descendants, per usual for transforms.
949        //
950        // From <https://drafts.csswg.org/css-transforms-2/#perspective-property>:
951        // > The use of this property with any value other than `none` […] establishes a
952        // > containing block for all descendants, just like the `transform` property does.
953        //
954        // From <https://drafts.csswg.org/css-transforms-2/#transform-style-property>:
955        // > A computed value of `preserve-3d` for `transform-style` on a transformable element
956        // > establishes both a stacking context and a containing block for all descendants.
957        if self.is_transformable(fragment_flags) &&
958            (self.has_transform_or_perspective_style() ||
959                self.used_transform_style(fragment_flags) ==
960                    ComputedTransformStyle::Preserve3d ||
961                will_change_bits
962                    .intersects(WillChangeBits::TRANSFORM | WillChangeBits::PERSPECTIVE))
963        {
964            return true;
965        }
966
967        // From <https://www.w3.org/TR/filter-effects-1/#propdef-filter>:
968        // > A value other than none for the filter property results in the creation of a containing
969        // > block for absolute and fixed positioned descendants unless the element it applies to is
970        // > a document root element in the current browsing context.
971        //
972        // From <https://drafts.fxtf.org/filter-effects-2/#BackdropFilterProperty>:
973        // > A computed value other than `none` results in the creation of both
974        // > a stacking context [CSS21] and a containing block for absolute and
975        // > fixed positioned descendants, unless the element it applies to is
976        // > a document root element in the current browsing context.
977        if !fragment_flags.contains(FragmentFlags::IS_ROOT_ELEMENT) &&
978            (!self.get_effects().filter.0.is_empty() ||
979                !self.get_effects().backdrop_filter.0.is_empty() ||
980                will_change_bits.intersects(WillChangeBits::FIXPOS_CB_NON_SVG))
981        {
982            return true;
983        }
984
985        // TODO: We need to handle CSS Contain here.
986        false
987    }
988
989    /// Resolve the preferred aspect ratio according to the given natural aspect
990    /// ratio and the `aspect-ratio` property.
991    /// See <https://drafts.csswg.org/css-sizing-4/#aspect-ratio>.
992    fn preferred_aspect_ratio(
993        &self,
994        natural_aspect_ratio: Option<CSSFloat>,
995        padding_border_sums: &LogicalVec2<Au>,
996    ) -> Option<AspectRatio> {
997        let &GenericAspectRatio {
998            ref auto,
999            ratio: mut preferred_ratio,
1000        } = self.get_aspect_ratio();
1001
1002        // For all cases where a ratio is specified:
1003        // "If the <ratio> is degenerate, the property instead behaves as auto."
1004        if matches!(preferred_ratio, PreferredRatio::Ratio(ratio) if ratio.is_degenerate()) {
1005            preferred_ratio = PreferredRatio::None;
1006        }
1007
1008        let to_logical_ratio = |physical_ratio| {
1009            if self.writing_mode.is_horizontal() {
1010                physical_ratio
1011            } else {
1012                1.0 / physical_ratio
1013            }
1014        };
1015
1016        match (auto, preferred_ratio) {
1017            // The value `auto`. Either the ratio was not specified, or was
1018            // degenerate and set to PreferredRatio::None above.
1019            //
1020            // "Replaced elements with a natural aspect ratio use that aspect
1021            // ratio; otherwise the box has no preferred aspect ratio. Size
1022            // calculations involving the aspect ratio work with the content box
1023            // dimensions always."
1024            (_, PreferredRatio::None) => natural_aspect_ratio
1025                .map(to_logical_ratio)
1026                .map(AspectRatio::from_logical_content_ratio),
1027            // "If both auto and a <ratio> are specified together, the preferred
1028            // aspect ratio is the specified ratio of width / height unless it
1029            // is a replaced element with a natural aspect ratio, in which case
1030            // that aspect ratio is used instead. In all cases, size
1031            // calculations involving the aspect ratio work with the content box
1032            // dimensions always."
1033            (true, PreferredRatio::Ratio(preferred_ratio)) => Some({
1034                let physical_ratio = natural_aspect_ratio
1035                    .unwrap_or_else(|| (preferred_ratio.0).0 / (preferred_ratio.1).0);
1036                AspectRatio::from_logical_content_ratio(to_logical_ratio(physical_ratio))
1037            }),
1038
1039            // "The box’s preferred aspect ratio is the specified ratio of width
1040            // / height. Size calculations involving the aspect ratio work with
1041            // the dimensions of the box specified by box-sizing."
1042            (false, PreferredRatio::Ratio(preferred_ratio)) => {
1043                // If the `box-sizing` is `border-box`, use the padding and
1044                // border when calculating the aspect ratio.
1045                let box_sizing_adjustment = match self.get_box_sizing() {
1046                    BoxSizing::ContentBox => LogicalVec2::zero(),
1047                    BoxSizing::BorderBox => *padding_border_sums,
1048                };
1049                Some(AspectRatio {
1050                    i_over_b: to_logical_ratio((preferred_ratio.0).0 / (preferred_ratio.1).0),
1051                    box_sizing_adjustment,
1052                })
1053            },
1054        }
1055    }
1056
1057    /// Whether or not this style specifies a non-transparent background.
1058    fn background_is_transparent(&self) -> bool {
1059        let background = self.get_background();
1060        let color = self.resolve_color(&background.background_color);
1061        color.alpha == 0.0 &&
1062            background
1063                .background_image
1064                .0
1065                .iter()
1066                .all(|layer| matches!(layer, ComputedImageLayer::None))
1067    }
1068
1069    /// Generate appropriate WebRender `PrimitiveFlags` that should be used
1070    /// for display items generated by the `Fragment` which owns this style.
1071    fn webrender_primitive_flags(&self) -> wr::PrimitiveFlags {
1072        match self.get_box().backface_visibility {
1073            BackfaceVisiblity::Visible => wr::PrimitiveFlags::default(),
1074            BackfaceVisiblity::Hidden => wr::PrimitiveFlags::empty(),
1075        }
1076    }
1077
1078    /// If the 'unicode-bidi' property has a value other than 'normal', return the bidi control codes
1079    /// to inject before and after the text content of the element.
1080    /// See the table in <http://dev.w3.org/csswg/css-writing-modes/#unicode-bidi>.
1081    fn bidi_control_chars(&self) -> (&'static str, &'static str) {
1082        match (
1083            self.get_text().unicode_bidi,
1084            self.get_inherited_box().direction,
1085        ) {
1086            (UnicodeBidi::Normal, _) => ("", ""),
1087            (UnicodeBidi::Embed, Direction::Ltr) => ("\u{202a}", "\u{202c}"),
1088            (UnicodeBidi::Embed, Direction::Rtl) => ("\u{202b}", "\u{202c}"),
1089            (UnicodeBidi::Isolate, Direction::Ltr) => ("\u{2066}", "\u{2069}"),
1090            (UnicodeBidi::Isolate, Direction::Rtl) => ("\u{2067}", "\u{2069}"),
1091            (UnicodeBidi::BidiOverride, Direction::Ltr) => ("\u{202d}", "\u{202c}"),
1092            (UnicodeBidi::BidiOverride, Direction::Rtl) => ("\u{202e}", "\u{202c}"),
1093            (UnicodeBidi::IsolateOverride, Direction::Ltr) => {
1094                ("\u{2068}\u{202d}", "\u{202c}\u{2069}")
1095            },
1096            (UnicodeBidi::IsolateOverride, Direction::Rtl) => {
1097                ("\u{2068}\u{202e}", "\u{202c}\u{2069}")
1098            },
1099            (UnicodeBidi::Plaintext, _) => ("\u{2068}", "\u{2069}"),
1100        }
1101    }
1102
1103    fn resolve_align_self(
1104        &self,
1105        resolved_auto_value: ItemPlacement,
1106        resolved_normal_value: AlignFlags,
1107    ) -> SelfAlignment {
1108        SelfAlignment(match self.get_align_self().0 {
1109            AlignFlags::AUTO => resolved_auto_value.0,
1110            AlignFlags::NORMAL => resolved_normal_value,
1111            value => value,
1112        })
1113    }
1114
1115    fn depends_on_block_constraints_due_to_relative_positioning(
1116        &self,
1117        writing_mode: WritingMode,
1118    ) -> bool {
1119        if !matches!(
1120            self.get_box().position,
1121            ComputedPosition::Relative | ComputedPosition::Sticky
1122        ) {
1123            return false;
1124        }
1125        let box_offsets = self.box_offsets(writing_mode);
1126        let has_percentage = |offset: LengthPercentageOrAuto<'_>| {
1127            offset
1128                .non_auto()
1129                .is_some_and(LengthPercentage::has_percentage)
1130        };
1131        has_percentage(box_offsets.block_start) || has_percentage(box_offsets.block_end)
1132    }
1133
1134    // <https://drafts.csswg.org/cssom-view/#overflow-directions>
1135    fn overflow_direction(&self) -> OverflowDirection {
1136        let inline_end_direction = self.writing_mode.inline_end_physical_side();
1137        let block_end_direction = self.writing_mode.block_end_physical_side();
1138
1139        let rightward = inline_end_direction == PhysicalSide::Right ||
1140            block_end_direction == PhysicalSide::Right;
1141        let downward = inline_end_direction == PhysicalSide::Bottom ||
1142            block_end_direction == PhysicalSide::Bottom;
1143
1144        // TODO(stevennovaryo): We should consider the flex-container's CSS (e.g. flow-direction: column-reverse).
1145        OverflowDirection {
1146            rightward,
1147            downward,
1148        }
1149    }
1150
1151    /// The default bidirectional embedding level for the writing mode of this style.
1152    ///
1153    /// Returns bidi level 0 if the mode is LTR, or 1 otherwise.
1154    fn to_bidi_level(&self) -> Level {
1155        if self.writing_mode.is_bidi_ltr() {
1156            Level::ltr()
1157        } else {
1158            Level::rtl()
1159        }
1160    }
1161
1162    fn white_space_may_hang_conditionally(&self) -> bool {
1163        *self.get_white_space_collapse() == WhiteSpaceCollapse::Preserve &&
1164            *self.get_text_wrap_mode() == TextWrapMode::Wrap
1165    }
1166}
1167
1168pub(crate) enum LayoutStyle<'a> {
1169    Default(&'a ComputedValues),
1170    Table(TableLayoutStyle<'a>),
1171}
1172
1173impl LayoutStyle<'_> {
1174    #[inline]
1175    pub(crate) fn style(&self) -> &ComputedValues {
1176        match self {
1177            Self::Default(style) => style,
1178            Self::Table(table) => table.style(),
1179        }
1180    }
1181
1182    #[inline]
1183    pub(crate) fn is_table(&self) -> bool {
1184        matches!(self, Self::Table(_))
1185    }
1186
1187    pub(crate) fn content_box_sizes_and_padding_border_margin(
1188        &self,
1189        containing_block: &IndefiniteContainingBlock,
1190    ) -> ContentBoxSizesAndPBM {
1191        let writing_mode = containing_block.style.writing_mode;
1192        let style = self.style();
1193        let box_size = style.box_size(writing_mode);
1194        let min_size = style.min_box_size(writing_mode);
1195        let max_size = style.max_box_size(writing_mode);
1196        let preferred_size_computes_to_auto = box_size.map(|size| size.is_initial());
1197
1198        let depends_on_block_constraints = |size: &Size<LengthPercentage>| {
1199            match size {
1200                // fit-content is like clamp(min-content, stretch, max-content), but currently
1201                // min-content and max-content have the same behavior in the block axis,
1202                // so there is no dependency on block constraints.
1203                // TODO: for flex and grid layout, min-content and max-content should be different.
1204                // TODO: We are assuming that Size::Initial doesn't stretch. However, it may actually
1205                // stretch flex and grid items depending on the CSS Align properties, in that case
1206                // the caller needs to take care of it.
1207                Size::Stretch => true,
1208                Size::Numeric(length_percentage) => length_percentage.has_percentage(),
1209                _ => false,
1210            }
1211        };
1212        let depends_on_block_constraints = depends_on_block_constraints(&box_size.block) ||
1213            depends_on_block_constraints(&min_size.block) ||
1214            depends_on_block_constraints(&max_size.block) ||
1215            style.depends_on_block_constraints_due_to_relative_positioning(writing_mode);
1216
1217        // <https://quirks.spec.whatwg.org/#the-percentage-height-calculation-quirk>
1218        // In quirks mode, in order to resolve percentages, if the actual containing block had an
1219        // indefinite block size, we can instead resolve against some further ancestor.
1220        // However, the spec says to only apply the quirk if `height` is set to a `<percentage>`.
1221        // TODO: What to do in a vertical writing mode? Blink and WebKit still apply the quirk
1222        // to the block axis. Gecko doesn't. See <https://github.com/whatwg/quirks/issues/62>.
1223        // TODO: Blink and WebKit only require a percentage on the preferred sizing property
1224        // for replaced elements. Non-replaced elements always have the quirk.
1225        // TODO: Blink and WebKit consider that a `calc()` that contains a percentage fulfills
1226        // the percentage requirement. See <https://github.com/whatwg/quirks/issues/48>.
1227        let containing_block_size = LogicalVec2 {
1228            inline: containing_block.size.inline_size,
1229            block: if box_size.block.to_percentage().is_some() {
1230                containing_block.maybe_quirky_block_size()
1231            } else {
1232                containing_block.block_size()
1233            },
1234        };
1235
1236        // <https://drafts.csswg.org/css-sizing-3/#cyclic-percentage-contribution>
1237        // If max size properties or preferred size properties are set to a value containing
1238        // indefinite percentages, we treat the entire value as the initial value of the property.
1239        // However, for min size properties, as well as for margins and paddings,
1240        // we instead resolve indefinite percentages against zero.
1241        let containing_block_size_or_zero =
1242            containing_block_size.map(|value| value.unwrap_or_default());
1243        let pbm = self.padding_border_margin_with_writing_mode_and_containing_block_inline_size(
1244            writing_mode,
1245            containing_block_size_or_zero.inline,
1246        );
1247
1248        let box_size = box_size.map_with(&containing_block_size, |size, basis| {
1249            size.resolve_percentages_for_preferred(*basis)
1250        });
1251        let content_box_size = style.content_box_size_for_box_size(box_size, &pbm);
1252        let min_size = min_size.percentages_relative_to_basis(&containing_block_size_or_zero);
1253        let content_min_box_size = style.content_min_box_size_for_min_size(min_size, &pbm);
1254        let max_size = max_size.map_with(&containing_block_size, |size, basis| {
1255            size.resolve_percentages_for_max(*basis)
1256        });
1257        let content_max_box_size = style.content_max_box_size_for_max_size(max_size, &pbm);
1258        ContentBoxSizesAndPBM {
1259            content_box_sizes: LogicalVec2 {
1260                block: Sizes::new(
1261                    content_box_size.block,
1262                    content_min_box_size.block,
1263                    content_max_box_size.block,
1264                ),
1265                inline: Sizes::new(
1266                    content_box_size.inline,
1267                    content_min_box_size.inline,
1268                    content_max_box_size.inline,
1269                ),
1270            },
1271            pbm,
1272            depends_on_block_constraints,
1273            preferred_size_computes_to_auto,
1274        }
1275    }
1276
1277    pub(crate) fn padding_border_margin(
1278        &self,
1279        containing_block: &ContainingBlock,
1280    ) -> PaddingBorderMargin {
1281        self.padding_border_margin_with_writing_mode_and_containing_block_inline_size(
1282            containing_block.style.writing_mode,
1283            containing_block.inline_size(),
1284        )
1285    }
1286
1287    pub(crate) fn padding_border_margin_with_writing_mode_and_containing_block_inline_size(
1288        &self,
1289        writing_mode: WritingMode,
1290        containing_block_inline_size: Au,
1291    ) -> PaddingBorderMargin {
1292        let padding = self
1293            .padding(writing_mode)
1294            .percentages_relative_to(containing_block_inline_size);
1295        let style = self.style();
1296        let border = self.border_width(writing_mode);
1297        let margin = style
1298            .margin(writing_mode)
1299            .percentages_relative_to(containing_block_inline_size);
1300        PaddingBorderMargin {
1301            padding_border_sums: LogicalVec2 {
1302                inline: padding.inline_sum() + border.inline_sum(),
1303                block: padding.block_sum() + border.block_sum(),
1304            },
1305            padding,
1306            border,
1307            margin,
1308        }
1309    }
1310
1311    pub(crate) fn padding(
1312        &self,
1313        containing_block_writing_mode: WritingMode,
1314    ) -> LogicalSides<LengthPercentage> {
1315        if matches!(self, Self::Table(table) if table.collapses_borders()) {
1316            // https://drafts.csswg.org/css-tables/#collapsed-style-overrides
1317            // > The padding of the table-root is ignored (as if it was set to 0px).
1318            return LogicalSides::zero();
1319        }
1320        let padding = self.style().get_padding().clone();
1321        LogicalSides::from_physical(
1322            &PhysicalSides::new(
1323                padding.padding_top.0,
1324                padding.padding_right.0,
1325                padding.padding_bottom.0,
1326                padding.padding_left.0,
1327            ),
1328            containing_block_writing_mode,
1329        )
1330    }
1331
1332    pub(crate) fn border_width(
1333        &self,
1334        containing_block_writing_mode: WritingMode,
1335    ) -> LogicalSides<Au> {
1336        let border_width = match self {
1337            // For tables in collapsed-borders mode we halve the border widths, because
1338            // > in this model, the width of the table includes half the table border.
1339            // https://www.w3.org/TR/CSS22/tables.html#collapsing-borders
1340            Self::Table(table) if table.collapses_borders() => table
1341                .halved_collapsed_border_widths()
1342                .to_physical(self.style().writing_mode),
1343            _ => {
1344                let border = self.style().get_border();
1345                let resolve = |width: &BorderSideWidth, style: BorderStyle| {
1346                    if style.none_or_hidden() {
1347                        Au::zero()
1348                    } else {
1349                        width.0
1350                    }
1351                };
1352                PhysicalSides::new(
1353                    resolve(&border.border_top_width, border.border_top_style),
1354                    resolve(&border.border_right_width, border.border_right_style),
1355                    resolve(&border.border_bottom_width, border.border_bottom_style),
1356                    resolve(&border.border_left_width, border.border_left_style),
1357                )
1358            },
1359        };
1360        LogicalSides::from_physical(&border_width, containing_block_writing_mode)
1361    }
1362}
1363
1364impl From<stylo::Display> for Display {
1365    fn from(packed: stylo::Display) -> Self {
1366        let outside = packed.outside();
1367        let inside = packed.inside();
1368
1369        let outside = match outside {
1370            stylo::DisplayOutside::Block => DisplayOutside::Block,
1371            stylo::DisplayOutside::Inline => DisplayOutside::Inline,
1372            stylo::DisplayOutside::TableCaption => {
1373                return Display::GeneratingBox(DisplayGeneratingBox::LayoutInternal(
1374                    DisplayLayoutInternal::TableCaption,
1375                ));
1376            },
1377            stylo::DisplayOutside::InternalTable => {
1378                let internal = match inside {
1379                    stylo::DisplayInside::TableRowGroup => DisplayLayoutInternal::TableRowGroup,
1380                    stylo::DisplayInside::TableColumn => DisplayLayoutInternal::TableColumn,
1381                    stylo::DisplayInside::TableColumnGroup => {
1382                        DisplayLayoutInternal::TableColumnGroup
1383                    },
1384                    stylo::DisplayInside::TableHeaderGroup => {
1385                        DisplayLayoutInternal::TableHeaderGroup
1386                    },
1387                    stylo::DisplayInside::TableFooterGroup => {
1388                        DisplayLayoutInternal::TableFooterGroup
1389                    },
1390                    stylo::DisplayInside::TableRow => DisplayLayoutInternal::TableRow,
1391                    stylo::DisplayInside::TableCell => DisplayLayoutInternal::TableCell,
1392                    _ => unreachable!("Non-internal DisplayInside found"),
1393                };
1394                return Display::GeneratingBox(DisplayGeneratingBox::LayoutInternal(internal));
1395            },
1396            // This should not be a value of DisplayInside, but oh well
1397            // special-case display: contents because we still want it to work despite the early return
1398            stylo::DisplayOutside::None if inside == stylo::DisplayInside::Contents => {
1399                return Display::Contents;
1400            },
1401            stylo::DisplayOutside::None => return Display::None,
1402        };
1403
1404        let inside = match inside {
1405            stylo::DisplayInside::Flow => DisplayInside::Flow {
1406                is_list_item: packed.is_list_item(),
1407            },
1408            stylo::DisplayInside::FlowRoot => DisplayInside::FlowRoot {
1409                is_list_item: packed.is_list_item(),
1410            },
1411            stylo::DisplayInside::Flex => DisplayInside::Flex,
1412            stylo::DisplayInside::Grid => DisplayInside::Grid,
1413            stylo::DisplayInside::GridLanes => unreachable!("Should be disabled behind a pref"),
1414            stylo::DisplayInside::Table => DisplayInside::Table,
1415
1416            // These should not be values of DisplayInside, but oh well
1417            stylo::DisplayInside::None => return Display::None,
1418            stylo::DisplayInside::Contents => return Display::Contents,
1419
1420            stylo::DisplayInside::TableRowGroup |
1421            stylo::DisplayInside::TableColumn |
1422            stylo::DisplayInside::TableColumnGroup |
1423            stylo::DisplayInside::TableHeaderGroup |
1424            stylo::DisplayInside::TableFooterGroup |
1425            stylo::DisplayInside::TableRow |
1426            stylo::DisplayInside::TableCell => unreachable!("Internal DisplayInside found"),
1427        };
1428        Display::GeneratingBox(DisplayGeneratingBox::OutsideInside { outside, inside })
1429    }
1430}
1431
1432pub(crate) trait Clamp: Sized {
1433    fn clamp_below_max(self, max: Option<Self>) -> Self;
1434    fn clamp_between_extremums(self, min: Self, max: Option<Self>) -> Self;
1435}
1436
1437impl Clamp for Au {
1438    fn clamp_below_max(self, max: Option<Self>) -> Self {
1439        match max {
1440            None => self,
1441            Some(max) => self.min(max),
1442        }
1443    }
1444
1445    fn clamp_between_extremums(self, min: Self, max: Option<Self>) -> Self {
1446        self.clamp_below_max(max).max(min)
1447    }
1448}
1449
1450pub(crate) trait TransformExt {
1451    fn change_basis(&self, x: f32, y: f32, z: f32) -> Self;
1452}
1453
1454impl TransformExt for LayoutTransform {
1455    /// <https://drafts.csswg.org/css-transforms/#transformation-matrix-computation>
1456    fn change_basis(&self, x: f32, y: f32, z: f32) -> Self {
1457        let pre_translation = Self::translation(x, y, z);
1458        let post_translation = Self::translation(-x, -y, -z);
1459        post_translation.then(self).then(&pre_translation)
1460    }
1461}