headless-browser.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*
  2. * Copyright (c) 2022, Dex♪ <dexes.ttp@gmail.com>
  3. * Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
  4. * Copyright (c) 2023, Andreas Kling <kling@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Badge.h>
  9. #include <AK/DeprecatedString.h>
  10. #include <AK/Function.h>
  11. #include <AK/LexicalPath.h>
  12. #include <AK/NonnullOwnPtr.h>
  13. #include <AK/Platform.h>
  14. #include <AK/String.h>
  15. #include <AK/URL.h>
  16. #include <AK/Vector.h>
  17. #include <LibCore/ArgsParser.h>
  18. #include <LibCore/DirIterator.h>
  19. #include <LibCore/EventLoop.h>
  20. #include <LibCore/File.h>
  21. #include <LibCore/Timer.h>
  22. #include <LibDiff/Format.h>
  23. #include <LibDiff/Generator.h>
  24. #include <LibFileSystem/FileSystem.h>
  25. #include <LibGfx/Bitmap.h>
  26. #include <LibGfx/Font/FontDatabase.h>
  27. #include <LibGfx/ImageFormats/PNGWriter.h>
  28. #include <LibGfx/Point.h>
  29. #include <LibGfx/Rect.h>
  30. #include <LibGfx/ShareableBitmap.h>
  31. #include <LibGfx/Size.h>
  32. #include <LibGfx/StandardCursor.h>
  33. #include <LibGfx/SystemTheme.h>
  34. #include <LibIPC/File.h>
  35. #include <LibWeb/Cookie/Cookie.h>
  36. #include <LibWeb/Cookie/ParsedCookie.h>
  37. #include <LibWeb/HTML/ActivateTab.h>
  38. #include <LibWeb/Loader/FrameLoader.h>
  39. #include <LibWebView/ViewImplementation.h>
  40. #include <LibWebView/WebContentClient.h>
  41. #if !defined(AK_OS_SERENITY)
  42. # include <Ladybird/HelperProcess.h>
  43. # include <Ladybird/Utilities.h>
  44. #endif
  45. class HeadlessWebContentView final : public WebView::ViewImplementation {
  46. public:
  47. 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, WebView::UseJavaScriptBytecode use_javascript_bytecode = WebView::UseJavaScriptBytecode::No)
  48. {
  49. auto view = TRY(adopt_nonnull_own_or_enomem(new (nothrow) HeadlessWebContentView(use_javascript_bytecode)));
  50. #if defined(AK_OS_SERENITY)
  51. view->m_client_state.client = TRY(WebView::WebContentClient::try_create(*view));
  52. (void)is_layout_test_mode;
  53. (void)use_javascript_bytecode;
  54. #else
  55. auto candidate_web_content_paths = TRY(get_paths_for_helper_process("WebContent"sv));
  56. view->m_client_state.client = TRY(launch_web_content_process(*view, candidate_web_content_paths, WebView::EnableCallgrindProfiling::No, is_layout_test_mode, use_javascript_bytecode, Ladybird::UseLagomNetworking::No));
  57. #endif
  58. view->client().async_update_system_theme(move(theme));
  59. view->client().async_update_system_fonts(Gfx::FontDatabase::default_font_query(), Gfx::FontDatabase::fixed_width_font_query(), Gfx::FontDatabase::window_title_font_query());
  60. view->m_viewport_rect = { { 0, 0 }, window_size };
  61. view->client().async_set_viewport_rect(view->m_viewport_rect);
  62. view->client().async_set_window_size(window_size);
  63. if (!web_driver_ipc_path.is_empty())
  64. view->client().async_connect_to_webdriver(web_driver_ipc_path);
  65. return view;
  66. }
  67. RefPtr<Gfx::Bitmap> take_screenshot()
  68. {
  69. return client().take_document_screenshot().bitmap();
  70. }
  71. ErrorOr<String> dump_layout_tree()
  72. {
  73. return String::from_deprecated_string(client().dump_layout_tree());
  74. }
  75. ErrorOr<String> dump_paint_tree()
  76. {
  77. return String::from_deprecated_string(client().dump_paint_tree());
  78. }
  79. ErrorOr<String> dump_text()
  80. {
  81. return String::from_deprecated_string(client().dump_text());
  82. }
  83. void clear_content_filters()
  84. {
  85. client().async_set_content_filters({});
  86. }
  87. private:
  88. HeadlessWebContentView(WebView::UseJavaScriptBytecode use_javascript_bytecode)
  89. : WebView::ViewImplementation(use_javascript_bytecode)
  90. {
  91. }
  92. void notify_server_did_layout(Badge<WebView::WebContentClient>, Gfx::IntSize) override { }
  93. void notify_server_did_paint(Badge<WebView::WebContentClient>, i32, Gfx::IntSize) override { }
  94. void notify_server_did_invalidate_content_rect(Badge<WebView::WebContentClient>, Gfx::IntRect const&) override { }
  95. void notify_server_did_change_selection(Badge<WebView::WebContentClient>) override { }
  96. void notify_server_did_request_cursor_change(Badge<WebView::WebContentClient>, Gfx::StandardCursor) override { }
  97. void notify_server_did_request_scroll(Badge<WebView::WebContentClient>, i32, i32) override { }
  98. void notify_server_did_request_scroll_to(Badge<WebView::WebContentClient>, Gfx::IntPoint) override { }
  99. void notify_server_did_request_scroll_into_view(Badge<WebView::WebContentClient>, Gfx::IntRect const&) override { }
  100. void notify_server_did_enter_tooltip_area(Badge<WebView::WebContentClient>, Gfx::IntPoint, DeprecatedString const&) override { }
  101. void notify_server_did_leave_tooltip_area(Badge<WebView::WebContentClient>) override { }
  102. void notify_server_did_request_alert(Badge<WebView::WebContentClient>, String const&) override { }
  103. void notify_server_did_request_confirm(Badge<WebView::WebContentClient>, String const&) override { }
  104. void notify_server_did_request_prompt(Badge<WebView::WebContentClient>, String const&, String const&) override { }
  105. void notify_server_did_request_set_prompt_text(Badge<WebView::WebContentClient>, String const&) override { }
  106. void notify_server_did_request_accept_dialog(Badge<WebView::WebContentClient>) override { }
  107. void notify_server_did_request_dismiss_dialog(Badge<WebView::WebContentClient>) override { }
  108. void notify_server_did_request_file(Badge<WebView::WebContentClient>, DeprecatedString const& path, i32 request_id) override
  109. {
  110. auto file = Core::File::open(path, Core::File::OpenMode::Read);
  111. if (file.is_error())
  112. client().async_handle_file_return(file.error().code(), {}, request_id);
  113. else
  114. client().async_handle_file_return(0, IPC::File(*file.value()), request_id);
  115. }
  116. void notify_server_did_finish_handling_input_event(bool) override { }
  117. void update_zoom() override { }
  118. void create_client(WebView::EnableCallgrindProfiling) override { }
  119. virtual Gfx::IntRect viewport_rect() const override { return m_viewport_rect; }
  120. virtual Gfx::IntPoint to_content_position(Gfx::IntPoint widget_position) const override { return widget_position; }
  121. virtual Gfx::IntPoint to_widget_position(Gfx::IntPoint content_position) const override { return content_position; }
  122. private:
  123. Gfx::IntRect m_viewport_rect;
  124. };
  125. static ErrorOr<NonnullRefPtr<Core::Timer>> load_page_for_screenshot_and_exit(Core::EventLoop& event_loop, HeadlessWebContentView& view, int screenshot_timeout)
  126. {
  127. // FIXME: Allow passing the output path as an argument.
  128. static constexpr auto output_file_path = "output.png"sv;
  129. if (FileSystem::exists(output_file_path))
  130. TRY(FileSystem::remove(output_file_path, FileSystem::RecursionMode::Disallowed));
  131. outln("Taking screenshot after {} seconds", screenshot_timeout);
  132. auto timer = TRY(Core::Timer::create_single_shot(
  133. screenshot_timeout * 1000,
  134. [&]() {
  135. if (auto screenshot = view.take_screenshot()) {
  136. outln("Saving screenshot to {}", output_file_path);
  137. auto output_file = MUST(Core::File::open(output_file_path, Core::File::OpenMode::Write));
  138. auto image_buffer = MUST(Gfx::PNGWriter::encode(*screenshot));
  139. MUST(output_file->write_until_depleted(image_buffer.bytes()));
  140. } else {
  141. warnln("No screenshot available");
  142. }
  143. event_loop.quit(0);
  144. }));
  145. timer->start();
  146. return timer;
  147. }
  148. static ErrorOr<URL> format_url(StringView url)
  149. {
  150. if (FileSystem::exists(url))
  151. return URL::create_with_file_scheme(TRY(FileSystem::real_path(url)).to_deprecated_string());
  152. URL formatted_url { url };
  153. if (!formatted_url.is_valid())
  154. formatted_url = TRY(String::formatted("http://{}", url));
  155. return formatted_url;
  156. }
  157. enum class TestMode {
  158. Layout,
  159. Text,
  160. };
  161. static ErrorOr<String> run_one_test(HeadlessWebContentView& view, StringView input_path, StringView expectation_path, TestMode mode, int timeout_in_milliseconds = 15000)
  162. {
  163. Core::EventLoop loop;
  164. bool did_timeout = false;
  165. auto timeout_timer = TRY(Core::Timer::create_single_shot(5000, [&] {
  166. did_timeout = true;
  167. loop.quit(0);
  168. }));
  169. view.load(URL::create_with_file_scheme(TRY(FileSystem::real_path(input_path)).to_deprecated_string()));
  170. (void)expectation_path;
  171. String result;
  172. if (mode == TestMode::Layout) {
  173. view.on_load_finish = [&](auto const&) {
  174. // NOTE: We take a screenshot here to force the lazy layout of SVG-as-image documents to happen.
  175. // It also causes a lot more code to run, which is good for finding bugs. :^)
  176. (void)view.take_screenshot();
  177. StringBuilder builder;
  178. builder.append(view.dump_layout_tree().release_value_but_fixme_should_propagate_errors());
  179. builder.append("\n"sv);
  180. builder.append(view.dump_paint_tree().release_value_but_fixme_should_propagate_errors());
  181. result = builder.to_string().release_value_but_fixme_should_propagate_errors();
  182. loop.quit(0);
  183. };
  184. } else if (mode == TestMode::Text) {
  185. view.on_load_finish = [&](auto const&) {
  186. result = view.dump_text().release_value_but_fixme_should_propagate_errors();
  187. loop.quit(0);
  188. };
  189. }
  190. timeout_timer->start(timeout_in_milliseconds);
  191. loop.exec();
  192. if (did_timeout)
  193. return Error::from_errno(ETIMEDOUT);
  194. return result;
  195. }
  196. enum class TestResult {
  197. Pass,
  198. Fail,
  199. Timeout,
  200. };
  201. static ErrorOr<TestResult> run_test(HeadlessWebContentView& view, StringView input_path, StringView expectation_path, TestMode mode)
  202. {
  203. auto result = run_one_test(view, input_path, expectation_path, mode);
  204. if (result.is_error() && result.error().code() == ETIMEDOUT)
  205. return TestResult::Timeout;
  206. if (result.is_error())
  207. return result.release_error();
  208. auto expectation_file_or_error = Core::File::open(expectation_path, Core::File::OpenMode::Read);
  209. if (expectation_file_or_error.is_error()) {
  210. warnln("Failed opening '{}': {}", expectation_path, expectation_file_or_error.error());
  211. return expectation_file_or_error.release_error();
  212. }
  213. auto expectation_file = expectation_file_or_error.release_value();
  214. auto expectation = TRY(String::from_utf8(StringView(TRY(expectation_file->read_until_eof()).bytes())));
  215. auto actual = result.release_value();
  216. auto actual_trimmed = TRY(actual.trim("\n"sv, TrimMode::Right));
  217. auto expectation_trimmed = TRY(expectation.trim("\n"sv, TrimMode::Right));
  218. if (actual_trimmed == expectation_trimmed)
  219. return TestResult::Pass;
  220. auto const color_output = isatty(STDOUT_FILENO) ? Diff::ColorOutput::Yes : Diff::ColorOutput::No;
  221. if (color_output == Diff::ColorOutput::Yes)
  222. outln("\n\033[33;1mTest failed\033[0m: {}", input_path);
  223. else
  224. outln("\nTest failed: {}", input_path);
  225. auto hunks = TRY(Diff::from_text(expectation, actual, 3));
  226. auto out = TRY(Core::File::standard_output());
  227. TRY(Diff::write_unified_header(expectation_path, expectation_path, *out));
  228. for (auto const& hunk : hunks)
  229. TRY(Diff::write_unified(hunk, *out, color_output));
  230. return TestResult::Fail;
  231. }
  232. struct Test {
  233. String input_path;
  234. String expectation_path;
  235. TestMode mode;
  236. Optional<TestResult> result;
  237. };
  238. static ErrorOr<void> collect_tests(Vector<Test>& tests, StringView path, StringView trail, TestMode mode)
  239. {
  240. Core::DirIterator it(TRY(String::formatted("{}/input/{}", path, trail)).to_deprecated_string(), Core::DirIterator::Flags::SkipDots);
  241. while (it.has_next()) {
  242. auto name = it.next_path();
  243. auto input_path = TRY(FileSystem::real_path(TRY(String::formatted("{}/input/{}/{}", path, trail, name))));
  244. if (FileSystem::is_directory(input_path)) {
  245. TRY(collect_tests(tests, path, TRY(String::formatted("{}/{}", trail, name)), mode));
  246. continue;
  247. }
  248. if (!name.ends_with(".html"sv))
  249. continue;
  250. auto basename = LexicalPath::title(name);
  251. auto expectation_path = TRY(String::formatted("{}/expected/{}/{}.txt", path, trail, basename));
  252. tests.append({ move(input_path), move(expectation_path), mode, {} });
  253. }
  254. return {};
  255. }
  256. static ErrorOr<int> run_tests(HeadlessWebContentView& view, StringView test_root_path)
  257. {
  258. view.clear_content_filters();
  259. Vector<Test> tests;
  260. TRY(collect_tests(tests, TRY(String::formatted("{}/Layout", test_root_path)), "."sv, TestMode::Layout));
  261. TRY(collect_tests(tests, TRY(String::formatted("{}/Text", test_root_path)), "."sv, TestMode::Text));
  262. size_t pass_count = 0;
  263. size_t fail_count = 0;
  264. size_t timeout_count = 0;
  265. bool is_tty = isatty(STDOUT_FILENO);
  266. outln("Running {} tests...", tests.size());
  267. for (size_t i = 0; i < tests.size(); ++i) {
  268. auto& test = tests[i];
  269. if (is_tty) {
  270. // Keep clearing and reusing the same line if stdout is a TTY.
  271. out("\33[2K\r");
  272. }
  273. out("{}/{}: {}", i + 1, tests.size(), LexicalPath::relative_path(test.input_path, test_root_path));
  274. if (is_tty)
  275. fflush(stdout);
  276. else
  277. outln("");
  278. test.result = TRY(run_test(view, test.input_path, test.expectation_path, test.mode));
  279. switch (*test.result) {
  280. case TestResult::Pass:
  281. ++pass_count;
  282. break;
  283. case TestResult::Fail:
  284. ++fail_count;
  285. break;
  286. case TestResult::Timeout:
  287. ++timeout_count;
  288. break;
  289. }
  290. }
  291. if (is_tty)
  292. outln("\33[2K\rDone!");
  293. outln("==================================================");
  294. outln("Pass: {}, Fail: {}, Timeout: {}", pass_count, fail_count, timeout_count);
  295. outln("==================================================");
  296. for (auto& test : tests) {
  297. if (*test.result == TestResult::Pass)
  298. continue;
  299. outln("{}: {}", *test.result == TestResult::Fail ? "Fail" : "Timeout", test.input_path);
  300. }
  301. if (timeout_count == 0 && fail_count == 0)
  302. return 0;
  303. return 1;
  304. }
  305. ErrorOr<int> serenity_main(Main::Arguments arguments)
  306. {
  307. Core::EventLoop event_loop;
  308. int screenshot_timeout = 1;
  309. StringView url;
  310. auto resources_folder = "/res"sv;
  311. StringView web_driver_ipc_path;
  312. bool dump_layout_tree = false;
  313. bool dump_text = false;
  314. bool is_layout_test_mode = false;
  315. StringView test_root_path;
  316. Core::ArgsParser args_parser;
  317. args_parser.set_general_help("This utility runs the Browser in headless mode.");
  318. args_parser.add_option(screenshot_timeout, "Take a screenshot after [n] seconds (default: 1)", "screenshot", 's', "n");
  319. args_parser.add_option(dump_layout_tree, "Dump layout tree and exit", "dump-layout-tree", 'd');
  320. args_parser.add_option(dump_text, "Dump text and exit", "dump-text", 'T');
  321. args_parser.add_option(test_root_path, "Run tests in path", "run-tests", 'R', "test-root-path");
  322. args_parser.add_option(resources_folder, "Path of the base resources folder (defaults to /res)", "resources", 'r', "resources-root-path");
  323. args_parser.add_option(web_driver_ipc_path, "Path to the WebDriver IPC socket", "webdriver-ipc-path", 0, "path");
  324. args_parser.add_option(is_layout_test_mode, "Enable layout test mode", "layout-test-mode", 0);
  325. args_parser.add_positional_argument(url, "URL to open", "url", Core::ArgsParser::Required::No);
  326. args_parser.parse(arguments);
  327. Gfx::FontDatabase::set_default_font_query("Katica 10 400 0");
  328. Gfx::FontDatabase::set_window_title_font_query("Katica 10 700 0");
  329. Gfx::FontDatabase::set_fixed_width_font_query("Csilla 10 400 0");
  330. auto fonts_path = LexicalPath::join(resources_folder, "fonts"sv);
  331. Gfx::FontDatabase::set_default_fonts_lookup_path(fonts_path.string());
  332. auto theme_path = LexicalPath::join(resources_folder, "themes"sv, "Default.ini"sv);
  333. auto theme = TRY(Gfx::load_system_theme(theme_path.string()));
  334. // FIXME: Allow passing the window size as an argument.
  335. static constexpr Gfx::IntSize window_size { 800, 600 };
  336. if (!test_root_path.is_empty()) {
  337. // --run-tests implies --layout-test-mode.
  338. is_layout_test_mode = true;
  339. }
  340. auto view = TRY(HeadlessWebContentView::create(move(theme), window_size, web_driver_ipc_path, is_layout_test_mode ? WebView::IsLayoutTestMode::Yes : WebView::IsLayoutTestMode::No, WebView::UseJavaScriptBytecode::Yes));
  341. RefPtr<Core::Timer> timer;
  342. if (!test_root_path.is_empty()) {
  343. return run_tests(*view, test_root_path);
  344. }
  345. if (dump_layout_tree) {
  346. view->on_load_finish = [&](auto const&) {
  347. (void)view->take_screenshot();
  348. auto layout_tree = view->dump_layout_tree().release_value_but_fixme_should_propagate_errors();
  349. auto paint_tree = view->dump_paint_tree().release_value_but_fixme_should_propagate_errors();
  350. out("{}\n{}", layout_tree, paint_tree);
  351. fflush(stdout);
  352. event_loop.quit(0);
  353. };
  354. } else if (dump_text) {
  355. view->on_load_finish = [&](auto const&) {
  356. auto text = view->dump_text().release_value_but_fixme_should_propagate_errors();
  357. out("{}", text);
  358. fflush(stdout);
  359. event_loop.quit(0);
  360. };
  361. } else if (web_driver_ipc_path.is_empty()) {
  362. timer = TRY(load_page_for_screenshot_and_exit(event_loop, *view, screenshot_timeout));
  363. }
  364. view->load(TRY(format_url(url)));
  365. return event_loop.exec();
  366. }