Skip to main content

layout/display_list/
mod.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::cell::{OnceCell, RefCell};
6use std::sync::atomic::Ordering;
7use std::sync::{Arc, LazyLock};
8
9use app_units::{AU_PER_PX, Au};
10use clip::Clip;
11pub(crate) use clip::ClipId;
12use euclid::{Box2D, Point2D, Rect, Scale, SideOffsets2D, Size2D, UnknownUnit, Vector2D};
13use fonts::{FontMetrics, ShapedTextSlice};
14use gradient::WebRenderGradient;
15use layout_api::ReflowStatistics;
16use paint_api::display_list::{PaintDisplayListInfo, SpatialTreeNodeInfo};
17use servo_arc::Arc as ServoArc;
18use servo_base::cross_process_instant::CrossProcessInstant;
19use servo_base::id::{PipelineId, ScrollTreeNodeId};
20use servo_config::opts::{DiagnosticsLogging, DiagnosticsLoggingOption};
21use servo_config::{pref, prefs};
22use servo_url::ServoUrl;
23use style::Zero;
24use style::color::{AbsoluteColor, ColorSpace};
25use style::computed_values::background_blend_mode::SingleComputedValue as BackgroundBlendMode;
26use style::computed_values::border_image_outset::T as BorderImageOutset;
27use style::computed_values::mix_blend_mode::T as ComputedMixBlendMode;
28use style::computed_values::overflow_x::T as ComputedOverflow;
29use style::computed_values::text_decoration_style::T as ComputedTextDecorationStyle;
30use style::computed_values::text_decoration_thickness::T as TextDecorationThickness;
31use style::dom::OpaqueNode;
32use style::properties::ComputedValues;
33use style::properties::longhands::visibility::computed_value::T as Visibility;
34use style::properties::style_structs::Border;
35use style::values::computed::basic_shape::ClipPath as ComputedClipPath;
36use style::values::computed::{
37    BorderImageSideWidth, BorderImageWidth, BorderStyle, LengthPercentage,
38    NonNegativeLengthOrNumber, NumberOrPercentage, OutlineStyle,
39};
40use style::values::generics::NonNegative;
41use style::values::generics::color::ColorOrAuto;
42use style::values::generics::rect::Rect as StyleRect;
43use style::values::specified::text::TextDecorationLine;
44use style_traits::{CSSPixel as StyloCSSPixel, DevicePixel as StyloDevicePixel};
45use webrender_api::units::{
46    DeviceIntSize, DevicePixel, LayoutPixel, LayoutPoint, LayoutRect, LayoutSideOffsets, LayoutSize,
47};
48use webrender_api::{
49    self as wr, BorderDetails, BorderRadius, BorderSide, BoxShadowClipMode, BuiltDisplayList,
50    ClipChainId, ClipMode, ColorF, CommonItemProperties, ComplexClipRegion, GlyphInstance,
51    MixBlendMode, NinePatchBorder, NinePatchBorderSource, NormalBorder, PrimitiveFlags,
52    PropertyBinding, PropertyBindingKey, RasterSpace, SpatialId, StackingContextFlags,
53    TransformStyle, units,
54};
55use wr::units::LayoutVector2D;
56
57use crate::context::{ImageResolver, ResolvedImage};
58use crate::display_list::background::BackgroundPainter;
59use crate::display_list::conversions::FilterToWebRender;
60pub(crate) use crate::display_list::conversions::ToWebRender;
61use crate::display_list::paint_traversal::{PaintTraversal, PaintTraversalHandler, TraversalState};
62use crate::fragment_tree::{
63    BackgroundMode, BaseFragment, BoxFragment, BoxFragmentWithStyle,
64    CumulativeContentRectCalculation, Fragment, FragmentFlags, FragmentStatus, FragmentTree,
65    IFrameFragment, ImageFragment, PositioningFragment, SpecificLayoutInfo, Tag, TextFragment,
66};
67use crate::geom::{
68    LengthPercentageOrAuto, PhysicalPoint, PhysicalRect, PhysicalSides, PhysicalSize,
69};
70use crate::replaced::NaturalSizes;
71use crate::style_ext::{BorderStyleColor, ComputedValuesExt};
72
73mod background;
74mod clip;
75mod conversions;
76mod gradient;
77mod hit_test;
78mod paint_timing_handler;
79mod paint_traversal;
80mod painted_region;
81mod stacking_context;
82
83pub(crate) use hit_test::{ClosestFragmentSearch, HitTest};
84pub(crate) use paint_timing_handler::{
85    ContainerTimingRootChain, ContainerTimingRoots, PaintTimingHandler,
86};
87pub(crate) use stacking_context::*;
88
89const INSERTION_POINT_LOGICAL_WIDTH: Au = Au(AU_PER_PX);
90
91/// A color to use for the selection rectangle when the document isn't focused (does not
92/// have system focus or its frame itself does not have focus).
93///
94/// TODO: This should eventually come from the system theme.
95static UNFOCUSED_SELECTION_COLOR: LazyLock<AbsoluteColor> =
96    LazyLock::new(|| AbsoluteColor::srgb_legacy(200, 200, 200, 1.0));
97
98pub(crate) struct DisplayListBuilder<'a> {
99    /// The [`FragmentTree`] that we are building a display list for.
100    fragment_tree: &'a FragmentTree,
101
102    /// The current [`ScrollTreeNodeId`] for this [`DisplayListBuilder`]. This is
103    /// necessary because some pieces of fragments as backgrounds with
104    /// `background-attachment: fixed` need to not scroll while the rest of the fragment
105    /// does.
106    current_reference_frame_scroll_node_id: ScrollTreeNodeId,
107
108    /// The [`wr::DisplayListBuilder`] for this Servo [`DisplayListBuilder`].
109    pub webrender_display_list_builder: &'a mut wr::DisplayListBuilder,
110
111    /// The [`PaintDisplayListInfo`] used to collect display list items and metadata.
112    pub paint_info: &'a mut PaintDisplayListInfo,
113
114    /// Data about the fragments that are highlighted by the inspector, if any.
115    ///
116    /// This data is collected during the traversal of the fragment tree and used
117    /// to paint the highlight at the very end.
118    inspector_highlight: Option<InspectorHighlight>,
119
120    /// Whether or not the `<body>` element should be painted. This is false if the root `<html>`
121    /// element inherits the `<body>`'s background to paint the page canvas background.
122    /// See <https://drafts.csswg.org/css-backgrounds/#body-background>.
123    paint_body_background: bool,
124
125    /// A mapping from [`ClipId`] To WebRender [`ClipChainId`] used when building this WebRender
126    /// display list.
127    clip_map: Vec<ClipChainId>,
128
129    /// An [`ImageResolver`] to use during display list construction.
130    image_resolver: Arc<ImageResolver>,
131
132    /// The device pixel ratio used for this `Document`'s display list.
133    device_pixel_ratio: Scale<f32, StyloCSSPixel, StyloDevicePixel>,
134
135    /// Handler for all Paint Timings
136    paint_timing_handler: &'a mut PaintTimingHandler,
137
138    /// Statistics collected about the reflow, in order to write tests for incremental layout.
139    reflow_statistics: &'a mut ReflowStatistics,
140
141    /// Whether the `largest_contentul_paint_enabled` preference is enabled.
142    largest_contentful_paint_enabled: bool,
143
144    /// Whether the `container_timing_enabled` preference is enabled.
145    container_timing_enabled: bool,
146
147    /// The background color used for the shell.
148    shell_background_color: AbsoluteColor,
149
150    /// Whether or not the `WebView` this display list is being rendered for has system focus
151    /// and is the focused frame in the frame tree.
152    frame_focused: bool,
153
154    /// Glyphs of the text fragment being built, reused across fragments to avoid
155    /// an allocation per fragment.
156    glyph_buffer: Vec<GlyphInstance>,
157}
158
159struct InspectorHighlight {
160    /// The node that should be highlighted
161    tag: Tag,
162
163    /// Accumulates information about the fragments that belong to the highlighted node.
164    ///
165    /// This information is collected as the fragment tree is traversed to build the
166    /// display list.
167    state: Option<HighlightTraversalState>,
168}
169
170struct HighlightTraversalState {
171    /// The smallest rectangle that fully encloses all fragments created by the highlighted
172    /// dom node, if any.
173    content_box: Rect<Au, StyloCSSPixel>,
174
175    spatial_id: SpatialId,
176
177    clip_chain_id: ClipChainId,
178
179    /// When the highlighted fragment is a box fragment we remember the information
180    /// needed to paint padding, border and margin areas.
181    maybe_box_fragment: Option<Arc<BoxFragment>>,
182}
183
184impl InspectorHighlight {
185    fn for_node(node: OpaqueNode) -> Self {
186        Self {
187            tag: Tag {
188                node,
189                // TODO: Support highlighting pseudo-elements.
190                pseudo_element_chain: Default::default(),
191            },
192            state: None,
193        }
194    }
195}
196
197impl DisplayListBuilder<'_> {
198    #[expect(clippy::too_many_arguments)]
199    pub(crate) fn build(
200        stacking_context_tree: &mut StackingContextTree,
201        fragment_tree: &FragmentTree,
202        image_resolver: Arc<ImageResolver>,
203        device_pixel_ratio: Scale<f32, StyloCSSPixel, StyloDevicePixel>,
204        highlighted_dom_node: Option<OpaqueNode>,
205        debug: &DiagnosticsLogging,
206        paint_timing_handler: &mut PaintTimingHandler,
207        reflow_statistics: &mut ReflowStatistics,
208        frame_focused: bool,
209    ) -> BuiltDisplayList {
210        // Build the rest of the display list which inclues all of the WebRender primitives.
211        let paint_info = &mut stacking_context_tree.paint_info;
212        let pipeline_id = paint_info.pipeline_id;
213        let mut webrender_display_list_builder =
214            webrender_api::DisplayListBuilder::new(pipeline_id);
215        webrender_display_list_builder.begin();
216
217        // `dump_serialized_display_list` doesn't actually print anything. It sets up
218        // the display list for printing the serialized version when `finalize()` is called.
219        // We need to call this before adding any display items so that they are printed
220        // during `finalize()`.
221        if debug.is_enabled(DiagnosticsLoggingOption::DisplayList) {
222            webrender_display_list_builder.dump_serialized_display_list();
223        }
224
225        let shell_background_color = {
226            let default_background_color = pref!(shell_background_color_rgba);
227            AbsoluteColor::new(
228                ColorSpace::Srgb,
229                default_background_color[0] as f32,
230                default_background_color[1] as f32,
231                default_background_color[2] as f32,
232                default_background_color[3] as f32,
233            )
234            .into_srgb_legacy()
235        };
236
237        let _span = profile_traits::trace_span!("DisplayListBuilder::build").entered();
238        let mut builder = DisplayListBuilder {
239            fragment_tree,
240            current_reference_frame_scroll_node_id: paint_info.root_reference_frame_id,
241            webrender_display_list_builder: &mut webrender_display_list_builder,
242            paint_info,
243            inspector_highlight: highlighted_dom_node.map(InspectorHighlight::for_node),
244            paint_body_background: true,
245            clip_map: Default::default(),
246            image_resolver,
247            device_pixel_ratio,
248            paint_timing_handler,
249            reflow_statistics,
250            largest_contentful_paint_enabled: pref!(largest_contentful_paint_enabled),
251            container_timing_enabled: pref!(container_timing_enabled),
252            shell_background_color,
253            frame_focused,
254            glyph_buffer: Vec::new(),
255        };
256
257        // Clear any caret color from previous display list constructions.
258        builder.paint_info.caret_property_binding = None;
259
260        builder.add_all_spatial_nodes();
261
262        for clip in stacking_context_tree.clip_store.0.iter() {
263            builder.add_clip_to_display_list(clip);
264        }
265
266        // Add a single hit test that covers the entire viewport, so that WebRender knows
267        // which pipeline it hits when doing hit testing.
268        let pipeline_id = builder.paint_info.pipeline_id;
269        let viewport_size = builder.paint_info.viewport_details.size;
270        let viewport_rect = LayoutRect::from_size(viewport_size.cast_unit());
271        builder.wr().push_hit_test(
272            viewport_rect,
273            ClipChainId::INVALID,
274            SpatialId::root_reference_frame(pipeline_id),
275            PrimitiveFlags::default(),
276            (0, 0), /* tag */
277        );
278
279        PaintTraversal::traverse(&stacking_context_tree.root_stacking_context, &mut builder);
280        builder.paint_dom_inspector_highlight();
281
282        webrender_display_list_builder.end().1
283    }
284
285    fn wr(&mut self) -> &mut wr::DisplayListBuilder {
286        self.webrender_display_list_builder
287    }
288
289    fn pipeline_id(&self) -> wr::PipelineId {
290        self.paint_info.pipeline_id
291    }
292
293    fn mark_is_paintable(&mut self) {
294        self.paint_timing_handler.mark_document_is_paintable();
295    }
296
297    fn mark_is_contentful(&mut self) {
298        self.paint_timing_handler.mark_document_is_contentful();
299    }
300
301    fn spatial_id(&self, id: ScrollTreeNodeId) -> SpatialId {
302        self.paint_info.scroll_tree.webrender_id(id)
303    }
304
305    fn clip_chain_id(&self, id: ClipId) -> ClipChainId {
306        match id {
307            ClipId::INVALID => ClipChainId::INVALID,
308            _ => *self
309                .clip_map
310                .get(id.0)
311                .expect("Should never try to get clip before adding it to WebRender display list"),
312        }
313    }
314
315    pub(crate) fn add_all_spatial_nodes(&mut self) {
316        // A count of the number of SpatialTree nodes pushed to the WebRender display
317        // list. This is merely to ensure that the currently-unused SpatialTreeItemKey
318        // produced for every SpatialTree node is unique.
319        let mut scroll_tree = std::mem::take(&mut self.paint_info.scroll_tree);
320        let mut mapping = Vec::with_capacity(scroll_tree.nodes.len());
321
322        mapping.push(SpatialId::root_reference_frame(self.pipeline_id()));
323        mapping.push(SpatialId::root_scroll_node(self.pipeline_id()));
324
325        for node in scroll_tree.nodes.iter().skip(2) {
326            let parent_scroll_node_id = node
327                .parent
328                .expect("Should have already added root reference frame");
329            let parent_spatial_node_id = mapping
330                .get(parent_scroll_node_id.index)
331                .expect("Should add spatial nodes to display list in order");
332
333            mapping.push(match &node.info {
334                SpatialTreeNodeInfo::ReferenceFrame(info) => {
335                    let spatial_id = self.wr().push_reference_frame(
336                        info.origin,
337                        *parent_spatial_node_id,
338                        info.transform_style,
339                        PropertyBinding::Value(*info.transform.to_transform()),
340                        info.kind,
341                    );
342                    self.wr().pop_reference_frame();
343                    spatial_id
344                },
345                SpatialTreeNodeInfo::Scroll(info) => {
346                    self.wr().define_scroll_frame(
347                        *parent_spatial_node_id,
348                        info.external_id,
349                        info.content_rect,
350                        info.clip_rect,
351                        LayoutVector2D::zero(), /* external_scroll_offset */
352                        0,                      /* scroll_offset_generation */
353                        wr::HasScrollLinkedEffect::No,
354                    )
355                },
356                SpatialTreeNodeInfo::Sticky(info) => {
357                    self.wr().define_sticky_frame(
358                        *parent_spatial_node_id,
359                        info.frame_rect,
360                        info.margins,
361                        info.vertical_offset_bounds,
362                        info.horizontal_offset_bounds,
363                        LayoutVector2D::zero(), /* previously_applied_offset */
364                        None,                   /* transform */
365                    )
366                },
367            });
368        }
369
370        scroll_tree.update_mapping(mapping);
371        self.paint_info.scroll_tree = scroll_tree;
372    }
373
374    /// Add the given [`Clip`] to the WebRender display list and create a mapping from
375    /// its [`ClipId`] to a WebRender [`ClipChainId`]. This happens:
376    ///  - When WebRender display list construction starts: All clips created during the
377    ///    `StackingContextTree` construction are added in one batch. These clips are used
378    ///    for things such as `overflow: scroll` elements.
379    ///  - When a clip is added during WebRender display list construction for individual
380    ///    items. In that case, this is called by [`Self::maybe_create_clip`].
381    pub(crate) fn add_clip_to_display_list(&mut self, clip: &Clip) -> ClipChainId {
382        assert_eq!(
383            clip.id.0,
384            self.clip_map.len(),
385            "Clips should be added in order"
386        );
387
388        let spatial_id = self.spatial_id(clip.parent_scroll_node_id);
389        let new_clip_id = if clip.radii.is_zero() {
390            self.wr().define_clip_rect(spatial_id, clip.rect)
391        } else {
392            self.wr().define_clip_rounded_rect(
393                spatial_id,
394                ComplexClipRegion {
395                    rect: clip.rect,
396                    radii: clip.radii,
397                    mode: ClipMode::Clip,
398                },
399            )
400        };
401
402        // WebRender has two different ways of expressing "no clip." ClipChainId::INVALID should be
403        // used for primitives, but `None` is used for stacking contexts and clip chains. We convert
404        // to the `Option<ClipChainId>` representation here. Just passing Some(ClipChainId::INVALID)
405        // leads to a crash.
406        let parent_clip_chain_id = match self.clip_chain_id(clip.parent_clip_id) {
407            ClipChainId::INVALID => None,
408            parent => Some(parent),
409        };
410        let clip_chain_id = self
411            .wr()
412            .define_clip_chain(parent_clip_chain_id, [new_clip_id]);
413        self.clip_map.push(clip_chain_id);
414        clip_chain_id
415    }
416
417    /// Add a new clip to the WebRender display list being built. This only happens during
418    /// WebRender display list building and these clips should be added after all clips
419    /// from the `StackingContextTree` have already been processed.
420    fn maybe_create_clip(
421        &mut self,
422        state: &TraversalState,
423        radii: wr::BorderRadius,
424        rect: units::LayoutRect,
425        force_clip_creation: bool,
426    ) -> Option<ClipChainId> {
427        if radii.is_zero() && !force_clip_creation {
428            return None;
429        }
430
431        Some(self.add_clip_to_display_list(&Clip {
432            id: ClipId(self.clip_map.len()),
433            radii,
434            rect,
435            parent_scroll_node_id: state.spatial_id,
436            parent_clip_id: state.clip_id,
437        }))
438    }
439
440    fn push_webrender_stacking_context_for_transform_if_necessary(
441        &mut self,
442        stacking_context: &StackingContext,
443    ) -> bool {
444        let StackingContextFragments::Fragment(fragment) = &stacking_context.fragment else {
445            return false;
446        };
447
448        let style = fragment.style();
449        let transform_style = style
450            .used_transform_style(fragment.base.flags)
451            .to_webrender();
452
453        if !style.has_effective_transform_or_perspective(FragmentFlags::empty()) &&
454            (transform_style == TransformStyle::Flat &&
455                !stacking_context.participates_in_a_3d_rendering_context)
456        {
457            return false;
458        }
459
460        // WebRender has two different ways of expressing "no clip." ClipChainId::INVALID
461        // should be used for primitives, but `None` is used for stacking contexts and
462        // clip chains. We convert to the `Option<ClipChainId>` representation here. Just
463        // passing Some(ClipChainId::INVALID) causes a panic.
464        let clip_chain_id = match stacking_context.clip_id {
465            ClipId::INVALID => None,
466            clip_id => Some(self.clip_chain_id(clip_id)),
467        };
468        let spatial_id = self.spatial_id(stacking_context.scroll_tree_node_id);
469
470        self.wr().push_stacking_context(
471            spatial_id,
472            style.webrender_primitive_flags(),
473            clip_chain_id,
474            transform_style,
475            MixBlendMode::Normal,
476            &[], // filters
477            &[], // filter_datas
478            wr::RasterSpace::Screen,
479            StackingContextFlags::empty(),
480            None, // snapshot
481        );
482        true
483    }
484
485    fn push_webrender_stacking_context_if_necessary(
486        &mut self,
487        stacking_context: &StackingContext,
488    ) -> bool {
489        if stacking_context.context_type == StackingContextType::StackingContainer {
490            return false;
491        }
492
493        let mut is_blend_container = stacking_context.children.iter().any(|child| {
494            child.fragment().is_some_and(|fragment| {
495                fragment.style().get_mix_blend_mode() != &ComputedMixBlendMode::Normal
496            })
497        });
498
499        let mix_blend_mode;
500        let mut filters: Vec<_>;
501        let mut stacking_context_flags = StackingContextFlags::empty();
502        match &stacking_context.fragment {
503            StackingContextFragments::Fragment(fragment) => {
504                let style = fragment.style();
505                let effects = style.get_effects();
506
507                mix_blend_mode = effects.mix_blend_mode.to_webrender();
508
509                // Do not create another blend container stacking context started by the root
510                // element, because the root background is painted above of it (at the root
511                // stacking context, which sits above the root fragment).
512                //
513                // TODO: Would it be cleaner to paint the root background at the root fragment
514                // instead of the root stacking context?
515                is_blend_container &= !fragment.base.flags.contains(FragmentFlags::IS_ROOT_ELEMENT);
516
517                // WebRender only uses the stacking context to apply certain effects. If we don't
518                // actually need to create a stacking context, just avoid creating one.
519                if !is_blend_container &&
520                    effects.filter.0.is_empty() &&
521                    effects.backdrop_filter.0.is_empty() &&
522                    effects.opacity == 1.0 &&
523                    effects.mix_blend_mode == ComputedMixBlendMode::Normal &&
524                    style.get_svg().clip_path == ComputedClipPath::None
525                {
526                    return false;
527                }
528
529                // Create the filter pipeline.
530                filters = effects
531                    .filter
532                    .0
533                    .iter()
534                    .map(|filter| FilterToWebRender::to_webrender(filter, &style))
535                    .collect();
536                if effects.opacity != 1.0 {
537                    filters.push(wr::FilterOp::Opacity(
538                        effects.opacity.into(),
539                        effects.opacity,
540                    ));
541                }
542            },
543            // WebRender only needs a stacking context at the root when the root stacking
544            // context itself is a blend container.
545            StackingContextFragments::Root if is_blend_container => {
546                mix_blend_mode = MixBlendMode::Normal;
547                filters = Vec::new();
548            },
549            _ => return false,
550        };
551
552        if is_blend_container {
553            stacking_context_flags.insert(StackingContextFlags::IS_BLEND_CONTAINER);
554        }
555
556        // WebRender has two different ways of expressing "no clip." ClipChainId::INVALID
557        // should be used for primitives, but `None` is used for stacking contexts and
558        // clip chains. We convert to the `Option<ClipChainId>` representation here. Just
559        // passing Some(ClipChainId::INVALID) causes a panic.
560        let clip_chain_id = match stacking_context.clip_id {
561            ClipId::INVALID => None,
562            clip_id => Some(self.clip_chain_id(clip_id)),
563        };
564        let spatial_id = self.spatial_id(stacking_context.scroll_tree_node_id);
565
566        self.wr().push_stacking_context(
567            spatial_id,
568            PrimitiveFlags::default(),
569            clip_chain_id,
570            TransformStyle::Flat,
571            mix_blend_mode,
572            &filters,
573            &[], // filter_datas
574            wr::RasterSpace::Screen,
575            stacking_context_flags,
576            None, // snapshot
577        );
578
579        true
580    }
581
582    fn common_properties(
583        &self,
584        state: &TraversalState,
585        clip_rect: units::LayoutRect,
586        style: &ComputedValues,
587    ) -> wr::CommonItemProperties {
588        // TODO(mrobinson): We should take advantage of this field to pass hit testing
589        // information. This will allow us to avoid creating hit testing display items
590        // for fragments that paint their entire border rectangle.
591        wr::CommonItemProperties {
592            clip_rect,
593            spatial_id: self.spatial_id(state.spatial_id),
594            clip_chain_id: self.clip_chain_id(state.clip_id),
595            flags: style.webrender_primitive_flags(),
596        }
597    }
598
599    /// Draw highlights around the node that is currently hovered in the devtools.
600    fn paint_dom_inspector_highlight(&mut self) {
601        let Some(highlight) = self
602            .inspector_highlight
603            .take()
604            .and_then(|highlight| highlight.state)
605        else {
606            return;
607        };
608
609        const CONTENT_BOX_HIGHLIGHT_COLOR: webrender_api::ColorF = webrender_api::ColorF {
610            r: 0.23,
611            g: 0.7,
612            b: 0.87,
613            a: 0.5,
614        };
615
616        const PADDING_BOX_HIGHLIGHT_COLOR: webrender_api::ColorF = webrender_api::ColorF {
617            r: 0.49,
618            g: 0.3,
619            b: 0.7,
620            a: 0.5,
621        };
622
623        const BORDER_BOX_HIGHLIGHT_COLOR: webrender_api::ColorF = webrender_api::ColorF {
624            r: 0.2,
625            g: 0.2,
626            b: 0.2,
627            a: 0.5,
628        };
629
630        const MARGIN_BOX_HIGHLIGHT_COLOR: webrender_api::ColorF = webrender_api::ColorF {
631            r: 1.,
632            g: 0.93,
633            b: 0.,
634            a: 0.5,
635        };
636
637        // Highlight content box
638        let content_box = highlight.content_box.to_webrender();
639        let properties = wr::CommonItemProperties {
640            clip_rect: content_box,
641            spatial_id: highlight.spatial_id,
642            clip_chain_id: highlight.clip_chain_id,
643            flags: wr::PrimitiveFlags::default(),
644        };
645
646        self.wr()
647            .push_rect(&properties, content_box, CONTENT_BOX_HIGHLIGHT_COLOR);
648
649        // Highlight margin, border and padding
650        if let Some(box_fragment) = highlight.maybe_box_fragment {
651            let mut paint_highlight =
652                |color: webrender_api::ColorF,
653                 fragment_relative_bounds: PhysicalRect<Au>,
654                 widths: webrender_api::units::LayoutSideOffsets| {
655                    if widths.is_zero() {
656                        return;
657                    }
658
659                    let bounds = box_fragment
660                        .offset_by_cumulative_content_offset(
661                            &fragment_relative_bounds,
662                            CumulativeContentRectCalculation::AlreadyDoneWithStackingContextTree,
663                        )
664                        .to_webrender();
665
666                    // We paint each highlighted area as if it was a border for simplicity
667                    let border_style = wr::BorderSide {
668                        color,
669                        style: wr::BorderStyle::Solid,
670                    };
671
672                    let details = wr::BorderDetails::Normal(wr::NormalBorder {
673                        top: border_style,
674                        right: border_style,
675                        bottom: border_style,
676                        left: border_style,
677                        radius: webrender_api::BorderRadius::default(),
678                        do_aa: true,
679                    });
680
681                    let common = wr::CommonItemProperties {
682                        clip_rect: bounds,
683                        spatial_id: highlight.spatial_id,
684                        clip_chain_id: highlight.clip_chain_id,
685                        flags: wr::PrimitiveFlags::default(),
686                    };
687                    self.wr().push_border(&common, bounds, widths, details)
688                };
689
690            paint_highlight(
691                PADDING_BOX_HIGHLIGHT_COLOR,
692                box_fragment.padding_rect(),
693                box_fragment.padding.to_webrender(),
694            );
695            paint_highlight(
696                BORDER_BOX_HIGHLIGHT_COLOR,
697                box_fragment.border_rect(),
698                box_fragment.border.to_webrender(),
699            );
700            paint_highlight(
701                MARGIN_BOX_HIGHLIGHT_COLOR,
702                box_fragment.margin_rect(),
703                box_fragment.margin.to_webrender(),
704            );
705        }
706    }
707
708    #[expect(clippy::too_many_arguments)]
709    fn collect_image_record(
710        &mut self,
711        state: &TraversalState,
712        bounds: LayoutRect,
713        clip_rect: LayoutRect,
714        tag: Option<Tag>,
715        url: Option<ServoUrl>,
716        natural_width: Option<Au>,
717        natural_height: Option<Au>,
718        load_time: Option<CrossProcessInstant>,
719    ) {
720        if !self.largest_contentful_paint_enabled {
721            return;
722        }
723
724        let transform = self
725            .paint_info
726            .scroll_tree
727            .cumulative_node_to_root_transform(state.spatial_id);
728
729        self.paint_timing_handler.append_image_record(
730            tag,
731            bounds,
732            clip_rect,
733            transform,
734            url,
735            natural_width,
736            natural_height,
737            load_time,
738        );
739    }
740
741    /// Accumulate a fragment painted by the element with the given `tag` into the
742    /// Container Timing state of each of the enclosing `container_timing_roots`.
743    #[expect(clippy::too_many_arguments)]
744    fn collect_container_timing_record(
745        &mut self,
746        state: &TraversalState,
747        container_timing_roots: &ContainerTimingRoots,
748        tag: Option<Tag>,
749        bounds: LayoutRect,
750        clip_rect: LayoutRect,
751        natural_width: Option<Au>,
752        natural_height: Option<Au>,
753    ) {
754        if !self.container_timing_enabled {
755            return;
756        }
757        let Some(container_timing_roots) = container_timing_roots else {
758            return;
759        };
760
761        // Like LCP collection, we skip if there's no containing element tag.
762        let Some(tag) = tag else {
763            return;
764        };
765
766        let transform = self
767            .paint_info
768            .scroll_tree
769            .cumulative_node_to_root_transform(state.spatial_id);
770
771        self.paint_timing_handler.update_container_timing(
772            container_timing_roots,
773            tag.node,
774            bounds,
775            clip_rect,
776            transform,
777            natural_width,
778            natural_height,
779        );
780    }
781
782    fn visit_stacking_context_reference_frame_info(
783        &mut self,
784        stacking_context: &StackingContext,
785    ) -> (usize, Option<ScrollTreeNodeId>) {
786        let Some(reference_frame_info) = &stacking_context.reference_frame_info else {
787            return (0, None);
788        };
789
790        // Note: Reference frames always establish a stacking context, so it is fine to check if
791        // this stacking context establishes a reference frame as well. We don't need to check
792        // every fragment.
793        let old_reference_frame_spatial_id = std::mem::replace(
794            &mut self.current_reference_frame_scroll_node_id,
795            stacking_context.scroll_tree_node_id,
796        );
797
798        if reference_frame_info.captured_clip_id == ClipId::INVALID {
799            return (0, Some(old_reference_frame_spatial_id));
800        }
801
802        // Although there is nothing in the display list API that prevents it, WebRender
803        // expects that reference frames that alter the coordinate space of their contents do
804        // not propagate clips to those contents. In order to achieve this, push an extra
805        // stacking context here that only specifies a clip. This stacking context will contain
806        // all of the contents of the reference frame, but because it is added in the parent
807        // spatial node, it has the coordinate space of the reference frame parent. In addition
808        // to this, reference frames reset the base `ClipId` value for descendants to
809        // `ClipId::INVALID` during stacking context tree construction.
810        let clip_chain_id = Some(self.clip_chain_id(reference_frame_info.captured_clip_id));
811        let spatial_id = self.spatial_id(reference_frame_info.parent_spatial_node_id);
812        self.wr().push_stacking_context(
813            spatial_id,
814            PrimitiveFlags::default(),
815            clip_chain_id,
816            webrender_api::TransformStyle::Flat,
817            webrender_api::MixBlendMode::Normal,
818            &[], // filters,
819            &[], // filter_datas
820            wr::RasterSpace::Screen,
821            wr::StackingContextFlags::empty(),
822            None, // snapshot
823        );
824
825        (1, Some(old_reference_frame_spatial_id))
826    }
827}
828
829impl PaintTraversalHandler for DisplayListBuilder<'_> {
830    /// A tuple composed of the number of real WebRender stacking contexts pushed
831    /// and the previous `Self::current_reference_frame_scroll_node_id` value of
832    /// the `DisplayListBuilder` when a stacking context was visited (or `None` if
833    /// the value was unmodified).
834    type StackingContextState = (usize, Option<ScrollTreeNodeId>);
835
836    fn visit_stacking_context(
837        &mut self,
838        stacking_context: &StackingContext,
839    ) -> Self::StackingContextState {
840        let (mut stacking_contexts_pushed, old_reference_frame) =
841            self.visit_stacking_context_reference_frame_info(stacking_context);
842        if self.push_webrender_stacking_context_for_transform_if_necessary(stacking_context) {
843            stacking_contexts_pushed += 1;
844        }
845        if self.push_webrender_stacking_context_if_necessary(stacking_context) {
846            stacking_contexts_pushed += 1;
847        }
848        (stacking_contexts_pushed, old_reference_frame)
849    }
850
851    fn leave_stacking_context(
852        &mut self,
853        _: &TraversalState,
854        stacking_context_state: Self::StackingContextState,
855    ) {
856        let (stacking_contexts_pushed, old_reference_frame) = stacking_context_state;
857        for _ in 0..stacking_contexts_pushed {
858            self.wr().pop_stacking_context();
859        }
860
861        if let Some(old_reference_frame) = old_reference_frame {
862            self.current_reference_frame_scroll_node_id = old_reference_frame;
863        }
864    }
865
866    fn visit_box(&mut self, state: &TraversalState, fragment: &BoxFragmentWithStyle<'_>) {
867        fragment.base.visit_fragment(self);
868
869        if let Some(mut inspector_highlight) = self.inspector_highlight.take() &&
870            fragment.base.tag == Some(inspector_highlight.tag)
871        {
872            inspector_highlight.register_fragment_of_highlighted_dom_node(self, state, fragment);
873            self.inspector_highlight = Some(inspector_highlight);
874        }
875
876        if fragment.style().get_inherited_box().visibility != Visibility::Visible {
877            return;
878        };
879
880        BuilderForBoxFragment::new(fragment, state.origin).build(self, state)
881    }
882
883    fn visit_iframe(&mut self, state: &TraversalState, fragment: &Arc<IFrameFragment>) {
884        fragment.base.visit_fragment(self);
885
886        let style = fragment.style.borrow();
887        if style.get_inherited_box().visibility != Visibility::Visible {
888            return;
889        }
890
891        let rect = fragment.base.rect().translate(state.origin.to_vector());
892        let common = self.common_properties(state, rect.to_webrender(), &style);
893        self.wr().push_iframe(
894            rect.to_webrender(),
895            common.clip_rect,
896            &wr::SpaceAndClipInfo {
897                spatial_id: common.spatial_id,
898                clip_chain_id: common.clip_chain_id,
899            },
900            fragment.pipeline_id.into(),
901            true,
902        );
903        // From <https://www.w3.org/TR/paint-timing/#mark-paint-timing>:
904        // > A parent frame should not be aware of the paint events from its
905        // > child iframes, and vice versa. This means that a frame that
906        // > contains just iframes will have first paint (due to the enclosing
907        // > boxes of the paintable iframes) but no first contentful paint.
908        self.paint_timing_handler
909            .check_if_paintable(rect.to_webrender(), state.accumulated_opacity);
910    }
911
912    fn visit_image(
913        &mut self,
914        state: &TraversalState,
915        containing_block: PhysicalRect<Au>,
916        fragment: &Arc<ImageFragment>,
917    ) {
918        fragment.base.visit_fragment(self);
919
920        let style = fragment.style.borrow();
921        if style.get_inherited_box().visibility != Visibility::Visible {
922            return;
923        }
924
925        let image_rendering = style.get_inherited_box().image_rendering.to_webrender();
926        let rect = fragment
927            .base
928            .rect()
929            .translate(containing_block.origin.to_vector())
930            .to_webrender();
931        let clip = fragment
932            .clip
933            .translate(containing_block.origin.to_vector())
934            .to_webrender();
935        let common = self.common_properties(state, clip, &style);
936
937        if let Some(image_key) = fragment.image_key {
938            self.wr().push_image(
939                &common,
940                rect,
941                image_rendering,
942                wr::AlphaType::PremultipliedAlpha,
943                image_key,
944                wr::ColorF::WHITE,
945            );
946
947            if self
948                .paint_timing_handler
949                .check_if_paintable(rect, state.accumulated_opacity)
950            {
951                // From <https://www.w3.org/TR/paint-timing/#contentful>:
952                // An element target is contentful when one or more of the following apply:
953                // > target is a replaced element representing an available image.
954                // From: <https://html.spec.whatwg.org/multipage/#img-available>
955                // When an image request's state is either partially available or completely available,
956                // the image request is said to be available.
957                // Hence, Skip Broken Images.
958                if !fragment.showing_broken_image_icon {
959                    self.mark_is_contentful();
960
961                    self.collect_image_record(
962                        state,
963                        rect,
964                        common.clip_rect,
965                        fragment.base.tag,
966                        fragment.url.clone(),
967                        fragment.natural_width,
968                        fragment.natural_height,
969                        fragment.load_time,
970                    );
971
972                    self.collect_container_timing_record(
973                        state,
974                        &state.container_timing_roots,
975                        state.containing_element_tag,
976                        rect,
977                        common.clip_rect,
978                        fragment.natural_width,
979                        fragment.natural_height,
980                    );
981                }
982            }
983        }
984
985        if fragment.showing_broken_image_icon {
986            Fragment::build_display_list_for_broken_image_border(self, &containing_block, &common);
987        }
988
989        if fragment.selected.load(Ordering::Relaxed) {
990            // If there is no selected style, just fall back to using the unfocused selection color,
991            // which is strictly better than not drawing a selection highlight.
992            let selected_style = fragment.selected_style.borrow();
993            let mut background_color =
994                if self.frame_focused && !ServoArc::ptr_eq(&*selected_style, &*style) {
995                    selected_style.resolve_color(&selected_style.get_background().background_color)
996                } else {
997                    *UNFOCUSED_SELECTION_COLOR
998                };
999
1000            if !background_color.is_transparent() {
1001                background_color.alpha *= 0.5;
1002                self.wr().push_rect(
1003                    &common,
1004                    containing_block.to_webrender(),
1005                    rgba(background_color),
1006                );
1007            }
1008        }
1009    }
1010
1011    fn visit_text(
1012        &mut self,
1013        state: &TraversalState,
1014        line_box_rect: PhysicalRect<Au>,
1015        fragment: &Arc<TextFragment>,
1016    ) {
1017        fragment.base.visit_fragment(self);
1018
1019        let style = fragment.style();
1020        if style.get_inherited_box().visibility != Visibility::Visible {
1021            return;
1022        }
1023        Fragment::build_display_list_for_text_fragment(fragment, self, state, &line_box_rect);
1024    }
1025
1026    fn visit_positioning(&mut self, _state: &TraversalState, fragment: &Arc<PositioningFragment>) {
1027        fragment.base.visit_fragment(self);
1028    }
1029
1030    /// This is an implementation of step 3 from:
1031    /// <https://drafts.csswg.org/css-position-4/#paint-a-stacking-context>:
1032    ///
1033    /// - See also: <https://drafts.csswg.org/css-backgrounds/#special-backgrounds>.
1034    /// - Note: This is only called for the root `StackingContext`.
1035    fn visit_box_for_root_background(&mut self, state: &TraversalState) {
1036        let Some(fragment) = self.fragment_tree.root_box_fragment() else {
1037            return;
1038        };
1039        let fragment = fragment.with_style();
1040
1041        let source_style = {
1042            // > For documents whose root element is an HTML HTML element or an XHTML html element
1043            // > [HTML]: if the computed value of background-image on the root element is none and its
1044            // > background-color is transparent, user agents must instead propagate the computed
1045            // > values of the background properties from that element’s first HTML BODY or XHTML body
1046            // > child element.
1047            let root_fragment_style = fragment.style();
1048            if root_fragment_style.background_is_transparent() {
1049                let body_fragment = self.fragment_tree.body_fragment();
1050                self.paint_body_background = body_fragment.is_none();
1051                body_fragment
1052                    .map(|body_fragment| body_fragment.style().clone())
1053                    .unwrap_or(fragment.style().clone())
1054            } else {
1055                root_fragment_style.clone()
1056            }
1057        };
1058
1059        // This can happen if the root fragment does not have a `<body>` child (either because it is
1060        // `display: none` or `display: contents`) or if the `<body>`'s background is transparent.
1061        if source_style.background_is_transparent() {
1062            return;
1063        }
1064
1065        // The painting area is theoretically the infinite 2D plane,
1066        // but we need a rectangle with finite coordinates.
1067        //
1068        // If the document is smaller than the viewport (and doesn’t scroll),
1069        // we still want to paint the rest of the viewport.
1070        // If it’s larger, we also want to paint areas reachable after scrolling.
1071        let painting_area = self
1072            .fragment_tree
1073            .initial_containing_block
1074            .union(&self.fragment_tree.scrollable_overflow())
1075            .to_webrender();
1076
1077        let background_color =
1078            source_style.resolve_color(&source_style.get_background().background_color);
1079        if background_color.alpha > 0.0 {
1080            let common = self.common_properties(state, painting_area, &source_style);
1081            let color = rgba(background_color);
1082            self.wr().push_rect(&common, painting_area, color);
1083
1084            // From <https://www.w3.org/TR/paint-timing/#sec-terminology>:
1085            // First paint ... includes non-default background paint and the enclosing box of an iframe.
1086            // The spec is vague. See also: https://github.com/w3c/paint-timing/issues/122
1087            if background_color != self.shell_background_color {
1088                self.mark_is_paintable();
1089            }
1090        }
1091
1092        let fragment_builder = BuilderForBoxFragment::new(
1093            &fragment,
1094            self.fragment_tree.initial_containing_block.origin,
1095        );
1096        let painter = BackgroundPainter {
1097            style: &source_style,
1098            painting_area_override: Some(painting_area),
1099            positioning_area_override: None,
1100        };
1101        fragment_builder.build_background_image(self, state, &painter);
1102    }
1103
1104    fn visit_box_for_outline(&mut self, state: &TraversalState, fragment: &Arc<BoxFragment>) {
1105        let fragment = fragment.with_style();
1106        if fragment.style().get_inherited_box().visibility != Visibility::Visible {
1107            return;
1108        };
1109        BuilderForBoxFragment::new(&fragment, state.origin).build_outline(self, state)
1110    }
1111
1112    fn visit_box_for_collapsed_table_borders(
1113        &mut self,
1114        state: &TraversalState,
1115        fragment: &BoxFragmentWithStyle<'_>,
1116    ) {
1117        if fragment.style().get_inherited_box().visibility != Visibility::Visible {
1118            return;
1119        };
1120        BuilderForBoxFragment::new(fragment, state.origin)
1121            .build_collapsed_table_borders(self, state)
1122    }
1123}
1124
1125impl InspectorHighlight {
1126    fn register_fragment_of_highlighted_dom_node(
1127        &mut self,
1128        builder: &DisplayListBuilder,
1129        traversal_state: &TraversalState,
1130        fragment: &Arc<BoxFragment>,
1131    ) {
1132        let spatial_id = builder.spatial_id(traversal_state.spatial_id);
1133        let clip_chain_id = builder.clip_chain_id(traversal_state.clip_id);
1134        let state = self.state.get_or_insert_with(|| HighlightTraversalState {
1135            content_box: Rect::zero(),
1136            spatial_id,
1137            clip_chain_id,
1138            maybe_box_fragment: Some(fragment.clone()),
1139        });
1140
1141        // We only need to highlight the first `SpatialId`. Typically this will include the bottommost
1142        // fragment for a node, which generally surrounds the entire content.
1143        if spatial_id != state.spatial_id {
1144            return;
1145        }
1146
1147        if clip_chain_id != ClipChainId::INVALID && state.clip_chain_id != ClipChainId::INVALID {
1148            debug_assert_eq!(
1149                clip_chain_id, state.clip_chain_id,
1150                "Fragments of the same node must either have no clip chain or the same one"
1151            );
1152        }
1153
1154        state.maybe_box_fragment = Some(fragment.clone());
1155        state.content_box = state.content_box.union(
1156            &fragment
1157                .base
1158                .rect()
1159                .translate(traversal_state.origin.to_vector()),
1160        );
1161    }
1162}
1163
1164impl Fragment {
1165    fn build_display_list_for_text_fragment(
1166        fragment: &TextFragment,
1167        builder: &mut DisplayListBuilder,
1168        state: &TraversalState,
1169        line_box_rect: &PhysicalRect<Au>,
1170    ) {
1171        // NB: The order of painting text components (CSS Text Decoration Module Level 3) is:
1172        // shadows, underline, overline, text, text-emphasis, and then line-through.
1173        let rect = fragment.base.rect().translate(state.origin.to_vector());
1174        let mut baseline_origin = rect.origin;
1175        baseline_origin.y += fragment.font_metrics.ascent;
1176
1177        let (largest_advance, entirely_white_space) = collect_glyphs(
1178            &mut builder.glyph_buffer,
1179            &fragment.glyphs,
1180            baseline_origin,
1181            fragment.justification_adjustment,
1182        );
1183
1184        if builder.glyph_buffer.is_empty() && !fragment.is_empty_for_text_cursor {
1185            return;
1186        }
1187
1188        let parent_style = fragment.style();
1189        // Gecko gets the text bounding box based on the ink overflow bounds. Since
1190        // we don't need to calculate this yet (as we do not implement `contain:
1191        // paint`), we just need to make sure these boundaries are big enough to
1192        // contain the inked portion of the glyphs. We assume that the descent and
1193        // ascent are big enough and then just expand the advance-based boundaries by
1194        // twice the size of the biggest advance in the advance dimention.
1195        let glyph_bounds = rect
1196            .inflate(largest_advance.scale_by(2.0), Au::zero())
1197            .to_webrender();
1198        let common = builder.common_properties(state, glyph_bounds, &parent_style);
1199
1200        // Shadows. According to CSS-BACKGROUNDS, text shadows render in *reverse* order (front to
1201        // back).
1202        let shadows = &parent_style.get_inherited_text().text_shadow;
1203        for shadow in shadows.0.iter().rev() {
1204            builder.wr().push_shadow(
1205                &wr::SpaceAndClipInfo {
1206                    spatial_id: common.spatial_id,
1207                    clip_chain_id: common.clip_chain_id,
1208                },
1209                wr::Shadow {
1210                    offset: LayoutVector2D::new(shadow.horizontal.px(), shadow.vertical.px()),
1211                    color: rgba(parent_style.resolve_color(&shadow.color)),
1212                    blur_radius: shadow.blur.px(),
1213                },
1214                true, /* should_inflate */
1215            );
1216        }
1217
1218        Self::build_display_list_for_text_selection(fragment, builder, state, line_box_rect);
1219
1220        for decoration in [
1221            TextDecorationLine::UNDERLINE,
1222            TextDecorationLine::SPELLING_ERROR,
1223            TextDecorationLine::GRAMMAR_ERROR,
1224            TextDecorationLine::OVERLINE,
1225        ] {
1226            Self::build_display_list_for_text_decoration_line(
1227                state,
1228                &parent_style,
1229                builder,
1230                rect,
1231                &fragment.font_metrics,
1232                decoration,
1233            );
1234        }
1235
1236        // For glyphs, we use `-webkit-text-fill-color` resolved against `color`, rather than `color` directly.
1237        // See <https://compat.spec.whatwg.org/#the-webkit-text-fill-color>.
1238        let glyph_fill_color =
1239            parent_style.resolve_color(parent_style.get__webkit_text_fill_color());
1240
1241        builder.webrender_display_list_builder.push_text(
1242            &common,
1243            glyph_bounds,
1244            &builder.glyph_buffer,
1245            fragment.font_key,
1246            rgba(glyph_fill_color),
1247            None,
1248        );
1249
1250        if builder
1251            .paint_timing_handler
1252            .check_if_paintable(glyph_bounds, state.accumulated_opacity)
1253        {
1254            // From <https://www.w3.org/TR/paint-timing/#contentful>:
1255            // An element target is contentful when one or more of the following apply:
1256            // > target has a text node child, representing non-empty text, and the node’s
1257            // > used opacity is greater than zero.
1258            if !entirely_white_space && *parent_style.get_opacity() > 0. {
1259                builder.mark_is_contentful();
1260
1261                builder.collect_container_timing_record(
1262                    state,
1263                    &state.container_timing_roots,
1264                    state.containing_element_tag,
1265                    glyph_bounds,
1266                    common.clip_rect,
1267                    None,
1268                    None,
1269                );
1270
1271                // Accumulate this text fragment for LCP by the containing element's tag
1272                if let Some(tag) = state.containing_element_tag &&
1273                    builder.largest_contentful_paint_enabled
1274                {
1275                    let transform = builder
1276                        .paint_info
1277                        .scroll_tree
1278                        .cumulative_node_to_root_transform(state.spatial_id);
1279                    builder.paint_timing_handler.accumulate_text_rect(
1280                        tag,
1281                        rect.to_webrender(),
1282                        transform,
1283                        &parent_style,
1284                    );
1285                }
1286            }
1287        }
1288
1289        Self::build_display_list_for_text_decoration_line(
1290            state,
1291            &parent_style,
1292            builder,
1293            rect,
1294            &fragment.font_metrics,
1295            TextDecorationLine::LINE_THROUGH,
1296        );
1297
1298        if !shadows.0.is_empty() {
1299            builder.wr().pop_all_shadows();
1300        }
1301    }
1302
1303    fn build_display_list_for_text_decoration_line(
1304        state: &TraversalState,
1305        parent_style: &ServoArc<ComputedValues>,
1306        builder: &mut DisplayListBuilder,
1307        rect: PhysicalRect<Au>,
1308        font_metrics: &FontMetrics,
1309        text_decoration_line: TextDecorationLine,
1310    ) {
1311        if state.text_decorations.is_empty() {
1312            return;
1313        }
1314
1315        let font_size = parent_style.get_font().font_size;
1316        let dppx = builder.device_pixel_ratio.get();
1317        let resolve_thickness = |thickness: &TextDecorationThickness| -> Au {
1318            let resolved = match thickness {
1319                TextDecorationThickness::LengthPercentage(length_percentage) => {
1320                    length_percentage.resolve(font_size.computed_size.0).px()
1321                },
1322                TextDecorationThickness::Auto | TextDecorationThickness::FromFont => {
1323                    font_metrics.underline_size.to_f32_px()
1324                },
1325            };
1326
1327            // If zero, return zero.
1328            // Else round down to the nearest physical pixel; floor at 1 physical pixel.
1329            // See: <https://drafts.csswg.org/css-values-4/#snap-as-a-line-width>
1330            if resolved == 0.0 {
1331                Au::zero()
1332            } else {
1333                Au::from_f32_px((resolved * dppx).floor().max(1.0) / dppx)
1334            }
1335        };
1336
1337        for text_decoration in state.text_decorations.iter() {
1338            if !text_decoration.line.contains(text_decoration_line) {
1339                continue;
1340            }
1341
1342            let (color, style, y_offset, height) = match text_decoration_line {
1343                // <https://drafts.csswg.org/css-text-decor-4/#valdef-text-decoration-line-underline>
1344                TextDecorationLine::UNDERLINE => (
1345                    text_decoration.color,
1346                    text_decoration.style,
1347                    font_metrics.ascent - font_metrics.underline_offset +
1348                        text_decoration.underline_offset,
1349                    resolve_thickness(&text_decoration.thickness),
1350                ),
1351                // <https://drafts.csswg.org/css-text-decor-4/#valdef-text-decoration-line-spelling-error>
1352                //
1353                // From <https://drafts.csswg.org/css-text-decor-4/#text-decoration-line-property>
1354                // > When spelling-error or grammar-error apply, the user agent must disregard the other
1355                // > sub-properties of text-decoration, as well any other properties typically affecting
1356                // > the appearance of line decorations (such as text-underline-position, color, stroke,
1357                // > or fill) when rendering these decorations. However, the user agent may take into
1358                // > account the accent-color property.
1359                //
1360                // This is why color and style are ignored here and for grammar errors.
1361                TextDecorationLine::SPELLING_ERROR => (
1362                    AbsoluteColor::srgb_legacy(255, 0, 0, 1.0),
1363                    ComputedTextDecorationStyle::Wavy,
1364                    font_metrics.ascent - font_metrics.underline_offset,
1365                    resolve_thickness(&TextDecorationThickness::Auto),
1366                ),
1367                // <https://drafts.csswg.org/css-text-decor-4/#valdef-text-decoration-line-grammar-error>
1368                TextDecorationLine::GRAMMAR_ERROR => (
1369                    AbsoluteColor::srgb_legacy(0, 128, 0, 1.0),
1370                    ComputedTextDecorationStyle::Wavy,
1371                    font_metrics.ascent - font_metrics.underline_offset,
1372                    resolve_thickness(&TextDecorationThickness::Auto),
1373                ),
1374                // <https://drafts.csswg.org/css-text-decor-4/#valdef-text-decoration-line-line-through>
1375                TextDecorationLine::LINE_THROUGH => (
1376                    text_decoration.color,
1377                    text_decoration.style,
1378                    font_metrics.ascent - font_metrics.strikeout_offset,
1379                    resolve_thickness(&text_decoration.thickness),
1380                ),
1381                // <https://drafts.csswg.org/css-text-decor-4/#valdef-text-decoration-line-overline>
1382                TextDecorationLine::OVERLINE => (
1383                    text_decoration.color,
1384                    text_decoration.style,
1385                    Au::zero(),
1386                    resolve_thickness(&text_decoration.thickness),
1387                ),
1388                _ => unreachable!("Got unexpected text decoration line"),
1389            };
1390
1391            if style == ComputedTextDecorationStyle::None {
1392                continue;
1393            }
1394
1395            let mut rect = rect;
1396            rect.origin.y += y_offset;
1397            rect.size.height = height;
1398
1399            let mut rect = rect.to_webrender();
1400            let wavy_line_thickness = rect.height().ceil();
1401            if style == ComputedTextDecorationStyle::Wavy {
1402                rect = rect.inflate(0.0, wavy_line_thickness);
1403            }
1404
1405            let common_properties = builder.common_properties(state, rect, parent_style);
1406
1407            // In Servo, text decorations can span multiple text fragments. In order to have dots,
1408            // dashes, and wavy line segments match up between multiple fragments, this code extends
1409            // the painting rect for the decoration types for which this matters to the origin. As
1410            // the rectangle starts at the origin, all painted decorations will be in phase. As the
1411            // clipping rectangle is left unchanged, the actual painted region remains the size of
1412            // the original rectangle.
1413            if matches!(
1414                style,
1415                ComputedTextDecorationStyle::Dotted |
1416                    ComputedTextDecorationStyle::Dashed |
1417                    ComputedTextDecorationStyle::Wavy,
1418            ) {
1419                rect.min.x = rect.min.x.min(0.0);
1420            }
1421
1422            builder.wr().push_line(
1423                &common_properties,
1424                &rect,
1425                wavy_line_thickness,
1426                wr::LineOrientation::Horizontal,
1427                &rgba(color),
1428                style.to_webrender(),
1429            );
1430
1431            if style == ComputedTextDecorationStyle::Double {
1432                let half_height = (rect.height() / 2.0).floor().max(1.0);
1433                let y_offset = match text_decoration_line {
1434                    TextDecorationLine::OVERLINE => -rect.height() - half_height,
1435                    _ => rect.height() + half_height,
1436                };
1437                let rect = rect.translate(Vector2D::new(0.0, y_offset));
1438                let common_properties = builder.common_properties(state, rect, parent_style);
1439                builder.wr().push_line(
1440                    &common_properties,
1441                    &rect,
1442                    wavy_line_thickness,
1443                    wr::LineOrientation::Horizontal,
1444                    &rgba(color),
1445                    style.to_webrender(),
1446                );
1447            }
1448        }
1449    }
1450
1451    fn build_display_list_for_broken_image_border(
1452        builder: &mut DisplayListBuilder,
1453        containing_block: &PhysicalRect<Au>,
1454        common: &CommonItemProperties,
1455    ) {
1456        let border_side = BorderSide {
1457            color: ColorF::BLACK,
1458            style: wr::BorderStyle::Inset,
1459        };
1460        builder.wr().push_border(
1461            common,
1462            containing_block.to_webrender(),
1463            LayoutSideOffsets::new_all_same(1.0),
1464            BorderDetails::Normal(NormalBorder {
1465                left: border_side,
1466                right: border_side,
1467                top: border_side,
1468                bottom: border_side,
1469                radius: BorderRadius::zero(),
1470                do_aa: true,
1471            }),
1472        );
1473    }
1474
1475    // TODO: This caret/text selection implementation currently does not account for vertical text
1476    // and RTL text properly.
1477    fn build_display_list_for_text_selection(
1478        fragment: &TextFragment,
1479        builder: &mut DisplayListBuilder<'_>,
1480        state: &TraversalState,
1481        line_box_rect: &PhysicalRect<Au>,
1482    ) {
1483        let run_data = &fragment.run_data;
1484        let Some(selection) = *run_data.selection.borrow() else {
1485            return;
1486        };
1487
1488        // The selection character range is in pre-transformed character offsets, so use the
1489        // OffsetMap contained within `run_data` to convert it to post-transformed character
1490        // offsets. This allows updating this selection directly from the DOM (skipping layout).
1491        let selection_character_range = run_data.map_dom_range_to_transformed_range(selection);
1492
1493        if fragment.character_range_in_dom_node.start > selection_character_range.end ||
1494            fragment.character_range_in_dom_node.end < selection_character_range.start
1495        {
1496            return;
1497        }
1498
1499        // When there is an active selection, the line is empty, and there is a forced linebreak,
1500        // layout will push an empty fragment in order to trigger painting of the cursor on an empty line.
1501        // This code ensure that it is only painted if the cursor is on the starting index of the empty
1502        // fragment.
1503        if fragment.is_empty_for_text_cursor &&
1504            !fragment
1505                .character_range_in_dom_node
1506                .contains(&selection_character_range.start)
1507        {
1508            return;
1509        }
1510
1511        let mut current_character_index = fragment.character_range_in_dom_node.start;
1512        let mut current_advance = Au::zero();
1513        let mut start_advance = None;
1514        let mut end_advance = None;
1515        for glyph_store in fragment.glyphs.iter() {
1516            let glyph_store_character_count = glyph_store.character_count();
1517            if current_character_index + glyph_store_character_count <
1518                selection_character_range.start
1519            {
1520                current_advance += glyph_store.total_advance() +
1521                    (fragment.justification_adjustment *
1522                        glyph_store.total_word_separators() as i32);
1523                current_character_index += glyph_store_character_count;
1524                continue;
1525            }
1526
1527            if current_character_index >= selection_character_range.end {
1528                break;
1529            }
1530
1531            for glyph in glyph_store.glyphs() {
1532                if current_character_index >= selection_character_range.start {
1533                    start_advance = start_advance.or(Some(current_advance));
1534                }
1535
1536                current_character_index += glyph.character_count();
1537                current_advance += glyph.advance();
1538                if glyph.char_is_word_separator() {
1539                    current_advance += fragment.justification_adjustment;
1540                }
1541
1542                if current_character_index <= selection_character_range.end {
1543                    end_advance = Some(current_advance);
1544                }
1545            }
1546        }
1547
1548        let start_x = start_advance.unwrap_or(current_advance);
1549        let end_x = end_advance.unwrap_or(current_advance);
1550
1551        let fragment_rect = fragment.base.rect();
1552        let fragment_origin =
1553            (state.origin + fragment_rect.origin.to_vector()) + Vector2D::new(start_x, Au::zero());
1554
1555        let parent_style = fragment.style();
1556        if !selection_character_range.is_empty() {
1557            let selection_rect = Rect::new(
1558                Point2D::new(fragment_origin.x, line_box_rect.min_y()),
1559                Size2D::new(end_x - start_x, line_box_rect.height()),
1560            )
1561            .to_webrender();
1562
1563            let unfocused_color = *UNFOCUSED_SELECTION_COLOR;
1564            let selected_style = fragment.selected_style();
1565            let selection_color = if builder.frame_focused {
1566                selected_style
1567                    .get_background_color()
1568                    .as_absolute()
1569                    .unwrap_or(&unfocused_color)
1570            } else {
1571                &unfocused_color
1572            };
1573
1574            let selection_common = builder.common_properties(state, selection_rect, &parent_style);
1575            builder
1576                .wr()
1577                .push_rect(&selection_common, selection_rect, rgba(*selection_color));
1578
1579            return;
1580        }
1581
1582        if !fragment.run_data.paints_caret.load(Ordering::Relaxed) {
1583            return;
1584        }
1585
1586        // Never paint a caret when the WebView does not have system focus. This matches
1587        // the behavior of other browsers.
1588        if !builder.frame_focused {
1589            return;
1590        }
1591
1592        let insertion_point_rect = Rect::new(
1593            fragment_origin,
1594            Size2D::new(
1595                INSERTION_POINT_LOGICAL_WIDTH,
1596                fragment.font_metrics.line_gap,
1597            ),
1598        )
1599        .to_webrender();
1600
1601        let caret_color = match parent_style.get_caret_color().0 {
1602            ColorOrAuto::Color(ref caret_color) => parent_style.resolve_color(caret_color),
1603            ColorOrAuto::Auto => *parent_style.get_color(),
1604        };
1605        let insertion_point_common =
1606            builder.common_properties(state, insertion_point_rect, &parent_style);
1607
1608        let caret_color = rgba(caret_color);
1609        let property_binding = if prefs::get().editing_caret_blink_time().is_some() {
1610            // It's okay to always use the same property binding key for this pipeline, as
1611            // there is currently only a single thing that animates in this way (the caret).
1612            // This code should be updated if we ever add more paint-side animations.
1613            let pipeline_id: PipelineId = builder.paint_info.pipeline_id.into();
1614            let property_binding_key = PropertyBindingKey::new(pipeline_id.into());
1615            builder.paint_info.caret_property_binding = Some((property_binding_key, caret_color));
1616            PropertyBinding::Binding(property_binding_key, caret_color)
1617        } else {
1618            PropertyBinding::Value(caret_color)
1619        };
1620
1621        builder.wr().push_rect_with_animation(
1622            &insertion_point_common,
1623            insertion_point_rect,
1624            property_binding,
1625        );
1626    }
1627}
1628
1629struct BuilderForBoxFragment<'a> {
1630    fragment: &'a BoxFragmentWithStyle<'a>,
1631    containing_block_origin: PhysicalPoint<Au>,
1632    border_rect: units::LayoutRect,
1633    margin_rect: OnceCell<units::LayoutRect>,
1634    padding_rect: OnceCell<units::LayoutRect>,
1635    content_rect: OnceCell<units::LayoutRect>,
1636    border_radius: OnceCell<wr::BorderRadius>,
1637    border_edge_clip_chain_id: RefCell<Option<ClipChainId>>,
1638    padding_edge_clip_chain_id: RefCell<Option<ClipChainId>>,
1639    content_edge_clip_chain_id: RefCell<Option<ClipChainId>>,
1640}
1641
1642impl<'a> BuilderForBoxFragment<'a> {
1643    fn new(
1644        fragment: &'a BoxFragmentWithStyle<'a>,
1645        containing_block_origin: PhysicalPoint<Au>,
1646    ) -> Self {
1647        let border_rect = fragment
1648            .border_rect()
1649            .translate(containing_block_origin.to_vector());
1650        Self {
1651            fragment,
1652            containing_block_origin,
1653            border_rect: border_rect.to_webrender(),
1654            border_radius: OnceCell::new(),
1655            margin_rect: OnceCell::new(),
1656            padding_rect: OnceCell::new(),
1657            content_rect: OnceCell::new(),
1658            border_edge_clip_chain_id: RefCell::new(None),
1659            padding_edge_clip_chain_id: RefCell::new(None),
1660            content_edge_clip_chain_id: RefCell::new(None),
1661        }
1662    }
1663
1664    fn border_radius(&self) -> BorderRadius {
1665        *self
1666            .border_radius
1667            .get_or_init(|| self.fragment.border_radius())
1668    }
1669
1670    fn content_rect(&self) -> &units::LayoutRect {
1671        self.content_rect.get_or_init(|| {
1672            self.fragment
1673                .content_rect()
1674                .translate(self.containing_block_origin.to_vector())
1675                .to_webrender()
1676        })
1677    }
1678
1679    fn padding_rect(&self) -> &units::LayoutRect {
1680        self.padding_rect.get_or_init(|| {
1681            self.fragment
1682                .padding_rect()
1683                .translate(self.containing_block_origin.to_vector())
1684                .to_webrender()
1685        })
1686    }
1687
1688    fn margin_rect(&self) -> &units::LayoutRect {
1689        self.margin_rect.get_or_init(|| {
1690            self.fragment
1691                .margin_rect()
1692                .translate(self.containing_block_origin.to_vector())
1693                .to_webrender()
1694        })
1695    }
1696
1697    fn border_edge_clip(
1698        &self,
1699        builder: &mut DisplayListBuilder,
1700        state: &TraversalState,
1701        force_clip_creation: bool,
1702    ) -> Option<ClipChainId> {
1703        if let Some(clip) = *self.border_edge_clip_chain_id.borrow() {
1704            return Some(clip);
1705        }
1706
1707        let maybe_clip = builder.maybe_create_clip(
1708            state,
1709            self.border_radius(),
1710            self.border_rect,
1711            force_clip_creation,
1712        );
1713        *self.border_edge_clip_chain_id.borrow_mut() = maybe_clip;
1714        maybe_clip
1715    }
1716
1717    fn padding_edge_clip(
1718        &self,
1719        builder: &mut DisplayListBuilder,
1720        state: &TraversalState,
1721        force_clip_creation: bool,
1722    ) -> Option<ClipChainId> {
1723        if let Some(clip) = *self.padding_edge_clip_chain_id.borrow() {
1724            return Some(clip);
1725        }
1726
1727        let radii = offset_radii(self.border_radius(), -self.fragment.border.to_webrender());
1728        let maybe_clip =
1729            builder.maybe_create_clip(state, radii, *self.padding_rect(), force_clip_creation);
1730        *self.padding_edge_clip_chain_id.borrow_mut() = maybe_clip;
1731        maybe_clip
1732    }
1733
1734    fn content_edge_clip(
1735        &self,
1736        builder: &mut DisplayListBuilder,
1737        state: &TraversalState,
1738        force_clip_creation: bool,
1739    ) -> Option<ClipChainId> {
1740        if let Some(clip) = *self.content_edge_clip_chain_id.borrow() {
1741            return Some(clip);
1742        }
1743
1744        let radii = offset_radii(
1745            self.border_radius(),
1746            -(self.fragment.border + self.fragment.padding).to_webrender(),
1747        );
1748        let maybe_clip =
1749            builder.maybe_create_clip(state, radii, *self.content_rect(), force_clip_creation);
1750        *self.content_edge_clip_chain_id.borrow_mut() = maybe_clip;
1751        maybe_clip
1752    }
1753
1754    fn build(&mut self, builder: &mut DisplayListBuilder, state: &TraversalState) {
1755        if self
1756            .fragment
1757            .base
1758            .flags
1759            .contains(FragmentFlags::DO_NOT_PAINT)
1760        {
1761            return;
1762        }
1763
1764        self.build_backdrop_filter(builder, state);
1765        self.build_background(builder, state);
1766        self.build_box_shadow(builder, state);
1767        if !self.fragment.is_table_grid_with_collapsed_borders() {
1768            self.build_border(builder, state);
1769        }
1770
1771        let overflow = self
1772            .fragment
1773            .style()
1774            .effective_overflow(self.fragment.base.flags);
1775        let scrolls_via_user_input =
1776            |overflow| matches!(overflow, ComputedOverflow::Scroll | ComputedOverflow::Auto);
1777        if (scrolls_via_user_input(overflow.x) || scrolls_via_user_input(overflow.y)) &&
1778            self.fragment.style().get_inherited_ui().pointer_events !=
1779                style::computed_values::pointer_events::T::None
1780        {
1781            let mut inner_state = state.clone();
1782            inner_state.spatial_id = self
1783                .fragment
1784                .generated_scroll_tree_node_id()
1785                .unwrap_or(state.spatial_id);
1786            inner_state.clip_id = self.fragment.generated_clip_id().unwrap_or(state.clip_id);
1787
1788            self.build_hit_test(
1789                builder,
1790                &inner_state,
1791                self.fragment
1792                    .scrollable_overflow()
1793                    .translate(self.containing_block_origin.to_vector())
1794                    .to_webrender(),
1795            );
1796        }
1797    }
1798
1799    fn build_hit_test(
1800        &self,
1801        builder: &mut DisplayListBuilder,
1802        state: &TraversalState,
1803        rect: LayoutRect,
1804    ) {
1805        let external_scroll_node_id = builder
1806            .paint_info
1807            .external_scroll_id_for_scroll_tree_node(state.spatial_id);
1808
1809        let common = builder.common_properties(state, rect, self.fragment.style());
1810        builder.wr().push_hit_test(
1811            common.clip_rect,
1812            common.clip_chain_id,
1813            common.spatial_id,
1814            common.flags,
1815            (external_scroll_node_id.0, 0), /* tag */
1816        );
1817    }
1818
1819    fn build_background_for_painter(
1820        &mut self,
1821        builder: &mut DisplayListBuilder,
1822        state: &TraversalState,
1823        painter: &BackgroundPainter,
1824    ) {
1825        let b = painter.style.get_background();
1826        let background_color = painter.style.resolve_color(&b.background_color);
1827        if background_color.alpha > 0.0 {
1828            // https://drafts.csswg.org/css-backgrounds/#background-color
1829            // “The background color is clipped according to the background-clip
1830            //  value associated with the bottom-most background image layer.”
1831            let layer_index = b.background_image.0.len() - 1;
1832            let bounds = painter.painting_area(self, builder, layer_index);
1833            let common = painter.common_properties(self, builder, state, layer_index, bounds);
1834            builder
1835                .wr()
1836                .push_rect(&common, bounds, rgba(background_color));
1837
1838            // From <https://www.w3.org/TR/paint-timing/#sec-terminology>:
1839            // First paint ... includes non-default background paint and the enclosing box of an iframe.
1840            // The spec is vague. See also: https://github.com/w3c/paint-timing/issues/122
1841            if background_color != builder.shell_background_color {
1842                builder.mark_is_paintable();
1843            }
1844        }
1845
1846        self.build_background_image(builder, state, painter);
1847    }
1848
1849    fn build_backdrop_filter(&mut self, builder: &mut DisplayListBuilder, state: &TraversalState) {
1850        // https://drafts.fxtf.org/filter-effects-2/#BackdropFilterProperty
1851        // > ... unless the element it applies to is a document root element in
1852        // > the current browsing context.
1853        if self
1854            .fragment
1855            .base
1856            .flags
1857            .contains(FragmentFlags::IS_ROOT_ELEMENT)
1858        {
1859            return;
1860        }
1861
1862        let style = self.fragment.style();
1863        let effects = style.get_effects();
1864        if effects.backdrop_filter.0.is_empty() {
1865            return;
1866        }
1867
1868        let filters: Vec<_> = effects
1869            .backdrop_filter
1870            .0
1871            .iter()
1872            .map(|filter| FilterToWebRender::to_webrender(filter, style))
1873            .collect();
1874
1875        let mut common = builder.common_properties(state, self.border_rect, style);
1876        if let Some(clip_chain_id) = self.border_edge_clip(builder, state, false) {
1877            common.clip_chain_id = clip_chain_id;
1878        }
1879        builder.wr().push_backdrop_filter(&common, &filters, &[]);
1880    }
1881
1882    fn build_background(&mut self, builder: &mut DisplayListBuilder, state: &TraversalState) {
1883        let flags = self.fragment.base.flags;
1884
1885        // The root element's background is painted separately as it might inherit the `<body>`'s
1886        // background.
1887        if flags.intersects(FragmentFlags::IS_ROOT_ELEMENT) {
1888            return;
1889        }
1890        // If the `<body>` background was inherited by the root element, don't paint it again here.
1891        if !builder.paint_body_background &&
1892            flags.intersects(FragmentFlags::IS_BODY_ELEMENT_OF_HTML_ELEMENT_ROOT)
1893        {
1894            return;
1895        }
1896
1897        // If this BoxFragment does not paint a background, do nothing.
1898        if let BackgroundMode::None = self.fragment.background_mode {
1899            return;
1900        }
1901
1902        // Paint all extra backgrounds for this BoxFragment. These are painted first, as that's
1903        // the order that they are expected to be painted for table cells (where this feature
1904        // is used).
1905        if let BackgroundMode::Extra(ref extra_backgrounds) = self.fragment.background_mode {
1906            for extra_background in extra_backgrounds {
1907                let positioning_area = extra_background.rect;
1908                let painter = BackgroundPainter {
1909                    style: &extra_background.style.borrow_mut(),
1910                    painting_area_override: None,
1911                    positioning_area_override: Some(
1912                        positioning_area
1913                            .translate(self.containing_block_origin.to_vector())
1914                            .to_webrender(),
1915                    ),
1916                };
1917                self.build_background_for_painter(builder, state, &painter);
1918            }
1919        }
1920
1921        let painter = BackgroundPainter {
1922            style: self.fragment.style(),
1923            painting_area_override: None,
1924            positioning_area_override: None,
1925        };
1926        self.build_background_for_painter(builder, state, &painter);
1927    }
1928
1929    fn build_background_image(
1930        &self,
1931        builder: &mut DisplayListBuilder,
1932        state: &TraversalState,
1933        painter: &BackgroundPainter,
1934    ) {
1935        let style = painter.style;
1936        let b = style.get_background();
1937        let need_blend_container = b
1938            .background_blend_mode
1939            .0
1940            .iter()
1941            .take(b.background_image.0.len())
1942            .any(|background_blend_mode| background_blend_mode != &BackgroundBlendMode::Normal);
1943
1944        let push_stacking_context = |builder: &mut DisplayListBuilder,
1945                                     blend_mode: BackgroundBlendMode,
1946                                     flags: StackingContextFlags|
1947         -> bool {
1948            let spatial_id = builder.spatial_id(state.spatial_id);
1949            builder.wr().push_stacking_context(
1950                spatial_id,
1951                PrimitiveFlags::default(),
1952                None,
1953                TransformStyle::Flat,
1954                blend_mode.to_webrender(),
1955                &[],
1956                &[],
1957                RasterSpace::Screen,
1958                flags,
1959                None,
1960            );
1961            true
1962        };
1963
1964        if need_blend_container {
1965            push_stacking_context(
1966                builder,
1967                BackgroundBlendMode::Normal,
1968                StackingContextFlags::IS_BLEND_CONTAINER,
1969            );
1970        }
1971
1972        let node = self.fragment.base.tag.map(|tag| tag.node);
1973        // Reverse because the property is top layer first, we want to paint bottom layer first.
1974        for (index, image) in b.background_image.0.iter().enumerate().rev() {
1975            let Ok(resolved_image) = builder.image_resolver.resolve_image(node, image) else {
1976                continue;
1977            };
1978            match resolved_image {
1979                ResolvedImage::Gradient(_) | ResolvedImage::Color(_) => {
1980                    let intrinsic = NaturalSizes::empty();
1981                    let Some(layer) =
1982                        &background::layout_layer(self, painter, builder, state, index, intrinsic)
1983                    else {
1984                        continue;
1985                    };
1986
1987                    let needs_blending = layer.blend_mode != BackgroundBlendMode::Normal;
1988                    if needs_blending {
1989                        push_stacking_context(builder, layer.blend_mode, Default::default());
1990                    }
1991
1992                    match resolved_image {
1993                        ResolvedImage::Gradient(gradient) => {
1994                            match gradient::build(style, gradient, layer.tile_size, builder) {
1995                                WebRenderGradient::Linear(linear_gradient) => {
1996                                    builder.wr().push_gradient(
1997                                        &layer.common,
1998                                        layer.bounds,
1999                                        linear_gradient,
2000                                        layer.tile_size,
2001                                        layer.tile_spacing,
2002                                    )
2003                                },
2004                                WebRenderGradient::Radial(radial_gradient) => {
2005                                    builder.wr().push_radial_gradient(
2006                                        &layer.common,
2007                                        layer.bounds,
2008                                        radial_gradient,
2009                                        layer.tile_size,
2010                                        layer.tile_spacing,
2011                                    )
2012                                },
2013                                WebRenderGradient::Conic(conic_gradient) => {
2014                                    builder.wr().push_conic_gradient(
2015                                        &layer.common,
2016                                        layer.bounds,
2017                                        conic_gradient,
2018                                        layer.tile_size,
2019                                        layer.tile_spacing,
2020                                    )
2021                                },
2022                            }
2023                        },
2024                        ResolvedImage::Color(color) => {
2025                            let color = rgba(style.resolve_color(color));
2026                            builder.wr().push_rect(&layer.common, layer.bounds, color);
2027                        },
2028                        _ => {},
2029                    }
2030
2031                    if needs_blending {
2032                        builder.wr().pop_stacking_context();
2033                    }
2034
2035                    builder
2036                        .paint_timing_handler
2037                        .check_if_paintable(layer.bounds, state.accumulated_opacity);
2038                },
2039                ResolvedImage::Image { image, size, url } => {
2040                    // FIXME: https://drafts.csswg.org/css-images-4/#the-image-resolution
2041                    let dppx = 1.0;
2042                    let intrinsic =
2043                        NaturalSizes::from_width_and_height(size.width / dppx, size.height / dppx);
2044                    let layer =
2045                        background::layout_layer(self, painter, builder, state, index, intrinsic);
2046
2047                    let scale = builder.device_pixel_ratio.get();
2048                    let default_size: DeviceIntSize =
2049                        Size2D::new(size.width * scale, size.height * scale).to_i32();
2050                    let preferred_size = layer.as_ref().map(|layer| {
2051                        Size2D::new(
2052                            layer.tile_size.width * scale,
2053                            layer.tile_size.height * scale,
2054                        )
2055                        .to_i32()
2056                    });
2057
2058                    let Some(image_key) = builder.image_resolver.image_key_from_cached_image(
2059                        &image,
2060                        preferred_size.unwrap_or(default_size),
2061                        node,
2062                    ) else {
2063                        continue;
2064                    };
2065
2066                    if let Some(layer) = layer {
2067                        let needs_blending = layer.blend_mode != BackgroundBlendMode::Normal;
2068                        if needs_blending {
2069                            push_stacking_context(builder, layer.blend_mode, Default::default());
2070                        }
2071
2072                        if layer.repeat {
2073                            builder.wr().push_repeating_image(
2074                                &layer.common,
2075                                layer.bounds,
2076                                layer.tile_size,
2077                                layer.tile_spacing,
2078                                style.get_image_rendering().to_webrender(),
2079                                wr::AlphaType::PremultipliedAlpha,
2080                                image_key,
2081                                wr::ColorF::WHITE,
2082                            )
2083                        } else {
2084                            builder.wr().push_image(
2085                                &layer.common,
2086                                layer.bounds,
2087                                style.get_image_rendering().to_webrender(),
2088                                wr::AlphaType::PremultipliedAlpha,
2089                                image_key,
2090                                wr::ColorF::WHITE,
2091                            )
2092                        }
2093
2094                        if needs_blending {
2095                            builder.wr().pop_stacking_context();
2096                        }
2097
2098                        if builder
2099                            .paint_timing_handler
2100                            .check_if_paintable(layer.bounds, state.accumulated_opacity)
2101                        {
2102                            // From <https://www.w3.org/TR/paint-timing/#sec-terminology>:
2103                            // An element target is contentful when one or more of the following apply:
2104                            // > target has a background-image which is a contentful image, and its used
2105                            // > background-size has non-zero width and height values.
2106                            builder.mark_is_contentful();
2107
2108                            let natural_width = Some(Au::from_f32_px(size.width / dppx));
2109                            let natural_height = Some(Au::from_f32_px(size.height / dppx));
2110                            builder.collect_image_record(
2111                                state,
2112                                layer.bounds,
2113                                layer.common.clip_rect,
2114                                self.fragment.base.tag,
2115                                Some(url),
2116                                natural_width,
2117                                natural_height,
2118                                image.load_time(),
2119                            );
2120
2121                            builder.collect_container_timing_record(
2122                                state,
2123                                &state.container_timing_roots_including(self.fragment),
2124                                self.fragment.base.tag.or(state.containing_element_tag),
2125                                layer.bounds,
2126                                layer.common.clip_rect,
2127                                natural_width,
2128                                natural_height,
2129                            );
2130                        }
2131                    }
2132                },
2133            }
2134        }
2135
2136        if need_blend_container {
2137            builder.wr().pop_stacking_context();
2138        }
2139    }
2140
2141    fn build_border_side(&self, style_color: BorderStyleColor) -> wr::BorderSide {
2142        wr::BorderSide {
2143            color: rgba(style_color.color),
2144            style: match style_color.style {
2145                BorderStyle::None => wr::BorderStyle::None,
2146                BorderStyle::Solid => wr::BorderStyle::Solid,
2147                BorderStyle::Double => wr::BorderStyle::Double,
2148                BorderStyle::Dotted => wr::BorderStyle::Dotted,
2149                BorderStyle::Dashed => wr::BorderStyle::Dashed,
2150                BorderStyle::Hidden => wr::BorderStyle::Hidden,
2151                BorderStyle::Groove => wr::BorderStyle::Groove,
2152                BorderStyle::Ridge => wr::BorderStyle::Ridge,
2153                BorderStyle::Inset => wr::BorderStyle::Inset,
2154                BorderStyle::Outset => wr::BorderStyle::Outset,
2155            },
2156        }
2157    }
2158
2159    fn build_collapsed_table_borders(
2160        &self,
2161        builder: &mut DisplayListBuilder,
2162        state: &TraversalState,
2163    ) {
2164        if self
2165            .fragment
2166            .base
2167            .flags
2168            .contains(FragmentFlags::DO_NOT_PAINT)
2169        {
2170            return;
2171        }
2172
2173        let layout_info = self.fragment.specific_layout_info();
2174        let Some(SpecificLayoutInfo::TableGridWithCollapsedBorders(table_info)) =
2175            layout_info.as_deref()
2176        else {
2177            return;
2178        };
2179        let mut common =
2180            builder.common_properties(state, units::LayoutRect::default(), self.fragment.style());
2181        let radius = wr::BorderRadius::default();
2182        let mut column_sum = Au::zero();
2183        for (x, column_size) in table_info.track_sizes.x.iter().enumerate() {
2184            let mut row_sum = Au::zero();
2185            for (y, row_size) in table_info.track_sizes.y.iter().enumerate() {
2186                let left_border = &table_info.collapsed_borders.x[x][y];
2187                let right_border = &table_info.collapsed_borders.x[x + 1][y];
2188                let top_border = &table_info.collapsed_borders.y[y][x];
2189                let bottom_border = &table_info.collapsed_borders.y[y + 1][x];
2190                let details = wr::BorderDetails::Normal(wr::NormalBorder {
2191                    left: self.build_border_side(left_border.style_color.clone()),
2192                    right: self.build_border_side(right_border.style_color.clone()),
2193                    top: self.build_border_side(top_border.style_color.clone()),
2194                    bottom: self.build_border_side(bottom_border.style_color.clone()),
2195                    radius,
2196                    do_aa: true,
2197                });
2198                let mut border_widths = PhysicalSides::new(
2199                    top_border.width,
2200                    right_border.width,
2201                    bottom_border.width,
2202                    left_border.width,
2203                );
2204                let left_adjustment = if x == 0 {
2205                    -border_widths.left / 2
2206                } else {
2207                    std::mem::take(&mut border_widths.left) / 2
2208                };
2209                let top_adjustment = if y == 0 {
2210                    -border_widths.top / 2
2211                } else {
2212                    std::mem::take(&mut border_widths.top) / 2
2213                };
2214                let origin =
2215                    PhysicalPoint::new(column_sum + left_adjustment, row_sum + top_adjustment);
2216                let size = PhysicalSize::new(
2217                    *column_size - left_adjustment + border_widths.right / 2,
2218                    *row_size - top_adjustment + border_widths.bottom / 2,
2219                );
2220                let border_rect = PhysicalRect::new(origin, size)
2221                    .translate(self.fragment.content_rect().origin.to_vector())
2222                    .translate(self.containing_block_origin.to_vector())
2223                    .to_webrender();
2224                common.clip_rect = border_rect;
2225                builder.wr().push_border(
2226                    &common,
2227                    border_rect,
2228                    border_widths.to_webrender(),
2229                    details,
2230                );
2231                row_sum += *row_size;
2232            }
2233            column_sum += *column_size;
2234        }
2235    }
2236
2237    fn build_border(&mut self, builder: &mut DisplayListBuilder, state: &TraversalState) {
2238        if self.fragment.has_collapsed_borders() {
2239            // Avoid painting borders for tables and table parts in collapsed-borders mode,
2240            // since the resulting collapsed borders are painted on their own in a special way.
2241            return;
2242        }
2243
2244        let style = self.fragment.style();
2245        let border = style.get_border();
2246        let border_widths = self.fragment.border.to_webrender();
2247
2248        if border_widths == SideOffsets2D::zero() {
2249            return;
2250        }
2251
2252        // `border-image` replaces an element's border entirely.
2253        if self.build_border_image(builder, state, border, border_widths) {
2254            return;
2255        }
2256
2257        let style_color = BorderStyleColor::from_style(style);
2258        let details = wr::BorderDetails::Normal(wr::NormalBorder {
2259            top: self.build_border_side(style_color.top),
2260            right: self.build_border_side(style_color.right),
2261            bottom: self.build_border_side(style_color.bottom),
2262            left: self.build_border_side(style_color.left),
2263            radius: self.border_radius(),
2264            do_aa: true,
2265        });
2266        let common = builder.common_properties(state, self.border_rect, style);
2267        builder
2268            .wr()
2269            .push_border(&common, self.border_rect, border_widths, details)
2270    }
2271
2272    /// Add a display item for image borders if necessary.
2273    fn build_border_image(
2274        &self,
2275        builder: &mut DisplayListBuilder,
2276        state: &TraversalState,
2277        border: &Border,
2278        border_widths: SideOffsets2D<f32, LayoutPixel>,
2279    ) -> bool {
2280        let style = self.fragment.style();
2281        let border_style_struct = style.get_border();
2282        let border_image_outset =
2283            resolve_border_image_outset(border_style_struct.border_image_outset, border_widths);
2284        let border_image_area = self.border_rect.to_rect().outer_rect(border_image_outset);
2285        let border_image_size = border_image_area.size;
2286        let border_image_widths = resolve_border_image_width(
2287            &border_style_struct.border_image_width,
2288            border_widths,
2289            border_image_size,
2290        );
2291        let border_image_repeat = &border_style_struct.border_image_repeat;
2292        let border_image_fill = border_style_struct.border_image_slice.fill;
2293        let border_image_slice = &border_style_struct.border_image_slice.offsets;
2294        let common = builder.common_properties(state, border_image_area.to_box2d(), style);
2295
2296        let stops = Vec::new();
2297        let mut width = border_image_size.width;
2298        let mut height = border_image_size.height;
2299        let node = self.fragment.base.tag.map(|tag| tag.node);
2300        let source = match builder
2301            .image_resolver
2302            .resolve_image(node, &border.border_image_source)
2303        {
2304            Err(_) => return false,
2305            Ok(ResolvedImage::Image { image, size, .. }) => {
2306                let scale = builder.device_pixel_ratio.get();
2307                let raster_size = Size2D::new(size.width * scale, size.height * scale).to_i32();
2308                let Some(key) =
2309                    builder
2310                        .image_resolver
2311                        .image_key_from_cached_image(&image, raster_size, node)
2312                else {
2313                    return false;
2314                };
2315
2316                if builder.paint_timing_handler.check_if_paintable(
2317                    Box2D::from_size(size.cast_unit()),
2318                    state.accumulated_opacity,
2319                ) {
2320                    // From <https://www.w3.org/TR/paint-timing/#contentful>:
2321                    // An element target is contentful when one or more of the following apply:
2322                    // > target has a background-image which is a contentful image,
2323                    // > and its used background-size has non-zero width and height values.
2324                    builder.mark_is_contentful();
2325                }
2326
2327                width = size.width;
2328                height = size.height;
2329                let image_rendering = style.get_image_rendering().to_webrender();
2330                NinePatchBorderSource::Image(key, image_rendering)
2331            },
2332            Ok(ResolvedImage::Gradient(gradient)) => {
2333                match gradient::build(style, gradient, border_image_size, builder) {
2334                    WebRenderGradient::Linear(gradient) => {
2335                        NinePatchBorderSource::Gradient(gradient)
2336                    },
2337                    WebRenderGradient::Radial(gradient) => {
2338                        NinePatchBorderSource::RadialGradient(gradient)
2339                    },
2340                    WebRenderGradient::Conic(gradient) => {
2341                        NinePatchBorderSource::ConicGradient(gradient)
2342                    },
2343                }
2344            },
2345            Ok(ResolvedImage::Color(color)) => {
2346                // NinePatchBorderSource doesn't support a lone color, so pretend that
2347                // its a linear gradient.
2348                let color = rgba(style.resolve_color(color));
2349                let gradient = builder.wr().create_gradient(
2350                    Point2D::zero(),
2351                    Point2D::zero(),
2352                    vec![
2353                        wr::GradientStop { offset: 0.0, color },
2354                        wr::GradientStop { offset: 1.0, color },
2355                    ],
2356                    wr::ExtendMode::Clamp,
2357                );
2358                NinePatchBorderSource::Gradient(gradient)
2359            },
2360        };
2361
2362        let size = Size2D::new(width as i32, height as i32);
2363
2364        // If the size of the border is zero or the size of the border image is zero, just
2365        // don't render anything. Zero-sized gradients cause problems in WebRender.
2366        if size.is_empty() || border_image_size.is_empty() {
2367            return true;
2368        }
2369
2370        let details = BorderDetails::NinePatch(NinePatchBorder {
2371            source,
2372            width: size.width,
2373            height: size.height,
2374            slice: resolve_border_image_slice(border_image_slice, size),
2375            fill: border_image_fill,
2376            repeat_horizontal: border_image_repeat.0.to_webrender(),
2377            repeat_vertical: border_image_repeat.1.to_webrender(),
2378        });
2379        builder.wr().push_border(
2380            &common,
2381            border_image_area.to_box2d(),
2382            border_image_widths,
2383            details,
2384        );
2385        builder.wr().push_stops(&stops);
2386        true
2387    }
2388
2389    fn build_outline(&self, builder: &mut DisplayListBuilder, state: &TraversalState) {
2390        let style = self.fragment.style();
2391        let outline = style.get_outline();
2392        if outline.outline_style.none_or_hidden() {
2393            return;
2394        }
2395        let width = outline.outline_width.0.to_f32_px();
2396        if width == 0.0 {
2397            return;
2398        }
2399        // <https://drafts.csswg.org/css-ui-3/#outline-offset>
2400        // > Negative values must cause the outline to shrink into the border box. Both
2401        // > the height and the width of outside of the shape drawn by the outline should
2402        // > not become smaller than twice the computed value of the outline-width
2403        // > property, to make sure that an outline can be rendered even with large
2404        // > negative values. User agents should apply this constraint independently in
2405        // > each dimension. If the outline is drawn as multiple disconnected shapes, this
2406        // > constraint applies to each shape separately.
2407        let offset = outline.outline_offset.to_f32_px() + width;
2408        let outline_rect = self.border_rect.inflate(
2409            offset.max(-self.border_rect.width() / 2.0 + width),
2410            offset.max(-self.border_rect.height() / 2.0 + width),
2411        );
2412        let common = builder.common_properties(state, outline_rect, style);
2413        let widths = SideOffsets2D::new_all_same(width);
2414        let border_style = match outline.outline_style {
2415            // TODO: treating 'auto' as 'solid' is allowed by the spec,
2416            // but we should do something better.
2417            OutlineStyle::Auto => BorderStyle::Solid,
2418            OutlineStyle::BorderStyle(s) => s,
2419        };
2420        let side = self.build_border_side(BorderStyleColor {
2421            style: border_style,
2422            color: style.resolve_color(&outline.outline_color),
2423        });
2424        let details = wr::BorderDetails::Normal(wr::NormalBorder {
2425            top: side,
2426            right: side,
2427            bottom: side,
2428            left: side,
2429            radius: offset_radii(self.border_radius(), SideOffsets2D::new_all_same(offset)),
2430            do_aa: true,
2431        });
2432        builder
2433            .wr()
2434            .push_border(&common, outline_rect, widths, details)
2435    }
2436
2437    fn build_box_shadow(&self, builder: &mut DisplayListBuilder, state: &TraversalState) {
2438        let style = self.fragment.style();
2439        let box_shadows = &style.get_effects().box_shadow.0;
2440        if box_shadows.is_empty() {
2441            return;
2442        }
2443
2444        // Note: According to CSS-BACKGROUNDS, box shadows render in *reverse* order (front to back).
2445        for box_shadow in box_shadows.iter().rev() {
2446            let (rect, clip_mode) = if box_shadow.inset {
2447                (*self.padding_rect(), BoxShadowClipMode::Inset)
2448            } else {
2449                (self.border_rect, BoxShadowClipMode::Outset)
2450            };
2451
2452            let offset = LayoutVector2D::new(
2453                box_shadow.base.horizontal.px(),
2454                box_shadow.base.vertical.px(),
2455            );
2456            let spread = box_shadow.spread.px();
2457            let blur = box_shadow.base.blur.px();
2458            let clip_rect = match clip_mode {
2459                // Inset shadows are always inside the rect.
2460                BoxShadowClipMode::Inset => rect,
2461                // Match webrender's box_shadow.rs Gaussian blur inflation.
2462                // (BLUR_SAMPLE_SCALE * blur).ceil(). BLUR_SAMPLE_SCALE is 3.0.
2463                BoxShadowClipMode::Outset => {
2464                    let extra_size_from_blur = (blur * 3.0).ceil();
2465                    rect.translate(offset)
2466                        .inflate(spread, spread)
2467                        .inflate(extra_size_from_blur, extra_size_from_blur)
2468                },
2469            };
2470            let border_radius = match clip_mode {
2471                BoxShadowClipMode::Inset => {
2472                    // The `border-radius` value applies to the border box, but inset shadows
2473                    // use the padding box instead. So we need to shrink the `border-radius`
2474                    // by the border widths.
2475                    offset_radii(self.border_radius(), -self.fragment.border.to_webrender())
2476                },
2477                BoxShadowClipMode::Outset => self.border_radius(),
2478            };
2479            let shadow_radius = offset_radii(
2480                border_radius,
2481                SideOffsets2D::new_all_same(match clip_mode {
2482                    BoxShadowClipMode::Inset => -spread,
2483                    BoxShadowClipMode::Outset => spread,
2484                }),
2485            );
2486            let common = builder.common_properties(state, clip_rect, style);
2487            builder.wr().push_box_shadow(
2488                &common,
2489                rect,
2490                offset,
2491                rgba(style.resolve_color(&box_shadow.base.color)),
2492                blur,
2493                spread,
2494                border_radius,
2495                shadow_radius,
2496                clip_mode,
2497            );
2498        }
2499    }
2500}
2501
2502fn rgba(color: AbsoluteColor) -> wr::ColorF {
2503    let rgba = color.to_color_space(ColorSpace::Srgb);
2504    wr::ColorF::new(
2505        rgba.components.0.clamp(0.0, 1.0),
2506        rgba.components.1.clamp(0.0, 1.0),
2507        rgba.components.2.clamp(0.0, 1.0),
2508        rgba.alpha.clamp(0.0, 1.0),
2509    )
2510}
2511
2512/// Clear `glyphs` and fill it with a [`GlyphInstance`] for every glyph in the given
2513/// `shaped_text_slices`. Return a tuple that contains:
2514///
2515/// - The measure of the largest advance
2516/// - A boolean which is true if the slices only contained white space.
2517fn collect_glyphs(
2518    glyphs: &mut Vec<GlyphInstance>,
2519    shaped_text_slices: &[Arc<ShapedTextSlice>],
2520    mut baseline_origin: PhysicalPoint<Au>,
2521    justification_adjustment: Au,
2522) -> (Au, bool) {
2523    glyphs.clear();
2524    let mut largest_advance = Au::zero();
2525    let mut entirely_white_space = true;
2526
2527    for shaped_text_slice in shaped_text_slices {
2528        entirely_white_space &= shaped_text_slice.all_white_space();
2529        for glyph in shaped_text_slice.glyphs() {
2530            let glyph_offset = glyph.offset().unwrap_or(Point2D::zero());
2531            let point = LayoutPoint::new(
2532                baseline_origin.x.to_f32_px() + glyph_offset.x.to_f32_px(),
2533                baseline_origin.y.to_f32_px() + glyph_offset.y.to_f32_px(),
2534            );
2535            let glyph_instance = GlyphInstance {
2536                index: glyph.id(),
2537                point,
2538            };
2539            glyphs.push(glyph_instance);
2540
2541            if glyph.char_is_word_separator() {
2542                baseline_origin.x += justification_adjustment;
2543            }
2544
2545            let advance = glyph.advance();
2546            baseline_origin.x += advance;
2547            largest_advance.max_assign(advance);
2548        }
2549    }
2550    (largest_advance, entirely_white_space)
2551}
2552
2553/// Given a set of corner radii for a rectangle, this function returns the corresponding radii
2554/// for the [outer rectangle][`Rect::outer_rect`] resulting from expanding the original
2555/// rectangle by the given offsets.
2556fn offset_radii(mut radii: BorderRadius, offsets: LayoutSideOffsets) -> BorderRadius {
2557    let expand = |radius: &mut f32, offset: f32| {
2558        // For negative offsets, just shrink the radius by that amount.
2559        if offset < 0.0 {
2560            *radius = (*radius + offset).max(0.0);
2561            return;
2562        }
2563
2564        // For positive offsets, expand the radius by that amount. But only if the
2565        // radius is positive, in order to preserve sharp corners.
2566        // TODO: this behavior is not continuous, we should use this algorithm instead:
2567        // https://github.com/w3c/csswg-drafts/issues/7103#issuecomment-3357331922
2568        if *radius > 0.0 {
2569            *radius += offset;
2570        }
2571    };
2572    if offsets.left != 0.0 {
2573        expand(&mut radii.top_left.width, offsets.left);
2574        expand(&mut radii.bottom_left.width, offsets.left);
2575    }
2576    if offsets.right != 0.0 {
2577        expand(&mut radii.top_right.width, offsets.right);
2578        expand(&mut radii.bottom_right.width, offsets.right);
2579    }
2580    if offsets.top != 0.0 {
2581        expand(&mut radii.top_left.height, offsets.top);
2582        expand(&mut radii.top_right.height, offsets.top);
2583    }
2584    if offsets.bottom != 0.0 {
2585        expand(&mut radii.bottom_right.height, offsets.bottom);
2586        expand(&mut radii.bottom_left.height, offsets.bottom);
2587    }
2588    radii
2589}
2590
2591/// Resolve the WebRender border-image outset area from the style values.
2592fn resolve_border_image_outset(
2593    outset: BorderImageOutset,
2594    border: SideOffsets2D<f32, LayoutPixel>,
2595) -> SideOffsets2D<f32, LayoutPixel> {
2596    fn image_outset_for_side(outset: NonNegativeLengthOrNumber, border_width: f32) -> f32 {
2597        match outset {
2598            NonNegativeLengthOrNumber::Length(length) => length.px(),
2599            NonNegativeLengthOrNumber::Number(factor) => border_width * factor.0,
2600        }
2601    }
2602
2603    SideOffsets2D::new(
2604        image_outset_for_side(outset.0, border.top),
2605        image_outset_for_side(outset.1, border.right),
2606        image_outset_for_side(outset.2, border.bottom),
2607        image_outset_for_side(outset.3, border.left),
2608    )
2609}
2610
2611/// Resolve the WebRender border-image width from the style values.
2612fn resolve_border_image_width(
2613    width: &BorderImageWidth,
2614    border: SideOffsets2D<f32, LayoutPixel>,
2615    border_area: Size2D<f32, LayoutPixel>,
2616) -> SideOffsets2D<f32, LayoutPixel> {
2617    fn image_width_for_side(
2618        border_image_width: &BorderImageSideWidth,
2619        border_width: f32,
2620        total_length: f32,
2621    ) -> f32 {
2622        match border_image_width {
2623            BorderImageSideWidth::LengthPercentage(v) => {
2624                v.to_used_value(Au::from_f32_px(total_length)).to_f32_px()
2625            },
2626            BorderImageSideWidth::Number(x) => border_width * x.0,
2627            BorderImageSideWidth::Auto => border_width,
2628        }
2629    }
2630
2631    SideOffsets2D::new(
2632        image_width_for_side(&width.0, border.top, border_area.height),
2633        image_width_for_side(&width.1, border.right, border_area.width),
2634        image_width_for_side(&width.2, border.bottom, border_area.height),
2635        image_width_for_side(&width.3, border.left, border_area.width),
2636    )
2637}
2638
2639/// Resolve the WebRender border-image slice from the style values.
2640fn resolve_border_image_slice(
2641    border_image_slice: &StyleRect<NonNegative<NumberOrPercentage>>,
2642    size: Size2D<i32, UnknownUnit>,
2643) -> SideOffsets2D<i32, DevicePixel> {
2644    fn resolve_percentage(value: NonNegative<NumberOrPercentage>, length: i32) -> i32 {
2645        match value.0 {
2646            NumberOrPercentage::Percentage(p) => (p.0 * length as f32).round() as i32,
2647            NumberOrPercentage::Number(n) => n.round() as i32,
2648        }
2649    }
2650
2651    SideOffsets2D::new(
2652        resolve_percentage(border_image_slice.0, size.height),
2653        resolve_percentage(border_image_slice.1, size.width),
2654        resolve_percentage(border_image_slice.2, size.height),
2655        resolve_percentage(border_image_slice.3, size.width),
2656    )
2657}
2658
2659pub(super) fn normalize_radii(rect: &units::LayoutRect, radius: &mut wr::BorderRadius) {
2660    // Normalize radii that add up to > 100%.
2661    // https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
2662    // > Let f = min(L_i/S_i), where i ∈ {top, right, bottom, left},
2663    // > S_i is the sum of the two corresponding radii of the corners on side i,
2664    // > and L_top = L_bottom = the width of the box,
2665    // > and L_left = L_right = the height of the box.
2666    // > If f < 1, then all corner radii are reduced by multiplying them by f.
2667    let f = (rect.width() / (radius.top_left.width + radius.top_right.width))
2668        .min(rect.width() / (radius.bottom_left.width + radius.bottom_right.width))
2669        .min(rect.height() / (radius.top_left.height + radius.bottom_left.height))
2670        .min(rect.height() / (radius.top_right.height + radius.bottom_right.height));
2671    if f < 1.0 {
2672        radius.top_left *= f;
2673        radius.top_right *= f;
2674        radius.bottom_right *= f;
2675        radius.bottom_left *= f;
2676    }
2677}
2678
2679/// <https://drafts.csswg.org/css-shapes-1/#valdef-shape-box-margin-box>
2680/// > The corner radii of this shape are determined by the corresponding
2681/// > border-radius and margin values. If the ratio of border-radius/margin is 1 or more,
2682/// > or margin is negative or zero, then the margin box corner radius is
2683/// > max(border-radius + margin, 0). If the ratio of border-radius/margin is less than 1,
2684/// > and margin is positive, then the margin box corner radius is
2685/// > border-radius + margin * (1 + (ratio-1)^3).
2686pub(super) fn compute_margin_box_radius(
2687    radius: wr::BorderRadius,
2688    layout_rect: LayoutSize,
2689    fragment: &BoxFragment,
2690) -> wr::BorderRadius {
2691    let style = fragment.style();
2692    let margin = style.physical_margin();
2693    let adjust_radius = |radius: f32, margin: f32| -> f32 {
2694        if margin <= 0. || (radius / margin) >= 1. {
2695            (radius + margin).max(0.)
2696        } else {
2697            radius + (margin * (1. + (radius / margin - 1.).powf(3.)))
2698        }
2699    };
2700    let compute_margin_radius = |radius: LayoutSize,
2701                                 layout_rect: LayoutSize,
2702                                 margin: Size2D<LengthPercentageOrAuto, UnknownUnit>|
2703     -> LayoutSize {
2704        let zero = LengthPercentage::zero();
2705        let width = margin
2706            .width
2707            .auto_is(|| &zero)
2708            .to_used_value(Au::from_f32_px(layout_rect.width));
2709        let height = margin
2710            .height
2711            .auto_is(|| &zero)
2712            .to_used_value(Au::from_f32_px(layout_rect.height));
2713        LayoutSize::new(
2714            adjust_radius(radius.width, width.to_f32_px()),
2715            adjust_radius(radius.height, height.to_f32_px()),
2716        )
2717    };
2718    wr::BorderRadius {
2719        top_left: compute_margin_radius(
2720            radius.top_left,
2721            layout_rect,
2722            Size2D::new(margin.left, margin.top),
2723        ),
2724        top_right: compute_margin_radius(
2725            radius.top_right,
2726            layout_rect,
2727            Size2D::new(margin.right, margin.top),
2728        ),
2729        bottom_left: compute_margin_radius(
2730            radius.bottom_left,
2731            layout_rect,
2732            Size2D::new(margin.left, margin.bottom),
2733        ),
2734        bottom_right: compute_margin_radius(
2735            radius.bottom_right,
2736            layout_rect,
2737            Size2D::new(margin.right, margin.bottom),
2738        ),
2739    }
2740}
2741
2742impl BoxFragment {
2743    fn border_radius(&self) -> BorderRadius {
2744        let style = self.style();
2745        let border = style.get_border();
2746        if border.border_top_left_radius.0.is_zero() &&
2747            border.border_top_right_radius.0.is_zero() &&
2748            border.border_bottom_right_radius.0.is_zero() &&
2749            border.border_bottom_left_radius.0.is_zero()
2750        {
2751            return BorderRadius::zero();
2752        }
2753
2754        let border_rect = self.border_rect();
2755        let resolve =
2756            |radius: &LengthPercentage, box_size: Au| radius.to_used_value(box_size).to_f32_px();
2757        let corner = |corner: &style::values::computed::BorderCornerRadius| {
2758            Size2D::new(
2759                resolve(&corner.0.width.0, border_rect.size.width),
2760                resolve(&corner.0.height.0, border_rect.size.height),
2761            )
2762        };
2763
2764        let mut radius = wr::BorderRadius {
2765            top_left: corner(&border.border_top_left_radius),
2766            top_right: corner(&border.border_top_right_radius),
2767            bottom_right: corner(&border.border_bottom_right_radius),
2768            bottom_left: corner(&border.border_bottom_left_radius),
2769        };
2770
2771        normalize_radii(&border_rect.to_webrender(), &mut radius);
2772        radius
2773    }
2774}
2775
2776impl BaseFragment {
2777    fn visit_fragment(&self, builder: &mut DisplayListBuilder) {
2778        match self.status() {
2779            FragmentStatus::New => {
2780                builder.reflow_statistics.rebuilt_fragment_count += 1;
2781                self.set_status(FragmentStatus::Clean)
2782            },
2783            FragmentStatus::StyleChanged => {
2784                builder.reflow_statistics.restyle_fragment_count += 1;
2785                self.set_status(FragmentStatus::Clean)
2786            },
2787            FragmentStatus::OnlyDescendantsChanged => {
2788                builder.reflow_statistics.only_descendants_changed_count += 1;
2789                self.set_status(FragmentStatus::Clean)
2790            },
2791            FragmentStatus::Clean => {},
2792        }
2793    }
2794}