headless-browser.cpp 18 KB

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