ConnectionFromClient.cpp 29 KB

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