BrowsingContext.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/DOM/Document.h>
  7. #include <LibWeb/DOM/HTMLCollection.h>
  8. #include <LibWeb/HTML/BrowsingContext.h>
  9. #include <LibWeb/HTML/BrowsingContextContainer.h>
  10. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  11. #include <LibWeb/HTML/HTMLAnchorElement.h>
  12. #include <LibWeb/HTML/HTMLInputElement.h>
  13. #include <LibWeb/HTML/Window.h>
  14. #include <LibWeb/Layout/BreakNode.h>
  15. #include <LibWeb/Layout/InitialContainingBlock.h>
  16. #include <LibWeb/Layout/TextNode.h>
  17. #include <LibWeb/Page/Page.h>
  18. namespace Web::HTML {
  19. BrowsingContext::BrowsingContext(Page& page, HTML::BrowsingContextContainer* container)
  20. : m_page(page)
  21. , m_loader(*this)
  22. , m_event_handler({}, *this)
  23. , m_container(container)
  24. {
  25. m_cursor_blink_timer = Core::Timer::construct(500, [this] {
  26. if (!is_focused_context())
  27. return;
  28. if (m_cursor_position.node() && m_cursor_position.node()->layout_node()) {
  29. m_cursor_blink_state = !m_cursor_blink_state;
  30. m_cursor_position.node()->layout_node()->set_needs_display();
  31. }
  32. });
  33. }
  34. BrowsingContext::~BrowsingContext() = default;
  35. void BrowsingContext::did_edit(Badge<EditEventHandler>)
  36. {
  37. reset_cursor_blink_cycle();
  38. if (m_cursor_position.node() && is<DOM::Text>(*m_cursor_position.node())) {
  39. auto& text_node = static_cast<DOM::Text&>(*m_cursor_position.node());
  40. if (auto* input_element = text_node.owner_input_element())
  41. input_element->did_edit_text_node({});
  42. }
  43. }
  44. void BrowsingContext::reset_cursor_blink_cycle()
  45. {
  46. m_cursor_blink_state = true;
  47. m_cursor_blink_timer->restart();
  48. if (m_cursor_position.is_valid() && m_cursor_position.node()->layout_node())
  49. m_cursor_position.node()->layout_node()->set_needs_display();
  50. }
  51. // https://html.spec.whatwg.org/multipage/browsers.html#top-level-browsing-context
  52. bool BrowsingContext::is_top_level() const
  53. {
  54. // 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.
  55. return !parent();
  56. }
  57. bool BrowsingContext::is_focused_context() const
  58. {
  59. return m_page && &m_page->focused_context() == this;
  60. }
  61. void BrowsingContext::set_active_document(DOM::Document* document)
  62. {
  63. if (m_active_document == document)
  64. return;
  65. m_cursor_position = {};
  66. if (m_active_document)
  67. m_active_document->detach_from_browsing_context({}, *this);
  68. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#resetBCName
  69. // FIXME: The rest of set_active_document does not follow the spec very closely, this just implements the
  70. // relevant steps for resetting the browsing context name and should be updated closer to the spec once
  71. // the other parts of history handling/navigating are implemented
  72. // 3. If newDocument's origin is not same origin with the current entry's document's origin, then:
  73. if (!document || !m_active_document || !document->origin().is_same_origin(m_active_document->origin())) {
  74. // 3. If the browsing context is a top-level browsing context, but not an auxiliary browsing context
  75. // whose disowned is false, then set the browsing context's name to the empty string.
  76. // FIXME: this is not checking the second part of the condition yet
  77. if (is_top_level())
  78. m_name = String::empty();
  79. }
  80. m_active_document = document;
  81. if (m_active_document) {
  82. m_active_document->attach_to_browsing_context({}, *this);
  83. if (m_page && is_top_level())
  84. m_page->client().page_did_change_title(m_active_document->title());
  85. }
  86. if (m_page)
  87. m_page->client().page_did_set_document_in_top_level_browsing_context(m_active_document);
  88. }
  89. void BrowsingContext::set_viewport_rect(Gfx::IntRect const& rect)
  90. {
  91. bool did_change = false;
  92. if (m_size != rect.size()) {
  93. m_size = rect.size();
  94. if (auto* document = active_document()) {
  95. // NOTE: Resizing the viewport changes the reference value for viewport-relative CSS lengths.
  96. document->invalidate_style();
  97. document->invalidate_layout();
  98. }
  99. did_change = true;
  100. }
  101. if (m_viewport_scroll_offset != rect.location()) {
  102. m_viewport_scroll_offset = rect.location();
  103. did_change = true;
  104. }
  105. if (did_change) {
  106. for (auto* client : m_viewport_clients)
  107. client->browsing_context_did_set_viewport_rect(rect);
  108. }
  109. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  110. HTML::main_thread_event_loop().schedule();
  111. }
  112. void BrowsingContext::set_size(Gfx::IntSize const& size)
  113. {
  114. if (m_size == size)
  115. return;
  116. m_size = size;
  117. if (auto* document = active_document()) {
  118. document->invalidate_style();
  119. document->invalidate_layout();
  120. }
  121. for (auto* client : m_viewport_clients)
  122. client->browsing_context_did_set_viewport_rect(viewport_rect());
  123. // Schedule the HTML event loop to ensure that a `resize` event gets fired.
  124. HTML::main_thread_event_loop().schedule();
  125. }
  126. void BrowsingContext::set_needs_display()
  127. {
  128. set_needs_display(viewport_rect());
  129. }
  130. void BrowsingContext::set_needs_display(Gfx::IntRect const& rect)
  131. {
  132. if (!viewport_rect().intersects(rect))
  133. return;
  134. if (is_top_level()) {
  135. if (m_page)
  136. m_page->client().page_did_invalidate(to_top_level_rect(rect));
  137. return;
  138. }
  139. if (container() && container()->layout_node())
  140. container()->layout_node()->set_needs_display();
  141. }
  142. void BrowsingContext::scroll_to(Gfx::IntPoint const& position)
  143. {
  144. if (active_document())
  145. active_document()->force_layout();
  146. if (m_page)
  147. m_page->client().page_did_request_scroll_to(position);
  148. }
  149. void BrowsingContext::scroll_to_anchor(String const& fragment)
  150. {
  151. if (!active_document())
  152. return;
  153. auto element = active_document()->get_element_by_id(fragment);
  154. if (!element) {
  155. auto candidates = active_document()->get_elements_by_name(fragment);
  156. for (auto& candidate : candidates->collect_matching_elements()) {
  157. if (is<HTML::HTMLAnchorElement>(*candidate)) {
  158. element = verify_cast<HTML::HTMLAnchorElement>(*candidate);
  159. break;
  160. }
  161. }
  162. }
  163. active_document()->force_layout();
  164. if (!element || !element->layout_node())
  165. return;
  166. auto& layout_node = *element->layout_node();
  167. Gfx::FloatRect float_rect { layout_node.box_type_agnostic_position(), { (float)viewport_rect().width(), (float)viewport_rect().height() } };
  168. if (is<Layout::Box>(layout_node)) {
  169. auto& layout_box = verify_cast<Layout::Box>(layout_node);
  170. auto padding_box = layout_box.box_model().padding_box();
  171. float_rect.translate_by(-padding_box.left, -padding_box.top);
  172. }
  173. if (m_page)
  174. m_page->client().page_did_request_scroll_into_view(enclosing_int_rect(float_rect));
  175. }
  176. Gfx::IntRect BrowsingContext::to_top_level_rect(Gfx::IntRect const& a_rect)
  177. {
  178. auto rect = a_rect;
  179. rect.set_location(to_top_level_position(a_rect.location()));
  180. return rect;
  181. }
  182. Gfx::IntPoint BrowsingContext::to_top_level_position(Gfx::IntPoint const& a_position)
  183. {
  184. auto position = a_position;
  185. for (auto* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
  186. if (ancestor->is_top_level())
  187. break;
  188. if (!ancestor->container())
  189. return {};
  190. if (!ancestor->container()->layout_node())
  191. return {};
  192. position.translate_by(ancestor->container()->layout_node()->box_type_agnostic_position().to_type<int>());
  193. }
  194. return position;
  195. }
  196. void BrowsingContext::set_cursor_position(DOM::Position position)
  197. {
  198. if (m_cursor_position == position)
  199. return;
  200. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  201. m_cursor_position.node()->layout_node()->set_needs_display();
  202. m_cursor_position = move(position);
  203. if (m_cursor_position.node() && m_cursor_position.node()->layout_node())
  204. m_cursor_position.node()->layout_node()->set_needs_display();
  205. reset_cursor_blink_cycle();
  206. }
  207. String BrowsingContext::selected_text() const
  208. {
  209. StringBuilder builder;
  210. if (!active_document())
  211. return {};
  212. auto* layout_root = active_document()->layout_node();
  213. if (!layout_root)
  214. return {};
  215. if (!layout_root->selection().is_valid())
  216. return {};
  217. auto selection = layout_root->selection().normalized();
  218. if (selection.start().layout_node == selection.end().layout_node) {
  219. if (!is<Layout::TextNode>(*selection.start().layout_node))
  220. return "";
  221. 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);
  222. }
  223. // Start node
  224. auto layout_node = selection.start().layout_node;
  225. if (is<Layout::TextNode>(*layout_node)) {
  226. auto& text = verify_cast<Layout::TextNode>(*layout_node).text_for_rendering();
  227. builder.append(text.substring(selection.start().index_in_node, text.length() - selection.start().index_in_node));
  228. }
  229. // Middle nodes
  230. layout_node = layout_node->next_in_pre_order();
  231. while (layout_node && layout_node != selection.end().layout_node) {
  232. if (is<Layout::TextNode>(*layout_node))
  233. builder.append(verify_cast<Layout::TextNode>(*layout_node).text_for_rendering());
  234. else if (is<Layout::BreakNode>(*layout_node) || is<Layout::BlockContainer>(*layout_node))
  235. builder.append('\n');
  236. layout_node = layout_node->next_in_pre_order();
  237. }
  238. // End node
  239. VERIFY(layout_node == selection.end().layout_node);
  240. if (is<Layout::TextNode>(*layout_node)) {
  241. auto& text = verify_cast<Layout::TextNode>(*layout_node).text_for_rendering();
  242. builder.append(text.substring(0, selection.end().index_in_node));
  243. }
  244. return builder.to_string();
  245. }
  246. void BrowsingContext::select_all()
  247. {
  248. if (!active_document())
  249. return;
  250. auto* layout_root = active_document()->layout_node();
  251. if (!layout_root)
  252. return;
  253. Layout::Node const* first_layout_node = layout_root;
  254. for (;;) {
  255. auto* next = first_layout_node->next_in_pre_order();
  256. if (!next)
  257. break;
  258. first_layout_node = next;
  259. if (is<Layout::TextNode>(*first_layout_node))
  260. break;
  261. }
  262. Layout::Node const* last_layout_node = first_layout_node;
  263. for (Layout::Node const* layout_node = first_layout_node; layout_node; layout_node = layout_node->next_in_pre_order()) {
  264. if (is<Layout::TextNode>(*layout_node))
  265. last_layout_node = layout_node;
  266. }
  267. VERIFY(first_layout_node);
  268. VERIFY(last_layout_node);
  269. int last_layout_node_index_in_node = 0;
  270. if (is<Layout::TextNode>(*last_layout_node)) {
  271. auto const& text_for_rendering = verify_cast<Layout::TextNode>(*last_layout_node).text_for_rendering();
  272. if (!text_for_rendering.is_empty())
  273. last_layout_node_index_in_node = text_for_rendering.length() - 1;
  274. }
  275. layout_root->set_selection({ { first_layout_node, 0 }, { last_layout_node, last_layout_node_index_in_node } });
  276. }
  277. void BrowsingContext::register_viewport_client(ViewportClient& client)
  278. {
  279. auto result = m_viewport_clients.set(&client);
  280. VERIFY(result == AK::HashSetResult::InsertedNewEntry);
  281. }
  282. void BrowsingContext::unregister_viewport_client(ViewportClient& client)
  283. {
  284. bool was_removed = m_viewport_clients.remove(&client);
  285. VERIFY(was_removed);
  286. }
  287. void BrowsingContext::register_frame_nesting(AK::URL const& url)
  288. {
  289. m_frame_nesting_levels.ensure(url)++;
  290. }
  291. bool BrowsingContext::is_frame_nesting_allowed(AK::URL const& url) const
  292. {
  293. return m_frame_nesting_levels.get(url).value_or(0) < 3;
  294. }
  295. bool BrowsingContext::increment_cursor_position_offset()
  296. {
  297. if (!m_cursor_position.increment_offset())
  298. return false;
  299. reset_cursor_blink_cycle();
  300. return true;
  301. }
  302. bool BrowsingContext::decrement_cursor_position_offset()
  303. {
  304. if (!m_cursor_position.decrement_offset())
  305. return false;
  306. reset_cursor_blink_cycle();
  307. return true;
  308. }
  309. DOM::Document* BrowsingContext::container_document()
  310. {
  311. if (auto* container = this->container())
  312. return &container->document();
  313. return nullptr;
  314. }
  315. DOM::Document const* BrowsingContext::container_document() const
  316. {
  317. if (auto* container = this->container())
  318. return &container->document();
  319. return nullptr;
  320. }
  321. // https://html.spec.whatwg.org/#rendering-opportunity
  322. bool BrowsingContext::has_a_rendering_opportunity() const
  323. {
  324. // 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,
  325. // accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.
  326. // FIXME: We should at the very least say `false` here if we're an inactive browser tab.
  327. return true;
  328. }
  329. // https://html.spec.whatwg.org/multipage/interaction.html#currently-focused-area-of-a-top-level-browsing-context
  330. RefPtr<DOM::Node> BrowsingContext::currently_focused_area()
  331. {
  332. // 1. If topLevelBC does not have system focus, then return null.
  333. if (!is_focused_context())
  334. return nullptr;
  335. // 2. Let candidate be topLevelBC's active document.
  336. auto* candidate = active_document();
  337. // 3. While candidate's focused area is a browsing context container with a non-null nested browsing context:
  338. // set candidate to the active document of that browsing context container's nested browsing context.
  339. while (candidate->focused_element()
  340. && is<HTML::BrowsingContextContainer>(candidate->focused_element())
  341. && static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()) {
  342. candidate = static_cast<HTML::BrowsingContextContainer&>(*candidate->focused_element()).nested_browsing_context()->active_document();
  343. }
  344. // 4. If candidate's focused area is non-null, set candidate to candidate's focused area.
  345. if (candidate->focused_element()) {
  346. // NOTE: We return right away here instead of assigning to candidate,
  347. // since that would require compromising type safety.
  348. return candidate->focused_element();
  349. }
  350. // 5. Return candidate.
  351. return candidate;
  352. }
  353. BrowsingContext* BrowsingContext::choose_a_browsing_context(StringView name, bool)
  354. {
  355. // The rules for choosing a browsing context, given a browsing context name
  356. // name, a browsing context current, and a boolean noopener are as follows:
  357. // 1. Let chosen be null.
  358. BrowsingContext* chosen = nullptr;
  359. // FIXME: 2. Let windowType be "existing or none".
  360. // FIXME: 3. Let sandboxingFlagSet be current's active document's active
  361. // sandboxing flag set.
  362. // 4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to current.
  363. if (name.is_empty() || name.equals_ignoring_case("_self"sv))
  364. chosen = this;
  365. // 5. Otherwise, if name is an ASCII case-insensitive match for "_parent",
  366. // set chosen to current's parent browsing context, if any, and current
  367. // otherwise.
  368. if (name.equals_ignoring_case("_parent"sv)) {
  369. if (auto* parent = this->parent())
  370. chosen = parent;
  371. else
  372. chosen = this;
  373. }
  374. // 6. Otherwise, if name is an ASCII case-insensitive match for "_top", set
  375. // chosen to current's top-level browsing context, if any, and current
  376. // otherwise.
  377. if (name.equals_ignoring_case("_top"sv)) {
  378. chosen = &top_level_browsing_context();
  379. }
  380. // FIXME: 7. Otherwise, if name is not an ASCII case-insensitive match for
  381. // "_blank", there exists a browsing context whose name is the same as name,
  382. // current is familiar with that browsing context, and the user agent
  383. // determines that the two browsing contexts are related enough that it is
  384. // ok if they reach each other, set chosen to that browsing context. If
  385. // there are multiple matching browsing contexts, the user agent should set
  386. // chosen to one in some arbitrary consistent manner, such as the most
  387. // recently opened, most recently focused, or more closely related.
  388. if (!name.equals_ignoring_case("_blank"sv)) {
  389. chosen = this;
  390. } else {
  391. // 8. Otherwise, a new browsing context is being requested, and what
  392. // happens depends on the user agent's configuration and abilities — it
  393. // is determined by the rules given for the first applicable option from
  394. // the following list:
  395. dbgln("FIXME: Create a new browsing context!");
  396. // --> If current's active window does not have transient activation and
  397. // the user agent has been configured to not show popups (i.e., the
  398. // user agent has a "popup blocker" enabled)
  399. //
  400. // The user agent may inform the user that a popup has been blocked.
  401. // --> If sandboxingFlagSet has the sandboxed auxiliary navigation
  402. // browsing context flag set
  403. //
  404. // The user agent may report to a developer console that a popup has
  405. // been blocked.
  406. // --> If the user agent has been configured such that in this instance
  407. // it will create a new browsing context
  408. //
  409. // 1. Set windowType to "new and unrestricted".
  410. // 2. If current's top-level browsing context's active document's
  411. // cross-origin opener policy's value is "same-origin" or
  412. // "same-origin-plus-COEP", then:
  413. // 2.1. Let currentDocument be current's active document.
  414. // 2.2. If currentDocument's origin is not same origin with
  415. // currentDocument's relevant settings object's top-level
  416. // origin, then set noopener to true, name to "_blank", and
  417. // windowType to "new with no opener".
  418. // 3. If noopener is true, then set chosen to the result of creating
  419. // a new top-level browsing context.
  420. // 4. Otherwise:
  421. // 4.1. Set chosen to the result of creating a new auxiliary
  422. // browsing context with current.
  423. // 4.2. If sandboxingFlagSet's sandboxed navigation browsing
  424. // context flag is set, then current must be set as chosen's one
  425. // permitted sandboxed navigator.
  426. // 5. If sandboxingFlagSet's sandbox propagates to auxiliary
  427. // browsing contexts flag is set, then all the flags that are set in
  428. // sandboxingFlagSet must be set in chosen's popup sandboxing flag
  429. // set.
  430. // 6. If name is not an ASCII case-insensitive match for "_blank",
  431. // then set chosen's name to name.
  432. // --> If the user agent has been configured such that in this instance
  433. // it will reuse current
  434. //
  435. // Set chosen to current.
  436. // --> If the user agent has been configured such that in this instance
  437. // it will not find a browsing context
  438. //
  439. // Do nothing.
  440. }
  441. // 9. Return chosen and windowType.
  442. return chosen;
  443. }
  444. }