BrowsingContext.cpp 30 KB

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