InspectorClient.cpp 29 KB

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