Document.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Luke Wilde <lukew@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/CharacterTypes.h>
  9. #include <AK/StringBuilder.h>
  10. #include <AK/Utf8View.h>
  11. #include <LibCore/Timer.h>
  12. #include <LibJS/Interpreter.h>
  13. #include <LibJS/Parser.h>
  14. #include <LibJS/Runtime/FunctionObject.h>
  15. #include <LibWeb/Bindings/MainThreadVM.h>
  16. #include <LibWeb/Bindings/WindowObject.h>
  17. #include <LibWeb/CSS/StyleComputer.h>
  18. #include <LibWeb/Cookie/ParsedCookie.h>
  19. #include <LibWeb/DOM/Comment.h>
  20. #include <LibWeb/DOM/CustomEvent.h>
  21. #include <LibWeb/DOM/DOMException.h>
  22. #include <LibWeb/DOM/Document.h>
  23. #include <LibWeb/DOM/DocumentFragment.h>
  24. #include <LibWeb/DOM/DocumentType.h>
  25. #include <LibWeb/DOM/Element.h>
  26. #include <LibWeb/DOM/ElementFactory.h>
  27. #include <LibWeb/DOM/Event.h>
  28. #include <LibWeb/DOM/ExceptionOr.h>
  29. #include <LibWeb/DOM/HTMLCollection.h>
  30. #include <LibWeb/DOM/Range.h>
  31. #include <LibWeb/DOM/ShadowRoot.h>
  32. #include <LibWeb/DOM/Text.h>
  33. #include <LibWeb/DOM/Window.h>
  34. #include <LibWeb/Dump.h>
  35. #include <LibWeb/HTML/AttributeNames.h>
  36. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  37. #include <LibWeb/HTML/EventNames.h>
  38. #include <LibWeb/HTML/HTMLAnchorElement.h>
  39. #include <LibWeb/HTML/HTMLAreaElement.h>
  40. #include <LibWeb/HTML/HTMLBodyElement.h>
  41. #include <LibWeb/HTML/HTMLEmbedElement.h>
  42. #include <LibWeb/HTML/HTMLFormElement.h>
  43. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  44. #include <LibWeb/HTML/HTMLHeadElement.h>
  45. #include <LibWeb/HTML/HTMLHtmlElement.h>
  46. #include <LibWeb/HTML/HTMLIFrameElement.h>
  47. #include <LibWeb/HTML/HTMLImageElement.h>
  48. #include <LibWeb/HTML/HTMLScriptElement.h>
  49. #include <LibWeb/HTML/HTMLTitleElement.h>
  50. #include <LibWeb/HTML/MessageEvent.h>
  51. #include <LibWeb/Layout/BlockFormattingContext.h>
  52. #include <LibWeb/Layout/InitialContainingBlock.h>
  53. #include <LibWeb/Layout/TreeBuilder.h>
  54. #include <LibWeb/Namespace.h>
  55. #include <LibWeb/Origin.h>
  56. #include <LibWeb/Page/BrowsingContext.h>
  57. #include <LibWeb/Page/Page.h>
  58. #include <LibWeb/SVG/TagNames.h>
  59. #include <LibWeb/UIEvents/KeyboardEvent.h>
  60. #include <LibWeb/UIEvents/MouseEvent.h>
  61. namespace Web::DOM {
  62. Document::Document(const AK::URL& url)
  63. : ParentNode(*this, NodeType::DOCUMENT_NODE)
  64. , m_style_computer(make<CSS::StyleComputer>(*this))
  65. , m_style_sheets(CSS::StyleSheetList::create(*this))
  66. , m_url(url)
  67. , m_window(Window::create_with_document(*this))
  68. , m_implementation(DOMImplementation::create(*this))
  69. , m_history(HTML::History::create(*this))
  70. {
  71. HTML::main_thread_event_loop().register_document({}, *this);
  72. m_style_update_timer = Core::Timer::create_single_shot(0, [this] {
  73. update_style();
  74. });
  75. m_forced_layout_timer = Core::Timer::create_single_shot(0, [this] {
  76. force_layout();
  77. });
  78. }
  79. Document::~Document()
  80. {
  81. }
  82. void Document::removed_last_ref()
  83. {
  84. VERIFY(!ref_count());
  85. VERIFY(!m_deletion_has_begun);
  86. if (m_referencing_node_count) {
  87. // The document has reached ref_count==0 but still has nodes keeping it alive.
  88. // At this point, sever all the node links we control.
  89. // If nodes remain elsewhere (e.g JS wrappers), they will keep the document alive.
  90. // NOTE: This makes sure we stay alive across for the duration of the cleanup below.
  91. increment_referencing_node_count();
  92. m_focused_element = nullptr;
  93. m_hovered_node = nullptr;
  94. m_pending_parsing_blocking_script = nullptr;
  95. m_inspected_node = nullptr;
  96. m_scripts_to_execute_when_parsing_has_finished.clear();
  97. m_scripts_to_execute_as_soon_as_possible.clear();
  98. m_associated_inert_template_document = nullptr;
  99. m_interpreter = nullptr;
  100. {
  101. // Gather up all the descendants of this document and prune them from the tree.
  102. // FIXME: This could definitely be more elegant.
  103. NonnullRefPtrVector<Node> descendants;
  104. for_each_in_inclusive_subtree([&](auto& node) {
  105. if (&node != this)
  106. descendants.append(node);
  107. return IterationDecision::Continue;
  108. });
  109. for (auto& node : descendants) {
  110. VERIFY(&node.document() == this);
  111. VERIFY(!node.is_document());
  112. if (node.parent())
  113. node.remove();
  114. }
  115. }
  116. m_in_removed_last_ref = false;
  117. decrement_referencing_node_count();
  118. return;
  119. }
  120. m_in_removed_last_ref = false;
  121. m_deletion_has_begun = true;
  122. HTML::main_thread_event_loop().unregister_document({}, *this);
  123. delete this;
  124. }
  125. Origin Document::origin() const
  126. {
  127. if (!m_url.is_valid())
  128. return {};
  129. return { m_url.protocol(), m_url.host(), m_url.port_or_default() };
  130. }
  131. void Document::set_origin(const Origin& origin)
  132. {
  133. m_url.set_protocol(origin.protocol());
  134. m_url.set_host(origin.host());
  135. m_url.set_port(origin.port());
  136. }
  137. void Document::schedule_style_update()
  138. {
  139. if (m_style_update_timer->is_active())
  140. return;
  141. m_style_update_timer->start();
  142. }
  143. void Document::schedule_forced_layout()
  144. {
  145. if (m_forced_layout_timer->is_active())
  146. return;
  147. m_forced_layout_timer->start();
  148. }
  149. bool Document::is_child_allowed(const Node& node) const
  150. {
  151. switch (node.type()) {
  152. case NodeType::DOCUMENT_NODE:
  153. case NodeType::TEXT_NODE:
  154. return false;
  155. case NodeType::COMMENT_NODE:
  156. return true;
  157. case NodeType::DOCUMENT_TYPE_NODE:
  158. return !first_child_of_type<DocumentType>();
  159. case NodeType::ELEMENT_NODE:
  160. return !first_child_of_type<Element>();
  161. default:
  162. return false;
  163. }
  164. }
  165. Element* Document::document_element()
  166. {
  167. return first_child_of_type<Element>();
  168. }
  169. const Element* Document::document_element() const
  170. {
  171. return first_child_of_type<Element>();
  172. }
  173. HTML::HTMLHtmlElement* Document::html_element()
  174. {
  175. auto* html = document_element();
  176. if (is<HTML::HTMLHtmlElement>(html))
  177. return verify_cast<HTML::HTMLHtmlElement>(html);
  178. return nullptr;
  179. }
  180. HTML::HTMLHeadElement* Document::head()
  181. {
  182. auto* html = html_element();
  183. if (!html)
  184. return nullptr;
  185. return html->first_child_of_type<HTML::HTMLHeadElement>();
  186. }
  187. HTML::HTMLElement* Document::body()
  188. {
  189. auto* html = html_element();
  190. if (!html)
  191. return nullptr;
  192. auto* first_body = html->first_child_of_type<HTML::HTMLBodyElement>();
  193. if (first_body)
  194. return first_body;
  195. auto* first_frameset = html->first_child_of_type<HTML::HTMLFrameSetElement>();
  196. if (first_frameset)
  197. return first_frameset;
  198. return nullptr;
  199. }
  200. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
  201. ExceptionOr<void> Document::set_body(HTML::HTMLElement* new_body)
  202. {
  203. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body))
  204. return DOM::HierarchyRequestError::create("Invalid document body element, must be 'body' or 'frameset'");
  205. auto* existing_body = body();
  206. if (existing_body) {
  207. auto replace_result = existing_body->parent()->replace_child(*new_body, *existing_body);
  208. if (replace_result.is_exception())
  209. return replace_result.exception();
  210. return {};
  211. }
  212. auto* document_element = this->document_element();
  213. if (!document_element)
  214. return DOM::HierarchyRequestError::create("Missing document element");
  215. auto append_result = document_element->append_child(*new_body);
  216. if (append_result.is_exception())
  217. return append_result.exception();
  218. return {};
  219. }
  220. String Document::title() const
  221. {
  222. auto* head_element = head();
  223. if (!head_element)
  224. return {};
  225. auto* title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  226. if (!title_element)
  227. return {};
  228. auto raw_title = title_element->text_content();
  229. StringBuilder builder;
  230. bool last_was_space = false;
  231. for (auto code_point : Utf8View(raw_title)) {
  232. if (is_ascii_space(code_point)) {
  233. last_was_space = true;
  234. } else {
  235. if (last_was_space && !builder.is_empty())
  236. builder.append(' ');
  237. builder.append_code_point(code_point);
  238. last_was_space = false;
  239. }
  240. }
  241. return builder.to_string();
  242. }
  243. void Document::set_title(const String& title)
  244. {
  245. auto* head_element = const_cast<HTML::HTMLHeadElement*>(head());
  246. if (!head_element)
  247. return;
  248. RefPtr<HTML::HTMLTitleElement> title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  249. if (!title_element) {
  250. title_element = static_ptr_cast<HTML::HTMLTitleElement>(create_element(HTML::TagNames::title));
  251. head_element->append_child(*title_element);
  252. }
  253. title_element->remove_all_children(true);
  254. title_element->append_child(adopt_ref(*new Text(*this, title)));
  255. if (auto* page = this->page()) {
  256. if (browsing_context() == &page->top_level_browsing_context())
  257. page->client().page_did_change_title(title);
  258. }
  259. }
  260. void Document::attach_to_browsing_context(Badge<BrowsingContext>, BrowsingContext& browsing_context)
  261. {
  262. m_browsing_context = browsing_context;
  263. update_layout();
  264. }
  265. void Document::detach_from_browsing_context(Badge<BrowsingContext>, BrowsingContext& browsing_context)
  266. {
  267. VERIFY(&browsing_context == m_browsing_context);
  268. tear_down_layout_tree();
  269. m_browsing_context = nullptr;
  270. }
  271. void Document::tear_down_layout_tree()
  272. {
  273. if (!m_layout_root)
  274. return;
  275. // Gather up all the layout nodes in a vector and detach them from parents
  276. // while the vector keeps them alive.
  277. NonnullRefPtrVector<Layout::Node> layout_nodes;
  278. m_layout_root->for_each_in_inclusive_subtree([&](auto& layout_node) {
  279. layout_nodes.append(layout_node);
  280. return IterationDecision::Continue;
  281. });
  282. for (auto& layout_node : layout_nodes) {
  283. if (layout_node.parent())
  284. layout_node.parent()->remove_child(layout_node);
  285. }
  286. m_layout_root = nullptr;
  287. }
  288. Color Document::background_color(const Palette& palette) const
  289. {
  290. auto default_color = palette.base();
  291. auto* body_element = body();
  292. if (!body_element)
  293. return default_color;
  294. auto* body_layout_node = body_element->layout_node();
  295. if (!body_layout_node)
  296. return default_color;
  297. auto color = body_layout_node->computed_values().background_color();
  298. if (!color.alpha())
  299. return default_color;
  300. return color;
  301. }
  302. RefPtr<Gfx::Bitmap> Document::background_image() const
  303. {
  304. auto* body_element = body();
  305. if (!body_element)
  306. return {};
  307. auto* body_layout_node = body_element->layout_node();
  308. if (!body_layout_node)
  309. return {};
  310. auto background_image = body_layout_node->background_image();
  311. if (!background_image)
  312. return {};
  313. return background_image->bitmap();
  314. }
  315. CSS::Repeat Document::background_repeat_x() const
  316. {
  317. auto* body_element = body();
  318. if (!body_element)
  319. return CSS::Repeat::Repeat;
  320. auto* body_layout_node = body_element->layout_node();
  321. if (!body_layout_node)
  322. return CSS::Repeat::Repeat;
  323. return body_layout_node->computed_values().background_repeat_x();
  324. }
  325. CSS::Repeat Document::background_repeat_y() const
  326. {
  327. auto* body_element = body();
  328. if (!body_element)
  329. return CSS::Repeat::Repeat;
  330. auto* body_layout_node = body_element->layout_node();
  331. if (!body_layout_node)
  332. return CSS::Repeat::Repeat;
  333. return body_layout_node->computed_values().background_repeat_y();
  334. }
  335. // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#parse-a-url
  336. AK::URL Document::parse_url(String const& url) const
  337. {
  338. // FIXME: Make sure we do this according to spec.
  339. return m_url.complete_url(url);
  340. }
  341. void Document::invalidate_layout()
  342. {
  343. tear_down_layout_tree();
  344. }
  345. void Document::force_layout()
  346. {
  347. invalidate_layout();
  348. update_layout();
  349. }
  350. void Document::ensure_layout()
  351. {
  352. if (!m_layout_root)
  353. update_layout();
  354. }
  355. void Document::update_layout()
  356. {
  357. if (!browsing_context())
  358. return;
  359. if (!m_layout_root) {
  360. Layout::TreeBuilder tree_builder;
  361. m_layout_root = static_ptr_cast<Layout::InitialContainingBlock>(tree_builder.build(*this));
  362. }
  363. Layout::BlockFormattingContext root_formatting_context(*m_layout_root, nullptr);
  364. root_formatting_context.run(*m_layout_root, Layout::LayoutMode::Default);
  365. m_layout_root->set_needs_display();
  366. if (browsing_context()->is_top_level()) {
  367. if (auto* page = this->page())
  368. page->client().page_did_layout();
  369. }
  370. }
  371. static void update_style_recursively(DOM::Node& node)
  372. {
  373. node.for_each_child([&](auto& child) {
  374. if (child.needs_style_update()) {
  375. if (is<Element>(child))
  376. verify_cast<Element>(child).recompute_style();
  377. child.set_needs_style_update(false);
  378. }
  379. if (child.child_needs_style_update()) {
  380. update_style_recursively(child);
  381. child.set_child_needs_style_update(false);
  382. }
  383. return IterationDecision::Continue;
  384. });
  385. }
  386. void Document::update_style()
  387. {
  388. if (!browsing_context())
  389. return;
  390. update_style_recursively(*this);
  391. update_layout();
  392. }
  393. RefPtr<Layout::Node> Document::create_layout_node()
  394. {
  395. return adopt_ref(*new Layout::InitialContainingBlock(*this, style_computer().create_document_style()));
  396. }
  397. void Document::set_link_color(Color color)
  398. {
  399. m_link_color = color;
  400. }
  401. void Document::set_active_link_color(Color color)
  402. {
  403. m_active_link_color = color;
  404. }
  405. void Document::set_visited_link_color(Color color)
  406. {
  407. m_visited_link_color = color;
  408. }
  409. const Layout::InitialContainingBlock* Document::layout_node() const
  410. {
  411. return static_cast<const Layout::InitialContainingBlock*>(Node::layout_node());
  412. }
  413. Layout::InitialContainingBlock* Document::layout_node()
  414. {
  415. return static_cast<Layout::InitialContainingBlock*>(Node::layout_node());
  416. }
  417. void Document::set_inspected_node(Node* node)
  418. {
  419. if (m_inspected_node == node)
  420. return;
  421. if (m_inspected_node && m_inspected_node->layout_node())
  422. m_inspected_node->layout_node()->set_needs_display();
  423. m_inspected_node = node;
  424. if (m_inspected_node && m_inspected_node->layout_node())
  425. m_inspected_node->layout_node()->set_needs_display();
  426. }
  427. void Document::set_hovered_node(Node* node)
  428. {
  429. if (m_hovered_node == node)
  430. return;
  431. RefPtr<Node> old_hovered_node = move(m_hovered_node);
  432. m_hovered_node = node;
  433. invalidate_style();
  434. }
  435. NonnullRefPtr<HTMLCollection> Document::get_elements_by_name(String const& name)
  436. {
  437. return HTMLCollection::create(*this, [name](Element const& element) {
  438. return element.name() == name;
  439. });
  440. }
  441. NonnullRefPtr<HTMLCollection> Document::get_elements_by_class_name(FlyString const& class_name)
  442. {
  443. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  444. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  445. });
  446. }
  447. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-applets
  448. NonnullRefPtr<HTMLCollection> Document::applets()
  449. {
  450. // FIXME: This should return the same HTMLCollection object every time,
  451. // but that would cause a reference cycle since HTMLCollection refs the root.
  452. return HTMLCollection::create(*this, [](auto&) { return false; });
  453. }
  454. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-anchors
  455. NonnullRefPtr<HTMLCollection> Document::anchors()
  456. {
  457. // FIXME: This should return the same HTMLCollection object every time,
  458. // but that would cause a reference cycle since HTMLCollection refs the root.
  459. return HTMLCollection::create(*this, [](Element const& element) {
  460. return is<HTML::HTMLAnchorElement>(element) && element.has_attribute(HTML::AttributeNames::name);
  461. });
  462. }
  463. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-images
  464. NonnullRefPtr<HTMLCollection> Document::images()
  465. {
  466. // FIXME: This should return the same HTMLCollection object every time,
  467. // but that would cause a reference cycle since HTMLCollection refs the root.
  468. return HTMLCollection::create(*this, [](Element const& element) {
  469. return is<HTML::HTMLImageElement>(element);
  470. });
  471. }
  472. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-embeds
  473. NonnullRefPtr<HTMLCollection> Document::embeds()
  474. {
  475. // FIXME: This should return the same HTMLCollection object every time,
  476. // but that would cause a reference cycle since HTMLCollection refs the root.
  477. return HTMLCollection::create(*this, [](Element const& element) {
  478. return is<HTML::HTMLEmbedElement>(element);
  479. });
  480. }
  481. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-plugins
  482. NonnullRefPtr<HTMLCollection> Document::plugins()
  483. {
  484. return embeds();
  485. }
  486. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-links
  487. NonnullRefPtr<HTMLCollection> Document::links()
  488. {
  489. // FIXME: This should return the same HTMLCollection object every time,
  490. // but that would cause a reference cycle since HTMLCollection refs the root.
  491. return HTMLCollection::create(*this, [](Element const& element) {
  492. return (is<HTML::HTMLAnchorElement>(element) || is<HTML::HTMLAreaElement>(element)) && element.has_attribute(HTML::AttributeNames::href);
  493. });
  494. }
  495. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-forms
  496. NonnullRefPtr<HTMLCollection> Document::forms()
  497. {
  498. // FIXME: This should return the same HTMLCollection object every time,
  499. // but that would cause a reference cycle since HTMLCollection refs the root.
  500. return HTMLCollection::create(*this, [](Element const& element) {
  501. return is<HTML::HTMLFormElement>(element);
  502. });
  503. }
  504. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-scripts
  505. NonnullRefPtr<HTMLCollection> Document::scripts()
  506. {
  507. // FIXME: This should return the same HTMLCollection object every time,
  508. // but that would cause a reference cycle since HTMLCollection refs the root.
  509. return HTMLCollection::create(*this, [](Element const& element) {
  510. return is<HTML::HTMLScriptElement>(element);
  511. });
  512. }
  513. Color Document::link_color() const
  514. {
  515. if (m_link_color.has_value())
  516. return m_link_color.value();
  517. if (!page())
  518. return Color::Blue;
  519. return page()->palette().link();
  520. }
  521. Color Document::active_link_color() const
  522. {
  523. if (m_active_link_color.has_value())
  524. return m_active_link_color.value();
  525. if (!page())
  526. return Color::Red;
  527. return page()->palette().active_link();
  528. }
  529. Color Document::visited_link_color() const
  530. {
  531. if (m_visited_link_color.has_value())
  532. return m_visited_link_color.value();
  533. if (!page())
  534. return Color::Magenta;
  535. return page()->palette().visited_link();
  536. }
  537. JS::Realm& Document::realm()
  538. {
  539. return interpreter().realm();
  540. }
  541. JS::Interpreter& Document::interpreter()
  542. {
  543. if (!m_interpreter) {
  544. auto& vm = Bindings::main_thread_vm();
  545. m_interpreter = JS::Interpreter::create<Bindings::WindowObject>(vm, *m_window);
  546. // NOTE: We must hook `on_call_stack_emptied` after the interpreter was created, as the initialization of the
  547. // WindowsObject can invoke some internal calls, which will eventually lead to this hook being called without
  548. // `m_interpreter` being fully initialized yet.
  549. // TODO: Hook up vm.on_promise_unhandled_rejection and vm.on_promise_rejection_handled
  550. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events
  551. vm.on_call_stack_emptied = [this] {
  552. auto& vm = m_interpreter->vm();
  553. vm.run_queued_promise_jobs();
  554. vm.run_queued_finalization_registry_cleanup_jobs();
  555. // FIXME: This isn't exactly the right place for this.
  556. HTML::main_thread_event_loop().perform_a_microtask_checkpoint();
  557. // Note: This is not an exception check for the promise jobs, they will just leave any
  558. // exception that already exists intact and never throw a new one (without cleaning it
  559. // up, that is). Taking care of any previous unhandled exception just happens to be the
  560. // very last thing we want to do, even after running promise jobs.
  561. if (auto* exception = vm.exception()) {
  562. auto value = exception->value();
  563. if (value.is_object()) {
  564. auto& object = value.as_object();
  565. auto name = object.get_without_side_effects(vm.names.name).value_or(JS::js_undefined());
  566. auto message = object.get_without_side_effects(vm.names.message).value_or(JS::js_undefined());
  567. if (name.is_accessor() || message.is_accessor()) {
  568. // The result is not going to be useful, let's just print the value. This affects DOMExceptions, for example.
  569. dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m {}", value);
  570. } else {
  571. dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m [{}] {}", name, message);
  572. }
  573. } else {
  574. dbgln("\033[31;1mUnhandled JavaScript exception:\033[0m {}", value);
  575. }
  576. for (auto& traceback_frame : exception->traceback()) {
  577. auto& function_name = traceback_frame.function_name;
  578. auto& source_range = traceback_frame.source_range;
  579. dbgln(" {} at {}:{}:{}", function_name, source_range.filename, source_range.start.line, source_range.start.column);
  580. }
  581. }
  582. vm.finish_execution_generation();
  583. };
  584. }
  585. return *m_interpreter;
  586. }
  587. JS::Value Document::run_javascript(const StringView& source, const StringView& filename)
  588. {
  589. auto parser = JS::Parser(JS::Lexer(source, filename));
  590. auto program = parser.parse_program();
  591. if (parser.has_errors()) {
  592. parser.print_errors(false);
  593. return JS::js_undefined();
  594. }
  595. auto& interpreter = document().interpreter();
  596. auto& vm = interpreter.vm();
  597. interpreter.run(interpreter.global_object(), *program);
  598. if (vm.exception())
  599. vm.clear_exception();
  600. return vm.last_value();
  601. }
  602. // https://dom.spec.whatwg.org/#dom-document-createelement
  603. // FIXME: This only implements step 6 of the algorithm and does not take in options.
  604. NonnullRefPtr<Element> Document::create_element(const String& tag_name)
  605. {
  606. // FIXME: Let namespace be the HTML namespace, if this is an HTML document or this’s content type is "application/xhtml+xml", and null otherwise.
  607. return DOM::create_element(*this, tag_name, Namespace::HTML);
  608. }
  609. // https://dom.spec.whatwg.org/#internal-createelementns-steps
  610. // FIXME: This only implements step 4 of the algorithm and does not take in options.
  611. NonnullRefPtr<Element> Document::create_element_ns(const String& namespace_, const String& qualified_name)
  612. {
  613. return DOM::create_element(*this, qualified_name, namespace_);
  614. }
  615. NonnullRefPtr<DocumentFragment> Document::create_document_fragment()
  616. {
  617. return adopt_ref(*new DocumentFragment(*this));
  618. }
  619. NonnullRefPtr<Text> Document::create_text_node(const String& data)
  620. {
  621. return adopt_ref(*new Text(*this, data));
  622. }
  623. NonnullRefPtr<Comment> Document::create_comment(const String& data)
  624. {
  625. return adopt_ref(*new Comment(*this, data));
  626. }
  627. NonnullRefPtr<Range> Document::create_range()
  628. {
  629. return Range::create(*this);
  630. }
  631. // https://dom.spec.whatwg.org/#dom-document-createevent
  632. NonnullRefPtr<Event> Document::create_event(const String& interface)
  633. {
  634. auto interface_lowercase = interface.to_lowercase();
  635. RefPtr<Event> event;
  636. if (interface_lowercase == "beforeunloadevent") {
  637. event = Event::create(""); // FIXME: Create BeforeUnloadEvent
  638. } else if (interface_lowercase == "compositionevent") {
  639. event = Event::create(""); // FIXME: Create CompositionEvent
  640. } else if (interface_lowercase == "customevent") {
  641. event = CustomEvent::create("");
  642. } else if (interface_lowercase == "devicemotionevent") {
  643. event = Event::create(""); // FIXME: Create DeviceMotionEvent
  644. } else if (interface_lowercase == "deviceorientationevent") {
  645. event = Event::create(""); // FIXME: Create DeviceOrientationEvent
  646. } else if (interface_lowercase == "dragevent") {
  647. event = Event::create(""); // FIXME: Create DragEvent
  648. } else if (interface_lowercase.is_one_of("event", "events")) {
  649. event = Event::create("");
  650. } else if (interface_lowercase == "focusevent") {
  651. event = Event::create(""); // FIXME: Create FocusEvent
  652. } else if (interface_lowercase == "hashchangeevent") {
  653. event = Event::create(""); // FIXME: Create HashChangeEvent
  654. } else if (interface_lowercase == "htmlevents") {
  655. event = Event::create("");
  656. } else if (interface_lowercase == "keyboardevent") {
  657. event = UIEvents::KeyboardEvent::create("");
  658. } else if (interface_lowercase == "messageevent") {
  659. event = HTML::MessageEvent::create("");
  660. } else if (interface_lowercase.is_one_of("mouseevent", "mouseevents")) {
  661. event = UIEvents::MouseEvent::create("", 0, 0, 0, 0);
  662. } else if (interface_lowercase == "storageevent") {
  663. event = Event::create(""); // FIXME: Create StorageEvent
  664. } else if (interface_lowercase == "svgevents") {
  665. event = Event::create("");
  666. } else if (interface_lowercase == "textevent") {
  667. event = Event::create(""); // FIXME: Create CompositionEvent
  668. } else if (interface_lowercase == "touchevent") {
  669. event = Event::create(""); // FIXME: Create TouchEvent
  670. } else if (interface_lowercase.is_one_of("uievent", "uievents")) {
  671. event = UIEvents::UIEvent::create("");
  672. } else {
  673. // FIXME:
  674. // 3. If constructor is null, then throw a "NotSupportedError" DOMException.
  675. // 4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "NotSupportedError" DOMException.
  676. TODO();
  677. }
  678. // Setting type to empty string is handled by each constructor.
  679. // FIXME:
  680. // 7. Initialize event’s timeStamp attribute to a DOMHighResTimeStamp representing the high resolution time from the time origin to now.
  681. event->set_is_trusted(false);
  682. event->set_initialized(false);
  683. return event.release_nonnull();
  684. }
  685. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  686. {
  687. m_pending_parsing_blocking_script = script;
  688. }
  689. NonnullRefPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLParser>)
  690. {
  691. return m_pending_parsing_blocking_script.release_nonnull();
  692. }
  693. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  694. {
  695. m_scripts_to_execute_when_parsing_has_finished.append(script);
  696. }
  697. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLParser>)
  698. {
  699. return move(m_scripts_to_execute_when_parsing_has_finished);
  700. }
  701. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  702. {
  703. m_scripts_to_execute_as_soon_as_possible.append(script);
  704. }
  705. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLParser>)
  706. {
  707. return move(m_scripts_to_execute_as_soon_as_possible);
  708. }
  709. // https://dom.spec.whatwg.org/#dom-document-importnode
  710. ExceptionOr<NonnullRefPtr<Node>> Document::import_node(NonnullRefPtr<Node> node, bool deep)
  711. {
  712. // 1. If node is a document or shadow root, then throw a "NotSupportedError" DOMException.
  713. if (is<Document>(*node) || is<ShadowRoot>(*node))
  714. return DOM::NotSupportedError::create("Cannot import a document or shadow root.");
  715. // 2. Return a clone of node, with this and the clone children flag set if deep is true.
  716. return node->clone_node(this, deep);
  717. }
  718. // https://dom.spec.whatwg.org/#concept-node-adopt
  719. void Document::adopt_node(Node& node)
  720. {
  721. auto& old_document = node.document();
  722. if (node.parent())
  723. node.remove();
  724. if (&old_document != this) {
  725. // FIXME: This should be shadow-including.
  726. node.for_each_in_inclusive_subtree([&](auto& inclusive_descendant) {
  727. inclusive_descendant.set_document({}, *this);
  728. // FIXME: If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.
  729. return IterationDecision::Continue;
  730. });
  731. // FIXME: For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom,
  732. // enqueue a custom element callback reaction with inclusiveDescendant, callback name "adoptedCallback",
  733. // and an argument list containing oldDocument and document.
  734. // FIXME: This should be shadow-including.
  735. node.for_each_in_inclusive_subtree([&](auto& inclusive_descendant) {
  736. inclusive_descendant.adopted_from(old_document);
  737. return IterationDecision::Continue;
  738. });
  739. }
  740. }
  741. // https://dom.spec.whatwg.org/#dom-document-adoptnode
  742. ExceptionOr<NonnullRefPtr<Node>> Document::adopt_node_binding(NonnullRefPtr<Node> node)
  743. {
  744. if (is<Document>(*node))
  745. return DOM::NotSupportedError::create("Cannot adopt a document into a document");
  746. if (is<ShadowRoot>(*node))
  747. return DOM::HierarchyRequestError::create("Cannot adopt a shadow root into a document");
  748. if (is<DocumentFragment>(*node) && verify_cast<DocumentFragment>(*node).host())
  749. return node;
  750. adopt_node(*node);
  751. return node;
  752. }
  753. const DocumentType* Document::doctype() const
  754. {
  755. return first_child_of_type<DocumentType>();
  756. }
  757. const String& Document::compat_mode() const
  758. {
  759. static String back_compat = "BackCompat";
  760. static String css1_compat = "CSS1Compat";
  761. if (m_quirks_mode == QuirksMode::Yes)
  762. return back_compat;
  763. return css1_compat;
  764. }
  765. bool Document::is_editable() const
  766. {
  767. return m_editable;
  768. }
  769. void Document::set_focused_element(Element* element)
  770. {
  771. if (m_focused_element == element)
  772. return;
  773. m_focused_element = element;
  774. if (m_layout_root)
  775. m_layout_root->set_needs_display();
  776. }
  777. void Document::set_active_element(Element* element)
  778. {
  779. if (m_active_element == element)
  780. return;
  781. m_active_element = element;
  782. if (m_layout_root)
  783. m_layout_root->set_needs_display();
  784. }
  785. String Document::ready_state() const
  786. {
  787. switch (m_readiness) {
  788. case HTML::DocumentReadyState::Loading:
  789. return "loading"sv;
  790. case HTML::DocumentReadyState::Interactive:
  791. return "interactive"sv;
  792. case HTML::DocumentReadyState::Complete:
  793. return "complete"sv;
  794. }
  795. VERIFY_NOT_REACHED();
  796. }
  797. // https://html.spec.whatwg.org/#update-the-current-document-readiness
  798. void Document::update_readiness(HTML::DocumentReadyState readiness_value)
  799. {
  800. // 1. If document's current document readiness equals readinessValue, then return.
  801. if (m_readiness == readiness_value)
  802. return;
  803. // The spec doesn't actually mention updating the current readiness value.
  804. // FIXME: https://github.com/whatwg/html/issues/7120
  805. m_readiness = readiness_value;
  806. // FIXME: 2. If document is associated with an HTML parser, then:
  807. // FIXME: 1. If document is associated with an HTML parser, then:
  808. // FIXME: 2. If readinessValue is "complete", and document's load timing info's DOM complete time is 0, then set document's load timing info's DOM complete time to now.
  809. // FIXME: 3. Otherwise, if readinessValue is "interactive", and document's load timing info's DOM interactive time is 0, then set document's load timing info's DOM interactive time to now.
  810. // 3. Fire an event named readystatechange at document.
  811. dispatch_event(Event::create(HTML::EventNames::readystatechange));
  812. }
  813. Page* Document::page()
  814. {
  815. return m_browsing_context ? m_browsing_context->page() : nullptr;
  816. }
  817. const Page* Document::page() const
  818. {
  819. return m_browsing_context ? m_browsing_context->page() : nullptr;
  820. }
  821. EventTarget* Document::get_parent(const Event& event)
  822. {
  823. if (event.type() == HTML::EventNames::load)
  824. return nullptr;
  825. return &window();
  826. }
  827. // https://html.spec.whatwg.org/multipage/browsing-the-web.html#completely-finish-loading
  828. void Document::completely_finish_loading()
  829. {
  830. // 1. Assert: document's browsing context is non-null.
  831. VERIFY(browsing_context());
  832. // FIXME: 2. Set document's completely loaded time to the current time.
  833. // 3. Let container be document's browsing context's container.
  834. auto* container = browsing_context()->container();
  835. // If container is an iframe element, then queue an element task on the DOM manipulation task source given container to run the iframe load event steps given container.
  836. if (container && is<HTML::HTMLIFrameElement>(*container)) {
  837. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container]() mutable {
  838. run_iframe_load_event_steps(static_cast<HTML::HTMLIFrameElement&>(*container));
  839. });
  840. }
  841. // Otherwise, if container is non-null, then queue an element task on the DOM manipulation task source given container to fire an event named load at container.
  842. else if (container) {
  843. container->queue_an_element_task(HTML::Task::Source::DOMManipulation, [container]() mutable {
  844. container->dispatch_event(DOM::Event::create(HTML::EventNames::load));
  845. });
  846. }
  847. }
  848. String Document::cookie(Cookie::Source source)
  849. {
  850. if (auto* page = this->page())
  851. return page->client().page_did_request_cookie(m_url, source);
  852. return {};
  853. }
  854. void Document::set_cookie(String cookie_string, Cookie::Source source)
  855. {
  856. auto cookie = Cookie::parse_cookie(cookie_string);
  857. if (!cookie.has_value())
  858. return;
  859. if (auto* page = this->page())
  860. page->client().page_did_set_cookie(m_url, cookie.value(), source);
  861. }
  862. String Document::dump_dom_tree_as_json() const
  863. {
  864. StringBuilder builder;
  865. JsonObjectSerializer json(builder);
  866. serialize_tree_as_json(json);
  867. json.finish();
  868. return builder.to_string();
  869. }
  870. // https://html.spec.whatwg.org/multipage/semantics.html#has-a-style-sheet-that-is-blocking-scripts
  871. bool Document::has_a_style_sheet_that_is_blocking_scripts() const
  872. {
  873. // A Document has a style sheet that is blocking scripts if its script-blocking style sheet counter is greater than 0,
  874. if (m_script_blocking_style_sheet_counter > 0)
  875. return true;
  876. // ...or if that Document has a non-null browsing context whose container document is non-null and has a script-blocking style sheet counter greater than 0.
  877. if (!browsing_context() || !browsing_context()->container_document())
  878. return false;
  879. return browsing_context()->container_document()->m_script_blocking_style_sheet_counter > 0;
  880. }
  881. String Document::referrer() const
  882. {
  883. // FIXME: Return the document's actual referrer.
  884. return "";
  885. }
  886. // https://html.spec.whatwg.org/multipage/browsers.html#fully-active
  887. bool Document::is_fully_active() const
  888. {
  889. // A Document d is said to be fully active when d's browsing context is non-null, d's browsing context's active document is d,
  890. // and either d's browsing context is a top-level browsing context, or d's browsing context's container document is fully active.
  891. return browsing_context() && browsing_context()->active_document() == this && (browsing_context()->is_top_level() || browsing_context()->container_document()->is_fully_active());
  892. }
  893. // https://html.spec.whatwg.org/multipage/browsers.html#active-document
  894. bool Document::is_active() const
  895. {
  896. // A browsing context's active document is its active window's associated Document.
  897. return browsing_context() && browsing_context()->active_document() == this;
  898. }
  899. // https://html.spec.whatwg.org/multipage/history.html#dom-document-location
  900. Bindings::LocationObject* Document::location()
  901. {
  902. // The Document object's location attribute's getter must return this Document object's relevant global object's Location object,
  903. // if this Document object is fully active, and null otherwise.
  904. if (!is_fully_active())
  905. return nullptr;
  906. return window().wrapper()->location_object();
  907. }
  908. // https://w3c.github.io/page-visibility/#hidden-attribute
  909. bool Document::hidden() const
  910. {
  911. return false;
  912. }
  913. // https://w3c.github.io/page-visibility/#visibilitystate-attribute
  914. String Document::visibility_state() const
  915. {
  916. return hidden() ? "hidden" : "visible";
  917. }
  918. }