TraversableNavigable.cpp 75 KB

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