HtmlView.cpp 15 KB

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