headless-browser.cpp 28 KB

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