HtmlView.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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/FileSystemPath.h>
  27. #include <AK/URL.h>
  28. #include <LibCore/File.h>
  29. #include <LibGUI/Application.h>
  30. #include <LibGUI/Painter.h>
  31. #include <LibGUI/ScrollBar.h>
  32. #include <LibGUI/Window.h>
  33. #include <LibGfx/PNGLoader.h>
  34. #include <LibWeb/DOM/Element.h>
  35. #include <LibWeb/DOM/ElementFactory.h>
  36. #include <LibWeb/DOM/HTMLAnchorElement.h>
  37. #include <LibWeb/DOM/HTMLImageElement.h>
  38. #include <LibWeb/DOM/MouseEvent.h>
  39. #include <LibWeb/DOM/Text.h>
  40. #include <LibWeb/Dump.h>
  41. #include <LibWeb/Frame.h>
  42. #include <LibWeb/HtmlView.h>
  43. #include <LibWeb/Layout/LayoutDocument.h>
  44. #include <LibWeb/Layout/LayoutNode.h>
  45. #include <LibWeb/Parser/HTMLParser.h>
  46. #include <LibWeb/RenderingContext.h>
  47. #include <LibWeb/ResourceLoader.h>
  48. #include <stdio.h>
  49. //#define SELECTION_DEBUG
  50. namespace Web {
  51. HtmlView::HtmlView()
  52. : m_main_frame(Web::Frame::create(*this))
  53. {
  54. main_frame().on_set_needs_display = [this](auto& content_rect) {
  55. if (content_rect.is_empty()) {
  56. update();
  57. return;
  58. }
  59. Gfx::Rect adjusted_rect = content_rect;
  60. adjusted_rect.set_location(to_widget_position(content_rect.location()));
  61. update(adjusted_rect);
  62. };
  63. set_should_hide_unnecessary_scrollbars(true);
  64. set_background_role(ColorRole::Base);
  65. }
  66. HtmlView::~HtmlView()
  67. {
  68. }
  69. void HtmlView::set_document(Document* new_document)
  70. {
  71. RefPtr<Document> old_document = document();
  72. if (new_document == old_document)
  73. return;
  74. if (old_document)
  75. old_document->on_layout_updated = nullptr;
  76. main_frame().set_document(new_document);
  77. if (new_document) {
  78. new_document->on_layout_updated = [this] {
  79. layout_and_sync_size();
  80. update();
  81. };
  82. }
  83. #ifdef HTML_DEBUG
  84. if (document != nullptr) {
  85. dbgprintf("\033[33;1mLayout tree before layout:\033[0m\n");
  86. ::dump_tree(*layout_root());
  87. }
  88. #endif
  89. layout_and_sync_size();
  90. update();
  91. }
  92. void HtmlView::layout_and_sync_size()
  93. {
  94. if (!document())
  95. return;
  96. bool had_vertical_scrollbar = vertical_scrollbar().is_visible();
  97. bool had_horizontal_scrollbar = horizontal_scrollbar().is_visible();
  98. main_frame().set_size(available_size());
  99. document()->layout();
  100. set_content_size(enclosing_int_rect(layout_root()->rect()).size());
  101. // NOTE: If layout caused us to gain or lose scrollbars, we have to lay out again
  102. // since the scrollbars now take up some of the available space.
  103. if (had_vertical_scrollbar != vertical_scrollbar().is_visible() || had_horizontal_scrollbar != horizontal_scrollbar().is_visible()) {
  104. main_frame().set_size(available_size());
  105. document()->layout();
  106. set_content_size(enclosing_int_rect(layout_root()->rect()).size());
  107. }
  108. main_frame().set_viewport_rect(visible_content_rect());
  109. #ifdef HTML_DEBUG
  110. dbgprintf("\033[33;1mLayout tree after layout:\033[0m\n");
  111. ::dump_tree(*layout_root());
  112. #endif
  113. }
  114. void HtmlView::resize_event(GUI::ResizeEvent& event)
  115. {
  116. GUI::ScrollableWidget::resize_event(event);
  117. layout_and_sync_size();
  118. }
  119. void HtmlView::paint_event(GUI::PaintEvent& event)
  120. {
  121. GUI::Frame::paint_event(event);
  122. GUI::Painter painter(*this);
  123. painter.add_clip_rect(widget_inner_rect());
  124. painter.add_clip_rect(event.rect());
  125. if (!layout_root()) {
  126. painter.fill_rect(event.rect(), palette().color(background_role()));
  127. return;
  128. }
  129. painter.fill_rect(event.rect(), document()->background_color(palette()));
  130. if (auto background_bitmap = document()->background_image()) {
  131. painter.draw_tiled_bitmap(event.rect(), *background_bitmap);
  132. }
  133. painter.translate(frame_thickness(), frame_thickness());
  134. painter.translate(-horizontal_scrollbar().value(), -vertical_scrollbar().value());
  135. RenderingContext context(painter, palette());
  136. context.set_should_show_line_box_borders(m_should_show_line_box_borders);
  137. context.set_viewport_rect(visible_content_rect());
  138. layout_root()->render(context);
  139. }
  140. void HtmlView::mousemove_event(GUI::MouseEvent& event)
  141. {
  142. if (!layout_root())
  143. return GUI::ScrollableWidget::mousemove_event(event);
  144. bool hovered_node_changed = false;
  145. bool is_hovering_link = false;
  146. bool was_hovering_link = document()->hovered_node() && document()->hovered_node()->is_link();
  147. auto result = layout_root()->hit_test(to_content_position(event.position()));
  148. const HTMLAnchorElement* hovered_link_element = nullptr;
  149. if (result.layout_node) {
  150. auto* node = result.layout_node->node();
  151. hovered_node_changed = node != document()->hovered_node();
  152. document()->set_hovered_node(const_cast<Node*>(node));
  153. if (node) {
  154. hovered_link_element = node->enclosing_link_element();
  155. if (hovered_link_element) {
  156. #ifdef HTML_DEBUG
  157. dbg() << "HtmlView: hovering over a link to " << hovered_link_element->href();
  158. #endif
  159. is_hovering_link = true;
  160. }
  161. auto offset = compute_mouse_event_offset(event.position(), *result.layout_node);
  162. const_cast<Node*>(node)->dispatch_event(MouseEvent::create("mousemove", offset.x(), offset.y()));
  163. }
  164. if (m_in_mouse_selection) {
  165. layout_root()->selection().set_end({ result.layout_node, result.index_in_node });
  166. dump_selection("MouseMove");
  167. update();
  168. }
  169. }
  170. if (window())
  171. window()->set_override_cursor(is_hovering_link ? GUI::StandardCursor::Hand : GUI::StandardCursor::None);
  172. if (hovered_node_changed) {
  173. update();
  174. auto* hovered_html_element = document()->hovered_node() ? document()->hovered_node()->enclosing_html_element() : nullptr;
  175. if (hovered_html_element && !hovered_html_element->title().is_null()) {
  176. auto screen_position = screen_relative_rect().location().translated(event.position());
  177. GUI::Application::the().show_tooltip(hovered_html_element->title(), screen_position.translated(4, 4));
  178. } else {
  179. GUI::Application::the().hide_tooltip();
  180. }
  181. }
  182. if (is_hovering_link != was_hovering_link) {
  183. if (on_link_hover) {
  184. on_link_hover(hovered_link_element ? document()->complete_url(hovered_link_element->href()).to_string() : String());
  185. }
  186. }
  187. event.accept();
  188. }
  189. void HtmlView::mousedown_event(GUI::MouseEvent& event)
  190. {
  191. if (!layout_root())
  192. return GUI::ScrollableWidget::mousemove_event(event);
  193. bool hovered_node_changed = false;
  194. auto result = layout_root()->hit_test(to_content_position(event.position()));
  195. if (result.layout_node) {
  196. auto* node = result.layout_node->node();
  197. hovered_node_changed = node != document()->hovered_node();
  198. document()->set_hovered_node(const_cast<Node*>(node));
  199. if (node) {
  200. if (auto* link = node->enclosing_link_element()) {
  201. dbg() << "HtmlView: clicking on a link to " << link->href();
  202. if (on_link_click)
  203. on_link_click(link->href());
  204. } else {
  205. if (event.button() == GUI::MouseButton::Left) {
  206. layout_root()->selection().set({ result.layout_node, result.index_in_node }, {});
  207. dump_selection("MouseDown");
  208. m_in_mouse_selection = true;
  209. }
  210. }
  211. auto offset = compute_mouse_event_offset(event.position(), *result.layout_node);
  212. const_cast<Node*>(node)->dispatch_event(MouseEvent::create("mousedown", offset.x(), offset.y()));
  213. }
  214. }
  215. if (hovered_node_changed)
  216. update();
  217. event.accept();
  218. }
  219. void HtmlView::mouseup_event(GUI::MouseEvent& event)
  220. {
  221. if (!layout_root())
  222. return GUI::ScrollableWidget::mouseup_event(event);
  223. auto result = layout_root()->hit_test(to_content_position(event.position()));
  224. if (result.layout_node) {
  225. if (auto* node = result.layout_node->node()) {
  226. auto offset = compute_mouse_event_offset(event.position(), *result.layout_node);
  227. const_cast<Node*>(node)->dispatch_event(MouseEvent::create("mouseup", offset.x(), offset.y()));
  228. }
  229. }
  230. if (event.button() == GUI::MouseButton::Left) {
  231. dump_selection("MouseUp");
  232. m_in_mouse_selection = false;
  233. }
  234. }
  235. void HtmlView::keydown_event(GUI::KeyEvent& event)
  236. {
  237. if (event.modifiers() == 0) {
  238. switch (event.key()) {
  239. case Key_Home:
  240. vertical_scrollbar().set_value(0);
  241. break;
  242. case Key_End:
  243. vertical_scrollbar().set_value(vertical_scrollbar().max());
  244. break;
  245. case Key_Down:
  246. vertical_scrollbar().set_value(vertical_scrollbar().value() + vertical_scrollbar().step());
  247. break;
  248. case Key_Up:
  249. vertical_scrollbar().set_value(vertical_scrollbar().value() - vertical_scrollbar().step());
  250. break;
  251. case Key_Left:
  252. horizontal_scrollbar().set_value(horizontal_scrollbar().value() + horizontal_scrollbar().step());
  253. break;
  254. case Key_Right:
  255. horizontal_scrollbar().set_value(horizontal_scrollbar().value() - horizontal_scrollbar().step());
  256. break;
  257. case Key_PageDown:
  258. vertical_scrollbar().set_value(vertical_scrollbar().value() + frame_inner_rect().height());
  259. break;
  260. case Key_PageUp:
  261. vertical_scrollbar().set_value(vertical_scrollbar().value() - frame_inner_rect().height());
  262. break;
  263. }
  264. }
  265. event.accept();
  266. }
  267. void HtmlView::reload()
  268. {
  269. load(main_frame().document()->url());
  270. }
  271. static RefPtr<Document> create_image_document(const ByteBuffer& data, const URL& url)
  272. {
  273. auto document = adopt(*new Document);
  274. document->set_url(url);
  275. auto bitmap = Gfx::load_png_from_memory(data.data(), data.size());
  276. ASSERT(bitmap);
  277. auto html_element = create_element(document, "html");
  278. document->append_child(html_element);
  279. auto head_element = create_element(document, "head");
  280. html_element->append_child(head_element);
  281. auto title_element = create_element(document, "title");
  282. head_element->append_child(title_element);
  283. auto basename = FileSystemPath(url.path()).basename();
  284. auto title_text = adopt(*new Text(document, String::format("%s [%dx%d]", basename.characters(), bitmap->width(), bitmap->height())));
  285. title_element->append_child(title_text);
  286. auto body_element = create_element(document, "body");
  287. html_element->append_child(body_element);
  288. auto image_element = create_element(document, "img");
  289. image_element->set_attribute("src", url.to_string());
  290. body_element->append_child(image_element);
  291. return document;
  292. }
  293. void HtmlView::load(const URL& url)
  294. {
  295. dbg() << "HtmlView::load: " << url.to_string();
  296. if (!url.is_valid()) {
  297. load_error_page(url, "Invalid URL");
  298. return;
  299. }
  300. if (window())
  301. window()->set_override_cursor(GUI::StandardCursor::None);
  302. if (on_load_start)
  303. on_load_start(url);
  304. ResourceLoader::the().load(
  305. url,
  306. [this, url](auto data) {
  307. if (data.is_null()) {
  308. load_error_page(url, "No data");
  309. return;
  310. }
  311. RefPtr<Document> document;
  312. if (url.path().ends_with(".png")) {
  313. document = create_image_document(data, url);
  314. } else {
  315. document = parse_html_document(data, url);
  316. }
  317. ASSERT(document);
  318. set_document(document);
  319. if (on_title_change)
  320. on_title_change(document->title());
  321. },
  322. [this, url](auto error) {
  323. load_error_page(url, error);
  324. });
  325. }
  326. void HtmlView::load_error_page(const URL& failed_url, const String& error)
  327. {
  328. auto error_page_url = "file:///res/html/error.html";
  329. ResourceLoader::the().load(
  330. error_page_url,
  331. [this, failed_url, error](auto data) {
  332. ASSERT(!data.is_null());
  333. auto html = String::format(
  334. String::copy(data).characters(),
  335. escape_html_entities(failed_url.to_string()).characters(),
  336. escape_html_entities(error).characters());
  337. auto document = parse_html_document(html, failed_url);
  338. ASSERT(document);
  339. set_document(document);
  340. if (on_title_change)
  341. on_title_change(document->title());
  342. },
  343. [](auto error) {
  344. dbg() << "Failed to load error page: " << error;
  345. ASSERT_NOT_REACHED();
  346. });
  347. }
  348. const LayoutDocument* HtmlView::layout_root() const
  349. {
  350. return document() ? document()->layout_node() : nullptr;
  351. }
  352. LayoutDocument* HtmlView::layout_root()
  353. {
  354. if (!document())
  355. return nullptr;
  356. return const_cast<LayoutDocument*>(document()->layout_node());
  357. }
  358. void HtmlView::scroll_to_anchor(const StringView& name)
  359. {
  360. if (!document())
  361. return;
  362. const auto* element = document()->get_element_by_id(name);
  363. if (!element) {
  364. auto candidates = document()->get_elements_by_name(name);
  365. for (auto* candidate : candidates) {
  366. if (is<HTMLAnchorElement>(*candidate)) {
  367. element = to<HTMLAnchorElement>(candidate);
  368. break;
  369. }
  370. }
  371. }
  372. if (!element) {
  373. dbg() << "HtmlView::scroll_to_anchor(): Anchor not found: '" << name << "'";
  374. return;
  375. }
  376. if (!element->layout_node()) {
  377. dbg() << "HtmlView::scroll_to_anchor(): Anchor found but without layout node: '" << name << "'";
  378. return;
  379. }
  380. auto& layout_node = *element->layout_node();
  381. Gfx::FloatRect float_rect { layout_node.box_type_agnostic_position(), { (float)visible_content_rect().width(), (float)visible_content_rect().height() } };
  382. scroll_into_view(enclosing_int_rect(float_rect), true, true);
  383. window()->set_override_cursor(GUI::StandardCursor::None);
  384. }
  385. Document* HtmlView::document()
  386. {
  387. return main_frame().document();
  388. }
  389. const Document* HtmlView::document() const
  390. {
  391. return main_frame().document();
  392. }
  393. void HtmlView::dump_selection(const char* event_name)
  394. {
  395. UNUSED_PARAM(event_name);
  396. #ifdef SELECTION_DEBUG
  397. dbg() << event_name << " selection start: "
  398. << layout_root()->selection().start().layout_node << ":" << layout_root()->selection().start().index_in_node << ", end: "
  399. << layout_root()->selection().end().layout_node << ":" << layout_root()->selection().end().index_in_node;
  400. #endif
  401. }
  402. void HtmlView::did_scroll()
  403. {
  404. main_frame().set_viewport_rect(visible_content_rect());
  405. }
  406. Gfx::Point HtmlView::compute_mouse_event_offset(const Gfx::Point& event_position, const LayoutNode& layout_node) const
  407. {
  408. auto content_event_position = to_content_position(event_position);
  409. auto top_left_of_layout_node = layout_node.box_type_agnostic_position();
  410. return {
  411. content_event_position.x() - static_cast<int>(top_left_of_layout_node.x()),
  412. content_event_position.y() - static_cast<int>(top_left_of_layout_node.y())
  413. };
  414. }
  415. }