BrowsingContext.cpp 60 KB

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