WebContentView.cpp 34 KB

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