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 QtGui 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 "qwindow.h"
41
42#include <qpa/qplatformwindow.h>
43#include <qpa/qplatformintegration.h>
44#include "qsurfaceformat.h"
45#ifndef QT_NO_OPENGL
46#include <qpa/qplatformopenglcontext.h>
47#include "qopenglcontext.h"
48#include "qopenglcontext_p.h"
49#endif
50#include "qscreen.h"
51
52#include "qwindow_p.h"
53#include "qguiapplication_p.h"
54#ifndef QT_NO_ACCESSIBILITY
55# include "qaccessible.h"
56#endif
57#include "qhighdpiscaling_p.h"
58#if QT_CONFIG(draganddrop)
59#include "qshapedpixmapdndwindow_p.h"
60#endif // QT_CONFIG(draganddrop)
61
62#include <private/qevent_p.h>
63
64#include <QtCore/QTimer>
65#include <QtCore/QDebug>
66
67#include <QStyleHints>
68#include <qpa/qplatformcursor.h>
69
70QT_BEGIN_NAMESPACE
71
72/*!
73 \class QWindow
74 \inmodule QtGui
75 \since 5.0
76 \brief The QWindow class represents a window in the underlying windowing system.
77
78 A window that is supplied a parent becomes a native child window of
79 their parent window.
80
81 An application will typically use QWidget or QQuickView for its UI, and not
82 QWindow directly. Still, it is possible to render directly to a QWindow
83 with QBackingStore or QOpenGLContext, when wanting to keep dependencies to
84 a minimum or when wanting to use OpenGL directly. The
85 \l{Raster Window Example} and \l{OpenGL Window Example}
86 are useful reference examples for how to render to a QWindow using
87 either approach.
88
89 \section1 Resource Management
90
91 Windows can potentially use a lot of memory. A usual measurement is
92 width times height times color depth. A window might also include multiple
93 buffers to support double and triple buffering, as well as depth and stencil
94 buffers. To release a window's memory resources, call the destroy() function.
95
96 \section1 Content Orientation
97
98 QWindow has reportContentOrientationChange() that can be used to specify
99 the layout of the window contents in relation to the screen. The content
100 orientation is simply a hint to the windowing system about which
101 orientation the window contents are in. It's useful when you wish to keep
102 the same window size, but rotate the contents instead, especially when
103 doing rotation animations between different orientations. The windowing
104 system might use this value to determine the layout of system popups or
105 dialogs.
106
107 \section1 Visibility and Windowing System Exposure
108
109 By default, the window is not visible, and you must call setVisible(true),
110 or show() or similar to make it visible. To make a window hidden again,
111 call setVisible(false) or hide(). The visible property describes the state
112 the application wants the window to be in. Depending on the underlying
113 system, a visible window might still not be shown on the screen. It could,
114 for instance, be covered by other opaque windows or moved outside the
115 physical area of the screen. On windowing systems that have exposure
116 notifications, the isExposed() accessor describes whether the window should
117 be treated as directly visible on screen. The exposeEvent() function is
118 called whenever an area of the window is invalidated, for example due to the
119 exposure in the windowing system changing. On windowing systems that do not
120 make this information visible to the application, isExposed() will simply
121 return the same value as isVisible().
122
123 QWindow::Visibility queried through visibility() is a convenience API
124 combining the functions of visible() and windowStates().
125
126 \section1 Rendering
127
128 There are two Qt APIs that can be used to render content into a window,
129 QBackingStore for rendering with a QPainter and flushing the contents
130 to a window with type QSurface::RasterSurface, and QOpenGLContext for
131 rendering with OpenGL to a window with type QSurface::OpenGLSurface.
132
133 The application can start rendering as soon as isExposed() returns \c true,
134 and can keep rendering until it isExposed() returns \c false. To find out when
135 isExposed() changes, reimplement exposeEvent(). The window will always get
136 a resize event before the first expose event.
137
138 \section1 Initial Geometry
139
140 If the window's width and height are left uninitialized, the window will
141 get a reasonable default geometry from the platform window. If the position
142 is left uninitialized, then the platform window will allow the windowing
143 system to position the window. For example on X11, the window manager
144 usually does some kind of smart positioning to try to avoid having new
145 windows completely obscure existing windows. However setGeometry()
146 initializes both the position and the size, so if you want a fixed size but
147 an automatic position, you should call resize() or setWidth() and
148 setHeight() instead.
149*/
150
151/*!
152 Creates a window as a top level on the \a targetScreen.
153
154 The window is not shown until setVisible(true), show(), or similar is called.
155
156 \sa setScreen()
157*/
158QWindow::QWindow(QScreen *targetScreen)
159 : QObject(*new QWindowPrivate(), nullptr)
160 , QSurface(QSurface::Window)
161{
162 Q_D(QWindow);
163 d->init(targetScreen);
164}
165
166static QWindow *nonDesktopParent(QWindow *parent)
167{
168 if (parent && parent->type() == Qt::Desktop) {
169 qWarning("QWindows cannot be reparented into desktop windows");
170 return nullptr;
171 }
172
173 return parent;
174}
175
176/*!
177 Creates a window as a child of the given \a parent window.
178
179 The window will be embedded inside the parent window, its coordinates
180 relative to the parent.
181
182 The screen is inherited from the parent.
183
184 \sa setParent()
185*/
186QWindow::QWindow(QWindow *parent)
187 : QWindow(*new QWindowPrivate(), parent)
188{
189}
190
191/*!
192 Creates a window as a child of the given \a parent window with the \a dd
193 private implementation.
194
195 The window will be embedded inside the parent window, its coordinates
196 relative to the parent.
197
198 The screen is inherited from the parent.
199
200 \internal
201 \sa setParent()
202*/
203QWindow::QWindow(QWindowPrivate &dd, QWindow *parent)
204 : QObject(dd, nonDesktopParent(parent))
205 , QSurface(QSurface::Window)
206{
207 Q_D(QWindow);
208 d->init();
209}
210
211/*!
212 Destroys the window.
213*/
214QWindow::~QWindow()
215{
216 Q_D(QWindow);
217 d->destroy();
218 QGuiApplicationPrivate::window_list.removeAll(this);
219 if (!QGuiApplicationPrivate::is_app_closing)
220 QGuiApplicationPrivate::instance()->modalWindowList.removeOne(this);
221
222 // focus_window is normally cleared in destroy(), but the window may in
223 // some cases end up becoming the focus window again. Clear it again
224 // here as a workaround. See QTBUG-75326.
225 if (QGuiApplicationPrivate::focus_window == this)
226 QGuiApplicationPrivate::focus_window = nullptr;
227}
228
229void QWindowPrivate::init(QScreen *targetScreen)
230{
231 Q_Q(QWindow);
232
233 parentWindow = static_cast<QWindow *>(q->QObject::parent());
234
235 if (!parentWindow)
236 connectToScreen(targetScreen ? targetScreen : QGuiApplication::primaryScreen());
237
238 // If your application aborts here, you are probably creating a QWindow
239 // before the screen list is populated.
240 if (Q_UNLIKELY(!parentWindow && !topLevelScreen)) {
241 qFatal("Cannot create window: no screens available");
242 exit(1);
243 }
244 QGuiApplicationPrivate::window_list.prepend(q);
245
246 requestedFormat = QSurfaceFormat::defaultFormat();
247}
248
249/*!
250 \enum QWindow::Visibility
251 \since 5.1
252
253 This enum describes what part of the screen the window occupies or should
254 occupy.
255
256 \value Windowed The window occupies part of the screen, but not necessarily
257 the entire screen. This state will occur only on windowing systems which
258 support showing multiple windows simultaneously. In this state it is
259 possible for the user to move and resize the window manually, if
260 WindowFlags permit it and if it is supported by the windowing system.
261
262 \value Minimized The window is reduced to an entry or icon on the task bar,
263 dock, task list or desktop, depending on how the windowing system handles
264 minimized windows.
265
266 \value Maximized The window occupies one entire screen, and the titlebar is
267 still visible. On most windowing systems this is the state achieved by
268 clicking the maximize button on the toolbar.
269
270 \value FullScreen The window occupies one entire screen, is not resizable,
271 and there is no titlebar. On some platforms which do not support showing
272 multiple simultaneous windows, this can be the usual visibility when the
273 window is not hidden.
274
275 \value AutomaticVisibility This means to give the window a default visible
276 state, which might be fullscreen or windowed depending on the platform.
277 It can be given as a parameter to setVisibility but will never be
278 read back from the visibility accessor.
279
280 \value Hidden The window is not visible in any way, however it may remember
281 a latent visibility which can be restored by setting AutomaticVisibility.
282*/
283
284/*!
285 \property QWindow::visibility
286 \brief the screen-occupation state of the window
287 \since 5.1
288
289 Visibility is whether the window should appear in the windowing system as
290 normal, minimized, maximized, fullscreen or hidden.
291
292 To set the visibility to AutomaticVisibility means to give the window
293 a default visible state, which might be fullscreen or windowed depending on
294 the platform.
295 When reading the visibility property you will always get the actual state,
296 never AutomaticVisibility.
297*/
298QWindow::Visibility QWindow::visibility() const
299{
300 Q_D(const QWindow);
301 return d->visibility;
302}
303
304void QWindow::setVisibility(Visibility v)
305{
306 switch (v) {
307 case Hidden:
308 hide();
309 break;
310 case AutomaticVisibility:
311 show();
312 break;
313 case Windowed:
314 showNormal();
315 break;
316 case Minimized:
317 showMinimized();
318 break;
319 case Maximized:
320 showMaximized();
321 break;
322 case FullScreen:
323 showFullScreen();
324 break;
325 default:
326 Q_ASSERT(false);
327 break;
328 }
329}
330
331/*
332 Subclasses may override this function to run custom setVisible
333 logic. Subclasses that do so must call the base class implementation
334 at some point to make the native window visible, and must not
335 call QWindow::setVisble() since that will recurse back here.
336*/
337void QWindowPrivate::setVisible(bool visible)
338{
339 Q_Q(QWindow);
340
341 if (this->visible != visible) {
342 this->visible = visible;
343 emit q->visibleChanged(visible);
344 updateVisibility();
345 } else if (platformWindow) {
346 // Visibility hasn't changed, and the platform window is in sync
347 return;
348 }
349
350 if (!platformWindow) {
351 // If we have a parent window, but the parent hasn't been created yet, we
352 // can defer creation until the parent is created or we're re-parented.
353 if (parentWindow && !parentWindow->handle())
354 return;
355
356 // We only need to create the window if it's being shown
357 if (visible) {
358 // FIXME: At this point we've already updated the visible state of
359 // the QWindow, so if the platform layer reads the window state during
360 // creation, and reflects that in the native window, it will end up
361 // with a visible window. This may in turn result in resize or expose
362 // events from the platform before we have sent the show event below.
363 q->create();
364 }
365 }
366
367 if (visible) {
368 // remove posted quit events when showing a new window
369 QCoreApplication::removePostedEvents(qApp, QEvent::Quit);
370
371 if (q->type() == Qt::Window) {
372 QGuiApplicationPrivate *app_priv = QGuiApplicationPrivate::instance();
373 QString &firstWindowTitle = app_priv->firstWindowTitle;
374 if (!firstWindowTitle.isEmpty()) {
375 q->setTitle(firstWindowTitle);
376 firstWindowTitle = QString();
377 }
378 if (!app_priv->forcedWindowIcon.isNull())
379 q->setIcon(app_priv->forcedWindowIcon);
380
381 // Handling of the -qwindowgeometry, -geometry command line arguments
382 static bool geometryApplied = false;
383 if (!geometryApplied) {
384 geometryApplied = true;
385 QGuiApplicationPrivate::applyWindowGeometrySpecificationTo(q);
386 }
387 }
388
389 QShowEvent showEvent;
390 QGuiApplication::sendEvent(q, &showEvent);
391 }
392
393 if (q->isModal()) {
394 if (visible)
395 QGuiApplicationPrivate::showModalWindow(q);
396 else
397 QGuiApplicationPrivate::hideModalWindow(q);
398 // QShapedPixmapWindow is used on some platforms for showing a drag pixmap, so don't block
399 // input to this window as it is performing a drag - QTBUG-63846
400 } else if (visible && QGuiApplication::modalWindow()
401#if QT_CONFIG(draganddrop)
402 && !qobject_cast<QShapedPixmapWindow *>(q)
403#endif // QT_CONFIG(draganddrop)
404 ) {
405 QGuiApplicationPrivate::updateBlockedStatus(q);
406 }
407
408#ifndef QT_NO_CURSOR
409 if (visible && (hasCursor || QGuiApplication::overrideCursor()))
410 applyCursor();
411#endif
412
413 if (platformWindow)
414 platformWindow->setVisible(visible);
415
416 if (!visible) {
417 QHideEvent hideEvent;
418 QGuiApplication::sendEvent(q, &hideEvent);
419 }
420}
421
422void QWindowPrivate::updateVisibility()
423{
424 Q_Q(QWindow);
425
426 QWindow::Visibility old = visibility;
427
428 if (!visible)
429 visibility = QWindow::Hidden;
430 else if (windowState & Qt::WindowMinimized)
431 visibility = QWindow::Minimized;
432 else if (windowState & Qt::WindowFullScreen)
433 visibility = QWindow::FullScreen;
434 else if (windowState & Qt::WindowMaximized)
435 visibility = QWindow::Maximized;
436 else
437 visibility = QWindow::Windowed;
438
439 if (visibility != old)
440 emit q->visibilityChanged(visibility);
441}
442
443void QWindowPrivate::updateSiblingPosition(SiblingPosition position)
444{
445 Q_Q(QWindow);
446
447 if (!q->parent())
448 return;
449
450 QObjectList &siblings = q->parent()->d_ptr->children;
451
452 const int siblingCount = siblings.size() - 1;
453 if (siblingCount == 0)
454 return;
455
456 const int currentPosition = siblings.indexOf(q);
457 Q_ASSERT(currentPosition >= 0);
458
459 const int targetPosition = position == PositionTop ? siblingCount : 0;
460
461 if (currentPosition == targetPosition)
462 return;
463
464 siblings.move(currentPosition, targetPosition);
465}
466
467inline bool QWindowPrivate::windowRecreationRequired(QScreen *newScreen) const
468{
469 Q_Q(const QWindow);
470 const QScreen *oldScreen = q->screen();
471 return oldScreen != newScreen && (platformWindow || !oldScreen)
472 && !(oldScreen && oldScreen->virtualSiblings().contains(newScreen));
473}
474
475inline void QWindowPrivate::disconnectFromScreen()
476{
477 if (topLevelScreen)
478 topLevelScreen = nullptr;
479}
480
481void QWindowPrivate::connectToScreen(QScreen *screen)
482{
483 disconnectFromScreen();
484 topLevelScreen = screen;
485}
486
487void QWindowPrivate::emitScreenChangedRecursion(QScreen *newScreen)
488{
489 Q_Q(QWindow);
490 emit q->screenChanged(newScreen);
491 for (QObject *child : q->children()) {
492 if (child->isWindowType())
493 static_cast<QWindow *>(child)->d_func()->emitScreenChangedRecursion(newScreen);
494 }
495}
496
497void QWindowPrivate::setTopLevelScreen(QScreen *newScreen, bool recreate)
498{
499 Q_Q(QWindow);
500 if (parentWindow) {
501 qWarning() << q << '(' << newScreen << "): Attempt to set a screen on a child window.";
502 return;
503 }
504 if (newScreen != topLevelScreen) {
505 const bool shouldRecreate = recreate && windowRecreationRequired(newScreen);
506 const bool shouldShow = visibilityOnDestroy && !topLevelScreen;
507 if (shouldRecreate && platformWindow)
508 q->destroy();
509 connectToScreen(newScreen);
510 if (shouldShow)
511 q->setVisible(true);
512 else if (newScreen && shouldRecreate)
513 create(true);
514 emitScreenChangedRecursion(newScreen);
515 }
516}
517
518void QWindowPrivate::create(bool recursive, WId nativeHandle)
519{
520 Q_Q(QWindow);
521 if (platformWindow)
522 return;
523
524 // avoid losing update requests when re-creating
525 const bool needsUpdate = updateRequestPending;
526 // the platformWindow, if there was one, is now gone, so make this flag reflect reality now
527 updateRequestPending = false;
528
529 if (q->parent())
530 q->parent()->create();
531
532 // QPlatformWindow will poll geometry() during construction below. Set the
533 // screen here so that high-dpi scaling will use the correct scale factor.
534 if (q->isTopLevel()) {
535 if (QScreen *screen = screenForGeometry(geometry))
536 setTopLevelScreen(screen, false);
537 }
538
539 QPlatformIntegration *platformIntegration = QGuiApplicationPrivate::platformIntegration();
540 platformWindow = nativeHandle ? platformIntegration->createForeignWindow(q, nativeHandle)
541 : platformIntegration->createPlatformWindow(q);
542 Q_ASSERT(platformWindow);
543
544 if (!platformWindow) {
545 qWarning() << "Failed to create platform window for" << q << "with flags" << q->flags();
546 return;
547 }
548
549 platformWindow->initialize();
550
551 QObjectList childObjects = q->children();
552 for (int i = 0; i < childObjects.size(); i ++) {
553 QObject *object = childObjects.at(i);
554 if (!object->isWindowType())
555 continue;
556
557 QWindow *childWindow = static_cast<QWindow *>(object);
558 if (recursive)
559 childWindow->d_func()->create(recursive);
560
561 // The child may have had deferred creation due to this window not being created
562 // at the time setVisible was called, so we re-apply the visible state, which
563 // may result in creating the child, and emitting the appropriate signals.
564 if (childWindow->isVisible())
565 childWindow->setVisible(true);
566
567 if (QPlatformWindow *childPlatformWindow = childWindow->d_func()->platformWindow)
568 childPlatformWindow->setParent(this->platformWindow);
569 }
570
571 QPlatformSurfaceEvent e(QPlatformSurfaceEvent::SurfaceCreated);
572 QGuiApplication::sendEvent(q, &e);
573
574 if (needsUpdate)
575 q->requestUpdate();
576}
577
578void QWindowPrivate::clearFocusObject()
579{
580}
581
582// Allows for manipulating the suggested geometry before a resize/move
583// event in derived classes for platforms that support it, for example to
584// implement heightForWidth().
585QRectF QWindowPrivate::closestAcceptableGeometry(const QRectF &rect) const
586{
587 Q_UNUSED(rect);
588 return QRectF();
589}
590
591/*!
592 Sets the \a surfaceType of the window.
593
594 Specifies whether the window is meant for raster rendering with
595 QBackingStore, or OpenGL rendering with QOpenGLContext.
596
597 The surfaceType will be used when the native surface is created
598 in the create() function. Calling this function after the native
599 surface has been created requires calling destroy() and create()
600 to release the old native surface and create a new one.
601
602 \sa QBackingStore, QOpenGLContext, create(), destroy()
603*/
604void QWindow::setSurfaceType(SurfaceType surfaceType)
605{
606 Q_D(QWindow);
607 d->surfaceType = surfaceType;
608}
609
610/*!
611 Returns the surface type of the window.
612
613 \sa setSurfaceType()
614*/
615QWindow::SurfaceType QWindow::surfaceType() const
616{
617 Q_D(const QWindow);
618 return d->surfaceType;
619}
620
621/*!
622 \property QWindow::visible
623 \brief whether the window is visible or not
624
625 This property controls the visibility of the window in the windowing system.
626
627 By default, the window is not visible, you must call setVisible(true), or
628 show() or similar to make it visible.
629
630 \sa show()
631*/
632void QWindow::setVisible(bool visible)
633{
634 Q_D(QWindow);
635
636 d->setVisible(visible);
637}
638
639bool QWindow::isVisible() const
640{
641 Q_D(const QWindow);
642
643 return d->visible;
644}
645
646/*!
647 Allocates the platform resources associated with the window.
648
649 It is at this point that the surface format set using setFormat() gets resolved
650 into an actual native surface. However, the window remains hidden until setVisible() is called.
651
652 Note that it is not usually necessary to call this function directly, as it will be implicitly
653 called by show(), setVisible(), and other functions that require access to the platform
654 resources.
655
656 Call destroy() to free the platform resources if necessary.
657
658 \sa destroy()
659*/
660void QWindow::create()
661{
662 Q_D(QWindow);
663 d->create(false);
664}
665
666/*!
667 Returns the window's platform id.
668
669 For platforms where this id might be useful, the value returned
670 will uniquely represent the window inside the corresponding screen.
671
672 \sa screen()
673*/
674WId QWindow::winId() const
675{
676 Q_D(const QWindow);
677
678 if(!d->platformWindow)
679 const_cast<QWindow *>(this)->create();
680
681 return d->platformWindow->winId();
682}
683
684 /*!
685 Returns the parent window, if any.
686
687 If \a mode is IncludeTransients, then the transient parent is returned
688 if there is no parent.
689
690 A window without a parent is known as a top level window.
691
692 \since 5.9
693*/
694QWindow *QWindow::parent(AncestorMode mode) const
695{
696 Q_D(const QWindow);
697 return d->parentWindow ? d->parentWindow : (mode == IncludeTransients ? transientParent() : nullptr);
698}
699
700/*!
701 Sets the \a parent Window. This will lead to the windowing system managing
702 the clip of the window, so it will be clipped to the \a parent window.
703
704 Setting \a parent to be \nullptr will make the window become a top level
705 window.
706
707 If \a parent is a window created by fromWinId(), then the current window
708 will be embedded inside \a parent, if the platform supports it.
709*/
710void QWindow::setParent(QWindow *parent)
711{
712 parent = nonDesktopParent(parent);
713
714 Q_D(QWindow);
715 if (d->parentWindow == parent)
716 return;
717
718 QScreen *newScreen = parent ? parent->screen() : screen();
719 if (d->windowRecreationRequired(newScreen)) {
720 qWarning() << this << '(' << parent << "): Cannot change screens (" << screen() << newScreen << ')';
721 return;
722 }
723
724 QObject::setParent(parent);
725 d->parentWindow = parent;
726
727 if (parent)
728 d->disconnectFromScreen();
729 else
730 d->connectToScreen(newScreen);
731
732 // If we were set visible, but not created because we were a child, and we're now
733 // re-parented into a created parent, or to being a top level, we need re-apply the
734 // visibility state, which will also create.
735 if (isVisible() && (!parent || parent->handle()))
736 setVisible(true);
737
738 if (d->platformWindow) {
739 if (parent)
740 parent->create();
741
742 d->platformWindow->setParent(parent ? parent->d_func()->platformWindow : nullptr);
743 }
744
745 QGuiApplicationPrivate::updateBlockedStatus(this);
746}
747
748/*!
749 Returns whether the window is top level, i.e. has no parent window.
750*/
751bool QWindow::isTopLevel() const
752{
753 Q_D(const QWindow);
754 return d->parentWindow == nullptr;
755}
756
757/*!
758 Returns whether the window is modal.
759
760 A modal window prevents other windows from getting any input.
761
762 \sa QWindow::modality
763*/
764bool QWindow::isModal() const
765{
766 Q_D(const QWindow);
767 return d->modality != Qt::NonModal;
768}
769
770/*! \property QWindow::modality
771 \brief the modality of the window
772
773 A modal window prevents other windows from receiving input events. Qt
774 supports two types of modality: Qt::WindowModal and Qt::ApplicationModal.
775
776 By default, this property is Qt::NonModal
777
778 \sa Qt::WindowModality
779*/
780
781Qt::WindowModality QWindow::modality() const
782{
783 Q_D(const QWindow);
784 return d->modality;
785}
786
787void QWindow::setModality(Qt::WindowModality modality)
788{
789 Q_D(QWindow);
790 if (d->modality == modality)
791 return;
792 d->modality = modality;
793 emit modalityChanged(modality);
794}
795
796/*! \fn void QWindow::modalityChanged(Qt::WindowModality modality)
797
798 This signal is emitted when the Qwindow::modality property changes to \a modality.
799*/
800
801/*!
802 Sets the window's surface \a format.
803
804 The format determines properties such as color depth, alpha, depth and
805 stencil buffer size, etc. For example, to give a window a transparent
806 background (provided that the window system supports compositing, and
807 provided that other content in the window does not make it opaque again):
808
809 \code
810 QSurfaceFormat format;
811 format.setAlphaBufferSize(8);
812 window.setFormat(format);
813 \endcode
814
815 The surface format will be resolved in the create() function. Calling
816 this function after create() has been called will not re-resolve the
817 surface format of the native surface.
818
819 When the format is not explicitly set via this function, the format returned
820 by QSurfaceFormat::defaultFormat() will be used. This means that when having
821 multiple windows, individual calls to this function can be replaced by one
822 single call to QSurfaceFormat::setDefaultFormat() before creating the first
823 window.
824
825 \sa create(), destroy(), QSurfaceFormat::setDefaultFormat()
826*/
827void QWindow::setFormat(const QSurfaceFormat &format)
828{
829 Q_D(QWindow);
830 d->requestedFormat = format;
831}
832
833/*!
834 Returns the requested surface format of this window.
835
836 If the requested format was not supported by the platform implementation,
837 the requestedFormat will differ from the actual window format.
838
839 This is the value set with setFormat().
840
841 \sa setFormat(), format()
842 */
843QSurfaceFormat QWindow::requestedFormat() const
844{
845 Q_D(const QWindow);
846 return d->requestedFormat;
847}
848
849/*!
850 Returns the actual format of this window.
851
852 After the window has been created, this function will return the actual surface format
853 of the window. It might differ from the requested format if the requested format could
854 not be fulfilled by the platform. It might also be a superset, for example certain
855 buffer sizes may be larger than requested.
856
857 \note Depending on the platform, certain values in this surface format may still
858 contain the requested values, that is, the values that have been passed to
859 setFormat(). Typical examples are the OpenGL version, profile and options. These may
860 not get updated during create() since these are context specific and a single window
861 may be used together with multiple contexts over its lifetime. Use the
862 QOpenGLContext's format() instead to query such values.
863
864 \sa create(), requestedFormat(), QOpenGLContext::format()
865*/
866QSurfaceFormat QWindow::format() const
867{
868 Q_D(const QWindow);
869 if (d->platformWindow)
870 return d->platformWindow->format();
871 return d->requestedFormat;
872}
873
874/*!
875 \property QWindow::flags
876 \brief the window flags of the window
877
878 The window flags control the window's appearance in the windowing system,
879 whether it's a dialog, popup, or a regular window, and whether it should
880 have a title bar, etc.
881
882 The actual window flags might differ from the flags set with setFlags()
883 if the requested flags could not be fulfilled.
884
885 \sa setFlag()
886*/
887void QWindow::setFlags(Qt::WindowFlags flags)
888{
889 Q_D(QWindow);
890 if (d->windowFlags == flags)
891 return;
892
893 if (d->platformWindow)
894 d->platformWindow->setWindowFlags(flags);
895 d->windowFlags = flags;
896}
897
898Qt::WindowFlags QWindow::flags() const
899{
900 Q_D(const QWindow);
901 Qt::WindowFlags flags = d->windowFlags;
902
903 if (d->platformWindow && d->platformWindow->isForeignWindow())
904 flags |= Qt::ForeignWindow;
905
906 return flags;
907}
908
909/*!
910 \since 5.9
911
912 Sets the window flag \a flag on this window if \a on is true;
913 otherwise clears the flag.
914
915 \sa setFlags(), flags(), type()
916*/
917void QWindow::setFlag(Qt::WindowType flag, bool on)
918{
919 Q_D(QWindow);
920 if (on)
921 setFlags(d->windowFlags | flag);
922 else
923 setFlags(d->windowFlags & ~flag);
924}
925
926/*!
927 Returns the type of the window.
928
929 This returns the part of the window flags that represents
930 whether the window is a dialog, tooltip, popup, regular window, etc.
931
932 \sa flags(), setFlags()
933*/
934Qt::WindowType QWindow::type() const
935{
936 return static_cast<Qt::WindowType>(int(flags() & Qt::WindowType_Mask));
937}
938
939/*!
940 \property QWindow::title
941 \brief the window's title in the windowing system
942
943 The window title might appear in the title area of the window decorations,
944 depending on the windowing system and the window flags. It might also
945 be used by the windowing system to identify the window in other contexts,
946 such as in the task switcher.
947
948 \sa flags()
949*/
950void QWindow::setTitle(const QString &title)
951{
952 Q_D(QWindow);
953 bool changed = false;
954 if (d->windowTitle != title) {
955 d->windowTitle = title;
956 changed = true;
957 }
958 if (d->platformWindow && type() != Qt::Desktop)
959 d->platformWindow->setWindowTitle(title);
960 if (changed)
961 emit windowTitleChanged(title);
962}
963
964QString QWindow::title() const
965{
966 Q_D(const QWindow);
967 return d->windowTitle;
968}
969
970/*!
971 \brief set the file name this window is representing.
972
973 The windowing system might use \a filePath to display the
974 path of the document this window is representing in the tile bar.
975
976*/
977void QWindow::setFilePath(const QString &filePath)
978{
979 Q_D(QWindow);
980 d->windowFilePath = filePath;
981 if (d->platformWindow)
982 d->platformWindow->setWindowFilePath(filePath);
983}
984
985/*!
986 \brief the file name this window is representing.
987
988 \sa setFilePath()
989*/
990QString QWindow::filePath() const
991{
992 Q_D(const QWindow);
993 return d->windowFilePath;
994}
995
996/*!
997 \brief Sets the window's \a icon in the windowing system
998
999 The window icon might be used by the windowing system for example to
1000 decorate the window, and/or in the task switcher.
1001
1002 \note On \macos, the window title bar icon is meant for windows representing
1003 documents, and will only show up if a file path is also set.
1004
1005 \sa setFilePath()
1006*/
1007void QWindow::setIcon(const QIcon &icon)
1008{
1009 Q_D(QWindow);
1010 d->windowIcon = icon;
1011 if (d->platformWindow)
1012 d->platformWindow->setWindowIcon(icon);
1013 QEvent e(QEvent::WindowIconChange);
1014 QCoreApplication::sendEvent(this, &e);
1015}
1016
1017/*!
1018 \brief Returns the window's icon in the windowing system
1019
1020 \sa setIcon()
1021*/
1022QIcon QWindow::icon() const
1023{
1024 Q_D(const QWindow);
1025 if (d->windowIcon.isNull())
1026 return QGuiApplication::windowIcon();
1027 return d->windowIcon;
1028}
1029
1030/*!
1031 Raise the window in the windowing system.
1032
1033 Requests that the window be raised to appear above other windows.
1034*/
1035void QWindow::raise()
1036{
1037 Q_D(QWindow);
1038
1039 d->updateSiblingPosition(QWindowPrivate::PositionTop);
1040
1041 if (d->platformWindow)
1042 d->platformWindow->raise();
1043}
1044
1045/*!
1046 Lower the window in the windowing system.
1047
1048 Requests that the window be lowered to appear below other windows.
1049*/
1050void QWindow::lower()
1051{
1052 Q_D(QWindow);
1053
1054 d->updateSiblingPosition(QWindowPrivate::PositionBottom);
1055
1056 if (d->platformWindow)
1057 d->platformWindow->lower();
1058}
1059
1060/*!
1061 \brief Start a system-specific resize operation
1062 \since 5.15
1063
1064 Calling this will start an interactive resize operation on the window by platforms
1065 that support it. The actual behavior may vary depending on the platform. Usually,
1066 it will make the window resize so that its edge follows the mouse cursor.
1067
1068 On platforms that support it, this method of resizing windows is preferred over
1069 \c setGeometry, because it allows a more native look-and-feel of resizing windows, e.g.
1070 letting the window manager snap this window against other windows, or special resizing
1071 behavior with animations when dragged to the edge of the screen.
1072
1073 \a edges should either be a single edge, or two adjacent edges (a corner). Other values
1074 are not allowed.
1075
1076 Returns true if the operation was supported by the system.
1077*/
1078bool QWindow::startSystemResize(Qt::Edges edges)
1079{
1080 Q_D(QWindow);
1081 if (Q_UNLIKELY(!isVisible() || !d->platformWindow || d->maximumSize == d->minimumSize))
1082 return false;
1083
1084 const bool isSingleEdge = edges == Qt::TopEdge || edges == Qt::RightEdge || edges == Qt::BottomEdge || edges == Qt::LeftEdge;
1085 const bool isCorner =
1086 edges == (Qt::TopEdge | Qt::LeftEdge) ||
1087 edges == (Qt::TopEdge | Qt::RightEdge) ||
1088 edges == (Qt::BottomEdge | Qt::RightEdge) ||
1089 edges == (Qt::BottomEdge | Qt::LeftEdge);
1090
1091 if (Q_UNLIKELY(!isSingleEdge && !isCorner)) {
1092 qWarning() << "Invalid edges" << edges << "passed to QWindow::startSystemResize, ignoring.";
1093 return false;
1094 }
1095
1096 return d->platformWindow->startSystemResize(edges);
1097}
1098
1099/*!
1100 \brief Start a system-specific move operation
1101 \since 5.15
1102
1103 Calling this will start an interactive move operation on the window by platforms
1104 that support it. The actual behavior may vary depending on the platform. Usually,
1105 it will make the window follow the mouse cursor until a mouse button is released.
1106
1107 On platforms that support it, this method of moving windows is preferred over
1108 \c setPosition, because it allows a more native look-and-feel of moving windows, e.g.
1109 letting the window manager snap this window against other windows, or special tiling
1110 or resizing behavior with animations when dragged to the edge of the screen.
1111 Furthermore, on some platforms such as Wayland, \c setPosition is not supported, so
1112 this is the only way the application can influence its position.
1113
1114 Returns true if the operation was supported by the system.
1115*/
1116bool QWindow::startSystemMove()
1117{
1118 Q_D(QWindow);
1119 if (Q_UNLIKELY(!isVisible() || !d->platformWindow))
1120 return false;
1121
1122 return d->platformWindow->startSystemMove();
1123}
1124
1125/*!
1126 \property QWindow::opacity
1127 \brief The opacity of the window in the windowing system.
1128 \since 5.1
1129
1130 If the windowing system supports window opacity, this can be used to fade the
1131 window in and out, or to make it semitransparent.
1132
1133 A value of 1.0 or above is treated as fully opaque, whereas a value of 0.0 or below
1134 is treated as fully transparent. Values inbetween represent varying levels of
1135 translucency between the two extremes.
1136
1137 The default value is 1.0.
1138*/
1139void QWindow::setOpacity(qreal level)
1140{
1141 Q_D(QWindow);
1142 if (level == d->opacity)
1143 return;
1144 d->opacity = level;
1145 if (d->platformWindow) {
1146 d->platformWindow->setOpacity(level);
1147 emit opacityChanged(level);
1148 }
1149}
1150
1151qreal QWindow::opacity() const
1152{
1153 Q_D(const QWindow);
1154 return d->opacity;
1155}
1156
1157/*!
1158 Sets the mask of the window.
1159
1160 The mask is a hint to the windowing system that the application does not
1161 want to receive mouse or touch input outside the given \a region.
1162
1163 The window manager may or may not choose to display any areas of the window
1164 not included in the mask, thus it is the application's responsibility to
1165 clear to transparent the areas that are not part of the mask.
1166*/
1167void QWindow::setMask(const QRegion &region)
1168{
1169 Q_D(QWindow);
1170 if (d->platformWindow)
1171 d->platformWindow->setMask(QHighDpi::toNativeLocalRegion(region, this));
1172 d->mask = region;
1173}
1174
1175/*!
1176 Returns the mask set on the window.
1177
1178 The mask is a hint to the windowing system that the application does not
1179 want to receive mouse or touch input outside the given region.
1180*/
1181QRegion QWindow::mask() const
1182{
1183 Q_D(const QWindow);
1184 return d->mask;
1185}
1186
1187/*!
1188 Requests the window to be activated, i.e. receive keyboard focus.
1189
1190 \sa isActive(), QGuiApplication::focusWindow(), QWindowsWindowFunctions::setWindowActivationBehavior()
1191*/
1192void QWindow::requestActivate()
1193{
1194 Q_D(QWindow);
1195 if (flags() & Qt::WindowDoesNotAcceptFocus) {
1196 qWarning() << "requestActivate() called for " << this << " which has Qt::WindowDoesNotAcceptFocus set.";
1197 return;
1198 }
1199 if (d->platformWindow)
1200 d->platformWindow->requestActivateWindow();
1201}
1202
1203/*!
1204 Returns if this window is exposed in the windowing system.
1205
1206 When the window is not exposed, it is shown by the application
1207 but it is still not showing in the windowing system, so the application
1208 should minimize animations and other graphical activities.
1209
1210 An exposeEvent() is sent every time this value changes.
1211
1212 \sa exposeEvent()
1213*/
1214bool QWindow::isExposed() const
1215{
1216 Q_D(const QWindow);
1217 return d->exposed;
1218}
1219
1220/*!
1221 \property QWindow::active
1222 \brief the active status of the window
1223 \since 5.1
1224
1225 \sa requestActivate()
1226*/
1227
1228/*!
1229 Returns \c true if the window should appear active from a style perspective.
1230
1231 This is the case for the window that has input focus as well as windows
1232 that are in the same parent / transient parent chain as the focus window.
1233
1234 To get the window that currently has focus, use QGuiApplication::focusWindow().
1235*/
1236bool QWindow::isActive() const
1237{
1238 Q_D(const QWindow);
1239 if (!d->platformWindow)
1240 return false;
1241
1242 QWindow *focus = QGuiApplication::focusWindow();
1243
1244 // Means the whole application lost the focus
1245 if (!focus)
1246 return false;
1247
1248 if (focus == this)
1249 return true;
1250
1251 if (QWindow *p = parent(IncludeTransients))
1252 return p->isActive();
1253 else
1254 return isAncestorOf(focus);
1255}
1256
1257/*!
1258 \property QWindow::contentOrientation
1259 \brief the orientation of the window's contents
1260
1261 This is a hint to the window manager in case it needs to display
1262 additional content like popups, dialogs, status bars, or similar
1263 in relation to the window.
1264
1265 The recommended orientation is QScreen::orientation() but
1266 an application doesn't have to support all possible orientations,
1267 and thus can opt to ignore the current screen orientation.
1268
1269 The difference between the window and the content orientation
1270 determines how much to rotate the content by. QScreen::angleBetween(),
1271 QScreen::transformBetween(), and QScreen::mapBetween() can be used
1272 to compute the necessary transform.
1273
1274 The default value is Qt::PrimaryOrientation
1275*/
1276void QWindow::reportContentOrientationChange(Qt::ScreenOrientation orientation)
1277{
1278 Q_D(QWindow);
1279 if (d->contentOrientation == orientation)
1280 return;
1281 if (d->platformWindow)
1282 d->platformWindow->handleContentOrientationChange(orientation);
1283 d->contentOrientation = orientation;
1284 emit contentOrientationChanged(orientation);
1285}
1286
1287Qt::ScreenOrientation QWindow::contentOrientation() const
1288{
1289 Q_D(const QWindow);
1290 return d->contentOrientation;
1291}
1292
1293/*!
1294 Returns the ratio between physical pixels and device-independent pixels
1295 for the window. This value is dependent on the screen the window is on,
1296 and may change when the window is moved.
1297
1298 Common values are 1.0 on normal displays and 2.0 on Apple "retina" displays.
1299
1300 \note For windows not backed by a platform window, meaning that create() was not
1301 called, the function will fall back to the associated QScreen's device pixel ratio.
1302
1303 \sa QScreen::devicePixelRatio()
1304*/
1305qreal QWindow::devicePixelRatio() const
1306{
1307 Q_D(const QWindow);
1308
1309 // If there is no platform window use the associated screen's devicePixelRatio,
1310 // which typically is the primary screen and will be correct for single-display
1311 // systems (a very common case).
1312 if (!d->platformWindow)
1313 return screen()->devicePixelRatio();
1314
1315 return d->platformWindow->devicePixelRatio() * QHighDpiScaling::factor(this);
1316}
1317
1318Qt::WindowState QWindowPrivate::effectiveState(Qt::WindowStates state)
1319{
1320 if (state & Qt::WindowMinimized)
1321 return Qt::WindowMinimized;
1322 else if (state & Qt::WindowFullScreen)
1323 return Qt::WindowFullScreen;
1324 else if (state & Qt::WindowMaximized)
1325 return Qt::WindowMaximized;
1326 return Qt::WindowNoState;
1327}
1328
1329/*!
1330 \brief set the screen-occupation state of the window
1331
1332 The window \a state represents whether the window appears in the
1333 windowing system as maximized, minimized, fullscreen, or normal.
1334
1335 The enum value Qt::WindowActive is not an accepted parameter.
1336
1337 \sa showNormal(), showFullScreen(), showMinimized(), showMaximized(), setWindowStates()
1338*/
1339void QWindow::setWindowState(Qt::WindowState state)
1340{
1341 setWindowStates(state);
1342}
1343
1344/*!
1345 \brief set the screen-occupation state of the window
1346 \since 5.10
1347
1348 The window \a state represents whether the window appears in the
1349 windowing system as maximized, minimized and/or fullscreen.
1350
1351 The window can be in a combination of several states. For example, if
1352 the window is both minimized and maximized, the window will appear
1353 minimized, but clicking on the task bar entry will restore it to the
1354 maximized state.
1355
1356 The enum value Qt::WindowActive should not be set.
1357
1358 \sa showNormal(), showFullScreen(), showMinimized(), showMaximized()
1359 */
1360void QWindow::setWindowStates(Qt::WindowStates state)
1361{
1362 Q_D(QWindow);
1363 if (state & Qt::WindowActive) {
1364 qWarning("QWindow::setWindowStates does not accept Qt::WindowActive");
1365 state &= ~Qt::WindowActive;
1366 }
1367
1368 if (d->platformWindow)
1369 d->platformWindow->setWindowState(state);
1370 d->windowState = state;
1371 emit windowStateChanged(QWindowPrivate::effectiveState(d->windowState));
1372 d->updateVisibility();
1373}
1374
1375/*!
1376 \brief the screen-occupation state of the window
1377
1378 \sa setWindowState(), windowStates()
1379*/
1380Qt::WindowState QWindow::windowState() const
1381{
1382 Q_D(const QWindow);
1383 return QWindowPrivate::effectiveState(d->windowState);
1384}
1385
1386/*!
1387 \brief the screen-occupation state of the window
1388 \since 5.10
1389
1390 The window can be in a combination of several states. For example, if
1391 the window is both minimized and maximized, the window will appear
1392 minimized, but clicking on the task bar entry will restore it to
1393 the maximized state.
1394
1395 \sa setWindowStates()
1396*/
1397Qt::WindowStates QWindow::windowStates() const
1398{
1399 Q_D(const QWindow);
1400 return d->windowState;
1401}
1402
1403/*!
1404 \fn QWindow::windowStateChanged(Qt::WindowState windowState)
1405
1406 This signal is emitted when the \a windowState changes, either
1407 by being set explicitly with setWindowStates(), or automatically when
1408 the user clicks one of the titlebar buttons or by other means.
1409*/
1410
1411/*!
1412 \property QWindow::transientParent
1413 \brief the window for which this window is a transient pop-up
1414 \since 5.13
1415
1416 This is a hint to the window manager that this window is a dialog or pop-up
1417 on behalf of the transient parent.
1418
1419 In order to cause the window to be centered above its transient \a parent by
1420 default, depending on the window manager, it may also be necessary to call
1421 setFlags() with a suitable \l Qt::WindowType (such as \c Qt::Dialog).
1422
1423 \sa parent()
1424*/
1425void QWindow::setTransientParent(QWindow *parent)
1426{
1427 Q_D(QWindow);
1428 if (parent && !parent->isTopLevel()) {
1429 qWarning() << parent << "must be a top level window.";
1430 return;
1431 }
1432 if (parent == this) {
1433 qWarning() << "transient parent" << parent << "cannot be same as window";
1434 return;
1435 }
1436
1437 d->transientParent = parent;
1438
1439 QGuiApplicationPrivate::updateBlockedStatus(this);
1440 emit transientParentChanged(parent);
1441}
1442
1443QWindow *QWindow::transientParent() const
1444{
1445 Q_D(const QWindow);
1446 return d->transientParent.data();
1447}
1448
1449/*
1450 The setter for the QWindow::transientParent property.
1451 The only reason this exists is to set the transientParentPropertySet flag
1452 so that Qt Quick knows whether it was set programmatically (because of
1453 Window declaration context) or because the user set the property.
1454*/
1455void QWindowPrivate::setTransientParent(QWindow *parent)
1456{
1457 Q_Q(QWindow);
1458 q->setTransientParent(parent);
1459 transientParentPropertySet = true;
1460}
1461
1462/*!
1463 \enum QWindow::AncestorMode
1464
1465 This enum is used to control whether or not transient parents
1466 should be considered ancestors.
1467
1468 \value ExcludeTransients Transient parents are not considered ancestors.
1469 \value IncludeTransients Transient parents are considered ancestors.
1470*/
1471
1472/*!
1473 Returns \c true if the window is an ancestor of the given \a child. If \a mode
1474 is IncludeTransients, then transient parents are also considered ancestors.
1475*/
1476bool QWindow::isAncestorOf(const QWindow *child, AncestorMode mode) const
1477{
1478 if (child->parent() == this || (mode == IncludeTransients && child->transientParent() == this))
1479 return true;
1480
1481 if (QWindow *parent = child->parent(mode)) {
1482 if (isAncestorOf(parent, mode))
1483 return true;
1484 } else if (handle() && child->handle()) {
1485 if (handle()->isAncestorOf(child->handle()))
1486 return true;
1487 }
1488
1489 return false;
1490}
1491
1492/*!
1493 Returns the minimum size of the window.
1494
1495 \sa setMinimumSize()
1496*/
1497QSize QWindow::minimumSize() const
1498{
1499 Q_D(const QWindow);
1500 return d->minimumSize;
1501}
1502
1503/*!
1504 Returns the maximum size of the window.
1505
1506 \sa setMaximumSize()
1507*/
1508QSize QWindow::maximumSize() const
1509{
1510 Q_D(const QWindow);
1511 return d->maximumSize;
1512}
1513
1514/*!
1515 Returns the base size of the window.
1516
1517 \sa setBaseSize()
1518*/
1519QSize QWindow::baseSize() const
1520{
1521 Q_D(const QWindow);
1522 return d->baseSize;
1523}
1524
1525/*!
1526 Returns the size increment of the window.
1527
1528 \sa setSizeIncrement()
1529*/
1530QSize QWindow::sizeIncrement() const
1531{
1532 Q_D(const QWindow);
1533 return d->sizeIncrement;
1534}
1535
1536/*!
1537 Sets the minimum size of the window.
1538
1539 This is a hint to the window manager to prevent resizing below the specified \a size.
1540
1541 \sa setMaximumSize(), minimumSize()
1542*/
1543void QWindow::setMinimumSize(const QSize &size)
1544{
1545 Q_D(QWindow);
1546 QSize adjustedSize = QSize(qBound(0, size.width(), QWINDOWSIZE_MAX), qBound(0, size.height(), QWINDOWSIZE_MAX));
1547 if (d->minimumSize == adjustedSize)
1548 return;
1549 QSize oldSize = d->minimumSize;
1550 d->minimumSize = adjustedSize;
1551 if (d->platformWindow && isTopLevel())
1552 d->platformWindow->propagateSizeHints();
1553 if (d->minimumSize.width() != oldSize.width())
1554 emit minimumWidthChanged(d->minimumSize.width());
1555 if (d->minimumSize.height() != oldSize.height())
1556 emit minimumHeightChanged(d->minimumSize.height());
1557}
1558
1559/*!
1560 \property QWindow::x
1561 \brief the x position of the window's geometry
1562*/
1563void QWindow::setX(int arg)
1564{
1565 Q_D(QWindow);
1566 if (x() != arg)
1567 setGeometry(QRect(arg, y(), width(), height()));
1568 else
1569 d->positionAutomatic = false;
1570}
1571
1572/*!
1573 \property QWindow::y
1574 \brief the y position of the window's geometry
1575*/
1576void QWindow::setY(int arg)
1577{
1578 Q_D(QWindow);
1579 if (y() != arg)
1580 setGeometry(QRect(x(), arg, width(), height()));
1581 else
1582 d->positionAutomatic = false;
1583}
1584
1585/*!
1586 \property QWindow::width
1587 \brief the width of the window's geometry
1588*/
1589void QWindow::setWidth(int arg)
1590{
1591 if (width() != arg)
1592 resize(arg, height());
1593}
1594
1595/*!
1596 \property QWindow::height
1597 \brief the height of the window's geometry
1598*/
1599void QWindow::setHeight(int arg)
1600{
1601 if (height() != arg)
1602 resize(width(), arg);
1603}
1604
1605/*!
1606 \property QWindow::minimumWidth
1607 \brief the minimum width of the window's geometry
1608*/
1609void QWindow::setMinimumWidth(int w)
1610{
1611 setMinimumSize(QSize(w, minimumHeight()));
1612}
1613
1614/*!
1615 \property QWindow::minimumHeight
1616 \brief the minimum height of the window's geometry
1617*/
1618void QWindow::setMinimumHeight(int h)
1619{
1620 setMinimumSize(QSize(minimumWidth(), h));
1621}
1622
1623/*!
1624 Sets the maximum size of the window.
1625
1626 This is a hint to the window manager to prevent resizing above the specified \a size.
1627
1628 \sa setMinimumSize(), maximumSize()
1629*/
1630void QWindow::setMaximumSize(const QSize &size)
1631{
1632 Q_D(QWindow);
1633 QSize adjustedSize = QSize(qBound(0, size.width(), QWINDOWSIZE_MAX), qBound(0, size.height(), QWINDOWSIZE_MAX));
1634 if (d->maximumSize == adjustedSize)
1635 return;
1636 QSize oldSize = d->maximumSize;
1637 d->maximumSize = adjustedSize;
1638 if (d->platformWindow && isTopLevel())
1639 d->platformWindow->propagateSizeHints();
1640 if (d->maximumSize.width() != oldSize.width())
1641 emit maximumWidthChanged(d->maximumSize.width());
1642 if (d->maximumSize.height() != oldSize.height())
1643 emit maximumHeightChanged(d->maximumSize.height());
1644}
1645
1646/*!
1647 \property QWindow::maximumWidth
1648 \brief the maximum width of the window's geometry
1649*/
1650void QWindow::setMaximumWidth(int w)
1651{
1652 setMaximumSize(QSize(w, maximumHeight()));
1653}
1654
1655/*!
1656 \property QWindow::maximumHeight
1657 \brief the maximum height of the window's geometry
1658*/
1659void QWindow::setMaximumHeight(int h)
1660{
1661 setMaximumSize(QSize(maximumWidth(), h));
1662}
1663
1664/*!
1665 Sets the base \a size of the window.
1666
1667 The base size is used to calculate a proper window size if the
1668 window defines sizeIncrement().
1669
1670 \sa setMinimumSize(), setMaximumSize(), setSizeIncrement(), baseSize()
1671*/
1672void QWindow::setBaseSize(const QSize &size)
1673{
1674 Q_D(QWindow);
1675 if (d->baseSize == size)
1676 return;
1677 d->baseSize = size;
1678 if (d->platformWindow && isTopLevel())
1679 d->platformWindow->propagateSizeHints();
1680}
1681
1682/*!
1683 Sets the size increment (\a size) of the window.
1684
1685 When the user resizes the window, the size will move in steps of
1686 sizeIncrement().width() pixels horizontally and
1687 sizeIncrement().height() pixels vertically, with baseSize() as the
1688 basis.
1689
1690 By default, this property contains a size with zero width and height.
1691
1692 The windowing system might not support size increments.
1693
1694 \sa setBaseSize(), setMinimumSize(), setMaximumSize()
1695*/
1696void QWindow::setSizeIncrement(const QSize &size)
1697{
1698 Q_D(QWindow);
1699 if (d->sizeIncrement == size)
1700 return;
1701 d->sizeIncrement = size;
1702 if (d->platformWindow && isTopLevel())
1703 d->platformWindow->propagateSizeHints();
1704}
1705
1706/*!
1707 Sets the geometry of the window, excluding its window frame, to a
1708 rectangle constructed from \a posx, \a posy, \a w and \a h.
1709
1710 The geometry is in relation to the virtualGeometry() of its screen.
1711
1712 \sa geometry()
1713*/
1714void QWindow::setGeometry(int posx, int posy, int w, int h)
1715{
1716 setGeometry(QRect(posx, posy, w, h));
1717}
1718
1719/*!
1720 \brief Sets the geometry of the window, excluding its window frame, to \a rect.
1721
1722 The geometry is in relation to the virtualGeometry() of its screen.
1723
1724 \sa geometry()
1725*/
1726void QWindow::setGeometry(const QRect &rect)
1727{
1728 Q_D(QWindow);
1729 d->positionAutomatic = false;
1730 const QRect oldRect = geometry();
1731 if (rect == oldRect)
1732 return;
1733
1734 d->positionPolicy = QWindowPrivate::WindowFrameExclusive;
1735 if (d->platformWindow) {
1736 QScreen *newScreen = d->screenForGeometry(rect);
1737 if (newScreen && isTopLevel())
1738 d->setTopLevelScreen(newScreen, true);
1739
1740 QRect nativeRect;
1741 if (newScreen && isTopLevel())
1742 nativeRect = QHighDpi::toNativePixels(rect, newScreen);
1743 else
1744 nativeRect = QHighDpi::toNativeLocalPosition(rect, newScreen);
1745 d->platformWindow->setGeometry(nativeRect);
1746 } else {
1747 d->geometry = rect;
1748
1749 if (rect.x() != oldRect.x())
1750 emit xChanged(rect.x());
1751 if (rect.y() != oldRect.y())
1752 emit yChanged(rect.y());
1753 if (rect.width() != oldRect.width())
1754 emit widthChanged(rect.width());
1755 if (rect.height() != oldRect.height())
1756 emit heightChanged(rect.height());
1757 }
1758}
1759
1760/*
1761 This is equivalent to QPlatformWindow::screenForGeometry, but in platform
1762 independent coordinates. The duplication is unfortunate, but there is a
1763 chicken and egg problem here: we cannot convert to native coordinates
1764 before we know which screen we are on.
1765*/
1766QScreen *QWindowPrivate::screenForGeometry(const QRect &newGeometry) const
1767{
1768 Q_Q(const QWindow);
1769 QScreen *currentScreen = q->screen();
1770 QScreen *fallback = currentScreen;
1771 QPoint center = newGeometry.center();
1772 if (!q->parent() && currentScreen && !currentScreen->geometry().contains(center)) {
1773 const auto screens = currentScreen->virtualSiblings();
1774 for (QScreen* screen : screens) {
1775 if (screen->geometry().contains(center))
1776 return screen;
1777 if (screen->geometry().intersects(newGeometry))
1778 fallback = screen;
1779 }
1780 }
1781 return fallback;
1782}
1783
1784
1785/*!
1786 Returns the geometry of the window, excluding its window frame.
1787
1788 The geometry is in relation to the virtualGeometry() of its screen.
1789
1790 \sa frameMargins(), frameGeometry()
1791*/
1792QRect QWindow::geometry() const
1793{
1794 Q_D(const QWindow);
1795 if (d->platformWindow) {
1796 const auto nativeGeometry = d->platformWindow->geometry();
1797 return QHighDpi::fromNativeWindowGeometry(nativeGeometry, this);
1798 }
1799 return d->geometry;
1800}
1801
1802/*!
1803 Returns the window frame margins surrounding the window.
1804
1805 \sa geometry(), frameGeometry()
1806*/
1807QMargins QWindow::frameMargins() const
1808{
1809 Q_D(const QWindow);
1810 if (d->platformWindow)
1811 return QHighDpi::fromNativePixels(d->platformWindow->frameMargins(), this);
1812 return QMargins();
1813}
1814
1815/*!
1816 Returns the geometry of the window, including its window frame.
1817
1818 The geometry is in relation to the virtualGeometry() of its screen.
1819
1820 \sa geometry(), frameMargins()
1821*/
1822QRect QWindow::frameGeometry() const
1823{
1824 Q_D(const QWindow);
1825 if (d->platformWindow) {
1826 QMargins m = frameMargins();
1827 return QHighDpi::fromNativeWindowGeometry(d->platformWindow->geometry(), this).adjusted(-m.left(), -m.top(), m.right(), m.bottom());
1828 }
1829 return d->geometry;
1830}
1831
1832/*!
1833 Returns the top left position of the window, including its window frame.
1834
1835 This returns the same value as frameGeometry().topLeft().
1836
1837 \sa geometry(), frameGeometry()
1838*/
1839QPoint QWindow::framePosition() const
1840{
1841 Q_D(const QWindow);
1842 if (d->platformWindow) {
1843 QMargins margins = frameMargins();
1844 return QHighDpi::fromNativeWindowGeometry(d->platformWindow->geometry().topLeft(), this) - QPoint(margins.left(), margins.top());
1845 }
1846 return d->geometry.topLeft();
1847}
1848
1849/*!
1850 Sets the upper left position of the window (\a point) including its window frame.
1851
1852 The position is in relation to the virtualGeometry() of its screen.
1853
1854 \sa setGeometry(), frameGeometry()
1855*/
1856void QWindow::setFramePosition(const QPoint &point)
1857{
1858 Q_D(QWindow);
1859 d->positionPolicy = QWindowPrivate::WindowFrameInclusive;
1860 d->positionAutomatic = false;
1861 if (d->platformWindow) {
1862 d->platformWindow->setGeometry(QHighDpi::toNativeWindowGeometry(QRect(point, size()), this));
1863 } else {
1864 d->geometry.moveTopLeft(point);
1865 }
1866}
1867
1868/*!
1869 \brief set the position of the window on the desktop to \a pt
1870
1871 The position is in relation to the virtualGeometry() of its screen.
1872
1873 For interactively moving windows, see startSystemMove(). For interactively
1874 resizing windows, see startSystemResize().
1875
1876 \sa position(), startSystemMove()
1877*/
1878void QWindow::setPosition(const QPoint &pt)
1879{
1880 setGeometry(QRect(pt, size()));
1881}
1882
1883/*!
1884 \brief set the position of the window on the desktop to \a posx, \a posy
1885
1886 The position is in relation to the virtualGeometry() of its screen.
1887
1888 \sa position()
1889*/
1890void QWindow::setPosition(int posx, int posy)
1891{
1892 setPosition(QPoint(posx, posy));
1893}
1894
1895/*!
1896 \fn QPoint QWindow::position() const
1897 \brief Returns the position of the window on the desktop excluding any window frame
1898
1899 \sa setPosition()
1900*/
1901
1902/*!
1903 \fn QSize QWindow::size() const
1904 \brief Returns the size of the window excluding any window frame
1905
1906 \sa resize()
1907*/
1908
1909/*!
1910 set the size of the window, excluding any window frame, to a QSize
1911 constructed from width \a w and height \a h
1912
1913 For interactively resizing windows, see startSystemResize().
1914
1915 \sa size(), geometry()
1916*/
1917void QWindow::resize(int w, int h)
1918{
1919 resize(QSize(w, h));
1920}
1921
1922/*!
1923 \brief set the size of the window, excluding any window frame, to \a newSize
1924
1925 \sa size(), geometry()
1926*/
1927void QWindow::resize(const QSize &newSize)
1928{
1929 Q_D(QWindow);
1930 d->positionPolicy = QWindowPrivate::WindowFrameExclusive;
1931 if (d->platformWindow) {
1932 d->platformWindow->setGeometry(QHighDpi::toNativePixels(QRect(position(), newSize), this));
1933 } else {
1934 const QSize oldSize = d->geometry.size();
1935 d->geometry.setSize(newSize);
1936 if (newSize.width() != oldSize.width())
1937 emit widthChanged(newSize.width());
1938 if (newSize.height() != oldSize.height())
1939 emit heightChanged(newSize.height());
1940 }
1941}
1942
1943/*!
1944 Releases the native platform resources associated with this window.
1945
1946 \sa create()
1947*/
1948void QWindow::destroy()
1949{
1950 Q_D(QWindow);
1951 if (!d->platformWindow)
1952 return;
1953
1954 if (d->platformWindow->isForeignWindow())
1955 return;
1956
1957 d->destroy();
1958}
1959
1960void QWindowPrivate::destroy()
1961{
1962 if (!platformWindow)
1963 return;
1964
1965 Q_Q(QWindow);
1966 QObjectList childrenWindows = q->children();
1967 for (int i = 0; i < childrenWindows.size(); i++) {
1968 QObject *object = childrenWindows.at(i);
1969 if (object->isWindowType()) {
1970 QWindow *w = static_cast<QWindow*>(object);
1971 qt_window_private(w)->destroy();
1972 }
1973 }
1974
1975 if (QGuiApplicationPrivate::focus_window == q)
1976 QGuiApplicationPrivate::focus_window = q->parent();
1977 if (QGuiApplicationPrivate::currentMouseWindow == q)
1978 QGuiApplicationPrivate::currentMouseWindow = q->parent();
1979 if (QGuiApplicationPrivate::currentMousePressWindow == q)
1980 QGuiApplicationPrivate::currentMousePressWindow = q->parent();
1981
1982 for (int i = 0; i < QGuiApplicationPrivate::tabletDevicePoints.size(); ++i)
1983 if (QGuiApplicationPrivate::tabletDevicePoints.at(i).target == q)
1984 QGuiApplicationPrivate::tabletDevicePoints[i].target = q->parent();
1985
1986 bool wasVisible = q->isVisible();
1987 visibilityOnDestroy = wasVisible && platformWindow;
1988
1989 q->setVisible(false);
1990
1991 // Let subclasses act, typically by doing graphics resource cleaup, when
1992 // the window, to which graphics resource may be tied, is going away.
1993 //
1994 // NB! This is disfunctional when destroy() is invoked from the dtor since
1995 // a reimplemented event() will not get called in the subclasses at that
1996 // stage. However, the typical QWindow cleanup involves either close() or
1997 // going through QWindowContainer, both of which will do an explicit, early
1998 // destroy(), which is good here.
1999
2000 QPlatformSurfaceEvent e(QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed);
2001 QGuiApplication::sendEvent(q, &e);
2002
2003 // Unset platformWindow before deleting, so that the destructor of the
2004 // platform window does not recurse back into the platform window via
2005 // this window during destruction (e.g. as a result of platform events).
2006 QPlatformWindow *pw = platformWindow;
2007 platformWindow = nullptr;
2008 delete pw;
2009
2010 resizeEventPending = true;
2011 receivedExpose = false;
2012 exposed = false;
2013}
2014
2015/*!
2016 Returns the platform window corresponding to the window.
2017
2018 \internal
2019*/
2020QPlatformWindow *QWindow::handle() const
2021{
2022 Q_D(const QWindow);
2023 return d->platformWindow;
2024}
2025
2026/*!
2027 Returns the platform surface corresponding to the window.
2028
2029 \internal
2030*/
2031QPlatformSurface *QWindow::surfaceHandle() const
2032{
2033 Q_D(const QWindow);
2034 return d->platformWindow;
2035}
2036
2037/*!
2038 Sets whether keyboard grab should be enabled or not (\a grab).
2039
2040 If the return value is true, the window receives all key events until
2041 setKeyboardGrabEnabled(false) is called; other windows get no key events at
2042 all. Mouse events are not affected. Use setMouseGrabEnabled() if you want
2043 to grab that.
2044
2045 \sa setMouseGrabEnabled()
2046*/
2047bool QWindow::setKeyboardGrabEnabled(bool grab)
2048{
2049 Q_D(QWindow);
2050 if (d->platformWindow)
2051 return d->platformWindow->setKeyboardGrabEnabled(grab);
2052 return false;
2053}
2054
2055/*!
2056 Sets whether mouse grab should be enabled or not (\a grab).
2057
2058 If the return value is true, the window receives all mouse events until setMouseGrabEnabled(false) is
2059 called; other windows get no mouse events at all. Keyboard events are not affected.
2060 Use setKeyboardGrabEnabled() if you want to grab that.
2061
2062 \sa setKeyboardGrabEnabled()
2063*/
2064bool QWindow::setMouseGrabEnabled(bool grab)
2065{
2066 Q_D(QWindow);
2067 if (d->platformWindow)
2068 return d->platformWindow->setMouseGrabEnabled(grab);
2069 return false;
2070}
2071
2072/*!
2073 Returns the screen on which the window is shown, or null if there is none.
2074
2075 For child windows, this returns the screen of the corresponding top level window.
2076
2077 \sa setScreen(), QScreen::virtualSiblings()
2078*/
2079QScreen *QWindow::screen() const
2080{
2081 Q_D(const QWindow);
2082 return d->parentWindow ? d->parentWindow->screen() : d->topLevelScreen.data();
2083}
2084
2085/*!
2086 Sets the screen on which the window should be shown.
2087
2088 If the window has been created, it will be recreated on the \a newScreen.
2089
2090 \note If the screen is part of a virtual desktop of multiple screens,
2091 the window will not move automatically to \a newScreen. To place the
2092 window relative to the screen, use the screen's topLeft() position.
2093
2094 This function only works for top level windows.
2095
2096 \sa screen(), QScreen::virtualSiblings()
2097*/
2098void QWindow::setScreen(QScreen *newScreen)
2099{
2100 Q_D(QWindow);
2101 if (!newScreen)
2102 newScreen = QGuiApplication::primaryScreen();
2103 d->setTopLevelScreen(newScreen, newScreen != nullptr);
2104}
2105
2106/*!
2107 \fn QWindow::screenChanged(QScreen *screen)
2108
2109 This signal is emitted when a window's \a screen changes, either
2110 by being set explicitly with setScreen(), or automatically when
2111 the window's screen is removed.
2112*/
2113
2114/*!
2115 Returns the accessibility interface for the object that the window represents
2116 \internal
2117 \sa QAccessible
2118 */
2119QAccessibleInterface *QWindow::accessibleRoot() const
2120{
2121 return nullptr;
2122}
2123
2124/*!
2125 \fn QWindow::focusObjectChanged(QObject *object)
2126
2127 This signal is emitted when the final receiver of events tied to focus
2128 is changed to \a object.
2129
2130 \sa focusObject()
2131*/
2132
2133/*!
2134 Returns the QObject that will be the final receiver of events tied focus, such
2135 as key events.
2136*/
2137QObject *QWindow::focusObject() const
2138{
2139 return const_cast<QWindow *>(this);
2140}
2141
2142/*!
2143 Shows the window.
2144
2145 This is equivalent to calling showFullScreen(), showMaximized(), or showNormal(),
2146 depending on the platform's default behavior for the window type and flags.
2147
2148 \sa showFullScreen(), showMaximized(), showNormal(), hide(), QStyleHints::showIsFullScreen(), flags()
2149*/
2150void QWindow::show()
2151{
2152 Qt::WindowState defaultState = QGuiApplicationPrivate::platformIntegration()->defaultWindowState(d_func()->windowFlags);
2153 if (defaultState == Qt::WindowFullScreen)
2154 showFullScreen();
2155 else if (defaultState == Qt::WindowMaximized)
2156 showMaximized();
2157 else
2158 showNormal();
2159}
2160
2161/*!
2162 Hides the window.
2163
2164 Equivalent to calling setVisible(false).
2165
2166 \sa show(), setVisible()
2167*/
2168void QWindow::hide()
2169{
2170 setVisible(false);
2171}
2172
2173/*!
2174 Shows the window as minimized.
2175
2176 Equivalent to calling setWindowStates(Qt::WindowMinimized) and then
2177 setVisible(true).
2178
2179 \sa setWindowStates(), setVisible()
2180*/
2181void QWindow::showMinimized()
2182{
2183 setWindowStates(Qt::WindowMinimized);
2184 setVisible(true);
2185}
2186
2187/*!
2188 Shows the window as maximized.
2189
2190 Equivalent to calling setWindowStates(Qt::WindowMaximized) and then
2191 setVisible(true).
2192
2193 \sa setWindowStates(), setVisible()
2194*/
2195void QWindow::showMaximized()
2196{
2197 setWindowStates(Qt::WindowMaximized);
2198 setVisible(true);
2199}
2200
2201/*!
2202 Shows the window as fullscreen.
2203
2204 Equivalent to calling setWindowStates(Qt::WindowFullScreen) and then
2205 setVisible(true).
2206
2207 \sa setWindowStates(), setVisible()
2208*/
2209void QWindow::showFullScreen()
2210{
2211 setWindowStates(Qt::WindowFullScreen);
2212 setVisible(true);
2213#if !defined Q_OS_QNX // On QNX this window will be activated anyway from libscreen
2214 // activating it here before libscreen activates it causes problems
2215 requestActivate();
2216#endif
2217}
2218
2219/*!
2220 Shows the window as normal, i.e. neither maximized, minimized, nor fullscreen.
2221
2222 Equivalent to calling setWindowStates(Qt::WindowNoState) and then
2223 setVisible(true).
2224
2225 \sa setWindowStates(), setVisible()
2226*/
2227void QWindow::showNormal()
2228{
2229 setWindowStates(Qt::WindowNoState);
2230 setVisible(true);
2231}
2232
2233/*!
2234 Close the window.
2235
2236 This closes the window, effectively calling destroy(), and potentially
2237 quitting the application. Returns \c true on success, false if it has a parent
2238 window (in which case the top level window should be closed instead).
2239
2240 \sa destroy(), QGuiApplication::quitOnLastWindowClosed(), closeEvent()
2241*/
2242bool QWindow::close()
2243{
2244 Q_D(QWindow);
2245
2246 // Do not close non top level windows
2247 if (parent())
2248 return false;
2249
2250 if (!d->platformWindow)
2251 return true;
2252
2253 return d->platformWindow->close();
2254}
2255
2256/*!
2257 The expose event (\a ev) is sent by the window system when a window moves
2258 between the un-exposed and exposed states.
2259
2260 An exposed window is potentially visible to the user. If the window is moved
2261 off screen, is made totally obscured by another window, is minimized, or
2262 similar, this function might be called and the value of isExposed() might
2263 change to false. You may use this event to limit expensive operations such
2264 as animations to only run when the window is exposed.
2265
2266 This event should not be used to paint. To handle painting implement
2267 paintEvent() instead.
2268
2269 A resize event will always be sent before the expose event the first time
2270 a window is shown.
2271
2272 \sa paintEvent(), isExposed()
2273*/
2274void QWindow::exposeEvent(QExposeEvent *ev)
2275{
2276 ev->ignore();
2277}
2278
2279/*!
2280 The paint event (\a ev) is sent by the window system whenever an area of
2281 the window needs a repaint, for example when initially showing the window,
2282 or due to parts of the window being uncovered by moving another window.
2283
2284 The application is expected to render into the window in response to the
2285 paint event, regardless of the exposed state of the window. For example,
2286 a paint event may be sent before the window is exposed, to prepare it for
2287 showing to the user.
2288
2289 \since 6.0
2290
2291 \sa exposeEvent()
2292*/
2293void QWindow::paintEvent(QPaintEvent *ev)
2294{
2295 ev->ignore();
2296}
2297
2298/*!
2299 Override this to handle window move events (\a ev).
2300*/
2301void QWindow::moveEvent(QMoveEvent *ev)
2302{
2303 ev->ignore();
2304}
2305
2306/*!
2307 Override this to handle resize events (\a ev).
2308
2309 The resize event is called whenever the window is resized in the windowing system,
2310 either directly through the windowing system acknowledging a setGeometry() or resize() request,
2311 or indirectly through the user resizing the window manually.
2312*/
2313void QWindow::resizeEvent(QResizeEvent *ev)
2314{
2315 ev->ignore();
2316}
2317
2318/*!
2319 Override this to handle show events (\a ev).
2320
2321 The function is called when the window has requested becoming visible.
2322
2323 If the window is successfully shown by the windowing system, this will
2324 be followed by a resize and an expose event.
2325*/
2326void QWindow::showEvent(QShowEvent *ev)
2327{
2328 ev->ignore();
2329}
2330
2331/*!
2332 Override this to handle hide events (\a ev).
2333
2334 The function is called when the window has requested being hidden in the
2335 windowing system.
2336*/
2337void QWindow::hideEvent(QHideEvent *ev)
2338{
2339 ev->ignore();
2340}
2341
2342/*!
2343 Override this to handle close events (\a ev).
2344
2345 The function is called when the window is requested to close. Call \l{QEvent::ignore()}
2346 on the event if you want to prevent the window from being closed.
2347
2348 \sa close()
2349*/
2350void QWindow::closeEvent(QCloseEvent *ev)
2351{
2352 Q_UNUSED(ev);
2353}
2354
2355/*!
2356 Override this to handle any event (\a ev) sent to the window.
2357 Return \c true if the event was recognized and processed.
2358
2359 Remember to call the base class version if you wish for mouse events,
2360 key events, resize events, etc to be dispatched as usual.
2361*/
2362bool QWindow::event(QEvent *ev)
2363{
2364 switch (ev->type()) {
2365 case QEvent::MouseMove:
2366 mouseMoveEvent(static_cast<QMouseEvent*>(ev));
2367 break;
2368
2369 case QEvent::MouseButtonPress:
2370 mousePressEvent(static_cast<QMouseEvent*>(ev));
2371 break;
2372
2373 case QEvent::MouseButtonRelease:
2374 mouseReleaseEvent(static_cast<QMouseEvent*>(ev));
2375 break;
2376
2377 case QEvent::MouseButtonDblClick:
2378 mouseDoubleClickEvent(static_cast<QMouseEvent*>(ev));
2379 break;
2380
2381 case QEvent::TouchBegin:
2382 case QEvent::TouchUpdate:
2383 case QEvent::TouchEnd:
2384 case QEvent::TouchCancel:
2385 touchEvent(static_cast<QTouchEvent *>(ev));
2386 break;
2387
2388 case QEvent::Move:
2389 moveEvent(static_cast<QMoveEvent*>(ev));
2390 break;
2391
2392 case QEvent::Resize:
2393 resizeEvent(static_cast<QResizeEvent*>(ev));
2394 break;
2395
2396 case QEvent::KeyPress:
2397 keyPressEvent(static_cast<QKeyEvent *>(ev));
2398 break;
2399
2400 case QEvent::KeyRelease:
2401 keyReleaseEvent(static_cast<QKeyEvent *>(ev));
2402 break;
2403
2404 case QEvent::FocusIn: {
2405 focusInEvent(static_cast<QFocusEvent *>(ev));
2406#ifndef QT_NO_ACCESSIBILITY
2407 QAccessible::State state;
2408 state.active = true;
2409 QAccessibleStateChangeEvent event(this, state);
2410 QAccessible::updateAccessibility(&event);
2411#endif
2412 break; }
2413
2414 case QEvent::FocusOut: {
2415 focusOutEvent(static_cast<QFocusEvent *>(ev));
2416#ifndef QT_NO_ACCESSIBILITY
2417 QAccessible::State state;
2418 state.active = true;
2419 QAccessibleStateChangeEvent event(this, state);
2420 QAccessible::updateAccessibility(&event);
2421#endif
2422 break; }
2423
2424#if QT_CONFIG(wheelevent)
2425 case QEvent::Wheel:
2426 wheelEvent(static_cast<QWheelEvent*>(ev));
2427 break;
2428#endif
2429
2430 case QEvent::Close:
2431 closeEvent(static_cast<QCloseEvent*>(ev));
2432 if (ev->isAccepted()) {
2433 Q_D(QWindow);
2434 bool wasVisible = isVisible();
2435 destroy();
2436 if (wasVisible) {
2437 // FIXME: This check for visibility is a workaround for both QWidgetWindow
2438 // and QWindow having logic to emit lastWindowClosed, and possibly quit the
2439 // application. We should find a better way to handle this.
2440 d->maybeQuitOnLastWindowClosed();
2441 }
2442 }
2443 break;
2444
2445 case QEvent::Expose:
2446 exposeEvent(static_cast<QExposeEvent *>(ev));
2447 break;
2448
2449 case QEvent::Paint:
2450 paintEvent(static_cast<QPaintEvent *>(ev));
2451 break;
2452
2453 case QEvent::Show:
2454 showEvent(static_cast<QShowEvent *>(ev));
2455 break;
2456
2457 case QEvent::Hide:
2458 hideEvent(static_cast<QHideEvent *>(ev));
2459 break;
2460
2461 case QEvent::ApplicationWindowIconChange:
2462 setIcon(icon());
2463 break;
2464
2465 case QEvent::WindowStateChange: {
2466 Q_D(QWindow);
2467 emit windowStateChanged(QWindowPrivate::effectiveState(d->windowState));
2468 d->updateVisibility();
2469 break;
2470 }
2471
2472#if QT_CONFIG(tabletevent)
2473 case QEvent::TabletPress:
2474 case QEvent::TabletMove:
2475 case QEvent::TabletRelease:
2476 tabletEvent(static_cast<QTabletEvent *>(ev));
2477 break;
2478#endif
2479
2480 case QEvent::PlatformSurface: {
2481 if ((static_cast<QPlatformSurfaceEvent *>(ev))->surfaceEventType() == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) {
2482#ifndef QT_NO_OPENGL
2483 QOpenGLContext *context = QOpenGLContext::currentContext();
2484 if (context && context->surface() == static_cast<QSurface *>(this))
2485 context->doneCurrent();
2486#endif
2487 }
2488 break;
2489 }
2490
2491 default:
2492 return QObject::event(ev);
2493 }
2494 return true;
2495}
2496
2497/*!
2498 Schedules a QEvent::UpdateRequest event to be delivered to this window.
2499
2500 The event is delivered in sync with the display vsync on platforms
2501 where this is possible. Otherwise, the event is delivered after a
2502 delay of 5 ms. The additional time is there to give the event loop
2503 a bit of idle time to gather system events, and can be overridden
2504 using the QT_QPA_UPDATE_IDLE_TIME environment variable.
2505
2506 When driving animations, this function should be called once after drawing
2507 has completed. Calling this function multiple times will result in a single
2508 event being delivered to the window.
2509
2510 Subclasses of QWindow should reimplement event(), intercept the event and
2511 call the application's rendering code, then call the base class
2512 implementation.
2513
2514 \note The subclass' reimplementation of event() must invoke the base class
2515 implementation, unless it is absolutely sure that the event does not need to
2516 be handled by the base class. For example, the default implementation of
2517 this function relies on QEvent::Timer events. Filtering them away would
2518 therefore break the delivery of the update events.
2519
2520 \since 5.5
2521*/
2522void QWindow::requestUpdate()
2523{
2524 Q_ASSERT_X(QThread::currentThread() == QCoreApplication::instance()->thread(),
2525 "QWindow", "Updates can only be scheduled from the GUI (main) thread");
2526
2527 Q_D(QWindow);
2528 if (d->updateRequestPending || !d->platformWindow)
2529 return;
2530 d->updateRequestPending = true;
2531 d->platformWindow->requestUpdate();
2532}
2533
2534/*!
2535 Override this to handle key press events (\a ev).
2536
2537 \sa keyReleaseEvent()
2538*/
2539void QWindow::keyPressEvent(QKeyEvent *ev)
2540{
2541 ev->ignore();
2542}
2543
2544/*!
2545 Override this to handle key release events (\a ev).
2546
2547 \sa keyPressEvent()
2548*/
2549void QWindow::keyReleaseEvent(QKeyEvent *ev)
2550{
2551 ev->ignore();
2552}
2553
2554/*!
2555 Override this to handle focus in events (\a ev).
2556
2557 Focus in events are sent when the window receives keyboard focus.
2558
2559 \sa focusOutEvent()
2560*/
2561void QWindow::focusInEvent(QFocusEvent *ev)
2562{
2563 ev->ignore();
2564}
2565
2566/*!
2567 Override this to handle focus out events (\a ev).
2568
2569 Focus out events are sent when the window loses keyboard focus.
2570
2571 \sa focusInEvent()
2572*/
2573void QWindow::focusOutEvent(QFocusEvent *ev)
2574{
2575 ev->ignore();
2576}
2577
2578/*!
2579 Override this to handle mouse press events (\a ev).
2580
2581 \sa mouseReleaseEvent()
2582*/
2583void QWindow::mousePressEvent(QMouseEvent *ev)
2584{
2585 ev->ignore();
2586}
2587
2588/*!
2589 Override this to handle mouse release events (\a ev).
2590
2591 \sa mousePressEvent()
2592*/
2593void QWindow::mouseReleaseEvent(QMouseEvent *ev)
2594{
2595 ev->ignore();
2596}
2597
2598/*!
2599 Override this to handle mouse double click events (\a ev).
2600
2601 \sa mousePressEvent(), QStyleHints::mouseDoubleClickInterval()
2602*/
2603void QWindow::mouseDoubleClickEvent(QMouseEvent *ev)
2604{
2605 ev->ignore();
2606}
2607
2608/*!
2609 Override this to handle mouse move events (\a ev).
2610*/
2611void QWindow::mouseMoveEvent(QMouseEvent *ev)
2612{
2613 ev->ignore();
2614}
2615
2616#if QT_CONFIG(wheelevent)
2617/*!
2618 Override this to handle mouse wheel or other wheel events (\a ev).
2619*/
2620void QWindow::wheelEvent(QWheelEvent *ev)
2621{
2622 ev->ignore();
2623}
2624#endif // QT_CONFIG(wheelevent)
2625
2626/*!
2627 Override this to handle touch events (\a ev).
2628*/
2629void QWindow::touchEvent(QTouchEvent *ev)
2630{
2631 ev->ignore();
2632}
2633
2634#if QT_CONFIG(tabletevent)
2635/*!
2636 Override this to handle tablet press, move, and release events (\a ev).
2637
2638 Proximity enter and leave events are not sent to windows, they are
2639 delivered to the application instance.
2640*/
2641void QWindow::tabletEvent(QTabletEvent *ev)
2642{
2643 ev->ignore();
2644}
2645#endif
2646
2647/*!
2648 Override this to handle platform dependent events.
2649 Will be given \a eventType, \a message and \a result.
2650
2651 This might make your application non-portable.
2652
2653 Should return true only if the event was handled.
2654*/
2655
2656#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
2657bool QWindow::nativeEvent(const QByteArray &eventType, void *message, qintptr *result)
2658#else
2659bool QWindow::nativeEvent(const QByteArray &eventType, void *message, long *result)
2660#endif
2661{
2662 Q_UNUSED(eventType);
2663 Q_UNUSED(message);
2664 Q_UNUSED(result);
2665 return false;
2666}
2667
2668/*!
2669 \fn QPointF QWindow::mapToGlobal(const QPointF &pos) const
2670
2671 Translates the window coordinate \a pos to global screen
2672 coordinates. For example, \c{mapToGlobal(QPointF(0,0))} would give
2673 the global coordinates of the top-left pixel of the window.
2674
2675 \sa mapFromGlobal()
2676 \since 6.0
2677*/
2678QPointF QWindow::mapToGlobal(const QPointF &pos) const
2679{
2680 Q_D(const QWindow);
2681 // QTBUG-43252, prefer platform implementation for foreign windows.
2682 if (d->platformWindow
2683 && (d->platformWindow->isForeignWindow() || d->platformWindow->isEmbedded())) {
2684 return QHighDpi::fromNativeLocalPosition(d->platformWindow->mapToGlobalF(QHighDpi::toNativeLocalPosition(pos, this)), this);
2685 }
2686
2687 if (!QHighDpiScaling::isActive())
2688 return pos + d->globalPosition();
2689
2690 // The normal pos + windowGlobalPos calculation may give a point which is outside
2691 // screen geometry for windows which span multiple screens, due to the way QHighDpiScaling
2692 // creates gaps between screens in the the device indendent cooordinate system.
2693 //
2694 // Map the position (and the window's global position) to native coordinates, perform
2695 // the addition, and then map back to device independent coordinates.
2696 QPointF nativeLocalPos = QHighDpi::toNativeLocalPosition(pos, this);
2697 QPointF nativeWindowGlobalPos = QHighDpi::toNativeGlobalPosition(QPointF(d->globalPosition()), this);
2698 QPointF nativeGlobalPos = nativeLocalPos + nativeWindowGlobalPos;
2699 QPointF deviceIndependentGlobalPos = QHighDpi::fromNativeGlobalPosition(nativeGlobalPos, this);
2700 return deviceIndependentGlobalPos;
2701}
2702
2703/*!
2704 \overload
2705*/
2706QPoint QWindow::mapToGlobal(const QPoint &pos) const
2707{
2708 return mapToGlobal(QPointF(pos)).toPoint();
2709}
2710
2711/*!
2712 \fn QPointF QWindow::mapFromGlobal(const QPointF &pos) const
2713
2714 Translates the global screen coordinate \a pos to window
2715 coordinates.
2716
2717 \sa mapToGlobal()
2718 \since 6.0
2719*/
2720QPointF QWindow::mapFromGlobal(const QPointF &pos) const
2721{
2722 Q_D(const QWindow);
2723 // QTBUG-43252, prefer platform implementation for foreign windows.
2724 if (d->platformWindow
2725 && (d->platformWindow->isForeignWindow() || d->platformWindow->isEmbedded())) {
2726 return QHighDpi::fromNativeLocalPosition(d->platformWindow->mapFromGlobalF(QHighDpi::toNativeLocalPosition(pos, this)), this);
2727 }
2728
2729 if (!QHighDpiScaling::isActive())
2730 return pos - d->globalPosition();
2731
2732 // Calculate local position in the native coordinate system. (See comment for the
2733 // correspinding mapToGlobal() code above).
2734 QPointF nativeGlobalPos = QHighDpi::toNativeGlobalPosition(pos, this);
2735 QPointF nativeWindowGlobalPos = QHighDpi::toNativeGlobalPosition(QPointF(d->globalPosition()), this);
2736 QPointF nativeLocalPos = nativeGlobalPos - nativeWindowGlobalPos;
2737 QPointF deviceIndependentLocalPos = QHighDpi::fromNativeLocalPosition(nativeLocalPos, this);
2738 return deviceIndependentLocalPos;
2739}
2740
2741/*!
2742 \overload
2743*/
2744QPoint QWindow::mapFromGlobal(const QPoint &pos) const
2745{
2746 return QWindow::mapFromGlobal(QPointF(pos)).toPoint();
2747}
2748
2749QPoint QWindowPrivate::globalPosition() const
2750{
2751 Q_Q(const QWindow);
2752 QPoint offset = q->position();
2753 for (const QWindow *p = q->parent(); p; p = p->parent()) {
2754 QPlatformWindow *pw = p->handle();
2755 if (pw && (pw->isForeignWindow() || pw->isEmbedded())) {
2756 // Use mapToGlobal() for foreign windows
2757 offset += p->mapToGlobal(QPoint(0, 0));
2758 break;
2759 } else {
2760 offset += p->position();
2761 }
2762 }
2763 return offset;
2764}
2765
2766Q_GUI_EXPORT QWindowPrivate *qt_window_private(QWindow *window)
2767{
2768 return window->d_func();
2769}
2770
2771void QWindowPrivate::maybeQuitOnLastWindowClosed()
2772{
2773 if (!QCoreApplication::instance())
2774 return;
2775
2776 Q_Q(QWindow);
2777 if (!q->isTopLevel())
2778 return;
2779 // Attempt to close the application only if this has WA_QuitOnClose set and a non-visible parent
2780 bool quitOnClose = QGuiApplication::quitOnLastWindowClosed() && !q->parent();
2781 QWindowList list = QGuiApplication::topLevelWindows();
2782 bool lastWindowClosed = true;
2783 for (int i = 0; i < list.size(); ++i) {
2784 QWindow *w = list.at(i);
2785 if (!w->isVisible() || w->transientParent() || w->type() == Qt::ToolTip)
2786 continue;
2787 lastWindowClosed = false;
2788 break;
2789 }
2790 if (lastWindowClosed) {
2791 QGuiApplicationPrivate::emitLastWindowClosed();
2792 if (quitOnClose) {
2793 QCoreApplicationPrivate *applicationPrivate = static_cast<QCoreApplicationPrivate*>(QObjectPrivate::get(QCoreApplication::instance()));
2794 applicationPrivate->maybeQuit();
2795 }
2796 }
2797}
2798
2799QWindow *QWindowPrivate::topLevelWindow(QWindow::AncestorMode mode) const
2800{
2801 Q_Q(const QWindow);
2802
2803 QWindow *window = const_cast<QWindow *>(q);
2804
2805 while (window) {
2806 QWindow *parent = window->parent(mode);
2807 if (!parent)
2808 break;
2809
2810 window = parent;
2811 }
2812
2813 return window;
2814}
2815
2816#if QT_CONFIG(opengl)
2817QOpenGLContext *QWindowPrivate::shareContext() const
2818{
2819 return qt_gl_global_share_context();
2820};
2821#endif
2822
2823/*!
2824 Creates a local representation of a window created by another process or by
2825 using native libraries below Qt.
2826
2827 Given the handle \a id to a native window, this method creates a QWindow
2828 object which can be used to represent the window when invoking methods like
2829 setParent() and setTransientParent().
2830
2831 This can be used, on platforms which support it, to embed a QWindow inside a
2832 native window, or to embed a native window inside a QWindow.
2833
2834 If foreign windows are not supported or embedding the native window
2835 failed in the platform plugin, this function returns \nullptr.
2836
2837 \note The resulting QWindow should not be used to manipulate the underlying
2838 native window (besides re-parenting), or to observe state changes of the
2839 native window. Any support for these kind of operations is incidental, highly
2840 platform dependent and untested.
2841
2842 \sa setParent()
2843*/
2844QWindow *QWindow::fromWinId(WId id)
2845{
2846 if (!QGuiApplicationPrivate::platformIntegration()->hasCapability(QPlatformIntegration::ForeignWindows)) {
2847 qWarning("QWindow::fromWinId(): platform plugin does not support foreign windows.");
2848 return nullptr;
2849 }
2850
2851 QWindow *window = new QWindow;
2852 qt_window_private(window)->create(false, id);
2853
2854 if (!window->handle()) {
2855 delete window;
2856 return nullptr;
2857 }
2858
2859 return window;
2860}
2861
2862/*!
2863 Causes an alert to be shown for \a msec miliseconds. If \a msec is \c 0 (the
2864 default), then the alert is shown indefinitely until the window becomes
2865 active again. This function has no effect on an active window.
2866
2867 In alert state, the window indicates that it demands attention, for example by
2868 flashing or bouncing the taskbar entry.
2869
2870 \since 5.1
2871*/
2872
2873void QWindow::alert(int msec)
2874{
2875 Q_D(QWindow);
2876 if (!d->platformWindow || d->platformWindow->isAlertState() || isActive())
2877 return;
2878 d->platformWindow->setAlertState(true);
2879 if (d->platformWindow->isAlertState() && msec)
2880 QTimer::singleShot(msec, this, SLOT(_q_clearAlert()));
2881}
2882
2883void QWindowPrivate::_q_clearAlert()
2884{
2885 if (platformWindow && platformWindow->isAlertState())
2886 platformWindow->setAlertState(false);
2887}
2888
2889#ifndef QT_NO_CURSOR
2890/*!
2891 \brief set the cursor shape for this window
2892
2893 The mouse \a cursor will assume this shape when it is over this
2894 window, unless an override cursor is set.
2895 See the \l{Qt::CursorShape}{list of predefined cursor objects} for a
2896 range of useful shapes.
2897
2898 If no cursor has been set, or after a call to unsetCursor(), the
2899 parent window's cursor is used.
2900
2901 By default, the cursor has the Qt::ArrowCursor shape.
2902
2903 Some underlying window implementations will reset the cursor if it
2904 leaves a window even if the mouse is grabbed. If you want to have
2905 a cursor set for all windows, even when outside the window, consider
2906 QGuiApplication::setOverrideCursor().
2907
2908 \sa QGuiApplication::setOverrideCursor()
2909*/
2910void QWindow::setCursor(const QCursor &cursor)
2911{
2912 Q_D(QWindow);
2913 d->setCursor(&cursor);
2914}
2915
2916/*!
2917 \brief Restores the default arrow cursor for this window.
2918 */
2919void QWindow::unsetCursor()
2920{
2921 Q_D(QWindow);
2922 d->setCursor(nullptr);
2923}
2924
2925/*!
2926 \brief the cursor shape for this window
2927
2928 \sa setCursor(), unsetCursor()
2929*/
2930QCursor QWindow::cursor() const
2931{
2932 Q_D(const QWindow);
2933 return d->cursor;
2934}
2935
2936void QWindowPrivate::setCursor(const QCursor *newCursor)
2937{
2938
2939 Q_Q(QWindow);
2940 if (newCursor) {
2941 const Qt::CursorShape newShape = newCursor->shape();
2942 if (newShape <= Qt::LastCursor && hasCursor && newShape == cursor.shape())
2943 return; // Unchanged and no bitmap/custom cursor.
2944 cursor = *newCursor;
2945 hasCursor = true;
2946 } else {
2947 if (!hasCursor)
2948 return;
2949 cursor = QCursor(Qt::ArrowCursor);
2950 hasCursor = false;
2951 }
2952 // Only attempt to emit signal if there is an actual platform cursor
2953 if (applyCursor()) {
2954 QEvent event(QEvent::CursorChange);
2955 QGuiApplication::sendEvent(q, &event);
2956 }
2957}
2958
2959// Apply the cursor and returns true iff the platform cursor exists
2960bool QWindowPrivate::applyCursor()
2961{
2962 Q_Q(QWindow);
2963 if (QScreen *screen = q->screen()) {
2964 if (QPlatformCursor *platformCursor = screen->handle()->cursor()) {
2965 if (!platformWindow)
2966 return true;
2967 QCursor *c = QGuiApplication::overrideCursor();
2968 if (c != nullptr && platformCursor->capabilities().testFlag(QPlatformCursor::OverrideCursor))
2969 return true;
2970 if (!c && hasCursor)
2971 c = &cursor;
2972 platformCursor->changeCursor(c, q);
2973 return true;
2974 }
2975 }
2976 return false;
2977}
2978#endif // QT_NO_CURSOR
2979
2980#ifndef QT_NO_DEBUG_STREAM
2981QDebug operator<<(QDebug debug, const QWindow *window)
2982{
2983 QDebugStateSaver saver(debug);
2984 debug.nospace();
2985 if (window) {
2986 debug << window->metaObject()->className() << '(' << (const void *)window;
2987 if (!window->objectName().isEmpty())
2988 debug << ", name=" << window->objectName();
2989 if (debug.verbosity() > 2) {
2990 const QRect geometry = window->geometry();
2991 if (window->isVisible())
2992 debug << ", visible";
2993 if (window->isExposed())
2994 debug << ", exposed";
2995 debug << ", state=" << window->windowState()
2996 << ", type=" << window->type() << ", flags=" << window->flags()
2997 << ", surface type=" << window->surfaceType();
2998 if (window->isTopLevel())
2999 debug << ", toplevel";
3000 debug << ", " << geometry.width() << 'x' << geometry.height()
3001 << Qt::forcesign << geometry.x() << geometry.y() << Qt::noforcesign;
3002 const QMargins margins = window->frameMargins();
3003 if (!margins.isNull())
3004 debug << ", margins=" << margins;
3005 debug << ", devicePixelRatio=" << window->devicePixelRatio();
3006 if (const QPlatformWindow *platformWindow = window->handle())
3007 debug << ", winId=0x" << Qt::hex << platformWindow->winId() << Qt::dec;
3008 if (const QScreen *screen = window->screen())
3009 debug << ", on " << screen->name();
3010 }
3011 debug << ')';
3012 } else {
3013 debug << "QWindow(0x0)";
3014 }
3015 return debug;
3016}
3017#endif // !QT_NO_DEBUG_STREAM
3018
3019#if QT_CONFIG(vulkan) || defined(Q_CLANG_QDOC)
3020
3021/*!
3022 Associates this window with the specified Vulkan \a instance.
3023
3024 \a instance must stay valid as long as this QWindow instance exists.
3025 */
3026void QWindow::setVulkanInstance(QVulkanInstance *instance)
3027{
3028 Q_D(QWindow);
3029 d->vulkanInstance = instance;
3030}
3031
3032/*!
3033 \return the associated Vulkan instance if any was set, otherwise \nullptr.
3034 */
3035QVulkanInstance *QWindow::vulkanInstance() const
3036{
3037 Q_D(const QWindow);
3038 return d->vulkanInstance;
3039}
3040
3041#endif // QT_CONFIG(vulkan)
3042
3043QT_END_NAMESPACE
3044
3045#include "moc_qwindow.cpp"
3046