Document.cpp 31 KB

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