WebContentView.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  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 "ConsoleWidget.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 <Browser/CookieJar.h>
  20. #include <Kernel/API/KeyCode.h>
  21. #include <LibCore/ArgsParser.h>
  22. #include <LibCore/EventLoop.h>
  23. #include <LibCore/File.h>
  24. #include <LibCore/IODevice.h>
  25. #include <LibCore/MemoryStream.h>
  26. #include <LibCore/Stream.h>
  27. #include <LibCore/System.h>
  28. #include <LibCore/Timer.h>
  29. #include <LibGfx/Bitmap.h>
  30. #include <LibGfx/Font/FontDatabase.h>
  31. #include <LibGfx/PNGWriter.h>
  32. #include <LibGfx/Painter.h>
  33. #include <LibGfx/Rect.h>
  34. #include <LibJS/Runtime/ConsoleObject.h>
  35. #include <LibMain/Main.h>
  36. #include <LibWeb/Loader/ContentFilter.h>
  37. #include <LibWebView/DOMTreeModel.h>
  38. #include <LibWebView/WebContentClient.h>
  39. #include <QApplication>
  40. #include <QCursor>
  41. #include <QIcon>
  42. #include <QInputDialog>
  43. #include <QLineEdit>
  44. #include <QMessageBox>
  45. #include <QMouseEvent>
  46. #include <QPaintEvent>
  47. #include <QPainter>
  48. #include <QScrollBar>
  49. #include <QSocketNotifier>
  50. #include <QTextEdit>
  51. #include <QTimer>
  52. #include <QToolTip>
  53. #include <QTreeView>
  54. #include <QVBoxLayout>
  55. WebContentView::WebContentView(int webdriver_fd_passing_socket)
  56. : m_webdriver_fd_passing_socket(webdriver_fd_passing_socket)
  57. {
  58. setMouseTracking(true);
  59. setFocusPolicy(Qt::FocusPolicy::StrongFocus);
  60. m_inverse_pixel_scaling_ratio = 1.0 / devicePixelRatio();
  61. verticalScrollBar()->setSingleStep(24);
  62. horizontalScrollBar()->setSingleStep(24);
  63. QObject::connect(verticalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  64. update_viewport_rect();
  65. });
  66. QObject::connect(horizontalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  67. update_viewport_rect();
  68. });
  69. create_client();
  70. }
  71. WebContentView::~WebContentView()
  72. {
  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 (event->button() & Qt::MouseButton::BackButton) {
  287. emit back_mouse_button();
  288. } else if (event->button() & Qt::MouseButton::ForwardButton) {
  289. emit forward_mouse_button();
  290. }
  291. if (button == 0) {
  292. // We could not convert Qt buttons to something that Lagom can
  293. // recognize - don't even bother propagating this to the web engine
  294. // as it will not handle it anyway, and it will (currently) assert
  295. return;
  296. }
  297. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  298. auto buttons = get_buttons_from_qt_event(*event);
  299. client().async_mouse_up(to_content(position), button, buttons, modifiers);
  300. }
  301. void WebContentView::keyPressEvent(QKeyEvent* event)
  302. {
  303. switch (event->key()) {
  304. case Qt::Key_Left:
  305. case Qt::Key_Right:
  306. case Qt::Key_Up:
  307. case Qt::Key_Down:
  308. case Qt::Key_PageUp:
  309. case Qt::Key_PageDown:
  310. QAbstractScrollArea::keyPressEvent(event);
  311. break;
  312. default:
  313. break;
  314. }
  315. if (event->key() == Qt::Key_Backtab) {
  316. // NOTE: Qt transforms Shift+Tab into a "Backtab", so we undo that transformation here.
  317. client().async_key_down(KeyCode::Key_Tab, Mod_Shift, '\t');
  318. return;
  319. }
  320. auto text = event->text();
  321. if (text.isEmpty()) {
  322. return;
  323. }
  324. auto point = event->text()[0].unicode();
  325. auto keycode = get_keycode_from_qt_keyboard_event(*event);
  326. auto modifiers = get_modifiers_from_qt_keyboard_event(*event);
  327. client().async_key_down(keycode, modifiers, point);
  328. }
  329. void WebContentView::keyReleaseEvent(QKeyEvent* event)
  330. {
  331. auto text = event->text();
  332. if (text.isEmpty()) {
  333. return;
  334. }
  335. auto point = event->text()[0].unicode();
  336. auto keycode = get_keycode_from_qt_keyboard_event(*event);
  337. auto modifiers = get_modifiers_from_qt_keyboard_event(*event);
  338. client().async_key_up(keycode, modifiers, point);
  339. }
  340. void WebContentView::focusInEvent(QFocusEvent*)
  341. {
  342. client().async_set_has_focus(true);
  343. }
  344. void WebContentView::focusOutEvent(QFocusEvent*)
  345. {
  346. client().async_set_has_focus(false);
  347. }
  348. Gfx::IntPoint WebContentView::to_content(Gfx::IntPoint viewport_position) const
  349. {
  350. return viewport_position.translated(horizontalScrollBar()->value(), verticalScrollBar()->value());
  351. }
  352. Gfx::IntPoint WebContentView::to_widget(Gfx::IntPoint content_position) const
  353. {
  354. return content_position.translated(-horizontalScrollBar()->value(), -verticalScrollBar()->value());
  355. }
  356. void WebContentView::paintEvent(QPaintEvent*)
  357. {
  358. QPainter painter(viewport());
  359. painter.scale(m_inverse_pixel_scaling_ratio, m_inverse_pixel_scaling_ratio);
  360. if (auto* bitmap = m_client_state.has_usable_bitmap ? m_client_state.front_bitmap.bitmap.ptr() : m_backup_bitmap.ptr()) {
  361. QImage q_image(bitmap->scanline_u8(0), bitmap->width(), bitmap->height(), QImage::Format_RGB32);
  362. painter.drawImage(QPoint(0, 0), q_image);
  363. return;
  364. }
  365. painter.fillRect(rect(), palette().base());
  366. }
  367. void WebContentView::resizeEvent(QResizeEvent* event)
  368. {
  369. QAbstractScrollArea::resizeEvent(event);
  370. handle_resize();
  371. }
  372. void WebContentView::handle_resize()
  373. {
  374. update_viewport_rect();
  375. if (m_client_state.has_usable_bitmap) {
  376. // NOTE: We keep the outgoing front bitmap as a backup so we have something to paint until we get a new one.
  377. m_backup_bitmap = m_client_state.front_bitmap.bitmap;
  378. }
  379. if (m_client_state.front_bitmap.bitmap)
  380. client().async_remove_backing_store(m_client_state.front_bitmap.id);
  381. if (m_client_state.back_bitmap.bitmap)
  382. client().async_remove_backing_store(m_client_state.back_bitmap.id);
  383. m_client_state.front_bitmap = {};
  384. m_client_state.back_bitmap = {};
  385. m_client_state.has_usable_bitmap = false;
  386. auto available_size = m_viewport_rect.size();
  387. if (available_size.is_empty())
  388. return;
  389. if (auto new_bitmap_or_error = Gfx::Bitmap::try_create_shareable(Gfx::BitmapFormat::BGRx8888, available_size); !new_bitmap_or_error.is_error()) {
  390. m_client_state.front_bitmap.bitmap = new_bitmap_or_error.release_value();
  391. m_client_state.front_bitmap.id = m_client_state.next_bitmap_id++;
  392. client().async_add_backing_store(m_client_state.front_bitmap.id, m_client_state.front_bitmap.bitmap->to_shareable_bitmap());
  393. }
  394. if (auto new_bitmap_or_error = Gfx::Bitmap::try_create_shareable(Gfx::BitmapFormat::BGRx8888, available_size); !new_bitmap_or_error.is_error()) {
  395. m_client_state.back_bitmap.bitmap = new_bitmap_or_error.release_value();
  396. m_client_state.back_bitmap.id = m_client_state.next_bitmap_id++;
  397. client().async_add_backing_store(m_client_state.back_bitmap.id, m_client_state.back_bitmap.bitmap->to_shareable_bitmap());
  398. }
  399. request_repaint();
  400. }
  401. void WebContentView::update_viewport_rect()
  402. {
  403. auto scaled_width = int(viewport()->width() / m_inverse_pixel_scaling_ratio);
  404. auto scaled_height = int(viewport()->height() / m_inverse_pixel_scaling_ratio);
  405. Gfx::IntRect rect(horizontalScrollBar()->value(), verticalScrollBar()->value(), scaled_width, scaled_height);
  406. m_viewport_rect = rect;
  407. client().async_set_viewport_rect(rect);
  408. request_repaint();
  409. }
  410. void WebContentView::debug_request(DeprecatedString const& request, DeprecatedString const& argument)
  411. {
  412. client().async_debug_request(request, argument);
  413. }
  414. void WebContentView::run_javascript(DeprecatedString const& js_source)
  415. {
  416. client().async_run_javascript(js_source);
  417. }
  418. void WebContentView::did_output_js_console_message(i32 message_index)
  419. {
  420. if (m_console_widget)
  421. m_console_widget->notify_about_new_console_message(message_index);
  422. }
  423. void WebContentView::did_get_js_console_messages(i32 start_index, Vector<DeprecatedString> message_types, Vector<DeprecatedString> messages)
  424. {
  425. if (m_console_widget)
  426. m_console_widget->handle_console_messages(start_index, message_types, messages);
  427. }
  428. void WebContentView::ensure_js_console_widget()
  429. {
  430. if (!m_console_widget) {
  431. m_console_widget = new Ladybird::ConsoleWidget;
  432. m_console_widget->setWindowTitle("JS Console");
  433. m_console_widget->resize(640, 480);
  434. m_console_widget->on_js_input = [this](auto js_source) {
  435. client().async_js_console_input(js_source);
  436. };
  437. m_console_widget->on_request_messages = [this](i32 start_index) {
  438. client().async_js_console_request_messages(start_index);
  439. };
  440. }
  441. }
  442. void WebContentView::show_js_console()
  443. {
  444. ensure_js_console_widget();
  445. m_console_widget->show();
  446. }
  447. void WebContentView::ensure_inspector_widget()
  448. {
  449. if (m_inspector_widget)
  450. return;
  451. #if 0
  452. m_inspector_widget = new QWidget;
  453. m_inspector_widget->setWindowTitle("Inspector");
  454. auto* layout = new QVBoxLayout;
  455. m_inspector_widget->setLayout(layout);
  456. auto* tree_view = new QTreeView;
  457. layout->addWidget(tree_view);
  458. auto dom_tree = m_page_client->page().top_level_browsing_context().active_document()->dump_dom_tree_as_json();
  459. auto dom_tree_model = ::WebView::DOMTreeModel::create(dom_tree);
  460. auto* model = new Ladybird::ModelTranslator(dom_tree_model);
  461. tree_view->setModel(model);
  462. tree_view->setHeaderHidden(true);
  463. tree_view->expandToDepth(3);
  464. m_inspector_widget->resize(640, 480);
  465. QObject::connect(tree_view->selectionModel(), &QItemSelectionModel::currentChanged, [this](QModelIndex const& index, QModelIndex const&) {
  466. auto const* json = (JsonObject const*)index.internalPointer();
  467. m_page_client->page().top_level_browsing_context().active_document()->set_inspected_node(Web::DOM::Node::from_id(json->get("id"sv).to_i32()));
  468. });
  469. #endif
  470. }
  471. void WebContentView::show_inspector()
  472. {
  473. ensure_inspector_widget();
  474. m_inspector_widget->show();
  475. }
  476. void WebContentView::set_color_scheme(ColorScheme color_scheme)
  477. {
  478. switch (color_scheme) {
  479. case ColorScheme::Auto:
  480. client().async_set_preferred_color_scheme(Web::CSS::PreferredColorScheme::Auto);
  481. break;
  482. case ColorScheme::Light:
  483. client().async_set_preferred_color_scheme(Web::CSS::PreferredColorScheme::Light);
  484. break;
  485. case ColorScheme::Dark:
  486. client().async_set_preferred_color_scheme(Web::CSS::PreferredColorScheme::Dark);
  487. break;
  488. }
  489. }
  490. void WebContentView::showEvent(QShowEvent* event)
  491. {
  492. QAbstractScrollArea::showEvent(event);
  493. client().async_set_system_visibility_state(true);
  494. }
  495. void WebContentView::hideEvent(QHideEvent* event)
  496. {
  497. QAbstractScrollArea::hideEvent(event);
  498. client().async_set_system_visibility_state(false);
  499. }
  500. WebContentClient& WebContentView::client()
  501. {
  502. VERIFY(m_client_state.client);
  503. return *m_client_state.client;
  504. }
  505. void WebContentView::create_client()
  506. {
  507. m_client_state = {};
  508. int socket_fds[2] {};
  509. MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fds));
  510. int ui_fd = socket_fds[0];
  511. int wc_fd = socket_fds[1];
  512. int fd_passing_socket_fds[2] {};
  513. MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fd_passing_socket_fds));
  514. int ui_fd_passing_fd = fd_passing_socket_fds[0];
  515. int wc_fd_passing_fd = fd_passing_socket_fds[1];
  516. auto child_pid = fork();
  517. if (!child_pid) {
  518. MUST(Core::System::close(ui_fd_passing_fd));
  519. MUST(Core::System::close(ui_fd));
  520. DeprecatedString takeover_string;
  521. if (auto* socket_takeover = getenv("SOCKET_TAKEOVER"))
  522. takeover_string = DeprecatedString::formatted("{} WebContent:{}", socket_takeover, wc_fd);
  523. else
  524. takeover_string = DeprecatedString::formatted("WebContent:{}", wc_fd);
  525. MUST(Core::System::setenv("SOCKET_TAKEOVER"sv, takeover_string, true));
  526. auto webcontent_fd_passing_socket_string = DeprecatedString::number(wc_fd_passing_fd);
  527. auto webdriver_fd_passing_socket_string = DeprecatedString::number(m_webdriver_fd_passing_socket);
  528. char const* argv[] = {
  529. "WebContent",
  530. "--webcontent-fd-passing-socket",
  531. webcontent_fd_passing_socket_string.characters(),
  532. "--webdriver-fd-passing-socket",
  533. webdriver_fd_passing_socket_string.characters(),
  534. nullptr,
  535. };
  536. auto rc = execvp("./WebContent/WebContent", const_cast<char**>(argv));
  537. if (rc < 0)
  538. rc = execvp((QCoreApplication::applicationDirPath() + "/WebContent").toStdString().c_str(), const_cast<char**>(argv));
  539. if (rc < 0)
  540. perror("execvp");
  541. VERIFY_NOT_REACHED();
  542. }
  543. MUST(Core::System::close(wc_fd_passing_fd));
  544. MUST(Core::System::close(wc_fd));
  545. auto socket = MUST(Core::Stream::LocalSocket::adopt_fd(ui_fd));
  546. MUST(socket->set_blocking(true));
  547. auto new_client = MUST(adopt_nonnull_ref_or_enomem(new (nothrow) WebView::WebContentClient(std::move(socket), *this)));
  548. new_client->set_fd_passing_socket(MUST(Core::Stream::LocalSocket::adopt_fd(ui_fd_passing_fd)));
  549. auto* notifier = new QSocketNotifier(new_client->socket().fd().value(), QSocketNotifier::Type::Read);
  550. QObject::connect(notifier, &QSocketNotifier::activated, [new_client = new_client.ptr()] {
  551. if (auto notifier = new_client->socket().notifier())
  552. notifier->on_ready_to_read();
  553. });
  554. struct DeferredInvokerQt final : IPC::DeferredInvoker {
  555. virtual ~DeferredInvokerQt() = default;
  556. virtual void schedule(Function<void()> callback) override
  557. {
  558. QTimer::singleShot(0, std::move(callback));
  559. }
  560. };
  561. new_client->set_deferred_invoker(make<DeferredInvokerQt>());
  562. m_client_state.client = new_client;
  563. m_client_state.client->on_web_content_process_crash = [this] {
  564. QTimer::singleShot(0, [this] {
  565. handle_web_content_process_crash();
  566. });
  567. };
  568. client().async_update_system_theme(Gfx::load_system_theme(DeprecatedString::formatted("{}/res/themes/Default.ini", s_serenity_resource_root)));
  569. client().async_update_system_fonts(Gfx::FontDatabase::default_font_query(), Gfx::FontDatabase::fixed_width_font_query(), Gfx::FontDatabase::window_title_font_query());
  570. // FIXME: Get the screen rect.
  571. // client().async_update_screen_rects(GUI::Desktop::the().rects(), GUI::Desktop::the().main_screen_index());
  572. }
  573. void WebContentView::handle_web_content_process_crash()
  574. {
  575. dbgln("WebContent process crashed!");
  576. create_client();
  577. VERIFY(m_client_state.client);
  578. // Don't keep a stale backup bitmap around.
  579. m_backup_bitmap = nullptr;
  580. handle_resize();
  581. StringBuilder builder;
  582. builder.append("<html><head><title>Crashed: "sv);
  583. builder.append(escape_html_entities(m_url.to_deprecated_string()));
  584. builder.append("</title></head><body>"sv);
  585. builder.append("<h1>Web page crashed"sv);
  586. if (!m_url.host().is_empty()) {
  587. builder.appendff(" on {}", escape_html_entities(m_url.host()));
  588. }
  589. builder.append("</h1>"sv);
  590. auto escaped_url = escape_html_entities(m_url.to_deprecated_string());
  591. builder.appendff("The web page <a href=\"{}\">{}</a> has crashed.<br><br>You can reload the page to try again.", escaped_url, escaped_url);
  592. builder.append("</body></html>"sv);
  593. load_html(builder.to_deprecated_string(), m_url);
  594. }
  595. void WebContentView::notify_server_did_paint(Badge<WebContentClient>, i32 bitmap_id)
  596. {
  597. if (m_client_state.back_bitmap.id == bitmap_id) {
  598. m_client_state.has_usable_bitmap = true;
  599. m_client_state.back_bitmap.pending_paints--;
  600. swap(m_client_state.back_bitmap, m_client_state.front_bitmap);
  601. // We don't need the backup bitmap anymore, so drop it.
  602. m_backup_bitmap = nullptr;
  603. viewport()->update();
  604. if (m_client_state.got_repaint_requests_while_painting) {
  605. m_client_state.got_repaint_requests_while_painting = false;
  606. request_repaint();
  607. }
  608. }
  609. }
  610. void WebContentView::notify_server_did_invalidate_content_rect(Badge<WebContentClient>, [[maybe_unused]] Gfx::IntRect const& content_rect)
  611. {
  612. request_repaint();
  613. }
  614. void WebContentView::notify_server_did_change_selection(Badge<WebContentClient>)
  615. {
  616. request_repaint();
  617. }
  618. void WebContentView::notify_server_did_request_cursor_change(Badge<WebContentClient>, Gfx::StandardCursor cursor)
  619. {
  620. switch (cursor) {
  621. case Gfx::StandardCursor::Hand:
  622. setCursor(Qt::PointingHandCursor);
  623. break;
  624. case Gfx::StandardCursor::IBeam:
  625. setCursor(Qt::IBeamCursor);
  626. break;
  627. case Gfx::StandardCursor::Arrow:
  628. default:
  629. setCursor(Qt::ArrowCursor);
  630. break;
  631. }
  632. }
  633. void WebContentView::notify_server_did_layout(Badge<WebContentClient>, Gfx::IntSize content_size)
  634. {
  635. verticalScrollBar()->setMinimum(0);
  636. verticalScrollBar()->setMaximum(content_size.height() - m_viewport_rect.height());
  637. verticalScrollBar()->setPageStep(m_viewport_rect.height());
  638. horizontalScrollBar()->setMinimum(0);
  639. horizontalScrollBar()->setMaximum(content_size.width() - m_viewport_rect.width());
  640. horizontalScrollBar()->setPageStep(m_viewport_rect.width());
  641. }
  642. void WebContentView::notify_server_did_change_title(Badge<WebContentClient>, DeprecatedString const& title)
  643. {
  644. emit title_changed(qstring_from_ak_deprecated_string(title));
  645. }
  646. void WebContentView::notify_server_did_request_scroll(Badge<WebContentClient>, i32 x_delta, i32 y_delta)
  647. {
  648. horizontalScrollBar()->setValue(horizontalScrollBar()->value() + x_delta);
  649. verticalScrollBar()->setValue(verticalScrollBar()->value() + y_delta);
  650. }
  651. void WebContentView::notify_server_did_request_scroll_to(Badge<WebContentClient>, Gfx::IntPoint scroll_position)
  652. {
  653. horizontalScrollBar()->setValue(scroll_position.x());
  654. verticalScrollBar()->setValue(scroll_position.y());
  655. }
  656. void WebContentView::notify_server_did_request_scroll_into_view(Badge<WebContentClient>, Gfx::IntRect const& rect)
  657. {
  658. if (m_viewport_rect.contains(rect))
  659. return;
  660. if (rect.top() < m_viewport_rect.top()) {
  661. verticalScrollBar()->setValue(rect.top());
  662. } else if (rect.top() > m_viewport_rect.top() && rect.bottom() > m_viewport_rect.bottom()) {
  663. verticalScrollBar()->setValue(rect.bottom() - m_viewport_rect.height() + 1);
  664. }
  665. }
  666. void WebContentView::notify_server_did_enter_tooltip_area(Badge<WebContentClient>, Gfx::IntPoint content_position, DeprecatedString const& tooltip)
  667. {
  668. auto widget_position = to_widget(content_position);
  669. QToolTip::showText(
  670. mapToGlobal(QPoint(widget_position.x(), widget_position.y())),
  671. qstring_from_ak_deprecated_string(tooltip),
  672. this);
  673. }
  674. void WebContentView::notify_server_did_leave_tooltip_area(Badge<WebContentClient>)
  675. {
  676. QToolTip::hideText();
  677. }
  678. void WebContentView::notify_server_did_hover_link(Badge<WebContentClient>, AK::URL const& url)
  679. {
  680. emit link_hovered(qstring_from_ak_deprecated_string(url.to_deprecated_string()));
  681. }
  682. void WebContentView::notify_server_did_unhover_link(Badge<WebContentClient>)
  683. {
  684. emit link_unhovered();
  685. }
  686. void WebContentView::notify_server_did_click_link(Badge<WebContentClient>, AK::URL const& url, DeprecatedString const& target, unsigned int modifiers)
  687. {
  688. // FIXME
  689. (void)url;
  690. (void)target;
  691. (void)modifiers;
  692. // if (on_link_click)
  693. // on_link_click(url, target, modifiers);
  694. }
  695. void WebContentView::notify_server_did_middle_click_link(Badge<WebContentClient>, AK::URL const& url, DeprecatedString const& target, unsigned int modifiers)
  696. {
  697. (void)url;
  698. (void)target;
  699. (void)modifiers;
  700. }
  701. void WebContentView::notify_server_did_start_loading(Badge<WebContentClient>, AK::URL const& url, bool is_redirect)
  702. {
  703. m_url = url;
  704. emit load_started(url, is_redirect);
  705. }
  706. void WebContentView::notify_server_did_finish_loading(Badge<WebContentClient>, AK::URL const& url)
  707. {
  708. m_url = url;
  709. }
  710. void WebContentView::notify_server_did_request_navigate_back(Badge<WebContentClient>)
  711. {
  712. emit navigate_back();
  713. }
  714. void WebContentView::notify_server_did_request_navigate_forward(Badge<WebContentClient>)
  715. {
  716. emit navigate_forward();
  717. }
  718. void WebContentView::notify_server_did_request_refresh(Badge<WebContentClient>)
  719. {
  720. emit refresh();
  721. }
  722. void WebContentView::notify_server_did_request_context_menu(Badge<WebContentClient>, Gfx::IntPoint content_position)
  723. {
  724. // FIXME
  725. (void)content_position;
  726. }
  727. void WebContentView::notify_server_did_request_link_context_menu(Badge<WebContentClient>, Gfx::IntPoint content_position, AK::URL const& url, DeprecatedString const&, unsigned)
  728. {
  729. // FIXME
  730. (void)content_position;
  731. (void)url;
  732. }
  733. void WebContentView::notify_server_did_request_image_context_menu(Badge<WebContentClient>, Gfx::IntPoint content_position, AK::URL const& url, DeprecatedString const&, unsigned, Gfx::ShareableBitmap const& bitmap)
  734. {
  735. // FIXME
  736. (void)content_position;
  737. (void)url;
  738. (void)bitmap;
  739. }
  740. void WebContentView::notify_server_did_request_alert(Badge<WebContentClient>, DeprecatedString const& message)
  741. {
  742. m_dialog = new QMessageBox(QMessageBox::Icon::Warning, "Ladybird", qstring_from_ak_deprecated_string(message), QMessageBox::StandardButton::Ok, this);
  743. m_dialog->exec();
  744. client().async_alert_closed();
  745. m_dialog = nullptr;
  746. }
  747. void WebContentView::notify_server_did_request_confirm(Badge<WebContentClient>, DeprecatedString const& message)
  748. {
  749. m_dialog = new QMessageBox(QMessageBox::Icon::Question, "Ladybird", qstring_from_ak_deprecated_string(message), QMessageBox::StandardButton::Ok | QMessageBox::StandardButton::Cancel, this);
  750. auto result = m_dialog->exec();
  751. client().async_confirm_closed(result == QMessageBox::StandardButton::Ok || result == QDialog::Accepted);
  752. m_dialog = nullptr;
  753. }
  754. void WebContentView::notify_server_did_request_prompt(Badge<WebContentClient>, DeprecatedString const& message, DeprecatedString const& default_)
  755. {
  756. m_dialog = new QInputDialog(this);
  757. auto& dialog = static_cast<QInputDialog&>(*m_dialog);
  758. dialog.setWindowTitle("Ladybird");
  759. dialog.setLabelText(qstring_from_ak_deprecated_string(message));
  760. dialog.setTextValue(qstring_from_ak_deprecated_string(default_));
  761. if (dialog.exec() == QDialog::Accepted)
  762. client().async_prompt_closed(ak_deprecated_string_from_qstring(dialog.textValue()));
  763. else
  764. client().async_prompt_closed({});
  765. m_dialog = nullptr;
  766. }
  767. void WebContentView::notify_server_did_request_set_prompt_text(Badge<WebContentClient>, DeprecatedString const& message)
  768. {
  769. if (m_dialog && is<QInputDialog>(*m_dialog))
  770. static_cast<QInputDialog&>(*m_dialog).setTextValue(qstring_from_ak_deprecated_string(message));
  771. }
  772. void WebContentView::notify_server_did_request_accept_dialog(Badge<WebContentClient>)
  773. {
  774. if (m_dialog)
  775. m_dialog->accept();
  776. }
  777. void WebContentView::notify_server_did_request_dismiss_dialog(Badge<WebContentClient>)
  778. {
  779. if (m_dialog)
  780. m_dialog->reject();
  781. }
  782. void WebContentView::get_source()
  783. {
  784. client().async_get_source();
  785. }
  786. void WebContentView::notify_server_did_get_source(AK::URL const& url, DeprecatedString const& source)
  787. {
  788. emit got_source(url, qstring_from_ak_deprecated_string(source));
  789. }
  790. void WebContentView::notify_server_did_get_dom_tree(DeprecatedString const& dom_tree)
  791. {
  792. if (on_get_dom_tree)
  793. on_get_dom_tree(dom_tree);
  794. }
  795. void WebContentView::notify_server_did_get_dom_node_properties(i32 node_id, DeprecatedString const& specified_style, DeprecatedString const& computed_style, DeprecatedString const& custom_properties, DeprecatedString const& node_box_sizing)
  796. {
  797. if (on_get_dom_node_properties)
  798. on_get_dom_node_properties(node_id, specified_style, computed_style, custom_properties, node_box_sizing);
  799. }
  800. void WebContentView::notify_server_did_output_js_console_message(i32 message_index)
  801. {
  802. if (m_console_widget)
  803. m_console_widget->notify_about_new_console_message(message_index);
  804. }
  805. void WebContentView::notify_server_did_get_js_console_messages(i32 start_index, Vector<DeprecatedString> const& message_types, Vector<DeprecatedString> const& messages)
  806. {
  807. if (m_console_widget)
  808. m_console_widget->handle_console_messages(start_index, message_types, messages);
  809. }
  810. void WebContentView::notify_server_did_change_favicon(Gfx::Bitmap const& bitmap)
  811. {
  812. auto qimage = QImage(bitmap.scanline_u8(0), bitmap.width(), bitmap.height(), QImage::Format_ARGB32);
  813. if (qimage.isNull())
  814. return;
  815. auto qpixmap = QPixmap::fromImage(qimage);
  816. if (qpixmap.isNull())
  817. return;
  818. emit favicon_changed(QIcon(qpixmap));
  819. }
  820. Vector<Web::Cookie::Cookie> WebContentView::notify_server_did_request_all_cookies(Badge<WebContentClient>, AK::URL const& url)
  821. {
  822. if (on_get_all_cookies)
  823. return on_get_all_cookies(url);
  824. return {};
  825. }
  826. Optional<Web::Cookie::Cookie> WebContentView::notify_server_did_request_named_cookie(Badge<WebContentClient>, AK::URL const& url, DeprecatedString const& name)
  827. {
  828. if (on_get_named_cookie)
  829. return on_get_named_cookie(url, name);
  830. return {};
  831. }
  832. DeprecatedString WebContentView::notify_server_did_request_cookie(Badge<WebContentClient>, AK::URL const& url, Web::Cookie::Source source)
  833. {
  834. if (on_get_cookie)
  835. return on_get_cookie(url, source);
  836. return {};
  837. }
  838. void WebContentView::notify_server_did_set_cookie(Badge<WebContentClient>, AK::URL const& url, Web::Cookie::ParsedCookie const& cookie, Web::Cookie::Source source)
  839. {
  840. if (on_set_cookie)
  841. on_set_cookie(url, cookie, source);
  842. }
  843. void WebContentView::notify_server_did_update_cookie(Badge<WebContentClient>, AK::URL const& url, Web::Cookie::Cookie const& cookie)
  844. {
  845. if (on_update_cookie)
  846. on_update_cookie(url, cookie);
  847. }
  848. void WebContentView::notify_server_did_update_resource_count(i32 count_waiting)
  849. {
  850. // FIXME
  851. (void)count_waiting;
  852. }
  853. void WebContentView::notify_server_did_request_restore_window()
  854. {
  855. emit restore_window();
  856. }
  857. Gfx::IntPoint WebContentView::notify_server_did_request_reposition_window(Gfx::IntPoint position)
  858. {
  859. return emit reposition_window(position);
  860. }
  861. Gfx::IntSize WebContentView::notify_server_did_request_resize_window(Gfx::IntSize size)
  862. {
  863. return emit resize_window(size);
  864. }
  865. Gfx::IntRect WebContentView::notify_server_did_request_maximize_window()
  866. {
  867. return emit maximize_window();
  868. }
  869. Gfx::IntRect WebContentView::notify_server_did_request_minimize_window()
  870. {
  871. return emit minimize_window();
  872. }
  873. Gfx::IntRect WebContentView::notify_server_did_request_fullscreen_window()
  874. {
  875. return emit fullscreen_window();
  876. }
  877. void WebContentView::notify_server_did_request_file(Badge<WebContentClient>, DeprecatedString const& path, i32 request_id)
  878. {
  879. auto file = Core::File::open(path, Core::OpenMode::ReadOnly);
  880. if (file.is_error())
  881. client().async_handle_file_return(file.error().code(), {}, request_id);
  882. else
  883. client().async_handle_file_return(0, IPC::File(file.value()->leak_fd()), request_id);
  884. }
  885. void WebContentView::request_repaint()
  886. {
  887. // If this widget was instantiated but not yet added to a window,
  888. // it won't have a back bitmap yet, so we can just skip repaint requests.
  889. if (!m_client_state.back_bitmap.bitmap)
  890. return;
  891. // Don't request a repaint until pending paint requests have finished.
  892. if (m_client_state.back_bitmap.pending_paints) {
  893. m_client_state.got_repaint_requests_while_painting = true;
  894. return;
  895. }
  896. m_client_state.back_bitmap.pending_paints++;
  897. client().async_paint(m_client_state.back_bitmap.bitmap->rect().translated(horizontalScrollBar()->value(), verticalScrollBar()->value()), m_client_state.back_bitmap.id);
  898. }
  899. bool WebContentView::event(QEvent* event)
  900. {
  901. // NOTE: We have to implement event() manually as Qt's focus navigation mechanism
  902. // eats all the Tab key presses by default.
  903. if (event->type() == QEvent::KeyPress) {
  904. keyPressEvent(static_cast<QKeyEvent*>(event));
  905. return true;
  906. }
  907. if (event->type() == QEvent::KeyRelease) {
  908. keyReleaseEvent(static_cast<QKeyEvent*>(event));
  909. return true;
  910. }
  911. return QAbstractScrollArea::event(event);
  912. }
  913. void WebContentView::notify_server_did_finish_handling_input_event(bool event_was_accepted)
  914. {
  915. // FIXME: Currently Ladybird handles the keyboard shortcuts before passing the event to web content, so
  916. // we don't need to do anything here. But we'll need to once we start asking web content first.
  917. (void)event_was_accepted;
  918. }