ClientConnection.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. /*
  2. * Copyright (c) 2020-2021, 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/Layout/InitialContainingBlock.h>
  23. #include <LibWeb/Loader/ContentFilter.h>
  24. #include <LibWeb/Loader/ResourceLoader.h>
  25. #include <WebContent/ClientConnection.h>
  26. #include <WebContent/PageHost.h>
  27. #include <WebContent/WebContentClientEndpoint.h>
  28. #include <pthread.h>
  29. namespace WebContent {
  30. ClientConnection::ClientConnection(NonnullOwnPtr<Core::Stream::LocalSocket> socket)
  31. : IPC::ClientConnection<WebContentClientEndpoint, WebContentServerEndpoint>(*this, move(socket), 1)
  32. , m_page_host(PageHost::create(*this))
  33. {
  34. m_paint_flush_timer = Core::Timer::create_single_shot(0, [this] { flush_pending_paint_requests(); });
  35. }
  36. ClientConnection::~ClientConnection()
  37. {
  38. }
  39. void ClientConnection::die()
  40. {
  41. Core::EventLoop::current().quit(0);
  42. }
  43. Web::Page& ClientConnection::page()
  44. {
  45. return m_page_host->page();
  46. }
  47. const Web::Page& ClientConnection::page() const
  48. {
  49. return m_page_host->page();
  50. }
  51. void ClientConnection::update_system_theme(const Core::AnonymousBuffer& theme_buffer)
  52. {
  53. Gfx::set_system_theme(theme_buffer);
  54. auto impl = Gfx::PaletteImpl::create_with_anonymous_buffer(theme_buffer);
  55. m_page_host->set_palette_impl(*impl);
  56. }
  57. void ClientConnection::update_system_fonts(String const& default_font_query, String const& fixed_width_font_query)
  58. {
  59. Gfx::FontDatabase::set_default_font_query(default_font_query);
  60. Gfx::FontDatabase::set_fixed_width_font_query(fixed_width_font_query);
  61. }
  62. void ClientConnection::update_screen_rects(const Vector<Gfx::IntRect>& rects, u32 main_screen)
  63. {
  64. m_page_host->set_screen_rects(rects, main_screen);
  65. }
  66. void ClientConnection::load_url(const URL& url)
  67. {
  68. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::LoadURL: url={}", url);
  69. String process_name;
  70. if (url.host().is_empty())
  71. process_name = "WebContent";
  72. else
  73. process_name = String::formatted("WebContent: {}", url.host());
  74. pthread_setname_np(pthread_self(), process_name.characters());
  75. page().load(url);
  76. }
  77. void ClientConnection::load_html(const String& html, const URL& url)
  78. {
  79. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::LoadHTML: html={}, url={}", html, url);
  80. page().load_html(html, url);
  81. }
  82. void ClientConnection::set_viewport_rect(const Gfx::IntRect& rect)
  83. {
  84. dbgln_if(SPAM_DEBUG, "handle: WebContentServer::SetViewportRect: rect={}", rect);
  85. m_page_host->set_viewport_rect(rect);
  86. }
  87. void ClientConnection::add_backing_store(i32 backing_store_id, const Gfx::ShareableBitmap& bitmap)
  88. {
  89. m_backing_stores.set(backing_store_id, *bitmap.bitmap());
  90. }
  91. void ClientConnection::remove_backing_store(i32 backing_store_id)
  92. {
  93. m_backing_stores.remove(backing_store_id);
  94. }
  95. void ClientConnection::paint(const Gfx::IntRect& content_rect, i32 backing_store_id)
  96. {
  97. for (auto& pending_paint : m_pending_paint_requests) {
  98. if (pending_paint.bitmap_id == backing_store_id) {
  99. pending_paint.content_rect = content_rect;
  100. return;
  101. }
  102. }
  103. auto it = m_backing_stores.find(backing_store_id);
  104. if (it == m_backing_stores.end()) {
  105. did_misbehave("Client requested paint with backing store ID");
  106. return;
  107. }
  108. auto& bitmap = *it->value;
  109. m_pending_paint_requests.append({ content_rect, bitmap, backing_store_id });
  110. m_paint_flush_timer->start();
  111. }
  112. void ClientConnection::flush_pending_paint_requests()
  113. {
  114. for (auto& pending_paint : m_pending_paint_requests) {
  115. m_page_host->paint(pending_paint.content_rect, *pending_paint.bitmap);
  116. async_did_paint(pending_paint.content_rect, pending_paint.bitmap_id);
  117. }
  118. m_pending_paint_requests.clear();
  119. }
  120. void ClientConnection::mouse_down(const Gfx::IntPoint& position, unsigned int button, [[maybe_unused]] unsigned int buttons, unsigned int modifiers)
  121. {
  122. page().handle_mousedown(position, button, modifiers);
  123. }
  124. void ClientConnection::mouse_move(const Gfx::IntPoint& position, [[maybe_unused]] unsigned int button, unsigned int buttons, unsigned int modifiers)
  125. {
  126. page().handle_mousemove(position, buttons, modifiers);
  127. }
  128. void ClientConnection::mouse_up(const Gfx::IntPoint& position, unsigned int button, [[maybe_unused]] unsigned int buttons, unsigned int modifiers)
  129. {
  130. page().handle_mouseup(position, button, modifiers);
  131. }
  132. void ClientConnection::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)
  133. {
  134. page().handle_mousewheel(position, button, modifiers, wheel_delta_x, wheel_delta_y);
  135. }
  136. void ClientConnection::key_down(i32 key, unsigned int modifiers, u32 code_point)
  137. {
  138. page().handle_keydown((KeyCode)key, modifiers, code_point);
  139. }
  140. void ClientConnection::key_up(i32 key, unsigned int modifiers, u32 code_point)
  141. {
  142. page().handle_keyup((KeyCode)key, modifiers, code_point);
  143. }
  144. void ClientConnection::debug_request(const String& request, const String& argument)
  145. {
  146. if (request == "dump-dom-tree") {
  147. if (auto* doc = page().top_level_browsing_context().active_document())
  148. Web::dump_tree(*doc);
  149. }
  150. if (request == "dump-layout-tree") {
  151. if (auto* doc = page().top_level_browsing_context().active_document()) {
  152. if (auto* icb = doc->layout_node())
  153. Web::dump_tree(*icb);
  154. }
  155. }
  156. if (request == "dump-stacking-context-tree") {
  157. if (auto* doc = page().top_level_browsing_context().active_document()) {
  158. if (auto* icb = doc->layout_node()) {
  159. if (auto* stacking_context = icb->stacking_context())
  160. stacking_context->dump();
  161. }
  162. }
  163. }
  164. if (request == "dump-style-sheets") {
  165. if (auto* doc = page().top_level_browsing_context().active_document()) {
  166. for (auto& sheet : doc->style_sheets().sheets()) {
  167. Web::dump_sheet(sheet);
  168. }
  169. }
  170. }
  171. if (request == "collect-garbage") {
  172. Web::Bindings::main_thread_vm().heap().collect_garbage(JS::Heap::CollectionType::CollectGarbage, true);
  173. }
  174. if (request == "set-line-box-borders") {
  175. bool state = argument == "on";
  176. m_page_host->set_should_show_line_box_borders(state);
  177. page().top_level_browsing_context().set_needs_display(page().top_level_browsing_context().viewport_rect());
  178. }
  179. if (request == "clear-cache") {
  180. Web::ResourceLoader::the().clear_cache();
  181. }
  182. if (request == "spoof-user-agent") {
  183. Web::ResourceLoader::the().set_user_agent(argument);
  184. }
  185. if (request == "same-origin-policy") {
  186. m_page_host->page().set_same_origin_policy_enabled(argument == "on");
  187. }
  188. }
  189. void ClientConnection::get_source()
  190. {
  191. if (auto* doc = page().top_level_browsing_context().active_document()) {
  192. async_did_get_source(doc->url(), doc->source());
  193. }
  194. }
  195. void ClientConnection::inspect_dom_tree()
  196. {
  197. if (auto* doc = page().top_level_browsing_context().active_document()) {
  198. async_did_get_dom_tree(doc->dump_dom_tree_as_json());
  199. }
  200. }
  201. Messages::WebContentServer::InspectDomNodeResponse ClientConnection::inspect_dom_node(i32 node_id)
  202. {
  203. auto& top_context = page().top_level_browsing_context();
  204. top_context.for_each_in_inclusive_subtree([&](auto& ctx) {
  205. if (ctx.active_document() != nullptr) {
  206. ctx.active_document()->set_inspected_node(nullptr);
  207. }
  208. return IterationDecision::Continue;
  209. });
  210. Web::DOM::Node* node = Web::DOM::Node::from_id(node_id);
  211. if (!node) {
  212. return { false, "", "", "" };
  213. }
  214. node->document().set_inspected_node(node);
  215. if (node->is_element()) {
  216. auto& element = verify_cast<Web::DOM::Element>(*node);
  217. if (!element.specified_css_values())
  218. return { false, "", "", "" };
  219. auto serialize_json = [](Web::CSS::StyleProperties const& properties) -> String {
  220. StringBuilder builder;
  221. JsonObjectSerializer serializer(builder);
  222. properties.for_each_property([&](auto property_id, auto& value) {
  223. serializer.add(Web::CSS::string_from_property_id(property_id), value.to_string());
  224. });
  225. serializer.finish();
  226. return builder.to_string();
  227. };
  228. auto serialize_custom_properties_json = [](Web::DOM::Element const& element) -> String {
  229. StringBuilder builder;
  230. JsonObjectSerializer serializer(builder);
  231. HashTable<String> seen_properties;
  232. auto const* element_to_check = &element;
  233. while (element_to_check) {
  234. for (auto const& property : element_to_check->custom_properties()) {
  235. if (!seen_properties.contains(property.key) && property.value.style.has_value()) {
  236. seen_properties.set(property.key);
  237. serializer.add(property.key, property.value.style.value().value->to_string());
  238. }
  239. }
  240. element_to_check = element_to_check->parent_element();
  241. }
  242. serializer.finish();
  243. return builder.to_string();
  244. };
  245. String specified_values_json = serialize_json(*element.specified_css_values());
  246. String computed_values_json = serialize_json(element.computed_style());
  247. String custom_properties_json = serialize_custom_properties_json(element);
  248. return { true, specified_values_json, computed_values_json, custom_properties_json };
  249. }
  250. return { false, "", "", "" };
  251. }
  252. Messages::WebContentServer::GetHoveredNodeIdResponse ClientConnection::get_hovered_node_id()
  253. {
  254. if (auto* document = page().top_level_browsing_context().active_document()) {
  255. auto hovered_node = document->hovered_node();
  256. if (hovered_node)
  257. return hovered_node->id();
  258. }
  259. return (i32)0;
  260. }
  261. void ClientConnection::initialize_js_console(Badge<PageHost>)
  262. {
  263. auto* document = page().top_level_browsing_context().active_document();
  264. auto interpreter = document->interpreter().make_weak_ptr();
  265. if (m_interpreter.ptr() == interpreter.ptr())
  266. return;
  267. m_interpreter = interpreter;
  268. m_console_client = make<WebContentConsoleClient>(interpreter->global_object().console(), interpreter, *this);
  269. interpreter->global_object().console().set_client(*m_console_client.ptr());
  270. }
  271. void ClientConnection::js_console_input(const String& js_source)
  272. {
  273. if (m_console_client)
  274. m_console_client->handle_input(js_source);
  275. }
  276. void ClientConnection::run_javascript(String const& js_source)
  277. {
  278. auto* active_document = page().top_level_browsing_context().active_document();
  279. if (!active_document)
  280. return;
  281. // This is partially based on "execute a javascript: URL request" https://html.spec.whatwg.org/multipage/browsing-the-web.html#javascript-protocol
  282. // Let settings be browsingContext's active document's relevant settings object.
  283. auto& settings = active_document->relevant_settings_object();
  284. // Let baseURL be settings's API base URL.
  285. auto base_url = settings.api_base_url();
  286. // Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.
  287. // FIXME: This doesn't pass in "default classic script fetch options"
  288. // FIXME: What should the filename be here?
  289. auto script = Web::HTML::ClassicScript::create("(client connection run_javascript)", js_source, settings, move(base_url));
  290. // Let evaluationStatus be the result of running the classic script script.
  291. auto evaluation_status = script->run();
  292. if (evaluation_status.is_error())
  293. dbgln("Exception :(");
  294. }
  295. void ClientConnection::js_console_request_messages(i32 start_index)
  296. {
  297. if (m_console_client)
  298. m_console_client->send_messages(start_index);
  299. }
  300. Messages::WebContentServer::GetSelectedTextResponse ClientConnection::get_selected_text()
  301. {
  302. return page().focused_context().selected_text();
  303. }
  304. void ClientConnection::select_all()
  305. {
  306. page().focused_context().select_all();
  307. page().client().page_did_change_selection();
  308. }
  309. Messages::WebContentServer::DumpLayoutTreeResponse ClientConnection::dump_layout_tree()
  310. {
  311. auto* document = page().top_level_browsing_context().active_document();
  312. if (!document)
  313. return String { "(no DOM tree)" };
  314. auto* layout_root = document->layout_node();
  315. if (!layout_root)
  316. return String { "(no layout tree)" };
  317. StringBuilder builder;
  318. Web::dump_tree(builder, *layout_root);
  319. return builder.to_string();
  320. }
  321. void ClientConnection::set_content_filters(Vector<String> const& filters)
  322. {
  323. for (auto& filter : filters)
  324. Web::ContentFilter::the().add_pattern(filter);
  325. }
  326. void ClientConnection::set_preferred_color_scheme(Web::CSS::PreferredColorScheme const& color_scheme)
  327. {
  328. m_page_host->set_preferred_color_scheme(color_scheme);
  329. }
  330. void ClientConnection::set_has_focus(bool has_focus)
  331. {
  332. m_page_host->set_has_focus(has_focus);
  333. }
  334. }