HtmlView.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 <LibCore/File.h>
  28. #include <LibGUI/Application.h>
  29. #include <LibGUI/Painter.h>
  30. #include <LibGUI/ScrollBar.h>
  31. #include <LibGUI/Window.h>
  32. #include <LibGfx/PNGLoader.h>
  33. #include <LibHTML/DOM/Element.h>
  34. #include <LibHTML/DOM/ElementFactory.h>
  35. #include <LibHTML/DOM/HTMLAnchorElement.h>
  36. #include <LibHTML/DOM/HTMLImageElement.h>
  37. #include <LibHTML/DOM/Text.h>
  38. #include <LibHTML/Dump.h>
  39. #include <LibHTML/Frame.h>
  40. #include <LibHTML/HtmlView.h>
  41. #include <LibHTML/Layout/LayoutDocument.h>
  42. #include <LibHTML/Layout/LayoutNode.h>
  43. #include <LibHTML/Parser/HTMLParser.h>
  44. #include <LibHTML/RenderingContext.h>
  45. #include <LibHTML/ResourceLoader.h>
  46. #include <stdio.h>
  47. HtmlView::HtmlView(GUI::Widget* parent)
  48. : GUI::ScrollableWidget(parent)
  49. , m_main_frame(::Frame::create(*this))
  50. {
  51. main_frame().on_set_needs_display = [this](auto& content_rect) {
  52. if (content_rect.is_empty()) {
  53. update();
  54. return;
  55. }
  56. Gfx::Rect adjusted_rect = content_rect;
  57. adjusted_rect.set_location(to_widget_position(content_rect.location()));
  58. update(adjusted_rect);
  59. };
  60. set_frame_shape(Gfx::FrameShape::Container);
  61. set_frame_shadow(Gfx::FrameShadow::Sunken);
  62. set_frame_thickness(2);
  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. }
  162. if (m_in_mouse_selection) {
  163. layout_root()->selection().set_end({ result.layout_node, result.index_in_node });
  164. dump_selection("MouseMove");
  165. update();
  166. }
  167. }
  168. if (window())
  169. window()->set_override_cursor(is_hovering_link ? GUI::StandardCursor::Hand : GUI::StandardCursor::None);
  170. if (hovered_node_changed) {
  171. update();
  172. auto* hovered_html_element = document()->hovered_node() ? document()->hovered_node()->enclosing_html_element() : nullptr;
  173. if (hovered_html_element && !hovered_html_element->title().is_null()) {
  174. auto screen_position = screen_relative_rect().location().translated(event.position());
  175. GUI::Application::the().show_tooltip(hovered_html_element->title(), screen_position.translated(4, 4));
  176. } else {
  177. GUI::Application::the().hide_tooltip();
  178. }
  179. }
  180. if (is_hovering_link != was_hovering_link) {
  181. if (on_link_hover) {
  182. on_link_hover(hovered_link_element ? document()->complete_url(hovered_link_element->href()).to_string() : String());
  183. }
  184. }
  185. event.accept();
  186. }
  187. void HtmlView::mousedown_event(GUI::MouseEvent& event)
  188. {
  189. if (!layout_root())
  190. return GUI::ScrollableWidget::mousemove_event(event);
  191. bool hovered_node_changed = false;
  192. auto result = layout_root()->hit_test(to_content_position(event.position()));
  193. if (result.layout_node) {
  194. auto* node = result.layout_node->node();
  195. hovered_node_changed = node != document()->hovered_node();
  196. document()->set_hovered_node(const_cast<Node*>(node));
  197. if (node) {
  198. if (auto* link = node->enclosing_link_element()) {
  199. dbg() << "HtmlView: clicking on a link to " << link->href();
  200. if (on_link_click)
  201. on_link_click(link->href());
  202. } else {
  203. if (event.button() == GUI::MouseButton::Left) {
  204. layout_root()->selection().set({ result.layout_node, result.index_in_node }, {});
  205. dump_selection("MouseDown");
  206. m_in_mouse_selection = true;
  207. }
  208. }
  209. }
  210. }
  211. if (hovered_node_changed)
  212. update();
  213. event.accept();
  214. }
  215. void HtmlView::mouseup_event(GUI::MouseEvent& event)
  216. {
  217. if (!layout_root())
  218. return GUI::ScrollableWidget::mouseup_event(event);
  219. if (event.button() == GUI::MouseButton::Left) {
  220. dump_selection("MouseUp");
  221. m_in_mouse_selection = false;
  222. }
  223. }
  224. void HtmlView::keydown_event(GUI::KeyEvent& event)
  225. {
  226. if (event.modifiers() == 0) {
  227. switch (event.key()) {
  228. case Key_Home:
  229. vertical_scrollbar().set_value(0);
  230. break;
  231. case Key_End:
  232. vertical_scrollbar().set_value(vertical_scrollbar().max());
  233. break;
  234. case Key_Down:
  235. vertical_scrollbar().set_value(vertical_scrollbar().value() + vertical_scrollbar().step());
  236. break;
  237. case Key_Up:
  238. vertical_scrollbar().set_value(vertical_scrollbar().value() - vertical_scrollbar().step());
  239. break;
  240. case Key_Left:
  241. horizontal_scrollbar().set_value(horizontal_scrollbar().value() + horizontal_scrollbar().step());
  242. break;
  243. case Key_Right:
  244. horizontal_scrollbar().set_value(horizontal_scrollbar().value() - horizontal_scrollbar().step());
  245. break;
  246. case Key_PageDown:
  247. vertical_scrollbar().set_value(vertical_scrollbar().value() + frame_inner_rect().height());
  248. break;
  249. case Key_PageUp:
  250. vertical_scrollbar().set_value(vertical_scrollbar().value() - frame_inner_rect().height());
  251. break;
  252. }
  253. }
  254. event.accept();
  255. }
  256. void HtmlView::reload()
  257. {
  258. load(main_frame().document()->url());
  259. }
  260. static RefPtr<Document> create_image_document(const ByteBuffer& data, const URL& url)
  261. {
  262. auto document = adopt(*new Document);
  263. document->set_url(url);
  264. auto bitmap = Gfx::load_png_from_memory(data.data(), data.size());
  265. ASSERT(bitmap);
  266. auto html_element = create_element(document, "html");
  267. document->append_child(html_element);
  268. auto head_element = create_element(document, "head");
  269. html_element->append_child(head_element);
  270. auto title_element = create_element(document, "title");
  271. head_element->append_child(title_element);
  272. auto basename = FileSystemPath(url.path()).basename();
  273. auto title_text = adopt(*new Text(document, String::format("%s [%dx%d]", basename.characters(), bitmap->width(), bitmap->height())));
  274. title_element->append_child(title_text);
  275. auto body_element = create_element(document, "body");
  276. html_element->append_child(body_element);
  277. auto image_element = create_element(document, "img");
  278. image_element->set_attribute("src", url.to_string());
  279. body_element->append_child(image_element);
  280. return document;
  281. }
  282. void HtmlView::load(const URL& url)
  283. {
  284. dbg() << "HtmlView::load: " << url;
  285. if (window())
  286. window()->set_override_cursor(GUI::StandardCursor::None);
  287. if (on_load_start)
  288. on_load_start(url);
  289. ResourceLoader::the().load(url, [this, url](auto data) {
  290. if (data.is_null()) {
  291. dbg() << "Load failed!";
  292. ASSERT_NOT_REACHED();
  293. }
  294. RefPtr<Document> document;
  295. if (url.path().ends_with(".png")) {
  296. document = create_image_document(data, url);
  297. } else {
  298. document = parse_html_document(data, url);
  299. }
  300. ASSERT(document);
  301. set_document(document);
  302. if (on_title_change)
  303. on_title_change(document->title());
  304. });
  305. }
  306. const LayoutDocument* HtmlView::layout_root() const
  307. {
  308. return document() ? document()->layout_node() : nullptr;
  309. }
  310. LayoutDocument* HtmlView::layout_root()
  311. {
  312. if (!document())
  313. return nullptr;
  314. return const_cast<LayoutDocument*>(document()->layout_node());
  315. }
  316. void HtmlView::scroll_to_anchor(const StringView& name)
  317. {
  318. if (!document())
  319. return;
  320. auto* element = document()->get_element_by_id(name);
  321. if (!element) {
  322. auto candidates = document()->get_elements_by_name(name);
  323. for (auto* candidate : candidates) {
  324. if (is<HTMLAnchorElement>(*candidate)) {
  325. element = to<HTMLAnchorElement>(candidate);
  326. break;
  327. }
  328. }
  329. }
  330. if (!element) {
  331. dbg() << "HtmlView::scroll_to_anchor(): Anchor not found: '" << name << "'";
  332. return;
  333. }
  334. if (!element->layout_node()) {
  335. dbg() << "HtmlView::scroll_to_anchor(): Anchor found but without layout node: '" << name << "'";
  336. return;
  337. }
  338. auto& layout_node = *element->layout_node();
  339. Gfx::FloatRect float_rect { layout_node.box_type_agnostic_position(), { (float)visible_content_rect().width(), (float)visible_content_rect().height() } };
  340. scroll_into_view(enclosing_int_rect(float_rect), true, true);
  341. window()->set_override_cursor(GUI::StandardCursor::None);
  342. }
  343. Document* HtmlView::document()
  344. {
  345. return main_frame().document();
  346. }
  347. const Document* HtmlView::document() const
  348. {
  349. return main_frame().document();
  350. }
  351. void HtmlView::dump_selection(const char* event_name)
  352. {
  353. dbg() << event_name << " selection start: "
  354. << layout_root()->selection().start().layout_node << ":" << layout_root()->selection().start().index_in_node << ", end: "
  355. << layout_root()->selection().end().layout_node << ":" << layout_root()->selection().end().index_in_node;
  356. }
  357. void HtmlView::did_scroll()
  358. {
  359. main_frame().set_viewport_rect(visible_content_rect());
  360. }