ConnectionFromClient.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  5. * Copyright (c) 2022, Tobias Christiansen <tobyase@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Debug.h>
  10. #include <AK/JsonObject.h>
  11. #include <AK/QuickSort.h>
  12. #include <LibGfx/Bitmap.h>
  13. #include <LibGfx/Font/FontDatabase.h>
  14. #include <LibGfx/SystemTheme.h>
  15. #include <LibJS/Console.h>
  16. #include <LibJS/Heap/Heap.h>
  17. #include <LibJS/Parser.h>
  18. #include <LibJS/Runtime/ConsoleObject.h>
  19. #include <LibJS/Runtime/JSONObject.h>
  20. #include <LibWeb/Bindings/MainThreadVM.h>
  21. #include <LibWeb/CSS/PropertyID.h>
  22. #include <LibWeb/Cookie/ParsedCookie.h>
  23. #include <LibWeb/DOM/Document.h>
  24. #include <LibWeb/DOM/NodeList.h>
  25. #include <LibWeb/Dump.h>
  26. #include <LibWeb/HTML/BrowsingContext.h>
  27. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  28. #include <LibWeb/HTML/Storage.h>
  29. #include <LibWeb/HTML/Window.h>
  30. #include <LibWeb/Layout/InitialContainingBlock.h>
  31. #include <LibWeb/Loader/ContentFilter.h>
  32. #include <LibWeb/Loader/ProxyMappings.h>
  33. #include <LibWeb/Loader/ResourceLoader.h>
  34. #include <LibWeb/Painting/PaintableBox.h>
  35. #include <LibWeb/Painting/StackingContext.h>
  36. #include <LibWeb/Platform/EventLoopPlugin.h>
  37. #include <WebContent/ConnectionFromClient.h>
  38. #include <WebContent/PageHost.h>
  39. #include <WebContent/WebContentClientEndpoint.h>
  40. #include <pthread.h>
  41. namespace WebContent {
  42. ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<Core::Stream::LocalSocket> socket)
  43. : IPC::ConnectionFromClient<WebContentClientEndpoint, WebContentServerEndpoint>(*this, move(socket), 1)
  44. , m_page_host(PageHost::create(*this))
  45. {
  46. m_paint_flush_timer = Web::Platform::Timer::create_single_shot(0, [this] { flush_pending_paint_requests(); });
  47. }
  48. void ConnectionFromClient::die()
  49. {
  50. Web::Platform::EventLoopPlugin::the().quit();
  51. }
  52. Web::Page& ConnectionFromClient::page()
  53. {
  54. return m_page_host->page();
  55. }
  56. Web::Page const& ConnectionFromClient::page() const
  57. {
  58. return m_page_host->page();
  59. }
  60. void ConnectionFromClient::update_system_theme(Core::AnonymousBuffer const& theme_buffer)
  61. {
  62. Gfx::set_system_theme(theme_buffer);
  63. auto impl = Gfx::PaletteImpl::create_with_anonymous_buffer(theme_buffer);
  64. m_page_host->set_palette_impl(*impl);
  65. }
  66. void ConnectionFromClient::update_system_fonts(String const& default_font_query, String const& fixed_width_font_query, String const& window_title_font_query)
  67. {
  68. Gfx::FontDatabase::set_default_font_query(default_font_query);
  69. Gfx::FontDatabase::set_fixed_width_font_query(fixed_width_font_query);
  70. Gfx::FontDatabase::set_window_title_font_query(window_title_font_query);
  71. }
  72. void ConnectionFromClient::update_screen_rects(Vector<Gfx::IntRect> const& rects, u32 main_screen)
  73. {
  74. m_page_host->set_screen_rects(rects, main_screen);
  75. }
  76. void ConnectionFromClient::load_url(const URL& url)
  77. {
  78. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::LoadURL: url={}", url);
  79. #if defined(AK_OS_SERENITY)
  80. String process_name;
  81. if (url.host().is_empty())
  82. process_name = "WebContent";
  83. else
  84. process_name = String::formatted("WebContent: {}", url.host());
  85. pthread_setname_np(pthread_self(), process_name.characters());
  86. #endif
  87. page().load(url);
  88. }
  89. void ConnectionFromClient::load_html(String const& html, const URL& url)
  90. {
  91. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::LoadHTML: html={}, url={}", html, url);
  92. page().load_html(html, url);
  93. }
  94. void ConnectionFromClient::set_viewport_rect(Gfx::IntRect const& rect)
  95. {
  96. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::SetViewportRect: rect={}", rect);
  97. m_page_host->set_viewport_rect(rect);
  98. }
  99. void ConnectionFromClient::add_backing_store(i32 backing_store_id, Gfx::ShareableBitmap const& bitmap)
  100. {
  101. m_backing_stores.set(backing_store_id, *bitmap.bitmap());
  102. }
  103. void ConnectionFromClient::remove_backing_store(i32 backing_store_id)
  104. {
  105. m_backing_stores.remove(backing_store_id);
  106. m_pending_paint_requests.remove_all_matching([backing_store_id](auto& pending_repaint_request) { return pending_repaint_request.bitmap_id == backing_store_id; });
  107. }
  108. void ConnectionFromClient::paint(Gfx::IntRect const& content_rect, i32 backing_store_id)
  109. {
  110. for (auto& pending_paint : m_pending_paint_requests) {
  111. if (pending_paint.bitmap_id == backing_store_id) {
  112. pending_paint.content_rect = content_rect;
  113. return;
  114. }
  115. }
  116. auto it = m_backing_stores.find(backing_store_id);
  117. if (it == m_backing_stores.end()) {
  118. did_misbehave("Client requested paint with backing store ID");
  119. return;
  120. }
  121. auto& bitmap = *it->value;
  122. m_pending_paint_requests.append({ content_rect, bitmap, backing_store_id });
  123. m_paint_flush_timer->start();
  124. }
  125. void ConnectionFromClient::flush_pending_paint_requests()
  126. {
  127. for (auto& pending_paint : m_pending_paint_requests) {
  128. m_page_host->paint(pending_paint.content_rect, *pending_paint.bitmap);
  129. async_did_paint(pending_paint.content_rect, pending_paint.bitmap_id);
  130. }
  131. m_pending_paint_requests.clear();
  132. }
  133. void ConnectionFromClient::mouse_down(Gfx::IntPoint const& position, unsigned int button, unsigned int buttons, unsigned int modifiers)
  134. {
  135. page().handle_mousedown(position, button, buttons, modifiers);
  136. }
  137. void ConnectionFromClient::mouse_move(Gfx::IntPoint const& position, [[maybe_unused]] unsigned int button, unsigned int buttons, unsigned int modifiers)
  138. {
  139. page().handle_mousemove(position, buttons, modifiers);
  140. }
  141. void ConnectionFromClient::mouse_up(Gfx::IntPoint const& position, unsigned int button, unsigned int buttons, unsigned int modifiers)
  142. {
  143. page().handle_mouseup(position, button, buttons, modifiers);
  144. }
  145. void ConnectionFromClient::mouse_wheel(Gfx::IntPoint const& position, unsigned int button, unsigned int buttons, unsigned int modifiers, i32 wheel_delta_x, i32 wheel_delta_y)
  146. {
  147. page().handle_mousewheel(position, button, buttons, modifiers, wheel_delta_x, wheel_delta_y);
  148. }
  149. void ConnectionFromClient::doubleclick(Gfx::IntPoint const& position, unsigned int button, unsigned int buttons, unsigned int modifiers)
  150. {
  151. page().handle_doubleclick(position, button, buttons, modifiers);
  152. }
  153. void ConnectionFromClient::key_down(i32 key, unsigned int modifiers, u32 code_point)
  154. {
  155. page().handle_keydown((KeyCode)key, modifiers, code_point);
  156. }
  157. void ConnectionFromClient::key_up(i32 key, unsigned int modifiers, u32 code_point)
  158. {
  159. page().handle_keyup((KeyCode)key, modifiers, code_point);
  160. }
  161. void ConnectionFromClient::debug_request(String const& request, String const& argument)
  162. {
  163. if (request == "dump-dom-tree") {
  164. if (auto* doc = page().top_level_browsing_context().active_document())
  165. Web::dump_tree(*doc);
  166. }
  167. if (request == "dump-layout-tree") {
  168. if (auto* doc = page().top_level_browsing_context().active_document()) {
  169. if (auto* icb = doc->layout_node())
  170. Web::dump_tree(*icb);
  171. }
  172. }
  173. if (request == "dump-stacking-context-tree") {
  174. if (auto* doc = page().top_level_browsing_context().active_document()) {
  175. if (auto* icb = doc->layout_node()) {
  176. if (auto* stacking_context = icb->paint_box()->stacking_context())
  177. stacking_context->dump();
  178. }
  179. }
  180. }
  181. if (request == "dump-style-sheets") {
  182. if (auto* doc = page().top_level_browsing_context().active_document()) {
  183. for (auto& sheet : doc->style_sheets().sheets()) {
  184. Web::dump_sheet(sheet);
  185. }
  186. }
  187. }
  188. if (request == "collect-garbage") {
  189. Web::Bindings::main_thread_vm().heap().collect_garbage(JS::Heap::CollectionType::CollectGarbage, true);
  190. }
  191. if (request == "set-line-box-borders") {
  192. bool state = argument == "on";
  193. m_page_host->set_should_show_line_box_borders(state);
  194. page().top_level_browsing_context().set_needs_display(page().top_level_browsing_context().viewport_rect());
  195. }
  196. if (request == "clear-cache") {
  197. Web::ResourceLoader::the().clear_cache();
  198. }
  199. if (request == "spoof-user-agent") {
  200. Web::ResourceLoader::the().set_user_agent(argument);
  201. }
  202. if (request == "same-origin-policy") {
  203. m_page_host->page().set_same_origin_policy_enabled(argument == "on");
  204. }
  205. if (request == "scripting") {
  206. m_page_host->page().set_is_scripting_enabled(argument == "on");
  207. }
  208. if (request == "dump-local-storage") {
  209. if (auto* doc = page().top_level_browsing_context().active_document())
  210. doc->window().local_storage()->dump();
  211. }
  212. }
  213. void ConnectionFromClient::get_source()
  214. {
  215. if (auto* doc = page().top_level_browsing_context().active_document()) {
  216. async_did_get_source(doc->url(), doc->source());
  217. }
  218. }
  219. void ConnectionFromClient::inspect_dom_tree()
  220. {
  221. if (auto* doc = page().top_level_browsing_context().active_document()) {
  222. async_did_get_dom_tree(doc->dump_dom_tree_as_json());
  223. }
  224. }
  225. Messages::WebContentServer::InspectDomNodeResponse ConnectionFromClient::inspect_dom_node(i32 node_id, Optional<Web::CSS::Selector::PseudoElement> const& pseudo_element)
  226. {
  227. auto& top_context = page().top_level_browsing_context();
  228. top_context.for_each_in_inclusive_subtree([&](auto& ctx) {
  229. if (ctx.active_document() != nullptr) {
  230. ctx.active_document()->set_inspected_node(nullptr);
  231. }
  232. return IterationDecision::Continue;
  233. });
  234. Web::DOM::Node* node = Web::DOM::Node::from_id(node_id);
  235. // Note: Nodes without layout (aka non-visible nodes, don't have style computed)
  236. if (!node || !node->layout_node()) {
  237. return { false, "", "", "", "" };
  238. }
  239. // FIXME: Pass the pseudo-element here.
  240. node->document().set_inspected_node(node);
  241. if (node->is_element()) {
  242. auto& element = verify_cast<Web::DOM::Element>(*node);
  243. if (!element.computed_css_values())
  244. return { false, "", "", "", "" };
  245. auto serialize_json = [](Web::CSS::StyleProperties const& properties) -> String {
  246. StringBuilder builder;
  247. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  248. properties.for_each_property([&](auto property_id, auto& value) {
  249. MUST(serializer.add(Web::CSS::string_from_property_id(property_id), value.to_string()));
  250. });
  251. MUST(serializer.finish());
  252. return builder.to_string();
  253. };
  254. auto serialize_custom_properties_json = [](Web::DOM::Element const& element) -> String {
  255. StringBuilder builder;
  256. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  257. HashTable<String> seen_properties;
  258. auto const* element_to_check = &element;
  259. while (element_to_check) {
  260. for (auto const& property : element_to_check->custom_properties()) {
  261. if (!seen_properties.contains(property.key)) {
  262. seen_properties.set(property.key);
  263. MUST(serializer.add(property.key, property.value.value->to_string()));
  264. }
  265. }
  266. element_to_check = element_to_check->parent_element();
  267. }
  268. MUST(serializer.finish());
  269. return builder.to_string();
  270. };
  271. auto serialize_node_box_sizing_json = [](Web::Layout::Node const* layout_node) -> String {
  272. if (!layout_node || !layout_node->is_box()) {
  273. return "{}";
  274. }
  275. auto* box = static_cast<Web::Layout::Box const*>(layout_node);
  276. auto box_model = box->box_model();
  277. StringBuilder builder;
  278. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  279. MUST(serializer.add("padding_top"sv, box_model.padding.top));
  280. MUST(serializer.add("padding_right"sv, box_model.padding.right));
  281. MUST(serializer.add("padding_bottom"sv, box_model.padding.bottom));
  282. MUST(serializer.add("padding_left"sv, box_model.padding.left));
  283. MUST(serializer.add("margin_top"sv, box_model.margin.top));
  284. MUST(serializer.add("margin_right"sv, box_model.margin.right));
  285. MUST(serializer.add("margin_bottom"sv, box_model.margin.bottom));
  286. MUST(serializer.add("margin_left"sv, box_model.margin.left));
  287. MUST(serializer.add("border_top"sv, box_model.border.top));
  288. MUST(serializer.add("border_right"sv, box_model.border.right));
  289. MUST(serializer.add("border_bottom"sv, box_model.border.bottom));
  290. MUST(serializer.add("border_left"sv, box_model.border.left));
  291. if (auto* paint_box = box->paint_box()) {
  292. MUST(serializer.add("content_width"sv, paint_box->content_width()));
  293. MUST(serializer.add("content_height"sv, paint_box->content_height()));
  294. } else {
  295. MUST(serializer.add("content_width"sv, 0));
  296. MUST(serializer.add("content_height"sv, 0));
  297. }
  298. MUST(serializer.finish());
  299. return builder.to_string();
  300. };
  301. if (pseudo_element.has_value()) {
  302. auto pseudo_element_node = element.get_pseudo_element_node(pseudo_element.value());
  303. if (!pseudo_element_node)
  304. return { false, "", "", "", "" };
  305. // FIXME: Pseudo-elements only exist as Layout::Nodes, which don't have style information
  306. // in a format we can use. So, we run the StyleComputer again to get the specified
  307. // values, and have to ignore the computed values and custom properties.
  308. auto pseudo_element_style = page().focused_context().active_document()->style_computer().compute_style(element, pseudo_element);
  309. String computed_values = serialize_json(pseudo_element_style);
  310. String resolved_values = "{}";
  311. String custom_properties_json = "{}";
  312. String node_box_sizing_json = serialize_node_box_sizing_json(pseudo_element_node.ptr());
  313. return { true, computed_values, resolved_values, custom_properties_json, node_box_sizing_json };
  314. }
  315. String computed_values = serialize_json(*element.computed_css_values());
  316. String resolved_values_json = serialize_json(element.resolved_css_values());
  317. String custom_properties_json = serialize_custom_properties_json(element);
  318. String node_box_sizing_json = serialize_node_box_sizing_json(element.layout_node());
  319. return { true, computed_values, resolved_values_json, custom_properties_json, node_box_sizing_json };
  320. }
  321. return { false, "", "", "", "" };
  322. }
  323. Messages::WebContentServer::GetHoveredNodeIdResponse ConnectionFromClient::get_hovered_node_id()
  324. {
  325. if (auto* document = page().top_level_browsing_context().active_document()) {
  326. auto hovered_node = document->hovered_node();
  327. if (hovered_node)
  328. return hovered_node->id();
  329. }
  330. return (i32)0;
  331. }
  332. void ConnectionFromClient::initialize_js_console(Badge<PageHost>)
  333. {
  334. auto* document = page().top_level_browsing_context().active_document();
  335. auto realm = document->realm().make_weak_ptr();
  336. if (m_realm.ptr() == realm.ptr())
  337. return;
  338. auto& console_object = *realm->intrinsics().console_object();
  339. m_realm = realm;
  340. m_console_client = make<WebContentConsoleClient>(console_object.console(), *m_realm, *this);
  341. console_object.console().set_client(*m_console_client.ptr());
  342. }
  343. void ConnectionFromClient::js_console_input(String const& js_source)
  344. {
  345. if (m_console_client)
  346. m_console_client->handle_input(js_source);
  347. }
  348. void ConnectionFromClient::run_javascript(String const& js_source)
  349. {
  350. auto* active_document = page().top_level_browsing_context().active_document();
  351. if (!active_document)
  352. return;
  353. // This is partially based on "execute a javascript: URL request" https://html.spec.whatwg.org/multipage/browsing-the-web.html#javascript-protocol
  354. // Let settings be browsingContext's active document's relevant settings object.
  355. auto& settings = active_document->relevant_settings_object();
  356. // Let baseURL be settings's API base URL.
  357. auto base_url = settings.api_base_url();
  358. // Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.
  359. // FIXME: This doesn't pass in "default classic script fetch options"
  360. // FIXME: What should the filename be here?
  361. auto script = Web::HTML::ClassicScript::create("(client connection run_javascript)", js_source, settings, move(base_url));
  362. // Let evaluationStatus be the result of running the classic script script.
  363. auto evaluation_status = script->run();
  364. if (evaluation_status.is_error())
  365. dbgln("Exception :(");
  366. }
  367. void ConnectionFromClient::js_console_request_messages(i32 start_index)
  368. {
  369. if (m_console_client)
  370. m_console_client->send_messages(start_index);
  371. }
  372. Messages::WebContentServer::GetDocumentElementResponse ConnectionFromClient::get_document_element()
  373. {
  374. auto* document = page().top_level_browsing_context().active_document();
  375. if (!document)
  376. return Optional<i32> {};
  377. return { document->id() };
  378. }
  379. Messages::WebContentServer::QuerySelectorAllResponse ConnectionFromClient::query_selector_all(i32 start_node_id, String const& selector)
  380. {
  381. auto* start_node = Web::DOM::Node::from_id(start_node_id);
  382. if (!start_node)
  383. return Optional<Vector<i32>> {};
  384. if (!start_node->is_element() && !start_node->is_document())
  385. return Optional<Vector<i32>> {};
  386. auto& start_element = verify_cast<Web::DOM::ParentNode>(*start_node);
  387. auto result = start_element.query_selector_all(selector);
  388. if (result.is_error())
  389. return Optional<Vector<i32>> {};
  390. auto element_list = result.release_value();
  391. Vector<i32> return_list;
  392. for (u32 i = 0; i < element_list->length(); i++) {
  393. auto node = element_list->item(i);
  394. return_list.append(node->id());
  395. }
  396. return { return_list };
  397. }
  398. Messages::WebContentServer::GetElementAttributeResponse ConnectionFromClient::get_element_attribute(i32 element_id, String const& name)
  399. {
  400. auto* node = Web::DOM::Node::from_id(element_id);
  401. if (!node)
  402. return Optional<String> {};
  403. if (!node->is_element())
  404. return Optional<String> {};
  405. auto& element = verify_cast<Web::DOM::Element>(*node);
  406. if (!element.has_attribute(name))
  407. return Optional<String> {};
  408. return { element.get_attribute(name) };
  409. }
  410. Messages::WebContentServer::GetElementPropertyResponse ConnectionFromClient::get_element_property(i32 element_id, String const& name)
  411. {
  412. auto* node = Web::DOM::Node::from_id(element_id);
  413. if (!node)
  414. return Optional<String> {};
  415. if (!node->is_element())
  416. return Optional<String> {};
  417. auto& element = verify_cast<Web::DOM::Element>(*node);
  418. auto property_or_error = element.get(name);
  419. if (property_or_error.is_throw_completion())
  420. return Optional<String> {};
  421. auto property = property_or_error.release_value();
  422. if (property.is_undefined())
  423. return Optional<String> {};
  424. auto string_or_error = property.to_string(element.vm());
  425. if (string_or_error.is_error())
  426. return Optional<String> {};
  427. return { string_or_error.release_value() };
  428. }
  429. Messages::WebContentServer::GetActiveDocumentsTypeResponse ConnectionFromClient::get_active_documents_type()
  430. {
  431. auto* active_document = page().top_level_browsing_context().active_document();
  432. if (!active_document)
  433. return { "" };
  434. auto type = active_document->document_type();
  435. switch (type) {
  436. case Web::DOM::Document::Type::HTML:
  437. return { "html" };
  438. break;
  439. case Web::DOM::Document::Type::XML:
  440. return { "xml" };
  441. break;
  442. }
  443. return { "" };
  444. }
  445. Messages::WebContentServer::GetComputedValueForElementResponse ConnectionFromClient::get_computed_value_for_element(i32 element_id, String const& property_name)
  446. {
  447. auto* node = Web::DOM::Node::from_id(element_id);
  448. if (!node)
  449. return { "" };
  450. if (!node->is_element())
  451. return { "" };
  452. auto& element = verify_cast<Web::DOM::Element>(*node);
  453. auto property_id = Web::CSS::property_id_from_string(property_name);
  454. auto computed_values = element.computed_css_values();
  455. if (!computed_values)
  456. return { "" };
  457. auto style_value = computed_values->property(property_id);
  458. return { style_value->to_string() };
  459. }
  460. Messages::WebContentServer::GetElementTextResponse ConnectionFromClient::get_element_text(i32 element_id)
  461. {
  462. auto* node = Web::DOM::Node::from_id(element_id);
  463. if (!node)
  464. return { "" };
  465. if (!node->is_element())
  466. return { "" };
  467. auto& element = verify_cast<Web::DOM::Element>(*node);
  468. return { element.layout_node()->dom_node()->text_content() };
  469. }
  470. Messages::WebContentServer::GetElementTagNameResponse ConnectionFromClient::get_element_tag_name(i32 element_id)
  471. {
  472. auto* node = Web::DOM::Node::from_id(element_id);
  473. if (!node)
  474. return { "" };
  475. if (!node->is_element())
  476. return { "" };
  477. auto& element = verify_cast<Web::DOM::Element>(*node);
  478. return { element.tag_name() };
  479. }
  480. Messages::WebContentServer::GetSelectedTextResponse ConnectionFromClient::get_selected_text()
  481. {
  482. return page().focused_context().selected_text();
  483. }
  484. void ConnectionFromClient::select_all()
  485. {
  486. page().focused_context().select_all();
  487. page().client().page_did_change_selection();
  488. }
  489. Messages::WebContentServer::DumpLayoutTreeResponse ConnectionFromClient::dump_layout_tree()
  490. {
  491. auto* document = page().top_level_browsing_context().active_document();
  492. if (!document)
  493. return String { "(no DOM tree)" };
  494. auto* layout_root = document->layout_node();
  495. if (!layout_root)
  496. return String { "(no layout tree)" };
  497. StringBuilder builder;
  498. Web::dump_tree(builder, *layout_root);
  499. return builder.to_string();
  500. }
  501. void ConnectionFromClient::set_content_filters(Vector<String> const& filters)
  502. {
  503. for (auto& filter : filters)
  504. Web::ContentFilter::the().add_pattern(filter);
  505. }
  506. void ConnectionFromClient::set_proxy_mappings(Vector<String> const& proxies, HashMap<String, size_t> const& mappings)
  507. {
  508. auto keys = mappings.keys();
  509. quick_sort(keys, [&](auto& a, auto& b) { return a.length() < b.length(); });
  510. OrderedHashMap<String, size_t> sorted_mappings;
  511. for (auto& key : keys) {
  512. auto value = *mappings.get(key);
  513. if (value >= proxies.size())
  514. continue;
  515. sorted_mappings.set(key, value);
  516. }
  517. Web::ProxyMappings::the().set_mappings(proxies, move(sorted_mappings));
  518. }
  519. void ConnectionFromClient::set_preferred_color_scheme(Web::CSS::PreferredColorScheme const& color_scheme)
  520. {
  521. m_page_host->set_preferred_color_scheme(color_scheme);
  522. }
  523. void ConnectionFromClient::set_has_focus(bool has_focus)
  524. {
  525. m_page_host->set_has_focus(has_focus);
  526. }
  527. void ConnectionFromClient::set_is_scripting_enabled(bool is_scripting_enabled)
  528. {
  529. m_page_host->set_is_scripting_enabled(is_scripting_enabled);
  530. }
  531. void ConnectionFromClient::set_is_webdriver_active(bool is_webdriver_active)
  532. {
  533. m_page_host->set_is_webdriver_active(is_webdriver_active);
  534. }
  535. void ConnectionFromClient::set_window_position(Gfx::IntPoint const& position)
  536. {
  537. m_page_host->set_window_position(position);
  538. }
  539. void ConnectionFromClient::set_window_size(Gfx::IntSize const& size)
  540. {
  541. m_page_host->set_window_size(size);
  542. }
  543. Messages::WebContentServer::GetLocalStorageEntriesResponse ConnectionFromClient::get_local_storage_entries()
  544. {
  545. auto* document = page().top_level_browsing_context().active_document();
  546. auto local_storage = document->window().local_storage();
  547. return local_storage->map();
  548. }
  549. Messages::WebContentServer::GetSessionStorageEntriesResponse ConnectionFromClient::get_session_storage_entries()
  550. {
  551. auto* document = page().top_level_browsing_context().active_document();
  552. auto session_storage = document->window().session_storage();
  553. return session_storage->map();
  554. }
  555. void ConnectionFromClient::handle_file_return(i32 error, Optional<IPC::File> const& file, i32 request_id)
  556. {
  557. auto result = m_requested_files.get(request_id);
  558. VERIFY(result.has_value());
  559. VERIFY(result.value()->on_file_request_finish);
  560. result.value()->on_file_request_finish(error != 0 ? Error::from_errno(error) : ErrorOr<i32> { file->take_fd() });
  561. m_requested_files.remove(request_id);
  562. }
  563. void ConnectionFromClient::request_file(NonnullRefPtr<Web::FileRequest>& file_request)
  564. {
  565. i32 const id = last_id++;
  566. m_requested_files.set(id, file_request);
  567. async_did_request_file(file_request->path(), id);
  568. }
  569. void ConnectionFromClient::set_system_visibility_state(bool visible)
  570. {
  571. m_page_host->page().top_level_browsing_context().set_system_visibility_state(
  572. visible
  573. ? Web::HTML::VisibilityState::Visible
  574. : Web::HTML::VisibilityState::Hidden);
  575. }
  576. Messages::WebContentServer::WebdriverExecuteScriptResponse ConnectionFromClient::webdriver_execute_script(String const& body, Vector<String> const& json_arguments, Optional<u64> const& timeout, bool async)
  577. {
  578. auto& page = m_page_host->page();
  579. auto* window = page.top_level_browsing_context().active_window();
  580. auto& vm = window->vm();
  581. auto arguments = JS::MarkedVector<JS::Value> { vm.heap() };
  582. for (auto const& argument_string : json_arguments) {
  583. // NOTE: These are assumed to be valid JSON values.
  584. auto json_value = MUST(JsonValue::from_string(argument_string));
  585. arguments.append(JS::JSONObject::parse_json_value(vm, json_value));
  586. }
  587. auto result = async
  588. ? Web::WebDriver::execute_async_script(page, body, move(arguments), timeout)
  589. : Web::WebDriver::execute_script(page, body, move(arguments), timeout);
  590. return { result.type, result.value.serialized<StringBuilder>() };
  591. }
  592. }