WebContentView.cpp 28 KB

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