dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / src / web / css / font_computer_2.lucb
#==============================================================================================
#
# font_computer_2 - CSS::FontComputer: font matching and the @font-feature-values of a family
#
# DESCRIPTION:
# Port of LibWeb/CSS/FontComputer.cpp (lines 299-473) and the inline members of
# FontComputer.h (lines 100-151): the constructor and document, visiting, the partial CSS
# font matching algorithm over the registered font faces and the font database (with its
# ascending and descending weight searches), and the @font-feature-values of a family.
#
# Copyright (c) 2018-2025, Andreas Kling <andreas@ladybird.org>
# Copyright (c) 2021, the SerenityOS developers.
# Copyright (c) 2021-2025, Sam Atkins <sam@ladybird.org>
# Copyright (c) 2024, Matthew Olsson <mattco@serenityos.org>
# Copyright (c) 2025, Callum Law <callumlaw1709@outlook.com>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: FontComputer.h ==========================================================================
## Ported from Libraries/LibWeb/CSS/FontComputer.h:105 Web::CSS::FontComputer::FontComputer.
pub func css_font_computer_construct(this: CssFontComputer*, document: DomDocument*):
this.m_document = document
## Ported from Libraries/LibWeb/CSS/FontComputer.h:112 Web::CSS::FontComputer::document.
pub func css_font_computer_document(this: CssFontComputer*) -> DomDocument*:
return this.m_document
## Ported from Libraries/LibWeb/CSS/FontComputer.h:113 Web::CSS::FontComputer::document.
pub func css_font_computer_document_const(this: CssFontComputer*) -> DomDocument*:
return this.m_document
# mark: Visiting and font matching ==============================================================
## Ported from Libraries/LibWeb/CSS/FontComputer.cpp:299 Web::CSS::FontComputer::visit_edges (override).
pub func css_font_computer_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
let this = (CssFontComputer*)base
gc.cell_visit_edges_impl(base, visitor)
gc.cell_visitor_visit_t_2(visitor, this.m_document)
for entry in ak.hash_map_begin(&this.m_font_faces):
gc.cell_visitor_visit_vector(visitor, &entry.value)
for entry in ak.hash_map_begin(&this.m_loaders_by_url):
gc.cell_visitor_visit_t_2(visitor, entry.value)
## Ported from Libraries/LibWeb/CSS/FontComputer.cpp:309 Web::CSS::FontComputer::find_matching_font_weight_ascending.
func css_font_computer_find_matching_font_weight_ascending(this: CssFontComputer*, candidates: const ak.Vector[CssFontComputerMatchingFontCandidate]*, target_weight: i32, font_size_in_pt: f32, variations: const web_fonts.FontVariationSettings*, font_feature_data: const CssFontFeatureData*, font_feature_values: const ak.HashMap[CssFontFeatureValueKey, ak.Vector[u32], CssFontFeatureValueKeyTraits]*, inclusive: bool) -> const web_fonts.FontCascadeList*?:
# auto pred = inclusive ? weight.min >= target_weight : weight.min > target_weight;
# auto it = find_if(candidates.begin(), candidates.end(), pred);
let span = ak.vector_span_const(candidates)
var it: usize = 0
while it < span.length:
let min = span[it].key.weight.min
if (min >= target_weight) if inclusive else (min > target_weight):
break
it += 1
while it < span.length:
if let found_font = css_font_computer_matching_font_candidate_font_with_point_size(&span[it], &this.m_font_faces, font_size_in_pt, variations, font_feature_data, font_feature_values):
return found_font
it += 1
return none
## Ported from Libraries/LibWeb/CSS/FontComputer.cpp:322 Web::CSS::FontComputer::find_matching_font_weight_descending.
func css_font_computer_find_matching_font_weight_descending(this: CssFontComputer*, candidates: const ak.Vector[CssFontComputerMatchingFontCandidate]*, target_weight: i32, font_size_in_pt: f32, variations: const web_fonts.FontVariationSettings*, font_feature_data: const CssFontFeatureData*, font_feature_values: const ak.HashMap[CssFontFeatureValueKey, ak.Vector[u32], CssFontFeatureValueKeyTraits]*, inclusive: bool) -> const web_fonts.FontCascadeList*?:
# auto pred = inclusive ? weight.max <= target_weight : weight.max < target_weight;
# auto it = find_if(candidates.rbegin(), candidates.rend(), pred);
let span = ak.vector_span_const(candidates)
var remaining = span.length
while remaining > 0:
let max = span[remaining - 1].key.weight.max
if (max <= target_weight) if inclusive else (max < target_weight):
break
remaining -= 1
while remaining > 0:
if let found_font = css_font_computer_matching_font_candidate_font_with_point_size(&span[remaining - 1], &this.m_font_faces, font_size_in_pt, variations, font_feature_data, font_feature_values):
return found_font
remaining -= 1
return none
## The captures of the callback font_matching_algorithm gives
## FontDatabase::for_each_typeface_with_family_name.
struct CssFontComputerFontMatchingAlgorithmSystemTypefaces:
var matching_family_fonts: ak.Vector[CssFontComputerMatchingFontCandidate]*
static func call(context: void*?, typeface: web_fonts.Typeface*):
let captures = (CssFontComputerFontMatchingAlgorithmSystemTypefaces*)(context else trap("no captures"))
# FIXME: Support system fonts that have a range of weights, etc.
let weight = CssFontWeightRange(min = (i32)web_fonts.typeface_weight(typeface), max = (i32)web_fonts.typeface_weight(typeface))
let key = css_font_face_key_new(web_fonts.typeface_family(typeface), weight, (i32)web_fonts.typeface_slope(typeface), 100)
ak.vector_append_t(captures.matching_family_fonts, CssFontComputerMatchingFontCandidate(key = key, width = (u32)web_fonts.typeface_width(typeface), system_typeface = typeface))
## A candidate predicate of font_matching_algorithm over one value (a width or a slope).
struct CssFontComputerFontMatchingAlgorithmCandidateIs:
var value: i64
## `matching_font_candidate.width != desired_width`.
static func width_differs(context: void*?, candidate: const CssFontComputerMatchingFontCandidate*) -> bool:
let captures = (CssFontComputerFontMatchingAlgorithmCandidateIs*)(context else trap("no captures"))
return (i64)candidate.width != captures.value
## `matching_font_candidate.key.slope != slope`.
static func slope_differs(context: void*?, candidate: const CssFontComputerMatchingFontCandidate*) -> bool:
let captures = (CssFontComputerFontMatchingAlgorithmCandidateIs*)(context else trap("no captures"))
return (i64)candidate.key.slope != captures.value
## font_matching_algorithm's quick_sort comparator: `a.key.weight.min < b.key.weight.min`.
func css_font_computer_candidate_weight_less_than(context: void*?, a: const CssFontComputerMatchingFontCandidate*, b: const CssFontComputerMatchingFontCandidate*) -> bool:
return a.key.weight.min < b.key.weight.min
## Ported from Libraries/LibWeb/CSS/FontComputer.cpp:337 Web::CSS::FontComputer::font_matching_algorithm.
# Partial implementation of the font-matching algorithm: https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm
# FIXME: This should be replaced by the full CSS font selection algorithm.
func css_font_computer_font_matching_algorithm(this: CssFontComputer*, family_name: ak.FlyString, weight: i32, font_width: CssPercentage, slope: i32, font_size_in_pt: f32, variations: const web_fonts.FontVariationSettings*, font_feature_data: const CssFontFeatureData*, font_feature_values: const ak.HashMap[CssFontFeatureValueKey, ak.Vector[u32], CssFontFeatureValueKeyTraits]*) -> const web_fonts.FontCascadeList*?:
# If a font family match occurs, the user agent assembles the set of font faces in that family and then
# narrows the set to a single face using other font properties in the order given below.
var matching_family_fonts: ak.Vector[CssFontComputerMatchingFontCandidate]
# FIXME: URL-backed faces with no typeface yet should trigger a load on demand, matching other engines.
for entry in ak.hash_map_begin(&this.m_font_faces):
if ak.fly_string_equals_ignoring_ascii_case_fly_string(&entry.key.family_name, &family_name):
ak.vector_append_t(&matching_family_fonts, css_font_computer_matching_font_candidate_new(entry.key))
ak.vector_last(&matching_family_fonts).width = css_font_width_bucket_from_percentage((f64)entry.key.width)
var system_typefaces = CssFontComputerFontMatchingAlgorithmSystemTypefaces(matching_family_fonts = &matching_family_fonts)
web_fonts.font_database_for_each_typeface_with_family_name(web_fonts.font_database_the(), family_name, ak.Function1[web_fonts.Typeface*, unit](call = CssFontComputerFontMatchingAlgorithmSystemTypefaces.call, context = &system_typefaces))
if ak.vector_is_empty(&matching_family_fonts):
return none
# 1. font-width is tried first.
let desired_width = css_font_width_bucket_from_percentage(css_percentage_value(&font_width))
var width_predicate = CssFontComputerFontMatchingAlgorithmCandidateIs(value = (i64)desired_width)
var has_desired_width = false
for candidate in ak.vector_span_const(&matching_family_fonts):
if candidate.width == desired_width:
has_desired_width = true
break
if has_desired_width:
_ = ak.vector_remove_all_matching(&matching_family_fonts, ak.Function1[const CssFontComputerMatchingFontCandidate*, bool](call = CssFontComputerFontMatchingAlgorithmCandidateIs.width_differs, context = &width_predicate))
ak.quick_sort_t_collection_t_less_than(ak.vector_span(&matching_family_fonts), ak.Function2[const CssFontComputerMatchingFontCandidate*, const CssFontComputerMatchingFontCandidate*, bool](call = css_font_computer_candidate_weight_less_than, context = none))
# 2. font-style is tried next.
# We don't have complete support of italic and oblique fonts, so matching on font-style can be simplified to:
# If a matching slope is found, all faces which don't have that matching slope are excluded from the matching set.
var slope_predicate = CssFontComputerFontMatchingAlgorithmCandidateIs(value = (i64)slope)
var has_slope = false
for candidate in ak.vector_span_const(&matching_family_fonts):
if candidate.key.slope == slope:
has_slope = true
break
if has_slope:
_ = ak.vector_remove_all_matching(&matching_family_fonts, ak.Function1[const CssFontComputerMatchingFontCandidate*, bool](call = CssFontComputerFontMatchingAlgorithmCandidateIs.slope_differs, context = &slope_predicate))
# 3. font-weight is matched next.
# If a font does not have any concept of varying strengths of weights, its weight is mapped according list in the
# property definition. If bolder/lighter relative weights are used, the effective weight is calculated based on
# the inherited weight value, as described in the definition of the font-weight property.
# FIXME: "varying strengths of weights"
# If the matching set after performing the steps above includes faces with weight values containing the
# font-weight desired value, faces with weight values which do not include the desired font-weight value are
# removed from the matching set.
let candidates = ak.vector_span_const(&matching_family_fonts)
# FIXME: This whole function currently just returns the first match instead of progressing further, so we'll do that here too.
var matching_weight_it: usize = 0
while matching_weight_it < candidates.length and not css_font_weight_range_contains_inclusive(&candidates[matching_weight_it].key.weight, weight):
matching_weight_it += 1
while matching_weight_it < candidates.length:
if let found_font = css_font_computer_matching_font_candidate_font_with_point_size(&candidates[matching_weight_it], &this.m_font_faces, font_size_in_pt, variations, font_feature_data, font_feature_values):
return found_font
matching_weight_it += 1
# If there is no face which contains the desired value, a weight value is chosen using the rules below:
# - If the desired weight is inclusively between 400 and 500, weights greater than or equal to the target weight
# are checked in ascending order until 500 is hit and checked, followed by weights less than the target weight
# in descending order, followed by weights greater than 500, until a match is found.
if weight >= 400 and weight <= 500:
var it: usize = 0
while it < candidates.length and not (candidates[it].key.weight.min >= weight):
it += 1
while it < candidates.length and candidates[it].key.weight.min <= 500:
if let found_font = css_font_computer_matching_font_candidate_font_with_point_size(&candidates[it], &this.m_font_faces, font_size_in_pt, variations, font_feature_data, font_feature_values):
return found_font
it += 1
if let found_font = css_font_computer_find_matching_font_weight_descending(this, &matching_family_fonts, weight, font_size_in_pt, variations, font_feature_data, font_feature_values, false):
return found_font
while it < candidates.length:
if let found_font = css_font_computer_matching_font_candidate_font_with_point_size(&candidates[it], &this.m_font_faces, font_size_in_pt, variations, font_feature_data, font_feature_values):
return found_font
it += 1
# - If the desired weight is less than 400, weights less than or equal to the desired weight are checked in
# descending order followed by weights above the desired weight in ascending order until a match is found.
if weight < 400:
if let found_font = css_font_computer_find_matching_font_weight_descending(this, &matching_family_fonts, weight, font_size_in_pt, variations, font_feature_data, font_feature_values, true):
return found_font
if let found_font = css_font_computer_find_matching_font_weight_ascending(this, &matching_family_fonts, weight, font_size_in_pt, variations, font_feature_data, font_feature_values, false):
return found_font
# - If the desired weight is greater than 500, weights greater than or equal to the desired weight are checked in
# ascending order followed by weights below the desired weight in descending order until a match is found.
if weight > 500:
if let found_font = css_font_computer_find_matching_font_weight_ascending(this, &matching_family_fonts, weight, font_size_in_pt, variations, font_feature_data, font_feature_values, true):
return found_font
if let found_font = css_font_computer_find_matching_font_weight_descending(this, &matching_family_fonts, weight, font_size_in_pt, variations, font_feature_data, font_feature_values, false):
return found_font
return none
## The captures of the callback font_feature_values_for_family gives
## StyleScope::for_each_active_css_style_sheet.
struct CssFontComputerFontFeatureValuesForFamilySheets:
var family_name: ak.FlyString
var font_feature_values: ak.HashMap[CssFontFeatureValueKey, ak.Vector[u32], CssFontFeatureValueKeyTraits]*
static func call(context: void*?, sheet: CssCssStyleSheet*):
let captures = (CssFontComputerFontFeatureValuesForFamilySheets*)(context else trap("no captures"))
# FIXME: Account for @font-feature-values within grouping (i.e. @media, @supports) rules as well.
let rules = css_css_style_sheet_rules(sheet)
for i in 0..<css_rule_list_length(rules):
let rule = css_rule_list_item(rules, i) else trap("null rule")
if let font_feature_values_rule = as_if_css_font_feature_values_rule(rule):
let families = css_font_feature_values_rule_font_families(font_feature_values_rule)
if not ak.vector_contains_slow[ak.FlyString, ak.FlyStringTraits](&families, captures.family_name):
continue
let rule_values = css_font_feature_values_rule_to_hash_map(font_feature_values_rule)
ak.hash_map_update(captures.font_feature_values, &rule_values)
## The captures of the initialization callback font_feature_values_for_family gives HashMap::ensure.
struct CssFontComputerFontFeatureValuesForFamily:
var this: CssFontComputer*
var family_name: ak.FlyString
static func call(context: void*?) -> ak.HashMap[CssFontFeatureValueKey, ak.Vector[u32], CssFontFeatureValueKeyTraits]:
let captures = (CssFontComputerFontFeatureValuesForFamily*)(context else trap("no captures"))
var font_feature_values: ak.HashMap[CssFontFeatureValueKey, ak.Vector[u32], CssFontFeatureValueKeyTraits]
# https://drafts.csswg.org/css-fonts/#font-feature-values-syntax
# For each <family-name> in the @font-feature-values prelude, each font feature value declaration defines a
# mapping between a (family name, feature block name, declaration name) tuple and the list of one or more
# integers from the declaration’s value. If the same tuple appears more than once in a document (such as if a
# single block), the last-defined one is used.
# FIXME: We only account for Author stylesheets here, we should also account for UserAgent and User
var sheets = CssFontComputerFontFeatureValuesForFamilySheets(family_name = captures.family_name, font_feature_values = &font_feature_values)
css_style_scope_for_each_active_css_style_sheet(dom_document_style_scope(captures.this.m_document), ak.Function1[CssCssStyleSheet*, unit](call = CssFontComputerFontFeatureValuesForFamilySheets.call, context = &sheets))
return font_feature_values
## Ported from Libraries/LibWeb/CSS/FontComputer.cpp:445 Web::CSS::FontComputer::font_feature_values_for_family.
func css_font_computer_font_feature_values_for_family(this: CssFontComputer*, family_name: ak.FlyString) -> const ak.HashMap[CssFontFeatureValueKey, ak.Vector[u32], CssFontFeatureValueKeyTraits]*:
var captures = CssFontComputerFontFeatureValuesForFamily(this = this, family_name = family_name)
_ = ak.hash_map_ensure_t_callback(&this.m_font_feature_values_cache, family_name, ak.Function0[ak.HashMap[CssFontFeatureValueKey, ak.Vector[u32], CssFontFeatureValueKeyTraits]](call = CssFontComputerFontFeatureValuesForFamily.call, context = &captures))
return ak.hash_map_get_k(&this.m_font_feature_values_cache, family_name) else trap("VERIFY: Optional::value()")