Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / platform / font_plugin.lucb

#==============================================================================================
#
#   font_plugin - Platform::FontPlugin: the default and generic font families
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Platform/FontPlugin.cpp (lines 1-206) with the inline members
#       of FontPlugin.h (line 55) and its AK::Traits<GenericFontKey> (lines 71-77, in
#       generated/types_traits.lucb). In layout test mode every generic family is SerenitySans
#       and the symbol font is Noto Emoji (DESIGN.md §6.1).
#
#       The plugin is process-wide and outlives every VM, as the font database does: it lives
#       in the C heap (the embedder allocates it there) and so do its tables, whatever allocator
#       is current, and the fonts it holds come from the database's C-heap typefaces
#       (DESIGN.md §3.3 rule 7, luce-browser-render's web_fonts/font_allocators.lucb).
#
#       Copyright (c) 2022, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: The plugin ==============================================================================

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:25 Web::Platform::FontPlugin::the.
pub func platform_font_plugin_the() -> PlatformFontPlugin*:
    return platform_s_the_3 else trap("VERIFY: no FontPlugin installed")

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:31 Web::Platform::FontPlugin::install.
pub func platform_font_plugin_install(plugin: PlatformFontPlugin*):
    assert(platform_s_the_3 == none)
    platform_s_the_3 = plugin

## `Vector<FlyString> { "..."_fly_string, ... }`.
func platform_font_plugin_fly_strings(names: const str[]) -> ak.Vector[ak.FlyString]:
    var vector: ak.Vector[ak.FlyString]
    for name in names:
        ak.vector_append_t(&vector, ak.fly_string_from_str(name))
    return vector

## `MUST(String::formatted("file://{}", path))`.
func platform_font_plugin_file_uri(path: const ak.String*) -> ak.String:
    var builder = ak.string_builder_new()
    ak.string_builder_append(&builder, "file://")
    ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(path))
    return ak.string_builder_to_string(&builder) else trap("MUST: String::formatted")

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:37 Web::Platform::FontPlugin::FontPlugin.
## `this` is in the C heap; what the plugin keeps is allocated there too.
pub func platform_font_plugin_construct(this: PlatformFontPlugin*, is_layout_test_mode: bool, font_provider: web_fonts.SystemFontProvider*? = none):
    let c_heap = web_fonts.font_allocators_c_heap()
    let previous = web_fonts.font_allocators_enter(&c_heap)
    defer web_fonts.font_allocators_leave(previous)
    with memory.heap:
        platform_font_plugin_construct_impl(this, is_layout_test_mode, font_provider)

## The body of FontPlugin::FontPlugin.
func platform_font_plugin_construct_impl(this: PlatformFontPlugin*, is_layout_test_mode: bool, font_provider: web_fonts.SystemFontProvider*?):
    this.m_is_layout_test_mode = is_layout_test_mode

    var provider = font_provider
    if provider == none:
        let path_font_provider = web_fonts.path_font_provider_create()
        provider = web_fonts.font_database_install_system_font_provider(web_fonts.font_database_the(), (web_fonts.SystemFontProvider*)path_font_provider)
    let system_font_provider = provider else trap("VERIFY: font provider")
    if let path_font_provider = web_fonts.as_if_path_font_provider(system_font_provider):
        # Load anything we can find in the system's font directories
        let font_directories = web_fonts.font_database_font_directories() else trap("FIXME: should propagate errors")
        for path in ak.vector_span_const(&font_directories):
            let uri = platform_font_plugin_file_uri(&path)
            web_fonts.path_font_provider_load_all_fonts_from_uri(path_font_provider, ak.string_bytes_as_string_view(&uri))

    platform_font_plugin_update_generic_fonts(this)

    let default_fixed_width_font_name = platform_font_plugin_generic_font_name(this, PlatformGenericFont.ui_monospace, 400, 0)
    this.m_default_fixed_width_font = web_fonts.font_database_get(web_fonts.font_database_the(), default_fixed_width_font_name, 12.0, 400, (u32)web_fonts.FontWidth.normal, 0)
    assert(this.m_default_fixed_width_font != none)

    if is_layout_test_mode:
        this.m_symbol_font_names = platform_font_plugin_fly_strings(["Noto Emoji"])
    else:
        if os.macos:
            this.m_symbol_font_names = platform_font_plugin_fly_strings(["Apple Color Emoji", "Apple Symbols"])
        else:
            this.m_symbol_font_names = platform_font_plugin_fly_strings(["Noto Color Emoji", "Noto Sans Symbols"])

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:68 Web::Platform::FontPlugin::default_font.
pub func platform_font_plugin_default_font(this: PlatformFontPlugin*, point_size: f32, font_variation_settings: web_fonts.FontVariationSettings? = none, shape_features: ak.Vector[web_fonts.ShapeFeature]? = none) -> web_fonts.Font*?:
    let font_name = platform_font_plugin_generic_font_name(this, PlatformGenericFont.ui_sans_serif, 400, 0)
    return web_fonts.font_database_get(web_fonts.font_database_the(), font_name, point_size, 400, (u32)web_fonts.FontWidth.normal, 0, font_variation_settings, shape_features)

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:74 Web::Platform::FontPlugin::default_fixed_width_font.
pub func platform_font_plugin_default_fixed_width_font(this: PlatformFontPlugin*) -> web_fonts.Font*:
    return this.m_default_fixed_width_font else trap("VERIFY: m_default_fixed_width_font")

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:79 Web::Platform::FontPlugin::symbol_font_names.
pub func platform_font_plugin_symbol_font_names(this: PlatformFontPlugin*) -> ak.Vector[ak.FlyString]:
    return ak.vector_clone(&this.m_symbol_font_names)

## Ported from Libraries/LibWeb/Platform/FontPlugin.h:55 Web::Platform::FontPlugin::is_layout_test_mode.
pub func platform_font_plugin_is_layout_test_mode(this: const PlatformFontPlugin*) -> bool:
    return this.m_is_layout_test_mode

# mark: Generic font families ===================================================================

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:84 Web::Platform::FontPlugin::update_generic_fonts.
## The fallback lists are kept in the C heap with the plugin.
pub func platform_font_plugin_update_generic_fonts(this: PlatformFontPlugin*):
    let c_heap = web_fonts.font_allocators_c_heap()
    let previous = web_fonts.font_allocators_enter(&c_heap)
    defer web_fonts.font_allocators_leave(previous)
    with memory.heap:
        platform_font_plugin_update_generic_fonts_impl(this)

## The body of FontPlugin::update_generic_fonts.
func platform_font_plugin_update_generic_fonts_impl(this: PlatformFontPlugin*):
    # Store fallback font lists for each generic font category.
    # The actual font selection happens in generic_font_name() based on the requested style.

    ak.vector_resize(&this.m_generic_font_fallbacks, (usize)PlatformGenericFont.count)

    # Fallback fonts to look for if Gfx::Font can't load expected font.
    # The lists are basically arbitrary, taken from https://www.w3.org/Style/Examples/007/fonts.en.html
    # (We also add Android-specific font names to the list from W3 where required.)
    let cursive_fallbacks = platform_font_plugin_fly_strings(["Comic Sans MS", "Comic Sans", "Apple Chancery", "Bradley Hand", "Brush Script MT", "Snell Roundhand", "URW Chancery L", "Dancing Script"])
    let fantasy_fallbacks = platform_font_plugin_fly_strings(["Impact", "Luminari", "Chalkduster", "Jazz LET", "Blippo", "Stencil Std", "Marker Felt", "Trattatello", "Coming Soon"])
    let monospace_fallbacks = platform_font_plugin_fly_strings(["Andale Mono", "Courier New", "Courier", "FreeMono", "OCR A Std", "Noto Sans Mono", "DejaVu Sans Mono", "Droid Sans Mono", "Liberation Mono"])
    let sans_serif_fallbacks = platform_font_plugin_fly_strings(["Arial", "Helvetica", "Verdana", "Trebuchet MS", "Gill Sans", "Noto Sans", "Avantgarde", "Optima", "Arial Narrow", "Liberation Sans", "Roboto"])
    let serif_fallbacks = platform_font_plugin_fly_strings(["Times", "Times New Roman", "Didot", "Georgia", "Palatino", "Bookman", "New Century Schoolbook", "American Typewriter", "Liberation Serif", "Roman", "Noto Serif"])

    # auto fallback_set = [&](GenericFont font) -> Vector<FlyString>& { return m_generic_font_fallbacks[to_underlying(font)]; };
    let fallbacks = &this.m_generic_font_fallbacks
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.cursive) = cursive_fallbacks
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.fantasy) = fantasy_fallbacks
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.monospace) = monospace_fallbacks
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.sans_serif) = sans_serif_fallbacks
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.serif) = serif_fallbacks
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.ui_monospace) = ak.vector_clone(ak.vector_at(fallbacks, (usize)PlatformGenericFont.monospace))
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.ui_rounded) = ak.vector_clone(ak.vector_at(fallbacks, (usize)PlatformGenericFont.sans_serif))
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.ui_sans_serif) = ak.vector_clone(ak.vector_at(fallbacks, (usize)PlatformGenericFont.sans_serif))
    *ak.vector_at(fallbacks, (usize)PlatformGenericFont.ui_serif) = ak.vector_clone(ak.vector_at(fallbacks, (usize)PlatformGenericFont.serif))

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:115 Web::Platform::FontPlugin::generic_font_name.
## `m_generic_font_cache.ensure(key, [&] { return compute_generic_font_name(...); })`, as a
## lookup, the computation in the current allocator, then the insertion in the C heap with the
## plugin (FlyStrings are valid anywhere).
pub func platform_font_plugin_generic_font_name(this: PlatformFontPlugin*, generic_font: PlatformGenericFont, weight: i32, slope: i32) -> ak.FlyString:
    if this.m_is_layout_test_mode:
        return ak.fly_string_from_str("SerenitySans")

    let key = PlatformGenericFontKey(generic_font = generic_font, weight = weight, slope = slope)
    if let cached = ak.hash_map_get_k(&this.m_generic_font_cache, key):
        return *cached
    let name = platform_font_plugin_compute_generic_font_name(this, generic_font, weight, slope)
    let c_heap = web_fonts.font_allocators_c_heap()
    let previous = web_fonts.font_allocators_enter(&c_heap)
    defer web_fonts.font_allocators_leave(previous)
    with memory.heap:
        _ = ak.hash_map_set(&this.m_generic_font_cache, key, name)
    return name

## The lambda FontPlugin::compute_generic_font_name passes to
## FontDatabase::for_each_typeface_with_family_name: the style a family offers.
struct PlatformFontPluginTypefaceStyles:
    var weight: i32
    var slope: i32
    var has_requested_weight: bool
    var has_requested_slope: bool
    var available_weights: ak.HashTable[u16, ak.U16Traits]

    static func call(context: void*?, typeface: web_fonts.Typeface*):
        let captures = (PlatformFontPluginTypefaceStyles*)(context else trap("for_each_typeface_with_family_name: no captures"))
        _ = ak.hash_table_set(&captures.available_weights, web_fonts.typeface_weight(typeface))
        if web_fonts.typeface_weight(typeface) == (u16)captures.weight:
            captures.has_requested_weight = true
        if web_fonts.typeface_slope(typeface) == (u8)captures.slope:
            captures.has_requested_slope = true

## Ported from Libraries/LibWeb/Platform/FontPlugin.cpp:126 Web::Platform::FontPlugin::compute_generic_font_name.
pub func platform_font_plugin_compute_generic_font_name(this: PlatformFontPlugin*, generic_font: PlatformGenericFont, weight: i32, slope: i32) -> ak.FlyString:
    # https://drafts.csswg.org/css-fonts-4/#generic-font-families
    # User agents should provide reasonable default choices for the generic font families, that express the
    # characteristics of each family as well as possible, within the limits allowed by the underlying technology.
    # NB: We prefer fonts that support the requested weight and slope, falling back to fonts with more style variety.

    let fallbacks = ak.vector_span_const(ak.vector_at(&this.m_generic_font_fallbacks, (usize)generic_font))

    let generic_family_name = match generic_font:
        .cursive => "cursive"
        .fantasy => "fantasy"
        .monospace, .ui_monospace => "monospace"
        .sans_serif, .ui_rounded, .ui_sans_serif => "sans-serif"
        .serif, .ui_serif => "serif"
        _ => trap("VERIFY_NOT_REACHED")

    if let name = web_fonts.typeface_skia_resolve_generic_family(ak.sv(generic_family_name), (u16)weight, (u8)slope):
        if web_fonts.font_database_get(web_fonts.font_database_the(), name, 16.0, (u32)weight, (u32)web_fonts.FontWidth.normal, (u32)slope) != none:
            return name

    # Score each fallback family based on how well it can satisfy the requested style.
    # Higher score = better match.
    var best_family = ak.fly_string_new()
    var best_score: i32 = -1

    for family in fallbacks:
        var score: i32 = 0
        var styles = PlatformFontPluginTypefaceStyles(weight = weight, slope = slope)

        web_fonts.font_database_for_each_typeface_with_family_name(web_fonts.font_database_the(), family, ak.Function1[web_fonts.Typeface*, unit](call = PlatformFontPluginTypefaceStyles.call, context = &styles))

        # Strongly prefer families that have the exact requested weight.
        if styles.has_requested_weight:
            score += 1000

        # Prefer families that have the exact requested slope.
        if styles.has_requested_slope:
            score += 100

        # As a tiebreaker, prefer families with more weight variety.
        # This helps select fonts that can handle both regular and bold text.
        score += (i32)ak.hash_table_size(&styles.available_weights)

        if score > best_score:
            best_score = score
            best_family = family

    return best_family