headless-browser.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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/ByteString.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 <Ladybird/Types.h>
  21. #include <LibCore/ArgsParser.h>
  22. #include <LibCore/ConfigFile.h>
  23. #include <LibCore/DirIterator.h>
  24. #include <LibCore/Directory.h>
  25. #include <LibCore/EventLoop.h>
  26. #include <LibCore/File.h>
  27. #include <LibCore/Promise.h>
  28. #include <LibCore/ResourceImplementationFile.h>
  29. #include <LibCore/Timer.h>
  30. #include <LibDiff/Format.h>
  31. #include <LibDiff/Generator.h>
  32. #include <LibFileSystem/FileSystem.h>
  33. #include <LibGfx/Bitmap.h>
  34. #include <LibGfx/Font/FontDatabase.h>
  35. #include <LibGfx/ImageFormats/PNGWriter.h>
  36. #include <LibGfx/Point.h>
  37. #include <LibGfx/Rect.h>
  38. #include <LibGfx/ShareableBitmap.h>
  39. #include <LibGfx/Size.h>
  40. #include <LibGfx/StandardCursor.h>
  41. #include <LibGfx/SystemTheme.h>
  42. #include <LibIPC/File.h>
  43. #include <LibWeb/Cookie/Cookie.h>
  44. #include <LibWeb/Cookie/ParsedCookie.h>
  45. #include <LibWeb/HTML/ActivateTab.h>
  46. #include <LibWeb/Worker/WebWorkerClient.h>
  47. #include <LibWebView/CookieJar.h>
  48. #include <LibWebView/Database.h>
  49. #include <LibWebView/URL.h>
  50. #include <LibWebView/ViewImplementation.h>
  51. #include <LibWebView/WebContentClient.h>
  52. #if !defined(AK_OS_SERENITY)
  53. # include <Ladybird/HelperProcess.h>
  54. # include <Ladybird/Utilities.h>
  55. #endif
  56. constexpr int DEFAULT_TIMEOUT_MS = 30000; // 30sec
  57. static StringView s_current_test_path;
  58. class HeadlessWebContentView final : public WebView::ViewImplementation {
  59. public:
  60. static ErrorOr<NonnullOwnPtr<HeadlessWebContentView>> create(Core::AnonymousBuffer theme, Gfx::IntSize const& window_size, StringView web_driver_ipc_path, Ladybird::IsLayoutTestMode is_layout_test_mode = Ladybird::IsLayoutTestMode::No)
  61. {
  62. #if defined(AK_OS_SERENITY)
  63. auto database = TRY(WebView::Database::create());
  64. #else
  65. auto sql_server_paths = TRY(get_paths_for_helper_process("SQLServer"sv));
  66. auto database = TRY(WebView::Database::create(move(sql_server_paths)));
  67. #endif
  68. auto cookie_jar = TRY(WebView::CookieJar::create(*database));
  69. auto view = TRY(adopt_nonnull_own_or_enomem(new (nothrow) HeadlessWebContentView(move(database), move(cookie_jar))));
  70. #if defined(AK_OS_SERENITY)
  71. view->m_client_state.client = TRY(WebView::WebContentClient::try_create(*view));
  72. (void)is_layout_test_mode;
  73. #else
  74. Ladybird::WebContentOptions web_content_options { .is_layout_test_mode = is_layout_test_mode };
  75. auto candidate_web_content_paths = TRY(get_paths_for_helper_process("WebContent"sv));
  76. view->m_client_state.client = TRY(launch_web_content_process(*view, candidate_web_content_paths, web_content_options));
  77. #endif
  78. view->client().async_update_system_theme(move(theme));
  79. view->client().async_update_system_fonts(Gfx::FontDatabase::default_font_query(), Gfx::FontDatabase::fixed_width_font_query(), Gfx::FontDatabase::window_title_font_query());
  80. view->m_viewport_rect = { { 0, 0 }, window_size };
  81. view->client().async_set_viewport_rect(view->m_viewport_rect.to_type<Web::DevicePixels>());
  82. view->client().async_set_window_size(window_size.to_type<Web::DevicePixels>());
  83. if (!web_driver_ipc_path.is_empty())
  84. view->client().async_connect_to_webdriver(web_driver_ipc_path);
  85. view->m_client_state.client->on_web_content_process_crash = [] {
  86. warnln("\033[31;1mWebContent Crashed!!\033[0m");
  87. if (!s_current_test_path.is_empty()) {
  88. warnln(" Last started test: {}", s_current_test_path);
  89. }
  90. VERIFY_NOT_REACHED();
  91. };
  92. return view;
  93. }
  94. RefPtr<Gfx::Bitmap> take_screenshot()
  95. {
  96. VERIFY(!m_pending_screenshot);
  97. m_pending_screenshot = Core::Promise<RefPtr<Gfx::Bitmap>>::construct();
  98. client().async_take_document_screenshot();
  99. auto screenshot = MUST(m_pending_screenshot->await());
  100. m_pending_screenshot = nullptr;
  101. return screenshot;
  102. }
  103. virtual void did_receive_screenshot(Badge<WebView::WebContentClient>, Gfx::ShareableBitmap const& screenshot) override
  104. {
  105. VERIFY(m_pending_screenshot);
  106. m_pending_screenshot->resolve(screenshot.bitmap());
  107. }
  108. ErrorOr<String> dump_layout_tree()
  109. {
  110. return String::from_byte_string(client().dump_layout_tree());
  111. }
  112. ErrorOr<String> dump_paint_tree()
  113. {
  114. return String::from_byte_string(client().dump_paint_tree());
  115. }
  116. ErrorOr<String> dump_text()
  117. {
  118. return String::from_byte_string(client().dump_text());
  119. }
  120. void clear_content_filters()
  121. {
  122. client().async_set_content_filters({});
  123. }
  124. private:
  125. HeadlessWebContentView(NonnullRefPtr<WebView::Database> database, WebView::CookieJar cookie_jar)
  126. : m_database(move(database))
  127. , m_cookie_jar(move(cookie_jar))
  128. {
  129. on_scroll_to_point = [this](auto position) {
  130. m_viewport_rect.set_location(position);
  131. client().async_set_viewport_rect(m_viewport_rect.to_type<Web::DevicePixels>());
  132. };
  133. on_scroll_by_delta = [this](auto x_delta, auto y_delta) {
  134. auto position = m_viewport_rect.location();
  135. position.set_x(position.x() + x_delta);
  136. position.set_y(position.y() + y_delta);
  137. if (on_scroll_to_point)
  138. on_scroll_to_point(position);
  139. };
  140. on_get_cookie = [this](auto const& url, auto source) -> ByteString {
  141. return m_cookie_jar.get_cookie(url, source);
  142. };
  143. on_set_cookie = [this](auto const& url, auto const& cookie, auto source) {
  144. m_cookie_jar.set_cookie(url, cookie, source);
  145. };
  146. on_request_worker_agent = []() {
  147. #if defined(AK_OS_SERENITY)
  148. auto worker_client = MUST(Web::HTML::WebWorkerClient::try_create());
  149. #else
  150. auto worker_client = MUST(launch_web_worker_process(MUST(get_paths_for_helper_process("WebWorker"sv))));
  151. #endif
  152. return worker_client->dup_sockets();
  153. };
  154. }
  155. void update_zoom() override { }
  156. void create_client() override { }
  157. virtual Web::DevicePixelRect viewport_rect() const override { return m_viewport_rect.to_type<Web::DevicePixels>(); }
  158. virtual Gfx::IntPoint to_content_position(Gfx::IntPoint widget_position) const override { return widget_position; }
  159. virtual Gfx::IntPoint to_widget_position(Gfx::IntPoint content_position) const override { return content_position; }
  160. private:
  161. Gfx::IntRect m_viewport_rect;
  162. RefPtr<Core::Promise<RefPtr<Gfx::Bitmap>>> m_pending_screenshot;
  163. NonnullRefPtr<WebView::Database> m_database;
  164. WebView::CookieJar m_cookie_jar;
  165. };
  166. static ErrorOr<NonnullRefPtr<Core::Timer>> load_page_for_screenshot_and_exit(Core::EventLoop& event_loop, HeadlessWebContentView& view, int screenshot_timeout)
  167. {
  168. // FIXME: Allow passing the output path as an argument.
  169. static constexpr auto output_file_path = "output.png"sv;
  170. if (FileSystem::exists(output_file_path))
  171. TRY(FileSystem::remove(output_file_path, FileSystem::RecursionMode::Disallowed));
  172. outln("Taking screenshot after {} seconds", screenshot_timeout);
  173. auto timer = TRY(Core::Timer::create_single_shot(
  174. screenshot_timeout * 1000,
  175. [&]() {
  176. if (auto screenshot = view.take_screenshot()) {
  177. outln("Saving screenshot to {}", output_file_path);
  178. auto output_file = MUST(Core::File::open(output_file_path, Core::File::OpenMode::Write));
  179. auto image_buffer = MUST(Gfx::PNGWriter::encode(*screenshot));
  180. MUST(output_file->write_until_depleted(image_buffer.bytes()));
  181. } else {
  182. warnln("No screenshot available");
  183. }
  184. event_loop.quit(0);
  185. }));
  186. timer->start();
  187. return timer;
  188. }
  189. enum class TestMode {
  190. Layout,
  191. Text,
  192. Ref,
  193. };
  194. enum class TestResult {
  195. Pass,
  196. Fail,
  197. Skipped,
  198. Timeout,
  199. };
  200. static StringView test_result_to_string(TestResult result)
  201. {
  202. switch (result) {
  203. case TestResult::Pass:
  204. return "Pass"sv;
  205. case TestResult::Fail:
  206. return "Fail"sv;
  207. case TestResult::Skipped:
  208. return "Skipped"sv;
  209. case TestResult::Timeout:
  210. return "Timeout"sv;
  211. }
  212. VERIFY_NOT_REACHED();
  213. }
  214. static ErrorOr<TestResult> run_dump_test(HeadlessWebContentView& view, StringView input_path, StringView expectation_path, TestMode mode, int timeout_in_milliseconds = DEFAULT_TIMEOUT_MS)
  215. {
  216. Core::EventLoop loop;
  217. bool did_timeout = false;
  218. auto timeout_timer = TRY(Core::Timer::create_single_shot(timeout_in_milliseconds, [&] {
  219. did_timeout = true;
  220. loop.quit(0);
  221. }));
  222. auto url = URL::create_with_file_scheme(TRY(FileSystem::real_path(input_path)).to_byte_string());
  223. String result;
  224. auto did_finish_test = false;
  225. auto did_finish_loading = false;
  226. if (mode == TestMode::Layout) {
  227. view.on_load_finish = [&](auto const& loaded_url) {
  228. VERIFY(url.equals(loaded_url, URL::ExcludeFragment::Yes));
  229. // NOTE: We take a screenshot here to force the lazy layout of SVG-as-image documents to happen.
  230. // It also causes a lot more code to run, which is good for finding bugs. :^)
  231. (void)view.take_screenshot();
  232. StringBuilder builder;
  233. builder.append(view.dump_layout_tree().release_value_but_fixme_should_propagate_errors());
  234. builder.append("\n"sv);
  235. builder.append(view.dump_paint_tree().release_value_but_fixme_should_propagate_errors());
  236. result = builder.to_string().release_value_but_fixme_should_propagate_errors();
  237. loop.quit(0);
  238. };
  239. view.on_text_test_finish = {};
  240. } else if (mode == TestMode::Text) {
  241. view.on_load_finish = [&](auto const& loaded_url) {
  242. VERIFY(url.equals(loaded_url, URL::ExcludeFragment::Yes));
  243. did_finish_loading = true;
  244. if (did_finish_test)
  245. loop.quit(0);
  246. };
  247. view.on_text_test_finish = [&]() {
  248. result = view.dump_text().release_value_but_fixme_should_propagate_errors();
  249. did_finish_test = true;
  250. if (did_finish_loading)
  251. loop.quit(0);
  252. };
  253. }
  254. view.load(url);
  255. timeout_timer->start();
  256. loop.exec();
  257. if (did_timeout)
  258. return TestResult::Timeout;
  259. if (expectation_path.is_empty()) {
  260. out("{}", result);
  261. return TestResult::Skipped;
  262. }
  263. auto expectation_file_or_error = Core::File::open(expectation_path, Core::File::OpenMode::Read);
  264. if (expectation_file_or_error.is_error()) {
  265. warnln("Failed opening '{}': {}", expectation_path, expectation_file_or_error.error());
  266. return expectation_file_or_error.release_error();
  267. }
  268. auto expectation_file = expectation_file_or_error.release_value();
  269. auto expectation = TRY(String::from_utf8(StringView(TRY(expectation_file->read_until_eof()).bytes())));
  270. auto actual = result;
  271. auto actual_trimmed = TRY(actual.trim("\n"sv, TrimMode::Right));
  272. auto expectation_trimmed = TRY(expectation.trim("\n"sv, TrimMode::Right));
  273. if (actual_trimmed == expectation_trimmed)
  274. return TestResult::Pass;
  275. auto const color_output = isatty(STDOUT_FILENO) ? Diff::ColorOutput::Yes : Diff::ColorOutput::No;
  276. if (color_output == Diff::ColorOutput::Yes)
  277. outln("\n\033[33;1mTest failed\033[0m: {}", input_path);
  278. else
  279. outln("\nTest failed: {}", input_path);
  280. auto hunks = TRY(Diff::from_text(expectation, actual, 3));
  281. auto out = TRY(Core::File::standard_output());
  282. TRY(Diff::write_unified_header(expectation_path, expectation_path, *out));
  283. for (auto const& hunk : hunks)
  284. TRY(Diff::write_unified(hunk, *out, color_output));
  285. return TestResult::Fail;
  286. }
  287. static ErrorOr<TestResult> run_ref_test(HeadlessWebContentView& view, StringView input_path, bool dump_failed_ref_tests, int timeout_in_milliseconds = DEFAULT_TIMEOUT_MS)
  288. {
  289. Core::EventLoop loop;
  290. bool did_timeout = false;
  291. auto timeout_timer = TRY(Core::Timer::create_single_shot(timeout_in_milliseconds, [&] {
  292. did_timeout = true;
  293. loop.quit(0);
  294. }));
  295. view.load(URL::create_with_file_scheme(TRY(FileSystem::real_path(input_path)).to_byte_string()));
  296. RefPtr<Gfx::Bitmap> actual_screenshot, expectation_screenshot;
  297. view.on_load_finish = [&](auto const&) {
  298. if (actual_screenshot) {
  299. expectation_screenshot = view.take_screenshot();
  300. loop.quit(0);
  301. } else {
  302. actual_screenshot = view.take_screenshot();
  303. view.debug_request("load-reference-page");
  304. }
  305. };
  306. timeout_timer->start();
  307. loop.exec();
  308. if (did_timeout)
  309. return TestResult::Timeout;
  310. VERIFY(actual_screenshot);
  311. VERIFY(expectation_screenshot);
  312. if (actual_screenshot->visually_equals(*expectation_screenshot))
  313. return TestResult::Pass;
  314. if (dump_failed_ref_tests) {
  315. warnln("\033[33;1mRef test {} failed; dumping screenshots\033[0m", input_path);
  316. auto title = LexicalPath::title(input_path);
  317. auto dump_screenshot = [&](Gfx::Bitmap& bitmap, StringView path) -> ErrorOr<void> {
  318. auto screenshot_file = TRY(Core::File::open(path, Core::File::OpenMode::Write));
  319. auto encoded_data = TRY(Gfx::PNGWriter::encode(bitmap));
  320. TRY(screenshot_file->write_until_depleted(encoded_data));
  321. warnln("\033[33;1mDumped {}\033[0m", TRY(FileSystem::real_path(path)));
  322. return {};
  323. };
  324. auto mkdir_result = Core::System::mkdir("test-dumps"sv, 0755);
  325. if (mkdir_result.is_error() && mkdir_result.error().code() != EEXIST)
  326. return mkdir_result.release_error();
  327. TRY(dump_screenshot(*actual_screenshot, TRY(String::formatted("test-dumps/{}.png", title))));
  328. TRY(dump_screenshot(*expectation_screenshot, TRY(String::formatted("test-dumps/{}-ref.png", title))));
  329. }
  330. return TestResult::Fail;
  331. }
  332. static ErrorOr<TestResult> run_test(HeadlessWebContentView& view, StringView input_path, StringView expectation_path, TestMode mode, bool dump_failed_ref_tests)
  333. {
  334. // Clear the current document.
  335. // FIXME: Implement a debug-request to do this more thoroughly.
  336. auto promise = Core::Promise<Empty>::construct();
  337. view.on_load_finish = [&](auto) {
  338. promise->resolve({});
  339. };
  340. view.on_text_test_finish = {};
  341. view.load(URL("about:blank"sv));
  342. MUST(promise->await());
  343. s_current_test_path = input_path;
  344. switch (mode) {
  345. case TestMode::Text:
  346. case TestMode::Layout:
  347. return run_dump_test(view, input_path, expectation_path, mode);
  348. case TestMode::Ref:
  349. return run_ref_test(view, input_path, dump_failed_ref_tests);
  350. default:
  351. VERIFY_NOT_REACHED();
  352. }
  353. }
  354. struct Test {
  355. String input_path;
  356. String expectation_path;
  357. TestMode mode;
  358. Optional<TestResult> result;
  359. };
  360. static Vector<ByteString> s_skipped_tests;
  361. static ErrorOr<void> load_test_config(StringView test_root_path)
  362. {
  363. auto config_path = LexicalPath::join(test_root_path, "TestConfig.ini"sv);
  364. auto config_or_error = Core::ConfigFile::open(config_path.string());
  365. if (config_or_error.is_error()) {
  366. if (config_or_error.error().code() == ENOENT)
  367. return {};
  368. dbgln("Unable to open test config {}", config_path);
  369. return config_or_error.release_error();
  370. }
  371. auto config = config_or_error.release_value();
  372. for (auto const& group : config->groups()) {
  373. if (group == "Skipped"sv) {
  374. for (auto& key : config->keys(group))
  375. s_skipped_tests.append(LexicalPath::join(test_root_path, key).string());
  376. } else {
  377. warnln("Unknown group '{}' in config {}", group, config_path);
  378. }
  379. }
  380. return {};
  381. }
  382. static ErrorOr<void> collect_dump_tests(Vector<Test>& tests, StringView path, StringView trail, TestMode mode)
  383. {
  384. Core::DirIterator it(TRY(String::formatted("{}/input/{}", path, trail)).to_byte_string(), Core::DirIterator::Flags::SkipDots);
  385. while (it.has_next()) {
  386. auto name = it.next_path();
  387. auto input_path = TRY(FileSystem::real_path(TRY(String::formatted("{}/input/{}/{}", path, trail, name))));
  388. if (FileSystem::is_directory(input_path)) {
  389. TRY(collect_dump_tests(tests, path, TRY(String::formatted("{}/{}", trail, name)), mode));
  390. continue;
  391. }
  392. if (!name.ends_with(".html"sv))
  393. continue;
  394. auto basename = LexicalPath::title(name);
  395. auto expectation_path = TRY(String::formatted("{}/expected/{}/{}.txt", path, trail, basename));
  396. tests.append({ move(input_path), move(expectation_path), mode, {} });
  397. }
  398. return {};
  399. }
  400. static ErrorOr<void> collect_ref_tests(Vector<Test>& tests, StringView path)
  401. {
  402. TRY(Core::Directory::for_each_entry(path, Core::DirIterator::SkipDots, [&](Core::DirectoryEntry const& entry, Core::Directory const&) -> ErrorOr<IterationDecision> {
  403. if (entry.type == Core::DirectoryEntry::Type::Directory)
  404. return IterationDecision::Continue;
  405. auto input_path = TRY(FileSystem::real_path(TRY(String::formatted("{}/{}", path, entry.name))));
  406. tests.append({ move(input_path), {}, TestMode::Ref, {} });
  407. return IterationDecision::Continue;
  408. }));
  409. return {};
  410. }
  411. static ErrorOr<int> run_tests(HeadlessWebContentView& view, StringView test_root_path, bool dump_failed_ref_tests)
  412. {
  413. view.clear_content_filters();
  414. TRY(load_test_config(test_root_path));
  415. Vector<Test> tests;
  416. TRY(collect_dump_tests(tests, TRY(String::formatted("{}/Layout", test_root_path)), "."sv, TestMode::Layout));
  417. TRY(collect_dump_tests(tests, TRY(String::formatted("{}/Text", test_root_path)), "."sv, TestMode::Text));
  418. TRY(collect_ref_tests(tests, TRY(String::formatted("{}/Ref", test_root_path))));
  419. size_t pass_count = 0;
  420. size_t fail_count = 0;
  421. size_t timeout_count = 0;
  422. size_t skipped_count = 0;
  423. bool is_tty = isatty(STDOUT_FILENO);
  424. outln("Running {} tests...", tests.size());
  425. for (size_t i = 0; i < tests.size(); ++i) {
  426. auto& test = tests[i];
  427. if (is_tty) {
  428. // Keep clearing and reusing the same line if stdout is a TTY.
  429. out("\33[2K\r");
  430. }
  431. out("{}/{}: {}", i + 1, tests.size(), LexicalPath::relative_path(test.input_path, test_root_path));
  432. if (is_tty)
  433. fflush(stdout);
  434. else
  435. outln("");
  436. if (s_skipped_tests.contains_slow(test.input_path.bytes_as_string_view())) {
  437. test.result = TestResult::Skipped;
  438. ++skipped_count;
  439. continue;
  440. }
  441. test.result = TRY(run_test(view, test.input_path, test.expectation_path, test.mode, dump_failed_ref_tests));
  442. switch (*test.result) {
  443. case TestResult::Pass:
  444. ++pass_count;
  445. break;
  446. case TestResult::Fail:
  447. ++fail_count;
  448. break;
  449. case TestResult::Timeout:
  450. ++timeout_count;
  451. break;
  452. case TestResult::Skipped:
  453. VERIFY_NOT_REACHED();
  454. break;
  455. }
  456. }
  457. if (is_tty)
  458. outln("\33[2K\rDone!");
  459. outln("==================================================");
  460. outln("Pass: {}, Fail: {}, Skipped: {}, Timeout: {}", pass_count, fail_count, skipped_count, timeout_count);
  461. outln("==================================================");
  462. for (auto& test : tests) {
  463. if (*test.result == TestResult::Pass)
  464. continue;
  465. outln("{}: {}", test_result_to_string(*test.result), test.input_path);
  466. }
  467. if (timeout_count == 0 && fail_count == 0)
  468. return 0;
  469. return 1;
  470. }
  471. ErrorOr<int> serenity_main(Main::Arguments arguments)
  472. {
  473. Core::EventLoop event_loop;
  474. int screenshot_timeout = 1;
  475. StringView raw_url;
  476. auto resources_folder = "/res"sv;
  477. StringView web_driver_ipc_path;
  478. bool dump_failed_ref_tests = false;
  479. bool dump_layout_tree = false;
  480. bool dump_text = false;
  481. bool is_layout_test_mode = false;
  482. StringView test_root_path;
  483. Core::ArgsParser args_parser;
  484. args_parser.set_general_help("This utility runs the Browser in headless mode.");
  485. args_parser.add_option(screenshot_timeout, "Take a screenshot after [n] seconds (default: 1)", "screenshot", 's', "n");
  486. args_parser.add_option(dump_layout_tree, "Dump layout tree and exit", "dump-layout-tree", 'd');
  487. args_parser.add_option(dump_text, "Dump text and exit", "dump-text", 'T');
  488. args_parser.add_option(test_root_path, "Run tests in path", "run-tests", 'R', "test-root-path");
  489. args_parser.add_option(dump_failed_ref_tests, "Dump screenshots of failing ref tests", "dump-failed-ref-tests", 'D');
  490. args_parser.add_option(resources_folder, "Path of the base resources folder (defaults to /res)", "resources", 'r', "resources-root-path");
  491. args_parser.add_option(web_driver_ipc_path, "Path to the WebDriver IPC socket", "webdriver-ipc-path", 0, "path");
  492. args_parser.add_option(is_layout_test_mode, "Enable layout test mode", "layout-test-mode", 0);
  493. args_parser.add_positional_argument(raw_url, "URL to open", "url", Core::ArgsParser::Required::No);
  494. args_parser.parse(arguments);
  495. Gfx::FontDatabase::set_default_font_query("Katica 10 400 0");
  496. Gfx::FontDatabase::set_window_title_font_query("Katica 10 700 0");
  497. Gfx::FontDatabase::set_fixed_width_font_query("Csilla 10 400 0");
  498. Core::ResourceImplementation::install(make<Core::ResourceImplementationFile>(MUST(String::from_utf8(resources_folder))));
  499. auto theme_path = LexicalPath::join(resources_folder, "themes"sv, "Default.ini"sv);
  500. auto theme = TRY(Gfx::load_system_theme(theme_path.string()));
  501. // FIXME: Allow passing the window size as an argument.
  502. static constexpr Gfx::IntSize window_size { 800, 600 };
  503. if (!test_root_path.is_empty()) {
  504. // --run-tests implies --layout-test-mode.
  505. is_layout_test_mode = true;
  506. }
  507. auto view = TRY(HeadlessWebContentView::create(move(theme), window_size, web_driver_ipc_path, is_layout_test_mode ? Ladybird::IsLayoutTestMode::Yes : Ladybird::IsLayoutTestMode::No));
  508. if (!test_root_path.is_empty()) {
  509. return run_tests(*view, test_root_path, dump_failed_ref_tests);
  510. }
  511. auto url = WebView::sanitize_url(raw_url);
  512. if (!url.has_value()) {
  513. warnln("Invalid URL: \"{}\"", raw_url);
  514. return Error::from_string_literal("Invalid URL");
  515. }
  516. if (dump_layout_tree) {
  517. TRY(run_dump_test(*view, raw_url, ""sv, TestMode::Layout));
  518. return 0;
  519. }
  520. if (dump_text) {
  521. TRY(run_dump_test(*view, raw_url, ""sv, TestMode::Text));
  522. return 0;
  523. }
  524. if (web_driver_ipc_path.is_empty()) {
  525. auto timer = TRY(load_page_for_screenshot_and_exit(event_loop, *view, screenshot_timeout));
  526. return event_loop.exec();
  527. }
  528. return 0;
  529. }