headless-browser.cpp 17 KB

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