TraversableNavigable.cpp 75 KB

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