headless-browser.cpp 18 KB

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