Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qwindowsintegration.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// Copyright (C) 2013 Samuel Gaist <samuel.gaist@edeltech.ch>
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
10#include "qwindowsmenu.h"
12
13#include "qwindowsscreen.h"
14#include "qwindowstheme.h"
16#include <QtGui/private/qtgui-config_p.h>
17#if QT_CONFIG(directwrite3)
18#include <QtGui/private/qwindowsdirectwritefontdatabase_p.h>
19#endif
20#ifndef QT_NO_FREETYPE
21# include <QtGui/private/qwindowsfontdatabase_ft_p.h>
22#endif
23#include <QtGui/private/qwindowsfontdatabase_p.h>
24#if QT_CONFIG(clipboard)
25# include "qwindowsclipboard.h"
26# if QT_CONFIG(draganddrop)
27# include "qwindowsdrag.h"
28# endif
29#endif
32#if QT_CONFIG(accessibility)
33# include "uiautomation/qwindowsuiaaccessibility.h"
34#endif
35
36#include <qpa/qplatformnativeinterface.h>
37#include <qpa/qwindowsysteminterface.h>
38#if QT_CONFIG(sessionmanager)
39# include "qwindowssessionmanager.h"
40#endif
41#include <QtGui/qpainter.h>
42#include <QtGui/qpen.h>
43#include <QtGui/qpointingdevice.h>
44#include <QtGui/private/qguiapplication_p.h>
45#include <QtGui/private/qhighdpiscaling_p.h>
46#include <QtGui/qpa/qplatforminputcontextfactory_p.h>
47#include <QtGui/qpa/qplatformcursor.h>
48
49#include <QtGui/private/qwindowsguieventdispatcher_p.h>
50
51#include <QtCore/qdebug.h>
52#include <QtCore/qvariant.h>
53
54#include <QtCore/qoperatingsystemversion.h>
55#include <QtCore/private/qfunctions_win_p.h>
56#include <QtCore/private/qcomptr_p.h>
57
58#include <limits.h>
59
60#if !defined(QT_NO_OPENGL)
62#endif
63
65
66#if QT_CONFIG(cpp_winrt)
67# include <QtCore/private/qt_winrtbase_p.h>
68# include <winrt/Windows.UI.Notifications.h>
69# include <winrt/Windows.Data.Xml.Dom.h>
70# include <winrt/Windows.Foundation.h>
71# include <winrt/Windows.UI.ViewManagement.h>
72#endif
73
74#include <memory>
75
76static inline void initOpenGlBlacklistResources()
77{
78 Q_INIT_RESOURCE(openglblacklists);
79}
80
81QT_BEGIN_NAMESPACE
82
83using namespace Qt::StringLiterals;
84
86{
88 explicit QWindowsIntegrationPrivate() = default;
90
91 void parseOptions(QWindowsIntegration *q, const QStringList &paramList);
92
93 unsigned m_options = 0;
96#if QT_CONFIG(clipboard)
98# if QT_CONFIG(draganddrop)
100# endif
101#endif
102#ifndef QT_NO_OPENGL
105#endif // QT_NO_OPENGL
107#if QT_CONFIG(accessibility)
109#endif
111};
112
113template <typename IntType>
114bool parseIntOption(const QString &parameter,const QLatin1StringView &option,
115 IntType minimumValue, IntType maximumValue, IntType *target)
116{
117 const int valueLength = parameter.size() - option.size() - 1;
118 if (valueLength < 1 || !parameter.startsWith(option) || parameter.at(option.size()) != u'=')
119 return false;
120 bool ok;
121 const auto valueRef = QStringView{parameter}.right(valueLength);
122 const int value = valueRef.toInt(&ok);
123 if (ok) {
124 if (value >= int(minimumValue) && value <= int(maximumValue))
125 *target = static_cast<IntType>(value);
126 else {
127 qWarning() << "Value" << value << "for option" << option << "out of range"
128 << minimumValue << ".." << maximumValue;
129 }
130 } else {
131 qWarning() << "Invalid value" << valueRef << "for option" << option;
132 }
133 return true;
134}
135
136using DarkModeHandlingFlag = QNativeInterface::Private::QWindowsApplication::DarkModeHandlingFlag;
137using DarkModeHandling = QNativeInterface::Private::QWindowsApplication::DarkModeHandling;
138
139static inline unsigned parseOptions(const QStringList &paramList,
140 int *tabletAbsoluteRange,
141 QtWindows::DpiAwareness *dpiAwareness,
142 DarkModeHandling *darkModeHandling)
143{
144 unsigned options = 0;
145 for (const QString &param : paramList) {
146 if (param.startsWith(u"fontengine=")) {
147 if (param.endsWith(u"gdi")) {
148 options |= QWindowsIntegration::FontDatabaseGDI;
149 } else if (param.endsWith(u"freetype")) {
150 options |= QWindowsIntegration::FontDatabaseFreeType;
151 } else if (param.endsWith(u"native")) {
152 options |= QWindowsIntegration::FontDatabaseNative;
153 }
154 } else if (param.startsWith(u"dialogs=")) {
155 if (param.endsWith(u"xp")) {
156 options |= QWindowsIntegration::XpNativeDialogs;
157 } else if (param.endsWith(u"none")) {
158 options |= QWindowsIntegration::NoNativeDialogs;
159 }
160 } else if (param == u"altgr") {
161 options |= QWindowsIntegration::DetectAltGrModifier;
162 } else if (param == u"gl=gdi") {
163 options |= QWindowsIntegration::DisableArb;
164 } else if (param == u"nodirectwrite") {
165 options |= QWindowsIntegration::DontUseDirectWriteFonts;
166 } else if (param == u"nocolorfonts") {
167 options |= QWindowsIntegration::DontUseColorFonts;
168 } else if (param == u"nomousefromtouch") {
169 options |= QWindowsIntegration::DontPassOsMouseEventsSynthesizedFromTouch;
170 } else if (parseIntOption(param, "verbose"_L1, 0, INT_MAX, &QWindowsContext::verbose)
171 || parseIntOption(param, "tabletabsoluterange"_L1, 0, INT_MAX, tabletAbsoluteRange)
172 || parseIntOption(param, "dpiawareness"_L1, QtWindows::DpiAwareness::Invalid,
173 QtWindows::DpiAwareness::PerMonitorVersion2, dpiAwareness)) {
174 } else if (param == u"menus=native") {
175 options |= QWindowsIntegration::AlwaysUseNativeMenus;
176 } else if (param == u"menus=none") {
177 options |= QWindowsIntegration::NoNativeMenus;
178 } else if (param == u"reverse") {
179 options |= QWindowsIntegration::RtlEnabled;
180 } else if (param == u"darkmode=0") {
181 *darkModeHandling = {};
182 } else if (param == u"darkmode=1") {
183 darkModeHandling->setFlag(DarkModeHandlingFlag::DarkModeWindowFrames);
184 darkModeHandling->setFlag(DarkModeHandlingFlag::DarkModeStyle, false);
185 } else if (param == u"darkmode=2") {
186 darkModeHandling->setFlag(DarkModeHandlingFlag::DarkModeWindowFrames);
187 darkModeHandling->setFlag(DarkModeHandlingFlag::DarkModeStyle);
188 } else {
189 qWarning() << "Unknown option" << param;
190 }
191 }
192 return options;
193}
194
195void QWindowsIntegrationPrivate::parseOptions(QWindowsIntegration *q, const QStringList &paramList)
196{
198
199 static bool dpiAwarenessSet = false;
200 // Default to per-monitor-v2 awareness (if available)
201 QtWindows::DpiAwareness dpiAwareness = QtWindows::DpiAwareness::PerMonitorVersion2;
202
203 int tabletAbsoluteRange = -1;
204 DarkModeHandling darkModeHandling = DarkModeHandlingFlag::DarkModeWindowFrames
205 | DarkModeHandlingFlag::DarkModeStyle;
206 m_options = ::parseOptions(paramList, &tabletAbsoluteRange, &dpiAwareness, &darkModeHandling);
207 q->setDarkModeHandling(darkModeHandling);
208 QWindowsFontDatabase::setFontOptions(m_options);
209 if (tabletAbsoluteRange >= 0)
211
212 QCoreApplication::setAttribute(Qt::AA_CompressHighFrequencyEvents);
213 QWindowSystemInterfacePrivate::TabletEvent::setPlatformSynthesizesMouse(false);
214
215 if (!dpiAwarenessSet) { // Set only once in case of repeated instantiations of QGuiApplication.
216 if (!QCoreApplication::testAttribute(Qt::AA_PluginApplication)) {
217 m_context.setProcessDpiAwareness(dpiAwareness);
218 qCDebug(lcQpaWindow) << "DpiAwareness=" << dpiAwareness
219 << "effective process DPI awareness=" << QWindowsContext::processDpiAwareness();
220 }
221 dpiAwarenessSet = true;
222 }
223
224 m_context.initTouch(m_options);
225 QPlatformCursor::setCapability(QPlatformCursor::OverrideCursor);
226
227 m_context.initPowerNotificationHandler();
228}
229
231{
232 delete m_fontDatabase;
233}
234
235QWindowsIntegration *QWindowsIntegration::m_instance = nullptr;
236
237QWindowsIntegration::QWindowsIntegration(const QStringList &paramList) :
239{
240 m_instance = this;
241 d->parseOptions(this, paramList);
242#if QT_CONFIG(clipboard)
243 d->m_clipboard.registerViewer();
244#endif
245 d->m_context.screenManager().initialize();
246 d->m_context.setDetectAltGrModifier((d->m_options & DetectAltGrModifier) != 0);
247}
248
250{
251 m_instance = nullptr;
252}
253
255{
256 auto icStrs = QPlatformInputContextFactory::requested();
257 icStrs.isEmpty() ? d->m_inputContext.reset(new QWindowsInputContext)
258 : d->m_inputContext.reset(QPlatformInputContextFactory::create(icStrs));
259}
260
261bool QWindowsIntegration::hasCapability(QPlatformIntegration::Capability cap) const
262{
263 switch (cap) {
264 case ThreadedPixmaps:
265 return true;
266#ifndef QT_NO_OPENGL
267 case OpenGL:
268#if !QT_CONFIG(run_opengl_tests)
269 // Workaround for build configs on WoA that don't have OpenGL installed
270 // FIXME: Detect at runtime
271 return false;
272#endif
273 return true;
274 case ThreadedOpenGL:
276 return glContext->supportsThreadedOpenGL();
277 return false;
278#endif // !QT_NO_OPENGL
279 case WindowMasks:
280 return true;
281 case MultipleWindows:
282 return true;
283 case ForeignWindows:
284 return true;
285 case ChildWindows:
286 return true;
287 case AllGLFunctionsQueryable:
288 return true;
289 case SwitchableWidgetComposition:
290 return false; // QTBUG-68329 QTBUG-53515 QTBUG-54734
291 case BackingStoreStaticContents:
292 return true;
293 case MouseCursorPositioning:
294 return true;
295 default:
296 return QPlatformIntegration::hasCapability(cap);
297 }
298 return false;
299}
300
301QPlatformWindow *QWindowsIntegration::createPlatformWindow(QWindow *window) const
302{
303 QWindowsWindowData requested;
304 requested.flags = window->flags();
305 requested.geometry = window->isTopLevel()
306 ? QHighDpi::toNativePixels(window->geometry(), window)
307 : QHighDpi::toNativeLocalPosition(window->geometry(), window);
308 if (!(requested.flags & Qt::FramelessWindowHint)) {
309 // Apply custom margins (see QWindowsWindow::setCustomMargins())).
310 const QVariant customMarginsV = window->property("_q_windowsCustomMargins");
311 if (customMarginsV.isValid())
312 requested.customMargins = qvariant_cast<QMargins>(customMarginsV);
313 }
314
315 QWindowsWindowData obtained =
316 QWindowsWindowData::create(window, requested,
317 QWindowsWindow::formatWindowTitle(window->title()));
318 qCDebug(lcQpaWindow).nospace()
319 << __FUNCTION__ << ' ' << window
320 << "\n Requested: " << requested.geometry << " frame incl.="
321 << QWindowsGeometryHint::positionIncludesFrame(window)
322 << ' ' << requested.flags
323 << "\n Obtained : " << obtained.geometry << " margins=" << obtained.fullFrameMargins
324 << " handle=" << obtained.hwnd << ' ' << obtained.flags << '\n';
325
326 if (Q_UNLIKELY(!obtained.hwnd))
327 return nullptr;
328
329 QWindowsWindow *result = createPlatformWindowHelper(window, obtained);
330 Q_ASSERT(result);
331
332 if (window->isTopLevel() && !QWindowsContext::shouldHaveNonClientDpiScaling(window))
334
335 if (QWindowsMenuBar *menuBarToBeInstalled = QWindowsMenuBar::menuBarOf(window))
336 menuBarToBeInstalled->install(result);
337
338 return result;
339}
340
341QPlatformWindow *QWindowsIntegration::createForeignWindow(QWindow *window, WId nativeHandle) const
342{
343 const HWND hwnd = reinterpret_cast<HWND>(nativeHandle);
344 if (!IsWindow(hwnd)) {
345 qWarning("Windows QPA: Invalid foreign window ID %p.", hwnd);
346 return nullptr;
347 }
348 auto *result = new QWindowsForeignWindow(window, hwnd);
349 const QRect obtainedGeometry = result->geometry();
350 QScreen *screen = nullptr;
351 if (const QPlatformScreen *pScreen = result->screenForGeometry(obtainedGeometry))
352 screen = pScreen->screen();
353 if (screen && screen != window->screen())
354 window->setScreen(screen);
355 qCDebug(lcQpaWindow) << "Foreign window:" << window << Qt::showbase << Qt::hex
356 << result->winId() << Qt::noshowbase << Qt::dec << obtainedGeometry << screen;
357 return result;
358}
359
360// Overridden to return a QWindowsDirect2DWindow in Direct2D plugin.
361QWindowsWindow *QWindowsIntegration::createPlatformWindowHelper(QWindow *window, const QWindowsWindowData &data) const
362{
363 return new QWindowsWindow(window, data);
364}
365
366#ifndef QT_NO_OPENGL
367
369{
370#if defined(QT_OPENGL_DYNAMIC)
371 QWindowsOpenGLTester::Renderer requestedRenderer = QWindowsOpenGLTester::requestedRenderer();
372 switch (requestedRenderer) {
373 case QWindowsOpenGLTester::DesktopGl:
374 if (QWindowsStaticOpenGLContext *glCtx = QOpenGLStaticContext::create()) {
375 if ((QWindowsOpenGLTester::supportedRenderers(requestedRenderer) & QWindowsOpenGLTester::DisableRotationFlag)
376 && !QWindowsScreen::setOrientationPreference(Qt::LandscapeOrientation)) {
377 qCWarning(lcQpaGl, "Unable to disable rotation.");
378 }
379 return glCtx;
380 }
381 qCWarning(lcQpaGl, "System OpenGL failed. Falling back to Software OpenGL.");
382 return QOpenGLStaticContext::create(true);
383 case QWindowsOpenGLTester::SoftwareRasterizer:
384 if (QWindowsStaticOpenGLContext *swCtx = QOpenGLStaticContext::create(true))
385 return swCtx;
386 qCWarning(lcQpaGl, "Software OpenGL failed. Falling back to system OpenGL.");
387 if (QWindowsOpenGLTester::supportedRenderers(requestedRenderer) & QWindowsOpenGLTester::DesktopGl)
388 return QOpenGLStaticContext::create();
389 return nullptr;
390 default:
391 break;
392 }
393
394 const QWindowsOpenGLTester::Renderers supportedRenderers = QWindowsOpenGLTester::supportedRenderers(requestedRenderer);
395 if (supportedRenderers.testFlag(QWindowsOpenGLTester::DisableProgramCacheFlag)
396 && !QCoreApplication::testAttribute(Qt::AA_DisableShaderDiskCache)) {
397 QCoreApplication::setAttribute(Qt::AA_DisableShaderDiskCache);
398 }
399 if (supportedRenderers & QWindowsOpenGLTester::DesktopGl) {
400 if (QWindowsStaticOpenGLContext *glCtx = QOpenGLStaticContext::create()) {
401 if ((supportedRenderers & QWindowsOpenGLTester::DisableRotationFlag)
402 && !QWindowsScreen::setOrientationPreference(Qt::LandscapeOrientation)) {
403 qCWarning(lcQpaGl, "Unable to disable rotation.");
404 }
405 return glCtx;
406 }
407 }
408 return QOpenGLStaticContext::create(true);
409#else
411#endif
412}
413
418
420{
421 qCDebug(lcQpaGl) << __FUNCTION__ << context->format();
423 std::unique_ptr<QWindowsOpenGLContext> result(staticOpenGLContext->createContext(context));
424 if (result->isValid())
425 return result.release();
426 }
427 return nullptr;
428}
429
431{
432#if !defined(QT_OPENGL_DYNAMIC)
433 return QOpenGLContext::LibGL;
434#else
435 if (const QWindowsStaticOpenGLContext *staticOpenGLContext = QWindowsIntegration::staticOpenGLContext())
436 return staticOpenGLContext->moduleType();
437 return QOpenGLContext::LibGL;
438#endif
439}
440
442{
444 return static_cast<HMODULE>(staticOpenGLContext->moduleHandle());
445
446 return nullptr;
447}
448
449QOpenGLContext *QWindowsIntegration::createOpenGLContext(HGLRC ctx, HWND window, QOpenGLContext *shareContext) const
450{
451 if (!ctx || !window)
452 return nullptr;
453
455 std::unique_ptr<QWindowsOpenGLContext> result(staticOpenGLContext->createContext(ctx, window));
456 if (result->isValid()) {
457 auto *context = new QOpenGLContext;
458 context->setShareContext(shareContext);
459 auto *contextPrivate = QOpenGLContextPrivate::get(context);
460 contextPrivate->adopt(result.release());
461 return context;
462 }
463 }
464
465 return nullptr;
466}
467
469{
471 if (!integration)
472 return nullptr;
473 QWindowsIntegrationPrivate *d = integration->d.data();
474 QMutexLocker lock(&d->m_staticContextLock);
475 if (d->m_staticOpenGLContext.isNull())
476 d->m_staticOpenGLContext.reset(QWindowsStaticOpenGLContext::create());
477 return d->m_staticOpenGLContext.data();
478}
479#endif // !QT_NO_OPENGL
480
482{
483 if (!d->m_fontDatabase) {
484#ifndef QT_NO_FREETYPE
485 if (d->m_options & QWindowsIntegration::FontDatabaseFreeType)
486 d->m_fontDatabase = new QWindowsFontDatabaseFT;
487 else
488#endif // QT_NO_FREETYPE
489#if QT_CONFIG(directwrite3)
490 if (!(d->m_options & (QWindowsIntegration::FontDatabaseGDI | QWindowsIntegration::DontUseDirectWriteFonts)))
491 d->m_fontDatabase = new QWindowsDirectWriteFontDatabase;
492 else
493#endif
494 d->m_fontDatabase = new QWindowsFontDatabase;
495 }
496 return d->m_fontDatabase;
497}
498
499#ifdef SPI_GETKEYBOARDSPEED
500static inline int keyBoardAutoRepeatRateMS()
501{
502 DWORD time = 0;
503 if (SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &time, 0))
504 return time ? 1000 / static_cast<int>(time) : 500;
505 return 30;
506}
507#endif
508
509QVariant QWindowsIntegration::styleHint(QPlatformIntegration::StyleHint hint) const
510{
511 switch (hint) {
512 case QPlatformIntegration::CursorFlashTime:
513 if (const unsigned timeMS = GetCaretBlinkTime())
514 return QVariant(timeMS != INFINITE ? int(timeMS) * 2 : 0);
515 break;
516#ifdef SPI_GETKEYBOARDSPEED
517 case KeyboardAutoRepeatRate:
518 return QVariant(keyBoardAutoRepeatRateMS());
519#endif
520 case QPlatformIntegration::ShowIsMaximized:
521 case QPlatformIntegration::StartDragTime:
522 case QPlatformIntegration::StartDragDistance:
523 case QPlatformIntegration::KeyboardInputInterval:
524 case QPlatformIntegration::ShowIsFullScreen:
525 case QPlatformIntegration::PasswordMaskDelay:
526 case QPlatformIntegration::StartDragVelocity:
527 break; // Not implemented
528 case QPlatformIntegration::FontSmoothingGamma:
529 return QVariant(QWindowsFontDatabase::fontSmoothingGamma());
530 case QPlatformIntegration::MouseDoubleClickInterval:
531 if (const UINT ms = GetDoubleClickTime())
532 return QVariant(int(ms));
533 break;
534 case QPlatformIntegration::UseRtlExtensions:
535 return QVariant(d->m_context.useRTLExtensions());
536 default:
537 break;
538 }
539 return QPlatformIntegration::styleHint(hint);
540}
541
542QPlatformKeyMapper *QWindowsIntegration::keyMapper() const
543{
544 return d->m_context.keyMapper();
545}
546
547#if QT_CONFIG(clipboard)
548QPlatformClipboard * QWindowsIntegration::clipboard() const
549{
550 return &d->m_clipboard;
551}
552# if QT_CONFIG(draganddrop)
553QPlatformDrag *QWindowsIntegration::drag() const
554{
555 return &d->m_drag;
556}
557# endif // QT_CONFIG(draganddrop)
558#endif // !QT_NO_CLIPBOARD
559
561{
562 return d->m_inputContext.data();
563}
564
565#if QT_CONFIG(accessibility)
566QPlatformAccessibility *QWindowsIntegration::accessibility() const
567{
568 return &d->m_accessibility;
569}
570#endif
571
573{
574 return d->m_options;
575}
576
577#if QT_CONFIG(sessionmanager)
578QPlatformSessionManager *QWindowsIntegration::createPlatformSessionManager(const QString &id, const QString &key) const
579{
580 return new QWindowsSessionManager(id, key);
581}
582#endif
583
585{
586 return new QWindowsGuiEventDispatcher;
587}
588
590{
591 return QStringList(QLatin1StringView(QWindowsTheme::name));
592}
593
595{
596 if (name == QLatin1StringView(QWindowsTheme::name))
597 return new QWindowsTheme;
598 return QPlatformIntegration::createPlatformTheme(name);
599}
600
602{
603 if (d->m_services.isNull())
604 d->m_services.reset(new QWindowsServices);
605
606 return d->m_services.data();
607}
608
610{
611 MessageBeep(MB_OK); // For QApplication
612}
613
615{
616 // Clamp to positive numbers, as the Windows API doesn't support negative numbers
617 number = qMax(0, number);
618
619 // Persist, so we can re-apply it on setting changes and Explorer restart
620 m_applicationBadgeNumber = number;
621
622 static const bool isWindows11 = QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows11;
623
624#if QT_CONFIG(cpp_winrt)
625 // We prefer the native BadgeUpdater API, that allows us to set a number directly,
626 // but it requires that the application has a package identity, and also doesn't
627 // seem to work in all cases on < Windows 11.
628 QT_TRY {
629 if (isWindows11 && qt_win_hasPackageIdentity()) {
630 using namespace winrt::Windows::UI::Notifications;
631 auto badgeXml = BadgeUpdateManager::GetTemplateContent(BadgeTemplateType::BadgeNumber);
632 badgeXml.SelectSingleNode(L"//badge/@value").NodeValue(winrt::box_value(winrt::to_hstring(number)));
633 BadgeUpdateManager::CreateBadgeUpdaterForApplication().Update(BadgeNotification(badgeXml));
634 return;
635 }
636 } QT_CATCH(...) {
637 // fall back to win32 implementation
638 }
639#endif
640
641 // Fallback for non-packaged apps, Windows 10, or Qt builds without WinRT/C++ support
642
643 if (!number) {
644 // Clear badge
645 setApplicationBadge(QImage());
646 return;
647 }
648
649 const bool isDarkMode = QWindowsTheme::instance()->colorScheme()
650 == Qt::ColorScheme::Dark;
651
652 QColor badgeColor;
653 QColor textColor;
654
655#if QT_CONFIG(cpp_winrt)
656 if (isWindows11) {
657 // Match colors used by BadgeUpdater
658 static const auto fromUIColor = [](winrt::Windows::UI::Color &&color) {
659 return QColor(color.R, color.G, color.B, color.A);
660 };
661 using namespace winrt::Windows::UI::ViewManagement;
662 const auto settings = UISettings();
663 badgeColor = fromUIColor(settings.GetColorValue(isDarkMode ?
664 UIColorType::AccentLight2 : UIColorType::Accent));
665 textColor = fromUIColor(settings.GetColorValue(UIColorType::Background));
666 }
667#endif
668
669 if (!badgeColor.isValid()) {
670 // Fall back to basic badge colors, based on Windows 10 look
671 badgeColor = isDarkMode ? Qt::black : QColor(220, 220, 220);
672 badgeColor.setAlphaF(0.5f);
673 textColor = isDarkMode ? Qt::white : Qt::black;
674 }
675
676 const auto devicePixelRatio = qApp->devicePixelRatio();
677
678 static const QSize iconBaseSize(16, 16);
679 QImage image(iconBaseSize * devicePixelRatio,
680 QImage::Format_ARGB32_Premultiplied);
681 image.fill(Qt::transparent);
682
683 QPainter painter(&image);
684
685 QRect badgeRect = image.rect();
686 QPen badgeBorderPen = Qt::NoPen;
687 if (!isWindows11) {
688 QColor badgeBorderColor = textColor;
689 badgeBorderColor.setAlphaF(0.5f);
690 badgeBorderPen = badgeBorderColor;
691 badgeRect.adjust(1, 1, -1, -1);
692 }
693 painter.setBrush(badgeColor);
694 painter.setPen(badgeBorderPen);
695 painter.setRenderHint(QPainter::Antialiasing);
696 painter.drawEllipse(badgeRect);
697
698 auto pixelSize = qCeil(10.5 * devicePixelRatio);
699 // Unlike the BadgeUpdater API we're limited by a square
700 // badge, so adjust the font size when above two digits.
701 const bool textOverflow = number > 99;
702 if (textOverflow)
703 pixelSize *= 0.8;
704
705 QFont font = painter.font();
706 font.setPixelSize(pixelSize);
707 font.setWeight(isWindows11 ? QFont::Medium : QFont::DemiBold);
708 painter.setFont(font);
709
710 painter.setRenderHint(QPainter::TextAntialiasing, devicePixelRatio > 1);
711 painter.setPen(textColor);
712
713 auto text = textOverflow ? u"99+"_s : QString::number(number);
714 painter.translate(textOverflow ? 1 : 0, textOverflow ? 0 : -1);
715 painter.drawText(image.rect(), Qt::AlignCenter, text);
716
717 painter.end();
718
719 setApplicationBadge(image);
720}
721
722void QWindowsIntegration::setApplicationBadge(const QImage &image)
723{
724 QComHelper comHelper;
725
726 ComPtr<ITaskbarList3> taskbarList;
727 CoCreateInstance(CLSID_TaskbarList, nullptr,
728 CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbarList));
729 if (!taskbarList) {
730 // There may not be any windows with a task bar button yet,
731 // in which case we'll apply the badge once a window with
732 // a button has been created.
733 return;
734 }
735
736 const auto hIcon = image.toHICON();
737
738 // Apply the icon to all top level windows, since the badge is
739 // set on an application level. If one of the windows go away
740 // the other windows will take over in showing the badge.
741 const auto topLevelWindows = QGuiApplication::topLevelWindows();
742 for (auto *topLevelWindow : topLevelWindows) {
743 if (!topLevelWindow->handle())
744 continue;
745 auto hwnd = reinterpret_cast<HWND>(topLevelWindow->winId());
746 taskbarList->SetOverlayIcon(hwnd, hIcon, L"");
747 }
748
749 DestroyIcon(hIcon);
750
751 // FIXME: Update icon when the application scale factor changes.
752 // Doing so in response to screen DPI changes is too soon, as the
753 // task bar is not yet ready for an updated icon, and will just
754 // result in a blurred icon even if our icon is high-DPI.
755}
756
758{
759 // The system color settings have changed, or we are reacting
760 // to a task bar button being created for the fist time or after
761 // Explorer had crashed and re-started. In any case, re-apply the
762 // badge so that everything is up to date.
763 if (m_applicationBadgeNumber)
764 setApplicationBadge(m_applicationBadgeNumber);
765}
766
767#if QT_CONFIG(vulkan)
768QPlatformVulkanInstance *QWindowsIntegration::createPlatformVulkanInstance(QVulkanInstance *instance) const
769{
770 return new QWindowsVulkanInstance(instance);
771}
772#endif
773
774QT_END_NAMESPACE
Static Open GL context containing version information, extension function pointers,...
static QOpenGLStaticContext * create(bool softwareRendering=false)
Singleton container for all relevant information.
static void setTabletAbsoluteRange(int a)
Window wrapping a foreign native window.
QStringList themeNames() const override
QPlatformKeyMapper * keyMapper() const override
Accessor for the platform integration's key mapper.
static QWindowsStaticOpenGLContext * staticOpenGLContext()
void setApplicationBadge(const QImage &image)
QOpenGLContext * createOpenGLContext(HGLRC context, HWND window, QOpenGLContext *shareContext) const override
QWindowsIntegration(const QStringList &paramList)
QAbstractEventDispatcher * createEventDispatcher() const override
Factory function for the GUI event dispatcher.
QPlatformTheme * createPlatformTheme(const QString &name) const override
bool hasCapability(QPlatformIntegration::Capability cap) const override
QOpenGLContext::OpenGLModuleType openGLModuleType() override
Platform integration function for querying the OpenGL implementation type.
QPlatformFontDatabase * fontDatabase() const override
Accessor for the platform integration's fontdatabase.
void initialize() override
Performs initialization steps that depend on having an event dispatcher available.
void setApplicationBadge(qint64 number) override
static QWindowsIntegration * instance()
HMODULE openGLModuleHandle() const override
void beep() const override
QPlatformInputContext * inputContext() const override
Returns the platforms input context.
QPlatformServices * services() const override
QVariant styleHint(StyleHint hint) const override
QPlatformOpenGLContext * createPlatformOpenGLContext(QOpenGLContext *context) const override
Factory function for QPlatformOpenGLContext.
Windows native menu bar.
void install(QWindowsWindow *window)
virtual void * moduleHandle() const =0
virtual bool supportsThreadedOpenGL() const
static const char * name
static QWindowsTheme * instance()
Raster or OpenGL Window.
void setFlag(unsigned f) const
static void initOpenGlBlacklistResources()
bool parseIntOption(const QString &parameter, const QLatin1StringView &option, IntType minimumValue, IntType maximumValue, IntType *target)
static unsigned parseOptions(const QStringList &paramList, int *tabletAbsoluteRange, QtWindows::DpiAwareness *dpiAwareness, DarkModeHandling *darkModeHandling)
QWindowsIntegrationPrivate()=default
QScopedPointer< QWindowsStaticOpenGLContext > m_staticOpenGLContext
void parseOptions(QWindowsIntegration *q, const QStringList &paramList)
QScopedPointer< QWindowsServices > m_services
QPlatformFontDatabase * m_fontDatabase
QScopedPointer< QPlatformInputContext > m_inputContext