ConnectionFromClient.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. * Copyright (c) 2020-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Sam Atkins <atkinssj@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/JsonObject.h>
  9. #include <LibGfx/Bitmap.h>
  10. #include <LibGfx/FontDatabase.h>
  11. #include <LibGfx/SystemTheme.h>
  12. #include <LibJS/Console.h>
  13. #include <LibJS/Heap/Heap.h>
  14. #include <LibJS/Interpreter.h>
  15. #include <LibJS/Parser.h>
  16. #include <LibWeb/Bindings/MainThreadVM.h>
  17. #include <LibWeb/Cookie/ParsedCookie.h>
  18. #include <LibWeb/DOM/Document.h>
  19. #include <LibWeb/Dump.h>
  20. #include <LibWeb/HTML/BrowsingContext.h>
  21. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  22. #include <LibWeb/HTML/Storage.h>
  23. #include <LibWeb/HTML/Window.h>
  24. #include <LibWeb/Layout/InitialContainingBlock.h>
  25. #include <LibWeb/Loader/ContentFilter.h>
  26. #include <LibWeb/Loader/ResourceLoader.h>
  27. #include <LibWeb/Painting/Paintable.h>
  28. #include <WebContent/ConnectionFromClient.h>
  29. #include <WebContent/PageHost.h>
  30. #include <WebContent/WebContentClientEndpoint.h>
  31. #include <pthread.h>
  32. namespace WebContent {
  33. ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<Core::Stream::LocalSocket> socket)
  34. : IPC::ConnectionFromClient<WebContentClientEndpoint, WebContentServerEndpoint>(*this, move(socket), 1)
  35. , m_page_host(PageHost::create(*this))
  36. {
  37. m_paint_flush_timer = Core::Timer::create_single_shot(0, [this] { flush_pending_paint_requests(); });
  38. }
  39. ConnectionFromClient::~ConnectionFromClient()
  40. {
  41. }
  42. void ConnectionFromClient::die()
  43. {
  44. Core::EventLoop::current().quit(0);
  45. }
  46. Web::Page& ConnectionFromClient::page()
  47. {
  48. return m_page_host->page();
  49. }
  50. const Web::Page& ConnectionFromClient::page() const
  51. {
  52. return m_page_host->page();
  53. }
  54. void ConnectionFromClient::update_system_theme(const Core::AnonymousBuffer& theme_buffer)
  55. {
  56. Gfx::set_system_theme(theme_buffer);
  57. auto impl = Gfx::PaletteImpl::create_with_anonymous_buffer(theme_buffer);
  58. m_page_host->set_palette_impl(*impl);
  59. }
  60. void ConnectionFromClient::update_system_fonts(String const& default_font_query, String const& fixed_width_font_query)
  61. {
  62. Gfx::FontDatabase::set_default_font_query(default_font_query);
  63. Gfx::FontDatabase::set_fixed_width_font_query(fixed_width_font_query);
  64. }
  65. void ConnectionFromClient::update_screen_rects(const Vector<Gfx::IntRect>& rects, u32 main_screen)
  66. {
  67. m_page_host->set_screen_rects(rects, main_screen);
  68. }
  69. void ConnectionFromClient::load_url(const URL& url)
  70. {
  71. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::LoadURL: url={}", url);
  72. String process_name;
  73. if (url.host().is_empty())
  74. process_name = "WebContent";
  75. else
  76. process_name = String::formatted("WebContent: {}", url.host());
  77. pthread_setname_np(pthread_self(), process_name.characters());
  78. page().load(url);
  79. }
  80. void ConnectionFromClient::load_html(const String& html, const URL& url)
  81. {
  82. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::LoadHTML: html={}, url={}", html, url);
  83. page().load_html(html, url);
  84. }
  85. void ConnectionFromClient::set_viewport_rect(const Gfx::IntRect& rect)
  86. {
  87. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::SetViewportRect: rect={}", rect);
  88. m_page_host->set_viewport_rect(rect);
  89. }
  90. void ConnectionFromClient::add_backing_store(i32 backing_store_id, const Gfx::ShareableBitmap& bitmap)
  91. {
  92. m_backing_stores.set(backing_store_id, *bitmap.bitmap());
  93. }
  94. void ConnectionFromClient::remove_backing_store(i32 backing_store_id)
  95. {
  96. m_backing_stores.remove(backing_store_id);
  97. }
  98. void ConnectionFromClient::paint(const Gfx::IntRect& content_rect, i32 backing_store_id)
  99. {
  100. for (auto& pending_paint : m_pending_paint_requests) {
  101. if (pending_paint.bitmap_id == backing_store_id) {
  102. pending_paint.content_rect = content_rect;
  103. return;
  104. }
  105. }
  106. auto it = m_backing_stores.find(backing_store_id);
  107. if (it == m_backing_stores.end()) {
  108. did_misbehave("Client requested paint with backing store ID");
  109. return;
  110. }
  111. auto& bitmap = *it->value;
  112. m_pending_paint_requests.append({ content_rect, bitmap, backing_store_id });
  113. m_paint_flush_timer->start();
  114. }
  115. void ConnectionFromClient::flush_pending_paint_requests()
  116. {
  117. for (auto& pending_paint : m_pending_paint_requests) {
  118. m_page_host->paint(pending_paint.content_rect, *pending_paint.bitmap);
  119. async_did_paint(pending_paint.content_rect, pending_paint.bitmap_id);
  120. }
  121. m_pending_paint_requests.clear();
  122. }
  123. void ConnectionFromClient::mouse_down(const Gfx::IntPoint& position, unsigned int button, [[maybe_unused]] unsigned int buttons, unsigned int modifiers)
  124. {
  125. page().handle_mousedown(position, button, modifiers);
  126. }
  127. void ConnectionFromClient::mouse_move(const Gfx::IntPoint& position, [[maybe_unused]] unsigned int button, unsigned int buttons, unsigned int modifiers)
  128. {
  129. page().handle_mousemove(position, buttons, modifiers);
  130. }
  131. void ConnectionFromClient::mouse_up(const Gfx::IntPoint& position, unsigned int button, [[maybe_unused]] unsigned int buttons, unsigned int modifiers)
  132. {
  133. page().handle_mouseup(position, button, modifiers);
  134. }
  135. void ConnectionFromClient::mouse_wheel(const Gfx::IntPoint& position, unsigned int button, [[maybe_unused]] unsigned int buttons, unsigned int modifiers, i32 wheel_delta_x, i32 wheel_delta_y)
  136. {
  137. page().handle_mousewheel(position, button, modifiers, wheel_delta_x, wheel_delta_y);
  138. }
  139. void ConnectionFromClient::key_down(i32 key, unsigned int modifiers, u32 code_point)
  140. {
  141. page().handle_keydown((KeyCode)key, modifiers, code_point);
  142. }
  143. void ConnectionFromClient::key_up(i32 key, unsigned int modifiers, u32 code_point)
  144. {
  145. page().handle_keyup((KeyCode)key, modifiers, code_point);
  146. }
  147. void ConnectionFromClient::debug_request(const String& request, const String& argument)
  148. {
  149. if (request == "dump-dom-tree") {
  150. if (auto* doc = page().top_level_browsing_context().active_document())
  151. Web::dump_tree(*doc);
  152. }
  153. if (request == "dump-layout-tree") {
  154. if (auto* doc = page().top_level_browsing_context().active_document()) {
  155. if (auto* icb = doc->layout_node())
  156. Web::dump_tree(*icb);
  157. }
  158. }
  159. if (request == "dump-stacking-context-tree") {
  160. if (auto* doc = page().top_level_browsing_context().active_document()) {
  161. if (auto* icb = doc->layout_node()) {
  162. if (auto* stacking_context = icb->m_paint_box->stacking_context())
  163. stacking_context->dump();
  164. }
  165. }
  166. }
  167. if (request == "dump-style-sheets") {
  168. if (auto* doc = page().top_level_browsing_context().active_document()) {
  169. for (auto& sheet : doc->style_sheets().sheets()) {
  170. Web::dump_sheet(sheet);
  171. }
  172. }
  173. }
  174. if (request == "collect-garbage") {
  175. Web::Bindings::main_thread_vm().heap().collect_garbage(JS::Heap::CollectionType::CollectGarbage, true);
  176. }
  177. if (request == "set-line-box-borders") {
  178. bool state = argument == "on";
  179. m_page_host->set_should_show_line_box_borders(state);
  180. page().top_level_browsing_context().set_needs_display(page().top_level_browsing_context().viewport_rect());
  181. }
  182. if (request == "clear-cache") {
  183. Web::ResourceLoader::the().clear_cache();
  184. }
  185. if (request == "spoof-user-agent") {
  186. Web::ResourceLoader::the().set_user_agent(argument);
  187. }
  188. if (request == "same-origin-policy") {
  189. m_page_host->page().set_same_origin_policy_enabled(argument == "on");
  190. }
  191. if (request == "dump-local-storage") {
  192. if (auto* doc = page().top_level_browsing_context().active_document())
  193. doc->window().local_storage()->dump();
  194. }
  195. }
  196. void ConnectionFromClient::get_source()
  197. {
  198. if (auto* doc = page().top_level_browsing_context().active_document()) {
  199. async_did_get_source(doc->url(), doc->source());
  200. }
  201. }
  202. void ConnectionFromClient::inspect_dom_tree()
  203. {
  204. if (auto* doc = page().top_level_browsing_context().active_document()) {
  205. async_did_get_dom_tree(doc->dump_dom_tree_as_json());
  206. }
  207. }
  208. Messages::WebContentServer::InspectDomNodeResponse ConnectionFromClient::inspect_dom_node(i32 node_id, Optional<Web::CSS::Selector::PseudoElement> const& pseudo_element)
  209. {
  210. auto& top_context = page().top_level_browsing_context();
  211. top_context.for_each_in_inclusive_subtree([&](auto& ctx) {
  212. if (ctx.active_document() != nullptr) {
  213. ctx.active_document()->set_inspected_node(nullptr);
  214. }
  215. return IterationDecision::Continue;
  216. });
  217. Web::DOM::Node* node = Web::DOM::Node::from_id(node_id);
  218. if (!node) {
  219. return { false, "", "", "", "" };
  220. }
  221. // FIXME: Pass the pseudo-element here.
  222. node->document().set_inspected_node(node);
  223. if (node->is_element()) {
  224. auto& element = verify_cast<Web::DOM::Element>(*node);
  225. if (!element.specified_css_values())
  226. return { false, "", "", "", "" };
  227. auto serialize_json = [](Web::CSS::StyleProperties const& properties) -> String {
  228. StringBuilder builder;
  229. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  230. properties.for_each_property([&](auto property_id, auto& value) {
  231. MUST(serializer.add(Web::CSS::string_from_property_id(property_id), value.to_string()));
  232. });
  233. MUST(serializer.finish());
  234. return builder.to_string();
  235. };
  236. auto serialize_custom_properties_json = [](Web::DOM::Element const& element) -> String {
  237. StringBuilder builder;
  238. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  239. HashTable<String> seen_properties;
  240. auto const* element_to_check = &element;
  241. while (element_to_check) {
  242. for (auto const& property : element_to_check->custom_properties()) {
  243. if (!seen_properties.contains(property.key)) {
  244. seen_properties.set(property.key);
  245. MUST(serializer.add(property.key, property.value.value->to_string()));
  246. }
  247. }
  248. element_to_check = element_to_check->parent_element();
  249. }
  250. MUST(serializer.finish());
  251. return builder.to_string();
  252. };
  253. auto serialize_node_box_sizing_json = [](Web::Layout::Node const* layout_node) -> String {
  254. if (!layout_node || !layout_node->is_box()) {
  255. return "{}";
  256. }
  257. auto* box = static_cast<Web::Layout::Box const*>(layout_node);
  258. auto box_model = box->box_model();
  259. StringBuilder builder;
  260. auto serializer = MUST(JsonObjectSerializer<>::try_create(builder));
  261. MUST(serializer.add("padding_top", box_model.padding.top));
  262. MUST(serializer.add("padding_right", box_model.padding.right));
  263. MUST(serializer.add("padding_bottom", box_model.padding.bottom));
  264. MUST(serializer.add("padding_left", box_model.padding.left));
  265. MUST(serializer.add("margin_top", box_model.margin.top));
  266. MUST(serializer.add("margin_right", box_model.margin.top));
  267. MUST(serializer.add("margin_bottom", box_model.margin.top));
  268. MUST(serializer.add("margin_left", box_model.margin.top));
  269. MUST(serializer.add("border_top", box_model.border.top));
  270. MUST(serializer.add("border_right", box_model.border.right));
  271. MUST(serializer.add("border_bottom", box_model.border.bottom));
  272. MUST(serializer.add("border_left", box_model.border.left));
  273. if (auto* paint_box = box->paint_box()) {
  274. MUST(serializer.add("content_width", paint_box->content_width()));
  275. MUST(serializer.add("content_height", paint_box->content_height()));
  276. } else {
  277. MUST(serializer.add("content_width", 0));
  278. MUST(serializer.add("content_height", 0));
  279. }
  280. MUST(serializer.finish());
  281. return builder.to_string();
  282. };
  283. if (pseudo_element.has_value()) {
  284. auto pseudo_element_node = element.get_pseudo_element_node(pseudo_element.value());
  285. if (pseudo_element_node.is_null())
  286. return { false, "", "", "", "" };
  287. // FIXME: Pseudo-elements only exist as Layout::Nodes, which don't have style information
  288. // in a format we can use. So, we run the StyleComputer again to get the specified
  289. // values, and have to ignore the computed values and custom properties.
  290. auto pseudo_element_style = page().focused_context().active_document()->style_computer().compute_style(element, pseudo_element);
  291. String specified_values_json = serialize_json(pseudo_element_style);
  292. String computed_values_json = "{}";
  293. String custom_properties_json = "{}";
  294. String node_box_sizing_json = serialize_node_box_sizing_json(pseudo_element_node.ptr());
  295. return { true, specified_values_json, computed_values_json, custom_properties_json, node_box_sizing_json };
  296. }
  297. String specified_values_json = serialize_json(*element.specified_css_values());
  298. String computed_values_json = serialize_json(element.computed_style());
  299. String custom_properties_json = serialize_custom_properties_json(element);
  300. String node_box_sizing_json = serialize_node_box_sizing_json(element.layout_node());
  301. return { true, specified_values_json, computed_values_json, custom_properties_json, node_box_sizing_json };
  302. }
  303. return { false, "", "", "", "" };
  304. }
  305. Messages::WebContentServer::GetHoveredNodeIdResponse ConnectionFromClient::get_hovered_node_id()
  306. {
  307. if (auto* document = page().top_level_browsing_context().active_document()) {
  308. auto hovered_node = document->hovered_node();
  309. if (hovered_node)
  310. return hovered_node->id();
  311. }
  312. return (i32)0;
  313. }
  314. void ConnectionFromClient::initialize_js_console(Badge<PageHost>)
  315. {
  316. auto* document = page().top_level_browsing_context().active_document();
  317. auto interpreter = document->interpreter().make_weak_ptr();
  318. if (m_interpreter.ptr() == interpreter.ptr())
  319. return;
  320. m_interpreter = interpreter;
  321. m_console_client = make<WebContentConsoleClient>(interpreter->global_object().console(), interpreter, *this);
  322. interpreter->global_object().console().set_client(*m_console_client.ptr());
  323. }
  324. void ConnectionFromClient::js_console_input(const String& js_source)
  325. {
  326. if (m_console_client)
  327. m_console_client->handle_input(js_source);
  328. }
  329. void ConnectionFromClient::run_javascript(String const& js_source)
  330. {
  331. auto* active_document = page().top_level_browsing_context().active_document();
  332. if (!active_document)
  333. return;
  334. // This is partially based on "execute a javascript: URL request" https://html.spec.whatwg.org/multipage/browsing-the-web.html#javascript-protocol
  335. // Let settings be browsingContext's active document's relevant settings object.
  336. auto& settings = active_document->relevant_settings_object();
  337. // Let baseURL be settings's API base URL.
  338. auto base_url = settings.api_base_url();
  339. // Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.
  340. // FIXME: This doesn't pass in "default classic script fetch options"
  341. // FIXME: What should the filename be here?
  342. auto script = Web::HTML::ClassicScript::create("(client connection run_javascript)", js_source, settings, move(base_url));
  343. // Let evaluationStatus be the result of running the classic script script.
  344. auto evaluation_status = script->run();
  345. if (evaluation_status.is_error())
  346. dbgln("Exception :(");
  347. }
  348. void ConnectionFromClient::js_console_request_messages(i32 start_index)
  349. {
  350. if (m_console_client)
  351. m_console_client->send_messages(start_index);
  352. }
  353. Messages::WebContentServer::GetSelectedTextResponse ConnectionFromClient::get_selected_text()
  354. {
  355. return page().focused_context().selected_text();
  356. }
  357. void ConnectionFromClient::select_all()
  358. {
  359. page().focused_context().select_all();
  360. page().client().page_did_change_selection();
  361. }
  362. Messages::WebContentServer::DumpLayoutTreeResponse ConnectionFromClient::dump_layout_tree()
  363. {
  364. auto* document = page().top_level_browsing_context().active_document();
  365. if (!document)
  366. return String { "(no DOM tree)" };
  367. auto* layout_root = document->layout_node();
  368. if (!layout_root)
  369. return String { "(no layout tree)" };
  370. StringBuilder builder;
  371. Web::dump_tree(builder, *layout_root);
  372. return builder.to_string();
  373. }
  374. void ConnectionFromClient::set_content_filters(Vector<String> const& filters)
  375. {
  376. for (auto& filter : filters)
  377. Web::ContentFilter::the().add_pattern(filter);
  378. }
  379. void ConnectionFromClient::set_preferred_color_scheme(Web::CSS::PreferredColorScheme const& color_scheme)
  380. {
  381. m_page_host->set_preferred_color_scheme(color_scheme);
  382. }
  383. void ConnectionFromClient::set_has_focus(bool has_focus)
  384. {
  385. m_page_host->set_has_focus(has_focus);
  386. }
  387. }