TraversableNavigable.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/MainThreadVM.h>
  7. #include <LibWeb/DOM/Document.h>
  8. #include <LibWeb/HTML/BrowsingContextGroup.h>
  9. #include <LibWeb/HTML/DocumentState.h>
  10. #include <LibWeb/HTML/NavigationParams.h>
  11. #include <LibWeb/HTML/SessionHistoryEntry.h>
  12. #include <LibWeb/HTML/TraversableNavigable.h>
  13. #include <LibWeb/Platform/EventLoopPlugin.h>
  14. namespace Web::HTML {
  15. TraversableNavigable::TraversableNavigable() = default;
  16. TraversableNavigable::~TraversableNavigable() = default;
  17. void TraversableNavigable::visit_edges(Cell::Visitor& visitor)
  18. {
  19. Base::visit_edges(visitor);
  20. for (auto& entry : m_session_history_entries)
  21. visitor.visit(entry);
  22. }
  23. static OrderedHashTable<TraversableNavigable*>& user_agent_top_level_traversable_set()
  24. {
  25. static OrderedHashTable<TraversableNavigable*> set;
  26. return set;
  27. }
  28. struct BrowsingContextAndDocument {
  29. JS::NonnullGCPtr<HTML::BrowsingContext> browsing_context;
  30. JS::NonnullGCPtr<DOM::Document> document;
  31. };
  32. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-browsing-context
  33. static WebIDL::ExceptionOr<BrowsingContextAndDocument> create_a_new_top_level_browsing_context_and_document(Page& page)
  34. {
  35. // 1. Let group and document be the result of creating a new browsing context group and document.
  36. auto [group, document] = TRY(BrowsingContextGroup::create_a_new_browsing_context_group_and_document(page));
  37. // 2. Return group's browsing context set[0] and document.
  38. return BrowsingContextAndDocument { **group->browsing_context_set().begin(), document };
  39. }
  40. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-traversable
  41. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_new_top_level_traversable(Page& page, JS::GCPtr<HTML::BrowsingContext> opener, String target_name)
  42. {
  43. auto& vm = Bindings::main_thread_vm();
  44. // 1. Let document be null.
  45. JS::GCPtr<DOM::Document> document = nullptr;
  46. // 2. If opener is null, then set document to the second return value of creating a new top-level browsing context and document.
  47. if (!opener) {
  48. document = TRY(create_a_new_top_level_browsing_context_and_document(page)).document;
  49. }
  50. // 3. Otherwise, set document to the second return value of creating a new auxiliary browsing context and document given opener.
  51. else {
  52. document = TRY(BrowsingContext::create_a_new_auxiliary_browsing_context_and_document(page, *opener)).document;
  53. }
  54. // 4. Let documentState be a new document state, with
  55. auto document_state = vm.heap().allocate_without_realm<DocumentState>();
  56. // document: document
  57. document_state->set_document(document);
  58. // navigable target name: targetName
  59. document_state->set_navigable_target_name(target_name);
  60. // 5. Let traversable be a new traversable navigable.
  61. auto traversable = vm.heap().allocate_without_realm<TraversableNavigable>();
  62. // 6. Initialize the navigable traversable given documentState.
  63. TRY_OR_THROW_OOM(vm, traversable->initialize_navigable(document_state, nullptr));
  64. // 7. Let initialHistoryEntry be traversable's active session history entry.
  65. auto initial_history_entry = traversable->active_session_history_entry();
  66. VERIFY(initial_history_entry);
  67. // 8. Set initialHistoryEntry's step to 0.
  68. initial_history_entry->step = 0;
  69. // 9. Append initialHistoryEntry to traversable's session history entries.
  70. traversable->m_session_history_entries.append(*initial_history_entry);
  71. // FIXME: 10. If opener is non-null, then legacy-clone a traversable storage shed given opener's top-level traversable and traversable. [STORAGE]
  72. // 11. Append traversable to the user agent's top-level traversable set.
  73. user_agent_top_level_traversable_set().set(traversable);
  74. // 12. Return traversable.
  75. return traversable;
  76. }
  77. // https://html.spec.whatwg.org/multipage/document-sequences.html#create-a-fresh-top-level-traversable
  78. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_fresh_top_level_traversable(Page& page, AK::URL const& initial_navigation_url, Variant<Empty, String, POSTResource> initial_navigation_post_resource)
  79. {
  80. // 1. Let traversable be the result of creating a new top-level traversable given null and the empty string.
  81. auto traversable = TRY(create_a_new_top_level_traversable(page, nullptr, {}));
  82. // 2. Navigate traversable to initialNavigationURL using traversable's active document, with documentResource set to initialNavigationPostResource.
  83. TRY(traversable->navigate(initial_navigation_url, *traversable->active_document(), initial_navigation_post_resource));
  84. // 3. Return traversable.
  85. return traversable;
  86. }
  87. // https://html.spec.whatwg.org/multipage/document-sequences.html#top-level-traversable
  88. bool TraversableNavigable::is_top_level_traversable() const
  89. {
  90. // A top-level traversable is a traversable navigable with a null parent.
  91. return parent() == nullptr;
  92. }
  93. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-used-history-steps
  94. Vector<int> TraversableNavigable::get_all_used_history_steps() const
  95. {
  96. // FIXME: 1. Assert: this is running within traversable's session history traversal queue.
  97. // 2. Let steps be an empty ordered set of non-negative integers.
  98. OrderedHashTable<int> steps;
  99. // 3. Let entryLists be the ordered set « traversable's session history entries ».
  100. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>> entry_lists { session_history_entries() };
  101. // 4. For each entryList of entryLists:
  102. while (!entry_lists.is_empty()) {
  103. auto entry_list = entry_lists.take_first();
  104. // 1. For each entry of entryList:
  105. for (auto& entry : entry_list) {
  106. // 1. Append entry's step to steps.
  107. steps.set(entry->step.get<int>());
  108. // 2. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  109. for (auto& nested_history : entry->document_state->nested_histories())
  110. entry_lists.append(nested_history.entries);
  111. }
  112. }
  113. // 5. Return steps, sorted.
  114. auto sorted_steps = steps.values();
  115. quick_sort(sorted_steps);
  116. return sorted_steps;
  117. }
  118. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-history-object-length-and-index
  119. TraversableNavigable::HistoryObjectLengthAndIndex TraversableNavigable::get_the_history_object_length_and_index(int step) const
  120. {
  121. // 1. Let steps be the result of getting all used history steps within traversable.
  122. auto steps = get_all_used_history_steps();
  123. // 2. Let scriptHistoryLength be the size of steps.
  124. auto script_history_length = steps.size();
  125. // 3. Assert: steps contains step.
  126. VERIFY(steps.contains_slow(step));
  127. // 4. Let scriptHistoryIndex be the index of step in steps.
  128. auto script_history_index = *steps.find_first_index(step);
  129. // 5. Return (scriptHistoryLength, scriptHistoryIndex).
  130. return HistoryObjectLengthAndIndex {
  131. .script_history_length = script_history_length,
  132. .script_history_index = script_history_index
  133. };
  134. }
  135. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-used-step
  136. int TraversableNavigable::get_the_used_step(int step) const
  137. {
  138. // 1. Let steps be the result of getting all used history steps within traversable.
  139. auto steps = get_all_used_history_steps();
  140. // 2. Return the greatest item in steps that is less than or equal to step.
  141. VERIFY(!steps.is_empty());
  142. Optional<int> result;
  143. for (size_t i = 0; i < steps.size(); i++) {
  144. if (steps[i] <= step) {
  145. if (!result.has_value() || (result.value() < steps[i])) {
  146. result = steps[i];
  147. }
  148. }
  149. }
  150. return result.value();
  151. }
  152. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#get-all-navigables-whose-current-session-history-entry-will-change-or-reload
  153. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_whose_current_session_history_entry_will_change_or_reload(int target_step) const
  154. {
  155. // 1. Let results be an empty list.
  156. Vector<JS::Handle<Navigable>> results;
  157. // 2. Let navigablesToCheck be « traversable ».
  158. Vector<JS::Handle<Navigable>> navigables_to_check;
  159. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  160. // 3. For each navigable of navigablesToCheck:
  161. while (!navigables_to_check.is_empty()) {
  162. auto navigable = navigables_to_check.take_first();
  163. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  164. auto target_entry = navigable->get_the_target_history_entry(target_step);
  165. // 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.
  166. if (target_entry != navigable->current_session_history_entry() || target_entry->document_state->reload_pending()) {
  167. results.append(*navigable);
  168. }
  169. // 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.
  170. if (target_entry->document_state->document() == navigable->active_document() && !target_entry->document_state->reload_pending()) {
  171. navigables_to_check.extend(navigable->child_navigables());
  172. }
  173. }
  174. // 4. Return results.
  175. return results;
  176. }
  177. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-history-step
  178. void TraversableNavigable::apply_the_history_step(int step, Optional<SourceSnapshotParams> source_snapshot_params)
  179. {
  180. // FIXME: 1. Assert: This is running within traversable's session history traversal queue.
  181. // 2. Let targetStep be the result of getting the used step given traversable and step.
  182. auto target_step = get_the_used_step(step);
  183. // FIXME: 3. If initiatorToCheck is given, then:
  184. // FIXME: 4. Let navigablesCrossingDocuments be the result of getting all navigables that might experience a cross-document traversal given traversable and targetStep.
  185. // FIXME: 5. If checkForUserCancelation is true, and the result of checking if unloading is user-canceled given navigablesCrossingDocuments given traversable and targetStep is true, then return.
  186. // 6. Let changingNavigables be the result of get all navigables whose current session history entry will change or reload given traversable and targetStep.
  187. auto changing_navigables = get_all_navigables_whose_current_session_history_entry_will_change_or_reload(target_step);
  188. // FIXME: 7. Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need history object length/index update given traversable and targetStep.
  189. // 8. For each navigable of changingNavigables:
  190. for (auto& navigable : changing_navigables) {
  191. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  192. auto target_entry = navigable->get_the_target_history_entry(target_step);
  193. // 2. Set navigable's current session history entry to targetEntry.
  194. navigable->set_current_session_history_entry(target_entry);
  195. // 3. Set navigable's ongoing navigation to "traversal".
  196. m_ongoing_navigation = Traversal::Tag;
  197. }
  198. // 9. Let totalChangeJobs be the size of changingNavigables.
  199. auto total_change_jobs = changing_navigables.size();
  200. // 10. Let completedChangeJobs be 0.
  201. size_t completed_change_jobs = 0;
  202. struct ChangingNavigableContinuationState {
  203. JS::Handle<DOM::Document> displayed_document;
  204. JS::Handle<SessionHistoryEntry> target_entry;
  205. JS::Handle<Navigable> navigable;
  206. bool update_only;
  207. };
  208. // 11. Let changingNavigableContinuations be an empty queue of changing navigable continuation states.
  209. Queue<ChangingNavigableContinuationState> changing_navigable_continuations;
  210. // 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:
  211. for (auto& navigable : changing_navigables) {
  212. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&] {
  213. // 1. Let displayedEntry be navigable's active session history entry.
  214. auto displayed_entry = navigable->active_session_history_entry();
  215. // 2. Let targetEntry be navigable's current session history entry.
  216. auto target_entry = navigable->current_session_history_entry();
  217. // 3. Let changingNavigableContinuation be a changing navigable continuation state with:
  218. auto changing_navigable_continuation = ChangingNavigableContinuationState {
  219. .displayed_document = displayed_entry->document_state->document(),
  220. .target_entry = target_entry,
  221. .navigable = navigable,
  222. .update_only = false
  223. };
  224. // 4. If displayedEntry is targetEntry and targetEntry's document state's reload pending is false, then:
  225. if (displayed_entry == target_entry && !target_entry->document_state->reload_pending()) {
  226. // 1. Set changingNavigableContinuation's update-only to true.
  227. changing_navigable_continuation.update_only = true;
  228. // 2. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  229. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  230. // 3. Abort these steps.
  231. return;
  232. }
  233. // 5. Let oldOrigin be targetEntry's document state's origin.
  234. [[maybe_unused]] auto old_origin = target_entry->document_state->origin();
  235. auto after_document_populated = [target_entry, changing_navigable_continuation, &changing_navigable_continuations]() mutable {
  236. // 1. If targetEntry's document is null, then set changingNavigableContinuation's update-only to true.
  237. if (!target_entry->document_state->document()) {
  238. changing_navigable_continuation.update_only = true;
  239. }
  240. // FIXME: 2. If targetEntry's document's origin is not oldOrigin, then set targetEntry's serialized state to StructuredSerializeForStorage(null).
  241. // FIXME: 3. If all of the following are true:
  242. // 4. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  243. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  244. };
  245. // 6. If targetEntry's document is null, or targetEntry's document state's reload pending is true, then:
  246. if (!target_entry->document_state->document() || target_entry->document_state->reload_pending()) {
  247. // FIXME: 1. Let navTimingType be "back_forward" if targetEntry's document is null; otherwise "reload".
  248. // FIXME: 2. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  249. // 3. Let potentiallyTargetSpecificSourceSnapshotParams be sourceSnapshotParams.
  250. Optional<SourceSnapshotParams> potentially_target_specific_source_snapshot_params = source_snapshot_params;
  251. // FIXME: 4. If potentiallyTargetSpecificSourceSnapshotParams is null, then set it to the result of snapshotting source snapshot params given navigable's active document.
  252. if (!potentially_target_specific_source_snapshot_params.has_value()) {
  253. potentially_target_specific_source_snapshot_params = SourceSnapshotParams {
  254. .has_transient_activation = false,
  255. .sandboxing_flags = navigable->active_document()->active_sandboxing_flag_set(),
  256. .allows_downloading = true,
  257. .fetch_client = navigable->active_document()->relevant_settings_object(),
  258. .source_policy_container = navigable->active_document()->policy_container()
  259. };
  260. }
  261. // 5. Set targetEntry's document state's reload pending to false.
  262. target_entry->document_state->set_reload_pending(false);
  263. // FIXME: 6. Let allowPOST be targetEntry's document state's reload pending.
  264. // 7. In parallel, attempt to populate the history entry's document for targetEntry, given navigable, potentiallyTargetSpecificSourceSnapshotParams,
  265. // targetSnapshotParams, with allowPOST set to allowPOST and completionSteps set to queue a global task on the navigation and traversal task source given
  266. // navigable's active window to run afterDocumentPopulated.
  267. navigable->populate_session_history_entry_document(target_entry, {}, {}, *potentially_target_specific_source_snapshot_params, [this, after_document_populated]() mutable {
  268. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), [after_document_populated]() mutable {
  269. after_document_populated();
  270. });
  271. })
  272. .release_value_but_fixme_should_propagate_errors();
  273. }
  274. // Otherwise, run afterDocumentPopulated immediately.
  275. else {
  276. after_document_populated();
  277. }
  278. });
  279. }
  280. // FIXME: 13. Let navigablesThatMustWaitBeforeHandlingSyncNavigation be an empty set.
  281. // FIXME: 14. While completedChangeJobs does not equal totalChangeJobs:
  282. while (completed_change_jobs != total_change_jobs) {
  283. // FIXME: 1. If traversable's running nested apply history step is false, then:
  284. // AD-HOC: Since currently populate_session_history_entry_document does not run in parallel
  285. // we call spin_until to interrupt execution of this function and let document population
  286. // to complete.
  287. Platform::EventLoopPlugin::the().spin_until([&] {
  288. return !changing_navigable_continuations.is_empty() || completed_change_jobs == total_change_jobs;
  289. });
  290. if (changing_navigable_continuations.is_empty()) {
  291. continue;
  292. }
  293. // 2. Let changingNavigableContinuation be the result of dequeuing from changingNavigableContinuations.
  294. auto changing_navigable_continuation = changing_navigable_continuations.dequeue();
  295. // 3. If changingNavigableContinuation is nothing, then continue.
  296. // 4. Let displayedDocument be changingNavigableContinuation's displayed document.
  297. auto displayed_document = changing_navigable_continuation.displayed_document;
  298. // 5. Let targetEntry be changingNavigableContinuation's target entry.
  299. auto target_entry = changing_navigable_continuation.target_entry;
  300. // 6. Let navigable be changingNavigableContinuation's navigable.
  301. auto navigable = changing_navigable_continuation.navigable;
  302. // 7. Set navigable's ongoing navigation to null.
  303. m_ongoing_navigation = {};
  304. // 8. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  305. auto [script_history_length, script_history_index] = get_the_history_object_length_and_index(target_step);
  306. (void)script_history_length;
  307. (void)script_history_index;
  308. // FIXME: 9. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation.
  309. // 10. Queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
  310. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), [&, target_entry, navigable, displayed_document, update_only = changing_navigable_continuation.update_only] {
  311. // 1. If changingNavigableContinuation's update-only is false, then:
  312. if (!update_only) {
  313. // 1. Unload displayedDocument given targetEntry's document.
  314. displayed_document->unload(target_entry->document_state->document());
  315. // FIXME: 2. For each childNavigable of displayedDocument's descendant navigables, queue a global task on the navigation and traversal task source given
  316. // childNavigable's active window to unload childNavigable's active document.
  317. // 3. Activate history entry targetEntry for navigable.
  318. navigable->activate_history_entry(*target_entry);
  319. }
  320. // FIXME: 2. If targetEntry's document is not equal to displayedDocument, then queue a global task on the navigation and traversal task source given targetEntry's document's
  321. // relevant global object to perform the following step. Otherwise, continue onward to perform the following step within the currently-queued task.
  322. // FIXME: 3. Update document for history step application given targetEntry's document, targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength, and
  323. // scriptHistoryIndex.
  324. // 4. Increment completedChangeJobs.
  325. completed_change_jobs++;
  326. });
  327. }
  328. // FIXME: 15. Let totalNonchangingJobs be the size of nonchangingNavigablesThatStillNeedUpdates.
  329. // FIXME: 16. Let completedNonchangingJobs be 0.
  330. // FIXME: 17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  331. // FIXME: 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:
  332. // FIXME: 19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.
  333. // 20. Set traversable's current session history step to targetStep.
  334. m_current_session_history_step = target_step;
  335. }
  336. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#clear-the-forward-session-history
  337. void TraversableNavigable::clear_the_forward_session_history()
  338. {
  339. // FIXME: 1. Assert: this is running within navigable's session history traversal queue.
  340. // 2. Let step be the navigable's current session history step.
  341. auto step = current_session_history_step();
  342. // 3. Let entryLists be the ordered set « navigable's session history entries ».
  343. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>&> entry_lists;
  344. entry_lists.append(session_history_entries());
  345. // 4. For each entryList of entryLists:
  346. while (!entry_lists.is_empty()) {
  347. auto& entry_list = entry_lists.take_first();
  348. // 1. Remove every session history entry from entryList that has a step greater than step.
  349. entry_list.remove_all_matching([step](auto& entry) {
  350. return entry->step.template get<int>() > step;
  351. });
  352. // 2. For each entry of entryList:
  353. for (auto& entry : entry_list) {
  354. // 1. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  355. for (auto& nested_history : entry->document_state->nested_histories()) {
  356. entry_lists.append(nested_history.entries);
  357. }
  358. }
  359. }
  360. }
  361. }