InspectorClient.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. /*
  2. * Copyright (c) 2023-2024, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Base64.h>
  7. #include <AK/Enumerate.h>
  8. #include <AK/JsonArray.h>
  9. #include <AK/JsonObject.h>
  10. #include <AK/LexicalPath.h>
  11. #include <AK/SourceGenerator.h>
  12. #include <AK/StringBuilder.h>
  13. #include <LibCore/Directory.h>
  14. #include <LibCore/File.h>
  15. #include <LibCore/Resource.h>
  16. #include <LibJS/MarkupGenerator.h>
  17. #include <LibWeb/Infra/Strings.h>
  18. #include <LibWebView/Application.h>
  19. #include <LibWebView/CookieJar.h>
  20. #include <LibWebView/InspectorClient.h>
  21. #include <LibWebView/SourceHighlighter.h>
  22. namespace WebView {
  23. static constexpr auto INSPECTOR_HTML = "resource://ladybird/inspector.html"sv;
  24. static constexpr auto INSPECTOR_CSS = "resource://ladybird/inspector.css"sv;
  25. static constexpr auto INSPECTOR_JS = "resource://ladybird/inspector.js"sv;
  26. static ErrorOr<JsonValue> parse_json_tree(StringView json)
  27. {
  28. auto parsed_tree = TRY(JsonValue::from_string(json));
  29. if (!parsed_tree.is_object())
  30. return Error::from_string_literal("Expected tree to be a JSON object");
  31. return parsed_tree;
  32. }
  33. static String style_sheet_identifier_to_json(Web::CSS::StyleSheetIdentifier const& identifier)
  34. {
  35. return MUST(String::formatted("{{ type: '{}', domNodeId: {}, url: '{}' }}"sv,
  36. Web::CSS::style_sheet_identifier_type_to_string(identifier.type),
  37. identifier.dom_element_unique_id.map([](auto& it) { return String::number(it); }).value_or("undefined"_string),
  38. identifier.url.value_or("undefined"_string)));
  39. }
  40. InspectorClient::InspectorClient(ViewImplementation& content_web_view, ViewImplementation& inspector_web_view)
  41. : m_content_web_view(content_web_view)
  42. , m_inspector_web_view(inspector_web_view)
  43. {
  44. m_content_web_view.on_received_dom_tree = [this](auto const& dom_tree) {
  45. auto result = parse_json_tree(dom_tree);
  46. if (result.is_error()) {
  47. dbgln("Failed to load DOM tree: {}", result.error());
  48. return;
  49. }
  50. auto dom_tree_html = generate_dom_tree(result.value().as_object());
  51. auto dom_tree_base64 = MUST(encode_base64(dom_tree_html.bytes()));
  52. auto script = MUST(String::formatted("inspector.loadDOMTree(\"{}\");", dom_tree_base64));
  53. m_inspector_web_view.run_javascript(script);
  54. m_dom_tree_loaded = true;
  55. if (m_pending_selection.has_value())
  56. select_node(m_pending_selection.release_value());
  57. else
  58. select_default_node();
  59. };
  60. m_content_web_view.on_received_dom_node_properties = [this](auto const& inspected_node_properties) {
  61. StringBuilder builder;
  62. // FIXME: Support box model metrics and ARIA properties.
  63. auto generate_property_script = [&](auto const& computed_style, auto const& resolved_style, auto const& custom_properties, auto const& fonts) {
  64. builder.append("inspector.createPropertyTables(\""sv);
  65. builder.append_escaped_for_json(computed_style);
  66. builder.append("\", \""sv);
  67. builder.append_escaped_for_json(resolved_style);
  68. builder.append("\", \""sv);
  69. builder.append_escaped_for_json(custom_properties);
  70. builder.append("\");"sv);
  71. builder.append("inspector.createFontList(\""sv);
  72. builder.append_escaped_for_json(fonts);
  73. builder.append("\");"sv);
  74. };
  75. if (inspected_node_properties.has_value()) {
  76. generate_property_script(
  77. inspected_node_properties->computed_style_json,
  78. inspected_node_properties->resolved_style_json,
  79. inspected_node_properties->custom_properties_json,
  80. inspected_node_properties->fonts_json);
  81. } else {
  82. generate_property_script("{}"sv, "{}"sv, "{}"sv, "{}"sv);
  83. }
  84. m_inspector_web_view.run_javascript(builder.string_view());
  85. };
  86. m_content_web_view.on_received_accessibility_tree = [this](auto const& accessibility_tree) {
  87. auto result = parse_json_tree(accessibility_tree);
  88. if (result.is_error()) {
  89. dbgln("Failed to load accessibility tree: {}", result.error());
  90. return;
  91. }
  92. auto accessibility_tree_html = generate_accessibility_tree(result.value().as_object());
  93. auto accessibility_tree_base64 = MUST(encode_base64(accessibility_tree_html.bytes()));
  94. auto script = MUST(String::formatted("inspector.loadAccessibilityTree(\"{}\");", accessibility_tree_base64));
  95. m_inspector_web_view.run_javascript(script);
  96. };
  97. m_content_web_view.on_received_hovered_node_id = [this](auto node_id) {
  98. select_node(node_id);
  99. };
  100. m_content_web_view.on_received_style_sheet_list = [this](auto const& style_sheets) {
  101. StringBuilder builder;
  102. builder.append("inspector.setStyleSheets(["sv);
  103. for (auto& style_sheet : style_sheets) {
  104. builder.appendff("{}, "sv, style_sheet_identifier_to_json(style_sheet));
  105. }
  106. builder.append("]);"sv);
  107. m_inspector_web_view.run_javascript(builder.string_view());
  108. };
  109. m_content_web_view.on_received_style_sheet_source = [this](Web::CSS::StyleSheetIdentifier const& identifier, auto const& base_url, String const& source) {
  110. auto html = highlight_source(identifier.url.value_or({}), base_url, source, Syntax::Language::CSS, HighlightOutputMode::SourceOnly);
  111. auto script = MUST(String::formatted("inspector.setStyleSheetSource({}, \"{}\");",
  112. style_sheet_identifier_to_json(identifier),
  113. MUST(encode_base64(html.bytes()))));
  114. m_inspector_web_view.run_javascript(script);
  115. };
  116. m_content_web_view.on_finshed_editing_dom_node = [this](auto const& node_id) {
  117. m_pending_selection = node_id;
  118. m_dom_tree_loaded = false;
  119. m_dom_node_attributes.clear();
  120. inspect();
  121. };
  122. m_content_web_view.on_received_dom_node_html = [this](auto const& html) {
  123. if (m_content_web_view.on_insert_clipboard_entry)
  124. m_content_web_view.on_insert_clipboard_entry(html, "unspecified"_string, "text/plain"_string);
  125. };
  126. m_content_web_view.on_received_console_message = [this](auto message_index) {
  127. handle_console_message(message_index);
  128. };
  129. m_content_web_view.on_received_console_messages = [this](auto start_index, auto const& message_types, auto const& messages) {
  130. handle_console_messages(start_index, message_types, messages);
  131. };
  132. m_inspector_web_view.enable_inspector_prototype();
  133. m_inspector_web_view.use_native_user_style_sheet();
  134. m_inspector_web_view.on_inspector_loaded = [this]() {
  135. m_inspector_loaded = true;
  136. inspect();
  137. m_content_web_view.js_console_request_messages(0);
  138. };
  139. m_inspector_web_view.on_inspector_requested_dom_tree_context_menu = [this](auto node_id, auto position, auto const& type, auto const& tag, auto const& attribute_index) {
  140. Optional<Attribute> attribute;
  141. if (attribute_index.has_value())
  142. attribute = m_dom_node_attributes.get(node_id)->at(*attribute_index);
  143. m_context_menu_data = ContextMenuData { node_id, tag, attribute };
  144. if (type.is_one_of("text"sv, "comment"sv)) {
  145. if (on_requested_dom_node_text_context_menu)
  146. on_requested_dom_node_text_context_menu(position);
  147. } else if (type == "tag"sv) {
  148. VERIFY(tag.has_value());
  149. if (on_requested_dom_node_tag_context_menu)
  150. on_requested_dom_node_tag_context_menu(position, *tag);
  151. } else if (type == "attribute"sv) {
  152. VERIFY(tag.has_value());
  153. VERIFY(attribute.has_value());
  154. if (on_requested_dom_node_attribute_context_menu)
  155. on_requested_dom_node_attribute_context_menu(position, *tag, *attribute);
  156. }
  157. };
  158. m_inspector_web_view.on_inspector_selected_dom_node = [this](auto node_id, auto const& pseudo_element) {
  159. m_content_web_view.inspect_dom_node(node_id, pseudo_element);
  160. };
  161. m_inspector_web_view.on_inspector_set_dom_node_text = [this](auto node_id, auto const& text) {
  162. m_content_web_view.set_dom_node_text(node_id, text);
  163. };
  164. m_inspector_web_view.on_inspector_set_dom_node_tag = [this](auto node_id, auto const& tag) {
  165. m_content_web_view.set_dom_node_tag(node_id, tag);
  166. };
  167. m_inspector_web_view.on_inspector_added_dom_node_attributes = [this](auto node_id, auto const& attributes) {
  168. m_content_web_view.add_dom_node_attributes(node_id, attributes);
  169. };
  170. m_inspector_web_view.on_inspector_replaced_dom_node_attribute = [this](auto node_id, u32 attribute_index, auto const& replacement_attributes) {
  171. auto const& attribute = m_dom_node_attributes.get(node_id)->at(attribute_index);
  172. m_content_web_view.replace_dom_node_attribute(node_id, attribute.name, replacement_attributes);
  173. };
  174. m_inspector_web_view.on_inspector_requested_cookie_context_menu = [this](auto cookie_index, auto position) {
  175. if (cookie_index >= m_cookies.size())
  176. return;
  177. m_cookie_context_menu_index = cookie_index;
  178. if (on_requested_cookie_context_menu)
  179. on_requested_cookie_context_menu(position, m_cookies[cookie_index]);
  180. };
  181. m_inspector_web_view.on_inspector_requested_style_sheet_source = [this](auto const& identifier) {
  182. m_content_web_view.request_style_sheet_source(identifier);
  183. };
  184. m_inspector_web_view.on_inspector_executed_console_script = [this](auto const& script) {
  185. append_console_source(script);
  186. m_content_web_view.js_console_input(script.to_byte_string());
  187. };
  188. m_inspector_web_view.on_inspector_exported_inspector_html = [this](String const& html) {
  189. auto maybe_inspector_path = Application::the().path_for_downloaded_file("inspector"sv);
  190. if (maybe_inspector_path.is_error()) {
  191. append_console_warning(MUST(String::formatted("Unable to select a download location: {}", maybe_inspector_path.error())));
  192. return;
  193. }
  194. auto inspector_path = maybe_inspector_path.release_value();
  195. if (auto result = Core::Directory::create(inspector_path.string(), Core::Directory::CreateDirectories::Yes); result.is_error()) {
  196. append_console_warning(MUST(String::formatted("Unable to create {}: {}", inspector_path, result.error())));
  197. return;
  198. }
  199. auto export_file = [&](auto name, auto const& contents) {
  200. auto path = inspector_path.append(name);
  201. auto file = Core::File::open(path.string(), Core::File::OpenMode::Write);
  202. if (file.is_error()) {
  203. append_console_warning(MUST(String::formatted("Unable to open {}: {}", path, file.error())));
  204. return false;
  205. }
  206. if (auto result = file.value()->write_until_depleted(contents); result.is_error()) {
  207. append_console_warning(MUST(String::formatted("Unable to save {}: {}", path, result.error())));
  208. return false;
  209. }
  210. return true;
  211. };
  212. auto inspector_css = MUST(Core::Resource::load_from_uri(INSPECTOR_CSS));
  213. auto inspector_js = MUST(Core::Resource::load_from_uri(INSPECTOR_JS));
  214. auto inspector_html = MUST(html.replace(INSPECTOR_CSS, "inspector.css"sv, ReplaceMode::All));
  215. inspector_html = MUST(inspector_html.replace(INSPECTOR_JS, "inspector.js"sv, ReplaceMode::All));
  216. if (!export_file("inspector.html"sv, inspector_html))
  217. return;
  218. if (!export_file("inspector.css"sv, inspector_css->data()))
  219. return;
  220. if (!export_file("inspector.js"sv, inspector_js->data()))
  221. return;
  222. append_console_message(MUST(String::formatted("Exported Inspector files to {}", inspector_path)));
  223. };
  224. load_inspector();
  225. }
  226. InspectorClient::~InspectorClient()
  227. {
  228. m_content_web_view.on_finshed_editing_dom_node = nullptr;
  229. m_content_web_view.on_received_accessibility_tree = nullptr;
  230. m_content_web_view.on_received_console_message = nullptr;
  231. m_content_web_view.on_received_console_messages = nullptr;
  232. m_content_web_view.on_received_dom_node_html = nullptr;
  233. m_content_web_view.on_received_dom_node_properties = nullptr;
  234. m_content_web_view.on_received_dom_tree = nullptr;
  235. m_content_web_view.on_received_hovered_node_id = nullptr;
  236. m_content_web_view.on_received_style_sheet_list = nullptr;
  237. m_content_web_view.on_inspector_requested_style_sheet_source = nullptr;
  238. }
  239. void InspectorClient::inspect()
  240. {
  241. if (!m_inspector_loaded)
  242. return;
  243. m_content_web_view.inspect_dom_tree();
  244. m_content_web_view.inspect_accessibility_tree();
  245. m_content_web_view.list_style_sheets();
  246. load_cookies();
  247. }
  248. void InspectorClient::reset()
  249. {
  250. static constexpr auto script = "inspector.reset();"sv;
  251. m_inspector_web_view.run_javascript(script);
  252. m_body_node_id.clear();
  253. m_pending_selection.clear();
  254. m_dom_tree_loaded = false;
  255. m_dom_node_attributes.clear();
  256. m_highest_notified_message_index = -1;
  257. m_highest_received_message_index = -1;
  258. m_waiting_for_messages = false;
  259. }
  260. void InspectorClient::select_hovered_node()
  261. {
  262. m_content_web_view.get_hovered_node_id();
  263. }
  264. void InspectorClient::select_default_node()
  265. {
  266. if (m_body_node_id.has_value())
  267. select_node(*m_body_node_id);
  268. }
  269. void InspectorClient::clear_selection()
  270. {
  271. m_content_web_view.clear_inspected_dom_node();
  272. static constexpr auto script = "inspector.clearInspectedDOMNode();"sv;
  273. m_inspector_web_view.run_javascript(script);
  274. }
  275. void InspectorClient::select_node(i32 node_id)
  276. {
  277. if (!m_dom_tree_loaded) {
  278. m_pending_selection = node_id;
  279. return;
  280. }
  281. auto script = MUST(String::formatted("inspector.inspectDOMNodeID({});", node_id));
  282. m_inspector_web_view.run_javascript(script);
  283. }
  284. void InspectorClient::load_cookies()
  285. {
  286. m_cookies = Application::cookie_jar().get_all_cookies(m_content_web_view.url());
  287. JsonArray json_cookies;
  288. for (auto const& [index, cookie] : enumerate(m_cookies)) {
  289. JsonObject json_cookie;
  290. json_cookie.set("index"sv, JsonValue { index });
  291. json_cookie.set("name"sv, JsonValue { cookie.name });
  292. json_cookie.set("value"sv, JsonValue { cookie.value });
  293. json_cookie.set("domain"sv, JsonValue { cookie.domain });
  294. json_cookie.set("path"sv, JsonValue { cookie.path });
  295. json_cookie.set("creationTime"sv, JsonValue { cookie.creation_time.milliseconds_since_epoch() });
  296. json_cookie.set("lastAccessTime"sv, JsonValue { cookie.last_access_time.milliseconds_since_epoch() });
  297. json_cookie.set("expiryTime"sv, JsonValue { cookie.expiry_time.milliseconds_since_epoch() });
  298. MUST(json_cookies.append(move(json_cookie)));
  299. }
  300. StringBuilder builder;
  301. builder.append("inspector.setCookies("sv);
  302. json_cookies.serialize(builder);
  303. builder.append(");"sv);
  304. m_inspector_web_view.run_javascript(builder.string_view());
  305. }
  306. void InspectorClient::context_menu_edit_dom_node()
  307. {
  308. VERIFY(m_context_menu_data.has_value());
  309. auto script = MUST(String::formatted("inspector.editDOMNodeID({});", m_context_menu_data->dom_node_id));
  310. m_inspector_web_view.run_javascript(script);
  311. m_context_menu_data.clear();
  312. }
  313. void InspectorClient::context_menu_copy_dom_node()
  314. {
  315. VERIFY(m_context_menu_data.has_value());
  316. m_content_web_view.get_dom_node_html(m_context_menu_data->dom_node_id);
  317. m_context_menu_data.clear();
  318. }
  319. void InspectorClient::context_menu_screenshot_dom_node()
  320. {
  321. VERIFY(m_context_menu_data.has_value());
  322. m_content_web_view.take_dom_node_screenshot(m_context_menu_data->dom_node_id)
  323. ->when_resolved([this](auto const& path) {
  324. append_console_message(MUST(String::formatted("Screenshot saved to: {}", path)));
  325. })
  326. .when_rejected([this](auto const& error) {
  327. append_console_warning(MUST(String::formatted("Warning: {}", error)));
  328. });
  329. m_context_menu_data.clear();
  330. }
  331. void InspectorClient::context_menu_create_child_element()
  332. {
  333. VERIFY(m_context_menu_data.has_value());
  334. m_content_web_view.create_child_element(m_context_menu_data->dom_node_id);
  335. m_context_menu_data.clear();
  336. }
  337. void InspectorClient::context_menu_create_child_text_node()
  338. {
  339. VERIFY(m_context_menu_data.has_value());
  340. m_content_web_view.create_child_text_node(m_context_menu_data->dom_node_id);
  341. m_context_menu_data.clear();
  342. }
  343. void InspectorClient::context_menu_clone_dom_node()
  344. {
  345. VERIFY(m_context_menu_data.has_value());
  346. m_content_web_view.clone_dom_node(m_context_menu_data->dom_node_id);
  347. m_context_menu_data.clear();
  348. }
  349. void InspectorClient::context_menu_remove_dom_node()
  350. {
  351. VERIFY(m_context_menu_data.has_value());
  352. m_content_web_view.remove_dom_node(m_context_menu_data->dom_node_id);
  353. m_context_menu_data.clear();
  354. }
  355. void InspectorClient::context_menu_add_dom_node_attribute()
  356. {
  357. VERIFY(m_context_menu_data.has_value());
  358. auto script = MUST(String::formatted("inspector.addAttributeToDOMNodeID({});", m_context_menu_data->dom_node_id));
  359. m_inspector_web_view.run_javascript(script);
  360. m_context_menu_data.clear();
  361. }
  362. void InspectorClient::context_menu_remove_dom_node_attribute()
  363. {
  364. VERIFY(m_context_menu_data.has_value());
  365. VERIFY(m_context_menu_data->attribute.has_value());
  366. m_content_web_view.replace_dom_node_attribute(m_context_menu_data->dom_node_id, m_context_menu_data->attribute->name, {});
  367. m_context_menu_data.clear();
  368. }
  369. void InspectorClient::context_menu_copy_dom_node_attribute_value()
  370. {
  371. VERIFY(m_context_menu_data.has_value());
  372. VERIFY(m_context_menu_data->attribute.has_value());
  373. if (m_content_web_view.on_insert_clipboard_entry)
  374. m_content_web_view.on_insert_clipboard_entry(m_context_menu_data->attribute->value, "unspecified"_string, "text/plain"_string);
  375. m_context_menu_data.clear();
  376. }
  377. void InspectorClient::context_menu_delete_cookie()
  378. {
  379. VERIFY(m_cookie_context_menu_index.has_value());
  380. VERIFY(*m_cookie_context_menu_index < m_cookies.size());
  381. auto& cookie = m_cookies[*m_cookie_context_menu_index];
  382. cookie.expiry_time = UnixDateTime::earliest();
  383. Application::cookie_jar().update_cookie(move(cookie));
  384. load_cookies();
  385. m_cookie_context_menu_index.clear();
  386. }
  387. void InspectorClient::context_menu_delete_all_cookies()
  388. {
  389. for (auto& cookie : m_cookies) {
  390. cookie.expiry_time = UnixDateTime::earliest();
  391. Application::cookie_jar().update_cookie(move(cookie));
  392. }
  393. load_cookies();
  394. m_cookie_context_menu_index.clear();
  395. }
  396. void InspectorClient::load_inspector()
  397. {
  398. auto inspector_html = MUST(Core::Resource::load_from_uri(INSPECTOR_HTML));
  399. auto generate_property_table = [&](auto name) {
  400. return MUST(String::formatted(R"~~~(
  401. <div id="{0}" class="tab-content">
  402. <table class="property-table">
  403. <thead>
  404. <tr>
  405. <th>Name</th>
  406. <th>Value</th>
  407. </tr>
  408. </thead>
  409. <tbody id="{0}-table">
  410. </tbody>
  411. </table>
  412. </div>
  413. )~~~",
  414. name));
  415. };
  416. StringBuilder builder;
  417. SourceGenerator generator { builder };
  418. generator.set("INSPECTOR_CSS"sv, INSPECTOR_CSS);
  419. generator.set("INSPECTOR_JS"sv, INSPECTOR_JS);
  420. generator.set("INSPECTOR_STYLE"sv, HTML_HIGHLIGHTER_STYLE);
  421. generator.set("COMPUTED_STYLE"sv, generate_property_table("computed-style"sv));
  422. generator.set("RESOVLED_STYLE"sv, generate_property_table("resolved-style"sv));
  423. generator.set("CUSTOM_PROPERTIES"sv, generate_property_table("custom-properties"sv));
  424. generator.append(inspector_html->data());
  425. m_inspector_web_view.load_html(generator.as_string_view());
  426. }
  427. template<typename Generator>
  428. static void generate_tree(StringBuilder& builder, JsonObject const& node, Generator&& generator)
  429. {
  430. if (auto children = node.get_array("children"sv); children.has_value() && !children->is_empty()) {
  431. auto name = node.get_byte_string("name"sv).value_or({});
  432. builder.append("<details>"sv);
  433. builder.append("<summary>"sv);
  434. generator(node);
  435. builder.append("</summary>"sv);
  436. children->for_each([&](auto const& child) {
  437. builder.append("<div>"sv);
  438. generate_tree(builder, child.as_object(), generator);
  439. builder.append("</div>"sv);
  440. });
  441. builder.append("</details>"sv);
  442. } else {
  443. generator(node);
  444. }
  445. }
  446. String InspectorClient::generate_dom_tree(JsonObject const& dom_tree)
  447. {
  448. StringBuilder builder;
  449. generate_tree(builder, dom_tree, [&](JsonObject const& node) {
  450. auto type = node.get_byte_string("type"sv).value_or("unknown"sv);
  451. auto name = node.get_byte_string("name"sv).value_or({});
  452. StringBuilder data_attributes;
  453. auto append_data_attribute = [&](auto name, auto value) {
  454. if (!data_attributes.is_empty())
  455. data_attributes.append(' ');
  456. data_attributes.appendff("data-{}=\"{}\"", name, value);
  457. };
  458. i32 node_id = 0;
  459. if (auto pseudo_element = node.get_integer<i32>("pseudo-element"sv); pseudo_element.has_value()) {
  460. node_id = node.get_integer<i32>("parent-id"sv).value();
  461. append_data_attribute("pseudo-element"sv, *pseudo_element);
  462. } else {
  463. node_id = node.get_integer<i32>("id"sv).value();
  464. }
  465. append_data_attribute("id"sv, node_id);
  466. if (type == "text"sv) {
  467. auto deprecated_text = node.get_byte_string("text"sv).release_value();
  468. deprecated_text = escape_html_entities(deprecated_text);
  469. auto text = MUST(Web::Infra::strip_and_collapse_whitespace(deprecated_text));
  470. builder.appendff("<span data-node-type=\"text\" class=\"hoverable editable\" {}>", data_attributes.string_view());
  471. if (text.is_empty())
  472. builder.appendff("<span class=\"internal\">{}</span>", name);
  473. else
  474. builder.append(text);
  475. builder.append("</span>"sv);
  476. return;
  477. }
  478. if (type == "comment"sv) {
  479. auto comment = node.get_byte_string("data"sv).release_value();
  480. comment = escape_html_entities(comment);
  481. builder.appendff("<span class=\"hoverable comment\" {}>", data_attributes.string_view());
  482. builder.append("<span>&lt;!--</span>"sv);
  483. builder.appendff("<span data-node-type=\"comment\" class=\"editable\">{}</span>", comment);
  484. builder.append("<span>--&gt;</span>"sv);
  485. builder.append("</span>"sv);
  486. return;
  487. }
  488. if (type == "shadow-root"sv) {
  489. auto mode = node.get_byte_string("mode"sv).release_value();
  490. builder.appendff("<span class=\"hoverable internal\" {}>", data_attributes.string_view());
  491. builder.appendff("{} ({})", name, mode);
  492. builder.append("</span>"sv);
  493. return;
  494. }
  495. if (type != "element"sv) {
  496. builder.appendff("<span class=\"hoverable internal\" {}>", data_attributes.string_view());
  497. builder.appendff(name);
  498. builder.append("</span>"sv);
  499. return;
  500. }
  501. if (name.equals_ignoring_ascii_case("BODY"sv))
  502. m_body_node_id = node_id;
  503. auto tag = name.to_lowercase();
  504. builder.appendff("<span class=\"hoverable\" {}>", data_attributes.string_view());
  505. builder.append("<span>&lt;</span>"sv);
  506. builder.appendff("<span data-node-type=\"tag\" data-tag=\"{0}\" class=\"editable tag\">{0}</span>", tag);
  507. if (auto attributes = node.get_object("attributes"sv); attributes.has_value()) {
  508. attributes->for_each_member([&](auto const& name, auto const& value) {
  509. auto& dom_node_attributes = m_dom_node_attributes.ensure(node_id);
  510. auto value_string = value.as_string();
  511. builder.append("&nbsp;"sv);
  512. builder.appendff("<span data-node-type=\"attribute\" data-tag=\"{}\" data-attribute-index={} class=\"editable\">", tag, dom_node_attributes.size());
  513. builder.appendff("<span class=\"attribute-name\">{}</span>", escape_html_entities(name));
  514. builder.append('=');
  515. builder.appendff("<span class=\"attribute-value\">\"{}\"</span>", escape_html_entities(value_string));
  516. builder.append("</span>"sv);
  517. dom_node_attributes.empend(MUST(String::from_byte_string(name)), MUST(String::from_byte_string(value_string)));
  518. });
  519. }
  520. builder.append("<span>&gt;</span>"sv);
  521. builder.append("</span>"sv);
  522. });
  523. return MUST(builder.to_string());
  524. }
  525. String InspectorClient::generate_accessibility_tree(JsonObject const& accessibility_tree)
  526. {
  527. StringBuilder builder;
  528. generate_tree(builder, accessibility_tree, [&](JsonObject const& node) {
  529. auto type = node.get_byte_string("type"sv).value_or("unknown"sv);
  530. auto role = node.get_byte_string("role"sv).value_or({});
  531. if (type == "text"sv) {
  532. auto text = node.get_byte_string("text"sv).release_value();
  533. text = escape_html_entities(text);
  534. builder.appendff("<span class=\"hoverable\">");
  535. builder.append(MUST(Web::Infra::strip_and_collapse_whitespace(text)));
  536. builder.append("</span>"sv);
  537. return;
  538. }
  539. if (type != "element"sv) {
  540. builder.appendff("<span class=\"hoverable internal\">");
  541. builder.appendff(role.to_lowercase());
  542. builder.append("</span>"sv);
  543. return;
  544. }
  545. auto name = node.get_byte_string("name"sv).value_or({});
  546. auto description = node.get_byte_string("description"sv).value_or({});
  547. builder.appendff("<span class=\"hoverable\">");
  548. builder.append(role.to_lowercase());
  549. builder.appendff(" name: \"{}\", description: \"{}\"", name, description);
  550. builder.append("</span>"sv);
  551. });
  552. return MUST(builder.to_string());
  553. }
  554. void InspectorClient::request_console_messages()
  555. {
  556. VERIFY(!m_waiting_for_messages);
  557. m_content_web_view.js_console_request_messages(m_highest_received_message_index + 1);
  558. m_waiting_for_messages = true;
  559. }
  560. void InspectorClient::handle_console_message(i32 message_index)
  561. {
  562. if (message_index <= m_highest_received_message_index) {
  563. dbgln("Notified about console message we already have");
  564. return;
  565. }
  566. if (message_index <= m_highest_notified_message_index) {
  567. dbgln("Notified about console message we're already aware of");
  568. return;
  569. }
  570. m_highest_notified_message_index = message_index;
  571. if (!m_waiting_for_messages)
  572. request_console_messages();
  573. }
  574. void InspectorClient::handle_console_messages(i32 start_index, ReadonlySpan<ByteString> message_types, ReadonlySpan<ByteString> messages)
  575. {
  576. auto end_index = start_index + static_cast<i32>(message_types.size()) - 1;
  577. if (end_index <= m_highest_received_message_index) {
  578. dbgln("Received old console messages");
  579. return;
  580. }
  581. for (size_t i = 0; i < message_types.size(); ++i) {
  582. auto const& type = message_types[i];
  583. auto const& message = messages[i];
  584. if (type == "html"sv)
  585. append_console_output(message);
  586. else if (type == "clear"sv)
  587. clear_console_output();
  588. else if (type == "group"sv)
  589. begin_console_group(message, true);
  590. else if (type == "groupCollapsed"sv)
  591. begin_console_group(message, false);
  592. else if (type == "groupEnd"sv)
  593. end_console_group();
  594. else
  595. VERIFY_NOT_REACHED();
  596. }
  597. m_highest_received_message_index = end_index;
  598. m_waiting_for_messages = false;
  599. if (m_highest_received_message_index < m_highest_notified_message_index)
  600. request_console_messages();
  601. }
  602. void InspectorClient::append_console_source(StringView source)
  603. {
  604. StringBuilder builder;
  605. builder.append("<span class=\"console-prompt\">&gt;&nbsp;</span>"sv);
  606. builder.append(MUST(JS::MarkupGenerator::html_from_source(source)));
  607. append_console_output(builder.string_view());
  608. }
  609. void InspectorClient::append_console_message(StringView message)
  610. {
  611. StringBuilder builder;
  612. builder.append("<span class=\"console-prompt\">#&nbsp;</span>"sv);
  613. builder.appendff("<span class=\"console-message\">{}</span>", message);
  614. append_console_output(builder.string_view());
  615. }
  616. void InspectorClient::append_console_warning(StringView warning)
  617. {
  618. StringBuilder builder;
  619. builder.append("<span class=\"console-prompt\">#&nbsp;</span>"sv);
  620. builder.appendff("<span class=\"console-warning\">{}</span>", warning);
  621. append_console_output(builder.string_view());
  622. }
  623. void InspectorClient::append_console_output(StringView html)
  624. {
  625. auto html_base64 = MUST(encode_base64(html.bytes()));
  626. auto script = MUST(String::formatted("inspector.appendConsoleOutput(\"{}\");", html_base64));
  627. m_inspector_web_view.run_javascript(script);
  628. }
  629. void InspectorClient::clear_console_output()
  630. {
  631. static constexpr auto script = "inspector.clearConsoleOutput();"sv;
  632. m_inspector_web_view.run_javascript(script);
  633. }
  634. void InspectorClient::begin_console_group(StringView label, bool start_expanded)
  635. {
  636. auto label_base64 = MUST(encode_base64(label.bytes()));
  637. auto script = MUST(String::formatted("inspector.beginConsoleGroup(\"{}\", {});", label_base64, start_expanded));
  638. m_inspector_web_view.run_javascript(script);
  639. }
  640. void InspectorClient::end_console_group()
  641. {
  642. static constexpr auto script = "inspector.endConsoleGroup();"sv;
  643. m_inspector_web_view.run_javascript(script);
  644. }
  645. }