Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / painting / paintable_fragment.lucb

#==============================================================================================
#
#   paintable_fragment - Painting::PaintableFragment: a line box fragment in the paint tree
#
#   DESCRIPTION:
#       Port of LibWeb/Painting/PaintableFragment.cpp (lines 1-302) and PaintableFragment.h's
#       inline members: a fragment made from a Layout::LineBoxFragment, its absolute rect and
#       orientation, the code unit under a point (grapheme by grapheme through the glyph run's
#       clusters), selection offsets and the rect of a range of its text.
#
#       Copyright (c) 2024-2025, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Glyph run clusters =========================================================================

## One cluster of for_each_cluster_in_glyph_run: its code units [start, end) and its advance.
struct PaintGlyphRunCluster:
    var start: usize
    var end: usize
    var width: f32

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:18 Web::Painting::for_each_cluster_in_glyph_run.
## The C++ template calls back for each cluster and stops on IterationDecision::Break; here it is an iterator
## (`for cluster in paint_glyph_run_clusters(...)`, `break`), DESIGN.md ยง2.9.
struct PaintGlyphRunClusters: luce.Iterable[PaintGlyphRunCluster, PaintGlyphRunClusters], luce.Iterator[PaintGlyphRunCluster]:
    var glyphs: const web_fonts.DrawGlyph[]
    var fragment_length_in_code_units: usize
    var index: usize
    var cursor: usize

    func iterator() -> PaintGlyphRunClusters:
        return self

    func next() -> PaintGlyphRunCluster?:
        while self.index < self.glyphs.length:
            let glyph = self.glyphs[self.index]
            self.index += 1
            if glyph.glyph_width == 0.0:
                continue

            let cluster_start = self.cursor
            let cluster_end = ak.min(self.cursor + glyph.length_in_code_units, self.fragment_length_in_code_units)
            self.cursor = cluster_end

            if cluster_end <= cluster_start:
                continue

            return PaintGlyphRunCluster(start = cluster_start, end = cluster_end, width = glyph.glyph_width)
        return none

## The clusters of `glyph_run` that lie within a fragment of `fragment_length_in_code_units` code units.
func paint_glyph_run_clusters(glyph_run: const web_fonts.GlyphRun*, fragment_length_in_code_units: usize) -> PaintGlyphRunClusters:
    return PaintGlyphRunClusters(glyphs = ak.vector_span_const(&glyph_run.m_glyphs), fragment_length_in_code_units = fragment_length_in_code_units, index = 0, cursor = 0)

# mark: Construction and accessors (PaintableFragment.h) =======================================

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:39 Web::Painting::PaintableFragment::PaintableFragment.
pub func paint_paintable_fragment_construct(this: PaintPaintableFragment*, fragment: LayoutLineBoxFragment):
    this.m_layout_node = layout_line_box_fragment_layout_node(&fragment)
    this.m_offset = layout_line_box_fragment_offset(&fragment)
    this.m_size = layout_line_box_fragment_size(&fragment)
    this.m_start_offset = layout_line_box_fragment_start(&fragment)
    this.m_length_in_code_units = layout_line_box_fragment_length_in_code_units(&fragment)
    this.m_glyph_run = layout_line_box_fragment_glyph_run(&fragment)
    this.m_shadows = ak.Vector[PaintShadowData]()
    this.m_baseline = layout_line_box_fragment_baseline(&fragment)
    this.m_text_decoration_thickness = gfx.CssPixels.from_int(0)
    this.m_writing_mode = layout_line_box_fragment_writing_mode(&fragment)
    this.m_has_trailing_whitespace = layout_line_box_fragment_has_trailing_whitespace(&fragment)

## `PaintableFragment { fragment }` by value.
pub func paint_paintable_fragment_new(fragment: LayoutLineBoxFragment) -> PaintPaintableFragment:
    var paintable_fragment: PaintPaintableFragment = ---
    paint_paintable_fragment_construct(&paintable_fragment, fragment)
    return paintable_fragment

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:24 Web::Painting::PaintableFragment::layout_node.
pub func paint_paintable_fragment_layout_node(this: const PaintPaintableFragment*) -> LayoutNode*:
    return this.m_layout_node

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:25 Web::Painting::PaintableFragment::paintable.
pub func paint_paintable_fragment_paintable(this: const PaintPaintableFragment*) -> PaintPaintable*:
    return layout_node_first_paintable(this.m_layout_node) else trap("a fragment's node has no paintable")

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:27 Web::Painting::PaintableFragment::start_offset.
pub func paint_paintable_fragment_start_offset(this: const PaintPaintableFragment*) -> usize:
    return this.m_start_offset

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:28 Web::Painting::PaintableFragment::length_in_code_units.
pub func paint_paintable_fragment_length_in_code_units(this: const PaintPaintableFragment*) -> usize:
    return this.m_length_in_code_units

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:30 Web::Painting::PaintableFragment::baseline.
pub func paint_paintable_fragment_baseline(this: const PaintPaintableFragment*) -> gfx.CssPixels:
    return this.m_baseline

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:31 Web::Painting::PaintableFragment::offset.
pub func paint_paintable_fragment_offset(this: const PaintPaintableFragment*) -> gfx.CssPixelPoint:
    return this.m_offset

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:32 Web::Painting::PaintableFragment::set_offset.
pub func paint_paintable_fragment_set_offset(this: PaintPaintableFragment*, offset: gfx.CssPixelPoint):
    this.m_offset = offset

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:33 Web::Painting::PaintableFragment::size.
pub func paint_paintable_fragment_size(this: const PaintPaintableFragment*) -> gfx.CssPixelSize:
    return this.m_size

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:35 Web::Painting::PaintableFragment::shadows.
pub func paint_paintable_fragment_shadows(this: const PaintPaintableFragment*) -> ak.Vector[PaintShadowData]:
    return this.m_shadows

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:36 Web::Painting::PaintableFragment::set_shadows.
pub func paint_paintable_fragment_set_shadows(this: PaintPaintableFragment*, shadows: ak.Vector[PaintShadowData]):
    this.m_shadows = shadows

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:40 Web::Painting::PaintableFragment::glyph_run.
pub func paint_paintable_fragment_glyph_run(this: const PaintPaintableFragment*) -> web_fonts.GlyphRun*?:
    return this.m_glyph_run

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:69 Web::Painting::PaintableFragment::width.
pub func paint_paintable_fragment_width(this: const PaintPaintableFragment*) -> gfx.CssPixels:
    return this.m_size.m_width

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:70 Web::Painting::PaintableFragment::height.
pub func paint_paintable_fragment_height(this: const PaintPaintableFragment*) -> gfx.CssPixels:
    return this.m_size.m_height

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:76 Web::Painting::PaintableFragment::text_decoration_thickness.
pub func paint_paintable_fragment_text_decoration_thickness(this: const PaintPaintableFragment*) -> gfx.CssPixels:
    return this.m_text_decoration_thickness

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:77 Web::Painting::PaintableFragment::set_text_decoration_thickness.
pub func paint_paintable_fragment_set_text_decoration_thickness(this: PaintPaintableFragment*, thickness: gfx.CssPixels):
    this.m_text_decoration_thickness = thickness

## Ported from Libraries/LibWeb/Painting/PaintableFragment.h:79 Web::Painting::PaintableFragment::has_trailing_whitespace.
pub func paint_paintable_fragment_has_trailing_whitespace(this: const PaintPaintableFragment*) -> bool:
    return this.m_has_trailing_whitespace

# mark: Geometry ===================================================================================

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:52 Web::Painting::PaintableFragment::absolute_rect.
pub func paint_paintable_fragment_absolute_rect(this: const PaintPaintableFragment*) -> gfx.CssPixelRect:
    var rect = gfx.CssPixelRect(paint_paintable_fragment_offset(this), paint_paintable_fragment_size(this))
    if let containing_block = paint_paintable_containing_block(paint_paintable_fragment_paintable(this)):
        gfx.css_pixel_rect_translate_by_css_pixel_point(&rect, paint_paintable_box_absolute_position(containing_block))
    return rect

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:60 Web::Painting::PaintableFragment::index_in_node_for_point.
pub func paint_paintable_fragment_index_in_node_for_point(this: const PaintPaintableFragment*, position: gfx.CssPixelPoint) -> usize:
    let text_paintable = as_if_paint_text_paintable(paint_paintable_fragment_paintable(this)) else return 0

    let absolute_rect = paint_paintable_fragment_absolute_rect(this)
    let relative_inline_offset = match paint_paintable_fragment_orientation(this):
        .horizontal => position.m_x.sub(gfx.css_pixel_rect_x(&absolute_rect)).to_float()
        .vertical => position.m_y.sub(gfx.css_pixel_rect_y(&absolute_rect)).to_float()
        _ => trap("VERIFY_NOT_REACHED")
    if relative_inline_offset < 0.0:
        return 0

    var tracker = GraphemeEdgeTracker()
    grapheme_edge_tracker_construct(&tracker, relative_inline_offset)

    if let glyph_run = this.m_glyph_run:
        let segmenter = layout_text_node_grapheme_segmenter(paint_text_paintable_layout_node(text_paintable))

        # A single glyph can cover several code units / graphemes. In the case of ligatures, we want clicks inside to
        # snap to the closest grapheme boundary inside it, not jump to either end. To achieve this we walk
        # per-grapheme rather than per-glyph, splitting each glyph's advance proportionally across the graphemes that
        # lie inside its cluster.
        clusters: for cluster in paint_glyph_run_clusters(glyph_run, this.m_length_in_code_units):
            let per_unit_advance = cluster.width / (f32)(cluster.end - cluster.start)

            var grapheme_start = this.m_start_offset + cluster.start
            let cluster_absolute_end = this.m_start_offset + cluster.end
            while grapheme_start < cluster_absolute_end:
                let next_boundary = web_unicode.segmenter_next_boundary(segmenter, grapheme_start, web_unicode.SegmenterInclusive.no)
                var boundary = cluster_absolute_end
                if let found = next_boundary:
                    boundary = (usize)found
                let grapheme_end = ak.min(boundary, cluster_absolute_end)
                if grapheme_end <= grapheme_start:
                    break

                let grapheme_units = grapheme_end - grapheme_start
                let grapheme_width = per_unit_advance * (f32)grapheme_units
                if grapheme_edge_tracker_update(&tracker, grapheme_units, grapheme_width) == ak.IterationDecision.break_:
                    break clusters

                grapheme_start = grapheme_end

    return this.m_start_offset + grapheme_edge_tracker_resolve(&tracker)

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:108 Web::Painting::PaintableFragment::compute_selection_offsets.
pub func paint_paintable_fragment_compute_selection_offsets(this: const PaintPaintableFragment*, selection_state: PaintPaintableSelectionState, start_offset_in_code_units: usize, end_offset_in_code_units: usize) -> PaintPaintableFragmentSelectionOffsets?:
    let start_index = this.m_start_offset
    let end_index = this.m_start_offset + this.m_length_in_code_units

    match selection_state:
        .none_:
            return none
        .full:
            return PaintPaintableFragmentSelectionOffsets(start = 0, end = this.m_length_in_code_units, include_trailing_whitespace = true)
        .start_and_end:
            if start_index > end_offset_in_code_units or end_index < start_offset_in_code_units:
                return none
            return PaintPaintableFragmentSelectionOffsets(
                start = start_offset_in_code_units - ak.min(start_offset_in_code_units, this.m_start_offset),
                end = ak.min(end_offset_in_code_units -% this.m_start_offset, this.m_length_in_code_units),
                include_trailing_whitespace = end_offset_in_code_units >= end_index,
            )
        .start:
            if end_index < start_offset_in_code_units:
                return none
            return PaintPaintableFragmentSelectionOffsets(
                start = start_offset_in_code_units - ak.min(start_offset_in_code_units, this.m_start_offset),
                end = this.m_length_in_code_units,
                include_trailing_whitespace = true,
            )
        .end:
            if start_index > end_offset_in_code_units:
                return none
            return PaintPaintableFragmentSelectionOffsets(
                start = 0,
                end = ak.min(end_offset_in_code_units -% this.m_start_offset, this.m_length_in_code_units),
                include_trailing_whitespace = end_offset_in_code_units >= end_index,
            )
        _: trap("VERIFY_NOT_REACHED")

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:150 Web::Painting::PaintableFragment::range_rect.
pub func paint_paintable_fragment_range_rect(this: const PaintPaintableFragment*, selection_state: PaintPaintableSelectionState, start_offset_in_code_units: usize, end_offset_in_code_units: usize) -> gfx.CssPixelRect:
    let offsets = paint_paintable_fragment_compute_selection_offsets(this, selection_state, start_offset_in_code_units, end_offset_in_code_units) else return gfx.CssPixelRect()

    var rect = paint_paintable_fragment_absolute_rect(this)
    var font = layout_node_first_available_font(paint_paintable_fragment_layout_node(this))
    if let glyph_run = paint_paintable_fragment_glyph_run(this):
        font = glyph_run.m_font

    var pixel_offset = gfx.CssPixels.from_int(0)
    var pixel_width = gfx.CssPixels.from_int(0)
    let orientation = paint_paintable_fragment_orientation(this)

    # When entire fragment is selected, use the rect's existing dimensions rather than recalculating from text.
    if offsets.start == 0 and offsets.end == this.m_length_in_code_units and this.m_length_in_code_units > 0:
        pixel_offset = gfx.CssPixels.from_int(0)
        pixel_width = gfx.css_pixel_rect_primary_size_for_orientation(&rect, orientation)
    else:
        var offset_accumulator: f32 = 0.0
        var width_accumulator: f32 = 0.0

        if let glyph_run = this.m_glyph_run:
            # Walk the glyph run, splitting any cluster that spans multiple code units proportionally between the
            # pre-selection offset and the in-selection width when the selection range partially overlaps the cluster.
            # This allows ligatures to be partially selected.
            for cluster in paint_glyph_run_clusters(glyph_run, this.m_length_in_code_units):
                if cluster.end <= offsets.start:
                    offset_accumulator += cluster.width
                    continue
                if cluster.start >= offsets.end:
                    continue

                let per_unit_advance = cluster.width / (f32)(cluster.end - cluster.start)

                if cluster.start < offsets.start:
                    offset_accumulator += per_unit_advance * (f32)(offsets.start - cluster.start)

                let in_sel_start = ak.max(cluster.start, offsets.start)
                let in_sel_end = ak.min(cluster.end, offsets.end)
                width_accumulator += per_unit_advance * (f32)(in_sel_end - in_sel_start)

        pixel_offset = gfx.CssPixels.from_f32(offset_accumulator)
        pixel_width = gfx.CssPixels.from_f32(width_accumulator)

    # When start equals end, this is a cursor position.
    if offsets.start == offsets.end:
        pixel_width = gfx.CssPixels.from_int(1)

    # Include an additional space at the end if we remembered that this fragment contained trailing whitespace. This
    # shows the user that at least one whitespace character was present when selecting text, even though we don't store
    # that whitespace in the glyph run or text fragment.
    if offsets.start != offsets.end and this.m_has_trailing_whitespace and offsets.include_trailing_whitespace:
        pixel_width = pixel_width.add(gfx.CssPixels.from_f32(web_fonts.font_glyph_width(font, (u32)' ')))

    gfx.css_pixel_rect_translate_primary_offset_for_orientation(&rect, orientation, pixel_offset)
    gfx.css_pixel_rect_set_primary_size_for_orientation(&rect, orientation, pixel_width)

    # Inflate so the rect covers glyph ascenders and descenders that may extend beyond the line box.
    let font_metrics = web_fonts.font_pixel_metrics(font)
    if font_metrics.ascent > 0.0 or font_metrics.descent > 0.0:
        let ascent = gfx.CssPixels.from_f32(font_metrics.ascent)
        let descent = gfx.CssPixels.from_f32(font_metrics.descent)
        let zero = gfx.CssPixels.from_int(0)
        let overflow_top = ak.max(zero, ascent.sub(this.m_baseline))
        let overflow_bottom = ak.max(zero, descent.sub(gfx.css_pixel_rect_secondary_size_for_orientation(&rect, orientation)).add(this.m_baseline))
        gfx.css_pixel_rect_inflate_secondary_for_orientation(&rect, orientation, overflow_top, overflow_bottom)

    return rect

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:222 Web::Painting::PaintableFragment::orientation.
pub func paint_paintable_fragment_orientation(this: const PaintPaintableFragment*) -> gfx.Orientation:
    match this.m_writing_mode:
        .horizontal_tb:
            return gfx.Orientation.horizontal
        .vertical_rl, .vertical_lr, .sideways_rl, .sideways_lr:
            return gfx.Orientation.vertical
        _: trap("VERIFY_NOT_REACHED")

# mark: Selections ================================================================================

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:237 Web::Painting::PaintableFragment::selection_range_for_text_control.
pub func paint_paintable_fragment_selection_range_for_text_control(this: const PaintPaintableFragment*) -> PaintPaintableFragmentSelectionOffsets?:
    # For focused text controls (input/textarea), determine selection from the control's internal state.
    let paintable = paint_paintable_fragment_paintable(this)
    let focused_area = dom_document_focused_area(paint_paintable_document(paintable)) else return none
    let text_control = as_if_form_associated_text_control_element(focused_area) else return none
    var text_node: DomNode*? = none
    if let text = html_form_associated_text_control_element_form_associated_element_to_text_node(text_control):
        text_node = text.dom_node()
    if paint_paintable_dom_node(paintable) != text_node:
        return none

    let selection_start = html_form_associated_text_control_element_selection_start(text_control)
    let selection_end = html_form_associated_text_control_element_selection_end(text_control)
    if selection_start == selection_end:
        return none

    return PaintPaintableFragmentSelectionOffsets(start = selection_start, end = selection_end)

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:255 Web::Painting::PaintableFragment::selection_offsets.
pub func paint_paintable_fragment_selection_offsets(this: const PaintPaintableFragment*) -> PaintPaintableFragmentSelectionOffsets?:
    if let offsets = paint_paintable_fragment_selection_range_for_text_control(this):
        return paint_paintable_fragment_compute_selection_offsets(this, PaintPaintableSelectionState.start_and_end, offsets.start, offsets.end)

    let paintable = paint_paintable_fragment_paintable(this)
    let selection_state = paint_paintable_selection_state(paintable)
    if selection_state == PaintPaintableSelectionState.none_:
        return none

    let selection = dom_document_get_selection(paint_paintable_document(paintable)) else return none
    let range = selection_selection_range(selection) else return none

    return paint_paintable_fragment_compute_selection_offsets(this, selection_state, (usize)dom_abstract_range_start_offset(range.dom_abstract_range()), (usize)dom_abstract_range_end_offset(range.dom_abstract_range()))

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:274 Web::Painting::PaintableFragment::selection_rect.
pub func paint_paintable_fragment_selection_rect(this: const PaintPaintableFragment*) -> gfx.CssPixelRect:
    if let offsets = paint_paintable_fragment_selection_range_for_text_control(this):
        return paint_paintable_fragment_range_rect(this, PaintPaintableSelectionState.start_and_end, offsets.start, offsets.end)

    let paintable = paint_paintable_fragment_paintable(this)
    let selection_state = paint_paintable_selection_state(paintable)
    if selection_state == PaintPaintableSelectionState.none_:
        return gfx.CssPixelRect()

    let selection = dom_document_get_selection(paint_paintable_document(paintable)) else return gfx.CssPixelRect()
    let range = selection_selection_range(selection) else return gfx.CssPixelRect()

    return paint_paintable_fragment_range_rect(this, selection_state, (usize)dom_abstract_range_start_offset(range.dom_abstract_range()), (usize)dom_abstract_range_end_offset(range.dom_abstract_range()))

## Ported from Libraries/LibWeb/Painting/PaintableFragment.cpp:293 Web::Painting::PaintableFragment::text.
pub func paint_paintable_fragment_text(this: const PaintPaintableFragment*) -> ak.Utf16View:
    let paintable = paint_paintable_fragment_paintable(this)
    if not is_paint_text_paintable(paintable):
        return ak.Utf16View()
    let text = layout_text_node_text_for_rendering(paint_text_paintable_layout_node(as_paint_text_paintable(paintable)))
    return ak.utf16_string_base_substring_view_usize(&text.utf16_string_base, this.m_start_offset, this.m_length_in_code_units)