ConnectionFromClient.cpp 36 KB

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