Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / css / font_face_1.lucb

#==============================================================================================
#
#   font_face_1 - CSS::FontFace: creating font faces, from script or from an @font-face rule
#
#   DESCRIPTION:
#       Port of LibWeb/CSS/FontFace.cpp (lines 1-408) and the inline members of FontFace.h
#       (lines 20-171): the descriptor computations, load_vector_font, the FontFace
#       constructor (its BinaryData branch with the asynchronous parse), CSS-connected faces,
#       the ParsedFontFace of a face, visiting, the status promise, the font computer of the
#       face's sets and the fonts of a face at a size. A FontFace holds a promise, a JS object:
#       creating one traps in WebIDL::create_promise until phase 3.
#
#       Copyright (c) 2024, Andrew Kaster <akaster@serenityos.org>
#       Copyright (c) 2025-2026, Sam Atkins <sam@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: FontFace.h ==============================================================================

## Ported from Libraries/LibWeb/CSS/FontFace.h:44 Web::CSS::FontFace::family.
pub func css_font_face_family(this: CssFontFace*) -> ak.String:
    return this.m_family

## Ported from Libraries/LibWeb/CSS/FontFace.h:48 Web::CSS::FontFace::style.
pub func css_font_face_style(this: CssFontFace*) -> ak.String:
    return this.m_style

## Ported from Libraries/LibWeb/CSS/FontFace.h:52 Web::CSS::FontFace::weight.
pub func css_font_face_weight(this: CssFontFace*) -> ak.String:
    return this.m_weight

## Ported from Libraries/LibWeb/CSS/FontFace.h:56 Web::CSS::FontFace::stretch.
pub func css_font_face_stretch(this: CssFontFace*) -> ak.String:
    return this.m_stretch

## Ported from Libraries/LibWeb/CSS/FontFace.h:60 Web::CSS::FontFace::unicode_range.
pub func css_font_face_unicode_range(this: CssFontFace*) -> ak.String:
    return this.m_unicode_range

## Ported from Libraries/LibWeb/CSS/FontFace.h:64 Web::CSS::FontFace::feature_settings.
pub func css_font_face_feature_settings(this: CssFontFace*) -> ak.String:
    return this.m_feature_settings

## Ported from Libraries/LibWeb/CSS/FontFace.h:68 Web::CSS::FontFace::variation_settings.
pub func css_font_face_variation_settings(this: CssFontFace*) -> ak.String:
    return this.m_variation_settings

## Ported from Libraries/LibWeb/CSS/FontFace.h:72 Web::CSS::FontFace::display.
pub func css_font_face_display(this: CssFontFace*) -> ak.String:
    return this.m_display

## Ported from Libraries/LibWeb/CSS/FontFace.h:76 Web::CSS::FontFace::ascent_override.
pub func css_font_face_ascent_override(this: CssFontFace*) -> ak.String:
    return this.m_ascent_override

## Ported from Libraries/LibWeb/CSS/FontFace.h:80 Web::CSS::FontFace::descent_override.
pub func css_font_face_descent_override(this: CssFontFace*) -> ak.String:
    return this.m_descent_override

## Ported from Libraries/LibWeb/CSS/FontFace.h:84 Web::CSS::FontFace::line_gap_override.
pub func css_font_face_line_gap_override(this: CssFontFace*) -> ak.String:
    return this.m_line_gap_override

## Ported from Libraries/LibWeb/CSS/FontFace.h:88 Web::CSS::FontFace::is_css_connected.
pub func css_font_face_is_css_connected(this: CssFontFace*) -> bool:
    return this.m_css_font_face_rule != none

## Ported from Libraries/LibWeb/CSS/FontFace.h:94 Web::CSS::FontFace::typeface.
pub func css_font_face_typeface(this: CssFontFace*) -> web_fonts.Typeface*?:
    return this.m_parsed_font

## Ported from Libraries/LibWeb/CSS/FontFace.h:96 Web::CSS::FontFace::declared_weight_range.
pub func css_font_face_declared_weight_range(this: CssFontFace*) -> CssFontWeightRange:
    return this.m_cached_weight_range

## Ported from Libraries/LibWeb/CSS/FontFace.h:97 Web::CSS::FontFace::declared_slope.
pub func css_font_face_declared_slope(this: CssFontFace*) -> i32:
    return this.m_cached_slope

## Ported from Libraries/LibWeb/CSS/FontFace.h:98 Web::CSS::FontFace::declared_width.
pub func css_font_face_declared_width(this: CssFontFace*) -> i32:
    return this.m_cached_width

## Ported from Libraries/LibWeb/CSS/FontFace.h:99 Web::CSS::FontFace::should_be_registered_with_font_computer.
pub func css_font_face_should_be_registered_with_font_computer(this: CssFontFace*) -> bool:
    return css_font_face_is_css_connected(this) or css_font_face_status(this) == BindFontFaceLoadStatus.loaded

## Ported from Libraries/LibWeb/CSS/FontFace.h:103 Web::CSS::FontFace::unicode_ranges.
pub func css_font_face_unicode_ranges(this: CssFontFace*) -> ak.Vector[web_fonts.UnicodeRange]:
    return this.m_unicode_ranges

## Ported from Libraries/LibWeb/CSS/FontFace.h:104 Web::CSS::FontFace::has_urls.
pub func css_font_face_has_urls(this: CssFontFace*) -> bool:
    return not ak.vector_is_empty(&this.m_urls)

## Ported from Libraries/LibWeb/CSS/FontFace.h:106 Web::CSS::FontFace::has_non_default_unicode_range.
pub func css_font_face_has_non_default_unicode_range(this: CssFontFace*) -> bool:
    if ak.vector_size(&this.m_unicode_ranges) != 1:
        return true
    let range = ak.vector_first_const(&this.m_unicode_ranges)
    return web_fonts.unicode_range_min_code_point(range) != 0 or web_fonts.unicode_range_max_code_point(range) != 0x10FFFF

## Ported from Libraries/LibWeb/CSS/FontFace.h:114 Web::CSS::FontFace::status.
pub func css_font_face_status(this: CssFontFace*) -> BindFontFaceLoadStatus:
    return this.m_status

## Ported from Libraries/LibWeb/CSS/FontFace.h:119 Web::CSS::FontFace::font_status_promise.
pub func css_font_face_font_status_promise(this: CssFontFace*) -> JsPromiseCapability*:
    return this.m_font_status_promise

# mark: Descriptors =============================================================================

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:46 Web::CSS::is_unsupported_source.
# In order to avoid conflicts with the old WinIE style of @font-face, if there is no format specified,
# we check to see if the URL ends with .eot. We will not try to load those.
# This matches the behavior of other engines (Blink, WebKit).
func css_is_unsupported_source(source: const CssParsedFontFaceSource*) -> bool:
    match source.local_or_url:
        .fly_string(_):
            return false
        .css_url(url):
            if let format_name = source.format_:
                return not css_font_format_is_supported(format_name)
            let url_string = css_url_url(&url)
            return ak.string_ends_with_bytes(&url_string, ak.sv(".eot"))

## The predicate of `m_urls.remove_all_matching(is_unsupported_source)`.
func css_is_unsupported_source_predicate(context: void*?, source: const CssParsedFontFaceSource*) -> bool:
    return css_is_unsupported_source(source)

## `static_cast<int>(StyleComputer::compute_font_weight(value, {})->as_number().number())`.
func css_font_face_computed_weight(value: CssStyleValue*) -> i32:
    return (i32)css_number_style_value_number(css_style_value_as_number(css_style_computer_compute_font_weight(value, none)))

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:55 Web::CSS::compute_weight_range.
func css_compute_weight_range(value: CssStyleValue*) -> CssFontWeightRange:
    if css_style_value_to_keyword(value) == css_data.Keyword.auto or css_style_value_to_keyword(value) == css_data.Keyword.normal:
        return CssFontWeightRange(min = 400, max = 400)

    let weight_values = css_style_value_list_values(css_style_value_as_value_list(value))
    if ak.vector_size(&weight_values) == 1:
        let one_weight = css_font_face_computed_weight(*ak.vector_at_const(&weight_values, 0))
        return CssFontWeightRange(min = one_weight, max = one_weight)
    if ak.vector_size(&weight_values) == 2:
        let first = css_font_face_computed_weight(*ak.vector_at_const(&weight_values, 0))
        let second = css_font_face_computed_weight(*ak.vector_at_const(&weight_values, 1))
        return CssFontWeightRange(min = ak.min(first, second), max = ak.max(first, second))
    return CssFontWeightRange(min = 400, max = 400)

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:73 Web::CSS::compute_slope.
func css_compute_slope(value: CssStyleValue*) -> i32:
    if css_style_value_to_keyword(value) == css_data.Keyword.auto or css_style_value_to_keyword(value) == css_data.Keyword.normal:
        return 0

    return css_font_style_style_value_to_font_slope(css_style_value_as_font_style(css_style_computer_compute_font_style(value)))

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:81 Web::CSS::compute_width.
func css_compute_width(value: CssStyleValue*) -> i32:
    if css_style_value_to_keyword(value) == css_data.Keyword.auto or css_style_value_to_keyword(value) == css_data.Keyword.normal:
        return 100

    return (i32)css_dimension_style_value_raw_value(css_style_value_as_percentage(css_style_computer_compute_font_width(value)).css_dimension_style_value())

# mark: Loading a vector font ===================================================================

## The captures of load_vector_font's preparation callback: the promise.
struct CssLoadVectorFontPrepared:
    var promise: CorePromise[web_fonts.Typeface*, ak.AkError]*

## load_vector_font's preparation callback.
func css_load_vector_font_prepared(context: void*?, prepared_font_data: ErrorOrCssPreparedVectorFontData):
    let promise = ((CssLoadVectorFontPrepared*)(context else trap("no captures"))).promise
    match prepared_font_data:
        .ak_error(failure):
            core_promise_reject(promise, failure)
            return
        .value(prepared):
            let result = css_try_load_vector_font(prepared.data, prepared.mime_type_essence) catch failure:
                core_promise_reject(promise, ak.ak_error_from_failure(failure))
                return

            core_promise_resolve(promise, result)

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:89 Web::CSS::load_vector_font.
func css_load_vector_font(realm: Realm*, data: ak.ByteBuffer) -> CorePromise[web_fonts.Typeface*, ak.AkError]*:
    let promise = core_promise_construct[web_fonts.Typeface*, ak.AkError]()

    if not css_requires_off_thread_vector_font_preparation(data):
        let result = css_try_load_vector_font(data) catch failure:
            core_promise_reject(promise, ak.ak_error_from_failure(failure))
            return promise

        core_promise_resolve(promise, result)
        return promise

    let captures = new CssLoadVectorFontPrepared(promise = promise) else trap("out of memory")
    css_prepare_vector_font_data_off_thread(data, ak.Function1[ErrorOrCssPreparedVectorFontData, unit](call = css_load_vector_font_prepared, context = captures))

    return promise

# mark: Creation ================================================================================

## A JS value of a DOMException (the implicit GC::Ref<DOMException> to JS::Value conversion).
func css_font_face_exception_value(exception: IdlDomException*) -> JsValue:
    return bind_platform_object_wrapper(exception.bind_platform_object())

## construct_impl's "FontFace constructor: Invalid {}" message for a descriptor.
func css_font_face_invalid_descriptor_message(descriptor_id: css_data.DescriptorId) -> ak.Utf16String:
    let name = css_data.to_string_descriptor_id(descriptor_id)
    let message = css_string_formatted("FontFace constructor: Invalid {}", [css_arg_fly_string(&name)])
    return ak.utf16_string_from_utf8_string(&message)

## construct_impl's try_set_descriptor lambda: parse one descriptor and hand it to its setter.
func css_font_face_construct_impl_try_set_descriptor(font_face: CssFontFace*, realm: Realm*, parsing_params: CssParsingParams, descriptor_id: css_data.DescriptorId, string: ak.String, setter_impl: func(CssFontFace*, CssStyleValue*) -> unit):
    let result = parse_css_descriptor(parsing_params, css_data.AtRuleId.font_face, css_descriptor_name_and_id_from_id(descriptor_id), ak.string_bytes_as_string_view(&string))
    if result == none:
        css_font_face_reject_status_promise(font_face, css_font_face_exception_value(idl_syntax_error_create(realm, css_font_face_invalid_descriptor_message(descriptor_id))))
        return
    setter_impl(font_face, result else trap("VERIFY: RefPtr::release_nonnull()"))

## The captures of the tasks of construct_impl's BinaryData branch: the realm and the face.
struct CssFontFaceConstructImplLoad:
    var realm: Realm*
    var font_face: CssFontFace*

## The captures of the task queued when the vector font of construct_impl's BinaryData branch
## has loaded, or failed.
struct CssFontFaceConstructImplLoaded:
    var font: CssFontFace*
    var vector_font: web_fonts.Typeface*?
    var error_: ak.AkError

## Removes `font` from a set's [[LoadingFonts]] (`remove_all_matching([font](auto const& entry) {
## return entry == font; })`, css_font_computer_is_face); if that empties the list, switch the set
## to loaded.
func css_font_face_remove_from_loading_fonts(font_face_set: CssFontFaceSet*, font: CssFontFace*):
    _ = ak.vector_remove_all_matching(css_font_face_set_loading_fonts(font_face_set), ak.Function1[const (CssFontFace*)*, bool](call = css_font_computer_is_face, context = font))
    if ak.vector_is_empty(css_font_face_set_loading_fonts(font_face_set)):
        css_font_face_set_switch_to_loaded(font_face_set)

## construct_impl's task for a successfully parsed vector font.
func css_font_face_construct_impl_did_load(context: void*?):
    let captures = (CssFontFaceConstructImplLoaded*)(context else trap("no captures"))
    let font = captures.font
    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, bind_platform_object_realm(font.bind_platform_object()), HtmlTemporaryExecutionContextCallbacksEnabled.yes)
    defer html_temporary_execution_context_destruct(&execution_context)
    # 1. If the load was successful, font face now represents the parsed font;
    #    fulfill font face’s [[FontStatusPromise]] with font face, and set its status attribute to "loaded".

    # FIXME: Are we supposed to set the properties of the FontFace based on the loaded vector font?
    font.m_parsed_font = captures.vector_font
    font.m_status = BindFontFaceLoadStatus.loaded
    idl_resolve_promise(bind_platform_object_realm(font.bind_platform_object()), font.m_font_status_promise, bind_platform_object_wrapper(font.bind_platform_object()))

    if let font_computer = css_font_face_font_computer(font):
        css_font_computer_register_font_face(font_computer, font)

    # For each FontFaceSet font face is in:
    for entry in ak.hash_table_begin(&font.m_containing_sets):
        let font_face_set = *entry
        # 1. Add font face to the FontFaceSet’s [[LoadedFonts]] list.
        ak.vector_append_t(css_font_face_set_loaded_fonts(font_face_set), font)

        # 2. Remove font face from the FontFaceSet’s [[LoadingFonts]] list. If font was the last item in
        #    that list (and so the list is now empty), switch the FontFaceSet to loaded.
        css_font_face_remove_from_loading_fonts(font_face_set, font)

    font.m_font_load_promise = none

## construct_impl's task for a vector font that failed to parse.
func css_font_face_construct_impl_did_fail(context: void*?):
    let captures = (CssFontFaceConstructImplLoaded*)(context else trap("no captures"))
    let font = captures.font
    let realm = bind_platform_object_realm(font.bind_platform_object())
    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, realm, HtmlTemporaryExecutionContextCallbacksEnabled.yes)
    defer html_temporary_execution_context_destruct(&execution_context)
    # 2. Otherwise, reject font face’s [[FontStatusPromise]] with a DOMException named "SyntaxError"
    #    and set font face’s status attribute to "error".
    let message = css_string_formatted("Failed to load font: {}", [ak.arg_string_view(ak.ak_error_string_literal(&captures.error_))])
    css_font_face_reject_status_promise(font, css_font_face_exception_value(idl_syntax_error_create(realm, ak.utf16_string_from_utf8_string(&message))))

    # For each FontFaceSet font face is in:
    for entry in ak.hash_table_begin(&font.m_containing_sets):
        let font_face_set = *entry
        # 1. Add font face to the FontFaceSet’s [[FailedFonts]] list.
        ak.vector_append_t(css_font_face_set_failed_fonts(font_face_set), font)

        # 2. Remove font face from the FontFaceSet’s [[LoadingFonts]] list. If font was the last item in
        #    that list (and so the list is now empty), switch the FontFaceSet to loaded.
        css_font_face_remove_from_loading_fonts(font_face_set, font)

    font.m_font_load_promise = none

## The captures of the font load promise's callbacks: the face's GC::Root (C++ gives each callback
## its own; the promise runs one of them, which releases the root the two share).
struct CssFontFaceConstructImplPromiseCallback:
    var font: gc.Root[CssFontFace]

## The face of a promise callback's captures, its root released.
func css_font_face_construct_impl_promise_callback_face(context: void*?) -> CssFontFace*:
    let captures = (CssFontFaceConstructImplPromiseCallback*)(context else trap("no captures"))
    let font = gc.root_cell(&captures.font) else trap("no face")
    gc.root_release(&captures.font)
    return font

## The font load promise's when_resolved callback: queue the task of a loaded font.
func css_font_face_construct_impl_when_resolved(context: void*?, vector_font: web_fonts.Typeface**):
    let font = css_font_face_construct_impl_promise_callback_face(context)
    let captures = new CssFontFaceConstructImplLoaded(font = font, vector_font = *vector_font, error_ = ak.AkError()) else trap("out of memory")
    _ = html_queue_global_task(HtmlTaskSource.font_loading, html_relevant_global_object((JsObject*)font), gc.create_function0(gc.cell_heap(font.cell()), ak.Function0[unit](call = css_font_face_construct_impl_did_load, context = captures)))

## The font load promise's when_rejected callback: queue the task of a failed font.
func css_font_face_construct_impl_when_rejected(context: void*?, failure: ak.AkError*):
    let font = css_font_face_construct_impl_promise_callback_face(context)
    let captures = new CssFontFaceConstructImplLoaded(font = font, vector_font = none, error_ = ak.ak_error_copy(*failure)) else trap("out of memory")
    _ = html_queue_global_task(HtmlTaskSource.font_loading, html_relevant_global_object((JsObject*)font), gc.create_function0(gc.cell_heap(font.cell()), ak.Function0[unit](call = css_font_face_construct_impl_did_fail, context = captures)))

## construct_impl's task for the font face's [[Data]] (step 3).
func css_font_face_construct_impl_load_data(context: void*?):
    let captures = (CssFontFaceConstructImplLoad*)(context else trap("no captures"))
    let font_face = captures.font_face
    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, bind_platform_object_realm(font_face.bind_platform_object()), HtmlTemporaryExecutionContextCallbacksEnabled.yes)
    defer html_temporary_execution_context_destruct(&execution_context)
    # 1.  Set font face’s status attribute to "loading".
    font_face.m_status = BindFontFaceLoadStatus.loading

    # 2. For each FontFaceSet font face is in:
    for entry in ak.hash_table_begin(&font_face.m_containing_sets):
        let font_face_set = *entry
        # 1. If the FontFaceSet’s [[LoadingFonts]] list is empty, switch the FontFaceSet to loading.
        if ak.vector_is_empty(css_font_face_set_loading_fonts(font_face_set)):
            css_font_face_set_switch_to_loading(font_face_set)

        # 2. Append font face to the FontFaceSet’s [[LoadingFonts]] list.
        ak.vector_append_t(css_font_face_set_loading_fonts(font_face_set), font_face)

    # 3. Asynchronously, attempt to parse the data in it as a font.
    #    When this is completed, successfully or not, queue a task to run the following steps synchronously:
    let font_load_promise = css_load_vector_font(captures.realm, font_face.m_binary_data)
    font_face.m_font_load_promise = font_load_promise

    let callback_captures = new CssFontFaceConstructImplPromiseCallback(font = gc.root_create(font_face)) else trap("out of memory")
    _ = core_promise_when_resolved(font_load_promise, ak.Function1[web_fonts.Typeface**, unit](call = css_font_face_construct_impl_when_resolved, context = callback_captures))
    _ = core_promise_when_rejected(font_load_promise, ak.Function1[ak.AkError*, unit](call = css_font_face_construct_impl_when_rejected, context = callback_captures))

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:126 Web::CSS::FontFace::construct_impl.
# https://drafts.csswg.org/css-font-loading/#font-face-constructor
pub func css_font_face_construct_impl(realm: Realm*, family: ak.String, source: CssFontFaceFontFaceSource, descriptors: const CssFontFaceDescriptors*) -> CssFontFace*:
    # 1. Let font face be a fresh FontFace object. Set font face’s status attribute to "unloaded",
    #    Set its internal [[FontStatusPromise]] slot to a fresh pending Promise object.
    let font_face = realm_create_css_font_face(realm, realm, idl_create_promise(realm))

    #    Parse the family argument, and the members of the descriptors argument,
    #    according to the grammars of the corresponding descriptors of the CSS @font-face rule.
    #    If the source argument is a CSSOMString, parse it according to the grammar of the CSS src descriptor of the @font-face rule.
    #    If any of them fail to parse correctly, reject font face’s [[FontStatusPromise]] with a DOMException named "SyntaxError",
    #    set font face’s corresponding attributes to the empty string, and set font face’s status attribute to "error".
    #    Otherwise, set font face’s corresponding attributes to the serialization of the parsed values.

    var parsing_params: CssParsingParams = ---
    css_parsing_params_construct_realm_css_parsing_mode(&parsing_params, realm)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.font_family, family, css_font_face_set_family_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.font_style, descriptors.style, css_font_face_set_style_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.font_weight, descriptors.weight, css_font_face_set_weight_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.font_width, descriptors.stretch, css_font_face_set_stretch_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.unicode_range, descriptors.unicode_range, css_font_face_set_unicode_range_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.font_feature_settings, descriptors.feature_settings, css_font_face_set_feature_settings_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.font_variation_settings, descriptors.variation_settings, css_font_face_set_variation_settings_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.font_display, descriptors.display, css_font_face_set_display_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.ascent_override, descriptors.ascent_override, css_font_face_set_ascent_override_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.descent_override, descriptors.descent_override, css_font_face_set_descent_override_impl)
    css_font_face_construct_impl_try_set_descriptor(font_face, realm, parsing_params, css_data.DescriptorId.line_gap_override, descriptors.line_gap_override, css_font_face_set_line_gap_override_impl)
    var parsed_source: CssStyleValue*?
    match source:
        .string(source_string):
            parsed_source = parse_css_descriptor(parsing_params, css_data.AtRuleId.font_face, css_descriptor_name_and_id_from_id(css_data.DescriptorId.src), ak.string_bytes_as_string_view(&source_string))
            if parsed_source == none:
                css_font_face_reject_status_promise(font_face, css_font_face_exception_value(idl_syntax_error_create(realm, css_font_face_invalid_descriptor_message(css_data.DescriptorId.src))))
        .idl_buffer_source(_):
            _ = 0
    #    Return font face. If font face’s status is "error", terminate this algorithm;
    #    otherwise, complete the rest of these steps asynchronously.
    # FIXME: Do the rest of this asynchronously.
    if css_font_face_status(font_face) == BindFontFaceLoadStatus.error_:
        return font_face

    # 2. If the source argument was a CSSOMString, set font face’s internal [[Urls]] slot to the string.
    #    If the source argument was a BinaryData, set font face’s internal [[Data]] slot to the passed argument.
    match source:
        .string(_):
            font_face.m_urls = css_parsed_font_face_sources_from_style_value(parsed_source else trap("VERIFY: the parsed source"))
            _ = ak.vector_remove_all_matching(&font_face.m_urls, ak.Function1[const CssParsedFontFaceSource*, bool](call = css_is_unsupported_source_predicate, context = none))
        .idl_buffer_source(buffer_source):
            let maybe_buffer = idl_get_buffer_source_copy(idl_bufferable_object_base_raw_object((buffer_source else trap("VERIFY: the buffer source")).idl_bufferable_object_base())) catch failure:
                # VERIFY(maybe_buffer.error().code() == ENOMEM); the JS::InternalError it rejects with is a JS object.
                trap("unported (P3): FontFace constructor: rejecting with an out-of-memory JS::InternalError")
            font_face.m_binary_data = maybe_buffer

    if ak.byte_buffer_is_empty(&font_face.m_binary_data) and ak.vector_is_empty(&font_face.m_urls):
        css_font_face_reject_status_promise(font_face, css_font_face_exception_value(idl_syntax_error_create(realm, ak.utf16_string_from_str("FontFace constructor: Invalid font source"))))

    # 3. If font face’s [[Data]] slot is not null, queue a task to run the following steps synchronously:
    if ak.byte_buffer_is_empty(&font_face.m_binary_data):
        return font_face

    let captures = new CssFontFaceConstructImplLoad(realm = realm, font_face = font_face) else trap("out of memory")
    _ = html_queue_global_task(HtmlTaskSource.font_loading, html_relevant_global_object((JsObject*)font_face), gc.create_function0(realm_heap(realm), ak.Function0[unit](call = css_font_face_construct_impl_load_data, context = captures)))

    return font_face

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:275 Web::CSS::FontFace::create_css_connected.
# https://drafts.csswg.org/css-font-loading/#font-face-css-connection
pub func css_font_face_create_css_connected(realm: Realm*, rule: CssFontFaceRule*) -> CssFontFace*:
    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, realm)
    defer html_temporary_execution_context_destruct(&execution_context)

    let font_face = realm_create_css_font_face(realm, realm, idl_create_promise(realm))

    font_face.m_css_font_face_rule = rule
    css_font_face_reparse_connected_css_font_face_rule_descriptors(font_face)

    if let src_value = css_descriptors_descriptor(css_font_face_rule_descriptors(rule).css_descriptors(), css_descriptor_name_and_id_from_id(css_data.DescriptorId.src)):
        font_face.m_urls = css_parsed_font_face_sources_from_style_value(src_value)
        _ = ak.vector_remove_all_matching(&font_face.m_urls, ak.Function1[const CssParsedFontFaceSource*, bool](call = css_is_unsupported_source_predicate, context = none))

    css_font_face_rule_set_css_connected_font_face(rule, font_face)

    return font_face

## `descriptors->descriptor_or_initial_value(DescriptorNameAndID::from_id(id))`, which the
## connected rule's descriptors always have.
func css_font_face_rule_descriptor_or_initial_value(descriptors: CssCssFontFaceDescriptors*, id: css_data.DescriptorId) -> CssStyleValue*:
    return css_descriptors_descriptor_or_initial_value(descriptors.css_descriptors(), css_descriptor_name_and_id_from_id(id)) else trap("VERIFY: RefPtr::operator*() on a missing descriptor")

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:294 Web::CSS::FontFace::reparse_connected_css_font_face_rule_descriptors.
pub func css_font_face_reparse_connected_css_font_face_rule_descriptors(this: CssFontFace*):
    let descriptors = css_font_face_rule_descriptors(this.m_css_font_face_rule else trap("VERIFY: m_css_font_face_rule"))

    let parent_rule = css_style_declaration_parent_rule(descriptors.css_style_declaration()) else trap("VERIFY: descriptors->parent_rule()")
    let parent_style_sheet = css_rule_parent_style_sheet(parent_rule) else trap("VERIFY: parent_rule()->parent_style_sheet()")
    let owning_document = css_css_style_sheet_owning_document(parent_style_sheet) else trap("VERIFY: parent_style_sheet()->owning_document()")
    let computation_context = CssComputationContext(length_resolution_context = css_length_resolution_context_for_document(owning_document))

    css_font_face_set_family_impl(this, css_descriptors_descriptor(descriptors.css_descriptors(), css_descriptor_name_and_id_from_id(css_data.DescriptorId.font_family)) else trap("VERIFY: RefPtr::operator*() on a missing font-family"))
    css_font_face_set_style_impl(this, css_style_value_absolutized(css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.font_style), computation_context))
    css_font_face_set_weight_impl(this, css_style_value_absolutized(css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.font_weight), computation_context))
    css_font_face_set_stretch_impl(this, css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.font_width))
    css_font_face_set_unicode_range_impl(this, css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.unicode_range))
    css_font_face_set_feature_settings_impl(this, css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.font_feature_settings))
    css_font_face_set_variation_settings_impl(this, css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.font_variation_settings))
    css_font_face_set_display_impl(this, css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.font_display))
    css_font_face_set_ascent_override_impl(this, css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.ascent_override))
    css_font_face_set_descent_override_impl(this, css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.descent_override))
    css_font_face_set_line_gap_override_impl(this, css_font_face_rule_descriptor_or_initial_value(descriptors, css_data.DescriptorId.line_gap_override))

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:315 Web::CSS::FontFace::parsed_font_face.
pub func css_font_face_parsed_font_face(this: CssFontFace*) -> CssParsedFontFace:
    if let rule = this.m_css_font_face_rule:
        return css_font_face_rule_font_face(rule)

    # FIXME: The ParsedFontFace is kind of expensive to create. We should be using a shared sub-object for the data
    let realm = bind_platform_object_realm(this.bind_platform_object())
    # Create a dummy CSSFontFaceRule so that we load relative to the document's base URL
    let dummy_rule = css_font_face_rule_create(realm, css_css_font_face_descriptors_create(realm, ak.Vector[CssDescriptor]()))
    let ascent_override: CssPercentage? = none  # FIXME: ascent_override
    let descent_override: CssPercentage? = none  # FIXME: descent_override
    let line_gap_override: CssPercentage? = none  # FIXME: line_gap_override
    let font_display = css_data.FontDisplay.auto  # FIXME: font_display
    let font_named_instance: ak.FlyString? = none  # font-named-instance doesn't exist in FontFace
    let font_language_override: ak.FlyString? = none  # font-language-override doesn't exist in FontFace
    let feature_settings: ak.OrderedHashMap[ak.FlyString, i32, ak.FlyStringTraits]? = none  # FIXME: feature_settings
    let variation_settings: ak.OrderedHashMap[ak.FlyString, f64, ak.FlyStringTraits]? = none  # FIXME: variation_settings
    var parsed_font_face: CssParsedFontFace = ---
    css_parsed_font_face_construct(&parsed_font_face, dummy_rule.css_rule(), ak.fly_string_from_string(this.m_family), this.m_cached_weight_range, this.m_cached_slope, this.m_cached_width, this.m_urls, this.m_unicode_ranges, ascent_override, descent_override, line_gap_override, font_display, font_named_instance, font_language_override, feature_settings, variation_settings)
    return parsed_font_face

# mark: The FontFace cell =======================================================================

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:341 Web::CSS::FontFace::FontFace.
pub func css_font_face_construct(this: CssFontFace*, realm: Realm*, font_status_promise: JsPromiseCapability*):
    bind_platform_object_construct_realm(this.bind_platform_object(), realm)
    css_font_face_init_fields(this)
    this.m_font_status_promise = font_status_promise

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:349 Web::CSS::FontFace::initialize (override).
pub func css_font_face_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.font_face)
    js_cell_initialize_impl(base, realm)

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:355 Web::CSS::FontFace::visit_edges (override).
pub func css_font_face_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (CssFontFace*)base
    bind_platform_object_visit_edges_impl(base, visitor)

    # visitor.visit(m_font_status_promise): WebIDL::Promise is opaque until phase 3 (a cell in the donor).
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_font_status_promise)
    gc.cell_visitor_visit_t(visitor, this.m_css_font_face_rule)
    gc.cell_visitor_visit_t(visitor, this.m_font_loader)
    for entry in ak.hash_table_begin(&this.m_containing_sets):
        gc.cell_visitor_visit_t_2(visitor, *entry)

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:366 Web::CSS::FontFace::loaded.
pub func css_font_face_loaded(this: CssFontFace*) -> JsPromiseCapability*:
    return this.m_font_status_promise

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:371 Web::CSS::FontFace::reject_status_promise.
func css_font_face_reject_status_promise(this: CssFontFace*, reason: JsValue):
    if this.m_status != BindFontFaceLoadStatus.error_:
        idl_reject_promise(bind_platform_object_realm(this.bind_platform_object()), this.m_font_status_promise, reason)
        idl_mark_promise_as_handled(this.m_font_status_promise)
        this.m_status = BindFontFaceLoadStatus.error_

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:380 Web::CSS::FontFace::font_computer.
func css_font_face_font_computer(this: CssFontFace*) -> CssFontComputer*?:
    for entry in ak.hash_table_begin(&this.m_containing_sets):
        let global = html_relevant_global_object((JsObject*)*entry)
        if let window = as_if_html_window((gc.Cell*)global):
            return dom_document_font_computer(html_window_associated_document(window))
    return none

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:390 Web::CSS::FontFace::disconnect_from_css_rule.
pub func css_font_face_disconnect_from_css_rule(this: CssFontFace*):
    this.m_css_font_face_rule = none

## Ported from Libraries/LibWeb/CSS/FontFace.cpp:395 Web::CSS::FontFace::font_with_point_size.
pub func css_font_face_font_with_point_size(this: CssFontFace*, point_size: f32, variations: web_fonts.FontVariationSettings, shape_features: ak.Vector[web_fonts.ShapeFeature]) -> const web_fonts.FontCascadeList*?:
    let font_list = web_fonts.font_cascade_list_create()
    if let font_loader = this.m_font_loader:
        if let font = css_font_loader_font_with_point_size(font_loader, point_size, variations, shape_features):
            web_fonts.font_cascade_list_add_vector(font_list, font, css_font_loader_unicode_ranges(font_loader))
    elif let parsed_font = this.m_parsed_font:
        web_fonts.font_cascade_list_add_vector(font_list, web_fonts.typeface_font(parsed_font, point_size, variations, shape_features), this.m_unicode_ranges)
    if web_fonts.font_cascade_list_is_empty(font_list):
        return none
    return font_list