TraversableNavigable.cpp 63 KB

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