ViewImplementation.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /*
  2. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Error.h>
  7. #include <AK/LexicalPath.h>
  8. #include <AK/String.h>
  9. #include <LibCore/DateTime.h>
  10. #include <LibCore/StandardPaths.h>
  11. #include <LibGfx/ImageFormats/PNGWriter.h>
  12. #include <LibWebView/ViewImplementation.h>
  13. namespace WebView {
  14. ViewImplementation::ViewImplementation()
  15. {
  16. m_backing_store_shrink_timer = Core::Timer::create_single_shot(3000, [this] {
  17. resize_backing_stores_if_needed(WindowResizeInProgress::No);
  18. }).release_value_but_fixme_should_propagate_errors();
  19. m_repeated_crash_timer = Core::Timer::create_single_shot(1000, [this] {
  20. // Reset the "crashing a lot" counter after 1 second in case we just
  21. // happen to be visiting crashy websites a lot.
  22. this->m_crash_count = 0;
  23. }).release_value_but_fixme_should_propagate_errors();
  24. }
  25. WebContentClient& ViewImplementation::client()
  26. {
  27. VERIFY(m_client_state.client);
  28. return *m_client_state.client;
  29. }
  30. WebContentClient const& ViewImplementation::client() const
  31. {
  32. VERIFY(m_client_state.client);
  33. return *m_client_state.client;
  34. }
  35. void ViewImplementation::load(AK::URL const& url)
  36. {
  37. m_url = url;
  38. client().async_load_url(url);
  39. }
  40. void ViewImplementation::load_html(StringView html, AK::URL const& url)
  41. {
  42. m_url = url;
  43. client().async_load_html(html, url);
  44. }
  45. void ViewImplementation::load_empty_document()
  46. {
  47. load_html(""sv, {});
  48. }
  49. void ViewImplementation::zoom_in()
  50. {
  51. if (m_zoom_level >= ZOOM_MAX_LEVEL)
  52. return;
  53. m_zoom_level += ZOOM_STEP;
  54. update_zoom();
  55. }
  56. void ViewImplementation::zoom_out()
  57. {
  58. if (m_zoom_level <= ZOOM_MIN_LEVEL)
  59. return;
  60. m_zoom_level -= ZOOM_STEP;
  61. update_zoom();
  62. }
  63. void ViewImplementation::reset_zoom()
  64. {
  65. m_zoom_level = 1.0f;
  66. update_zoom();
  67. }
  68. void ViewImplementation::set_preferred_color_scheme(Web::CSS::PreferredColorScheme color_scheme)
  69. {
  70. client().async_set_preferred_color_scheme(color_scheme);
  71. }
  72. DeprecatedString ViewImplementation::selected_text()
  73. {
  74. return client().get_selected_text();
  75. }
  76. void ViewImplementation::select_all()
  77. {
  78. client().async_select_all();
  79. }
  80. void ViewImplementation::get_source()
  81. {
  82. client().async_get_source();
  83. }
  84. void ViewImplementation::inspect_dom_tree()
  85. {
  86. client().async_inspect_dom_tree();
  87. }
  88. void ViewImplementation::inspect_accessibility_tree()
  89. {
  90. client().async_inspect_accessibility_tree();
  91. }
  92. ErrorOr<ViewImplementation::DOMNodeProperties> ViewImplementation::inspect_dom_node(i32 node_id, Optional<Web::CSS::Selector::PseudoElement> pseudo_element)
  93. {
  94. auto response = client().inspect_dom_node(node_id, pseudo_element);
  95. if (!response.has_style())
  96. return Error::from_string_view("Inspected node returned no style"sv);
  97. return DOMNodeProperties {
  98. .computed_style_json = TRY(String::from_deprecated_string(response.take_computed_style())),
  99. .resolved_style_json = TRY(String::from_deprecated_string(response.take_resolved_style())),
  100. .custom_properties_json = TRY(String::from_deprecated_string(response.take_custom_properties())),
  101. .node_box_sizing_json = TRY(String::from_deprecated_string(response.take_node_box_sizing())),
  102. .aria_properties_state_json = TRY(String::from_deprecated_string(response.take_aria_properties_state())),
  103. };
  104. }
  105. void ViewImplementation::clear_inspected_dom_node()
  106. {
  107. client().inspect_dom_node(0, {});
  108. }
  109. i32 ViewImplementation::get_hovered_node_id()
  110. {
  111. return client().get_hovered_node_id();
  112. }
  113. void ViewImplementation::debug_request(DeprecatedString const& request, DeprecatedString const& argument)
  114. {
  115. client().async_debug_request(request, argument);
  116. }
  117. void ViewImplementation::run_javascript(StringView js_source)
  118. {
  119. client().async_run_javascript(js_source);
  120. }
  121. void ViewImplementation::js_console_input(DeprecatedString const& js_source)
  122. {
  123. client().async_js_console_input(js_source);
  124. }
  125. void ViewImplementation::js_console_request_messages(i32 start_index)
  126. {
  127. client().async_js_console_request_messages(start_index);
  128. }
  129. void ViewImplementation::toggle_media_play_state()
  130. {
  131. client().async_toggle_media_play_state();
  132. }
  133. void ViewImplementation::toggle_media_mute_state()
  134. {
  135. client().async_toggle_media_mute_state();
  136. }
  137. void ViewImplementation::toggle_media_loop_state()
  138. {
  139. client().async_toggle_media_loop_state();
  140. }
  141. void ViewImplementation::toggle_media_controls_state()
  142. {
  143. client().async_toggle_media_controls_state();
  144. }
  145. void ViewImplementation::handle_resize()
  146. {
  147. resize_backing_stores_if_needed(WindowResizeInProgress::Yes);
  148. m_backing_store_shrink_timer->restart();
  149. }
  150. void ViewImplementation::resize_backing_stores_if_needed(WindowResizeInProgress window_resize_in_progress)
  151. {
  152. if (m_client_state.has_usable_bitmap) {
  153. // NOTE: We keep the outgoing front bitmap as a backup so we have something to paint until we get a new one.
  154. m_backup_bitmap = m_client_state.front_bitmap.bitmap;
  155. m_backup_bitmap_size = m_client_state.front_bitmap.last_painted_size;
  156. }
  157. m_client_state.has_usable_bitmap = false;
  158. auto viewport_rect = this->viewport_rect();
  159. if (viewport_rect.is_empty())
  160. return;
  161. Gfx::IntSize minimum_needed_size;
  162. if (window_resize_in_progress == WindowResizeInProgress::Yes) {
  163. // Pad the minimum needed size so that we don't have to keep reallocating backing stores while the window is being resized.
  164. minimum_needed_size = { viewport_rect.width() + 256, viewport_rect.height() + 256 };
  165. } else {
  166. // If we're not in the middle of a resize, we can shrink the backing store size to match the viewport size.
  167. minimum_needed_size = viewport_rect.size();
  168. m_client_state.front_bitmap = {};
  169. m_client_state.back_bitmap = {};
  170. }
  171. auto reallocate_backing_store_if_needed = [&](SharedBitmap& backing_store) {
  172. if (!backing_store.bitmap || !backing_store.bitmap->size().contains(minimum_needed_size)) {
  173. if (auto new_bitmap_or_error = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, minimum_needed_size); !new_bitmap_or_error.is_error()) {
  174. if (backing_store.bitmap)
  175. client().async_remove_backing_store(backing_store.id);
  176. backing_store.pending_paints = 0;
  177. backing_store.bitmap = new_bitmap_or_error.release_value();
  178. backing_store.id = m_client_state.next_bitmap_id++;
  179. client().async_add_backing_store(backing_store.id, backing_store.bitmap->to_shareable_bitmap());
  180. }
  181. backing_store.last_painted_size = viewport_rect.size();
  182. }
  183. };
  184. reallocate_backing_store_if_needed(m_client_state.front_bitmap);
  185. reallocate_backing_store_if_needed(m_client_state.back_bitmap);
  186. request_repaint();
  187. }
  188. void ViewImplementation::request_repaint()
  189. {
  190. // If this widget was instantiated but not yet added to a window,
  191. // it won't have a back bitmap yet, so we can just skip repaint requests.
  192. if (!m_client_state.back_bitmap.bitmap)
  193. return;
  194. // Don't request a repaint until pending paint requests have finished.
  195. if (m_client_state.back_bitmap.pending_paints) {
  196. m_client_state.got_repaint_requests_while_painting = true;
  197. return;
  198. }
  199. m_client_state.back_bitmap.pending_paints++;
  200. client().async_paint(viewport_rect(), m_client_state.back_bitmap.id);
  201. }
  202. void ViewImplementation::handle_web_content_process_crash()
  203. {
  204. dbgln("WebContent process crashed!");
  205. ++m_crash_count;
  206. constexpr size_t max_reasonable_crash_count = 5U;
  207. if (m_crash_count >= max_reasonable_crash_count) {
  208. dbgln("WebContent has crashed {} times in quick succession! Not restarting...", m_crash_count);
  209. m_repeated_crash_timer->stop();
  210. return;
  211. }
  212. m_repeated_crash_timer->restart();
  213. create_client();
  214. VERIFY(m_client_state.client);
  215. // Don't keep a stale backup bitmap around.
  216. m_backup_bitmap = nullptr;
  217. handle_resize();
  218. StringBuilder builder;
  219. builder.append("<html><head><title>Crashed: "sv);
  220. builder.append(escape_html_entities(m_url.to_deprecated_string()));
  221. builder.append("</title></head><body>"sv);
  222. builder.append("<h1>Web page crashed"sv);
  223. if (!m_url.host().has<Empty>()) {
  224. builder.appendff(" on {}", escape_html_entities(m_url.serialized_host().release_value_but_fixme_should_propagate_errors()));
  225. }
  226. builder.append("</h1>"sv);
  227. auto escaped_url = escape_html_entities(m_url.to_deprecated_string());
  228. builder.appendff("The web page <a href=\"{}\">{}</a> has crashed.<br><br>You can reload the page to try again.", escaped_url, escaped_url);
  229. builder.append("</body></html>"sv);
  230. load_html(builder.to_deprecated_string(), m_url);
  231. }
  232. ErrorOr<void> ViewImplementation::take_screenshot(ScreenshotType type)
  233. {
  234. Gfx::ShareableBitmap bitmap;
  235. switch (type) {
  236. case ScreenshotType::Visible:
  237. if (auto* visible_bitmap = m_client_state.has_usable_bitmap ? m_client_state.front_bitmap.bitmap.ptr() : m_backup_bitmap.ptr())
  238. bitmap = visible_bitmap->to_shareable_bitmap();
  239. break;
  240. case ScreenshotType::Full:
  241. bitmap = client().take_document_screenshot();
  242. break;
  243. }
  244. if (!bitmap.is_valid())
  245. return Error::from_string_view("Failed to take a screenshot of the current tab"sv);
  246. LexicalPath path { Core::StandardPaths::downloads_directory() };
  247. path = path.append(TRY(Core::DateTime::now().to_string("screenshot-%Y-%m-%d-%H-%M-%S.png"sv)));
  248. auto encoded = TRY(Gfx::PNGWriter::encode(*bitmap.bitmap()));
  249. auto screenshot_file = TRY(Core::File::open(path.string(), Core::File::OpenMode::Write));
  250. TRY(screenshot_file->write_until_depleted(encoded));
  251. return {};
  252. }
  253. }