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