BrowsingContext.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/MainThreadVM.h>
  7. #include <LibWeb/DOM/Document.h>
  8. #include <LibWeb/DOM/Event.h>
  9. #include <LibWeb/DOM/HTMLCollection.h>
  10. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  11. #include <LibWeb/HTML/BrowsingContext.h>
  12. #include <LibWeb/HTML/BrowsingContextContainer.h>
  13. #include <LibWeb/HTML/BrowsingContextGroup.h>
  14. #include <LibWeb/HTML/CrossOrigin/CrossOriginOpenerPolicy.h>
  15. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  16. #include <LibWeb/HTML/HTMLAnchorElement.h>
  17. #include <LibWeb/HTML/HTMLInputElement.h>
  18. #include <LibWeb/HTML/SandboxingFlagSet.h>
  19. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  20. #include <LibWeb/HTML/Window.h>
  21. #include <LibWeb/HTML/WindowProxy.h>
  22. #include <LibWeb/HighResolutionTime/TimeOrigin.h>
  23. #include <LibWeb/Layout/BreakNode.h>
  24. #include <LibWeb/Layout/InitialContainingBlock.h>
  25. #include <LibWeb/Layout/TextNode.h>
  26. #include <LibWeb/Page/Page.h>
  27. namespace Web::HTML {
  28. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#matches-about:blank
  29. static bool url_matches_about_blank(AK::URL const& url)
  30. {
  31. // A URL matches about:blank if its scheme is "about", its path contains a single string "blank", its username and password are the empty string, and its host is null.
  32. return url.scheme() == "about"sv
  33. && url.path() == "blank"sv
  34. && url.username().is_empty()
  35. && url.password().is_empty()
  36. && url.host().is_null();
  37. }
  38. // https://url.spec.whatwg.org/#concept-url-origin
  39. static HTML::Origin url_origin(AK::URL const& url)
  40. {
  41. // FIXME: Move this whole function somewhere better.
  42. if (url.scheme() == "blob"sv) {
  43. // FIXME: Implement
  44. return HTML::Origin {};
  45. }
  46. if (url.scheme().is_one_of("ftp"sv, "http"sv, "https"sv, "ws"sv, "wss"sv)) {
  47. // Return the tuple origin (url’s scheme, url’s host, url’s port, null).
  48. return HTML::Origin(url.scheme(), url.host(), url.port().value_or(0));
  49. }
  50. if (url.scheme() == "file"sv) {
  51. // Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin.
  52. // Note: We must return an origin with the `file://' protocol for `file://' iframes to work from `file://' pages.
  53. return HTML::Origin(url.scheme(), String(), 0);
  54. }
  55. return HTML::Origin {};
  56. }
  57. // https://html.spec.whatwg.org/multipage/browsers.html#determining-the-origin
  58. HTML::Origin determine_the_origin(BrowsingContext const& browsing_context, Optional<AK::URL> url, SandboxingFlagSet sandbox_flags, Optional<HTML::Origin> invocation_origin)
  59. {
  60. // 1. If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin.
  61. if (sandbox_flags.flags & SandboxingFlagSet::SandboxedOrigin) {
  62. return HTML::Origin {};
  63. }
  64. // 2. If url is null, then return a new opaque origin.
  65. if (!url.has_value()) {
  66. return HTML::Origin {};
  67. }
  68. // 3. If invocationOrigin is non-null and url matches about:blank, then return invocationOrigin.
  69. if (invocation_origin.has_value() && url_matches_about_blank(*url)) {
  70. return invocation_origin.value();
  71. }
  72. // 4. If url is about:srcdoc, then return the origin of browsingContext's container document.
  73. if (url == AK::URL("about:srcdoc")) {
  74. VERIFY(browsing_context.container_document());
  75. return browsing_context.container_document()->origin();
  76. }
  77. // 5. Return url's origin.
  78. return url_origin(*url);
  79. }
  80. // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-top-level-browsing-context
  81. NonnullRefPtr<BrowsingContext> BrowsingContext::create_a_new_top_level_browsing_context(Web::Page& page)
  82. {
  83. // 1. Let group be the result of creating a new browsing context group.
  84. auto group = BrowsingContextGroup::create_a_new_browsing_context_group(page);
  85. // 2. Return group's browsing context set[0].
  86. return *group->browsing_context_set().begin();
  87. }
  88. // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-browsing-context
  89. NonnullRefPtr<BrowsingContext> BrowsingContext::create_a_new_browsing_context(Page& page, JS::GCPtr<DOM::Document> creator, JS::GCPtr<DOM::Element> embedder, BrowsingContextGroup&)
  90. {
  91. // 1. Let browsingContext be a new browsing context.
  92. BrowsingContextContainer* container = (embedder && is<BrowsingContextContainer>(*embedder)) ? static_cast<BrowsingContextContainer*>(embedder.ptr()) : nullptr;
  93. auto browsing_context = adopt_ref(*new BrowsingContext(page, container));
  94. // 2. Let unsafeContextCreationTime be the unsafe shared current time.
  95. [[maybe_unused]] auto unsafe_context_creation_time = HighResolutionTime::unsafe_shared_current_time();
  96. // 3. If creator is non-null, then set browsingContext's creator origin to return creator's origin,
  97. // browsingContext's creator URL to return creator's URL,
  98. // browsingContext's creator base URL to return creator's base URL,
  99. // FIXME: and browsingContext's virtual browsing context group ID to creator's top-level browsing context's virtual browsing context group ID.
  100. if (creator) {
  101. browsing_context->m_creator_origin = creator->origin();
  102. browsing_context->m_creator_url = creator->url();
  103. browsing_context->m_creator_base_url = creator->base_url();
  104. }
  105. // FIXME: 4. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedded.
  106. SandboxingFlagSet sandbox_flags;
  107. // 5. Let origin be the result of determining the origin given browsingContext, about:blank, sandboxFlags, and browsingContext's creator origin.
  108. auto origin = determine_the_origin(browsing_context, AK::URL("about:blank"), sandbox_flags, browsing_context->m_creator_origin);
  109. // FIXME: 6. Let permissionsPolicy be the result of creating a permissions policy given browsingContext and origin. [PERMISSIONSPOLICY]
  110. // FIXME: 7. Let agent be the result of obtaining a similar-origin window agent given origin, group, and false.
  111. JS::GCPtr<Window> window;
  112. // 8. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  113. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  114. Bindings::main_thread_vm(),
  115. [&](JS::Realm& realm) -> JS::Object* {
  116. browsing_context->m_window_proxy = realm.heap().allocate<WindowProxy>(realm, realm);
  117. // - For the global object, create a new Window object.
  118. window = HTML::Window::create(realm);
  119. return window.ptr();
  120. },
  121. [&](JS::Realm&) -> JS::Object* {
  122. // - For the global this binding, use browsingContext's WindowProxy object.
  123. return browsing_context->m_window_proxy;
  124. });
  125. // 9. Let topLevelCreationURL be about:blank if embedder is null; otherwise embedder's relevant settings object's top-level creation URL.
  126. auto top_level_creation_url = !embedder ? AK::URL("about:blank") : relevant_settings_object(*embedder).top_level_creation_url;
  127. // 10. Let topLevelOrigin be origin if embedder is null; otherwise embedder's relevant settings object's top-level origin.
  128. auto top_level_origin = !embedder ? origin : relevant_settings_object(*embedder).origin();
  129. // 11. Set up a window environment settings object with about:blank, realm execution context, null, topLevelCreationURL, and topLevelOrigin.
  130. HTML::WindowEnvironmentSettingsObject::setup(
  131. AK::URL("about:blank"),
  132. move(realm_execution_context),
  133. {},
  134. top_level_creation_url,
  135. top_level_origin);
  136. // 12. Let loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling
  137. // coarsen time with unsafeContextCreationTime and the new environment settings object's cross-origin isolated capability.
  138. auto load_timing_info = DOM::DocumentLoadTimingInfo();
  139. load_timing_info.navigation_start_time = HighResolutionTime::coarsen_time(
  140. unsafe_context_creation_time,
  141. verify_cast<WindowEnvironmentSettingsObject>(Bindings::host_defined_environment_settings_object(window->realm())).cross_origin_isolated_capability() == CanUseCrossOriginIsolatedAPIs::Yes);
  142. // 13. Let coop be a new cross-origin opener policy.
  143. auto coop = CrossOriginOpenerPolicy {};
  144. // 14. If creator is non-null and creator's origin is same origin with creator's relevant settings object's top-level origin,
  145. // then set coop to creator's browsing context's top-level browsing context's active document's cross-origin opener policy.
  146. if (creator && creator->origin().is_same_origin(relevant_settings_object(*creator).top_level_origin)) {
  147. VERIFY(creator->browsing_context());
  148. auto* top_level_document = creator->browsing_context()->top_level_browsing_context().active_document();
  149. VERIFY(top_level_document);
  150. coop = top_level_document->cross_origin_opener_policy();
  151. }
  152. // 15. Let document be a new Document, marked as an HTML document in quirks mode,
  153. // whose content type is "text/html",
  154. // origin is origin,
  155. // FIXME: active sandboxing flag set is sandboxFlags,
  156. // FIXME: permissions policy is permissionsPolicy,
  157. // cross-origin opener policy is coop,
  158. // load timing info is loadTimingInfo,
  159. // FIXME: navigation id is null,
  160. // and which is ready for post-load tasks.
  161. auto document = DOM::Document::create(window->realm());
  162. // Non-standard
  163. document->set_window({}, *window);
  164. window->set_associated_document(*document);
  165. document->set_quirks_mode(DOM::QuirksMode::Yes);
  166. document->set_content_type("text/html");
  167. document->set_origin(origin);
  168. document->set_url(AK::URL("about:blank"));
  169. document->set_cross_origin_opener_policy(coop);
  170. document->set_load_timing_info(load_timing_info);
  171. document->set_ready_for_post_load_tasks(true);
  172. // FIXME: 16. Assert: document's URL and document's relevant settings object's creation URL are about:blank.
  173. // 17. Set document's is initial about:blank to true.
  174. document->set_is_initial_about_blank(true);
  175. // 18. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element.
  176. auto html_node = document->create_element(HTML::TagNames::html).release_value();
  177. html_node->append_child(document->create_element(HTML::TagNames::head).release_value());
  178. html_node->append_child(document->create_element(HTML::TagNames::body).release_value());
  179. document->append_child(html_node);
  180. // 19. Set the active document of browsingContext to document.
  181. browsing_context->set_active_document(*document);
  182. // 20. If browsingContext's creator URL is non-null, then set document's referrer to the serialization of it.
  183. if (browsing_context->m_creator_url.has_value()) {
  184. document->set_referrer(browsing_context->m_creator_url->serialize());
  185. }
  186. // FIXME: 21. If creator is non-null, then set document's policy container to a clone of creator's policy container.
  187. // 22. Append a new session history entry to browsingContext's session history whose URL is about:blank and document is document.
  188. browsing_context->m_session_history.append(HTML::SessionHistoryEntry {
  189. .url = AK::URL("about:blank"),
  190. .document = document.ptr(),
  191. .serialized_state = {},
  192. .policy_container = {},
  193. .scroll_restoration_mode = {},
  194. .browsing_context_name = {},
  195. .original_source_browsing_context = {},
  196. });
  197. // 23. Completely finish loading document.
  198. document->completely_finish_loading();
  199. // 24. Return browsingContext.
  200. return browsing_context;
  201. }
  202. BrowsingContext::BrowsingContext(Page& page, HTML::BrowsingContextContainer* container)
  203. : m_page(page)
  204. , m_loader(*this)
  205. , m_event_handler({}, *this)
  206. , m_container(container)
  207. {
  208. m_cursor_blink_timer = Platform::Timer::create_repeating(500, [this] {
  209. if (!is_focused_context())
  210. return;
  211. if (m_cursor_position.node() && m_cursor_position.node()->layout_node()) {
  212. m_cursor_blink_state = !m_cursor_blink_state;
  213. m_cursor_position.node()->layout_node()->set_needs_display();
  214. }
  215. });
  216. }
  217. BrowsingContext::~BrowsingContext() = default;
  218. void BrowsingContext::did_edit(Badge<EditEventHandler>)
  219. {
  220. reset_cursor_blink_cycle();
  221. if (m_cursor_position.node() && is<DOM::Text>(*m_cursor_position.node())) {
  222. auto& text_node = static_cast<DOM::Text&>(*m_cursor_position.node());
  223. if (auto* input_element = text_node.owner_input_element())
  224. input_element->did_edit_text_node({});
  225. }
  226. }
  227. void BrowsingContext::reset_cursor_blink_cycle()
  228. {
  229. m_cursor_blink_state = true;
  230. m_cursor_blink_timer->restart();
  231. if (m_cursor_position.is_valid() && m_cursor_position.node()->layout_node())
  232. m_cursor_position.node()->layout_node()->set_needs_display();
  233. }
  234. // https://html.spec.whatwg.org/multipage/browsers.html#top-level-browsing-context
  235. bool BrowsingContext::is_top_level() const
  236. {
  237. // A browsing context that has no parent browsing context is the top-level browsing context for itself and all of the browsing contexts for which it is an ancestor browsing context.
  238. return !parent();
  239. }
  240. bool BrowsingContext::is_focused_context() const
  241. {
  242. return m_page && &m_page->focused_context() == this;
  243. }
  244. // https://html.spec.whatwg.org/multipage/browsers.html#set-the-active-document
  245. void BrowsingContext::set_active_document(JS::NonnullGCPtr<DOM::Document> document)
  246. {
  247. auto previously_active_document = active_document();
  248. // 1. Let window be document's relevant global object.
  249. auto& window = verify_cast<HTML::Window>(relevant_global_object(document));
  250. // 2. Set document's visibility state to browsingContext's top-level browsing context's system visibility state.
  251. document->set_visibility_state({}, top_level_browsing_context().system_visibility_state());
  252. // 3. Set browsingContext's active window to window.
  253. m_window_proxy->set_window({}, window);
  254. // 4. Set window's associated Document to document.
  255. window.set_associated_document(document);
  256. // 5. Set window's relevant settings object's execution ready flag.
  257. relevant_settings_object(window).execution_ready = true;
  258. // AD-HOC:
  259. document->set_browsing_context(this);
  260. if (m_page && is_top_level())
  261. m_page->client().page_did_change_title(document->title());
  262. if (previously_active_document && previously_active_document != document.ptr())
  263. previously_active_document->did_stop_being_active_document_in_browsing_context({});
  264. }
  265. void BrowsingContext::set_viewport_rect(Gfx::IntRect const& rect)
  266. {
  267. bool did_change = false;
  268. if (m_size != rect.size()) {
  269. m_size = rect.size();
  270. if (auto* document = active_document()) {
  271. // NOTE: Resizing the viewport changes the reference value for viewport-relative CSS lengths.
  272. document->invalidate_style();
  273. document->invalidate_layout();
  274. }
  275. did_change = true;
  276. }
  277. if (m_viewport_scroll_offset != rect.location()) {
  278. m_viewport_scroll_offset = rect.location();
  279. scroll_offset_did_change();
  280. did_change = true;
  281. }
  282. if (did_change) {
  283. for (auto* client : m_viewport_clients)
  284. client->browsing_context_did_set_viewport_rect(rect);
  285. }
  286. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  287. HTML::main_thread_event_loop().schedule();
  288. }
  289. void BrowsingContext::set_size(Gfx::IntSize const& size)
  290. {
  291. if (m_size == size)
  292. return;
  293. m_size = size;
  294. if (auto* document = active_document()) {
  295. document->invalidate_style();
  296. document->invalidate_layout();
  297. }
  298. for (auto* client : m_viewport_clients)
  299. client->browsing_context_did_set_viewport_rect(viewport_rect());
  300. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  301. HTML::main_thread_event_loop().schedule();
  302. }
  303. void BrowsingContext::set_needs_display()
  304. {
  305. set_needs_display(viewport_rect());
  306. }
  307. void BrowsingContext::set_needs_display(Gfx::IntRect const& rect)
  308. {
  309. if (!viewport_rect().intersects(rect))
  310. return;
  311. if (is_top_level()) {
  312. if (m_page)
  313. m_page->client().page_did_invalidate(to_top_level_rect(rect));
  314. return;
  315. }
  316. if (container() && container()->layout_node())
  317. container()->layout_node()->set_needs_display();
  318. }
  319. void BrowsingContext::scroll_to(Gfx::IntPoint const& position)
  320. {
  321. if (active_document())
  322. active_document()->force_layout();
  323. if (m_page)
  324. m_page->client().page_did_request_scroll_to(position);
  325. }
  326. void BrowsingContext::scroll_to_anchor(String const& fragment)
  327. {
  328. JS::GCPtr<DOM::Document> document = active_document();
  329. if (!document)
  330. return;
  331. auto element = document->get_element_by_id(fragment);
  332. if (!element) {
  333. auto candidates = document->get_elements_by_name(fragment);
  334. for (auto& candidate : candidates->collect_matching_elements()) {
  335. if (is<HTML::HTMLAnchorElement>(*candidate)) {
  336. element = &verify_cast<HTML::HTMLAnchorElement>(*candidate);
  337. break;
  338. }
  339. }
  340. }
  341. if (!element)
  342. return;
  343. document->force_layout();
  344. if (!element->layout_node())
  345. return;
  346. auto& layout_node = *element->layout_node();
  347. Gfx::FloatRect float_rect { layout_node.box_type_agnostic_position(), { (float)viewport_rect().width(), (float)viewport_rect().height() } };
  348. if (is<Layout::Box>(layout_node)) {
  349. auto& layout_box = verify_cast<Layout::Box>(layout_node);
  350. auto padding_box = layout_box.box_model().padding_box();
  351. float_rect.translate_by(-padding_box.left, -padding_box.top);
  352. }
  353. if (m_page)
  354. m_page->client().page_did_request_scroll_into_view(enclosing_int_rect(float_rect));
  355. }
  356. Gfx::IntRect BrowsingContext::to_top_level_rect(Gfx::IntRect const& a_rect)
  357. {
  358. auto rect = a_rect;
  359. rect.set_location(to_top_level_position(a_rect.location()));
  360. return rect;
  361. }
  362. Gfx::IntPoint BrowsingContext::to_top_level_position(Gfx::IntPoint const& a_position)
  363. {
  364. auto position = a_position;
  365. for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  366. if (ancestor->is_top_level())
  367. break;
  368. if (!ancestor->container())
  369. return {};
  370. if (!ancestor->container()->layout_node())
  371. return {};
  372. position.translate_by(ancestor->container()->layout_node()->box_type_agnostic_position().to_type<int>());
  373. }
  374. return position;
  375. }
  376. void BrowsingContext::set_cursor_position(DOM::Position position)
  377. {
  378. if (m_cursor_position == position)
  379. return;
  380. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  381. m_cursor_position.node()->layout_node()->set_needs_display();
  382. m_cursor_position = move(position);
  383. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  384. m_cursor_position.node()->layout_node()->set_needs_display();
  385. reset_cursor_blink_cycle();
  386. }
  387. String BrowsingContext::selected_text() const
  388. {
  389. StringBuilder builder;
  390. if (!active_document())
  391. return {};
  392. auto* layout_root = active_document()->layout_node();
  393. if (!layout_root)
  394. return {};
  395. if (!layout_root->selection().is_valid())
  396. return {};
  397. auto selection = layout_root->selection().normalized();
  398. if (selection.start().layout_node == selection.end().layout_node) {
  399. if (!is<Layout::TextNode>(*selection.start().layout_node))
  400. return "";
  401. return verify_cast<Layout::TextNode>(*selection.start().layout_node).text_for_rendering().substring(selection.start().index_in_node, selection.end().index_in_node - selection.start().index_in_node);
  402. }
  403. // Start node
  404. auto layout_node = selection.start().layout_node;
  405. if (is<Layout::TextNode>(*layout_node)) {
  406. auto& text = verify_cast<Layout::TextNode>(*layout_node).text_for_rendering();
  407. builder.append(text.substring(selection.start().index_in_node, text.length() - selection.start().index_in_node));
  408. }
  409. // Middle nodes
  410. layout_node = layout_node->next_in_pre_order();
  411. while (layout_node && layout_node != selection.end().layout_node) {
  412. if (is<Layout::TextNode>(*layout_node))
  413. builder.append(verify_cast<Layout::TextNode>(*layout_node).text_for_rendering());
  414. else if (is<Layout::BreakNode>(*layout_node) || is<Layout::BlockContainer>(*layout_node))
  415. builder.append('\n');
  416. layout_node = layout_node->next_in_pre_order();
  417. }
  418. // End node
  419. VERIFY(layout_node == selection.end().layout_node);
  420. if (is<Layout::TextNode>(*layout_node)) {
  421. auto& text = verify_cast<Layout::TextNode>(*layout_node).text_for_rendering();
  422. builder.append(text.substring(0, selection.end().index_in_node));
  423. }
  424. return builder.to_string();
  425. }
  426. void BrowsingContext::select_all()
  427. {
  428. if (!active_document())
  429. return;
  430. auto* layout_root = active_document()->layout_node();
  431. if (!layout_root)
  432. return;
  433. Layout::Node const* first_layout_node = layout_root;
  434. for (;;) {
  435. auto* next = first_layout_node->next_in_pre_order();
  436. if (!next)
  437. break;
  438. first_layout_node = next;
  439. if (is<Layout::TextNode>(*first_layout_node))
  440. break;
  441. }
  442. Layout::Node const* last_layout_node = first_layout_node;
  443. for (Layout::Node const* layout_node = first_layout_node; layout_node; layout_node = layout_node->next_in_pre_order()) {
  444. if (is<Layout::TextNode>(*layout_node))
  445. last_layout_node = layout_node;
  446. }
  447. VERIFY(first_layout_node);
  448. VERIFY(last_layout_node);
  449. int last_layout_node_index_in_node = 0;
  450. if (is<Layout::TextNode>(*last_layout_node)) {
  451. auto const& text_for_rendering = verify_cast<Layout::TextNode>(*last_layout_node).text_for_rendering();
  452. if (!text_for_rendering.is_empty())
  453. last_layout_node_index_in_node = text_for_rendering.length() - 1;
  454. }
  455. layout_root->set_selection({ { first_layout_node, 0 }, { last_layout_node, last_layout_node_index_in_node } });
  456. }
  457. void BrowsingContext::register_viewport_client(ViewportClient& client)
  458. {
  459. auto result = m_viewport_clients.set(&client);
  460. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  461. }
  462. void BrowsingContext::unregister_viewport_client(ViewportClient& client)
  463. {
  464. bool was_removed = m_viewport_clients.remove(&client);
  465. VERIFY(was_removed);
  466. }
  467. void BrowsingContext::register_frame_nesting(AK::URL const& url)
  468. {
  469. m_frame_nesting_levels.ensure(url)++;
  470. }
  471. bool BrowsingContext::is_frame_nesting_allowed(AK::URL const& url) const
  472. {
  473. return m_frame_nesting_levels.get(url).value_or(0) < 3;
  474. }
  475. bool BrowsingContext::increment_cursor_position_offset()
  476. {
  477. if (!m_cursor_position.increment_offset())
  478. return false;
  479. reset_cursor_blink_cycle();
  480. return true;
  481. }
  482. bool BrowsingContext::decrement_cursor_position_offset()
  483. {
  484. if (!m_cursor_position.decrement_offset())
  485. return false;
  486. reset_cursor_blink_cycle();
  487. return true;
  488. }
  489. DOM::Document* BrowsingContext::container_document()
  490. {
  491. if (auto* container = this->container())
  492. return &container->document();
  493. return nullptr;
  494. }
  495. DOM::Document const* BrowsingContext::container_document() const
  496. {
  497. if (auto* container = this->container())
  498. return &container->document();
  499. return nullptr;
  500. }
  501. // https://html.spec.whatwg.org/#rendering-opportunity
  502. bool BrowsingContext::has_a_rendering_opportunity() const
  503. {
  504. // A browsing context has a rendering opportunity if the user agent is currently able to present the contents of the browsing context to the user,
  505. // accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.
  506. // FIXME: We should at the very least say `false` here if we're an inactive browser tab.
  507. return true;
  508. }
  509. // https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-browsing-context
  510. JS::GCPtr<DOM::Node> BrowsingContext::currently_focused_area()
  511. {
  512. // 1. If topLevelBC does not have system focus, then return null.
  513. if (!is_focused_context())
  514. return nullptr;
  515. // 2. Let candidate be topLevelBC's active document.
  516. auto* candidate = active_document();
  517. // 3. While candidate's focused area is a browsing context container with a non-null nested browsing context:
  518. // set candidate to the active document of that browsing context container's nested browsing context.
  519. while (candidate->focused_element()
  520. && is<HTML::BrowsingContextContainer>(candidate->focused_element())
  521. && static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()) {
  522. candidate = static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document();
  523. }
  524. // 4. If candidate's focused area is non-null, set candidate to candidate's focused area.
  525. if (candidate->focused_element()) {
  526. // NOTE: We return right away here instead of assigning to candidate,
  527. // since that would require compromising type safety.
  528. return candidate->focused_element();
  529. }
  530. // 5. Return candidate.
  531. return candidate;
  532. }
  533. BrowsingContext* BrowsingContext::choose_a_browsing_context(StringView name, bool)
  534. {
  535. // The rules for choosing a browsing context, given a browsing context name
  536. // name, a browsing context current, and a boolean noopener are as follows:
  537. // 1. Let chosen be null.
  538. BrowsingContext* chosen = nullptr;
  539. // FIXME: 2. Let windowType be "existing or none".
  540. // FIXME: 3. Let sandboxingFlagSet be current's active document's active
  541. // sandboxing flag set.
  542. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to current.
  543. if (name.is_empty() || name.equals_ignoring_case("_self"sv))
  544. chosen = this;
  545. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent",
  546. // set chosen to current's parent browsing context, if any, and current
  547. // otherwise.
  548. if (name.equals_ignoring_case("_parent"sv)) {
  549. if (auto* parent = this->parent())
  550. chosen = parent;
  551. else
  552. chosen = this;
  553. }
  554. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top", set
  555. // chosen to current's top-level browsing context, if any, and current
  556. // otherwise.
  557. if (name.equals_ignoring_case("_top"sv)) {
  558. chosen = &top_level_browsing_context();
  559. }
  560. // FIXME: 7. Otherwise, if name is not an ASCII case-insensitive match for
  561. // "_blank", there exists a browsing context whose name is the same as name,
  562. // current is familiar with that browsing context, and the user agent
  563. // determines that the two browsing contexts are related enough that it is
  564. // ok if they reach each other, set chosen to that browsing context. If
  565. // there are multiple matching browsing contexts, the user agent should set
  566. // chosen to one in some arbitrary consistent manner, such as the most
  567. // recently opened, most recently focused, or more closely related.
  568. if (!name.equals_ignoring_case("_blank"sv)) {
  569. chosen = this;
  570. } else {
  571. // 8. Otherwise, a new browsing context is being requested, and what
  572. // happens depends on the user agent's configuration and abilities — it
  573. // is determined by the rules given for the first applicable option from
  574. // the following list:
  575. dbgln("FIXME: Create a new browsing context!");
  576. // --> If current's active window does not have transient activation and
  577. // the user agent has been configured to not show popups (i.e., the
  578. // user agent has a "popup blocker" enabled)
  579. //
  580. // The user agent may inform the user that a popup has been blocked.
  581. // --> If sandboxingFlagSet has the sandboxed auxiliary navigation
  582. // browsing context flag set
  583. //
  584. // The user agent may report to a developer console that a popup has
  585. // been blocked.
  586. // --> If the user agent has been configured such that in this instance
  587. // it will create a new browsing context
  588. //
  589. // 1. Set windowType to "new and unrestricted".
  590. // 2. If current's top-level browsing context's active document's
  591. // cross-origin opener policy's value is "same-origin" or
  592. // "same-origin-plus-COEP", then:
  593. // 2.1. Let currentDocument be current's active document.
  594. // 2.2. If currentDocument's origin is not same origin with
  595. // currentDocument's relevant settings object's top-level
  596. // origin, then set noopener to true, name to "_blank", and
  597. // windowType to "new with no opener".
  598. // 3. If noopener is true, then set chosen to the result of creating
  599. // a new top-level browsing context.
  600. // 4. Otherwise:
  601. // 4.1. Set chosen to the result of creating a new auxiliary
  602. // browsing context with current.
  603. // 4.2. If sandboxingFlagSet's sandboxed navigation browsing
  604. // context flag is set, then current must be set as chosen's one
  605. // permitted sandboxed navigator.
  606. // 5. If sandboxingFlagSet's sandbox propagates to auxiliary
  607. // browsing contexts flag is set, then all the flags that are set in
  608. // sandboxingFlagSet must be set in chosen's popup sandboxing flag
  609. // set.
  610. // 6. If name is not an ASCII case-insensitive match for "_blank",
  611. // then set chosen's name to name.
  612. // --> If the user agent has been configured such that in this instance
  613. // it will reuse current
  614. //
  615. // Set chosen to current.
  616. // --> If the user agent has been configured such that in this instance
  617. // it will not find a browsing context
  618. //
  619. // Do nothing.
  620. }
  621. // 9. Return chosen and windowType.
  622. return chosen;
  623. }
  624. // https://html.spec.whatwg.org/multipage/browsers.html#document-tree-child-browsing-context
  625. size_t BrowsingContext::document_tree_child_browsing_context_count() const
  626. {
  627. size_t count = 0;
  628. // A browsing context child is a document-tree child browsing context of parent if child is a child browsing context and child's container is in a document tree.
  629. for_each_child([this, &count](BrowsingContext const& child) {
  630. if (child.is_child_of(*this) && child.container()->in_a_document_tree())
  631. ++count;
  632. });
  633. return count;
  634. }
  635. // https://html.spec.whatwg.org/multipage/browsers.html#child-browsing-context
  636. bool BrowsingContext::is_child_of(BrowsingContext const& parent) const
  637. {
  638. // A browsing context child is said to be a child browsing context of another browsing context parent,
  639. // if child's container document is non-null and child's container document's browsing context is parent.
  640. return container_document() && container_document()->browsing_context() == &parent;
  641. }
  642. // https://html.spec.whatwg.org/multipage/dom.html#still-on-its-initial-about:blank-document
  643. bool BrowsingContext::still_on_its_initial_about_blank_document() const
  644. {
  645. // A browsing context browsingContext is still on its initial about:blank Document
  646. // if browsingContext's session history's size is 1
  647. // and browsingContext's session history[0]'s document's is initial about:blank is true.
  648. return m_session_history.size() == 1
  649. && m_session_history[0].document
  650. && m_session_history[0].document->is_initial_about_blank();
  651. }
  652. DOM::Document const* BrowsingContext::active_document() const
  653. {
  654. auto* window = active_window();
  655. if (!window)
  656. return nullptr;
  657. return &window->associated_document();
  658. }
  659. DOM::Document* BrowsingContext::active_document()
  660. {
  661. auto* window = active_window();
  662. if (!window)
  663. return nullptr;
  664. return &window->associated_document();
  665. }
  666. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  667. HTML::Window* BrowsingContext::active_window()
  668. {
  669. return m_window_proxy->window();
  670. }
  671. // https://html.spec.whatwg.org/multipage/browsers.html#active-window
  672. HTML::Window const* BrowsingContext::active_window() const
  673. {
  674. return m_window_proxy->window();
  675. }
  676. HTML::WindowProxy* BrowsingContext::window_proxy()
  677. {
  678. return m_window_proxy.ptr();
  679. }
  680. HTML::WindowProxy const* BrowsingContext::window_proxy() const
  681. {
  682. return m_window_proxy.ptr();
  683. }
  684. void BrowsingContext::scroll_offset_did_change()
  685. {
  686. // https://w3c.github.io/csswg-drafts/cssom-view-1/#scrolling-events
  687. // Whenever a viewport gets scrolled (whether in response to user interaction or by an API), the user agent must run these steps:
  688. // 1. Let doc be the viewport’s associated Document.
  689. auto* doc = active_document();
  690. VERIFY(doc);
  691. // 2. If doc is already in doc’s pending scroll event targets, abort these steps.
  692. for (auto& target : doc->pending_scroll_event_targets()) {
  693. if (target.ptr() == doc)
  694. return;
  695. }
  696. // 3. Append doc to doc’s pending scroll event targets.
  697. doc->pending_scroll_event_targets().append(*doc);
  698. }
  699. BrowsingContextGroup* BrowsingContext::group()
  700. {
  701. return m_group;
  702. }
  703. void BrowsingContext::set_group(BrowsingContextGroup* group)
  704. {
  705. m_group = group;
  706. }
  707. // https://html.spec.whatwg.org/multipage/browsers.html#bcg-remove
  708. void BrowsingContext::remove()
  709. {
  710. // 1. Assert: browsingContext's group is non-null, because a browsing context only gets discarded once.
  711. VERIFY(group());
  712. // 2. Let group be browsingContext's group.
  713. NonnullRefPtr<BrowsingContextGroup> group = *this->group();
  714. // 3. Set browsingContext's group to null.
  715. set_group(nullptr);
  716. // 4. Remove browsingContext from group's browsing context set.
  717. group->browsing_context_set().remove(*this);
  718. // 5. If group's browsing context set is empty, then remove group from the user agent's browsing context group set.
  719. // NOTE: This is done by ~BrowsingContextGroup() when the refcount reaches 0.
  720. }
  721. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate
  722. WebIDL::ExceptionOr<void> BrowsingContext::navigate(
  723. NonnullRefPtr<Fetch::Infrastructure::Request> resource,
  724. BrowsingContext& source_browsing_context,
  725. bool exceptions_enabled,
  726. HistoryHandlingBehavior history_handling,
  727. Optional<PolicyContainer> history_policy_container,
  728. String navigation_type,
  729. Optional<String> navigation_id,
  730. Function<void(NonnullRefPtr<Fetch::Infrastructure::Response>)> process_response_end_of_body)
  731. {
  732. // 1. If resource is a URL, then set resource to a new request whose URL is resource.
  733. // NOTE: This function only accepts resources that are already a request, so this is irrelevant.
  734. // 2. If resource is a request and historyHandling is "reload", then set resource's reload-navigation flag.
  735. if (history_handling == HistoryHandlingBehavior::Reload)
  736. resource->set_reload_navigation(true);
  737. // 3. If the source browsing context is not allowed to navigate browsingContext, then:
  738. if (!source_browsing_context.is_allowed_to_navigate(*this)) {
  739. // 1. If exceptionsEnabled is given and is true, then throw a "SecurityError" DOMException.
  740. if (exceptions_enabled) {
  741. VERIFY(source_browsing_context.active_document());
  742. return WebIDL::SecurityError::create(source_browsing_context.active_document()->realm(), "Source browsing context not allowed to navigate"sv);
  743. }
  744. // FIXME: 2. Otherwise, the user agent may instead offer to open resource in a new top-level browsing context
  745. // or in the top-level browsing context of the source browsing context, at the user's option,
  746. // in which case the user agent must navigate that designated top-level browsing context
  747. // to resource as if the user had requested it independently.
  748. }
  749. // 4. If navigationId is null:
  750. if (!navigation_id.has_value()) {
  751. // 1. If historyHandling is "reload", and browsingContext's active document's navigation id is not null,
  752. if (history_handling == HistoryHandlingBehavior::Reload && active_document()->navigation_id().has_value()) {
  753. // let navigationId be browsingContext's active document's navigation id.
  754. navigation_id = active_document()->navigation_id();
  755. } else {
  756. // Otherwise let navigation id be the result of generating a random UUID. [UUID]
  757. // FIXME: Generate a UUID.
  758. navigation_id = "FIXME";
  759. }
  760. }
  761. // FIXME: 5. If browsingContext's active document's unload counter is greater than 0,
  762. // then invoke WebDriver BiDi navigation failed
  763. // with a WebDriver BiDi navigation status whose id is navigationId, status is "canceled", and url is resource's url
  764. // and return.
  765. // 6. If historyHandling is "default", and any of the following are true:
  766. // - browsingContext is still on its initial about:blank Document
  767. // - resource is a request whose URL equals browsingContext's active document's URL
  768. // - resource is a request whose URL's scheme is "javascript"
  769. if (history_handling == HistoryHandlingBehavior::Default
  770. && (still_on_its_initial_about_blank_document()
  771. || resource->url().equals(active_document()->url())
  772. || resource->url().scheme() == "javascript"sv)) {
  773. // then set historyHandling to "replace".
  774. history_handling = HistoryHandlingBehavior::Replace;
  775. }
  776. // 7. If historyHandling is not "reload", resource is a request,
  777. // resource's URL equals browsingContext's active document's URL with exclude fragments set to true,
  778. // and resource's URL's fragment is non-null, then:
  779. if (history_handling != HistoryHandlingBehavior::Reload
  780. && resource->url().equals(active_document()->url(), AK::URL::ExcludeFragment::Yes)
  781. && !resource->url().fragment().is_null()) {
  782. // 1. Navigate to a fragment given browsingContext, resource's URL, historyHandling, and navigationId.
  783. navigate_to_a_fragment(resource->url(), history_handling, *navigation_id);
  784. // 2. Return.
  785. return {};
  786. }
  787. // FIXME: 8. Let incumbentNavigationOrigin be the origin of the incumbent settings object,
  788. // or if no script was involved, the origin of the node document of the element that initiated the navigation.
  789. // FIXME: 9. Let initiatorPolicyContainer be a clone of the source browsing context's active document's policy container.
  790. // FIXME: 10. If resource is a request, then set resource's policy container to initiatorPolicyContainer.
  791. // FIXME: 11. Cancel any preexisting but not yet mature attempt to navigate browsingContext,
  792. // including canceling any instances of the fetch algorithm started by those attempts.
  793. // If one of those attempts has already created and initialized a new Document object,
  794. // abort that Document also.
  795. // (Navigation attempts that have matured already have session history entries,
  796. // and are therefore handled during the update the session history with the new page algorithm, later.)
  797. // FIXME: 12. Let unloadPromptResult be the result of calling prompt to unload with the active document of browsingContext.
  798. // If this instance of the navigation algorithm gets canceled while this step is running,
  799. // the prompt to unload algorithm must nonetheless be run to completion.
  800. // FIXME: 13. If unloadPromptResult is "refuse", then return a new WebDriver BiDi navigation status whose id is navigationId and status is "canceled".
  801. // 14. Abort the active document of browsingContext.
  802. active_document()->abort();
  803. // FIXME: 15. If browsingContext is a child browsing context, then put it in the delaying load events mode.
  804. // The user agent must take this child browsing context out of the delaying load events mode when this navigation algorithm later matures,
  805. // or when it terminates (whether due to having run all the steps, or being canceled, or being aborted),
  806. // whichever happens first.
  807. // FIXME: 16. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and browsingContext's container.
  808. // FIXME: 17. Let allowedToDownload be the result of running the allowed to download algorithm given the source browsing context and browsingContext.
  809. // 18. Let hasTransientActivation be true if the source browsing context's active window has transient activation; otherwise false.
  810. [[maybe_unused]] bool has_transient_activation = source_browsing_context.active_window()->has_transient_activation();
  811. // FIXME: 19. Invoke WebDriver BiDi navigation started with browsingContext, and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "pending".
  812. // 20. Return, and continue running these steps in parallel.
  813. // FIXME: Implement the rest of this algorithm
  814. (void)history_policy_container;
  815. (void)navigation_type;
  816. (void)process_response_end_of_body;
  817. // AD-HOC:
  818. loader().load(resource->url(), FrameLoader::Type::IFrame);
  819. return {};
  820. }
  821. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#navigate-fragid
  822. WebIDL::ExceptionOr<void> BrowsingContext::navigate_to_a_fragment(AK::URL const& url, HistoryHandlingBehavior history_handling, String navigation_id)
  823. {
  824. // 1. If historyHandling is not "replace",
  825. if (history_handling != HistoryHandlingBehavior::Replace) {
  826. // FIXME: then remove all the entries in browsingContext's session history after the current entry.
  827. // (If the current entry is the last entry in the session history, then no entries are removed.)
  828. }
  829. // 2. Remove any tasks queued by the history traversal task source that are associated with any Document objects
  830. // in browsingContext's top-level browsing context's document family.
  831. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([&](HTML::Task const& task) {
  832. return task.source() == Task::Source::HistoryTraversal
  833. && task.document()
  834. && top_level_browsing_context().document_family_contains(*task.document());
  835. });
  836. // 3. Append a new session history entry to the session history whose URL is url,
  837. // document is the current entry's document,
  838. // policy container is the current entry's policy-container
  839. // and scroll restoration mode is the current entry's scroll restoration mode.
  840. m_session_history.append(SessionHistoryEntry {
  841. .url = url,
  842. .document = current_entry().document,
  843. .serialized_state = {},
  844. .policy_container = current_entry().policy_container,
  845. .scroll_restoration_mode = current_entry().scroll_restoration_mode,
  846. .browsing_context_name = {},
  847. .original_source_browsing_context = {},
  848. });
  849. // 4. Traverse the history to the new entry, with historyHandling set to historyHandling.
  850. // This will scroll to the fragment given in what is now the document's URL.
  851. TRY(traverse_the_history(m_session_history.size() - 1, history_handling));
  852. // FIXME: 5. Invoke WebDriver BiDi fragment navigated with browsingContext,
  853. // and a new WebDriver BiDi navigation status whose id is navigationId, url is resource's url, and status is "complete".
  854. (void)navigation_id;
  855. return {};
  856. }
  857. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#traverse-the-history
  858. WebIDL::ExceptionOr<void> BrowsingContext::traverse_the_history(size_t entry_index, HistoryHandlingBehavior history_handling, bool explicit_history_navigation)
  859. {
  860. auto* entry = &m_session_history[entry_index];
  861. // 1. If entry's document is null, then:
  862. if (!entry->document) {
  863. // 1. Assert: historyHandling is "default".
  864. VERIFY(history_handling == HistoryHandlingBehavior::Default);
  865. // 2. Let request be a new request whose URL is entry's URL.
  866. auto request = Fetch::Infrastructure::Request::create();
  867. request->set_url(entry->url);
  868. // 3. If explicitHistoryNavigation is true, then set request's history-navigation flag.
  869. if (explicit_history_navigation)
  870. request->set_history_navigation(true);
  871. // 4. Navigate the browsing context to request with historyHandling set to "entry update"
  872. // and with historyPolicyContainer set to entry's policy container.
  873. // The navigation must be done using the same source browsing context as was used the first time entry was created.
  874. VERIFY(entry->original_source_browsing_context);
  875. TRY(navigate(move(request), *entry->original_source_browsing_context, false, HistoryHandlingBehavior::EntryUpdate, entry->policy_container));
  876. // 5. Return.
  877. return {};
  878. }
  879. // FIXME: 2. Save persisted state to the current entry.
  880. // 3. Let newDocument be entry's document.
  881. JS::GCPtr<DOM::Document> new_document = entry->document.ptr();
  882. // 4. Assert: newDocument's is initial about:blank is false,
  883. // i.e., we never traverse back to the initial about:blank Document because it always gets replaced when we navigate away from it.
  884. VERIFY(!new_document->is_initial_about_blank());
  885. // 5. If newDocument is different than the current entry's document, or historyHandling is "entry update" or "reload", then:
  886. if (new_document.ptr() != current_entry().document.ptr()
  887. || history_handling == HistoryHandlingBehavior::EntryUpdate) {
  888. // FIXME: 1. If newDocument's suspended timer handles is not empty:
  889. // FIXME: 1. Assert: newDocument's suspension time is not zero.
  890. // FIXME: 2. Let suspendDuration be the current high resolution time minus newDocument's suspension time.
  891. // FIXME: 3. Let activeTimers be newDocument's relevant global object's map of active timers.
  892. // FIXME: 4. For each handle in newDocument's suspended timer handles, if activeTimers[handle] exists, then increase activeTimers[handle] by suspendDuration.
  893. }
  894. // 2. Remove any tasks queued by the history traversal task source
  895. // that are associated with any Document objects in the top-level browsing context's document family.
  896. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([&](HTML::Task const& task) {
  897. return task.source() == Task::Source::HistoryTraversal
  898. && task.document()
  899. && top_level_browsing_context().document_family_contains(*task.document());
  900. });
  901. // 3. If newDocument's origin is not same origin with the current entry's document's origin, then:
  902. if (!new_document->origin().is_same_origin(current_entry().document->origin())) {
  903. // FIXME: 1. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the active document
  904. // and that are contiguous with the current entry.
  905. // FIXME: 2. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to the current browsing context name.
  906. // FIXME: 3. If the browsing context is a top-level browsing context, but not an auxiliary browsing context whose disowned is false, then set the browsing context's name to the empty string.
  907. }
  908. // 4. Set the active document of the browsing context to newDocument.
  909. set_active_document(*new_document);
  910. // 5. If entry's browsing context name is not null, then:
  911. if (entry->browsing_context_name.has_value()) {
  912. // 1. Set the browsing context's name to entry's browsing context name.
  913. m_name = *entry->browsing_context_name;
  914. // FIXME: 2. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the new active document's origin and that are contiguous with entry.
  915. // FIXME: 3. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to null.
  916. }
  917. // FIXME: 6. If newDocument has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.
  918. // 7. If newDocument's current document readiness "complete",
  919. if (new_document->ready_state() == "complete"sv) {
  920. // then queue a global task on the DOM manipulation task source given newDocument's relevant global object to run the following steps:
  921. queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*new_document), [new_document]() mutable {
  922. // 1. If newDocument's page showing flag is true, then abort these steps.
  923. if (new_document->page_showing())
  924. return;
  925. // 2. Set newDocument's page showing flag to true.
  926. new_document->set_page_showing(true);
  927. // 3. Update the visibility state of newDocument to "hidden".
  928. new_document->update_the_visibility_state(VisibilityState::Hidden);
  929. // 4. Fire a page transition event named pageshow at newDocument's relevant global object with true.
  930. auto& window = verify_cast<HTML::Window>(relevant_global_object(*new_document));
  931. window.fire_a_page_transition_event(HTML::EventNames::pageshow, true);
  932. });
  933. }
  934. // 6. Set newDocument's URL to entry's URL.
  935. new_document->set_url(entry->url);
  936. // 7. Let hashChanged be false, and let oldURL and newURL be null.
  937. bool hash_changed = false;
  938. Optional<AK::URL> old_url;
  939. Optional<AK::URL> new_url;
  940. // 8. If entry's URL's fragment is not identical to the current entry's URL's fragment,
  941. // and entry's document equals the current entry's document,
  942. if (entry->url.fragment() != current_entry().url.fragment()
  943. && entry->document.ptr() == current_entry().document.ptr()) {
  944. // then set hashChanged to true, set oldURL to the current entry's URL, and set newURL to entry's URL.
  945. hash_changed = true;
  946. old_url = current_entry().url;
  947. new_url = entry->url;
  948. }
  949. // 9. If historyHandling is "replace", then remove the entry immediately before entry in the session history.
  950. if (history_handling == HistoryHandlingBehavior::Replace) {
  951. // FIXME: This is gnarly.
  952. m_session_history.remove(entry_index - 1);
  953. entry_index--;
  954. entry = &m_session_history[entry_index];
  955. }
  956. // 10. If entry's persisted user state is null, and its URL's fragment is non-null, then scroll to the fragment.
  957. if (!entry->url.fragment().is_null()) {
  958. // FIXME: Implement the full "scroll to the fragment" algorithm:
  959. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier
  960. scroll_to_anchor(entry->url.fragment());
  961. }
  962. // 11. Set the current entry to entry.
  963. m_session_history_index = entry_index;
  964. // 12. Let targetRealm be the current Realm Record.
  965. auto* target_realm = Bindings::main_thread_vm().current_realm();
  966. VERIFY(target_realm);
  967. // FIXME: 13. Let state be null.
  968. // FIXME: 14. If entry's serialized state is not null, then set state to StructuredDeserialize(entry's serialized state, targetRealm).
  969. // If this throws an exception, catch it and ignore the exception.
  970. // FIXME: 15. Set newDocument's History object's state to state.
  971. // FIXME: 16. Let stateChanged be true if newDocument has a latest entry, and that entry is not entry; otherwise let it be false.
  972. // FIXME: 17. Set newDocument's latest entry to entry.
  973. // FIXME: 18. If stateChanged is true, then fire an event named popstate at newDocument's relevant global object, using PopStateEvent, with the state attribute initialized to state.
  974. // FIXME: 19. Restore persisted state from entry.
  975. // 20. If hashChanged is true,
  976. if (hash_changed) {
  977. // then queue a global task on the DOM manipulation task source given newDocument's relevant global object
  978. queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*new_document), [new_document]() mutable {
  979. // to fire an event named hashchange at newDocument's relevant global object,
  980. // using HashChangeEvent, with the oldURL attribute initialized to oldURL
  981. // and the newURL attribute initialized to newURL.
  982. // FIXME: Implement a proper HashChangeEvent class.
  983. auto event = DOM::Event::create(verify_cast<HTML::Window>(relevant_global_object(*new_document)).realm(), HTML::EventNames::hashchange);
  984. new_document->dispatch_event(event);
  985. });
  986. }
  987. return {};
  988. }
  989. // https://html.spec.whatwg.org/multipage/browsers.html#allowed-to-navigate
  990. bool BrowsingContext::is_allowed_to_navigate(BrowsingContext const& other) const
  991. {
  992. VERIFY(active_window());
  993. VERIFY(active_document());
  994. // 1. If A is not the same browsing context as B,
  995. // and A is not one of the ancestor browsing contexts of B,
  996. // and B is not a top-level browsing context,
  997. // FIXME: and A's active document's active sandboxing flag set has its sandboxed navigation browsing context flag set,
  998. // then return false.
  999. if (this != &other
  1000. && !this->is_ancestor_of(other)
  1001. && !other.is_top_level()) {
  1002. return false;
  1003. }
  1004. // 2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:
  1005. if (other.is_top_level() && other.is_ancestor_of(*this)) {
  1006. // 1. If A's active window has transient activation
  1007. // and A's active document's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set,
  1008. // then return false.
  1009. if (active_window()->has_transient_activation()
  1010. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedTopLevelNavigationWithUserActivation) {
  1011. return false;
  1012. }
  1013. // 2. Otherwise, if A's active window does not have transient activation
  1014. // and A's active document's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set,
  1015. // then return false.
  1016. if (!active_window()->has_transient_activation()
  1017. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedTopLevelNavigationWithoutUserActivation) {
  1018. return false;
  1019. }
  1020. }
  1021. // 3. Otherwise, if B is a top-level browsing context,
  1022. // and is neither A nor one of the ancestor browsing contexts of A,
  1023. // and A's Document's active sandboxing flag set has its sandboxed navigation browsing context flag set,
  1024. // and A is not the one permitted sandboxed navigator of B,
  1025. // then return false.
  1026. if (other.is_top_level()
  1027. && &other != this
  1028. && !other.is_ancestor_of(*this)
  1029. && active_document()->active_sandboxing_flag_set().flags & SandboxingFlagSet::SandboxedNavigation
  1030. && this != other.the_one_permitted_sandboxed_navigator()) {
  1031. return false;
  1032. }
  1033. // 4. Return true.
  1034. return true;
  1035. }
  1036. // https://html.spec.whatwg.org/multipage/origin.html#one-permitted-sandboxed-navigator
  1037. BrowsingContext const* BrowsingContext::the_one_permitted_sandboxed_navigator() const
  1038. {
  1039. // FIXME: Implement this.
  1040. return nullptr;
  1041. }
  1042. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  1043. Vector<JS::Handle<DOM::Document>> BrowsingContext::document_family() const
  1044. {
  1045. HashTable<DOM::Document*> documents;
  1046. for (auto& entry : m_session_history) {
  1047. if (!entry.document)
  1048. continue;
  1049. if (documents.set(entry.document.ptr()) == AK::HashSetResult::ReplacedExistingEntry)
  1050. continue;
  1051. for (auto& context : entry.document->list_of_descendant_browsing_contexts()) {
  1052. for (auto& document : context->document_family()) {
  1053. documents.set(document.ptr());
  1054. }
  1055. }
  1056. }
  1057. Vector<JS::Handle<DOM::Document>> family;
  1058. for (auto* document : documents) {
  1059. family.append(*document);
  1060. }
  1061. return family;
  1062. }
  1063. // https://html.spec.whatwg.org/multipage/browsers.html#document-family
  1064. bool BrowsingContext::document_family_contains(DOM::Document const& document) const
  1065. {
  1066. return document_family().first_matching([&](auto& entry) { return entry.ptr() == &document; }).has_value();
  1067. }
  1068. VisibilityState BrowsingContext::system_visibility_state() const
  1069. {
  1070. return m_system_visibility_state;
  1071. }
  1072. // https://html.spec.whatwg.org/multipage/interaction.html#system-visibility-state
  1073. void BrowsingContext::set_system_visibility_state(VisibilityState visibility_state)
  1074. {
  1075. if (m_system_visibility_state == visibility_state)
  1076. return;
  1077. m_system_visibility_state = visibility_state;
  1078. // When a user-agent determines that the system visibility state for top-level browsing context context
  1079. // has changed to newState, it must queue a task on the user interaction task source to update
  1080. // the visibility state of all the Document objects in the top-level browsing context's document family with newState.
  1081. auto document_family = top_level_browsing_context().document_family();
  1082. queue_global_task(Task::Source::UserInteraction, Bindings::main_thread_vm().current_realm()->global_object(), [visibility_state, document_family = move(document_family)]() mutable {
  1083. for (auto& document : document_family) {
  1084. document->update_the_visibility_state(visibility_state);
  1085. }
  1086. });
  1087. }
  1088. // https://html.spec.whatwg.org/multipage/window-object.html#a-browsing-context-is-discarded
  1089. void BrowsingContext::discard()
  1090. {
  1091. // 1. Discard all Document objects for all the entries in browsingContext's session history.
  1092. for (auto& entry : m_session_history) {
  1093. if (entry.document)
  1094. entry.document->discard();
  1095. }
  1096. // AD-HOC:
  1097. // FIXME: This should be in the session history!
  1098. if (auto* document = active_document())
  1099. document->discard();
  1100. // 2. If browsingContext is a top-level browsing context, then remove browsingContext.
  1101. if (is_top_level())
  1102. remove();
  1103. // AD-HOC:
  1104. if (parent())
  1105. parent()->remove_child(*this);
  1106. }
  1107. // https://html.spec.whatwg.org/multipage/window-object.html#close-a-browsing-context
  1108. void BrowsingContext::close()
  1109. {
  1110. VERIFY(active_document());
  1111. // FIXME: 1. If the result of calling prompt to unload with browsingContext's active document is "refuse", then return.
  1112. // 2. Unload browsingContext's active document.
  1113. active_document()->unload();
  1114. // 3. Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser).
  1115. if (m_page)
  1116. m_page->client().page_did_close_browsing_context(*this);
  1117. // 4. Discard browsingContext.
  1118. discard();
  1119. }
  1120. }