summaryrefslogtreecommitdiffstats
path: root/src/plugins/platforms/windows/qwindowsopengltester.cpp
blob: 63ecbfe0eaa5b03990d1c5ddd0dbeb53f59829c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qwindowsopengltester.h"
#include "qwindowscontext.h"

#include <QtCore/qvariant.h>
#include <QtCore/qdebug.h>
#include <QtCore/qtextstream.h>
#include <QtCore/qcoreapplication.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qstandardpaths.h>
#include <QtCore/qlibrary.h>
#include <QtCore/qlibraryinfo.h>
#include <QtCore/qhash.h>

#ifndef QT_NO_OPENGL
#include <private/qopengl_p.h>
#endif

#include <QtCore/qt_windows.h>
#include <private/qsystemlibrary_p.h>
#include <d3d9.h>
#include <d3d10.h>
#include <dxgi.h>

QT_BEGIN_NAMESPACE

static const DWORD VENDOR_ID_AMD = 0x1002;

static GpuDescription adapterIdentifierToGpuDescription(const D3DADAPTER_IDENTIFIER9 &adapterIdentifier)
{
    GpuDescription result;
    result.vendorId = adapterIdentifier.VendorId;
    result.deviceId = adapterIdentifier.DeviceId;
    result.revision = adapterIdentifier.Revision;
    result.subSysId = adapterIdentifier.SubSysId;
    QVector<int> version(4, 0);
    version[0] = HIWORD(adapterIdentifier.DriverVersion.HighPart); // Product
    version[1] = LOWORD(adapterIdentifier.DriverVersion.HighPart); // Version
    version[2] = HIWORD(adapterIdentifier.DriverVersion.LowPart); // Sub version
    version[3] = LOWORD(adapterIdentifier.DriverVersion.LowPart); // build
    result.driverVersion = QVersionNumber(version);
    result.driverName = adapterIdentifier.Driver;
    result.description = adapterIdentifier.Description;
    return result;
}

class QGraphicsAdapterInfo
{
public:
    Q_DISABLE_COPY_MOVE(QGraphicsAdapterInfo)

    QGraphicsAdapterInfo();
    ~QGraphicsAdapterInfo();

    bool isValid() const;

    UINT adapterCount() const;
    bool retrieveAdapterIdentifier(UINT n, D3DADAPTER_IDENTIFIER9 *adapterIdentifier) const;

private:
    QSystemLibrary m_dxgilib;
    IDXGIFactory1 *m_dxgiFactory1 = nullptr;

    QSystemLibrary m_d3d9lib;
    IDirect3D9 *m_direct3D9 = nullptr;

    /* This is a value from the DXGI_ADAPTER_FLAG enum.
     * However, it's not available in dxgi.h from MinGW,
     * so define it here in any case. */
    enum { DXGI_ADAPTER_FLAG_SOFTWARE = 2 };

    UINT adapterCountDXGI() const;
    bool retrieveAdapterIdentifierDXGI(UINT n, D3DADAPTER_IDENTIFIER9 *adapterIdentifier) const;

    UINT adapterCountD3D9() const;
    bool retrieveAdapterIdentifierD3D9(UINT n, D3DADAPTER_IDENTIFIER9 *adapterIdentifier) const;
};

QGraphicsAdapterInfo::QGraphicsAdapterInfo() :
    m_dxgilib(QStringLiteral("dxgi")),
    m_d3d9lib(QStringLiteral("d3d9"))
{
    using PtrCreateDXGIFactory1 = HRESULT (WINAPI *)(REFIID, void**);

    if (m_dxgilib.load()) {
        if (auto createDXGIFactory1 = (PtrCreateDXGIFactory1)m_dxgilib.resolve("CreateDXGIFactory1"))
            createDXGIFactory1(IID_PPV_ARGS(&m_dxgiFactory1));
    }

    if (!m_dxgiFactory1) {
        using PtrDirect3DCreate9 = IDirect3D9 *(WINAPI *)(UINT);

        if (m_d3d9lib.load()) {
            if (auto direct3DCreate9 = (PtrDirect3DCreate9)m_d3d9lib.resolve("Direct3DCreate9"))
                m_direct3D9 = direct3DCreate9(D3D_SDK_VERSION);
        }
    }
}

QGraphicsAdapterInfo::~QGraphicsAdapterInfo()
{
    if (m_dxgiFactory1)
       m_dxgiFactory1->Release();
    if (m_direct3D9)
       m_direct3D9->Release();
}

bool QGraphicsAdapterInfo::isValid() const
{
    return m_dxgiFactory1 != nullptr || m_direct3D9 != nullptr;
}

UINT QGraphicsAdapterInfo::adapterCount() const
{
    if (m_dxgiFactory1)
        return adapterCountDXGI();
    if (m_direct3D9)
        return adapterCountD3D9();
    return 0;
}

bool QGraphicsAdapterInfo::retrieveAdapterIdentifier(UINT n, D3DADAPTER_IDENTIFIER9 *adapterIdentifier) const
{
    if (m_dxgiFactory1)
        return retrieveAdapterIdentifierDXGI(n, adapterIdentifier);
    if (m_direct3D9)
        return retrieveAdapterIdentifierD3D9(n, adapterIdentifier);
    return false;
}

UINT QGraphicsAdapterInfo::adapterCountDXGI() const
{
    /* DXGI doesn't have an adapterCount(), instead we have to call EnumAdapters1()
     * until DXGI_ERROR_NOT_FOUND is returned. */
    UINT n = 0;

    IDXGIAdapter1 *adapter;
    while (SUCCEEDED(m_dxgiFactory1->EnumAdapters1(n, &adapter))) {
        adapter->Release();
        ++n;
    }

    return n;
}

// Detect whether we are running under 64-bit Windows.
static bool isWow64Process()
{
    typedef BOOL (WINAPI *IsWow64ProcessPtr)(HANDLE hProcess, PBOOL Wow64Process);
    IsWow64ProcessPtr IsWow64Process = (IsWow64ProcessPtr)QLibrary::resolve(
                QStringLiteral("kernel32.dll"), "IsWow64Process");

    if (IsWow64Process) {
        BOOL IsWow64 = FALSE;
        if (IsWow64Process(GetCurrentProcess(), &IsWow64))
            return IsWow64;
    }
    return false;
}

// Read a string value from registry
static QString regGetString(HKEY key, const wchar_t* valueName)
{
    QVarLengthArray<wchar_t, MAX_PATH> buf (MAX_PATH);
    LRESULT res;
    DWORD bufSize = buf.size() * sizeof(wchar_t);
    res = RegGetValue(key, nullptr, valueName,
                      RRF_RT_REG_SZ | RRF_RT_REG_MULTI_SZ, nullptr,
                      buf.data(), &bufSize);
    if (res == ERROR_MORE_DATA) {
        buf.resize(bufSize / sizeof(wchar_t));
        bufSize = buf.size() * sizeof(wchar_t);
        res = RegGetValue(key, nullptr, valueName,
                        RRF_RT_REG_SZ | RRF_RT_REG_MULTI_SZ, nullptr,
                        buf.data(), &bufSize);
    }
    /* In case of REG_MULTI_SZ, this returns just the first string,
     * but that is sufficient for our purposes. */
    if (res == ERROR_SUCCESS)
        return QString::fromWCharArray(buf.data());
    return QString();
}

// Read driver name given a DeviceKey
static QString retrieveDriverName(const wchar_t *driverKey)
{
    /* Kernel-style prefix, maps to HKLM
     * (see https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/registry-key-object-routines) */
    static const wchar_t prefixMappingHKLM[] = L"\\Registry\\Machine\\";
    const size_t prefixMappingHKLMLen = wcslen(prefixMappingHKLM);
    if (wcsnicmp(driverKey, prefixMappingHKLM, prefixMappingHKLMLen) != 0)
        return QString();

    driverKey += prefixMappingHKLMLen;
    QString driverPath;
    HKEY key;
    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, driverKey, 0, KEY_READ | KEY_WOW64_64KEY, &key) == ERROR_SUCCESS) {
        const wchar_t *valueName =
                isWow64Process() ? L"UserModeDriverNameWow" : L"UserModeDriverName";
        driverPath = regGetString(key, valueName);
        RegCloseKey(key);
    }
    if (!driverPath.isEmpty()) {
        int fileNameSep = driverPath.lastIndexOf(QLatin1Char('\\'));
        if (fileNameSep >= 0)
            driverPath = driverPath.mid(fileNameSep + 1);
        return driverPath;
    }
    return QString();
}

// Retrieve driver name for a display device from registry.
static QString driverNameForDevice(const wchar_t *displayDevice)
{
    QString driverName;
    DISPLAY_DEVICE dd;
    memset(&dd, 0, sizeof(dd));
    dd.cb = sizeof(dd);
    for (int dev = 0; EnumDisplayDevices(nullptr, dev, &dd, 0); ++dev) {
        if (wcsicmp(displayDevice, dd.DeviceName) == 0) {
            // DeviceKey is documented as "internal", but it's a registry key in kernel format
            driverName = retrieveDriverName(dd.DeviceKey);
            break;
        }
    }
    if (driverName.isEmpty()) {
        /* Fall back to driver name from EnumDisplaySettings.
         * This is only a fallback as on Windows 10 this just returns an device-independent
         * name. OTOH, it's possible to recognize RDP connections from the driver name. */
        DEVMODE devMode;
        if (EnumDisplaySettings(displayDevice, ENUM_CURRENT_SETTINGS, &devMode))
            driverName = QString::fromWCharArray(devMode.dmDeviceName);
    }
    return driverName;
}

bool QGraphicsAdapterInfo::retrieveAdapterIdentifierDXGI(UINT n, D3DADAPTER_IDENTIFIER9 *adapterIdentifier) const
{
    IDXGIAdapter1 *adapter;
    if (FAILED(m_dxgiFactory1->EnumAdapters1(n, &adapter)))
        return false;

    bool result = false;

    DXGI_ADAPTER_DESC1 adapterDesc;
    if (SUCCEEDED(adapter->GetDesc1(&adapterDesc))) {
        if ((adapterDesc.VendorId != 0) && (adapterDesc.DeviceId != 0) // Don't use adapter description of Software Devices
            && ((adapterDesc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) == 0)) {
            memset(adapterIdentifier, 0, sizeof(*adapterIdentifier));
            WideCharToMultiByte(1252, 0, adapterDesc.Description, -1,
                                adapterIdentifier->Description,
                                sizeof(adapterIdentifier->Description), nullptr, nullptr);
            adapterIdentifier->Description[sizeof(adapterIdentifier->Description) - 1] = 0;
            adapterIdentifier->VendorId = adapterDesc.VendorId;
            adapterIdentifier->DeviceId = adapterDesc.DeviceId;
            adapterIdentifier->SubSysId = adapterDesc.SubSysId;
            adapterIdentifier->Revision = adapterDesc.Revision;

            LARGE_INTEGER umdVersion;
            if (SUCCEEDED(adapter->CheckInterfaceSupport(__uuidof(ID3D10Device), &umdVersion))) {
                adapterIdentifier->DriverVersion = umdVersion;
                result = true;
            }

            /* DXGI doesn't expose the driver name, but we can get it from the registry.
             * But we need a device name to follow. */
            IDXGIOutput *output = nullptr;
            if (SUCCEEDED(adapter->EnumOutputs (0, &output))) {
                DXGI_OUTPUT_DESC outputDesc;
                if (SUCCEEDED(output->GetDesc (&outputDesc))) {
                    QString driverName = driverNameForDevice(outputDesc.DeviceName);
                    qstrncpy(adapterIdentifier->Driver, driverName.toLatin1().constData(),
                             sizeof(adapterIdentifier->Driver));
                }
                output->Release();
            }
        }
    }

    adapter->Release();

    return result;
}

UINT QGraphicsAdapterInfo::adapterCountD3D9() const
{
    return m_direct3D9->GetAdapterCount();
}

bool QGraphicsAdapterInfo::retrieveAdapterIdentifierD3D9(UINT n, D3DADAPTER_IDENTIFIER9 *adapterIdentifier) const
{
    return SUCCEEDED(m_direct3D9->GetAdapterIdentifier(n, 0, adapterIdentifier));
}

GpuDescription GpuDescription::detect()
{
    GpuDescription result;
    QGraphicsAdapterInfo adapterInfo;
    if (!adapterInfo.isValid())
        return result;

    D3DADAPTER_IDENTIFIER9 adapterIdentifier;
    bool isAMD = false;
    // Adapter "0" is D3DADAPTER_DEFAULT which returns the default adapter. In
    // multi-GPU, multi-screen setups this is the GPU that is associated with
    // the "main display" in the Display Settings, and this is the GPU OpenGL
    // and D3D uses by default. Therefore querying any additional adapters is
    // futile and not useful for our purposes in general, except for
    // identifying a few special cases later on.
    if (adapterInfo.retrieveAdapterIdentifier(0, &adapterIdentifier)) {
        result = adapterIdentifierToGpuDescription(adapterIdentifier);
        isAMD = result.vendorId == VENDOR_ID_AMD;
    }

    // Detect QTBUG-50371 (having AMD as the default adapter results in a crash
    // when starting apps on a screen connected to the Intel card) by looking
    // for a default AMD adapter and an additional non-AMD one.
    if (isAMD) {
        const UINT adapterCount = adapterInfo.adapterCount();
        for (UINT adp = 1; adp < adapterCount; ++adp) {
            if (adapterInfo.retrieveAdapterIdentifier(adp, &adapterIdentifier)
                && adapterIdentifier.VendorId != VENDOR_ID_AMD) {
                // Bingo. Now figure out the display for the AMD card.
                DISPLAY_DEVICE dd;
                memset(&dd, 0, sizeof(dd));
                dd.cb = sizeof(dd);
                for (int dev = 0; EnumDisplayDevices(nullptr, dev, &dd, 0); ++dev) {
                    if (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) {
                        // DeviceName is something like \\.\DISPLAY1 which can be used to
                        // match with the MONITORINFOEX::szDevice queried by QWindowsScreen.
                        result.gpuSuitableScreen = QString::fromWCharArray(dd.DeviceName);
                        break;
                    }
                }
                break;
            }
        }
    }

    return result;
}

QVector<GpuDescription> GpuDescription::detectAll()
{
    QVector<GpuDescription> result;
    QGraphicsAdapterInfo adapterInfo;
    if (const UINT adapterCount = adapterInfo.adapterCount()) {
        for (UINT adp = 0; adp < adapterCount; ++adp) {
            D3DADAPTER_IDENTIFIER9 adapterIdentifier;
            if (adapterInfo.retrieveAdapterIdentifier(adp, &adapterIdentifier))
                result.append(adapterIdentifierToGpuDescription(adapterIdentifier));
        }
    }
    return result;
}

#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug d, const GpuDescription &gd)
{
    QDebugStateSaver s(d);
    d.nospace();
    d << Qt::hex << Qt::showbase << "GpuDescription(vendorId=" << gd.vendorId
      << ", deviceId=" << gd.deviceId << ", subSysId=" << gd.subSysId
      << Qt::dec << Qt::noshowbase << ", revision=" << gd.revision
      << ", driver: " << gd.driverName
      << ", version=" << gd.driverVersion << ", " << gd.description
      << gd.gpuSuitableScreen << ')';
    return d;
}
#endif // !QT_NO_DEBUG_STREAM

// Return printable string formatted like the output of the dxdiag tool.
QString GpuDescription::toString() const
{
    QString result;
    QTextStream str(&result);
    str <<   "         Card name         : " << description
        << "\n       Driver Name         : " << driverName
        << "\n    Driver Version         : " << driverVersion.toString()
        << "\n         Vendor ID         : 0x" << qSetPadChar(QLatin1Char('0'))
        << Qt::uppercasedigits << Qt::hex << qSetFieldWidth(4) << vendorId
        << "\n         Device ID         : 0x" << qSetFieldWidth(4) << deviceId
        << "\n         SubSys ID         : 0x" << qSetFieldWidth(8) << subSysId
        << "\n       Revision ID         : 0x" << qSetFieldWidth(4) << revision
        << Qt::dec;
    if (!gpuSuitableScreen.isEmpty())
        str << "\nGL windows forced to screen: " << gpuSuitableScreen;
    return result;
}

QVariant GpuDescription::toVariant() const
{
    QVariantMap result;
    result.insert(QStringLiteral("vendorId"), QVariant(vendorId));
    result.insert(QStringLiteral("deviceId"), QVariant(deviceId));
    result.insert(QStringLiteral("subSysId"),QVariant(subSysId));
    result.insert(QStringLiteral("revision"), QVariant(revision));
    result.insert(QStringLiteral("driver"), QVariant(QLatin1String(driverName)));
    result.insert(QStringLiteral("driverProduct"), QVariant(driverVersion.segmentAt(0)));
    result.insert(QStringLiteral("driverVersion"), QVariant(driverVersion.segmentAt(1)));
    result.insert(QStringLiteral("driverSubVersion"), QVariant(driverVersion.segmentAt(2)));
    result.insert(QStringLiteral("driverBuild"), QVariant(driverVersion.segmentAt(3)));
    result.insert(QStringLiteral("driverVersionString"), driverVersion.toString());
    result.insert(QStringLiteral("description"), QVariant(QLatin1String(description)));
    result.insert(QStringLiteral("printable"), QVariant(toString()));
    return result;
}

QWindowsOpenGLTester::Renderer QWindowsOpenGLTester::requestedGlesRenderer()
{
    const char platformVar[] = "QT_ANGLE_PLATFORM";
    if (qEnvironmentVariableIsSet(platformVar)) {
        const QByteArray anglePlatform = qgetenv(platformVar);
        if (anglePlatform == "d3d11")
            return QWindowsOpenGLTester::AngleRendererD3d11;
        if (anglePlatform == "d3d9")
            return QWindowsOpenGLTester::AngleRendererD3d9;
        if (anglePlatform == "warp")
            return QWindowsOpenGLTester::AngleRendererD3d11Warp;
        qCWarning(lcQpaGl) << "Invalid value set for " << platformVar << ": " << anglePlatform;
    }
    return QWindowsOpenGLTester::InvalidRenderer;
}

QWindowsOpenGLTester::Renderer QWindowsOpenGLTester::requestedRenderer()
{
    const char openGlVar[] = "QT_OPENGL";
    if (QCoreApplication::testAttribute(Qt::AA_UseOpenGLES)) {
        const Renderer glesRenderer = QWindowsOpenGLTester::requestedGlesRenderer();
        return glesRenderer != InvalidRenderer ? glesRenderer : Gles;
    }
    if (QCoreApplication::testAttribute(Qt::AA_UseDesktopOpenGL))
        return QWindowsOpenGLTester::DesktopGl;
    if (QCoreApplication::testAttribute(Qt::AA_UseSoftwareOpenGL))
        return QWindowsOpenGLTester::SoftwareRasterizer;
    if (qEnvironmentVariableIsSet(openGlVar)) {
        const QByteArray requested = qgetenv(openGlVar);
        if (requested == "angle") {
            const Renderer glesRenderer = QWindowsOpenGLTester::requestedGlesRenderer();
            return glesRenderer != InvalidRenderer ? glesRenderer : Gles;
        }
        if (requested == "desktop")
            return QWindowsOpenGLTester::DesktopGl;
        if (requested == "software")
            return QWindowsOpenGLTester::SoftwareRasterizer;
        qCWarning(lcQpaGl) << "Invalid value set for " << openGlVar << ": " << requested;
    }
    return QWindowsOpenGLTester::InvalidRenderer;
}

static inline QString resolveBugListFile(const QString &fileName)
{
    if (QFileInfo(fileName).isAbsolute())
        return fileName;
    // Try QLibraryInfo::SettingsPath which is typically empty unless specified in qt.conf,
    // then resolve via QStandardPaths::ConfigLocation.
    const QString settingsPath = QLibraryInfo::location(QLibraryInfo::SettingsPath);
    if (!settingsPath.isEmpty()) { // SettingsPath is empty unless specified in qt.conf.
        const QFileInfo fi(settingsPath + QLatin1Char('/') + fileName);
        if (fi.isFile())
            return fi.absoluteFilePath();
    }
    return QStandardPaths::locate(QStandardPaths::ConfigLocation, fileName);
}

#ifndef QT_NO_OPENGL
typedef QHash<QOpenGLConfig::Gpu, QWindowsOpenGLTester::Renderers> SupportedRenderersCache;
Q_GLOBAL_STATIC(SupportedRenderersCache, supportedRenderersCache)
#endif

QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::detectSupportedRenderers(const GpuDescription &gpu,
                                                                               Renderer requested)
{
#if defined(QT_NO_OPENGL)
    Q_UNUSED(gpu)
    Q_UNUSED(requested)
    return 0;
#else
    QOpenGLConfig::Gpu qgpu = QOpenGLConfig::Gpu::fromDevice(gpu.vendorId, gpu.deviceId, gpu.driverVersion, gpu.description);
    SupportedRenderersCache *srCache = supportedRenderersCache();
    SupportedRenderersCache::const_iterator it = srCache->constFind(qgpu);
    if (it != srCache->cend())
        return *it;

    QWindowsOpenGLTester::Renderers result(QWindowsOpenGLTester::AngleRendererD3d11
        | QWindowsOpenGLTester::AngleRendererD3d9
        | QWindowsOpenGLTester::AngleRendererD3d11Warp
        | QWindowsOpenGLTester::SoftwareRasterizer);

    // Don't test for GL if explicitly requested or GLES only is requested
    if (requested == DesktopGl
        || ((requested & GlesMask) == 0 && testDesktopGL())) {
            result |= QWindowsOpenGLTester::DesktopGl;
    }

    const char bugListFileVar[] = "QT_OPENGL_BUGLIST";
    QString buglistFileName = QStringLiteral(":/qt-project.org/windows/openglblacklists/default.json");

    if (qEnvironmentVariableIsSet(bugListFileVar)) {
        const QString fileName = resolveBugListFile(QFile::decodeName(qgetenv(bugListFileVar)));
        if (!fileName.isEmpty())
            buglistFileName = fileName;
    }

    QSet<QString> features = QOpenGLConfig::gpuFeatures(qgpu, buglistFileName);
    qCDebug(lcQpaGl) << "GPU features:" << features;

    if (features.contains(QStringLiteral("disable_desktopgl"))) { // Qt-specific
        qCDebug(lcQpaGl) << "Disabling Desktop GL: " << gpu;
        result &= ~QWindowsOpenGLTester::DesktopGl;
    }
    if (features.contains(QStringLiteral("disable_angle"))) { // Qt-specific keyword
        qCDebug(lcQpaGl) << "Disabling ANGLE: " << gpu;
        result &= ~QWindowsOpenGLTester::GlesMask;
    } else {
        if (features.contains(QStringLiteral("disable_d3d11"))) { // standard keyword
            qCDebug(lcQpaGl) << "Disabling D3D11: " << gpu;
            result &= ~QWindowsOpenGLTester::AngleRendererD3d11;
        }
        if (features.contains(QStringLiteral("disable_d3d9"))) { // Qt-specific
            qCDebug(lcQpaGl) << "Disabling D3D9: " << gpu;
            result &= ~QWindowsOpenGLTester::AngleRendererD3d9;
        }
    }
    if (features.contains(QStringLiteral("disable_rotation"))) {
        qCDebug(lcQpaGl) << "Disabling rotation: " << gpu;
        result |= DisableRotationFlag;
    }
    if (features.contains(QStringLiteral("disable_program_cache"))) {
        qCDebug(lcQpaGl) << "Disabling program cache: " << gpu;
        result |= DisableProgramCacheFlag;
    }
    srCache->insert(qgpu, result);
    return result;
#endif // !QT_NO_OPENGL
}

QWindowsOpenGLTester::Renderers QWindowsOpenGLTester::supportedRenderers(Renderer requested)
{
    const GpuDescription gpu = GpuDescription::detect();
    const QWindowsOpenGLTester::Renderers result = detectSupportedRenderers(gpu, requested);
    qCDebug(lcQpaGl) << __FUNCTION__ << gpu << requested << "renderer: " << result;
    return result;
}

bool QWindowsOpenGLTester::testDesktopGL()
{
#if !defined(QT_NO_OPENGL)
    typedef HGLRC (WINAPI *CreateContextType)(HDC);
    typedef BOOL (WINAPI *DeleteContextType)(HGLRC);
    typedef BOOL (WINAPI *MakeCurrentType)(HDC, HGLRC);
    typedef PROC (WINAPI *WglGetProcAddressType)(LPCSTR);

    HMODULE lib = nullptr;
    HWND wnd = nullptr;
    HDC dc = nullptr;
    HGLRC context = nullptr;
    LPCTSTR className = L"qtopengltest";

    CreateContextType CreateContext = nullptr;
    DeleteContextType DeleteContext = nullptr;
    MakeCurrentType MakeCurrent = nullptr;
    WglGetProcAddressType WGL_GetProcAddress = nullptr;

    bool result = false;

    // Test #1: Load opengl32.dll and try to resolve an OpenGL 2 function.
    // This will typically fail on systems that do not have a real OpenGL driver.
    lib = LoadLibraryA("opengl32.dll");
    if (lib) {
        CreateContext = reinterpret_cast<CreateContextType>(
            reinterpret_cast<QFunctionPointer>(::GetProcAddress(lib, "wglCreateContext")));
        if (!CreateContext)
            goto cleanup;
        DeleteContext = reinterpret_cast<DeleteContextType>(
            reinterpret_cast<QFunctionPointer>(::GetProcAddress(lib, "wglDeleteContext")));
        if (!DeleteContext)
            goto cleanup;
        MakeCurrent = reinterpret_cast<MakeCurrentType>(
            reinterpret_cast<QFunctionPointer>(::GetProcAddress(lib, "wglMakeCurrent")));
        if (!MakeCurrent)
            goto cleanup;
        WGL_GetProcAddress = reinterpret_cast<WglGetProcAddressType>(
            reinterpret_cast<QFunctionPointer>(::GetProcAddress(lib, "wglGetProcAddress")));
        if (!WGL_GetProcAddress)
            goto cleanup;

        WNDCLASS wclass;
        wclass.cbClsExtra = 0;
        wclass.cbWndExtra = 0;
        wclass.hInstance = static_cast<HINSTANCE>(GetModuleHandle(nullptr));
        wclass.hIcon = nullptr;
        wclass.hCursor = nullptr;
        wclass.hbrBackground = HBRUSH(COLOR_BACKGROUND);
        wclass.lpszMenuName = nullptr;
        wclass.lpfnWndProc = DefWindowProc;
        wclass.lpszClassName = className;
        wclass.style = CS_OWNDC;
        if (!RegisterClass(&wclass))
            goto cleanup;
        wnd = CreateWindow(className, L"qtopenglproxytest", WS_OVERLAPPED,
                           0, 0, 640, 480, nullptr, nullptr, wclass.hInstance, nullptr);
        if (!wnd)
            goto cleanup;
        dc = GetDC(wnd);
        if (!dc)
            goto cleanup;

        PIXELFORMATDESCRIPTOR pfd;
        memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
        pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
        pfd.nVersion = 1;
        pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_GENERIC_FORMAT;
        pfd.iPixelType = PFD_TYPE_RGBA;
        // Use the GDI functions. Under the hood this will call the wgl variants in opengl32.dll.
        int pixelFormat = ChoosePixelFormat(dc, &pfd);
        if (!pixelFormat)
            goto cleanup;
        if (!SetPixelFormat(dc, pixelFormat, &pfd))
            goto cleanup;
        context = CreateContext(dc);
        if (!context)
            goto cleanup;
        if (!MakeCurrent(dc, context))
            goto cleanup;

        // Now that there is finally a context current, try doing something useful.

        // Check the version. If we got 1.x then it's all hopeless and we can stop right here.
        typedef const GLubyte * (APIENTRY * GetString_t)(GLenum name);
        auto GetString = reinterpret_cast<GetString_t>(
            reinterpret_cast<QFunctionPointer>(::GetProcAddress(lib, "glGetString")));
        if (GetString) {
            if (const char *versionStr = reinterpret_cast<const char *>(GetString(GL_VERSION))) {
                const QByteArray version(versionStr);
                const int majorDot = version.indexOf('.');
                if (majorDot != -1) {
                    int minorDot = version.indexOf('.', majorDot + 1);
                    if (minorDot == -1)
                        minorDot = version.size();
                    const int major = version.mid(0, majorDot).toInt();
                    const int minor = version.mid(majorDot + 1, minorDot - majorDot - 1).toInt();
                    qCDebug(lcQpaGl, "Basic wglCreateContext gives version %d.%d", major, minor);
                    // Try to be as lenient as possible. Missing version, bogus values and
                    // such are all accepted. The driver may still be functional. Only
                    // check for known-bad cases, like versions "1.4.0 ...".
                    if (major == 1) {
                        result = false;
                        qCDebug(lcQpaGl, "OpenGL version too low");
                    }
                }
            }
        } else {
            result = false;
            qCDebug(lcQpaGl, "OpenGL 1.x entry points not found");
        }

        // Check for a shader-specific function.
        if (WGL_GetProcAddress("glCreateShader")) {
            result = true;
            qCDebug(lcQpaGl, "OpenGL 2.0 entry points available");
        } else {
            qCDebug(lcQpaGl, "OpenGL 2.0 entry points not found");
        }
    } else {
        qCDebug(lcQpaGl, "Failed to load opengl32.dll");
    }

cleanup:
    if (MakeCurrent)
        MakeCurrent(nullptr, nullptr);
    if (context)
        DeleteContext(context);
    if (dc && wnd)
        ReleaseDC(wnd, dc);
    if (wnd) {
        DestroyWindow(wnd);
        UnregisterClass(className, GetModuleHandle(nullptr));
    }
    // No FreeLibrary. Some implementations, Mesa in particular, deadlock when trying to unload.

    return result;
#else
    return false;
#endif // !QT_NO_OPENGL
}

QT_END_NAMESPACE