WebContentView.cpp 29 KB

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