WebContentView.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. /*
  2. * Copyright (c) 2022-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "WebContentView.h"
  8. #include "Application.h"
  9. #include "StringUtils.h"
  10. #include <AK/Assertions.h>
  11. #include <AK/ByteBuffer.h>
  12. #include <AK/Format.h>
  13. #include <AK/LexicalPath.h>
  14. #include <AK/NonnullOwnPtr.h>
  15. #include <AK/Types.h>
  16. #include <Kernel/API/KeyCode.h>
  17. #include <Ladybird/HelperProcess.h>
  18. #include <Ladybird/Utilities.h>
  19. #include <LibCore/EventLoop.h>
  20. #include <LibCore/Resource.h>
  21. #include <LibCore/Timer.h>
  22. #include <LibGfx/Bitmap.h>
  23. #include <LibGfx/Font/FontDatabase.h>
  24. #include <LibGfx/ImageFormats/PNGWriter.h>
  25. #include <LibGfx/Painter.h>
  26. #include <LibGfx/Palette.h>
  27. #include <LibGfx/Rect.h>
  28. #include <LibGfx/SystemTheme.h>
  29. #include <LibWeb/Crypto/Crypto.h>
  30. #include <LibWeb/Worker/WebWorkerClient.h>
  31. #include <LibWebView/WebContentClient.h>
  32. #include <QApplication>
  33. #include <QCursor>
  34. #include <QGuiApplication>
  35. #include <QIcon>
  36. #include <QLineEdit>
  37. #include <QMimeData>
  38. #include <QMouseEvent>
  39. #include <QPaintEvent>
  40. #include <QPainter>
  41. #include <QPalette>
  42. #include <QScrollBar>
  43. #include <QTextEdit>
  44. #include <QTimer>
  45. #include <QToolTip>
  46. namespace Ladybird {
  47. bool is_using_dark_system_theme(QWidget&);
  48. WebContentView::WebContentView(QWidget* window, WebContentOptions const& web_content_options, StringView webdriver_content_ipc_path, RefPtr<WebView::WebContentClient> parent_client, size_t page_index)
  49. : QAbstractScrollArea(window)
  50. , m_web_content_options(web_content_options)
  51. , m_webdriver_content_ipc_path(webdriver_content_ipc_path)
  52. {
  53. m_client_state.client = parent_client;
  54. m_client_state.page_index = page_index;
  55. setMouseTracking(true);
  56. setAcceptDrops(true);
  57. setFocusPolicy(Qt::FocusPolicy::StrongFocus);
  58. m_device_pixel_ratio = devicePixelRatio();
  59. verticalScrollBar()->setSingleStep(24);
  60. horizontalScrollBar()->setSingleStep(24);
  61. QObject::connect(verticalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  62. update_viewport_rect();
  63. });
  64. QObject::connect(horizontalScrollBar(), &QScrollBar::valueChanged, [this](int) {
  65. update_viewport_rect();
  66. });
  67. initialize_client((parent_client == nullptr) ? CreateNewClient::Yes : CreateNewClient::No);
  68. on_did_layout = [this](auto content_size) {
  69. verticalScrollBar()->setMinimum(0);
  70. verticalScrollBar()->setMaximum(content_size.height() - m_viewport_rect.height());
  71. verticalScrollBar()->setPageStep(m_viewport_rect.height());
  72. horizontalScrollBar()->setMinimum(0);
  73. horizontalScrollBar()->setMaximum(content_size.width() - m_viewport_rect.width());
  74. horizontalScrollBar()->setPageStep(m_viewport_rect.width());
  75. };
  76. on_ready_to_paint = [this]() {
  77. viewport()->update();
  78. };
  79. on_scroll_by_delta = [this](auto x_delta, auto y_delta) {
  80. horizontalScrollBar()->setValue(max(0, horizontalScrollBar()->value() + x_delta));
  81. verticalScrollBar()->setValue(max(0, verticalScrollBar()->value() + y_delta));
  82. };
  83. on_scroll_to_point = [this](auto position) {
  84. horizontalScrollBar()->setValue(position.x());
  85. verticalScrollBar()->setValue(position.y());
  86. };
  87. on_cursor_change = [this](auto cursor) {
  88. update_cursor(cursor);
  89. };
  90. on_enter_tooltip_area = [this](auto position, auto const& tooltip) {
  91. auto tooltip_without_carriage_return = tooltip.contains("\r"sv)
  92. ? tooltip.replace("\r\n"sv, "\n"sv, ReplaceMode::All).replace("\r"sv, "\n"sv, ReplaceMode::All)
  93. : tooltip;
  94. QToolTip::showText(
  95. mapToGlobal(QPoint(position.x(), position.y())),
  96. qstring_from_ak_string(tooltip_without_carriage_return),
  97. this);
  98. };
  99. on_leave_tooltip_area = []() {
  100. QToolTip::hideText();
  101. };
  102. on_finish_handling_key_event = [this](auto const& event) {
  103. finish_handling_key_event(event);
  104. };
  105. on_request_worker_agent = []() {
  106. auto& request_server_client = static_cast<Ladybird::Application*>(QApplication::instance())->request_server_client;
  107. auto worker_client = MUST(launch_web_worker_process(MUST(get_paths_for_helper_process("WebWorker"sv)), *request_server_client));
  108. return worker_client->dup_socket();
  109. };
  110. }
  111. WebContentView::~WebContentView()
  112. {
  113. if (m_client_state.client)
  114. m_client_state.client->unregister_view(m_client_state.page_index);
  115. }
  116. static GUI::MouseButton get_button_from_qt_event(QSinglePointEvent const& event)
  117. {
  118. if (event.button() == Qt::MouseButton::LeftButton)
  119. return GUI::MouseButton::Primary;
  120. if (event.button() == Qt::MouseButton::RightButton)
  121. return GUI::MouseButton::Secondary;
  122. if (event.button() == Qt::MouseButton::MiddleButton)
  123. return GUI::MouseButton::Middle;
  124. if (event.button() == Qt::MouseButton::BackButton)
  125. return GUI::MouseButton::Backward;
  126. if (event.buttons() == Qt::MouseButton::ForwardButton)
  127. return GUI::MouseButton::Forward;
  128. return GUI::MouseButton::None;
  129. }
  130. static GUI::MouseButton get_buttons_from_qt_event(QSinglePointEvent const& event)
  131. {
  132. auto buttons = GUI::MouseButton::None;
  133. if (event.buttons().testFlag(Qt::MouseButton::LeftButton))
  134. buttons |= GUI::MouseButton::Primary;
  135. if (event.buttons().testFlag(Qt::MouseButton::RightButton))
  136. buttons |= GUI::MouseButton::Secondary;
  137. if (event.buttons().testFlag(Qt::MouseButton::MiddleButton))
  138. buttons |= GUI::MouseButton::Middle;
  139. if (event.buttons().testFlag(Qt::MouseButton::BackButton))
  140. buttons |= GUI::MouseButton::Backward;
  141. if (event.buttons().testFlag(Qt::MouseButton::ForwardButton))
  142. buttons |= GUI::MouseButton::Forward;
  143. return buttons;
  144. }
  145. static KeyModifier get_modifiers_from_qt_mouse_event(QSinglePointEvent const& event)
  146. {
  147. auto modifiers = KeyModifier::Mod_None;
  148. if (event.modifiers().testFlag(Qt::AltModifier))
  149. modifiers |= KeyModifier::Mod_Alt;
  150. if (event.modifiers().testFlag(Qt::ControlModifier))
  151. modifiers |= KeyModifier::Mod_Ctrl;
  152. if (event.modifiers().testFlag(Qt::ShiftModifier))
  153. modifiers |= KeyModifier::Mod_Shift;
  154. return modifiers;
  155. }
  156. static KeyModifier get_modifiers_from_qt_keyboard_event(QKeyEvent const& event)
  157. {
  158. auto modifiers = KeyModifier::Mod_None;
  159. if (event.modifiers().testFlag(Qt::AltModifier))
  160. modifiers |= KeyModifier::Mod_Alt;
  161. if (event.modifiers().testFlag(Qt::ControlModifier))
  162. modifiers |= KeyModifier::Mod_Ctrl;
  163. if (event.modifiers().testFlag(Qt::MetaModifier))
  164. modifiers |= KeyModifier::Mod_Super;
  165. if (event.modifiers().testFlag(Qt::ShiftModifier))
  166. modifiers |= KeyModifier::Mod_Shift;
  167. if (event.modifiers().testFlag(Qt::AltModifier))
  168. modifiers |= KeyModifier::Mod_AltGr;
  169. if (event.modifiers().testFlag(Qt::KeypadModifier))
  170. modifiers |= KeyModifier::Mod_Keypad;
  171. return modifiers;
  172. }
  173. static KeyCode get_keycode_from_qt_keyboard_event(QKeyEvent const& event)
  174. {
  175. struct Mapping {
  176. constexpr Mapping(Qt::Key q, KeyCode s)
  177. : qt_key(q)
  178. , serenity_key(s)
  179. {
  180. }
  181. Qt::Key qt_key;
  182. KeyCode serenity_key;
  183. };
  184. // https://doc.qt.io/qt-6/qt.html#Key-enum
  185. constexpr Mapping mappings[] = {
  186. { Qt::Key_0, Key_0 },
  187. { Qt::Key_1, Key_1 },
  188. { Qt::Key_2, Key_2 },
  189. { Qt::Key_3, Key_3 },
  190. { Qt::Key_4, Key_4 },
  191. { Qt::Key_5, Key_5 },
  192. { Qt::Key_6, Key_6 },
  193. { Qt::Key_7, Key_7 },
  194. { Qt::Key_8, Key_8 },
  195. { Qt::Key_9, Key_9 },
  196. { Qt::Key_A, Key_A },
  197. { Qt::Key_Alt, Key_Alt },
  198. { Qt::Key_Ampersand, Key_Ampersand },
  199. { Qt::Key_Apostrophe, Key_Apostrophe },
  200. { Qt::Key_AsciiCircum, Key_Circumflex },
  201. { Qt::Key_AsciiTilde, Key_Tilde },
  202. { Qt::Key_Asterisk, Key_Asterisk },
  203. { Qt::Key_At, Key_AtSign },
  204. { Qt::Key_B, Key_B },
  205. { Qt::Key_Backslash, Key_Backslash },
  206. { Qt::Key_Backspace, Key_Backspace },
  207. { Qt::Key_Bar, Key_Pipe },
  208. { Qt::Key_BraceLeft, Key_LeftBrace },
  209. { Qt::Key_BraceRight, Key_RightBrace },
  210. { Qt::Key_BracketLeft, Key_LeftBracket },
  211. { Qt::Key_BracketRight, Key_RightBracket },
  212. { Qt::Key_C, Key_C },
  213. { Qt::Key_CapsLock, Key_CapsLock },
  214. { Qt::Key_Colon, Key_Colon },
  215. { Qt::Key_Comma, Key_Comma },
  216. { Qt::Key_Control, Key_Control },
  217. { Qt::Key_D, Key_D },
  218. { Qt::Key_Delete, Key_Delete },
  219. { Qt::Key_Dollar, Key_Dollar },
  220. { Qt::Key_Down, Key_Down },
  221. { Qt::Key_E, Key_E },
  222. { Qt::Key_End, Key_End },
  223. { Qt::Key_Equal, Key_Equal },
  224. { Qt::Key_Enter, Key_Return },
  225. { Qt::Key_Escape, Key_Escape },
  226. { Qt::Key_Exclam, Key_ExclamationPoint },
  227. { Qt::Key_exclamdown, Key_ExclamationPoint },
  228. { Qt::Key_F, Key_F },
  229. { Qt::Key_F1, Key_F1 },
  230. { Qt::Key_F10, Key_F10 },
  231. { Qt::Key_F11, Key_F11 },
  232. { Qt::Key_F12, Key_F12 },
  233. { Qt::Key_F2, Key_F2 },
  234. { Qt::Key_F3, Key_F3 },
  235. { Qt::Key_F4, Key_F4 },
  236. { Qt::Key_F5, Key_F5 },
  237. { Qt::Key_F6, Key_F6 },
  238. { Qt::Key_F7, Key_F7 },
  239. { Qt::Key_F8, Key_F8 },
  240. { Qt::Key_F9, Key_F9 },
  241. { Qt::Key_G, Key_G },
  242. { Qt::Key_Greater, Key_GreaterThan },
  243. { Qt::Key_H, Key_H },
  244. { Qt::Key_Home, Key_Home },
  245. { Qt::Key_I, Key_I },
  246. { Qt::Key_Insert, Key_Insert },
  247. { Qt::Key_J, Key_J },
  248. { Qt::Key_K, Key_K },
  249. { Qt::Key_L, Key_L },
  250. { Qt::Key_Left, Key_Left },
  251. { Qt::Key_Less, Key_LessThan },
  252. { Qt::Key_M, Key_M },
  253. { Qt::Key_Menu, Key_Menu },
  254. { Qt::Key_Meta, Key_Super },
  255. { Qt::Key_Minus, Key_Minus },
  256. { Qt::Key_N, Key_N },
  257. { Qt::Key_NumberSign, Key_Hashtag },
  258. { Qt::Key_NumLock, Key_NumLock },
  259. { Qt::Key_O, Key_O },
  260. { Qt::Key_P, Key_P },
  261. { Qt::Key_PageDown, Key_PageDown },
  262. { Qt::Key_PageUp, Key_PageUp },
  263. { Qt::Key_ParenLeft, Key_LeftParen },
  264. { Qt::Key_ParenRight, Key_RightParen },
  265. { Qt::Key_Percent, Key_Percent },
  266. { Qt::Key_Period, Key_Period },
  267. { Qt::Key_Plus, Key_Plus },
  268. { Qt::Key_Print, Key_PrintScreen },
  269. { Qt::Key_Q, Key_Q },
  270. { Qt::Key_Question, Key_QuestionMark },
  271. { Qt::Key_QuoteDbl, Key_DoubleQuote },
  272. { Qt::Key_QuoteLeft, Key_Backtick },
  273. { Qt::Key_R, Key_R },
  274. { Qt::Key_Return, Key_Return },
  275. { Qt::Key_Right, Key_Right },
  276. { Qt::Key_S, Key_S },
  277. { Qt::Key_ScrollLock, Key_ScrollLock },
  278. { Qt::Key_Semicolon, Key_Semicolon },
  279. { Qt::Key_Shift, Key_LeftShift },
  280. { Qt::Key_Slash, Key_Slash },
  281. { Qt::Key_Space, Key_Space },
  282. { Qt::Key_Super_L, Key_Super },
  283. { Qt::Key_Super_R, Key_Super },
  284. { Qt::Key_SysReq, Key_SysRq },
  285. { Qt::Key_T, Key_T },
  286. { Qt::Key_Tab, Key_Tab },
  287. { Qt::Key_U, Key_U },
  288. { Qt::Key_Underscore, Key_Underscore },
  289. { Qt::Key_Up, Key_Up },
  290. { Qt::Key_V, Key_V },
  291. { Qt::Key_W, Key_W },
  292. { Qt::Key_X, Key_X },
  293. { Qt::Key_Y, Key_Y },
  294. { Qt::Key_Z, Key_Z },
  295. };
  296. for (auto const& mapping : mappings) {
  297. if (event.key() == mapping.qt_key)
  298. return mapping.serenity_key;
  299. }
  300. return Key_Invalid;
  301. }
  302. void WebContentView::keyPressEvent(QKeyEvent* event)
  303. {
  304. enqueue_native_event(Web::KeyEvent::Type::KeyDown, *event);
  305. }
  306. void WebContentView::keyReleaseEvent(QKeyEvent* event)
  307. {
  308. enqueue_native_event(Web::KeyEvent::Type::KeyUp, *event);
  309. }
  310. void WebContentView::mouseMoveEvent(QMouseEvent* event)
  311. {
  312. enqueue_native_event(Web::MouseEvent::Type::MouseMove, *event);
  313. }
  314. void WebContentView::mousePressEvent(QMouseEvent* event)
  315. {
  316. enqueue_native_event(Web::MouseEvent::Type::MouseDown, *event);
  317. }
  318. void WebContentView::mouseReleaseEvent(QMouseEvent* event)
  319. {
  320. enqueue_native_event(Web::MouseEvent::Type::MouseUp, *event);
  321. if (event->button() == Qt::MouseButton::BackButton) {
  322. if (on_navigate_back)
  323. on_navigate_back();
  324. } else if (event->button() == Qt::MouseButton::ForwardButton) {
  325. if (on_navigate_forward)
  326. on_navigate_forward();
  327. }
  328. }
  329. void WebContentView::wheelEvent(QWheelEvent* event)
  330. {
  331. if (event->modifiers().testFlag(Qt::ControlModifier)) {
  332. event->ignore();
  333. return;
  334. }
  335. enqueue_native_event(Web::MouseEvent::Type::MouseWheel, *event);
  336. }
  337. void WebContentView::mouseDoubleClickEvent(QMouseEvent* event)
  338. {
  339. enqueue_native_event(Web::MouseEvent::Type::DoubleClick, *event);
  340. }
  341. void WebContentView::dragEnterEvent(QDragEnterEvent* event)
  342. {
  343. if (event->mimeData()->hasUrls())
  344. event->acceptProposedAction();
  345. }
  346. void WebContentView::dropEvent(QDropEvent* event)
  347. {
  348. VERIFY(event->mimeData()->hasUrls());
  349. emit urls_dropped(event->mimeData()->urls());
  350. event->acceptProposedAction();
  351. }
  352. void WebContentView::focusInEvent(QFocusEvent*)
  353. {
  354. client().async_set_has_focus(m_client_state.page_index, true);
  355. }
  356. void WebContentView::focusOutEvent(QFocusEvent*)
  357. {
  358. client().async_set_has_focus(m_client_state.page_index, false);
  359. }
  360. void WebContentView::paintEvent(QPaintEvent*)
  361. {
  362. QPainter painter(viewport());
  363. painter.scale(1 / m_device_pixel_ratio, 1 / m_device_pixel_ratio);
  364. Gfx::Bitmap const* bitmap = nullptr;
  365. Gfx::IntSize bitmap_size;
  366. if (m_client_state.has_usable_bitmap) {
  367. bitmap = m_client_state.front_bitmap.bitmap.ptr();
  368. bitmap_size = m_client_state.front_bitmap.last_painted_size.to_type<int>();
  369. } else {
  370. bitmap = m_backup_bitmap.ptr();
  371. bitmap_size = m_backup_bitmap_size.to_type<int>();
  372. }
  373. if (bitmap) {
  374. QImage q_image(bitmap->scanline_u8(0), bitmap->width(), bitmap->height(), QImage::Format_RGB32);
  375. painter.drawImage(QPoint(0, 0), q_image, QRect(0, 0, bitmap_size.width(), bitmap_size.height()));
  376. if (bitmap_size.width() < width()) {
  377. painter.fillRect(bitmap_size.width(), 0, width() - bitmap_size.width(), bitmap->height(), palette().base());
  378. }
  379. if (bitmap_size.height() < height()) {
  380. painter.fillRect(0, bitmap_size.height(), width(), height() - bitmap_size.height(), palette().base());
  381. }
  382. return;
  383. }
  384. painter.fillRect(rect(), palette().base());
  385. }
  386. void WebContentView::resizeEvent(QResizeEvent* event)
  387. {
  388. QAbstractScrollArea::resizeEvent(event);
  389. update_viewport_rect();
  390. handle_resize();
  391. }
  392. void WebContentView::set_viewport_rect(Gfx::IntRect rect)
  393. {
  394. m_viewport_rect = rect;
  395. client().async_set_viewport_rect(m_client_state.page_index, rect.to_type<Web::DevicePixels>());
  396. }
  397. void WebContentView::set_window_size(Gfx::IntSize size)
  398. {
  399. client().async_set_window_size(m_client_state.page_index, size.to_type<Web::DevicePixels>());
  400. }
  401. void WebContentView::set_window_position(Gfx::IntPoint position)
  402. {
  403. client().async_set_window_position(m_client_state.page_index, position.to_type<Web::DevicePixels>());
  404. }
  405. void WebContentView::set_device_pixel_ratio(double device_pixel_ratio)
  406. {
  407. m_device_pixel_ratio = device_pixel_ratio;
  408. client().async_set_device_pixels_per_css_pixel(m_client_state.page_index, m_device_pixel_ratio * m_zoom_level);
  409. update_viewport_rect();
  410. handle_resize();
  411. }
  412. void WebContentView::update_viewport_rect()
  413. {
  414. auto scaled_width = int(viewport()->width() * m_device_pixel_ratio);
  415. auto scaled_height = int(viewport()->height() * m_device_pixel_ratio);
  416. Gfx::IntRect rect(max(0, horizontalScrollBar()->value()), max(0, verticalScrollBar()->value()), scaled_width, scaled_height);
  417. set_viewport_rect(rect);
  418. }
  419. void WebContentView::update_zoom()
  420. {
  421. client().async_set_device_pixels_per_css_pixel(m_client_state.page_index, m_device_pixel_ratio * m_zoom_level);
  422. update_viewport_rect();
  423. }
  424. void WebContentView::showEvent(QShowEvent* event)
  425. {
  426. QAbstractScrollArea::showEvent(event);
  427. client().async_set_system_visibility_state(m_client_state.page_index, true);
  428. }
  429. void WebContentView::hideEvent(QHideEvent* event)
  430. {
  431. QAbstractScrollArea::hideEvent(event);
  432. client().async_set_system_visibility_state(m_client_state.page_index, false);
  433. }
  434. static Core::AnonymousBuffer make_system_theme_from_qt_palette(QWidget& widget, WebContentView::PaletteMode mode)
  435. {
  436. auto qt_palette = widget.palette();
  437. auto theme_file = mode == WebContentView::PaletteMode::Default ? "Default"sv : "Dark"sv;
  438. auto theme_ini = MUST(Core::Resource::load_from_uri(MUST(String::formatted("resource://themes/{}.ini", theme_file))));
  439. auto theme = Gfx::load_system_theme(theme_ini->filesystem_path().to_byte_string()).release_value_but_fixme_should_propagate_errors();
  440. auto palette_impl = Gfx::PaletteImpl::create_with_anonymous_buffer(theme);
  441. auto palette = Gfx::Palette(move(palette_impl));
  442. auto translate = [&](Gfx::ColorRole gfx_color_role, QPalette::ColorRole qt_color_role) {
  443. auto new_color = Gfx::Color::from_argb(qt_palette.color(qt_color_role).rgba());
  444. palette.set_color(gfx_color_role, new_color);
  445. };
  446. translate(Gfx::ColorRole::ThreedHighlight, QPalette::ColorRole::Light);
  447. translate(Gfx::ColorRole::ThreedShadow1, QPalette::ColorRole::Mid);
  448. translate(Gfx::ColorRole::ThreedShadow2, QPalette::ColorRole::Dark);
  449. translate(Gfx::ColorRole::HoverHighlight, QPalette::ColorRole::Light);
  450. translate(Gfx::ColorRole::Link, QPalette::ColorRole::Link);
  451. translate(Gfx::ColorRole::VisitedLink, QPalette::ColorRole::LinkVisited);
  452. translate(Gfx::ColorRole::Button, QPalette::ColorRole::Button);
  453. translate(Gfx::ColorRole::ButtonText, QPalette::ColorRole::ButtonText);
  454. translate(Gfx::ColorRole::Selection, QPalette::ColorRole::Highlight);
  455. translate(Gfx::ColorRole::SelectionText, QPalette::ColorRole::HighlightedText);
  456. palette.set_flag(Gfx::FlagRole::IsDark, is_using_dark_system_theme(widget));
  457. return theme;
  458. }
  459. void WebContentView::update_palette(PaletteMode mode)
  460. {
  461. client().async_update_system_theme(m_client_state.page_index, make_system_theme_from_qt_palette(*this, mode));
  462. }
  463. void WebContentView::update_screen_rects()
  464. {
  465. auto screens = QGuiApplication::screens();
  466. if (!screens.empty()) {
  467. Vector<Web::DevicePixelRect> screen_rects;
  468. for (auto const& screen : screens) {
  469. auto geometry = screen->geometry();
  470. screen_rects.append(Web::DevicePixelRect(geometry.x(), geometry.y(), geometry.width(), geometry.height()));
  471. }
  472. // FIXME: Update the screens again when QGuiApplication::screenAdded/Removed signals are emitted
  473. // NOTE: The first item in QGuiApplication::screens is always the primary screen.
  474. // This is not specified in the documentation but QGuiApplication::primaryScreen
  475. // always returns the first item in the list if it isn't empty.
  476. client().async_update_screen_rects(m_client_state.page_index, screen_rects, 0);
  477. }
  478. }
  479. void WebContentView::initialize_client(WebView::ViewImplementation::CreateNewClient create_new_client)
  480. {
  481. if (create_new_client == CreateNewClient::Yes) {
  482. m_client_state = {};
  483. Optional<IPC::File> request_server_socket;
  484. if (m_web_content_options.use_lagom_networking == UseLagomNetworking::Yes) {
  485. auto& protocol = static_cast<Ladybird::Application*>(QApplication::instance())->request_server_client;
  486. // FIXME: Fail to open the tab, rather than crashing the whole application if this fails
  487. auto socket = connect_new_request_server_client(*protocol).release_value_but_fixme_should_propagate_errors();
  488. request_server_socket = AK::move(socket);
  489. }
  490. auto candidate_web_content_paths = get_paths_for_helper_process("WebContent"sv).release_value_but_fixme_should_propagate_errors();
  491. auto new_client = launch_web_content_process(*this, candidate_web_content_paths, m_web_content_options, AK::move(request_server_socket)).release_value_but_fixme_should_propagate_errors();
  492. m_client_state.client = new_client;
  493. } else {
  494. m_client_state.client->register_view(m_client_state.page_index, *this);
  495. }
  496. m_client_state.client->on_web_content_process_crash = [this] {
  497. Core::deferred_invoke([this] {
  498. handle_web_content_process_crash();
  499. });
  500. };
  501. m_client_state.client_handle = Web::Crypto::generate_random_uuid().release_value_but_fixme_should_propagate_errors();
  502. client().async_set_window_handle(m_client_state.page_index, m_client_state.client_handle);
  503. client().async_set_device_pixels_per_css_pixel(m_client_state.page_index, m_device_pixel_ratio);
  504. update_palette();
  505. client().async_update_system_fonts(m_client_state.page_index, Gfx::FontDatabase::default_font_query(), Gfx::FontDatabase::fixed_width_font_query(), Gfx::FontDatabase::window_title_font_query());
  506. update_screen_rects();
  507. if (!m_webdriver_content_ipc_path.is_empty())
  508. client().async_connect_to_webdriver(m_client_state.page_index, m_webdriver_content_ipc_path);
  509. }
  510. void WebContentView::update_cursor(Gfx::StandardCursor cursor)
  511. {
  512. switch (cursor) {
  513. case Gfx::StandardCursor::Hidden:
  514. setCursor(Qt::BlankCursor);
  515. break;
  516. case Gfx::StandardCursor::Arrow:
  517. setCursor(Qt::ArrowCursor);
  518. break;
  519. case Gfx::StandardCursor::Crosshair:
  520. setCursor(Qt::CrossCursor);
  521. break;
  522. case Gfx::StandardCursor::IBeam:
  523. setCursor(Qt::IBeamCursor);
  524. break;
  525. case Gfx::StandardCursor::ResizeHorizontal:
  526. setCursor(Qt::SizeHorCursor);
  527. break;
  528. case Gfx::StandardCursor::ResizeVertical:
  529. setCursor(Qt::SizeVerCursor);
  530. break;
  531. case Gfx::StandardCursor::ResizeDiagonalTLBR:
  532. setCursor(Qt::SizeFDiagCursor);
  533. break;
  534. case Gfx::StandardCursor::ResizeDiagonalBLTR:
  535. setCursor(Qt::SizeBDiagCursor);
  536. break;
  537. case Gfx::StandardCursor::ResizeColumn:
  538. setCursor(Qt::SplitHCursor);
  539. break;
  540. case Gfx::StandardCursor::ResizeRow:
  541. setCursor(Qt::SplitVCursor);
  542. break;
  543. case Gfx::StandardCursor::Hand:
  544. setCursor(Qt::PointingHandCursor);
  545. break;
  546. case Gfx::StandardCursor::Help:
  547. setCursor(Qt::WhatsThisCursor);
  548. break;
  549. case Gfx::StandardCursor::Drag:
  550. setCursor(Qt::ClosedHandCursor);
  551. break;
  552. case Gfx::StandardCursor::DragCopy:
  553. setCursor(Qt::DragCopyCursor);
  554. break;
  555. case Gfx::StandardCursor::Move:
  556. setCursor(Qt::DragMoveCursor);
  557. break;
  558. case Gfx::StandardCursor::Wait:
  559. setCursor(Qt::BusyCursor);
  560. break;
  561. case Gfx::StandardCursor::Disallowed:
  562. setCursor(Qt::ForbiddenCursor);
  563. break;
  564. case Gfx::StandardCursor::Eyedropper:
  565. case Gfx::StandardCursor::Zoom:
  566. // FIXME: No corresponding Qt cursors, default to Arrow
  567. default:
  568. setCursor(Qt::ArrowCursor);
  569. break;
  570. }
  571. }
  572. Web::DevicePixelRect WebContentView::viewport_rect() const
  573. {
  574. return m_viewport_rect.to_type<Web::DevicePixels>();
  575. }
  576. QPoint WebContentView::map_point_to_global_position(Gfx::IntPoint position) const
  577. {
  578. return mapToGlobal(QPoint { position.x(), position.y() } / device_pixel_ratio());
  579. }
  580. Gfx::IntPoint WebContentView::to_content_position(Gfx::IntPoint widget_position) const
  581. {
  582. return widget_position.translated(max(0, horizontalScrollBar()->value()), max(0, verticalScrollBar()->value()));
  583. }
  584. Gfx::IntPoint WebContentView::to_widget_position(Gfx::IntPoint content_position) const
  585. {
  586. return content_position.translated(-(max(0, horizontalScrollBar()->value())), -(max(0, verticalScrollBar()->value())));
  587. }
  588. bool WebContentView::event(QEvent* event)
  589. {
  590. // NOTE: We have to implement event() manually as Qt's focus navigation mechanism
  591. // eats all the Tab key presses by default.
  592. if (event->type() == QEvent::KeyPress) {
  593. keyPressEvent(static_cast<QKeyEvent*>(event));
  594. return true;
  595. }
  596. if (event->type() == QEvent::KeyRelease) {
  597. keyReleaseEvent(static_cast<QKeyEvent*>(event));
  598. return true;
  599. }
  600. if (event->type() == QEvent::PaletteChange) {
  601. update_palette();
  602. return QAbstractScrollArea::event(event);
  603. }
  604. if (event->type() == QEvent::ShortcutOverride) {
  605. event->accept();
  606. return true;
  607. }
  608. return QAbstractScrollArea::event(event);
  609. }
  610. ErrorOr<String> WebContentView::dump_layout_tree()
  611. {
  612. return String::from_byte_string(client().dump_layout_tree(m_client_state.page_index));
  613. }
  614. void WebContentView::enqueue_native_event(Web::MouseEvent::Type type, QSinglePointEvent const& event)
  615. {
  616. auto position = to_content_position({ event.position().x() * m_device_pixel_ratio, event.position().y() * m_device_pixel_ratio });
  617. auto screen_position = Gfx::IntPoint { event.globalPosition().x() * m_device_pixel_ratio, event.globalPosition().y() * m_device_pixel_ratio };
  618. auto button = get_button_from_qt_event(event);
  619. auto buttons = get_buttons_from_qt_event(event);
  620. auto modifiers = get_modifiers_from_qt_mouse_event(event);
  621. if (button == 0 && (type == Web::MouseEvent::Type::MouseDown || type == Web::MouseEvent::Type::MouseUp)) {
  622. // We could not convert Qt buttons to something that LibWeb can recognize - don't even bother propagating this
  623. // to the web engine as it will not handle it anyway, and it will (currently) assert.
  624. return;
  625. }
  626. int wheel_delta_x = 0;
  627. int wheel_delta_y = 0;
  628. if (type == Web::MouseEvent::Type::MouseWheel) {
  629. auto const& wheel_event = static_cast<QWheelEvent const&>(event);
  630. if (auto pixel_delta = -wheel_event.pixelDelta(); !pixel_delta.isNull()) {
  631. wheel_delta_x = pixel_delta.x();
  632. wheel_delta_y = pixel_delta.y();
  633. } else {
  634. auto angle_delta = -wheel_event.angleDelta();
  635. float delta_x = -static_cast<float>(angle_delta.x()) / 120.0f;
  636. float delta_y = static_cast<float>(angle_delta.y()) / 120.0f;
  637. auto step_x = delta_x * static_cast<float>(QApplication::wheelScrollLines()) * m_device_pixel_ratio;
  638. auto step_y = delta_y * static_cast<float>(QApplication::wheelScrollLines()) * m_device_pixel_ratio;
  639. auto scroll_step_size = static_cast<float>(verticalScrollBar()->singleStep());
  640. wheel_delta_x = static_cast<int>(step_x * scroll_step_size);
  641. wheel_delta_y = static_cast<int>(step_y * scroll_step_size);
  642. }
  643. }
  644. enqueue_input_event(Web::MouseEvent { type, position.to_type<Web::DevicePixels>(), screen_position.to_type<Web::DevicePixels>(), button, buttons, modifiers, wheel_delta_x, wheel_delta_y, nullptr });
  645. }
  646. struct KeyData : Web::ChromeInputData {
  647. explicit KeyData(QKeyEvent const& event)
  648. : event(adopt_own(*event.clone()))
  649. {
  650. }
  651. NonnullOwnPtr<QKeyEvent> event;
  652. };
  653. void WebContentView::enqueue_native_event(Web::KeyEvent::Type type, QKeyEvent const& event)
  654. {
  655. auto keycode = get_keycode_from_qt_keyboard_event(event);
  656. auto modifiers = get_modifiers_from_qt_keyboard_event(event);
  657. auto text = event.text();
  658. auto code_point = text.isEmpty() ? 0u : event.text()[0].unicode();
  659. auto to_web_event = [&]() -> Web::KeyEvent {
  660. if (event.key() == Qt::Key_Backtab) {
  661. // Qt transforms Shift+Tab into a "Backtab", so we undo that transformation here.
  662. return { type, KeyCode::Key_Tab, Mod_Shift, '\t', make<KeyData>(event) };
  663. }
  664. if (event.key() == Qt::Key_Enter || event.key() == Qt::Key_Return) {
  665. // This ensures consistent behavior between systems that treat Enter as '\n' and '\r\n'
  666. return { type, KeyCode::Key_Return, Mod_Shift, '\n', make<KeyData>(event) };
  667. }
  668. return { type, keycode, modifiers, code_point, make<KeyData>(event) };
  669. };
  670. enqueue_input_event(to_web_event());
  671. }
  672. void WebContentView::finish_handling_key_event(Web::KeyEvent const& key_event)
  673. {
  674. auto& chrome_data = verify_cast<KeyData>(*key_event.chrome_data);
  675. auto& event = *chrome_data.event;
  676. switch (key_event.type) {
  677. case Web::KeyEvent::Type::KeyDown:
  678. QAbstractScrollArea::keyPressEvent(&event);
  679. break;
  680. case Web::KeyEvent::Type::KeyUp:
  681. QAbstractScrollArea::keyReleaseEvent(&event);
  682. break;
  683. }
  684. if (!event.isAccepted())
  685. QApplication::sendEvent(parent(), &event);
  686. }
  687. }