BrowsingContext.cpp 57 KB

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