Qt
Internal/Contributor docs for the Qt SDK. <b>Note:</b> These are NOT official API docs; those are found <a href='https://doc.qt.io/'>here</a>.
Loading...
Searching...
No Matches
qplatformwindow.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "qplatformwindow.h"
5#include "qplatformwindow_p.h"
6#include "qplatformscreen.h"
7
8#include <private/qguiapplication_p.h>
9#include <qpa/qwindowsysteminterface.h>
10#include <QtGui/qwindow.h>
11#include <QtGui/qscreen.h>
12#include <private/qhighdpiscaling_p.h>
13#include <private/qwindow_p.h>
14
15
17
29
36
47
52{
53 return static_cast<QWindow *>(m_surface);
54}
55
60{
61 return window()->parent() ? window()->parent()->handle() : nullptr;
62}
63
69{
70 QScreen *scr = window()->screen();
71 return scr ? scr->handle() : nullptr;
72}
73
81
101{
102 Q_D(QPlatformWindow);
103 d->rect = rect;
104}
105
110{
111 Q_D(const QPlatformWindow);
112 return d->rect;
113}
114
123{
124 return QRect();
125}
126
128{
129 return QMargins();
130}
131
138{
139 return QMargins();
140}
141
155
161{
163}
164
172{
173 return window()->isVisible();
174}
175
183{
184 return false;
185}
186
195{
196 for (const QPlatformWindow *parent = child->parent(); parent; parent = parent->parent()) {
197 if (parent == this)
198 return true;
199 }
200
201 return false;
202}
203
211{
212 return false;
213}
214
223{
224 const QPlatformWindow *p = this;
225 QPoint result = pos;
226 while (p) {
227 result += p->geometry().topLeft();
228 p = p->parent();
229 }
230 return result;
231}
232
234{
235 const QPoint posPt = pos.toPoint();
236 const QPointF delta = pos - posPt;
237 return mapToGlobal(posPt) + delta;
238}
239
241{
242 const QPoint posPt = pos.toPoint();
243 const QPointF delta = pos - posPt;
244 return mapFromGlobal(posPt) + delta;
245}
246
255{
256 const QPlatformWindow *p = this;
257 QPoint result = pos;
258 while (p) {
259 result -= p->geometry().topLeft();
260 p = p->parent();
261 }
262 return result;
263}
264
272{
273}
274
279{
280 // Return anything but 0. Returning 0 would cause havoc with QWidgets on
281 // very basic platform plugins that do not reimplement this function,
282 // because the top-level widget's internalWinId() would always be 0 which
283 // would mean top-levels are never treated as native.
284 return WId(1);
285}
286
287//jl: It would be useful to have a property on the platform window which indicated if the sub-class
288// supported the setParent. If not, then geometry would be in screen coordinates.
295{
297 qWarning("This plugin does not support setParent!");
298}
299
309
313void QPlatformWindow::setWindowFilePath(const QString &filePath) { Q_UNUSED(filePath); }
314
319
328{
329 return QWindowSystemInterface::handleCloseEvent<QWindowSystemInterface::SynchronousDelivery>(window());
330}
331
335void QPlatformWindow::raise() { qWarning("This plugin does not support raise()"); }
336
340void QPlatformWindow::lower() { qWarning("This plugin does not support lower()"); }
341
348void QPlatformWindow::propagateSizeHints() {qWarning("This plugin does not support propagateSizeHints()"); }
349
354{
356 qWarning("This plugin does not support setting window opacity");
357}
358
364{
365 Q_UNUSED(region);
366 qWarning("This plugin does not support setting window masks");
367}
368
386
400
409{
410 return 1.0;
411}
412
414{
415 Q_UNUSED(grab);
416 qWarning("This plugin does not support grabbing the keyboard");
417 return false;
418}
419
421{
422 Q_UNUSED(grab);
423 qWarning("This plugin does not support grabbing the mouse");
424 return false;
425}
426
433{
434 Q_UNUSED(modified);
435 return false;
436}
437
448{
449 Q_D(QPlatformWindow);
450
451 if (event->type() == QEvent::Timer) {
452 if (static_cast<QTimerEvent *>(event)->timerId() == d->updateTimer.timerId()) {
453 d->updateTimer.stop();
455 return true;
456 }
457 }
458
459 return false;
460}
461
472{
473 Q_UNUSED(edges);
474 return false;
475}
476
487{
488 return false;
489}
490
499{
500 Q_UNUSED(enabled); // Do not warn as widgets enable it by default causing warnings with XCB.
501}
502
509{
510 return false;
511}
512
522{
523 QString fullTitle = title;
525 // Append display name, if set.
526 if (!fullTitle.isEmpty())
527 fullTitle += separator;
529 } else if (fullTitle.isEmpty()) {
530 // Don't let the window title be completely empty, use the app name as fallback.
532 }
533 return fullTitle;
534}
535
548{
549 QPlatformScreen *currentScreen = screen();
550 QPlatformScreen *fallback = currentScreen;
551 // QRect::center can return a value outside the rectangle if it's empty.
552 // Apply mapToGlobal() in case it is a foreign/embedded window.
553 QPoint center = newGeometry.isEmpty() ? newGeometry.topLeft() : newGeometry.center();
554 if (isForeignWindow())
555 center = mapToGlobal(center - newGeometry.topLeft());
556
557 if (!parent() && currentScreen && !currentScreen->geometry().contains(center)) {
558 const auto screens = currentScreen->virtualSiblings();
559 for (QPlatformScreen *screen : screens) {
560 const QRect screenGeometry = screen->geometry();
561 if (screenGeometry.contains(center))
562 return screen;
563 if (screenGeometry.intersects(newGeometry))
564 fallback = screen;
565 }
566 }
567 return fallback;
568}
569
574{
575 return size.expandedTo(QSize(0, 0)).boundedTo(QSize(QWINDOWSIZE_MAX, QWINDOWSIZE_MAX));
576}
577
590
600{
601 return false;
602}
603
604// Return the effective screen for the initial geometry of a window. In a
605// multimonitor-setup, try to find the right screen by checking the transient
606// parent or the mouse cursor for parentless windows (cf QTBUG-34204,
607// QDialog::adjustPosition()), unless a non-primary screen has been set,
608// in which case we try to respect that.
609static inline const QScreen *effectiveScreen(const QWindow *window)
610{
611 if (!window)
613 const QScreen *screen = window->screen();
614 if (!screen)
617 return screen;
618#ifndef QT_NO_CURSOR
619 const QList<QScreen *> siblings = screen->virtualSiblings();
620 if (siblings.size() > 1) {
621 const QPoint referencePoint = window->transientParent() ? window->transientParent()->geometry().center() : QCursor::pos();
622 for (const QScreen *sibling : siblings) {
623 if (sibling->geometry().contains(referencePoint))
624 return sibling;
625 }
626 }
627#endif
628 return screen;
629}
630
644
645static QSize fixInitialSize(QSize size, const QWindow *w, int deviceIndependentDefaultWidth,
646 int deviceIndependentDefaultHeight)
647{
648 if (size.width() == 0) {
649 const int minWidth = w->minimumWidth();
650 size.setWidth(minWidth > 0 ? minWidth : deviceIndependentDefaultWidth);
651 }
652 if (size.height() == 0) {
653 const int minHeight = w->minimumHeight();
654 size.setHeight(minHeight > 0 ? minHeight : deviceIndependentDefaultHeight);
655 }
656 return size;
657}
658
672QRect QPlatformWindow::initialGeometry(const QWindow *w, const QRect &initialGeometry,
673 int defaultWidth, int defaultHeight,
674 const QScreen **resultingScreenReturn)
675{
676 if (resultingScreenReturn)
677 *resultingScreenReturn = w->screen();
678 if (!w->isTopLevel()) {
679 const qreal factor = QHighDpiScaling::factor(w);
680 const QSize deviceIndependentSize =
682 defaultWidth, defaultHeight);
683 return QRect(initialGeometry.topLeft(), QHighDpi::toNative(deviceIndependentSize, factor));
684 }
685 const auto *wp = qt_window_private(const_cast<QWindow*>(w));
686 const bool position = wp->positionAutomatic && w->type() != Qt::Popup;
687 if (!position && !wp->resizeAutomatic)
688 return initialGeometry;
689 const QScreen *screen = wp->positionAutomatic
692 if (!screen)
693 return initialGeometry;
694 if (resultingScreenReturn)
695 *resultingScreenReturn = screen;
696 // initialGeometry refers to window's screen
697 QRect deviceIndependentRect(QHighDpi::fromNativePixels(initialGeometry, w));
698 if (wp->resizeAutomatic)
699 deviceIndependentRect.setSize(
700 fixInitialSize(deviceIndependentRect.size(), w, defaultWidth, defaultHeight));
701 if (position) {
702 const QRect availableDeviceIndependentGeometry = screen->availableGeometry();
703 // Center unless the geometry ( + unknown window frame) is too large for the screen).
704 if (deviceIndependentRect.height() < (availableDeviceIndependentGeometry.height() * 8) / 9
705 && deviceIndependentRect.width()
706 < (availableDeviceIndependentGeometry.width() * 8) / 9) {
707 const QWindow *tp = w->transientParent();
708 if (tp) {
709 // A transient window should be centered w.r.t. its transient parent.
710 deviceIndependentRect.moveCenter(tp->geometry().center());
711 } else {
712 // Center the window on the screen. (Only applicable on platforms
713 // which do not provide a better way.)
714 deviceIndependentRect.moveCenter(availableDeviceIndependentGeometry.center());
715 }
716 }
717 }
718 return QHighDpi::toNativePixels(deviceIndependentRect, screen);
719}
720
738{
739 Q_D(QPlatformWindow);
740
741 static bool customUpdateIntervalValid = false;
742 static int customUpdateInterval = qEnvironmentVariableIntValue("QT_QPA_UPDATE_IDLE_TIME",
743 &customUpdateIntervalValid);
744 int updateInterval = customUpdateInterval;
745 if (!customUpdateIntervalValid) {
746 updateInterval = 5;
747 if (QPlatformScreen *currentScreen = screen()) {
748 const qreal refreshRate = currentScreen->refreshRate();
749 if (refreshRate > 60.0)
750 updateInterval /= refreshRate / 60.0;
751 }
752 }
753
754 Q_ASSERT(!d->updateTimer.isActive());
755 d->updateTimer.start(updateInterval, Qt::PreciseTimer, window());
756}
757
764{
765 return qt_window_private(window())->updateRequestPending;
766}
767
776{
778
779 QWindow *w = window();
781
782 // We expect that the platform plugins send DevicePixelRatioChange events.
783 // As a fail-safe make a final check here to make sure the cached DPR value is
784 // always up to date before delivering the update request.
785 if (wp->updateDevicePixelRatio()) {
786 qWarning() << "The cached device pixel ratio value was stale on window update. "
787 << "Please file a QTBUG which explains how to reproduce.";
788 }
789
790 wp->updateRequestPending = false;
793}
794
802
810
815{
816 return QHighDpi::toNativePixels(window()->baseSize(), window());
817}
818
823{
824 QSize increment = window()->sizeIncrement();
826 return increment;
827
828 // Normalize the increment. If not set the increment can be
829 // (-1, -1) or (0, 0). Make that (1, 1) which is scalable.
830 if (increment.isEmpty())
831 increment = QSize(1, 1);
832
834}
835
843
851
859{
860 const QRectF rectF = QHighDpi::fromNativeWindowGeometry(nativeRect, qWindow);
861 const QRectF correctedGeometryF = qt_window_private(const_cast<QWindow *>(qWindow))->closestAcceptableGeometry(rectF);
862 return !correctedGeometryF.isEmpty() && rectF != correctedGeometryF
863 ? QHighDpi::toNativeWindowGeometry(correctedGeometryF, qWindow) : nativeRect;
864}
865
870
static bool sendEvent(QObject *receiver, QEvent *event)
Sends event event directly to receiver receiver, using the notify() function.
QString applicationName
the name of this application
static QPoint pos()
Returns the position of the cursor (hot spot) of the primary screen in global screen coordinates.
Definition qcursor.cpp:188
\inmodule QtCore
Definition qcoreevent.h:45
@ UpdateRequest
Definition qcoreevent.h:113
static QString * displayName
QScreen * primaryScreen
the primary (or default) screen of the application.
static QScreen * screenAt(const QPoint &point)
Returns the screen at point, or \nullptr if outside of any screen.
static bool isActive()
static qreal factor(C *context)
The QIcon class provides scalable icons in different modes and states.
Definition qicon.h:20
\inmodule QtCore
Definition qmargins.h:24
The QPlatformScreen class provides an abstraction for visual displays.
virtual QRect geometry() const =0
Reimplement in subclass to return the pixel geometry of the screen.
virtual QRect availableGeometry() const
Reimplement in subclass to return the pixel geometry of the available space This normally is the desk...
The QPlatformSurface class provides an abstraction for a surface.
friend class QPlatformWindow
The QPlatformWindow class provides an abstraction for top-level windows.
virtual bool startSystemMove()
Reimplement this method to start a system move operation if the system supports it and return true to...
QRect windowFrameGeometry() const
Returns the QWindow frame geometry.
virtual bool isExposed() const
Returns if this window is exposed in the windowing system.
static QString formatWindowTitle(const QString &title, const QString &separator)
Call this method to put together a window title composed of title separator the application display n...
virtual void setWindowFlags(Qt::WindowFlags flags)
Requests setting the window flags of this surface to flags.
virtual bool frameStrutEventsEnabled() const
Reimplement this method to return whether frame strut events are enabled.
virtual bool isAlertState() const
Reimplement this method return whether the window is in an alert state.
virtual void setWindowFilePath(const QString &title)
Reimplement to set the window file path to filePath.
virtual QPoint mapFromGlobal(const QPoint &pos) const
Translates the global screen coordinate pos to window coordinates using native methods.
virtual void setVisible(bool visible)
Reimplemented in subclasses to show the surface if visible is true, and hide it if visible is false.
virtual void setWindowTitle(const QString &title)
Reimplement to set the window title to title.
virtual void initialize()
Called as part of QWindow::create(), after constructing the window.
QWindow * window() const
Returns the window which belongs to the QPlatformWindow.
QPlatformScreen * screenForGeometry(const QRect &newGeometry) const
Helper function for finding the new screen for newGeometry in response to a geometry changed event.
QPlatformScreen * screen() const override
Returns the platform screen handle corresponding to this platform window, or null if the window is no...
QSize windowMinimumSize() const
Returns the QWindow minimum size.
virtual bool windowEvent(QEvent *event)
Reimplement this method to be able to do any platform specific event handling.
static QRectF closestAcceptableGeometry(const QWindow *w, const QRectF &nativeRect)
Returns the closest acceptable geometry for a given geometry before a resize/move event for platforms...
virtual QRect normalGeometry() const
Returns the geometry of a window in 'normal' state (neither maximized, fullscreen nor minimized) for ...
QPlatformWindow * parent() const
Returns the parent platform window (or \nullptr if orphan).
virtual void handleContentOrientationChange(Qt::ScreenOrientation orientation)
Handle changes to the orientation of the platform window's contents.
virtual void setGeometry(const QRect &rect)
This function is called by Qt whenever a window is moved or resized using the QWindow API.
virtual void setFrameStrutEventsEnabled(bool enabled)
Reimplement this method to set whether frame strut events should be sent to enabled.
static QSize constrainWindowSize(const QSize &size)
Returns a size with both dimensions bounded to [0, QWINDOWSIZE_MAX].
virtual bool setWindowModified(bool modified)
Reimplement to be able to let Qt indicate that the window has been modified.
bool hasPendingUpdateRequest() const
Returns true if the window has a pending update request.
virtual void setWindowState(Qt::WindowStates state)
Requests setting the window state of this surface to type.
virtual QSurfaceFormat format() const override
Returns the actual surface format of the window.
virtual void setMask(const QRegion &region)
Reimplement to be able to let Qt set the mask of a window.
virtual void requestActivateWindow()
Reimplement to let Qt be able to request activation/focus for a window.
virtual void setOpacity(qreal level)
Reimplement to be able to let Qt set the opacity level of a window.
virtual void raise()
Reimplement to be able to let Qt raise windows to the top of the desktop.
virtual QRect geometry() const
Returns the current geometry of a window.
QPointF mapFromGlobalF(const QPointF &pos) const
virtual QMargins safeAreaMargins() const
The safe area margins of a window represent the area that is safe to place content within,...
virtual void setParent(const QPlatformWindow *window)
This function is called to enable native child window in QPA.
~QPlatformWindow() override
Virtual destructor does not delete its top level window.
virtual void propagateSizeHints()
Reimplement to propagate the size hints of the QWindow.
virtual void setAlertState(bool enabled)
Reimplement this method to set whether the window demands attention (for example, by flashing the tas...
virtual void deliverUpdateRequest()
Delivers an QEvent::UpdateRequest event to the window.
virtual bool isActive() const
Returns true if the window should appear active from a style perspective.
virtual void requestUpdate()
Requests an QEvent::UpdateRequest event.
QRectF windowClosestAcceptableGeometry(const QRectF &nativeRect) const
virtual WId winId() const
Reimplement in subclasses to return a handle to the native window.
virtual void invalidateSurface()
Invalidates the window's surface by releasing its surface buffers.
virtual bool isEmbedded() const
Returns true if the window is a child of a non-Qt window.
virtual bool isAncestorOf(const QPlatformWindow *child) const
Returns true if the window is an ancestor of the given child.
virtual QMargins frameMargins() const
virtual qreal devicePixelRatio() const
Reimplement this function in subclass to return the device pixel ratio for the window.
QPointF mapToGlobalF(const QPointF &pos) const
QRect windowGeometry() const
Returns the QWindow geometry.
virtual QPoint mapToGlobal(const QPoint &pos) const
Translates the window coordinate pos to global screen coordinates using native methods.
virtual bool close()
Reimplement to let the platform handle non-spontaneous window close.
virtual bool startSystemResize(Qt::Edges edges)
Reimplement this method to start a system resize operation if the system supports it and return true ...
virtual bool isForeignWindow() const
virtual bool setKeyboardGrabEnabled(bool grab)
QSize windowBaseSize() const
Returns the QWindow base size.
QSize windowMaximumSize() const
Returns the QWindow maximum size.
virtual void lower()
Reimplement to be able to let Qt lower windows to the bottom of the desktop.
static QRect initialGeometry(const QWindow *w, const QRect &initialGeometry, int defaultWidth, int defaultHeight, const QScreen **resultingScreenReturn=nullptr)
Helper function to get initial geometry on windowing systems which do not do smart positioning and al...
virtual bool setMouseGrabEnabled(bool grab)
QSize windowSizeIncrement() const
Returns the QWindow size increment.
virtual void setWindowIcon(const QIcon &icon)
Reimplement to set the window icon to icon.
\inmodule QtCore\reentrant
Definition qpoint.h:217
\inmodule QtCore\reentrant
Definition qpoint.h:25
\inmodule QtCore\reentrant
Definition qrect.h:484
\inmodule QtCore\reentrant
Definition qrect.h:30
constexpr bool isEmpty() const noexcept
Returns true if the rectangle is empty, otherwise returns false.
Definition qrect.h:167
bool intersects(const QRect &r) const noexcept
Returns true if this rectangle intersects with the given rectangle (i.e., there is at least one pixel...
Definition qrect.cpp:1069
constexpr QPoint topLeft() const noexcept
Returns the position of the rectangle's top-left corner.
Definition qrect.h:221
bool contains(const QRect &r, bool proper=false) const noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition qrect.cpp:855
constexpr QPoint center() const noexcept
Returns the center point of the rectangle.
Definition qrect.h:233
The QRegion class specifies a clip region for a painter.
Definition qregion.h:27
The QScreen class is used to query screen properties. \inmodule QtGui.
Definition qscreen.h:32
QList< QScreen * > virtualSiblings() const
Get the screen's virtual siblings.
Definition qscreen.cpp:357
QPlatformScreen * handle() const
Get the platform screen handle.
Definition qscreen.cpp:83
\inmodule QtCore
Definition qsize.h:25
\macro QT_RESTRICTED_CAST_FROM_ASCII
Definition qstring.h:129
bool endsWith(const QString &s, Qt::CaseSensitivity cs=Qt::CaseSensitive) const
Returns true if the string ends with s; otherwise returns false.
Definition qstring.cpp:5506
The QSurfaceFormat class represents the format of a QSurface. \inmodule QtGui.
\inmodule QtCore
Definition qcoreevent.h:366
int timerId() const
Returns the unique timer identifier, which is the same identifier as returned from QObject::startTime...
Definition qcoreevent.h:370
bool updateRequestPending
Definition qwindow_p.h:147
bool updateDevicePixelRatio()
Definition qwindow.cpp:1400
static bool flushWindowSystemEvents(QEventLoop::ProcessEventsFlags flags=QEventLoop::AllEvents)
Make Qt Gui process all events on the event queue immediately.
static void handleFocusWindowChanged(QWindow *window, Qt::FocusReason r=Qt::OtherFocusReason)
static bool handleExposeEvent(QWindow *window, const QRegion &region)
\inmodule QtGui
Definition qwindow.h:63
rect
[4]
T toNativePixels(const T &value, const C *context)
T toNative(const T &value, qreal scaleFactor, QPoint origin=QPoint(0, 0))
T fromNativePixels(const T &value, const C *context)
T fromNative(const T &value, qreal scaleFactor, QPoint origin=QPoint(0, 0))
T toNativeWindowGeometry(const T &value, const C *context)
T fromNativeWindowGeometry(const T &value, const C *context)
Combined button and popup list for selecting options.
@ PreciseTimer
ScreenOrientation
Definition qnamespace.h:271
@ Popup
Definition qnamespace.h:211
#define qWarning
Definition qlogging.h:166
GLenum GLuint GLint level
GLfloat GLfloat GLfloat w
[0]
GLenum GLuint GLintptr GLsizeiptr size
[1]
GLenum GLenum GLsizei const GLuint GLboolean enabled
GLbitfield flags
GLboolean enable
struct _cl_event * event
GLuint64EXT * result
[6]
GLfloat GLfloat p
[1]
static QSize fixInitialSize(QSize size, const QWindow *w, int deviceIndependentDefaultWidth, int deviceIndependentDefaultHeight)
static const QScreen * effectiveScreen(const QWindow *window)
#define QWINDOWSIZE_MAX
static qreal position(const QQuickItem *item, QQuickAnchors::Anchor anchorLine)
#define Q_ASSERT(cond)
Definition qrandom.cpp:47
QScreen * screen
[1]
Definition main.cpp:29
Q_CORE_EXPORT int qEnvironmentVariableIntValue(const char *varName, bool *ok=nullptr) noexcept
#define Q_UNUSED(x)
double qreal
Definition qtypes.h:187
Q_GUI_EXPORT QWindowPrivate * qt_window_private(QWindow *window)
Definition qwindow.cpp:2950
static QRect frameGeometry(HWND hwnd, bool topLevel)
QtConcurrent::task([]{ qDebug("Hello, world!");}).spawn(FutureResult void increment(QPromise< int > &promise, int i)
[10]
QString title
[35]
QLayoutItem * child
[0]
aWidget window() -> setWindowTitle("New Window Title")
[2]
QNetworkRequest request(url)