Document.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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 AK::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_or_default() };
  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. AK::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::ensure_layout()
  344. {
  345. if (!m_layout_root)
  346. update_layout();
  347. }
  348. void Document::update_layout()
  349. {
  350. if (!browsing_context())
  351. return;
  352. if (!m_layout_root) {
  353. Layout::TreeBuilder tree_builder;
  354. m_layout_root = static_ptr_cast<Layout::InitialContainingBlock>(tree_builder.build(*this));
  355. }
  356. Layout::BlockFormattingContext root_formatting_context(*m_layout_root, nullptr);
  357. root_formatting_context.run(*m_layout_root, Layout::LayoutMode::Default);
  358. m_layout_root->set_needs_display();
  359. if (browsing_context()->is_top_level()) {
  360. if (auto* page = this->page())
  361. page->client().page_did_layout();
  362. }
  363. }
  364. static void update_style_recursively(DOM::Node& node)
  365. {
  366. node.for_each_child([&](auto& child) {
  367. if (child.needs_style_update()) {
  368. if (is<Element>(child))
  369. verify_cast<Element>(child).recompute_style();
  370. child.set_needs_style_update(false);
  371. }
  372. if (child.child_needs_style_update()) {
  373. update_style_recursively(child);
  374. child.set_child_needs_style_update(false);
  375. }
  376. return IterationDecision::Continue;
  377. });
  378. }
  379. void Document::update_style()
  380. {
  381. update_style_recursively(*this);
  382. update_layout();
  383. }
  384. RefPtr<Layout::Node> Document::create_layout_node()
  385. {
  386. return adopt_ref(*new Layout::InitialContainingBlock(*this, CSS::StyleProperties::create()));
  387. }
  388. void Document::set_link_color(Color color)
  389. {
  390. m_link_color = color;
  391. }
  392. void Document::set_active_link_color(Color color)
  393. {
  394. m_active_link_color = color;
  395. }
  396. void Document::set_visited_link_color(Color color)
  397. {
  398. m_visited_link_color = color;
  399. }
  400. const Layout::InitialContainingBlock* Document::layout_node() const
  401. {
  402. return static_cast<const Layout::InitialContainingBlock*>(Node::layout_node());
  403. }
  404. Layout::InitialContainingBlock* Document::layout_node()
  405. {
  406. return static_cast<Layout::InitialContainingBlock*>(Node::layout_node());
  407. }
  408. void Document::set_inspected_node(Node* node)
  409. {
  410. if (m_inspected_node == node)
  411. return;
  412. if (m_inspected_node && m_inspected_node->layout_node())
  413. m_inspected_node->layout_node()->set_needs_display();
  414. m_inspected_node = node;
  415. if (m_inspected_node && m_inspected_node->layout_node())
  416. m_inspected_node->layout_node()->set_needs_display();
  417. }
  418. void Document::set_hovered_node(Node* node)
  419. {
  420. if (m_hovered_node == node)
  421. return;
  422. RefPtr<Node> old_hovered_node = move(m_hovered_node);
  423. m_hovered_node = node;
  424. invalidate_style();
  425. }
  426. NonnullRefPtr<HTMLCollection> Document::get_elements_by_name(String const& name)
  427. {
  428. return HTMLCollection::create(*this, [name](Element const& element) {
  429. return element.name() == name;
  430. });
  431. }
  432. NonnullRefPtr<HTMLCollection> Document::get_elements_by_tag_name(FlyString const& tag_name)
  433. {
  434. // FIXME: Support "*" for tag_name
  435. // https://dom.spec.whatwg.org/#concept-getelementsbytagname
  436. return HTMLCollection::create(*this, [tag_name](Element const& element) {
  437. if (element.namespace_() == Namespace::HTML)
  438. return element.local_name().to_lowercase() == tag_name.to_lowercase();
  439. return element.local_name() == tag_name;
  440. });
  441. }
  442. NonnullRefPtr<HTMLCollection> Document::get_elements_by_class_name(FlyString const& class_name)
  443. {
  444. return HTMLCollection::create(*this, [class_name, quirks_mode = document().in_quirks_mode()](Element const& element) {
  445. return element.has_class(class_name, quirks_mode ? CaseSensitivity::CaseInsensitive : CaseSensitivity::CaseSensitive);
  446. });
  447. }
  448. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-applets
  449. NonnullRefPtr<HTMLCollection> Document::applets()
  450. {
  451. // FIXME: This should return the same HTMLCollection object every time,
  452. // but that would cause a reference cycle since HTMLCollection refs the root.
  453. return HTMLCollection::create(*this, [](auto&) { return false; });
  454. }
  455. // https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-anchors
  456. NonnullRefPtr<HTMLCollection> Document::anchors()
  457. {
  458. // FIXME: This should return the same HTMLCollection object every time,
  459. // but that would cause a reference cycle since HTMLCollection refs the root.
  460. return HTMLCollection::create(*this, [](Element const& element) {
  461. return is<HTML::HTMLAnchorElement>(element) && element.has_attribute(HTML::AttributeNames::name);
  462. });
  463. }
  464. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-images
  465. NonnullRefPtr<HTMLCollection> Document::images()
  466. {
  467. // FIXME: This should return the same HTMLCollection object every time,
  468. // but that would cause a reference cycle since HTMLCollection refs the root.
  469. return HTMLCollection::create(*this, [](Element const& element) {
  470. return is<HTML::HTMLImageElement>(element);
  471. });
  472. }
  473. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-embeds
  474. NonnullRefPtr<HTMLCollection> Document::embeds()
  475. {
  476. // FIXME: This should return the same HTMLCollection object every time,
  477. // but that would cause a reference cycle since HTMLCollection refs the root.
  478. return HTMLCollection::create(*this, [](Element const& element) {
  479. return is<HTML::HTMLEmbedElement>(element);
  480. });
  481. }
  482. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-plugins
  483. NonnullRefPtr<HTMLCollection> Document::plugins()
  484. {
  485. return embeds();
  486. }
  487. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-links
  488. NonnullRefPtr<HTMLCollection> Document::links()
  489. {
  490. // FIXME: This should return the same HTMLCollection object every time,
  491. // but that would cause a reference cycle since HTMLCollection refs the root.
  492. return HTMLCollection::create(*this, [](Element const& element) {
  493. return (is<HTML::HTMLAnchorElement>(element) || is<HTML::HTMLAreaElement>(element)) && element.has_attribute(HTML::AttributeNames::href);
  494. });
  495. }
  496. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-forms
  497. NonnullRefPtr<HTMLCollection> Document::forms()
  498. {
  499. // FIXME: This should return the same HTMLCollection object every time,
  500. // but that would cause a reference cycle since HTMLCollection refs the root.
  501. return HTMLCollection::create(*this, [](Element const& element) {
  502. return is<HTML::HTMLFormElement>(element);
  503. });
  504. }
  505. // https://html.spec.whatwg.org/multipage/dom.html#dom-document-scripts
  506. NonnullRefPtr<HTMLCollection> Document::scripts()
  507. {
  508. // FIXME: This should return the same HTMLCollection object every time,
  509. // but that would cause a reference cycle since HTMLCollection refs the root.
  510. return HTMLCollection::create(*this, [](Element const& element) {
  511. return is<HTML::HTMLScriptElement>(element);
  512. });
  513. }
  514. Color Document::link_color() const
  515. {
  516. if (m_link_color.has_value())
  517. return m_link_color.value();
  518. if (!page())
  519. return Color::Blue;
  520. return page()->palette().link();
  521. }
  522. Color Document::active_link_color() const
  523. {
  524. if (m_active_link_color.has_value())
  525. return m_active_link_color.value();
  526. if (!page())
  527. return Color::Red;
  528. return page()->palette().active_link();
  529. }
  530. Color Document::visited_link_color() const
  531. {
  532. if (m_visited_link_color.has_value())
  533. return m_visited_link_color.value();
  534. if (!page())
  535. return Color::Magenta;
  536. return page()->palette().visited_link();
  537. }
  538. JS::Interpreter& Document::interpreter()
  539. {
  540. if (!m_interpreter) {
  541. auto& vm = Bindings::main_thread_vm();
  542. m_interpreter = JS::Interpreter::create<Bindings::WindowObject>(vm, *m_window);
  543. // NOTE: We must hook `on_call_stack_emptied` after the interpreter was created, as the initialization of the
  544. // WindowsObject can invoke some internal calls, which will eventually lead to this hook being called without
  545. // `m_interpreter` being fully initialized yet.
  546. // TODO: Hook up vm.on_promise_unhandled_rejection and vm.on_promise_rejection_handled
  547. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events
  548. vm.on_call_stack_emptied = [this] {
  549. auto& vm = m_interpreter->vm();
  550. vm.run_queued_promise_jobs();
  551. vm.run_queued_finalization_registry_cleanup_jobs();
  552. // Note: This is not an exception check for the promise jobs, they will just leave any
  553. // exception that already exists intact and never throw a new one (without cleaning it
  554. // up, that is). Taking care of any previous unhandled exception just happens to be the
  555. // very last thing we want to do, even after running promise jobs.
  556. if (auto* exception = vm.exception()) {
  557. auto value = exception->value();
  558. if (value.is_object()) {
  559. auto& object = value.as_object();
  560. auto name = object.get_without_side_effects(vm.names.name).value_or(JS::js_undefined());
  561. auto message = object.get_without_side_effects(vm.names.message).value_or(JS::js_undefined());
  562. if (name.is_accessor() || message.is_accessor()) {
  563. // The result is not going to be useful, let's just print the value. This affects DOMExceptions, for example.
  564. dbgln("Unhandled JavaScript exception: {}", value);
  565. } else {
  566. dbgln("Unhandled JavaScript exception: [{}] {}", name, message);
  567. }
  568. } else {
  569. dbgln("Unhandled JavaScript exception: {}", value);
  570. }
  571. for (auto& traceback_frame : exception->traceback()) {
  572. auto& function_name = traceback_frame.function_name;
  573. auto& source_range = traceback_frame.source_range;
  574. dbgln(" {} at {}:{}:{}", function_name, source_range.filename, source_range.start.line, source_range.start.column);
  575. }
  576. }
  577. vm.finish_execution_generation();
  578. };
  579. }
  580. return *m_interpreter;
  581. }
  582. JS::Value Document::run_javascript(const StringView& source, const StringView& filename)
  583. {
  584. auto parser = JS::Parser(JS::Lexer(source, filename));
  585. auto program = parser.parse_program();
  586. if (parser.has_errors()) {
  587. parser.print_errors(false);
  588. return JS::js_undefined();
  589. }
  590. auto& interpreter = document().interpreter();
  591. auto& vm = interpreter.vm();
  592. interpreter.run(interpreter.global_object(), *program);
  593. if (vm.exception())
  594. vm.clear_exception();
  595. return vm.last_value();
  596. }
  597. // https://dom.spec.whatwg.org/#dom-document-createelement
  598. // FIXME: This only implements step 6 of the algorithm and does not take in options.
  599. NonnullRefPtr<Element> Document::create_element(const String& tag_name)
  600. {
  601. // 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.
  602. return DOM::create_element(*this, tag_name, Namespace::HTML);
  603. }
  604. // https://dom.spec.whatwg.org/#internal-createelementns-steps
  605. // FIXME: This only implements step 4 of the algorithm and does not take in options.
  606. NonnullRefPtr<Element> Document::create_element_ns(const String& namespace_, const String& qualified_name)
  607. {
  608. return DOM::create_element(*this, qualified_name, namespace_);
  609. }
  610. NonnullRefPtr<DocumentFragment> Document::create_document_fragment()
  611. {
  612. return adopt_ref(*new DocumentFragment(*this));
  613. }
  614. NonnullRefPtr<Text> Document::create_text_node(const String& data)
  615. {
  616. return adopt_ref(*new Text(*this, data));
  617. }
  618. NonnullRefPtr<Comment> Document::create_comment(const String& data)
  619. {
  620. return adopt_ref(*new Comment(*this, data));
  621. }
  622. NonnullRefPtr<Range> Document::create_range()
  623. {
  624. return Range::create(*this);
  625. }
  626. // https://dom.spec.whatwg.org/#dom-document-createevent
  627. NonnullRefPtr<Event> Document::create_event(const String& interface)
  628. {
  629. auto interface_lowercase = interface.to_lowercase();
  630. RefPtr<Event> event;
  631. if (interface_lowercase == "beforeunloadevent") {
  632. event = Event::create(""); // FIXME: Create BeforeUnloadEvent
  633. } else if (interface_lowercase == "compositionevent") {
  634. event = Event::create(""); // FIXME: Create CompositionEvent
  635. } else if (interface_lowercase == "customevent") {
  636. event = Event::create(""); // FIXME: Create CustomEvent
  637. } else if (interface_lowercase == "devicemotionevent") {
  638. event = Event::create(""); // FIXME: Create DeviceMotionEvent
  639. } else if (interface_lowercase == "deviceorientationevent") {
  640. event = Event::create(""); // FIXME: Create DeviceOrientationEvent
  641. } else if (interface_lowercase == "dragevent") {
  642. event = Event::create(""); // FIXME: Create DragEvent
  643. } else if (interface_lowercase.is_one_of("event", "events")) {
  644. event = Event::create("");
  645. } else if (interface_lowercase == "focusevent") {
  646. event = Event::create(""); // FIXME: Create FocusEvent
  647. } else if (interface_lowercase == "hashchangeevent") {
  648. event = Event::create(""); // FIXME: Create HashChangeEvent
  649. } else if (interface_lowercase == "htmlevents") {
  650. event = Event::create("");
  651. } else if (interface_lowercase == "keyboardevent") {
  652. event = Event::create(""); // FIXME: Create KeyboardEvent
  653. } else if (interface_lowercase == "messageevent") {
  654. event = Event::create(""); // FIXME: Create MessageEvent
  655. } else if (interface_lowercase.is_one_of("mouseevent", "mouseevents")) {
  656. event = UIEvents::MouseEvent::create("", 0, 0, 0, 0);
  657. } else if (interface_lowercase == "storageevent") {
  658. event = Event::create(""); // FIXME: Create StorageEvent
  659. } else if (interface_lowercase == "svgevents") {
  660. event = Event::create("");
  661. } else if (interface_lowercase == "textevent") {
  662. event = Event::create(""); // FIXME: Create CompositionEvent
  663. } else if (interface_lowercase == "touchevent") {
  664. event = Event::create(""); // FIXME: Create TouchEvent
  665. } else if (interface_lowercase.is_one_of("uievent", "uievents")) {
  666. event = UIEvents::UIEvent::create("");
  667. } else {
  668. // FIXME:
  669. // 3. If constructor is null, then throw a "NotSupportedError" DOMException.
  670. // 4. If the interface indicated by constructor is not exposed on the relevant global object of this, then throw a "NotSupportedError" DOMException.
  671. TODO();
  672. }
  673. // Setting type to empty string is handled by each constructor.
  674. // FIXME:
  675. // 7. Initialize event’s timeStamp attribute to a DOMHighResTimeStamp representing the high resolution time from the time origin to now.
  676. event->set_is_trusted(false);
  677. event->set_initialized(false);
  678. return event.release_nonnull();
  679. }
  680. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  681. {
  682. m_pending_parsing_blocking_script = script;
  683. }
  684. NonnullRefPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLDocumentParser>)
  685. {
  686. return m_pending_parsing_blocking_script.release_nonnull();
  687. }
  688. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  689. {
  690. m_scripts_to_execute_when_parsing_has_finished.append(script);
  691. }
  692. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLDocumentParser>)
  693. {
  694. return move(m_scripts_to_execute_when_parsing_has_finished);
  695. }
  696. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  697. {
  698. m_scripts_to_execute_as_soon_as_possible.append(script);
  699. }
  700. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLDocumentParser>)
  701. {
  702. return move(m_scripts_to_execute_as_soon_as_possible);
  703. }
  704. // https://dom.spec.whatwg.org/#concept-node-adopt
  705. void Document::adopt_node(Node& node)
  706. {
  707. auto& old_document = node.document();
  708. if (node.parent())
  709. node.remove();
  710. if (&old_document != this) {
  711. // FIXME: This should be shadow-including.
  712. node.for_each_in_inclusive_subtree([&](auto& inclusive_descendant) {
  713. inclusive_descendant.set_document({}, *this);
  714. // FIXME: If inclusiveDescendant is an element, then set the node document of each attribute in inclusiveDescendant’s attribute list to document.
  715. return IterationDecision::Continue;
  716. });
  717. // FIXME: For each inclusiveDescendant in node’s shadow-including inclusive descendants that is custom,
  718. // enqueue a custom element callback reaction with inclusiveDescendant, callback name "adoptedCallback",
  719. // and an argument list containing oldDocument and document.
  720. // FIXME: This should be shadow-including.
  721. node.for_each_in_inclusive_subtree([&](auto& inclusive_descendant) {
  722. inclusive_descendant.adopted_from(old_document);
  723. return IterationDecision::Continue;
  724. });
  725. }
  726. }
  727. // https://dom.spec.whatwg.org/#dom-document-adoptnode
  728. ExceptionOr<NonnullRefPtr<Node>> Document::adopt_node_binding(NonnullRefPtr<Node> node)
  729. {
  730. if (is<Document>(*node))
  731. return DOM::NotSupportedError::create("Cannot adopt a document into a document");
  732. if (is<ShadowRoot>(*node))
  733. return DOM::HierarchyRequestError::create("Cannot adopt a shadow root into a document");
  734. if (is<DocumentFragment>(*node) && verify_cast<DocumentFragment>(*node).host())
  735. return node;
  736. adopt_node(*node);
  737. return node;
  738. }
  739. const DocumentType* Document::doctype() const
  740. {
  741. return first_child_of_type<DocumentType>();
  742. }
  743. const String& Document::compat_mode() const
  744. {
  745. static String back_compat = "BackCompat";
  746. static String css1_compat = "CSS1Compat";
  747. if (m_quirks_mode == QuirksMode::Yes)
  748. return back_compat;
  749. return css1_compat;
  750. }
  751. bool Document::is_editable() const
  752. {
  753. return m_editable;
  754. }
  755. void Document::set_focused_element(Element* element)
  756. {
  757. if (m_focused_element == element)
  758. return;
  759. m_focused_element = element;
  760. if (m_layout_root)
  761. m_layout_root->set_needs_display();
  762. }
  763. void Document::set_active_element(Element* element)
  764. {
  765. if (m_active_element == element)
  766. return;
  767. m_active_element = element;
  768. if (m_layout_root)
  769. m_layout_root->set_needs_display();
  770. }
  771. void Document::set_ready_state(const String& ready_state)
  772. {
  773. m_ready_state = ready_state;
  774. dispatch_event(Event::create(HTML::EventNames::readystatechange));
  775. }
  776. Page* Document::page()
  777. {
  778. return m_browsing_context ? m_browsing_context->page() : nullptr;
  779. }
  780. const Page* Document::page() const
  781. {
  782. return m_browsing_context ? m_browsing_context->page() : nullptr;
  783. }
  784. EventTarget* Document::get_parent(const Event& event)
  785. {
  786. if (event.type() == HTML::EventNames::load)
  787. return nullptr;
  788. return &window();
  789. }
  790. void Document::completely_finish_loading()
  791. {
  792. // FIXME: This needs to handle iframes.
  793. dispatch_event(DOM::Event::create(HTML::EventNames::load));
  794. }
  795. String Document::cookie(Cookie::Source source)
  796. {
  797. if (auto* page = this->page())
  798. return page->client().page_did_request_cookie(m_url, source);
  799. return {};
  800. }
  801. void Document::set_cookie(String cookie_string, Cookie::Source source)
  802. {
  803. auto cookie = Cookie::parse_cookie(cookie_string);
  804. if (!cookie.has_value())
  805. return;
  806. if (auto* page = this->page())
  807. page->client().page_did_set_cookie(m_url, cookie.value(), source);
  808. }
  809. String Document::dump_dom_tree_as_json() const
  810. {
  811. StringBuilder builder;
  812. JsonObjectSerializer json(builder);
  813. serialize_tree_as_json(json);
  814. json.finish();
  815. return builder.to_string();
  816. }
  817. // https://html.spec.whatwg.org/multipage/semantics.html#has-a-style-sheet-that-is-blocking-scripts
  818. bool Document::has_a_style_sheet_that_is_blocking_scripts() const
  819. {
  820. // A Document has a style sheet that is blocking scripts if its script-blocking style sheet counter is greater than 0,
  821. if (m_script_blocking_style_sheet_counter > 0)
  822. return true;
  823. // ...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.
  824. if (!browsing_context() || !browsing_context()->container_document())
  825. return false;
  826. return browsing_context()->container_document()->m_script_blocking_style_sheet_counter > 0;
  827. }
  828. String Document::referrer() const
  829. {
  830. // FIXME: Return the document's actual referrer.
  831. return "";
  832. }
  833. // https://html.spec.whatwg.org/multipage/browsers.html#fully-active
  834. bool Document::is_fully_active() const
  835. {
  836. // 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,
  837. // and either d's browsing context is a top-level browsing context, or d's browsing context's container document is fully active.
  838. return browsing_context() && browsing_context()->active_document() == this && (browsing_context()->is_top_level() || browsing_context()->container_document()->is_fully_active());
  839. }
  840. // https://html.spec.whatwg.org/multipage/history.html#dom-document-location
  841. Bindings::LocationObject* Document::location()
  842. {
  843. // The Document object's location attribute's getter must return this Document object's relevant global object's Location object,
  844. // if this Document object is fully active, and null otherwise.
  845. if (!is_fully_active())
  846. return nullptr;
  847. return window().wrapper()->location_object();
  848. }
  849. }