WebContentView.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. /*
  2. * Copyright (c) 2022-2023, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2023, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Settings.h"
  8. #include <AK/Assertions.h>
  9. #include <AK/ByteBuffer.h>
  10. #include <AK/Format.h>
  11. #include <AK/LexicalPath.h>
  12. #include <AK/NonnullOwnPtr.h>
  13. #include <AK/Types.h>
  14. #include <LibCore/EventLoop.h>
  15. #include <LibCore/Resource.h>
  16. #include <LibCore/Timer.h>
  17. #include <LibGfx/Bitmap.h>
  18. #include <LibGfx/Font/FontDatabase.h>
  19. #include <LibGfx/ImageFormats/PNGWriter.h>
  20. #include <LibGfx/Palette.h>
  21. #include <LibGfx/Rect.h>
  22. #include <LibGfx/SystemTheme.h>
  23. #include <LibWeb/UIEvents/KeyCode.h>
  24. #include <LibWeb/UIEvents/MouseButton.h>
  25. #include <LibWebView/Application.h>
  26. #include <LibWebView/WebContentClient.h>
  27. #include <UI/Qt/Application.h>
  28. #include <UI/Qt/StringUtils.h>
  29. #include <UI/Qt/WebContentView.h>
  30. #include <QApplication>
  31. #include <QCursor>
  32. #include <QGuiApplication>
  33. #include <QIcon>
  34. #include <QMimeData>
  35. #include <QMouseEvent>
  36. #include <QPaintEvent>
  37. #include <QPainter>
  38. #include <QPalette>
  39. #include <QScrollBar>
  40. #include <QTextEdit>
  41. #include <QTimer>
  42. #include <QToolTip>
  43. namespace Ladybird {
  44. bool is_using_dark_system_theme(QWidget&);
  45. WebContentView::WebContentView(QWidget* window, RefPtr<WebView::WebContentClient> parent_client, size_t page_index)
  46. : QWidget(window)
  47. {
  48. m_client_state.client = parent_client;
  49. m_client_state.page_index = page_index;
  50. setAttribute(Qt::WA_InputMethodEnabled, true);
  51. setMouseTracking(true);
  52. setAcceptDrops(true);
  53. setFocusPolicy(Qt::FocusPolicy::StrongFocus);
  54. m_device_pixel_ratio = devicePixelRatio();
  55. QObject::connect(qGuiApp, &QGuiApplication::screenRemoved, [this](QScreen*) {
  56. update_screen_rects();
  57. });
  58. QObject::connect(qGuiApp, &QGuiApplication::screenAdded, [this](QScreen*) {
  59. update_screen_rects();
  60. });
  61. m_tooltip_hover_timer.setSingleShot(true);
  62. QObject::connect(&m_tooltip_hover_timer, &QTimer::timeout, [this] {
  63. if (m_tooltip_text.has_value())
  64. QToolTip::showText(
  65. QCursor::pos(),
  66. qstring_from_ak_string(m_tooltip_text.value()),
  67. this);
  68. });
  69. initialize_client((parent_client == nullptr) ? CreateNewClient::Yes : CreateNewClient::No);
  70. on_ready_to_paint = [this]() {
  71. update();
  72. };
  73. on_cursor_change = [this](auto cursor) {
  74. update_cursor(cursor);
  75. };
  76. on_request_tooltip_override = [this](auto position, auto const& tooltip) {
  77. m_tooltip_override = true;
  78. if (m_tooltip_hover_timer.isActive())
  79. m_tooltip_hover_timer.stop();
  80. auto tooltip_without_carriage_return = tooltip.contains("\r"sv)
  81. ? tooltip.replace("\r\n"sv, "\n"sv, ReplaceMode::All).replace("\r"sv, "\n"sv, ReplaceMode::All)
  82. : tooltip;
  83. QToolTip::showText(
  84. mapToGlobal(QPoint(position.x(), position.y())),
  85. qstring_from_ak_string(tooltip_without_carriage_return),
  86. this);
  87. };
  88. on_stop_tooltip_override = [this]() {
  89. m_tooltip_override = false;
  90. };
  91. on_enter_tooltip_area = [this](auto const& tooltip) {
  92. m_tooltip_text = tooltip.contains("\r"sv)
  93. ? tooltip.replace("\r\n"sv, "\n"sv, ReplaceMode::All).replace("\r"sv, "\n"sv, ReplaceMode::All)
  94. : tooltip;
  95. };
  96. on_leave_tooltip_area = [this]() {
  97. m_tooltip_text.clear();
  98. };
  99. on_finish_handling_key_event = [this](auto const& event) {
  100. finish_handling_key_event(event);
  101. };
  102. on_finish_handling_drag_event = [this](auto const& event) {
  103. finish_handling_drag_event(event);
  104. };
  105. m_select_dropdown = new QMenu("Select Dropdown", this);
  106. QObject::connect(m_select_dropdown, &QMenu::aboutToHide, this, [this]() {
  107. if (!m_select_dropdown->activeAction())
  108. select_dropdown_closed({});
  109. });
  110. on_request_select_dropdown = [this](Gfx::IntPoint content_position, i32 minimum_width, Vector<Web::HTML::SelectItem> items) {
  111. m_select_dropdown->clear();
  112. m_select_dropdown->setMinimumWidth(minimum_width / device_pixel_ratio());
  113. auto add_menu_item = [this](Web::HTML::SelectItemOption const& item_option, bool in_option_group) {
  114. QAction* action = new QAction(qstring_from_ak_string(in_option_group ? MUST(String::formatted(" {}", item_option.label)) : item_option.label), this);
  115. action->setCheckable(true);
  116. action->setChecked(item_option.selected);
  117. action->setDisabled(item_option.disabled);
  118. action->setData(QVariant(static_cast<uint>(item_option.id)));
  119. QObject::connect(action, &QAction::triggered, this, &WebContentView::select_dropdown_action);
  120. m_select_dropdown->addAction(action);
  121. };
  122. for (auto const& item : items) {
  123. if (item.has<Web::HTML::SelectItemOptionGroup>()) {
  124. auto const& item_option_group = item.get<Web::HTML::SelectItemOptionGroup>();
  125. QAction* subtitle = new QAction(qstring_from_ak_string(item_option_group.label), this);
  126. subtitle->setDisabled(true);
  127. m_select_dropdown->addAction(subtitle);
  128. for (auto const& item_option : item_option_group.items)
  129. add_menu_item(item_option, true);
  130. }
  131. if (item.has<Web::HTML::SelectItemOption>())
  132. add_menu_item(item.get<Web::HTML::SelectItemOption>(), false);
  133. if (item.has<Web::HTML::SelectItemSeparator>())
  134. m_select_dropdown->addSeparator();
  135. }
  136. m_select_dropdown->exec(map_point_to_global_position(content_position));
  137. };
  138. }
  139. WebContentView::~WebContentView() = default;
  140. void WebContentView::select_dropdown_action()
  141. {
  142. QAction* action = qobject_cast<QAction*>(sender());
  143. select_dropdown_closed(action->data().value<uint>());
  144. }
  145. static Web::UIEvents::MouseButton get_button_from_qt_mouse_button(Qt::MouseButton button)
  146. {
  147. if (button == Qt::MouseButton::LeftButton)
  148. return Web::UIEvents::MouseButton::Primary;
  149. if (button == Qt::MouseButton::RightButton)
  150. return Web::UIEvents::MouseButton::Secondary;
  151. if (button == Qt::MouseButton::MiddleButton)
  152. return Web::UIEvents::MouseButton::Middle;
  153. if (button == Qt::MouseButton::BackButton)
  154. return Web::UIEvents::MouseButton::Backward;
  155. if (button == Qt::MouseButton::ForwardButton)
  156. return Web::UIEvents::MouseButton::Forward;
  157. return Web::UIEvents::MouseButton::None;
  158. }
  159. static Web::UIEvents::MouseButton get_buttons_from_qt_mouse_buttons(Qt::MouseButtons buttons)
  160. {
  161. auto result = Web::UIEvents::MouseButton::None;
  162. if (buttons.testFlag(Qt::MouseButton::LeftButton))
  163. result |= Web::UIEvents::MouseButton::Primary;
  164. if (buttons.testFlag(Qt::MouseButton::RightButton))
  165. result |= Web::UIEvents::MouseButton::Secondary;
  166. if (buttons.testFlag(Qt::MouseButton::MiddleButton))
  167. result |= Web::UIEvents::MouseButton::Middle;
  168. if (buttons.testFlag(Qt::MouseButton::BackButton))
  169. result |= Web::UIEvents::MouseButton::Backward;
  170. if (buttons.testFlag(Qt::MouseButton::ForwardButton))
  171. result |= Web::UIEvents::MouseButton::Forward;
  172. return result;
  173. }
  174. static Web::UIEvents::KeyModifier get_modifiers_from_qt_keyboard_modifiers(Qt::KeyboardModifiers modifiers)
  175. {
  176. auto result = Web::UIEvents::KeyModifier::Mod_None;
  177. if (modifiers.testFlag(Qt::AltModifier))
  178. result |= Web::UIEvents::KeyModifier::Mod_Alt;
  179. if (modifiers.testFlag(Qt::ControlModifier))
  180. result |= Web::UIEvents::KeyModifier::Mod_Ctrl;
  181. if (modifiers.testFlag(Qt::ShiftModifier))
  182. result |= Web::UIEvents::KeyModifier::Mod_Shift;
  183. return result;
  184. }
  185. static Web::UIEvents::KeyModifier get_modifiers_from_qt_key_event(QKeyEvent const& event)
  186. {
  187. auto modifiers = Web::UIEvents::KeyModifier::Mod_None;
  188. if (event.modifiers().testFlag(Qt::AltModifier))
  189. modifiers |= Web::UIEvents::KeyModifier::Mod_Alt;
  190. if (event.modifiers().testFlag(Qt::ControlModifier))
  191. modifiers |= Web::UIEvents::KeyModifier::Mod_Ctrl;
  192. if (event.modifiers().testFlag(Qt::MetaModifier))
  193. modifiers |= Web::UIEvents::KeyModifier::Mod_Super;
  194. if (event.modifiers().testFlag(Qt::ShiftModifier))
  195. modifiers |= Web::UIEvents::KeyModifier::Mod_Shift;
  196. if (event.modifiers().testFlag(Qt::KeypadModifier))
  197. modifiers |= Web::UIEvents::KeyModifier::Mod_Keypad;
  198. return modifiers;
  199. }
  200. static Web::UIEvents::KeyCode get_keycode_from_qt_key_event(QKeyEvent const& event)
  201. {
  202. struct Mapping {
  203. constexpr Mapping(Qt::Key q, Web::UIEvents::KeyCode s)
  204. : qt_key(q)
  205. , serenity_key(s)
  206. {
  207. }
  208. Qt::Key qt_key;
  209. Web::UIEvents::KeyCode serenity_key;
  210. };
  211. // FIXME: Qt does not differentiate between left-and-right modifier keys. Unfortunately, it seems like we would have
  212. // to inspect event.nativeScanCode() / event.nativeVirtualKey() to do so, which has platform-dependent values.
  213. // For now, we default to left keys.
  214. // https://doc.qt.io/qt-6/qt.html#Key-enum
  215. static constexpr Mapping mappings[] = {
  216. { Qt::Key_0, Web::UIEvents::Key_0 },
  217. { Qt::Key_1, Web::UIEvents::Key_1 },
  218. { Qt::Key_2, Web::UIEvents::Key_2 },
  219. { Qt::Key_3, Web::UIEvents::Key_3 },
  220. { Qt::Key_4, Web::UIEvents::Key_4 },
  221. { Qt::Key_5, Web::UIEvents::Key_5 },
  222. { Qt::Key_6, Web::UIEvents::Key_6 },
  223. { Qt::Key_7, Web::UIEvents::Key_7 },
  224. { Qt::Key_8, Web::UIEvents::Key_8 },
  225. { Qt::Key_9, Web::UIEvents::Key_9 },
  226. { Qt::Key_A, Web::UIEvents::Key_A },
  227. { Qt::Key_Alt, Web::UIEvents::Key_LeftAlt },
  228. { Qt::Key_Ampersand, Web::UIEvents::Key_Ampersand },
  229. { Qt::Key_Apostrophe, Web::UIEvents::Key_Apostrophe },
  230. { Qt::Key_AsciiCircum, Web::UIEvents::Key_Circumflex },
  231. { Qt::Key_AsciiTilde, Web::UIEvents::Key_Tilde },
  232. { Qt::Key_Asterisk, Web::UIEvents::Key_Asterisk },
  233. { Qt::Key_At, Web::UIEvents::Key_AtSign },
  234. { Qt::Key_B, Web::UIEvents::Key_B },
  235. { Qt::Key_Backslash, Web::UIEvents::Key_Backslash },
  236. { Qt::Key_Backspace, Web::UIEvents::Key_Backspace },
  237. { Qt::Key_Bar, Web::UIEvents::Key_Pipe },
  238. { Qt::Key_BraceLeft, Web::UIEvents::Key_LeftBrace },
  239. { Qt::Key_BraceRight, Web::UIEvents::Key_RightBrace },
  240. { Qt::Key_BracketLeft, Web::UIEvents::Key_LeftBracket },
  241. { Qt::Key_BracketRight, Web::UIEvents::Key_RightBracket },
  242. { Qt::Key_C, Web::UIEvents::Key_C },
  243. { Qt::Key_CapsLock, Web::UIEvents::Key_CapsLock },
  244. { Qt::Key_Colon, Web::UIEvents::Key_Colon },
  245. { Qt::Key_Comma, Web::UIEvents::Key_Comma },
  246. { Qt::Key_Control, Web::UIEvents::Key_LeftControl },
  247. { Qt::Key_D, Web::UIEvents::Key_D },
  248. { Qt::Key_Delete, Web::UIEvents::Key_Delete },
  249. { Qt::Key_Dollar, Web::UIEvents::Key_Dollar },
  250. { Qt::Key_Down, Web::UIEvents::Key_Down },
  251. { Qt::Key_E, Web::UIEvents::Key_E },
  252. { Qt::Key_End, Web::UIEvents::Key_End },
  253. { Qt::Key_Equal, Web::UIEvents::Key_Equal },
  254. { Qt::Key_Enter, Web::UIEvents::Key_Return },
  255. { Qt::Key_Escape, Web::UIEvents::Key_Escape },
  256. { Qt::Key_Exclam, Web::UIEvents::Key_ExclamationPoint },
  257. { Qt::Key_exclamdown, Web::UIEvents::Key_ExclamationPoint },
  258. { Qt::Key_F, Web::UIEvents::Key_F },
  259. { Qt::Key_F1, Web::UIEvents::Key_F1 },
  260. { Qt::Key_F10, Web::UIEvents::Key_F10 },
  261. { Qt::Key_F11, Web::UIEvents::Key_F11 },
  262. { Qt::Key_F12, Web::UIEvents::Key_F12 },
  263. { Qt::Key_F2, Web::UIEvents::Key_F2 },
  264. { Qt::Key_F3, Web::UIEvents::Key_F3 },
  265. { Qt::Key_F4, Web::UIEvents::Key_F4 },
  266. { Qt::Key_F5, Web::UIEvents::Key_F5 },
  267. { Qt::Key_F6, Web::UIEvents::Key_F6 },
  268. { Qt::Key_F7, Web::UIEvents::Key_F7 },
  269. { Qt::Key_F8, Web::UIEvents::Key_F8 },
  270. { Qt::Key_F9, Web::UIEvents::Key_F9 },
  271. { Qt::Key_G, Web::UIEvents::Key_G },
  272. { Qt::Key_Greater, Web::UIEvents::Key_GreaterThan },
  273. { Qt::Key_H, Web::UIEvents::Key_H },
  274. { Qt::Key_Home, Web::UIEvents::Key_Home },
  275. { Qt::Key_I, Web::UIEvents::Key_I },
  276. { Qt::Key_Insert, Web::UIEvents::Key_Insert },
  277. { Qt::Key_J, Web::UIEvents::Key_J },
  278. { Qt::Key_K, Web::UIEvents::Key_K },
  279. { Qt::Key_L, Web::UIEvents::Key_L },
  280. { Qt::Key_Left, Web::UIEvents::Key_Left },
  281. { Qt::Key_Less, Web::UIEvents::Key_LessThan },
  282. { Qt::Key_M, Web::UIEvents::Key_M },
  283. { Qt::Key_Menu, Web::UIEvents::Key_Menu },
  284. { Qt::Key_Meta, Web::UIEvents::Key_LeftSuper },
  285. { Qt::Key_Minus, Web::UIEvents::Key_Minus },
  286. { Qt::Key_N, Web::UIEvents::Key_N },
  287. { Qt::Key_NumberSign, Web::UIEvents::Key_Hashtag },
  288. { Qt::Key_NumLock, Web::UIEvents::Key_NumLock },
  289. { Qt::Key_O, Web::UIEvents::Key_O },
  290. { Qt::Key_P, Web::UIEvents::Key_P },
  291. { Qt::Key_PageDown, Web::UIEvents::Key_PageDown },
  292. { Qt::Key_PageUp, Web::UIEvents::Key_PageUp },
  293. { Qt::Key_ParenLeft, Web::UIEvents::Key_LeftParen },
  294. { Qt::Key_ParenRight, Web::UIEvents::Key_RightParen },
  295. { Qt::Key_Percent, Web::UIEvents::Key_Percent },
  296. { Qt::Key_Period, Web::UIEvents::Key_Period },
  297. { Qt::Key_Plus, Web::UIEvents::Key_Plus },
  298. { Qt::Key_Print, Web::UIEvents::Key_PrintScreen },
  299. { Qt::Key_Q, Web::UIEvents::Key_Q },
  300. { Qt::Key_Question, Web::UIEvents::Key_QuestionMark },
  301. { Qt::Key_QuoteDbl, Web::UIEvents::Key_DoubleQuote },
  302. { Qt::Key_QuoteLeft, Web::UIEvents::Key_Backtick },
  303. { Qt::Key_R, Web::UIEvents::Key_R },
  304. { Qt::Key_Return, Web::UIEvents::Key_Return },
  305. { Qt::Key_Right, Web::UIEvents::Key_Right },
  306. { Qt::Key_S, Web::UIEvents::Key_S },
  307. { Qt::Key_ScrollLock, Web::UIEvents::Key_ScrollLock },
  308. { Qt::Key_Semicolon, Web::UIEvents::Key_Semicolon },
  309. { Qt::Key_Shift, Web::UIEvents::Key_LeftShift },
  310. { Qt::Key_Slash, Web::UIEvents::Key_Slash },
  311. { Qt::Key_Space, Web::UIEvents::Key_Space },
  312. { Qt::Key_Super_L, Web::UIEvents::Key_LeftSuper },
  313. { Qt::Key_Super_R, Web::UIEvents::Key_RightSuper },
  314. { Qt::Key_SysReq, Web::UIEvents::Key_SysRq },
  315. { Qt::Key_T, Web::UIEvents::Key_T },
  316. { Qt::Key_Tab, Web::UIEvents::Key_Tab },
  317. { Qt::Key_U, Web::UIEvents::Key_U },
  318. { Qt::Key_Underscore, Web::UIEvents::Key_Underscore },
  319. { Qt::Key_Up, Web::UIEvents::Key_Up },
  320. { Qt::Key_V, Web::UIEvents::Key_V },
  321. { Qt::Key_W, Web::UIEvents::Key_W },
  322. { Qt::Key_X, Web::UIEvents::Key_X },
  323. { Qt::Key_Y, Web::UIEvents::Key_Y },
  324. { Qt::Key_Z, Web::UIEvents::Key_Z },
  325. };
  326. for (auto const& mapping : mappings) {
  327. if (event.key() == mapping.qt_key)
  328. return mapping.serenity_key;
  329. }
  330. return Web::UIEvents::Key_Invalid;
  331. }
  332. void WebContentView::keyPressEvent(QKeyEvent* event)
  333. {
  334. enqueue_native_event(Web::KeyEvent::Type::KeyDown, *event);
  335. }
  336. void WebContentView::keyReleaseEvent(QKeyEvent* event)
  337. {
  338. enqueue_native_event(Web::KeyEvent::Type::KeyUp, *event);
  339. }
  340. void WebContentView::inputMethodEvent(QInputMethodEvent* event)
  341. {
  342. if (!event->commitString().isEmpty()) {
  343. QKeyEvent keyEvent(QEvent::KeyPress, 0, Qt::NoModifier, event->commitString());
  344. keyPressEvent(&keyEvent);
  345. }
  346. event->accept();
  347. }
  348. QVariant WebContentView::inputMethodQuery(Qt::InputMethodQuery) const
  349. {
  350. return QVariant();
  351. }
  352. void WebContentView::mouseMoveEvent(QMouseEvent* event)
  353. {
  354. if (!m_tooltip_override) {
  355. if (QToolTip::isVisible())
  356. QToolTip::hideText();
  357. m_tooltip_hover_timer.start(600);
  358. }
  359. enqueue_native_event(Web::MouseEvent::Type::MouseMove, *event);
  360. QWidget::mouseMoveEvent(event);
  361. }
  362. void WebContentView::mousePressEvent(QMouseEvent* event)
  363. {
  364. enqueue_native_event(Web::MouseEvent::Type::MouseDown, *event);
  365. }
  366. void WebContentView::mouseReleaseEvent(QMouseEvent* event)
  367. {
  368. enqueue_native_event(Web::MouseEvent::Type::MouseUp, *event);
  369. if (event->button() == Qt::MouseButton::BackButton)
  370. traverse_the_history_by_delta(-1);
  371. else if (event->button() == Qt::MouseButton::ForwardButton)
  372. traverse_the_history_by_delta(1);
  373. }
  374. void WebContentView::wheelEvent(QWheelEvent* event)
  375. {
  376. if (event->modifiers().testFlag(Qt::ControlModifier)) {
  377. event->ignore();
  378. return;
  379. }
  380. enqueue_native_event(Web::MouseEvent::Type::MouseWheel, *event);
  381. }
  382. void WebContentView::mouseDoubleClickEvent(QMouseEvent* event)
  383. {
  384. enqueue_native_event(Web::MouseEvent::Type::DoubleClick, *event);
  385. }
  386. void WebContentView::dragEnterEvent(QDragEnterEvent* event)
  387. {
  388. if (!event->mimeData()->hasUrls())
  389. return;
  390. enqueue_native_event(Web::DragEvent::Type::DragStart, *event);
  391. event->acceptProposedAction();
  392. }
  393. void WebContentView::dragMoveEvent(QDragMoveEvent* event)
  394. {
  395. enqueue_native_event(Web::DragEvent::Type::DragMove, *event);
  396. event->acceptProposedAction();
  397. }
  398. void WebContentView::dragLeaveEvent(QDragLeaveEvent*)
  399. {
  400. // QDragLeaveEvent does not contain any mouse position or button information.
  401. Web::DragEvent event {};
  402. event.type = Web::DragEvent::Type::DragEnd;
  403. enqueue_input_event(AK::move(event));
  404. }
  405. void WebContentView::dropEvent(QDropEvent* event)
  406. {
  407. enqueue_native_event(Web::DragEvent::Type::Drop, *event);
  408. event->acceptProposedAction();
  409. }
  410. void WebContentView::focusInEvent(QFocusEvent*)
  411. {
  412. client().async_set_has_focus(m_client_state.page_index, true);
  413. }
  414. void WebContentView::focusOutEvent(QFocusEvent*)
  415. {
  416. client().async_set_has_focus(m_client_state.page_index, false);
  417. }
  418. void WebContentView::paintEvent(QPaintEvent*)
  419. {
  420. QPainter painter(this);
  421. painter.scale(1 / m_device_pixel_ratio, 1 / m_device_pixel_ratio);
  422. Gfx::Bitmap const* bitmap = nullptr;
  423. Gfx::IntSize bitmap_size;
  424. if (m_client_state.has_usable_bitmap) {
  425. bitmap = m_client_state.front_bitmap.bitmap.ptr();
  426. bitmap_size = m_client_state.front_bitmap.last_painted_size.to_type<int>();
  427. } else {
  428. bitmap = m_backup_bitmap.ptr();
  429. bitmap_size = m_backup_bitmap_size.to_type<int>();
  430. }
  431. if (bitmap) {
  432. QImage q_image(bitmap->scanline_u8(0), bitmap->width(), bitmap->height(), bitmap->pitch(), QImage::Format_RGB32);
  433. painter.drawImage(QPoint(0, 0), q_image, QRect(0, 0, bitmap_size.width(), bitmap_size.height()));
  434. if (bitmap_size.width() < width()) {
  435. painter.fillRect(bitmap_size.width(), 0, width() - bitmap_size.width(), bitmap->height(), palette().base());
  436. }
  437. if (bitmap_size.height() < height()) {
  438. painter.fillRect(0, bitmap_size.height(), width(), height() - bitmap_size.height(), palette().base());
  439. }
  440. return;
  441. }
  442. painter.fillRect(rect(), palette().base());
  443. }
  444. void WebContentView::resizeEvent(QResizeEvent* event)
  445. {
  446. QWidget::resizeEvent(event);
  447. update_viewport_size();
  448. handle_resize();
  449. }
  450. void WebContentView::set_viewport_rect(Gfx::IntRect rect)
  451. {
  452. m_viewport_size = rect.size();
  453. client().async_set_viewport_size(m_client_state.page_index, rect.size().to_type<Web::DevicePixels>());
  454. }
  455. void WebContentView::set_device_pixel_ratio(double device_pixel_ratio)
  456. {
  457. m_device_pixel_ratio = device_pixel_ratio;
  458. client().async_set_device_pixels_per_css_pixel(m_client_state.page_index, m_device_pixel_ratio * m_zoom_level);
  459. update_viewport_size();
  460. handle_resize();
  461. }
  462. void WebContentView::update_viewport_size()
  463. {
  464. auto scaled_width = int(width() * m_device_pixel_ratio);
  465. auto scaled_height = int(height() * m_device_pixel_ratio);
  466. Gfx::IntRect rect(0, 0, scaled_width, scaled_height);
  467. set_viewport_rect(rect);
  468. }
  469. void WebContentView::update_zoom()
  470. {
  471. client().async_set_device_pixels_per_css_pixel(m_client_state.page_index, m_device_pixel_ratio * m_zoom_level);
  472. update_viewport_size();
  473. }
  474. void WebContentView::showEvent(QShowEvent* event)
  475. {
  476. QWidget::showEvent(event);
  477. set_system_visibility_state(Web::HTML::VisibilityState::Visible);
  478. }
  479. void WebContentView::hideEvent(QHideEvent* event)
  480. {
  481. QWidget::hideEvent(event);
  482. set_system_visibility_state(Web::HTML::VisibilityState::Hidden);
  483. }
  484. static Core::AnonymousBuffer make_system_theme_from_qt_palette(QWidget& widget, WebContentView::PaletteMode mode)
  485. {
  486. auto qt_palette = widget.palette();
  487. auto theme_file = mode == WebContentView::PaletteMode::Default ? "Default"sv : "Dark"sv;
  488. auto theme_ini = MUST(Core::Resource::load_from_uri(MUST(String::formatted("resource://themes/{}.ini", theme_file))));
  489. auto theme = Gfx::load_system_theme(theme_ini->filesystem_path().to_byte_string()).release_value_but_fixme_should_propagate_errors();
  490. auto palette_impl = Gfx::PaletteImpl::create_with_anonymous_buffer(theme);
  491. auto palette = Gfx::Palette(move(palette_impl));
  492. auto translate = [&](Gfx::ColorRole gfx_color_role, QPalette::ColorRole qt_color_role) {
  493. auto new_color = Gfx::Color::from_argb(qt_palette.color(qt_color_role).rgba());
  494. palette.set_color(gfx_color_role, new_color);
  495. };
  496. translate(Gfx::ColorRole::ThreedHighlight, QPalette::ColorRole::Light);
  497. translate(Gfx::ColorRole::ThreedShadow1, QPalette::ColorRole::Mid);
  498. translate(Gfx::ColorRole::ThreedShadow2, QPalette::ColorRole::Dark);
  499. translate(Gfx::ColorRole::HoverHighlight, QPalette::ColorRole::Light);
  500. translate(Gfx::ColorRole::Link, QPalette::ColorRole::Link);
  501. translate(Gfx::ColorRole::VisitedLink, QPalette::ColorRole::LinkVisited);
  502. translate(Gfx::ColorRole::Button, QPalette::ColorRole::Button);
  503. translate(Gfx::ColorRole::ButtonText, QPalette::ColorRole::ButtonText);
  504. translate(Gfx::ColorRole::Selection, QPalette::ColorRole::Highlight);
  505. translate(Gfx::ColorRole::SelectionText, QPalette::ColorRole::HighlightedText);
  506. palette.set_flag(Gfx::FlagRole::IsDark, is_using_dark_system_theme(widget));
  507. return theme;
  508. }
  509. void WebContentView::update_palette(PaletteMode mode)
  510. {
  511. client().async_update_system_theme(m_client_state.page_index, make_system_theme_from_qt_palette(*this, mode));
  512. }
  513. void WebContentView::update_screen_rects()
  514. {
  515. auto screens = QGuiApplication::screens();
  516. if (!screens.empty()) {
  517. Vector<Web::DevicePixelRect> screen_rects;
  518. for (auto const& screen : screens) {
  519. // NOTE: QScreen::geometry() returns the 'device-independent pixels', we multiply
  520. // by the device pixel ratio to get the 'physical pixels' of the display.
  521. auto geometry = screen->geometry();
  522. auto device_pixel_ratio = screen->devicePixelRatio();
  523. screen_rects.append(Web::DevicePixelRect(geometry.x(), geometry.y(), geometry.width() * device_pixel_ratio, geometry.height() * device_pixel_ratio));
  524. }
  525. // NOTE: The first item in QGuiApplication::screens is always the primary screen.
  526. // This is not specified in the documentation but QGuiApplication::primaryScreen
  527. // always returns the first item in the list if it isn't empty.
  528. client().async_update_screen_rects(m_client_state.page_index, screen_rects, 0);
  529. }
  530. }
  531. void WebContentView::initialize_client(WebView::ViewImplementation::CreateNewClient create_new_client)
  532. {
  533. ViewImplementation::initialize_client(create_new_client);
  534. update_palette();
  535. update_screen_rects();
  536. }
  537. void WebContentView::update_cursor(Gfx::StandardCursor cursor)
  538. {
  539. switch (cursor) {
  540. case Gfx::StandardCursor::Hidden:
  541. setCursor(Qt::BlankCursor);
  542. break;
  543. case Gfx::StandardCursor::Arrow:
  544. setCursor(Qt::ArrowCursor);
  545. break;
  546. case Gfx::StandardCursor::Crosshair:
  547. setCursor(Qt::CrossCursor);
  548. break;
  549. case Gfx::StandardCursor::IBeam:
  550. setCursor(Qt::IBeamCursor);
  551. break;
  552. case Gfx::StandardCursor::ResizeHorizontal:
  553. setCursor(Qt::SizeHorCursor);
  554. break;
  555. case Gfx::StandardCursor::ResizeVertical:
  556. setCursor(Qt::SizeVerCursor);
  557. break;
  558. case Gfx::StandardCursor::ResizeDiagonalTLBR:
  559. setCursor(Qt::SizeFDiagCursor);
  560. break;
  561. case Gfx::StandardCursor::ResizeDiagonalBLTR:
  562. setCursor(Qt::SizeBDiagCursor);
  563. break;
  564. case Gfx::StandardCursor::ResizeColumn:
  565. setCursor(Qt::SplitHCursor);
  566. break;
  567. case Gfx::StandardCursor::ResizeRow:
  568. setCursor(Qt::SplitVCursor);
  569. break;
  570. case Gfx::StandardCursor::Hand:
  571. setCursor(Qt::PointingHandCursor);
  572. break;
  573. case Gfx::StandardCursor::Help:
  574. setCursor(Qt::WhatsThisCursor);
  575. break;
  576. case Gfx::StandardCursor::Drag:
  577. setCursor(Qt::ClosedHandCursor);
  578. break;
  579. case Gfx::StandardCursor::DragCopy:
  580. setCursor(Qt::DragCopyCursor);
  581. break;
  582. case Gfx::StandardCursor::Move:
  583. setCursor(Qt::DragMoveCursor);
  584. break;
  585. case Gfx::StandardCursor::Wait:
  586. setCursor(Qt::BusyCursor);
  587. break;
  588. case Gfx::StandardCursor::Disallowed:
  589. setCursor(Qt::ForbiddenCursor);
  590. break;
  591. case Gfx::StandardCursor::Eyedropper:
  592. case Gfx::StandardCursor::Zoom:
  593. // FIXME: No corresponding Qt cursors, default to Arrow
  594. default:
  595. setCursor(Qt::ArrowCursor);
  596. break;
  597. }
  598. }
  599. Web::DevicePixelSize WebContentView::viewport_size() const
  600. {
  601. return m_viewport_size.to_type<Web::DevicePixels>();
  602. }
  603. QPoint WebContentView::map_point_to_global_position(Gfx::IntPoint position) const
  604. {
  605. return mapToGlobal(QPoint { position.x(), position.y() } / device_pixel_ratio());
  606. }
  607. Gfx::IntPoint WebContentView::to_content_position(Gfx::IntPoint widget_position) const
  608. {
  609. return widget_position;
  610. }
  611. Gfx::IntPoint WebContentView::to_widget_position(Gfx::IntPoint content_position) const
  612. {
  613. return content_position;
  614. }
  615. bool WebContentView::event(QEvent* event)
  616. {
  617. // NOTE: We have to implement event() manually as Qt's focus navigation mechanism
  618. // eats all the Tab key presses by default.
  619. if (event->type() == QEvent::KeyPress) {
  620. keyPressEvent(static_cast<QKeyEvent*>(event));
  621. return true;
  622. }
  623. if (event->type() == QEvent::KeyRelease) {
  624. keyReleaseEvent(static_cast<QKeyEvent*>(event));
  625. return true;
  626. }
  627. if (event->type() == QEvent::PaletteChange) {
  628. update_palette();
  629. return QWidget::event(event);
  630. }
  631. if (event->type() == QEvent::ShortcutOverride) {
  632. event->accept();
  633. return true;
  634. }
  635. return QWidget::event(event);
  636. }
  637. void WebContentView::enqueue_native_event(Web::MouseEvent::Type type, QSinglePointEvent const& event)
  638. {
  639. Web::DevicePixelPoint position = { event.position().x() * m_device_pixel_ratio, event.position().y() * m_device_pixel_ratio };
  640. auto screen_position = Gfx::IntPoint { event.globalPosition().x() * m_device_pixel_ratio, event.globalPosition().y() * m_device_pixel_ratio };
  641. auto button = get_button_from_qt_mouse_button(event.button());
  642. auto buttons = get_buttons_from_qt_mouse_buttons(event.buttons());
  643. auto modifiers = get_modifiers_from_qt_keyboard_modifiers(event.modifiers());
  644. if (button == 0 && (type == Web::MouseEvent::Type::MouseDown || type == Web::MouseEvent::Type::MouseUp)) {
  645. // We could not convert Qt buttons to something that LibWeb can recognize - don't even bother propagating this
  646. // to the web engine as it will not handle it anyway, and it will (currently) assert.
  647. return;
  648. }
  649. int wheel_delta_x = 0;
  650. int wheel_delta_y = 0;
  651. if (type == Web::MouseEvent::Type::MouseWheel) {
  652. auto const& wheel_event = static_cast<QWheelEvent const&>(event);
  653. if (auto pixel_delta = -wheel_event.pixelDelta(); !pixel_delta.isNull()) {
  654. wheel_delta_x = pixel_delta.x();
  655. wheel_delta_y = pixel_delta.y();
  656. } else {
  657. auto angle_delta = -wheel_event.angleDelta();
  658. float delta_x = -static_cast<float>(angle_delta.x()) / 120.0f;
  659. float delta_y = static_cast<float>(angle_delta.y()) / 120.0f;
  660. static constexpr float scroll_step_size = 24;
  661. auto step_x = delta_x * static_cast<float>(QApplication::wheelScrollLines()) * m_device_pixel_ratio;
  662. auto step_y = delta_y * static_cast<float>(QApplication::wheelScrollLines()) * m_device_pixel_ratio;
  663. wheel_delta_x = static_cast<int>(step_x * scroll_step_size);
  664. wheel_delta_y = static_cast<int>(step_y * scroll_step_size);
  665. }
  666. wheel_delta_x = static_cast<int>(static_cast<double>(wheel_delta_x) * Settings::the()->scrolling_speed() / 100.0);
  667. wheel_delta_y = static_cast<int>(static_cast<double>(wheel_delta_y) * Settings::the()->scrolling_speed() / 100.0);
  668. if (Settings::the()->invert_vertical_scrolling()) {
  669. wheel_delta_y = -wheel_delta_y;
  670. }
  671. if (Settings::the()->invert_horizontal_scrolling()) {
  672. wheel_delta_x = -wheel_delta_x;
  673. }
  674. }
  675. enqueue_input_event(Web::MouseEvent { type, position, screen_position.to_type<Web::DevicePixels>(), button, buttons, modifiers, wheel_delta_x, wheel_delta_y, nullptr });
  676. }
  677. struct DragData : Web::ChromeInputData {
  678. explicit DragData(QDropEvent const& event)
  679. : urls(event.mimeData()->urls())
  680. {
  681. }
  682. QList<QUrl> urls;
  683. };
  684. void WebContentView::enqueue_native_event(Web::DragEvent::Type type, QDropEvent const& event)
  685. {
  686. Web::DevicePixelPoint position = { event.position().x() * m_device_pixel_ratio, event.position().y() * m_device_pixel_ratio };
  687. auto global_position = mapToGlobal(event.position());
  688. auto screen_position = Gfx::IntPoint { global_position.x() * m_device_pixel_ratio, global_position.y() * m_device_pixel_ratio };
  689. auto button = get_button_from_qt_mouse_button(Qt::LeftButton);
  690. auto buttons = get_buttons_from_qt_mouse_buttons(event.buttons());
  691. auto modifiers = get_modifiers_from_qt_keyboard_modifiers(event.modifiers());
  692. Vector<Web::HTML::SelectedFile> files;
  693. OwnPtr<DragData> chrome_data;
  694. if (type == Web::DragEvent::Type::DragStart) {
  695. VERIFY(event.mimeData()->hasUrls());
  696. for (auto const& url : event.mimeData()->urls()) {
  697. auto file_path = ak_byte_string_from_qstring(url.toLocalFile());
  698. if (auto file = Web::HTML::SelectedFile::from_file_path(file_path); file.is_error())
  699. warnln("Unable to open file {}: {}", file_path, file.error());
  700. else
  701. files.append(file.release_value());
  702. }
  703. } else if (type == Web::DragEvent::Type::Drop) {
  704. chrome_data = make<DragData>(event);
  705. }
  706. enqueue_input_event(Web::DragEvent { type, position, screen_position.to_type<Web::DevicePixels>(), button, buttons, modifiers, AK::move(files), AK::move(chrome_data) });
  707. }
  708. void WebContentView::finish_handling_drag_event(Web::DragEvent const& event)
  709. {
  710. if (event.type != Web::DragEvent::Type::Drop)
  711. return;
  712. auto const& chrome_data = verify_cast<DragData>(*event.chrome_data);
  713. emit urls_dropped(chrome_data.urls);
  714. }
  715. struct KeyData : Web::ChromeInputData {
  716. explicit KeyData(QKeyEvent const& event)
  717. : event(adopt_own(*event.clone()))
  718. {
  719. }
  720. NonnullOwnPtr<QKeyEvent> event;
  721. };
  722. void WebContentView::enqueue_native_event(Web::KeyEvent::Type type, QKeyEvent const& event)
  723. {
  724. auto keycode = get_keycode_from_qt_key_event(event);
  725. auto modifiers = get_modifiers_from_qt_key_event(event);
  726. auto text = event.text();
  727. auto code_point = text.isEmpty() ? 0u : event.text()[0].unicode();
  728. auto to_web_event = [&]() -> Web::KeyEvent {
  729. if (event.key() == Qt::Key_Backtab) {
  730. // Qt transforms Shift+Tab into a "Backtab", so we undo that transformation here.
  731. return { type, Web::UIEvents::KeyCode::Key_Tab, Web::UIEvents::Mod_Shift, '\t', event.isAutoRepeat(), make<KeyData>(event) };
  732. }
  733. if (event.key() == Qt::Key_Enter || event.key() == Qt::Key_Return) {
  734. // This ensures consistent behavior between systems that treat Enter as '\n' and '\r\n'
  735. return { type, Web::UIEvents::KeyCode::Key_Return, modifiers, '\n', event.isAutoRepeat(), make<KeyData>(event) };
  736. }
  737. return { type, keycode, modifiers, code_point, event.isAutoRepeat(), make<KeyData>(event) };
  738. };
  739. enqueue_input_event(to_web_event());
  740. }
  741. void WebContentView::finish_handling_key_event(Web::KeyEvent const& key_event)
  742. {
  743. auto& chrome_data = verify_cast<KeyData>(*key_event.chrome_data);
  744. auto& event = *chrome_data.event;
  745. switch (key_event.type) {
  746. case Web::KeyEvent::Type::KeyDown:
  747. QWidget::keyPressEvent(&event);
  748. break;
  749. case Web::KeyEvent::Type::KeyUp:
  750. QWidget::keyReleaseEvent(&event);
  751. break;
  752. }
  753. if (!event.isAccepted())
  754. QApplication::sendEvent(parent(), &event);
  755. }
  756. }