Document.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/StringBuilder.h>
  27. #include <LibCore/Timer.h>
  28. #include <LibGUI/Application.h>
  29. #include <LibGUI/DisplayLink.h>
  30. #include <LibGUI/MessageBox.h>
  31. #include <LibJS/Interpreter.h>
  32. #include <LibJS/Parser.h>
  33. #include <LibJS/Runtime/Function.h>
  34. #include <LibWeb/Bindings/DocumentWrapper.h>
  35. #include <LibWeb/Bindings/WindowObject.h>
  36. #include <LibWeb/CSS/StyleResolver.h>
  37. #include <LibWeb/DOM/Comment.h>
  38. #include <LibWeb/DOM/Document.h>
  39. #include <LibWeb/DOM/DocumentFragment.h>
  40. #include <LibWeb/DOM/DocumentType.h>
  41. #include <LibWeb/DOM/Element.h>
  42. #include <LibWeb/DOM/ElementFactory.h>
  43. #include <LibWeb/DOM/Event.h>
  44. #include <LibWeb/DOM/Text.h>
  45. #include <LibWeb/DOM/Window.h>
  46. #include <LibWeb/Dump.h>
  47. #include <LibWeb/HTML/AttributeNames.h>
  48. #include <LibWeb/HTML/HTMLBodyElement.h>
  49. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  50. #include <LibWeb/HTML/HTMLHeadElement.h>
  51. #include <LibWeb/HTML/HTMLHtmlElement.h>
  52. #include <LibWeb/HTML/HTMLScriptElement.h>
  53. #include <LibWeb/HTML/HTMLTitleElement.h>
  54. #include <LibWeb/InProcessWebView.h>
  55. #include <LibWeb/Layout/BlockFormattingContext.h>
  56. #include <LibWeb/Layout/LayoutDocument.h>
  57. #include <LibWeb/Layout/LayoutTreeBuilder.h>
  58. #include <LibWeb/Namespace.h>
  59. #include <LibWeb/Origin.h>
  60. #include <LibWeb/Page/Frame.h>
  61. #include <LibWeb/SVG/TagNames.h>
  62. #include <stdio.h>
  63. namespace Web::DOM {
  64. Document::Document(const URL& url)
  65. : ParentNode(*this, NodeType::DOCUMENT_NODE)
  66. , m_style_resolver(make<CSS::StyleResolver>(*this))
  67. , m_style_sheets(CSS::StyleSheetList::create(*this))
  68. , m_url(url)
  69. , m_window(Window::create_with_document(*this))
  70. , m_implementation(DOMImplementation::create(*this))
  71. {
  72. m_style_update_timer = Core::Timer::create_single_shot(0, [this] {
  73. update_style();
  74. });
  75. }
  76. Document::~Document()
  77. {
  78. }
  79. void Document::removed_last_ref()
  80. {
  81. ASSERT(!ref_count());
  82. ASSERT(!m_deletion_has_begun);
  83. if (m_referencing_node_count) {
  84. // The document has reached ref_count==0 but still has nodes keeping it alive.
  85. // At this point, sever all the node links we control.
  86. // If nodes remain elsewhere (e.g JS wrappers), they will keep the document alive.
  87. // NOTE: This makes sure we stay alive across for the duration of the cleanup below.
  88. increment_referencing_node_count();
  89. m_focused_element = nullptr;
  90. m_hovered_node = nullptr;
  91. m_pending_parsing_blocking_script = nullptr;
  92. m_inspected_node = nullptr;
  93. m_scripts_to_execute_when_parsing_has_finished.clear();
  94. m_scripts_to_execute_as_soon_as_possible.clear();
  95. m_associated_inert_template_document = nullptr;
  96. m_interpreter = nullptr;
  97. {
  98. // Gather up all the descendants of this document and prune them from the tree.
  99. // FIXME: This could definitely be more elegant.
  100. NonnullRefPtrVector<Node> descendants;
  101. for_each_in_subtree([&](auto& node) {
  102. if (&node != this)
  103. descendants.append(node);
  104. return IterationDecision::Continue;
  105. });
  106. for (auto& node : descendants) {
  107. ASSERT(&node.document() == this);
  108. ASSERT(!node.is_document());
  109. if (node.parent())
  110. node.parent()->remove_child(node);
  111. }
  112. }
  113. m_in_removed_last_ref = false;
  114. decrement_referencing_node_count();
  115. return;
  116. }
  117. m_in_removed_last_ref = false;
  118. m_deletion_has_begun = true;
  119. delete this;
  120. }
  121. Origin Document::origin() const
  122. {
  123. if (!m_url.is_valid())
  124. return {};
  125. return { m_url.protocol(), m_url.host(), m_url.port() };
  126. }
  127. void Document::set_origin(const Origin& origin)
  128. {
  129. m_url.set_protocol(origin.protocol());
  130. m_url.set_host(origin.host());
  131. m_url.set_port(origin.port());
  132. }
  133. void Document::schedule_style_update()
  134. {
  135. if (m_style_update_timer->is_active())
  136. return;
  137. m_style_update_timer->start();
  138. }
  139. bool Document::is_child_allowed(const Node& node) const
  140. {
  141. switch (node.type()) {
  142. case NodeType::DOCUMENT_NODE:
  143. case NodeType::TEXT_NODE:
  144. return false;
  145. case NodeType::COMMENT_NODE:
  146. return true;
  147. case NodeType::DOCUMENT_TYPE_NODE:
  148. return !first_child_of_type<DocumentType>();
  149. case NodeType::ELEMENT_NODE:
  150. return !first_child_of_type<Element>();
  151. default:
  152. return false;
  153. }
  154. }
  155. const Element* Document::document_element() const
  156. {
  157. return first_child_of_type<Element>();
  158. }
  159. const HTML::HTMLHtmlElement* Document::html_element() const
  160. {
  161. auto* html = document_element();
  162. if (is<HTML::HTMLHtmlElement>(html))
  163. return downcast<HTML::HTMLHtmlElement>(html);
  164. return nullptr;
  165. }
  166. const HTML::HTMLHeadElement* Document::head() const
  167. {
  168. auto* html = html_element();
  169. if (!html)
  170. return nullptr;
  171. return html->first_child_of_type<HTML::HTMLHeadElement>();
  172. }
  173. const HTML::HTMLElement* Document::body() const
  174. {
  175. auto* html = html_element();
  176. if (!html)
  177. return nullptr;
  178. auto* first_body = html->first_child_of_type<HTML::HTMLBodyElement>();
  179. if (first_body)
  180. return first_body;
  181. auto* first_frameset = html->first_child_of_type<HTML::HTMLFrameSetElement>();
  182. if (first_frameset)
  183. return first_frameset;
  184. return nullptr;
  185. }
  186. void Document::set_body(HTML::HTMLElement& new_body)
  187. {
  188. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body)) {
  189. // FIXME: throw a "HierarchyRequestError" DOMException.
  190. return;
  191. }
  192. auto* existing_body = body();
  193. if (existing_body) {
  194. TODO();
  195. return;
  196. }
  197. auto* html = document_element();
  198. if (!html) {
  199. // FIXME: throw a "HierarchyRequestError" DOMException.
  200. return;
  201. }
  202. // FIXME: Implement this once there's a non-const first_child_of_type:
  203. // "Otherwise, the body element is null, but there's a document element. Append the new value to the document element."
  204. TODO();
  205. }
  206. String Document::title() const
  207. {
  208. auto* head_element = head();
  209. if (!head_element)
  210. return {};
  211. auto* title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  212. if (!title_element)
  213. return {};
  214. return title_element->text_content();
  215. }
  216. void Document::attach_to_frame(Badge<Frame>, Frame& frame)
  217. {
  218. m_frame = frame;
  219. for_each_in_subtree([&](auto& node) {
  220. node.document_did_attach_to_frame(frame);
  221. return IterationDecision::Continue;
  222. });
  223. layout();
  224. }
  225. void Document::detach_from_frame(Badge<Frame>, Frame& frame)
  226. {
  227. for_each_in_subtree([&](auto& node) {
  228. node.document_will_detach_from_frame(frame);
  229. return IterationDecision::Continue;
  230. });
  231. tear_down_layout_tree();
  232. m_frame = nullptr;
  233. }
  234. void Document::tear_down_layout_tree()
  235. {
  236. if (!m_layout_root)
  237. return;
  238. // Gather up all the layout nodes in a vector and detach them from parents
  239. // while the vector keeps them alive.
  240. NonnullRefPtrVector<LayoutNode> layout_nodes;
  241. m_layout_root->for_each_in_subtree([&](auto& layout_node) {
  242. layout_nodes.append(layout_node);
  243. return IterationDecision::Continue;
  244. });
  245. for (auto& layout_node : layout_nodes) {
  246. if (layout_node.parent())
  247. layout_node.parent()->remove_child(layout_node);
  248. }
  249. m_layout_root = nullptr;
  250. }
  251. Color Document::background_color(const Palette& palette) const
  252. {
  253. auto default_color = palette.base();
  254. auto* body_element = body();
  255. if (!body_element)
  256. return default_color;
  257. auto* body_layout_node = body_element->layout_node();
  258. if (!body_layout_node)
  259. return default_color;
  260. auto background_color = body_layout_node->specified_style().property(CSS::PropertyID::BackgroundColor);
  261. if (!background_color.has_value() || !background_color.value()->is_color())
  262. return default_color;
  263. return background_color.value()->to_color(*this);
  264. }
  265. RefPtr<Gfx::Bitmap> Document::background_image() const
  266. {
  267. auto* body_element = body();
  268. if (!body_element)
  269. return {};
  270. auto* body_layout_node = body_element->layout_node();
  271. if (!body_layout_node)
  272. return {};
  273. auto background_image = body_layout_node->specified_style().property(CSS::PropertyID::BackgroundImage);
  274. if (!background_image.has_value() || !background_image.value()->is_image())
  275. return {};
  276. auto& image_value = static_cast<const CSS::ImageStyleValue&>(*background_image.value());
  277. if (!image_value.bitmap())
  278. return {};
  279. return *image_value.bitmap();
  280. }
  281. URL Document::complete_url(const String& string) const
  282. {
  283. return m_url.complete_url(string);
  284. }
  285. void Document::invalidate_layout()
  286. {
  287. tear_down_layout_tree();
  288. }
  289. void Document::force_layout()
  290. {
  291. invalidate_layout();
  292. layout();
  293. }
  294. void Document::layout()
  295. {
  296. if (!frame())
  297. return;
  298. if (!m_layout_root) {
  299. LayoutTreeBuilder tree_builder;
  300. m_layout_root = static_ptr_cast<LayoutDocument>(tree_builder.build(*this));
  301. }
  302. Layout::BlockFormattingContext root_formatting_context(*m_layout_root);
  303. root_formatting_context.run(LayoutMode::Default);
  304. m_layout_root->set_needs_display();
  305. if (frame()->is_main_frame()) {
  306. if (auto* page = this->page())
  307. page->client().page_did_layout();
  308. }
  309. }
  310. void Document::update_style()
  311. {
  312. for_each_in_subtree_of_type<Element>([&](auto& element) {
  313. if (element.needs_style_update())
  314. element.recompute_style();
  315. return IterationDecision::Continue;
  316. });
  317. update_layout();
  318. }
  319. void Document::update_layout()
  320. {
  321. if (!frame())
  322. return;
  323. layout();
  324. }
  325. RefPtr<LayoutNode> Document::create_layout_node(const CSS::StyleProperties*)
  326. {
  327. return adopt(*new LayoutDocument(*this, CSS::StyleProperties::create()));
  328. }
  329. void Document::set_link_color(Color color)
  330. {
  331. m_link_color = color;
  332. }
  333. void Document::set_active_link_color(Color color)
  334. {
  335. m_active_link_color = color;
  336. }
  337. void Document::set_visited_link_color(Color color)
  338. {
  339. m_visited_link_color = color;
  340. }
  341. const LayoutDocument* Document::layout_node() const
  342. {
  343. return static_cast<const LayoutDocument*>(Node::layout_node());
  344. }
  345. LayoutDocument* Document::layout_node()
  346. {
  347. return static_cast<LayoutDocument*>(Node::layout_node());
  348. }
  349. void Document::set_inspected_node(Node* node)
  350. {
  351. if (m_inspected_node == node)
  352. return;
  353. if (m_inspected_node && m_inspected_node->layout_node())
  354. m_inspected_node->layout_node()->set_needs_display();
  355. m_inspected_node = node;
  356. if (m_inspected_node && m_inspected_node->layout_node())
  357. m_inspected_node->layout_node()->set_needs_display();
  358. }
  359. void Document::set_hovered_node(Node* node)
  360. {
  361. if (m_hovered_node == node)
  362. return;
  363. RefPtr<Node> old_hovered_node = move(m_hovered_node);
  364. m_hovered_node = node;
  365. invalidate_style();
  366. }
  367. NonnullRefPtrVector<Element> Document::get_elements_by_name(const String& name) const
  368. {
  369. NonnullRefPtrVector<Element> elements;
  370. for_each_in_subtree_of_type<Element>([&](auto& element) {
  371. if (element.attribute(HTML::AttributeNames::name) == name)
  372. elements.append(element);
  373. return IterationDecision::Continue;
  374. });
  375. return elements;
  376. }
  377. NonnullRefPtrVector<Element> Document::get_elements_by_tag_name(const FlyString& tag_name) const
  378. {
  379. NonnullRefPtrVector<Element> elements;
  380. for_each_in_subtree_of_type<Element>([&](auto& element) {
  381. if (element.local_name() == tag_name)
  382. elements.append(element);
  383. return IterationDecision::Continue;
  384. });
  385. return elements;
  386. }
  387. Color Document::link_color() const
  388. {
  389. if (m_link_color.has_value())
  390. return m_link_color.value();
  391. if (!page())
  392. return Color::Blue;
  393. return page()->palette().link();
  394. }
  395. Color Document::active_link_color() const
  396. {
  397. if (m_active_link_color.has_value())
  398. return m_active_link_color.value();
  399. if (!page())
  400. return Color::Red;
  401. return page()->palette().active_link();
  402. }
  403. Color Document::visited_link_color() const
  404. {
  405. if (m_visited_link_color.has_value())
  406. return m_visited_link_color.value();
  407. if (!page())
  408. return Color::Magenta;
  409. return page()->palette().visited_link();
  410. }
  411. static JS::VM& main_thread_vm()
  412. {
  413. static RefPtr<JS::VM> vm;
  414. if (!vm)
  415. vm = JS::VM::create();
  416. return *vm;
  417. }
  418. JS::Interpreter& Document::interpreter()
  419. {
  420. if (!m_interpreter)
  421. m_interpreter = JS::Interpreter::create<Bindings::WindowObject>(main_thread_vm(), *m_window);
  422. return *m_interpreter;
  423. }
  424. JS::Value Document::run_javascript(const StringView& source)
  425. {
  426. auto parser = JS::Parser(JS::Lexer(source));
  427. auto program = parser.parse_program();
  428. if (parser.has_errors()) {
  429. parser.print_errors();
  430. return JS::js_undefined();
  431. }
  432. auto& interpreter = document().interpreter();
  433. auto result = interpreter.run(interpreter.global_object(), *program);
  434. if (interpreter.exception())
  435. interpreter.vm().clear_exception();
  436. return result;
  437. }
  438. NonnullRefPtr<Element> Document::create_element(const String& tag_name)
  439. {
  440. // 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.
  441. return DOM::create_element(*this, tag_name, Namespace::HTML);
  442. }
  443. NonnullRefPtr<DocumentFragment> Document::create_document_fragment()
  444. {
  445. return adopt(*new DocumentFragment(*this));
  446. }
  447. NonnullRefPtr<Text> Document::create_text_node(const String& data)
  448. {
  449. return adopt(*new Text(*this, data));
  450. }
  451. NonnullRefPtr<Comment> Document::create_comment(const String& data)
  452. {
  453. return adopt(*new Comment(*this, data));
  454. }
  455. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  456. {
  457. m_pending_parsing_blocking_script = script;
  458. }
  459. NonnullRefPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLDocumentParser>)
  460. {
  461. return m_pending_parsing_blocking_script.release_nonnull();
  462. }
  463. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  464. {
  465. m_scripts_to_execute_when_parsing_has_finished.append(script);
  466. }
  467. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLDocumentParser>)
  468. {
  469. return move(m_scripts_to_execute_when_parsing_has_finished);
  470. }
  471. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  472. {
  473. m_scripts_to_execute_as_soon_as_possible.append(script);
  474. }
  475. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLDocumentParser>)
  476. {
  477. return move(m_scripts_to_execute_as_soon_as_possible);
  478. }
  479. void Document::adopt_node(Node& subtree_root)
  480. {
  481. subtree_root.for_each_in_subtree([&](auto& node) {
  482. node.set_document({}, *this);
  483. return IterationDecision::Continue;
  484. });
  485. }
  486. const DocumentType* Document::doctype() const
  487. {
  488. return first_child_of_type<DocumentType>();
  489. }
  490. const String& Document::compat_mode() const
  491. {
  492. static String back_compat = "BackCompat";
  493. static String css1_compat = "CSS1Compat";
  494. if (m_quirks_mode == QuirksMode::Yes)
  495. return back_compat;
  496. return css1_compat;
  497. }
  498. bool Document::is_editable() const
  499. {
  500. return m_editable;
  501. }
  502. void Document::set_focused_element(Element* element)
  503. {
  504. if (m_focused_element == element)
  505. return;
  506. m_focused_element = element;
  507. if (m_layout_root)
  508. m_layout_root->set_needs_display();
  509. }
  510. void Document::set_ready_state(const String& ready_state)
  511. {
  512. m_ready_state = ready_state;
  513. dispatch_event(Event::create("readystatechange"));
  514. }
  515. Page* Document::page()
  516. {
  517. return m_frame ? m_frame->page() : nullptr;
  518. }
  519. const Page* Document::page() const
  520. {
  521. return m_frame ? m_frame->page() : nullptr;
  522. }
  523. }