Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / layout / svg_formatting_context_2.lucb

#==============================================================================================
#
#   svg_formatting_context_2 - Layout::SVGFormattingContext: graphics elements, text, images,
#                              masks, clip paths, patterns and groups
#
#   DESCRIPTION:
#       Port of LibWeb/Layout/SVGFormattingContext.cpp (lines 376-609): the paths of <text>
#       and <textPath> (https://svgwg.org/svg2-draft/text.html#TextAnchoringProperties), the
#       path, bounding box and SVG transforms of a graphics element, the transform of its
#       nearest transformed ancestor, images, masks, clip paths and patterns laid out as
#       viewports in their content units, and the bounding box of a container element
#       (https://svgwg.org/svg2-draft/struct.html#Groups).
#
#       Copyright (c) 2021-2023, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
#       Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
#       Copyright (c) 2023, MacDue <macdue@dueutil.tech>
#       Copyright (c) 2025, Jelle Raaijmakers <jelle@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Text ====================================================================================

## Ported from Libraries/LibWeb/Layout/SVGFormattingContext.cpp:376 Web::Layout::SVGFormattingContext::compute_path_for_text.
func layout_svg_formatting_context_compute_path_for_text(this: LayoutSvgFormattingContext*, text_box: LayoutSvgTextBox*) -> gfx.Path:
    let text_element = layout_svg_text_box_dom_node(text_box)
    # FIXME: Use per-code-point fonts.
    let font = layout_node_first_available_font(text_box.layout_node())
    let text_contents = svg_text_content_element_text_contents(text_element.svg_text_content_element())
    let text_width = web_fonts.font_width(font, ak.utf16_string_base_utf16_view(&text_contents.utf16_string_base))
    var text_offset = this.m_current_text_position

    # https://svgwg.org/svg2-draft/text.html#TextAnchoringProperties
    match svg_text_content_element_text_anchor(text_element.svg_text_content_element()) else SvgTextAnchor.start:
        .start:
            # The rendered characters are aligned such that the start of the resulting rendered text is at the initial
            # current text position.
            _ = text_width
        .middle:
            # The rendered characters are shifted such that the geometric middle of the resulting rendered text
            # (determined from the initial and final current text position before applying the text-anchor property)
            # is at the initial current text position.
            gfx.float_point_translate_by_f32_f32(&text_offset, -text_width / 2.0f32, 0.0f32)
        .end:
            # The rendered characters are shifted such that the end of the resulting rendered text (final current text
            # position before applying the text-anchor property) is at the initial current text position.
            gfx.float_point_translate_by_f32_f32(&text_offset, -text_width, 0.0f32)
        _:
            trap("VERIFY_NOT_REACHED")

    let baseline_metric = layout_resolve_dominant_baseline_metric(&layout_node_computed_values(text_box.layout_node()).computed_values)
    gfx.float_point_translate_by_f32_f32(&text_offset, 0.0f32, layout_dominant_baseline_offset(baseline_metric, web_fonts.font_pixel_metrics(font)))

    var path: gfx.Path
    gfx.path_move_to(&path, text_offset)
    web_fonts.path_text_utf16_view(&path, ak.utf16_string_base_utf16_view(&text_contents.utf16_string_base), font)
    return path

## Ported from Libraries/LibWeb/Layout/SVGFormattingContext.cpp:417 Web::Layout::SVGFormattingContext::compute_path_for_text_path.
func layout_svg_formatting_context_compute_path_for_text_path(this: LayoutSvgFormattingContext*, text_path_box: LayoutSvgTextPathBox*) -> gfx.Path:
    let text_path_element = layout_svg_text_path_box_dom_node(text_path_box)
    let path_or_shape = svg_text_path_element_path_or_shape(text_path_element) else return gfx.Path()

    # FIXME: Use per-code-point fonts.
    let font = layout_node_first_available_font(text_path_box.layout_node())
    let text_contents = svg_text_content_element_text_contents(text_path_element.svg_text_content_element())

    let shape_path = svg_geometry_element_get_path(path_or_shape, this.m_viewport_size)
    return web_fonts.path_place_text_along_utf16_view(&shape_path, ak.utf16_string_base_utf16_view(&text_contents.utf16_string_base), font)

# mark: Graphics elements =======================================================================

## Ported from Libraries/LibWeb/Layout/SVGFormattingContext.cpp:432 Web::Layout::SVGFormattingContext::layout_path_like_element.
func layout_svg_formatting_context_layout_path_like_element(this: LayoutSvgFormattingContext*, graphics_box: LayoutSvgGraphicsBox*):
    let graphics_box_state = layout_state_get_mutable(layout_svg_formatting_context_state(this), graphics_box.layout_node_with_style())
    let computed_svg_transforms = layout_state_used_values_computed_svg_transforms(graphics_box_state) else trap("VERIFY: the graphics box has computed SVG transforms")

    var to_css_pixels_transform = layout_identity_affine_transform()
    gfx.affine_transform_multiply(&to_css_pixels_transform, this.m_current_viewbox_transform)
    gfx.affine_transform_multiply(&to_css_pixels_transform, paint_svg_graphics_paintable_computed_transforms_svg_transform(&computed_svg_transforms))

    var path: gfx.Path
    if is_layout_svg_geometry_box(graphics_box):
        let geometry_box = (LayoutSvgGeometryBox*)graphics_box
        path = svg_geometry_element_get_path(layout_svg_geometry_box_dom_node(geometry_box), this.m_viewport_size)
    elif let text_box = as_if_layout_svg_text_box(graphics_box):
        # FIXME: Text offsets must be calculated per character. This only applies the first character's offset.
        let text_positioning = svg_text_positioning_element_text_positioning(layout_svg_text_box_dom_node(text_box))
        svg_text_positioning_apply_to_text_position(&text_positioning, text_box.layout_node(), this.m_viewport_size, &this.m_current_text_position, 0)

        path = layout_svg_formatting_context_compute_path_for_text(this, text_box)

        # <text> and <tspan> elements can contain more text elements.
        for child in layout_node_children(text_box.layout_node()):
            let child_graphics_box = as_if_layout_svg_graphics_box(child) else continue
            if is_layout_svg_text_box(child) or is_layout_svg_text_path_box(child):
                layout_svg_formatting_context_layout_graphics_element(this, child_graphics_box)
    elif let text_path_box = as_if_layout_svg_text_path_box(graphics_box):
        # FIXME: Support <tspan> in <textPath>.
        path = layout_svg_formatting_context_compute_path_for_text_path(this, text_path_box)

    let path_bounding_box = gfx.path_bounding_box(&path)
    this.m_current_text_position = gfx.float_rect_bottom_right(&path_bounding_box)
    let mapped_bounding_box = gfx.affine_transform_map_f32_float_rect(&to_css_pixels_transform, path_bounding_box)
    var transformed_bounding_box = gfx.float_rect_to_type_css_pixels(&mapped_bounding_box)
    # Stroke increases the path's size by stroke_width/2 per side.
    let stroke_width = gfx.css_pixels_nearest_value_for_f32(svg_graphics_element_visible_stroke_width(layout_svg_graphics_box_dom_node(graphics_box)) * gfx.affine_transform_x_scale(&this.m_current_viewbox_transform))
    gfx.css_pixel_rect_inflate_css_pixels_css_pixels(&transformed_bounding_box, stroke_width, stroke_width)
    layout_state_used_values_set_content_offset(graphics_box_state, gfx.css_pixel_rect_top_left(&transformed_bounding_box))
    layout_state_used_values_set_content_width(graphics_box_state, gfx.css_pixel_rect_width(&transformed_bounding_box))
    layout_state_used_values_set_content_height(graphics_box_state, gfx.css_pixel_rect_height(&transformed_bounding_box))
    layout_state_used_values_set_has_definite_width(graphics_box_state, true)
    layout_state_used_values_set_has_definite_height(graphics_box_state, true)
    layout_state_used_values_set_computed_svg_path(graphics_box_state, path)

## Ported from Libraries/LibWeb/Layout/SVGFormattingContext.cpp:477 Web::Layout::SVGFormattingContext::get_parent_svg_transform.
func layout_svg_formatting_context_get_parent_svg_transform(this: LayoutSvgFormattingContext*, box: LayoutSvgGraphicsBox*) -> gfx.AffineTransform:
    # Mask/clip boxes are transform boundaries — the target's transform is applied separately at paint time.
    var ancestor = tree_node_parent(box.layout_node())
    while let at = ancestor:
        if is_layout_svg_mask_box(at) or is_layout_svg_clip_box(at) or is_layout_svg_pattern_box(at):
            return layout_identity_affine_transform()
        if let svg_graphics_ancestor = as_if_layout_svg_graphics_box(at):
            let ancestor_state = layout_state_get(layout_svg_formatting_context_state(this), svg_graphics_ancestor.layout_node_with_style())
            if let computed_svg_transforms = layout_state_used_values_computed_svg_transforms(ancestor_state):
                return paint_svg_graphics_paintable_computed_transforms_svg_transform(&computed_svg_transforms)
        ancestor = tree_node_parent(at)
    return layout_identity_affine_transform()

## Ported from Libraries/LibWeb/Layout/SVGFormattingContext.cpp:492 Web::Layout::SVGFormattingContext::layout_graphics_element.
func layout_svg_formatting_context_layout_graphics_element(this: LayoutSvgFormattingContext*, graphics_box: LayoutSvgGraphicsBox*):
    let graphics_box_state = layout_state_get_mutable(layout_svg_formatting_context_state(this), graphics_box.layout_node_with_style())
    var svg_transform = layout_svg_formatting_context_get_parent_svg_transform(this, graphics_box)
    gfx.affine_transform_multiply(&svg_transform, svg_graphics_element_element_transform(layout_svg_graphics_box_dom_node(graphics_box)))
    var computed_transforms: PaintSvgGraphicsPaintableComputedTransforms = ---
    paint_svg_graphics_paintable_computed_transforms_construct(&computed_transforms, this.m_current_viewbox_transform, svg_transform)
    layout_state_used_values_set_computed_svg_transforms(graphics_box_state, computed_transforms)

    if layout_is_container_element(graphics_box.layout_node()):
        # https://svgwg.org/svg2-draft/struct.html#Groups
        # 5.2. Grouping: the ‘g’ element
        # The ‘g’ element is a container element for grouping together related graphics elements.
        layout_svg_formatting_context_layout_container_element(this, graphics_box.layout_svg_box())
    elif is_layout_svg_image_box(graphics_box):
        layout_svg_formatting_context_layout_image_element(this, (LayoutSvgImageBox*)graphics_box)
    else:
        # Assume this is a path-like element.
        layout_svg_formatting_context_layout_path_like_element(this, graphics_box)

    if let mask_box = tree_node_first_child_of_type(graphics_box.layout_node(), &layout_svg_mask_box_class):
        layout_svg_formatting_context_layout_mask_or_clip(this, (LayoutSvgBox*)mask_box)

    if let clip_box = tree_node_first_child_of_type(graphics_box.layout_node(), &layout_svg_clip_box_class):
        layout_svg_formatting_context_layout_mask_or_clip(this, (LayoutSvgBox*)clip_box)

    for child in layout_node_children(graphics_box.layout_node()):
        if is_layout_svg_pattern_box(child):
            layout_svg_formatting_context_layout_mask_or_clip(this, (LayoutSvgBox*)child)

## Ported from Libraries/LibWeb/Layout/SVGFormattingContext.cpp:523 Web::Layout::SVGFormattingContext::layout_image_element.
func layout_svg_formatting_context_layout_image_element(this: LayoutSvgFormattingContext*, image_box: LayoutSvgImageBox*):
    let box_state = layout_state_get_mutable(layout_svg_formatting_context_state(this), image_box.layout_node_with_style())
    let computed_svg_transforms = layout_state_used_values_computed_svg_transforms(box_state) else trap("VERIFY: the image box has computed SVG transforms")

    var to_css_pixels_transform = layout_identity_affine_transform()
    gfx.affine_transform_multiply(&to_css_pixels_transform, this.m_current_viewbox_transform)
    gfx.affine_transform_multiply(&to_css_pixels_transform, paint_svg_graphics_paintable_computed_transforms_svg_transform(&computed_svg_transforms))
    let mapped_bounding_box = gfx.affine_transform_map_f32_float_rect(&to_css_pixels_transform, svg_image_element_bounding_box(layout_svg_image_box_dom_node(image_box)))
    let bounding_box = gfx.float_rect_to_type_css_pixels(&mapped_bounding_box)

    layout_state_used_values_set_content_x(box_state, gfx.css_pixel_rect_x(&bounding_box))
    layout_state_used_values_set_content_y(box_state, gfx.css_pixel_rect_y(&bounding_box))
    layout_state_used_values_set_content_width(box_state, gfx.css_pixel_rect_width(&bounding_box))
    layout_state_used_values_set_content_height(box_state, gfx.css_pixel_rect_height(&bounding_box))
    layout_state_used_values_set_has_definite_width(box_state, true)
    layout_state_used_values_set_has_definite_height(box_state, true)

# mark: Masks, clip paths and patterns ==========================================================

## Ported from Libraries/LibWeb/Layout/SVGFormattingContext.cpp:541 Web::Layout::SVGFormattingContext::layout_mask_or_clip.
func layout_svg_formatting_context_layout_mask_or_clip(this: LayoutSvgFormattingContext*, mask_or_clip: LayoutSvgBox*):
    var content_units = SvgUnits.object_bounding_box
    if is_layout_svg_mask_box(mask_or_clip):
        content_units = svg_mask_element_mask_content_units(layout_svg_mask_box_dom_node((LayoutSvgMaskBox*)mask_or_clip))
    elif is_layout_svg_clip_box(mask_or_clip):
        content_units = svg_clip_path_element_clip_path_units(layout_svg_clip_box_dom_node((LayoutSvgClipBox*)mask_or_clip))
    elif is_layout_svg_pattern_box(mask_or_clip):
        content_units = svg_pattern_element_pattern_content_units(layout_svg_pattern_box_dom_node((LayoutSvgPatternBox*)mask_or_clip))
    else:
        trap("VERIFY_NOT_REACHED")
    # FIXME: Somehow limit <clipPath> contents to: shape elements, <text>, and <use>.
    let state = layout_svg_formatting_context_state(this)
    let layout_state = layout_state_get_mutable(state, mask_or_clip.layout_node_with_style())
    var parent_viewbox_transform = this.m_current_viewbox_transform

    let pattern_box = as_if_layout_svg_pattern_box(mask_or_clip)
    var pattern_has_view_box = false
    if let box = pattern_box:
        pattern_has_view_box = svg_fit_to_view_box_view_box(&layout_svg_pattern_box_dom_node(box).svg_fit_to_view_box) != none
    if pattern_has_view_box:
        let pattern = layout_svg_pattern_box_dom_node(pattern_box else trap("unreachable"))
        if svg_pattern_element_pattern_units(pattern) == SvgUnits.user_space_on_use:
            let pattern_width = svg_pattern_element_pattern_width(pattern)
            let pattern_height = svg_pattern_element_pattern_height(pattern)
            layout_state_used_values_set_content_width(layout_state, gfx.css_pixels_nearest_value_for_f32(svg_number_percentage_resolve_relative_to(&pattern_width, this.m_viewport_size.m_width.to_float())))
            layout_state_used_values_set_content_height(layout_state, gfx.css_pixels_nearest_value_for_f32(svg_number_percentage_resolve_relative_to(&pattern_height, this.m_viewport_size.m_height.to_float())))
        else:
            let parent = tree_node_parent(mask_or_clip.layout_node()) else trap("VERIFY: a pattern box has a parent")
            let parent_node_state = layout_state_get(state, (LayoutNodeWithStyle*)parent)
            let pattern_width = svg_pattern_element_pattern_width(pattern)
            let pattern_height = svg_pattern_element_pattern_height(pattern)
            layout_state_used_values_set_content_width(layout_state, gfx.css_pixels_nearest_value_for_f64(f64(svg_number_percentage_value(&pattern_width)) * layout_state_used_values_content_width(parent_node_state).to_double()))
            layout_state_used_values_set_content_height(layout_state, gfx.css_pixels_nearest_value_for_f64(f64(svg_number_percentage_value(&pattern_height)) * layout_state_used_values_content_height(parent_node_state).to_double()))
            parent_viewbox_transform = layout_identity_affine_transform()
            gfx.affine_transform_translate_float_point(&parent_viewbox_transform, gfx.css_pixel_point_to_type_f32(&parent_node_state.offset))
    elif content_units == SvgUnits.object_bounding_box:
        let parent = tree_node_parent(mask_or_clip.layout_node()) else trap("VERIFY: a mask or clip box has a parent")
        let parent_node_state = layout_state_get(state, (LayoutNodeWithStyle*)parent)
        layout_state_used_values_set_content_width(layout_state, layout_state_used_values_content_width(parent_node_state))
        layout_state_used_values_set_content_height(layout_state, layout_state_used_values_content_height(parent_node_state))
        # https://svgwg.org/svg2-draft/pservers.html#PatternElementPatternContentUnitsAttribute
        parent_viewbox_transform = layout_identity_affine_transform()
        gfx.affine_transform_translate_float_point(&parent_viewbox_transform, gfx.css_pixel_point_to_type_f32(&parent_node_state.offset))
        if pattern_box != none:
            gfx.affine_transform_scale_f32(&parent_viewbox_transform, layout_state_used_values_content_width(parent_node_state).to_float(), layout_state_used_values_content_height(parent_node_state).to_float())
    else:
        layout_state_used_values_set_content_width(layout_state, this.m_viewport_size.m_width)
        layout_state_used_values_set_content_height(layout_state, this.m_viewport_size.m_height)
    # Pretend masks/clips are a viewport so we can scale the contents depending on the `contentUnits`.
    let nested_context = layout_make_svg_formatting_context(this, mask_or_clip.layout_box(), parent_viewbox_transform)
    layout_state_used_values_set_has_definite_width(layout_state, true)
    layout_state_used_values_set_has_definite_height(layout_state, true)
    layout_formatting_context_run(nested_context.layout_formatting_context(), layout_svg_formatting_context_available_space(this))

# mark: Container elements ======================================================================

## Ported from Libraries/LibWeb/Layout/SVGFormattingContext.cpp:587 Web::Layout::SVGFormattingContext::layout_container_element.
func layout_svg_formatting_context_layout_container_element(this: LayoutSvgFormattingContext*, container: LayoutSvgBox*):
    let box_state = layout_state_get_mutable(layout_svg_formatting_context_state(this), container.layout_node_with_style())
    var bounding_box = css_pixel_bounding_box_new()
    for child in layout_node_children(container.layout_node()):
        let child_box = as_if_layout_box(child) else continue
        # Masks/clips/patterns do not change the bounding box of their parents.
        if is_layout_svg_mask_box(child) or is_layout_svg_clip_box(child) or is_layout_svg_pattern_box(child):
            continue
        layout_svg_formatting_context_layout_svg_element(this, child_box)
        let child_state = layout_state_get(layout_svg_formatting_context_state(this), child_box.layout_node_with_style())
        css_pixel_bounding_box_add_point_css_pixel_point(&bounding_box, child_state.offset)
        css_pixel_bounding_box_add_point_css_pixel_point(&bounding_box, gfx.css_pixel_point_translated_css_pixels_css_pixels(&child_state.offset, layout_state_used_values_content_width(child_state), layout_state_used_values_content_height(child_state)))
    layout_state_used_values_set_content_x(box_state, css_pixel_bounding_box_x(&bounding_box))
    layout_state_used_values_set_content_y(box_state, css_pixel_bounding_box_y(&bounding_box))
    layout_state_used_values_set_content_width(box_state, css_pixel_bounding_box_width(&bounding_box))
    layout_state_used_values_set_content_height(box_state, css_pixel_bounding_box_height(&bounding_box))
    layout_state_used_values_set_has_definite_width(box_state, true)
    layout_state_used_values_set_has_definite_height(box_state, true)