Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / html_link_element_2.lucb

#==============================================================================================
#
#   html_link_element_2 - HTML::HTMLLinkElement: link types, fetched resources and favicons
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLLinkElement.cpp (lines 473-1028): fetching and processing the
#       dns-prefetch, preconnect and preload link types, the linked resource fetch setup
#       steps (icon, stylesheet), matching a preload type, preloading, processing a fetched
#       linked resource (an icon, or a style sheet made with the document's style sheet list),
#       decoding favicons and the fallback favicon, and which link types are fetched. All of
#       this runs on fetched resources (phase 2); the fetching itself is closure stubs.
#
#==============================================================================================

# mark: dns-prefetch, preconnect, preload =======================================================

## Ported from HTMLLinkElement.cpp:474 Web::HTML::HTMLLinkElement::fetch_and_process_linked_dns_prefetch_resource.
# https://html.spec.whatwg.org/multipage/links.html#link-type-dns-prefetch:fetch-and-process-the-linked-resource-2
pub func html_link_element_fetch_and_process_linked_dns_prefetch_resource(this: HtmlLinkElement*):
    let href = dom_element_get_attribute(this.dom_element(), html_attribute_names_href) else return

    # 1. Let url be the result of encoding-parsing a URL given el's href attribute's value, relative to el's node document.
    let url = dom_document_encoding_parse_url(dom_node_document(this.dom_node()), ak.string_bytes_as_string_view(&href))

    # 2. If url is failure, then return.
    let url_record = url else return

    # FIXME: 3. Let partitionKey be the result of determining the network partition key given el's node document's relevant
    #           settings object.

    # 4. The user agent should resolve an origin given partitionKey and url's origin.
    # FIXME: This should go through Fetch: https://fetch.spec.whatwg.org/#resolve-an-origin
    resource_loader_prefetch_dns(url_record)

## Ported from HTMLLinkElement.cpp:496 Web::HTML::HTMLLinkElement::fetch_and_process_linked_preconnect_resource.
# https://html.spec.whatwg.org/multipage/links.html#link-type-preconnect:fetch-and-process-the-linked-resource-2
pub func html_link_element_fetch_and_process_linked_preconnect_resource(this: HtmlLinkElement*):
    # The fetch and process the linked resource steps for this type of linked resource, given a link element el, are to
    # create link options from el and to preconnect given the result.
    html_link_element_preconnect(this, html_link_element_create_link_options(this))

## fetch_and_process_linked_preload_resource's processResponse (its context is the element).
func html_link_element_preload_process_response(context: void*?, response: FetchResponse*):
    let this = (HtmlLinkElement*)(context else trap("preload: no link element"))
    let realm = html_element_realm(this.html_element())
    # 1. If response is a network error, fire an event named error at el. Otherwise, fire an event named load at el.
    if fetch_response_is_network_error(response):
        _ = dom_event_target_dispatch_event(this.dom_event_target(), dom_event_create(realm, html_event_names_error))
    else:
        _ = dom_event_target_dispatch_event(this.dom_event_target(), dom_event_create(realm, html_event_names_load))

## Ported from HTMLLinkElement.cpp:504 Web::HTML::HTMLLinkElement::fetch_and_process_linked_preload_resource.
# https://html.spec.whatwg.org/multipage/links.html#link-type-preload:fetch-and-process-the-linked-resource-2
pub func html_link_element_fetch_and_process_linked_preload_resource(this: HtmlLinkElement*):
    # FIXME: 1. Update the source set for el.

    # 2. Let options be the result of creating link options from el.
    let options = html_link_element_create_link_options(this)

    # 3. Let destination be the result of translating the keyword representing the state of el's as attribute.
    let destination = html_translate_a_preload_destination(dom_element_get_attribute(this.dom_element(), html_attribute_names_as))

    # 4. If destination is null, then return.
    # 5. Set options's destination to destination.
    match destination:
        .empty: return
        .destination(value): options.destination = value

    # 6. Preload options, with the following steps given a response response:
    html_link_element_preload(this, options, gc.create_function1(gc.cell_heap(this.cell()), ak.Function1[FetchResponse*, unit](call = html_link_element_preload_process_response, context = this)))

# mark: Linked resource fetch setup steps =======================================================

## Ported from HTMLLinkElement.cpp:532 Web::HTML::HTMLLinkElement::linked_resource_fetch_setup_steps.
# https://html.spec.whatwg.org/multipage/semantics.html#linked-resource-fetch-setup-steps
pub func html_link_element_linked_resource_fetch_setup_steps(this: HtmlLinkElement*, request: FetchRequest*) -> bool:
    if (this.m_relationship & html_link_element_relationship_icon) != 0:
        return html_link_element_icon_linked_resource_fetch_setup_steps(this, request)
    if (this.m_relationship & html_link_element_relationship_stylesheet) != 0:
        return html_link_element_stylesheet_linked_resource_fetch_setup_steps(this, request)
    return true

## Ported from HTMLLinkElement.cpp:542 Web::HTML::HTMLLinkElement::icon_linked_resource_fetch_setup_steps.
# https://html.spec.whatwg.org/multipage/links.html#rel-icon:linked-resource-fetch-setup-steps
pub func html_link_element_icon_linked_resource_fetch_setup_steps(this: HtmlLinkElement*, request: FetchRequest*) -> bool:
    # 1. Set request's destination to "image".
    fetch_request_set_destination(request, FetchRequestDestination.image)

    # 2. Return true.
    return true

## Ported from HTMLLinkElement.cpp:552 Web::HTML::HTMLLinkElement::stylesheet_linked_resource_fetch_setup_steps.
# https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:linked-resource-fetch-setup-steps
pub func html_link_element_stylesheet_linked_resource_fetch_setup_steps(this: HtmlLinkElement*, request: FetchRequest*) -> bool:
    let element = this.dom_element()
    let document = dom_node_document(this.dom_node())
    # 1. If el's disabled attribute is set, then return false.
    if dom_element_has_attribute(element, html_attribute_names_disabled):
        return false

    # 2. If el contributes a script-blocking style sheet, append el to its node document's script-blocking style sheet set.
    if dom_element_contributes_a_script_blocking_style_sheet(element):
        _ = ak.hash_table_set(dom_document_script_blocking_style_sheet_set(document), element)

    # 3. If el's media attribute's value matches the environment and el is potentially render-blocking, then block rendering on el.
    # FIXME: Check media attribute value.
    if dom_element_is_potentially_render_blocking(element):
        dom_element_block_rendering(element)

    # m_document_load_event_delayer.emplace(document()): a previous delayer, if any, is destroyed first.
    html_link_element_clear_document_load_event_delayer(this)
    var delayer: DomDocumentLoadEventDelayer = ---
    dom_document_load_event_delayer_construct(&delayer, document)
    this.m_document_load_event_delayer = delayer

    # 4. If el is currently render-blocking, then set request's render-blocking to true.
    if dom_document_is_render_blocking_element(document, element):
        fetch_request_set_render_blocking(request, true)

    # FIXME: We currently don't set the destination for stylesheets, so we do it here.
    #        File a spec issue that the destination for stylesheets is not actually set if the `as` attribute is missing.
    fetch_request_set_destination(request, FetchRequestDestination.style)

    # 5. Return true.
    return true

## Ported from HTMLLinkElement.cpp:582 Web::HTML::HTMLLinkElement::preconnect.
# https://html.spec.whatwg.org/multipage/links.html#preconnect
pub func html_link_element_preconnect(this: HtmlLinkElement*, options: HtmlLinkElementLinkProcessingOptions*):
    # 1. If options's href is an empty string, return.
    if ak.string_is_empty(&options.href):
        return

    # 2. Let url be the result of encoding-parsing a URL given options's href, relative to options's base URL.
    # FIXME: Spec issue: We should be parsing this URL relative to a document or environment settings object.
    #        https://github.com/whatwg/html/issues/9715
    let url = domurl_parse(ak.string_bytes_as_string_view(&options.href), options.base_url)

    # 3. If url is failure, then return.
    let url_record = url else return

    # 4. If url's scheme is not an HTTP(S) scheme, then return.
    let scheme = web_url.url_scheme(&url_record)
    if not ak.string_eq_string_view(&scheme, ak.sv("http")) and not ak.string_eq_string_view(&scheme, ak.sv("https")):
        return

    # FIXME: 5. Let partitionKey be the result of determining the network partition key given options's environment.
    # FIXME: 6. Let useCredentials be true.
    # FIXME: 7. If options's crossorigin is Anonymous and options's origin does not have the same origin as url's origin,
    #           then set useCredentials to false.

    # 8. The user agent should obtain a connection given partitionKey, url's origin, and useCredentials.
    # FIXME: This should go through Fetch: https://fetch.spec.whatwg.org/#concept-connection-obtain
    resource_loader_preconnect(url_record)

## Ported from HTMLLinkElement.cpp:612 Web::HTML::type_matches_destination.
# https://html.spec.whatwg.org/multipage/links.html#match-preload-type
func html_type_matches_destination(type_: ak.StringView, destination: FetchRequestDestination?) -> bool:
    # 1. If type is an empty string, then return true.
    if ak.string_view_is_empty(&type_):
        return true

    # 2. If destination is "fetch", then return true.
    # FIXME: Spec issue: "fetch" will have been turned to an empty string by this point.
    let destination_value = destination else return true

    # 3. Let mimeTypeRecord be the result of parsing type.
    let mime_type_record = mime_type_parse(type_)

    # 4. If mimeTypeRecord is failure, then return false.
    let mime_type = mime_type_record else return false

    # FIXME: 5. If mimeTypeRecord is not supported by the user agent, then return false.

    let essence = mime_type_essence(&mime_type)
    # 6. If any of the following are true:
    # destination is "audio" or "video", and mimeTypeRecord is an audio or video MIME type;
    if ((destination_value == FetchRequestDestination.audio or destination_value == FetchRequestDestination.video) and mime_type_is_audio_or_video(&mime_type)) or (fetch_destination_is_script_like(destination_value) and mime_type_is_javascript(&mime_type)) or (destination_value == FetchRequestDestination.image and mime_type_is_image(&mime_type)) or (destination_value == FetchRequestDestination.font and mime_type_is_font(&mime_type)) or (destination_value == FetchRequestDestination.json and mime_type_is_json(&mime_type)) or (destination_value == FetchRequestDestination.style and ak.string_eq_string_view(&essence, ak.sv("text/css"))) or (destination_value == FetchRequestDestination.track and ak.string_eq_string_view(&essence, ak.sv("text/vtt"))):
        # (destination is a script-like destination and mimeTypeRecord is a JavaScript MIME type;
        #  destination is "image" and mimeTypeRecord is an image MIME type;
        #  destination is "font" and mimeTypeRecord is a font MIME type;
        #  destination is "json" and mimeTypeRecord is a JSON MIME type;
        #  destination is "style" and mimeTypeRecord's essence is text/css; or
        #  destination is "track" and mimeTypeRecord's essence is text/vtt,)
        # then return true.
        return true

    # 7. Return false.
    return false

## The captures preload's steps share: `[&realm, options = GC::Ref { options }, process_response,
## entry, report_timing]`, the controller holder and the preload key.
struct HtmlLinkElementPreload:
    var realm: Realm*
    var options: HtmlLinkElementLinkProcessingOptions*
    var process_response: gc.Function1[FetchResponse*, unit]*?
    var entry: HtmlPreloadEntry*
    var report_timing: gc.Function1[DomDocument*, unit]*?
    var controller_holder: FetchControllerHolder*
    var key: HtmlPreloadKey

    ## reportTiming given a Document document: report timing for controller given document's relevant global object.
    static func report_timing_steps(context: void*?, document: DomDocument*):
        let captures = (HtmlLinkElementPreload*)(context else trap("preload: no captures"))
        let controller = fetch_controller_holder_controller(captures.controller_holder) else trap("VERIFY: the preload's controller")
        fetch_controller_report_timing(controller, html_relevant_global_object((JsObject*)document))

    ## processResponseConsumeBody.
    static func process_response_consume_body(context: void*?, response_: FetchResponse*, body_bytes: FetchAlgorithmsBodyBytes):
        let captures = (HtmlLinkElementPreload*)(context else trap("preload: no captures"))
        let realm = captures.realm
        # FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:
        #        https://github.com/whatwg/html/issues/9355
        var response = fetch_response_unsafe_response(response_)

        match body_bytes:
            # 1. If bodyBytes is a byte sequence, then set response's body to bodyBytes as a body.
            .byte_buffer(byte_sequence):
                fetch_response_set_body(response, fetch_byte_sequence_as_body(realm, ak.byte_buffer_bytes_const(&byte_sequence)))
            # 2. Otherwise, set response to a network error.
            _:
                response = fetch_response_network_error(realm_vm(realm), ak.string_from_str("Expected preload response to contain a body"))

        # FIXME: 3. Set unsafeEndTime to the unsafe shared current time.

        # 4. If options's document is not null, then call reportTiming given options's document.
        if let document = captures.options.document:
            let report_timing = captures.report_timing else trap("reportTiming")
            ak.function1_call(&report_timing.function, document)

        # 5. If entry's on response available is null, then set entry's response to response; otherwise call entry's
        #    on response available given response.
        if let on_response_available = html_preload_entry_on_response_available(captures.entry):
            ak.function1_call(&on_response_available.function, response)
        else:
            html_preload_entry_set_response(captures.entry, response)

        # 6. If processResponse is given, then call processResponse with response.
        if let process_response = captures.process_response:
            ak.function1_call(&process_response.function, response)

    ## commit given a Document document.
    static func commit(context: void*?, document: DomDocument*):
        let captures = (HtmlLinkElementPreload*)(context else trap("preload: no captures"))
        # 1. If entry's response is not null, then call reportTiming given document.
        if html_preload_entry_response(captures.entry) != none:
            let report_timing = captures.report_timing else trap("reportTiming")
            ak.function1_call(&report_timing.function, document)

        # 2. Set document's map of preloaded resources[key] to entry.
        _ = ak.hash_map_set(dom_document_map_of_preloaded_resources(document), captures.key, captures.entry)

## Ported from HTMLLinkElement.cpp:665 Web::HTML::HTMLLinkElement::preload.
# https://html.spec.whatwg.org/multipage/links.html#preload
pub func html_link_element_preload(this: HtmlLinkElement*, options: HtmlLinkElementLinkProcessingOptions*, process_response: gc.Function1[FetchResponse*, unit]*?):
    let realm = html_element_realm(this.html_element())
    let vm = realm_vm(realm)

    # 1. If options's type doesn't match options's destination, then return.
    if not html_type_matches_destination(ak.string_bytes_as_string_view(&options.type_), options.destination):
        return

    # FIXME: 2. If options's destination is "image" and options's source set is not null, then set options's href to the
    #           result of selecting an image source from options's source set.
    if ak.string_is_empty(&options.href):
        return

    # 3. Let request be the result of creating a link request given options.
    # 4. If request is null, then return.
    let request = html_link_element_create_link_request(this, options) else return

    # FIXME: 5. Let unsafeEndTime be 0.

    # 6. Let entry be a new preload entry whose integrity metadata is options's integrity.
    let entry = realm_create_html_preload_entry(realm)
    html_preload_entry_set_integrity_metadata(entry, options.integrity)

    # 7. Let key be the result of creating a preload key given request.
    let key = html_create_a_preload_key(request)

    # 8. If options's document is null, then set request's initiator type to "early hint".
    if options.document == none:
        fetch_request_set_initiator_type(request, FetchRequestInitiatorType.early_hint)

    # 9. Let controller be null.
    let controller_holder = fetch_controller_holder_create(vm)

    let captures = new HtmlLinkElementPreload(realm = realm, options = options, process_response = process_response, entry = entry, report_timing = none, controller_holder = controller_holder, key = key) else trap("out of memory")

    # 10. Let reportTiming given a Document document be to report timing for controller given document's relevant global object.
    captures.report_timing = gc.create_function1(realm_heap(realm), ak.Function1[DomDocument*, unit](call = HtmlLinkElementPreload.report_timing_steps, context = captures))

    # 11. Set controller to the result of fetching request, with processResponseConsumeBody set to the following steps
    #     given a response response and null, failure, or a byte sequence bodyBytes:
    let fetch_controller = fetch_fetching_fetch(realm, request, fetch_algorithms_create_with_process_response_consume_body(vm, ak.Function2[FetchResponse*, FetchAlgorithmsBodyBytes, unit](call = HtmlLinkElementPreload.process_response_consume_body, context = captures)))
    this.m_fetch_controller = fetch_controller
    fetch_controller_holder_set_controller(controller_holder, fetch_controller)

    # 12. Let commit be the following steps given a Document document:
    let commit = gc.create_function1(realm_heap(realm), ak.Function1[DomDocument*, unit](call = HtmlLinkElementPreload.commit, context = captures))

    # 13. If options's document is null, then set options's on document ready to commit. Otherwise, call commit with
    #     options's document.
    if let document = options.document:
        ak.function1_call(&commit.function, document)
    else:
        options.on_document_ready = commit

# mark: Processing the linked resource ==========================================================

## Ported from HTMLLinkElement.cpp:762 Web::HTML::HTMLLinkElement::process_linked_resource.
# https://html.spec.whatwg.org/multipage/semantics.html#process-the-linked-resource
pub func html_link_element_process_linked_resource(this: HtmlLinkElement*, success: bool, response: FetchResponse*, body_bytes: ak.ByteBuffer):
    if (this.m_relationship & html_link_element_relationship_icon) != 0:
        html_link_element_process_icon_resource(this, success, response, body_bytes)
    elif (this.m_relationship & html_link_element_relationship_stylesheet) != 0:
        html_link_element_process_stylesheet_resource(this, success, response, body_bytes)

## Ported from HTMLLinkElement.cpp:772 Web::HTML::HTMLLinkElement::process_icon_resource.
# AD-HOC: The spec is underspecified for fetching and processing rel="icon" See:
#         https://github.com/whatwg/html/issues/1769
pub func html_link_element_process_icon_resource(this: HtmlLinkElement*, success: bool, response: FetchResponse*, body_bytes: ak.ByteBuffer):
    if not success:
        return

    this.m_loaded_icon = HtmlLinkElementLoadedIcon(url = fetch_response_url(response) else web_url.url_empty(), icon = body_bytes)
    dom_document_check_favicon_after_loading_link_resource(dom_node_document(this.dom_node()))

## Ported from HTMLLinkElement.cpp:782 Web::HTML::HTMLLinkElement::process_stylesheet_resource.
# https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:process-the-linked-resource
pub func html_link_element_process_stylesheet_resource(this: HtmlLinkElement*, success_argument: bool, response: FetchResponse*, body_bytes: ak.ByteBuffer):
    var success = success_argument
    let element = this.dom_element()
    let document = dom_node_document(this.dom_node())
    let realm = html_element_realm(this.html_element())
    if not dom_document_is_fully_active(document):
        return

    # 1. If the resource's Content-Type metadata is not text/css, then set success to false.
    var mime_type_string = this.m_mime_type
    var mime_type_charset: ak.String? = none
    let extracted_mime_type = fetch_extract_mime_type(fetch_response_header_list(response))
    if let mime_type = extracted_mime_type:
        if mime_type_string == none:
            mime_type_string = mime_type_essence(&mime_type)
        if let charset = ak.ordered_hash_map_get_k_const(mime_type_parameters(&mime_type), ak.string_from_str("charset")):
            mime_type_charset = *charset

    if let mime_type_value = mime_type_string:
        if not ak.string_eq_string_view(&mime_type_value, ak.sv("text/css")):
            success = false

    # FIXME: 2. If el no longer creates an external resource link that contributes to the styling processing model,
    #           or if, since the resource in question was fetched, it has become appropriate to fetch it again, then return.

    # 3. If el has an associated CSS style sheet, remove the CSS style sheet.
    if let loaded_style_sheet = this.m_loaded_style_sheet:
        css_style_sheet_list_remove_a_css_style_sheet(dom_element_document_or_shadow_root_style_sheets(element), loaded_style_sheet)
        this.m_loaded_style_sheet = none

    # 4. If success is true, then:
    if success:
        # 1. Create a CSS style sheet with the following properties:
        #        type
        #            text/css
        #        location
        #            response's URL list[0]
        #        owner node
        #            element
        #        media
        #            The media attribute of element.
        #        title
        #            The title attribute of element, if element is in a document tree, or the empty string otherwise.
        #        alternate flag
        #            Set if the link is an alternative style sheet and element's explicitly enabled is false; unset otherwise.
        #        origin-clean flag
        #            Set if the resource is CORS-same-origin; unset otherwise.
        #        parent CSS style sheet
        #        owner CSS rule
        #            null
        #        disabled flag
        #            Left at its default value.
        #        CSS rules
        #          Left uninitialized.
        #
        # The CSS environment encoding is the result of running the following steps: [CSSSYNTAX]
        #     1. If the element has a charset attribute, get an encoding from that attribute's value. If that succeeds, return the resulting encoding. [ENCODING]
        #     2. Otherwise, return the document's character encoding. [DOM]
        var environment_encoding: ak.StringView? = none
        var document_encoding = ak.string_new()
        if let charset = dom_element_attribute(element, html_attribute_names_charset):
            environment_encoding = text_codec.get_standardized_encoding(ak.string_bytes_as_string_view(&charset))

        if environment_encoding == none:
            if let encoding = dom_document_encoding(document):
                document_encoding = encoding
                environment_encoding = ak.string_bytes_as_string_view(&document_encoding)

        let maybe_decoded_string: ak.String? = css_decode_bytes(environment_encoding, mime_type_charset, &body_bytes) catch failure: recover none
        if let decoded_string = maybe_decoded_string:
            let url_list = fetch_response_url_list(response)
            assert(not ak.vector_is_empty(url_list))
            var title = ak.string_new()
            if dom_node_in_a_document_tree(this.dom_node()):
                title = dom_element_attribute(element, html_attribute_names_title) else ak.string_new()
            var alternate = CssStyleSheetListAlternate.no
            if (this.m_relationship & html_link_element_relationship_alternate) != 0 and not this.m_explicitly_enabled:
                alternate = CssStyleSheetListAlternate.yes
            this.m_loaded_style_sheet = css_style_sheet_list_create_a_css_style_sheet(dom_element_document_or_shadow_root_style_sheets(element),
                                                                                      decoded_string,
                                                                                      ak.string_from_str("text/css"),
                                                                                      element,
                                                                                      dom_element_attribute(element, html_attribute_names_media) else ak.string_new(),
                                                                                      title,
                                                                                      alternate,
                                                                                      CssStyleSheetListOriginClean.yes,
                                                                                      *ak.vector_first(url_list),
                                                                                      none,
                                                                                      none)

            # 2. Fire an event named load at el.
            _ = dom_event_target_dispatch_event(this.dom_event_target(), dom_event_create(realm, html_event_names_load))
        else:
            let url = fetch_response_url(response) else web_url.url_empty()
            let url_string = web_url.url_to_string(&url)
            ak.dbgln(f"Failed to decode CSS file: {ak.string_view_text(ak.string_bytes_as_string_view(&url_string))}")
            _ = dom_event_target_dispatch_event(this.dom_event_target(), dom_event_create(realm, html_event_names_error))
    # 5. Otherwise, fire an event named error at el.
    else:
        _ = dom_event_target_dispatch_event(this.dom_event_target(), dom_event_create(realm, html_event_names_error))

    # 6. If el contributes a script-blocking style sheet, then:
    if dom_element_contributes_a_script_blocking_style_sheet(element):
        let script_blocking_style_sheet_set = dom_document_script_blocking_style_sheet_set(document)
        # 1. Assert: el's node document's script-blocking style sheet set contains el.
        assert(ak.hash_table_contains_t(script_blocking_style_sheet_set, element))

        # 2. Remove el from its node document's script-blocking style sheet set.
        _ = ak.hash_table_remove_t(script_blocking_style_sheet_set, element)
        dom_document_schedule_html_parser_end_check(document)

    # 7. Unblock rendering on el.
    dom_element_unblock_rendering(element)

    if let loaded_style_sheet = this.m_loaded_style_sheet:
        let style_sheet_loading_state = css_css_style_sheet_loading_state(loaded_style_sheet)
        if style_sheet_loading_state == CssStyleSheetLoadingState.loaded or style_sheet_loading_state == CssStyleSheetLoadingState.error_:
            html_link_element_finished_loading_critical_style_subresources(this, HtmlLinkElementAnyFailed.yes if style_sheet_loading_state == CssStyleSheetLoadingState.error_ else HtmlLinkElementAnyFailed.no)
    else:
        html_link_element_clear_document_load_event_delayer(this)

# mark: Favicons ================================================================================

## The captures of decode_favicon's decode callbacks: `[document = GC::Root(document), promise]`
## (managed memory keeps the document) and the URL for the failure message.
struct HtmlDecodeFavicon:
    var document: DomDocument*
    var promise: CorePromise[bool, ak.AkError]*

    ## on_successful_decode.
    static func decoded(context: void*?, decoded_image: PlatformDecodedImage*):
        let captures = (HtmlDecodeFavicon*)(context else trap("decode favicon: no captures"))
        let favicon_bitmap = ak.vector_at(&decoded_image.frames, 0).bitmap else trap("a decoded favicon frame")

        if let navigable = dom_node_navigable(captures.document.dom_node()):
            if html_navigable_is_traversable(navigable):
                let traversable = html_navigable_traversable_navigable(navigable) else trap("a traversable navigable")
                page_client_page_did_change_favicon(page_client(html_navigable_page(traversable.html_navigable())), *favicon_bitmap)

        core_promise_resolve(captures.promise, true)

    ## on_failed_decode.
    static func failed(context: void*?, error_: ak.AkError*):
        let captures = (HtmlDecodeFavicon*)(context else trap("decode favicon: no captures"))
        core_promise_reject(captures.promise, *error_)

## Ported from HTMLLinkElement.cpp:895 Web::HTML::decode_favicon.
func html_decode_favicon(favicon_data: const u8[], favicon_url: web_url.Url, document: DomDocument*) -> CorePromise[bool, ak.AkError]*:
    let promise = core_promise_construct[bool, ak.AkError]()

    let basename = web_url.url_basename(&favicon_url)
    let basename_view = ak.byte_string_view(&basename)
    if ak.string_view_ends_with_string_view(&basename_view, ak.sv(".svg")):
        let result = svg_decoded_image_data_create(dom_document_realm(document), dom_document_page(document), favicon_url, favicon_data) catch:
            core_promise_reject(promise, ak.ak_error_from_string_view_string_view(ak.sv("Failed to decode SVG favicon")))
            return promise

        # FIXME: Calculate size based on device pixel ratio
        let size = gfx.IntSize(m_width = 32, m_height = 32)
        let maybe_immutable_bitmap = html_decoded_image_data_bitmap(result.html_decoded_image_data(), 0, size)
        if maybe_immutable_bitmap == none:
            core_promise_reject(promise, ak.ak_error_from_string_view_string_view(ak.sv("Failed to get bitmap from SVG favicon")))
            return promise
        let immutable_bitmap = maybe_immutable_bitmap else trap("VERIFY_NOT_REACHED")
        let bitmap = gfx.immutable_bitmap_bitmap(immutable_bitmap) else trap("an immutable bitmap's bitmap")
        if let navigable = dom_node_navigable(document.dom_node()):
            if html_navigable_is_traversable(navigable):
                let traversable = html_navigable_traversable_navigable(navigable) else trap("a traversable navigable")
                page_client_page_did_change_favicon(page_client(html_navigable_page(traversable.html_navigable())), *bitmap)
        core_promise_resolve(promise, true)
        return promise

    let captures = new HtmlDecodeFavicon(document = document, promise = promise) else trap("out of memory")
    _ = platform_image_codec_plugin_decode_image(platform_image_codec_plugin_the(), favicon_data, ak.Function1[PlatformDecodedImage*, unit](call = HtmlDecodeFavicon.decoded, context = captures), ak.Function1[ak.AkError*, unit](call = HtmlDecodeFavicon.failed, context = captures))

    return promise

## Ported from HTMLLinkElement.cpp:943 Web::HTML::HTMLLinkElement::load_favicon_and_use_if_window_is_active.
pub func html_link_element_load_favicon_and_use_if_window_is_active(this: HtmlLinkElement*) -> bool:
    if not html_link_element_has_loaded_icon(this):
        return false

    # FIXME: Refactor the caller(s) to handle the async nature of image loading
    let loaded_icon = this.m_loaded_icon else trap("VERIFY: a loaded icon")
    let promise = html_decode_favicon(ak.byte_buffer_bytes_const(&loaded_icon.icon), loaded_icon.url, dom_node_document(this.dom_node()))
    match core_promise_await(promise):
        .value(_): return true
        .error_(_): return false

## The captures of the fallback favicon's processResponse and body steps: `[document, request]`.
struct HtmlLinkElementFallbackFavicon:
    var document: DomDocument*
    var request: FetchRequest*

    ## processResponse.
    static func process_response(context: void*?, response: FetchResponse*):
        let captures = (HtmlLinkElementFallbackFavicon*)(context else trap("fallback favicon: no captures"))
        let realm = dom_document_realm(captures.document)
        let global = realm_global_object(realm)

        let process_body = gc.create_function1(realm_heap(realm), ak.Function1[ak.ByteBuffer, unit](call = HtmlLinkElementFallbackFavicon.process_body, context = captures))
        let process_body_error = gc.create_function1(realm_heap(realm), ak.Function1[JsValue, unit](call = HtmlLinkElementFallbackFavicon.process_body_error, context = captures))

        # Check for failed favicon response
        if not fetch_is_ok_status(fetch_response_status(response)) or fetch_response_body(response) == none:
            return

        # 3. Use response's unsafe response as an icon as if it had been declared using the icon keyword.
        if let body = fetch_response_body(fetch_response_unsafe_response(response)):
            fetch_body_fully_read(body, realm, process_body, process_body_error, .js_object(global))

    ## process_body.
    static func process_body(context: void*?, body: ak.ByteBuffer):
        let captures = (HtmlLinkElementFallbackFavicon*)(context else trap("fallback favicon: no captures"))
        _ = html_decode_favicon(ak.byte_buffer_bytes_const(&body), fetch_request_url(captures.request), captures.document)

    ## process_body_error.
    static func process_body_error(context: void*?, error_: JsValue):
        return

## Ported from HTMLLinkElement.cpp:955 Web::HTML::HTMLLinkElement::load_fallback_favicon_if_needed.
# https://html.spec.whatwg.org/multipage/links.html#rel-icon:the-link-element-3
pub func html_link_element_load_fallback_favicon_if_needed(document: DomDocument*):
    let realm = dom_document_realm(document)
    let vm = realm_vm(realm)

    # In the absence of a link with the icon keyword, for Document objects whose URL's scheme is an HTTP(S) scheme,
    # user agents may instead run these steps in parallel:
    if dom_document_has_active_favicon(document):
        return
    let url = dom_document_url(document)
    let scheme = web_url.url_scheme(&url)
    if not ak.string_eq_string_view(&scheme, ak.sv("http")) and not ak.string_eq_string_view(&scheme, ak.sv("https")):
        return

    # AD-HOC: Don't load fallback favicon for auxiliary browsing contexts (popup windows).
    # This matches the behavior observed in Chrome and Firefox, and avoids unnecessary network requests
    # that can interfere with Content Security Policy violation reporting.
    # See: https://github.com/whatwg/html/issues/12082
    let browsing_context = dom_document_browsing_context(document) else trap("VERIFY: a browsing context")
    if html_browsing_context_is_auxiliary(browsing_context):
        return

    # 1. Let request be a new request whose URL is the URL record obtained by resolving the URL "/favicon.ico" against
    #    the Document object's URL, client is the Document object's relevant settings object, destination is "image",
    #    synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.
    # NOTE: Fetch requests no longer have a synchronous flag, see https://github.com/whatwg/fetch/pull/1165
    let favicon_url = dom_document_encoding_parse_url(document, ak.sv("/favicon.ico"))

    # It is possible for the URL parser to fail if the document's base URL is invalid.
    let favicon_url_record = favicon_url else return

    let request = fetch_request_create(vm)
    fetch_request_set_url(request, favicon_url_record)
    fetch_request_set_client(request, dom_document_relevant_settings_object(document))
    fetch_request_set_destination(request, FetchRequestDestination.image)
    fetch_request_set_credentials_mode(request, FetchRequestCredentialsMode.include)
    fetch_request_set_use_url_credentials(request, true)

    # 2. Let response be the result of fetching request.
    let captures = new HtmlLinkElementFallbackFavicon(document = document, request = request) else trap("out of memory")
    _ = fetch_fetching_fetch(realm, request, fetch_algorithms_create_with_process_response(vm, ak.Function1[FetchResponse*, unit](call = HtmlLinkElementFallbackFavicon.process_response, context = captures)))

## Ported from HTMLLinkElement.cpp:1016 Web::HTML::HTMLLinkElement::should_fetch_and_process_resource_type.
pub func html_link_element_should_fetch_and_process_resource_type(this: HtmlLinkElement*) -> bool:
    # https://html.spec.whatwg.org/multipage/links.html#link-type-dns-prefetch:fetch-and-process-the-linked-resource
    # https://html.spec.whatwg.org/multipage/links.html#link-type-preconnect:fetch-and-process-the-linked-resource
    # https://html.spec.whatwg.org/multipage/links.html#link-type-preload:fetch-and-process-the-linked-resource
    # https://html.spec.whatwg.org/multipage/links.html#link-type-stylesheet:fetch-and-process-the-linked-resource
    if (this.m_relationship & (html_link_element_relationship_dns_prefetch | html_link_element_relationship_preconnect | html_link_element_relationship_preload | html_link_element_relationship_stylesheet)) != 0:
        return true

    # AD-HOC: The spec is underspecified for fetching and processing rel="icon". See:
    #         https://github.com/whatwg/html/issues/1769
    return (this.m_relationship & html_link_element_relationship_icon) != 0