ConnectionFromClient.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021-2023, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2021-2023, Linus Groh <linusg@serenityos.org>
  5. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  6. * Copyright (c) 2022, Tim Flynn <trflynn89@serenityos.org>
  7. * Copyright (c) 2023, Andrew Kaster <akaster@serenityos.org>
  8. *
  9. * SPDX-License-Identifier: BSD-2-Clause
  10. */
  11. #include <AK/Debug.h>
  12. #include <AK/JsonObject.h>
  13. #include <AK/QuickSort.h>
  14. #include <LibGfx/Bitmap.h>
  15. #include <LibGfx/Font/FontDatabase.h>
  16. #include <LibGfx/SystemTheme.h>
  17. #include <LibJS/Bytecode/Interpreter.h>
  18. #include <LibJS/Console.h>
  19. #include <LibJS/Heap/Heap.h>
  20. #include <LibJS/Runtime/ConsoleObject.h>
  21. #include <LibWeb/ARIA/RoleType.h>
  22. #include <LibWeb/Bindings/MainThreadVM.h>
  23. #include <LibWeb/CSS/StyleComputer.h>
  24. #include <LibWeb/DOM/Document.h>
  25. #include <LibWeb/Dump.h>
  26. #include <LibWeb/HTML/BrowsingContext.h>
  27. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  28. #include <LibWeb/HTML/Storage.h>
  29. #include <LibWeb/HTML/TraversableNavigable.h>
  30. #include <LibWeb/HTML/Window.h>
  31. #include <LibWeb/Layout/Viewport.h>
  32. #include <LibWeb/Loader/ContentFilter.h>
  33. #include <LibWeb/Loader/ProxyMappings.h>
  34. #include <LibWeb/Loader/ResourceLoader.h>
  35. #include <LibWeb/Painting/StackingContext.h>
  36. #include <LibWeb/Painting/ViewportPaintable.h>
  37. #include <LibWeb/PermissionsPolicy/AutoplayAllowlist.h>
  38. #include <LibWeb/Platform/EventLoopPlugin.h>
  39. #include <WebContent/ConnectionFromClient.h>
  40. #include <WebContent/PageClient.h>
  41. #include <WebContent/PageHost.h>
  42. #include <WebContent/WebContentClientEndpoint.h>
  43. #include <pthread.h>
  44. namespace WebContent {
  45. ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<Core::LocalSocket> socket)
  46. : IPC::ConnectionFromClient<WebContentClientEndpoint, WebContentServerEndpoint>(*this, move(socket), 1)
  47. , m_page_host(PageHost::create(*this))
  48. {
  49. m_paint_flush_timer = Web::Platform::Timer::create_single_shot(0, [this] { flush_pending_paint_requests(); });
  50. m_input_event_queue_timer = Web::Platform::Timer::create_single_shot(0, [this] { process_next_input_event(); });
  51. }
  52. void ConnectionFromClient::die()
  53. {
  54. Web::Platform::EventLoopPlugin::the().quit();
  55. }
  56. PageClient& ConnectionFromClient::page(u64 index)
  57. {
  58. return m_page_host->page(index);
  59. }
  60. PageClient const& ConnectionFromClient::page(u64 index) const
  61. {
  62. return m_page_host->page(index);
  63. }
  64. Messages::WebContentServer::GetWindowHandleResponse ConnectionFromClient::get_window_handle()
  65. {
  66. return page().page().top_level_browsing_context().window_handle();
  67. }
  68. void ConnectionFromClient::set_window_handle(String const& handle)
  69. {
  70. page().page().top_level_browsing_context().set_window_handle(handle);
  71. }
  72. void ConnectionFromClient::connect_to_webdriver(DeprecatedString const& webdriver_ipc_path)
  73. {
  74. // FIXME: Propagate this error back to the browser.
  75. if (auto result = page().connect_to_webdriver(webdriver_ipc_path); result.is_error())
  76. dbgln("Unable to connect to the WebDriver process: {}", result.error());
  77. }
  78. void ConnectionFromClient::update_system_theme(Core::AnonymousBuffer const& theme_buffer)
  79. {
  80. Gfx::set_system_theme(theme_buffer);
  81. auto impl = Gfx::PaletteImpl::create_with_anonymous_buffer(theme_buffer);
  82. page().set_palette_impl(*impl);
  83. }
  84. void ConnectionFromClient::update_system_fonts(DeprecatedString const& default_font_query, DeprecatedString const& fixed_width_font_query, DeprecatedString const& window_title_font_query)
  85. {
  86. Gfx::FontDatabase::set_default_font_query(default_font_query);
  87. Gfx::FontDatabase::set_fixed_width_font_query(fixed_width_font_query);
  88. Gfx::FontDatabase::set_window_title_font_query(window_title_font_query);
  89. }
  90. void ConnectionFromClient::update_screen_rects(Vector<Gfx::IntRect> const& rects, u32 main_screen)
  91. {
  92. page().set_screen_rects(rects, main_screen);
  93. }
  94. void ConnectionFromClient::load_url(const URL& url)
  95. {
  96. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::LoadURL: url={}", url);
  97. #if defined(AK_OS_SERENITY)
  98. DeprecatedString process_name;
  99. if (url.host().has<Empty>() || url.host() == String {})
  100. process_name = "WebContent";
  101. else
  102. process_name = DeprecatedString::formatted("WebContent: {}", url.serialized_host().release_value_but_fixme_should_propagate_errors());
  103. pthread_setname_np(pthread_self(), process_name.characters());
  104. #endif
  105. page().page().load(url);
  106. }
  107. void ConnectionFromClient::load_html(DeprecatedString const& html)
  108. {
  109. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::LoadHTML: html={}", html);
  110. page().page().load_html(html);
  111. }
  112. void ConnectionFromClient::set_viewport_rect(Gfx::IntRect const& rect)
  113. {
  114. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::SetViewportRect: rect={}", rect);
  115. page().set_viewport_rect(rect.to_type<Web::DevicePixels>());
  116. }
  117. void ConnectionFromClient::add_backing_store(i32 backing_store_id, Gfx::ShareableBitmap const& bitmap)
  118. {
  119. m_backing_stores.set(backing_store_id, *const_cast<Gfx::ShareableBitmap&>(bitmap).bitmap());
  120. }
  121. void ConnectionFromClient::remove_backing_store(i32 backing_store_id)
  122. {
  123. m_backing_stores.remove(backing_store_id);
  124. m_pending_paint_requests.remove_all_matching([backing_store_id](auto& pending_repaint_request) { return pending_repaint_request.bitmap_id == backing_store_id; });
  125. }
  126. void ConnectionFromClient::paint(Gfx::IntRect const& content_rect, i32 backing_store_id)
  127. {
  128. for (auto& pending_paint : m_pending_paint_requests) {
  129. if (pending_paint.bitmap_id == backing_store_id) {
  130. pending_paint.content_rect = content_rect;
  131. return;
  132. }
  133. }
  134. auto it = m_backing_stores.find(backing_store_id);
  135. if (it == m_backing_stores.end()) {
  136. did_misbehave("Client requested paint with backing store ID");
  137. return;
  138. }
  139. auto& bitmap = *it->value;
  140. m_pending_paint_requests.append({ content_rect, bitmap, backing_store_id });
  141. m_paint_flush_timer->start();
  142. }
  143. void ConnectionFromClient::flush_pending_paint_requests()
  144. {
  145. for (auto& pending_paint : m_pending_paint_requests) {
  146. page().paint(pending_paint.content_rect.to_type<Web::DevicePixels>(), *pending_paint.bitmap);
  147. async_did_paint(pending_paint.content_rect, pending_paint.bitmap_id);
  148. }
  149. m_pending_paint_requests.clear();
  150. }
  151. void ConnectionFromClient::process_next_input_event()
  152. {
  153. if (m_input_event_queue.is_empty())
  154. return;
  155. auto event = m_input_event_queue.dequeue();
  156. event.visit(
  157. [&](QueuedMouseEvent const& event) {
  158. switch (event.type) {
  159. case QueuedMouseEvent::Type::MouseDown:
  160. report_finished_handling_input_event(page().page().handle_mousedown(
  161. event.position.to_type<Web::DevicePixels>(),
  162. event.screen_position.to_type<Web::DevicePixels>(),
  163. event.button, event.buttons, event.modifiers));
  164. break;
  165. case QueuedMouseEvent::Type::MouseUp:
  166. report_finished_handling_input_event(page().page().handle_mouseup(
  167. event.position.to_type<Web::DevicePixels>(),
  168. event.screen_position.to_type<Web::DevicePixels>(),
  169. event.button, event.buttons, event.modifiers));
  170. break;
  171. case QueuedMouseEvent::Type::MouseMove:
  172. // NOTE: We have to notify the client about coalesced MouseMoves,
  173. // so we do that by saying none of them were handled by the web page.
  174. for (size_t i = 0; i < event.coalesced_event_count; ++i) {
  175. report_finished_handling_input_event(false);
  176. }
  177. report_finished_handling_input_event(page().page().handle_mousemove(
  178. event.position.to_type<Web::DevicePixels>(),
  179. event.screen_position.to_type<Web::DevicePixels>(),
  180. event.buttons, event.modifiers));
  181. break;
  182. case QueuedMouseEvent::Type::DoubleClick:
  183. report_finished_handling_input_event(page().page().handle_doubleclick(
  184. event.position.to_type<Web::DevicePixels>(),
  185. event.screen_position.to_type<Web::DevicePixels>(),
  186. event.button, event.buttons, event.modifiers));
  187. break;
  188. case QueuedMouseEvent::Type::MouseWheel:
  189. for (size_t i = 0; i < event.coalesced_event_count; ++i) {
  190. report_finished_handling_input_event(false);
  191. }
  192. report_finished_handling_input_event(page().page().handle_mousewheel(
  193. event.position.to_type<Web::DevicePixels>(),
  194. event.screen_position.to_type<Web::DevicePixels>(),
  195. event.button, event.buttons, event.modifiers, event.wheel_delta_x, event.wheel_delta_y));
  196. break;
  197. }
  198. },
  199. [&](QueuedKeyboardEvent const& event) {
  200. switch (event.type) {
  201. case QueuedKeyboardEvent::Type::KeyDown:
  202. report_finished_handling_input_event(page().page().handle_keydown((KeyCode)event.key, event.modifiers, event.code_point));
  203. break;
  204. case QueuedKeyboardEvent::Type::KeyUp:
  205. report_finished_handling_input_event(page().page().handle_keyup((KeyCode)event.key, event.modifiers, event.code_point));
  206. break;
  207. }
  208. });
  209. if (!m_input_event_queue.is_empty())
  210. m_input_event_queue_timer->start();
  211. }
  212. void ConnectionFromClient::mouse_down(Gfx::IntPoint position, Gfx::IntPoint screen_position, unsigned int button, unsigned int buttons, unsigned int modifiers)
  213. {
  214. enqueue_input_event(
  215. QueuedMouseEvent {
  216. .type = QueuedMouseEvent::Type::MouseDown,
  217. .position = position,
  218. .screen_position = screen_position,
  219. .button = button,
  220. .buttons = buttons,
  221. .modifiers = modifiers,
  222. });
  223. }
  224. void ConnectionFromClient::mouse_move(Gfx::IntPoint position, Gfx::IntPoint screen_position, [[maybe_unused]] unsigned int button, unsigned int buttons, unsigned int modifiers)
  225. {
  226. auto event = QueuedMouseEvent {
  227. .type = QueuedMouseEvent::Type::MouseMove,
  228. .position = position,
  229. .screen_position = screen_position,
  230. .button = button,
  231. .buttons = buttons,
  232. .modifiers = modifiers,
  233. };
  234. // OPTIMIZATION: Coalesce with previous unprocessed event iff the previous event is also a MouseMove event.
  235. if (!m_input_event_queue.is_empty()
  236. && m_input_event_queue.tail().has<QueuedMouseEvent>()
  237. && m_input_event_queue.tail().get<QueuedMouseEvent>().type == QueuedMouseEvent::Type::MouseMove) {
  238. event.coalesced_event_count = m_input_event_queue.tail().get<QueuedMouseEvent>().coalesced_event_count + 1;
  239. m_input_event_queue.tail() = event;
  240. return;
  241. }
  242. enqueue_input_event(move(event));
  243. }
  244. void ConnectionFromClient::mouse_up(Gfx::IntPoint position, Gfx::IntPoint screen_position, unsigned int button, unsigned int buttons, unsigned int modifiers)
  245. {
  246. enqueue_input_event(
  247. QueuedMouseEvent {
  248. .type = QueuedMouseEvent::Type::MouseUp,
  249. .position = position,
  250. .screen_position = screen_position,
  251. .button = button,
  252. .buttons = buttons,
  253. .modifiers = modifiers,
  254. });
  255. }
  256. void ConnectionFromClient::mouse_wheel(Gfx::IntPoint position, Gfx::IntPoint screen_position, unsigned int button, unsigned int buttons, unsigned int modifiers, i32 wheel_delta_x, i32 wheel_delta_y)
  257. {
  258. auto event = QueuedMouseEvent {
  259. .type = QueuedMouseEvent::Type::MouseWheel,
  260. .position = position,
  261. .screen_position = screen_position,
  262. .button = button,
  263. .buttons = buttons,
  264. .modifiers = modifiers,
  265. .wheel_delta_x = wheel_delta_x,
  266. .wheel_delta_y = wheel_delta_y,
  267. };
  268. // OPTIMIZATION: Coalesce with previous unprocessed event if the previous event is also a MouseWheel event.
  269. if (!m_input_event_queue.is_empty()
  270. && m_input_event_queue.tail().has<QueuedMouseEvent>()
  271. && m_input_event_queue.tail().get<QueuedMouseEvent>().type == QueuedMouseEvent::Type::MouseWheel) {
  272. auto const& last_event = m_input_event_queue.tail().get<QueuedMouseEvent>();
  273. event.coalesced_event_count = last_event.coalesced_event_count + 1;
  274. event.wheel_delta_x += last_event.wheel_delta_x;
  275. event.wheel_delta_y += last_event.wheel_delta_y;
  276. m_input_event_queue.tail() = event;
  277. return;
  278. }
  279. enqueue_input_event(move(event));
  280. }
  281. void ConnectionFromClient::doubleclick(Gfx::IntPoint position, Gfx::IntPoint screen_position, unsigned int button, unsigned int buttons, unsigned int modifiers)
  282. {
  283. enqueue_input_event(
  284. QueuedMouseEvent {
  285. .type = QueuedMouseEvent::Type::DoubleClick,
  286. .position = position,
  287. .screen_position = screen_position,
  288. .button = button,
  289. .buttons = buttons,
  290. .modifiers = modifiers,
  291. });
  292. }
  293. void ConnectionFromClient::key_down(i32 key, unsigned int modifiers, u32 code_point)
  294. {
  295. enqueue_input_event(
  296. QueuedKeyboardEvent {
  297. .type = QueuedKeyboardEvent::Type::KeyDown,
  298. .key = key,
  299. .modifiers = modifiers,
  300. .code_point = code_point,
  301. });
  302. }
  303. void ConnectionFromClient::key_up(i32 key, unsigned int modifiers, u32 code_point)
  304. {
  305. enqueue_input_event(
  306. QueuedKeyboardEvent {
  307. .type = QueuedKeyboardEvent::Type::KeyUp,
  308. .key = key,
  309. .modifiers = modifiers,
  310. .code_point = code_point,
  311. });
  312. }
  313. void ConnectionFromClient::enqueue_input_event(Variant<QueuedMouseEvent, QueuedKeyboardEvent> event)
  314. {
  315. m_input_event_queue.enqueue(move(event));
  316. m_input_event_queue_timer->start();
  317. }
  318. void ConnectionFromClient::report_finished_handling_input_event(bool event_was_handled)
  319. {
  320. async_did_finish_handling_input_event(event_was_handled);
  321. }
  322. void ConnectionFromClient::debug_request(DeprecatedString const& request, DeprecatedString const& argument)
  323. {
  324. if (request == "dump-session-history") {
  325. auto const& traversable = page().page().top_level_traversable();
  326. Web::dump_tree(*traversable);
  327. }
  328. if (request == "dump-dom-tree") {
  329. if (auto* doc = page().page().top_level_browsing_context().active_document())
  330. Web::dump_tree(*doc);
  331. return;
  332. }
  333. if (request == "dump-layout-tree") {
  334. if (auto* doc = page().page().top_level_browsing_context().active_document()) {
  335. if (auto* viewport = doc->layout_node())
  336. Web::dump_tree(*viewport);
  337. }
  338. return;
  339. }
  340. if (request == "dump-paint-tree") {
  341. if (auto* doc = page().page().top_level_browsing_context().active_document()) {
  342. if (auto* paintable = doc->paintable())
  343. Web::dump_tree(*paintable);
  344. }
  345. return;
  346. }
  347. if (request == "dump-stacking-context-tree") {
  348. if (auto* doc = page().page().top_level_browsing_context().active_document()) {
  349. if (auto* viewport = doc->layout_node()) {
  350. if (auto* stacking_context = viewport->paintable_box()->stacking_context())
  351. stacking_context->dump();
  352. }
  353. }
  354. return;
  355. }
  356. if (request == "dump-style-sheets") {
  357. if (auto* doc = page().page().top_level_browsing_context().active_document()) {
  358. for (auto& sheet : doc->style_sheets().sheets()) {
  359. if (auto result = Web::dump_sheet(sheet); result.is_error())
  360. dbgln("Failed to dump style sheets: {}", result.error());
  361. }
  362. }
  363. return;
  364. }
  365. if (request == "dump-all-resolved-styles") {
  366. if (auto* doc = page().page().top_level_browsing_context().active_document()) {
  367. Queue<Web::DOM::Node*> elements_to_visit;
  368. elements_to_visit.enqueue(doc->document_element());
  369. while (!elements_to_visit.is_empty()) {
  370. auto element = elements_to_visit.dequeue();
  371. for (auto& child : element->children_as_vector())
  372. elements_to_visit.enqueue(child.ptr());
  373. if (element->is_element()) {
  374. auto styles = doc->style_computer().compute_style(*static_cast<Web::DOM::Element*>(element)).release_value_but_fixme_should_propagate_errors();
  375. dbgln("+ Element {}", element->debug_description());
  376. auto& properties = styles->properties();
  377. for (size_t i = 0; i < properties.size(); ++i)
  378. dbgln("| {} = {}", Web::CSS::string_from_property_id(static_cast<Web::CSS::PropertyID>(i)), properties[i].has_value() ? properties[i]->style->to_string() : ""_string);
  379. dbgln("---");
  380. }
  381. }
  382. }
  383. return;
  384. }
  385. if (request == "collect-garbage") {
  386. Web::Bindings::main_thread_vm().heap().collect_garbage(JS::Heap::CollectionType::CollectGarbage, true);
  387. return;
  388. }
  389. if (request == "dump-gc-graph") {
  390. Web::Bindings::main_thread_vm().heap().dump_graph();
  391. return;
  392. }
  393. if (request == "set-line-box-borders") {
  394. bool state = argument == "on";
  395. page().set_should_show_line_box_borders(state);
  396. page().page().top_level_traversable()->set_needs_display(page().page().top_level_traversable()->viewport_rect());
  397. return;
  398. }
  399. if (request == "clear-cache") {
  400. Web::ResourceLoader::the().clear_cache();
  401. return;
  402. }
  403. if (request == "spoof-user-agent") {
  404. Web::ResourceLoader::the().set_user_agent(MUST(String::from_deprecated_string(argument)));
  405. return;
  406. }
  407. if (request == "same-origin-policy") {
  408. page().page().set_same_origin_policy_enabled(argument == "on");
  409. return;
  410. }
  411. if (request == "scripting") {
  412. page().page().set_is_scripting_enabled(argument == "on");
  413. return;
  414. }
  415. if (request == "block-pop-ups") {
  416. page().page().set_should_block_pop_ups(argument == "on");
  417. return;
  418. }
  419. if (request == "dump-local-storage") {
  420. if (auto* document = page().page().top_level_browsing_context().active_document())
  421. document->window().local_storage().release_value_but_fixme_should_propagate_errors()->dump();
  422. return;
  423. }
  424. if (request == "load-reference-page") {
  425. if (auto* document = page().page().top_level_browsing_context().active_document()) {
  426. auto maybe_link = document->query_selector("link[rel=match]"sv);
  427. if (maybe_link.is_error() || !maybe_link.value()) {
  428. // To make sure that we fail the ref-test if the link is missing, load the error page.
  429. load_html("<h1>Failed to find &lt;link rel=&quot;match&quot; /&gt; in ref test page!</h1> Make sure you added it.");
  430. } else {
  431. auto link = maybe_link.release_value();
  432. auto url = document->parse_url(link->deprecated_get_attribute(Web::HTML::AttributeNames::href));
  433. load_url(url);
  434. }
  435. }
  436. return;
  437. }
  438. }
  439. void ConnectionFromClient::get_source()
  440. {
  441. if (auto* doc = page().page().top_level_browsing_context().active_document()) {
  442. async_did_get_source(doc->url(), doc->source());
  443. }
  444. }
  445. void ConnectionFromClient::inspect_dom_tree()
  446. {
  447. if (auto* doc = page().page().top_level_browsing_context().active_document()) {
  448. async_did_get_dom_tree(doc->dump_dom_tree_as_json());
  449. }
  450. }
  451. Messages::WebContentServer::InspectDomNodeResponse ConnectionFromClient::inspect_dom_node(i32 node_id, Optional<Web::CSS::Selector::PseudoElement> const& pseudo_element)
  452. {
  453. auto& top_context = page().page().top_level_browsing_context();
  454. top_context.for_each_in_inclusive_subtree([&](auto& ctx) {
  455. if (ctx.active_document() != nullptr) {
  456. ctx.active_document()->set_inspected_node(nullptr, {});
  457. }
  458. return IterationDecision::Continue;
  459. });
  460. Web::DOM::Node* node = Web::DOM::Node::from_unique_id(node_id);
  461. // Note: Nodes without layout (aka non-visible nodes, don't have style computed)
  462. if (!node || !node->layout_node()) {
  463. return { false, "", "", "", "", "" };
  464. }
  465. node->document().set_inspected_node(node, pseudo_element);
  466. if (node->is_element()) {
  467. auto& element = verify_cast<Web::DOM::Element>(*node);
  468. if (!element.computed_css_values())
  469. return { false, "", "", "", "", "" };
  470. auto serialize_json = [](Web::CSS::StyleProperties const& properties) -> DeprecatedString {
  471. StringBuilder builder;
  472. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  473. properties.for_each_property([&](auto property_id, auto& value) {
  474. MUST(serializer.add(Web::CSS::string_from_property_id(property_id), value.to_string().to_deprecated_string()));
  475. });
  476. MUST(serializer.finish());
  477. return builder.to_deprecated_string();
  478. };
  479. auto serialize_custom_properties_json = [](Web::DOM::Element const& element, Optional<Web::CSS::Selector::PseudoElement> pseudo_element) -> DeprecatedString {
  480. StringBuilder builder;
  481. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  482. HashTable<FlyString> seen_properties;
  483. auto const* element_to_check = &element;
  484. while (element_to_check) {
  485. for (auto const& property : element_to_check->custom_properties(pseudo_element)) {
  486. if (!seen_properties.contains(property.key)) {
  487. seen_properties.set(property.key);
  488. MUST(serializer.add(property.key, property.value.value->to_string()));
  489. }
  490. }
  491. element_to_check = element_to_check->parent_element();
  492. }
  493. MUST(serializer.finish());
  494. return builder.to_deprecated_string();
  495. };
  496. auto serialize_node_box_sizing_json = [](Web::Layout::Node const* layout_node) -> DeprecatedString {
  497. if (!layout_node || !layout_node->is_box()) {
  498. return "{}";
  499. }
  500. auto* box = static_cast<Web::Layout::Box const*>(layout_node);
  501. auto box_model = box->box_model();
  502. StringBuilder builder;
  503. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  504. MUST(serializer.add("padding_top"sv, box_model.padding.top.to_double()));
  505. MUST(serializer.add("padding_right"sv, box_model.padding.right.to_double()));
  506. MUST(serializer.add("padding_bottom"sv, box_model.padding.bottom.to_double()));
  507. MUST(serializer.add("padding_left"sv, box_model.padding.left.to_double()));
  508. MUST(serializer.add("margin_top"sv, box_model.margin.top.to_double()));
  509. MUST(serializer.add("margin_right"sv, box_model.margin.right.to_double()));
  510. MUST(serializer.add("margin_bottom"sv, box_model.margin.bottom.to_double()));
  511. MUST(serializer.add("margin_left"sv, box_model.margin.left.to_double()));
  512. MUST(serializer.add("border_top"sv, box_model.border.top.to_double()));
  513. MUST(serializer.add("border_right"sv, box_model.border.right.to_double()));
  514. MUST(serializer.add("border_bottom"sv, box_model.border.bottom.to_double()));
  515. MUST(serializer.add("border_left"sv, box_model.border.left.to_double()));
  516. if (auto* paintable_box = box->paintable_box()) {
  517. MUST(serializer.add("content_width"sv, paintable_box->content_width().to_double()));
  518. MUST(serializer.add("content_height"sv, paintable_box->content_height().to_double()));
  519. } else {
  520. MUST(serializer.add("content_width"sv, 0));
  521. MUST(serializer.add("content_height"sv, 0));
  522. }
  523. MUST(serializer.finish());
  524. return builder.to_deprecated_string();
  525. };
  526. auto serialize_aria_properties_state_json = [](Web::DOM::Element const& element) -> DeprecatedString {
  527. auto role_name = element.role_or_default();
  528. if (!role_name.has_value()) {
  529. return "";
  530. }
  531. auto aria_data = MUST(Web::ARIA::AriaData::build_data(element));
  532. auto role = MUST(Web::ARIA::RoleType::build_role_object(role_name.value(), element.is_focusable(), *aria_data));
  533. StringBuilder builder;
  534. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  535. MUST(role->serialize_as_json(serializer));
  536. MUST(serializer.finish());
  537. return builder.to_deprecated_string();
  538. };
  539. if (pseudo_element.has_value()) {
  540. auto pseudo_element_node = element.get_pseudo_element_node(pseudo_element.value());
  541. if (!pseudo_element_node)
  542. return { false, "", "", "", "", "" };
  543. // FIXME: Pseudo-elements only exist as Layout::Nodes, which don't have style information
  544. // in a format we can use. So, we run the StyleComputer again to get the specified
  545. // values, and have to ignore the computed values and custom properties.
  546. auto pseudo_element_style = MUST(page().page().focused_context().active_document()->style_computer().compute_style(element, pseudo_element));
  547. DeprecatedString computed_values = serialize_json(pseudo_element_style);
  548. DeprecatedString resolved_values = "{}";
  549. DeprecatedString custom_properties_json = serialize_custom_properties_json(element, pseudo_element);
  550. DeprecatedString node_box_sizing_json = serialize_node_box_sizing_json(pseudo_element_node.ptr());
  551. return { true, computed_values, resolved_values, custom_properties_json, node_box_sizing_json, "" };
  552. }
  553. DeprecatedString computed_values = serialize_json(*element.computed_css_values());
  554. DeprecatedString resolved_values_json = serialize_json(element.resolved_css_values());
  555. DeprecatedString custom_properties_json = serialize_custom_properties_json(element, {});
  556. DeprecatedString node_box_sizing_json = serialize_node_box_sizing_json(element.layout_node());
  557. DeprecatedString aria_properties_state_json = serialize_aria_properties_state_json(element);
  558. return { true, computed_values, resolved_values_json, custom_properties_json, node_box_sizing_json, aria_properties_state_json };
  559. }
  560. return { false, "", "", "", "", "" };
  561. }
  562. Messages::WebContentServer::GetHoveredNodeIdResponse ConnectionFromClient::get_hovered_node_id()
  563. {
  564. if (auto* document = page().page().top_level_browsing_context().active_document()) {
  565. auto hovered_node = document->hovered_node();
  566. if (hovered_node)
  567. return hovered_node->unique_id();
  568. }
  569. return (i32)0;
  570. }
  571. void ConnectionFromClient::initialize_js_console(Badge<PageClient>, Web::DOM::Document& document)
  572. {
  573. auto& realm = document.realm();
  574. auto console_object = realm.intrinsics().console_object();
  575. auto console_client = make<WebContentConsoleClient>(console_object->console(), document.realm(), *this);
  576. console_object->console().set_client(*console_client);
  577. VERIFY(document.browsing_context());
  578. if (document.browsing_context()->is_top_level()) {
  579. m_top_level_document_console_client = console_client->make_weak_ptr();
  580. }
  581. m_console_clients.set(&document, move(console_client));
  582. }
  583. void ConnectionFromClient::destroy_js_console(Badge<PageClient>, Web::DOM::Document& document)
  584. {
  585. m_console_clients.remove(&document);
  586. }
  587. void ConnectionFromClient::js_console_input(DeprecatedString const& js_source)
  588. {
  589. if (m_top_level_document_console_client)
  590. m_top_level_document_console_client->handle_input(js_source);
  591. }
  592. void ConnectionFromClient::run_javascript(DeprecatedString const& js_source)
  593. {
  594. auto* active_document = page().page().top_level_browsing_context().active_document();
  595. if (!active_document)
  596. return;
  597. // This is partially based on "execute a javascript: URL request" https://html.spec.whatwg.org/multipage/browsing-the-web.html#javascript-protocol
  598. // Let settings be browsingContext's active document's relevant settings object.
  599. auto& settings = active_document->relevant_settings_object();
  600. // Let baseURL be settings's API base URL.
  601. auto base_url = settings.api_base_url();
  602. // Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.
  603. // FIXME: This doesn't pass in "default classic script fetch options"
  604. // FIXME: What should the filename be here?
  605. auto script = Web::HTML::ClassicScript::create("(client connection run_javascript)", js_source, settings, move(base_url));
  606. // Let evaluationStatus be the result of running the classic script script.
  607. auto evaluation_status = script->run();
  608. if (evaluation_status.is_error())
  609. dbgln("Exception :(");
  610. }
  611. void ConnectionFromClient::js_console_request_messages(i32 start_index)
  612. {
  613. if (m_top_level_document_console_client)
  614. m_top_level_document_console_client->send_messages(start_index);
  615. }
  616. Messages::WebContentServer::TakeDocumentScreenshotResponse ConnectionFromClient::take_document_screenshot()
  617. {
  618. auto* document = page().page().top_level_browsing_context().active_document();
  619. if (!document || !document->document_element())
  620. return { {} };
  621. auto const& content_size = page().content_size();
  622. Web::DevicePixelRect rect { { 0, 0 }, content_size };
  623. auto bitmap = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, rect.size().to_type<int>()).release_value_but_fixme_should_propagate_errors();
  624. page().paint(rect, *bitmap);
  625. return { bitmap->to_shareable_bitmap() };
  626. }
  627. Messages::WebContentServer::GetSelectedTextResponse ConnectionFromClient::get_selected_text()
  628. {
  629. return page().page().focused_context().selected_text();
  630. }
  631. void ConnectionFromClient::select_all()
  632. {
  633. page().page().focused_context().select_all();
  634. page().page().client().page_did_change_selection();
  635. }
  636. Messages::WebContentServer::DumpLayoutTreeResponse ConnectionFromClient::dump_layout_tree()
  637. {
  638. auto* document = page().page().top_level_browsing_context().active_document();
  639. if (!document)
  640. return DeprecatedString { "(no DOM tree)" };
  641. document->update_layout();
  642. auto* layout_root = document->layout_node();
  643. if (!layout_root)
  644. return DeprecatedString { "(no layout tree)" };
  645. StringBuilder builder;
  646. Web::dump_tree(builder, *layout_root);
  647. return builder.to_deprecated_string();
  648. }
  649. Messages::WebContentServer::DumpPaintTreeResponse ConnectionFromClient::dump_paint_tree()
  650. {
  651. auto* document = page().page().top_level_browsing_context().active_document();
  652. if (!document)
  653. return DeprecatedString { "(no DOM tree)" };
  654. document->update_layout();
  655. auto* layout_root = document->layout_node();
  656. if (!layout_root)
  657. return DeprecatedString { "(no layout tree)" };
  658. if (!layout_root->paintable())
  659. return DeprecatedString { "(no paint tree)" };
  660. StringBuilder builder;
  661. Web::dump_tree(builder, *layout_root->paintable());
  662. return builder.to_deprecated_string();
  663. }
  664. Messages::WebContentServer::DumpTextResponse ConnectionFromClient::dump_text()
  665. {
  666. auto* document = page().page().top_level_browsing_context().active_document();
  667. if (!document)
  668. return DeprecatedString { "(no DOM tree)" };
  669. if (!document->body())
  670. return DeprecatedString { "(no body)" };
  671. return document->body()->inner_text();
  672. }
  673. void ConnectionFromClient::set_content_filters(Vector<String> const& filters)
  674. {
  675. Web::ContentFilter::the().set_patterns(filters).release_value_but_fixme_should_propagate_errors();
  676. }
  677. void ConnectionFromClient::set_autoplay_allowed_on_all_websites()
  678. {
  679. auto& autoplay_allowlist = Web::PermissionsPolicy::AutoplayAllowlist::the();
  680. autoplay_allowlist.enable_globally();
  681. }
  682. void ConnectionFromClient::set_autoplay_allowlist(Vector<String> const& allowlist)
  683. {
  684. auto& autoplay_allowlist = Web::PermissionsPolicy::AutoplayAllowlist::the();
  685. autoplay_allowlist.enable_for_origins(allowlist).release_value_but_fixme_should_propagate_errors();
  686. }
  687. void ConnectionFromClient::set_proxy_mappings(Vector<DeprecatedString> const& proxies, HashMap<DeprecatedString, size_t> const& mappings)
  688. {
  689. auto keys = mappings.keys();
  690. quick_sort(keys, [&](auto& a, auto& b) { return a.length() < b.length(); });
  691. OrderedHashMap<DeprecatedString, size_t> sorted_mappings;
  692. for (auto& key : keys) {
  693. auto value = *mappings.get(key);
  694. if (value >= proxies.size())
  695. continue;
  696. sorted_mappings.set(key, value);
  697. }
  698. Web::ProxyMappings::the().set_mappings(proxies, move(sorted_mappings));
  699. }
  700. void ConnectionFromClient::set_preferred_color_scheme(Web::CSS::PreferredColorScheme const& color_scheme)
  701. {
  702. page().set_preferred_color_scheme(color_scheme);
  703. }
  704. void ConnectionFromClient::set_has_focus(bool has_focus)
  705. {
  706. page().set_has_focus(has_focus);
  707. }
  708. void ConnectionFromClient::set_is_scripting_enabled(bool is_scripting_enabled)
  709. {
  710. page().set_is_scripting_enabled(is_scripting_enabled);
  711. }
  712. void ConnectionFromClient::set_device_pixels_per_css_pixel(float device_pixels_per_css_pixel)
  713. {
  714. page().set_device_pixels_per_css_pixel(device_pixels_per_css_pixel);
  715. }
  716. void ConnectionFromClient::set_window_position(Gfx::IntPoint position)
  717. {
  718. page().set_window_position(position.to_type<Web::DevicePixels>());
  719. }
  720. void ConnectionFromClient::set_window_size(Gfx::IntSize size)
  721. {
  722. page().set_window_size(size.to_type<Web::DevicePixels>());
  723. }
  724. Messages::WebContentServer::GetLocalStorageEntriesResponse ConnectionFromClient::get_local_storage_entries()
  725. {
  726. auto* document = page().page().top_level_browsing_context().active_document();
  727. auto local_storage = document->window().local_storage().release_value_but_fixme_should_propagate_errors();
  728. return local_storage->map();
  729. }
  730. Messages::WebContentServer::GetSessionStorageEntriesResponse ConnectionFromClient::get_session_storage_entries()
  731. {
  732. auto* document = page().page().top_level_browsing_context().active_document();
  733. auto session_storage = document->window().session_storage().release_value_but_fixme_should_propagate_errors();
  734. return session_storage->map();
  735. }
  736. void ConnectionFromClient::handle_file_return(i32 error, Optional<IPC::File> const& file, i32 request_id)
  737. {
  738. auto file_request = m_requested_files.take(request_id);
  739. VERIFY(file_request.has_value());
  740. VERIFY(file_request.value().on_file_request_finish);
  741. file_request.value().on_file_request_finish(error != 0 ? Error::from_errno(error) : ErrorOr<i32> { file->take_fd() });
  742. }
  743. void ConnectionFromClient::request_file(Web::FileRequest file_request)
  744. {
  745. i32 const id = last_id++;
  746. auto path = file_request.path();
  747. m_requested_files.set(id, move(file_request));
  748. async_did_request_file(path, id);
  749. }
  750. void ConnectionFromClient::set_system_visibility_state(bool visible)
  751. {
  752. page().page().top_level_traversable()->set_system_visibility_state(
  753. visible
  754. ? Web::HTML::VisibilityState::Visible
  755. : Web::HTML::VisibilityState::Hidden);
  756. }
  757. void ConnectionFromClient::alert_closed()
  758. {
  759. page().page().alert_closed();
  760. }
  761. void ConnectionFromClient::confirm_closed(bool accepted)
  762. {
  763. page().page().confirm_closed(accepted);
  764. }
  765. void ConnectionFromClient::prompt_closed(Optional<String> const& response)
  766. {
  767. page().page().prompt_closed(response);
  768. }
  769. void ConnectionFromClient::color_picker_closed(Optional<Color> const& picked_color)
  770. {
  771. page().page().color_picker_closed(picked_color);
  772. }
  773. void ConnectionFromClient::toggle_media_play_state()
  774. {
  775. page().page().toggle_media_play_state().release_value_but_fixme_should_propagate_errors();
  776. }
  777. void ConnectionFromClient::toggle_media_mute_state()
  778. {
  779. page().page().toggle_media_mute_state();
  780. }
  781. void ConnectionFromClient::toggle_media_loop_state()
  782. {
  783. page().page().toggle_media_loop_state().release_value_but_fixme_should_propagate_errors();
  784. }
  785. void ConnectionFromClient::toggle_media_controls_state()
  786. {
  787. page().page().toggle_media_controls_state().release_value_but_fixme_should_propagate_errors();
  788. }
  789. void ConnectionFromClient::set_user_style(String const& source)
  790. {
  791. page().page().set_user_style(source);
  792. }
  793. void ConnectionFromClient::inspect_accessibility_tree()
  794. {
  795. if (auto* doc = page().page().top_level_browsing_context().active_document()) {
  796. async_did_get_accessibility_tree(doc->dump_accessibility_tree_as_json());
  797. }
  798. }
  799. void ConnectionFromClient::enable_inspector_prototype()
  800. {
  801. Web::HTML::Window::set_inspector_object_exposed(true);
  802. }
  803. }