WebContentView.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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::AltModifier))
  210. modifiers |= Web::UIEvents::KeyModifier::Mod_AltGr;
  211. if (event.modifiers().testFlag(Qt::KeypadModifier))
  212. modifiers |= Web::UIEvents::KeyModifier::Mod_Keypad;
  213. return modifiers;
  214. }
  215. static Web::UIEvents::KeyCode get_keycode_from_qt_key_event(QKeyEvent const& event)
  216. {
  217. struct Mapping {
  218. constexpr Mapping(Qt::Key q, Web::UIEvents::KeyCode s)
  219. : qt_key(q)
  220. , serenity_key(s)
  221. {
  222. }
  223. Qt::Key qt_key;
  224. Web::UIEvents::KeyCode serenity_key;
  225. };
  226. // https://doc.qt.io/qt-6/qt.html#Key-enum
  227. constexpr Mapping mappings[] = {
  228. { Qt::Key_0, Web::UIEvents::Key_0 },
  229. { Qt::Key_1, Web::UIEvents::Key_1 },
  230. { Qt::Key_2, Web::UIEvents::Key_2 },
  231. { Qt::Key_3, Web::UIEvents::Key_3 },
  232. { Qt::Key_4, Web::UIEvents::Key_4 },
  233. { Qt::Key_5, Web::UIEvents::Key_5 },
  234. { Qt::Key_6, Web::UIEvents::Key_6 },
  235. { Qt::Key_7, Web::UIEvents::Key_7 },
  236. { Qt::Key_8, Web::UIEvents::Key_8 },
  237. { Qt::Key_9, Web::UIEvents::Key_9 },
  238. { Qt::Key_A, Web::UIEvents::Key_A },
  239. { Qt::Key_Alt, Web::UIEvents::Key_Alt },
  240. { Qt::Key_Ampersand, Web::UIEvents::Key_Ampersand },
  241. { Qt::Key_Apostrophe, Web::UIEvents::Key_Apostrophe },
  242. { Qt::Key_AsciiCircum, Web::UIEvents::Key_Circumflex },
  243. { Qt::Key_AsciiTilde, Web::UIEvents::Key_Tilde },
  244. { Qt::Key_Asterisk, Web::UIEvents::Key_Asterisk },
  245. { Qt::Key_At, Web::UIEvents::Key_AtSign },
  246. { Qt::Key_B, Web::UIEvents::Key_B },
  247. { Qt::Key_Backslash, Web::UIEvents::Key_Backslash },
  248. { Qt::Key_Backspace, Web::UIEvents::Key_Backspace },
  249. { Qt::Key_Bar, Web::UIEvents::Key_Pipe },
  250. { Qt::Key_BraceLeft, Web::UIEvents::Key_LeftBrace },
  251. { Qt::Key_BraceRight, Web::UIEvents::Key_RightBrace },
  252. { Qt::Key_BracketLeft, Web::UIEvents::Key_LeftBracket },
  253. { Qt::Key_BracketRight, Web::UIEvents::Key_RightBracket },
  254. { Qt::Key_C, Web::UIEvents::Key_C },
  255. { Qt::Key_CapsLock, Web::UIEvents::Key_CapsLock },
  256. { Qt::Key_Colon, Web::UIEvents::Key_Colon },
  257. { Qt::Key_Comma, Web::UIEvents::Key_Comma },
  258. { Qt::Key_Control, Web::UIEvents::Key_Control },
  259. { Qt::Key_D, Web::UIEvents::Key_D },
  260. { Qt::Key_Delete, Web::UIEvents::Key_Delete },
  261. { Qt::Key_Dollar, Web::UIEvents::Key_Dollar },
  262. { Qt::Key_Down, Web::UIEvents::Key_Down },
  263. { Qt::Key_E, Web::UIEvents::Key_E },
  264. { Qt::Key_End, Web::UIEvents::Key_End },
  265. { Qt::Key_Equal, Web::UIEvents::Key_Equal },
  266. { Qt::Key_Enter, Web::UIEvents::Key_Return },
  267. { Qt::Key_Escape, Web::UIEvents::Key_Escape },
  268. { Qt::Key_Exclam, Web::UIEvents::Key_ExclamationPoint },
  269. { Qt::Key_exclamdown, Web::UIEvents::Key_ExclamationPoint },
  270. { Qt::Key_F, Web::UIEvents::Key_F },
  271. { Qt::Key_F1, Web::UIEvents::Key_F1 },
  272. { Qt::Key_F10, Web::UIEvents::Key_F10 },
  273. { Qt::Key_F11, Web::UIEvents::Key_F11 },
  274. { Qt::Key_F12, Web::UIEvents::Key_F12 },
  275. { Qt::Key_F2, Web::UIEvents::Key_F2 },
  276. { Qt::Key_F3, Web::UIEvents::Key_F3 },
  277. { Qt::Key_F4, Web::UIEvents::Key_F4 },
  278. { Qt::Key_F5, Web::UIEvents::Key_F5 },
  279. { Qt::Key_F6, Web::UIEvents::Key_F6 },
  280. { Qt::Key_F7, Web::UIEvents::Key_F7 },
  281. { Qt::Key_F8, Web::UIEvents::Key_F8 },
  282. { Qt::Key_F9, Web::UIEvents::Key_F9 },
  283. { Qt::Key_G, Web::UIEvents::Key_G },
  284. { Qt::Key_Greater, Web::UIEvents::Key_GreaterThan },
  285. { Qt::Key_H, Web::UIEvents::Key_H },
  286. { Qt::Key_Home, Web::UIEvents::Key_Home },
  287. { Qt::Key_I, Web::UIEvents::Key_I },
  288. { Qt::Key_Insert, Web::UIEvents::Key_Insert },
  289. { Qt::Key_J, Web::UIEvents::Key_J },
  290. { Qt::Key_K, Web::UIEvents::Key_K },
  291. { Qt::Key_L, Web::UIEvents::Key_L },
  292. { Qt::Key_Left, Web::UIEvents::Key_Left },
  293. { Qt::Key_Less, Web::UIEvents::Key_LessThan },
  294. { Qt::Key_M, Web::UIEvents::Key_M },
  295. { Qt::Key_Menu, Web::UIEvents::Key_Menu },
  296. { Qt::Key_Meta, Web::UIEvents::Key_Super },
  297. { Qt::Key_Minus, Web::UIEvents::Key_Minus },
  298. { Qt::Key_N, Web::UIEvents::Key_N },
  299. { Qt::Key_NumberSign, Web::UIEvents::Key_Hashtag },
  300. { Qt::Key_NumLock, Web::UIEvents::Key_NumLock },
  301. { Qt::Key_O, Web::UIEvents::Key_O },
  302. { Qt::Key_P, Web::UIEvents::Key_P },
  303. { Qt::Key_PageDown, Web::UIEvents::Key_PageDown },
  304. { Qt::Key_PageUp, Web::UIEvents::Key_PageUp },
  305. { Qt::Key_ParenLeft, Web::UIEvents::Key_LeftParen },
  306. { Qt::Key_ParenRight, Web::UIEvents::Key_RightParen },
  307. { Qt::Key_Percent, Web::UIEvents::Key_Percent },
  308. { Qt::Key_Period, Web::UIEvents::Key_Period },
  309. { Qt::Key_Plus, Web::UIEvents::Key_Plus },
  310. { Qt::Key_Print, Web::UIEvents::Key_PrintScreen },
  311. { Qt::Key_Q, Web::UIEvents::Key_Q },
  312. { Qt::Key_Question, Web::UIEvents::Key_QuestionMark },
  313. { Qt::Key_QuoteDbl, Web::UIEvents::Key_DoubleQuote },
  314. { Qt::Key_QuoteLeft, Web::UIEvents::Key_Backtick },
  315. { Qt::Key_R, Web::UIEvents::Key_R },
  316. { Qt::Key_Return, Web::UIEvents::Key_Return },
  317. { Qt::Key_Right, Web::UIEvents::Key_Right },
  318. { Qt::Key_S, Web::UIEvents::Key_S },
  319. { Qt::Key_ScrollLock, Web::UIEvents::Key_ScrollLock },
  320. { Qt::Key_Semicolon, Web::UIEvents::Key_Semicolon },
  321. { Qt::Key_Shift, Web::UIEvents::Key_LeftShift },
  322. { Qt::Key_Slash, Web::UIEvents::Key_Slash },
  323. { Qt::Key_Space, Web::UIEvents::Key_Space },
  324. { Qt::Key_Super_L, Web::UIEvents::Key_Super },
  325. { Qt::Key_Super_R, Web::UIEvents::Key_Super },
  326. { Qt::Key_SysReq, Web::UIEvents::Key_SysRq },
  327. { Qt::Key_T, Web::UIEvents::Key_T },
  328. { Qt::Key_Tab, Web::UIEvents::Key_Tab },
  329. { Qt::Key_U, Web::UIEvents::Key_U },
  330. { Qt::Key_Underscore, Web::UIEvents::Key_Underscore },
  331. { Qt::Key_Up, Web::UIEvents::Key_Up },
  332. { Qt::Key_V, Web::UIEvents::Key_V },
  333. { Qt::Key_W, Web::UIEvents::Key_W },
  334. { Qt::Key_X, Web::UIEvents::Key_X },
  335. { Qt::Key_Y, Web::UIEvents::Key_Y },
  336. { Qt::Key_Z, Web::UIEvents::Key_Z },
  337. };
  338. for (auto const& mapping : mappings) {
  339. if (event.key() == mapping.qt_key)
  340. return mapping.serenity_key;
  341. }
  342. return Web::UIEvents::Key_Invalid;
  343. }
  344. void WebContentView::keyPressEvent(QKeyEvent* event)
  345. {
  346. enqueue_native_event(Web::KeyEvent::Type::KeyDown, *event);
  347. }
  348. void WebContentView::keyReleaseEvent(QKeyEvent* event)
  349. {
  350. enqueue_native_event(Web::KeyEvent::Type::KeyUp, *event);
  351. }
  352. void WebContentView::inputMethodEvent(QInputMethodEvent* event)
  353. {
  354. if (!event->commitString().isEmpty()) {
  355. QKeyEvent keyEvent(QEvent::KeyPress, 0, Qt::NoModifier, event->commitString());
  356. keyPressEvent(&keyEvent);
  357. }
  358. event->accept();
  359. }
  360. QVariant WebContentView::inputMethodQuery(Qt::InputMethodQuery) const
  361. {
  362. return QVariant();
  363. }
  364. void WebContentView::mouseMoveEvent(QMouseEvent* event)
  365. {
  366. if (!m_tooltip_override) {
  367. if (QToolTip::isVisible())
  368. QToolTip::hideText();
  369. m_tooltip_hover_timer.start(600);
  370. }
  371. enqueue_native_event(Web::MouseEvent::Type::MouseMove, *event);
  372. }
  373. void WebContentView::mousePressEvent(QMouseEvent* event)
  374. {
  375. enqueue_native_event(Web::MouseEvent::Type::MouseDown, *event);
  376. }
  377. void WebContentView::mouseReleaseEvent(QMouseEvent* event)
  378. {
  379. enqueue_native_event(Web::MouseEvent::Type::MouseUp, *event);
  380. if (event->button() == Qt::MouseButton::BackButton)
  381. traverse_the_history_by_delta(-1);
  382. else if (event->button() == Qt::MouseButton::ForwardButton)
  383. traverse_the_history_by_delta(1);
  384. }
  385. void WebContentView::wheelEvent(QWheelEvent* event)
  386. {
  387. if (event->modifiers().testFlag(Qt::ControlModifier)) {
  388. event->ignore();
  389. return;
  390. }
  391. enqueue_native_event(Web::MouseEvent::Type::MouseWheel, *event);
  392. }
  393. void WebContentView::mouseDoubleClickEvent(QMouseEvent* event)
  394. {
  395. enqueue_native_event(Web::MouseEvent::Type::DoubleClick, *event);
  396. }
  397. void WebContentView::dragEnterEvent(QDragEnterEvent* event)
  398. {
  399. if (!event->mimeData()->hasUrls())
  400. return;
  401. enqueue_native_event(Web::DragEvent::Type::DragStart, *event);
  402. event->acceptProposedAction();
  403. }
  404. void WebContentView::dragMoveEvent(QDragMoveEvent* event)
  405. {
  406. enqueue_native_event(Web::DragEvent::Type::DragMove, *event);
  407. event->acceptProposedAction();
  408. }
  409. void WebContentView::dragLeaveEvent(QDragLeaveEvent*)
  410. {
  411. // QDragLeaveEvent does not contain any mouse position or button information.
  412. Web::DragEvent event {};
  413. event.type = Web::DragEvent::Type::DragEnd;
  414. enqueue_input_event(AK::move(event));
  415. }
  416. void WebContentView::dropEvent(QDropEvent* event)
  417. {
  418. enqueue_native_event(Web::DragEvent::Type::Drop, *event);
  419. event->acceptProposedAction();
  420. }
  421. void WebContentView::focusInEvent(QFocusEvent*)
  422. {
  423. client().async_set_has_focus(m_client_state.page_index, true);
  424. }
  425. void WebContentView::focusOutEvent(QFocusEvent*)
  426. {
  427. client().async_set_has_focus(m_client_state.page_index, false);
  428. }
  429. void WebContentView::paintEvent(QPaintEvent*)
  430. {
  431. QPainter painter(viewport());
  432. painter.scale(1 / m_device_pixel_ratio, 1 / m_device_pixel_ratio);
  433. Gfx::Bitmap const* bitmap = nullptr;
  434. Gfx::IntSize bitmap_size;
  435. if (m_client_state.has_usable_bitmap) {
  436. bitmap = m_client_state.front_bitmap.bitmap.ptr();
  437. bitmap_size = m_client_state.front_bitmap.last_painted_size.to_type<int>();
  438. } else {
  439. bitmap = m_backup_bitmap.ptr();
  440. bitmap_size = m_backup_bitmap_size.to_type<int>();
  441. }
  442. if (bitmap) {
  443. QImage q_image(bitmap->scanline_u8(0), bitmap->width(), bitmap->height(), bitmap->pitch(), QImage::Format_RGB32);
  444. painter.drawImage(QPoint(0, 0), q_image, QRect(0, 0, bitmap_size.width(), bitmap_size.height()));
  445. if (bitmap_size.width() < width()) {
  446. painter.fillRect(bitmap_size.width(), 0, width() - bitmap_size.width(), bitmap->height(), palette().base());
  447. }
  448. if (bitmap_size.height() < height()) {
  449. painter.fillRect(0, bitmap_size.height(), width(), height() - bitmap_size.height(), palette().base());
  450. }
  451. return;
  452. }
  453. painter.fillRect(rect(), palette().base());
  454. }
  455. void WebContentView::resizeEvent(QResizeEvent* event)
  456. {
  457. QAbstractScrollArea::resizeEvent(event);
  458. update_viewport_size();
  459. handle_resize();
  460. }
  461. void WebContentView::set_viewport_rect(Gfx::IntRect rect)
  462. {
  463. m_viewport_size = rect.size();
  464. client().async_set_viewport_size(m_client_state.page_index, rect.size().to_type<Web::DevicePixels>());
  465. }
  466. void WebContentView::set_window_size(Gfx::IntSize size)
  467. {
  468. client().async_set_window_size(m_client_state.page_index, size.to_type<Web::DevicePixels>());
  469. }
  470. void WebContentView::set_window_position(Gfx::IntPoint position)
  471. {
  472. client().async_set_window_position(m_client_state.page_index, position.to_type<Web::DevicePixels>());
  473. }
  474. void WebContentView::set_device_pixel_ratio(double device_pixel_ratio)
  475. {
  476. m_device_pixel_ratio = device_pixel_ratio;
  477. client().async_set_device_pixels_per_css_pixel(m_client_state.page_index, m_device_pixel_ratio * m_zoom_level);
  478. update_viewport_size();
  479. handle_resize();
  480. }
  481. void WebContentView::update_viewport_size()
  482. {
  483. auto scaled_width = int(viewport()->width() * m_device_pixel_ratio);
  484. auto scaled_height = int(viewport()->height() * m_device_pixel_ratio);
  485. Gfx::IntRect rect(0, 0, scaled_width, scaled_height);
  486. set_viewport_rect(rect);
  487. }
  488. void WebContentView::update_zoom()
  489. {
  490. client().async_set_device_pixels_per_css_pixel(m_client_state.page_index, m_device_pixel_ratio * m_zoom_level);
  491. update_viewport_size();
  492. }
  493. void WebContentView::showEvent(QShowEvent* event)
  494. {
  495. QAbstractScrollArea::showEvent(event);
  496. client().async_set_system_visibility_state(m_client_state.page_index, true);
  497. }
  498. void WebContentView::hideEvent(QHideEvent* event)
  499. {
  500. QAbstractScrollArea::hideEvent(event);
  501. client().async_set_system_visibility_state(m_client_state.page_index, false);
  502. }
  503. static Core::AnonymousBuffer make_system_theme_from_qt_palette(QWidget& widget, WebContentView::PaletteMode mode)
  504. {
  505. auto qt_palette = widget.palette();
  506. auto theme_file = mode == WebContentView::PaletteMode::Default ? "Default"sv : "Dark"sv;
  507. auto theme_ini = MUST(Core::Resource::load_from_uri(MUST(String::formatted("resource://themes/{}.ini", theme_file))));
  508. auto theme = Gfx::load_system_theme(theme_ini->filesystem_path().to_byte_string()).release_value_but_fixme_should_propagate_errors();
  509. auto palette_impl = Gfx::PaletteImpl::create_with_anonymous_buffer(theme);
  510. auto palette = Gfx::Palette(move(palette_impl));
  511. auto translate = [&](Gfx::ColorRole gfx_color_role, QPalette::ColorRole qt_color_role) {
  512. auto new_color = Gfx::Color::from_argb(qt_palette.color(qt_color_role).rgba());
  513. palette.set_color(gfx_color_role, new_color);
  514. };
  515. translate(Gfx::ColorRole::ThreedHighlight, QPalette::ColorRole::Light);
  516. translate(Gfx::ColorRole::ThreedShadow1, QPalette::ColorRole::Mid);
  517. translate(Gfx::ColorRole::ThreedShadow2, QPalette::ColorRole::Dark);
  518. translate(Gfx::ColorRole::HoverHighlight, QPalette::ColorRole::Light);
  519. translate(Gfx::ColorRole::Link, QPalette::ColorRole::Link);
  520. translate(Gfx::ColorRole::VisitedLink, QPalette::ColorRole::LinkVisited);
  521. translate(Gfx::ColorRole::Button, QPalette::ColorRole::Button);
  522. translate(Gfx::ColorRole::ButtonText, QPalette::ColorRole::ButtonText);
  523. translate(Gfx::ColorRole::Selection, QPalette::ColorRole::Highlight);
  524. translate(Gfx::ColorRole::SelectionText, QPalette::ColorRole::HighlightedText);
  525. palette.set_flag(Gfx::FlagRole::IsDark, is_using_dark_system_theme(widget));
  526. return theme;
  527. }
  528. void WebContentView::update_palette(PaletteMode mode)
  529. {
  530. client().async_update_system_theme(m_client_state.page_index, make_system_theme_from_qt_palette(*this, mode));
  531. }
  532. void WebContentView::update_screen_rects()
  533. {
  534. auto screens = QGuiApplication::screens();
  535. if (!screens.empty()) {
  536. Vector<Web::DevicePixelRect> screen_rects;
  537. for (auto const& screen : screens) {
  538. // NOTE: QScreen::geometry() returns the 'device-independent pixels', we multiply
  539. // by the device pixel ratio to get the 'physical pixels' of the display.
  540. auto geometry = screen->geometry();
  541. auto device_pixel_ratio = screen->devicePixelRatio();
  542. screen_rects.append(Web::DevicePixelRect(geometry.x(), geometry.y(), geometry.width() * device_pixel_ratio, geometry.height() * device_pixel_ratio));
  543. }
  544. // NOTE: The first item in QGuiApplication::screens is always the primary screen.
  545. // This is not specified in the documentation but QGuiApplication::primaryScreen
  546. // always returns the first item in the list if it isn't empty.
  547. client().async_update_screen_rects(m_client_state.page_index, screen_rects, 0);
  548. }
  549. }
  550. void WebContentView::initialize_client(WebView::ViewImplementation::CreateNewClient create_new_client)
  551. {
  552. if (create_new_client == CreateNewClient::Yes) {
  553. m_client_state = {};
  554. auto& request_server_client = static_cast<Ladybird::Application*>(QApplication::instance())->request_server_client;
  555. // FIXME: Fail to open the tab, rather than crashing the whole application if this fails
  556. auto request_server_socket = connect_new_request_server_client(*request_server_client).release_value_but_fixme_should_propagate_errors();
  557. auto image_decoder = static_cast<Ladybird::Application*>(QApplication::instance())->image_decoder_client();
  558. auto image_decoder_socket = connect_new_image_decoder_client(*image_decoder).release_value_but_fixme_should_propagate_errors();
  559. auto candidate_web_content_paths = get_paths_for_helper_process("WebContent"sv).release_value_but_fixme_should_propagate_errors();
  560. 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();
  561. m_client_state.client = new_client;
  562. } else {
  563. m_client_state.client->register_view(m_client_state.page_index, *this);
  564. }
  565. m_client_state.client->on_web_content_process_crash = [this] {
  566. Core::deferred_invoke([this] {
  567. handle_web_content_process_crash();
  568. });
  569. };
  570. m_client_state.client_handle = Web::Crypto::generate_random_uuid().release_value_but_fixme_should_propagate_errors();
  571. client().async_set_window_handle(m_client_state.page_index, m_client_state.client_handle);
  572. client().async_set_device_pixels_per_css_pixel(m_client_state.page_index, m_device_pixel_ratio);
  573. update_palette();
  574. update_screen_rects();
  575. if (auto webdriver_content_ipc_path = WebView::Application::chrome_options().webdriver_content_ipc_path; webdriver_content_ipc_path.has_value())
  576. client().async_connect_to_webdriver(m_client_state.page_index, *webdriver_content_ipc_path);
  577. }
  578. void WebContentView::update_cursor(Gfx::StandardCursor cursor)
  579. {
  580. switch (cursor) {
  581. case Gfx::StandardCursor::Hidden:
  582. setCursor(Qt::BlankCursor);
  583. break;
  584. case Gfx::StandardCursor::Arrow:
  585. setCursor(Qt::ArrowCursor);
  586. break;
  587. case Gfx::StandardCursor::Crosshair:
  588. setCursor(Qt::CrossCursor);
  589. break;
  590. case Gfx::StandardCursor::IBeam:
  591. setCursor(Qt::IBeamCursor);
  592. break;
  593. case Gfx::StandardCursor::ResizeHorizontal:
  594. setCursor(Qt::SizeHorCursor);
  595. break;
  596. case Gfx::StandardCursor::ResizeVertical:
  597. setCursor(Qt::SizeVerCursor);
  598. break;
  599. case Gfx::StandardCursor::ResizeDiagonalTLBR:
  600. setCursor(Qt::SizeFDiagCursor);
  601. break;
  602. case Gfx::StandardCursor::ResizeDiagonalBLTR:
  603. setCursor(Qt::SizeBDiagCursor);
  604. break;
  605. case Gfx::StandardCursor::ResizeColumn:
  606. setCursor(Qt::SplitHCursor);
  607. break;
  608. case Gfx::StandardCursor::ResizeRow:
  609. setCursor(Qt::SplitVCursor);
  610. break;
  611. case Gfx::StandardCursor::Hand:
  612. setCursor(Qt::PointingHandCursor);
  613. break;
  614. case Gfx::StandardCursor::Help:
  615. setCursor(Qt::WhatsThisCursor);
  616. break;
  617. case Gfx::StandardCursor::Drag:
  618. setCursor(Qt::ClosedHandCursor);
  619. break;
  620. case Gfx::StandardCursor::DragCopy:
  621. setCursor(Qt::DragCopyCursor);
  622. break;
  623. case Gfx::StandardCursor::Move:
  624. setCursor(Qt::DragMoveCursor);
  625. break;
  626. case Gfx::StandardCursor::Wait:
  627. setCursor(Qt::BusyCursor);
  628. break;
  629. case Gfx::StandardCursor::Disallowed:
  630. setCursor(Qt::ForbiddenCursor);
  631. break;
  632. case Gfx::StandardCursor::Eyedropper:
  633. case Gfx::StandardCursor::Zoom:
  634. // FIXME: No corresponding Qt cursors, default to Arrow
  635. default:
  636. setCursor(Qt::ArrowCursor);
  637. break;
  638. }
  639. }
  640. Web::DevicePixelSize WebContentView::viewport_size() const
  641. {
  642. return m_viewport_size.to_type<Web::DevicePixels>();
  643. }
  644. QPoint WebContentView::map_point_to_global_position(Gfx::IntPoint position) const
  645. {
  646. return mapToGlobal(QPoint { position.x(), position.y() } / device_pixel_ratio());
  647. }
  648. Gfx::IntPoint WebContentView::to_content_position(Gfx::IntPoint widget_position) const
  649. {
  650. return widget_position;
  651. }
  652. Gfx::IntPoint WebContentView::to_widget_position(Gfx::IntPoint content_position) const
  653. {
  654. return content_position;
  655. }
  656. bool WebContentView::event(QEvent* event)
  657. {
  658. // NOTE: We have to implement event() manually as Qt's focus navigation mechanism
  659. // eats all the Tab key presses by default.
  660. if (event->type() == QEvent::KeyPress) {
  661. keyPressEvent(static_cast<QKeyEvent*>(event));
  662. return true;
  663. }
  664. if (event->type() == QEvent::KeyRelease) {
  665. keyReleaseEvent(static_cast<QKeyEvent*>(event));
  666. return true;
  667. }
  668. if (event->type() == QEvent::PaletteChange) {
  669. update_palette();
  670. return QAbstractScrollArea::event(event);
  671. }
  672. if (event->type() == QEvent::ShortcutOverride) {
  673. event->accept();
  674. return true;
  675. }
  676. return QAbstractScrollArea::event(event);
  677. }
  678. void WebContentView::enqueue_native_event(Web::MouseEvent::Type type, QSinglePointEvent const& event)
  679. {
  680. Web::DevicePixelPoint position = { event.position().x() * m_device_pixel_ratio, event.position().y() * m_device_pixel_ratio };
  681. auto screen_position = Gfx::IntPoint { event.globalPosition().x() * m_device_pixel_ratio, event.globalPosition().y() * m_device_pixel_ratio };
  682. auto button = get_button_from_qt_mouse_button(event.button());
  683. auto buttons = get_buttons_from_qt_mouse_buttons(event.buttons());
  684. auto modifiers = get_modifiers_from_qt_keyboard_modifiers(event.modifiers());
  685. if (button == 0 && (type == Web::MouseEvent::Type::MouseDown || type == Web::MouseEvent::Type::MouseUp)) {
  686. // We could not convert Qt buttons to something that LibWeb can recognize - don't even bother propagating this
  687. // to the web engine as it will not handle it anyway, and it will (currently) assert.
  688. return;
  689. }
  690. int wheel_delta_x = 0;
  691. int wheel_delta_y = 0;
  692. if (type == Web::MouseEvent::Type::MouseWheel) {
  693. auto const& wheel_event = static_cast<QWheelEvent const&>(event);
  694. if (auto pixel_delta = -wheel_event.pixelDelta(); !pixel_delta.isNull()) {
  695. wheel_delta_x = pixel_delta.x();
  696. wheel_delta_y = pixel_delta.y();
  697. } else {
  698. auto angle_delta = -wheel_event.angleDelta();
  699. float delta_x = -static_cast<float>(angle_delta.x()) / 120.0f;
  700. float delta_y = static_cast<float>(angle_delta.y()) / 120.0f;
  701. auto step_x = delta_x * static_cast<float>(QApplication::wheelScrollLines()) * m_device_pixel_ratio;
  702. auto step_y = delta_y * static_cast<float>(QApplication::wheelScrollLines()) * m_device_pixel_ratio;
  703. auto scroll_step_size = static_cast<float>(verticalScrollBar()->singleStep());
  704. wheel_delta_x = static_cast<int>(step_x * scroll_step_size);
  705. wheel_delta_y = static_cast<int>(step_y * scroll_step_size);
  706. }
  707. }
  708. enqueue_input_event(Web::MouseEvent { type, position, screen_position.to_type<Web::DevicePixels>(), button, buttons, modifiers, wheel_delta_x, wheel_delta_y, nullptr });
  709. }
  710. struct DragData : Web::ChromeInputData {
  711. explicit DragData(QDropEvent const& event)
  712. : urls(event.mimeData()->urls())
  713. {
  714. }
  715. QList<QUrl> urls;
  716. };
  717. void WebContentView::enqueue_native_event(Web::DragEvent::Type type, QDropEvent const& event)
  718. {
  719. Web::DevicePixelPoint position = { event.position().x() * m_device_pixel_ratio, event.position().y() * m_device_pixel_ratio };
  720. auto global_position = mapToGlobal(event.position());
  721. auto screen_position = Gfx::IntPoint { global_position.x() * m_device_pixel_ratio, global_position.y() * m_device_pixel_ratio };
  722. auto button = get_button_from_qt_mouse_button(Qt::LeftButton);
  723. auto buttons = get_buttons_from_qt_mouse_buttons(event.buttons());
  724. auto modifiers = get_modifiers_from_qt_keyboard_modifiers(event.modifiers());
  725. Vector<Web::HTML::SelectedFile> files;
  726. OwnPtr<DragData> chrome_data;
  727. if (type == Web::DragEvent::Type::DragStart) {
  728. VERIFY(event.mimeData()->hasUrls());
  729. for (auto const& url : event.mimeData()->urls()) {
  730. auto file_path = ak_byte_string_from_qstring(url.toLocalFile());
  731. if (auto file = Web::HTML::SelectedFile::from_file_path(file_path); file.is_error())
  732. warnln("Unable to open file {}: {}", file_path, file.error());
  733. else
  734. files.append(file.release_value());
  735. }
  736. } else if (type == Web::DragEvent::Type::Drop) {
  737. chrome_data = make<DragData>(event);
  738. }
  739. enqueue_input_event(Web::DragEvent { type, position, screen_position.to_type<Web::DevicePixels>(), button, buttons, modifiers, AK::move(files), AK::move(chrome_data) });
  740. }
  741. void WebContentView::finish_handling_drag_event(Web::DragEvent const& event)
  742. {
  743. if (event.type != Web::DragEvent::Type::Drop)
  744. return;
  745. auto const& chrome_data = verify_cast<DragData>(*event.chrome_data);
  746. emit urls_dropped(chrome_data.urls);
  747. }
  748. struct KeyData : Web::ChromeInputData {
  749. explicit KeyData(QKeyEvent const& event)
  750. : event(adopt_own(*event.clone()))
  751. {
  752. }
  753. NonnullOwnPtr<QKeyEvent> event;
  754. };
  755. void WebContentView::enqueue_native_event(Web::KeyEvent::Type type, QKeyEvent const& event)
  756. {
  757. auto keycode = get_keycode_from_qt_key_event(event);
  758. auto modifiers = get_modifiers_from_qt_key_event(event);
  759. auto text = event.text();
  760. auto code_point = text.isEmpty() ? 0u : event.text()[0].unicode();
  761. auto to_web_event = [&]() -> Web::KeyEvent {
  762. if (event.key() == Qt::Key_Backtab) {
  763. // Qt transforms Shift+Tab into a "Backtab", so we undo that transformation here.
  764. return { type, Web::UIEvents::KeyCode::Key_Tab, Web::UIEvents::Mod_Shift, '\t', make<KeyData>(event) };
  765. }
  766. if (event.key() == Qt::Key_Enter || event.key() == Qt::Key_Return) {
  767. // This ensures consistent behavior between systems that treat Enter as '\n' and '\r\n'
  768. return { type, Web::UIEvents::KeyCode::Key_Return, Web::UIEvents::Mod_Shift, '\n', make<KeyData>(event) };
  769. }
  770. return { type, keycode, modifiers, code_point, make<KeyData>(event) };
  771. };
  772. enqueue_input_event(to_web_event());
  773. }
  774. void WebContentView::finish_handling_key_event(Web::KeyEvent const& key_event)
  775. {
  776. auto& chrome_data = verify_cast<KeyData>(*key_event.chrome_data);
  777. auto& event = *chrome_data.event;
  778. switch (key_event.type) {
  779. case Web::KeyEvent::Type::KeyDown:
  780. QAbstractScrollArea::keyPressEvent(&event);
  781. break;
  782. case Web::KeyEvent::Type::KeyUp:
  783. QAbstractScrollArea::keyReleaseEvent(&event);
  784. break;
  785. }
  786. if (!event.isAccepted())
  787. QApplication::sendEvent(parent(), &event);
  788. }
  789. }