Document.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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 <AK/Utf8View.h>
  28. #include <LibCore/Timer.h>
  29. #include <LibGUI/Application.h>
  30. #include <LibGUI/DisplayLink.h>
  31. #include <LibGUI/MessageBox.h>
  32. #include <LibJS/Interpreter.h>
  33. #include <LibJS/Parser.h>
  34. #include <LibJS/Runtime/Function.h>
  35. #include <LibWeb/Bindings/DocumentWrapper.h>
  36. #include <LibWeb/Bindings/WindowObject.h>
  37. #include <LibWeb/CSS/StyleResolver.h>
  38. #include <LibWeb/DOM/Comment.h>
  39. #include <LibWeb/DOM/Document.h>
  40. #include <LibWeb/DOM/DocumentFragment.h>
  41. #include <LibWeb/DOM/DocumentType.h>
  42. #include <LibWeb/DOM/Element.h>
  43. #include <LibWeb/DOM/ElementFactory.h>
  44. #include <LibWeb/DOM/Event.h>
  45. #include <LibWeb/DOM/Text.h>
  46. #include <LibWeb/DOM/Window.h>
  47. #include <LibWeb/Dump.h>
  48. #include <LibWeb/HTML/AttributeNames.h>
  49. #include <LibWeb/HTML/EventNames.h>
  50. #include <LibWeb/HTML/HTMLBodyElement.h>
  51. #include <LibWeb/HTML/HTMLFrameSetElement.h>
  52. #include <LibWeb/HTML/HTMLHeadElement.h>
  53. #include <LibWeb/HTML/HTMLHtmlElement.h>
  54. #include <LibWeb/HTML/HTMLScriptElement.h>
  55. #include <LibWeb/HTML/HTMLTitleElement.h>
  56. #include <LibWeb/InProcessWebView.h>
  57. #include <LibWeb/Layout/BlockFormattingContext.h>
  58. #include <LibWeb/Layout/InitialContainingBlockBox.h>
  59. #include <LibWeb/Layout/TreeBuilder.h>
  60. #include <LibWeb/Namespace.h>
  61. #include <LibWeb/Origin.h>
  62. #include <LibWeb/Page/Frame.h>
  63. #include <LibWeb/SVG/TagNames.h>
  64. #include <ctype.h>
  65. #include <stdio.h>
  66. namespace Web::DOM {
  67. Document::Document(const URL& url)
  68. : ParentNode(*this, NodeType::DOCUMENT_NODE)
  69. , m_style_resolver(make<CSS::StyleResolver>(*this))
  70. , m_style_sheets(CSS::StyleSheetList::create(*this))
  71. , m_url(url)
  72. , m_window(Window::create_with_document(*this))
  73. , m_implementation(DOMImplementation::create(*this))
  74. {
  75. m_style_update_timer = Core::Timer::create_single_shot(0, [this] {
  76. update_style();
  77. });
  78. }
  79. Document::~Document()
  80. {
  81. }
  82. void Document::removed_last_ref()
  83. {
  84. ASSERT(!ref_count());
  85. ASSERT(!m_deletion_has_begun);
  86. if (m_referencing_node_count) {
  87. // The document has reached ref_count==0 but still has nodes keeping it alive.
  88. // At this point, sever all the node links we control.
  89. // If nodes remain elsewhere (e.g JS wrappers), they will keep the document alive.
  90. // NOTE: This makes sure we stay alive across for the duration of the cleanup below.
  91. increment_referencing_node_count();
  92. m_focused_element = nullptr;
  93. m_hovered_node = nullptr;
  94. m_pending_parsing_blocking_script = nullptr;
  95. m_inspected_node = nullptr;
  96. m_scripts_to_execute_when_parsing_has_finished.clear();
  97. m_scripts_to_execute_as_soon_as_possible.clear();
  98. m_associated_inert_template_document = nullptr;
  99. m_interpreter = nullptr;
  100. {
  101. // Gather up all the descendants of this document and prune them from the tree.
  102. // FIXME: This could definitely be more elegant.
  103. NonnullRefPtrVector<Node> descendants;
  104. for_each_in_subtree([&](auto& node) {
  105. if (&node != this)
  106. descendants.append(node);
  107. return IterationDecision::Continue;
  108. });
  109. for (auto& node : descendants) {
  110. ASSERT(&node.document() == this);
  111. ASSERT(!node.is_document());
  112. if (node.parent())
  113. node.parent()->remove_child(node);
  114. }
  115. }
  116. m_in_removed_last_ref = false;
  117. decrement_referencing_node_count();
  118. return;
  119. }
  120. m_in_removed_last_ref = false;
  121. m_deletion_has_begun = true;
  122. delete this;
  123. }
  124. Origin Document::origin() const
  125. {
  126. if (!m_url.is_valid())
  127. return {};
  128. return { m_url.protocol(), m_url.host(), m_url.port() };
  129. }
  130. void Document::set_origin(const Origin& origin)
  131. {
  132. m_url.set_protocol(origin.protocol());
  133. m_url.set_host(origin.host());
  134. m_url.set_port(origin.port());
  135. }
  136. void Document::schedule_style_update()
  137. {
  138. if (m_style_update_timer->is_active())
  139. return;
  140. m_style_update_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. const Element* Document::document_element() const
  159. {
  160. return first_child_of_type<Element>();
  161. }
  162. const HTML::HTMLHtmlElement* Document::html_element() const
  163. {
  164. auto* html = document_element();
  165. if (is<HTML::HTMLHtmlElement>(html))
  166. return downcast<HTML::HTMLHtmlElement>(html);
  167. return nullptr;
  168. }
  169. const HTML::HTMLHeadElement* Document::head() const
  170. {
  171. auto* html = html_element();
  172. if (!html)
  173. return nullptr;
  174. return html->first_child_of_type<HTML::HTMLHeadElement>();
  175. }
  176. const HTML::HTMLElement* Document::body() const
  177. {
  178. auto* html = html_element();
  179. if (!html)
  180. return nullptr;
  181. auto* first_body = html->first_child_of_type<HTML::HTMLBodyElement>();
  182. if (first_body)
  183. return first_body;
  184. auto* first_frameset = html->first_child_of_type<HTML::HTMLFrameSetElement>();
  185. if (first_frameset)
  186. return first_frameset;
  187. return nullptr;
  188. }
  189. void Document::set_body(HTML::HTMLElement& new_body)
  190. {
  191. if (!is<HTML::HTMLBodyElement>(new_body) && !is<HTML::HTMLFrameSetElement>(new_body)) {
  192. // FIXME: throw a "HierarchyRequestError" DOMException.
  193. return;
  194. }
  195. auto* existing_body = body();
  196. if (existing_body) {
  197. TODO();
  198. return;
  199. }
  200. auto* html = document_element();
  201. if (!html) {
  202. // FIXME: throw a "HierarchyRequestError" DOMException.
  203. return;
  204. }
  205. // FIXME: Implement this once there's a non-const first_child_of_type:
  206. // "Otherwise, the body element is null, but there's a document element. Append the new value to the document element."
  207. TODO();
  208. }
  209. String Document::title() const
  210. {
  211. auto* head_element = head();
  212. if (!head_element)
  213. return {};
  214. auto* title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  215. if (!title_element)
  216. return {};
  217. auto raw_title = title_element->text_content();
  218. StringBuilder builder;
  219. bool last_was_space = false;
  220. for (auto code_point : Utf8View(raw_title)) {
  221. if (isspace(code_point)) {
  222. last_was_space = true;
  223. } else {
  224. if (last_was_space && !builder.is_empty())
  225. builder.append(' ');
  226. builder.append_code_point(code_point);
  227. last_was_space = false;
  228. }
  229. }
  230. return builder.to_string();
  231. }
  232. void Document::set_title(const String& title)
  233. {
  234. auto* head_element = const_cast<HTML::HTMLHeadElement*>(head());
  235. if (!head_element)
  236. return;
  237. RefPtr<HTML::HTMLTitleElement> title_element = head_element->first_child_of_type<HTML::HTMLTitleElement>();
  238. if (!title_element) {
  239. title_element = static_ptr_cast<HTML::HTMLTitleElement>(create_element(HTML::TagNames::title));
  240. head_element->append_child(*title_element);
  241. }
  242. while (RefPtr<Node> child = title_element->first_child())
  243. title_element->remove_child(child.release_nonnull());
  244. title_element->append_child(adopt(*new Text(*this, title)));
  245. if (auto* page = this->page())
  246. page->client().page_did_change_title(title);
  247. }
  248. void Document::attach_to_frame(Badge<Frame>, Frame& frame)
  249. {
  250. m_frame = frame;
  251. update_layout();
  252. }
  253. void Document::detach_from_frame(Badge<Frame>, Frame& frame)
  254. {
  255. ASSERT(&frame == m_frame);
  256. tear_down_layout_tree();
  257. m_frame = nullptr;
  258. }
  259. void Document::tear_down_layout_tree()
  260. {
  261. if (!m_layout_root)
  262. return;
  263. // Gather up all the layout nodes in a vector and detach them from parents
  264. // while the vector keeps them alive.
  265. NonnullRefPtrVector<Layout::Node> layout_nodes;
  266. m_layout_root->for_each_in_subtree([&](auto& layout_node) {
  267. layout_nodes.append(layout_node);
  268. return IterationDecision::Continue;
  269. });
  270. for (auto& layout_node : layout_nodes) {
  271. if (layout_node.parent())
  272. layout_node.parent()->remove_child(layout_node);
  273. }
  274. m_layout_root = nullptr;
  275. }
  276. Color Document::background_color(const Palette& palette) const
  277. {
  278. auto default_color = palette.base();
  279. auto* body_element = body();
  280. if (!body_element)
  281. return default_color;
  282. auto* body_layout_node = body_element->layout_node();
  283. if (!body_layout_node)
  284. return default_color;
  285. auto color = body_layout_node->style().background_color();
  286. if (!color.alpha())
  287. return default_color;
  288. return color;
  289. }
  290. RefPtr<Gfx::Bitmap> Document::background_image() const
  291. {
  292. auto* body_element = body();
  293. if (!body_element)
  294. return {};
  295. auto* body_layout_node = body_element->layout_node();
  296. if (!body_layout_node)
  297. return {};
  298. auto background_image = body_layout_node->specified_style().property(CSS::PropertyID::BackgroundImage);
  299. if (!background_image.has_value() || !background_image.value()->is_image())
  300. return {};
  301. auto& image_value = static_cast<const CSS::ImageStyleValue&>(*background_image.value());
  302. if (!image_value.bitmap())
  303. return {};
  304. return *image_value.bitmap();
  305. }
  306. URL Document::complete_url(const String& string) const
  307. {
  308. return m_url.complete_url(string);
  309. }
  310. void Document::invalidate_layout()
  311. {
  312. tear_down_layout_tree();
  313. }
  314. void Document::force_layout()
  315. {
  316. invalidate_layout();
  317. update_layout();
  318. }
  319. void Document::update_layout()
  320. {
  321. if (!frame())
  322. return;
  323. if (!m_layout_root) {
  324. Layout::TreeBuilder tree_builder;
  325. m_layout_root = static_ptr_cast<Layout::InitialContainingBlockBox>(tree_builder.build(*this));
  326. }
  327. Layout::BlockFormattingContext root_formatting_context(*m_layout_root, nullptr);
  328. root_formatting_context.run(*m_layout_root, Layout::LayoutMode::Default);
  329. m_layout_root->set_needs_display();
  330. if (frame()->is_main_frame()) {
  331. if (auto* page = this->page())
  332. page->client().page_did_layout();
  333. }
  334. }
  335. static void update_style_recursively(DOM::Node& node)
  336. {
  337. node.for_each_child([&](auto& child) {
  338. if (child.needs_style_update()) {
  339. if (is<Element>(child))
  340. downcast<Element>(child).recompute_style();
  341. child.set_needs_style_update(false);
  342. }
  343. if (child.child_needs_style_update()) {
  344. update_style_recursively(child);
  345. child.set_child_needs_style_update(false);
  346. }
  347. return IterationDecision::Continue;
  348. });
  349. }
  350. void Document::update_style()
  351. {
  352. update_style_recursively(*this);
  353. update_layout();
  354. }
  355. RefPtr<Layout::Node> Document::create_layout_node(const CSS::StyleProperties*)
  356. {
  357. return adopt(*new Layout::InitialContainingBlockBox(*this, CSS::StyleProperties::create()));
  358. }
  359. void Document::set_link_color(Color color)
  360. {
  361. m_link_color = color;
  362. }
  363. void Document::set_active_link_color(Color color)
  364. {
  365. m_active_link_color = color;
  366. }
  367. void Document::set_visited_link_color(Color color)
  368. {
  369. m_visited_link_color = color;
  370. }
  371. const Layout::InitialContainingBlockBox* Document::layout_node() const
  372. {
  373. return static_cast<const Layout::InitialContainingBlockBox*>(Node::layout_node());
  374. }
  375. Layout::InitialContainingBlockBox* Document::layout_node()
  376. {
  377. return static_cast<Layout::InitialContainingBlockBox*>(Node::layout_node());
  378. }
  379. void Document::set_inspected_node(Node* node)
  380. {
  381. if (m_inspected_node == node)
  382. return;
  383. if (m_inspected_node && m_inspected_node->layout_node())
  384. m_inspected_node->layout_node()->set_needs_display();
  385. m_inspected_node = node;
  386. if (m_inspected_node && m_inspected_node->layout_node())
  387. m_inspected_node->layout_node()->set_needs_display();
  388. }
  389. void Document::set_hovered_node(Node* node)
  390. {
  391. if (m_hovered_node == node)
  392. return;
  393. RefPtr<Node> old_hovered_node = move(m_hovered_node);
  394. m_hovered_node = node;
  395. invalidate_style();
  396. }
  397. NonnullRefPtrVector<Element> Document::get_elements_by_name(const String& name) const
  398. {
  399. NonnullRefPtrVector<Element> elements;
  400. for_each_in_subtree_of_type<Element>([&](auto& element) {
  401. if (element.attribute(HTML::AttributeNames::name) == name)
  402. elements.append(element);
  403. return IterationDecision::Continue;
  404. });
  405. return elements;
  406. }
  407. NonnullRefPtrVector<Element> Document::get_elements_by_tag_name(const FlyString& tag_name) const
  408. {
  409. NonnullRefPtrVector<Element> elements;
  410. for_each_in_subtree_of_type<Element>([&](auto& element) {
  411. if (element.local_name() == tag_name)
  412. elements.append(element);
  413. return IterationDecision::Continue;
  414. });
  415. return elements;
  416. }
  417. NonnullRefPtrVector<Element> Document::get_elements_by_class_name(const FlyString& class_name) const
  418. {
  419. NonnullRefPtrVector<Element> elements;
  420. for_each_in_subtree_of_type<Element>([&](auto& element) {
  421. if (element.has_class(class_name))
  422. elements.append(element);
  423. return IterationDecision::Continue;
  424. });
  425. return elements;
  426. }
  427. Color Document::link_color() const
  428. {
  429. if (m_link_color.has_value())
  430. return m_link_color.value();
  431. if (!page())
  432. return Color::Blue;
  433. return page()->palette().link();
  434. }
  435. Color Document::active_link_color() const
  436. {
  437. if (m_active_link_color.has_value())
  438. return m_active_link_color.value();
  439. if (!page())
  440. return Color::Red;
  441. return page()->palette().active_link();
  442. }
  443. Color Document::visited_link_color() const
  444. {
  445. if (m_visited_link_color.has_value())
  446. return m_visited_link_color.value();
  447. if (!page())
  448. return Color::Magenta;
  449. return page()->palette().visited_link();
  450. }
  451. static JS::VM& main_thread_vm()
  452. {
  453. static RefPtr<JS::VM> vm;
  454. if (!vm) {
  455. vm = JS::VM::create();
  456. vm->set_should_log_exceptions(true);
  457. }
  458. return *vm;
  459. }
  460. JS::Interpreter& Document::interpreter()
  461. {
  462. if (!m_interpreter)
  463. m_interpreter = JS::Interpreter::create<Bindings::WindowObject>(main_thread_vm(), *m_window);
  464. return *m_interpreter;
  465. }
  466. JS::Value Document::run_javascript(const StringView& source)
  467. {
  468. auto parser = JS::Parser(JS::Lexer(source));
  469. auto program = parser.parse_program();
  470. if (parser.has_errors()) {
  471. parser.print_errors();
  472. return JS::js_undefined();
  473. }
  474. auto& interpreter = document().interpreter();
  475. auto result = interpreter.run(interpreter.global_object(), *program);
  476. if (interpreter.exception())
  477. interpreter.vm().clear_exception();
  478. return result;
  479. }
  480. NonnullRefPtr<Element> Document::create_element(const String& tag_name)
  481. {
  482. // 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.
  483. return DOM::create_element(*this, tag_name, Namespace::HTML);
  484. }
  485. NonnullRefPtr<DocumentFragment> Document::create_document_fragment()
  486. {
  487. return adopt(*new DocumentFragment(*this));
  488. }
  489. NonnullRefPtr<Text> Document::create_text_node(const String& data)
  490. {
  491. return adopt(*new Text(*this, data));
  492. }
  493. NonnullRefPtr<Comment> Document::create_comment(const String& data)
  494. {
  495. return adopt(*new Comment(*this, data));
  496. }
  497. void Document::set_pending_parsing_blocking_script(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement* script)
  498. {
  499. m_pending_parsing_blocking_script = script;
  500. }
  501. NonnullRefPtr<HTML::HTMLScriptElement> Document::take_pending_parsing_blocking_script(Badge<HTML::HTMLDocumentParser>)
  502. {
  503. return m_pending_parsing_blocking_script.release_nonnull();
  504. }
  505. void Document::add_script_to_execute_when_parsing_has_finished(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  506. {
  507. m_scripts_to_execute_when_parsing_has_finished.append(script);
  508. }
  509. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_when_parsing_has_finished(Badge<HTML::HTMLDocumentParser>)
  510. {
  511. return move(m_scripts_to_execute_when_parsing_has_finished);
  512. }
  513. void Document::add_script_to_execute_as_soon_as_possible(Badge<HTML::HTMLScriptElement>, HTML::HTMLScriptElement& script)
  514. {
  515. m_scripts_to_execute_as_soon_as_possible.append(script);
  516. }
  517. NonnullRefPtrVector<HTML::HTMLScriptElement> Document::take_scripts_to_execute_as_soon_as_possible(Badge<HTML::HTMLDocumentParser>)
  518. {
  519. return move(m_scripts_to_execute_as_soon_as_possible);
  520. }
  521. void Document::adopt_node(Node& subtree_root)
  522. {
  523. subtree_root.for_each_in_subtree([&](auto& node) {
  524. node.set_document({}, *this);
  525. return IterationDecision::Continue;
  526. });
  527. }
  528. const DocumentType* Document::doctype() const
  529. {
  530. return first_child_of_type<DocumentType>();
  531. }
  532. const String& Document::compat_mode() const
  533. {
  534. static String back_compat = "BackCompat";
  535. static String css1_compat = "CSS1Compat";
  536. if (m_quirks_mode == QuirksMode::Yes)
  537. return back_compat;
  538. return css1_compat;
  539. }
  540. bool Document::is_editable() const
  541. {
  542. return m_editable;
  543. }
  544. void Document::set_focused_element(Element* element)
  545. {
  546. if (m_focused_element == element)
  547. return;
  548. m_focused_element = element;
  549. if (m_layout_root)
  550. m_layout_root->set_needs_display();
  551. }
  552. void Document::set_ready_state(const String& ready_state)
  553. {
  554. m_ready_state = ready_state;
  555. dispatch_event(Event::create(HTML::EventNames::readystatechange));
  556. }
  557. Page* Document::page()
  558. {
  559. return m_frame ? m_frame->page() : nullptr;
  560. }
  561. const Page* Document::page() const
  562. {
  563. return m_frame ? m_frame->page() : nullptr;
  564. }
  565. EventTarget* Document::get_parent(const Event& event)
  566. {
  567. if (event.type() == HTML::EventNames::load)
  568. return nullptr;
  569. return &window();
  570. }
  571. void Document::completely_finish_loading()
  572. {
  573. // FIXME: This needs to handle iframes.
  574. dispatch_event(DOM::Event::create(HTML::EventNames::load));
  575. }
  576. }