SimpleWebView.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. /*
  2. * Copyright (c) 2022, Dex♪ <dexes.ttp@gmail.com>
  3. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #define AK_DONT_REPLACE_STD
  8. #include "SimpleWebView.h"
  9. #include "ConsoleClient.h"
  10. #include "CookieJar.h"
  11. #include "EventLoopPluginQt.h"
  12. #include "FontPluginQt.h"
  13. #include "ImageCodecPluginLadybird.h"
  14. #include "ModelTranslator.h"
  15. #include "PageClientLadybird.h"
  16. #include "RequestManagerQt.h"
  17. #include "Utilities.h"
  18. #include "WebSocketClientManagerLadybird.h"
  19. #include <AK/Assertions.h>
  20. #include <AK/ByteBuffer.h>
  21. #include <AK/Format.h>
  22. #include <AK/HashTable.h>
  23. #include <AK/LexicalPath.h>
  24. #include <AK/NonnullOwnPtr.h>
  25. #include <AK/StringBuilder.h>
  26. #include <AK/Types.h>
  27. #include <LibCore/ArgsParser.h>
  28. #include <LibCore/EventLoop.h>
  29. #include <LibCore/File.h>
  30. #include <LibCore/IODevice.h>
  31. #include <LibCore/MemoryStream.h>
  32. #include <LibCore/Stream.h>
  33. #include <LibCore/System.h>
  34. #include <LibCore/Timer.h>
  35. #include <LibGfx/Bitmap.h>
  36. #include <LibGfx/Font/FontDatabase.h>
  37. #include <LibGfx/PNGWriter.h>
  38. #include <LibGfx/Rect.h>
  39. #include <LibJS/Runtime/ConsoleObject.h>
  40. #include <LibMain/Main.h>
  41. #include <LibWeb/Bindings/MainThreadVM.h>
  42. #include <LibWeb/Cookie/ParsedCookie.h>
  43. #include <LibWeb/DOM/Document.h>
  44. #include <LibWeb/Dump.h>
  45. #include <LibWeb/HTML/BrowsingContext.h>
  46. #include <LibWeb/HTML/Scripting/ClassicScript.h>
  47. #include <LibWeb/HTML/Storage.h>
  48. #include <LibWeb/HTML/Window.h>
  49. #include <LibWeb/Layout/InitialContainingBlock.h>
  50. #include <LibWeb/Loader/ContentFilter.h>
  51. #include <LibWeb/Loader/ResourceLoader.h>
  52. #include <LibWeb/Page/Page.h>
  53. #include <LibWeb/Painting/PaintableBox.h>
  54. #include <LibWeb/Painting/StackingContext.h>
  55. #include <LibWeb/Platform/EventLoopPlugin.h>
  56. #include <LibWebView/DOMTreeModel.h>
  57. #include <QApplication>
  58. #include <QCursor>
  59. #include <QIcon>
  60. #include <QLineEdit>
  61. #include <QMessageBox>
  62. #include <QMouseEvent>
  63. #include <QPaintEvent>
  64. #include <QPainter>
  65. #include <QScrollBar>
  66. #include <QTextEdit>
  67. #include <QToolTip>
  68. #include <QTreeView>
  69. #include <QVBoxLayout>
  70. String s_serenity_resource_root;
  71. SimpleWebView::SimpleWebView()
  72. {
  73. setMouseTracking(true);
  74. m_page_client = Ladybird::PageClientLadybird::create(*this);
  75. m_page_client->setup_palette(Gfx::load_system_theme(String::formatted("{}/res/themes/Default.ini", s_serenity_resource_root)));
  76. // FIXME: Allow passing these values as arguments
  77. m_page_client->set_viewport_rect({ 0, 0, 800, 600 });
  78. m_inverse_pixel_scaling_ratio = 1.0 / devicePixelRatio();
  79. verticalScrollBar()->setSingleStep(24);
  80. horizontalScrollBar()->setSingleStep(24);
  81. QObject::connect(verticalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  82. update_viewport_rect();
  83. });
  84. QObject::connect(horizontalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  85. update_viewport_rect();
  86. });
  87. }
  88. SimpleWebView::~SimpleWebView()
  89. {
  90. }
  91. void SimpleWebView::reload()
  92. {
  93. auto url = m_page_client->page().top_level_browsing_context().active_document()->url();
  94. m_page_client->load(url);
  95. }
  96. void SimpleWebView::load(String const& url)
  97. {
  98. m_page_client->load(AK::URL(url));
  99. }
  100. unsigned get_button_from_qt_event(QMouseEvent const& event)
  101. {
  102. if (event.button() == Qt::MouseButton::LeftButton)
  103. return 1;
  104. if (event.button() == Qt::MouseButton::RightButton)
  105. return 2;
  106. if (event.button() == Qt::MouseButton::MiddleButton)
  107. return 4;
  108. if (event.button() == Qt::MouseButton::BackButton)
  109. return 8;
  110. if (event.buttons() == Qt::MouseButton::ForwardButton)
  111. return 16;
  112. return 0;
  113. }
  114. unsigned get_buttons_from_qt_event(QMouseEvent const& event)
  115. {
  116. unsigned buttons = 0;
  117. if (event.buttons() & Qt::MouseButton::LeftButton)
  118. buttons |= 1;
  119. if (event.buttons() & Qt::MouseButton::RightButton)
  120. buttons |= 2;
  121. if (event.buttons() & Qt::MouseButton::MiddleButton)
  122. buttons |= 4;
  123. if (event.buttons() & Qt::MouseButton::BackButton)
  124. buttons |= 8;
  125. if (event.buttons() & Qt::MouseButton::ForwardButton)
  126. buttons |= 16;
  127. return buttons;
  128. }
  129. unsigned get_modifiers_from_qt_mouse_event(QMouseEvent const& event)
  130. {
  131. unsigned modifiers = 0;
  132. if (event.modifiers() & Qt::Modifier::ALT)
  133. modifiers |= 1;
  134. if (event.modifiers() & Qt::Modifier::CTRL)
  135. modifiers |= 2;
  136. if (event.modifiers() & Qt::Modifier::SHIFT)
  137. modifiers |= 4;
  138. return modifiers;
  139. }
  140. unsigned get_modifiers_from_qt_keyboard_event(QKeyEvent const& event)
  141. {
  142. auto modifiers = 0;
  143. if (event.modifiers().testFlag(Qt::AltModifier))
  144. modifiers |= KeyModifier::Mod_Alt;
  145. if (event.modifiers().testFlag(Qt::ControlModifier))
  146. modifiers |= KeyModifier::Mod_Ctrl;
  147. if (event.modifiers().testFlag(Qt::MetaModifier))
  148. modifiers |= KeyModifier::Mod_Super;
  149. if (event.modifiers().testFlag(Qt::ShiftModifier))
  150. modifiers |= KeyModifier::Mod_Shift;
  151. if (event.modifiers().testFlag(Qt::AltModifier))
  152. modifiers |= KeyModifier::Mod_AltGr;
  153. return modifiers;
  154. }
  155. KeyCode get_keycode_from_qt_keyboard_event(QKeyEvent const& event)
  156. {
  157. struct Mapping {
  158. constexpr Mapping(Qt::Key q, KeyCode s)
  159. : qt_key(q)
  160. , serenity_key(s)
  161. {
  162. }
  163. Qt::Key qt_key;
  164. KeyCode serenity_key;
  165. };
  166. constexpr Mapping mappings[] = {
  167. { Qt::Key_0, Key_0 },
  168. { Qt::Key_1, Key_1 },
  169. { Qt::Key_2, Key_2 },
  170. { Qt::Key_3, Key_3 },
  171. { Qt::Key_4, Key_4 },
  172. { Qt::Key_5, Key_5 },
  173. { Qt::Key_6, Key_6 },
  174. { Qt::Key_7, Key_7 },
  175. { Qt::Key_8, Key_8 },
  176. { Qt::Key_9, Key_9 },
  177. { Qt::Key_A, Key_A },
  178. { Qt::Key_Alt, Key_Alt },
  179. { Qt::Key_Ampersand, Key_Ampersand },
  180. { Qt::Key_Apostrophe, Key_Apostrophe },
  181. { Qt::Key_AsciiCircum, Key_Circumflex },
  182. { Qt::Key_AsciiTilde, Key_Tilde },
  183. { Qt::Key_Asterisk, Key_Asterisk },
  184. { Qt::Key_At, Key_AtSign },
  185. { Qt::Key_B, Key_B },
  186. { Qt::Key_Backslash, Key_Backslash },
  187. { Qt::Key_Backspace, Key_Backspace },
  188. { Qt::Key_Bar, Key_Pipe },
  189. { Qt::Key_BraceLeft, Key_LeftBrace },
  190. { Qt::Key_BraceRight, Key_RightBrace },
  191. { Qt::Key_BracketLeft, Key_LeftBracket },
  192. { Qt::Key_BracketRight, Key_RightBracket },
  193. { Qt::Key_C, Key_C },
  194. { Qt::Key_CapsLock, Key_CapsLock },
  195. { Qt::Key_Colon, Key_Colon },
  196. { Qt::Key_Comma, Key_Comma },
  197. { Qt::Key_Control, Key_Control },
  198. { Qt::Key_D, Key_D },
  199. { Qt::Key_Delete, Key_Delete },
  200. { Qt::Key_Dollar, Key_Dollar },
  201. { Qt::Key_Down, Key_Down },
  202. { Qt::Key_E, Key_E },
  203. { Qt::Key_End, Key_End },
  204. { Qt::Key_Equal, Key_Equal },
  205. { Qt::Key_Escape, Key_Escape },
  206. { Qt::Key_exclamdown, Key_ExclamationPoint },
  207. { Qt::Key_F, Key_F },
  208. { Qt::Key_F1, Key_F1 },
  209. { Qt::Key_F10, Key_F10 },
  210. { Qt::Key_F11, Key_F11 },
  211. { Qt::Key_F12, Key_F12 },
  212. { Qt::Key_F2, Key_F2 },
  213. { Qt::Key_F3, Key_F3 },
  214. { Qt::Key_F4, Key_F4 },
  215. { Qt::Key_F5, Key_F5 },
  216. { Qt::Key_F6, Key_F6 },
  217. { Qt::Key_F7, Key_F7 },
  218. { Qt::Key_F8, Key_F8 },
  219. { Qt::Key_F9, Key_F9 },
  220. { Qt::Key_G, Key_G },
  221. { Qt::Key_Greater, Key_GreaterThan },
  222. { Qt::Key_H, Key_H },
  223. { Qt::Key_Home, Key_Home },
  224. { Qt::Key_I, Key_I },
  225. { Qt::Key_Insert, Key_Insert },
  226. { Qt::Key_J, Key_J },
  227. { Qt::Key_K, Key_K },
  228. { Qt::Key_L, Key_L },
  229. { Qt::Key_Left, Key_Left },
  230. { Qt::Key_Less, Key_LessThan },
  231. { Qt::Key_M, Key_M },
  232. { Qt::Key_Menu, Key_Menu },
  233. { Qt::Key_Minus, Key_Minus },
  234. { Qt::Key_N, Key_N },
  235. { Qt::Key_NumLock, Key_NumLock },
  236. { Qt::Key_O, Key_O },
  237. { Qt::Key_P, Key_P },
  238. { Qt::Key_PageDown, Key_PageDown },
  239. { Qt::Key_PageUp, Key_PageUp },
  240. { Qt::Key_ParenLeft, Key_LeftParen },
  241. { Qt::Key_ParenRight, Key_RightParen },
  242. { Qt::Key_Percent, Key_Percent },
  243. { Qt::Key_Period, Key_Period },
  244. { Qt::Key_Plus, Key_Plus },
  245. { Qt::Key_Print, Key_PrintScreen },
  246. { Qt::Key_Q, Key_Q },
  247. { Qt::Key_Question, Key_QuestionMark },
  248. { Qt::Key_QuoteDbl, Key_DoubleQuote },
  249. { Qt::Key_R, Key_R },
  250. { Qt::Key_Return, Key_Return },
  251. { Qt::Key_Right, Key_Right },
  252. { Qt::Key_S, Key_S },
  253. { Qt::Key_ScrollLock, Key_ScrollLock },
  254. { Qt::Key_Semicolon, Key_Semicolon },
  255. { Qt::Key_Shift, Key_LeftShift },
  256. { Qt::Key_Slash, Key_Slash },
  257. { Qt::Key_Space, Key_Space },
  258. { Qt::Key_Super_L, Key_Super },
  259. { Qt::Key_SysReq, Key_SysRq },
  260. { Qt::Key_T, Key_T },
  261. { Qt::Key_Tab, Key_Tab },
  262. { Qt::Key_U, Key_U },
  263. { Qt::Key_Underscore, Key_Underscore },
  264. { Qt::Key_Up, Key_Up },
  265. { Qt::Key_V, Key_V },
  266. { Qt::Key_W, Key_W },
  267. { Qt::Key_X, Key_X },
  268. { Qt::Key_Y, Key_Y },
  269. { Qt::Key_Z, Key_Z },
  270. };
  271. for (auto const& mapping : mappings) {
  272. if (event.key() == mapping.qt_key)
  273. return mapping.serenity_key;
  274. }
  275. return Key_Invalid;
  276. }
  277. void SimpleWebView::mouseMoveEvent(QMouseEvent* event)
  278. {
  279. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  280. auto buttons = get_buttons_from_qt_event(*event);
  281. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  282. m_page_client->page().handle_mousemove(to_content(position), buttons, modifiers);
  283. }
  284. void SimpleWebView::mousePressEvent(QMouseEvent* event)
  285. {
  286. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  287. auto button = get_button_from_qt_event(*event);
  288. if (button == 0) {
  289. // We could not convert Qt buttons to something that Lagom can
  290. // recognize - don't even bother propagating this to the web engine
  291. // as it will not handle it anyway, and it will (currently) assert
  292. return;
  293. }
  294. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  295. m_page_client->page().handle_mousedown(to_content(position), button, modifiers);
  296. }
  297. void SimpleWebView::mouseReleaseEvent(QMouseEvent* event)
  298. {
  299. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  300. auto button = get_button_from_qt_event(*event);
  301. if (button == 0) {
  302. // We could not convert Qt buttons to something that Lagom can
  303. // recognize - don't even bother propagating this to the web engine
  304. // as it will not handle it anyway, and it will (currently) assert
  305. return;
  306. }
  307. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  308. m_page_client->page().handle_mouseup(to_content(position), button, modifiers);
  309. }
  310. void SimpleWebView::keyPressEvent(QKeyEvent* event)
  311. {
  312. switch (event->key()) {
  313. case Qt::Key_Left:
  314. case Qt::Key_Right:
  315. case Qt::Key_Up:
  316. case Qt::Key_Down:
  317. case Qt::Key_PageUp:
  318. case Qt::Key_PageDown:
  319. QAbstractScrollArea::keyPressEvent(event);
  320. break;
  321. default:
  322. break;
  323. }
  324. auto text = event->text();
  325. if (text.isEmpty()) {
  326. return;
  327. }
  328. auto point = event->text()[0].unicode();
  329. auto keycode = get_keycode_from_qt_keyboard_event(*event);
  330. auto modifiers = get_modifiers_from_qt_keyboard_event(*event);
  331. m_page_client->page().handle_keydown(keycode, modifiers, point);
  332. }
  333. void SimpleWebView::keyReleaseEvent(QKeyEvent* event)
  334. {
  335. auto text = event->text();
  336. if (text.isEmpty()) {
  337. return;
  338. }
  339. auto point = event->text()[0].unicode();
  340. auto keycode = get_keycode_from_qt_keyboard_event(*event);
  341. auto modifiers = get_modifiers_from_qt_keyboard_event(*event);
  342. m_page_client->page().handle_keyup(keycode, modifiers, point);
  343. }
  344. Gfx::IntPoint SimpleWebView::to_content(Gfx::IntPoint viewport_position) const
  345. {
  346. return viewport_position.translated(horizontalScrollBar()->value(), verticalScrollBar()->value());
  347. }
  348. Gfx::IntPoint SimpleWebView::to_widget(Gfx::IntPoint content_position) const
  349. {
  350. return content_position.translated(-horizontalScrollBar()->value(), -verticalScrollBar()->value());
  351. }
  352. void SimpleWebView::paintEvent(QPaintEvent* event)
  353. {
  354. QPainter painter(viewport());
  355. painter.setClipRect(event->rect());
  356. painter.scale(m_inverse_pixel_scaling_ratio, m_inverse_pixel_scaling_ratio);
  357. auto output_rect = m_page_client->viewport_rect();
  358. output_rect.set_x(horizontalScrollBar()->value());
  359. output_rect.set_y(verticalScrollBar()->value());
  360. auto output_bitmap = MUST(Gfx::Bitmap::try_create(Gfx::BitmapFormat::BGRx8888, output_rect.size()));
  361. m_page_client->paint(output_rect, output_bitmap);
  362. QImage q_image(output_bitmap->scanline_u8(0), output_bitmap->width(), output_bitmap->height(), QImage::Format_RGB32);
  363. painter.drawImage(QPoint(0, 0), q_image);
  364. }
  365. void SimpleWebView::resizeEvent(QResizeEvent* event)
  366. {
  367. QAbstractScrollArea::resizeEvent(event);
  368. update_viewport_rect();
  369. }
  370. void SimpleWebView::update_viewport_rect()
  371. {
  372. auto scaled_width = int(size().width() / m_inverse_pixel_scaling_ratio);
  373. auto scaled_height = int(size().height() / m_inverse_pixel_scaling_ratio);
  374. Gfx::IntRect rect(horizontalScrollBar()->value(), verticalScrollBar()->value(), scaled_width, scaled_height);
  375. m_page_client->set_viewport_rect(rect);
  376. }
  377. static void platform_init()
  378. {
  379. #ifdef AK_OS_ANDROID
  380. extern void android_platform_init();
  381. android_platform_init();
  382. #else
  383. s_serenity_resource_root = [] {
  384. auto const* source_dir = getenv("SERENITY_SOURCE_DIR");
  385. if (source_dir) {
  386. return String::formatted("{}/Base", source_dir);
  387. }
  388. auto* home = getenv("XDG_CONFIG_HOME") ?: getenv("HOME");
  389. VERIFY(home);
  390. auto home_lagom = String::formatted("{}/.lagom", home);
  391. if (Core::File::is_directory(home_lagom))
  392. return home_lagom;
  393. auto app_dir = akstring_from_qstring(QApplication::applicationDirPath());
  394. return LexicalPath(app_dir).parent().append("share"sv).string();
  395. }();
  396. #endif
  397. }
  398. static ErrorOr<void> load_content_filters()
  399. {
  400. auto file = TRY(Core::Stream::File::open(String::formatted("{}/home/anon/.config/BrowserContentFilters.txt", s_serenity_resource_root), Core::Stream::OpenMode::Read));
  401. auto ad_filter_list = TRY(Core::Stream::BufferedFile::create(move(file)));
  402. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  403. while (TRY(ad_filter_list->can_read_line())) {
  404. auto line = TRY(ad_filter_list->read_line(buffer));
  405. if (!line.is_empty())
  406. Web::ContentFilter::the().add_pattern(line);
  407. }
  408. return {};
  409. }
  410. void initialize_web_engine()
  411. {
  412. platform_init();
  413. Web::Platform::EventLoopPlugin::install(*new Ladybird::EventLoopPluginQt);
  414. Web::Platform::ImageCodecPlugin::install(*new Ladybird::ImageCodecPluginLadybird);
  415. Web::ResourceLoader::initialize(RequestManagerQt::create());
  416. Web::WebSockets::WebSocketClientManager::initialize(Ladybird::WebSocketClientManagerLadybird::create());
  417. Web::FrameLoader::set_default_favicon_path(String::formatted("{}/res/icons/16x16/app-browser.png", s_serenity_resource_root));
  418. Web::Platform::FontPlugin::install(*new Ladybird::FontPluginQt);
  419. Web::FrameLoader::set_error_page_url(String::formatted("file://{}/res/html/error.html", s_serenity_resource_root));
  420. auto maybe_content_filter_error = load_content_filters();
  421. if (maybe_content_filter_error.is_error())
  422. dbgln("Failed to load content filters: {}", maybe_content_filter_error.error());
  423. }
  424. void SimpleWebView::debug_request(String const& request, String const& argument)
  425. {
  426. auto& page = m_page_client->page();
  427. if (request == "dump-dom-tree") {
  428. if (auto* doc = page.top_level_browsing_context().active_document())
  429. Web::dump_tree(*doc);
  430. }
  431. if (request == "dump-layout-tree") {
  432. if (auto* doc = page.top_level_browsing_context().active_document()) {
  433. if (auto* icb = doc->layout_node())
  434. Web::dump_tree(*icb);
  435. }
  436. }
  437. if (request == "dump-stacking-context-tree") {
  438. if (auto* doc = page.top_level_browsing_context().active_document()) {
  439. if (auto* icb = doc->layout_node()) {
  440. if (auto* stacking_context = icb->paint_box()->stacking_context())
  441. stacking_context->dump();
  442. }
  443. }
  444. }
  445. if (request == "dump-style-sheets") {
  446. if (auto* doc = page.top_level_browsing_context().active_document()) {
  447. for (auto& sheet : doc->style_sheets().sheets()) {
  448. Web::dump_sheet(sheet);
  449. }
  450. }
  451. }
  452. if (request == "collect-garbage") {
  453. Web::Bindings::main_thread_vm().heap().collect_garbage(JS::Heap::CollectionType::CollectGarbage, true);
  454. }
  455. if (request == "set-line-box-borders") {
  456. bool state = argument == "on";
  457. m_page_client->set_should_show_line_box_borders(state);
  458. page.top_level_browsing_context().set_needs_display(page.top_level_browsing_context().viewport_rect());
  459. }
  460. if (request == "clear-cache") {
  461. Web::ResourceLoader::the().clear_cache();
  462. }
  463. if (request == "spoof-user-agent") {
  464. Web::ResourceLoader::the().set_user_agent(argument);
  465. }
  466. if (request == "same-origin-policy") {
  467. page.set_same_origin_policy_enabled(argument == "on");
  468. }
  469. if (request == "scripting") {
  470. page.set_is_scripting_enabled(argument == "on");
  471. }
  472. if (request == "dump-local-storage") {
  473. if (auto* doc = page.top_level_browsing_context().active_document())
  474. doc->window().local_storage()->dump();
  475. }
  476. if (request == "dump-cookies"sv)
  477. m_page_client->dump_cookies();
  478. }
  479. String SimpleWebView::source() const
  480. {
  481. auto* document = m_page_client->page().top_level_browsing_context().active_document();
  482. if (!document)
  483. return String::empty();
  484. return document->source();
  485. }
  486. void SimpleWebView::run_javascript(String const& js_source) const
  487. {
  488. auto* active_document = const_cast<Web::DOM::Document*>(m_page_client->page().top_level_browsing_context().active_document());
  489. if (!active_document)
  490. return;
  491. // This is partially based on "execute a javascript: URL request" https://html.spec.whatwg.org/multipage/browsing-the-web.html#javascript-protocol
  492. // Let settings be browsingContext's active document's relevant settings object.
  493. auto& settings = active_document->relevant_settings_object();
  494. // Let baseURL be settings's API base URL.
  495. auto base_url = settings.api_base_url();
  496. // Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.
  497. // FIXME: This doesn't pass in "default classic script fetch options"
  498. // FIXME: What should the filename be here?
  499. auto script = Web::HTML::ClassicScript::create("(client connection run_javascript)", js_source, settings, base_url);
  500. // Let evaluationStatus be the result of running the classic script script.
  501. auto evaluation_status = script->run();
  502. if (evaluation_status.is_error())
  503. dbgln("Exception :(");
  504. }
  505. void SimpleWebView::did_output_js_console_message(i32 message_index)
  506. {
  507. m_page_client->m_console_client->send_messages(message_index);
  508. }
  509. void SimpleWebView::did_get_js_console_messages(i32, Vector<String>, Vector<String> messages)
  510. {
  511. ensure_js_console_widget();
  512. for (auto& message : messages) {
  513. m_js_console_output_edit->append(qstring_from_akstring(message).trimmed());
  514. }
  515. }
  516. void SimpleWebView::ensure_js_console_widget()
  517. {
  518. if (!m_js_console_widget) {
  519. m_js_console_widget = new QWidget(this);
  520. m_js_console_widget->setWindowTitle("JS Console");
  521. auto* layout = new QVBoxLayout(m_js_console_widget);
  522. m_js_console_widget->setLayout(layout);
  523. m_js_console_output_edit = new QTextEdit(this);
  524. m_js_console_output_edit->setReadOnly(true);
  525. m_js_console_input_edit = new QLineEdit(this);
  526. layout->addWidget(m_js_console_output_edit);
  527. layout->addWidget(m_js_console_input_edit);
  528. m_js_console_widget->resize(640, 480);
  529. QObject::connect(m_js_console_input_edit, &QLineEdit::returnPressed, [this] {
  530. auto code = m_js_console_input_edit->text().trimmed();
  531. m_js_console_input_edit->clear();
  532. m_js_console_output_edit->append(QString("> %1").arg(code));
  533. m_page_client->initialize_js_console();
  534. m_page_client->m_console_client->handle_input(akstring_from_qstring(code));
  535. });
  536. }
  537. }
  538. void SimpleWebView::show_js_console()
  539. {
  540. ensure_js_console_widget();
  541. m_js_console_widget->show();
  542. m_js_console_input_edit->setFocus();
  543. }
  544. void SimpleWebView::ensure_inspector_widget()
  545. {
  546. if (m_inspector_widget)
  547. return;
  548. m_inspector_widget = new QWidget;
  549. m_inspector_widget->setWindowTitle("Inspector");
  550. auto* layout = new QVBoxLayout;
  551. m_inspector_widget->setLayout(layout);
  552. auto* tree_view = new QTreeView;
  553. layout->addWidget(tree_view);
  554. auto dom_tree = m_page_client->page().top_level_browsing_context().active_document()->dump_dom_tree_as_json();
  555. auto dom_tree_model = ::WebView::DOMTreeModel::create(dom_tree);
  556. auto* model = new Ladybird::ModelTranslator(dom_tree_model);
  557. tree_view->setModel(model);
  558. tree_view->setHeaderHidden(true);
  559. tree_view->expandToDepth(3);
  560. m_inspector_widget->resize(640, 480);
  561. QObject::connect(tree_view->selectionModel(), &QItemSelectionModel::currentChanged, [this](QModelIndex const& index, QModelIndex const&) {
  562. auto const* json = (JsonObject const*)index.internalPointer();
  563. m_page_client->page().top_level_browsing_context().active_document()->set_inspected_node(Web::DOM::Node::from_id(json->get("id"sv).to_i32()));
  564. });
  565. }
  566. void SimpleWebView::show_inspector()
  567. {
  568. ensure_inspector_widget();
  569. m_inspector_widget->show();
  570. }
  571. void SimpleWebView::set_color_scheme(ColorScheme color_scheme)
  572. {
  573. switch (color_scheme) {
  574. case ColorScheme::Auto:
  575. m_page_client->m_preferred_color_scheme = Web::CSS::PreferredColorScheme::Auto;
  576. break;
  577. case ColorScheme::Light:
  578. m_page_client->m_preferred_color_scheme = Web::CSS::PreferredColorScheme::Light;
  579. break;
  580. case ColorScheme::Dark:
  581. m_page_client->m_preferred_color_scheme = Web::CSS::PreferredColorScheme::Dark;
  582. break;
  583. }
  584. if (auto* document = m_page_client->page().top_level_browsing_context().active_document())
  585. document->invalidate_style();
  586. }
  587. void SimpleWebView::showEvent(QShowEvent* event)
  588. {
  589. QAbstractScrollArea::showEvent(event);
  590. m_page_client->page().top_level_browsing_context().set_system_visibility_state(Web::HTML::VisibilityState::Visible);
  591. }
  592. void SimpleWebView::hideEvent(QHideEvent* event)
  593. {
  594. QAbstractScrollArea::hideEvent(event);
  595. m_page_client->page().top_level_browsing_context().set_system_visibility_state(Web::HTML::VisibilityState::Hidden);
  596. }