Compare commits

...

18 Commits

Author SHA1 Message Date
kleuter
ff167a036d v6.8.1 2025-03-21 13:11:05 +01:00
kleuter
b149cc3eb2 one more change from Qt 6.8.2 2025-03-17 18:15:19 +01:00
kleuter
97ed722167 update to Qt 6.8.2 2025-03-17 18:04:27 +01:00
kleuter
15d5fb5382 turn off directwrite fonts on Windows prior to Windows 10 (issue https://github.com/crystalidea/qt6windows7/issues/33) 2025-03-17 17:22:31 +01:00
Kleuter
e92ba4dce4
Merge pull request #28 from wsxarcher/patch-1
Fix build for non-windows
2025-01-28 16:19:22 +01:00
Kleuter
50a1a7f6e9
Update README.md 2025-01-21 18:10:27 +01:00
kleuter
f56de58895 fixed #26 2025-01-21 17:27:49 +01:00
kleuter
b371361f55 qwindowsintegration.cpp original 2025-01-21 12:02:54 +01:00
Kleuter
aabe4f68c7
Merge pull request #29 from wsxarcher/patch-2
Fix mingw cross compilation on linux
2024-12-28 10:03:34 +01:00
Kleuter
263451546b
Merge pull request #30 from wsxarcher/patch-3
Fix gcc (mingw) compilation of pointer comparison in switch using ifs
2024-12-28 09:59:23 +01:00
wsxarcher
04ec1a740d fix gcc compilation of pointer comparison 2024-12-27 23:53:49 +01:00
Marco Bartoli
5a8a83f569 Fix mingw cross compilation 2024-12-16 02:02:54 +01:00
Marco Bartoli
d6525e7907
Fix build on non-windows 2024-12-15 23:00:30 +01:00
Kleuter
45d7e6576d
Update README.md 2024-12-13 15:50:31 +01:00
kleuter
8c8f9a4e87 Qt 6.8.1 2024-12-13 13:51:13 +01:00
Kleuter
a9966ab3ae
Update README.md 2024-11-21 14:34:17 +01:00
kleuter
4f4f7a7c46 fixed compilation when using non-microsoft compiler 2024-11-19 13:57:04 +01:00
Kleuter
6ba197bce4
Update README.md 2024-11-18 13:56:33 +01:00
16 changed files with 985 additions and 92 deletions

View File

@ -1,21 +1,16 @@
This repository provides a backport of the Qt 6.8.0 qtbase module, tailored for compatibility with Windows 7 and 8. It contains patched source files from the qtbase module, along with some additional required files. To apply the backport, simply copy the contents of the src folder into your qtbase/src directory, replacing the existing files.
This repository provides a backport of the Qt 6.8.2 qtbase module, tailored for compatibility with Windows 7, 8 and 8.1. It contains patched source files from the qtbase module, along with some additional required files. To apply the backport, simply copy the contents of the src folder into your qtbase/src directory, replacing the existing files.
This approach builds upon the methodology discussed in [forum thread](https://forum.qt.io/topic/133002/qt-creator-6-0-1-and-qt-6-2-2-running-on-windows-7/60) but offers significant enhancements, including important fallbacks to the default Qt 6 behavior when running on newer versions of Windows.
This approach builds upon the methodology discussed in this forum [thread](https://forum.qt.io/topic/133002/qt-creator-6-0-1-and-qt-6-2-2-running-on-windows-7/60) but offers significant enhancements, including important fallbacks to the default Qt 6 behavior when running on newer versions of Windows.
You have two options for compiling Qt:
You can compile it yourself using your preferred compiler and build options or can use our [compile_win.pl](https://github.com/crystalidea/qt-build-tools/tree/master/6.8.1) build script, which utilizes Visual C++ 2022 and includes OpenSSL 3.0.13 statically linked. Alternatively, you can download our [prebuild Qt dlls](https://github.com/crystalidea/qt6windows7/releases), which also include the Qt Designer binary for demonstration purposes.
- Compile it yourself using your preferred compiler and build options.
- Use our [compile_win.pl](https://github.com/crystalidea/qt-build-tools/tree/master/6.8.0) build script, which utilizes Visual C++ 2022 and includes OpenSSL 3.0.13 statically linked.
Alternatively, you can download our [prebuild Qt dlls](https://github.com/crystalidea/qt6windows7/releases), which also include the Qt Designer binary for demonstration purposes.
**Qt 6.8.0 designer running on Windows 7**:
**Qt 6.8.2 designer running on Windows 7**:
![Qt Designer](designer.png)
**Other modules**:
Many of other modules should also work on Windows 7 without modifications, e.g.
Many of other Qt 6 modules are known to work fine on Windows 7 without modifications when compiled with patched qtbase. Verified modules:
- qt5compat
- qtimageformats
@ -28,7 +23,8 @@ Many of other modules should also work on Windows 7 without modifications, e.g.
### Older versions:
- [Qt 6.7.3](https://github.com/crystalidea/qt6windows7/releases/tag/v6.7.3)
- [Qt 6.8.1](https://github.com/crystalidea/qt6windows7/releases/tag/v6.8.1)
- [Qt 6.8.0](https://github.com/crystalidea/qt6windows7/releases/tag/v6.8.0)
- [Qt 6.7.2](https://github.com/crystalidea/qt6windows7/releases/tag/v6.7.2)
- [Qt 6.6.3](https://github.com/crystalidea/qt6windows7/releases/tag/v6.6.3)
- [Qt 6.6.2](https://github.com/crystalidea/qt6windows7/releases/tag/v6.6.2)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 63 KiB

View File

@ -12,7 +12,7 @@
#include <qt_windows.h>
#include <shlobj.h>
#include <VersionHelpers.h>
#include <versionhelpers.h>
#include <intshcut.h>
#include <qvarlengtharray.h>

View File

@ -637,6 +637,7 @@ void QRecursiveMutex::unlock() noexcept
/*!
\internal helper for lock()
*/
Q_NEVER_INLINE
void QBasicMutex::lockInternal() QT_MUTEX_LOCK_NOEXCEPT
{
if (futexAvailable()) {
@ -670,6 +671,7 @@ bool QBasicMutex::lockInternal(int timeout) QT_MUTEX_LOCK_NOEXCEPT
/*!
\internal helper for tryLock(QDeadlineTimer)
*/
Q_NEVER_INLINE
bool QBasicMutex::lockInternal(QDeadlineTimer deadlineTimer) QT_MUTEX_LOCK_NOEXCEPT
{
if (deadlineTimer.hasExpired())
@ -809,6 +811,7 @@ bool QBasicMutex::lockInternal(QDeadlineTimer deadlineTimer) QT_MUTEX_LOCK_NOEXC
/*!
\internal
*/
Q_NEVER_INLINE
void QBasicMutex::unlockInternal() noexcept
{
QMutexPrivate *copy = d_ptr.loadAcquire();

View File

@ -11,6 +11,7 @@
#include <private/qcoreapplication_p.h>
#include <private/qeventdispatcher_win_p.h>
#include "qloggingcategory.h"
#include <qt_windows.h>
@ -76,7 +77,7 @@ QThreadData *QThreadData::current(bool createIfNecessary)
// avoid recursion.
TlsSetValue(qt_current_thread_data_tls_index, threadData);
QT_TRY {
threadData->thread = new QAdoptedThread(threadData);
threadData->thread.storeRelease(new QAdoptedThread(threadData));
} QT_CATCH(...) {
TlsSetValue(qt_current_thread_data_tls_index, 0);
threadData->deref();
@ -101,7 +102,7 @@ QThreadData *QThreadData::current(bool createIfNecessary)
0,
FALSE,
DUPLICATE_SAME_ACCESS);
qt_watch_adopted_thread(realHandle, threadData->thread);
qt_watch_adopted_thread(realHandle, threadData->thread.loadRelaxed());
}
}
return threadData;
@ -209,7 +210,7 @@ DWORD WINAPI qt_adopted_thread_watcher_function(LPVOID)
auto thread_p = static_cast<QThreadPrivate *>(QObjectPrivate::get(thread));
Q_UNUSED(thread_p);
Q_ASSERT(!thread_p->finished);
QThreadPrivate::finish(thread);
thread_p->finish();
}
data->deref();
@ -240,6 +241,8 @@ typedef struct tagTHREADNAME_INFO
typedef HRESULT(WINAPI* SetThreadDescriptionFunc)(HANDLE, PCWSTR);
#if defined(Q_CC_MSVC)
// Helper function to set the thread name using RaiseException and __try
static void setThreadNameUsingException(HANDLE threadId, LPCSTR threadName) {
THREADNAME_INFO info;
@ -256,6 +259,8 @@ static void setThreadNameUsingException(HANDLE threadId, LPCSTR threadName) {
}
}
#endif // Q_CC_MSVC
void qt_set_thread_name(HANDLE threadId, const QString &name)
{
HMODULE hKernel32 = GetModuleHandleW(L"Kernel32.dll");
@ -278,7 +283,6 @@ void qt_set_thread_name(HANDLE threadId, const QString &name)
}
}
/**************************************************************************
** QThreadPrivate
*************************************************************************/
@ -322,7 +326,7 @@ unsigned int __stdcall QT_ENSURE_STACK_ALIGNED_FOR_SSE QThreadPrivate::start(voi
QThread::setTerminationEnabled(true);
thr->run();
finish(arg);
thr->d_func()->finish();
return 0;
}
@ -337,10 +341,10 @@ unsigned int __stdcall QT_ENSURE_STACK_ALIGNED_FOR_SSE QThreadPrivate::start(voi
In those cases, \a arg will not be the current thread.
*/
void QThreadPrivate::finish(void *arg, bool lockAnyway) noexcept
void QThreadPrivate::finish(bool lockAnyway) noexcept
{
QThread *thr = reinterpret_cast<QThread *>(arg);
QThreadPrivate *d = thr->d_func();
QThreadPrivate *d = this;
QThread *thr = q_func();
QMutexLocker locker(lockAnyway ? &d->mutex : nullptr);
d->isInFinish = true;
@ -349,7 +353,6 @@ void QThreadPrivate::finish(void *arg, bool lockAnyway) noexcept
if (lockAnyway)
locker.unlock();
emit thr->finished(QThread::QPrivateSignal());
qCDebug(lcDeleteLater) << "Sending deferred delete events as part of finishing thread" << thr;
QCoreApplicationPrivate::sendPostedEvents(nullptr, QEvent::DeferredDelete, d->data);
QThreadStorageData::finish(tls_data);
if (lockAnyway)
@ -534,7 +537,7 @@ void QThread::terminate()
}
TerminateThread(d->handle, 0);
QThreadPrivate::finish(this, false);
d->finish(false);
}
bool QThread::wait(QDeadlineTimer deadline)
@ -548,6 +551,13 @@ bool QThread::wait(QDeadlineTimer deadline)
}
if (d->finished || !d->running)
return true;
return d->wait(locker, deadline);
}
bool QThreadPrivate::wait(QMutexLocker<QMutex> &locker, QDeadlineTimer deadline)
{
Q_ASSERT(locker.isLocked());
QThreadPrivate *d = this;
++d->waiters;
locker.mutex()->unlock();
@ -572,7 +582,7 @@ bool QThread::wait(QDeadlineTimer deadline)
if (ret && !d->finished) {
// thread was terminated by someone else
QThreadPrivate::finish(this, false);
d->finish(false);
}
if (d->finished && !d->waiters) {
@ -592,7 +602,7 @@ void QThread::setTerminationEnabled(bool enabled)
QMutexLocker locker(&d->mutex);
d->terminationEnabled = enabled;
if (enabled && d->terminatePending) {
QThreadPrivate::finish(thr, false);
d->finish(false);
locker.unlock(); // don't leave the mutex locked!
_endthreadex(0);
}

View File

@ -12,7 +12,7 @@
#include <cstdio>
#include <VersionHelpers.h>
#include <versionhelpers.h>
QT_BEGIN_NAMESPACE
@ -3312,6 +3312,10 @@ bool QD3D11Texture::prepareCreate(QSize *adjustedSize)
if (tex || tex3D || tex1D)
destroy();
QRHI_RES_RHI(QRhiD3D11);
if (!rhiD->isTextureFormatSupported(m_format, m_flags))
return false;
const bool isDepth = isDepthTextureFormat(m_format);
const bool isCube = m_flags.testFlag(CubeMap);
const bool is3D = m_flags.testFlag(ThreeDimensional);
@ -3322,7 +3326,6 @@ bool QD3D11Texture::prepareCreate(QSize *adjustedSize)
const QSize size = is1D ? QSize(qMax(1, m_pixelSize.width()), 1)
: (m_pixelSize.isEmpty() ? QSize(1, 1) : m_pixelSize);
QRHI_RES_RHI(QRhiD3D11);
dxgiFormat = toD3DTextureFormat(m_format, m_flags);
mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1);
sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount);

View File

@ -4210,6 +4210,10 @@ bool QD3D12Texture::prepareCreate(QSize *adjustedSize)
if (!handle.isNull())
destroy();
QRHI_RES_RHI(QRhiD3D12);
if (!rhiD->isTextureFormatSupported(m_format, m_flags))
return false;
const bool isDepth = isDepthTextureFormat(m_format);
const bool isCube = m_flags.testFlag(CubeMap);
const bool is3D = m_flags.testFlag(ThreeDimensional);
@ -4240,7 +4244,7 @@ bool QD3D12Texture::prepareCreate(QSize *adjustedSize)
else
srvFormat = toD3DTextureFormat(m_readViewFormat.format, m_readViewFormat.srgb ? sRGB : Flags());
}
QRHI_RES_RHI(QRhiD3D12);
mipLevelCount = uint(hasMipMaps ? rhiD->q->mipLevelsForSize(size) : 1);
sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, dxgiFormat);
if (sampleDesc.Count > 1) {
@ -5693,7 +5697,16 @@ bool QD3D12GraphicsPipeline::create()
}
QD3D12RenderPassDescriptor *rpD = QRHI_RES(QD3D12RenderPassDescriptor, m_renderPassDesc);
const DXGI_SAMPLE_DESC sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, DXGI_FORMAT(rpD->colorFormat[0]));
DXGI_FORMAT format = DXGI_FORMAT_UNKNOWN;
if (rpD->colorAttachmentCount > 0) {
format = DXGI_FORMAT(rpD->colorFormat[0]);
} else if (rpD->hasDepthStencil) {
format = DXGI_FORMAT(rpD->dsFormat);
} else {
qWarning("Cannot create graphics pipeline state without color or depthStencil format");
return false;
}
const DXGI_SAMPLE_DESC sampleDesc = rhiD->effectiveSampleDesc(m_sampleCount, format);
struct {
QD3D12PipelineStateSubObject<ID3D12RootSignature *, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE> rootSig;

View File

@ -1562,11 +1562,9 @@ void QWindowsContext::setAsyncExpose(bool value)
DWORD QWindowsContext::readAdvancedExplorerSettings(const wchar_t *subKey, DWORD defaultValue)
{
const auto value =
QWinRegistryKey(HKEY_CURRENT_USER,
LR"(Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced)")
.dwordValue(subKey);
return value.second ? value.first : defaultValue;
const auto advancedSettings = QWinRegistryKey(
HKEY_CURRENT_USER, LR"(Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced)");
return advancedSettings.value<DWORD>(subKey).value_or(defaultValue);
}
static inline bool isEmptyRect(const RECT &rect)

View File

@ -0,0 +1,779 @@
// Copyright (C) 2016 The Qt Company Ltd.
// Copyright (C) 2013 Samuel Gaist <samuel.gaist@edeltech.ch>
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#include "qwindowsintegration.h"
#include "qwindowswindow.h"
#include "qwindowscontext.h"
#include "qwin10helpers.h"
#include "qwindowsmenu.h"
#include "qwindowsopenglcontext.h"
#include "qwindowsscreen.h"
#include "qwindowstheme.h"
#include "qwindowsservices.h"
#include <QtGui/private/qtgui-config_p.h>
#if QT_CONFIG(directwrite3)
#include <QtGui/private/qwindowsdirectwritefontdatabase_p.h>
#endif
#ifndef QT_NO_FREETYPE
# include <QtGui/private/qwindowsfontdatabase_ft_p.h>
#endif
#include <QtGui/private/qwindowsfontdatabase_p.h>
#if QT_CONFIG(clipboard)
# include "qwindowsclipboard.h"
# if QT_CONFIG(draganddrop)
# include "qwindowsdrag.h"
# endif
#endif
#include "qwindowsinputcontext.h"
#include "qwindowskeymapper.h"
#if QT_CONFIG(accessibility)
# include "uiautomation/qwindowsuiaaccessibility.h"
#endif
#include <qpa/qplatformnativeinterface.h>
#include <qpa/qwindowsysteminterface.h>
#if QT_CONFIG(sessionmanager)
# include "qwindowssessionmanager.h"
#endif
#include <QtGui/qpointingdevice.h>
#include <QtGui/private/qguiapplication_p.h>
#include <QtGui/private/qhighdpiscaling_p.h>
#include <QtGui/qpa/qplatforminputcontextfactory_p.h>
#include <QtGui/qpa/qplatformcursor.h>
#include <QtGui/private/qwindowsguieventdispatcher_p.h>
#include <QtCore/qdebug.h>
#include <QtCore/qvariant.h>
#include <QtCore/qoperatingsystemversion.h>
#include <QtCore/private/qfunctions_win_p.h>
#include <wrl.h>
#include <limits.h>
#if !defined(QT_NO_OPENGL)
# include "qwindowsglcontext.h"
#endif
#include "qwindowsopengltester.h"
#if QT_CONFIG(cpp_winrt)
# include <QtCore/private/qt_winrtbase_p.h>
# include <winrt/Windows.UI.Notifications.h>
# include <winrt/Windows.Data.Xml.Dom.h>
# include <winrt/Windows.Foundation.h>
# include <winrt/Windows.UI.ViewManagement.h>
#endif
#include <memory>
static inline void initOpenGlBlacklistResources()
{
Q_INIT_RESOURCE(openglblacklists);
}
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
struct QWindowsIntegrationPrivate
{
Q_DISABLE_COPY_MOVE(QWindowsIntegrationPrivate)
explicit QWindowsIntegrationPrivate() = default;
~QWindowsIntegrationPrivate();
void parseOptions(QWindowsIntegration *q, const QStringList &paramList);
unsigned m_options = 0;
QWindowsContext m_context;
QPlatformFontDatabase *m_fontDatabase = nullptr;
#if QT_CONFIG(clipboard)
QWindowsClipboard m_clipboard;
# if QT_CONFIG(draganddrop)
QWindowsDrag m_drag;
# endif
#endif
#ifndef QT_NO_OPENGL
QMutex m_staticContextLock;
QScopedPointer<QWindowsStaticOpenGLContext> m_staticOpenGLContext;
#endif // QT_NO_OPENGL
QScopedPointer<QPlatformInputContext> m_inputContext;
#if QT_CONFIG(accessibility)
QWindowsUiaAccessibility m_accessibility;
#endif
QWindowsServices m_services;
};
template <typename IntType>
bool parseIntOption(const QString &parameter,const QLatin1StringView &option,
IntType minimumValue, IntType maximumValue, IntType *target)
{
const int valueLength = parameter.size() - option.size() - 1;
if (valueLength < 1 || !parameter.startsWith(option) || parameter.at(option.size()) != u'=')
return false;
bool ok;
const auto valueRef = QStringView{parameter}.right(valueLength);
const int value = valueRef.toInt(&ok);
if (ok) {
if (value >= int(minimumValue) && value <= int(maximumValue))
*target = static_cast<IntType>(value);
else {
qWarning() << "Value" << value << "for option" << option << "out of range"
<< minimumValue << ".." << maximumValue;
}
} else {
qWarning() << "Invalid value" << valueRef << "for option" << option;
}
return true;
}
using DarkModeHandlingFlag = QNativeInterface::Private::QWindowsApplication::DarkModeHandlingFlag;
using DarkModeHandling = QNativeInterface::Private::QWindowsApplication::DarkModeHandling;
static inline unsigned parseOptions(const QStringList &paramList,
int *tabletAbsoluteRange,
QtWindows::DpiAwareness *dpiAwareness,
DarkModeHandling *darkModeHandling)
{
unsigned options = 0;
for (const QString &param : paramList) {
if (param.startsWith(u"fontengine=")) {
if (param.endsWith(u"gdi")) {
options |= QWindowsIntegration::FontDatabaseGDI;
} else if (param.endsWith(u"freetype")) {
options |= QWindowsIntegration::FontDatabaseFreeType;
} else if (param.endsWith(u"native")) {
options |= QWindowsIntegration::FontDatabaseNative;
}
} else if (param.startsWith(u"dialogs=")) {
if (param.endsWith(u"xp")) {
options |= QWindowsIntegration::XpNativeDialogs;
} else if (param.endsWith(u"none")) {
options |= QWindowsIntegration::NoNativeDialogs;
}
} else if (param == u"altgr") {
options |= QWindowsIntegration::DetectAltGrModifier;
} else if (param == u"gl=gdi") {
options |= QWindowsIntegration::DisableArb;
} else if (param == u"nodirectwrite") {
options |= QWindowsIntegration::DontUseDirectWriteFonts;
} else if (param == u"nocolorfonts") {
options |= QWindowsIntegration::DontUseColorFonts;
} else if (param == u"nomousefromtouch") {
options |= QWindowsIntegration::DontPassOsMouseEventsSynthesizedFromTouch;
} else if (parseIntOption(param, "verbose"_L1, 0, INT_MAX, &QWindowsContext::verbose)
|| parseIntOption(param, "tabletabsoluterange"_L1, 0, INT_MAX, tabletAbsoluteRange)
|| parseIntOption(param, "dpiawareness"_L1, QtWindows::DpiAwareness::Invalid,
QtWindows::DpiAwareness::PerMonitorVersion2, dpiAwareness)) {
} else if (param == u"menus=native") {
options |= QWindowsIntegration::AlwaysUseNativeMenus;
} else if (param == u"menus=none") {
options |= QWindowsIntegration::NoNativeMenus;
} else if (param == u"reverse") {
options |= QWindowsIntegration::RtlEnabled;
} else if (param == u"darkmode=0") {
*darkModeHandling = {};
} else if (param == u"darkmode=1") {
darkModeHandling->setFlag(DarkModeHandlingFlag::DarkModeWindowFrames);
darkModeHandling->setFlag(DarkModeHandlingFlag::DarkModeStyle, false);
} else if (param == u"darkmode=2") {
darkModeHandling->setFlag(DarkModeHandlingFlag::DarkModeWindowFrames);
darkModeHandling->setFlag(DarkModeHandlingFlag::DarkModeStyle);
} else {
qWarning() << "Unknown option" << param;
}
}
return options;
}
void QWindowsIntegrationPrivate::parseOptions(QWindowsIntegration *q, const QStringList &paramList)
{
initOpenGlBlacklistResources();
static bool dpiAwarenessSet = false;
// Default to per-monitor-v2 awareness (if available)
QtWindows::DpiAwareness dpiAwareness = QtWindows::DpiAwareness::PerMonitorVersion2;
int tabletAbsoluteRange = -1;
DarkModeHandling darkModeHandling = DarkModeHandlingFlag::DarkModeWindowFrames
| DarkModeHandlingFlag::DarkModeStyle;
m_options = ::parseOptions(paramList, &tabletAbsoluteRange, &dpiAwareness, &darkModeHandling);
q->setDarkModeHandling(darkModeHandling);
QWindowsFontDatabase::setFontOptions(m_options);
if (tabletAbsoluteRange >= 0)
QWindowsContext::setTabletAbsoluteRange(tabletAbsoluteRange);
QCoreApplication::setAttribute(Qt::AA_CompressHighFrequencyEvents);
QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(false);
if (!dpiAwarenessSet) { // Set only once in case of repeated instantiations of QGuiApplication.
if (!QCoreApplication::testAttribute(Qt::AA_PluginApplication)) {
m_context.setProcessDpiAwareness(dpiAwareness);
qCDebug(lcQpaWindow) << "DpiAwareness=" << dpiAwareness
<< "effective process DPI awareness=" << QWindowsContext::processDpiAwareness();
}
dpiAwarenessSet = true;
}
m_context.initTouch(m_options);
QPlatformCursor::setCapability(QPlatformCursor::OverrideCursor);
m_context.initPowerNotificationHandler();
}
QWindowsIntegrationPrivate::~QWindowsIntegrationPrivate()
{
delete m_fontDatabase;
}
QWindowsIntegration *QWindowsIntegration::m_instance = nullptr;
QWindowsIntegration::QWindowsIntegration(const QStringList &paramList) :
d(new QWindowsIntegrationPrivate)
{
m_instance = this;
d->parseOptions(this, paramList);
#if QT_CONFIG(clipboard)
d->m_clipboard.registerViewer();
#endif
d->m_context.screenManager().initialize();
d->m_context.setDetectAltGrModifier((d->m_options & DetectAltGrModifier) != 0);
}
QWindowsIntegration::~QWindowsIntegration()
{
m_instance = nullptr;
}
void QWindowsIntegration::initialize()
{
auto icStrs = QPlatformInputContextFactory::requested();
icStrs.isEmpty() ? d->m_inputContext.reset(new QWindowsInputContext)
: d->m_inputContext.reset(QPlatformInputContextFactory::create(icStrs));
}
bool QWindowsIntegration::hasCapability(QPlatformIntegration::Capability cap) const
{
switch (cap) {
case ThreadedPixmaps:
return true;
#ifndef QT_NO_OPENGL
case OpenGL:
return true;
case ThreadedOpenGL:
if (const QWindowsStaticOpenGLContext *glContext = QWindowsIntegration::staticOpenGLContext())
return glContext->supportsThreadedOpenGL();
return false;
#endif // !QT_NO_OPENGL
case WindowMasks:
return true;
case MultipleWindows:
return true;
case ForeignWindows:
return true;
case RasterGLSurface:
return true;
case AllGLFunctionsQueryable:
return true;
case SwitchableWidgetComposition:
return false; // QTBUG-68329 QTBUG-53515 QTBUG-54734
case BackingStoreStaticContents:
return true;
default:
return QPlatformIntegration::hasCapability(cap);
}
return false;
}
QPlatformWindow *QWindowsIntegration::createPlatformWindow(QWindow *window) const
{
if (window->type() == Qt::Desktop) {
auto *result = new QWindowsDesktopWindow(window);
qCDebug(lcQpaWindow) << "Desktop window:" << window
<< Qt::showbase << Qt::hex << result->winId() << Qt::noshowbase << Qt::dec << result->geometry();
return result;
}
QWindowsWindowData requested;
requested.flags = window->flags();
requested.geometry = window->isTopLevel()
? QHighDpi::toNativePixels(window->geometry(), window)
: QHighDpi::toNativeLocalPosition(window->geometry(), window);
if (!(requested.flags & Qt::FramelessWindowHint)) {
// Apply custom margins (see QWindowsWindow::setCustomMargins())).
const QVariant customMarginsV = window->property("_q_windowsCustomMargins");
if (customMarginsV.isValid())
requested.customMargins = qvariant_cast<QMargins>(customMarginsV);
}
QWindowsWindowData obtained =
QWindowsWindowData::create(window, requested,
QWindowsWindow::formatWindowTitle(window->title()));
qCDebug(lcQpaWindow).nospace()
<< __FUNCTION__ << ' ' << window
<< "\n Requested: " << requested.geometry << " frame incl.="
<< QWindowsGeometryHint::positionIncludesFrame(window)
<< ' ' << requested.flags
<< "\n Obtained : " << obtained.geometry << " margins=" << obtained.fullFrameMargins
<< " handle=" << obtained.hwnd << ' ' << obtained.flags << '\n';
if (Q_UNLIKELY(!obtained.hwnd))
return nullptr;
QWindowsWindow *result = createPlatformWindowHelper(window, obtained);
Q_ASSERT(result);
if (window->isTopLevel() && !QWindowsContext::shouldHaveNonClientDpiScaling(window))
result->setFlag(QWindowsWindow::DisableNonClientScaling);
if (QWindowsMenuBar *menuBarToBeInstalled = QWindowsMenuBar::menuBarOf(window))
menuBarToBeInstalled->install(result);
return result;
}
QPlatformWindow *QWindowsIntegration::createForeignWindow(QWindow *window, WId nativeHandle) const
{
const HWND hwnd = reinterpret_cast<HWND>(nativeHandle);
if (!IsWindow(hwnd)) {
qWarning("Windows QPA: Invalid foreign window ID %p.", hwnd);
return nullptr;
}
auto *result = new QWindowsForeignWindow(window, hwnd);
const QRect obtainedGeometry = result->geometry();
QScreen *screen = nullptr;
if (const QPlatformScreen *pScreen = result->screenForGeometry(obtainedGeometry))
screen = pScreen->screen();
if (screen && screen != window->screen())
window->setScreen(screen);
qCDebug(lcQpaWindow) << "Foreign window:" << window << Qt::showbase << Qt::hex
<< result->winId() << Qt::noshowbase << Qt::dec << obtainedGeometry << screen;
return result;
}
// Overridden to return a QWindowsDirect2DWindow in Direct2D plugin.
QWindowsWindow *QWindowsIntegration::createPlatformWindowHelper(QWindow *window, const QWindowsWindowData &data) const
{
return new QWindowsWindow(window, data);
}
#ifndef QT_NO_OPENGL
QWindowsStaticOpenGLContext *QWindowsStaticOpenGLContext::doCreate()
{
#if defined(QT_OPENGL_DYNAMIC)
QWindowsOpenGLTester::Renderer requestedRenderer = QWindowsOpenGLTester::requestedRenderer();
switch (requestedRenderer) {
case QWindowsOpenGLTester::DesktopGl:
if (QWindowsStaticOpenGLContext *glCtx = QOpenGLStaticContext::create()) {
if ((QWindowsOpenGLTester::supportedRenderers(requestedRenderer) & QWindowsOpenGLTester::DisableRotationFlag)
&& !QWindowsScreen::setOrientationPreference(Qt::LandscapeOrientation)) {
qCWarning(lcQpaGl, "Unable to disable rotation.");
}
return glCtx;
}
qCWarning(lcQpaGl, "System OpenGL failed. Falling back to Software OpenGL.");
return QOpenGLStaticContext::create(true);
case QWindowsOpenGLTester::SoftwareRasterizer:
if (QWindowsStaticOpenGLContext *swCtx = QOpenGLStaticContext::create(true))
return swCtx;
qCWarning(lcQpaGl, "Software OpenGL failed. Falling back to system OpenGL.");
if (QWindowsOpenGLTester::supportedRenderers(requestedRenderer) & QWindowsOpenGLTester::DesktopGl)
return QOpenGLStaticContext::create();
return nullptr;
default:
break;
}
const QWindowsOpenGLTester::Renderers supportedRenderers = QWindowsOpenGLTester::supportedRenderers(requestedRenderer);
if (supportedRenderers.testFlag(QWindowsOpenGLTester::DisableProgramCacheFlag)
&& !QCoreApplication::testAttribute(Qt::AA_DisableShaderDiskCache)) {
QCoreApplication::setAttribute(Qt::AA_DisableShaderDiskCache);
}
if (supportedRenderers & QWindowsOpenGLTester::DesktopGl) {
if (QWindowsStaticOpenGLContext *glCtx = QOpenGLStaticContext::create()) {
if ((supportedRenderers & QWindowsOpenGLTester::DisableRotationFlag)
&& !QWindowsScreen::setOrientationPreference(Qt::LandscapeOrientation)) {
qCWarning(lcQpaGl, "Unable to disable rotation.");
}
return glCtx;
}
}
return QOpenGLStaticContext::create(true);
#else
return QOpenGLStaticContext::create();
#endif
}
QWindowsStaticOpenGLContext *QWindowsStaticOpenGLContext::create()
{
return QWindowsStaticOpenGLContext::doCreate();
}
QPlatformOpenGLContext *QWindowsIntegration::createPlatformOpenGLContext(QOpenGLContext *context) const
{
qCDebug(lcQpaGl) << __FUNCTION__ << context->format();
if (QWindowsStaticOpenGLContext *staticOpenGLContext = QWindowsIntegration::staticOpenGLContext()) {
std::unique_ptr<QWindowsOpenGLContext> result(staticOpenGLContext->createContext(context));
if (result->isValid())
return result.release();
}
return nullptr;
}
QOpenGLContext::OpenGLModuleType QWindowsIntegration::openGLModuleType()
{
#if !defined(QT_OPENGL_DYNAMIC)
return QOpenGLContext::LibGL;
#else
if (const QWindowsStaticOpenGLContext *staticOpenGLContext = QWindowsIntegration::staticOpenGLContext())
return staticOpenGLContext->moduleType();
return QOpenGLContext::LibGL;
#endif
}
HMODULE QWindowsIntegration::openGLModuleHandle() const
{
if (QWindowsStaticOpenGLContext *staticOpenGLContext = QWindowsIntegration::staticOpenGLContext())
return static_cast<HMODULE>(staticOpenGLContext->moduleHandle());
return nullptr;
}
QOpenGLContext *QWindowsIntegration::createOpenGLContext(HGLRC ctx, HWND window, QOpenGLContext *shareContext) const
{
if (!ctx || !window)
return nullptr;
if (QWindowsStaticOpenGLContext *staticOpenGLContext = QWindowsIntegration::staticOpenGLContext()) {
std::unique_ptr<QWindowsOpenGLContext> result(staticOpenGLContext->createContext(ctx, window));
if (result->isValid()) {
auto *context = new QOpenGLContext;
context->setShareContext(shareContext);
auto *contextPrivate = QOpenGLContextPrivate::get(context);
contextPrivate->adopt(result.release());
return context;
}
}
return nullptr;
}
QWindowsStaticOpenGLContext *QWindowsIntegration::staticOpenGLContext()
{
QWindowsIntegration *integration = QWindowsIntegration::instance();
if (!integration)
return nullptr;
QWindowsIntegrationPrivate *d = integration->d.data();
QMutexLocker lock(&d->m_staticContextLock);
if (d->m_staticOpenGLContext.isNull())
d->m_staticOpenGLContext.reset(QWindowsStaticOpenGLContext::create());
return d->m_staticOpenGLContext.data();
}
#endif // !QT_NO_OPENGL
QPlatformFontDatabase *QWindowsIntegration::fontDatabase() const
{
if (!d->m_fontDatabase) {
#ifndef QT_NO_FREETYPE
if (d->m_options & QWindowsIntegration::FontDatabaseFreeType)
d->m_fontDatabase = new QWindowsFontDatabaseFT;
else
#endif // QT_NO_FREETYPE
#if QT_CONFIG(directwrite3)
/* IDWriteFontFace3 is only reportedly available starting with Windows 10. This change is necessary starting
with Qt 6.8, where DirectWrite is used by default to populate the font database.
More info: https://github.com/videolan/vlc/blob/master/contrib/src/qt/0001-Use-DirectWrite-font-database-only-with-Windows-10-a.patch
*/
if (QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows10 &&
!(d->m_options & (QWindowsIntegration::FontDatabaseGDI | QWindowsIntegration::DontUseDirectWriteFonts)))
d->m_fontDatabase = new QWindowsDirectWriteFontDatabase;
else
#endif
d->m_fontDatabase = new QWindowsFontDatabase;
}
return d->m_fontDatabase;
}
#ifdef SPI_GETKEYBOARDSPEED
static inline int keyBoardAutoRepeatRateMS()
{
DWORD time = 0;
if (SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &time, 0))
return time ? 1000 / static_cast<int>(time) : 500;
return 30;
}
#endif
QVariant QWindowsIntegration::styleHint(QPlatformIntegration::StyleHint hint) const
{
switch (hint) {
case QPlatformIntegration::CursorFlashTime:
if (const unsigned timeMS = GetCaretBlinkTime())
return QVariant(timeMS != INFINITE ? int(timeMS) * 2 : 0);
break;
#ifdef SPI_GETKEYBOARDSPEED
case KeyboardAutoRepeatRate:
return QVariant(keyBoardAutoRepeatRateMS());
#endif
case QPlatformIntegration::ShowIsMaximized:
case QPlatformIntegration::StartDragTime:
case QPlatformIntegration::StartDragDistance:
case QPlatformIntegration::KeyboardInputInterval:
case QPlatformIntegration::ShowIsFullScreen:
case QPlatformIntegration::PasswordMaskDelay:
case QPlatformIntegration::StartDragVelocity:
break; // Not implemented
case QPlatformIntegration::FontSmoothingGamma:
return QVariant(QWindowsFontDatabase::fontSmoothingGamma());
case QPlatformIntegration::MouseDoubleClickInterval:
if (const UINT ms = GetDoubleClickTime())
return QVariant(int(ms));
break;
case QPlatformIntegration::UseRtlExtensions:
return QVariant(d->m_context.useRTLExtensions());
default:
break;
}
return QPlatformIntegration::styleHint(hint);
}
QPlatformKeyMapper *QWindowsIntegration::keyMapper() const
{
return d->m_context.keyMapper();
}
#if QT_CONFIG(clipboard)
QPlatformClipboard * QWindowsIntegration::clipboard() const
{
return &d->m_clipboard;
}
# if QT_CONFIG(draganddrop)
QPlatformDrag *QWindowsIntegration::drag() const
{
return &d->m_drag;
}
# endif // QT_CONFIG(draganddrop)
#endif // !QT_NO_CLIPBOARD
QPlatformInputContext * QWindowsIntegration::inputContext() const
{
return d->m_inputContext.data();
}
#if QT_CONFIG(accessibility)
QPlatformAccessibility *QWindowsIntegration::accessibility() const
{
return &d->m_accessibility;
}
#endif
unsigned QWindowsIntegration::options() const
{
return d->m_options;
}
#if QT_CONFIG(sessionmanager)
QPlatformSessionManager *QWindowsIntegration::createPlatformSessionManager(const QString &id, const QString &key) const
{
return new QWindowsSessionManager(id, key);
}
#endif
QAbstractEventDispatcher * QWindowsIntegration::createEventDispatcher() const
{
return new QWindowsGuiEventDispatcher;
}
QStringList QWindowsIntegration::themeNames() const
{
return QStringList(QLatin1StringView(QWindowsTheme::name));
}
QPlatformTheme *QWindowsIntegration::createPlatformTheme(const QString &name) const
{
if (name == QLatin1StringView(QWindowsTheme::name))
return new QWindowsTheme;
return QPlatformIntegration::createPlatformTheme(name);
}
QPlatformServices *QWindowsIntegration::services() const
{
return &d->m_services;
}
void QWindowsIntegration::beep() const
{
MessageBeep(MB_OK); // For QApplication
}
void QWindowsIntegration::setApplicationBadge(qint64 number)
{
// Clamp to positive numbers, as the Windows API doesn't support negative numbers
number = qMax(0, number);
// Persist, so we can re-apply it on setting changes and Explorer restart
m_applicationBadgeNumber = number;
static const bool isWindows11 = QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows11;
#if QT_CONFIG(cpp_winrt)
// We prefer the native BadgeUpdater API, that allows us to set a number directly,
// but it requires that the application has a package identity, and also doesn't
// seem to work in all cases on < Windows 11.
QT_TRY {
if (isWindows11 && qt_win_hasPackageIdentity()) {
using namespace winrt::Windows::UI::Notifications;
auto badgeXml = BadgeUpdateManager::GetTemplateContent(BadgeTemplateType::BadgeNumber);
badgeXml.SelectSingleNode(L"//badge/@value").NodeValue(winrt::box_value(winrt::to_hstring(number)));
BadgeUpdateManager::CreateBadgeUpdaterForApplication().Update(BadgeNotification(badgeXml));
return;
}
} QT_CATCH(...) {
// fall back to win32 implementation
}
#endif
// Fallback for non-packaged apps, Windows 10, or Qt builds without WinRT/C++ support
if (!number) {
// Clear badge
setApplicationBadge(QImage());
return;
}
const bool isDarkMode = QWindowsTheme::instance()->colorScheme()
== Qt::ColorScheme::Dark;
QColor badgeColor;
QColor textColor;
#if QT_CONFIG(cpp_winrt)
if (isWindows11) {
// Match colors used by BadgeUpdater
static const auto fromUIColor = [](winrt::Windows::UI::Color &&color) {
return QColor(color.R, color.G, color.B, color.A);
};
using namespace winrt::Windows::UI::ViewManagement;
const auto settings = UISettings();
badgeColor = fromUIColor(settings.GetColorValue(isDarkMode ?
UIColorType::AccentLight2 : UIColorType::Accent));
textColor = fromUIColor(settings.GetColorValue(UIColorType::Background));
}
#endif
if (!badgeColor.isValid()) {
// Fall back to basic badge colors, based on Windows 10 look
badgeColor = isDarkMode ? Qt::black : QColor(220, 220, 220);
badgeColor.setAlphaF(0.5f);
textColor = isDarkMode ? Qt::white : Qt::black;
}
const auto devicePixelRatio = qApp->devicePixelRatio();
static const QSize iconBaseSize(16, 16);
QImage image(iconBaseSize * devicePixelRatio,
QImage::Format_ARGB32_Premultiplied);
image.fill(Qt::transparent);
QPainter painter(&image);
QRect badgeRect = image.rect();
QPen badgeBorderPen = Qt::NoPen;
if (!isWindows11) {
QColor badgeBorderColor = textColor;
badgeBorderColor.setAlphaF(0.5f);
badgeBorderPen = badgeBorderColor;
badgeRect.adjust(1, 1, -1, -1);
}
painter.setBrush(badgeColor);
painter.setPen(badgeBorderPen);
painter.setRenderHint(QPainter::Antialiasing);
painter.drawEllipse(badgeRect);
auto pixelSize = qCeil(10.5 * devicePixelRatio);
// Unlike the BadgeUpdater API we're limited by a square
// badge, so adjust the font size when above two digits.
const bool textOverflow = number > 99;
if (textOverflow)
pixelSize *= 0.8;
QFont font = painter.font();
font.setPixelSize(pixelSize);
font.setWeight(isWindows11 ? QFont::Medium : QFont::DemiBold);
painter.setFont(font);
painter.setRenderHint(QPainter::TextAntialiasing, devicePixelRatio > 1);
painter.setPen(textColor);
auto text = textOverflow ? u"99+"_s : QString::number(number);
painter.translate(textOverflow ? 1 : 0, textOverflow ? 0 : -1);
painter.drawText(image.rect(), Qt::AlignCenter, text);
painter.end();
setApplicationBadge(image);
}
void QWindowsIntegration::setApplicationBadge(const QImage &image)
{
QComHelper comHelper;
using Microsoft::WRL::ComPtr;
ComPtr<ITaskbarList3> taskbarList;
CoCreateInstance(CLSID_TaskbarList, nullptr,
CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbarList));
if (!taskbarList) {
// There may not be any windows with a task bar button yet,
// in which case we'll apply the badge once a window with
// a button has been created.
return;
}
const auto hIcon = image.toHICON();
// Apply the icon to all top level windows, since the badge is
// set on an application level. If one of the windows go away
// the other windows will take over in showing the badge.
const auto topLevelWindows = QGuiApplication::topLevelWindows();
for (auto *topLevelWindow : topLevelWindows) {
if (!topLevelWindow->handle())
continue;
auto hwnd = reinterpret_cast<HWND>(topLevelWindow->winId());
taskbarList->SetOverlayIcon(hwnd, hIcon, L"");
}
DestroyIcon(hIcon);
// FIXME: Update icon when the application scale factor changes.
// Doing so in response to screen DPI changes is too soon, as the
// task bar is not yet ready for an updated icon, and will just
// result in a blurred icon even if our icon is high-DPI.
}
void QWindowsIntegration::updateApplicationBadge()
{
// The system color settings have changed, or we are reacting
// to a task bar button being created for the fist time or after
// Explorer had crashed and re-started. In any case, re-apply the
// badge so that everything is up to date.
if (m_applicationBadgeNumber)
setApplicationBadge(m_applicationBadgeNumber);
}
#if QT_CONFIG(vulkan)
QPlatformVulkanInstance *QWindowsIntegration::createPlatformVulkanInstance(QVulkanInstance *instance) const
{
return new QWindowsVulkanInstance(instance);
}
#endif
QT_END_NAMESPACE

View File

@ -1359,6 +1359,11 @@ QList<QKeyCombination> QWindowsKeyMapper::possibleKeyCombinations(const QKeyEven
return result;
}
// If Key_Tab+Shift is pressed we add Key_Backtab without
// shift modifier as a possible combination too
if (baseKey == Qt::Key_Tab && (keyMods & Qt::ShiftModifier))
result << (Qt::Key_Backtab | (keyMods & ~Qt::ShiftModifier));
// The base key is _always_ valid, of course
result << QKeyCombination::fromCombined(int(baseKey) + int(keyMods));

View File

@ -132,12 +132,12 @@ namespace {
struct DiRegKeyHandleTraits
{
using Type = HKEY;
static Type invalidValue()
static Type invalidValue() noexcept
{
// The setupapi.h functions return INVALID_HANDLE_VALUE when failing to open a registry key
return reinterpret_cast<HKEY>(INVALID_HANDLE_VALUE);
}
static bool close(Type handle) { return RegCloseKey(handle) == ERROR_SUCCESS; }
static bool close(Type handle) noexcept { return RegCloseKey(handle) == ERROR_SUCCESS; }
};
using DiRegKeyHandle = QUniqueHandle<DiRegKeyHandleTraits>;
@ -145,11 +145,11 @@ using DiRegKeyHandle = QUniqueHandle<DiRegKeyHandleTraits>;
struct DevInfoHandleTraits
{
using Type = HDEVINFO;
static Type invalidValue()
static Type invalidValue() noexcept
{
return reinterpret_cast<HDEVINFO>(INVALID_HANDLE_VALUE);
}
static bool close(Type handle) { return SetupDiDestroyDeviceInfoList(handle) == TRUE; }
static bool close(Type handle) noexcept { return SetupDiDestroyDeviceInfoList(handle) == TRUE; }
};
using DevInfoHandle = QUniqueHandle<DevInfoHandleTraits>;

View File

@ -501,7 +501,8 @@ QWindowsTheme *QWindowsTheme::m_instance = nullptr;
QWindowsTheme::QWindowsTheme()
{
m_instance = this;
s_colorScheme = QWindowsTheme::queryColorScheme();
s_colorScheme = Qt::ColorScheme::Unknown; // Used inside QWindowsTheme::effectiveColorScheme();
s_colorScheme = QWindowsTheme::effectiveColorScheme();
std::fill(m_fonts, m_fonts + NFonts, nullptr);
std::fill(m_palettes, m_palettes + NPalettes, nullptr);
refresh();
@ -596,12 +597,15 @@ Qt::ColorScheme QWindowsTheme::colorScheme() const
Qt::ColorScheme QWindowsTheme::effectiveColorScheme()
{
auto integration = QWindowsIntegration::instance();
if (queryHighContrast())
return Qt::ColorScheme::Unknown;
if (s_colorSchemeOverride != Qt::ColorScheme::Unknown)
return s_colorSchemeOverride;
if (s_colorScheme != Qt::ColorScheme::Unknown)
return s_colorScheme;
if (!integration->darkModeHandling().testFlag(QWindowsApplication::DarkModeStyle))
return Qt::ColorScheme::Light;
return queryColorScheme();
}
@ -839,7 +843,6 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
{
int resourceId = -1;
SHSTOCKICONID stockId = SIID_INVALID;
UINT stockFlags = 0;
LPCTSTR iconName = nullptr;
switch (sp) {
case DriveCDIcon:
@ -863,14 +866,12 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
resourceId = 7;
break;
case FileLinkIcon:
stockFlags = SHGSI_LINKOVERLAY;
Q_FALLTHROUGH();
case FileIcon:
stockId = SIID_DOCNOASSOC;
resourceId = 1;
break;
case DirLinkIcon:
stockFlags = SHGSI_LINKOVERLAY;
Q_FALLTHROUGH();
case DirClosedIcon:
case DirIcon:
@ -884,7 +885,6 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
resourceId = 16;
break;
case DirLinkOpenIcon:
stockFlags = SHGSI_LINKOVERLAY;
Q_FALLTHROUGH();
case DirOpenIcon:
stockId = SIID_FOLDEROPEN;
@ -924,18 +924,34 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
break;
}
// Even with SHGSI_LINKOVERLAY flag set, loaded Icon with SHDefExtractIcon doesn't have
// any overlay, so we avoid SHGSI_LINKOVERLAY flag and draw it manually (QTBUG-131843)
const auto drawLinkOverlayIconIfNeeded = [](StandardPixmap sp, QPixmap &pixmap, QSizeF pixmapSize) {
if (sp == FileLinkIcon || sp == DirLinkIcon || sp == DirLinkOpenIcon) {
QPainter painter(&pixmap);
const QSizeF linkSize = pixmapSize / (pixmapSize.height() >= 48 ? 3 : 2);
static constexpr auto LinkOverlayIconId = 16769;
const QPixmap link = loadIconFromShell32(LinkOverlayIconId, linkSize.toSize());
const int yPos = pixmap.height() - link.size().height();
painter.drawPixmap(0, yPos, int(linkSize.width()), int(linkSize.height()), link);
}
};
if (stockId != SIID_INVALID) {
SHSTOCKICONINFO iconInfo;
memset(&iconInfo, 0, sizeof(iconInfo));
iconInfo.cbSize = sizeof(iconInfo);
stockFlags |= SHGSI_ICONLOCATION;
constexpr UINT stockFlags = SHGSI_ICONLOCATION;
if (SHGetStockIconInfo(stockId, stockFlags, &iconInfo) == S_OK) {
const auto iconSize = pixmapSize.width();
HICON icon;
if (SHDefExtractIcon(iconInfo.szPath, iconInfo.iIcon, 0, &icon, nullptr, iconSize) == S_OK) {
QPixmap pixmap = qt_pixmapFromWinHICON(icon);
DestroyIcon(icon);
return pixmap;
if (!pixmap.isNull()) {
drawLinkOverlayIconIfNeeded(sp, pixmap, pixmap.size());
return pixmap;
}
}
}
}
@ -943,11 +959,7 @@ QPixmap QWindowsTheme::standardPixmap(StandardPixmap sp, const QSizeF &pixmapSiz
if (resourceId != -1) {
QPixmap pixmap = loadIconFromShell32(resourceId, pixmapSize);
if (!pixmap.isNull()) {
if (sp == FileLinkIcon || sp == DirLinkIcon || sp == DirLinkOpenIcon) {
QPainter painter(&pixmap);
QPixmap link = loadIconFromShell32(30, pixmapSize);
painter.drawPixmap(0, 0, int(pixmapSize.width()), int(pixmapSize.height()), link);
}
drawLinkOverlayIconIfNeeded(sp, pixmap, pixmapSize);
return pixmap;
}
}
@ -1186,9 +1198,11 @@ Qt::ColorScheme QWindowsTheme::queryColorScheme()
if (queryHighContrast())
return Qt::ColorScheme::Unknown;
const auto setting = QWinRegistryKey(HKEY_CURRENT_USER, LR"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)")
.dwordValue(L"AppsUseLightTheme");
return setting.second && setting.first == 0 ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light;
QWinRegistryKey personalizeKey{
HKEY_CURRENT_USER, LR"(Software\Microsoft\Windows\CurrentVersion\Themes\Personalize)"
};
const bool useDarkTheme = personalizeKey.value<DWORD>(L"AppsUseLightTheme") == 0;
return useDarkTheme ? Qt::ColorScheme::Dark : Qt::ColorScheme::Light;
}
bool QWindowsTheme::queryHighContrast()

View File

@ -1401,10 +1401,12 @@ void QWindowsForeignWindow::setParent(const QPlatformWindow *newParentWindow)
const HWND newParent = newParentWindow ? reinterpret_cast<HWND>(newParentWindow->winId()) : HWND(nullptr);
const bool isTopLevel = !newParent;
const DWORD oldStyle = style();
qCDebug(lcQpaWindow) << __FUNCTION__ << window() << "newParent="
<< newParentWindow << newParent << "oldStyle=" << debugWinStyle(oldStyle);
SetParent(m_hwnd, newParent);
if (wasTopLevel != isTopLevel) { // Top level window flags need to be set/cleared manually.
auto updateWindowFlags = [&]{
// Top level window flags need to be set/cleared manually.
DWORD newStyle = oldStyle;
if (isTopLevel) {
newStyle = m_topLevelStyle;
@ -1414,6 +1416,20 @@ void QWindowsForeignWindow::setParent(const QPlatformWindow *newParentWindow)
newStyle |= WS_CHILD;
}
SetWindowLongPtr(m_hwnd, GWL_STYLE, newStyle);
};
if (wasTopLevel && !isTopLevel) {
// Becoming a child window requires the style
// flags to be updated before reparenting.
updateWindowFlags();
}
SetParent(m_hwnd, newParent);
if (!wasTopLevel && isTopLevel) {
// Becoming a top level window requires the style
// flags to be updated after reparenting.
updateWindowFlags();
}
}
@ -2496,12 +2512,6 @@ QWindowsWindowData QWindowsWindow::setWindowFlags_sys(Qt::WindowFlags wt,
return result;
}
inline bool QWindowsBaseWindow::hasMaximumSize() const
{
const auto maximumSize = window()->maximumSize();
return maximumSize.width() != QWINDOWSIZE_MAX || maximumSize.height() != QWINDOWSIZE_MAX;
}
void QWindowsWindow::handleWindowStateChange(Qt::WindowStates state)
{
qCDebug(lcQpaWindow) << __FUNCTION__ << this << window()
@ -2518,20 +2528,7 @@ void QWindowsWindow::handleWindowStateChange(Qt::WindowStates state)
GetWindowPlacement(m_data.hwnd, &windowPlacement);
const RECT geometry = RECTfromQRect(m_data.restoreGeometry);
windowPlacement.rcNormalPosition = geometry;
// A bug in windows 10 grows
// - ptMaxPosition.x by the task bar's width, if it's on the left
// - ptMaxPosition.y by the task bar's height, if it's on the top
// each time GetWindowPlacement() is called.
// The offset of the screen's left edge (as per frameMargins_sys().left()) is ignored.
// => Check for windows 10 and correct.
static const auto windows11 = QOperatingSystemVersion::Windows11_21H2;
static const bool isWindows10 = QOperatingSystemVersion::current() < windows11;
if (isWindows10 && hasMaximumSize()) {
const QMargins margins = frameMargins_sys();
const QPoint topLeft = window()->screen()->geometry().topLeft();
windowPlacement.ptMaxPosition = POINT{ topLeft.x() - margins.left(), topLeft.y() };
}
correctWindowPlacement(windowPlacement);
// Even if the window is hidden, windowPlacement's showCmd is not SW_HIDE, so change it
// manually to avoid unhiding a hidden window with the subsequent call to
@ -2563,6 +2560,65 @@ void QWindowsWindow::handleWindowStateChange(Qt::WindowStates state)
}
}
// Apply corrections to window placement in Windows 10
// Related to task bar on top or left.
inline bool QWindowsBaseWindow::hasMaximumHeight() const
{
return window()->maximumHeight() != QWINDOWSIZE_MAX;
}
inline bool QWindowsBaseWindow::hasMaximumWidth() const
{
return window()->maximumWidth() != QWINDOWSIZE_MAX;
}
inline bool QWindowsBaseWindow::hasMaximumSize() const
{
return hasMaximumHeight() || hasMaximumWidth();
}
void QWindowsWindow::correctWindowPlacement(WINDOWPLACEMENT &windowPlacement)
{
static const auto windows11 = QOperatingSystemVersion::Windows11_21H2;
static const bool isWindows10 = QOperatingSystemVersion::current() < windows11;
if (!isWindows10)
return;
// Correct normal position by placement offset on Windows 10
// (where task bar can be on any side of the screen)
const QPoint offset = windowPlacementOffset(m_data.hwnd, m_data.restoreGeometry.topLeft());
windowPlacement.rcNormalPosition = RECTfromQRect(m_data.restoreGeometry.translated(-offset));
qCDebug(lcQpaWindow) << "Corrected normal position by" << -offset;
// A bug in windows 10 grows
// - ptMaxPosition.x by the task bar's width, if it's on the left
// - ptMaxPosition.y by the task bar's height, if it's on the top
// each time GetWindowPlacement() is called.
// The offset of the screen's left edge (as per frameMargins_sys().left()) is ignored.
// => Check for windows 10 and correct.
if (hasMaximumSize()) {
const QMargins margins = frameMargins_sys();
const QPoint topLeft = window()->screen()->geometry().topLeft();
windowPlacement.ptMaxPosition = POINT{ topLeft.x() - margins.left(), topLeft.y() };
qCDebug(lcQpaWindow) << "Window has maximum size. Corrected topLeft by"
<< -margins.left();
// If there is a placement offset correct width/height unless restricted,
// in order to fit window onto the screen.
if (offset.x() > 0 && !hasMaximumWidth()) {
const int adjust = offset.x() / window()->devicePixelRatio();
window()->setWidth(window()->width() - adjust);
qCDebug(lcQpaWindow) << "Width shortened by" << adjust << "logical pixels.";
}
if (offset.y() > 0 && !hasMaximumHeight()) {
const int adjust = offset.y() / window()->devicePixelRatio();
window()->setHeight(window()->height() - adjust);
qCDebug(lcQpaWindow) << "Height shortened by" << adjust << "logical pixels.";
}
}
}
void QWindowsWindow::updateRestoreGeometry()
{
m_data.restoreGeometry = normalFrameGeometry(m_data.hwnd);
@ -2707,8 +2763,24 @@ void QWindowsWindow::setWindowState_sys(Qt::WindowStates newState)
setFlag(WithinMaximize);
if (newState & Qt::WindowFullScreen)
setFlag(MaximizeToFullScreen);
ShowWindow(m_data.hwnd,
(newState & Qt::WindowMaximized) ? SW_MAXIMIZE : SW_SHOWNOACTIVATE);
if (m_data.flags & Qt::FramelessWindowHint) {
if (newState == Qt::WindowNoState) {
const QRect &rect = m_savedFrameGeometry;
MoveWindow(m_data.hwnd, rect.x(), rect.y(), rect.width(), rect.height(), true);
} else {
HMONITOR monitor = MonitorFromWindow(m_data.hwnd, MONITOR_DEFAULTTONEAREST);
MONITORINFO monitorInfo = {};
monitorInfo.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(monitor, &monitorInfo);
const RECT &rect = monitorInfo.rcWork;
m_savedFrameGeometry = geometry();
MoveWindow(m_data.hwnd, rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, true);
}
} else {
ShowWindow(m_data.hwnd,
(newState & Qt::WindowMaximized) ? SW_MAXIMIZE : SW_SHOWNOACTIVATE);
}
clearFlag(WithinMaximize);
clearFlag(MaximizeToFullScreen);
} else if (visible && (oldState & newState & Qt::WindowMinimized)) {

View File

@ -363,7 +363,7 @@ void QWindowsUiaMainProvider::fillVariantArrayForRelation(QAccessibleInterface*
{
Q_ASSERT(accessible);
typedef QPair<QAccessibleInterface*, QAccessible::Relation> RelationPair;
typedef std::pair<QAccessibleInterface*, QAccessible::Relation> RelationPair;
const QList<RelationPair> relationInterfaces = accessible->relations(relation);
if (relationInterfaces.empty())
return;

View File

@ -261,16 +261,13 @@ static BOOL GetDisplayAutoRotationPreferences(
static BOOL SetProcessDpiAwarenessContext(
IN DPI_AWARENESS_CONTEXT DpiContext)
{
switch ((ULONG_PTR)DpiContext) {
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_UNAWARE:
if ((ULONG_PTR)DpiContext == (ULONG_PTR)DPI_AWARENESS_CONTEXT_UNAWARE) {
//NOTHING;
break;
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_SYSTEM_AWARE:
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE:
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2:
} else if ((ULONG_PTR)DpiContext == (ULONG_PTR)DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ||
(ULONG_PTR)DpiContext == (ULONG_PTR)DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ||
(ULONG_PTR)DpiContext == (ULONG_PTR)DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) {
SetProcessDPIAware();
break;
default:
} else {
return FALSE;
}
@ -287,14 +284,13 @@ static BOOL AreDpiAwarenessContextsEqual(
static BOOL IsValidDpiAwarenessContext(
IN DPI_AWARENESS_CONTEXT Value)
{
switch ((ULONG_PTR)Value) {
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_UNAWARE:
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED:
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_SYSTEM_AWARE:
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE:
case (ULONG_PTR)DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2:
if ((ULONG_PTR)Value == (ULONG_PTR)DPI_AWARENESS_CONTEXT_UNAWARE ||
(ULONG_PTR)Value == (ULONG_PTR)DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED ||
(ULONG_PTR)Value == (ULONG_PTR)DPI_AWARENESS_CONTEXT_SYSTEM_AWARE ||
(ULONG_PTR)Value == (ULONG_PTR)DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE ||
(ULONG_PTR)Value == (ULONG_PTR)DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2) {
return TRUE;
default:
} else {
return FALSE;
}
}

View File

@ -59,7 +59,9 @@
#include <algorithm>
#if defined(Q_OS_WIN)
#include "../../plugins/platforms/windows/vxkex.h"
#endif
QT_BEGIN_NAMESPACE
@ -256,8 +258,10 @@ void QWindowsStyle::polish(QPalette &pal)
QCommonStyle::polish(pal);
}
#if defined(Q_OS_WIN)
typedef BOOL (WINAPI *GetSystemMetricsForDpiFunc)(int, UINT);
typedef BOOL (WINAPI *SystemParametersInfoForDpiFunc)(UINT, UINT, PVOID, UINT, UINT);
#endif
int QWindowsStylePrivate::pixelMetricFromSystemDp(QStyle::PixelMetric pm, const QStyleOption *, const QWidget *widget)
{