BrowsingContext.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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/Bindings/Wrapper.h>
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/DOM/HTMLCollection.h>
  10. #include <LibWeb/HTML/BrowsingContext.h>
  11. #include <LibWeb/HTML/BrowsingContextContainer.h>
  12. #include <LibWeb/HTML/CrossOrigin/CrossOriginOpenerPolicy.h>
  13. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  14. #include <LibWeb/HTML/HTMLAnchorElement.h>
  15. #include <LibWeb/HTML/HTMLInputElement.h>
  16. #include <LibWeb/HTML/SandboxingFlagSet.h>
  17. #include <LibWeb/HTML/Scripting/WindowEnvironmentSettingsObject.h>
  18. #include <LibWeb/HTML/Window.h>
  19. #include <LibWeb/Layout/BreakNode.h>
  20. #include <LibWeb/Layout/InitialContainingBlock.h>
  21. #include <LibWeb/Layout/TextNode.h>
  22. #include <LibWeb/Page/Page.h>
  23. namespace Web::HTML {
  24. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#matches-about:blank
  25. static bool url_matches_about_blank(AK::URL const& url)
  26. {
  27. // 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.
  28. return url.scheme() == "about"sv
  29. && url.path() == "blank"sv
  30. && url.username().is_empty()
  31. && url.password().is_empty()
  32. && url.host().is_null();
  33. }
  34. // https://url.spec.whatwg.org/#concept-url-origin
  35. static HTML::Origin url_origin(AK::URL const& url)
  36. {
  37. // FIXME: Move this whole function somewhere better.
  38. if (url.scheme() == "blob"sv) {
  39. // FIXME: Implement
  40. return HTML::Origin {};
  41. }
  42. if (url.scheme().is_one_of("ftp"sv, "http"sv, "https"sv, "ws"sv, "wss"sv)) {
  43. // Return the tuple origin (url’s scheme, url’s host, url’s port, null).
  44. return HTML::Origin(url.scheme(), url.host(), url.port().value_or(0));
  45. }
  46. if (url.scheme() == "file"sv) {
  47. // Unfortunate as it is, this is left as an exercise to the reader. When in doubt, return a new opaque origin.
  48. // Note: We must return an origin with the `file://' protocol for `file://' iframes to work from `file://' pages.
  49. return HTML::Origin(url.protocol(), String(), 0);
  50. }
  51. return HTML::Origin {};
  52. }
  53. // https://html.spec.whatwg.org/multipage/browsers.html#determining-the-origin
  54. HTML::Origin determine_the_origin(BrowsingContext const& browsing_context, Optional<AK::URL> url, SandboxingFlagSet sandbox_flags, Optional<HTML::Origin> invocation_origin)
  55. {
  56. // 1. If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin.
  57. if (sandbox_flags.flags & SandboxingFlagSet::SandboxedOrigin) {
  58. return HTML::Origin {};
  59. }
  60. // 2. If url is null, then return a new opaque origin.
  61. if (!url.has_value()) {
  62. return HTML::Origin {};
  63. }
  64. // 3. If invocationOrigin is non-null and url matches about:blank, then return invocationOrigin.
  65. if (invocation_origin.has_value() && url_matches_about_blank(*url)) {
  66. return invocation_origin.value();
  67. }
  68. // 4. If url is about:srcdoc, then return the origin of browsingContext's container document.
  69. if (url == AK::URL("about:srcdoc")) {
  70. VERIFY(browsing_context.container_document());
  71. return browsing_context.container_document()->origin();
  72. }
  73. // 5. Return url's origin.
  74. return url_origin(*url);
  75. }
  76. // https://html.spec.whatwg.org/multipage/browsers.html#creating-a-new-browsing-context
  77. NonnullRefPtr<BrowsingContext> BrowsingContext::create_a_new_browsing_context(Page& page, JS::GCPtr<DOM::Document> creator, JS::GCPtr<DOM::Element> embedder)
  78. {
  79. // 1. Let browsingContext be a new browsing context.
  80. BrowsingContextContainer* container = (embedder && is<BrowsingContextContainer>(*embedder)) ? static_cast<BrowsingContextContainer*>(embedder.ptr()) : nullptr;
  81. auto browsing_context = adopt_ref(*new BrowsingContext(page, container));
  82. // 2. Let unsafeContextCreationTime be the unsafe shared current time.
  83. [[maybe_unused]] auto unsafe_context_creation_time = HTML::main_thread_event_loop().unsafe_shared_current_time();
  84. // 3. If creator is non-null, then set browsingContext's creator origin to return creator's origin,
  85. // browsingContext's creator URL to return creator's URL,
  86. // browsingContext's creator base URL to return creator's base URL,
  87. // FIXME: and browsingContext's virtual browsing context group ID to creator's top-level browsing context's virtual browsing context group ID.
  88. if (creator) {
  89. browsing_context->m_creator_origin = creator->origin();
  90. browsing_context->m_creator_url = creator->url();
  91. browsing_context->m_creator_base_url = creator->base_url();
  92. }
  93. // FIXME: 4. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedded.
  94. SandboxingFlagSet sandbox_flags;
  95. // 5. Let origin be the result of determining the origin given browsingContext, about:blank, sandboxFlags, and browsingContext's creator origin.
  96. auto origin = determine_the_origin(browsing_context, AK::URL("about:blank"), sandbox_flags, browsing_context->m_creator_origin);
  97. // FIXME: 6. Let permissionsPolicy be the result of creating a permissions policy given browsingContext and origin. [PERMISSIONSPOLICY]
  98. // FIXME: 7. Let agent be the result of obtaining a similar-origin window agent given origin, group, and false.
  99. JS::GCPtr<Window> window;
  100. // 8. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:
  101. auto realm_execution_context = Bindings::create_a_new_javascript_realm(
  102. Bindings::main_thread_vm(),
  103. [&](JS::Realm& realm) -> JS::Object* {
  104. // - For the global object, create a new Window object.
  105. window = HTML::Window::create(realm);
  106. return window.ptr();
  107. },
  108. [](JS::Realm&) -> JS::Object* {
  109. // FIXME: - For the global this binding, use browsingContext's WindowProxy object.
  110. return nullptr;
  111. });
  112. // 9. Let topLevelCreationURL be about:blank if embedder is null; otherwise embedder's relevant settings object's top-level creation URL.
  113. auto top_level_creation_url = !embedder ? AK::URL("about:blank") : relevant_settings_object(*embedder).top_level_creation_url;
  114. // 10. Let topLevelOrigin be origin if embedder is null; otherwise embedder's relevant settings object's top-level origin.
  115. auto top_level_origin = !embedder ? origin : relevant_settings_object(*embedder).origin();
  116. // 11. Set up a window environment settings object with about:blank, realm execution context, null, topLevelCreationURL, and topLevelOrigin.
  117. HTML::WindowEnvironmentSettingsObject::setup(
  118. AK::URL("about:blank"),
  119. move(realm_execution_context),
  120. {},
  121. top_level_creation_url,
  122. top_level_origin);
  123. // FIXME: 12. Let loadTimingInfo be a new document load timing info with its navigation start time set to the result of calling
  124. // coarsen time with unsafeContextCreationTime and the new environment settings object's cross-origin isolated capability.
  125. // 13. Let coop be a new cross-origin opener policy.
  126. auto coop = CrossOriginOpenerPolicy {};
  127. // 14. If creator is non-null and creator's origin is same origin with creator's relevant settings object's top-level origin,
  128. // then set coop to creator's browsing context's top-level browsing context's active document's cross-origin opener policy.
  129. if (creator && creator->origin().is_same_origin(relevant_settings_object(*creator).top_level_origin)) {
  130. VERIFY(creator->browsing_context());
  131. auto* top_level_document = creator->browsing_context()->top_level_browsing_context().active_document();
  132. VERIFY(top_level_document);
  133. coop = top_level_document->cross_origin_opener_policy();
  134. }
  135. // 15. Let document be a new Document, marked as an HTML document in quirks mode,
  136. // whose content type is "text/html",
  137. // origin is origin,
  138. // FIXME: active sandboxing flag set is sandboxFlags,
  139. // FIXME: permissions policy is permissionsPolicy,
  140. // cross-origin opener policy is coop,
  141. // FIXME: load timing info is loadTimingInfo,
  142. // FIXME: navigation id is null,
  143. // and which is ready for post-load tasks.
  144. auto document = DOM::Document::create(*window);
  145. // Non-standard
  146. document->set_window({}, *window);
  147. window->set_associated_document(*document);
  148. document->set_quirks_mode(DOM::QuirksMode::Yes);
  149. document->set_content_type("text/html");
  150. document->set_origin(origin);
  151. document->set_url(AK::URL("about:blank"));
  152. document->set_cross_origin_opener_policy(coop);
  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. html_node->append_child(document->create_element(HTML::TagNames::head).release_value());
  160. html_node->append_child(document->create_element(HTML::TagNames::body).release_value());
  161. document->append_child(html_node);
  162. // 19. Set the active document of browsingContext to document.
  163. browsing_context->m_active_document = JS::make_handle(*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. });
  178. // Non-standard:
  179. document->attach_to_browsing_context({}, browsing_context);
  180. // 23. Completely finish loading document.
  181. document->completely_finish_loading();
  182. // 24. Return browsingContext.
  183. return browsing_context;
  184. }
  185. BrowsingContext::BrowsingContext(Page& page, HTML::BrowsingContextContainer* container)
  186. : m_page(page)
  187. , m_loader(*this)
  188. , m_event_handler({}, *this)
  189. , m_container(container)
  190. {
  191. m_cursor_blink_timer = Core::Timer::construct(500, [this] {
  192. if (!is_focused_context())
  193. return;
  194. if (m_cursor_position.node() && m_cursor_position.node()->layout_node()) {
  195. m_cursor_blink_state = !m_cursor_blink_state;
  196. m_cursor_position.node()->layout_node()->set_needs_display();
  197. }
  198. });
  199. }
  200. BrowsingContext::~BrowsingContext() = default;
  201. void BrowsingContext::did_edit(Badge<EditEventHandler>)
  202. {
  203. reset_cursor_blink_cycle();
  204. if (m_cursor_position.node() && is<DOM::Text>(*m_cursor_position.node())) {
  205. auto& text_node = static_cast<DOM::Text&>(*m_cursor_position.node());
  206. if (auto* input_element = text_node.owner_input_element())
  207. input_element->did_edit_text_node({});
  208. }
  209. }
  210. void BrowsingContext::reset_cursor_blink_cycle()
  211. {
  212. m_cursor_blink_state = true;
  213. m_cursor_blink_timer->restart();
  214. if (m_cursor_position.is_valid() && m_cursor_position.node()->layout_node())
  215. m_cursor_position.node()->layout_node()->set_needs_display();
  216. }
  217. // https://html.spec.whatwg.org/multipage/browsers.html#top-level-browsing-context
  218. bool BrowsingContext::is_top_level() const
  219. {
  220. // 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.
  221. return !parent();
  222. }
  223. bool BrowsingContext::is_focused_context() const
  224. {
  225. return m_page && &m_page->focused_context() == this;
  226. }
  227. void BrowsingContext::set_active_document(DOM::Document* document)
  228. {
  229. if (m_active_document.ptr() == document)
  230. return;
  231. m_cursor_position = {};
  232. if (m_active_document)
  233. m_active_document->detach_from_browsing_context({}, *this);
  234. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#resetBCName
  235. // FIXME: The rest of set_active_document does not follow the spec very closely, this just implements the
  236. // relevant steps for resetting the browsing context name and should be updated closer to the spec once
  237. // the other parts of history handling/navigating are implemented
  238. // 3. If newDocument's origin is not same origin with the current entry's document's origin, then:
  239. if (!document || !m_active_document || !document->origin().is_same_origin(m_active_document->origin())) {
  240. // 3. If the browsing context is a top-level browsing context, but not an auxiliary browsing context
  241. // whose disowned is false, then set the browsing context's name to the empty string.
  242. // FIXME: this is not checking the second part of the condition yet
  243. if (is_top_level())
  244. m_name = String::empty();
  245. }
  246. m_active_document = JS::make_handle(document);
  247. if (m_active_document) {
  248. m_active_document->attach_to_browsing_context({}, *this);
  249. if (m_page && is_top_level())
  250. m_page->client().page_did_change_title(m_active_document->title());
  251. }
  252. }
  253. void BrowsingContext::set_viewport_rect(Gfx::IntRect const& rect)
  254. {
  255. bool did_change = false;
  256. if (m_size != rect.size()) {
  257. m_size = rect.size();
  258. if (auto* document = active_document()) {
  259. // NOTE: Resizing the viewport changes the reference value for viewport-relative CSS lengths.
  260. document->invalidate_style();
  261. document->invalidate_layout();
  262. }
  263. did_change = true;
  264. }
  265. if (m_viewport_scroll_offset != rect.location()) {
  266. m_viewport_scroll_offset = rect.location();
  267. did_change = true;
  268. }
  269. if (did_change) {
  270. for (auto* client : m_viewport_clients)
  271. client->browsing_context_did_set_viewport_rect(rect);
  272. }
  273. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  274. HTML::main_thread_event_loop().schedule();
  275. }
  276. void BrowsingContext::set_size(Gfx::IntSize const& size)
  277. {
  278. if (m_size == size)
  279. return;
  280. m_size = size;
  281. if (auto* document = active_document()) {
  282. document->invalidate_style();
  283. document->invalidate_layout();
  284. }
  285. for (auto* client : m_viewport_clients)
  286. client->browsing_context_did_set_viewport_rect(viewport_rect());
  287. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  288. HTML::main_thread_event_loop().schedule();
  289. }
  290. void BrowsingContext::set_needs_display()
  291. {
  292. set_needs_display(viewport_rect());
  293. }
  294. void BrowsingContext::set_needs_display(Gfx::IntRect const& rect)
  295. {
  296. if (!viewport_rect().intersects(rect))
  297. return;
  298. if (is_top_level()) {
  299. if (m_page)
  300. m_page->client().page_did_invalidate(to_top_level_rect(rect));
  301. return;
  302. }
  303. if (container() && container()->layout_node())
  304. container()->layout_node()->set_needs_display();
  305. }
  306. void BrowsingContext::scroll_to(Gfx::IntPoint const& position)
  307. {
  308. if (active_document())
  309. active_document()->force_layout();
  310. if (m_page)
  311. m_page->client().page_did_request_scroll_to(position);
  312. }
  313. void BrowsingContext::scroll_to_anchor(String const& fragment)
  314. {
  315. if (!active_document())
  316. return;
  317. auto element = active_document()->get_element_by_id(fragment);
  318. if (!element) {
  319. auto candidates = active_document()->get_elements_by_name(fragment);
  320. for (auto& candidate : candidates->collect_matching_elements()) {
  321. if (is<HTML::HTMLAnchorElement>(*candidate)) {
  322. element = &verify_cast<HTML::HTMLAnchorElement>(*candidate);
  323. break;
  324. }
  325. }
  326. }
  327. active_document()->force_layout();
  328. if (!element || !element->layout_node())
  329. return;
  330. auto& layout_node = *element->layout_node();
  331. Gfx::FloatRect float_rect { layout_node.box_type_agnostic_position(), { (float)viewport_rect().width(), (float)viewport_rect().height() } };
  332. if (is<Layout::Box>(layout_node)) {
  333. auto& layout_box = verify_cast<Layout::Box>(layout_node);
  334. auto padding_box = layout_box.box_model().padding_box();
  335. float_rect.translate_by(-padding_box.left, -padding_box.top);
  336. }
  337. if (m_page)
  338. m_page->client().page_did_request_scroll_into_view(enclosing_int_rect(float_rect));
  339. }
  340. Gfx::IntRect BrowsingContext::to_top_level_rect(Gfx::IntRect const& a_rect)
  341. {
  342. auto rect = a_rect;
  343. rect.set_location(to_top_level_position(a_rect.location()));
  344. return rect;
  345. }
  346. Gfx::IntPoint BrowsingContext::to_top_level_position(Gfx::IntPoint const& a_position)
  347. {
  348. auto position = a_position;
  349. for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  350. if (ancestor->is_top_level())
  351. break;
  352. if (!ancestor->container())
  353. return {};
  354. if (!ancestor->container()->layout_node())
  355. return {};
  356. position.translate_by(ancestor->container()->layout_node()->box_type_agnostic_position().to_type<int>());
  357. }
  358. return position;
  359. }
  360. void BrowsingContext::set_cursor_position(DOM::Position position)
  361. {
  362. if (m_cursor_position == position)
  363. return;
  364. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  365. m_cursor_position.node()->layout_node()->set_needs_display();
  366. m_cursor_position = move(position);
  367. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  368. m_cursor_position.node()->layout_node()->set_needs_display();
  369. reset_cursor_blink_cycle();
  370. }
  371. String BrowsingContext::selected_text() const
  372. {
  373. StringBuilder builder;
  374. if (!active_document())
  375. return {};
  376. auto* layout_root = active_document()->layout_node();
  377. if (!layout_root)
  378. return {};
  379. if (!layout_root->selection().is_valid())
  380. return {};
  381. auto selection = layout_root->selection().normalized();
  382. if (selection.start().layout_node == selection.end().layout_node) {
  383. if (!is<Layout::TextNode>(*selection.start().layout_node))
  384. return "";
  385. 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);
  386. }
  387. // Start node
  388. auto layout_node = selection.start().layout_node;
  389. if (is<Layout::TextNode>(*layout_node)) {
  390. auto& text = verify_cast<Layout::TextNode>(*layout_node).text_for_rendering();
  391. builder.append(text.substring(selection.start().index_in_node, text.length() - selection.start().index_in_node));
  392. }
  393. // Middle nodes
  394. layout_node = layout_node->next_in_pre_order();
  395. while (layout_node && layout_node != selection.end().layout_node) {
  396. if (is<Layout::TextNode>(*layout_node))
  397. builder.append(verify_cast<Layout::TextNode>(*layout_node).text_for_rendering());
  398. else if (is<Layout::BreakNode>(*layout_node) || is<Layout::BlockContainer>(*layout_node))
  399. builder.append('\n');
  400. layout_node = layout_node->next_in_pre_order();
  401. }
  402. // End node
  403. VERIFY(layout_node == selection.end().layout_node);
  404. if (is<Layout::TextNode>(*layout_node)) {
  405. auto& text = verify_cast<Layout::TextNode>(*layout_node).text_for_rendering();
  406. builder.append(text.substring(0, selection.end().index_in_node));
  407. }
  408. return builder.to_string();
  409. }
  410. void BrowsingContext::select_all()
  411. {
  412. if (!active_document())
  413. return;
  414. auto* layout_root = active_document()->layout_node();
  415. if (!layout_root)
  416. return;
  417. Layout::Node const* first_layout_node = layout_root;
  418. for (;;) {
  419. auto* next = first_layout_node->next_in_pre_order();
  420. if (!next)
  421. break;
  422. first_layout_node = next;
  423. if (is<Layout::TextNode>(*first_layout_node))
  424. break;
  425. }
  426. Layout::Node const* last_layout_node = first_layout_node;
  427. for (Layout::Node const* layout_node = first_layout_node; layout_node; layout_node = layout_node->next_in_pre_order()) {
  428. if (is<Layout::TextNode>(*layout_node))
  429. last_layout_node = layout_node;
  430. }
  431. VERIFY(first_layout_node);
  432. VERIFY(last_layout_node);
  433. int last_layout_node_index_in_node = 0;
  434. if (is<Layout::TextNode>(*last_layout_node)) {
  435. auto const& text_for_rendering = verify_cast<Layout::TextNode>(*last_layout_node).text_for_rendering();
  436. if (!text_for_rendering.is_empty())
  437. last_layout_node_index_in_node = text_for_rendering.length() - 1;
  438. }
  439. layout_root->set_selection({ { first_layout_node, 0 }, { last_layout_node, last_layout_node_index_in_node } });
  440. }
  441. void BrowsingContext::register_viewport_client(ViewportClient& client)
  442. {
  443. auto result = m_viewport_clients.set(&client);
  444. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  445. }
  446. void BrowsingContext::unregister_viewport_client(ViewportClient& client)
  447. {
  448. bool was_removed = m_viewport_clients.remove(&client);
  449. VERIFY(was_removed);
  450. }
  451. void BrowsingContext::register_frame_nesting(AK::URL const& url)
  452. {
  453. m_frame_nesting_levels.ensure(url)++;
  454. }
  455. bool BrowsingContext::is_frame_nesting_allowed(AK::URL const& url) const
  456. {
  457. return m_frame_nesting_levels.get(url).value_or(0) < 3;
  458. }
  459. bool BrowsingContext::increment_cursor_position_offset()
  460. {
  461. if (!m_cursor_position.increment_offset())
  462. return false;
  463. reset_cursor_blink_cycle();
  464. return true;
  465. }
  466. bool BrowsingContext::decrement_cursor_position_offset()
  467. {
  468. if (!m_cursor_position.decrement_offset())
  469. return false;
  470. reset_cursor_blink_cycle();
  471. return true;
  472. }
  473. DOM::Document* BrowsingContext::container_document()
  474. {
  475. if (auto* container = this->container())
  476. return &container->document();
  477. return nullptr;
  478. }
  479. DOM::Document const* BrowsingContext::container_document() const
  480. {
  481. if (auto* container = this->container())
  482. return &container->document();
  483. return nullptr;
  484. }
  485. // https://html.spec.whatwg.org/#rendering-opportunity
  486. bool BrowsingContext::has_a_rendering_opportunity() const
  487. {
  488. // 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,
  489. // accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.
  490. // FIXME: We should at the very least say `false` here if we're an inactive browser tab.
  491. return true;
  492. }
  493. // https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-browsing-context
  494. JS::GCPtr<DOM::Node> BrowsingContext::currently_focused_area()
  495. {
  496. // 1. If topLevelBC does not have system focus, then return null.
  497. if (!is_focused_context())
  498. return nullptr;
  499. // 2. Let candidate be topLevelBC's active document.
  500. auto* candidate = active_document();
  501. // 3. While candidate's focused area is a browsing context container with a non-null nested browsing context:
  502. // set candidate to the active document of that browsing context container's nested browsing context.
  503. while (candidate->focused_element()
  504. && is<HTML::BrowsingContextContainer>(candidate->focused_element())
  505. && static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()) {
  506. candidate = static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document();
  507. }
  508. // 4. If candidate's focused area is non-null, set candidate to candidate's focused area.
  509. if (candidate->focused_element()) {
  510. // NOTE: We return right away here instead of assigning to candidate,
  511. // since that would require compromising type safety.
  512. return candidate->focused_element();
  513. }
  514. // 5. Return candidate.
  515. return candidate;
  516. }
  517. BrowsingContext* BrowsingContext::choose_a_browsing_context(StringView name, bool)
  518. {
  519. // The rules for choosing a browsing context, given a browsing context name
  520. // name, a browsing context current, and a boolean noopener are as follows:
  521. // 1. Let chosen be null.
  522. BrowsingContext* chosen = nullptr;
  523. // FIXME: 2. Let windowType be "existing or none".
  524. // FIXME: 3. Let sandboxingFlagSet be current's active document's active
  525. // sandboxing flag set.
  526. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to current.
  527. if (name.is_empty() || name.equals_ignoring_case("_self"sv))
  528. chosen = this;
  529. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent",
  530. // set chosen to current's parent browsing context, if any, and current
  531. // otherwise.
  532. if (name.equals_ignoring_case("_parent"sv)) {
  533. if (auto* parent = this->parent())
  534. chosen = parent;
  535. else
  536. chosen = this;
  537. }
  538. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top", set
  539. // chosen to current's top-level browsing context, if any, and current
  540. // otherwise.
  541. if (name.equals_ignoring_case("_top"sv)) {
  542. chosen = &top_level_browsing_context();
  543. }
  544. // FIXME: 7. Otherwise, if name is not an ASCII case-insensitive match for
  545. // "_blank", there exists a browsing context whose name is the same as name,
  546. // current is familiar with that browsing context, and the user agent
  547. // determines that the two browsing contexts are related enough that it is
  548. // ok if they reach each other, set chosen to that browsing context. If
  549. // there are multiple matching browsing contexts, the user agent should set
  550. // chosen to one in some arbitrary consistent manner, such as the most
  551. // recently opened, most recently focused, or more closely related.
  552. if (!name.equals_ignoring_case("_blank"sv)) {
  553. chosen = this;
  554. } else {
  555. // 8. Otherwise, a new browsing context is being requested, and what
  556. // happens depends on the user agent's configuration and abilities — it
  557. // is determined by the rules given for the first applicable option from
  558. // the following list:
  559. dbgln("FIXME: Create a new browsing context!");
  560. // --> If current's active window does not have transient activation and
  561. // the user agent has been configured to not show popups (i.e., the
  562. // user agent has a "popup blocker" enabled)
  563. //
  564. // The user agent may inform the user that a popup has been blocked.
  565. // --> If sandboxingFlagSet has the sandboxed auxiliary navigation
  566. // browsing context flag set
  567. //
  568. // The user agent may report to a developer console that a popup has
  569. // been blocked.
  570. // --> If the user agent has been configured such that in this instance
  571. // it will create a new browsing context
  572. //
  573. // 1. Set windowType to "new and unrestricted".
  574. // 2. If current's top-level browsing context's active document's
  575. // cross-origin opener policy's value is "same-origin" or
  576. // "same-origin-plus-COEP", then:
  577. // 2.1. Let currentDocument be current's active document.
  578. // 2.2. If currentDocument's origin is not same origin with
  579. // currentDocument's relevant settings object's top-level
  580. // origin, then set noopener to true, name to "_blank", and
  581. // windowType to "new with no opener".
  582. // 3. If noopener is true, then set chosen to the result of creating
  583. // a new top-level browsing context.
  584. // 4. Otherwise:
  585. // 4.1. Set chosen to the result of creating a new auxiliary
  586. // browsing context with current.
  587. // 4.2. If sandboxingFlagSet's sandboxed navigation browsing
  588. // context flag is set, then current must be set as chosen's one
  589. // permitted sandboxed navigator.
  590. // 5. If sandboxingFlagSet's sandbox propagates to auxiliary
  591. // browsing contexts flag is set, then all the flags that are set in
  592. // sandboxingFlagSet must be set in chosen's popup sandboxing flag
  593. // set.
  594. // 6. If name is not an ASCII case-insensitive match for "_blank",
  595. // then set chosen's name to name.
  596. // --> If the user agent has been configured such that in this instance
  597. // it will reuse current
  598. //
  599. // Set chosen to current.
  600. // --> If the user agent has been configured such that in this instance
  601. // it will not find a browsing context
  602. //
  603. // Do nothing.
  604. }
  605. // 9. Return chosen and windowType.
  606. return chosen;
  607. }
  608. // https://html.spec.whatwg.org/multipage/dom.html#still-on-its-initial-about:blank-document
  609. bool BrowsingContext::still_on_its_initial_about_blank_document() const
  610. {
  611. // A browsing context browsingContext is still on its initial about:blank Document
  612. // if browsingContext's session history's size is 1
  613. // and browsingContext's session history[0]'s document's is initial about:blank is true.
  614. return m_session_history.size() == 1
  615. && m_session_history[0].document
  616. && m_session_history[0].document->is_initial_about_blank();
  617. }
  618. DOM::Document const* BrowsingContext::active_document() const
  619. {
  620. return m_active_document.cell();
  621. }
  622. DOM::Document* BrowsingContext::active_document()
  623. {
  624. return m_active_document.cell();
  625. }
  626. }