TraversableNavigable.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.h>
  7. #include <LibWeb/Bindings/MainThreadVM.h>
  8. #include <LibWeb/CSS/SystemColor.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/HTML/BrowsingContextGroup.h>
  11. #include <LibWeb/HTML/DocumentState.h>
  12. #include <LibWeb/HTML/Navigation.h>
  13. #include <LibWeb/HTML/NavigationParams.h>
  14. #include <LibWeb/HTML/Parser/HTMLParser.h>
  15. #include <LibWeb/HTML/SessionHistoryEntry.h>
  16. #include <LibWeb/HTML/TraversableNavigable.h>
  17. #include <LibWeb/HTML/Window.h>
  18. #include <LibWeb/Page/Page.h>
  19. #include <LibWeb/Painting/CommandExecutorCPU.h>
  20. #include <LibWeb/Painting/CommandExecutorSkia.h>
  21. #include <LibWeb/Platform/EventLoopPlugin.h>
  22. #ifdef HAS_ACCELERATED_GRAPHICS
  23. # include <LibWeb/Painting/CommandExecutorGPU.h>
  24. #endif
  25. namespace Web::HTML {
  26. JS_DEFINE_ALLOCATOR(TraversableNavigable);
  27. TraversableNavigable::TraversableNavigable(JS::NonnullGCPtr<Page> page)
  28. : Navigable(page)
  29. , m_session_history_traversal_queue(vm().heap().allocate_without_realm<SessionHistoryTraversalQueue>())
  30. {
  31. }
  32. TraversableNavigable::~TraversableNavigable() = default;
  33. void TraversableNavigable::visit_edges(Cell::Visitor& visitor)
  34. {
  35. Base::visit_edges(visitor);
  36. visitor.visit(m_session_history_entries);
  37. visitor.visit(m_session_history_traversal_queue);
  38. }
  39. static OrderedHashTable<TraversableNavigable*>& user_agent_top_level_traversable_set()
  40. {
  41. static OrderedHashTable<TraversableNavigable*> set;
  42. return set;
  43. }
  44. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-browsing-context
  45. WebIDL::ExceptionOr<BrowsingContextAndDocument> create_a_new_top_level_browsing_context_and_document(JS::NonnullGCPtr<Page> page)
  46. {
  47. // 1. Let group and document be the result of creating a new browsing context group and document.
  48. auto [group, document] = TRY(BrowsingContextGroup::create_a_new_browsing_context_group_and_document(page));
  49. // 2. Return group's browsing context set[0] and document.
  50. return BrowsingContextAndDocument { **group->browsing_context_set().begin(), document };
  51. }
  52. // https://html.spec.whatwg.org/multipage/document-sequences.html#creating-a-new-top-level-traversable
  53. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_new_top_level_traversable(JS::NonnullGCPtr<Page> page, JS::GCPtr<HTML::BrowsingContext> opener, String target_name)
  54. {
  55. auto& vm = Bindings::main_thread_vm();
  56. // 1. Let document be null.
  57. JS::GCPtr<DOM::Document> document = nullptr;
  58. // 2. If opener is null, then set document to the second return value of creating a new top-level browsing context and document.
  59. if (!opener) {
  60. document = TRY(create_a_new_top_level_browsing_context_and_document(page)).document;
  61. }
  62. // 3. Otherwise, set document to the second return value of creating a new auxiliary browsing context and document given opener.
  63. else {
  64. document = TRY(BrowsingContext::create_a_new_auxiliary_browsing_context_and_document(page, *opener)).document;
  65. }
  66. // 4. Let documentState be a new document state, with
  67. auto document_state = vm.heap().allocate_without_realm<DocumentState>();
  68. // document: document
  69. document_state->set_document(document);
  70. // initiator origin: null if opener is null; otherwise, document's origin
  71. document_state->set_initiator_origin(opener ? Optional<Origin> {} : document->origin());
  72. // origin: document's origin
  73. document_state->set_origin(document->origin());
  74. // navigable target name: targetName
  75. document_state->set_navigable_target_name(target_name);
  76. // about base URL: document's about base URL
  77. document_state->set_about_base_url(document->about_base_url());
  78. // 5. Let traversable be a new traversable navigable.
  79. auto traversable = vm.heap().allocate_without_realm<TraversableNavigable>(page);
  80. // 6. Initialize the navigable traversable given documentState.
  81. TRY_OR_THROW_OOM(vm, traversable->initialize_navigable(document_state, nullptr));
  82. // 7. Let initialHistoryEntry be traversable's active session history entry.
  83. auto initial_history_entry = traversable->active_session_history_entry();
  84. VERIFY(initial_history_entry);
  85. // 8. Set initialHistoryEntry's step to 0.
  86. initial_history_entry->set_step(0);
  87. // 9. Append initialHistoryEntry to traversable's session history entries.
  88. traversable->m_session_history_entries.append(*initial_history_entry);
  89. // FIXME: 10. If opener is non-null, then legacy-clone a traversable storage shed given opener's top-level traversable and traversable. [STORAGE]
  90. // 11. Append traversable to the user agent's top-level traversable set.
  91. user_agent_top_level_traversable_set().set(traversable);
  92. // 12. Return traversable.
  93. return traversable;
  94. }
  95. // https://html.spec.whatwg.org/multipage/document-sequences.html#create-a-fresh-top-level-traversable
  96. WebIDL::ExceptionOr<JS::NonnullGCPtr<TraversableNavigable>> TraversableNavigable::create_a_fresh_top_level_traversable(JS::NonnullGCPtr<Page> page, URL::URL const& initial_navigation_url, Variant<Empty, String, POSTResource> initial_navigation_post_resource)
  97. {
  98. // 1. Let traversable be the result of creating a new top-level traversable given null and the empty string.
  99. auto traversable = TRY(create_a_new_top_level_traversable(page, nullptr, {}));
  100. page->set_top_level_traversable(traversable);
  101. // AD-HOC: Mark the about:blank document as finished parsing if we're only going to about:blank
  102. // Skip the initial navigation as well. This matches the behavior of the window open steps.
  103. if (url_matches_about_blank(initial_navigation_url)) {
  104. Platform::EventLoopPlugin::the().deferred_invoke([traversable, initial_navigation_url] {
  105. // FIXME: We do this other places too when creating a new about:blank document. Perhaps it's worth a spec issue?
  106. HTML::HTMLParser::the_end(*traversable->active_document());
  107. // FIXME: If we perform the URL and history update steps here, we start hanging tests and the UI process will
  108. // try to load() the initial URLs passed on the command line before we finish processing the events here.
  109. // However, because we call this before the PageClient is fully initialized... that gets awkward.
  110. });
  111. }
  112. else {
  113. // 2. Navigate traversable to initialNavigationURL using traversable's active document, with documentResource set to initialNavigationPostResource.
  114. TRY(traversable->navigate({ .url = initial_navigation_url,
  115. .source_document = *traversable->active_document(),
  116. .document_resource = initial_navigation_post_resource }));
  117. }
  118. // 3. Return traversable.
  119. return traversable;
  120. }
  121. // https://html.spec.whatwg.org/multipage/document-sequences.html#top-level-traversable
  122. bool TraversableNavigable::is_top_level_traversable() const
  123. {
  124. // A top-level traversable is a traversable navigable with a null parent.
  125. return parent() == nullptr;
  126. }
  127. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-used-history-steps
  128. Vector<int> TraversableNavigable::get_all_used_history_steps() const
  129. {
  130. // FIXME: 1. Assert: this is running within traversable's session history traversal queue.
  131. // 2. Let steps be an empty ordered set of non-negative integers.
  132. OrderedHashTable<int> steps;
  133. // 3. Let entryLists be the ordered set « traversable's session history entries ».
  134. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>> entry_lists { session_history_entries() };
  135. // 4. For each entryList of entryLists:
  136. while (!entry_lists.is_empty()) {
  137. auto entry_list = entry_lists.take_first();
  138. // 1. For each entry of entryList:
  139. for (auto& entry : entry_list) {
  140. // 1. Append entry's step to steps.
  141. steps.set(entry->step().get<int>());
  142. // 2. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  143. for (auto& nested_history : entry->document_state()->nested_histories())
  144. entry_lists.append(nested_history.entries);
  145. }
  146. }
  147. // 5. Return steps, sorted.
  148. auto sorted_steps = steps.values();
  149. quick_sort(sorted_steps);
  150. return sorted_steps;
  151. }
  152. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-history-object-length-and-index
  153. TraversableNavigable::HistoryObjectLengthAndIndex TraversableNavigable::get_the_history_object_length_and_index(int step) const
  154. {
  155. // 1. Let steps be the result of getting all used history steps within traversable.
  156. auto steps = get_all_used_history_steps();
  157. // 2. Let scriptHistoryLength be the size of steps.
  158. auto script_history_length = steps.size();
  159. // 3. Assert: steps contains step.
  160. VERIFY(steps.contains_slow(step));
  161. // 4. Let scriptHistoryIndex be the index of step in steps.
  162. auto script_history_index = *steps.find_first_index(step);
  163. // 5. Return (scriptHistoryLength, scriptHistoryIndex).
  164. return HistoryObjectLengthAndIndex {
  165. .script_history_length = script_history_length,
  166. .script_history_index = script_history_index
  167. };
  168. }
  169. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-the-used-step
  170. int TraversableNavigable::get_the_used_step(int step) const
  171. {
  172. // 1. Let steps be the result of getting all used history steps within traversable.
  173. auto steps = get_all_used_history_steps();
  174. // 2. Return the greatest item in steps that is less than or equal to step.
  175. VERIFY(!steps.is_empty());
  176. Optional<int> result;
  177. for (size_t i = 0; i < steps.size(); i++) {
  178. if (steps[i] <= step) {
  179. if (!result.has_value() || (result.value() < steps[i])) {
  180. result = steps[i];
  181. }
  182. }
  183. }
  184. return result.value();
  185. }
  186. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#get-all-navigables-whose-current-session-history-entry-will-change-or-reload
  187. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_whose_current_session_history_entry_will_change_or_reload(int target_step) const
  188. {
  189. // 1. Let results be an empty list.
  190. Vector<JS::Handle<Navigable>> results;
  191. // 2. Let navigablesToCheck be « traversable ».
  192. Vector<JS::Handle<Navigable>> navigables_to_check;
  193. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  194. // 3. For each navigable of navigablesToCheck:
  195. while (!navigables_to_check.is_empty()) {
  196. auto navigable = navigables_to_check.take_first();
  197. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  198. auto target_entry = navigable->get_the_target_history_entry(target_step);
  199. // 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.
  200. if (target_entry != navigable->current_session_history_entry() || target_entry->document_state()->reload_pending()) {
  201. results.append(*navigable);
  202. }
  203. // 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.
  204. if (target_entry->document() == navigable->active_document() && !target_entry->document_state()->reload_pending()) {
  205. navigables_to_check.extend(navigable->child_navigables());
  206. }
  207. }
  208. // 4. Return results.
  209. return results;
  210. }
  211. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-navigables-that-only-need-history-object-length/index-update
  212. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_that_only_need_history_object_length_index_update(int target_step) const
  213. {
  214. // NOTE: Other navigables might not be impacted by the traversal. For example, if the response is a 204, the currently active document will remain.
  215. // Additionally, going 'back' after a 204 will change the current session history entry, but the active session history entry will already be correct.
  216. // 1. Let results be an empty list.
  217. Vector<JS::Handle<Navigable>> results;
  218. // 2. Let navigablesToCheck be « traversable ».
  219. Vector<JS::Handle<Navigable>> navigables_to_check;
  220. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  221. // 3. For each navigable of navigablesToCheck:
  222. while (!navigables_to_check.is_empty()) {
  223. auto navigable = navigables_to_check.take_first();
  224. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  225. auto target_entry = navigable->get_the_target_history_entry(target_step);
  226. // 2. If targetEntry is navigable's current session history entry and targetEntry's document state's reload pending is false, then:
  227. if (target_entry == navigable->current_session_history_entry() && !target_entry->document_state()->reload_pending()) {
  228. // 1. Append navigable to results.
  229. results.append(navigable);
  230. // 2. Extend navigablesToCheck with navigable's child navigables.
  231. navigables_to_check.extend(navigable->child_navigables());
  232. }
  233. }
  234. // 4. Return results.
  235. return results;
  236. }
  237. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#getting-all-navigables-that-might-experience-a-cross-document-traversal
  238. Vector<JS::Handle<Navigable>> TraversableNavigable::get_all_navigables_that_might_experience_a_cross_document_traversal(int target_step) const
  239. {
  240. // NOTE: From traversable's session history traversal queue's perspective, these documents are candidates for going cross-document during the
  241. // traversal described by targetStep. They will not experience a cross-document traversal if the status code for their target document is
  242. // HTTP 204 No Content.
  243. // Note that if a given navigable might experience a cross-document traversal, this algorithm will return navigable but not its child navigables.
  244. // Those would end up unloaded, not traversed.
  245. // 1. Let results be an empty list.
  246. Vector<JS::Handle<Navigable>> results;
  247. // 2. Let navigablesToCheck be « traversable ».
  248. Vector<JS::Handle<Navigable>> navigables_to_check;
  249. navigables_to_check.append(const_cast<TraversableNavigable&>(*this));
  250. // 3. For each navigable of navigablesToCheck:
  251. while (!navigables_to_check.is_empty()) {
  252. auto navigable = navigables_to_check.take_first();
  253. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  254. auto target_entry = navigable->get_the_target_history_entry(target_step);
  255. // 2. If targetEntry's document is not navigable's document or targetEntry's document state's reload pending is true, then append navigable to results.
  256. // NOTE: Although navigable's active history entry can change synchronously, the new entry will always have the same Document,
  257. // so accessing navigable's document is reliable.
  258. if (target_entry->document() != navigable->active_document() || target_entry->document_state()->reload_pending()) {
  259. results.append(navigable);
  260. }
  261. // 3. Otherwise, extend navigablesToCheck with navigable's child navigables.
  262. // Adding child navigables to navigablesToCheck means those navigables will also be checked by this loop.
  263. // Child navigables are only checked if the navigable's active document will not change as part of this traversal.
  264. else {
  265. navigables_to_check.extend(navigable->child_navigables());
  266. }
  267. }
  268. // 4. Return results.
  269. return results;
  270. }
  271. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#deactivate-a-document-for-a-cross-document-navigation
  272. static void deactivate_a_document_for_cross_document_navigation(JS::NonnullGCPtr<DOM::Document> displayed_document, Optional<UserNavigationInvolvement>, JS::NonnullGCPtr<SessionHistoryEntry> target_entry, JS::NonnullGCPtr<JS::HeapFunction<void()>> after_potential_unloads)
  273. {
  274. // 1. Let navigable be displayedDocument's node navigable.
  275. auto navigable = displayed_document->navigable();
  276. // 2. Let potentiallyTriggerViewTransition be false.
  277. auto potentially_trigger_view_transition = false;
  278. // FIXME: 3. Let isBrowserUINavigation be true if userNavigationInvolvement is "browser UI"; otherwise false.
  279. // FIXME: 4. Set potentiallyTriggerViewTransition to the result of calling can navigation trigger a cross-document
  280. // view-transition? given displayedDocument, targetEntry's document, navigationType, and isBrowserUINavigation.
  281. // 5. If potentiallyTriggerViewTransition is false, then:
  282. if (!potentially_trigger_view_transition) {
  283. // FIXME 1. Let firePageSwapBeforeUnload be the following step
  284. // 1. Fire the pageswap event given displayedDocument, targetEntry, navigationType, and null.
  285. // 2. Set the ongoing navigation for navigable to null.
  286. navigable->set_ongoing_navigation({});
  287. // 3. Unload a document and its descendants given displayedDocument, targetEntry's document, afterPotentialUnloads, and firePageSwapBeforeUnload.
  288. displayed_document->unload_a_document_and_its_descendants(target_entry->document(), after_potential_unloads);
  289. }
  290. // FIXME: 6. Otherwise, queue a global task on the navigation and traversal task source given navigable's active window to run the steps:
  291. else {
  292. // FIXME: 1. Let proceedWithNavigationAfterViewTransitionCapture be the following step:
  293. // 1. Append the following session history traversal steps to navigable's traversable navigable:
  294. // 1. Set the ongoing navigation for navigable to null.
  295. // 2. Unload a document and its descendants given displayedDocument, targetEntry's document, and afterPotentialUnloads.
  296. // FIXME: 2. Let viewTransition be the result of setting up a cross-document view-transition given displayedDocument,
  297. // targetEntry's document, navigationType, and proceedWithNavigationAfterViewTransitionCapture.
  298. // FIXME: 3. Fire the pageswap event given displayedDocument, targetEntry, navigationType, and viewTransition.
  299. // FIXME: 4. If viewTransition is null, then run proceedWithNavigationAfterViewTransitionCapture.
  300. TODO();
  301. }
  302. }
  303. struct ChangingNavigableContinuationState : public JS::Cell {
  304. JS_CELL(ChangingNavigableContinuationState, JS::Cell);
  305. JS_DECLARE_ALLOCATOR(ChangingNavigableContinuationState);
  306. JS::GCPtr<DOM::Document> displayed_document;
  307. JS::GCPtr<SessionHistoryEntry> target_entry;
  308. JS::GCPtr<Navigable> navigable;
  309. bool update_only = false;
  310. JS::GCPtr<SessionHistoryEntry> populated_target_entry;
  311. bool populated_cloned_target_session_history_entry = false;
  312. virtual void visit_edges(Cell::Visitor& visitor) override
  313. {
  314. Base::visit_edges(visitor);
  315. visitor.visit(displayed_document);
  316. visitor.visit(target_entry);
  317. visitor.visit(navigable);
  318. visitor.visit(populated_target_entry);
  319. }
  320. };
  321. JS_DEFINE_ALLOCATOR(ChangingNavigableContinuationState);
  322. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-history-step
  323. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_history_step(
  324. int step,
  325. bool check_for_cancelation,
  326. IGNORE_USE_IN_ESCAPING_LAMBDA Optional<SourceSnapshotParams> source_snapshot_params,
  327. JS::GCPtr<Navigable> initiator_to_check,
  328. Optional<UserNavigationInvolvement> user_involvement_for_navigate_events,
  329. IGNORE_USE_IN_ESCAPING_LAMBDA Optional<Bindings::NavigationType> navigation_type,
  330. IGNORE_USE_IN_ESCAPING_LAMBDA SynchronousNavigation synchronous_navigation)
  331. {
  332. auto& vm = this->vm();
  333. // FIXME: 1. Assert: This is running within traversable's session history traversal queue.
  334. // 2. Let targetStep be the result of getting the used step given traversable and step.
  335. auto target_step = get_the_used_step(step);
  336. // Note: Calling this early so we can re-use the same list in 3.2 and 6.
  337. auto change_or_reload_navigables = get_all_navigables_whose_current_session_history_entry_will_change_or_reload(target_step);
  338. // 3. If initiatorToCheck is not null, then:
  339. if (initiator_to_check != nullptr) {
  340. // 1. Assert: sourceSnapshotParams is not null.
  341. VERIFY(source_snapshot_params.has_value());
  342. // 2. For each navigable of get all navigables whose current session history entry will change or reload:
  343. // if initiatorToCheck is not allowed by sandboxing to navigate navigable given sourceSnapshotParams, then return "initiator-disallowed".
  344. for (auto const& navigable : change_or_reload_navigables) {
  345. if (!initiator_to_check->allowed_by_sandboxing_to_navigate(*navigable, *source_snapshot_params))
  346. return HistoryStepResult::InitiatorDisallowed;
  347. }
  348. }
  349. // 4. Let navigablesCrossingDocuments be the result of getting all navigables that might experience a cross-document traversal given traversable and targetStep.
  350. [[maybe_unused]] auto navigables_crossing_documents = get_all_navigables_that_might_experience_a_cross_document_traversal(target_step);
  351. // 5. FIXME: If checkForCancelation is true, and the result of checking if unloading is canceled given navigablesCrossingDocuments, traversable, targetStep,
  352. // and userInvolvementForNavigateEvents is not "continue", then return that result.
  353. (void)check_for_cancelation;
  354. // 6. Let changingNavigables be the result of get all navigables whose current session history entry will change or reload given traversable and targetStep.
  355. auto changing_navigables = move(change_or_reload_navigables);
  356. // 7. Let nonchangingNavigablesThatStillNeedUpdates be the result of getting all navigables that only need history object length/index update given traversable and targetStep.
  357. auto non_changing_navigables_that_still_need_updates = get_all_navigables_that_only_need_history_object_length_index_update(target_step);
  358. // 8. For each navigable of changingNavigables:
  359. for (auto& navigable : changing_navigables) {
  360. // 1. Let targetEntry be the result of getting the target history entry given navigable and targetStep.
  361. auto target_entry = navigable->get_the_target_history_entry(target_step);
  362. // 2. Set navigable's current session history entry to targetEntry.
  363. navigable->set_current_session_history_entry(target_entry);
  364. // 3. Set navigable's ongoing navigation to "traversal".
  365. navigable->set_ongoing_navigation(Traversal::Tag);
  366. }
  367. // 9. Let totalChangeJobs be the size of changingNavigables.
  368. auto total_change_jobs = changing_navigables.size();
  369. // 10. Let completedChangeJobs be 0.
  370. IGNORE_USE_IN_ESCAPING_LAMBDA size_t completed_change_jobs = 0;
  371. // 11. Let changingNavigableContinuations be an empty queue of changing navigable continuation states.
  372. // NOTE: This queue is used to split the operations on changingNavigables into two parts. Specifically, changingNavigableContinuations holds data for the second part.
  373. IGNORE_USE_IN_ESCAPING_LAMBDA Queue<JS::Handle<ChangingNavigableContinuationState>> changing_navigable_continuations;
  374. // 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:
  375. for (auto& navigable : changing_navigables) {
  376. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), JS::create_heap_function(heap(), [&] {
  377. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  378. if (navigable->has_been_destroyed()) {
  379. completed_change_jobs++;
  380. return;
  381. }
  382. // 1. Let displayedEntry be navigable's active session history entry.
  383. auto displayed_entry = navigable->active_session_history_entry();
  384. // 2. Let targetEntry be navigable's current session history entry.
  385. auto target_entry = navigable->current_session_history_entry();
  386. // 3. Let changingNavigableContinuation be a changing navigable continuation state with:
  387. auto changing_navigable_continuation = vm.heap().allocate_without_realm<ChangingNavigableContinuationState>();
  388. changing_navigable_continuation->displayed_document = displayed_entry->document();
  389. changing_navigable_continuation->target_entry = target_entry;
  390. changing_navigable_continuation->navigable = navigable;
  391. changing_navigable_continuation->update_only = false;
  392. changing_navigable_continuation->populated_target_entry = nullptr;
  393. changing_navigable_continuation->populated_cloned_target_session_history_entry = false;
  394. // 4. If displayedEntry is targetEntry and targetEntry's document state's reload pending is false, then:
  395. if (synchronous_navigation == SynchronousNavigation::Yes && !target_entry->document_state()->reload_pending()) {
  396. // 1. Set changingNavigableContinuation's update-only to true.
  397. changing_navigable_continuation->update_only = true;
  398. // 2. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  399. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  400. // 3. Abort these steps.
  401. return;
  402. }
  403. // 5. Switch on navigationType:
  404. if (navigation_type.has_value()) {
  405. switch (navigation_type.value()) {
  406. case Bindings::NavigationType::Reload:
  407. // - "reload": Assert: targetEntry's document state's reload pending is true.
  408. VERIFY(target_entry->document_state()->reload_pending());
  409. break;
  410. case Bindings::NavigationType::Traverse:
  411. // - "traverse": Assert: targetEntry's document state's ever populated is true.
  412. VERIFY(target_entry->document_state()->ever_populated());
  413. break;
  414. case Bindings::NavigationType::Replace:
  415. // FIXME: Add ever populated check
  416. // - "replace": Assert: targetEntry's step is displayedEntry's step and targetEntry's document state's ever populated is false.
  417. VERIFY(target_entry->step() == displayed_entry->step());
  418. break;
  419. case Bindings::NavigationType::Push:
  420. // FIXME: Add ever populated check, and fix the bug where top level traversable's step is not updated when a child navigable navigates
  421. // - "push": Assert: targetEntry's step is displayedEntry's step + 1 and targetEntry's document state's ever populated is false.
  422. VERIFY(target_entry->step().get<int>() > displayed_entry->step().get<int>());
  423. break;
  424. }
  425. }
  426. // 6. Let oldOrigin be targetEntry's document state's origin.
  427. auto old_origin = target_entry->document_state()->origin();
  428. // FIXME: 7. If navigable is not traversable, and targetEntry is not navigable's current session history entry,
  429. // and oldOrigin is the same as navigable's current session history entry's document state's origin,
  430. // then fire a traverse navigate event given targetEntry and userInvolvementForNavigateEvents.
  431. auto after_document_populated = [old_origin, changing_navigable_continuation, &changing_navigable_continuations, &vm, &navigable](bool populated_cloned_target_she, JS::NonnullGCPtr<SessionHistoryEntry> target_entry) mutable {
  432. changing_navigable_continuation->populated_target_entry = target_entry;
  433. changing_navigable_continuation->populated_cloned_target_session_history_entry = populated_cloned_target_she;
  434. // 1. If targetEntry's document is null, then set changingNavigableContinuation's update-only to true.
  435. if (!target_entry->document()) {
  436. changing_navigable_continuation->update_only = true;
  437. }
  438. else {
  439. // 2. If targetEntry's document's origin is not oldOrigin, then set targetEntry's classic history API state to StructuredSerializeForStorage(null).
  440. if (target_entry->document()->origin() != old_origin) {
  441. target_entry->set_classic_history_api_state(MUST(structured_serialize_for_storage(vm, JS::js_null())));
  442. }
  443. // 3. If all of the following are true:
  444. // - navigable's parent is null;
  445. // - targetEntry's document's browsing context is not an auxiliary browsing context whose opener browsing context is non-null; and
  446. // - targetEntry's document's origin is not oldOrigin,
  447. // then set targetEntry's document state's navigable target name to the empty string.
  448. if (navigable->parent() != nullptr
  449. && target_entry->document()->browsing_context()->opener_browsing_context() == nullptr
  450. && target_entry->document_state()->origin() != old_origin) {
  451. target_entry->document_state()->set_navigable_target_name(String {});
  452. }
  453. }
  454. // 4. Enqueue changingNavigableContinuation on changingNavigableContinuations.
  455. changing_navigable_continuations.enqueue(move(changing_navigable_continuation));
  456. };
  457. // 8. If targetEntry's document is null, or targetEntry's document state's reload pending is true, then:
  458. if (!target_entry->document() || target_entry->document_state()->reload_pending()) {
  459. // FIXME: 1. Let navTimingType be "back_forward" if targetEntry's document is null; otherwise "reload".
  460. // 2. Let targetSnapshotParams be the result of snapshotting target snapshot params given navigable.
  461. auto target_snapshot_params = navigable->snapshot_target_snapshot_params();
  462. // 3. Let potentiallyTargetSpecificSourceSnapshotParams be sourceSnapshotParams.
  463. Optional<SourceSnapshotParams> potentially_target_specific_source_snapshot_params = source_snapshot_params;
  464. // 4. If potentiallyTargetSpecificSourceSnapshotParams is null, then set it to the result of snapshotting source snapshot params given navigable's active document.
  465. if (!potentially_target_specific_source_snapshot_params.has_value()) {
  466. potentially_target_specific_source_snapshot_params = navigable->active_document()->snapshot_source_snapshot_params();
  467. }
  468. // 5. Set targetEntry's document state's reload pending to false.
  469. target_entry->document_state()->set_reload_pending(false);
  470. // 6. Let allowPOST be targetEntry's document state's reload pending.
  471. auto allow_POST = target_entry->document_state()->reload_pending();
  472. // https://github.com/whatwg/html/issues/9869
  473. // Reloading requires population of the active session history entry, making it inactive.
  474. // This results in a situation where tasks that unload the previous document and activate a new
  475. // document cannot run. To resolve this, the target entry is cloned before it is populated.
  476. // After the unloading of the previous document is completed, all fields potentially affected by the
  477. // population are copied from the cloned target entry to the actual target entry.
  478. auto populated_target_entry = target_entry->clone();
  479. // 7. In parallel, attempt to populate the history entry's document for targetEntry, given navigable, potentiallyTargetSpecificSourceSnapshotParams,
  480. // targetSnapshotParams, with allowPOST set to allowPOST and completionSteps set to queue a global task on the navigation and traversal task source given
  481. // navigable's active window to run afterDocumentPopulated.
  482. Platform::EventLoopPlugin::the().deferred_invoke([populated_target_entry, potentially_target_specific_source_snapshot_params, target_snapshot_params, this, allow_POST, navigable, after_document_populated = JS::create_heap_function(this->heap(), move(after_document_populated))] {
  483. navigable->populate_session_history_entry_document(populated_target_entry, *potentially_target_specific_source_snapshot_params, target_snapshot_params, {}, Empty {}, CSPNavigationType::Other, allow_POST, [this, after_document_populated, populated_target_entry]() mutable {
  484. queue_global_task(Task::Source::NavigationAndTraversal, *active_window(), JS::create_heap_function(this->heap(), [after_document_populated, populated_target_entry]() mutable {
  485. after_document_populated->function()(true, populated_target_entry);
  486. }));
  487. })
  488. .release_value_but_fixme_should_propagate_errors();
  489. });
  490. }
  491. // Otherwise, run afterDocumentPopulated immediately.
  492. else {
  493. after_document_populated(false, *target_entry);
  494. }
  495. }));
  496. }
  497. auto check_if_document_population_tasks_completed = JS::SafeFunction<bool()>([&] {
  498. return changing_navigable_continuations.size() + completed_change_jobs == total_change_jobs;
  499. });
  500. if (synchronous_navigation == SynchronousNavigation::Yes) {
  501. // NOTE: Synchronous navigation should never require document population, so it is safe to process only NavigationAndTraversal source.
  502. main_thread_event_loop().spin_processing_tasks_with_source_until(Task::Source::NavigationAndTraversal, move(check_if_document_population_tasks_completed));
  503. } else {
  504. // NOTE: Process all task sources while waiting because reloading or back/forward navigation might require fetching to populate a document.
  505. main_thread_event_loop().spin_until(move(check_if_document_population_tasks_completed));
  506. }
  507. // 13. Let navigablesThatMustWaitBeforeHandlingSyncNavigation be an empty set.
  508. Vector<JS::GCPtr<Navigable>> navigables_that_must_wait_before_handling_sync_navigation;
  509. // 14. While completedChangeJobs does not equal totalChangeJobs:
  510. while (!changing_navigable_continuations.is_empty()) {
  511. // NOTE: Synchronous navigations that are intended to take place before this traversal jump the queue at this point,
  512. // so they can be added to the correct place in traversable's session history entries before this traversal
  513. // potentially unloads their document. More details can be found here (https://html.spec.whatwg.org/multipage/browsing-the-web.html#sync-navigation-steps-queue-jumping-examples)
  514. // 1. If traversable's running nested apply history step is false, then:
  515. if (!m_running_nested_apply_history_step) {
  516. // 1. While traversable's session history traversal queue's algorithm set contains one or more synchronous
  517. // navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation:
  518. // 1. Let steps be the first item in traversable's session history traversal queue's algorithm set
  519. // that is synchronous navigation steps with a target navigable not contained in navigablesThatMustWaitBeforeHandlingSyncNavigation.
  520. // 2. Remove steps from traversable's session history traversal queue's algorithm set.
  521. for (auto entry = m_session_history_traversal_queue->first_synchronous_navigation_steps_with_target_navigable_not_contained_in(navigables_that_must_wait_before_handling_sync_navigation);
  522. entry;
  523. entry = m_session_history_traversal_queue->first_synchronous_navigation_steps_with_target_navigable_not_contained_in(navigables_that_must_wait_before_handling_sync_navigation)) {
  524. // 3. Set traversable's running nested apply history step to true.
  525. m_running_nested_apply_history_step = true;
  526. // 4. Run steps.
  527. entry->execute_steps();
  528. // 5. Set traversable's running nested apply history step to false.
  529. m_running_nested_apply_history_step = false;
  530. }
  531. }
  532. // 2. Let changingNavigableContinuation be the result of dequeuing from changingNavigableContinuations.
  533. auto changing_navigable_continuation = changing_navigable_continuations.dequeue();
  534. // 3. If changingNavigableContinuation is nothing, then continue.
  535. // 4. Let displayedDocument be changingNavigableContinuation's displayed document.
  536. auto displayed_document = changing_navigable_continuation->displayed_document;
  537. // 5. Let targetEntry be changingNavigableContinuation's target entry.
  538. JS::GCPtr<SessionHistoryEntry> const populated_target_entry = changing_navigable_continuation->populated_target_entry;
  539. // 6. Let navigable be changingNavigableContinuation's navigable.
  540. auto navigable = changing_navigable_continuation->navigable;
  541. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  542. if (navigable->has_been_destroyed())
  543. continue;
  544. // 7. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  545. auto history_object_length_and_index = get_the_history_object_length_and_index(target_step);
  546. auto script_history_length = history_object_length_and_index.script_history_length;
  547. auto script_history_index = history_object_length_and_index.script_history_index;
  548. // 8. Append navigable to navigablesThatMustWaitBeforeHandlingSyncNavigation.
  549. navigables_that_must_wait_before_handling_sync_navigation.append(*navigable);
  550. // 9. Let entriesForNavigationAPI be the result of getting session history entries for the navigation API given navigable and targetStep.
  551. auto entries_for_navigation_api = get_session_history_entries_for_the_navigation_api(*navigable, target_step);
  552. // 12. In both cases, let afterPotentialUnloads be the following steps:
  553. bool const update_only = changing_navigable_continuation->update_only;
  554. JS::GCPtr<SessionHistoryEntry> const target_entry = changing_navigable_continuation->target_entry;
  555. bool const populated_cloned_target_session_history_entry = changing_navigable_continuation->populated_cloned_target_session_history_entry;
  556. auto after_potential_unload = JS::create_heap_function(this->heap(), [navigable, update_only, target_entry, populated_target_entry, populated_cloned_target_session_history_entry, displayed_document, &completed_change_jobs, script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api), &heap = this->heap()] {
  557. if (populated_cloned_target_session_history_entry) {
  558. target_entry->set_document_state(populated_target_entry->document_state());
  559. target_entry->set_url(populated_target_entry->url());
  560. target_entry->set_classic_history_api_state(populated_target_entry->classic_history_api_state());
  561. }
  562. // 1. If changingNavigableContinuation's update-only is false, then activate history entry targetEntry for navigable.
  563. if (!update_only)
  564. navigable->activate_history_entry(*target_entry);
  565. // 2. Let updateDocument be an algorithm step which performs update document for history step application given
  566. // targetEntry's document, targetEntry, changingNavigableContinuation's update-only, scriptHistoryLength,
  567. // scriptHistoryIndex, navigationType, entriesForNavigationAPI, and displayedEntry.
  568. auto update_document = [script_history_length, script_history_index, entries_for_navigation_api = move(entries_for_navigation_api), target_entry, update_only] {
  569. target_entry->document()->update_for_history_step_application(*target_entry, update_only, script_history_length, script_history_index, entries_for_navigation_api);
  570. };
  571. // 3. If targetEntry's document is equal to displayedDocument, then perform updateDocument.
  572. if (target_entry->document().ptr() == displayed_document.ptr()) {
  573. update_document();
  574. }
  575. // 5. Otherwise, queue a global task on the navigation and traversal task source given targetEntry's document's relevant global object to perform updateDocument
  576. else {
  577. queue_global_task(Task::Source::NavigationAndTraversal, relevant_global_object(*target_entry->document()), JS::create_heap_function(heap, move(update_document)));
  578. }
  579. // 6. Increment completedChangeJobs.
  580. completed_change_jobs++;
  581. });
  582. // 10. If changingNavigableContinuation's update-only is true, or targetEntry's document is displayedDocument, then:
  583. if (changing_navigable_continuation->update_only || populated_target_entry->document().ptr() == displayed_document.ptr()) {
  584. // 1. Set the ongoing navigation for navigable to null.
  585. navigable->set_ongoing_navigation({});
  586. // 2. Queue a global task on the navigation and traversal task source given navigable's active window to perform afterPotentialUnloads.
  587. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), after_potential_unload);
  588. }
  589. // 11. Otherwise:
  590. else {
  591. // 1. Assert: navigationType is not null.
  592. VERIFY(navigation_type.has_value());
  593. // 2. Deactivate displayedDocument, given userNavigationInvolvement, targetEntry, navigationType, and afterPotentialUnloads.
  594. deactivate_a_document_for_cross_document_navigation(*displayed_document, user_involvement_for_navigate_events, *populated_target_entry, after_potential_unload);
  595. }
  596. }
  597. main_thread_event_loop().spin_processing_tasks_with_source_until(Task::Source::NavigationAndTraversal, [&] {
  598. return completed_change_jobs == total_change_jobs;
  599. });
  600. // 15. Let totalNonchangingJobs be the size of nonchangingNavigablesThatStillNeedUpdates.
  601. auto total_non_changing_jobs = non_changing_navigables_that_still_need_updates.size();
  602. // 16. Let completedNonchangingJobs be 0.
  603. IGNORE_USE_IN_ESCAPING_LAMBDA auto completed_non_changing_jobs = 0u;
  604. // 17. Let (scriptHistoryLength, scriptHistoryIndex) be the result of getting the history object length and index given traversable and targetStep.
  605. auto length_and_index = get_the_history_object_length_and_index(target_step);
  606. IGNORE_USE_IN_ESCAPING_LAMBDA auto script_history_length = length_and_index.script_history_length;
  607. IGNORE_USE_IN_ESCAPING_LAMBDA auto script_history_index = length_and_index.script_history_index;
  608. // 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:
  609. for (auto& navigable : non_changing_navigables_that_still_need_updates) {
  610. if (navigable->has_been_destroyed()) {
  611. ++completed_non_changing_jobs;
  612. continue;
  613. }
  614. queue_global_task(Task::Source::NavigationAndTraversal, *navigable->active_window(), JS::create_heap_function(heap(), [&] {
  615. // NOTE: This check is not in the spec but we should not continue navigation if navigable has been destroyed.
  616. if (navigable->has_been_destroyed()) {
  617. ++completed_non_changing_jobs;
  618. return;
  619. }
  620. // 1. Let document be navigable's active document.
  621. auto document = navigable->active_document();
  622. // 2. Set document's history object's index to scriptHistoryIndex.
  623. document->history()->m_index = script_history_index;
  624. // 3. Set document's history object's length to scriptHistoryLength.
  625. document->history()->m_length = script_history_length;
  626. // 4. Increment completedNonchangingJobs.
  627. ++completed_non_changing_jobs;
  628. }));
  629. }
  630. // 19. Wait for completedNonchangingJobs to equal totalNonchangingJobs.
  631. // AD-HOC: Since currently populate_session_history_entry_document does not run in parallel
  632. // we call spin_until to interrupt execution of this function and let document population
  633. // to complete.
  634. main_thread_event_loop().spin_processing_tasks_with_source_until(Task::Source::NavigationAndTraversal, [&] {
  635. return completed_non_changing_jobs == total_non_changing_jobs;
  636. });
  637. // 20. Set traversable's current session history step to targetStep.
  638. m_current_session_history_step = target_step;
  639. // Not in the spec:
  640. auto back_enabled = m_current_session_history_step > 0;
  641. VERIFY(m_session_history_entries.size() > 0);
  642. auto forward_enabled = can_go_forward();
  643. page().client().page_did_update_navigation_buttons_state(back_enabled, forward_enabled);
  644. page().client().page_did_change_url(current_session_history_entry()->url());
  645. // 21. Return "applied".
  646. return HistoryStepResult::Applied;
  647. }
  648. Vector<JS::NonnullGCPtr<SessionHistoryEntry>> TraversableNavigable::get_session_history_entries_for_the_navigation_api(JS::NonnullGCPtr<Navigable> navigable, int target_step)
  649. {
  650. // 1. Let rawEntries be the result of getting session history entries for navigable.
  651. auto raw_entries = navigable->get_session_history_entries();
  652. if (raw_entries.is_empty())
  653. return {};
  654. // 2. Let entriesForNavigationAPI be a new empty list.
  655. Vector<JS::NonnullGCPtr<SessionHistoryEntry>> entries_for_navigation_api;
  656. // 3. Let startingIndex be the index of the session history entry in rawEntries who has the greatest step less than or equal to targetStep.
  657. // FIXME: Use min/max_element algorithm or some such here
  658. int starting_index = 0;
  659. auto max_step = 0;
  660. for (auto i = 0u; i < raw_entries.size(); ++i) {
  661. auto const& entry = raw_entries[i];
  662. if (entry->step().has<int>()) {
  663. auto step = entry->step().get<int>();
  664. if (step <= target_step && step > max_step) {
  665. starting_index = static_cast<int>(i);
  666. }
  667. }
  668. }
  669. // 4. Append rawEntries[startingIndex] to entriesForNavigationAPI.
  670. entries_for_navigation_api.append(raw_entries[starting_index]);
  671. // 5. Let startingOrigin be rawEntries[startingIndex]'s document state's origin.
  672. auto starting_origin = raw_entries[starting_index]->document_state()->origin();
  673. // 6. Let i be startingIndex − 1.
  674. auto i = starting_index - 1;
  675. // 7. While i > 0:
  676. while (i > 0) {
  677. auto& entry = raw_entries[static_cast<unsigned>(i)];
  678. // 1. If rawEntries[i]'s document state's origin is not same origin with startingOrigin, then break.
  679. auto entry_origin = entry->document_state()->origin();
  680. if (starting_origin.has_value() && entry_origin.has_value() && !entry_origin->is_same_origin(*starting_origin))
  681. break;
  682. // 2. Prepend rawEntries[i] to entriesForNavigationAPI.
  683. entries_for_navigation_api.prepend(entry);
  684. // 3. Set i to i − 1.
  685. --i;
  686. }
  687. // 8. Set i to startingIndex + 1.
  688. i = starting_index + 1;
  689. // 9. While i < rawEntries's size:
  690. while (i < static_cast<int>(raw_entries.size())) {
  691. auto& entry = raw_entries[static_cast<unsigned>(i)];
  692. // 1. If rawEntries[i]'s document state's origin is not same origin with startingOrigin, then break.
  693. auto entry_origin = entry->document_state()->origin();
  694. if (starting_origin.has_value() && entry_origin.has_value() && !entry_origin->is_same_origin(*starting_origin))
  695. break;
  696. // 2. Append rawEntries[i] to entriesForNavigationAPI.
  697. entries_for_navigation_api.append(entry);
  698. // 3. Set i to i + 1.
  699. ++i;
  700. }
  701. // 10. Return entriesForNavigationAPI.
  702. return entries_for_navigation_api;
  703. }
  704. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#clear-the-forward-session-history
  705. void TraversableNavigable::clear_the_forward_session_history()
  706. {
  707. // FIXME: 1. Assert: this is running within navigable's session history traversal queue.
  708. // 2. Let step be the navigable's current session history step.
  709. auto step = current_session_history_step();
  710. // 3. Let entryLists be the ordered set « navigable's session history entries ».
  711. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>>&> entry_lists;
  712. entry_lists.append(session_history_entries());
  713. // 4. For each entryList of entryLists:
  714. while (!entry_lists.is_empty()) {
  715. auto& entry_list = entry_lists.take_first();
  716. // 1. Remove every session history entry from entryList that has a step greater than step.
  717. entry_list.remove_all_matching([step](auto& entry) {
  718. return entry->step().template get<int>() > step;
  719. });
  720. // 2. For each entry of entryList:
  721. for (auto& entry : entry_list) {
  722. // 1. For each nestedHistory of entry's document state's nested histories, append nestedHistory's entries list to entryLists.
  723. for (auto& nested_history : entry->document_state()->nested_histories()) {
  724. entry_lists.append(nested_history.entries);
  725. }
  726. }
  727. }
  728. }
  729. bool TraversableNavigable::can_go_forward() const
  730. {
  731. auto step = current_session_history_step();
  732. Vector<Vector<JS::NonnullGCPtr<SessionHistoryEntry>> const&> entry_lists;
  733. entry_lists.append(session_history_entries());
  734. while (!entry_lists.is_empty()) {
  735. auto const& entry_list = entry_lists.take_first();
  736. for (auto const& entry : entry_list) {
  737. if (entry->step().template get<int>() > step)
  738. return true;
  739. for (auto& nested_history : entry->document_state()->nested_histories())
  740. entry_lists.append(nested_history.entries);
  741. }
  742. }
  743. return false;
  744. }
  745. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history-by-a-delta
  746. void TraversableNavigable::traverse_the_history_by_delta(int delta, Optional<DOM::Document&> source_document)
  747. {
  748. // 1. Let sourceSnapshotParams and initiatorToCheck be null.
  749. Optional<SourceSnapshotParams> source_snapshot_params = {};
  750. JS::GCPtr<Navigable> initiator_to_check = nullptr;
  751. // 2. Let userInvolvement be "browser UI".
  752. UserNavigationInvolvement user_involvement = UserNavigationInvolvement::BrowserUI;
  753. // 1. If sourceDocument is given, then:
  754. if (source_document.has_value()) {
  755. // 1. Set sourceSnapshotParams to the result of snapshotting source snapshot params given sourceDocument.
  756. source_snapshot_params = source_document->snapshot_source_snapshot_params();
  757. // 2. Set initiatorToCheck to sourceDocument's node navigable.
  758. initiator_to_check = source_document->navigable();
  759. // 3. Set userInvolvement to "none".
  760. user_involvement = UserNavigationInvolvement::None;
  761. }
  762. // 4. Append the following session history traversal steps to traversable:
  763. append_session_history_traversal_steps([this, delta, source_snapshot_params = move(source_snapshot_params), initiator_to_check, user_involvement] {
  764. // 1. Let allSteps be the result of getting all used history steps for traversable.
  765. auto all_steps = get_all_used_history_steps();
  766. // 2. Let currentStepIndex be the index of traversable's current session history step within allSteps.
  767. auto current_step_index = *all_steps.find_first_index(current_session_history_step());
  768. // 3. Let targetStepIndex be currentStepIndex plus delta
  769. auto target_step_index = current_step_index + delta;
  770. // 4. If allSteps[targetStepIndex] does not exist, then abort these steps.
  771. if (target_step_index >= all_steps.size()) {
  772. return;
  773. }
  774. // 5. Apply the traverse history step allSteps[targetStepIndex] to traversable, given sourceSnapshotParams,
  775. // initiatorToCheck, and userInvolvement.
  776. apply_the_traverse_history_step(all_steps[target_step_index], source_snapshot_params, initiator_to_check, user_involvement);
  777. });
  778. }
  779. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#update-for-navigable-creation/destruction
  780. TraversableNavigable::HistoryStepResult TraversableNavigable::update_for_navigable_creation_or_destruction()
  781. {
  782. // 1. Let step be traversable's current session history step.
  783. auto step = current_session_history_step();
  784. // 2. Return the result of applying the history step to traversable given false, null, null, null, and null.
  785. return apply_the_history_step(step, false, {}, {}, {}, {}, SynchronousNavigation::No);
  786. }
  787. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#apply-the-reload-history-step
  788. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_reload_history_step()
  789. {
  790. // 1. Let step be traversable's current session history step.
  791. auto step = current_session_history_step();
  792. // 2. Return the result of applying the history step step to traversable given true, null, null, null, and "reload".
  793. return apply_the_history_step(step, true, {}, {}, {}, Bindings::NavigationType::Reload, SynchronousNavigation::No);
  794. }
  795. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_push_or_replace_history_step(int step, HistoryHandlingBehavior history_handling, SynchronousNavigation synchronous_navigation)
  796. {
  797. // 1. Return the result of applying the history step step to traversable given false, null, null, null, and historyHandling.
  798. auto navigation_type = history_handling == HistoryHandlingBehavior::Replace ? Bindings::NavigationType::Replace : Bindings::NavigationType::Push;
  799. return apply_the_history_step(step, false, {}, {}, {}, navigation_type, synchronous_navigation);
  800. }
  801. TraversableNavigable::HistoryStepResult TraversableNavigable::apply_the_traverse_history_step(int step, Optional<SourceSnapshotParams> source_snapshot_params, JS::GCPtr<Navigable> initiator_to_check, UserNavigationInvolvement user_involvement)
  802. {
  803. // 1. Return the result of applying the history step step to traversable given true, sourceSnapshotParams, initiatorToCheck, userInvolvement, and "traverse".
  804. return apply_the_history_step(step, true, move(source_snapshot_params), initiator_to_check, user_involvement, Bindings::NavigationType::Traverse, SynchronousNavigation::No);
  805. }
  806. // https://html.spec.whatwg.org/multipage/document-sequences.html#close-a-top-level-traversable
  807. void TraversableNavigable::close_top_level_traversable()
  808. {
  809. VERIFY(is_top_level_traversable());
  810. // 1. Let toUnload be traversable's active document's inclusive descendant navigables.
  811. auto to_unload = active_document()->inclusive_descendant_navigables();
  812. // FIXME: 2. If the result of checking if unloading is user-canceled for toUnload is true, then return.
  813. // 3. Unload the active documents of each of toUnload.
  814. for (auto navigable : to_unload) {
  815. navigable->active_document()->unload();
  816. }
  817. // 4. Destroy traversable.
  818. destroy_top_level_traversable();
  819. }
  820. // https://html.spec.whatwg.org/multipage/document-sequences.html#destroy-a-top-level-traversable
  821. void TraversableNavigable::destroy_top_level_traversable()
  822. {
  823. VERIFY(is_top_level_traversable());
  824. // 1. Let browsingContext be traversable's active browsing context.
  825. auto browsing_context = active_browsing_context();
  826. // 2. For each historyEntry in traversable's session history entries:
  827. for (auto& history_entry : m_session_history_entries) {
  828. // 1. Let document be historyEntry's document.
  829. auto document = history_entry->document();
  830. // 2. If document is not null, then destroy document.
  831. if (document)
  832. document->destroy();
  833. }
  834. // 3. Remove browsingContext.
  835. if (!browsing_context) {
  836. dbgln("TraversableNavigable::destroy_top_level_traversable: No browsing context?");
  837. } else {
  838. browsing_context->remove();
  839. }
  840. // 4. Remove traversable from the user interface (e.g., close or hide its tab in a tabbed browser).
  841. page().client().page_did_close_top_level_traversable();
  842. // 5. Remove traversable from the user agent's top-level traversable set.
  843. user_agent_top_level_traversable_set().remove(this);
  844. // FIXME: Figure out why we need to do this... we shouldn't be leaking Navigables for all time.
  845. // However, without this, we can keep stale destroyed traversables around.
  846. set_has_been_destroyed();
  847. all_navigables().remove(this);
  848. }
  849. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#finalize-a-same-document-navigation
  850. void finalize_a_same_document_navigation(JS::NonnullGCPtr<TraversableNavigable> traversable, JS::NonnullGCPtr<Navigable> target_navigable, JS::NonnullGCPtr<SessionHistoryEntry> target_entry, JS::GCPtr<SessionHistoryEntry> entry_to_replace, HistoryHandlingBehavior history_handling)
  851. {
  852. // NOTE: This is not in the spec but we should not navigate destroyed navigable.
  853. if (target_navigable->has_been_destroyed())
  854. return;
  855. // FIXME: 1. Assert: this is running on traversable's session history traversal queue.
  856. // 2. If targetNavigable's active session history entry is not targetEntry, then return.
  857. if (target_navigable->active_session_history_entry() != target_entry) {
  858. return;
  859. }
  860. // 3. Let targetStep be null.
  861. Optional<int> target_step;
  862. // 4. Let targetEntries be the result of getting session history entries for targetNavigable.
  863. auto& target_entries = target_navigable->get_session_history_entries();
  864. // 5. If entryToReplace is null, then:
  865. // FIXME: Checking containment of entryToReplace should not be needed.
  866. // For more details see https://github.com/whatwg/html/issues/10232#issuecomment-2037543137
  867. if (!entry_to_replace || !target_entries.contains_slow(JS::NonnullGCPtr { *entry_to_replace })) {
  868. // 1. Clear the forward session history of traversable.
  869. traversable->clear_the_forward_session_history();
  870. // 2. Set targetStep to traversable's current session history step + 1.
  871. target_step = traversable->current_session_history_step() + 1;
  872. // 3. Set targetEntry's step to targetStep.
  873. target_entry->set_step(*target_step);
  874. // 4. Append targetEntry to targetEntries.
  875. target_entries.append(target_entry);
  876. } else {
  877. // 1. Replace entryToReplace with targetEntry in targetEntries.
  878. *(target_entries.find(*entry_to_replace)) = target_entry;
  879. // 2. Set targetEntry's step to entryToReplace's step.
  880. target_entry->set_step(entry_to_replace->step());
  881. // 3. Set targetStep to traversable's current session history step.
  882. target_step = traversable->current_session_history_step();
  883. }
  884. // 6. Apply the push/replace history step targetStep to traversable given historyHandling.
  885. traversable->apply_the_push_or_replace_history_step(*target_step, history_handling, TraversableNavigable::SynchronousNavigation::Yes);
  886. }
  887. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  888. void TraversableNavigable::set_system_visibility_state(VisibilityState visibility_state)
  889. {
  890. if (m_system_visibility_state == visibility_state)
  891. return;
  892. m_system_visibility_state = visibility_state;
  893. // When a user-agent determines that the system visibility state for
  894. // traversable navigable traversable has changed to newState, it must run the following steps:
  895. // 1. Let navigables be the inclusive descendant navigables of traversable's active document.
  896. auto navigables = active_document()->inclusive_descendant_navigables();
  897. // 2. For each navigable of navigables:
  898. for (auto& navigable : navigables) {
  899. // 1. Let document be navigable's active document.
  900. auto document = navigable->active_document();
  901. VERIFY(document);
  902. // 2. Queue a global task on the user interaction task source given document's relevant global object
  903. // to update the visibility state of document with newState.
  904. queue_global_task(Task::Source::UserInteraction, relevant_global_object(*document), JS::create_heap_function(heap(), [visibility_state, document] {
  905. document->update_the_visibility_state(visibility_state);
  906. }));
  907. }
  908. }
  909. // https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-traversable
  910. JS::GCPtr<DOM::Node> TraversableNavigable::currently_focused_area()
  911. {
  912. // 1. If traversable does not have system focus, then return null.
  913. if (!is_focused())
  914. return nullptr;
  915. // 2. Let candidate be traversable's active document.
  916. auto candidate = active_document();
  917. // 3. While candidate's focused area is a navigable container with a non-null content navigable:
  918. // set candidate to the active document of that navigable container's content navigable.
  919. while (candidate->focused_element()
  920. && is<HTML::NavigableContainer>(candidate->focused_element())
  921. && static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).content_navigable()) {
  922. candidate = static_cast<HTML::NavigableContainer&>(*candidate->focused_element()).content_navigable()->active_document();
  923. }
  924. // 4. If candidate's focused area is non-null, set candidate to candidate's focused area.
  925. if (candidate->focused_element()) {
  926. // NOTE: We return right away here instead of assigning to candidate,
  927. // since that would require compromising type safety.
  928. return candidate->focused_element();
  929. }
  930. // 5. Return candidate.
  931. return candidate;
  932. }
  933. void TraversableNavigable::paint(Web::DevicePixelRect const& content_rect, Gfx::Bitmap& target, Web::PaintOptions paint_options)
  934. {
  935. Painting::CommandList painting_commands;
  936. Painting::RecordingPainter recording_painter(painting_commands);
  937. Gfx::IntRect bitmap_rect { {}, content_rect.size().to_type<int>() };
  938. recording_painter.fill_rect(bitmap_rect, Web::CSS::SystemColor::canvas());
  939. Web::HTML::Navigable::PaintConfig paint_config;
  940. paint_config.paint_overlay = paint_options.paint_overlay == Web::PaintOptions::PaintOverlay::Yes;
  941. paint_config.should_show_line_box_borders = paint_options.should_show_line_box_borders;
  942. paint_config.has_focus = paint_options.has_focus;
  943. record_painting_commands(recording_painter, paint_config);
  944. auto painting_command_executor_type = page().client().painting_command_executor_type();
  945. if (painting_command_executor_type == PaintingCommandExecutorType::GPU) {
  946. #ifdef HAS_ACCELERATED_GRAPHICS
  947. Web::Painting::CommandExecutorGPU painting_command_executor(*paint_options.accelerated_graphics_context, target);
  948. painting_commands.execute(painting_command_executor);
  949. #else
  950. static bool has_warned_about_configuration = false;
  951. if (!has_warned_about_configuration) {
  952. warnln("\033[31;1mConfigured to use GPU painter, but current platform does not have accelerated graphics\033[0m");
  953. has_warned_about_configuration = true;
  954. }
  955. #endif
  956. } else if (painting_command_executor_type == PaintingCommandExecutorType::Skia) {
  957. Painting::CommandExecutorSkia painting_command_executor(target);
  958. painting_commands.execute(painting_command_executor);
  959. } else {
  960. Web::Painting::CommandExecutorCPU painting_command_executor(target);
  961. painting_commands.execute(painting_command_executor);
  962. }
  963. }
  964. }