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