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

source code of qtbase/src/widgets/kernel/qwidgetwindow.cpp