Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / traversable_navigable_3.lucb

#==============================================================================================
#
#   traversable_navigable_3 - HTML::TraversableNavigable: applying a history step (the
#   continuations, the non-changing navigables, completion) and its entry points
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/HTML/TraversableNavigable.cpp lines 831-1165
#       (ApplyHistoryStepState::process_continuations, enter_waiting_for_non_changing_jobs and
#       complete, TraversableNavigable::apply_the_history_step and
#       apply_the_history_step_after_unload_check).
#
#       Copyright (c) 2022, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2023-2025, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Processing continuations ================================================================

## The when_resolved callback of a synchronous navigation's steps run during process_continuations.
func html_apply_history_step_state_sync_navigation_resolved(context: void*?, arg0: ak.Empty*):
    let this = (HtmlApplyHistoryStepState*)(context else trap("no state"))
    # 5. Set traversable's running nested apply history step to false.
    assert(this.m_pending_sync_nav_promise != none)
    this.m_pending_sync_nav_promise = none
    this.m_traversable.m_apply_history_step_state = this
    this.m_traversable.m_paused_apply_history_step_state = none
    html_apply_history_step_state_process_continuations(this)

## The captures of process_continuations' afterPotentialUnloads (step 12).
struct HtmlApplyHistoryStepStateAfterPotentialUnload:
    var this: HtmlApplyHistoryStepState*
    var navigable: HtmlNavigable*
    var update_only: bool
    var target_entry: HtmlSessionHistoryEntry*
    var continuation: HtmlChangingNavigableContinuationState*
    var population_output: HtmlPopulateSessionHistoryEntryDocumentOutput*?
    var old_origin: web_url.Origin?
    var displayed_document_id: i64?
    var script_history_length: u64
    var script_history_index: u64
    var entries_for_navigation_api: ak.Vector[HtmlSessionHistoryEntry*]
    var navigation_type: BindNavigationType?

## The captures of afterPotentialUnloads' updateDocument.
struct HtmlApplyHistoryStepStateUpdateDocument:
    var script_history_length: u64
    var script_history_index: u64
    var entries_for_navigation_api: ak.Vector[HtmlSessionHistoryEntry*]
    var target_entry: HtmlSessionHistoryEntry*
    var update_only: bool
    var navigation_type: BindNavigationType?
    var previous_entry: HtmlSessionHistoryEntry*?
    var resolved_document: DomDocument*

## afterPotentialUnloads' updateDocument.
func html_apply_history_step_state_update_document(context: void*?):
    let captures = (HtmlApplyHistoryStepStateUpdateDocument*)(context else trap("no captures"))
    dom_document_update_for_history_step_application(captures.resolved_document, captures.target_entry, captures.update_only, usize(captures.script_history_length), usize(captures.script_history_index), captures.navigation_type, captures.entries_for_navigation_api, captures.previous_entry, captures.navigation_type != none)

## process_continuations' afterPotentialUnloads.
func html_apply_history_step_state_after_potential_unload(context: void*?):
    let captures = (HtmlApplyHistoryStepStateAfterPotentialUnload*)(context else trap("no captures"))
    let this = captures.this
    let navigable = captures.navigable
    let target_entry = captures.target_entry
    let continuation = captures.continuation

    if let population_output = captures.population_output:
        html_populate_session_history_entry_document_output_apply_to(population_output, target_entry)

    # Post-population adjustments — only run when a fresh document was produced
    # (not for 204/205 no-document outcomes where resolved_document is the old active document).
    var output_document: DomDocument*? = none
    if let population_output = captures.population_output:
        output_document = population_output.document
    let has_fresh_document = this.m_pending_document != none or output_document != none
    if has_fresh_document:
        let resolved_document = continuation.resolved_document else trap("no resolved document")
        # 2. If targetEntry's document's origin is not oldOrigin, then set targetEntry's classic history API state to StructuredSerializeForStorage(null).
        if not html_optional_origin_equals(dom_document_origin(resolved_document), captures.old_origin):
            let vm = js_cell_vm(navigable.js_cell())
            html_session_history_entry_set_classic_history_api_state(target_entry, html_structured_serialize_for_storage(vm, js_null()) else trap("MUST: structured_serialize_for_storage"))

        # 3. If all of the following are true:
        #     - navigable's parent is null;
        #     - targetEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
        #     - targetEntry's document's origin is not oldOrigin,
        #    then set targetEntry's document state's navigable target name to the empty string.
        let resolved_browsing_context = dom_document_browsing_context(resolved_document) else trap("no browsing context")
        let target_state = html_session_history_entry_document_state(target_entry) else trap("no document state")
        if html_navigable_parent(navigable) == none and not (html_browsing_context_is_auxiliary(resolved_browsing_context) and html_browsing_context_opener_browsing_context(resolved_browsing_context) != none) and not html_optional_origin_equals(html_document_state_origin(target_state), captures.old_origin):
            html_document_state_set_navigable_target_name(target_state, ak.string_new())

    # 1. Let previousEntry be navigable's active session history entry.
    let previous_entry = html_navigable_active_session_history_entry(navigable)

    # 2. If changingNavigableContinuation's update-only is false, then activate history entry targetEntry for navigable.
    let resolved_document = continuation.resolved_document else trap("no resolved document")
    if not captures.update_only:
        html_navigable_activate_history_entry(navigable, target_entry, resolved_document)

    # 3. Let updateDocument be an algorithm step which performs update document for history step application given
    #    targetEntry's document, targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength,
    #    scriptHistoryIndex, navigationType, entriesForNavigationAPI, and previousEntry.
    let update_document = new HtmlApplyHistoryStepStateUpdateDocument(script_history_length = captures.script_history_length, script_history_index = captures.script_history_index, entries_for_navigation_api = captures.entries_for_navigation_api, target_entry = target_entry, update_only = captures.update_only, navigation_type = captures.navigation_type, previous_entry = previous_entry, resolved_document = resolved_document) else trap("out of memory")

    # 4. If targetEntry's document is equal to displayedDocument, then perform updateDocument.
    # NOTE: We compare against the pre-activation displayed_document_id (not the current
    #       active entry) because activate_history_entry() has already updated the active entry above.
    if html_document_state_document_id(html_session_history_entry_document_state(target_entry) else trap("no document state")) == captures.displayed_document_id:
        html_apply_history_step_state_update_document(update_document)
    # AD-HOC: When the document already has its parser pre-loaded with in-memory data (currently set up
    #         only for about:srcdoc), perform updateDocument synchronously instead of queueing it.
    #         updateDocument calls Document::set_ready_to_run_scripts(), which kicks off the deferred
    #         parser. Running it in the same task as activation guarantees the body element exists before
    #         script in the parent navigable can observe the new document — matching Chrome and Firefox
    #         behavior for srcdoc iframes.
    elif dom_document_has_deferred_parser_start(resolved_document):
        html_apply_history_step_state_update_document(update_document)
    # 5. Otherwise, queue a global task on the navigation and traversal task source given targetEntry's document's relevant global object to perform updateDocument
    else:
        _ = html_queue_global_task(HtmlTaskSource.navigation_and_traversal, html_relevant_global_object((JsObject*)resolved_document), gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_apply_history_step_state_update_document, context = update_document)))

    # 6. Increment completedChangeJobs.
    html_apply_history_step_state_signal_progress(this)

## Ported from TraversableNavigable.cpp:831 Web::HTML::ApplyHistoryStepState::process_continuations.
pub func html_apply_history_step_state_process_continuations(this: HtmlApplyHistoryStepState*):
    while true:
        # NOTE: Synchronous navigations that are intended to take place before this traversal jump the queue at this point,
        #       so they can be added to the correct place in traversable's session history entries before this traversal
        #       potentially unloads their document. More details can be found here (https://html.spec.whatwg.org/multipage/browsing-the-web.html#sync-navigation-steps-queue-jumping-examples)
        # 1. If traversable's running nested apply history step is false, then:
        if this.m_traversable.m_paused_apply_history_step_state == none:
            # 1. While traversable's session history traversal queue's algorithm set contains one or more synchronous
            #    navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation:
            #   1. Let steps be the first item in traversable's session history traversal queue's algorithm set
            #    that is synchronous navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation.
            #   2. Remove steps from traversable's session history traversal queue's algorithm set.
            if let entry = html_session_history_traversal_queue_first_synchronous_navigation_steps_with_target_navigable_not_contained_in(this.m_traversable.m_session_history_traversal_queue, &this.m_navigables_that_must_wait_before_handling_sync_navigation):
                assert(this.m_traversable.m_paused_apply_history_step_state == none)
                this.m_traversable.m_paused_apply_history_step_state = this

                # 4. Run steps.
                let promise = core_promise_construct[ak.Empty, ak.AkError]()
                html_session_history_traversal_queue_entry_execute_steps(entry, promise)

                # GC safety: `this` is kept alive by m_paused_apply_history_step_state (visited).
                # The promise is kept alive by m_pending_sync_nav_promise (RefPtr).
                assert(this.m_pending_sync_nav_promise == none)
                this.m_pending_sync_nav_promise = promise
                _ = core_promise_when_resolved(promise, ak.Function1[ak.Empty*, unit](call = html_apply_history_step_state_sync_navigation_resolved, context = this))
                return

        if this.m_continuation_index == ak.vector_size(&this.m_continuations):
            if this.m_phase == HtmlApplyHistoryStepStatePhase.processing_continuations:
                this.m_phase = HtmlApplyHistoryStepStatePhase.waiting_for_change_job_completion
                html_apply_history_step_state_try_advance(this)
            return

        # 3. If changingNavigableContinuation is nothing, then continue.

        let continuation = *ak.vector_at(&this.m_continuations, this.m_continuation_index)
        this.m_continuation_index += 1

        # 4. Let displayedDocument be changingNavigableContinuation's displayed document.
        let displayed_document = continuation.displayed_document else trap("no displayed document")

        # 5. Let targetEntry be changingNavigableContinuation's target entry.
        let population_output = continuation.population_output
        let old_origin = continuation.old_origin

        # 6. Let navigable be changingNavigableContinuation's navigable.
        let navigable = continuation.navigable else trap("no navigable")

        # AD-HOC: We should not continue navigation if navigable has been destroyed.
        if html_navigable_has_been_destroyed(navigable):
            html_apply_history_step_state_signal_progress(this)
            continue
        # AD-HOC: The displayed document may have been destroyed during the nested step execution above.
        if dom_document_navigable(displayed_document) == none:
            html_apply_history_step_state_signal_progress(this)
            continue

        assert(this.m_target_step == html_traversable_navigable_get_the_used_step(this.m_traversable, this.m_step))

        # 7. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
        let history_object_length_and_index = html_traversable_navigable_get_the_history_object_length_and_index(this.m_traversable, this.m_target_step)
        let script_history_length = history_object_length_and_index.script_history_length
        let script_history_index = history_object_length_and_index.script_history_index

        # 8. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation.
        _ = ak.hash_table_set(&this.m_navigables_that_must_wait_before_handling_sync_navigation, navigable)

        # 9. Let entriesForNavigationAPI be the result of getting session history entries for the navigation API given navigable and targetStep.
        let entries_for_navigation_api = html_traversable_navigable_get_session_history_entries_for_the_navigation_api(this.m_traversable, navigable, this.m_target_step)

        # NOTE: Steps 10 and 11 come after step 12.

        # 12. In both cases, let afterPotentialUnloads be the following steps:
        let target_entry = continuation.target_entry else trap("no target entry")
        let captures = new HtmlApplyHistoryStepStateAfterPotentialUnload(this = this, navigable = navigable, update_only = continuation.update_only, target_entry = target_entry, continuation = continuation, population_output = population_output, old_origin = old_origin, displayed_document_id = continuation.displayed_document_id, script_history_length = script_history_length, script_history_index = script_history_index, entries_for_navigation_api = entries_for_navigation_api, navigation_type = this.m_navigation_type) else trap("out of memory")
        let after_potential_unload = gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_apply_history_step_state_after_potential_unload, context = captures))

        # 10. If changingNavigableContinuation's update-only is true, or targetEntry's document is displayedDocument, then:
        if continuation.update_only or continuation.resolved_document == displayed_document:
            # 1. Set the ongoing navigation for navigable to null.
            html_navigable_set_ongoing_navigation(navigable, EmptyOrHtmlNavigableTraversalOrString.empty)

            # 2. Queue a global task on the navigation and traversal task source given navigable's active window to perform afterPotentialUnloads.
            _ = html_queue_global_task(HtmlTaskSource.navigation_and_traversal, (JsObject*)(html_navigable_active_window(navigable) else trap("no active window")), after_potential_unload)
        # 11. Otherwise:
        else:
            # 1. Assert: navigationType is not null.
            assert(this.m_navigation_type != none)

            # 2. Deactivate displayedDocument, given userInvolvement, targetEntry, navigationType, and afterPotentialUnloads.
            html_deactivate_a_document_for_cross_document_navigation(displayed_document, this.m_user_involvement, target_entry, continuation.resolved_document, after_potential_unload)

# mark: Non-changing navigables and completion ==================================================

## The captures of enter_waiting_for_non_changing_jobs' per-navigable task.
struct HtmlApplyHistoryStepStateNonChangingTask:
    var this: HtmlApplyHistoryStepState*
    var navigable: HtmlNavigable*
    var script_history_length: u64
    var script_history_index: u64

## enter_waiting_for_non_changing_jobs' step 18 task for one navigable.
func html_apply_history_step_state_non_changing_navigable(context: void*?):
    let captures = (HtmlApplyHistoryStepStateNonChangingTask*)(context else trap("no captures"))
    let this = captures.this
    let navigable = captures.navigable
    if html_navigable_has_been_destroyed(navigable) or html_navigable_active_window(navigable) == none or not dom_document_is_fully_active(html_navigable_active_document(navigable) else trap("no active document")):
        html_apply_history_step_state_signal_progress(this)
        return

    # 1. Let document be navigable's active document.
    let document = html_navigable_active_document(navigable) else trap("no active document")

    # 2. Set document's history object's index to scriptHistoryIndex.
    html_history_set_index(dom_document_history(document), usize(captures.script_history_index))

    # 3. Set document's history object's length to scriptHistoryLength.
    html_history_set_length(dom_document_history(document), usize(captures.script_history_length))

    # 4. Increment completedNonchangingJobs.
    html_apply_history_step_state_signal_progress(this)

## Ported from TraversableNavigable.cpp:1009 Web::HTML::ApplyHistoryStepState::enter_waiting_for_non_changing_jobs.
pub func html_apply_history_step_state_enter_waiting_for_non_changing_jobs(this: HtmlApplyHistoryStepState*):
    assert(this.m_target_step == html_traversable_navigable_get_the_used_step(this.m_traversable, this.m_step))

    # 17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
    let length_and_index = html_traversable_navigable_get_the_history_object_length_and_index(this.m_traversable, this.m_target_step)
    let script_history_length = length_and_index.script_history_length
    let script_history_index = length_and_index.script_history_index

    # 18. For each navigable of nonchangingNavigablesThatStillNeedUpdates, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
    for navigable in ak.vector_span(&this.m_non_changing_navigables):
        # AD-HOC: This check is not in the spec but we should not continue navigation if navigable has been destroyed,
        #         or if there's no active window.
        if html_navigable_has_been_destroyed(navigable) or html_navigable_active_window(navigable) == none:
            this.m_completed_non_changing_jobs += 1
            continue
        # AD-HOC: Queue with null document instead of using queue_global_task.
        #         Tasks associated with a document are only runnable when fully active.
        #         In the async state machine, documents can become non-fully-active between
        #         queue time and execution, causing the task to be permanently stuck.
        #         A null-document task is always runnable; we check validity inside.
        let task = new HtmlApplyHistoryStepStateNonChangingTask(this = this, navigable = navigable, script_history_length = script_history_length, script_history_index = script_history_index) else trap("out of memory")
        _ = html_queue_a_task(HtmlTaskSource.navigation_and_traversal, none, none, gc.create_function0(gc.cell_heap(this.cell()), ak.Function0[unit](call = html_apply_history_step_state_non_changing_navigable, context = task)))

    html_apply_history_step_state_try_advance(this)

## Ported from TraversableNavigable.cpp:1054 Web::HTML::ApplyHistoryStepState::complete.
pub func html_apply_history_step_state_complete(this: HtmlApplyHistoryStepState*):
    if this.m_phase == HtmlApplyHistoryStepStatePhase.completed:
        return
    this.m_phase = HtmlApplyHistoryStepStatePhase.completed
    platform_timer_stop(this.m_timeout)

    let traversable = this.m_traversable

    # 20. Set traversable's current session history step to targetStep.
    traversable.m_current_session_history_step = this.m_target_step

    # Not in the spec:
    let back_enabled = traversable.m_current_session_history_step > 0
    assert(ak.vector_size(&traversable.m_session_history_entries) > 0)
    let forward_enabled = html_traversable_navigable_can_go_forward(traversable)
    let client = page_client(html_navigable_page(traversable.html_navigable()))
    page_client_page_did_update_navigation_buttons_state(client, back_enabled, forward_enabled)
    page_client_page_did_change_url(client, html_session_history_entry_url(html_navigable_current_session_history_entry(traversable.html_navigable()) else trap("no current session history entry")))

    # Clear state BEFORE on_complete, because on_complete may resolve a promise
    # that triggers the next session history traversal queue entry.
    # For nested states, the outer state is restored by the when_resolved callback
    # on the sync nav step's promise in process_continuations().
    traversable.m_apply_history_step_state = none

    # 21. Return "applied".
    if let on_complete = this.m_on_complete:
        ak.function1_call(&on_complete.function, HtmlHistoryStepResult.applied)

# mark: Applying the history step ===============================================================

## The captures of apply_the_history_step's unload check callback.
struct HtmlTraversableNavigableApplyTheHistoryStepChecked:
    var this: HtmlTraversableNavigable*
    var step: i32
    var target_step: i32
    var source_snapshot_params: HtmlSourceSnapshotParams*?
    var user_involvement: HtmlUserNavigationInvolvement
    var navigation_type: BindNavigationType?
    var synchronous_navigation: HtmlTraversableNavigableSynchronousNavigation
    var pending_document: DomDocument*?
    var on_complete: gc.Function1[HtmlHistoryStepResult, unit]*

## apply_the_history_step's step 5 callback: the result of checking if unloading is canceled.
func html_traversable_navigable_apply_the_history_step_checked(context: void*?, result: HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult):
    let captures = (HtmlTraversableNavigableApplyTheHistoryStepChecked*)(context else trap("no captures"))
    if result == HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.canceled_by_before_unload:
        ak.function1_call(&captures.on_complete.function, HtmlHistoryStepResult.canceled_by_before_unload)
        return
    if result == HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult.canceled_by_navigate:
        ak.function1_call(&captures.on_complete.function, HtmlHistoryStepResult.canceled_by_navigate)
        return
    html_traversable_navigable_apply_the_history_step_after_unload_check(captures.this, captures.step, captures.target_step, captures.source_snapshot_params, captures.user_involvement, captures.navigation_type, captures.synchronous_navigation, captures.pending_document, captures.on_complete)

## Ported from TraversableNavigable.cpp:1083 Web::HTML::TraversableNavigable::apply_the_history_step.
# https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-history-step
func html_traversable_navigable_apply_the_history_step(this: HtmlTraversableNavigable*, step: i32, check_for_cancelation: bool, source_snapshot_params: HtmlSourceSnapshotParams*?, initiator_to_check: HtmlNavigable*?, user_involvement: HtmlUserNavigationInvolvement, navigation_type: BindNavigationType?, synchronous_navigation: HtmlTraversableNavigableSynchronousNavigation, pending_document: DomDocument*?, on_complete: gc.Function1[HtmlHistoryStepResult, unit]*):
    # FIXME: 1. Assert: This is running within traversable's session history traversal queue.

    assert(this.m_apply_history_step_state == none or this.m_paused_apply_history_step_state != none)

    # 2. Let targetStep be the result of getting the used step given traversable and step.
    let target_step = html_traversable_navigable_get_the_used_step(this, step)

    # 3. If initiatorToCheck is not null, then:
    if let initiator = initiator_to_check:
        # 1. Assert: sourceSnapshotParams is not null.
        let snapshot = source_snapshot_params else trap("VERIFY: source_snapshot_params")

        # 2. For each navigable of get all navigables whose current session history entry will change or reload:
        #    if initiatorToCheck is not allowed by sandboxing to navigate navigable given sourceSnapshotParams, then return "initiator-disallowed".
        var navigables = html_traversable_navigable_get_all_navigables_whose_current_session_history_entry_will_change_or_reload(this, target_step)
        for navigable in ak.vector_span(&navigables):
            if not html_navigable_allowed_by_sandboxing_to_navigate(initiator, navigable else trap("no navigable"), snapshot):
                ak.function1_call(&on_complete.function, HtmlHistoryStepResult.initiator_disallowed)
                return

    # 4. Let navigablesCrossingDocuments be the result of getting all navigables that might experience a cross-document traversal given traversable and targetStep.
    let navigables_crossing_documents = html_traversable_navigable_get_all_navigables_that_might_experience_a_cross_document_traversal(this, target_step)

    # 5. If checkForCancelation is true, and the result of checking if unloading is canceled given navigablesCrossingDocuments, traversable, targetStep,
    #    and userInvolvement is not "continue", then return that result.
    if check_for_cancelation:
        let captures = new HtmlTraversableNavigableApplyTheHistoryStepChecked(this = this, step = step, target_step = target_step, source_snapshot_params = source_snapshot_params, user_involvement = user_involvement, navigation_type = navigation_type, synchronous_navigation = synchronous_navigation, pending_document = pending_document, on_complete = on_complete) else trap("out of memory")
        html_traversable_navigable_check_if_unloading_is_canceled_html_traversable_navigable(this, navigables_crossing_documents, this, target_step, user_involvement, gc.create_function1(gc.cell_heap(this.cell()), ak.Function1[HtmlTraversableNavigableCheckIfUnloadingIsCanceledResult, unit](call = html_traversable_navigable_apply_the_history_step_checked, context = captures)))
        return

    # 6. Let changingNavigables be the result of get all navigables whose current session history entry will change or reload given traversable and targetStep.
    html_traversable_navigable_apply_the_history_step_after_unload_check(this, step, target_step, source_snapshot_params, user_involvement, navigation_type, synchronous_navigation, pending_document, on_complete)

## Ported from TraversableNavigable.cpp:1141 Web::HTML::TraversableNavigable::apply_the_history_step_after_unload_check.
func html_traversable_navigable_apply_the_history_step_after_unload_check(this: HtmlTraversableNavigable*, step: i32, target_step: i32, source_snapshot_params: HtmlSourceSnapshotParams*?, user_involvement: HtmlUserNavigationInvolvement, navigation_type: BindNavigationType?, synchronous_navigation: HtmlTraversableNavigableSynchronousNavigation, pending_document: DomDocument*?, on_complete: gc.Function1[HtmlHistoryStepResult, unit]*):
    let state = heap_allocate_html_apply_history_step_state(gc.cell_heap(this.cell()), this, step, target_step, source_snapshot_params, user_involvement, navigation_type, synchronous_navigation, pending_document, on_complete)

    assert(this.m_apply_history_step_state == none or this.m_paused_apply_history_step_state != none)
    this.m_apply_history_step_state = state

    html_apply_history_step_state_start(state)