WebContentView.cpp 35 KB

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