Truly independent web browser
LibWebView: Keep a history step's changing navigables on its run
Shannon Booth2b8127992b39
diff --git a/Libraries/LibWebView/ApplyHistoryStep.cpp b/Libraries/LibWebView/ApplyHistoryStep.cppindex ee9c9319be8..34344b15188 100644--- a/Libraries/LibWebView/ApplyHistoryStep.cpp+++ b/Libraries/LibWebView/ApplyHistoryStep.cpp@@ -4,18 +4,16 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/ScopeGuard.h>#include <LibWebView/ApplyHistoryStep.h>-#include <LibWebView/CanonicalNavigable.h>+#include <LibWebView/CanonicalDocument.h>+#include <LibWebView/CanonicalTraversable.h>+#include <LibWebView/NavigationLoader.h>namespace WebView {ApplyHistoryStep::ApplyHistoryStep(- TraversableSessionHistory& session_history,- CanonicalNavigable& traversable_navigable,- SessionHistoryTraversalQueue& session_history_traversal_queue,- TraversableApplyHistoryStepState& traversable_state,- ApplyHistoryStepJobs jobs,+ CanonicalTraversable& traversable,+ HistoryOperation& operation,Web::HTML::CrossProcessId operation_id,u64 operation_sequence_number,i32 step,@@ -25,11 +23,11 @@ ApplyHistoryStep::ApplyHistoryStep(Web::HTML::UserNavigationInvolvement user_involvement,Optional<Web::Bindings::NavigationType> navigation_type,Function<void(Web::HTML::HistoryStepResult)> on_complete)- : m_session_history(session_history)- , m_traversable_navigable(traversable_navigable)- , m_session_history_traversal_queue(session_history_traversal_queue)- , m_traversable_state(traversable_state)- , m_jobs(move(jobs))+ : m_traversable(traversable)+ , m_session_history(traversable.m_session_history)+ , m_session_history_traversal_queue(traversable.m_history_traversal_queue)+ , m_traversable_state(traversable.m_apply_history_step_traversable_state)+ , m_operation(operation), m_operation_id(operation_id), m_operation_sequence_number(operation_sequence_number), m_step(step)@@ -39,13 +37,12 @@ ApplyHistoryStep::ApplyHistoryStep(, m_user_involvement(user_involvement), m_navigation_type(navigation_type), m_on_complete(move(on_complete))- , m_generation(++traversable_state.generation_counter)+ , m_generation(++m_traversable_state.generation_counter){}ApplyHistoryStep::~ApplyHistoryStep(){- clear_all_ongoing_navigation_traversals();if (m_running_synchronous_navigation_steps)m_traversable_state.running_nested_apply_history_step = false;}@@ -70,23 +67,19 @@ void ApplyHistoryStep::apply_the_history_step()// 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".- auto const* initiator = find_navigable(*m_initiator_to_check);+ auto initiator = m_traversable.find(*m_initiator_to_check);// NB: sourceSnapshotParams's sandboxing flags are its source document's, which the UI process holds too.Web::InitiatorSourceSnapshot source_snapshot_params {.sandboxing_flags = m_source_snapshot_params->sandboxing_flags,.has_transient_activation = m_source_snapshot_params->has_transient_activation,};- if (initiator)+ if (initiator.has_value())source_snapshot_params.sandboxing_flags |= initiator->active_document().active_sandboxing_flag_set();- for (auto navigable_id : m_session_history.get_all_navigables_whose_current_session_history_entry_will_change_or_reload(m_traversable_navigable, m_target_step)) {- auto const* navigable = find_navigable(navigable_id);- if (!navigable)- continue;-+ for (auto& navigable : m_session_history.get_all_navigables_whose_current_session_history_entry_will_change_or_reload(m_traversable, m_target_step)) {// NB: A removed initiator is no longer related to any navigable in the canonical tree. Apply the sandboxed// navigation flag instead of treating the missing relationship as permission.- auto allowed = initiator- ? initiator->allowed_by_sandboxing_to_navigate(*navigable, source_snapshot_params)+ auto allowed = initiator.has_value()+ ? initiator->allowed_by_sandboxing_to_navigate(navigable, source_snapshot_params): !has_flag(source_snapshot_params.sandboxing_flags, Web::HTML::SandboxingFlagSet::SandboxedNavigation);if (!allowed) {return_result(Web::HTML::HistoryStepResult::InitiatorDisallowed);@@ -97,7 +90,7 @@ void ApplyHistoryStep::apply_the_history_step()// 4. Let navigablesCrossingDocuments be the result of getting all navigables that might experience a// cross-document traversal given traversable and targetStep.- auto navigables_crossing_documents = m_session_history.get_all_navigables_that_might_experience_a_cross_document_traversal(m_traversable_navigable, m_target_step);+ auto navigables_crossing_documents = m_session_history.get_all_navigables_that_might_experience_a_cross_document_traversal(m_traversable, m_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@@ -107,13 +100,11 @@ void ApplyHistoryStep::apply_the_history_step()return;}- auto* target_entry = m_session_history.get_the_target_history_entry(m_traversable_navigable, m_target_step);+ auto* target_entry = m_session_history.get_the_target_history_entry(m_traversable, m_target_step);VERIFY(target_entry);- m_jobs.check_if_unloading_is_canceled(move(navigables_crossing_documents), *target_entry, m_user_involvement,+ m_traversable.check_if_unloading_is_canceled(*this, move(navigables_crossing_documents), *target_entry, m_user_involvement,[this](Web::HTML::CheckIfUnloadingIsCanceledResult result) {- if (m_completed)- return;switch (result) {case Web::HTML::CheckIfUnloadingIsCanceledResult::CanceledByBeforeUnload:return_result(Web::HTML::HistoryStepResult::CanceledByBeforeUnload);@@ -132,8 +123,7 @@ void ApplyHistoryStep::get_changing_and_nonchanging_navigables(){// 6. Let changingNavigables be the result of get all navigables whose current session history entry will change// or reload given traversable and targetStep.- for (auto navigable_id : m_session_history.get_all_navigables_whose_current_session_history_entry_will_change_or_reload(m_traversable_navigable, m_target_step))- m_changing_navigables.append({ .id = navigable_id });+ auto changing_navigables = m_session_history.get_all_navigables_whose_current_session_history_entry_will_change_or_reload(m_traversable, m_target_step);// AD-HOC: Unconditionally populating a document here could unload and re-navigate a frame because an unrelated// navigable was created or destroyed, which no other engine does. So an update for a navigable's creation@@ -141,39 +131,36 @@ void ApplyHistoryStep::get_changing_and_nonchanging_navigables()// document. A navigable its creation marked as traversing is the exception: it populates the entry its// nested history kept. See https://github.com/whatwg/html/issues/12724.if (!m_navigation_type.has_value()) {- m_changing_navigables.remove_all_matching([&](ChangingNavigable const& changing_navigable) {- auto const* navigable = find_navigable(changing_navigable.id);- auto const* target_entry = navigable ? m_session_history.get_the_target_history_entry(*navigable, m_target_step) : nullptr;- if (!target_entry)- return false;- auto crosses_documents = !navigable->active_document_is(*target_entry) || target_entry->document_state->reload_pending;- return navigable->ongoing_navigation_id().has_value() || (crosses_documents && !navigable->ongoing_navigation().has<CanonicalNavigable::Traversal>());+ changing_navigables.remove_all_matching([&](CanonicalNavigable const& navigable) {+ auto const& target_entry = *m_session_history.get_the_target_history_entry(navigable, m_target_step);+ auto crosses_documents = !navigable.active_document_is(target_entry) || target_entry.document_state->reload_pending;+ return navigable.ongoing_navigation_id().has_value() || (crosses_documents && !navigable.ongoing_navigation().has<CanonicalNavigable::Traversal>());});}// 7. Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need// history object length/index update given traversable and targetStep.- m_nonchanging_navigables_that_still_need_updates = m_session_history.get_all_navigables_that_only_need_history_object_length_index_update(m_traversable_navigable, m_target_step);+ m_nonchanging_navigables_that_still_need_updates = m_session_history.get_all_navigables_that_only_need_history_object_length_index_update(m_traversable, m_target_step);// 8. For each navigable of changingNavigables:- for (auto& changing_navigable : m_changing_navigables) {- auto* navigable = find_navigable(changing_navigable.id);-+ for (auto& navigable : changing_navigables) {// 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.- auto* target_entry = navigable ? m_session_history.get_the_target_history_entry(*navigable, m_target_step) : nullptr;- if (!target_entry)- continue;+ auto* target_entry = m_session_history.get_the_target_history_entry(navigable, m_target_step);+ VERIFY(target_entry);++ m_changing_navigables.append(make<ChangingNavigable>(navigable, *target_entry));+ auto& changing_navigable = *m_changing_navigables.last();// 2. Set navigable's current session history entry to targetEntry.- navigable->set_current_session_history_entry(target_entry);+ navigable.set_current_session_history_entry(target_entry);// 3. If targetEntry's document is not navigable's active document, then queue a global task on the navigation// and traversal task source of navigable's active window to run these steps:- if (!navigable->active_document_is(*target_entry))- m_jobs.queue_navigation_api_state_clear_task(changing_navigable.id);+ if (!navigable.active_document_is(*target_entry))+ m_traversable.queue_navigation_api_state_clear_task(*this, changing_navigable);// 4. Set navigable's ongoing navigation to "traversal".- set_ongoing_navigation_to_traversal(changing_navigable, *navigable, *target_entry);+ set_ongoing_navigation_to_traversal(changing_navigable, navigable, *target_entry);}run_changing_navigable_jobs();@@ -181,60 +168,26 @@ void ApplyHistoryStep::get_changing_and_nonchanging_navigables()void ApplyHistoryStep::run_changing_navigable_jobs(){- // 12. For each navigable of changingNavigables, queue a global task on the navigation and traversal task source.+ // 12. For each navigable of changingNavigables, queue a global task on the navigation and traversal task source of+ // navigable's active window to run the steps:for (auto& changing_navigable : m_changing_navigables) {- auto navigable_id = changing_navigable.id;- auto const* navigable = find_navigable(navigable_id);- auto* target_entry = navigable ? m_session_history.get_the_target_history_entry(*navigable, m_target_step) : nullptr;- if (!target_entry) {- // AD-HOC: The canonical mirror can briefly disagree with the live navigable tree while a created or- // removed child navigable is reconciled; complete the job as skipped instead of dispatching it.- changing_navigable_job_completed(navigable_id, Web::HTML::ChangingNavigableHistoryStepJobDisposition::Skipped);- continue;- }-- ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob job {- .navigable_id = navigable_id,- .target_entry = *target_entry,- .target_entry_reload_pending = target_entry->document_state->reload_pending,- .user_involvement = m_user_involvement,- .navigation_type = m_navigation_type,- .traversal_yields_to = changing_navigable.traversal_yields_to,- .canceled_navigation_id = changing_navigable.canceled_navigation_id,- .source_snapshot_params = m_source_snapshot_params,- };- if (!m_jobs.select_changing_navigable_history_step_job_endpoint(job)) {- changing_navigable_job_completed(navigable_id, Web::HTML::ChangingNavigableHistoryStepJobDisposition::Skipped);- continue;- }- changing_navigable.claimed_target_entry = target_entry;-- m_jobs.run_changing_navigable_history_step_job(- move(job),- [this, navigable_id](Web::HTML::ChangingNavigableHistoryStepJobDisposition disposition) {- changing_navigable_job_completed(navigable_id, disposition);- });+ changing_navigable->target_entry_reload_pending = changing_navigable->target_entry->document_state->reload_pending;+ if (!m_traversable.run_changing_navigable_history_step_job(*this, *changing_navigable))+ end_changing_navigable_job(*changing_navigable);}- m_changing_jobs_dispatched = true;process_changing_navigable_continuations();}-void ApplyHistoryStep::changing_navigable_job_completed(Web::HTML::CrossProcessId navigable_id, Web::HTML::ChangingNavigableHistoryStepJobDisposition disposition)+void ApplyHistoryStep::changing_navigable_job_completed(ChangingNavigable& changing_navigable, Web::HTML::ChangingNavigableHistoryStepJobDisposition disposition){- if (m_completed)- return;-- if (disposition != Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready)- clear_ongoing_navigation_traversal(navigable_id);-switch (disposition) {case Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready:// 4. Enqueue changingNavigableContinuation on changingNavigableContinuations.- m_changing_navigable_continuations.append(navigable_id);+ m_changing_navigable_continuations.append(&changing_navigable);break;case Web::HTML::ChangingNavigableHistoryStepJobDisposition::Skipped:- m_completed_change_jobs++;+ end_changing_navigable_job(changing_navigable);break;case Web::HTML::ChangingNavigableHistoryStepJobDisposition::Stale:// NB: A stale run completes with "applied" so callers waiting on it proceed; the newer navigation that made@@ -243,25 +196,44 @@ void ApplyHistoryStep::changing_navigable_job_completed(Web::HTML::CrossProcessIreturn;}- if (m_changing_jobs_dispatched- && !m_processing_changing_navigable_continuations- && !m_continuation_in_flight- && !m_running_synchronous_navigation_steps) {- process_changing_navigable_continuations();- }+ process_changing_navigable_continuations();+}++// The job ends, without activating the document it populated.+void ApplyHistoryStep::end_changing_navigable_job(ChangingNavigable& changing_navigable)+{+ auto& navigable = changing_navigable.navigable();+ changing_navigable.job_ended = true;+ if (auto population_loader = move(changing_navigable.population_loader))+ population_loader->reclaim_response_body_after_failed_handoff();+ if (auto document = move(changing_navigable.populated_document))+ navigable.abandon_populated_document(changing_navigable.target_entry->document_state, *document);+ navigable.clear_ongoing_navigation_traversal(m_operation_id);++ m_changing_navigable_continuations.remove_first_matching([&](auto* continuation) { return continuation == &changing_navigable; });+ if (m_continuation_being_applied == &changing_navigable)+ m_continuation_being_applied = nullptr;++ // 14.12.6. Increment completedChangeJobs.+ // NB: Also for a job that ends without its continuation being applied.+ m_completed_change_jobs++;+}++// NB: The page each update was sent to owes its reply, so an update completes once.+void ApplyHistoryStep::nonchanging_navigable_updated()+{+ // 18.4. Increment completedNonchangingJobs.+ m_completed_nonchanging_jobs++;++ // 19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.+ if (m_completed_nonchanging_jobs == m_nonchanging_navigables_that_still_need_updates.size())+ set_current_session_history_step();}void ApplyHistoryStep::process_changing_navigable_continuations(){- if (m_completed- || m_processing_changing_navigable_continuations- || m_continuation_in_flight- || m_running_synchronous_navigation_steps) {+ if (m_continuation_being_applied || m_running_synchronous_navigation_steps)return;- }-- m_processing_changing_navigable_continuations = true;- ScopeGuard processing_guard = [this] { m_processing_changing_navigable_continuations = false; };// 14. While completedChangeJobs does not equal totalChangeJobs:while (m_completed_change_jobs != m_changing_navigables.size()) {@@ -306,12 +278,13 @@ void ApplyHistoryStep::process_changing_navigable_continuations()continue;}m_running_synchronous_navigation_steps = promise;- promise->when_resolved([weak_this = make_weak_ptr()](Empty&) {- if (!weak_this)+ promise->when_resolved([&traversable = m_traversable, operation_id = m_operation_id](Empty&) {+ auto* run = traversable.find_history_step_run(operation_id);+ if (!run)return;- weak_this->m_traversable_state.running_nested_apply_history_step = false;- weak_this->m_running_synchronous_navigation_steps = nullptr;- weak_this->process_changing_navigable_continuations();+ run->m_traversable_state.running_nested_apply_history_step = false;+ run->m_running_synchronous_navigation_steps = nullptr;+ run->process_changing_navigable_continuations();});return;}@@ -323,13 +296,13 @@ void ApplyHistoryStep::process_changing_navigable_continuations()// 3. If changingNavigableContinuation is nothing, then continue.if (m_changing_navigable_continuations.is_empty())return;- auto navigable_id = m_changing_navigable_continuations.take_first();+ auto& changing_navigable_continuation = *m_changing_navigable_continuations.take_first();// NB: targetStep was computed before the asynchronous parts of this algorithm. Re-normalize it in case a// child navigable's removal made it unused meanwhile.m_target_step = m_session_history.get_the_used_step(m_step).value();- auto* navigable = find_navigable(navigable_id);+ auto& navigable = changing_navigable_continuation.navigable();// AD-HOC: The spec has the continuation activate the target entry the job's task retained, without checking it// against the session history again. But the sync navigations that jumped the queue above ran while the@@ -350,10 +323,9 @@ void ApplyHistoryStep::process_changing_navigable_continuations()// CanonicalBrowsingContext::SessionHistoryCommit, WebKit HistoryController::updateForStandardLoad,// Blink NavigationControllerImpl::RendererDidNavigateToNewEntry.// NB: navigable's own sync navigations wait from step 8 on. So, none of them can change the entry after this.- auto* target_entry = navigable ? m_session_history.get_the_target_history_entry(*navigable, m_target_step) : nullptr;+ auto* target_entry = m_session_history.get_the_target_history_entry(navigable, m_target_step);RefPtr<CanonicalSessionHistoryEntry> updated_target_entry;- auto* changing_navigable = find_changing_navigable(navigable_id);- if (auto claimed_target_entry = changing_navigable ? changing_navigable->claimed_target_entry : nullptr; target_entry && claimed_target_entry) {+ if (NonnullRefPtr claimed_target_entry = changing_navigable_continuation.target_entry; target_entry) {auto is_in_claimed_slot = target_entry->document_state == claimed_target_entry->document_state&& target_entry->navigation_api_key == claimed_target_entry->navigation_api_key;if (is_in_claimed_slot) {@@ -363,12 +335,10 @@ void ApplyHistoryStep::process_changing_navigable_continuations()return_result(Web::HTML::HistoryStepResult::Applied);return;} else if (m_navigation_type == Web::Bindings::NavigationType::Push) {- target_entry = append_the_claimed_target_entry_again(*navigable, *claimed_target_entry);+ target_entry = append_the_claimed_target_entry_again(navigable, *claimed_target_entry);if (!target_entry) {- // NB: The push left the navigable no entries to append to. As for a navigable that is gone, its- // continuation cannot be applied.- clear_ongoing_navigation_traversal(navigable_id);- m_completed_change_jobs++;+ // NB: The push left the navigable no entries to append to, so its continuation cannot be applied.+ end_changing_navigable_job(changing_navigable_continuation);continue;}updated_target_entry = target_entry;@@ -380,40 +350,30 @@ void ApplyHistoryStep::process_changing_navigable_continuations()auto history_object_length_and_index = m_session_history.get_the_history_object_length_and_index(m_target_step);// 8. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation.- m_navigables_that_must_wait_before_handling_sync_navigation.set(navigable_id);+ m_navigables_that_must_wait_before_handling_sync_navigation.set(changing_navigable_continuation.id);// 9. Let entriesForNavigationAPI be the result of getting session history entries for the navigation API// given navigable and targetStep.- auto entries_for_navigation_api = navigable ? m_session_history.get_session_history_entries_for_the_navigation_api(*navigable, m_target_step) : Optional<Vector<Web::HTML::SessionHistoryEntryDescriptor>> {};- if (!navigable || !history_object_length_and_index.has_value() || !entries_for_navigation_api.has_value()) {- // AD-HOC: The navigable is gone, or the canonical mirror is reconciling it. Its continuation cannot be- // applied; count the job as completed and move on.- clear_ongoing_navigation_traversal(navigable_id);- m_completed_change_jobs++;+ auto entries_for_navigation_api = m_session_history.get_session_history_entries_for_the_navigation_api(navigable, m_target_step);+ if (!history_object_length_and_index.has_value() || !entries_for_navigation_api.has_value()) {+ // AD-HOC: The canonical mirror is reconciling the navigable, so its continuation cannot be applied.+ end_changing_navigable_job(changing_navigable_continuation);continue;}- // NB: One continuation is applied at a time, so synchronous navigations queued by its application are in the- // traversal queue before the next continuation checks for them.- m_continuation_in_flight = true;- m_jobs.apply_changing_navigable_history_step_continuation(- {- .navigable_id = navigable_id,- .updated_target_entry = move(updated_target_entry),- .history_object_length_and_index = *history_object_length_and_index,- .entries_for_navigation_api = entries_for_navigation_api.release_value(),- },- [this, navigable_id] {- if (m_completed)- return;- m_continuation_in_flight = false;- clear_ongoing_navigation_traversal(navigable_id);- // 10. Increment completedChangeJobs.- m_completed_change_jobs++;- process_changing_navigable_continuations();- });- if (m_continuation_in_flight)- return;+ // If a sync navigation that jumped the queue changed the job's target entry while the job was paused, then the+ // job follows, so that the entry recorded as the navigable's active one is the entry as the session history has+ // it.+ if (updated_target_entry)+ changing_navigable_continuation.target_entry = updated_target_entry.release_nonnull();++ m_continuation_being_applied = &changing_navigable_continuation;+ changing_navigable_continuation.continuation = ChangingNavigable::Continuation {+ .history_object_length_and_index = *history_object_length_and_index,+ .entries_for_navigation_api = entries_for_navigation_api.release_value(),+ };+ m_traversable.apply_changing_navigable_history_step_continuation(*this, changing_navigable_continuation);+ return;}update_nonchanging_navigables();@@ -450,7 +410,7 @@ void ApplyHistoryStep::update_nonchanging_navigables()// 17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index// given traversable and targetStep.auto history_object_length_and_index = m_session_history.get_the_history_object_length_and_index(m_target_step);- if (!history_object_length_and_index.has_value() || m_nonchanging_navigables_that_still_need_updates.is_empty()) {+ if (!history_object_length_and_index.has_value()) {set_current_session_history_step();return;}@@ -458,17 +418,13 @@ void ApplyHistoryStep::update_nonchanging_navigables()// 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 (auto navigable_id : m_nonchanging_navigables_that_still_need_updates) {- m_jobs.update_nonchanging_navigable_history_step_state(navigable_id, *history_object_length_and_index, [this] {- if (m_completed)- return;- // 4. Increment completedNonchangingJobs.+ if (!m_traversable.update_nonchanging_navigable_history_step_state(*this, navigable_id, *history_object_length_and_index))m_completed_nonchanging_jobs++;-- // 19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.- if (m_completed_nonchanging_jobs == m_nonchanging_navigables_that_still_need_updates.size())- set_current_session_history_step();- });}++ // 19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.+ if (m_completed_nonchanging_jobs == m_nonchanging_navigables_that_still_need_updates.size())+ set_current_session_history_step();}void ApplyHistoryStep::set_current_session_history_step()@@ -493,17 +449,20 @@ void ApplyHistoryStep::set_current_session_history_step()return_result(Web::HTML::HistoryStepResult::Applied);}+void ApplyHistoryStep::abandon()+{+ for (auto& changing_navigable : m_changing_navigables) {+ if (changing_navigable->has_pending_job())+ end_changing_navigable_job(*changing_navigable);+ }+}+void ApplyHistoryStep::return_result(Web::HTML::HistoryStepResult result){- if (m_completed)- return;- m_completed = true;- clear_all_ongoing_navigation_traversals();- if (m_on_complete)- m_on_complete(result);+ m_on_complete(result);}-Web::HTML::SessionHistoryEntryDescriptor ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob::target_entry_descriptor() const+Web::HTML::SessionHistoryEntryDescriptor ChangingNavigable::target_entry_descriptor() const{auto descriptor = target_entry->descriptor();descriptor.document_state.reload_pending = target_entry_reload_pending;@@ -535,7 +494,6 @@ void ApplyHistoryStep::set_ongoing_navigation_to_traversal(ChangingNavigable& chif (m_navigation_type == Web::Bindings::NavigationType::Reload && newer_navigation_was_admitted)return;navigable.set_ongoing_navigation_to_traversal(m_operation_id);- changing_navigable.has_ongoing_history_traversal = true;return;}@@ -554,37 +512,10 @@ void ApplyHistoryStep::set_ongoing_navigation_to_traversal(ChangingNavigable& chnavigable.clear_ongoing_navigation();}-ApplyHistoryStep::ChangingNavigable* ApplyHistoryStep::find_changing_navigable(Web::HTML::CrossProcessId navigable_id)-{- auto it = m_changing_navigables.find_if([&](auto const& changing_navigable) { return changing_navigable.id == navigable_id; });- return it == m_changing_navigables.end() ? nullptr : &*it;-}--void ApplyHistoryStep::clear_ongoing_navigation_traversal(Web::HTML::CrossProcessId navigable_id)-{- auto* changing_navigable = find_changing_navigable(navigable_id);- if (!changing_navigable || !exchange(changing_navigable->has_ongoing_history_traversal, false))- return;- if (auto* navigable = find_navigable(navigable_id))- navigable->clear_ongoing_navigation_traversal(m_operation_id);-}--void ApplyHistoryStep::clear_all_ongoing_navigation_traversals()-{- for (auto& changing_navigable : m_changing_navigables)- clear_ongoing_navigation_traversal(changing_navigable.id);-}--CanonicalNavigable* ApplyHistoryStep::find_navigable(Web::HTML::CrossProcessId navigable_id)+ChangingNavigable* ApplyHistoryStep::changing_navigable(Web::HTML::CrossProcessId navigable_id) const{- CanonicalNavigable* result = nullptr;- m_traversable_navigable.for_each_in_inclusive_subtree([&](CanonicalNavigable& navigable) {- if (navigable.id() != navigable_id)- return IterationDecision::Continue;- result = &navigable;- return IterationDecision::Break;- });- return result;+ auto it = m_changing_navigables.find_if([&](auto const& changing_navigable) { return changing_navigable->id == navigable_id; });+ return it == m_changing_navigables.end() ? nullptr : it->ptr();}}diff --git a/Libraries/LibWebView/ApplyHistoryStep.h b/Libraries/LibWebView/ApplyHistoryStep.hindex 715ded64af0..a2e56e18dff 100644--- a/Libraries/LibWebView/ApplyHistoryStep.h+++ b/Libraries/LibWebView/ApplyHistoryStep.h@@ -9,6 +9,7 @@#include <AK/Function.h>#include <AK/HashMap.h>#include <AK/HashTable.h>+#include <AK/NonnullOwnPtr.h>#include <AK/Optional.h>#include <AK/RefPtr.h>#include <AK/Utf16String.h>@@ -21,6 +22,7 @@#include <LibWebCommon/HTML/HistoryOperation.h>#include <LibWebCommon/HTML/NavigationSourceSnapshot.h>#include <LibWebCommon/HTML/UserNavigationInvolvement.h>+#include <LibWebView/CanonicalNavigable.h>#include <LibWebView/Export.h>#include <LibWebView/Forward.h>#include <LibWebView/SessionHistory.h>@@ -28,56 +30,57 @@namespace WebView {-// Cross-process jobs used by apply the history step. Each job must complete exactly once, including after endpoint-// loss, and must not call back after its operation completes.-struct WEBVIEW_API ApplyHistoryStepJobs {-- // https://html.spec.whatwg.org/multipage/browsing-the-web.html#checking-if-unloading-is-canceled- // NB: Given targetStep's target entry, which the traversable's host resolves no further.- Function<void(Vector<Web::HTML::CrossProcessId> navigables_that_need_before_unload, NonnullRefPtr<CanonicalSessionHistoryEntry> target_entry, Web::HTML::UserNavigationInvolvement user_involvement_for_navigate_event, Function<void(Web::HTML::CheckIfUnloadingIsCanceledResult)> on_complete)> check_if_unloading_is_canceled;-- // NB: This queued work runs in the process hosting the active Window.- Function<void(Web::HTML::CrossProcessId navigable_id)> queue_navigation_api_state_clear_task;-- // One iteration of "12. For each navigable of changingNavigables, queue a global task ...". The job claims its- // navigable and either enqueues a changing navigable continuation in its own process (Ready) or reports why it- // could not (see Web::HTML::ChangingNavigableHistoryStepJobDisposition).- struct ChangingNavigableHistoryStepJob {- Web::HTML::CrossProcessId navigable_id;- // The target entry selected from canonical session history. The receiving process retains this exact entry- // instead of resolving a target step against its local session history projection.- NonnullRefPtr<CanonicalSessionHistoryEntry> target_entry;- // Whether the target entry's document state's reload pending was true when the job claimed it. Populating the- // document sets it to false.- bool target_entry_reload_pending { false };-- // The target entry as the job claimed it, for the processes the job runs in.- Web::HTML::SessionHistoryEntryDescriptor target_entry_descriptor() const;- Web::HTML::UserNavigationInvolvement user_involvement { Web::HTML::UserNavigationInvolvement::None };- Optional<Web::Bindings::NavigationType> navigation_type;- Web::HTML::TraversalYieldsTo traversal_yields_to { Web::HTML::TraversalYieldsTo::Nothing };- // The admitted navigation a same-document traversal canceled.- Optional<Utf16String> canceled_navigation_id {};- Optional<Web::HTML::NavigationSourceSnapshot> source_snapshot_params {};- };- Function<bool(ChangingNavigableHistoryStepJob&)> select_changing_navigable_history_step_job_endpoint;- Function<void(ChangingNavigableHistoryStepJob, Function<void(Web::HTML::ChangingNavigableHistoryStepJobDisposition)> on_complete)> run_changing_navigable_history_step_job;-- // The "second part" of a changing navigable's job ("12. In both cases, let afterPotentialUnloads be ..."),- // applied to the continuation the job enqueued in its own process.- struct ApplyChangingNavigableHistoryStepContinuation {- Web::HTML::CrossProcessId navigable_id;- // The job's target entry as the session history has it now, if a sync navigation that jumped the queue while- // the job was paused changed that: The entry that replaced it in its slot, which the continuation activates- // instead — or the target entry itself at a later step, if the run had to append it again.- RefPtr<CanonicalSessionHistoryEntry> updated_target_entry {};+// One of a run's changingNavigables: its history step job, and the changing navigable continuation the job enqueues.+// NB: The process running the job retains the rest of the continuation's state. What waits on the job looks the record+// up again by its operation and navigable, which name it for as long as its run lasts.+struct WEBVIEW_API ChangingNavigable {+ AK_ALLOC_WITH_KMALLOC;++ ChangingNavigable(CanonicalNavigable& navigable, NonnullRefPtr<CanonicalSessionHistoryEntry> target_entry)+ : id(navigable.id())+ , target_entry(move(target_entry))+ , m_navigable(navigable.make_weak_ptr())+ {+ }++ CanonicalNavigable& navigable() const+ {+ VERIFY(m_navigable);+ return *m_navigable;+ }++ bool has_pending_job() const { return !job_ended; }++ Web::HTML::CrossProcessId id;++ // The process running the job retains this exact entry instead of resolving a target step against its local session+ // history projection. The run looks it up again before it is activated, and follows a sync navigation that changed+ // it (whatwg/html#12961).+ NonnullRefPtr<CanonicalSessionHistoryEntry> target_entry;+ // Whether targetEntry's document state's reload pending was true when the job claimed it. Populating the document+ // sets it to false.+ bool target_entry_reload_pending { false };+ // The target entry as the job claimed it, for the processes the job runs in.+ Web::HTML::SessionHistoryEntryDescriptor target_entry_descriptor() const;++ // Nothing more comes from the process running the job, and it counts towards completedChangeJobs.+ bool job_ended { false };+ // AD-HOC: What a same-document traversal yields to, with the admitted navigation it canceled.+ Web::HTML::TraversalYieldsTo traversal_yields_to { Web::HTML::TraversalYieldsTo::Nothing };+ Optional<Utf16String> canceled_navigation_id {};+ // The run's part of the continuation, which the process running the job applies with the rest.+ struct Continuation {Web::HTML::HistoryObjectLengthAndIndex history_object_length_and_index;Vector<Web::HTML::SessionHistoryEntryDescriptor> entries_for_navigation_api;};- Function<void(ApplyChangingNavigableHistoryStepContinuation, Function<void()> on_complete)> apply_changing_navigable_history_step_continuation;+ Optional<Continuation> continuation;- // One iteration of "18. For each navigable of nonchangingNavigablesThatStillNeedUpdates, queue a global task ...".- Function<void(Web::HTML::CrossProcessId navigable_id, Web::HTML::HistoryObjectLengthAndIndex, Function<void()> on_complete)> update_nonchanging_navigable_history_step_state;+ Web::HTML::UnloadDisplayedDocument unload_displayed_document { Web::HTML::UnloadDisplayedDocument::No };+ RefPtr<NavigationLoader> population_loader;+ RefPtr<CanonicalDocument> populated_document;++private:+ WeakPtr<CanonicalNavigable> m_navigable;};// The apply-history-step state a traversable navigable shares across runs.@@ -97,10 +100,10 @@ struct TraversableApplyHistoryStepState {// https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-history-step//// One run of the apply-the-history-step algorithm, coordinated from the UI process. The algorithm's traversal-wide-// variables live on this object; the per-navigable jobs run through caller-supplied functions in the processes-// hosting the documents, and their completion callbacks resume the algorithm at the phase that dispatched them.-class WEBVIEW_API ApplyHistoryStep- : public Weakable<ApplyHistoryStep> {+// variables live on this object; the traversable runs the per-navigable jobs in the processes hosting the documents,+// and their completions resume the algorithm at the phase that dispatched them. Each job reports to the run exactly+// once, including after its process is lost.+class WEBVIEW_API ApplyHistoryStep {AK_MAKE_NONCOPYABLE(ApplyHistoryStep);AK_MAKE_NONMOVABLE(ApplyHistoryStep);@@ -108,11 +111,8 @@ public:AK_ALLOC_WITH_KMALLOC;ApplyHistoryStep(- TraversableSessionHistory& session_history,- CanonicalNavigable& traversable_navigable,- SessionHistoryTraversalQueue& session_history_traversal_queue,- TraversableApplyHistoryStepState& traversable_state,- ApplyHistoryStepJobs jobs,+ CanonicalTraversable& traversable,+ HistoryOperation& operation,Web::HTML::CrossProcessId operation_id,u64 operation_sequence_number,i32 step,@@ -125,34 +125,43 @@ public:~ApplyHistoryStep();void apply_the_history_step();+ // The run's operation finished. Its pending jobs end, and it calls none of its jobs from then on.+ void abandon();- bool completed() const { return m_completed; }// The step this run committed as the current session history step, if it was the run that committed.Optional<i32> committed_step() const { return m_committed_step; }+ HistoryOperation& operation() const { return m_operation; }+ Web::HTML::CrossProcessId operation_id() const { return m_operation_id; }+ Web::HTML::UserNavigationInvolvement user_involvement() const { return m_user_involvement; }+ Optional<Web::Bindings::NavigationType> navigation_type() const { return m_navigation_type; }+ Optional<Web::HTML::NavigationSourceSnapshot> const& source_snapshot_params() const { return m_source_snapshot_params; }++ Vector<NonnullOwnPtr<ChangingNavigable>> const& changing_navigables() const { return m_changing_navigables; }+ ChangingNavigable* changing_navigable(Web::HTML::CrossProcessId) const;++ void changing_navigable_job_completed(ChangingNavigable&, Web::HTML::ChangingNavigableHistoryStepJobDisposition);+ void nonchanging_navigable_updated();+ // The run goes on once its continuations are processed again.+ void end_changing_navigable_job(ChangingNavigable&);+ void process_changing_navigable_continuations();+private:void get_changing_and_nonchanging_navigables();void run_changing_navigable_jobs();- void process_changing_navigable_continuations();void update_nonchanging_navigables();void set_current_session_history_step();CanonicalSessionHistoryEntry* append_the_claimed_target_entry_again(CanonicalNavigable&, CanonicalSessionHistoryEntry& claimed_target_entry);- void changing_navigable_job_completed(Web::HTML::CrossProcessId, Web::HTML::ChangingNavigableHistoryStepJobDisposition);- struct ChangingNavigable;- ChangingNavigable* find_changing_navigable(Web::HTML::CrossProcessId);void set_ongoing_navigation_to_traversal(ChangingNavigable&, CanonicalNavigable&, CanonicalSessionHistoryEntry const&);- void clear_ongoing_navigation_traversal(Web::HTML::CrossProcessId);- void clear_all_ongoing_navigation_traversals();void return_result(Web::HTML::HistoryStepResult);- CanonicalNavigable* find_navigable(Web::HTML::CrossProcessId);+ CanonicalTraversable& m_traversable;TraversableSessionHistory& m_session_history;- CanonicalNavigable& m_traversable_navigable;SessionHistoryTraversalQueue& m_session_history_traversal_queue;TraversableApplyHistoryStepState& m_traversable_state;- ApplyHistoryStepJobs m_jobs;+ HistoryOperation& m_operation;Web::HTML::CrossProcessId const m_operation_id;u64 const m_operation_sequence_number;@@ -169,21 +178,13 @@ private:// The algorithm's variables.i32 m_target_step { 0 };- struct ChangingNavigable {- Web::HTML::CrossProcessId id;- // The target entry the navigable's job claimed, looked up again before it is activated (whatwg/html#12961).- RefPtr<CanonicalSessionHistoryEntry> claimed_target_entry {};- // AD-HOC: What a same-document traversal yields to, with the admitted navigation it canceled.- Web::HTML::TraversalYieldsTo traversal_yields_to { Web::HTML::TraversalYieldsTo::Nothing };- Optional<Utf16String> canceled_navigation_id {};- bool has_ongoing_history_traversal { false };- };- Vector<ChangingNavigable> m_changing_navigables;+ Vector<NonnullOwnPtr<ChangingNavigable>> m_changing_navigables;Vector<Web::HTML::CrossProcessId> m_nonchanging_navigables_that_still_need_updates;size_t m_completed_change_jobs { 0 };- // NB: The continuation states live in the processes that ran the jobs; this queue holds the navigables whose- // continuations are ready to be applied.- Vector<Web::HTML::CrossProcessId> m_changing_navigable_continuations;+ Vector<ChangingNavigable*> m_changing_navigable_continuations;+ // AD-HOC: One continuation is applied at a time, so synchronous navigations queued by its application are in the+ // traversal queue before the next continuation checks for them.+ ChangingNavigable* m_continuation_being_applied { nullptr };HashTable<Web::HTML::CrossProcessId> m_navigables_that_must_wait_before_handling_sync_navigation;size_t m_completed_nonchanging_jobs { 0 };@@ -195,12 +196,7 @@ private:// The synchronous navigation steps this run is paused on ("running nested apply history step" is true).RefPtr<Core::Promise<Empty>> m_running_synchronous_navigation_steps;- bool m_changing_jobs_dispatched { false };- bool m_processing_changing_navigable_continuations { false };- bool m_continuation_in_flight { false };-Optional<i32> m_committed_step;- bool m_completed { false };};}diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cppindex 24754a0c61a..82c7c12100f 100644--- a/Libraries/LibWebView/CanonicalTraversable.cpp+++ b/Libraries/LibWebView/CanonicalTraversable.cpp@@ -952,7 +952,7 @@ StringView CanonicalTraversable::browser_history_traversal_stage_to_string(BrowsVERIFY_NOT_REACHED();}-struct CanonicalTraversable::HistoryOperation {+struct HistoryOperation {AK_ALLOC_WITH_KMALLOC;// A traversal from the browser's UI, to the step selected at its queue position.@@ -985,35 +985,12 @@ struct CanonicalTraversable::HistoryOperation {bool finished { false };Optional<Web::HTML::CrossProcessId> beforeunload_check_id;- struct PendingChangingJob {- AK_ALLOC_WITH_KMALLOC;-- PendingChangingJob(ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob job, Function<void(Web::HTML::ChangingNavigableHistoryStepJobDisposition)> on_complete)- : job(move(job))- , on_complete(move(on_complete))- {- }-- void abandon(Optional<CanonicalNavigable&> navigable)- {- if (population_loader)- population_loader->reclaim_response_body_after_failed_handoff();- if (navigable.has_value() && document)- navigable->abandon_populated_document(job.target_entry->document_state, *document);- }-- ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob job;- Function<void(Web::HTML::ChangingNavigableHistoryStepJobDisposition)> on_complete;- Optional<ApplyHistoryStepJobs::ApplyChangingNavigableHistoryStepContinuation> continuation;- Function<void()> on_continuation_complete;-- Web::HTML::UnloadDisplayedDocument unload_displayed_document { Web::HTML::UnloadDisplayedDocument::No };+ ChangingNavigable* pending_changing_job(Web::HTML::CrossProcessId navigable_id) const+ {+ auto* changing_navigable = algorithm ? algorithm->changing_navigable(navigable_id) : nullptr;+ return changing_navigable && changing_navigable->has_pending_job() ? changing_navigable : nullptr;+ }- RefPtr<NavigationLoader> population_loader;- RefPtr<CanonicalDocument> document;- };- HashMap<Web::HTML::CrossProcessId, NonnullOwnPtr<PendingChangingJob>> pending_changing_jobs;- HashMap<Web::HTML::CrossProcessId, Function<void()>> pending_nonchanging_updates;OwnPtr<ApplyHistoryStep> algorithm;RefPtr<Core::Promise<Empty>> queue_promise;@@ -1049,7 +1026,7 @@ size_t CanonicalTraversable::effective_current_session_history_step_index() consreturn m_session_history.current_used_step_index();}-CanonicalTraversable::HistoryOperation* CanonicalTraversable::ongoing_browser_history_traversal()+HistoryOperation* CanonicalTraversable::ongoing_browser_history_traversal(){return m_browser_history_traversal;}@@ -1258,8 +1235,8 @@ void CanonicalTraversable::did_not_receive_reply(OwedReply const& owed)auto* operation = find_history_operation(owed.id);if (!operation || awaits_crash_recovery)return;- if (auto on_complete = operation->pending_nonchanging_updates.take(owed.navigable_id); on_complete.has_value())- (*on_complete)();+ if (operation->algorithm)+ operation->algorithm->nonchanging_navigable_updated();return;}case OwedReply::Kind::ChangingJob:@@ -1268,15 +1245,15 @@ void CanonicalTraversable::did_not_receive_reply(OwedReply const& owed)auto* operation = find_history_operation(owed.id);if (!operation || awaits_crash_recovery)return;- if (auto complete = end_changing_navigable_history_step_job(*operation, owed.navigable_id, Web::HTML::ChangingNavigableHistoryStepJobDisposition::Skipped))- complete();+ if (auto* changing_navigable = operation->pending_changing_job(owed.navigable_id))+ operation->algorithm->changing_navigable_job_completed(*changing_navigable, Web::HTML::ChangingNavigableHistoryStepJobDisposition::Skipped);return;}}VERIFY_NOT_REACHED();}-CanonicalTraversable::HistoryOperation* CanonicalTraversable::find_history_operation(Web::HTML::CrossProcessId operation_id)+HistoryOperation* CanonicalTraversable::find_history_operation(Web::HTML::CrossProcessId operation_id){auto operation = m_history_operations.find(operation_id);if (operation == m_history_operations.end())@@ -1284,6 +1261,12 @@ CanonicalTraversable::HistoryOperation* CanonicalTraversable::find_history_operareturn operation->value.ptr();}+ApplyHistoryStep* CanonicalTraversable::find_history_step_run(Web::HTML::CrossProcessId operation_id)+{+ auto* operation = find_history_operation(operation_id);+ return operation ? operation->algorithm.ptr() : nullptr;+}+bool CanonicalTraversable::navigation_transaction_matches(HistoryOperation const& operation, WebContentPage& page, Optional<Web::HTML::CrossProcessId> reply_navigable_id) const{if (!operation.parameters.has<Web::FinalizeCrossDocumentNavigationHistoryOperationParameters>())@@ -1303,54 +1286,13 @@ void CanonicalTraversable::add_history_operation_completion_endpoint(HistoryOperoperation.completion_endpoints.append(move(endpoint));}-bool CanonicalTraversable::select_changing_navigable_history_step_job_endpoint(HistoryOperation& operation, ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob& job)-{- auto navigable = find(job.navigable_id);- if (!navigable.has_value())- return false;-- auto endpoint = changing_job_endpoint(*navigable, *job.target_entry->document_state);- if (!endpoint || !endpoint->is_open())- return false;-- if (navigable->is_top_level_traversable()) {- if (!operation.parameters.has<Web::ReloadHistoryOperationParameters>()- && job.target_entry->document_state->document.ptr() != &navigable->active_document()) {- if (auto view = this->view(); view.has_value())- view->reset_blocked_request_count();- }- if (operation.is_browser_traversal()) {- if (auto callback = move(operation.browser_traversal().on_ready))- callback();- }- }-- add_history_operation_completion_endpoint(operation, *endpoint);-- // A reload's top-level job repopulates the view's document; begin the recorded load where the job is- // dispatched instead of having the job echo it back.- if (navigable->is_top_level_traversable()- && operation.parameters.has<Web::ReloadHistoryOperationParameters>()) {- if (endpoint->is_open()) {- // A load a history operation starts, rather than a navigation, is tracked as the active document's.- clear_active_document_load();- endpoint->begin_top_level_load(job.target_entry->url);- }- }- return true;-}-void CanonicalTraversable::did_finish_history_navigation_params_creation(WebContentPage& source_page, Web::HTML::CrossProcessId operation_id, Web::HTML::HistoryNavigationPopulation population){auto navigable_id = population.request.navigable_id;- auto* operation = find_history_operation(operation_id);auto discard = [&] { NavigationLoader::discard(source_page.client().is_private(), population.result); };- if (!operation) {- discard();- return;- }- auto job = operation->pending_changing_jobs.get(navigable_id);- if (!job.has_value() || job.value()->population_loader+ auto* operation = find_history_operation(operation_id);+ auto* changing_navigable = operation ? operation->pending_changing_job(navigable_id) : nullptr;+ if (!changing_navigable || changing_navigable->population_loader|| !navigation_transaction_matches(*operation, source_page, navigable_id)|| !source_page.take_owed_reply({ OwedReply::Kind::ChangingJob, operation_id, navigable_id })) {discard();@@ -1358,198 +1300,205 @@ void CanonicalTraversable::did_finish_history_navigation_params_creation(WebCont}// NB: The process populating the entry echoes its request. A file: URL in it that is not the entry's would give the// process a document created from another file: URL, and possibly with it local file access.- if (population.request.history_entry.url.scheme() == "file"sv && population.request.history_entry.url != job.value()->job.target_entry->url) {+ if (population.request.history_entry.url.scheme() == "file"sv && population.request.history_entry.url != changing_navigable->target_entry->url) {discard();- did_fail_history_navigation_population(operation_id, navigable_id, source_page);+ did_fail_history_navigation_population(*operation, *changing_navigable, source_page);return;}// The document's sandboxing flags are at least those the UI process snapshots for the navigable.- if (auto navigable = find(navigable_id); navigable.has_value())- population.request.target_snapshot_params.sandboxing_flags |= navigable->snapshot_target_snapshot_params().sandboxing_flags;- auto& loader = job.value()->population_loader;+ population.request.target_snapshot_params.sandboxing_flags |= changing_navigable->navigable().snapshot_target_snapshot_params().sandboxing_flags;+ auto& loader = changing_navigable->population_loader;loader = NavigationLoader::create(source_page.client().is_private(), move(population.request));loader->did_finish_navigation_params_creation(move(population.result));- loader->acquire_response_body([weak_this = make_weak_ptr(), operation_id, navigable_id, source_page = NonnullRefPtr<WebContentPage>(source_page)](bool succeeded) {- if (!weak_this)+ loader->acquire_response_body([this, operation_id, navigable_id, source_page = NonnullRefPtr<WebContentPage>(source_page)](bool succeeded) {+ auto* operation = find_history_operation(operation_id);+ auto* changing_navigable = operation ? operation->pending_changing_job(navigable_id) : nullptr;+ if (!changing_navigable)return;- auto& traversable = static_cast<CanonicalTraversable&>(*weak_this);if (!succeeded) {- traversable.did_fail_history_navigation_population(operation_id, navigable_id, *source_page);+ did_fail_history_navigation_population(*operation, *changing_navigable, *source_page);return;}- traversable.continue_history_navigation_population(operation_id, navigable_id);+ continue_history_navigation_population(*operation, *changing_navigable);});}-void CanonicalTraversable::did_fail_history_navigation_population(Web::HTML::CrossProcessId operation_id, Web::HTML::CrossProcessId navigable_id, WebContentPage& page)+void CanonicalTraversable::did_fail_history_navigation_population(HistoryOperation& operation, ChangingNavigable& changing_navigable, WebContentPage& page){- auto* operation = find_history_operation(operation_id);- if (!operation)- return;- auto disposition = navigation_transaction_matches(*operation, page, navigable_id)+ auto disposition = navigation_transaction_matches(operation, page, changing_navigable.id)? Web::HTML::ChangingNavigableHistoryStepJobDisposition::Skipped: Web::HTML::ChangingNavigableHistoryStepJobDisposition::Stale;- if (auto complete = end_changing_navigable_history_step_job(*operation, navigable_id, disposition))- complete();+ operation.algorithm->changing_navigable_job_completed(changing_navigable, disposition);}-void CanonicalTraversable::continue_history_navigation_population(Web::HTML::CrossProcessId operation_id, Web::HTML::CrossProcessId navigable_id)+void CanonicalTraversable::continue_history_navigation_population(HistoryOperation& operation, ChangingNavigable& changing_navigable){- auto* operation = find_history_operation(operation_id);- auto navigable = find(navigable_id);- if (!operation || !navigable.has_value())+ if (!changing_navigable.population_loader)return;- auto pending_job = operation->pending_changing_jobs.get(navigable_id);- auto endpoint = changing_job_endpoint(*operation, navigable_id);- if (!pending_job.has_value() || !endpoint || !pending_job.value()->population_loader)+ auto endpoint = changing_job_endpoint(changing_navigable);+ if (!endpoint)return;- auto loader = move(pending_job.value()->population_loader);+ auto loader = move(changing_navigable.population_loader);- NonnullRefPtr target_entry = pending_job.value()->job.target_entry;+ NonnullRefPtr target_entry = *changing_navigable.target_entry;+ auto operation_id = operation.operation_id;+ auto navigable_id = changing_navigable.id;+ auto navigable = changing_navigable.navigable().make_weak_ptr();auto host_or_error = navigable->obtain_page_to_populate_document(target_entry, *loader, *endpoint);- if (host_or_error.is_error()) {- did_fail_history_navigation_population(operation_id, navigable_id, *endpoint);++ // Obtaining the page can replace the tab's process, whose change callbacks can end the job, and with its operation+ // the record.+ if (!find_history_operation(operation_id) || !operation.pending_changing_job(navigable_id)) {+ if (navigable && !host_or_error.is_error() && host_or_error.value().document)+ navigable->abandon_populated_document(target_entry->document_state, *host_or_error.value().document);return;}- auto host = host_or_error.release_value();-- // Obtaining the page can replace the tab's process, whose change callbacks can finish the operation.- operation = find_history_operation(operation_id);- if (operation)- pending_job = operation->pending_changing_jobs.get(navigable_id);- if (!operation || !pending_job.has_value()) {- if (host.document)- navigable->abandon_populated_document(target_entry->document_state, *host.document);+ if (host_or_error.is_error()) {+ did_fail_history_navigation_population(operation, changing_navigable, *endpoint);return;}+ auto host = host_or_error.release_value();if (host.document)- pending_job.value()->document = host.document;+ changing_navigable.populated_document = host.document;endpoint = host.page;- add_history_operation_completion_endpoint(*operation, *endpoint);- auto& job = *pending_job.value();- job.population_loader = move(loader);- auto finish_handoff = [weak_this = make_weak_ptr(), weak_loader = job.population_loader->make_weak_ptr(), operation_id, navigable_id, endpoint](bool succeeded) {- if (!weak_this || !weak_loader)- return;- auto& traversable = static_cast<CanonicalTraversable&>(*weak_this);- auto* operation = traversable.find_history_operation(operation_id);- if (!operation)- return;- auto pending_job = operation->pending_changing_jobs.get(navigable_id);- if (!pending_job.has_value() || pending_job.value()->population_loader.ptr() != weak_loader.ptr())+ add_history_operation_completion_endpoint(operation, *endpoint);+ changing_navigable.population_loader = move(loader);+ auto finish_handoff = [this, operation_id, navigable_id, weak_loader = changing_navigable.population_loader->make_weak_ptr(), endpoint](bool succeeded) {+ auto* operation = find_history_operation(operation_id);+ auto* changing_navigable = operation ? operation->pending_changing_job(navigable_id) : nullptr;+ if (!changing_navigable || !weak_loader || changing_navigable->population_loader.ptr() != weak_loader.ptr())return;if (!succeeded || !endpoint->is_open()) {- traversable.did_fail_history_navigation_population(operation_id, navigable_id, *endpoint);+ did_fail_history_navigation_population(*operation, *changing_navigable, *endpoint);return;}- auto& job = *pending_job.value();- auto& loader = *job.population_loader;+ auto& loader = *changing_navigable->population_loader;endpoint->owe_reply({ OwedReply::Kind::ChangingJob, operation_id, navigable_id });- endpoint->async_continue_history_navigation_population(operation_id, job.job.target_entry_descriptor(), job.job.navigation_type,+ endpoint->async_continue_history_navigation_population(operation_id, changing_navigable->target_entry_descriptor(), operation->algorithm->navigation_type(),Web::HTML::HistoryNavigationPopulation { loader.request(), loader.take_result() });};if (auto client_id = endpoint->client().request_server_site_bindings().client_id(); client_id.has_value()) {if (auto request_server = RequestServerManager::the().instance_for_client(*client_id)) {- job.population_loader->move_response_body_to(*request_server, move(finish_handoff));+ changing_navigable.population_loader->move_response_body_to(*request_server, move(finish_handoff));return;}}finish_handoff(false);}-void CanonicalTraversable::dispatch_changing_navigable_history_step_job(HistoryOperation& operation, Web::HTML::CrossProcessId navigable_id)+bool CanonicalTraversable::run_changing_navigable_history_step_job(ApplyHistoryStep& run, ChangingNavigable& changing_navigable){- auto endpoint = changing_job_endpoint(operation, navigable_id);- VERIFY(endpoint);- auto pending_job = operation.pending_changing_jobs.get(navigable_id);- VERIFY(pending_job.has_value());+ auto& operation = run.operation();+ auto navigable_id = changing_navigable.id;+ auto& navigable = changing_navigable.navigable();+ auto endpoint = changing_job_endpoint(changing_navigable);+ if (!endpoint || !endpoint->is_open())+ return false;++ if (navigable.is_top_level_traversable()) {+ if (!operation.parameters.has<Web::ReloadHistoryOperationParameters>()+ && changing_navigable.target_entry->document_state->document.ptr() != &navigable.active_document()) {+ if (auto view = this->view(); view.has_value())+ view->reset_blocked_request_count();+ }+ if (operation.is_browser_traversal()) {+ if (auto callback = move(operation.browser_traversal().on_ready))+ callback();+ }+ }++ add_history_operation_completion_endpoint(operation, *endpoint);++ // A reload's top-level job repopulates the view's document; begin the recorded load where the job is+ // dispatched instead of having the job echo it back.+ if (navigable.is_top_level_traversable()+ && operation.parameters.has<Web::ReloadHistoryOperationParameters>()) {+ if (endpoint->is_open()) {+ // A load a history operation starts, rather than a navigation, is tracked as the active document's.+ clear_active_document_load();+ endpoint->begin_top_level_load(changing_navigable.target_entry->url);+ }+ }- if (pending_job.value()->population_loader)- pending_job.value()->population_loader->reclaim_response_body_after_failed_handoff();- pending_job.value()->population_loader = nullptr;- auto target_entry = pending_job.value()->job.target_entry_descriptor();Optional<Utf16String> finalized_navigation_id;- if (auto const* parameters = operation.parameters.get_pointer<Web::FinalizeCrossDocumentNavigationHistoryOperationParameters>(); parameters && parameters->navigable_id == navigable_id)+ if (auto const* parameters = operation.parameters.get_pointer<Web::FinalizeCrossDocumentNavigationHistoryOperationParameters>(); parameters && parameters->navigable_id == navigable_id) {finalized_navigation_id = parameters->navigation_id;+ if (auto const& populated_document = changing_navigable.target_entry->document_state->populated_document; populated_document.has_value())+ changing_navigable.populated_document = populated_document->document;+ }endpoint->owe_reply({ OwedReply::Kind::ChangingJob, operation.operation_id, navigable_id });endpoint->async_run_changing_navigable_history_job(operation.operation_id, navigable_id,- move(target_entry), pending_job.value()->job.user_involvement,- pending_job.value()->job.navigation_type,- pending_job.value()->job.traversal_yields_to,- pending_job.value()->job.canceled_navigation_id,+ changing_navigable.target_entry_descriptor(), run.user_involvement(),+ run.navigation_type(),+ changing_navigable.traversal_yields_to,+ changing_navigable.canceled_navigation_id,finalized_navigation_id,- pending_job.value()->job.source_snapshot_params);+ run.source_snapshot_params());+ return true;}-void CanonicalTraversable::dispatch_changing_navigable_history_step_continuation(HistoryOperation& operation, Web::HTML::CrossProcessId navigable_id)+void CanonicalTraversable::apply_changing_navigable_history_step_continuation(ApplyHistoryStep& run, ChangingNavigable& changing_navigable){- auto pending_job = operation.pending_changing_jobs.get(navigable_id);- VERIFY(pending_job.has_value());- VERIFY(pending_job.value()->continuation.has_value());- VERIFY(!pending_job.value()->on_complete);+ VERIFY(changing_navigable.continuation.has_value());// 10. If changingNavigableContinuation's update-only is true, or targetEntry's document is displayedDocument:- if (pending_job.value()->unload_displayed_document == Web::HTML::UnloadDisplayedDocument::No) {+ if (changing_navigable.unload_displayed_document == Web::HTML::UnloadDisplayedDocument::No) {// 1. Set navigable's ongoing navigation to null.// NB: The canonical traversal claim is released when the continuation is applied. The queued task mirrors// the null transition into the process-local projection.// 2. Queue a global task on the navigation and traversal task source given navigable's active window to// perform afterPotentialUnloads.- send_changing_navigable_continuation_task(operation, navigable_id, Web::HTML::UnloadDisplayedDocument::No);+ send_changing_navigable_continuation_task(run.operation(), changing_navigable);} else {// 11. Otherwise:// 1. Assert: navigationType is not null.// AD-HOC: Except for a navigable created by a document repopulated for its entry, which displays its initial// about:blank until an update for a navigable's creation or destruction restores the entry its nested// history kept. See https://github.com/whatwg/html/issues/12724.- auto navigable = find(navigable_id);- VERIFY(pending_job.value()->job.navigation_type.has_value() || (navigable.has_value() && navigable->active_document().is_initial_about_blank()));+ VERIFY(run.navigation_type().has_value() || changing_navigable.navigable().active_document().is_initial_about_blank());// 2. Deactivate displayedDocument, given userInvolvement, targetEntry, navigationType, and// afterPotentialUnloads.- deactivate_a_document_for_cross_document_navigation(operation, navigable_id);+ deactivate_a_document_for_cross_document_navigation(run.operation(), changing_navigable);}}-void CanonicalTraversable::send_changing_navigable_continuation_task(HistoryOperation& operation, Web::HTML::CrossProcessId navigable_id, Web::HTML::UnloadDisplayedDocument unload_displayed_document)+void CanonicalTraversable::send_changing_navigable_continuation_task(HistoryOperation& operation, ChangingNavigable& changing_navigable){- auto endpoint = changing_job_endpoint(operation, navigable_id);+ VERIFY(changing_navigable.has_pending_job());+ VERIFY(changing_navigable.continuation.has_value());+ auto endpoint = changing_job_endpoint(changing_navigable);if (!endpoint)return;- auto pending_job = operation.pending_changing_jobs.get(navigable_id);- VERIFY(pending_job.has_value());- VERIFY(pending_job.value()->continuation.has_value());- auto const& document_state = *pending_job.value()->job.target_entry->document_state;- if (unload_displayed_document == Web::HTML::UnloadDisplayedDocument::Yes && pending_job.value()->job.target_entry_reload_pending+ auto const& document_state = *changing_navigable.target_entry->document_state;+ if (changing_navigable.unload_displayed_document == Web::HTML::UnloadDisplayedDocument::Yes && changing_navigable.target_entry_reload_pending&& operation.parameters.has<Web::ReloadHistoryOperationParameters>()) {// INTEROP: Reloading rebuilds the child history tree from the replacement document, as in WebKit.// Keep the old entries until population succeeds so an abandoned reload preserves them.- auto navigable = find(navigable_id);- if (navigable.has_value()) {- Vector<Web::HTML::CrossProcessId> nested_history_ids;- for (auto const& nested_history : document_state.nested_histories)- nested_history_ids.append(nested_history.id);- for (auto nested_history_id : nested_history_ids)- remove_nested_history(*navigable, document_state.id, nested_history_id);- }+ Vector<Web::HTML::CrossProcessId> nested_history_ids;+ for (auto const& nested_history : document_state.nested_histories)+ nested_history_ids.append(nested_history.id);+ for (auto nested_history_id : nested_history_ids)+ remove_nested_history(changing_navigable.navigable(), document_state.id, nested_history_id);}- auto continuation = *pending_job.value()->continuation;- endpoint->owe_reply({ OwedReply::Kind::ContinuationApplied, operation.operation_id, navigable_id });+ auto continuation = *changing_navigable.continuation;+ endpoint->owe_reply({ OwedReply::Kind::ContinuationApplied, operation.operation_id, changing_navigable.id });endpoint->async_apply_changing_navigable_continuation(- operation.operation_id, navigable_id,+ operation.operation_id, changing_navigable.id,continuation.history_object_length_and_index.script_history_length,continuation.history_object_length_and_index.script_history_index,move(continuation.entries_for_navigation_api),- unload_displayed_document);+ changing_navigable.unload_displayed_document);}// https://html.spec.whatwg.org/multipage/browsing-the-web.html#deactivate-a-document-for-a-cross-document-navigation-void CanonicalTraversable::deactivate_a_document_for_cross_document_navigation(HistoryOperation& operation, Web::HTML::CrossProcessId navigable_id)+void CanonicalTraversable::deactivate_a_document_for_cross_document_navigation(HistoryOperation& operation, ChangingNavigable& changing_navigable){+// 1. Let navigable be displayedDocument's node navigable.// 2. Let potentiallyTriggerViewTransition be false.// FIXME: 3. Let isBrowserUINavigation be true if userNavigationInvolvement is "browser UI"; otherwise false.@@ -1564,14 +1513,13 @@ void CanonicalTraversable::deactivate_a_document_for_cross_document_navigation(H// 2. Set navigable's ongoing navigation to null.// NB: The process running the job applies this step to its projection of the navigable, and reports back before// step 3 runs in unload_displayed_document_for_cross_document_navigation().- if (auto navigable = find(navigable_id); navigable.has_value())- navigable->clear_ongoing_navigation_traversal(operation.operation_id);+ changing_navigable.navigable().clear_ongoing_navigation_traversal(operation.operation_id);- auto endpoint = changing_job_endpoint(operation, navigable_id);+ auto endpoint = changing_job_endpoint(changing_navigable);if (!endpoint)return;- endpoint->owe_reply({ OwedReply::Kind::UnloadPreparation, operation.operation_id, navigable_id });- endpoint->async_prepare_changing_navigable_for_unload(operation.operation_id, navigable_id);+ endpoint->owe_reply({ OwedReply::Kind::UnloadPreparation, operation.operation_id, changing_navigable.id });+ endpoint->async_prepare_changing_navigable_for_unload(operation.operation_id, changing_navigable.id);// FIXME: 6. Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:// 1. Let proceedWithNavigationAfterViewTransitionCapture be the following step:@@ -1585,43 +1533,40 @@ void CanonicalTraversable::deactivate_a_document_for_cross_document_navigation(H}// https://html.spec.whatwg.org/multipage/browsing-the-web.html#deactivate-a-document-for-a-cross-document-navigation-void CanonicalTraversable::unload_displayed_document_for_cross_document_navigation(HistoryOperation& operation, Web::HTML::CrossProcessId navigable_id)+void CanonicalTraversable::unload_displayed_document_for_cross_document_navigation(HistoryOperation& operation, ChangingNavigable& changing_navigable){// 5. If potentiallyTriggerViewTransition is false, then:// 3. Unload a document and its descendants given displayedDocument, targetEntry's document,// afterPotentialUnloads, and firePageSwapBeforeUnload.- auto endpoint = changing_job_endpoint(operation, navigable_id);+ auto endpoint = changing_job_endpoint(changing_navigable);if (!endpoint)return;- auto operation_id = operation.operation_id;- unload_a_document_and_its_descendants(navigable_id, *endpoint, Web::HTML::ChildNavigableDestruction::No, [this, operation_id, navigable_id](UnloadedInItsHost) {+ unload_a_document_and_its_descendants(changing_navigable.id, *endpoint, Web::HTML::ChildNavigableDestruction::No, [this, operation_id = operation.operation_id, navigable_id = changing_navigable.id](UnloadedInItsHost) {// afterPotentialUnloads runs in the continuation task, in the process running the job. That process first// unloads the document it displays: displayedDocument, or the stand-in of a host chosen for the new document.auto* operation = find_history_operation(operation_id);- if (!operation || !operation->pending_changing_jobs.contains(navigable_id))- return;- send_changing_navigable_continuation_task(*operation, navigable_id, Web::HTML::UnloadDisplayedDocument::Yes);+ if (auto* changing_navigable = operation ? operation->pending_changing_job(navigable_id) : nullptr)+ send_changing_navigable_continuation_task(*operation, *changing_navigable);});}// The process running a changing navigable's job activated targetEntry's document and applied the continuation's// remaining steps.-void CanonicalTraversable::did_activate_history_entry(HistoryOperation& operation, Web::HTML::CrossProcessId navigable_id, NonnullRefPtr<WebContentPage> source_page, CanonicalSessionHistoryEntry& target_entry, Web::HTML::HostedNavigableState activated_navigable_state)+void CanonicalTraversable::did_activate_history_entry(HistoryOperation& operation, ChangingNavigable& changing_navigable, NonnullRefPtr<WebContentPage> source_page, Web::HTML::HostedNavigableState activated_navigable_state){- auto navigable = find(navigable_id);- if (!navigable.has_value())- return;+ auto& navigable = changing_navigable.navigable();+ auto& target_entry = *changing_navigable.target_entry;- RefPtr<WebContentPage> host = page_hosting(*navigable);+ RefPtr<WebContentPage> host = page_hosting(navigable);if (auto const& populated_document = target_entry.document_state->populated_document; populated_document.has_value() && populated_document->document->host() == source_page)host = source_page;Optional<Utf16String const&> navigation_id;if (auto navigation = finalized_navigation(operation))navigation_id = navigation->navigation_id;- navigable->did_commit_navigation(target_entry, move(activated_navigable_state), operation.sequence_number, navigation_id, move(host));+ navigable.did_commit_navigation(target_entry, move(activated_navigable_state), operation.sequence_number, navigation_id, move(host));- if (navigable_id == id()) {+ if (&navigable == this) {if (auto view = this->view(); view.has_value()) {// NB: The address bar can already show a pending navigation's URL while the old document// is still visible. Only apply the destination's zoom after its document is activated.@@ -1766,9 +1711,8 @@ void CanonicalTraversable::did_receive_changing_navigable_unload_preparation_comif (!source_page.take_owed_reply({ OwedReply::Kind::UnloadPreparation, operation_id, navigable_id }))return;auto* operation = find_history_operation(operation_id);- if (!operation || !operation->pending_changing_jobs.contains(navigable_id))- return;- unload_displayed_document_for_cross_document_navigation(*operation, navigable_id);+ if (auto* changing_navigable = operation ? operation->pending_changing_job(navigable_id) : nullptr)+ unload_displayed_document_for_cross_document_navigation(*operation, *changing_navigable);}// Step 6 of unload a document and its descendants for a document hosted by a page other than the one continuing the@@ -1808,13 +1752,11 @@ bool CanonicalTraversable::is_unloading_document_of(Web::HTML::CrossProcessId nabool CanonicalTraversable::is_handing_navigable_to_another_page(CanonicalNavigable const& navigable) const{for (auto const& operation : m_history_operations) {- auto pending_job = operation.value->pending_changing_jobs.get(navigable.id());- if (!pending_job.has_value())- continue;- auto const& job = *pending_job.value();- if (job.continuation.has_value()- && job.unload_displayed_document == Web::HTML::UnloadDisplayedDocument::Yes- && changing_job_endpoint(navigable, *job.job.target_entry->document_state) != navigable.active_document().host()) {+ auto const* changing_navigable = operation.value->pending_changing_job(navigable.id());+ if (changing_navigable+ && changing_navigable->continuation.has_value()+ && changing_navigable->unload_displayed_document == Web::HTML::UnloadDisplayedDocument::Yes+ && changing_job_endpoint(*changing_navigable) != navigable.active_document().host()) {return true;}}@@ -1827,12 +1769,16 @@ bool CanonicalTraversable::is_handing_navigable_to_another_page(CanonicalNavigabbool CanonicalTraversable::page_populates_a_history_entry_for_local_file(WebContentPage const& page, ByteString const& path) const{for (auto const& [operation_id, operation] : m_history_operations) {- for (auto const& [navigable_id, pending_job] : operation->pending_changing_jobs) {- auto const& target_entry = *pending_job->job.target_entry;+ if (!operation->algorithm)+ continue;+ for (auto const& changing_navigable : operation->algorithm->changing_navigables()) {+ if (!changing_navigable->has_pending_job())+ continue;+ auto const& target_entry = *changing_navigable->target_entry;if (target_entry.document_state->held_local_file_content&& target_entry.url.scheme() == "file"sv&& target_entry.url.file_path() == path- && changing_job_endpoint(*operation, navigable_id) == &page)+ && changing_job_endpoint(*changing_navigable) == &page)return true;}}@@ -1846,15 +1792,9 @@ RefPtr<WebContentPage> CanonicalTraversable::changing_job_endpoint(CanonicalNavireturn page_hosting(navigable);}-RefPtr<WebContentPage> CanonicalTraversable::changing_job_endpoint(HistoryOperation const& operation, Web::HTML::CrossProcessId navigable_id) const+RefPtr<WebContentPage> CanonicalTraversable::changing_job_endpoint(ChangingNavigable const& changing_navigable) const{- auto navigable = find(navigable_id);- if (!navigable.has_value())- return nullptr;- auto job = operation.pending_changing_jobs.get(navigable_id);- if (!job.has_value())- return page_hosting(*navigable);- return changing_job_endpoint(*navigable, *job.value()->job.target_entry->document_state);+ return changing_job_endpoint(changing_navigable.navigable(), *changing_navigable.target_entry->document_state);}void CanonicalTraversable::did_receive_descendant_unload_task_complete(WebContentPage& source_page, Web::HTML::CrossProcessId unload_id, Web::HTML::CrossProcessId navigable_id)@@ -1880,119 +1820,79 @@ void CanonicalTraversable::did_receive_child_navigable_unload_request(WebContent});}-Function<void()> CanonicalTraversable::end_changing_navigable_history_step_job(HistoryOperation& operation, Web::HTML::CrossProcessId navigable_id, Web::HTML::ChangingNavigableHistoryStepJobDisposition disposition)-{- auto pending_job = operation.pending_changing_jobs.take(navigable_id);- if (!pending_job.has_value())- return {};- auto& job = *pending_job.value();- job.abandon(find(navigable_id));- if (job.on_complete)- return [on_complete = move(job.on_complete), disposition] { on_complete(disposition); };- // Until the step supplies a ready job's continuation, applying it finds no job and completes locally.- return move(job.on_continuation_complete);-}-void CanonicalTraversable::end_history_jobs(CanonicalNavigable const& navigable, CanonicalDocument const* populated_document){- struct Completion {- WeakPtr<ApplyHistoryStep> step;- Function<void()> complete;- };- Vector<Completion> completions;+ // NB: A job ends now, but its run goes on later: It can go on to dispatch other jobs, which must not see the tree+ // mid-change.+ Vector<Web::HTML::CrossProcessId> operations_with_ended_changing_jobs;+ Vector<Web::HTML::CrossProcessId> operations_with_ended_nonchanging_updates;for (auto& entry : m_history_operations) {auto& operation = *entry.value;- auto job = operation.pending_changing_jobs.get(navigable.id());- if (job.has_value() && (!populated_document || job.value()->document == populated_document)) {- if (auto complete = end_changing_navigable_history_step_job(operation, navigable.id(), Web::HTML::ChangingNavigableHistoryStepJobDisposition::Skipped))- completions.append({ operation.algorithm->make_weak_ptr(), move(complete) });+ if (auto* changing_navigable = operation.pending_changing_job(navigable.id()); changing_navigable && (!populated_document || changing_navigable->populated_document == populated_document)) {+ operation.algorithm->end_changing_navigable_job(*changing_navigable);+ operations_with_ended_changing_jobs.append(operation.operation_id);}- if (populated_document)+ if (populated_document || !operation.algorithm)continue;- if (auto on_complete = operation.pending_nonchanging_updates.take(navigable.id()); on_complete.has_value())- completions.append({ operation.algorithm->make_weak_ptr(), on_complete.release_value() });+ // NB: Taking the reply a page owes for the navigable's update ignores the reply if it comes after all.+ auto owed_update = OwedReply { OwedReply::Kind::NonchangingUpdate, operation.operation_id, navigable.id() };+ if (any_of(operation.completion_endpoints, [&](auto& endpoint) { return endpoint->take_owed_reply(owed_update); }))+ operations_with_ended_nonchanging_updates.append(operation.operation_id);}- if (completions.is_empty())+ if (operations_with_ended_changing_jobs.is_empty() && operations_with_ended_nonchanging_updates.is_empty())return;- Core::deferred_invoke([completions = move(completions)] {- for (auto const& completion : completions) {- if (completion.step)- completion.complete();+ Core::deferred_invoke([this, weak_this = make_weak_ptr<CanonicalTraversable>(), operations_with_ended_changing_jobs = move(operations_with_ended_changing_jobs), operations_with_ended_nonchanging_updates = move(operations_with_ended_nonchanging_updates)] {+ if (!weak_this)+ return;+ for (auto operation_id : operations_with_ended_changing_jobs) {+ if (auto* operation = find_history_operation(operation_id))+ operation->algorithm->process_changing_navigable_continuations();+ }+ for (auto operation_id : operations_with_ended_nonchanging_updates) {+ if (auto* operation = find_history_operation(operation_id))+ operation->algorithm->nonchanging_navigable_updated();}});}-ApplyHistoryStepJobs CanonicalTraversable::create_apply_history_step_jobs(HistoryOperation& operation)+void CanonicalTraversable::check_if_unloading_is_canceled(ApplyHistoryStep& run, Vector<Web::HTML::CrossProcessId> navigables_that_need_before_unload, NonnullRefPtr<CanonicalSessionHistoryEntry> target_entry, Web::HTML::UserNavigationInvolvement user_involvement_for_navigate_event, Function<void(Web::HTML::CheckIfUnloadingIsCanceledResult)> on_complete){- return {- .check_if_unloading_is_canceled = [this, &operation](Vector<Web::HTML::CrossProcessId> navigables_that_need_before_unload, NonnullRefPtr<CanonicalSessionHistoryEntry> target_entry, Web::HTML::UserNavigationInvolvement user_involvement_for_navigate_event, Function<void(Web::HTML::CheckIfUnloadingIsCanceledResult)> on_complete) {- if (operation.finished)+ auto& operation = run.operation();+ auto check_id = check_if_unloading_is_canceled(move(navigables_that_need_before_unload), move(target_entry), user_involvement_for_navigate_event, {}, Web::HTML::UnloadPromptShown::No,+ [this, operation_id = operation.operation_id, on_complete = move(on_complete)](Web::HTML::CheckIfUnloadingIsCanceledResult result, Web::HTML::UnloadPromptShown) {+ auto* operation = find_history_operation(operation_id);+ if (!operation)return;- auto check_id = check_if_unloading_is_canceled(move(navigables_that_need_before_unload), move(target_entry), user_involvement_for_navigate_event, {}, Web::HTML::UnloadPromptShown::No,- [this, operation_id = operation.operation_id, on_complete = move(on_complete)](Web::HTML::CheckIfUnloadingIsCanceledResult result, Web::HTML::UnloadPromptShown) {- auto* operation = find_history_operation(operation_id);- if (!operation)- return;- operation->beforeunload_check_id.clear();- on_complete(result);- });- // The check can finish, and the operation with it, before it returns.- if (!operation.finished)- operation.beforeunload_check_id = check_id; },- .queue_navigation_api_state_clear_task = [this, &operation](Web::HTML::CrossProcessId navigable_id) {- auto navigable = find(navigable_id);- if (operation.finished || !navigable.has_value())- return;- auto endpoint = page_hosting(*navigable);- if (!endpoint)- return;- add_history_operation_completion_endpoint(operation, *endpoint);- endpoint->async_queue_navigation_api_state_clear_task(navigable_id); },- .select_changing_navigable_history_step_job_endpoint = [this, &operation](ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob& job) { return !operation.finished && select_changing_navigable_history_step_job_endpoint(operation, job); },- .run_changing_navigable_history_step_job = [this, &operation](ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob job, Function<void(Web::HTML::ChangingNavigableHistoryStepJobDisposition)> on_complete) {- if (operation.finished)- return;- auto navigable_id = job.navigable_id;- auto pending_job = make<HistoryOperation::PendingChangingJob>(move(job), move(on_complete));- if (auto const* parameters = operation.parameters.get_pointer<Web::FinalizeCrossDocumentNavigationHistoryOperationParameters>(); parameters && parameters->navigable_id == navigable_id) {- if (auto const& populated_document = pending_job->job.target_entry->document_state->populated_document; populated_document.has_value())- pending_job->document = populated_document->document;- }- operation.pending_changing_jobs.set(navigable_id, move(pending_job));- dispatch_changing_navigable_history_step_job(operation, navigable_id); },- .apply_changing_navigable_history_step_continuation = [this, &operation](ApplyHistoryStepJobs::ApplyChangingNavigableHistoryStepContinuation continuation, Function<void()> on_complete) {- if (operation.finished)- return;- auto navigable_id = continuation.navigable_id;- auto pending_job = operation.pending_changing_jobs.get(navigable_id);- if (!pending_job.has_value()) {- on_complete();- return;- }- // If a sync navigation that jumped the queue changed the job's target entry while the job was paused, then- // the job follows — so that the entry recorded as the navigable's active one, and any re-dispatch of the- // job, name the entry as the session history has it.- if (continuation.updated_target_entry)- pending_job.value()->job.target_entry = *continuation.updated_target_entry;- pending_job.value()->continuation = move(continuation);- pending_job.value()->on_continuation_complete = move(on_complete);- dispatch_changing_navigable_history_step_continuation(operation, navigable_id); },- .update_nonchanging_navigable_history_step_state = [this, &operation](Web::HTML::CrossProcessId navigable_id, Web::HTML::HistoryObjectLengthAndIndex history_object_length_and_index, Function<void()> on_complete) {- if (operation.finished)- return;- auto navigable = find(navigable_id);- RefPtr<WebContentPage> endpoint = navigable.has_value() ? page_hosting(*navigable) : nullptr;- if (!endpoint || !endpoint->is_open()) {- on_complete();- return;- }- add_history_operation_completion_endpoint(operation, *endpoint);- operation.pending_nonchanging_updates.set(navigable_id, move(on_complete));- endpoint->owe_reply({ OwedReply::Kind::NonchangingUpdate, operation.operation_id, navigable_id });- endpoint->async_update_nonchanging_navigable_history_state(operation.operation_id, navigable_id,- history_object_length_and_index.script_history_length, history_object_length_and_index.script_history_index); },- };+ operation->beforeunload_check_id.clear();+ on_complete(result);+ });+ // The check can finish, and the operation with it, before it returns.+ if (!operation.finished)+ operation.beforeunload_check_id = check_id;+}++void CanonicalTraversable::queue_navigation_api_state_clear_task(ApplyHistoryStep& run, ChangingNavigable& changing_navigable)+{+ auto endpoint = page_hosting(changing_navigable.navigable());+ if (!endpoint)+ return;+ add_history_operation_completion_endpoint(run.operation(), *endpoint);+ endpoint->async_queue_navigation_api_state_clear_task(changing_navigable.id);+}++bool CanonicalTraversable::update_nonchanging_navigable_history_step_state(ApplyHistoryStep& run, Web::HTML::CrossProcessId navigable_id, Web::HTML::HistoryObjectLengthAndIndex history_object_length_and_index)+{+ auto& operation = run.operation();+ auto navigable = find(navigable_id);+ RefPtr<WebContentPage> endpoint = navigable.has_value() ? page_hosting(*navigable) : nullptr;+ if (!endpoint || !endpoint->is_open())+ return false;+ add_history_operation_completion_endpoint(operation, *endpoint);+ endpoint->owe_reply({ OwedReply::Kind::NonchangingUpdate, operation.operation_id, navigable_id });+ endpoint->async_update_nonchanging_navigable_history_state(operation.operation_id, navigable_id,+ history_object_length_and_index.script_history_length, history_object_length_and_index.script_history_index);+ return true;}void CanonicalTraversable::run_history_operation_at_queue_position(Web::HTML::CrossProcessId operation_id, Web::HistoryOperationParameters request, RefPtr<WebContentPage> requesting_page, u64 sequence_number, RefPtr<CanonicalSessionHistoryEntry> target_entry, NonnullRefPtr<Core::Promise<Empty>> promise)@@ -2229,12 +2129,9 @@ void CanonicalTraversable::apply_history_step(HistoryOperation& operation, i32 sVERIFY(!operation.algorithm);auto operation_id = operation.operation_id;operation.algorithm = make<ApplyHistoryStep>(- m_session_history, *this, m_history_traversal_queue, m_apply_history_step_traversable_state, create_apply_history_step_jobs(operation),- operation_id, operation.sequence_number,+ *this, operation, operation_id, operation.sequence_number,step, check_for_cancelation, initiator_to_check, move(source_snapshot_params), user_involvement, navigation_type,[this, &operation](Web::HTML::HistoryStepResult result) {- if (operation.finished)- return;finish_history_operation(operation.operation_id, result);});operation.algorithm->apply_the_history_step();@@ -2701,7 +2598,7 @@ void CanonicalTraversable::end_history_operation(Web::HTML::CrossProcessId operasettle_history_operation(operation.release_nonnull());}-OwnPtr<CanonicalTraversable::HistoryOperation> CanonicalTraversable::take_history_operation(Web::HTML::CrossProcessId operation_id)+OwnPtr<HistoryOperation> CanonicalTraversable::take_history_operation(Web::HTML::CrossProcessId operation_id){auto operation = m_history_operations.take(operation_id);if (!operation.has_value())@@ -2713,10 +2610,9 @@ OwnPtr<CanonicalTraversable::HistoryOperation> CanonicalTraversable::take_historif ((*operation)->beforeunload_check_id.has_value())m_pending_beforeunload_checks.remove(*(*operation)->beforeunload_check_id);- // A changing job still pending when its operation finishes never activates the document it populated. The job- // stays with the operation: its completion can be what finished it.- for (auto const& [navigable_id, pending_job] : (*operation)->pending_changing_jobs)- pending_job->abandon(find(navigable_id));+ // A changing job still pending when its operation finishes never activates the document it populated.+ if (auto& run = (*operation)->algorithm)+ run->abandon();if (auto const* parameters = (*operation)->parameters.get_pointer<Web::NavigableCreationHistoryOperationParameters>()) {if (auto navigable = find(parameters->navigable_id); navigable.has_value())navigable->clear_ongoing_navigation_traversal(operation_id);@@ -2886,43 +2782,39 @@ void CanonicalTraversable::did_receive_changing_navigable_history_job_ready(WebC{if (!source_page.take_owed_reply({ OwedReply::Kind::ChangingJob, operation_id, navigable_id }))return;- if (auto* operation = find_history_operation(operation_id)) {- auto pending_job = operation->pending_changing_jobs.get(navigable_id);- if (!pending_job.has_value())- return;-- if (!navigation_transaction_matches(*operation, source_page, navigable_id))- disposition = Web::HTML::ChangingNavigableHistoryStepJobDisposition::Stale;+ auto* operation = find_history_operation(operation_id);+ auto* changing_navigable = operation ? operation->pending_changing_job(navigable_id) : nullptr;+ if (!changing_navigable)+ return;- if (disposition == Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready) {- pending_job.value()->unload_displayed_document = unload_displayed_document;- auto on_complete = move(pending_job.value()->on_complete);- on_complete(disposition);- return;- }+ if (!navigation_transaction_matches(*operation, source_page, navigable_id))+ disposition = Web::HTML::ChangingNavigableHistoryStepJobDisposition::Stale;- if (auto complete = end_changing_navigable_history_step_job(*operation, navigable_id, disposition))- complete();+ if (disposition == Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready) {+ changing_navigable->unload_displayed_document = unload_displayed_document;+ operation->algorithm->changing_navigable_job_completed(*changing_navigable, disposition);+ return;}++ operation->algorithm->changing_navigable_job_completed(*changing_navigable, disposition);}void CanonicalTraversable::did_receive_changing_navigable_continuation_applied(WebContentPage& source_page, Web::HTML::CrossProcessId operation_id, Web::HTML::CrossProcessId navigable_id, Optional<Web::HTML::HostedNavigableState> activated_navigable_state, Optional<Web::HTML::SessionHistoryEntryPersistedState> previous_entry_persisted_state){if (!source_page.take_owed_reply({ OwedReply::Kind::ContinuationApplied, operation_id, navigable_id }))return;- if (auto* operation = find_history_operation(operation_id)) {- auto pending_job = operation->pending_changing_jobs.take(navigable_id);- if (!pending_job.has_value())- return;+ auto* operation = find_history_operation(operation_id);+ if (auto* changing_navigable = operation ? operation->pending_changing_job(navigable_id) : nullptr) {+ auto& navigable = changing_navigable->navigable();+ auto document = move(changing_navigable->populated_document);+ // The job ends first, so that activating its document does not end it as one for the document it replaces.+ operation->algorithm->end_changing_navigable_job(*changing_navigable);if (activated_navigable_state.has_value())- did_activate_history_entry(*operation, navigable_id, source_page, *pending_job.value()->job.target_entry, activated_navigable_state.release_value());- else if (auto navigable = find(navigable_id); navigable.has_value() && pending_job.value()->document)- navigable->abandon_populated_document(pending_job.value()->job.target_entry->document_state, *pending_job.value()->document);- if (previous_entry_persisted_state.has_value()) {- auto navigable = find(navigable_id);- if (navigable.has_value())- update_session_history_entry_persisted_state(*navigable, *previous_entry_persisted_state);- }+ did_activate_history_entry(*operation, *changing_navigable, source_page, activated_navigable_state.release_value());+ else if (document)+ navigable.abandon_populated_document(changing_navigable->target_entry->document_state, *document);+ if (previous_entry_persisted_state.has_value())+ update_session_history_entry_persisted_state(navigable, *previous_entry_persisted_state);// A replacement document's creation operation also applies a top-level continuation, but it runs before// the document has accepted the UI-owned history state. Only the browser traversal itself reaches the// observable top-level completion point here.@@ -2930,8 +2822,7 @@ void CanonicalTraversable::did_receive_changing_navigable_continuation_applied(Wif (auto view = this->view(); view.has_value())view->did_apply_top_level_history_traversal_step(operation_id);}- if (pending_job.value()->on_continuation_complete)- pending_job.value()->on_continuation_complete();+ operation->algorithm->process_changing_navigable_continuations();}if (auto view = this->view(); view.has_value())@@ -2942,10 +2833,8 @@ void CanonicalTraversable::did_receive_nonchanging_navigable_history_state_updat{if (!source_page.take_owed_reply({ OwedReply::Kind::NonchangingUpdate, operation_id, navigable_id }))return;- if (auto* operation = find_history_operation(operation_id)) {- if (auto on_complete = operation->pending_nonchanging_updates.take(navigable_id); on_complete.has_value())- (*on_complete)();- }+ if (auto* operation = find_history_operation(operation_id); operation && operation->algorithm)+ operation->algorithm->nonchanging_navigable_updated();}}diff --git a/Libraries/LibWebView/CanonicalTraversable.h b/Libraries/LibWebView/CanonicalTraversable.hindex 7ae10bfbde9..8b429d1705e 100644--- a/Libraries/LibWebView/CanonicalTraversable.h+++ b/Libraries/LibWebView/CanonicalTraversable.h@@ -43,8 +43,9 @@ enum class WebContentProcessLost : bool {Yes,};-class WEBVIEW_API CanonicalTraversable final- : public CanonicalNavigable {+class WEBVIEW_API CanonicalTraversable final : public CanonicalNavigable {+ friend class ApplyHistoryStep;+public:CanonicalTraversable(Web::HTML::CrossProcessId id, NonnullRefPtr<CanonicalSessionHistoryEntry> initial_history_entry);virtual ~CanonicalTraversable() override;@@ -181,22 +182,25 @@ public:private:ViewImplementation* m_view { nullptr };- struct HistoryOperation;void session_history_changed();+ void check_if_unloading_is_canceled(ApplyHistoryStep&, Vector<Web::HTML::CrossProcessId> navigables_that_need_before_unload, NonnullRefPtr<CanonicalSessionHistoryEntry> target_entry, Web::HTML::UserNavigationInvolvement user_involvement_for_navigate_event, Function<void(Web::HTML::CheckIfUnloadingIsCanceledResult)> on_complete);+ void queue_navigation_api_state_clear_task(ApplyHistoryStep&, ChangingNavigable&);+ bool run_changing_navigable_history_step_job(ApplyHistoryStep&, ChangingNavigable&);+ void apply_changing_navigable_history_step_continuation(ApplyHistoryStep&, ChangingNavigable&);+ bool update_nonchanging_navigable_history_step_state(ApplyHistoryStep&, Web::HTML::CrossProcessId navigable_id, Web::HTML::HistoryObjectLengthAndIndex);+HistoryOperation* find_history_operation(Web::HTML::CrossProcessId operation_id);+ ApplyHistoryStep* find_history_step_run(Web::HTML::CrossProcessId operation_id);bool navigation_transaction_matches(HistoryOperation const&, WebContentPage&, Optional<Web::HTML::CrossProcessId> reply_navigable_id = {}) const;RefPtr<CanonicalNavigation> finalized_navigation(HistoryOperation const&) const;bool update_session_history_entry_persisted_state(CanonicalNavigable&, Web::HTML::SessionHistoryEntryPersistedState const&);void add_history_operation_completion_endpoint(HistoryOperation&, NonnullRefPtr<WebContentPage>);- bool select_changing_navigable_history_step_job_endpoint(HistoryOperation&, ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob&);- void dispatch_changing_navigable_history_step_job(HistoryOperation&, Web::HTML::CrossProcessId navigable_id);- void did_fail_history_navigation_population(Web::HTML::CrossProcessId operation_id, Web::HTML::CrossProcessId navigable_id, WebContentPage&);- void continue_history_navigation_population(Web::HTML::CrossProcessId operation_id, Web::HTML::CrossProcessId navigable_id);- void dispatch_changing_navigable_history_step_continuation(HistoryOperation&, Web::HTML::CrossProcessId navigable_id);- void send_changing_navigable_continuation_task(HistoryOperation&, Web::HTML::CrossProcessId navigable_id, Web::HTML::UnloadDisplayedDocument);- void deactivate_a_document_for_cross_document_navigation(HistoryOperation&, Web::HTML::CrossProcessId navigable_id);- void unload_displayed_document_for_cross_document_navigation(HistoryOperation&, Web::HTML::CrossProcessId navigable_id);- void did_activate_history_entry(HistoryOperation&, Web::HTML::CrossProcessId navigable_id, NonnullRefPtr<WebContentPage> source_page, CanonicalSessionHistoryEntry& target_entry, Web::HTML::HostedNavigableState activated_navigable_state);+ void did_fail_history_navigation_population(HistoryOperation&, ChangingNavigable&, WebContentPage&);+ void continue_history_navigation_population(HistoryOperation&, ChangingNavigable&);+ void send_changing_navigable_continuation_task(HistoryOperation&, ChangingNavigable&);+ void deactivate_a_document_for_cross_document_navigation(HistoryOperation&, ChangingNavigable&);+ void unload_displayed_document_for_cross_document_navigation(HistoryOperation&, ChangingNavigable&);+ void did_activate_history_entry(HistoryOperation&, ChangingNavigable&, NonnullRefPtr<WebContentPage> source_page, Web::HTML::HostedNavigableState activated_navigable_state);enum class UnloadedInItsHost : bool {No,Yes,@@ -205,11 +209,9 @@ private:void unload_document_in_its_host(NonnullRefPtr<WebContentPage>, Web::HTML::CrossProcessId navigable_id, Web::HTML::ChildNavigableDestruction, Function<void()> after_unload);void stand_in_for_lost_document(CanonicalNavigable&);RefPtr<WebContentPage> changing_job_endpoint(CanonicalNavigable const&, CanonicalDocumentState const& target_document_state) const;- RefPtr<WebContentPage> changing_job_endpoint(HistoryOperation const&, Web::HTML::CrossProcessId navigable_id) const;+ RefPtr<WebContentPage> changing_job_endpoint(ChangingNavigable const&) const;void dispatch_descendant_unload_task(Web::HTML::CrossProcessId unload_id, Web::HTML::CrossProcessId navigable_id);void complete_descendant_unload_task(Web::HTML::CrossProcessId unload_id, Web::HTML::CrossProcessId navigable_id);- [[nodiscard]] Function<void()> end_changing_navigable_history_step_job(HistoryOperation&, Web::HTML::CrossProcessId navigable_id, Web::HTML::ChangingNavigableHistoryStepJobDisposition);- ApplyHistoryStepJobs create_apply_history_step_jobs(HistoryOperation&);void run_history_operation(HistoryOperation&);void traverse_the_history_by_a_delta_at_queue_position(HistoryOperation&, Web::TraverseByDeltaHistoryOperationParameters const&);void perform_a_navigation_api_traversal_at_queue_position(HistoryOperation&, Web::NavigationAPITraverseHistoryOperationParameters const&);diff --git a/Libraries/LibWebView/Forward.h b/Libraries/LibWebView/Forward.hindex 02121e6a1a5..d41d5a03143 100644--- a/Libraries/LibWebView/Forward.h+++ b/Libraries/LibWebView/Forward.h@@ -15,6 +15,7 @@ namespace WebView {class Action;class Application;+class ApplyHistoryStep;class AudioServerControlClient;class Autocomplete;class AutocompleteService;@@ -43,6 +44,7 @@ class FontServiceHost;class HistoryStore;class HSTSStore;class Menu;+class NavigationLoader;class OutOfProcessWebView;class ProcessManager;class RequestServerInstance;@@ -64,8 +66,10 @@ class WebUI;struct DownloadRecord;struct BookmarkItem;struct BrowserOptions;+struct ChangingNavigable;struct CookieStorageKey;struct HistoryEntry;+struct HistoryOperation;struct SearchEngine;struct WebContentOptions;class WebContentPage;diff --git a/Libraries/LibWebView/SessionHistory.cpp b/Libraries/LibWebView/SessionHistory.cppindex 191716bccc5..339f9541b5d 100644--- a/Libraries/LibWebView/SessionHistory.cpp+++ b/Libraries/LibWebView/SessionHistory.cpp@@ -660,17 +660,17 @@ Optional<Vector<Web::HTML::SessionHistoryEntryDescriptor>> TraversableSessionHis}// https://html.spec.whatwg.org/multipage/browsing-the-web.html#get-all-navigables-whose-current-session-history-entry-will-change-or-reload-Vector<Web::HTML::CrossProcessId> TraversableSessionHistory::get_all_navigables_whose_current_session_history_entry_will_change_or_reload(CanonicalNavigable const& traversable, i32 target_step) const+Vector<CanonicalNavigable&> TraversableSessionHistory::get_all_navigables_whose_current_session_history_entry_will_change_or_reload(CanonicalNavigable& traversable, i32 target_step) const{// 1. Let results be an empty list.- Vector<Web::HTML::CrossProcessId> results;+ Vector<CanonicalNavigable&> results;// 2. Let navigablesToCheck be « traversable ».- Vector<CanonicalNavigable const*> navigables_to_check { &traversable };+ Vector<CanonicalNavigable*> navigables_to_check { &traversable };// 3. For each navigable of navigablesToCheck:while (!navigables_to_check.is_empty()) {- auto const* navigable = navigables_to_check.take_first();+ auto* navigable = navigables_to_check.take_first();// 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.auto const* target_entry = get_the_target_history_entry(*navigable, target_step);@@ -680,7 +680,7 @@ Vector<Web::HTML::CrossProcessId> TraversableSessionHistory::get_all_navigables_// 2. If targetEntry is not navigable's current session history entry or targetEntry's document state's reload// pending is true, then append navigable to results.if (!navigable->current_session_history_entry_is(*target_entry) || target_entry->document_state->reload_pending)- results.append(navigable->id());+ results.append(*navigable);// 3. If targetEntry's document is navigable's document, and targetEntry's document state's reload pending is// false, then extend navigablesToCheck with the child navigables of navigable.diff --git a/Libraries/LibWebView/SessionHistory.h b/Libraries/LibWebView/SessionHistory.hindex 3d8017cc82d..e10ab8a12a8 100644--- a/Libraries/LibWebView/SessionHistory.h+++ b/Libraries/LibWebView/SessionHistory.h@@ -68,7 +68,7 @@ public:[[nodiscard]] CanonicalSessionHistoryEntry* get_the_target_history_entry(CanonicalNavigable const&, i32 step) const;[[nodiscard]] Optional<Web::HTML::HistoryObjectLengthAndIndex> get_the_history_object_length_and_index(i32 step) const;[[nodiscard]] Optional<Vector<Web::HTML::SessionHistoryEntryDescriptor>> get_session_history_entries_for_the_navigation_api(CanonicalNavigable const&, i32 target_step) const;- [[nodiscard]] Vector<Web::HTML::CrossProcessId> get_all_navigables_whose_current_session_history_entry_will_change_or_reload(CanonicalNavigable const& traversable, i32 target_step) const;+ [[nodiscard]] Vector<CanonicalNavigable&> get_all_navigables_whose_current_session_history_entry_will_change_or_reload(CanonicalNavigable& traversable, i32 target_step) const;[[nodiscard]] Vector<Web::HTML::CrossProcessId> get_all_navigables_that_might_experience_a_cross_document_traversal(CanonicalNavigable const& traversable, i32 target_step) const;[[nodiscard]] Vector<Web::HTML::CrossProcessId> get_all_navigables_that_only_need_history_object_length_index_update(CanonicalNavigable const& traversable, i32 target_step) const;void set_current_session_history_step(i32 step)diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 7d3fdfedd0b..a2a89a06d78 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -1,6 +1,5 @@set(TEST_SOURCESTestAccessibilityTreeManager.cpp- TestApplyHistoryStep.cppTestBackgroundNetworking.cppTestAutocompleteMuxer.cppTestAutocompleteRanker.cppdiff --git a/Tests/LibWebView/TestApplyHistoryStep.cpp b/Tests/LibWebView/TestApplyHistoryStep.cppdeleted file mode 100644index d6e5f3e6feb..00000000000--- a/Tests/LibWebView/TestApplyHistoryStep.cpp+++ /dev/null@@ -1,922 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/OwnPtr.h>-#include <LibCore/EventLoop.h>-#include <LibTest/TestCase.h>-#include <LibURL/Parser.h>-#include <LibWebView/ApplyHistoryStep.h>-#include <LibWebView/CanonicalBrowsingContext.h>-#include <LibWebView/CanonicalNavigable.h>-#include <LibWebView/CanonicalNavigation.h>-#include <LibWebView/CanonicalTraversable.h>-#include <LibWebView/WebContentClient.h>--static NonnullRefPtr<WebView::CanonicalSessionHistoryEntry> initial_history_entry()-{- return MUST(WebView::CanonicalSessionHistoryEntry::create_from_descriptor(Web::HTML::create_initial_session_history_entry_descriptor({}, {}, {})));-}--static Web::HTML::CrossProcessId root_id() { return { 1, 1 }; }-static Web::HTML::CrossProcessId child_id() { return { 1, 2 }; }-static Web::HTML::CrossProcessId first_operation_id() { return { 2, 1 }; }-static Web::HTML::CrossProcessId second_operation_id() { return { 2, 2 }; }-static Web::HTML::CrossProcessId third_operation_id() { return { 2, 3 }; }--static Web::HTML::NavigationSourceSnapshot source_snapshot_params(Web::HTML::SandboxingFlagSet sandboxing_flags = {})-{- Web::HTML::NavigationSourceSnapshot snapshot;- snapshot.sandboxing_flags = sandboxing_flags;- return snapshot;-}--static URL::URL parse_url(StringView url)-{- auto parsed_url = URL::Parser::basic_parse(url);- VERIFY(parsed_url.has_value());- return parsed_url.release_value();-}--// Each test entry has a document state of its own, unless a test gives it one.-// A navigation whose steps are checking if unloading is canceled, in no page.-static WebView::CanonicalNavigation::Start navigation_for_testing(Utf16String navigation_id, u64 sequence_number = 0, RefPtr<WebView::CanonicalSessionHistoryEntry> history_entry = {})-{- return {- .url = URL::about_blank(),- .navigation_id = navigation_id,- .sequence_number = sequence_number,- .state = WebView::CanonicalNavigation::CheckingIfUnloadingIsCanceled { Web::HTML::NavigationStartRequest {- .navigable_id = {},- .url = URL::about_blank(),- .document_resource = {},- .request_referrer = Web::Fetch::Infrastructure::RequestReferrer::Client,- .request_referrer_policy = Web::ReferrerPolicy::ReferrerPolicy::EmptyString,- .initiator_origin = URL::Origin::create_opaque(),- .initiator_base_url = {},- .navigable_target_name = {},- .source_snapshot_params = Web::HTML::create_navigation_source_snapshot_without_a_source_document(),- .target_snapshot_params = {},- .csp_navigation_type = Web::ContentSecurityPolicy::Directives::NavigationType::Other,- .history_handling = Web::Bindings::NavigationHistoryBehavior::Auto,- .user_involvement = Web::HTML::UserNavigationInvolvement::None,- .navigation_id = navigation_id,- .classic_history_api_state = {},- .navigation_api_state = {},- .navigation_api_key = {},- .navigation_api_id = {},- .directive_state_id = {},- .directive_state_value = {},- } },- .history_entry = move(history_entry),- };-}--static u64 s_next_test_document_state_local_id = 1000000;--static Web::HTML::SessionHistoryEntryDescriptor entry(i32 step, StringView url)-{- auto parsed_url = parse_url(url);- return {- .step = step,- .url = parsed_url,- .document_state = {- .id = { 3, s_next_test_document_state_local_id++ },- .history_policy_container = Web::HTML::DocumentStateClient::Tag,- .request_referrer = Web::Fetch::Infrastructure::RequestReferrer::Client,- .request_referrer_policy = Web::ReferrerPolicy::DEFAULT_REFERRER_POLICY,- .initiator_origin = {},- .origin = parsed_url.origin(),- .about_base_url = {},- .resource = {},- .reload_pending = false,- .ever_populated = true,- .navigable_target_name = {},- .nested_histories = {},- },- .classic_history_api_state = {},- .navigation_api_state = {},- .navigation_api_key = Utf16String::from_utf8(url),- .navigation_api_id = Utf16String::from_utf8(url),- .scroll_restoration_mode = Web::HTML::ScrollRestorationMode::Auto,- .scroll_position_data = {},- .directive_state_id = { 3, 2000 + static_cast<u64>(step) },- .directive_state_value = {},- };-}--namespace {--class FakeJobRunner {-public:- using ChangingNavigableHistoryStepJob = WebView::ApplyHistoryStepJobs::ChangingNavigableHistoryStepJob;- using ApplyChangingNavigableHistoryStepContinuation = WebView::ApplyHistoryStepJobs::ApplyChangingNavigableHistoryStepContinuation;-- struct UnloadingCheck {- NonnullRefPtr<WebView::CanonicalSessionHistoryEntry> target_entry;- Vector<Web::HTML::CrossProcessId> navigables_that_need_before_unload;- Function<void(Web::HTML::CheckIfUnloadingIsCanceledResult)> on_complete;- };- struct ChangingJob {- ChangingNavigableHistoryStepJob job;- Function<void(Web::HTML::ChangingNavigableHistoryStepJobDisposition)> on_complete;- };- struct Continuation {- ApplyChangingNavigableHistoryStepContinuation continuation;- Function<void()> on_complete;- };- struct NonchangingUpdate {- Web::HTML::CrossProcessId navigable_id;- Web::HTML::HistoryObjectLengthAndIndex history_object_length_and_index;- Function<void()> on_complete;- };-- WebView::ApplyHistoryStepJobs jobs()- {- return {- .check_if_unloading_is_canceled = [this](Vector<Web::HTML::CrossProcessId> navigables_that_need_before_unload, NonnullRefPtr<WebView::CanonicalSessionHistoryEntry> target_entry, Web::HTML::UserNavigationInvolvement, Function<void(Web::HTML::CheckIfUnloadingIsCanceledResult)> on_complete) { unloading_checks.append({ move(target_entry), move(navigables_that_need_before_unload), move(on_complete) }); },- .queue_navigation_api_state_clear_task = [this](Web::HTML::CrossProcessId navigable_id) { navigation_api_state_clear_tasks.append(navigable_id); },- .select_changing_navigable_history_step_job_endpoint = [this](ChangingNavigableHistoryStepJob& job) {- selected_changing_job_endpoints.append(job.navigable_id);- return true; },- .run_changing_navigable_history_step_job = [this](ChangingNavigableHistoryStepJob job, Function<void(Web::HTML::ChangingNavigableHistoryStepJobDisposition)> on_complete) { changing_jobs.append({ move(job), move(on_complete) }); },- .apply_changing_navigable_history_step_continuation = [this](ApplyChangingNavigableHistoryStepContinuation continuation, Function<void()> on_complete) { continuations.append({ move(continuation), move(on_complete) }); },- .update_nonchanging_navigable_history_step_state = [this](Web::HTML::CrossProcessId navigable_id, Web::HTML::HistoryObjectLengthAndIndex history_object_length_and_index, Function<void()> on_complete) { nonchanging_updates.append({ navigable_id, history_object_length_and_index, move(on_complete) }); },- };- }-- Vector<UnloadingCheck> unloading_checks;- Vector<Web::HTML::CrossProcessId> navigation_api_state_clear_tasks;- Vector<Web::HTML::CrossProcessId> selected_changing_job_endpoints;- Vector<ChangingJob> changing_jobs;- Vector<Continuation> continuations;- Vector<NonchangingUpdate> nonchanging_updates;-};--struct TestTraversable {- TestTraversable()- {- traversable.set_id(root_id());- traversable.set_active_session_history_entry(WebView::CanonicalSessionHistoryEntry::create(WebView::CanonicalDocumentState::create({}, WebView::CanonicalBrowsingContext::create_a_new_top_level_browsing_context_and_document({}).document)));- }-- WebView::CanonicalNavigable& add_child(Web::HTML::CrossProcessId id)- {- auto& child = traversable.append_child(make<WebView::CanonicalNavigable>(id));- child.set_active_session_history_entry(WebView::CanonicalSessionHistoryEntry::create(WebView::CanonicalDocumentState::create({}, WebView::CanonicalBrowsingContext::create_a_new_top_level_browsing_context_and_document({}).document)));- return child;- }-- // Two top-level entries; the current entry is the second.- void with_two_top_level_entries()- {- VERIFY(history.initialize_for_testing({ entry(0, "https://a.example/"sv), entry(1, "https://b.example/"sv) }, { 0, 1 }, 1));- initialize_navigable_entry_identities();- }-- void with_two_same_document_top_level_entries()- {- auto first_entry = entry(0, "https://a.example/first"sv);- auto second_entry = entry(1, "https://a.example/second"sv);- second_entry.document_state.id = first_entry.document_state.id;- VERIFY(history.initialize_for_testing({ move(first_entry), move(second_entry) }, { 0, 1 }, 1));- initialize_navigable_entry_identities();- }-- // Three top-level entries; the current entry is the second.- void with_three_top_level_entries()- {- VERIFY(history.initialize_for_testing({ entry(0, "https://a.example/"sv), entry(1, "https://b.example/"sv), entry(2, "https://c.example/"sv) }, { 0, 1, 2 }, 1));- initialize_navigable_entry_identities();- }-- // One top-level entry whose document holds a child navigable that has pushed an entry (step 1), followed by a- // later top-level entry (step 2). The current step is the child's pushed entry.- void with_child_navigable_history()- {- add_child(child_id());- auto top0 = entry(0, "https://top.example/0"sv);- top0.document_state.nested_histories.append({- .id = child_id(),- .entries = { entry(0, "https://child.example/0"sv), entry(1, "https://child.example/1"sv) },- });- VERIFY(history.initialize_for_testing({ move(top0), entry(2, "https://top.example/1"sv) }, { 0, 1, 2 }, 1));- initialize_navigable_entry_identities();- }-- void with_two_changing_navigables()- {- add_child(child_id());-- auto top0 = entry(0, "https://top.example/0"sv);- top0.document_state.nested_histories.append({- .id = child_id(),- .entries = { entry(0, "https://child.example/0"sv), entry(2, "https://child.example/2"sv) },- });-- auto top2 = entry(2, "https://top.example/2"sv);- top2.document_state.id = top0.document_state.id;- VERIFY(history.initialize_for_testing({ move(top0), move(top2) }, { 0, 2 }, 1));- initialize_navigable_entry_identities();- }-- void with_finalized_cross_document_replacement()- {- auto initial_entry = entry(0, "https://a.example/"sv);- VERIFY(history.initialize_for_testing({ initial_entry }, { 0 }, 0));- initialize_navigable_entry_identities();-- auto* current_entry = &history.current_entry();- VERIFY(history.replace_session_history_entry(traversable, *current_entry, MUST(WebView::CanonicalSessionHistoryEntry::create_from_descriptor(entry(0, "https://b.example/"sv)))));- }-- WebView::ApplyHistoryStep& apply_step(i32 step, Optional<Web::Bindings::NavigationType> navigation_type, bool check_for_cancelation = false, Optional<Web::HTML::CrossProcessId> initiator_to_check = {}, Optional<Web::HTML::NavigationSourceSnapshot> source_snapshot_params = {})- {- operation = make<WebView::ApplyHistoryStep>(history, traversable, queue, state, runner.jobs(), second_operation_id(), 2, step,- check_for_cancelation, initiator_to_check, move(source_snapshot_params), Web::HTML::UserNavigationInvolvement::BrowserUI,- navigation_type,- [this](Web::HTML::HistoryStepResult history_step_result) { result = history_step_result; });- operation->apply_the_history_step();- return *operation;- }-- WebView::ApplyHistoryStep& traverse_to_step(i32 step, bool check_for_cancelation = false, Optional<Web::HTML::CrossProcessId> initiator_to_check = {}, Optional<Web::HTML::NavigationSourceSnapshot> source_snapshot_params = {})- {- return apply_step(step, Web::Bindings::NavigationType::Traverse, check_for_cancelation, initiator_to_check, move(source_snapshot_params));- }-- Optional<i32> current_step() const- {- return history.used_steps()[history.current_used_step_index()];- }-- void initialize_navigable_entry_identities()- {- auto step = current_step();- VERIFY(step.has_value());- traversable.for_each_in_inclusive_subtree([&](WebView::CanonicalNavigable& navigable) {- auto* current_entry = history.get_the_target_history_entry(navigable, *step);- VERIFY(current_entry);- if (auto const& previous_active_entry = navigable.active_session_history_entry())- current_entry->document_state->document = previous_active_entry->document_state->document;- navigable.set_current_session_history_entry(current_entry);- navigable.set_active_session_history_entry(current_entry);- return IterationDecision::Continue;- });- }-- WebView::TraversableSessionHistory history { initial_history_entry() };- WebView::CanonicalTraversable traversable { {}, initial_history_entry() };- WebView::SessionHistoryTraversalQueue queue;- WebView::TraversableApplyHistoryStepState state;- FakeJobRunner runner;- OwnPtr<WebView::ApplyHistoryStep> operation;- Optional<Web::HTML::HistoryStepResult> result;-};--}--TEST_CASE(ongoing_traversal_is_owned_by_its_history_operation)-{- WebView::CanonicalNavigable navigable(root_id());-- navigable.set_ongoing_navigation_to_traversal(first_operation_id());- navigable.set_ongoing_navigation_to_traversal(second_operation_id());- navigable.clear_ongoing_navigation_traversal(first_operation_id());- EXPECT(navigable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());-- navigable.clear_ongoing_navigation_traversal(second_operation_id());- EXPECT(!navigable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());-- navigable.set_ongoing_navigation_to_traversal(first_operation_id());- navigable.clear_ongoing_navigation();- EXPECT(!navigable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());-}--TEST_CASE(finalized_replacement_is_selected_from_the_navigables_current_entry)-{- TestTraversable test;- test.with_finalized_cross_document_replacement();-- test.apply_step(0, Web::Bindings::NavigationType::Replace);- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- EXPECT_EQ(test.runner.changing_jobs[0].job.navigable_id, root_id());- EXPECT_EQ(test.runner.changing_jobs[0].job.target_entry->url, parse_url("https://b.example/"sv));-}--TEST_CASE(traversal_runs_the_changing_root_job_and_commits_the_target_step)-{- TestTraversable test;- test.with_two_top_level_entries();-- auto& operation = test.traverse_to_step(0);- EXPECT(test.runner.unloading_checks.is_empty());-- EXPECT_EQ(test.runner.selected_changing_job_endpoints.size(), 1uz);- EXPECT_EQ(test.runner.selected_changing_job_endpoints[0], root_id());- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- auto* target_entry = test.history.get_the_target_history_entry(test.traversable, 0);- VERIFY(target_entry);- EXPECT(test.traversable.current_session_history_entry_is(*target_entry));- EXPECT(!test.traversable.active_document_is(*target_entry));- EXPECT_EQ(test.runner.navigation_api_state_clear_tasks.size(), 1uz);- EXPECT_EQ(test.runner.navigation_api_state_clear_tasks[0], root_id());- EXPECT(test.traversable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());- auto& job = test.runner.changing_jobs[0];- EXPECT_EQ(job.job.navigable_id, root_id());- EXPECT_EQ(job.job.target_entry->url, parse_url("https://a.example/"sv));- job.on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);-- EXPECT_EQ(test.runner.continuations.size(), 1uz);- auto& continuation = test.runner.continuations[0];- EXPECT_EQ(continuation.continuation.navigable_id, root_id());- EXPECT_EQ(continuation.continuation.history_object_length_and_index.script_history_length, 2u);- EXPECT_EQ(continuation.continuation.history_object_length_and_index.script_history_index, 0u);- EXPECT_EQ(continuation.continuation.entries_for_navigation_api.size(), 1uz);- continuation.on_complete();-- EXPECT(test.runner.nonchanging_updates.is_empty());- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 0);- EXPECT(operation.completed());- EXPECT(!test.traversable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());-}--TEST_CASE(same_document_traversal_does_not_clear_the_navigation_api_state)-{- TestTraversable test;- test.with_two_same_document_top_level_entries();-- test.traverse_to_step(0);- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- EXPECT(test.runner.navigation_api_state_clear_tasks.is_empty());-}--TEST_CASE(same_document_traversal_yields_to_a_navigation_awaiting_admission)-{- TestTraversable test;- test.with_two_same_document_top_level_entries();-- test.traverse_to_step(0);- EXPECT(!test.traversable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- auto const& job = test.runner.changing_jobs[0].job;- EXPECT(job.traversal_yields_to == Web::HTML::TraversalYieldsTo::UnadmittedNavigation);- EXPECT(!job.canceled_navigation_id.has_value());-}--TEST_CASE(same_document_traversal_names_the_older_navigation_it_cancels)-{- TestTraversable test;- test.with_two_same_document_top_level_entries();- test.traversable.set_ongoing_navigation(navigation_for_testing("older"_utf16, 1));-- test.traverse_to_step(0);- EXPECT(!test.traversable.ongoing_navigation_id().has_value());- EXPECT(!test.traversable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- auto const& job = test.runner.changing_jobs[0].job;- EXPECT(job.traversal_yields_to == Web::HTML::TraversalYieldsTo::UnadmittedNavigation);- EXPECT_EQ(job.canceled_navigation_id, "older"_utf16);-}--TEST_CASE(same_document_traversal_yields_to_a_newer_admitted_navigation)-{- TestTraversable test;- test.with_two_same_document_top_level_entries();- test.traversable.set_ongoing_navigation(navigation_for_testing("newer"_utf16, 3));-- test.traverse_to_step(0);- EXPECT(test.traversable.ongoing_navigation_id().has_value());- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- auto const& job = test.runner.changing_jobs[0].job;- EXPECT(job.traversal_yields_to == Web::HTML::TraversalYieldsTo::AdmittedNavigation);- EXPECT(!job.canceled_navigation_id.has_value());-}--TEST_CASE(cross_document_traversal_cancels_a_newer_navigation)-{- TestTraversable test;- test.with_two_top_level_entries();- test.traversable.set_ongoing_navigation(navigation_for_testing("newer"_utf16, 3));-- test.traverse_to_step(0);- EXPECT(!test.traversable.ongoing_navigation_id().has_value());- EXPECT(test.traversable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- auto const& job = test.runner.changing_jobs[0].job;- EXPECT(job.traversal_yields_to == Web::HTML::TraversalYieldsTo::Nothing);- EXPECT(!job.canceled_navigation_id.has_value());-}--TEST_CASE(canceled_unloading_returns_before_any_changing_jobs)-{- TestTraversable test;- test.with_two_top_level_entries();-- test.traverse_to_step(0, true);- EXPECT_EQ(test.runner.unloading_checks.size(), 1uz);- auto* target_entry = test.history.get_the_target_history_entry(test.traversable, 0);- VERIFY(target_entry);- EXPECT(!test.traversable.current_session_history_entry_is(*target_entry));- auto& job = test.runner.unloading_checks[0];- EXPECT_EQ(job.target_entry->step, 0);- EXPECT_EQ(job.target_entry->url, parse_url("https://a.example/"sv));- EXPECT_EQ(job.navigables_that_need_before_unload.size(), 1uz);- EXPECT_EQ(job.navigables_that_need_before_unload[0], root_id());- job.on_complete(Web::HTML::CheckIfUnloadingIsCanceledResult::CanceledByBeforeUnload);-- EXPECT(test.runner.changing_jobs.is_empty());- EXPECT(test.result == Web::HTML::HistoryStepResult::CanceledByBeforeUnload);- EXPECT_EQ(test.current_step(), 1);- EXPECT(!test.traversable.current_session_history_entry_is(*target_entry));-}--TEST_CASE(disallowed_initiator_returns_before_the_cancelation_check)-{- TestTraversable test;- test.with_two_top_level_entries();- test.add_child(child_id());-- test.traverse_to_step(0, true, child_id(),- source_snapshot_params(Web::HTML::SandboxingFlagSet::SandboxedTopLevelNavigationWithoutUserActivation));-- EXPECT(test.runner.unloading_checks.is_empty());- EXPECT(test.runner.changing_jobs.is_empty());- EXPECT(test.result == Web::HTML::HistoryStepResult::InitiatorDisallowed);- EXPECT_EQ(test.current_step(), 1);-}--TEST_CASE(allowed_initiator_proceeds_to_the_cancelation_check)-{- TestTraversable test;- test.with_two_top_level_entries();- test.add_child(child_id());-- test.traverse_to_step(0, true, child_id(), source_snapshot_params());-- EXPECT_EQ(test.runner.unloading_checks.size(), 1uz);- EXPECT(!test.result.has_value());-}--TEST_CASE(initiator_without_a_snapshot_fails_closed)-{- TestTraversable test;- test.with_two_top_level_entries();- test.add_child(child_id());-- test.traverse_to_step(0, true, child_id());-- EXPECT(test.runner.unloading_checks.is_empty());- EXPECT(test.runner.changing_jobs.is_empty());- EXPECT(test.result == Web::HTML::HistoryStepResult::InitiatorDisallowed);-}--TEST_CASE(sandboxed_removed_initiator_is_disallowed)-{- TestTraversable test;- test.with_two_top_level_entries();-- test.traverse_to_step(0, true, child_id(), source_snapshot_params(Web::HTML::SandboxingFlagSet::SandboxedNavigation));-- EXPECT(test.runner.unloading_checks.is_empty());- EXPECT(test.runner.changing_jobs.is_empty());- EXPECT(test.result == Web::HTML::HistoryStepResult::InitiatorDisallowed);-}--TEST_CASE(unsandboxed_removed_initiator_proceeds_to_the_cancelation_check)-{- TestTraversable test;- test.with_two_top_level_entries();-- test.traverse_to_step(0, true, child_id(), source_snapshot_params());-- EXPECT_EQ(test.runner.unloading_checks.size(), 1uz);- EXPECT(!test.result.has_value());-}--TEST_CASE(child_navigable_traversal_updates_the_nonchanging_root)-{- TestTraversable test;- test.with_child_navigable_history();-- test.traverse_to_step(0);- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- auto& job = test.runner.changing_jobs[0];- EXPECT_EQ(job.job.navigable_id, child_id());- EXPECT_EQ(job.job.target_entry->url, parse_url("https://child.example/0"sv));- job.on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);-- EXPECT_EQ(test.runner.continuations.size(), 1uz);- auto& continuation = test.runner.continuations[0];- EXPECT_EQ(continuation.continuation.navigable_id, child_id());- EXPECT_EQ(continuation.continuation.history_object_length_and_index.script_history_length, 3u);- EXPECT_EQ(continuation.continuation.history_object_length_and_index.script_history_index, 0u);- EXPECT_EQ(continuation.continuation.entries_for_navigation_api.size(), 2uz);- continuation.on_complete();-- EXPECT_EQ(test.runner.nonchanging_updates.size(), 1uz);- auto& nonchanging_update = test.runner.nonchanging_updates[0];- EXPECT_EQ(nonchanging_update.navigable_id, root_id());- EXPECT_EQ(nonchanging_update.history_object_length_and_index.script_history_index, 0u);- EXPECT(!test.result.has_value());- nonchanging_update.on_complete();-- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 0);-}--TEST_CASE(skipped_changing_job_still_applies_the_history_step)-{- TestTraversable test;- test.with_child_navigable_history();-- test.traverse_to_step(0);- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- auto& child = *test.traversable.children().first();- auto* target_entry = test.history.get_the_target_history_entry(child, 0);- VERIFY(target_entry);- EXPECT(child.current_session_history_entry_is(*target_entry));- EXPECT(!child.active_document_is(*target_entry));- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Skipped);-- EXPECT(test.runner.continuations.is_empty());- EXPECT_EQ(test.runner.nonchanging_updates.size(), 1uz);- test.runner.nonchanging_updates[0].on_complete();-- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 0);- EXPECT(!child.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());-}--TEST_CASE(ready_continuations_interleave_with_still_running_changing_jobs)-{- TestTraversable test;- test.with_two_changing_navigables();-- test.traverse_to_step(0);- EXPECT_EQ(test.runner.changing_jobs.size(), 2uz);-- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT_EQ(test.runner.continuations.size(), 1uz);-- test.runner.changing_jobs[1].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT_EQ(test.runner.continuations.size(), 1uz);-- test.runner.continuations[0].on_complete();- EXPECT_EQ(test.runner.continuations.size(), 2uz);- EXPECT(!test.result.has_value());-- test.runner.continuations[1].on_complete();- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 0);-}--TEST_CASE(stale_changing_job_completes_without_committing_the_target_step)-{- TestTraversable test;- test.with_two_top_level_entries();-- test.traverse_to_step(0);- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Stale);-- EXPECT(test.runner.continuations.is_empty());- EXPECT(test.runner.nonchanging_updates.is_empty());- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 1);- EXPECT(!test.traversable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());-}--TEST_CASE(synchronous_navigation_steps_jump_the_queue_before_continuations)-{- Core::EventLoop event_loop;- TestTraversable test;- test.with_two_top_level_entries();-- bool synchronous_steps_ran = false;- RefPtr<Core::Promise<Empty>> synchronous_steps_signal;- test.queue.append_session_history_synchronous_navigation_steps(child_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>> signal) {- synchronous_steps_ran = true;- synchronous_steps_signal = signal;- });-- test.traverse_to_step(0);- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- EXPECT(synchronous_steps_ran);- EXPECT(test.state.running_nested_apply_history_step);- EXPECT(test.runner.continuations.is_empty());-- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT(test.runner.continuations.is_empty());-- synchronous_steps_signal->resolve({});- EXPECT(!test.state.running_nested_apply_history_step);- EXPECT_EQ(test.runner.continuations.size(), 1uz);-- // A synchronous navigation targeting a navigable that has already been traversed no longer jumps the queue.- bool late_synchronous_steps_ran = false;- test.queue.append_session_history_synchronous_navigation_steps(root_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>>) {- late_synchronous_steps_ran = true;- });- test.runner.continuations[0].on_complete();-- EXPECT(!late_synchronous_steps_ran);- EXPECT(!test.queue.is_empty());- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 0);-}--TEST_CASE(synchronous_navigation_steps_queued_by_a_nested_step_do_not_starve_the_continuation)-{- Core::EventLoop event_loop;- TestTraversable test;- test.with_two_top_level_entries();-- bool later_synchronous_steps_ran = false;- RefPtr<Core::Promise<Empty>> synchronous_steps_signal;- test.queue.append_session_history_synchronous_navigation_steps(child_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>> signal) {- synchronous_steps_signal = signal;- test.queue.append_session_history_synchronous_navigation_steps(child_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>>) {- later_synchronous_steps_ran = true;- });- });-- test.traverse_to_step(0);- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT(synchronous_steps_signal);- EXPECT(test.runner.continuations.is_empty());-- synchronous_steps_signal->resolve({});- EXPECT(!later_synchronous_steps_ran);- EXPECT_EQ(test.runner.continuations.size(), 1uz);- EXPECT(!test.queue.is_empty());-}--TEST_CASE(canceled_run_does_not_resume_after_synchronous_navigation)-{- Core::EventLoop event_loop;- TestTraversable test;- test.with_two_top_level_entries();-- RefPtr<Core::Promise<Empty>> synchronous_steps_signal;- test.queue.append_session_history_synchronous_navigation_steps(child_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>> signal) {- synchronous_steps_signal = signal;- });-- test.traverse_to_step(0);- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT(synchronous_steps_signal);- EXPECT(test.state.running_nested_apply_history_step);-- test.operation = nullptr;- EXPECT(!test.state.running_nested_apply_history_step);- EXPECT(!test.traversable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());-- synchronous_steps_signal->resolve({});- EXPECT(test.runner.continuations.is_empty());-}--TEST_CASE(an_older_run_does_not_commit_over_a_newer_runs_step)-{- TestTraversable test;- test.with_three_top_level_entries();-- Optional<Web::HTML::HistoryStepResult> older_result;- WebView::ApplyHistoryStep older_operation(test.history, test.traversable, test.queue, test.state, test.runner.jobs(), first_operation_id(), 1, 0,- false, {}, {}, Web::HTML::UserNavigationInvolvement::BrowserUI, Web::Bindings::NavigationType::Traverse,- [&](Web::HTML::HistoryStepResult result) { older_result = result; });-- // A newer run (for example a synchronous navigation that jumped the queue) commits first.- test.traverse_to_step(2);- EXPECT_EQ(test.runner.changing_jobs.size(), 1uz);- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT_EQ(test.runner.continuations.size(), 1uz);- test.runner.continuations[0].on_complete();- EXPECT_EQ(test.current_step(), 2);-- older_operation.apply_the_history_step();- EXPECT_EQ(test.runner.changing_jobs.size(), 2uz);- test.runner.changing_jobs[1].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT_EQ(test.runner.continuations.size(), 2uz);- test.runner.continuations[1].on_complete();-- EXPECT(older_result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 2);-}--TEST_CASE(a_paused_run_commits_after_a_newer_run_recommits_the_current_step)-{- Core::EventLoop event_loop;- TestTraversable test;- test.with_two_top_level_entries();-- // A push whose finalization appended its entry at step 2.- VERIFY(test.history.push_session_history_entry(test.traversable, MUST(WebView::CanonicalSessionHistoryEntry::create_from_descriptor(entry(2, "https://c.example/"sv)))) == 2);-- // A synchronous replace from the page the push is unloading is queued behind the push and jumps the queue while the- // push waits on its changing job. It re-commits the current step, moving nothing.- OwnPtr<WebView::ApplyHistoryStep> nested_operation;- Optional<Web::HTML::HistoryStepResult> nested_result;- test.queue.append_session_history_synchronous_navigation_steps(child_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>> signal) {- nested_operation = make<WebView::ApplyHistoryStep>(test.history, test.traversable, test.queue, test.state, test.runner.jobs(), third_operation_id(), 3, 1,- false, Optional<Web::HTML::CrossProcessId> {}, Optional<Web::HTML::NavigationSourceSnapshot> {}, Web::HTML::UserNavigationInvolvement::None, Web::Bindings::NavigationType::Replace,- [&, signal](Web::HTML::HistoryStepResult result) {- nested_result = result;- signal->resolve({});- });- nested_operation->apply_the_history_step();- });-- test.apply_step(2, Web::Bindings::NavigationType::Push);- EXPECT(!test.runner.changing_jobs.is_empty());- EXPECT(nested_operation);-- // Complete whatever the nested run dispatched; the push's own job (the first) stays pending.- for (size_t i = 1; i < test.runner.changing_jobs.size(); ++i)- test.runner.changing_jobs[i].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- for (size_t i = 0; i < test.runner.continuations.size(); ++i)- test.runner.continuations[i].on_complete();- EXPECT(nested_result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(nested_operation->committed_step(), 1);- EXPECT_EQ(test.current_step(), 1);- EXPECT(!test.state.running_nested_apply_history_step);-- // The push resumes, and commits its own step.- auto continuation_count = test.runner.continuations.size();- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT_EQ(test.runner.continuations.size(), continuation_count + 1);- test.runner.continuations[continuation_count].on_complete();-- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.operation->committed_step(), 2);- EXPECT_EQ(test.current_step(), 2);-}--TEST_CASE(a_paused_traversal_is_abandoned_once_a_jumping_push_removes_its_target_entry)-{- Core::EventLoop event_loop;- TestTraversable test;- test.with_three_top_level_entries();-- // A same-document push from the current page is queued behind a forward traversal, and jumps the queue while the- // traversal waits on its changing job. It clears the forward entry that the traversal has claimed.- OwnPtr<WebView::ApplyHistoryStep> nested_operation;- Optional<Web::HTML::HistoryStepResult> nested_result;- test.queue.append_session_history_synchronous_navigation_steps(child_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>> signal) {- auto pushed_entry = WebView::CanonicalSessionHistoryEntry::create(test.history.top_level_entry_for_step(1)->document_state);- pushed_entry->url = parse_url("https://b.example/pushed"sv);- VERIFY(test.history.push_session_history_entry(test.traversable, move(pushed_entry)) == 2);- nested_operation = make<WebView::ApplyHistoryStep>(test.history, test.traversable, test.queue, test.state, test.runner.jobs(), third_operation_id(), 3, 2,- false, Optional<Web::HTML::CrossProcessId> {}, Optional<Web::HTML::NavigationSourceSnapshot> {}, Web::HTML::UserNavigationInvolvement::None, Web::Bindings::NavigationType::Push,- [&, signal](Web::HTML::HistoryStepResult result) {- nested_result = result;- signal->resolve({});- });- nested_operation->apply_the_history_step();- });-- test.traverse_to_step(2);- EXPECT(!test.runner.changing_jobs.is_empty());- EXPECT_EQ(test.runner.changing_jobs[0].job.target_entry->url, parse_url("https://c.example/"sv));- EXPECT(nested_operation);-- // Complete whatever the nested run dispatched; the traversal's own job (the first) stays pending.- for (size_t i = 1; i < test.runner.changing_jobs.size(); ++i)- test.runner.changing_jobs[i].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- for (size_t i = 0; i < test.runner.continuations.size(); ++i)- test.runner.continuations[i].on_complete();- EXPECT(nested_result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 2);-- // The traversal's job reports in, but its target entry is gone: No continuation is applied, and the push's entry- // stays current.- auto continuation_count = test.runner.continuations.size();- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT_EQ(test.runner.continuations.size(), continuation_count);- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT(!test.operation->committed_step().has_value());- EXPECT_EQ(test.current_step(), 2);- EXPECT_EQ(test.history.current_entry().url, parse_url("https://b.example/pushed"sv));- EXPECT(!test.traversable.ongoing_navigation().has<WebView::CanonicalNavigable::Traversal>());-}--TEST_CASE(a_paused_push_appends_its_entry_again_once_a_jumping_push_clears_it)-{- Core::EventLoop event_loop;- TestTraversable test;- test.with_three_top_level_entries();-- // A cross-document navigation from the page at step 1 has been finalized: Its entry took the place of the forward- // history, and its push waits on its changing job.- auto navigation_entry = MUST(WebView::CanonicalSessionHistoryEntry::create_from_descriptor(entry(2, "https://d.example/"sv)));- VERIFY(test.history.push_session_history_entry(test.traversable, navigation_entry) == 2);-- // A same-document push from the page being navigated away from is queued behind the navigation, and jumps the queue- // while the navigation waits. It clears the navigation's entry as forward history, and takes its step.- OwnPtr<WebView::ApplyHistoryStep> nested_operation;- Optional<Web::HTML::HistoryStepResult> nested_result;- test.queue.append_session_history_synchronous_navigation_steps(child_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>> signal) {- auto pushed_entry = WebView::CanonicalSessionHistoryEntry::create(test.history.top_level_entry_for_step(1)->document_state);- pushed_entry->url = parse_url("https://b.example/pushed"sv);- VERIFY(test.history.push_session_history_entry(test.traversable, move(pushed_entry)) == 2);- nested_operation = make<WebView::ApplyHistoryStep>(test.history, test.traversable, test.queue, test.state, test.runner.jobs(), third_operation_id(), 3, 2,- false, Optional<Web::HTML::CrossProcessId> {}, Optional<Web::HTML::NavigationSourceSnapshot> {}, Web::HTML::UserNavigationInvolvement::None, Web::Bindings::NavigationType::Push,- [&, signal](Web::HTML::HistoryStepResult result) {- nested_result = result;- signal->resolve({});- });- nested_operation->apply_the_history_step();- });-- test.apply_step(2, Web::Bindings::NavigationType::Push);- EXPECT(!test.runner.changing_jobs.is_empty());- EXPECT_EQ(test.runner.changing_jobs[0].job.target_entry->url, parse_url("https://d.example/"sv));- EXPECT(nested_operation);-- // Complete whatever the nested run dispatched; the navigation's own job (the first) stays pending.- for (size_t i = 1; i < test.runner.changing_jobs.size(); ++i)- test.runner.changing_jobs[i].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- for (size_t i = 0; i < test.runner.continuations.size(); ++i)- test.runner.continuations[i].on_complete();- EXPECT(nested_result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 2);-- // The navigation's job reports in. Its entry goes back into the session history, after the pushed entry, and the- // navigation commits there.- auto continuation_count = test.runner.continuations.size();- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT_EQ(test.runner.continuations.size(), continuation_count + 1);- auto& continuation = test.runner.continuations[continuation_count].continuation;- VERIFY(continuation.updated_target_entry);- EXPECT_EQ(continuation.updated_target_entry->url, navigation_entry->url);- EXPECT_EQ(continuation.updated_target_entry->navigation_api_id, navigation_entry->navigation_api_id);- EXPECT_EQ(continuation.updated_target_entry->step, 3);- test.runner.continuations[continuation_count].on_complete();-- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.operation->committed_step(), 3);- EXPECT_EQ(test.current_step(), 3);- EXPECT_EQ(test.history.current_entry().url, navigation_entry->url);- auto entries = test.history.get_session_history_entries(test.traversable);- VERIFY(entries.has_value());- EXPECT_EQ(entries->size(), 4u);- EXPECT_EQ(entries->at(2)->url, parse_url("https://b.example/pushed"sv));-}--TEST_CASE(a_paused_reload_continues_with_the_entry_that_a_jumping_replace_put_in_its_targets_slot)-{- Core::EventLoop event_loop;- TestTraversable test;- test.with_two_top_level_entries();- test.history.current_entry().document_state->reload_pending = true;-- // A same-document replace from the page being reloaded is queued behind the reload, and jumps the queue while the- // reload waits on its changing job. It replaces the entry that the reload has claimed, keeping its navigation API- // key and its document state.- RefPtr reloading_entry = test.history.current_entry();- auto replacement_entry = WebView::CanonicalSessionHistoryEntry::create(reloading_entry->document_state);- replacement_entry->url = parse_url("https://b.example/?replaced"sv);- replacement_entry->navigation_api_key = reloading_entry->navigation_api_key;- replacement_entry->navigation_api_id = "https://b.example/?replaced"_utf16;-- OwnPtr<WebView::ApplyHistoryStep> nested_operation;- Optional<Web::HTML::HistoryStepResult> nested_result;- test.queue.append_session_history_synchronous_navigation_steps(child_id(), {}, [&](NonnullRefPtr<Core::Promise<Empty>> signal) {- VERIFY(test.history.replace_session_history_entry(test.traversable, *reloading_entry, replacement_entry));- nested_operation = make<WebView::ApplyHistoryStep>(test.history, test.traversable, test.queue, test.state, test.runner.jobs(), third_operation_id(), 3, 1,- false, Optional<Web::HTML::CrossProcessId> {}, Optional<Web::HTML::NavigationSourceSnapshot> {}, Web::HTML::UserNavigationInvolvement::None, Web::Bindings::NavigationType::Replace,- [&, signal](Web::HTML::HistoryStepResult result) {- nested_result = result;- signal->resolve({});- });- nested_operation->apply_the_history_step();- });-- test.apply_step(1, Web::Bindings::NavigationType::Reload);- EXPECT(!test.runner.changing_jobs.is_empty());- EXPECT_EQ(test.runner.changing_jobs[0].job.target_entry->navigation_api_id, reloading_entry->navigation_api_id);- EXPECT(nested_operation);-- // Complete whatever the nested run dispatched; the reload's own job (the first) stays pending.- for (size_t i = 1; i < test.runner.changing_jobs.size(); ++i)- test.runner.changing_jobs[i].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- for (size_t i = 0; i < test.runner.continuations.size(); ++i)- test.runner.continuations[i].on_complete();- EXPECT(nested_result == Web::HTML::HistoryStepResult::Applied);-- // The reload resumes, and its continuation names the replacement as the entry to activate.- auto continuation_count = test.runner.continuations.size();- test.runner.changing_jobs[0].on_complete(Web::HTML::ChangingNavigableHistoryStepJobDisposition::Ready);- EXPECT_EQ(test.runner.continuations.size(), continuation_count + 1);- auto const& continuation = test.runner.continuations[continuation_count].continuation;- VERIFY(continuation.updated_target_entry);- EXPECT_EQ(continuation.updated_target_entry->navigation_api_id, replacement_entry->navigation_api_id);- EXPECT_EQ(continuation.updated_target_entry->url, replacement_entry->url);- test.runner.continuations[continuation_count].on_complete();-- EXPECT(test.result == Web::HTML::HistoryStepResult::Applied);- EXPECT_EQ(test.current_step(), 1);-}