Document.cpp 33 KB

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