Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / painting / background_painting.lucb

#==============================================================================================
#
#   background_painting - Painting::BackgroundPainting: resolving and painting backgrounds
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Painting/BackgroundPainting.cpp (lines 1-459) and the inline
#       member of BackgroundPainting.h: the background color, then each background layer back to
#       front (clipped to its box and border radii, positioned, repeated, blended), the
#       background-clip: text mask, and resolving the CSS background layers of a box (their
#       positioning areas, sizes and positions) for painting.
#
#       `get_box` takes the C++ `auto const&` paintable box as a PaintPaintableBox*. The
#       `for_each_image_device_rect` lambda of paint_background is a function called with the
#       loop's state; its two callbacks are the two loops that call it.
#
#       Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
#       Copyright (c) 2022, MacDue <macdue@dueutil.tech>
#       Copyright (c) 2026, mikiubo <michele.uboldi@gmail.com>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Helpers ===================================================================================

## Ported from Libraries/LibWeb/Painting/BackgroundPainting.cpp:22 Web::Painting::append_text_clip_paths.
func paint_append_text_clip_paths(context: DisplayListRecordingContext*, paintable: PaintPaintable*):
    let display_list_recorder = display_list_recording_context_display_list_recorder(context)
    var iterator = paint_paintable_inclusive_subtree(paintable).iterator()
    while let sub_paintable = iterator.next():
        # https://drafts.csswg.org/css-backgrounds-4/#valdef-background-clip-text
        if sub_paintable != paintable:
            let layout_node = paint_paintable_layout_node(sub_paintable)
            if not layout_node_is_in_flow(layout_node) and not layout_node_is_floating(layout_node):
                iterator.skip_children()
                continue
        if let paintable_lines = as_if_paint_paintable_with_lines(sub_paintable):
            for fragment in &ak.vector_span(paint_paintable_with_lines_fragments(paintable_lines)):
                if not is_layout_text_node(paint_paintable_fragment_layout_node(fragment)):
                    continue
                let glyph_run = paint_paintable_fragment_glyph_run(fragment) else continue
                let glyphs = web_fonts.glyph_run_glyphs_const(glyph_run)
                if ak.vector_is_empty(&glyphs):
                    continue
                let fragment_absolute_rect = paint_paintable_fragment_absolute_rect(fragment)
                let fragment_absolute_device_rect = display_list_recording_context_enclosing_device_rect(context, fragment_absolute_rect)
                let scale = display_list_recording_context_device_pixels_per_css_pixel(context)
                let baseline_start = gfx.FloatPoint(m_x = gfx.css_pixel_rect_x(&fragment_absolute_rect).to_float(),
                                                    m_y = gfx.css_pixel_rect_y(&fragment_absolute_rect).to_float() + paint_paintable_fragment_baseline(fragment).to_float())
                display_list.display_list_recorder_draw_glyph_run(display_list_recorder, gfx.float_point_mul(&baseline_start, (f32)scale), glyph_run, gfx.color_new_named_color(gfx.ColorNamedColor.black), fragment_absolute_device_rect, scale, paint_paintable_fragment_orientation(fragment))

## Ported from Libraries/LibWeb/Painting/BackgroundPainting.h:32 Web::Painting::BackgroundBox::shrink.
pub func paint_background_box_shrink(this: PaintBackgroundBox*, top: gfx.CssPixels, right: gfx.CssPixels, bottom: gfx.CssPixels, left: gfx.CssPixels):
    gfx.css_pixel_rect_shrink_css_pixels_css_pixels_css_pixels(&this.rect, top, right, bottom, left)
    display_list.border_radii_data_shrink(&this.radii, top, right, bottom, left)

## Ported from Libraries/LibWeb/Painting/BackgroundPainting.cpp:53 Web::Painting::get_box.
func paint_get_box(box_clip: css_data.BackgroundBox, border_box: PaintBackgroundBox, paintable_box: PaintPaintableBox*) -> PaintBackgroundBox:
    var box = border_box
    let box_model = paint_paintable_box_box_model(paintable_box)
    # The C++ switch falls through from the content box to the padding box to the border box.
    if box_clip == css_data.BackgroundBox.content_box:
        let padding = box_model.padding
        paint_background_box_shrink(&box, padding.top, padding.right, padding.bottom, padding.left)
    if box_clip == css_data.BackgroundBox.content_box or box_clip == css_data.BackgroundBox.padding_box:
        let border = box_model.border
        paint_background_box_shrink(&box, border.top, border.right, border.bottom, border.left)
    return box

# mark: Painting ==================================================================================

## The state of the `for_each_image_device_rect` lambda of paint_background.
struct PaintBackgroundImageTiling:
    var image_rect: gfx.CssPixelRect
    var initial_image_x: gfx.CssPixels
    var image_y: gfx.CssPixels
    var css_clip_rect: gfx.CssPixelRect
    var repeat_x: bool
    var repeat_y: bool
    var x_step: gfx.CssPixels
    var y_step: gfx.CssPixels

## The `for_each_image_device_rect` lambda of paint_background: the device rect of every tile of the image that
## the clip rect shows, in rows. Its callbacks: unite each into `fill_rect` (a single-pixel image) or paint the
## image into each (`image`, else none).
func paint_background_for_each_image_device_rect(context: DisplayListRecordingContext*, tiling: PaintBackgroundImageTiling*, fill_rect: gfx.DevicePixelRect*?, image: CssAbstractImageStyleValue*?, image_rendering: css_data.ImageRendering):
    while tiling.image_y.lt(gfx.css_pixel_rect_bottom(&tiling.css_clip_rect)):
        gfx.css_pixel_rect_set_y(&tiling.image_rect, tiling.image_y)

        var image_x = tiling.initial_image_x
        while image_x.lt(gfx.css_pixel_rect_right(&tiling.css_clip_rect)):
            gfx.css_pixel_rect_set_x(&tiling.image_rect, image_x)
            var image_device_rect = display_list_recording_context_rounded_device_rect(context, tiling.image_rect)
            # If the image's dimensions were rounded to zero then they need to be restored to avoid a crash.
            # There's no need to check that !image_rect.is_empty() because empty images are discarded in resolve_background_layers.
            if gfx.device_pixel_rect_width(&image_device_rect) == 0:
                gfx.device_pixel_rect_set_width(&image_device_rect, 1)
            if gfx.device_pixel_rect_height(&image_device_rect) == 0:
                gfx.device_pixel_rect_set_height(&image_device_rect, 1)
            if let united = fill_rect:
                gfx.device_pixel_rect_unite(united, image_device_rect)
            if let painted = image:
                css_abstract_image_style_value_paint(painted, context, image_device_rect, image_rendering)
            if not tiling.repeat_x:
                break
            image_x = image_x.add(tiling.x_step)

        if not tiling.repeat_y:
            break
        tiling.image_y = tiling.image_y.add(tiling.y_step)

## `floor(step * ceil((image_position - clip_position) / step))` of paint_background: how far to move an image rect
## to the first tile position that is still visible.
func paint_background_tile_delta(image_position: gfx.CssPixels, clip_position: gfx.CssPixels, step: gfx.CssPixels) -> gfx.CssPixels:
    let fraction = image_position.sub(clip_position).div(step)
    return gfx.floor(step.mul(gfx.ceil(gfx.css_pixel_fraction_to_css_pixels(&fraction))))

## Ported from Libraries/LibWeb/Painting/BackgroundPainting.cpp:74 Web::Painting::paint_background.
# https://www.w3.org/TR/css-backgrounds-3/#backgrounds
pub func paint_paint_background(context: DisplayListRecordingContext*, paintable_box: PaintPaintableBox*, image_rendering: css_data.ImageRendering, resolved_background: PaintResolvedBackground, border_radii: display_list.BorderRadiiData):
    let display_list_recorder = display_list_recording_context_display_list_recorder(context)

    # https://drafts.fxtf.org/compositing/#background-blend-mode
    # Background layers must not blend with the content that is behind the element,
    # instead they must act as if they are rendered into an isolated group.
    # OPTIMIZATION: It is only required to render the element into an isolated group,
    #               if a background blend mode other than normal are used.
    var paint_into_isolated_group = false
    for layer in ak.vector_span_const(&resolved_background.layers):
        if layer.blend_mode != css_data.MixBlendMode.normal:
            paint_into_isolated_group = true
            break

    let is_root_element = layout_node_is_root_element(paint_paintable_layout_node(paintable_box.paint_paintable()))
    let needs_text_clip = resolved_background.needs_text_clip and not is_root_element

    if needs_text_clip:
        display_list.display_list_recorder_save(display_list_recorder)
        display_list.display_list_recorder_add_clip_rect(display_list_recorder, display_list_recording_context_rounded_device_rect(context, resolved_background.background_rect))
        display_list.display_list_recorder_save_layer(display_list_recorder)

    if paint_into_isolated_group:
        display_list.display_list_recorder_save_layer(display_list_recorder)

    let border_box = PaintBackgroundBox(rect = resolved_background.background_rect, radii = border_radii)

    let color_box = resolved_background.color_box

    if is_root_element:
        display_list.display_list_recorder_fill_rect(display_list_recorder,
                                                     display_list_recording_context_enclosing_device_rect(context, color_box.rect),
                                                     resolved_background.color)
    else:
        display_list.display_list_recorder_fill_rect_with_rounded_corners_corner_radii(display_list_recorder,
                                                                                       display_list_recording_context_rounded_device_rect(context, color_box.rect),
                                                                                       resolved_background.color,
                                                                                       border_radii_data_as_corners(&color_box.radii, display_list_recording_context_device_pixel_converter(context)))

    # struct { DevicePixels top, bottom, left, right } clip_shrink;
    var clip_shrink_top: i32 = 0
    var clip_shrink_bottom: i32 = 0
    var clip_shrink_left: i32 = 0
    var clip_shrink_right: i32 = 0

    let computed_values = &paint_paintable_computed_values(paintable_box.paint_paintable()).computed_values
    let border_top = css_computed_values_border_top(computed_values)
    let border_bottom = css_computed_values_border_bottom(computed_values)
    let border_left = css_computed_values_border_left(computed_values)
    let border_right = css_computed_values_border_right(computed_values)

    if gfx.color_alpha(&border_top.color) == 255 and gfx.color_alpha(&border_bottom.color) == 255 and gfx.color_alpha(&border_left.color) == 255 and gfx.color_alpha(&border_right.color) == 255:
        clip_shrink_top = display_list_recording_context_rounded_device_pixels(context, border_top.width)
        clip_shrink_bottom = display_list_recording_context_rounded_device_pixels(context, border_bottom.width)
        clip_shrink_left = display_list_recording_context_rounded_device_pixels(context, border_left.width)
        clip_shrink_right = display_list_recording_context_rounded_device_pixels(context, border_right.width)

    # Note: Background layers are ordered front-to-back, so we paint them in reverse
    var layer_index = ak.vector_size(&resolved_background.layers)
    while layer_index > 0:
        layer_index -= 1
        let layer = *ak.vector_at_const(&resolved_background.layers, layer_index)
        var state = display_list.display_list_recorder_state_saver_new(display_list_recorder)
        defer display_list.display_list_recorder_state_saver_destroy(&state)

        # Clip
        let clip_box = paint_get_box(layer.clip, border_box, paintable_box)

        let css_clip_rect = clip_box.rect
        var clip_rect = display_list_recording_context_rounded_device_rect(context, css_clip_rect)
        var corner_clip = paint_scoped_corner_radius_clip_new(context, display_list_recording_context_rounded_device_rect(context, css_clip_rect), clip_box.radii, display_list.CornerClip.outside, not is_root_element)
        defer paint_scoped_corner_radius_clip_destruct(&corner_clip)
        if not is_root_element:
            display_list.display_list_recorder_add_clip_rect(display_list_recorder, clip_rect)

            if layer.clip == css_data.BackgroundBox.border_box:
                # Shrink the effective clip rect if to account for the bits the borders will definitely paint over
                # (if they all have alpha == 255).
                gfx.device_pixel_rect_shrink_i32_i32_i32(&clip_rect, clip_shrink_top, clip_shrink_right, clip_shrink_bottom, clip_shrink_left)

        let image = layer.background_image
        var image_rect = layer.image_rect
        var background_positioning_area = layer.background_positioning_area

        match layer.attachment:
            .fixed:
                let root = layout_node_root(paint_paintable_layout_node(paintable_box.paint_paintable()))
                let navigable = layout_node_navigable(root.layout_node()) else trap("the layout root has no navigable")
                gfx.css_pixel_rect_set_location(&background_positioning_area, html_navigable_viewport_scroll_offset(navigable))
            .local_:
                if not paint_paintable_is_viewport_paintable(paintable_box.paint_paintable()):
                    let scroll_offset = paint_paintable_box_scroll_offset(paintable_box)
                    gfx.css_pixel_rect_translate_by_css_pixels_css_pixels(&background_positioning_area, scroll_offset.m_x.neg(), scroll_offset.m_y.neg())
            .scroll:
                _ = 0
            _:
                trap("VERIFY_NOT_REACHED")

        gfx.css_pixel_rect_set_left(&image_rect, gfx.css_pixel_rect_left(&background_positioning_area).add(layer.position_x))
        gfx.css_pixel_rect_set_top(&image_rect, gfx.css_pixel_rect_top(&background_positioning_area).add(layer.position_y))

        # Repetition
        var repeat_x = false
        var repeat_y = false
        var repeat_x_has_gap = false
        var repeat_y_has_gap = false
        var x_step = gfx.CssPixels.from_int(0)
        var y_step = gfx.CssPixels.from_int(0)

        match layer.repeat_x:
            .round:
                x_step = gfx.css_pixel_rect_width(&image_rect)
                repeat_x = true
            .space:
                let whole_images_fraction = gfx.css_pixel_rect_width(&background_positioning_area).div(gfx.css_pixel_rect_width(&image_rect))
                let whole_images = gfx.css_pixel_fraction_to_int(&whole_images_fraction)
                if whole_images <= 1:
                    x_step = gfx.css_pixel_rect_width(&image_rect)
                    repeat_x = false
                else:
                    let space = math.mod(gfx.css_pixel_rect_width(&background_positioning_area).to_double(), gfx.css_pixel_rect_width(&image_rect).to_double())
                    x_step = gfx.css_pixel_rect_width(&image_rect).add(gfx.css_pixels_nearest_value_for_f64(space / (f64)(whole_images - 1)))
                    repeat_x = true
                    repeat_x_has_gap = true
            .repeat:
                x_step = gfx.css_pixel_rect_width(&image_rect)
                repeat_x = true
            .no_repeat:
                repeat_x = false
            _:
                trap("VERIFY_NOT_REACHED")
        # Move image_rect to the left-most tile position that is still visible
        if repeat_x and gfx.css_pixel_rect_x(&image_rect).gt(gfx.css_pixel_rect_x(&css_clip_rect)):
            let x_delta = paint_background_tile_delta(gfx.css_pixel_rect_x(&image_rect), gfx.css_pixel_rect_x(&css_clip_rect), x_step)
            gfx.css_pixel_rect_set_x(&image_rect, gfx.css_pixel_rect_x(&image_rect).sub(x_delta))

        match layer.repeat_y:
            .round:
                y_step = gfx.css_pixel_rect_height(&image_rect)
                repeat_y = true
            .space:
                let whole_images_fraction = gfx.css_pixel_rect_height(&background_positioning_area).div(gfx.css_pixel_rect_height(&image_rect))
                let whole_images = gfx.css_pixel_fraction_to_int(&whole_images_fraction)
                if whole_images <= 1:
                    y_step = gfx.css_pixel_rect_height(&image_rect)
                    repeat_y = false
                else:
                    # fmod of two floats (the float overload).
                    let space = (f32)math.mod((f64)gfx.css_pixel_rect_height(&background_positioning_area).to_float(), (f64)gfx.css_pixel_rect_height(&image_rect).to_float())
                    y_step = gfx.css_pixel_rect_height(&image_rect).add(gfx.css_pixels_nearest_value_for_f64((f64)space / (f64)(whole_images - 1)))
                    repeat_y = true
                    repeat_y_has_gap = true
            .repeat:
                y_step = gfx.css_pixel_rect_height(&image_rect)
                repeat_y = true
            .no_repeat:
                repeat_y = false
            _:
                trap("VERIFY_NOT_REACHED")
        # Move image_rect to the top-most tile position that is still visible
        if repeat_y and gfx.css_pixel_rect_y(&image_rect).gt(gfx.css_pixel_rect_y(&css_clip_rect)):
            let y_delta = paint_background_tile_delta(gfx.css_pixel_rect_y(&image_rect), gfx.css_pixel_rect_y(&css_clip_rect), y_step)
            gfx.css_pixel_rect_set_y(&image_rect, gfx.css_pixel_rect_y(&image_rect).sub(y_delta))

        let initial_image_x = gfx.css_pixel_rect_x(&image_rect)
        let image_y = gfx.css_pixel_rect_y(&image_rect)

        css_abstract_image_style_value_resolve_for_size(image, paint_paintable_box_layout_node_with_style_and_box_metrics(paintable_box).layout_node_with_style(), gfx.css_pixel_rect_size(&image_rect))

        var tiling = PaintBackgroundImageTiling(image_rect = image_rect, initial_image_x = initial_image_x, image_y = image_y, css_clip_rect = css_clip_rect,
                                                repeat_x = repeat_x, repeat_y = repeat_y, x_step = x_step, y_step = y_step)

        let compositing_and_blending_operator = paint_mix_blend_mode_to_compositing_and_blending_operator(layer.blend_mode)
        if compositing_and_blending_operator != gfx.CompositingAndBlendingOperator.normal:
            display_list.display_list_recorder_apply_effects(display_list_recorder, 1.0, compositing_and_blending_operator)

        if let color = css_abstract_image_style_value_color_if_single_pixel_bitmap(image):
            # OPTIMIZATION: If the image is a single pixel, we can just fill the whole area with it.
            #               However, we must first figure out the real coverage area, taking repeat etc into account.

            # FIXME: This could be written in a far more efficient way.
            var fill_rect = gfx.DevicePixelRect()
            paint_background_for_each_image_device_rect(context, &tiling, &fill_rect, none, image_rendering)
            display_list.display_list_recorder_fill_rect(display_list_recorder, fill_rect, color)
        elif css_style_value_is_image(image.css_style_value()) and (repeat_x or repeat_y) and not repeat_x_has_gap and not repeat_y_has_gap:
            # Use a dedicated painting command for repeated images instead of recording a separate command for each instance
            # of a repeated background, so the painter has the opportunity to optimize the painting of repeated images.
            var dest_rect = display_list_recording_context_rounded_device_rect(context, tiling.image_rect)
            # If the image's dimensions were rounded to zero then they need to be restored to avoid a crash.
            # There's no need to check that !image_rect.is_empty() because empty images are discarded in resolve_background_layers.
            if gfx.device_pixel_rect_width(&dest_rect) == 0:
                gfx.device_pixel_rect_set_width(&dest_rect, 1)
            if gfx.device_pixel_rect_height(&dest_rect) == 0:
                gfx.device_pixel_rect_set_height(&dest_rect, 1)

            let bitmap = css_image_style_value_current_frame_bitmap(css_style_value_as_image(image.css_style_value()), dest_rect) else trap("the repeated image has no bitmap")
            let scaling_mode = css_to_gfx_scaling_mode(image_rendering, gfx.immutable_bitmap_size(bitmap), gfx.device_pixel_rect_size(&dest_rect))
            display_list.display_list_recorder_draw_repeated_immutable_bitmap(display_list_recording_context_display_list_recorder(context), dest_rect, clip_rect, bitmap, scaling_mode, repeat_x, repeat_y)
        else:
            paint_background_for_each_image_device_rect(context, &tiling, none, image, image_rendering)

        if compositing_and_blending_operator != gfx.CompositingAndBlendingOperator.normal:
            display_list.display_list_recorder_restore(display_list_recorder)

    if paint_into_isolated_group:
        display_list.display_list_recorder_restore(display_list_recorder)

    if needs_text_clip:
        display_list.display_list_recorder_apply_effects(display_list_recorder, 1.0, gfx.CompositingAndBlendingOperator.destination_in)
        paint_append_text_clip_paths(context, paintable_box.paint_paintable())
        display_list.display_list_recorder_restore(display_list_recorder)
        display_list.display_list_recorder_restore(display_list_recorder)
        display_list.display_list_recorder_restore(display_list_recorder)

# mark: Resolving background layers ===============================================================

## The `round_to_natural` lambda of resolve_background_layers.
func paint_background_round_to_natural(value: gfx.CssPixels) -> gfx.CssPixels:
    let rounded = gfx.round(value)
    if rounded.le(gfx.CssPixels.from_int(0)):
        return gfx.CssPixels.from_int(1)
    return rounded

## `a / b` of two CSSPixels converted back to CSSPixels (a CSSPixelFraction passed where CSSPixels is expected).
func paint_background_divided(a: gfx.CssPixels, b: gfx.CssPixels) -> gfx.CssPixels:
    let fraction = a.div(b)
    return gfx.css_pixel_fraction_to_css_pixels(&fraction)

## Ported from Libraries/LibWeb/Painting/BackgroundPainting.cpp:333 Web::Painting::resolve_background_layers.
pub func paint_resolve_background_layers(layers: ak.Vector[CssBackgroundLayerData], paintable_box: PaintPaintableBox*, background_color: gfx.Color, background_color_clip: css_data.BackgroundBox, border_rect: gfx.CssPixelRect, border_radii: display_list.BorderRadiiData) -> PaintResolvedBackground:
    let border_box = PaintBackgroundBox(rect = border_rect, radii = border_radii)

    let color_box = paint_get_box(background_color_clip, border_box, paintable_box)
    let layout_node = paint_paintable_layout_node(paintable_box.paint_paintable())

    var resolved_layers = ak.Vector[PaintResolvedBackgroundLayerData]()
    for layer in ak.vector_span_const(&layers):
        if not css_abstract_image_style_value_is_paintable(layer.background_image):
            continue

        let background_positioning_area = paint_get_box(layer.origin, border_box, paintable_box).rect
        let image = layer.background_image

        var specified_width: gfx.CssPixels? = none
        var specified_height: gfx.CssPixels? = none
        if layer.size_type == CssBackgroundSize.length_percentage:
            if not css_length_percentage_or_auto_is_auto(&layer.size_x):
                let size_x = css_length_percentage_or_auto_length_percentage(&layer.size_x)
                specified_width = css_percentage_or_to_px(&size_x.percentage_or, layout_node, gfx.css_pixel_rect_width(&background_positioning_area))
            if not css_length_percentage_or_auto_is_auto(&layer.size_y):
                let size_y = css_length_percentage_or_auto_length_percentage(&layer.size_y)
                specified_height = css_percentage_or_to_px(&size_y.percentage_or, layout_node, gfx.css_pixel_rect_height(&background_positioning_area))
        let concrete_image_size = css_run_default_sizing_algorithm(
            specified_width, specified_height,
            CssSizeWithAspectRatio(width = css_abstract_image_style_value_natural_width(image), height = css_abstract_image_style_value_natural_height(image), aspect_ratio = css_abstract_image_style_value_natural_aspect_ratio(image)),
            gfx.css_pixel_rect_size(&background_positioning_area))

        # If the image has no size, there's nothing to paint.
        if gfx.css_pixel_size_is_empty(&concrete_image_size):
            continue

        # Size
        var image_rect = gfx.CssPixelRect()
        match layer.size_type:
            .contain:
                let max_width_ratio = gfx.css_pixel_rect_width(&background_positioning_area).to_double() / concrete_image_size.m_width.to_double()
                let max_height_ratio = gfx.css_pixel_rect_height(&background_positioning_area).to_double() / concrete_image_size.m_height.to_double()
                let ratio = ak.min_f64(max_width_ratio, max_height_ratio)
                gfx.css_pixel_rect_set_size_css_pixels(&image_rect, gfx.css_pixels_scaled_f64(&concrete_image_size.m_width, ratio), gfx.css_pixels_scaled_f64(&concrete_image_size.m_height, ratio))
            .cover:
                let max_width_ratio = gfx.css_pixel_rect_width(&background_positioning_area).to_double() / concrete_image_size.m_width.to_double()
                let max_height_ratio = gfx.css_pixel_rect_height(&background_positioning_area).to_double() / concrete_image_size.m_height.to_double()
                let ratio = ak.max_f64(max_width_ratio, max_height_ratio)
                gfx.css_pixel_rect_set_size_css_pixels(&image_rect, gfx.css_pixels_scaled_f64(&concrete_image_size.m_width, ratio), gfx.css_pixels_scaled_f64(&concrete_image_size.m_height, ratio))
            .length_percentage:
                gfx.css_pixel_rect_set_size_css_pixel_size(&image_rect, concrete_image_size)
            _:
                trap("VERIFY_NOT_REACHED")

        # If after sizing we have a 0px image, we're done. Attempting to paint this would be an infinite loop.
        if gfx.css_pixel_rect_is_empty(&image_rect):
            continue

        # If background-repeat is round for one (or both) dimensions, there is a second step.
        # The UA must scale the image in that dimension (or both dimensions) so that it fits a
        # whole number of times in the background positioning area.
        if layer.repeat_x == css_data.Repetition.round or layer.repeat_y == css_data.Repetition.round:
            # If X ≠ 0 is the width of the image after step one and W is the width of the
            # background positioning area, then the rounded width X' = W / round(W / X)
            # where round() is a function that returns the nearest natural number
            # (integer greater than zero).
            if layer.repeat_x == css_data.Repetition.round:
                let width = gfx.css_pixel_rect_width(&background_positioning_area)
                gfx.css_pixel_rect_set_width(&image_rect, paint_background_divided(width, paint_background_round_to_natural(paint_background_divided(width, gfx.css_pixel_rect_width(&image_rect)))))
            if layer.repeat_y == css_data.Repetition.round:
                let height = gfx.css_pixel_rect_height(&background_positioning_area)
                gfx.css_pixel_rect_set_height(&image_rect, paint_background_divided(height, paint_background_round_to_natural(paint_background_divided(height, gfx.css_pixel_rect_height(&image_rect)))))

            # If background-repeat is round for one dimension only and if background-size is auto
            # for the other dimension, then there is a third step: that other dimension is scaled
            # so that the original aspect ratio is restored.
            if layer.repeat_x != layer.repeat_y:
                if css_length_percentage_or_auto_is_auto(&layer.size_x):
                    gfx.css_pixel_rect_set_width(&image_rect, gfx.css_pixel_rect_height(&image_rect).mul_fraction(concrete_image_size.m_width.div(concrete_image_size.m_height)))
                if css_length_percentage_or_auto_is_auto(&layer.size_y):
                    gfx.css_pixel_rect_set_height(&image_rect, gfx.css_pixel_rect_width(&image_rect).mul_fraction(concrete_image_size.m_height.div(concrete_image_size.m_width)))

        # If after round adjustments we have a 0px image, we're done.
        if gfx.css_pixel_rect_is_empty(&image_rect):
            continue

        let space_x = gfx.css_pixel_rect_width(&background_positioning_area).sub(gfx.css_pixel_rect_width(&image_rect))
        let space_y = gfx.css_pixel_rect_height(&background_positioning_area).sub(gfx.css_pixel_rect_height(&image_rect))

        let position_x = css_percentage_or_to_px(&layer.position_x.percentage_or, layout_node, space_x)
        let position_y = css_percentage_or_to_px(&layer.position_y.percentage_or, layout_node, space_y)

        ak.vector_append_t(&resolved_layers, PaintResolvedBackgroundLayerData(
            background_image = layer.background_image,
            attachment = layer.attachment,
            clip = layer.clip,
            position_x = position_x,
            position_y = position_y,
            background_positioning_area = background_positioning_area,
            image_rect = image_rect,
            repeat_x = layer.repeat_x,
            repeat_y = layer.repeat_y,
            blend_mode = layer.blend_mode))

    return PaintResolvedBackground(color_box = color_box,
                                   layers = resolved_layers,
                                   needs_text_clip = background_color_clip == css_data.BackgroundBox.text,
                                   background_rect = border_rect,
                                   color = background_color)