ConnectionFromClient.cpp 30 KB

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