Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / navigable_1.lucb

#==============================================================================================
#
#   navigable_1 - HTML::Navigable: the navigation state cells, the set of all navigables,
#   construction, GC edges, load-event delaying and session history entry accessors
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/Navigable.cpp lines 1-397 (NavigationParamsFetchStateHolder,
#       InternalNavigationResult, PopulateSessionHistoryEntryDocumentOutput::apply_to and
#       visit_edges, all_navigables, child_navigables, is_ancestor_of, the constructor,
#       destruction, visit_edges, NavigateParams::visit_edges, is_script_closable, delaying
#       load events, the session history entry accessors), with the inline functions of
#       Navigable.h that belong to them.
#
#       Copyright (c) 2022-2024, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2023-2025, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
#       Copyright (c) 2025, Luke Wilde <luke@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: NavigationParamsFetchStateHolder ========================================================

## Ported from Navigable.cpp:72 Web::HTML::NavigationParamsFetchStateHolder::NavigationParamsFetchStateHolder,
## with the default member initializers.
pub func html_navigation_params_fetch_state_holder_construct(this: HtmlNavigationParamsFetchStateHolder*, coop_enforcement_result: HtmlOpenerPolicyEnforcementResult, current_url: web_url.Url, request: FetchRequest*, initiator_origin: web_url.Origin?, history_policy_container: HtmlSerializedPolicyContainerOrHtmlDocumentStateClient, about_base_url: web_url.Url?, source_snapshot_params: HtmlSourceSnapshotParams*, request_referrer: FetchRequestReferrerType, request_referrer_policy: ReferrerPolicyReferrerPolicy, origin: web_url.Origin?, resource: EmptyOrStringOrHtmlPostResource, ever_populated: bool, navigable_target_name: ak.String):
    this.response_coop = HtmlOpenerPolicy()
    this.coop_enforcement_result = coop_enforcement_result
    this.current_url = current_url
    this.request = request
    this.initiator_origin = initiator_origin
    this.history_policy_container = history_policy_container
    this.about_base_url = about_base_url
    this.source_snapshot_params = source_snapshot_params
    this.request_referrer = request_referrer
    this.request_referrer_policy = request_referrer_policy
    this.origin = origin
    this.resource = resource
    this.ever_populated = ever_populated
    this.navigable_target_name = navigable_target_name

## Ported from Navigable.cpp:143 Web::HTML::NavigationParamsFetchStateHolder::visit_edges (override).
pub func html_navigation_params_fetch_state_holder_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlNavigationParamsFetchStateHolder*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.response)  # opaque in phase 1
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.fetch_controller)  # opaque in phase 1
    gc.cell_visitor_visit_t(visitor, this.response_policy_container)
    gc.cell_visitor_visit_t(visitor, this.commit_early_hints)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.request)  # opaque in phase 1
    gc.cell_visitor_visit_t(visitor, this.navigable)
    gc.cell_visitor_visit_t_2(visitor, this.source_snapshot_params)
    gc.cell_visitor_visit_t(visitor, this.continuation_steps)

## `realm.heap().allocate<NavigationParamsFetchStateHolder>(...)`: a fetch state holder cell
## constructed under DeferGC.
func heap_allocate_html_navigation_params_fetch_state_holder(heap: gc.Heap*, coop_enforcement_result: HtmlOpenerPolicyEnforcementResult, current_url: web_url.Url, request: FetchRequest*, initiator_origin: web_url.Origin?, history_policy_container: HtmlSerializedPolicyContainerOrHtmlDocumentStateClient, about_base_url: web_url.Url?, source_snapshot_params: HtmlSourceSnapshotParams*, request_referrer: FetchRequestReferrerType, request_referrer_policy: ReferrerPolicyReferrerPolicy, origin: web_url.Origin?, resource: EmptyOrStringOrHtmlPostResource, ever_populated: bool, navigable_target_name: ak.String) -> HtmlNavigationParamsFetchStateHolder*:
    let holder = (HtmlNavigationParamsFetchStateHolder*)web_heap_allocate_cell(heap, &html_navigation_params_fetch_state_holder_class)
    gc.heap_defer_gc(heap)
    html_navigation_params_fetch_state_holder_construct(holder, coop_enforcement_result, current_url, request, initiator_origin, history_policy_container, about_base_url, source_snapshot_params, request_referrer, request_referrer_policy, origin, resource, ever_populated, navigable_target_name)
    gc.heap_undefer_gc(heap)
    return holder

# mark: InternalNavigationResult ================================================================

## `realm.heap().allocate<InternalNavigationResult>()`: a result cell with its default member
## initializers (a null navigation params).
func heap_allocate_html_internal_navigation_result(heap: gc.Heap*) -> HtmlInternalNavigationResult*:
    let result = (HtmlInternalNavigationResult*)web_heap_allocate_cell(heap, &html_internal_navigation_result_class)
    result.navigation_params = HtmlNavigableNavigationParamsVariant.optional_string(none)
    return result

## The visit of a NavigationParamsVariant's navigation params (the visitor lambdas of
## InternalNavigationResult and PopulateSessionHistoryEntryDocumentOutput).
func html_visit_navigation_params_variant(visitor: gc.CellVisitor*, navigation_params: HtmlNavigableNavigationParamsVariant):
    match navigation_params:
        .optional_string(_):
            return
        .html_navigation_params(params):
            gc.cell_visitor_visit_t_2(visitor, params)
        .html_non_fetch_scheme_navigation_params(params):
            gc.cell_visitor_visit_t_2(visitor, params)

## Ported from Navigable.cpp:175 Web::HTML::InternalNavigationResult::visit_edges (override).
pub func html_internal_navigation_result_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlInternalNavigationResult*)base
    gc.cell_visit_edges_impl(base, visitor)
    html_visit_navigation_params_variant(visitor, this.navigation_params)

# mark: PopulateSessionHistoryEntryDocumentOutput ===============================================

## `heap().allocate<PopulateSessionHistoryEntryDocumentOutput>()`: an output cell with its
## default member initializers.
func heap_allocate_html_populate_session_history_entry_document_output(heap: gc.Heap*) -> HtmlPopulateSessionHistoryEntryDocumentOutput*:
    let output = (HtmlPopulateSessionHistoryEntryDocumentOutput*)web_heap_allocate_cell(heap, &html_populate_session_history_entry_document_output_class)
    output.navigation_params = HtmlNavigableNavigationParamsVariant.optional_string(none)
    html_populate_session_history_entry_document_output_init_fields(output)
    return output

## Ported from Navigable.cpp:189 Web::HTML::PopulateSessionHistoryEntryDocumentOutput::apply_to.
pub func html_populate_session_history_entry_document_output_apply_to(this: HtmlPopulateSessionHistoryEntryDocumentOutput*, entry: HtmlSessionHistoryEntry*):
    if let replacement = this.replacement_document_state:
        html_session_history_entry_set_document_state(entry, replacement)
    if let redirected_url = this.redirected_url:
        html_session_history_entry_set_url(entry, redirected_url)
    if let classic_history_api_state = this.classic_history_api_state:
        html_session_history_entry_set_classic_history_api_state(entry, classic_history_api_state)
        this.classic_history_api_state = none
    if this.resource_cleared:
        html_document_state_set_resource(html_session_history_entry_document_state(entry) else trap("no document state"), EmptyOrStringOrHtmlPostResource.empty)

    # Step from populate_session_history_entry_document()
    # 7. If entry's document state's document is not null, then:
    if let document = this.document:
        let document_state = html_session_history_entry_document_state(entry) else trap("no document state")
        html_document_state_set_document_id(document_state, dom_node_unique_id(document.dom_node()))

        # 1. Set entry's document state's ever populated to true.
        html_document_state_set_ever_populated(document_state, true)

        # 2. If saveExtraDocumentState is true:
        if this.save_extra_document_state:
            # 1. Set entry's document state's origin to document's origin.
            html_document_state_set_origin(document_state, dom_document_origin(document))

            # 2. If document's URL requires storing the policy container in history, then:
            if html_url_requires_storing_the_policy_container_in_history(dom_document_url(document)):
                # 1. Assert: navigationParams is a navigation params (i.e., neither null nor a non-fetch scheme navigation params).
                # 2. Set entry's document state's history policy container to navigationParams's policy container.
                match this.navigation_params:
                    .html_navigation_params(params):
                        let policy_container = params.policy_container else trap("dereferencing a null policy container")
                        html_document_state_set_history_policy_container(document_state, HtmlSerializedPolicyContainerOrHtmlDocumentStateClient.html_serialized_policy_container(html_policy_container_serialize(policy_container)))
                    _:
                        trap("VERIFY: navigation_params.has<GC::Ref<NavigationParams>>()")

        # 3. If entry's document state's request referrer is "client", and navigationParams is a navigation params (i.e., neither null nor a non-fetch scheme navigation params), then:
        if html_request_referrer_is_client(html_document_state_request_referrer(document_state)):
            if let params = html_navigation_params_variant_navigation_params(this.navigation_params):
                if let request = params.request:
                    # NB: We don't assert navigationParams's request is not null because srcdoc navigations create NavigationParams with a null request.

                    # 1. Set entry's document state's request referrer to navigationParams's request's referrer.
                    html_document_state_set_request_referrer(document_state, fetch_request_referrer(request))

## `referrer == Fetch::Infrastructure::Request::Referrer::Client` on a ReferrerType.
func html_request_referrer_is_client(referrer: FetchRequestReferrerType) -> bool:
    match referrer:
        .fetch_request_referrer(value):
            return value == FetchRequestReferrer.client
        .url(_):
            return false

## `navigation_params.get_pointer<GC::Ref<NavigationParams>>()` on a NavigationParamsVariant.
func html_navigation_params_variant_navigation_params(navigation_params: HtmlNavigableNavigationParamsVariant) -> HtmlNavigationParams*?:
    match navigation_params:
        .html_navigation_params(params):
            return params
        _:
            return none

## Ported from Navigable.cpp:237 Web::HTML::PopulateSessionHistoryEntryDocumentOutput::visit_edges (override).
pub func html_populate_session_history_entry_document_output_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlPopulateSessionHistoryEntryDocumentOutput*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.document)
    html_visit_navigation_params_variant(visitor, this.navigation_params)

# mark: All navigables ==========================================================================

## The static set of all_navigables: raw pointers (GC::RawRef), which keep nothing alive; a
## navigable's finalize removes it. It lives in the C heap.
var html_all_navigables_storage: ak.HashTable[HtmlNavigable*, ak.PtrTraits[HtmlNavigable]]

## Ported from Navigable.cpp:247 Web::HTML::all_navigables.
pub func html_all_navigables() -> ak.HashTable[HtmlNavigable*, ak.PtrTraits[HtmlNavigable]]*:
    return &html_all_navigables_storage

## Ported from Navigable.cpp:254 Web::HTML::Navigable::child_navigables.
# https://html.spec.whatwg.org/multipage/document-sequences.html#child-navigable
pub func html_navigable_child_navigables(this: HtmlNavigable*) -> ak.Vector[HtmlNavigable*?]:
    var results = ak.Vector[HtmlNavigable*?]()
    for entry_pointer in ak.hash_table_begin(html_all_navigables()):
        let entry = *entry_pointer
        let current_entry = html_navigable_current_session_history_entry(entry) else trap("no current session history entry")
        match html_session_history_entry_step(current_entry):
            .html_session_history_entry_pending(_):
                continue
            .i32_(_):
                if html_navigable_parent(entry) == this:
                    ak.vector_append_t(&results, entry)

    return results

## Ported from Navigable.cpp:267 Web::HTML::Navigable::is_ancestor_of.
pub func html_navigable_is_ancestor_of(this: HtmlNavigable*, other: HtmlNavigable*) -> bool:
    var ancestor = html_navigable_parent(other)
    while let current = ancestor:
        if current == this:
            return true
        ancestor = html_navigable_parent(current)
    return false

# mark: Construction and destruction ============================================================

## The capture of the rendering thread's presentation callback: the page's client.
struct HtmlNavigablePresentationCallbackCaptures:
    var page_client: PageClient*?

## The rendering thread's presentation callback of Navigable::Navigable.
func html_navigable_presentation_callback(context: void*?, viewport_rect: gfx.DevicePixelRect, bitmap_id: i32):
    let captures = (HtmlNavigablePresentationCallbackCaptures*)(context else trap("no captures"))
    if let client = captures.page_client:
        page_client_page_did_paint(client, viewport_rect, bitmap_id)

## `heap().allocate<Painting::BackingStoreManager>(*this)`: a BackingStoreManager cell constructed
## under DeferGC.
func heap_allocate_paint_backing_store_manager(heap: gc.Heap*, navigable: HtmlNavigable*) -> PaintBackingStoreManager*:
    let manager = (PaintBackingStoreManager*)web_heap_allocate_cell(heap, &paint_backing_store_manager_class)
    gc.heap_defer_gc(heap)
    paint_backing_store_manager_construct(manager, navigable)
    gc.heap_undefer_gc(heap)
    return manager

## Ported from Navigable.cpp:276 Web::HTML::Navigable::Navigable, with the default member
## initializers.
pub func html_navigable_construct(this: HtmlNavigable*, page: Page*, is_svg_page: bool):
    html_navigable_init_fields(this)
    this.m_ongoing_navigation = EmptyOrHtmlNavigableTraversalOrString.empty
    this.m_page = page
    event_handler_construct(&this.m_event_handler, this)
    this.m_is_svg_page = is_svg_page
    this.m_backing_store_manager = heap_allocate_paint_backing_store_manager(gc.cell_heap(this.cell()), this)
    let client = page_client(page)
    let captures = new HtmlNavigablePresentationCallbackCaptures(page_client = client) else trap("out of memory")
    html_rendering_thread_construct(&this.m_rendering_thread, ak.Function2[gfx.DevicePixelRect, i32, unit](call = html_navigable_presentation_callback, context = captures))

    with memory.heap:
        _ = ak.hash_table_set(html_all_navigables(), this)

    if not this.m_is_svg_page:
        let display_list_player_type = page_client_display_list_player_type(page_client(page))
        html_rendering_thread_set_skia_player(&this.m_rendering_thread, display_list.display_list_player_cpu_create())
        html_rendering_thread_start(&this.m_rendering_thread, display_list_player_type)

## Ported from Navigable.cpp:297 Web::HTML::Navigable::set_has_been_destroyed.
pub func html_navigable_set_has_been_destroyed(this: HtmlNavigable*):
    this.m_has_been_destroyed = true

## Ported from Navigable.cpp:302 Web::HTML::Navigable::remove_from_all_navigables.
pub func html_navigable_remove_from_all_navigables(this: HtmlNavigable*):
    if let document = this.m_active_document:
        dom_document_set_navigable(document, none)
    with memory.heap:
        _ = ak.hash_table_remove_t(html_all_navigables(), this)

## Ported from Navigable.cpp:309 Web::HTML::Navigable::finalize (override).
pub func html_navigable_finalize_impl(base: gc.Cell*):
    let this = (HtmlNavigable*)base
    with memory.heap:
        _ = ak.hash_table_remove_t(html_all_navigables(), this)
    gc.cell_finalize_impl(base)

## Ported from Navigable.cpp:315 Web::HTML::Navigable::visit_edges (override).
pub func html_navigable_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlNavigable*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t_2(visitor, this.m_page)
    gc.cell_visitor_visit_t(visitor, this.m_parent)
    gc.cell_visitor_visit_t(visitor, this.m_active_document)
    gc.cell_visitor_visit_t(visitor, this.m_container)
    gc.cell_visitor_visit_t_2(visitor, this.m_backing_store_manager)
    event_handler_visit_edges(&this.m_event_handler, visitor)

    for navigation_params in &ak.vector_span(&this.m_pending_navigations):
        html_navigable_navigate_params_visit_edges(navigation_params, visitor)

## Ported from Navigable.cpp:330 Web::HTML::Navigable::NavigateParams::visit_edges.
pub func html_navigable_navigate_params_visit_edges(this: HtmlNavigableNavigateParams*, visitor: gc.CellVisitor*):
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.response)  # opaque in phase 1
    gc.cell_visitor_visit_t_2(visitor, this.source_document)
    gc.cell_visitor_visit_t(visitor, this.source_element)
    if let entries = this.form_data_entry_list:
        for entry in ak.vector_span_const(&entries):
            match entry.value:
                .file_api_file(file):
                    gc.cell_visitor_visit_cell(visitor, (gc.Cell*)file)  # opaque in phase 1
                .string(_):
                    continue

# mark: Script-closability and delaying load events =============================================

## Ported from Navigable.cpp:344 Web::HTML::Navigable::is_script_closable.
# https://html.spec.whatwg.org/multipage/nav-history-apis.html#script-closable
pub func html_navigable_is_script_closable(this: HtmlNavigable*) -> bool:
    # A navigable is script-closable if it is a top-level traversable, and any of the following are true:
    # - its is created by web content is true; or
    # - its session history entries's size is 1.
    if not html_navigable_is_top_level_traversable(this):
        return false

    return html_traversable_navigable_is_created_by_web_content(as_html_traversable_navigable(this)) or ak.vector_size(html_navigable_get_session_history_entries(this)) == 1

## Ported from Navigable.cpp:356 Web::HTML::Navigable::set_delaying_load_events.
pub func html_navigable_set_delaying_load_events(this: HtmlNavigable*, value: bool):
    if value:
        let document = html_navigable_container_document(this) else trap("VERIFY: document")
        html_navigable_clear_load_event_delayer(&this.m_delaying_the_load_event)
        var delayer: DomDocumentLoadEventDelayer = ---
        dom_document_load_event_delayer_construct(&delayer, document)
        this.m_delaying_the_load_event = delayer
    else:
        html_navigable_clear_load_event_delayer(&this.m_delaying_the_load_event)

## Ported from Navigable.h:87 Web::HTML::Navigable::is_delaying_load_events.
pub func html_navigable_is_delaying_load_events(this: HtmlNavigable*) -> bool:
    return this.m_delaying_the_load_event != none

## `Optional<DocumentLoadEventDelayer>::clear()`: destroys a held delayer.
func html_navigable_clear_load_event_delayer(delayer: (DomDocumentLoadEventDelayer?)*):
    if let held = *delayer:
        var released = held
        dom_document_load_event_delayer_destruct(&released)
    *delayer = none

## Ported from Navigable.cpp:367 Web::HTML::Navigable::set_navigation_load_event_guard.
pub func html_navigable_set_navigation_load_event_guard(this: HtmlNavigable*, parent_doc: DomDocument*):
    html_navigable_clear_load_event_delayer(&this.m_navigation_load_event_guard)
    var guard: DomDocumentLoadEventDelayer = ---
    dom_document_load_event_delayer_construct(&guard, parent_doc)
    this.m_navigation_load_event_guard = guard

## Ported from Navigable.cpp:372 Web::HTML::Navigable::clear_navigation_load_event_guard.
pub func html_navigable_clear_navigation_load_event_guard(this: HtmlNavigable*):
    html_navigable_clear_load_event_delayer(&this.m_navigation_load_event_guard)

# mark: Session history entries =================================================================

## Ported from Navigable.cpp:377 Web::HTML::Navigable::active_session_history_entry.
pub func html_navigable_active_session_history_entry(this: HtmlNavigable*) -> HtmlSessionHistoryEntry*?:
    return this.m_active_session_history_entry

## Ported from Navigable.cpp:382 Web::HTML::Navigable::set_active_session_history_entry.
pub func html_navigable_set_active_session_history_entry(this: HtmlNavigable*, entry: HtmlSessionHistoryEntry*?):
    this.m_active_session_history_entry = entry

## Ported from Navigable.cpp:387 Web::HTML::Navigable::current_session_history_entry.
pub func html_navigable_current_session_history_entry(this: HtmlNavigable*) -> HtmlSessionHistoryEntry*?:
    return this.m_current_session_history_entry

## Ported from Navigable.cpp:392 Web::HTML::Navigable::set_current_session_history_entry.
pub func html_navigable_set_current_session_history_entry(this: HtmlNavigable*, entry: HtmlSessionHistoryEntry*?):
    this.m_current_session_history_entry = entry

# mark: Navigable.h =============================================================================

## Ported from Navigable.h:74 Web::HTML::Navigable::is_traversable (virtual).
pub func html_navigable_is_traversable_impl(this: HtmlNavigable*) -> bool:
    return false

## Ported from Navigable.h:76 Web::HTML::Navigable::id.
pub func html_navigable_id(this: HtmlNavigable*) -> ak.String:
    return this.m_id

## Ported from Navigable.h:77 Web::HTML::Navigable::parent.
pub func html_navigable_parent(this: HtmlNavigable*) -> HtmlNavigable*?:
    return this.m_parent

## Ported from Navigable.h:80 Web::HTML::Navigable::is_closing.
pub func html_navigable_is_closing(this: HtmlNavigable*) -> bool:
    return this.m_closing

## Ported from Navigable.h:81 Web::HTML::Navigable::set_closing.
pub func html_navigable_set_closing(this: HtmlNavigable*, value: bool):
    this.m_closing = value

## Ported from Navigable.h:118 Web::HTML::Navigable::is_top_level_traversable (virtual).
pub func html_navigable_is_top_level_traversable_impl(this: HtmlNavigable*) -> bool:
    return false

## Ported from Navigable.h:135 Web::HTML::Navigable::ongoing_navigation.
pub func html_navigable_ongoing_navigation(this: HtmlNavigable*) -> EmptyOrHtmlNavigableTraversalOrString:
    return this.m_ongoing_navigation

## Ported from Navigable.h:186 Web::HTML::Navigable::has_been_destroyed.
pub func html_navigable_has_been_destroyed(this: HtmlNavigable*) -> bool:
    return this.m_has_been_destroyed

## Ported from Navigable.h:207 Web::HTML::Navigable::page.
pub func html_navigable_page(this: HtmlNavigable*) -> Page*:
    return this.m_page

## Ported from Navigable.h:208 Web::HTML::Navigable::page (const).
pub func html_navigable_page_const(this: HtmlNavigable*) -> Page*:
    return this.m_page