WebContentView.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #define AK_DONT_REPLACE_STD
  7. #include "WebContentView.h"
  8. #include "CookieJar.h"
  9. #include "ModelTranslator.h"
  10. #include "Utilities.h"
  11. #include <AK/Assertions.h>
  12. #include <AK/ByteBuffer.h>
  13. #include <AK/Format.h>
  14. #include <AK/HashTable.h>
  15. #include <AK/LexicalPath.h>
  16. #include <AK/NonnullOwnPtr.h>
  17. #include <AK/StringBuilder.h>
  18. #include <AK/Types.h>
  19. #include <Kernel/API/KeyCode.h>
  20. #include <LibCore/ArgsParser.h>
  21. #include <LibCore/EventLoop.h>
  22. #include <LibCore/File.h>
  23. #include <LibCore/IODevice.h>
  24. #include <LibCore/MemoryStream.h>
  25. #include <LibCore/Stream.h>
  26. #include <LibCore/System.h>
  27. #include <LibCore/Timer.h>
  28. #include <LibGfx/Bitmap.h>
  29. #include <LibGfx/Font/FontDatabase.h>
  30. #include <LibGfx/PNGWriter.h>
  31. #include <LibGfx/Painter.h>
  32. #include <LibGfx/Rect.h>
  33. #include <LibJS/Runtime/ConsoleObject.h>
  34. #include <LibMain/Main.h>
  35. #include <LibWeb/Loader/ContentFilter.h>
  36. #include <LibWebView/DOMTreeModel.h>
  37. #include <LibWebView/WebContentClient.h>
  38. #include <QApplication>
  39. #include <QCursor>
  40. #include <QIcon>
  41. #include <QLineEdit>
  42. #include <QMessageBox>
  43. #include <QMouseEvent>
  44. #include <QPaintEvent>
  45. #include <QPainter>
  46. #include <QScrollBar>
  47. #include <QSocketNotifier>
  48. #include <QTextEdit>
  49. #include <QTimer>
  50. #include <QToolTip>
  51. #include <QTreeView>
  52. #include <QVBoxLayout>
  53. WebContentView::WebContentView()
  54. {
  55. setMouseTracking(true);
  56. m_inverse_pixel_scaling_ratio = 1.0 / devicePixelRatio();
  57. verticalScrollBar()->setSingleStep(24);
  58. horizontalScrollBar()->setSingleStep(24);
  59. QObject::connect(verticalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  60. update_viewport_rect();
  61. });
  62. QObject::connect(horizontalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  63. update_viewport_rect();
  64. });
  65. create_client();
  66. }
  67. WebContentView::~WebContentView()
  68. {
  69. }
  70. void WebContentView::reload()
  71. {
  72. load(m_url);
  73. }
  74. void WebContentView::load(AK::URL const& url)
  75. {
  76. m_url = url;
  77. client().async_load_url(url);
  78. }
  79. void WebContentView::load_html(StringView html, AK::URL const& url)
  80. {
  81. m_url = url;
  82. client().async_load_html(html, url);
  83. }
  84. unsigned get_button_from_qt_event(QMouseEvent const& event)
  85. {
  86. if (event.button() == Qt::MouseButton::LeftButton)
  87. return 1;
  88. if (event.button() == Qt::MouseButton::RightButton)
  89. return 2;
  90. if (event.button() == Qt::MouseButton::MiddleButton)
  91. return 4;
  92. if (event.button() == Qt::MouseButton::BackButton)
  93. return 8;
  94. if (event.buttons() == Qt::MouseButton::ForwardButton)
  95. return 16;
  96. return 0;
  97. }
  98. unsigned get_buttons_from_qt_event(QMouseEvent const& event)
  99. {
  100. unsigned buttons = 0;
  101. if (event.buttons() & Qt::MouseButton::LeftButton)
  102. buttons |= 1;
  103. if (event.buttons() & Qt::MouseButton::RightButton)
  104. buttons |= 2;
  105. if (event.buttons() & Qt::MouseButton::MiddleButton)
  106. buttons |= 4;
  107. if (event.buttons() & Qt::MouseButton::BackButton)
  108. buttons |= 8;
  109. if (event.buttons() & Qt::MouseButton::ForwardButton)
  110. buttons |= 16;
  111. return buttons;
  112. }
  113. unsigned get_modifiers_from_qt_mouse_event(QMouseEvent const& event)
  114. {
  115. unsigned modifiers = 0;
  116. if (event.modifiers() & Qt::Modifier::ALT)
  117. modifiers |= 1;
  118. if (event.modifiers() & Qt::Modifier::CTRL)
  119. modifiers |= 2;
  120. if (event.modifiers() & Qt::Modifier::SHIFT)
  121. modifiers |= 4;
  122. return modifiers;
  123. }
  124. unsigned get_modifiers_from_qt_keyboard_event(QKeyEvent const& event)
  125. {
  126. auto modifiers = 0;
  127. if (event.modifiers().testFlag(Qt::AltModifier))
  128. modifiers |= KeyModifier::Mod_Alt;
  129. if (event.modifiers().testFlag(Qt::ControlModifier))
  130. modifiers |= KeyModifier::Mod_Ctrl;
  131. if (event.modifiers().testFlag(Qt::MetaModifier))
  132. modifiers |= KeyModifier::Mod_Super;
  133. if (event.modifiers().testFlag(Qt::ShiftModifier))
  134. modifiers |= KeyModifier::Mod_Shift;
  135. if (event.modifiers().testFlag(Qt::AltModifier))
  136. modifiers |= KeyModifier::Mod_AltGr;
  137. return modifiers;
  138. }
  139. KeyCode get_keycode_from_qt_keyboard_event(QKeyEvent const& event)
  140. {
  141. struct Mapping {
  142. constexpr Mapping(Qt::Key q, KeyCode s)
  143. : qt_key(q)
  144. , serenity_key(s)
  145. {
  146. }
  147. Qt::Key qt_key;
  148. KeyCode serenity_key;
  149. };
  150. constexpr Mapping mappings[] = {
  151. { Qt::Key_0, Key_0 },
  152. { Qt::Key_1, Key_1 },
  153. { Qt::Key_2, Key_2 },
  154. { Qt::Key_3, Key_3 },
  155. { Qt::Key_4, Key_4 },
  156. { Qt::Key_5, Key_5 },
  157. { Qt::Key_6, Key_6 },
  158. { Qt::Key_7, Key_7 },
  159. { Qt::Key_8, Key_8 },
  160. { Qt::Key_9, Key_9 },
  161. { Qt::Key_A, Key_A },
  162. { Qt::Key_Alt, Key_Alt },
  163. { Qt::Key_Ampersand, Key_Ampersand },
  164. { Qt::Key_Apostrophe, Key_Apostrophe },
  165. { Qt::Key_AsciiCircum, Key_Circumflex },
  166. { Qt::Key_AsciiTilde, Key_Tilde },
  167. { Qt::Key_Asterisk, Key_Asterisk },
  168. { Qt::Key_At, Key_AtSign },
  169. { Qt::Key_B, Key_B },
  170. { Qt::Key_Backslash, Key_Backslash },
  171. { Qt::Key_Backspace, Key_Backspace },
  172. { Qt::Key_Bar, Key_Pipe },
  173. { Qt::Key_BraceLeft, Key_LeftBrace },
  174. { Qt::Key_BraceRight, Key_RightBrace },
  175. { Qt::Key_BracketLeft, Key_LeftBracket },
  176. { Qt::Key_BracketRight, Key_RightBracket },
  177. { Qt::Key_C, Key_C },
  178. { Qt::Key_CapsLock, Key_CapsLock },
  179. { Qt::Key_Colon, Key_Colon },
  180. { Qt::Key_Comma, Key_Comma },
  181. { Qt::Key_Control, Key_Control },
  182. { Qt::Key_D, Key_D },
  183. { Qt::Key_Delete, Key_Delete },
  184. { Qt::Key_Dollar, Key_Dollar },
  185. { Qt::Key_Down, Key_Down },
  186. { Qt::Key_E, Key_E },
  187. { Qt::Key_End, Key_End },
  188. { Qt::Key_Equal, Key_Equal },
  189. { Qt::Key_Escape, Key_Escape },
  190. { Qt::Key_exclamdown, Key_ExclamationPoint },
  191. { Qt::Key_F, Key_F },
  192. { Qt::Key_F1, Key_F1 },
  193. { Qt::Key_F10, Key_F10 },
  194. { Qt::Key_F11, Key_F11 },
  195. { Qt::Key_F12, Key_F12 },
  196. { Qt::Key_F2, Key_F2 },
  197. { Qt::Key_F3, Key_F3 },
  198. { Qt::Key_F4, Key_F4 },
  199. { Qt::Key_F5, Key_F5 },
  200. { Qt::Key_F6, Key_F6 },
  201. { Qt::Key_F7, Key_F7 },
  202. { Qt::Key_F8, Key_F8 },
  203. { Qt::Key_F9, Key_F9 },
  204. { Qt::Key_G, Key_G },
  205. { Qt::Key_Greater, Key_GreaterThan },
  206. { Qt::Key_H, Key_H },
  207. { Qt::Key_Home, Key_Home },
  208. { Qt::Key_I, Key_I },
  209. { Qt::Key_Insert, Key_Insert },
  210. { Qt::Key_J, Key_J },
  211. { Qt::Key_K, Key_K },
  212. { Qt::Key_L, Key_L },
  213. { Qt::Key_Left, Key_Left },
  214. { Qt::Key_Less, Key_LessThan },
  215. { Qt::Key_M, Key_M },
  216. { Qt::Key_Menu, Key_Menu },
  217. { Qt::Key_Minus, Key_Minus },
  218. { Qt::Key_N, Key_N },
  219. { Qt::Key_NumLock, Key_NumLock },
  220. { Qt::Key_O, Key_O },
  221. { Qt::Key_P, Key_P },
  222. { Qt::Key_PageDown, Key_PageDown },
  223. { Qt::Key_PageUp, Key_PageUp },
  224. { Qt::Key_ParenLeft, Key_LeftParen },
  225. { Qt::Key_ParenRight, Key_RightParen },
  226. { Qt::Key_Percent, Key_Percent },
  227. { Qt::Key_Period, Key_Period },
  228. { Qt::Key_Plus, Key_Plus },
  229. { Qt::Key_Print, Key_PrintScreen },
  230. { Qt::Key_Q, Key_Q },
  231. { Qt::Key_Question, Key_QuestionMark },
  232. { Qt::Key_QuoteDbl, Key_DoubleQuote },
  233. { Qt::Key_R, Key_R },
  234. { Qt::Key_Return, Key_Return },
  235. { Qt::Key_Right, Key_Right },
  236. { Qt::Key_S, Key_S },
  237. { Qt::Key_ScrollLock, Key_ScrollLock },
  238. { Qt::Key_Semicolon, Key_Semicolon },
  239. { Qt::Key_Shift, Key_LeftShift },
  240. { Qt::Key_Slash, Key_Slash },
  241. { Qt::Key_Space, Key_Space },
  242. { Qt::Key_Super_L, Key_Super },
  243. { Qt::Key_SysReq, Key_SysRq },
  244. { Qt::Key_T, Key_T },
  245. { Qt::Key_Tab, Key_Tab },
  246. { Qt::Key_U, Key_U },
  247. { Qt::Key_Underscore, Key_Underscore },
  248. { Qt::Key_Up, Key_Up },
  249. { Qt::Key_V, Key_V },
  250. { Qt::Key_W, Key_W },
  251. { Qt::Key_X, Key_X },
  252. { Qt::Key_Y, Key_Y },
  253. { Qt::Key_Z, Key_Z },
  254. };
  255. for (auto const& mapping : mappings) {
  256. if (event.key() == mapping.qt_key)
  257. return mapping.serenity_key;
  258. }
  259. return Key_Invalid;
  260. }
  261. void WebContentView::mouseMoveEvent(QMouseEvent* event)
  262. {
  263. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  264. auto buttons = get_buttons_from_qt_event(*event);
  265. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  266. client().async_mouse_move(to_content(position), 0, buttons, modifiers);
  267. }
  268. void WebContentView::mousePressEvent(QMouseEvent* event)
  269. {
  270. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  271. auto button = get_button_from_qt_event(*event);
  272. if (button == 0) {
  273. // We could not convert Qt buttons to something that Lagom can
  274. // recognize - don't even bother propagating this to the web engine
  275. // as it will not handle it anyway, and it will (currently) assert
  276. return;
  277. }
  278. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  279. auto buttons = get_buttons_from_qt_event(*event);
  280. client().async_mouse_down(to_content(position), button, buttons, modifiers);
  281. }
  282. void WebContentView::mouseReleaseEvent(QMouseEvent* event)
  283. {
  284. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  285. auto button = get_button_from_qt_event(*event);
  286. if (button == 0) {
  287. // We could not convert Qt buttons to something that Lagom can
  288. // recognize - don't even bother propagating this to the web engine
  289. // as it will not handle it anyway, and it will (currently) assert
  290. return;
  291. }
  292. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  293. auto buttons = get_buttons_from_qt_event(*event);
  294. client().async_mouse_up(to_content(position), button, buttons, modifiers);
  295. }
  296. void WebContentView::keyPressEvent(QKeyEvent* event)
  297. {
  298. switch (event->key()) {
  299. case Qt::Key_Left:
  300. case Qt::Key_Right:
  301. case Qt::Key_Up:
  302. case Qt::Key_Down:
  303. case Qt::Key_PageUp:
  304. case Qt::Key_PageDown:
  305. QAbstractScrollArea::keyPressEvent(event);
  306. break;
  307. default:
  308. break;
  309. }
  310. auto text = event->text();
  311. if (text.isEmpty()) {
  312. return;
  313. }
  314. auto point = event->text()[0].unicode();
  315. auto keycode = get_keycode_from_qt_keyboard_event(*event);
  316. auto modifiers = get_modifiers_from_qt_keyboard_event(*event);
  317. client().async_key_down(keycode, modifiers, point);
  318. }
  319. void WebContentView::keyReleaseEvent(QKeyEvent* event)
  320. {
  321. auto text = event->text();
  322. if (text.isEmpty()) {
  323. return;
  324. }
  325. auto point = event->text()[0].unicode();
  326. auto keycode = get_keycode_from_qt_keyboard_event(*event);
  327. auto modifiers = get_modifiers_from_qt_keyboard_event(*event);
  328. client().async_key_up(keycode, modifiers, point);
  329. }
  330. Gfx::IntPoint WebContentView::to_content(Gfx::IntPoint viewport_position) const
  331. {
  332. return viewport_position.translated(horizontalScrollBar()->value(), verticalScrollBar()->value());
  333. }
  334. Gfx::IntPoint WebContentView::to_widget(Gfx::IntPoint content_position) const
  335. {
  336. return content_position.translated(-horizontalScrollBar()->value(), -verticalScrollBar()->value());
  337. }
  338. void WebContentView::paintEvent(QPaintEvent*)
  339. {
  340. QPainter painter(viewport());
  341. painter.scale(m_inverse_pixel_scaling_ratio, m_inverse_pixel_scaling_ratio);
  342. if (auto* bitmap = m_client_state.has_usable_bitmap ? m_client_state.front_bitmap.bitmap.ptr() : m_backup_bitmap.ptr()) {
  343. QImage q_image(bitmap->scanline_u8(0), bitmap->width(), bitmap->height(), QImage::Format_RGB32);
  344. painter.drawImage(QPoint(0, 0), q_image);
  345. return;
  346. }
  347. painter.fillRect(rect(), palette().base());
  348. }
  349. void WebContentView::resizeEvent(QResizeEvent* event)
  350. {
  351. QAbstractScrollArea::resizeEvent(event);
  352. handle_resize();
  353. }
  354. void WebContentView::handle_resize()
  355. {
  356. update_viewport_rect();
  357. if (m_client_state.has_usable_bitmap) {
  358. // NOTE: We keep the outgoing front bitmap as a backup so we have something to paint until we get a new one.
  359. m_backup_bitmap = m_client_state.front_bitmap.bitmap;
  360. }
  361. if (m_client_state.front_bitmap.bitmap)
  362. client().async_remove_backing_store(m_client_state.front_bitmap.id);
  363. if (m_client_state.back_bitmap.bitmap)
  364. client().async_remove_backing_store(m_client_state.back_bitmap.id);
  365. m_client_state.front_bitmap = {};
  366. m_client_state.back_bitmap = {};
  367. m_client_state.has_usable_bitmap = false;
  368. auto available_size = m_viewport_rect.size();
  369. if (available_size.is_empty())
  370. return;
  371. if (auto new_bitmap_or_error = Gfx::Bitmap::try_create_shareable(Gfx::BitmapFormat::BGRx8888, available_size); !new_bitmap_or_error.is_error()) {
  372. m_client_state.front_bitmap.bitmap = new_bitmap_or_error.release_value();
  373. m_client_state.front_bitmap.id = m_client_state.next_bitmap_id++;
  374. client().async_add_backing_store(m_client_state.front_bitmap.id, m_client_state.front_bitmap.bitmap->to_shareable_bitmap());
  375. }
  376. if (auto new_bitmap_or_error = Gfx::Bitmap::try_create_shareable(Gfx::BitmapFormat::BGRx8888, available_size); !new_bitmap_or_error.is_error()) {
  377. m_client_state.back_bitmap.bitmap = new_bitmap_or_error.release_value();
  378. m_client_state.back_bitmap.id = m_client_state.next_bitmap_id++;
  379. client().async_add_backing_store(m_client_state.back_bitmap.id, m_client_state.back_bitmap.bitmap->to_shareable_bitmap());
  380. }
  381. request_repaint();
  382. }
  383. void WebContentView::update_viewport_rect()
  384. {
  385. auto scaled_width = int(viewport()->width() / m_inverse_pixel_scaling_ratio);
  386. auto scaled_height = int(viewport()->height() / m_inverse_pixel_scaling_ratio);
  387. Gfx::IntRect rect(horizontalScrollBar()->value(), verticalScrollBar()->value(), scaled_width, scaled_height);
  388. m_viewport_rect = rect;
  389. client().async_set_viewport_rect(rect);
  390. request_repaint();
  391. }
  392. void WebContentView::debug_request(String const& request, String const& argument)
  393. {
  394. client().async_debug_request(request, argument);
  395. }
  396. void WebContentView::run_javascript(String const& js_source)
  397. {
  398. client().async_run_javascript(js_source);
  399. }
  400. void WebContentView::did_output_js_console_message(i32 message_index)
  401. {
  402. // FIXME
  403. (void)message_index;
  404. }
  405. void WebContentView::did_get_js_console_messages(i32, Vector<String>, Vector<String> messages)
  406. {
  407. ensure_js_console_widget();
  408. for (auto& message : messages) {
  409. m_js_console_output_edit->append(qstring_from_akstring(message).trimmed());
  410. }
  411. }
  412. void WebContentView::ensure_js_console_widget()
  413. {
  414. if (!m_js_console_widget) {
  415. m_js_console_widget = new QWidget;
  416. m_js_console_widget->setWindowTitle("JS Console");
  417. auto* layout = new QVBoxLayout(m_js_console_widget);
  418. m_js_console_widget->setLayout(layout);
  419. m_js_console_output_edit = new QTextEdit(this);
  420. m_js_console_output_edit->setReadOnly(true);
  421. m_js_console_input_edit = new QLineEdit(this);
  422. layout->addWidget(m_js_console_output_edit);
  423. layout->addWidget(m_js_console_input_edit);
  424. m_js_console_widget->resize(640, 480);
  425. QObject::connect(m_js_console_input_edit, &QLineEdit::returnPressed, [this] {
  426. auto code = m_js_console_input_edit->text().trimmed();
  427. client().async_js_console_input(akstring_from_qstring(code));
  428. m_js_console_input_edit->clear();
  429. m_js_console_output_edit->append(QString("> %1").arg(code));
  430. });
  431. }
  432. }
  433. void WebContentView::show_js_console()
  434. {
  435. ensure_js_console_widget();
  436. m_js_console_widget->show();
  437. m_js_console_input_edit->setFocus();
  438. }
  439. void WebContentView::ensure_inspector_widget()
  440. {
  441. if (m_inspector_widget)
  442. return;
  443. #if 0
  444. m_inspector_widget = new QWidget;
  445. m_inspector_widget->setWindowTitle("Inspector");
  446. auto* layout = new QVBoxLayout;
  447. m_inspector_widget->setLayout(layout);
  448. auto* tree_view = new QTreeView;
  449. layout->addWidget(tree_view);
  450. auto dom_tree = m_page_client->page().top_level_browsing_context().active_document()->dump_dom_tree_as_json();
  451. auto dom_tree_model = ::WebView::DOMTreeModel::create(dom_tree);
  452. auto* model = new Ladybird::ModelTranslator(dom_tree_model);
  453. tree_view->setModel(model);
  454. tree_view->setHeaderHidden(true);
  455. tree_view->expandToDepth(3);
  456. m_inspector_widget->resize(640, 480);
  457. QObject::connect(tree_view->selectionModel(), &QItemSelectionModel::currentChanged, [this](QModelIndex const& index, QModelIndex const&) {
  458. auto const* json = (JsonObject const*)index.internalPointer();
  459. m_page_client->page().top_level_browsing_context().active_document()->set_inspected_node(Web::DOM::Node::from_id(json->get("id"sv).to_i32()));
  460. });
  461. #endif
  462. }
  463. void WebContentView::show_inspector()
  464. {
  465. ensure_inspector_widget();
  466. m_inspector_widget->show();
  467. }
  468. void WebContentView::set_color_scheme(ColorScheme color_scheme)
  469. {
  470. switch (color_scheme) {
  471. case ColorScheme::Auto:
  472. client().async_set_preferred_color_scheme(Web::CSS::PreferredColorScheme::Auto);
  473. break;
  474. case ColorScheme::Light:
  475. client().async_set_preferred_color_scheme(Web::CSS::PreferredColorScheme::Light);
  476. break;
  477. case ColorScheme::Dark:
  478. client().async_set_preferred_color_scheme(Web::CSS::PreferredColorScheme::Dark);
  479. break;
  480. }
  481. }
  482. void WebContentView::showEvent(QShowEvent* event)
  483. {
  484. QAbstractScrollArea::showEvent(event);
  485. client().async_set_system_visibility_state(true);
  486. }
  487. void WebContentView::hideEvent(QHideEvent* event)
  488. {
  489. QAbstractScrollArea::hideEvent(event);
  490. client().async_set_system_visibility_state(false);
  491. }
  492. WebContentClient& WebContentView::client()
  493. {
  494. VERIFY(m_client_state.client);
  495. return *m_client_state.client;
  496. }
  497. void WebContentView::create_client()
  498. {
  499. m_client_state = {};
  500. int socket_fds[2] {};
  501. MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fds));
  502. int ui_fd = socket_fds[0];
  503. int wc_fd = socket_fds[1];
  504. int fd_passing_socket_fds[2] {};
  505. MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fd_passing_socket_fds));
  506. int ui_fd_passing_fd = fd_passing_socket_fds[0];
  507. int wc_fd_passing_fd = fd_passing_socket_fds[1];
  508. auto child_pid = fork();
  509. if (!child_pid) {
  510. auto takeover_string = String::formatted("x:{}", wc_fd);
  511. MUST(Core::System::setenv("SOCKET_TAKEOVER"sv, takeover_string, true));
  512. auto fd_passing_socket_string = String::formatted("{}", wc_fd_passing_fd);
  513. MUST(Core::System::setenv("FD_PASSING_SOCKET"sv, fd_passing_socket_string, true));
  514. auto rc = execlp("./WebContent/WebContent", "WebContent", nullptr);
  515. if (rc < 0)
  516. perror("execlp");
  517. VERIFY_NOT_REACHED();
  518. }
  519. auto socket = MUST(Core::Stream::LocalSocket::adopt_fd(ui_fd));
  520. MUST(socket->set_blocking(true));
  521. auto new_client = MUST(adopt_nonnull_ref_or_enomem(new (nothrow) WebView::WebContentClient(std::move(socket), *this)));
  522. new_client->set_fd_passing_socket(MUST(Core::Stream::LocalSocket::adopt_fd(ui_fd_passing_fd)));
  523. auto* notifier = new QSocketNotifier(new_client->socket().fd().value(), QSocketNotifier::Type::Read);
  524. QObject::connect(notifier, &QSocketNotifier::activated, [new_client = new_client.ptr()] {
  525. if (auto notifier = new_client->socket().notifier())
  526. notifier->on_ready_to_read();
  527. });
  528. struct DeferredInvokerQt final : IPC::DeferredInvoker {
  529. virtual ~DeferredInvokerQt() = default;
  530. virtual void schedule(Function<void()> callback) override
  531. {
  532. QTimer::singleShot(0, std::move(callback));
  533. }
  534. };
  535. new_client->set_deferred_invoker(make<DeferredInvokerQt>());
  536. m_client_state.client = new_client;
  537. m_client_state.client->on_web_content_process_crash = [this] {
  538. QTimer::singleShot(0, [this] {
  539. handle_web_content_process_crash();
  540. });
  541. };
  542. client().async_update_system_theme(Gfx::load_system_theme(String::formatted("{}/res/themes/Default.ini", s_serenity_resource_root)));
  543. client().async_update_system_fonts(Gfx::FontDatabase::default_font_query(), Gfx::FontDatabase::fixed_width_font_query(), Gfx::FontDatabase::window_title_font_query());
  544. // FIXME: Get the screen rect.
  545. // client().async_update_screen_rects(GUI::Desktop::the().rects(), GUI::Desktop::the().main_screen_index());
  546. }
  547. void WebContentView::handle_web_content_process_crash()
  548. {
  549. dbgln("WebContent process crashed!");
  550. create_client();
  551. VERIFY(m_client_state.client);
  552. // Don't keep a stale backup bitmap around.
  553. m_backup_bitmap = nullptr;
  554. handle_resize();
  555. StringBuilder builder;
  556. builder.append("<html><head><title>Crashed: "sv);
  557. builder.append(escape_html_entities(m_url.to_string()));
  558. builder.append("</title></head><body>"sv);
  559. builder.append("<h1>Web page crashed"sv);
  560. if (!m_url.host().is_empty()) {
  561. builder.appendff(" on {}", escape_html_entities(m_url.host()));
  562. }
  563. builder.append("</h1>"sv);
  564. auto escaped_url = escape_html_entities(m_url.to_string());
  565. builder.appendff("The web page <a href=\"{}\">{}</a> has crashed.<br><br>You can reload the page to try again.", escaped_url, escaped_url);
  566. builder.append("</body></html>"sv);
  567. load_html(builder.to_string(), m_url);
  568. }
  569. void WebContentView::notify_server_did_paint(Badge<WebContentClient>, i32 bitmap_id)
  570. {
  571. if (m_client_state.back_bitmap.id == bitmap_id) {
  572. m_client_state.has_usable_bitmap = true;
  573. m_client_state.back_bitmap.pending_paints--;
  574. swap(m_client_state.back_bitmap, m_client_state.front_bitmap);
  575. // We don't need the backup bitmap anymore, so drop it.
  576. m_backup_bitmap = nullptr;
  577. viewport()->update();
  578. if (m_client_state.got_repaint_requests_while_painting) {
  579. m_client_state.got_repaint_requests_while_painting = false;
  580. request_repaint();
  581. }
  582. }
  583. }
  584. void WebContentView::notify_server_did_invalidate_content_rect(Badge<WebContentClient>, [[maybe_unused]] Gfx::IntRect const& content_rect)
  585. {
  586. request_repaint();
  587. }
  588. void WebContentView::notify_server_did_change_selection(Badge<WebContentClient>)
  589. {
  590. request_repaint();
  591. }
  592. void WebContentView::notify_server_did_request_cursor_change(Badge<WebContentClient>, Gfx::StandardCursor cursor)
  593. {
  594. switch (cursor) {
  595. case Gfx::StandardCursor::Hand:
  596. setCursor(Qt::PointingHandCursor);
  597. break;
  598. case Gfx::StandardCursor::IBeam:
  599. setCursor(Qt::IBeamCursor);
  600. break;
  601. case Gfx::StandardCursor::Arrow:
  602. default:
  603. setCursor(Qt::ArrowCursor);
  604. break;
  605. }
  606. }
  607. void WebContentView::notify_server_did_layout(Badge<WebContentClient>, Gfx::IntSize const& content_size)
  608. {
  609. verticalScrollBar()->setMinimum(0);
  610. verticalScrollBar()->setMaximum(content_size.height() - m_viewport_rect.height());
  611. verticalScrollBar()->setPageStep(m_viewport_rect.height());
  612. horizontalScrollBar()->setMinimum(0);
  613. horizontalScrollBar()->setMaximum(content_size.width() - m_viewport_rect.width());
  614. horizontalScrollBar()->setPageStep(m_viewport_rect.width());
  615. }
  616. void WebContentView::notify_server_did_change_title(Badge<WebContentClient>, String const& title)
  617. {
  618. emit title_changed(qstring_from_akstring(title));
  619. }
  620. void WebContentView::notify_server_did_request_scroll(Badge<WebContentClient>, i32 x_delta, i32 y_delta)
  621. {
  622. horizontalScrollBar()->setValue(horizontalScrollBar()->value() + x_delta);
  623. verticalScrollBar()->setValue(verticalScrollBar()->value() + y_delta);
  624. }
  625. void WebContentView::notify_server_did_request_scroll_to(Badge<WebContentClient>, Gfx::IntPoint const& scroll_position)
  626. {
  627. horizontalScrollBar()->setValue(scroll_position.x());
  628. verticalScrollBar()->setValue(scroll_position.y());
  629. }
  630. void WebContentView::notify_server_did_request_scroll_into_view(Badge<WebContentClient>, Gfx::IntRect const& rect)
  631. {
  632. if (m_viewport_rect.contains(rect))
  633. return;
  634. if (rect.top() < m_viewport_rect.top()) {
  635. verticalScrollBar()->setValue(rect.top());
  636. } else if (rect.top() > m_viewport_rect.top() && rect.bottom() > m_viewport_rect.bottom()) {
  637. verticalScrollBar()->setValue(rect.bottom() - m_viewport_rect.height() + 1);
  638. }
  639. }
  640. void WebContentView::notify_server_did_enter_tooltip_area(Badge<WebContentClient>, Gfx::IntPoint const& content_position, String const& tooltip)
  641. {
  642. auto widget_position = to_widget(content_position);
  643. QToolTip::showText(
  644. mapToGlobal(QPoint(widget_position.x(), widget_position.y())),
  645. qstring_from_akstring(tooltip),
  646. this);
  647. }
  648. void WebContentView::notify_server_did_leave_tooltip_area(Badge<WebContentClient>)
  649. {
  650. QToolTip::hideText();
  651. }
  652. void WebContentView::notify_server_did_hover_link(Badge<WebContentClient>, AK::URL const& url)
  653. {
  654. emit link_hovered(qstring_from_akstring(url.to_string()));
  655. }
  656. void WebContentView::notify_server_did_unhover_link(Badge<WebContentClient>)
  657. {
  658. emit link_unhovered();
  659. }
  660. void WebContentView::notify_server_did_click_link(Badge<WebContentClient>, AK::URL const& url, String const& target, unsigned int modifiers)
  661. {
  662. // FIXME
  663. (void)url;
  664. (void)target;
  665. (void)modifiers;
  666. // if (on_link_click)
  667. // on_link_click(url, target, modifiers);
  668. }
  669. void WebContentView::notify_server_did_middle_click_link(Badge<WebContentClient>, AK::URL const& url, String const& target, unsigned int modifiers)
  670. {
  671. (void)url;
  672. (void)target;
  673. (void)modifiers;
  674. }
  675. void WebContentView::notify_server_did_start_loading(Badge<WebContentClient>, AK::URL const& url)
  676. {
  677. emit load_started(url);
  678. }
  679. void WebContentView::notify_server_did_finish_loading(Badge<WebContentClient>, AK::URL const& url)
  680. {
  681. // FIXME
  682. (void)url;
  683. }
  684. void WebContentView::notify_server_did_request_context_menu(Badge<WebContentClient>, Gfx::IntPoint const& content_position)
  685. {
  686. // FIXME
  687. (void)content_position;
  688. }
  689. void WebContentView::notify_server_did_request_link_context_menu(Badge<WebContentClient>, Gfx::IntPoint const& content_position, AK::URL const& url, String const&, unsigned)
  690. {
  691. // FIXME
  692. (void)content_position;
  693. (void)url;
  694. }
  695. void WebContentView::notify_server_did_request_image_context_menu(Badge<WebContentClient>, Gfx::IntPoint const& content_position, AK::URL const& url, String const&, unsigned, Gfx::ShareableBitmap const& bitmap)
  696. {
  697. // FIXME
  698. (void)content_position;
  699. (void)url;
  700. (void)bitmap;
  701. }
  702. void WebContentView::notify_server_did_request_alert(Badge<WebContentClient>, String const& message)
  703. {
  704. QMessageBox::warning(this, "Ladybird", qstring_from_akstring(message));
  705. }
  706. bool WebContentView::notify_server_did_request_confirm(Badge<WebContentClient>, String const& message)
  707. {
  708. auto result = QMessageBox::question(this, "Ladybird", qstring_from_akstring(message),
  709. QMessageBox::StandardButton::Ok | QMessageBox::StandardButton::Cancel);
  710. return result == QMessageBox::StandardButton::Ok;
  711. }
  712. String WebContentView::notify_server_did_request_prompt(Badge<WebContentClient>, String const& message, String const& default_)
  713. {
  714. // FIXME
  715. (void)message;
  716. (void)default_;
  717. return String::empty();
  718. }
  719. void WebContentView::get_source()
  720. {
  721. client().async_get_source();
  722. }
  723. void WebContentView::notify_server_did_get_source(AK::URL const& url, String const& source)
  724. {
  725. emit got_source(url, qstring_from_akstring(source));
  726. }
  727. void WebContentView::notify_server_did_get_dom_tree(String const& dom_tree)
  728. {
  729. if (on_get_dom_tree)
  730. on_get_dom_tree(dom_tree);
  731. }
  732. void WebContentView::notify_server_did_get_dom_node_properties(i32 node_id, String const& specified_style, String const& computed_style, String const& custom_properties, String const& node_box_sizing)
  733. {
  734. if (on_get_dom_node_properties)
  735. on_get_dom_node_properties(node_id, specified_style, computed_style, custom_properties, node_box_sizing);
  736. }
  737. void WebContentView::notify_server_did_output_js_console_message(i32 message_index)
  738. {
  739. if (on_js_console_new_message)
  740. on_js_console_new_message(message_index);
  741. }
  742. void WebContentView::notify_server_did_get_js_console_messages(i32 start_index, Vector<String> const& message_types, Vector<String> const& messages)
  743. {
  744. if (on_get_js_console_messages)
  745. on_get_js_console_messages(start_index, message_types, messages);
  746. }
  747. void WebContentView::notify_server_did_change_favicon(Gfx::Bitmap const& bitmap)
  748. {
  749. auto qimage = QImage(bitmap.scanline_u8(0), bitmap.width(), bitmap.height(), QImage::Format_ARGB32);
  750. if (qimage.isNull())
  751. return;
  752. auto qpixmap = QPixmap::fromImage(qimage);
  753. if (qpixmap.isNull())
  754. return;
  755. emit favicon_changed(QIcon(qpixmap));
  756. }
  757. String WebContentView::notify_server_did_request_cookie(Badge<WebContentClient>, AK::URL const& url, Web::Cookie::Source source)
  758. {
  759. if (on_get_cookie)
  760. return on_get_cookie(url, source);
  761. return {};
  762. }
  763. void WebContentView::notify_server_did_set_cookie(Badge<WebContentClient>, AK::URL const& url, Web::Cookie::ParsedCookie const& cookie, Web::Cookie::Source source)
  764. {
  765. if (on_set_cookie)
  766. on_set_cookie(url, cookie, source);
  767. }
  768. void WebContentView::notify_server_did_update_resource_count(i32 count_waiting)
  769. {
  770. // FIXME
  771. (void)count_waiting;
  772. }
  773. void WebContentView::notify_server_did_request_file(Badge<WebContentClient>, String const& path, i32 request_id)
  774. {
  775. auto file = Core::File::open(path, Core::OpenMode::ReadOnly);
  776. if (file.is_error())
  777. client().async_handle_file_return(file.error().code(), {}, request_id);
  778. else
  779. client().async_handle_file_return(0, IPC::File(file.value()->leak_fd()), request_id);
  780. }
  781. void WebContentView::request_repaint()
  782. {
  783. // If this widget was instantiated but not yet added to a window,
  784. // it won't have a back bitmap yet, so we can just skip repaint requests.
  785. if (!m_client_state.back_bitmap.bitmap)
  786. return;
  787. // Don't request a repaint until pending paint requests have finished.
  788. if (m_client_state.back_bitmap.pending_paints) {
  789. m_client_state.got_repaint_requests_while_painting = true;
  790. return;
  791. }
  792. m_client_state.back_bitmap.pending_paints++;
  793. client().async_paint(m_client_state.back_bitmap.bitmap->rect().translated(horizontalScrollBar()->value(), verticalScrollBar()->value()), m_client_state.back_bitmap.id);
  794. }