WebContentView.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. /*
  2. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #define AK_DONT_REPLACE_STD
  8. #include "WebContentView.h"
  9. #include "ConsoleWidget.h"
  10. #include "HelperProcess.h"
  11. #include "InspectorWidget.h"
  12. #include "Utilities.h"
  13. #include <AK/Assertions.h>
  14. #include <AK/ByteBuffer.h>
  15. #include <AK/Format.h>
  16. #include <AK/HashTable.h>
  17. #include <AK/LexicalPath.h>
  18. #include <AK/NonnullOwnPtr.h>
  19. #include <AK/StringBuilder.h>
  20. #include <AK/Types.h>
  21. #include <Browser/CookieJar.h>
  22. #include <Kernel/API/KeyCode.h>
  23. #include <LibCore/ArgsParser.h>
  24. #include <LibCore/EventLoop.h>
  25. #include <LibCore/File.h>
  26. #include <LibCore/IODevice.h>
  27. #include <LibCore/Stream.h>
  28. #include <LibCore/System.h>
  29. #include <LibCore/Timer.h>
  30. #include <LibGfx/Bitmap.h>
  31. #include <LibGfx/Font/FontDatabase.h>
  32. #include <LibGfx/PNGWriter.h>
  33. #include <LibGfx/Painter.h>
  34. #include <LibGfx/Rect.h>
  35. #include <LibGfx/SystemTheme.h>
  36. #include <LibJS/Runtime/ConsoleObject.h>
  37. #include <LibMain/Main.h>
  38. #include <LibWeb/Loader/ContentFilter.h>
  39. #include <LibWebView/WebContentClient.h>
  40. #include <QApplication>
  41. #include <QCursor>
  42. #include <QIcon>
  43. #include <QInputDialog>
  44. #include <QLineEdit>
  45. #include <QMessageBox>
  46. #include <QMimeData>
  47. #include <QMouseEvent>
  48. #include <QPaintEvent>
  49. #include <QPainter>
  50. #include <QScrollBar>
  51. #include <QTextEdit>
  52. #include <QTimer>
  53. #include <QToolTip>
  54. WebContentView::WebContentView(StringView webdriver_content_ipc_path)
  55. : m_webdriver_content_ipc_path(webdriver_content_ipc_path)
  56. {
  57. setMouseTracking(true);
  58. setAcceptDrops(true);
  59. setFocusPolicy(Qt::FocusPolicy::StrongFocus);
  60. m_device_pixel_ratio = devicePixelRatio();
  61. m_inverse_pixel_scaling_ratio = 1.0 / m_device_pixel_ratio;
  62. verticalScrollBar()->setSingleStep(24);
  63. horizontalScrollBar()->setSingleStep(24);
  64. QObject::connect(verticalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  65. update_viewport_rect();
  66. });
  67. QObject::connect(horizontalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  68. update_viewport_rect();
  69. });
  70. create_client();
  71. }
  72. WebContentView::~WebContentView()
  73. {
  74. close_sub_widgets();
  75. }
  76. unsigned get_button_from_qt_event(QMouseEvent const& event)
  77. {
  78. if (event.button() == Qt::MouseButton::LeftButton)
  79. return 1;
  80. if (event.button() == Qt::MouseButton::RightButton)
  81. return 2;
  82. if (event.button() == Qt::MouseButton::MiddleButton)
  83. return 4;
  84. if (event.button() == Qt::MouseButton::BackButton)
  85. return 8;
  86. if (event.buttons() == Qt::MouseButton::ForwardButton)
  87. return 16;
  88. return 0;
  89. }
  90. unsigned get_buttons_from_qt_event(QMouseEvent const& event)
  91. {
  92. unsigned buttons = 0;
  93. if (event.buttons() & Qt::MouseButton::LeftButton)
  94. buttons |= 1;
  95. if (event.buttons() & Qt::MouseButton::RightButton)
  96. buttons |= 2;
  97. if (event.buttons() & Qt::MouseButton::MiddleButton)
  98. buttons |= 4;
  99. if (event.buttons() & Qt::MouseButton::BackButton)
  100. buttons |= 8;
  101. if (event.buttons() & Qt::MouseButton::ForwardButton)
  102. buttons |= 16;
  103. return buttons;
  104. }
  105. unsigned get_modifiers_from_qt_mouse_event(QMouseEvent const& event)
  106. {
  107. unsigned modifiers = 0;
  108. if (event.modifiers() & Qt::Modifier::ALT)
  109. modifiers |= 1;
  110. if (event.modifiers() & Qt::Modifier::CTRL)
  111. modifiers |= 2;
  112. if (event.modifiers() & Qt::Modifier::SHIFT)
  113. modifiers |= 4;
  114. return modifiers;
  115. }
  116. unsigned get_modifiers_from_qt_keyboard_event(QKeyEvent const& event)
  117. {
  118. auto modifiers = 0;
  119. if (event.modifiers().testFlag(Qt::AltModifier))
  120. modifiers |= KeyModifier::Mod_Alt;
  121. if (event.modifiers().testFlag(Qt::ControlModifier))
  122. modifiers |= KeyModifier::Mod_Ctrl;
  123. if (event.modifiers().testFlag(Qt::MetaModifier))
  124. modifiers |= KeyModifier::Mod_Super;
  125. if (event.modifiers().testFlag(Qt::ShiftModifier))
  126. modifiers |= KeyModifier::Mod_Shift;
  127. if (event.modifiers().testFlag(Qt::AltModifier))
  128. modifiers |= KeyModifier::Mod_AltGr;
  129. return modifiers;
  130. }
  131. KeyCode get_keycode_from_qt_keyboard_event(QKeyEvent const& event)
  132. {
  133. struct Mapping {
  134. constexpr Mapping(Qt::Key q, KeyCode s)
  135. : qt_key(q)
  136. , serenity_key(s)
  137. {
  138. }
  139. Qt::Key qt_key;
  140. KeyCode serenity_key;
  141. };
  142. constexpr Mapping mappings[] = {
  143. { Qt::Key_0, Key_0 },
  144. { Qt::Key_1, Key_1 },
  145. { Qt::Key_2, Key_2 },
  146. { Qt::Key_3, Key_3 },
  147. { Qt::Key_4, Key_4 },
  148. { Qt::Key_5, Key_5 },
  149. { Qt::Key_6, Key_6 },
  150. { Qt::Key_7, Key_7 },
  151. { Qt::Key_8, Key_8 },
  152. { Qt::Key_9, Key_9 },
  153. { Qt::Key_A, Key_A },
  154. { Qt::Key_Alt, Key_Alt },
  155. { Qt::Key_Ampersand, Key_Ampersand },
  156. { Qt::Key_Apostrophe, Key_Apostrophe },
  157. { Qt::Key_AsciiCircum, Key_Circumflex },
  158. { Qt::Key_AsciiTilde, Key_Tilde },
  159. { Qt::Key_Asterisk, Key_Asterisk },
  160. { Qt::Key_At, Key_AtSign },
  161. { Qt::Key_B, Key_B },
  162. { Qt::Key_Backslash, Key_Backslash },
  163. { Qt::Key_Backspace, Key_Backspace },
  164. { Qt::Key_Bar, Key_Pipe },
  165. { Qt::Key_BraceLeft, Key_LeftBrace },
  166. { Qt::Key_BraceRight, Key_RightBrace },
  167. { Qt::Key_BracketLeft, Key_LeftBracket },
  168. { Qt::Key_BracketRight, Key_RightBracket },
  169. { Qt::Key_C, Key_C },
  170. { Qt::Key_CapsLock, Key_CapsLock },
  171. { Qt::Key_Colon, Key_Colon },
  172. { Qt::Key_Comma, Key_Comma },
  173. { Qt::Key_Control, Key_Control },
  174. { Qt::Key_D, Key_D },
  175. { Qt::Key_Delete, Key_Delete },
  176. { Qt::Key_Dollar, Key_Dollar },
  177. { Qt::Key_Down, Key_Down },
  178. { Qt::Key_E, Key_E },
  179. { Qt::Key_End, Key_End },
  180. { Qt::Key_Equal, Key_Equal },
  181. { Qt::Key_Escape, Key_Escape },
  182. { Qt::Key_exclamdown, Key_ExclamationPoint },
  183. { Qt::Key_F, Key_F },
  184. { Qt::Key_F1, Key_F1 },
  185. { Qt::Key_F10, Key_F10 },
  186. { Qt::Key_F11, Key_F11 },
  187. { Qt::Key_F12, Key_F12 },
  188. { Qt::Key_F2, Key_F2 },
  189. { Qt::Key_F3, Key_F3 },
  190. { Qt::Key_F4, Key_F4 },
  191. { Qt::Key_F5, Key_F5 },
  192. { Qt::Key_F6, Key_F6 },
  193. { Qt::Key_F7, Key_F7 },
  194. { Qt::Key_F8, Key_F8 },
  195. { Qt::Key_F9, Key_F9 },
  196. { Qt::Key_G, Key_G },
  197. { Qt::Key_Greater, Key_GreaterThan },
  198. { Qt::Key_H, Key_H },
  199. { Qt::Key_Home, Key_Home },
  200. { Qt::Key_I, Key_I },
  201. { Qt::Key_Insert, Key_Insert },
  202. { Qt::Key_J, Key_J },
  203. { Qt::Key_K, Key_K },
  204. { Qt::Key_L, Key_L },
  205. { Qt::Key_Left, Key_Left },
  206. { Qt::Key_Less, Key_LessThan },
  207. { Qt::Key_M, Key_M },
  208. { Qt::Key_Menu, Key_Menu },
  209. { Qt::Key_Minus, Key_Minus },
  210. { Qt::Key_N, Key_N },
  211. { Qt::Key_NumLock, Key_NumLock },
  212. { Qt::Key_O, Key_O },
  213. { Qt::Key_P, Key_P },
  214. { Qt::Key_PageDown, Key_PageDown },
  215. { Qt::Key_PageUp, Key_PageUp },
  216. { Qt::Key_ParenLeft, Key_LeftParen },
  217. { Qt::Key_ParenRight, Key_RightParen },
  218. { Qt::Key_Percent, Key_Percent },
  219. { Qt::Key_Period, Key_Period },
  220. { Qt::Key_Plus, Key_Plus },
  221. { Qt::Key_Print, Key_PrintScreen },
  222. { Qt::Key_Q, Key_Q },
  223. { Qt::Key_Question, Key_QuestionMark },
  224. { Qt::Key_QuoteDbl, Key_DoubleQuote },
  225. { Qt::Key_R, Key_R },
  226. { Qt::Key_Return, Key_Return },
  227. { Qt::Key_Right, Key_Right },
  228. { Qt::Key_S, Key_S },
  229. { Qt::Key_ScrollLock, Key_ScrollLock },
  230. { Qt::Key_Semicolon, Key_Semicolon },
  231. { Qt::Key_Shift, Key_LeftShift },
  232. { Qt::Key_Slash, Key_Slash },
  233. { Qt::Key_Space, Key_Space },
  234. { Qt::Key_Super_L, Key_Super },
  235. { Qt::Key_SysReq, Key_SysRq },
  236. { Qt::Key_T, Key_T },
  237. { Qt::Key_Tab, Key_Tab },
  238. { Qt::Key_U, Key_U },
  239. { Qt::Key_Underscore, Key_Underscore },
  240. { Qt::Key_Up, Key_Up },
  241. { Qt::Key_V, Key_V },
  242. { Qt::Key_W, Key_W },
  243. { Qt::Key_X, Key_X },
  244. { Qt::Key_Y, Key_Y },
  245. { Qt::Key_Z, Key_Z },
  246. };
  247. for (auto const& mapping : mappings) {
  248. if (event.key() == mapping.qt_key)
  249. return mapping.serenity_key;
  250. }
  251. return Key_Invalid;
  252. }
  253. void WebContentView::mouseMoveEvent(QMouseEvent* event)
  254. {
  255. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  256. auto buttons = get_buttons_from_qt_event(*event);
  257. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  258. client().async_mouse_move(to_content(position), 0, buttons, modifiers);
  259. }
  260. void WebContentView::mousePressEvent(QMouseEvent* event)
  261. {
  262. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  263. auto button = get_button_from_qt_event(*event);
  264. if (button == 0) {
  265. // We could not convert Qt buttons to something that Lagom can
  266. // recognize - don't even bother propagating this to the web engine
  267. // as it will not handle it anyway, and it will (currently) assert
  268. return;
  269. }
  270. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  271. auto buttons = get_buttons_from_qt_event(*event);
  272. client().async_mouse_down(to_content(position), button, buttons, modifiers);
  273. }
  274. void WebContentView::mouseReleaseEvent(QMouseEvent* event)
  275. {
  276. Gfx::IntPoint position(event->position().x() / m_inverse_pixel_scaling_ratio, event->position().y() / m_inverse_pixel_scaling_ratio);
  277. auto button = get_button_from_qt_event(*event);
  278. if (event->button() & Qt::MouseButton::BackButton) {
  279. emit back_mouse_button();
  280. } else if (event->button() & Qt::MouseButton::ForwardButton) {
  281. emit forward_mouse_button();
  282. }
  283. if (button == 0) {
  284. // We could not convert Qt buttons to something that Lagom can
  285. // recognize - don't even bother propagating this to the web engine
  286. // as it will not handle it anyway, and it will (currently) assert
  287. return;
  288. }
  289. auto modifiers = get_modifiers_from_qt_mouse_event(*event);
  290. auto buttons = get_buttons_from_qt_event(*event);
  291. client().async_mouse_up(to_content(position), button, buttons, modifiers);
  292. }
  293. void WebContentView::dragEnterEvent(QDragEnterEvent* event)
  294. {
  295. if (event->mimeData()->hasUrls())
  296. event->acceptProposedAction();
  297. }
  298. void WebContentView::dropEvent(QDropEvent* event)
  299. {
  300. VERIFY(event->mimeData()->hasUrls());
  301. emit urls_dropped(event->mimeData()->urls());
  302. event->acceptProposedAction();
  303. }
  304. void WebContentView::keyPressEvent(QKeyEvent* event)
  305. {
  306. switch (event->key()) {
  307. case Qt::Key_Left:
  308. case Qt::Key_Right:
  309. case Qt::Key_Up:
  310. case Qt::Key_Down:
  311. case Qt::Key_PageUp:
  312. case Qt::Key_PageDown:
  313. QAbstractScrollArea::keyPressEvent(event);
  314. break;
  315. default:
  316. break;
  317. }
  318. if (event->key() == Qt::Key_Backtab) {
  319. // NOTE: Qt transforms Shift+Tab into a "Backtab", so we undo that transformation here.
  320. client().async_key_down(KeyCode::Key_Tab, Mod_Shift, '\t');
  321. return;
  322. }
  323. auto text = event->text();
  324. if (text.isEmpty()) {
  325. return;
  326. }
  327. auto point = event->text()[0].unicode();
  328. auto keycode = get_keycode_from_qt_keyboard_event(*event);
  329. auto modifiers = get_modifiers_from_qt_keyboard_event(*event);
  330. client().async_key_down(keycode, modifiers, point);
  331. }
  332. void WebContentView::keyReleaseEvent(QKeyEvent* event)
  333. {
  334. auto text = event->text();
  335. if (text.isEmpty()) {
  336. return;
  337. }
  338. auto point = event->text()[0].unicode();
  339. auto keycode = get_keycode_from_qt_keyboard_event(*event);
  340. auto modifiers = get_modifiers_from_qt_keyboard_event(*event);
  341. client().async_key_up(keycode, modifiers, point);
  342. }
  343. void WebContentView::focusInEvent(QFocusEvent*)
  344. {
  345. client().async_set_has_focus(true);
  346. }
  347. void WebContentView::focusOutEvent(QFocusEvent*)
  348. {
  349. client().async_set_has_focus(false);
  350. }
  351. Gfx::IntPoint WebContentView::to_content(Gfx::IntPoint viewport_position) const
  352. {
  353. return viewport_position.translated(horizontalScrollBar()->value(), verticalScrollBar()->value());
  354. }
  355. Gfx::IntPoint WebContentView::to_widget(Gfx::IntPoint content_position) const
  356. {
  357. return content_position.translated(-horizontalScrollBar()->value(), -verticalScrollBar()->value());
  358. }
  359. void WebContentView::paintEvent(QPaintEvent*)
  360. {
  361. QPainter painter(viewport());
  362. painter.scale(m_inverse_pixel_scaling_ratio, m_inverse_pixel_scaling_ratio);
  363. if (auto* bitmap = m_client_state.has_usable_bitmap ? m_client_state.front_bitmap.bitmap.ptr() : m_backup_bitmap.ptr()) {
  364. QImage q_image(bitmap->scanline_u8(0), bitmap->width(), bitmap->height(), QImage::Format_RGB32);
  365. painter.drawImage(QPoint(0, 0), q_image);
  366. return;
  367. }
  368. painter.fillRect(rect(), palette().base());
  369. }
  370. void WebContentView::resizeEvent(QResizeEvent* event)
  371. {
  372. QAbstractScrollArea::resizeEvent(event);
  373. handle_resize();
  374. }
  375. void WebContentView::handle_resize()
  376. {
  377. update_viewport_rect();
  378. if (m_client_state.has_usable_bitmap) {
  379. // NOTE: We keep the outgoing front bitmap as a backup so we have something to paint until we get a new one.
  380. m_backup_bitmap = m_client_state.front_bitmap.bitmap;
  381. }
  382. if (m_client_state.front_bitmap.bitmap)
  383. client().async_remove_backing_store(m_client_state.front_bitmap.id);
  384. if (m_client_state.back_bitmap.bitmap)
  385. client().async_remove_backing_store(m_client_state.back_bitmap.id);
  386. m_client_state.front_bitmap = {};
  387. m_client_state.back_bitmap = {};
  388. m_client_state.has_usable_bitmap = false;
  389. auto available_size = m_viewport_rect.size();
  390. if (available_size.is_empty())
  391. return;
  392. if (auto new_bitmap_or_error = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRx8888, available_size); !new_bitmap_or_error.is_error()) {
  393. m_client_state.front_bitmap.bitmap = new_bitmap_or_error.release_value();
  394. m_client_state.front_bitmap.id = m_client_state.next_bitmap_id++;
  395. client().async_add_backing_store(m_client_state.front_bitmap.id, m_client_state.front_bitmap.bitmap->to_shareable_bitmap());
  396. }
  397. if (auto new_bitmap_or_error = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRx8888, available_size); !new_bitmap_or_error.is_error()) {
  398. m_client_state.back_bitmap.bitmap = new_bitmap_or_error.release_value();
  399. m_client_state.back_bitmap.id = m_client_state.next_bitmap_id++;
  400. client().async_add_backing_store(m_client_state.back_bitmap.id, m_client_state.back_bitmap.bitmap->to_shareable_bitmap());
  401. }
  402. request_repaint();
  403. }
  404. void WebContentView::set_viewport_rect(Gfx::IntRect rect)
  405. {
  406. m_viewport_rect = rect;
  407. client().async_set_viewport_rect(rect);
  408. }
  409. void WebContentView::update_viewport_rect()
  410. {
  411. auto scaled_width = int(viewport()->width() / m_inverse_pixel_scaling_ratio);
  412. auto scaled_height = int(viewport()->height() / m_inverse_pixel_scaling_ratio);
  413. Gfx::IntRect rect(horizontalScrollBar()->value(), verticalScrollBar()->value(), scaled_width, scaled_height);
  414. set_viewport_rect(rect);
  415. request_repaint();
  416. }
  417. void WebContentView::did_output_js_console_message(i32 message_index)
  418. {
  419. if (m_console_widget)
  420. m_console_widget->notify_about_new_console_message(message_index);
  421. }
  422. void WebContentView::did_get_js_console_messages(i32 start_index, Vector<DeprecatedString> message_types, Vector<DeprecatedString> messages)
  423. {
  424. if (m_console_widget)
  425. m_console_widget->handle_console_messages(start_index, message_types, messages);
  426. }
  427. void WebContentView::ensure_js_console_widget()
  428. {
  429. if (!m_console_widget) {
  430. m_console_widget = new Ladybird::ConsoleWidget;
  431. m_console_widget->setWindowTitle("JS Console");
  432. m_console_widget->resize(640, 480);
  433. m_console_widget->on_js_input = [this](auto js_source) {
  434. client().async_js_console_input(js_source);
  435. };
  436. m_console_widget->on_request_messages = [this](i32 start_index) {
  437. client().async_js_console_request_messages(start_index);
  438. };
  439. }
  440. }
  441. void WebContentView::show_js_console()
  442. {
  443. ensure_js_console_widget();
  444. m_console_widget->show();
  445. }
  446. void WebContentView::ensure_inspector_widget()
  447. {
  448. if (m_inspector_widget)
  449. return;
  450. m_inspector_widget = new Ladybird::InspectorWidget;
  451. m_inspector_widget->setWindowTitle("Inspector");
  452. m_inspector_widget->resize(640, 480);
  453. m_inspector_widget->on_close = [this] {
  454. clear_inspected_dom_node();
  455. };
  456. m_inspector_widget->on_dom_node_inspected = [&](auto id, auto pseudo_element) {
  457. return inspect_dom_node(id, pseudo_element);
  458. };
  459. }
  460. void WebContentView::close_sub_widgets()
  461. {
  462. auto close_widget_window = [](auto* widget) {
  463. if (widget)
  464. widget->close();
  465. };
  466. close_widget_window(m_console_widget);
  467. close_widget_window(m_inspector_widget);
  468. }
  469. bool WebContentView::is_inspector_open() const
  470. {
  471. return m_inspector_widget && m_inspector_widget->isVisible();
  472. }
  473. void WebContentView::show_inspector()
  474. {
  475. ensure_inspector_widget();
  476. m_inspector_widget->show();
  477. inspect_dom_tree();
  478. }
  479. void WebContentView::update_zoom()
  480. {
  481. client().async_set_device_pixels_per_css_pixel(m_device_pixel_ratio * m_zoom_level);
  482. update_viewport_rect();
  483. request_repaint();
  484. }
  485. void WebContentView::showEvent(QShowEvent* event)
  486. {
  487. QAbstractScrollArea::showEvent(event);
  488. client().async_set_system_visibility_state(true);
  489. }
  490. void WebContentView::hideEvent(QHideEvent* event)
  491. {
  492. QAbstractScrollArea::hideEvent(event);
  493. client().async_set_system_visibility_state(false);
  494. }
  495. void WebContentView::create_client()
  496. {
  497. m_client_state = {};
  498. int socket_fds[2] {};
  499. MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fds));
  500. int ui_fd = socket_fds[0];
  501. int wc_fd = socket_fds[1];
  502. int fd_passing_socket_fds[2] {};
  503. MUST(Core::System::socketpair(AF_LOCAL, SOCK_STREAM, 0, fd_passing_socket_fds));
  504. int ui_fd_passing_fd = fd_passing_socket_fds[0];
  505. int wc_fd_passing_fd = fd_passing_socket_fds[1];
  506. auto child_pid = fork();
  507. if (!child_pid) {
  508. MUST(Core::System::close(ui_fd_passing_fd));
  509. MUST(Core::System::close(ui_fd));
  510. auto takeover_string = DeprecatedString::formatted("WebContent:{}", wc_fd);
  511. MUST(Core::System::setenv("SOCKET_TAKEOVER"sv, takeover_string, true));
  512. auto webcontent_fd_passing_socket_string = DeprecatedString::number(wc_fd_passing_fd);
  513. Vector<StringView, 5> arguments {
  514. "WebContent"sv,
  515. "--webcontent-fd-passing-socket"sv,
  516. webcontent_fd_passing_socket_string
  517. };
  518. if (!m_webdriver_content_ipc_path.is_empty()) {
  519. arguments.append("--webdriver-content-path"sv);
  520. arguments.append(m_webdriver_content_ipc_path);
  521. }
  522. auto result = spawn_helper_process("WebContent"sv, arguments, Core::System::SearchInPath::Yes);
  523. if (result.is_error())
  524. warnln("Could not launch WebContent: {}", result.error());
  525. VERIFY_NOT_REACHED();
  526. }
  527. MUST(Core::System::close(wc_fd_passing_fd));
  528. MUST(Core::System::close(wc_fd));
  529. auto socket = MUST(Core::Stream::LocalSocket::adopt_fd(ui_fd));
  530. MUST(socket->set_blocking(true));
  531. auto new_client = MUST(adopt_nonnull_ref_or_enomem(new (nothrow) WebView::WebContentClient(std::move(socket), *this)));
  532. new_client->set_fd_passing_socket(MUST(Core::Stream::LocalSocket::adopt_fd(ui_fd_passing_fd)));
  533. m_web_content_notifier.setSocket(new_client->socket().fd().value());
  534. m_web_content_notifier.setEnabled(true);
  535. QObject::connect(&m_web_content_notifier, &QSocketNotifier::activated, [new_client = new_client.ptr()] {
  536. if (auto notifier = new_client->socket().notifier())
  537. notifier->on_ready_to_read();
  538. });
  539. struct DeferredInvokerQt final : IPC::DeferredInvoker {
  540. virtual ~DeferredInvokerQt() = default;
  541. virtual void schedule(Function<void()> callback) override
  542. {
  543. QTimer::singleShot(0, std::move(callback));
  544. }
  545. };
  546. new_client->set_deferred_invoker(make<DeferredInvokerQt>());
  547. m_client_state.client = new_client;
  548. m_client_state.client->on_web_content_process_crash = [this] {
  549. QTimer::singleShot(0, [this] {
  550. handle_web_content_process_crash();
  551. });
  552. };
  553. client().async_set_device_pixels_per_css_pixel(m_device_pixel_ratio);
  554. client().async_update_system_theme(MUST(Gfx::load_system_theme(DeprecatedString::formatted("{}/res/themes/Default.ini", s_serenity_resource_root))));
  555. client().async_update_system_fonts(Gfx::FontDatabase::default_font_query(), Gfx::FontDatabase::fixed_width_font_query(), Gfx::FontDatabase::window_title_font_query());
  556. // FIXME: Get the screen rect.
  557. // client().async_update_screen_rects(GUI::Desktop::the().rects(), GUI::Desktop::the().main_screen_index());
  558. }
  559. void WebContentView::handle_web_content_process_crash()
  560. {
  561. dbgln("WebContent process crashed!");
  562. create_client();
  563. VERIFY(m_client_state.client);
  564. // Don't keep a stale backup bitmap around.
  565. m_backup_bitmap = nullptr;
  566. handle_resize();
  567. StringBuilder builder;
  568. builder.append("<html><head><title>Crashed: "sv);
  569. builder.append(escape_html_entities(m_url.to_deprecated_string()));
  570. builder.append("</title></head><body>"sv);
  571. builder.append("<h1>Web page crashed"sv);
  572. if (!m_url.host().is_empty()) {
  573. builder.appendff(" on {}", escape_html_entities(m_url.host()));
  574. }
  575. builder.append("</h1>"sv);
  576. auto escaped_url = escape_html_entities(m_url.to_deprecated_string());
  577. builder.appendff("The web page <a href=\"{}\">{}</a> has crashed.<br><br>You can reload the page to try again.", escaped_url, escaped_url);
  578. builder.append("</body></html>"sv);
  579. load_html(builder.to_deprecated_string(), m_url);
  580. }
  581. void WebContentView::notify_server_did_paint(Badge<WebContentClient>, i32 bitmap_id)
  582. {
  583. if (m_client_state.back_bitmap.id == bitmap_id) {
  584. m_client_state.has_usable_bitmap = true;
  585. m_client_state.back_bitmap.pending_paints--;
  586. swap(m_client_state.back_bitmap, m_client_state.front_bitmap);
  587. // We don't need the backup bitmap anymore, so drop it.
  588. m_backup_bitmap = nullptr;
  589. viewport()->update();
  590. if (m_client_state.got_repaint_requests_while_painting) {
  591. m_client_state.got_repaint_requests_while_painting = false;
  592. request_repaint();
  593. }
  594. }
  595. }
  596. void WebContentView::notify_server_did_invalidate_content_rect(Badge<WebContentClient>, [[maybe_unused]] Gfx::IntRect const& content_rect)
  597. {
  598. request_repaint();
  599. }
  600. void WebContentView::notify_server_did_change_selection(Badge<WebContentClient>)
  601. {
  602. request_repaint();
  603. }
  604. void WebContentView::notify_server_did_request_cursor_change(Badge<WebContentClient>, Gfx::StandardCursor cursor)
  605. {
  606. switch (cursor) {
  607. case Gfx::StandardCursor::Hand:
  608. setCursor(Qt::PointingHandCursor);
  609. break;
  610. case Gfx::StandardCursor::IBeam:
  611. setCursor(Qt::IBeamCursor);
  612. break;
  613. case Gfx::StandardCursor::Arrow:
  614. default:
  615. setCursor(Qt::ArrowCursor);
  616. break;
  617. }
  618. }
  619. void WebContentView::notify_server_did_layout(Badge<WebContentClient>, Gfx::IntSize content_size)
  620. {
  621. verticalScrollBar()->setMinimum(0);
  622. verticalScrollBar()->setMaximum(content_size.height() - m_viewport_rect.height());
  623. verticalScrollBar()->setPageStep(m_viewport_rect.height());
  624. horizontalScrollBar()->setMinimum(0);
  625. horizontalScrollBar()->setMaximum(content_size.width() - m_viewport_rect.width());
  626. horizontalScrollBar()->setPageStep(m_viewport_rect.width());
  627. }
  628. void WebContentView::notify_server_did_change_title(Badge<WebContentClient>, DeprecatedString const& title)
  629. {
  630. emit title_changed(qstring_from_ak_deprecated_string(title));
  631. }
  632. void WebContentView::notify_server_did_request_scroll(Badge<WebContentClient>, i32 x_delta, i32 y_delta)
  633. {
  634. horizontalScrollBar()->setValue(horizontalScrollBar()->value() + x_delta);
  635. verticalScrollBar()->setValue(verticalScrollBar()->value() + y_delta);
  636. }
  637. void WebContentView::notify_server_did_request_scroll_to(Badge<WebContentClient>, Gfx::IntPoint scroll_position)
  638. {
  639. horizontalScrollBar()->setValue(scroll_position.x());
  640. verticalScrollBar()->setValue(scroll_position.y());
  641. }
  642. void WebContentView::notify_server_did_request_scroll_into_view(Badge<WebContentClient>, Gfx::IntRect const& rect)
  643. {
  644. if (m_viewport_rect.contains(rect))
  645. return;
  646. if (rect.top() < m_viewport_rect.top()) {
  647. verticalScrollBar()->setValue(rect.top());
  648. } else if (rect.top() > m_viewport_rect.top() && rect.bottom() > m_viewport_rect.bottom()) {
  649. verticalScrollBar()->setValue(rect.bottom() - m_viewport_rect.height() + 1);
  650. }
  651. }
  652. void WebContentView::notify_server_did_enter_tooltip_area(Badge<WebContentClient>, Gfx::IntPoint content_position, DeprecatedString const& tooltip)
  653. {
  654. auto widget_position = to_widget(content_position);
  655. QToolTip::showText(
  656. mapToGlobal(QPoint(widget_position.x(), widget_position.y())),
  657. qstring_from_ak_deprecated_string(tooltip),
  658. this);
  659. }
  660. void WebContentView::notify_server_did_leave_tooltip_area(Badge<WebContentClient>)
  661. {
  662. QToolTip::hideText();
  663. }
  664. void WebContentView::notify_server_did_hover_link(Badge<WebContentClient>, AK::URL const& url)
  665. {
  666. emit link_hovered(qstring_from_ak_deprecated_string(url.to_deprecated_string()));
  667. }
  668. void WebContentView::notify_server_did_unhover_link(Badge<WebContentClient>)
  669. {
  670. emit link_unhovered();
  671. }
  672. void WebContentView::notify_server_did_click_link(Badge<WebContentClient>, AK::URL const& url, DeprecatedString const& target, unsigned int modifiers)
  673. {
  674. // FIXME
  675. (void)url;
  676. (void)target;
  677. (void)modifiers;
  678. // if (on_link_click)
  679. // on_link_click(url, target, modifiers);
  680. }
  681. void WebContentView::notify_server_did_middle_click_link(Badge<WebContentClient>, AK::URL const& url, DeprecatedString const& target, unsigned int modifiers)
  682. {
  683. (void)url;
  684. (void)target;
  685. (void)modifiers;
  686. }
  687. void WebContentView::notify_server_did_start_loading(Badge<WebContentClient>, AK::URL const& url, bool is_redirect)
  688. {
  689. m_url = url;
  690. emit load_started(url, is_redirect);
  691. if (m_inspector_widget)
  692. m_inspector_widget->clear_dom_json();
  693. }
  694. void WebContentView::notify_server_did_finish_loading(Badge<WebContentClient>, AK::URL const& url)
  695. {
  696. m_url = url;
  697. if (is_inspector_open())
  698. inspect_dom_tree();
  699. if (on_load_finish)
  700. on_load_finish(url);
  701. }
  702. void WebContentView::notify_server_did_request_navigate_back(Badge<WebContentClient>)
  703. {
  704. emit navigate_back();
  705. }
  706. void WebContentView::notify_server_did_request_navigate_forward(Badge<WebContentClient>)
  707. {
  708. emit navigate_forward();
  709. }
  710. void WebContentView::notify_server_did_request_refresh(Badge<WebContentClient>)
  711. {
  712. emit refresh();
  713. }
  714. void WebContentView::notify_server_did_request_context_menu(Badge<WebContentClient>, Gfx::IntPoint content_position)
  715. {
  716. // FIXME
  717. (void)content_position;
  718. }
  719. void WebContentView::notify_server_did_request_link_context_menu(Badge<WebContentClient>, Gfx::IntPoint content_position, AK::URL const& url, DeprecatedString const&, unsigned)
  720. {
  721. // FIXME
  722. (void)content_position;
  723. (void)url;
  724. }
  725. 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)
  726. {
  727. // FIXME
  728. (void)content_position;
  729. (void)url;
  730. (void)bitmap;
  731. }
  732. void WebContentView::notify_server_did_request_alert(Badge<WebContentClient>, DeprecatedString const& message)
  733. {
  734. m_dialog = new QMessageBox(QMessageBox::Icon::Warning, "Ladybird", qstring_from_ak_deprecated_string(message), QMessageBox::StandardButton::Ok, this);
  735. m_dialog->exec();
  736. client().async_alert_closed();
  737. m_dialog = nullptr;
  738. }
  739. void WebContentView::notify_server_did_request_confirm(Badge<WebContentClient>, DeprecatedString const& message)
  740. {
  741. m_dialog = new QMessageBox(QMessageBox::Icon::Question, "Ladybird", qstring_from_ak_deprecated_string(message), QMessageBox::StandardButton::Ok | QMessageBox::StandardButton::Cancel, this);
  742. auto result = m_dialog->exec();
  743. client().async_confirm_closed(result == QMessageBox::StandardButton::Ok || result == QDialog::Accepted);
  744. m_dialog = nullptr;
  745. }
  746. void WebContentView::notify_server_did_request_prompt(Badge<WebContentClient>, DeprecatedString const& message, DeprecatedString const& default_)
  747. {
  748. m_dialog = new QInputDialog(this);
  749. auto& dialog = static_cast<QInputDialog&>(*m_dialog);
  750. dialog.setWindowTitle("Ladybird");
  751. dialog.setLabelText(qstring_from_ak_deprecated_string(message));
  752. dialog.setTextValue(qstring_from_ak_deprecated_string(default_));
  753. if (dialog.exec() == QDialog::Accepted)
  754. client().async_prompt_closed(ak_deprecated_string_from_qstring(dialog.textValue()));
  755. else
  756. client().async_prompt_closed({});
  757. m_dialog = nullptr;
  758. }
  759. void WebContentView::notify_server_did_request_set_prompt_text(Badge<WebContentClient>, DeprecatedString const& message)
  760. {
  761. if (m_dialog && is<QInputDialog>(*m_dialog))
  762. static_cast<QInputDialog&>(*m_dialog).setTextValue(qstring_from_ak_deprecated_string(message));
  763. }
  764. void WebContentView::notify_server_did_request_accept_dialog(Badge<WebContentClient>)
  765. {
  766. if (m_dialog)
  767. m_dialog->accept();
  768. }
  769. void WebContentView::notify_server_did_request_dismiss_dialog(Badge<WebContentClient>)
  770. {
  771. if (m_dialog)
  772. m_dialog->reject();
  773. }
  774. void WebContentView::notify_server_did_get_source(AK::URL const& url, DeprecatedString const& source)
  775. {
  776. emit got_source(url, qstring_from_ak_deprecated_string(source));
  777. }
  778. void WebContentView::notify_server_did_get_dom_tree(DeprecatedString const& dom_tree)
  779. {
  780. if (on_get_dom_tree)
  781. on_get_dom_tree(dom_tree);
  782. if (m_inspector_widget)
  783. m_inspector_widget->set_dom_json(dom_tree);
  784. }
  785. 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)
  786. {
  787. if (on_get_dom_node_properties)
  788. on_get_dom_node_properties(node_id, specified_style, computed_style, custom_properties, node_box_sizing);
  789. }
  790. void WebContentView::notify_server_did_output_js_console_message(i32 message_index)
  791. {
  792. if (m_console_widget)
  793. m_console_widget->notify_about_new_console_message(message_index);
  794. }
  795. void WebContentView::notify_server_did_get_js_console_messages(i32 start_index, Vector<DeprecatedString> const& message_types, Vector<DeprecatedString> const& messages)
  796. {
  797. if (m_console_widget)
  798. m_console_widget->handle_console_messages(start_index, message_types, messages);
  799. }
  800. void WebContentView::notify_server_did_change_favicon(Gfx::Bitmap const& bitmap)
  801. {
  802. auto qimage = QImage(bitmap.scanline_u8(0), bitmap.width(), bitmap.height(), QImage::Format_ARGB32);
  803. if (qimage.isNull())
  804. return;
  805. auto qpixmap = QPixmap::fromImage(qimage);
  806. if (qpixmap.isNull())
  807. return;
  808. emit favicon_changed(QIcon(qpixmap));
  809. }
  810. Vector<Web::Cookie::Cookie> WebContentView::notify_server_did_request_all_cookies(Badge<WebContentClient>, AK::URL const& url)
  811. {
  812. if (on_get_all_cookies)
  813. return on_get_all_cookies(url);
  814. return {};
  815. }
  816. Optional<Web::Cookie::Cookie> WebContentView::notify_server_did_request_named_cookie(Badge<WebContentClient>, AK::URL const& url, DeprecatedString const& name)
  817. {
  818. if (on_get_named_cookie)
  819. return on_get_named_cookie(url, name);
  820. return {};
  821. }
  822. DeprecatedString WebContentView::notify_server_did_request_cookie(Badge<WebContentClient>, AK::URL const& url, Web::Cookie::Source source)
  823. {
  824. if (on_get_cookie)
  825. return on_get_cookie(url, source);
  826. return {};
  827. }
  828. void WebContentView::notify_server_did_set_cookie(Badge<WebContentClient>, AK::URL const& url, Web::Cookie::ParsedCookie const& cookie, Web::Cookie::Source source)
  829. {
  830. if (on_set_cookie)
  831. on_set_cookie(url, cookie, source);
  832. }
  833. void WebContentView::notify_server_did_update_cookie(Badge<WebContentClient>, Web::Cookie::Cookie const& cookie)
  834. {
  835. if (on_update_cookie)
  836. on_update_cookie(cookie);
  837. }
  838. void WebContentView::notify_server_did_update_resource_count(i32 count_waiting)
  839. {
  840. // FIXME
  841. (void)count_waiting;
  842. }
  843. void WebContentView::notify_server_did_request_restore_window()
  844. {
  845. emit restore_window();
  846. }
  847. Gfx::IntPoint WebContentView::notify_server_did_request_reposition_window(Gfx::IntPoint position)
  848. {
  849. return emit reposition_window(position);
  850. }
  851. Gfx::IntSize WebContentView::notify_server_did_request_resize_window(Gfx::IntSize size)
  852. {
  853. return emit resize_window(size);
  854. }
  855. Gfx::IntRect WebContentView::notify_server_did_request_maximize_window()
  856. {
  857. return emit maximize_window();
  858. }
  859. Gfx::IntRect WebContentView::notify_server_did_request_minimize_window()
  860. {
  861. return emit minimize_window();
  862. }
  863. Gfx::IntRect WebContentView::notify_server_did_request_fullscreen_window()
  864. {
  865. return emit fullscreen_window();
  866. }
  867. void WebContentView::notify_server_did_request_file(Badge<WebContentClient>, DeprecatedString const& path, i32 request_id)
  868. {
  869. auto file = Core::Stream::File::open(path, Core::Stream::OpenMode::Read);
  870. if (file.is_error())
  871. client().async_handle_file_return(file.error().code(), {}, request_id);
  872. else
  873. client().async_handle_file_return(0, IPC::File(*file.value()), request_id);
  874. }
  875. void WebContentView::request_repaint()
  876. {
  877. // If this widget was instantiated but not yet added to a window,
  878. // it won't have a back bitmap yet, so we can just skip repaint requests.
  879. if (!m_client_state.back_bitmap.bitmap)
  880. return;
  881. // Don't request a repaint until pending paint requests have finished.
  882. if (m_client_state.back_bitmap.pending_paints) {
  883. m_client_state.got_repaint_requests_while_painting = true;
  884. return;
  885. }
  886. m_client_state.back_bitmap.pending_paints++;
  887. client().async_paint(m_client_state.back_bitmap.bitmap->rect().translated(horizontalScrollBar()->value(), verticalScrollBar()->value()), m_client_state.back_bitmap.id);
  888. }
  889. bool WebContentView::event(QEvent* event)
  890. {
  891. // NOTE: We have to implement event() manually as Qt's focus navigation mechanism
  892. // eats all the Tab key presses by default.
  893. if (event->type() == QEvent::KeyPress) {
  894. keyPressEvent(static_cast<QKeyEvent*>(event));
  895. return true;
  896. }
  897. if (event->type() == QEvent::KeyRelease) {
  898. keyReleaseEvent(static_cast<QKeyEvent*>(event));
  899. return true;
  900. }
  901. return QAbstractScrollArea::event(event);
  902. }
  903. void WebContentView::notify_server_did_finish_handling_input_event(bool event_was_accepted)
  904. {
  905. // FIXME: Currently Ladybird handles the keyboard shortcuts before passing the event to web content, so
  906. // we don't need to do anything here. But we'll need to once we start asking web content first.
  907. (void)event_was_accepted;
  908. }
  909. void WebContentView::notify_server_did_get_accessibility_tree(DeprecatedString const&)
  910. {
  911. dbgln("TODO: support accessibility tree in Ladybird");
  912. }
  913. ErrorOr<String> WebContentView::dump_layout_tree()
  914. {
  915. return String::from_deprecated_string(client().dump_layout_tree());
  916. }