Skip to content

Truly independent web browser

38.2 KB
Raw Blame
/*
 * Copyright (c) 2018-2025, Andreas Kling <[email protected]>
 * Copyright (c) 2021, sin-ack <[email protected]>
 * Copyright (c) 2024-2025, Aliaksandr Kalenik <[email protected]>
 * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/AnyOf.h>
#include <AK/Array.h>
#include <AK/BitCast.h>
#include <AK/HashFunctions.h>
#include <AK/Math.h>
#include <AK/NumericLimits.h>
#include <AK/Utf16String.h>
#include <AK/Utf16View.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Font/Typeface.h>
#include <LibGfx/Point.h>
#include <LibGfx/TextLayout.h>
#include <LibUnicode/CharacterTypes.h>
#include <RustFFI.h>
#include <harfbuzz/hb.h>

namespace Gfx {

// How far synthetic bold can spread the ink of a font's glyphs past their outlines, in device pixels. The rasterizer
// decides the stroke, so this allows for the widest it's known to use: It bounds what a run may paint, and isn't a
// measurement of its ink.
static float synthetic_bold_outset(Font const& font, float scale)
{
    if (!font.synthesis().bold)
        return 0;
    return max(font.pixel_size() * scale / 24, 1.0f);
}

// Tight bounds of the ink of the painted glyphs, from their own extents, in the coordinates of glyph_run_bounding_box().
// Empty if no painted glyph has ink.
static FloatRect glyph_run_ink_bounding_box(Font const& font, ReadonlySpan<ShapedGlyph> glyphs, float scale)
{
    auto font_ascent = font.pixel_metrics().ascent;
    auto* hb_font = font.harfbuzz_font();
    int x_scale = 0;
    int y_scale = 0;
    hb_font_get_scale(hb_font, &x_scale, &y_scale);
    if (x_scale <= 0 || y_scale <= 0)
        return {};
    auto units_to_pixels_x = font.pixel_size() * scale / x_scale;
    auto units_to_pixels_y = font.pixel_size() * scale / y_scale;

    FloatRect bounds;
    for (auto const& glyph : glyphs) {
        if (!glyph.should_paint)
            continue;
        hb_glyph_extents_t extents;
        if (!hb_font_get_glyph_extents(hb_font, glyph.glyph_id, &extents))
            continue;
        auto origin_x = glyph.position.x() * scale;
        auto origin_y = (glyph.position.y() + font_ascent) * scale;
        // HarfBuzz extents have y pointing up, so `height` is negative for ink above the baseline.
        FloatRect glyph_bounds {
            origin_x + extents.x_bearing * units_to_pixels_x,
            origin_y - extents.y_bearing * units_to_pixels_y,
            extents.width * units_to_pixels_x,
            -extents.height * units_to_pixels_y,
        };
        bounds.unite(glyph_bounds);
    }
    return bounds;
}

FloatRect glyph_run_bounding_box(Font const& font, ReadonlySpan<ShapedGlyph> glyphs, float scale)
{
    auto font_ascent = font.pixel_metrics().ascent;

    // NOTE: This is a plain min/max rather than FloatRect::unite(), because a run with a single glyph must still
    //       produce a (zero-sized) origin box that gets expanded by the font bounds below.
    bool has_painted_glyphs = false;
    float min_x = NumericLimits<float>::max();
    float min_y = NumericLimits<float>::max();
    float max_x = NumericLimits<float>::lowest();
    float max_y = NumericLimits<float>::lowest();
    for (auto const& glyph : glyphs) {
        if (!glyph.should_paint)
            continue;
        auto origin_x = glyph.position.x() * scale;
        auto origin_y = (glyph.position.y() + font_ascent) * scale;
        if (!__builtin_isfinite(origin_x) || !__builtin_isfinite(origin_y))
            return {};
        min_x = min(min_x, origin_x);
        min_y = min(min_y, origin_y);
        max_x = max(max_x, origin_x);
        max_y = max(max_y, origin_y);
        has_painted_glyphs = true;
    }
    if (!has_painted_glyphs)
        return {};

    auto font_bounding_box = font.typeface().bounding_box_in_font_units();
    if (!font_bounding_box.is_empty()) {
        auto font_units_to_pixels = font.pixel_size() * scale / font_bounding_box.units_per_em;
        // Font units have y pointing up, device pixels have y pointing down.
        auto left = min_x + font_bounding_box.x_min * font_units_to_pixels;
        auto right = max_x + font_bounding_box.x_max * font_units_to_pixels;
        auto top = min_y - font_bounding_box.y_max * font_units_to_pixels;
        auto bottom = max_y - font_bounding_box.y_min * font_units_to_pixels;
        // A synthetic oblique shifts each point of a glyph along the line by its height above the baseline.
        if (auto angle = font.synthesis().oblique_angle; angle != 0) {
            auto slant = AK::tan(AK::to_radians(angle));
            auto shift_at_top = font_bounding_box.y_max * font_units_to_pixels * slant;
            auto shift_at_bottom = font_bounding_box.y_min * font_units_to_pixels * slant;
            left += min(0.0f, min(shift_at_top, shift_at_bottom));
            right += max(0.0f, max(shift_at_top, shift_at_bottom));
        }
        auto outset = synthetic_bold_outset(font, scale);
        left -= outset;
        right += outset;
        top -= outset;
        bottom += outset;
        return { left, top, right - left, bottom - top };
    }

    // The font doesn't record an overall bounding box (e.g. bitmap-only fonts), so unite the glyphs' own extents.
    // NB: HarfBuzz slants the extents of a synthetic oblique itself.
    auto bounds = glyph_run_ink_bounding_box(font, glyphs, scale);
    if (auto outset = synthetic_bold_outset(font, scale); outset > 0 && !bounds.is_empty())
        bounds.inflate(outset * 2, outset * 2);
    return bounds;
}

namespace {

struct OutlinePoint {
    double x { 0 };
    double y { 0 };
};

// Roots of a*t^2 + b*t + c = 0 with t in [0, 1]. Duplicate roots may be reported twice.
size_t quadratic_roots_in_unit_interval(double a, double b, double c, Array<double, 2>& roots)
{
    size_t count = 0;
    auto add_root = [&](double t) {
        // NOTE: Written so that a NaN root (e.g. from a degenerate division) is rejected too.
        if (t >= 0 && t <= 1)
            roots[count++] = t;
    };

    if (a == 0) {
        if (b != 0)
            add_root(-c / b);
        return count;
    }

    auto discriminant = b * b - 4 * a * c;
    if (discriminant < 0)
        return 0;

    // The numerically stable form: computing the smaller root as c / q instead of (-b - sqrt(d)) / 2a avoids
    // catastrophic cancellation when |a| is tiny compared to |b| (a nearly-linear curve).
    auto q = -0.5 * (b + __builtin_copysign(AK::sqrt(discriminant), b));
    add_root(q / a);
    if (q != 0)
        add_root(c / q);
    return count;
}

// Roots of a*t^3 + b*t^2 + c*t + d = 0 with t in [0, 1]. The polynomial is split at the extrema of its derivative,
// so each piece is monotonic and has at most one root, which is then found by bisection. Unlike a closed-form
// solution, this can neither miss nor invent roots inside the interval.
size_t cubic_roots_in_unit_interval(double a, double b, double c, double d, Array<double, 3>& roots)
{
    auto evaluate = [&](double t) {
        return ((a * t + b) * t + c) * t + d;
    };

    Array<double, 4> breakpoints {};
    size_t breakpoint_count = 0;
    breakpoints[breakpoint_count++] = 0;
    Array<double, 2> extrema;
    auto extrema_count = quadratic_roots_in_unit_interval(3 * a, 2 * b, c, extrema);
    if (extrema_count == 2 && extrema[0] > extrema[1])
        swap(extrema[0], extrema[1]);
    for (size_t i = 0; i < extrema_count; ++i) {
        if (extrema[i] > 0 && extrema[i] < 1 && extrema[i] != breakpoints[breakpoint_count - 1])
            breakpoints[breakpoint_count++] = extrema[i];
    }
    breakpoints[breakpoint_count++] = 1;

    constexpr double value_tolerance = 1e-6;
    constexpr double parameter_tolerance = 1e-7;

    size_t count = 0;
    for (size_t i = 0; i + 1 < breakpoint_count; ++i) {
        auto start = breakpoints[i];
        auto end = breakpoints[i + 1];
        auto value_at_start = evaluate(start);
        auto value_at_end = evaluate(end);
        if (AK::fabs(value_at_start) <= value_tolerance) {
            roots[count++] = start;
            continue;
        }
        if (AK::fabs(value_at_end) <= value_tolerance) {
            roots[count++] = end;
            continue;
        }
        if ((value_at_start < 0) == (value_at_end < 0))
            continue;
        while (end - start > parameter_tolerance) {
            auto middle = 0.5 * (start + end);
            auto value_at_middle = evaluate(middle);
            if (value_at_middle == 0) {
                start = end = middle;
                break;
            }
            if ((value_at_middle < 0) == (value_at_start < 0)) {
                start = middle;
                value_at_start = value_at_middle;
            } else {
                end = middle;
            }
        }
        roots[count++] = 0.5 * (start + end);
    }
    return count;
}

// Tracks the horizontal extent of a glyph outline's ink inside a horizontal band, in glyph-local device pixels with
// y pointing down. This mirrors how Skia computes text blob intercepts: every point where an outline segment
// crosses the top or bottom edge of the band widens the extent, and so does every segment point (including
// control points) that lies strictly inside the band.
struct InkExtentInBand {
    double band_top { 0 };
    double band_bottom { 0 };
    double units_to_pixels_x { 0 };
    double units_to_pixels_y { 0 };
    double left { NumericLimits<double>::max() };
    double right { NumericLimits<double>::lowest() };

    OutlinePoint to_device_pixels(float x, float y) const
    {
        // HarfBuzz outlines have y pointing up.
        return { x * units_to_pixels_x, -y * units_to_pixels_y };
    }

    void expand(double x)
    {
        left = min(left, x);
        right = max(right, x);
    }

    bool overlaps_band(double segment_top, double segment_bottom) const
    {
        return band_top <= segment_bottom && segment_top <= band_bottom;
    }

    void expand_by_points_strictly_inside_band(ReadonlySpan<OutlinePoint> points)
    {
        for (auto const& point : points) {
            if (band_top < point.y && point.y < band_bottom)
                expand(point.x);
        }
    }

    void add_line(OutlinePoint p0, OutlinePoint p1)
    {
        if (!overlaps_band(min(p0.y, p1.y), max(p0.y, p1.y)))
            return;
        for (auto offset : { band_top, band_bottom }) {
            // NOTE: A horizontal line makes this a division by zero; the resulting inf/NaN fails the range check.
            auto t = (offset - p0.y) / (p1.y - p0.y);
            if (t >= 0 && t < 1)
                expand(p0.x + t * (p1.x - p0.x));
        }
        expand_by_points_strictly_inside_band(Array { p0, p1 });
    }

    void add_quadratic(OutlinePoint p0, OutlinePoint p1, OutlinePoint p2)
    {
        if (!overlaps_band(min(p0.y, min(p1.y, p2.y)), max(p0.y, max(p1.y, p2.y))))
            return;
        // y(t) = (y0 - 2*y1 + y2) * t^2 + 2 * (y1 - y0) * t + y0
        auto a = p0.y - 2 * p1.y + p2.y;
        auto b = 2 * (p1.y - p0.y);
        for (auto offset : { band_top, band_bottom }) {
            Array<double, 2> roots;
            auto count = quadratic_roots_in_unit_interval(a, b, p0.y - offset, roots);
            for (size_t i = 0; i < count; ++i) {
                auto t = roots[i];
                auto u = 1 - t;
                expand(u * u * p0.x + 2 * u * t * p1.x + t * t * p2.x);
            }
        }
        expand_by_points_strictly_inside_band(Array { p0, p1, p2 });
    }

    void add_cubic(OutlinePoint p0, OutlinePoint p1, OutlinePoint p2, OutlinePoint p3)
    {
        if (!overlaps_band(min(min(p0.y, p1.y), min(p2.y, p3.y)), max(max(p0.y, p1.y), max(p2.y, p3.y))))
            return;
        // y(t) = (-y0 + 3*y1 - 3*y2 + y3) * t^3 + (3*y0 - 6*y1 + 3*y2) * t^2 + (-3*y0 + 3*y1) * t + y0
        auto a = -p0.y + 3 * p1.y - 3 * p2.y + p3.y;
        auto b = 3 * p0.y - 6 * p1.y + 3 * p2.y;
        auto c = -3 * p0.y + 3 * p1.y;
        for (auto offset : { band_top, band_bottom }) {
            Array<double, 3> roots;
            auto count = cubic_roots_in_unit_interval(a, b, c, p0.y - offset, roots);
            for (size_t i = 0; i < count; ++i) {
                auto t = roots[i];
                auto u = 1 - t;
                expand(u * u * u * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t * t * t * p3.x);
            }
        }
        expand_by_points_strictly_inside_band(Array { p0, p1, p2, p3 });
    }
};

// NOTE: HarfBuzz emits the implicit line that closes each contour as a regular line_to before close_path, so only
//       the segment callbacks are needed. The quadratic callback must be set, otherwise HarfBuzz converts quadratic
//       segments to cubics.
hb_draw_funcs_t* ink_extent_draw_funcs()
{
    static hb_draw_funcs_t* draw_funcs = [] {
        auto* funcs = hb_draw_funcs_create();
        hb_draw_funcs_set_line_to_func(
            funcs, [](hb_draw_funcs_t*, void* draw_data, hb_draw_state_t* state, float to_x, float to_y, void*) {
                auto& ink_extent = *static_cast<InkExtentInBand*>(draw_data);
                ink_extent.add_line(
                    ink_extent.to_device_pixels(state->current_x, state->current_y),
                    ink_extent.to_device_pixels(to_x, to_y));
            },
            nullptr, nullptr);
        hb_draw_funcs_set_quadratic_to_func(
            funcs, [](hb_draw_funcs_t*, void* draw_data, hb_draw_state_t* state, float control_x, float control_y, float to_x, float to_y, void*) {
                auto& ink_extent = *static_cast<InkExtentInBand*>(draw_data);
                ink_extent.add_quadratic(
                    ink_extent.to_device_pixels(state->current_x, state->current_y),
                    ink_extent.to_device_pixels(control_x, control_y),
                    ink_extent.to_device_pixels(to_x, to_y));
            },
            nullptr, nullptr);
        hb_draw_funcs_set_cubic_to_func(
            funcs, [](hb_draw_funcs_t*, void* draw_data, hb_draw_state_t* state, float control1_x, float control1_y, float control2_x, float control2_y, float to_x, float to_y, void*) {
                auto& ink_extent = *static_cast<InkExtentInBand*>(draw_data);
                ink_extent.add_cubic(
                    ink_extent.to_device_pixels(state->current_x, state->current_y),
                    ink_extent.to_device_pixels(control1_x, control1_y),
                    ink_extent.to_device_pixels(control2_x, control2_y),
                    ink_extent.to_device_pixels(to_x, to_y));
            },
            nullptr, nullptr);
        hb_draw_funcs_make_immutable(funcs);
        return funcs;
    }();
    return draw_funcs;
}

}

Vector<float> glyph_run_glyph_intercepts(Font const& font, ReadonlySpan<ShapedGlyph> glyphs, float scale, float y_top, float y_bottom)
{
    if (!(scale > 0) || !__builtin_isfinite(scale))
        return {};

    auto* hb_font = font.harfbuzz_font();
    int x_scale = 0;
    int y_scale = 0;
    hb_font_get_scale(hb_font, &x_scale, &y_scale);
    if (x_scale <= 0 || y_scale <= 0)
        return {};
    auto units_to_pixels_x = static_cast<double>(font.pixel_size()) * scale / x_scale;
    auto units_to_pixels_y = static_cast<double>(font.pixel_size()) * scale / y_scale;
    auto font_ascent = font.pixel_metrics().ascent;

    Vector<float> intervals;
    for (auto const& glyph : glyphs) {
        if (!glyph.should_paint)
            continue;
        auto origin_x = static_cast<double>(glyph.position.x()) * scale;
        auto origin_y = (static_cast<double>(glyph.position.y()) + font_ascent) * scale;

        // Move the band into glyph-local coordinates, with the origin at the glyph's baseline origin.
        auto band_top = y_top - origin_y;
        auto band_bottom = y_bottom - origin_y;

        // Skip glyphs whose bounding box doesn't reach the band before decoding their outline.
        hb_glyph_extents_t extents;
        if (hb_font_get_glyph_extents(hb_font, glyph.glyph_id, &extents)) {
            auto glyph_top = -extents.y_bearing * units_to_pixels_y;
            auto glyph_bottom = -(extents.y_bearing + extents.height) * units_to_pixels_y;
            if (glyph_bottom < band_top || band_bottom < glyph_top)
                continue;
        }

        InkExtentInBand ink_extent {
            .band_top = band_top,
            .band_bottom = band_bottom,
            .units_to_pixels_x = units_to_pixels_x,
            .units_to_pixels_y = units_to_pixels_y,
        };
        hb_font_draw_glyph(hb_font, glyph.glyph_id, ink_extent_draw_funcs(), &ink_extent);

        // Glyphs without an outline (e.g. spaces) never widen the extent and produce no interval.
        if (ink_extent.left < ink_extent.right) {
            intervals.append(static_cast<float>(ink_extent.left + origin_x));
            intervals.append(static_cast<float>(ink_extent.right + origin_x));
        }
    }
    return intervals;
}

static hb_buffer_t* setup_text_shaping(Utf16View const& string, Font const& font, FFI::TextType text_type, float letter_spacing, FFI::JoiningContext joining_context = {}, bool vertical_forms = false)
{
    hb_buffer_t* buffer = hb_buffer_create();

    // A zero width joiner as context before or after the text gives the letters at its edges the forms that join them
    // to letters outside it.
    static constexpr hb_codepoint_t ZERO_WIDTH_JOINER = 0x200D;
    if (joining_context.joins_before)
        hb_buffer_add_codepoints(buffer, &ZERO_WIDTH_JOINER, 1, 1, 0);

    if (string.has_ascii_storage()) {
        hb_buffer_add_utf8(buffer, string.ascii_span().data(), string.length_in_code_units(), 0, -1);
        // Fast path for ASCII: we know it's Latin script, LTR direction.
        hb_buffer_set_script(buffer, HB_SCRIPT_LATIN);
        hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
    } else {
        if (string.has_latin1_storage())
            hb_buffer_add_latin1(buffer, string.latin1_span().data(), string.length_in_code_units(), 0, -1);
        else
            hb_buffer_add_utf16(buffer, reinterpret_cast<u16 const*>(string.utf16_span().data()), string.length_in_code_units(), 0, -1);
        // For non-ASCII, set direction from text_type if known, otherwise guess.
        if (text_type == FFI::TextType::Ltr) {
            hb_buffer_set_direction(buffer, HB_DIRECTION_LTR);
            hb_buffer_guess_segment_properties(buffer);
        } else if (text_type == FFI::TextType::Rtl) {
            hb_buffer_set_direction(buffer, HB_DIRECTION_RTL);
            hb_buffer_guess_segment_properties(buffer);
        } else {
            hb_buffer_guess_segment_properties(buffer);
        }
    }

    if (joining_context.joins_after)
        hb_buffer_add_codepoints(buffer, &ZERO_WIDTH_JOINER, 1, 0, 0);

    auto* hb_font = font.harfbuzz_font();
    Vector<hb_feature_t, 8> hb_features;
    hb_features.ensure_capacity(font.features().size() + (vertical_forms ? 1 : 0));
    // https://drafts.csswg.org/css-writing-modes-4/#typeset-upright
    // "Additionally, font features (such as alternate glyphs and other transformation) intended for use in vertical
    //  typesetting must be used. (E.g. the OpenType vert feature must be enabled.)"
    // NB: That gives glyphs set upright the vertical forms the font has for them: the vertical long vowel mark,
    //     brackets that open downwards, and punctuation that sits in the top-right corner of the em box.
    // NB: It goes first, so that font-feature-settings can still turn it off.
    if (vertical_forms)
        hb_features.append({ .tag = HB_TAG('v', 'e', 'r', 't'), .value = 1, .start = 0, .end = HB_FEATURE_GLOBAL_END });

    for (auto const& feature : font.features()) {
        hb_features.unchecked_append({
            .tag = HB_TAG(feature.tag[0], feature.tag[1], feature.tag[2], feature.tag[3]),
            .value = feature.value,
            .start = 0,
            .end = HB_FEATURE_GLOBAL_END,
        });
    }

    // https://drafts.csswg.org/css-fonts-4/#feature-variation-precedence
    // 11. Feature settings determined by properties other than font-variant or font-feature-settings are applied. For
    //     example, setting a non-default value for the letter-spacing property disables optional ligatures.
    // NB: The optional ligatures are the ones CSS Text names: those not required for fundamentally correct glyph
    //     shaping, which leaves rlig on. A feature that font-feature-settings set stays as it is, since step 13
    //     applies font-feature-settings after this step. And HarfBuzz applies the last of the features with one tag,
    //     so these go after the font's own.
    if (letter_spacing != 0) {
        for (auto tag : { HB_TAG('l', 'i', 'g', 'a'), HB_TAG('c', 'l', 'i', 'g'), HB_TAG('d', 'l', 'i', 'g'), HB_TAG('h', 'l', 'i', 'g') }) {
            auto set_by_feature_settings = any_of(font.features(), [&](auto const& feature) {
                return feature.set_by_feature_settings && HB_TAG(feature.tag[0], feature.tag[1], feature.tag[2], feature.tag[3]) == tag;
            });
            if (!set_by_feature_settings)
                hb_features.append({ .tag = tag, .value = 0, .start = 0, .end = HB_FEATURE_GLOBAL_END });
        }
    }

    hb_shape(hb_font, buffer, hb_features.data(), hb_features.size());

    return buffer;
}

// https://drafts.csswg.org/css-text-4/#word-separator
static bool is_word_separator(u32 code_point)
{
    // Word-separator characters include the space (U+0020), the no-break space (U+00A0), the Ethiopic word space
    // (U+1361), the Aegean word separators (U+10100,U+10101), the Ugaritic word divider (U+1039F), and the Phoenician
    // Word Separator (U+1091F).
    // AD-HOC: Only the space and no-break space are treated as word separators, matching other engines. The line feed
    //         is also included because whitespace collapsing can leave a segment break in shaped text, where it
    //         behaves as a space.
    return code_point == 0x0020 || code_point == 0x00A0 || code_point == 0x000A;
}

// https://drafts.csswg.org/css-text-3/#cursive-script
static bool is_cursive_script(u32 code_point)
{
    switch (hb_unicode_script(hb_unicode_funcs_get_default(), code_point)) {
    case HB_SCRIPT_ARABIC:
    case HB_SCRIPT_HANIFI_ROHINGYA:
    case HB_SCRIPT_MANDAIC:
    case HB_SCRIPT_MONGOLIAN:
    case HB_SCRIPT_NKO:
    case HB_SCRIPT_PHAGS_PA:
    case HB_SCRIPT_SYRIAC:
        return true;
    case HB_SCRIPT_COMMON:
    case HB_SCRIPT_INHERITED: {
        // https://drafts.csswg.org/css-text-3/#character-properties
        // script property: Defined in Unicode Standard Annex #24 [UAX24] and given as the Script property in the
        // Unicode Character Database [UAX44]. (UAs must include any ScriptExtensions.txt assignments in this mapping.)
        // NB: So a character that serves several scripts, as the tatweel (U+0640) does, belongs to a cursive script
        //     when one of its script extensions is one.
        static auto const cursive_scripts = [] {
            constexpr Array names { "Arab"sv, "Rohg"sv, "Mand"sv, "Mong"sv, "Nkoo"sv, "Phag"sv, "Syrc"sv };
            Array<Unicode::Script, names.size()> scripts;
            for (size_t i = 0; i < names.size(); ++i)
                scripts[i] = Unicode::script_from_string(names[i]).release_value();
            return scripts;
        }();
        return any_of(cursive_scripts, [&](auto script) { return Unicode::code_point_has_script_extension(code_point, script); });
    }
    default:
        return false;
    }
}

// Whether letter-spacing goes after the last glyph of the cluster starting at cluster_start: Every cluster takes it but
// one that starts with a character of a cursive script.
static bool cluster_takes_letter_spacing(Utf16View const& string, u32 cluster_start)
{
    // https://drafts.csswg.org/css-text-3/#cursive-tracking
    // Otherwise, if the UA cannot expand text from a cursive script without breaking its cursive connections, it must
    // not apply spacing between any pair of that script's typographic letter units at all (effectively treating each
    // word as a single typographic letter unit for the purpose of letter-spacing).
    // NB: Spaces still take it: Their script is Common, with no extensions.
    return cluster_start >= string.length_in_code_units() || !is_cursive_script(string.code_point_at(cluster_start));
}

static bool is_hangul_filler(u32 code_point)
{
    return code_point == 0x115F || code_point == 0x1160 || code_point == 0x3164 || code_point == 0xFFA0;
}

// https://drafts.csswg.org/css-text-3/#white-space-phase-2
// 4. If there remains any sequence of white space, other space separators, and/or preserved tabs at the end of a line
//    (after bidi reordering [CSS-WRITING-MODES-4]):
//    - If white-space is set to normal, nowrap, or pre-line, the UA must hang this sequence (unconditionally).
// AD-HOC: Of the other space separators, only the ideographic space (U+3000) counts, so the rest (the em space, e.g.)
//         stay on the line.
static bool is_trailing_space(u16 code_unit)
{
    return is_ascii_space(code_unit) || code_unit == 0x3000;
}

static size_t length_of_trailing_ascii_whitespace_run(Utf16View const& string)
{
    size_t length = 0;
    while (length < string.length_in_code_units() && is_ascii_space(string.code_unit_at(string.length_in_code_units() - length - 1)))
        ++length;
    return length;
}

static size_t length_of_trailing_whitespace_run(Utf16View const& string)
{
    size_t length = 0;
    while (length < string.length_in_code_units() && is_trailing_space(string.code_unit_at(string.length_in_code_units() - length - 1)))
        ++length;
    return length;
}

struct TrailingWhitespace {
    size_t length_in_code_units { 0 };
    float advance { 0 };
    // The advance of the ASCII white space at the very end alone, which intrinsic sizing takes off, since an
    // ideographic space that hangs at the end of a line still counts toward its intrinsic sizes.
    float ascii_advance { 0 };
};

struct ShapedGlyphs {
    Vector<ShapedGlyph> glyphs;
    float width { 0 };
    TrailingWhitespace trailing_whitespace;
    bool requires_context_for_breaks { false };
};

static ShapedGlyphs build_origin_relative_shape(Utf16View const& string, Font const& font, FFI::TextType text_type, float letter_spacing, float word_spacing, FFI::JoiningContext joining_context, bool vertical_forms)
{
    auto const& metrics = font.pixel_metrics();
    auto* buffer = setup_text_shaping(string, font, text_type, letter_spacing, joining_context, vertical_forms);

    u32 glyph_count;
    auto const* glyph_info = hb_buffer_get_glyph_infos(buffer, &glyph_count);
    auto const* positions = hb_buffer_get_glyph_positions(buffer, &glyph_count);

    Vector<ShapedGlyph> glyphs;
    glyphs.ensure_capacity(glyph_count);
    FloatPoint point;
    bool requires_context_for_breaks = false;

    // The trailing whitespace advance is recorded so that trimming it at line end can subtract exactly what shaping
    // added, spacing included.
    TrailingWhitespace trailing_whitespace { .length_in_code_units = length_of_trailing_whitespace_run(string), .advance = 0 };
    auto first_trailing_whitespace_offset = string.length_in_code_units() - trailing_whitespace.length_in_code_units;
    auto first_trailing_ascii_whitespace_offset = string.length_in_code_units() - length_of_trailing_ascii_whitespace_run(string);

    auto is_right_to_left = hb_buffer_get_direction(buffer) == HB_DIRECTION_RTL;
    auto cluster_length_in_code_units = [&](auto index) -> size_t {
        auto starting_offset = glyph_info[index].cluster;
        if (is_right_to_left) {
            for (size_t i = index; i-- > 0;) {
                if (auto offset = glyph_info[i].cluster; offset != starting_offset)
                    return offset - starting_offset;
            }
        } else {
            for (size_t i = index + 1; i < glyph_count; ++i) {
                if (auto offset = glyph_info[i].cluster; offset != starting_offset)
                    return offset - starting_offset;
            }
        }

        return string.length_in_code_units() - starting_offset;
    };

    auto glyph_length_in_code_units = [&](auto index) -> size_t {
        if (index > 0 && glyph_info[index - 1].cluster == glyph_info[index].cluster)
            return 0;
        return cluster_length_in_code_units(index);
    };

    // A glyph is left unpainted only when everything in its cluster is default-ignorable. A cluster that merely starts
    // with one, such as a Hangul syllable whose initial is the choseong filler, still shows its other characters.
    auto should_paint_glyph = [&](auto index) {
        auto starting_offset = glyph_info[index].cluster;
        if (starting_offset >= string.length_in_code_units())
            return true;
        auto has_hangul_filler = false;
        for (auto code_point : string.substring_view(starting_offset, cluster_length_in_code_units(index))) {
            if (is_hangul_filler(code_point)) {
                has_hangul_filler = true;
                continue;
            }
            if (!Unicode::code_point_has_default_ignorable_code_point_property(code_point))
                return true;
        }
        // AD-HOC: The Hangul fillers have the Default_Ignorable_Code_Point property, but fonts give them a spacing
        //         glyph, and a filler that stands alone takes that glyph's advance. A filler no font has a glyph for
        //         stays invisible, rather than showing the missing-glyph box.
        return has_hangul_filler && glyph_info[index].codepoint != 0;
    };

    // NB: HarfBuzz positions glyphs in font space, where y grows upward, so its y offsets and advances are negated
    //     for our coordinates, where y grows downward.
    bool should_paint = true;
    for (size_t i = 0; i < glyph_count; ++i) {
        // Every glyph of a cluster gets the same answer, so it's worked out once, at the cluster's first glyph.
        if (i == 0 || glyph_info[i - 1].cluster != glyph_info[i].cluster)
            should_paint = should_paint_glyph(i);
        auto glyph_length = glyph_length_in_code_units(i);
        requires_context_for_breaks |= glyph_length > 1
            || (hb_glyph_info_get_glyph_flags(&glyph_info[i]) & HB_GLYPH_FLAG_UNSAFE_TO_BREAK);
        auto position = point
            - FloatPoint { 0, metrics.ascent }
            + FloatPoint { positions[i].x_offset, -positions[i].y_offset } / text_shaping_resolution;

        // https://drafts.csswg.org/css-text-3/#letter-spacing-property
        // This property specifies additional spacing (commonly called tracking) between adjacent typographic character
        // units.
        // NB: A cluster's glyphs (a base and its marks, or a conjunct's parts) are one typographic character unit, so
        //     the spacing goes after the cluster's last glyph only. Spacing after any other glyph of the cluster would
        //     push the glyphs after it away from the ones they attach to.
        auto is_last_glyph_of_cluster = i + 1 == glyph_count || glyph_info[i + 1].cluster != glyph_info[i].cluster;
        float extra_advance = 0;
        if (is_last_glyph_of_cluster) {
            if (letter_spacing != 0 && cluster_takes_letter_spacing(string, glyph_info[i].cluster))
                extra_advance = letter_spacing;
            if (auto starting_offset = glyph_info[i].cluster; starting_offset < string.length_in_code_units()
                && is_word_separator(string.code_point_at(starting_offset)))
                extra_advance += word_spacing;
        }

        glyphs.unchecked_append({
            .position = position,
            .length_in_code_units = glyph_length,
            .glyph_width = should_paint ? positions[i].x_advance / text_shaping_resolution + extra_advance : 0,
            .glyph_id = glyph_info[i].codepoint,
            .cluster_start = glyph_info[i].cluster,
            .should_paint = should_paint,
            .is_rtl = is_right_to_left,
        });

        if (!should_paint)
            continue;

        point += FloatPoint { positions[i].x_advance, -positions[i].y_advance } / text_shaping_resolution;

        // NOTE: The spec says that we "really should not" apply letter-spacing to the trailing edge of a line but
        //       other browsers do so we will as well. https://drafts.csswg.org/css-text/#example-7880704e
        point.translate_by(extra_advance, 0);

        if (glyph_info[i].cluster >= first_trailing_whitespace_offset)
            trailing_whitespace.advance += glyphs.last().glyph_width;
        if (glyph_info[i].cluster >= first_trailing_ascii_whitespace_offset)
            trailing_whitespace.ascii_advance += glyphs.last().glyph_width;
    }

    hb_buffer_destroy(buffer);

    return ShapedGlyphs { move(glyphs), point.x(), trailing_whitespace, requires_context_for_breaks };
}

float measure_text_width(Utf16View const& string, Font const& font, float letter_spacing)
{
    auto* buffer = setup_text_shaping(string, font, FFI::TextType::Common, letter_spacing);

    u32 glyph_count;
    auto const* glyph_info = hb_buffer_get_glyph_infos(buffer, &glyph_count);
    auto const* positions = hb_buffer_get_glyph_positions(buffer, &glyph_count);

    double point_x = 0;
    size_t cluster_count = 0;
    for (size_t i = 0; i < glyph_count; ++i) {
        point_x += positions[i].x_advance;
        if (letter_spacing != 0 && (i + 1 == glyph_count || glyph_info[i + 1].cluster != glyph_info[i].cluster)
            && cluster_takes_letter_spacing(string, glyph_info[i].cluster))
            ++cluster_count;
    }

    hb_buffer_destroy(buffer);
    return static_cast<float>(point_x / text_shaping_resolution + cluster_count * letter_spacing);
}

}

static_assert(sizeof(Gfx::FFI::ShapedGlyph) == sizeof(Gfx::ShapedGlyph));
static_assert(alignof(Gfx::FFI::ShapedGlyph) == alignof(Gfx::ShapedGlyph));
static_assert(IsTriviallyCopyable<Gfx::FFI::ShapedGlyph>);
static_assert(IsTriviallyCopyable<Gfx::ShapedGlyph>);
static_assert(sizeof(Gfx::FloatPoint) == 2 * sizeof(float));
static_assert(offsetof(Gfx::FFI::ShapedGlyph, x) == offsetof(Gfx::ShapedGlyph, position));
static_assert(offsetof(Gfx::FFI::ShapedGlyph, y) == offsetof(Gfx::ShapedGlyph, position) + sizeof(float));
static_assert(offsetof(Gfx::FFI::ShapedGlyph, length_in_code_units) == offsetof(Gfx::ShapedGlyph, length_in_code_units));
static_assert(offsetof(Gfx::FFI::ShapedGlyph, glyph_width) == offsetof(Gfx::ShapedGlyph, glyph_width));
static_assert(offsetof(Gfx::FFI::ShapedGlyph, glyph_id) == offsetof(Gfx::ShapedGlyph, glyph_id));
static_assert(offsetof(Gfx::FFI::ShapedGlyph, should_paint) == offsetof(Gfx::ShapedGlyph, should_paint));

extern "C" {
void ladybird_gfx_shape_text_uncached(void const*, u16 const*, size_t, Gfx::FFI::TextType, float, float, Gfx::FFI::JoiningContext, bool, void*, void (*)(void*, Gfx::FFI::ShapedGlyph const*, size_t, float, size_t, float, float, bool));
float ladybird_gfx_font_measure_text_width(void const*, u16 const*, size_t);
void ladybird_gfx_glyph_run_bounding_box(void const*, Gfx::FFI::ShapedGlyph const*, size_t, float, float*);
void ladybird_gfx_glyph_run_ink_bounding_box(void const*, Gfx::FFI::ShapedGlyph const*, size_t, float, float*);
void ladybird_gfx_glyph_run_glyph_intercepts(void const*, Gfx::FFI::ShapedGlyph const*, size_t, float, float, float, void*, void (*)(void*, float));
}

extern "C" void ladybird_gfx_shape_text_uncached(
    void const* font,
    u16 const* text_utf16,
    size_t length_in_code_units,
    Gfx::FFI::TextType text_type,
    float letter_spacing,
    float word_spacing,
    Gfx::FFI::JoiningContext joining_context,
    bool vertical_forms,
    void* sink,
    void (*emit)(void*, Gfx::FFI::ShapedGlyph const*, size_t, float, size_t, float, float, bool))
{
    VERIFY(font);
    VERIFY(text_utf16 || length_in_code_units == 0);
    VERIFY(emit);
    auto text = length_in_code_units == 0
        ? Utf16View {}
        : Utf16View { reinterpret_cast<char16_t const*>(text_utf16), length_in_code_units };
    auto shape = Gfx::build_origin_relative_shape(
        text,
        *static_cast<Gfx::Font const*>(font),
        text_type,
        letter_spacing,
        word_spacing,
        joining_context,
        vertical_forms);
    emit(
        sink,
        reinterpret_cast<Gfx::FFI::ShapedGlyph const*>(shape.glyphs.data()),
        shape.glyphs.size(),
        shape.width,
        shape.trailing_whitespace.length_in_code_units,
        shape.trailing_whitespace.advance,
        shape.trailing_whitespace.ascii_advance,
        shape.requires_context_for_breaks);
}

extern "C" float ladybird_gfx_font_measure_text_width(
    void const* font,
    u16 const* text_utf16,
    size_t length_in_code_units)
{
    VERIFY(font);
    VERIFY(text_utf16 || length_in_code_units == 0);
    auto text = length_in_code_units == 0
        ? Utf16View {}
        : Utf16View { reinterpret_cast<char16_t const*>(text_utf16), length_in_code_units };
    return Gfx::measure_text_width(text, *static_cast<Gfx::Font const*>(font));
}

extern "C" void ladybird_gfx_glyph_run_bounding_box(
    void const* font,
    Gfx::FFI::ShapedGlyph const* glyphs,
    size_t glyph_count,
    float scale,
    float* out_rect)
{
    VERIFY(font);
    VERIFY(glyphs || glyph_count == 0);
    VERIFY(out_rect);
    auto bounds = Gfx::glyph_run_bounding_box(
        *static_cast<Gfx::Font const*>(font),
        { reinterpret_cast<Gfx::ShapedGlyph const*>(glyphs), glyph_count },
        scale);
    out_rect[0] = bounds.x();
    out_rect[1] = bounds.y();
    out_rect[2] = bounds.width();
    out_rect[3] = bounds.height();
}

extern "C" void ladybird_gfx_glyph_run_ink_bounding_box(
    void const* font,
    Gfx::FFI::ShapedGlyph const* glyphs,
    size_t glyph_count,
    float scale,
    float* out_rect)
{
    VERIFY(font);
    VERIFY(glyphs || glyph_count == 0);
    VERIFY(out_rect);
    auto bounds = Gfx::glyph_run_ink_bounding_box(
        *static_cast<Gfx::Font const*>(font),
        { reinterpret_cast<Gfx::ShapedGlyph const*>(glyphs), glyph_count },
        scale);
    out_rect[0] = bounds.x();
    out_rect[1] = bounds.y();
    out_rect[2] = bounds.width();
    out_rect[3] = bounds.height();
}

extern "C" void ladybird_gfx_glyph_run_glyph_intercepts(
    void const* font,
    Gfx::FFI::ShapedGlyph const* glyphs,
    size_t glyph_count,
    float scale,
    float y_top,
    float y_bottom,
    void* sink,
    void (*push)(void*, float))
{
    VERIFY(font);
    VERIFY(glyphs || glyph_count == 0);
    VERIFY(push);
    auto intercepts = Gfx::glyph_run_glyph_intercepts(
        *static_cast<Gfx::Font const*>(font),
        { reinterpret_cast<Gfx::ShapedGlyph const*>(glyphs), glyph_count },
        scale,
        y_top,
        y_bottom);
    for (auto value : intercepts)
        push(sink, value);
}
static_assert(offsetof(Gfx::FFI::ShapedGlyph, cluster_start) == offsetof(Gfx::ShapedGlyph, cluster_start));
static_assert(offsetof(Gfx::FFI::ShapedGlyph, is_rtl) == offsetof(Gfx::ShapedGlyph, is_rtl));