ConnectionFromClient.cpp 19 KB

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