WebContentView.cpp 27 KB

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