headless-browser.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*
  2. * Copyright (c) 2022, Dex♪ <dexes.ttp@gmail.com>
  3. * Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Badge.h>
  8. #include <AK/DeprecatedString.h>
  9. #include <AK/Function.h>
  10. #include <AK/LexicalPath.h>
  11. #include <AK/NonnullOwnPtr.h>
  12. #include <AK/Platform.h>
  13. #include <AK/String.h>
  14. #include <AK/URL.h>
  15. #include <AK/Vector.h>
  16. #include <LibCore/ArgsParser.h>
  17. #include <LibCore/DeprecatedFile.h>
  18. #include <LibCore/EventLoop.h>
  19. #include <LibCore/File.h>
  20. #include <LibCore/Timer.h>
  21. #include <LibFileSystem/FileSystem.h>
  22. #include <LibGfx/Bitmap.h>
  23. #include <LibGfx/Font/FontDatabase.h>
  24. #include <LibGfx/ImageFormats/PNGWriter.h>
  25. #include <LibGfx/Point.h>
  26. #include <LibGfx/Rect.h>
  27. #include <LibGfx/ShareableBitmap.h>
  28. #include <LibGfx/Size.h>
  29. #include <LibGfx/StandardCursor.h>
  30. #include <LibGfx/SystemTheme.h>
  31. #include <LibIPC/File.h>
  32. #include <LibWeb/Cookie/Cookie.h>
  33. #include <LibWeb/Cookie/ParsedCookie.h>
  34. #include <LibWeb/HTML/ActivateTab.h>
  35. #include <LibWeb/Loader/FrameLoader.h>
  36. #include <LibWebView/ViewImplementation.h>
  37. #include <LibWebView/WebContentClient.h>
  38. #if !defined(AK_OS_SERENITY)
  39. # include <Ladybird/HelperProcess.h>
  40. # include <QCoreApplication>
  41. #endif
  42. class HeadlessWebContentView final : public WebView::ViewImplementation {
  43. public:
  44. static ErrorOr<NonnullOwnPtr<HeadlessWebContentView>> create(Core::AnonymousBuffer theme, Gfx::IntSize const& window_size, StringView web_driver_ipc_path, WebView::IsLayoutTestMode is_layout_test_mode = WebView::IsLayoutTestMode::No)
  45. {
  46. auto view = TRY(adopt_nonnull_own_or_enomem(new (nothrow) HeadlessWebContentView()));
  47. #if defined(AK_OS_SERENITY)
  48. view->m_client_state.client = TRY(WebView::WebContentClient::try_create(*view));
  49. (void)is_layout_test_mode;
  50. #else
  51. auto candidate_web_content_paths = TRY(get_paths_for_helper_process("WebContent"sv));
  52. view->m_client_state.client = TRY(view->launch_web_content_process(candidate_web_content_paths, WebView::EnableCallgrindProfiling::No, is_layout_test_mode));
  53. #endif
  54. view->client().async_update_system_theme(move(theme));
  55. view->client().async_update_system_fonts(Gfx::FontDatabase::default_font_query(), Gfx::FontDatabase::fixed_width_font_query(), Gfx::FontDatabase::window_title_font_query());
  56. view->client().async_set_viewport_rect({ { 0, 0 }, window_size });
  57. view->client().async_set_window_size(window_size);
  58. if (!web_driver_ipc_path.is_empty())
  59. view->client().async_connect_to_webdriver(web_driver_ipc_path);
  60. return view;
  61. }
  62. RefPtr<Gfx::Bitmap> take_screenshot()
  63. {
  64. return client().take_document_screenshot().bitmap();
  65. }
  66. ErrorOr<String> dump_layout_tree()
  67. {
  68. return String::from_deprecated_string(client().dump_layout_tree());
  69. }
  70. Function<void(const URL&)> on_load_finish;
  71. private:
  72. HeadlessWebContentView() = default;
  73. void notify_server_did_layout(Badge<WebView::WebContentClient>, Gfx::IntSize) override { }
  74. void notify_server_did_paint(Badge<WebView::WebContentClient>, i32, Gfx::IntSize) override { }
  75. void notify_server_did_invalidate_content_rect(Badge<WebView::WebContentClient>, Gfx::IntRect const&) override { }
  76. void notify_server_did_change_selection(Badge<WebView::WebContentClient>) override { }
  77. void notify_server_did_request_cursor_change(Badge<WebView::WebContentClient>, Gfx::StandardCursor) override { }
  78. void notify_server_did_change_title(Badge<WebView::WebContentClient>, DeprecatedString const&) override { }
  79. void notify_server_did_request_scroll(Badge<WebView::WebContentClient>, i32, i32) override { }
  80. void notify_server_did_request_scroll_to(Badge<WebView::WebContentClient>, Gfx::IntPoint) override { }
  81. void notify_server_did_request_scroll_into_view(Badge<WebView::WebContentClient>, Gfx::IntRect const&) override { }
  82. void notify_server_did_enter_tooltip_area(Badge<WebView::WebContentClient>, Gfx::IntPoint, DeprecatedString const&) override { }
  83. void notify_server_did_leave_tooltip_area(Badge<WebView::WebContentClient>) override { }
  84. void notify_server_did_hover_link(Badge<WebView::WebContentClient>, const URL&) override { }
  85. void notify_server_did_unhover_link(Badge<WebView::WebContentClient>) override { }
  86. void notify_server_did_click_link(Badge<WebView::WebContentClient>, const URL&, DeprecatedString const&, unsigned) override { }
  87. void notify_server_did_middle_click_link(Badge<WebView::WebContentClient>, const URL&, DeprecatedString const&, unsigned) override { }
  88. void notify_server_did_start_loading(Badge<WebView::WebContentClient>, const URL&, bool) override { }
  89. void notify_server_did_finish_loading(Badge<WebView::WebContentClient>, const URL& url) override
  90. {
  91. if (on_load_finish)
  92. on_load_finish(url);
  93. }
  94. void notify_server_did_request_navigate_back(Badge<WebView::WebContentClient>) override { }
  95. void notify_server_did_request_navigate_forward(Badge<WebView::WebContentClient>) override { }
  96. void notify_server_did_request_refresh(Badge<WebView::WebContentClient>) override { }
  97. void notify_server_did_request_context_menu(Badge<WebView::WebContentClient>, Gfx::IntPoint) override { }
  98. void notify_server_did_request_link_context_menu(Badge<WebView::WebContentClient>, Gfx::IntPoint, const URL&, DeprecatedString const&, unsigned) override { }
  99. void notify_server_did_request_image_context_menu(Badge<WebView::WebContentClient>, Gfx::IntPoint, const URL&, DeprecatedString const&, unsigned, Gfx::ShareableBitmap const&) override { }
  100. void notify_server_did_request_alert(Badge<WebView::WebContentClient>, String const&) override { }
  101. void notify_server_did_request_confirm(Badge<WebView::WebContentClient>, String const&) override { }
  102. void notify_server_did_request_prompt(Badge<WebView::WebContentClient>, String const&, String const&) override { }
  103. void notify_server_did_request_set_prompt_text(Badge<WebView::WebContentClient>, String const&) override { }
  104. void notify_server_did_request_accept_dialog(Badge<WebView::WebContentClient>) override { }
  105. void notify_server_did_request_dismiss_dialog(Badge<WebView::WebContentClient>) override { }
  106. void notify_server_did_get_source(const URL&, DeprecatedString const&) override { }
  107. void notify_server_did_get_dom_tree(DeprecatedString const&) override { }
  108. void notify_server_did_get_dom_node_properties(i32, DeprecatedString const&, DeprecatedString const&, DeprecatedString const&, DeprecatedString const&) override { }
  109. void notify_server_did_get_accessibility_tree(DeprecatedString const&) override { }
  110. void notify_server_did_output_js_console_message(i32) override { }
  111. void notify_server_did_get_js_console_messages(i32, Vector<DeprecatedString> const&, Vector<DeprecatedString> const&) override { }
  112. void notify_server_did_change_favicon(Gfx::Bitmap const&) override { }
  113. Vector<Web::Cookie::Cookie> notify_server_did_request_all_cookies(Badge<WebView::WebContentClient>, URL const&) override { return {}; }
  114. Optional<Web::Cookie::Cookie> notify_server_did_request_named_cookie(Badge<WebView::WebContentClient>, URL const&, DeprecatedString const&) override { return {}; }
  115. DeprecatedString notify_server_did_request_cookie(Badge<WebView::WebContentClient>, const URL&, Web::Cookie::Source) override { return {}; }
  116. void notify_server_did_set_cookie(Badge<WebView::WebContentClient>, const URL&, Web::Cookie::ParsedCookie const&, Web::Cookie::Source) override { }
  117. void notify_server_did_update_cookie(Badge<WebView::WebContentClient>, Web::Cookie::Cookie const&) override { }
  118. String notify_server_did_request_new_tab(Badge<WebView::WebContentClient>, Web::HTML::ActivateTab) override { return {}; }
  119. void notify_server_did_request_activate_tab(Badge<WebView::WebContentClient>) override { }
  120. void notify_server_did_close_browsing_context(Badge<WebView::WebContentClient>) override { }
  121. void notify_server_did_update_resource_count(i32) override { }
  122. void notify_server_did_request_restore_window() override { }
  123. Gfx::IntPoint notify_server_did_request_reposition_window(Gfx::IntPoint) override { return {}; }
  124. Gfx::IntSize notify_server_did_request_resize_window(Gfx::IntSize) override { return {}; }
  125. Gfx::IntRect notify_server_did_request_maximize_window() override { return {}; }
  126. Gfx::IntRect notify_server_did_request_minimize_window() override { return {}; }
  127. Gfx::IntRect notify_server_did_request_fullscreen_window() override { return {}; }
  128. void notify_server_did_request_file(Badge<WebView::WebContentClient>, DeprecatedString const& path, i32 request_id) override
  129. {
  130. auto file = Core::File::open(path, Core::File::OpenMode::Read);
  131. if (file.is_error())
  132. client().async_handle_file_return(file.error().code(), {}, request_id);
  133. else
  134. client().async_handle_file_return(0, IPC::File(*file.value()), request_id);
  135. }
  136. void notify_server_did_finish_handling_input_event(bool) override { }
  137. void update_zoom() override { }
  138. void create_client(WebView::EnableCallgrindProfiling) override { }
  139. };
  140. static ErrorOr<NonnullRefPtr<Core::Timer>> load_page_for_screenshot_and_exit(Core::EventLoop& event_loop, HeadlessWebContentView& view, int screenshot_timeout)
  141. {
  142. // FIXME: Allow passing the output path as an argument.
  143. static constexpr auto output_file_path = "output.png"sv;
  144. if (FileSystem::exists(output_file_path))
  145. TRY(FileSystem::remove(output_file_path, FileSystem::RecursionMode::Disallowed));
  146. outln("Taking screenshot after {} seconds", screenshot_timeout);
  147. auto timer = TRY(Core::Timer::create_single_shot(
  148. screenshot_timeout * 1000,
  149. [&]() {
  150. if (auto screenshot = view.take_screenshot()) {
  151. outln("Saving screenshot to {}", output_file_path);
  152. auto output_file = MUST(Core::File::open(output_file_path, Core::File::OpenMode::Write));
  153. auto image_buffer = MUST(Gfx::PNGWriter::encode(*screenshot));
  154. MUST(output_file->write_until_depleted(image_buffer.bytes()));
  155. } else {
  156. warnln("No screenshot available");
  157. }
  158. event_loop.quit(0);
  159. }));
  160. timer->start();
  161. return timer;
  162. }
  163. static ErrorOr<URL> format_url(StringView url)
  164. {
  165. if (FileSystem::exists(url))
  166. return URL::create_with_file_scheme(Core::DeprecatedFile::real_path_for(url));
  167. URL formatted_url { url };
  168. if (!formatted_url.is_valid())
  169. formatted_url = TRY(String::formatted("http://{}", url));
  170. return formatted_url;
  171. }
  172. ErrorOr<int> serenity_main(Main::Arguments arguments)
  173. {
  174. #if !defined(AK_OS_SERENITY)
  175. QCoreApplication app(arguments.argc, arguments.argv);
  176. #endif
  177. Core::EventLoop event_loop;
  178. int screenshot_timeout = 1;
  179. StringView url;
  180. auto resources_folder = "/res"sv;
  181. StringView web_driver_ipc_path;
  182. bool dump_layout_tree = false;
  183. bool is_layout_test_mode = false;
  184. Core::ArgsParser args_parser;
  185. args_parser.set_general_help("This utility runs the Browser in headless mode.");
  186. args_parser.add_option(screenshot_timeout, "Take a screenshot after [n] seconds (default: 1)", "screenshot", 's', "n");
  187. args_parser.add_option(dump_layout_tree, "Dump layout tree and exit", "dump-layout-tree", 'd');
  188. args_parser.add_option(resources_folder, "Path of the base resources folder (defaults to /res)", "resources", 'r', "resources-root-path");
  189. args_parser.add_option(web_driver_ipc_path, "Path to the WebDriver IPC socket", "webdriver-ipc-path", 0, "path");
  190. args_parser.add_option(is_layout_test_mode, "Enable layout test mode", "layout-test-mode", 0);
  191. args_parser.add_positional_argument(url, "URL to open", "url", Core::ArgsParser::Required::Yes);
  192. args_parser.parse(arguments);
  193. Gfx::FontDatabase::set_default_font_query("Katica 10 400 0");
  194. Gfx::FontDatabase::set_window_title_font_query("Katica 10 700 0");
  195. Gfx::FontDatabase::set_fixed_width_font_query("Csilla 10 400 0");
  196. auto fonts_path = LexicalPath::join(resources_folder, "fonts"sv);
  197. Gfx::FontDatabase::set_default_fonts_lookup_path(fonts_path.string());
  198. auto theme_path = LexicalPath::join(resources_folder, "themes"sv, "Default.ini"sv);
  199. auto theme = TRY(Gfx::load_system_theme(theme_path.string()));
  200. // FIXME: Allow passing the window size as an argument.
  201. static constexpr Gfx::IntSize window_size { 800, 600 };
  202. auto view = TRY(HeadlessWebContentView::create(move(theme), window_size, web_driver_ipc_path, is_layout_test_mode ? WebView::IsLayoutTestMode::Yes : WebView::IsLayoutTestMode::No));
  203. RefPtr<Core::Timer> timer;
  204. if (dump_layout_tree) {
  205. view->on_load_finish = [&](auto const&) {
  206. auto layout_tree = view->dump_layout_tree().release_value_but_fixme_should_propagate_errors();
  207. out("{}", layout_tree);
  208. fflush(stdout);
  209. event_loop.quit(0);
  210. };
  211. } else if (web_driver_ipc_path.is_empty()) {
  212. timer = TRY(load_page_for_screenshot_and_exit(event_loop, *view, screenshot_timeout));
  213. }
  214. view->load(TRY(format_url(url)));
  215. return event_loop.exec();
  216. }