BrowsingContext.cpp 60 KB

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