/qtbase/src/widgets/kernel/qwidgetwindow.cpp

https://bitbucket.org/lotiuss/qt-5.11.0 · C++ · 1091 lines · 857 code · 128 blank · 106 comment · 229 complexity · c0f9c8119286a7e0aae8da53bc5b8bcd MD5 · raw file

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2016 The Qt Company Ltd.
  4. ** Contact: https://www.qt.io/licensing/
  5. **
  6. ** This file is part of the QtWidgets module of the Qt Toolkit.
  7. **
  8. ** $QT_BEGIN_LICENSE:LGPL$
  9. ** Commercial License Usage
  10. ** Licensees holding valid commercial Qt licenses may use this file in
  11. ** accordance with the commercial license agreement provided with the
  12. ** Software or, alternatively, in accordance with the terms contained in
  13. ** a written agreement between you and The Qt Company. For licensing terms
  14. ** and conditions see https://www.qt.io/terms-conditions. For further
  15. ** information use the contact form at https://www.qt.io/contact-us.
  16. **
  17. ** GNU Lesser General Public License Usage
  18. ** Alternatively, this file may be used under the terms of the GNU Lesser
  19. ** General Public License version 3 as published by the Free Software
  20. ** Foundation and appearing in the file LICENSE.LGPL3 included in the
  21. ** packaging of this file. Please review the following information to
  22. ** ensure the GNU Lesser General Public License version 3 requirements
  23. ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
  24. **
  25. ** GNU General Public License Usage
  26. ** Alternatively, this file may be used under the terms of the GNU
  27. ** General Public License version 2.0 or (at your option) the GNU General
  28. ** Public license version 3 or any later version approved by the KDE Free
  29. ** Qt Foundation. The licenses are as published by the Free Software
  30. ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
  31. ** included in the packaging of this file. Please review the following
  32. ** information to ensure the GNU General Public License requirements will
  33. ** be met: https://www.gnu.org/licenses/gpl-2.0.html and
  34. ** https://www.gnu.org/licenses/gpl-3.0.html.
  35. **
  36. ** $QT_END_LICENSE$
  37. **
  38. ****************************************************************************/
  39. #include "private/qwindow_p.h"
  40. #include "qwidgetwindow_p.h"
  41. #include "qlayout.h"
  42. #include "private/qwidget_p.h"
  43. #include "private/qapplication_p.h"
  44. #ifndef QT_NO_ACCESSIBILITY
  45. #include <QtGui/qaccessible.h>
  46. #endif
  47. #include <private/qwidgetbackingstore_p.h>
  48. #include <qpa/qwindowsysteminterface_p.h>
  49. #include <qpa/qplatformtheme.h>
  50. #include <qpa/qplatformwindow.h>
  51. #include <private/qgesturemanager_p.h>
  52. #include <private/qhighdpiscaling_p.h>
  53. QT_BEGIN_NAMESPACE
  54. Q_WIDGETS_EXPORT extern bool qt_tab_all_widgets();
  55. Q_WIDGETS_EXPORT QWidget *qt_button_down = 0; // widget got last button-down
  56. // popup control
  57. QWidget *qt_popup_down = 0; // popup that contains the pressed widget
  58. extern int openPopupCount;
  59. bool qt_replay_popup_mouse_event = false;
  60. extern bool qt_try_modal(QWidget *widget, QEvent::Type type);
  61. class QWidgetWindowPrivate : public QWindowPrivate
  62. {
  63. Q_DECLARE_PUBLIC(QWidgetWindow)
  64. public:
  65. void setVisible(bool visible) override
  66. {
  67. Q_Q(QWidgetWindow);
  68. if (QWidget *widget = q->widget())
  69. widget->setVisible(visible);
  70. else
  71. QWindowPrivate::setVisible(visible);
  72. }
  73. QWindow *eventReceiver() override {
  74. Q_Q(QWidgetWindow);
  75. QWindow *w = q;
  76. while (w->parent() && qobject_cast<QWidgetWindow *>(w) && qobject_cast<QWidgetWindow *>(w->parent())) {
  77. w = w->parent();
  78. }
  79. return w;
  80. }
  81. void clearFocusObject() override
  82. {
  83. Q_Q(QWidgetWindow);
  84. QWidget *widget = q->widget();
  85. if (widget && widget->focusWidget())
  86. widget->focusWidget()->clearFocus();
  87. }
  88. QRectF closestAcceptableGeometry(const QRectF &rect) const override;
  89. #if QT_CONFIG(opengl)
  90. QOpenGLContext *shareContext() const override;
  91. #endif
  92. void processSafeAreaMarginsChanged() override
  93. {
  94. Q_Q(QWidgetWindow);
  95. if (QWidget *widget = q->widget())
  96. QWidgetPrivate::get(widget)->updateContentsRect();
  97. }
  98. };
  99. QRectF QWidgetWindowPrivate::closestAcceptableGeometry(const QRectF &rect) const
  100. {
  101. Q_Q(const QWidgetWindow);
  102. const QWidget *widget = q->widget();
  103. if (!widget || !widget->isWindow() || !widget->hasHeightForWidth())
  104. return QRect();
  105. const QSize oldSize = rect.size().toSize();
  106. const QSize newSize = QLayout::closestAcceptableSize(widget, oldSize);
  107. if (newSize == oldSize)
  108. return QRectF();
  109. const int dw = newSize.width() - oldSize.width();
  110. const int dh = newSize.height() - oldSize.height();
  111. QRectF result = rect;
  112. const QRectF currentGeometry(widget->geometry());
  113. const qreal topOffset = result.top() - currentGeometry.top();
  114. const qreal bottomOffset = result.bottom() - currentGeometry.bottom();
  115. if (qAbs(topOffset) > qAbs(bottomOffset))
  116. result.setTop(result.top() - dh); // top edge drag
  117. else
  118. result.setBottom(result.bottom() + dh); // bottom edge drag
  119. const qreal leftOffset = result.left() - currentGeometry.left();
  120. const qreal rightOffset = result.right() - currentGeometry.right();
  121. if (qAbs(leftOffset) > qAbs(rightOffset))
  122. result.setLeft(result.left() - dw); // left edge drag
  123. else
  124. result.setRight(result.right() + dw); // right edge drag
  125. return result;
  126. }
  127. #if QT_CONFIG(opengl)
  128. QOpenGLContext *QWidgetWindowPrivate::shareContext() const
  129. {
  130. Q_Q(const QWidgetWindow);
  131. const QWidgetPrivate *widgetPrivate = QWidgetPrivate::get(q->widget());
  132. return widgetPrivate->shareContext();
  133. }
  134. #endif // opengl
  135. QWidgetWindow::QWidgetWindow(QWidget *widget)
  136. : QWindow(*new QWidgetWindowPrivate(), 0)
  137. , m_widget(widget)
  138. {
  139. updateObjectName();
  140. // Enable QOpenGLWidget/QQuickWidget children if the platform plugin supports it,
  141. // and the application developer has not explicitly disabled it.
  142. if (QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::RasterGLSurface)
  143. && !QApplication::testAttribute(Qt::AA_ForceRasterWidgets)) {
  144. setSurfaceType(QSurface::RasterGLSurface);
  145. }
  146. connect(widget, &QObject::objectNameChanged, this, &QWidgetWindow::updateObjectName);
  147. connect(this, SIGNAL(screenChanged(QScreen*)), this, SLOT(handleScreenChange()));
  148. }
  149. QWidgetWindow::~QWidgetWindow()
  150. {
  151. }
  152. #ifndef QT_NO_ACCESSIBILITY
  153. QAccessibleInterface *QWidgetWindow::accessibleRoot() const
  154. {
  155. if (m_widget)
  156. return QAccessible::queryAccessibleInterface(m_widget);
  157. return 0;
  158. }
  159. #endif
  160. QObject *QWidgetWindow::focusObject() const
  161. {
  162. QWidget *windowWidget = m_widget;
  163. if (!windowWidget)
  164. return nullptr;
  165. // A window can't have a focus object if it's being destroyed.
  166. if (QWidgetPrivate::get(windowWidget)->data.in_destructor)
  167. return nullptr;
  168. QWidget *widget = windowWidget->focusWidget();
  169. if (!widget)
  170. widget = windowWidget;
  171. QObject *focusObj = QWidgetPrivate::get(widget)->focusObject();
  172. if (focusObj)
  173. return focusObj;
  174. return widget;
  175. }
  176. void QWidgetWindow::setNativeWindowVisibility(bool visible)
  177. {
  178. Q_D(QWidgetWindow);
  179. // Call base class setVisible() implementation to run the QWindow
  180. // visibility logic. Don't call QWidgetWindowPrivate::setVisible()
  181. // since that will recurse back into QWidget code.
  182. d->QWindowPrivate::setVisible(visible);
  183. }
  184. static inline bool shouldBePropagatedToWidget(QEvent *event)
  185. {
  186. switch (event->type()) {
  187. // Handing show events to widgets would cause them to be triggered twice
  188. case QEvent::Show:
  189. case QEvent::Hide:
  190. case QEvent::Timer:
  191. case QEvent::DynamicPropertyChange:
  192. case QEvent::ChildAdded:
  193. case QEvent::ChildRemoved:
  194. return false;
  195. default:
  196. return true;
  197. }
  198. }
  199. bool QWidgetWindow::event(QEvent *event)
  200. {
  201. if (!m_widget)
  202. return QWindow::event(event);
  203. if (m_widget->testAttribute(Qt::WA_DontShowOnScreen)) {
  204. // \a event is uninteresting for QWidgetWindow, the event was probably
  205. // generated before WA_DontShowOnScreen was set
  206. if (!shouldBePropagatedToWidget(event))
  207. return true;
  208. return QCoreApplication::forwardEvent(m_widget, event);
  209. }
  210. switch (event->type()) {
  211. case QEvent::Close:
  212. handleCloseEvent(static_cast<QCloseEvent *>(event));
  213. return true;
  214. case QEvent::Enter:
  215. case QEvent::Leave:
  216. handleEnterLeaveEvent(event);
  217. return true;
  218. // these should not be sent to QWidget, the corresponding events
  219. // are sent by QApplicationPrivate::notifyActiveWindowChange()
  220. case QEvent::FocusIn:
  221. handleFocusInEvent(static_cast<QFocusEvent *>(event));
  222. Q_FALLTHROUGH();
  223. case QEvent::FocusOut: {
  224. #ifndef QT_NO_ACCESSIBILITY
  225. QAccessible::State state;
  226. state.active = true;
  227. QAccessibleStateChangeEvent ev(m_widget, state);
  228. QAccessible::updateAccessibility(&ev);
  229. #endif
  230. return false; }
  231. case QEvent::FocusAboutToChange:
  232. if (QApplicationPrivate::focus_widget) {
  233. if (QApplicationPrivate::focus_widget->testAttribute(Qt::WA_InputMethodEnabled))
  234. QGuiApplication::inputMethod()->commit();
  235. QGuiApplication::forwardEvent(QApplicationPrivate::focus_widget, event);
  236. }
  237. return true;
  238. case QEvent::KeyPress:
  239. case QEvent::KeyRelease:
  240. case QEvent::ShortcutOverride:
  241. handleKeyEvent(static_cast<QKeyEvent *>(event));
  242. return true;
  243. case QEvent::MouseMove:
  244. case QEvent::MouseButtonPress:
  245. case QEvent::MouseButtonRelease:
  246. case QEvent::MouseButtonDblClick:
  247. handleMouseEvent(static_cast<QMouseEvent *>(event));
  248. return true;
  249. case QEvent::NonClientAreaMouseMove:
  250. case QEvent::NonClientAreaMouseButtonPress:
  251. case QEvent::NonClientAreaMouseButtonRelease:
  252. case QEvent::NonClientAreaMouseButtonDblClick:
  253. handleNonClientAreaMouseEvent(static_cast<QMouseEvent *>(event));
  254. return true;
  255. case QEvent::TouchBegin:
  256. case QEvent::TouchUpdate:
  257. case QEvent::TouchEnd:
  258. case QEvent::TouchCancel:
  259. handleTouchEvent(static_cast<QTouchEvent *>(event));
  260. return true;
  261. case QEvent::Move:
  262. handleMoveEvent(static_cast<QMoveEvent *>(event));
  263. return true;
  264. case QEvent::Resize:
  265. handleResizeEvent(static_cast<QResizeEvent *>(event));
  266. return true;
  267. #if QT_CONFIG(wheelevent)
  268. case QEvent::Wheel:
  269. handleWheelEvent(static_cast<QWheelEvent *>(event));
  270. return true;
  271. #endif
  272. #ifndef QT_NO_DRAGANDDROP
  273. case QEvent::DragEnter:
  274. case QEvent::DragMove:
  275. handleDragEnterMoveEvent(static_cast<QDragMoveEvent *>(event));
  276. return true;
  277. case QEvent::DragLeave:
  278. handleDragLeaveEvent(static_cast<QDragLeaveEvent *>(event));
  279. return true;
  280. case QEvent::Drop:
  281. handleDropEvent(static_cast<QDropEvent *>(event));
  282. return true;
  283. #endif
  284. case QEvent::Expose:
  285. handleExposeEvent(static_cast<QExposeEvent *>(event));
  286. return true;
  287. case QEvent::WindowStateChange:
  288. QWindow::event(event); // Update QWindow::Visibility and emit signals.
  289. handleWindowStateChangedEvent(static_cast<QWindowStateChangeEvent *>(event));
  290. return true;
  291. case QEvent::ThemeChange: {
  292. QEvent widgetEvent(QEvent::ThemeChange);
  293. QCoreApplication::forwardEvent(m_widget, &widgetEvent, event);
  294. }
  295. return true;
  296. #if QT_CONFIG(tabletevent)
  297. case QEvent::TabletPress:
  298. case QEvent::TabletMove:
  299. case QEvent::TabletRelease:
  300. handleTabletEvent(static_cast<QTabletEvent *>(event));
  301. return true;
  302. #endif
  303. #ifndef QT_NO_GESTURES
  304. case QEvent::NativeGesture:
  305. handleGestureEvent(static_cast<QNativeGestureEvent *>(event));
  306. return true;
  307. #endif
  308. #ifndef QT_NO_CONTEXTMENU
  309. case QEvent::ContextMenu:
  310. handleContextMenuEvent(static_cast<QContextMenuEvent *>(event));
  311. return true;
  312. #endif // QT_NO_CONTEXTMENU
  313. case QEvent::WindowBlocked:
  314. qt_button_down = 0;
  315. break;
  316. case QEvent::UpdateRequest:
  317. // This is not the same as an UpdateRequest for a QWidget. That just
  318. // syncs the backing store while here we also must mark as dirty.
  319. m_widget->repaint();
  320. return true;
  321. default:
  322. break;
  323. }
  324. if (shouldBePropagatedToWidget(event) && QCoreApplication::forwardEvent(m_widget, event))
  325. return true;
  326. return QWindow::event(event);
  327. }
  328. QPointer<QWidget> qt_last_mouse_receiver = 0;
  329. void QWidgetWindow::handleEnterLeaveEvent(QEvent *event)
  330. {
  331. #if !defined(Q_OS_OSX) && !defined(Q_OS_IOS) // Cocoa tracks popups
  332. // Ignore all enter/leave events from QPA if we are not on the first-level context menu.
  333. // This prevents duplicated events on most platforms. Fake events will be delivered in
  334. // QWidgetWindow::handleMouseEvent(QMouseEvent *). Make an exception whether the widget
  335. // is already under mouse - let the mouse leave.
  336. if (QApplicationPrivate::inPopupMode() && m_widget != QApplication::activePopupWidget() && !m_widget->underMouse())
  337. return;
  338. #endif
  339. if (event->type() == QEvent::Leave) {
  340. QWidget *enter = 0;
  341. // Check from window system event queue if the next queued enter targets a window
  342. // in the same window hierarchy (e.g. enter a child of this window). If so,
  343. // remove the enter event from queue and handle both in single dispatch.
  344. QWindowSystemInterfacePrivate::EnterEvent *systemEvent =
  345. static_cast<QWindowSystemInterfacePrivate::EnterEvent *>
  346. (QWindowSystemInterfacePrivate::peekWindowSystemEvent(QWindowSystemInterfacePrivate::Enter));
  347. const QPointF globalPosF = systemEvent ? systemEvent->globalPos : QGuiApplicationPrivate::lastCursorPosition;
  348. if (systemEvent) {
  349. if (QWidgetWindow *enterWindow = qobject_cast<QWidgetWindow *>(systemEvent->enter))
  350. {
  351. QWindow *thisParent = this;
  352. QWindow *enterParent = enterWindow;
  353. while (thisParent->parent())
  354. thisParent = thisParent->parent();
  355. while (enterParent->parent())
  356. enterParent = enterParent->parent();
  357. if (thisParent == enterParent) {
  358. QGuiApplicationPrivate::currentMouseWindow = enterWindow;
  359. enter = enterWindow->widget();
  360. QWindowSystemInterfacePrivate::removeWindowSystemEvent(systemEvent);
  361. }
  362. }
  363. }
  364. // Enter-leave between sibling widgets is ignored when there is a mousegrabber - this makes
  365. // both native and non-native widgets work similarly.
  366. // When mousegrabbing, leaves are only generated if leaving the parent window.
  367. if (!enter || !QWidget::mouseGrabber()) {
  368. // Preferred leave target is the last mouse receiver, unless it has native window,
  369. // in which case it is assumed to receive it's own leave event when relevant.
  370. QWidget *leave = m_widget;
  371. if (qt_last_mouse_receiver && !qt_last_mouse_receiver->internalWinId())
  372. leave = qt_last_mouse_receiver.data();
  373. QApplicationPrivate::dispatchEnterLeave(enter, leave, globalPosF);
  374. qt_last_mouse_receiver = enter;
  375. }
  376. } else {
  377. const QEnterEvent *ee = static_cast<QEnterEvent *>(event);
  378. QWidget *child = m_widget->childAt(ee->pos());
  379. QWidget *receiver = child ? child : m_widget.data();
  380. QWidget *leave = nullptr;
  381. if (QApplicationPrivate::inPopupMode() && receiver == m_widget
  382. && qt_last_mouse_receiver != m_widget) {
  383. // This allows to deliver the leave event to the native widget
  384. // action on first-level menu.
  385. leave = qt_last_mouse_receiver;
  386. }
  387. QApplicationPrivate::dispatchEnterLeave(receiver, leave, ee->screenPos());
  388. qt_last_mouse_receiver = receiver;
  389. }
  390. }
  391. QWidget *QWidgetWindow::getFocusWidget(FocusWidgets fw)
  392. {
  393. QWidget *tlw = m_widget;
  394. QWidget *w = tlw->nextInFocusChain();
  395. QWidget *last = tlw;
  396. uint focus_flag = qt_tab_all_widgets() ? Qt::TabFocus : Qt::StrongFocus;
  397. while (w != tlw)
  398. {
  399. if (((w->focusPolicy() & focus_flag) == focus_flag)
  400. && w->isVisibleTo(m_widget) && w->isEnabled())
  401. {
  402. last = w;
  403. if (fw == FirstFocusWidget)
  404. break;
  405. }
  406. w = w->nextInFocusChain();
  407. }
  408. return last;
  409. }
  410. void QWidgetWindow::handleFocusInEvent(QFocusEvent *e)
  411. {
  412. QWidget *focusWidget = 0;
  413. if (e->reason() == Qt::BacktabFocusReason)
  414. focusWidget = getFocusWidget(LastFocusWidget);
  415. else if (e->reason() == Qt::TabFocusReason)
  416. focusWidget = getFocusWidget(FirstFocusWidget);
  417. if (focusWidget != 0)
  418. focusWidget->setFocus();
  419. }
  420. void QWidgetWindow::handleNonClientAreaMouseEvent(QMouseEvent *e)
  421. {
  422. QApplication::forwardEvent(m_widget, e);
  423. }
  424. void QWidgetWindow::handleMouseEvent(QMouseEvent *event)
  425. {
  426. static const QEvent::Type contextMenuTrigger =
  427. QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::ContextMenuOnMouseRelease).toBool() ?
  428. QEvent::MouseButtonRelease : QEvent::MouseButtonPress;
  429. if (qApp->d_func()->inPopupMode()) {
  430. QWidget *activePopupWidget = qApp->activePopupWidget();
  431. QPoint mapped = event->pos();
  432. if (activePopupWidget != m_widget)
  433. mapped = activePopupWidget->mapFromGlobal(event->globalPos());
  434. bool releaseAfter = false;
  435. QWidget *popupChild = activePopupWidget->childAt(mapped);
  436. if (activePopupWidget != qt_popup_down) {
  437. qt_button_down = 0;
  438. qt_popup_down = 0;
  439. }
  440. switch (event->type()) {
  441. case QEvent::MouseButtonPress:
  442. case QEvent::MouseButtonDblClick:
  443. qt_button_down = popupChild;
  444. qt_popup_down = activePopupWidget;
  445. break;
  446. case QEvent::MouseButtonRelease:
  447. releaseAfter = true;
  448. break;
  449. default:
  450. break; // nothing for mouse move
  451. }
  452. int oldOpenPopupCount = openPopupCount;
  453. if (activePopupWidget->isEnabled()) {
  454. // deliver event
  455. qt_replay_popup_mouse_event = false;
  456. QWidget *receiver = activePopupWidget;
  457. QPoint widgetPos = mapped;
  458. if (qt_button_down)
  459. receiver = qt_button_down;
  460. else if (popupChild)
  461. receiver = popupChild;
  462. if (receiver != activePopupWidget)
  463. widgetPos = receiver->mapFromGlobal(event->globalPos());
  464. #if !defined(Q_OS_OSX) && !defined(Q_OS_IOS) // Cocoa tracks popups
  465. const bool reallyUnderMouse = activePopupWidget->rect().contains(mapped);
  466. const bool underMouse = activePopupWidget->underMouse();
  467. if (underMouse != reallyUnderMouse) {
  468. if (reallyUnderMouse) {
  469. const QPoint receiverMapped = receiver->mapFromGlobal(event->screenPos().toPoint());
  470. // Prevent negative mouse position on enter event - this event
  471. // should be properly handled in "handleEnterLeaveEvent()".
  472. if (receiverMapped.x() >= 0 && receiverMapped.y() >= 0) {
  473. QApplicationPrivate::dispatchEnterLeave(receiver, nullptr, event->screenPos());
  474. qt_last_mouse_receiver = receiver;
  475. }
  476. } else {
  477. QApplicationPrivate::dispatchEnterLeave(nullptr, qt_last_mouse_receiver, event->screenPos());
  478. qt_last_mouse_receiver = receiver;
  479. receiver = activePopupWidget;
  480. }
  481. }
  482. #endif
  483. if ((event->type() != QEvent::MouseButtonPress)
  484. || !(event->flags().testFlag(Qt::MouseEventCreatedDoubleClick))) {
  485. QMouseEvent e(event->type(), widgetPos, event->windowPos(), event->screenPos(),
  486. event->button(), event->buttons(), event->modifiers(), event->source());
  487. e.setTimestamp(event->timestamp());
  488. QApplicationPrivate::sendMouseEvent(receiver, &e, receiver, receiver->window(), &qt_button_down, qt_last_mouse_receiver);
  489. qt_last_mouse_receiver = receiver;
  490. }
  491. } else {
  492. // close disabled popups when a mouse button is pressed or released
  493. switch (event->type()) {
  494. case QEvent::MouseButtonPress:
  495. case QEvent::MouseButtonDblClick:
  496. case QEvent::MouseButtonRelease:
  497. activePopupWidget->close();
  498. break;
  499. default:
  500. break;
  501. }
  502. }
  503. if (qApp->activePopupWidget() != activePopupWidget
  504. && qt_replay_popup_mouse_event
  505. && QGuiApplicationPrivate::platformIntegration()->styleHint(QPlatformIntegration::ReplayMousePressOutsidePopup).toBool()) {
  506. if (m_widget->windowType() != Qt::Popup)
  507. qt_button_down = 0;
  508. if (event->type() == QEvent::MouseButtonPress) {
  509. // the popup disappeared, replay the mouse press event
  510. QWidget *w = QApplication::widgetAt(event->globalPos());
  511. if (w && !QApplicationPrivate::isBlockedByModal(w)) {
  512. // activate window of the widget under mouse pointer
  513. if (!w->isActiveWindow()) {
  514. w->activateWindow();
  515. w->window()->raise();
  516. }
  517. QWindow *win = w->windowHandle();
  518. if (!win)
  519. win = w->nativeParentWidget()->windowHandle();
  520. if (win) {
  521. const QRect globalGeometry = win->isTopLevel()
  522. ? win->geometry()
  523. : QRect(win->mapToGlobal(QPoint(0, 0)), win->size());
  524. if (globalGeometry.contains(event->globalPos())) {
  525. // Use postEvent() to ensure the local QEventLoop terminates when called from QMenu::exec()
  526. const QPoint localPos = win->mapFromGlobal(event->globalPos());
  527. QMouseEvent *e = new QMouseEvent(QEvent::MouseButtonPress, localPos, localPos, event->globalPos(),
  528. event->button(), event->buttons(), event->modifiers(), event->source());
  529. QCoreApplicationPrivate::setEventSpontaneous(e, true);
  530. e->setTimestamp(event->timestamp());
  531. QCoreApplication::postEvent(win, e);
  532. }
  533. }
  534. }
  535. }
  536. qt_replay_popup_mouse_event = false;
  537. #ifndef QT_NO_CONTEXTMENU
  538. } else if (event->type() == contextMenuTrigger
  539. && event->button() == Qt::RightButton
  540. && (openPopupCount == oldOpenPopupCount)) {
  541. QWidget *receiver = activePopupWidget;
  542. if (qt_button_down)
  543. receiver = qt_button_down;
  544. else if(popupChild)
  545. receiver = popupChild;
  546. QContextMenuEvent e(QContextMenuEvent::Mouse, mapped, event->globalPos(), event->modifiers());
  547. QApplication::forwardEvent(receiver, &e, event);
  548. }
  549. #else
  550. Q_UNUSED(contextMenuTrigger)
  551. Q_UNUSED(oldOpenPopupCount)
  552. }
  553. #endif
  554. if (releaseAfter) {
  555. qt_button_down = 0;
  556. qt_popup_down = 0;
  557. }
  558. return;
  559. }
  560. // modal event handling
  561. if (QApplicationPrivate::instance()->modalState() && !qt_try_modal(m_widget, event->type()))
  562. return;
  563. // which child should have it?
  564. QWidget *widget = m_widget->childAt(event->pos());
  565. QPoint mapped = event->pos();
  566. if (!widget)
  567. widget = m_widget;
  568. if (event->type() == QEvent::MouseButtonPress)
  569. qt_button_down = widget;
  570. QWidget *receiver = QApplicationPrivate::pickMouseReceiver(m_widget, event->windowPos().toPoint(), &mapped, event->type(), event->buttons(),
  571. qt_button_down, widget);
  572. if (!receiver)
  573. return;
  574. if ((event->type() != QEvent::MouseButtonPress)
  575. || !(event->flags().testFlag(Qt::MouseEventCreatedDoubleClick))) {
  576. // The preceding statement excludes MouseButtonPress events which caused
  577. // creation of a MouseButtonDblClick event. QTBUG-25831
  578. QMouseEvent translated(event->type(), mapped, event->windowPos(), event->screenPos(),
  579. event->button(), event->buttons(), event->modifiers(), event->source());
  580. translated.setTimestamp(event->timestamp());
  581. QApplicationPrivate::sendMouseEvent(receiver, &translated, widget, m_widget,
  582. &qt_button_down, qt_last_mouse_receiver);
  583. event->setAccepted(translated.isAccepted());
  584. }
  585. #ifndef QT_NO_CONTEXTMENU
  586. if (event->type() == contextMenuTrigger && event->button() == Qt::RightButton
  587. && m_widget->rect().contains(event->pos())) {
  588. QContextMenuEvent e(QContextMenuEvent::Mouse, mapped, event->globalPos(), event->modifiers());
  589. QGuiApplication::forwardEvent(receiver, &e, event);
  590. }
  591. #endif
  592. }
  593. void QWidgetWindow::handleTouchEvent(QTouchEvent *event)
  594. {
  595. if (event->type() == QEvent::TouchCancel) {
  596. QApplicationPrivate::translateTouchCancel(event->device(), event->timestamp());
  597. event->accept();
  598. } else if (qApp->d_func()->inPopupMode()) {
  599. // Ignore touch events for popups. This will cause QGuiApplication to synthesise mouse
  600. // events instead, which QWidgetWindow::handleMouseEvent will forward correctly:
  601. event->ignore();
  602. } else {
  603. event->setAccepted(QApplicationPrivate::translateRawTouchEvent(m_widget, event->device(), event->touchPoints(), event->timestamp()));
  604. }
  605. }
  606. void QWidgetWindow::handleKeyEvent(QKeyEvent *event)
  607. {
  608. if (QApplicationPrivate::instance()->modalState() && !qt_try_modal(m_widget, event->type()))
  609. return;
  610. QObject *receiver = QWidget::keyboardGrabber();
  611. if (!receiver && QApplicationPrivate::inPopupMode()) {
  612. QWidget *popup = QApplication::activePopupWidget();
  613. QWidget *popupFocusWidget = popup->focusWidget();
  614. receiver = popupFocusWidget ? popupFocusWidget : popup;
  615. }
  616. if (!receiver)
  617. receiver = focusObject();
  618. QGuiApplication::forwardEvent(receiver, event);
  619. }
  620. bool QWidgetWindow::updateSize()
  621. {
  622. bool changed = false;
  623. if (m_widget->testAttribute(Qt::WA_OutsideWSRange))
  624. return changed;
  625. if (m_widget->data->crect.size() != geometry().size()) {
  626. changed = true;
  627. m_widget->data->crect.setSize(geometry().size());
  628. }
  629. updateMargins();
  630. return changed;
  631. }
  632. bool QWidgetWindow::updatePos()
  633. {
  634. bool changed = false;
  635. if (m_widget->testAttribute(Qt::WA_OutsideWSRange))
  636. return changed;
  637. if (m_widget->data->crect.topLeft() != geometry().topLeft()) {
  638. changed = true;
  639. m_widget->data->crect.moveTopLeft(geometry().topLeft());
  640. }
  641. updateMargins();
  642. return changed;
  643. }
  644. void QWidgetWindow::updateMargins()
  645. {
  646. const QMargins margins = frameMargins();
  647. QTLWExtra *te = m_widget->d_func()->topData();
  648. te->posIncludesFrame= false;
  649. te->frameStrut.setCoords(margins.left(), margins.top(), margins.right(), margins.bottom());
  650. m_widget->data->fstrut_dirty = false;
  651. }
  652. static void sendScreenChangeRecursively(QWidget *widget)
  653. {
  654. QEvent e(QEvent::ScreenChangeInternal);
  655. QApplication::sendEvent(widget, &e);
  656. QWidgetPrivate *d = QWidgetPrivate::get(widget);
  657. for (int i = 0; i < d->children.size(); ++i) {
  658. QWidget *w = qobject_cast<QWidget *>(d->children.at(i));
  659. if (w)
  660. sendScreenChangeRecursively(w);
  661. }
  662. }
  663. void QWidgetWindow::handleScreenChange()
  664. {
  665. // Send an event recursively to the widget and its children.
  666. sendScreenChangeRecursively(m_widget);
  667. // Invalidate the backing store buffer and repaint immediately.
  668. if (screen())
  669. repaintWindow();
  670. }
  671. void QWidgetWindow::repaintWindow()
  672. {
  673. if (!m_widget->isVisible() || !m_widget->updatesEnabled() || !m_widget->rect().isValid())
  674. return;
  675. QTLWExtra *tlwExtra = m_widget->window()->d_func()->maybeTopData();
  676. if (tlwExtra && !tlwExtra->inTopLevelResize && tlwExtra->backingStore)
  677. tlwExtra->backingStoreTracker->markDirty(m_widget->rect(), m_widget,
  678. QWidgetBackingStore::UpdateNow, QWidgetBackingStore::BufferInvalid);
  679. }
  680. // Store normal geometry used for saving application settings.
  681. void QWidgetWindow::updateNormalGeometry()
  682. {
  683. QTLWExtra *tle = m_widget->d_func()->maybeTopData();
  684. if (!tle)
  685. return;
  686. // Ask platform window, default to widget geometry.
  687. QRect normalGeometry;
  688. if (const QPlatformWindow *pw = handle())
  689. normalGeometry = QHighDpi::fromNativePixels(pw->normalGeometry(), this);
  690. if (!normalGeometry.isValid() && !(m_widget->windowState() & ~Qt::WindowActive))
  691. normalGeometry = m_widget->geometry();
  692. if (normalGeometry.isValid())
  693. tle->normalGeometry = normalGeometry;
  694. }
  695. void QWidgetWindow::handleMoveEvent(QMoveEvent *event)
  696. {
  697. if (updatePos())
  698. QGuiApplication::forwardEvent(m_widget, event);
  699. }
  700. void QWidgetWindow::handleResizeEvent(QResizeEvent *event)
  701. {
  702. QSize oldSize = m_widget->data->crect.size();
  703. if (updateSize()) {
  704. QGuiApplication::forwardEvent(m_widget, event);
  705. if (m_widget->d_func()->paintOnScreen()) {
  706. QRegion updateRegion(geometry());
  707. if (m_widget->testAttribute(Qt::WA_StaticContents))
  708. updateRegion -= QRect(0, 0, oldSize.width(), oldSize.height());
  709. m_widget->d_func()->syncBackingStore(updateRegion);
  710. } else {
  711. m_widget->d_func()->syncBackingStore();
  712. }
  713. }
  714. }
  715. void QWidgetWindow::handleCloseEvent(QCloseEvent *event)
  716. {
  717. bool is_closing = m_widget->d_func()->close_helper(QWidgetPrivate::CloseWithSpontaneousEvent);
  718. event->setAccepted(is_closing);
  719. }
  720. #if QT_CONFIG(wheelevent)
  721. void QWidgetWindow::handleWheelEvent(QWheelEvent *event)
  722. {
  723. if (QApplicationPrivate::instance()->modalState() && !qt_try_modal(m_widget, event->type()))
  724. return;
  725. QWidget *rootWidget = m_widget;
  726. QPoint pos = event->pos();
  727. // Use proper popup window for wheel event. Some QPA sends the wheel
  728. // event to the root menu, so redirect it to the proper popup window.
  729. QWidget *activePopupWidget = QApplication::activePopupWidget();
  730. if (activePopupWidget && activePopupWidget != m_widget) {
  731. rootWidget = activePopupWidget;
  732. pos = rootWidget->mapFromGlobal(event->globalPos());
  733. }
  734. // which child should have it?
  735. QWidget *widget = rootWidget->childAt(pos);
  736. if (!widget)
  737. widget = rootWidget;
  738. QPoint mapped = widget->mapFrom(rootWidget, pos);
  739. QWheelEvent translated(mapped, event->globalPos(), event->pixelDelta(), event->angleDelta(), event->delta(), event->orientation(), event->buttons(), event->modifiers(), event->phase(), event->source(), event->inverted());
  740. QGuiApplication::forwardEvent(widget, &translated, event);
  741. }
  742. #endif // QT_CONFIG(wheelevent)
  743. #ifndef QT_NO_DRAGANDDROP
  744. void QWidgetWindow::handleDragEnterMoveEvent(QDragMoveEvent *event)
  745. {
  746. Q_ASSERT(event->type() ==QEvent::DragMove || !m_dragTarget);
  747. // Find a target widget under mouse that accepts drops (QTBUG-22987).
  748. QWidget *widget = m_widget->childAt(event->pos());
  749. if (!widget)
  750. widget = m_widget;
  751. for ( ; widget && !widget->isWindow() && !widget->acceptDrops(); widget = widget->parentWidget()) ;
  752. if (widget && !widget->acceptDrops())
  753. widget = 0;
  754. // Target widget unchanged: DragMove
  755. if (widget && widget == m_dragTarget.data()) {
  756. Q_ASSERT(event->type() == QEvent::DragMove);
  757. const QPoint mapped = widget->mapFromGlobal(m_widget->mapToGlobal(event->pos()));
  758. QDragMoveEvent translated(mapped, event->possibleActions(), event->mimeData(), event->mouseButtons(), event->keyboardModifiers());
  759. translated.setDropAction(event->dropAction());
  760. if (event->isAccepted()) { // Handling 'DragEnter' should suffice for the application.
  761. translated.accept();
  762. translated.setDropAction(event->dropAction());
  763. }
  764. QGuiApplication::forwardEvent(widget, &translated, event);
  765. if (translated.isAccepted()) {
  766. event->accept();
  767. } else {
  768. event->ignore();
  769. }
  770. event->setDropAction(translated.dropAction());
  771. return;
  772. }
  773. // Target widget changed: Send DragLeave to previous, DragEnter to new if there is any
  774. if (m_dragTarget.data()) {
  775. QDragLeaveEvent le;
  776. QGuiApplication::forwardEvent(m_dragTarget.data(), &le, event);
  777. m_dragTarget = 0;
  778. }
  779. if (!widget) {
  780. event->ignore();
  781. return;
  782. }
  783. m_dragTarget = widget;
  784. const QPoint mapped = widget->mapFromGlobal(m_widget->mapToGlobal(event->pos()));
  785. QDragEnterEvent translated(mapped, event->possibleActions(), event->mimeData(), event->mouseButtons(), event->keyboardModifiers());
  786. QGuiApplication::forwardEvent(widget, &translated, event);
  787. if (translated.isAccepted()) {
  788. event->accept();
  789. } else {
  790. event->ignore();
  791. }
  792. event->setDropAction(translated.dropAction());
  793. }
  794. void QWidgetWindow::handleDragLeaveEvent(QDragLeaveEvent *event)
  795. {
  796. if (m_dragTarget)
  797. QGuiApplication::forwardEvent(m_dragTarget.data(), event);
  798. m_dragTarget = 0;
  799. }
  800. void QWidgetWindow::handleDropEvent(QDropEvent *event)
  801. {
  802. if (Q_UNLIKELY(m_dragTarget.isNull())) {
  803. qWarning() << m_widget << ": No drag target set.";
  804. event->ignore();
  805. return;
  806. }
  807. const QPoint mapped = m_dragTarget.data()->mapFromGlobal(m_widget->mapToGlobal(event->pos()));
  808. QDropEvent translated(mapped, event->possibleActions(), event->mimeData(), event->mouseButtons(), event->keyboardModifiers());
  809. QGuiApplication::forwardEvent(m_dragTarget.data(), &translated, event);
  810. if (translated.isAccepted())
  811. event->accept();
  812. event->setDropAction(translated.dropAction());
  813. m_dragTarget = 0;
  814. }
  815. #endif // QT_NO_DRAGANDDROP
  816. void QWidgetWindow::handleExposeEvent(QExposeEvent *event)
  817. {
  818. QWidgetPrivate *wPriv = m_widget->d_func();
  819. const bool exposed = isExposed();
  820. if (wPriv->childrenHiddenByWState) {
  821. // If widgets has been previously hidden by window state change event
  822. // and they aren't yet shown...
  823. if (exposed) {
  824. // If the window becomes exposed...
  825. if (!wPriv->childrenShownByExpose) {
  826. // ... and they haven't been shown by this function yet - show it.
  827. wPriv->showChildren(true);
  828. QShowEvent showEvent;
  829. QCoreApplication::forwardEvent(m_widget, &showEvent, event);
  830. wPriv->childrenShownByExpose = true;
  831. }
  832. } else {
  833. // If the window becomes not exposed...
  834. if (wPriv->childrenShownByExpose) {
  835. // ... and child widgets was previously shown by the expose event - hide widgets again.
  836. // This is a workaround, because sometimes when window is minimized programatically,
  837. // the QPA can notify that the window is exposed after changing window state to minimized
  838. // and then, the QPA can send next expose event with null exposed region (not exposed).
  839. wPriv->hideChildren(true);
  840. QHideEvent hideEvent;
  841. QCoreApplication::forwardEvent(m_widget, &hideEvent, event);
  842. wPriv->childrenShownByExpose = false;
  843. }
  844. }
  845. }
  846. if (exposed) {
  847. m_widget->setAttribute(Qt::WA_Mapped);
  848. if (!event->region().isNull())
  849. wPriv->syncBackingStore(event->region());
  850. } else {
  851. m_widget->setAttribute(Qt::WA_Mapped, false);
  852. }
  853. }
  854. void QWidgetWindow::handleWindowStateChangedEvent(QWindowStateChangeEvent *event)
  855. {
  856. // QWindow does currently not know 'active'.
  857. Qt::WindowStates eventState = event->oldState();
  858. Qt::WindowStates widgetState = m_widget->windowState();
  859. Qt::WindowStates windowState = windowStates();
  860. if (widgetState & Qt::WindowActive)
  861. eventState |= Qt::WindowActive;
  862. // Determine the new widget state, remember maximized/full screen
  863. // during minimized.
  864. if (windowState & Qt::WindowMinimized) {
  865. widgetState |= Qt::WindowMinimized;
  866. } else {
  867. widgetState = windowState | (widgetState & Qt::WindowActive);
  868. if (windowState) // Maximized or FullScreen
  869. updateNormalGeometry();
  870. }
  871. // Sent event if the state changed (that is, it is not triggered by
  872. // QWidget::setWindowState(), which also sends an event to the widget).
  873. if (widgetState != Qt::WindowStates::Int(m_widget->data->window_state)) {
  874. m_widget->data->window_state = uint(widgetState);
  875. QWindowStateChangeEvent widgetEvent(eventState);
  876. QGuiApplication::forwardEvent(m_widget, &widgetEvent, event);
  877. }
  878. }
  879. bool QWidgetWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
  880. {
  881. return m_widget->nativeEvent(eventType, message, result);
  882. }
  883. #if QT_CONFIG(tabletevent)
  884. void QWidgetWindow::handleTabletEvent(QTabletEvent *event)
  885. {
  886. static QPointer<QWidget> qt_tablet_target = 0;
  887. QWidget *widget = qt_tablet_target;
  888. if (!widget) {
  889. widget = m_widget->childAt(event->pos());
  890. if (event->type() == QEvent::TabletPress) {
  891. if (!widget)
  892. widget = m_widget;
  893. qt_tablet_target = widget;
  894. }
  895. }
  896. if (widget) {
  897. QPointF delta = event->globalPosF() - event->globalPos();
  898. QPointF mapped = widget->mapFromGlobal(event->globalPos()) + delta;
  899. QTabletEvent ev(event->type(), mapped, event->globalPosF(), event->device(), event->pointerType(),
  900. event->pressure(), event->xTilt(), event->yTilt(), event->tangentialPressure(),
  901. event->rotation(), event->z(), event->modifiers(), event->uniqueId(), event->button(), event->buttons());
  902. ev.setTimestamp(event->timestamp());
  903. QGuiApplication::forwardEvent(widget, &ev, event);
  904. event->setAccepted(ev.isAccepted());
  905. }
  906. if (event->type() == QEvent::TabletRelease && event->buttons() == Qt::NoButton)
  907. qt_tablet_target = 0;
  908. }
  909. #endif // QT_CONFIG(tabletevent)
  910. #ifndef QT_NO_GESTURES
  911. void QWidgetWindow::handleGestureEvent(QNativeGestureEvent *e)
  912. {
  913. // copy-pasted code to find correct widget follows:
  914. QObject *receiver = 0;
  915. if (QApplicationPrivate::inPopupMode()) {
  916. QWidget *popup = QApplication::activePopupWidget();
  917. QWidget *popupFocusWidget = popup->focusWidget();
  918. receiver = popupFocusWidget ? popupFocusWidget : popup;
  919. }
  920. if (!receiver)
  921. receiver = QApplication::widgetAt(e->globalPos());
  922. if (!receiver)
  923. receiver = m_widget; // last resort
  924. QApplication::forwardEvent(receiver, e);
  925. }
  926. #endif // QT_NO_GESTURES
  927. #ifndef QT_NO_CONTEXTMENU
  928. void QWidgetWindow::handleContextMenuEvent(QContextMenuEvent *e)
  929. {
  930. // We are only interested in keyboard originating context menu events here,
  931. // mouse originated context menu events for widgets are generated in mouse handling methods.
  932. if (e->reason() != QContextMenuEvent::Keyboard)
  933. return;
  934. QWidget *fw = QWidget::keyboardGrabber();
  935. if (!fw) {
  936. if (QApplication::activePopupWidget()) {
  937. fw = (QApplication::activePopupWidget()->focusWidget()
  938. ? QApplication::activePopupWidget()->focusWidget()
  939. : QApplication::activePopupWidget());
  940. } else if (QApplication::focusWidget()) {
  941. fw = QApplication::focusWidget();
  942. } else {
  943. fw = m_widget;
  944. }
  945. }
  946. if (fw && fw->isEnabled()) {
  947. QPoint pos = fw->inputMethodQuery(Qt::ImMicroFocus).toRect().center();
  948. QContextMenuEvent widgetEvent(QContextMenuEvent::Keyboard, pos, fw->mapToGlobal(pos),
  949. e->modifiers());
  950. QGuiApplication::forwardEvent(fw, &widgetEvent, e);
  951. }
  952. }
  953. #endif // QT_NO_CONTEXTMENU
  954. void QWidgetWindow::updateObjectName()
  955. {
  956. QString name = m_widget->objectName();
  957. if (name.isEmpty())
  958. name = QString::fromUtf8(m_widget->metaObject()->className()) + QLatin1String("Class");
  959. name += QLatin1String("Window");
  960. setObjectName(name);
  961. }
  962. QT_END_NAMESPACE
  963. #include "moc_qwidgetwindow_p.cpp"