aboutsummaryrefslogtreecommitdiffstats
path: root/LibOVR/Src/Displays/OVR_Win32_Display.cpp
blob: 6ddf030bbefabe2d68b3273fd66078c5e27431c6 (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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
/************************************************************************************

Filename    :   OVR_Win32_Display.cpp
Content     :   Win32 Display implementation
Created     :   May 6, 2014
Authors     :   Dean Beeler

Copyright   :   Copyright 2014 Oculus VR, LLC All Rights reserved.

Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); 
you may not use the Oculus VR Rift SDK except in compliance with the License, 
which is provided at the time of installation or download, or which 
otherwise accompanies this software in either electronic or hard copy form.

You may obtain a copy of the License at

http://www.oculusvr.com/licenses/LICENSE-3.2 

Unless required by applicable law or agreed to in writing, the Oculus VR SDK 
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*************************************************************************************/

#include <Windows.h>

#include "OVR_Win32_Display.h"
#include "OVR_Win32_Dxgi_Display.h"

#include <stdio.h>
#include <tchar.h>
#include <string.h>
#include <stdlib.h>
#include <winioctl.h>
#include <SetupAPI.h>
#include <Mmsystem.h>
#include <conio.h>

#ifdef OVR_COMPAT_EDID_VIA_WMI
# pragma comment(lib, "wbemuuid.lib")
#include <wbemidl.h>
#else // OVR_COMPAT_EDID_VIA_WMI
#include <setupapi.h>
#include <initguid.h>
#endif // OVR_COMPAT_EDID_VIA_WMI

// WIN32_LEAN_AND_MEAN included in OVR_Atomic.h may break 'byte' declaration.
#ifdef WIN32_LEAN_AND_MEAN
 typedef unsigned char byte;
#endif

#include "../Kernel/OVR_String.h"
#include "../Kernel/OVR_Log.h"

typedef struct
{
	HANDLE	hDevice;
	UINT	ExpectedWidth;
	UINT	ExpectedHeight;
	HWND	hWindow;
	bool	CompatibilityMode;
    bool    HideDK1Mode;
} ContextStruct;

static ContextStruct GlobalDisplayContext = {0};

 
//-------------------------------------------------------------------------------------
// ***** Display enumeration Helpers

// THere are two ways to enumerate display: through our driver (DeviceIoControl)
// and through Win32 EnumDisplayMonitors (compatibility mode).


namespace OVR { 

ULONG getRiftCount( HANDLE hDevice )
{
	ULONG riftCount = 0;
	DWORD bytesReturned = 0;

	BOOL result = DeviceIoControl( hDevice, IOCTL_RIFTMGR_GET_RIFT_COUNT, NULL, 0,
                                   &riftCount, sizeof( ULONG ), &bytesReturned, NULL );

	if( result )
		return riftCount;
	else
		return 0;
}

ULONG getRift( HANDLE hDevice, int index )
{
	ULONG riftCount = getRiftCount( hDevice );
	DWORD bytesReturned = 0;
	BOOL result;

	if( riftCount >= (ULONG)index )
	{
		RIFT_STATUS riftStatus[16] = {0};

		result = DeviceIoControl( hDevice, IOCTL_RIFTMGR_GET_RIFT_ARRAY, riftStatus,
                                  riftCount * sizeof( RIFT_STATUS ), &riftCount,
                                  sizeof( ULONG ), &bytesReturned, NULL );
		if( result )
		{
			PRIFT_STATUS tmpRift;
			unsigned int i;
			for( i = 0, tmpRift = riftStatus; i < riftCount; ++i, ++tmpRift )
			{
				if( i == (unsigned int)index )
					return tmpRift->childUid;
			}
		}
		else
		{
			printf("Failed to get array of rift devices\n");
		}
	}

	return 0;
}

#define EDID_LENGTH                             0x80

#define EDID_HEADER                             0x00
#define EDID_HEADER_END                         0x07

#define ID_MANUFACTURER_NAME                    0x08
#define ID_MANUFACTURER_NAME_END                0x09

#define EDID_STRUCT_VERSION                     0x12
#define EDID_STRUCT_REVISION                    0x13

#define ESTABLISHED_TIMING_1                    0x23
#define ESTABLISHED_TIMING_2                    0x24
#define MANUFACTURERS_TIMINGS                   0x25

#define DETAILED_TIMING_DESCRIPTIONS_START      0x36
#define DETAILED_TIMING_DESCRIPTION_SIZE        18
#define NO_DETAILED_TIMING_DESCRIPTIONS         4

#define DETAILED_TIMING_DESCRIPTION_1           0x36
#define DETAILED_TIMING_DESCRIPTION_2           0x48
#define DETAILED_TIMING_DESCRIPTION_3           0x5a
#define DETAILED_TIMING_DESCRIPTION_4           0x6c

#define MONITOR_NAME            0xfc
#define MONITOR_LIMITS          0xfd
#define MONITOR_SERIAL			0xff

#define UNKNOWN_DESCRIPTOR      -1
#define DETAILED_TIMING_BLOCK   -2

#define DESCRIPTOR_DATA         5

const byte edid_v1_header[] = { 0x00, 0xff, 0xff, 0xff,
	                            0xff, 0xff, 0xff, 0x00 };

const byte edid_v1_descriptor_flag[] = { 0x00, 0x00 };


static int blockType( byte* block )
{
	if ( !strncmp( (const char*)edid_v1_descriptor_flag, (const char*)block, 2 ) )
	{
		// descriptor
		if ( block[ 2 ] != 0 )
			return UNKNOWN_DESCRIPTOR;
		return block[ 3 ];
	}
    else
    {		
		return DETAILED_TIMING_BLOCK;
	}
}

static char* getMonitorName( byte const* block )
{
	static char name[ 13 ];
	unsigned    i;
	byte const* ptr = block + DESCRIPTOR_DATA;

	for( i = 0; i < 13; i++, ptr++ )
	{
		if ( *ptr == 0xa )
		{
			name[ i ] = 0;
			return name;
		}

		name[ i ] = *ptr;
	}

	return name;
}


static bool parseEdid( byte* edid, OVR::Win32::DisplayEDID& edidResult )
{
	unsigned i;
	byte* block;
	char* monitor_name = "Unknown";
	byte checksum = 0;

	for( i = 0; i < EDID_LENGTH; i++ )
		checksum += edid[ i ];

	// Bad checksum, fail EDID
	if (  checksum != 0  )
		return false;

	if ( strncmp( (const char*)edid+EDID_HEADER, (const char*)edid_v1_header, EDID_HEADER_END+1 ) )
	{
		// First bytes don't match EDID version 1 header
		return false;
	}

	//printf( "\n# EDID version %d revision %d\n", (int)edid[EDID_STRUCT_VERSION],(int)edid[EDID_STRUCT_REVISION] );

	// Monitor name and timings 

	char serialNumber[14];
	memset( serialNumber, 0, 14 );

	block = edid + DETAILED_TIMING_DESCRIPTIONS_START;

	for( i = 0; i < NO_DETAILED_TIMING_DESCRIPTIONS; i++,
		block += DETAILED_TIMING_DESCRIPTION_SIZE )
	{

		if ( blockType( block ) == MONITOR_NAME )
		{
			monitor_name = getMonitorName( block );
		}

		if( blockType( block ) == MONITOR_SERIAL )
		{
			memcpy( serialNumber, block + 5, 13 );
			break;
		}
	}

	BYTE vendorString[4] = {0};

	vendorString[0] = (edid[8] >> 2 & 31) + 64;
	vendorString[1] = ((edid[8] & 3) << 3) | (edid[9] >> 5) + 64;
	vendorString[2] = (edid[9] & 31) + 64;

	edidResult.ModelNumber  = *(UINT16*)&edid[10];
	edidResult.MonitorName  = OVR::String(monitor_name);
	edidResult.VendorName   = OVR::String((const char*)vendorString);
	edidResult.SerialNumber = OVR::String(serialNumber);
	
#if 0
	printf( "\tIdentifier \"%s\"\n", monitor_name );
	printf( "\tVendorName \"%s\"\n", vendorString );
	printf( "\tModelName \"%s\"\n", monitor_name );
	printf( "\tModelNumber %d\n", modelNumber );
	printf( "\tSerialNumber \"%x\"\n", *serialPointer );
#endif

	// FIXME: Get timings as well, though they aren't very useful here
	// except for the vertical refresh rate, presumably

	return true;
}

static bool getEdid(HANDLE hDevice, ULONG uid, OVR::Win32::DisplayEDID& edidResult)
{
	ULONG       riftCount = 0;
	DWORD       bytesReturned = 0;
	RIFT_STATUS riftStatus[16] = {0};

	BOOL result = DeviceIoControl( hDevice, IOCTL_RIFTMGR_GET_RIFT_COUNT, NULL, 0,
                                   &riftCount, sizeof( ULONG ), &bytesReturned, NULL );

    if (!result)
    {
        return false;
    }

	result = DeviceIoControl( hDevice, IOCTL_RIFTMGR_GET_RIFT_ARRAY, &riftStatus,
                              riftCount * sizeof( RIFT_STATUS ), &riftCount, sizeof(ULONG),
                              &bytesReturned, NULL );
    if (!result)
    {
        return false;
    }

    for (ULONG i = 0; i < riftCount; ++i)
    {
		ULONG riftUid = riftStatus[i].childUid;
        if (riftUid == uid)
        {
            char edidBuffer[512];

            result = DeviceIoControl(hDevice, IOCTL_RIFTMGR_GETEDID, &riftUid, sizeof(ULONG),
                                     edidBuffer, 512, &bytesReturned, NULL);

            if (result)
            {
                if (parseEdid((byte*)edidBuffer, edidResult))
                {
                    return true;
                }
                else
                {
                    OVR_DEBUG_LOG(("[Win32Display] WARNING: The driver was not able to return EDID for a display"));
                }
            }

            break;
        }
	}

    return false;
}


// Used to capture all the active monitor handles
struct MonitorSet
{
    enum { MaxMonitors = 8 };
    HMONITOR Monitors[MaxMonitors];
    int      MonitorCount;
    int      PrimaryCount;
};

static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData)
{
	MonitorSet* monitorSet = (MonitorSet*)dwData;
	if (monitorSet->MonitorCount >= MonitorSet::MaxMonitors)
		return FALSE;

	monitorSet->Monitors[monitorSet->MonitorCount] = hMonitor;
	monitorSet->MonitorCount++;
	return TRUE;
};

#ifdef OVR_COMPAT_EDID_VIA_WMI

static bool getCompatDisplayEDID( WCHAR* displayName, String& serialNumberStr, String& userFriendlyNameStr )
{
	IWbemLocator *pLoc = NULL;
	IWbemServices *pSvc = NULL;
	HRESULT hres;

	static bool initialized = false;
	static bool selfInitialized = true;
	if (!initialized)
	{
		hres = CoInitializeEx(0, COINIT_MULTITHREADED);
		if (FAILED(hres))
		{
            
            LogError("{ERR-082} [Display] WARNING: Failed to initialize COM library. Error code = 0x%x", hres);
            OVR_ASSERT(false);
            return false;
		}

		hres = CoInitializeSecurity(
			NULL,
			-1,                          // COM authentication
			NULL,                        // Authentication services
			NULL,                        // Reserved
			RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
			RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
			NULL,                        // Authentication info
			EOAC_NONE,                   // Additional capabilities 
			NULL                         // Reserved
			);

		if (FAILED(hres))
		{
            LogError("{ERR-083} [Display] WARNING: Failed to initialize security. Error code = 0x%x", hres);
            OVR_ASSERT(false);
            selfInitialized = false;
		}

		initialized = true;
	}

	hres = CoCreateInstance(
		CLSID_WbemLocator,
		0,
		CLSCTX_INPROC_SERVER,
		IID_IWbemLocator, (LPVOID *)&pLoc);

	if (FAILED(hres))
	{
        LogError("{ERR-084} [Display] WARNING: Failed to create IWbemLocator object.Err code = 0x%x", hres);
        OVR_ASSERT(false);
        return false;
	}

	BSTR AbackB = SysAllocString(L"root\\WMI");
	// Connect to the root\cimv2 namespace with
	// the current user and obtain pointer pSvc
	// to make IWbemServices calls.
	hres = pLoc->ConnectServer(
		AbackB, // Object path of WMI namespace
		NULL,                    // User name. NULL = current user
		NULL,                    // User password. NULL = current
		0,                       // Locale. NULL indicates current
		NULL,                    // Security flags.
		0,                       // Authority (e.g. Kerberos)
		0,                       // Context object 
		&pSvc                    // pointer to IWbemServices proxy
		);
	SysFreeString(AbackB);

	if (FAILED(hres))
	{
        LogError("{ERR-085} [Display] WARNING: Could not connect to root\\WMI. Error code = 0x%x", hres);
        OVR_ASSERT(false);
        pLoc->Release();
		return false;
	}

	hres = CoSetProxyBlanket(
		pSvc,                        // Indicates the proxy to set
		RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
		RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
		NULL,                        // Server principal name 
		RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
		RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
		NULL,                        // client identity
		EOAC_NONE                    // proxy capabilities 
		);

	if (FAILED(hres))
	{
        LogError("{ERR-086} [Display] WARNING: Could not set proxy blanket. Error code = 0x%x", hres);
        OVR_ASSERT(false);
        pSvc->Release();
		pLoc->Release();
		return false;
	}


	BSTR wql = SysAllocString(L"WQL");
	BSTR select = SysAllocString(L"SELECT * FROM WmiMonitorID");
	IEnumWbemClassObject* pEnumerator = NULL;
	hres = pSvc->ExecQuery(
		wql,
		select,
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		&pEnumerator);
	SysFreeString(wql);
	SysFreeString(select);

	if (FAILED(hres))
	{
        LogError("{ERR-087} [Display] WARNING: Query for operating system name failed. Error code = 0x%x", hres);
        OVR_ASSERT(false);
        pSvc->Release();
		pLoc->Release();
		return false;
	}

    int enumeratedCount = 0;
    bool found = false;

	IWbemClassObject *pclsObj = 0;
	while (pEnumerator)
	{
        ULONG uReturn = 0;
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

        if (FAILED(hr) || !uReturn)
        {
            break;
        }

        ++enumeratedCount;

		VARIANT vtProp;
		hr = pclsObj->Get(L"InstanceName", 0, &vtProp, 0, 0);

		WCHAR* instanceName = vtProp.bstrVal;
		WCHAR* nextToken = NULL;
		if (SUCCEEDED(hr) &&
            wcstok_s(instanceName, L"\\", &nextToken) != NULL)
		{
			WCHAR* aToken = wcstok_s(NULL, L"\\", &nextToken);

			if (aToken != NULL)
			{
				VariantClear(&vtProp);

				if (wcscmp(aToken, displayName) != 0)
				{
                    pclsObj->Release();
                    continue;
				}

				// Read serial

				hr = pclsObj->Get(L"SerialNumberID", 0, &vtProp, 0, 0);

                if (SUCCEEDED(hr))
                {
                    if (vtProp.vt != VT_NULL && vtProp.parray != NULL)
                    {
                        static const int MaxSerialBytes = 14;
                        char serialNumber[MaxSerialBytes] = { 0 };

                        UINT32* serialArray = (UINT32*)vtProp.parray->pvData;
                        for (int i = 0; i < MaxSerialBytes; ++i)
                        {
                            serialNumber[i] = (BYTE)(serialArray[i] & 0xff);
                        }

                        serialNumber[sizeof(serialNumber)-1] = '\0';
                        serialNumberStr = serialNumber;
                    }
                    else
                    {
                        LogError("{ERR-088} [Display] WARNING: Wrong data format for SerialNumberID");
                    }

                    VariantClear(&vtProp);
                }
                else
                {
                    LogError("{ERR-089} [Display] WARNING: Failure getting display SerialNumberID: %d", (int)hr);
                }

				// Read length of name

                int userFriendlyNameLen = 0;

				hr = pclsObj->Get(L"UserFriendlyNameLength", 0, &vtProp, 0, 0);

                if (SUCCEEDED(hr))
                {
                    if (vtProp.vt != VT_NULL)
                    {
                        userFriendlyNameLen = vtProp.iVal;

                        if (userFriendlyNameLen <= 0)
                        {
                            userFriendlyNameLen = 0;

                            LogError("{ERR-090} [Display] WARNING: UserFriendlyNameLength = 0");
                        }
                    }
                    else
                    {
                        LogError("{ERR-091} [Display] WARNING: Wrong data format for UserFriendlyNameLength");
                    }

                    VariantClear(&vtProp);
                }
                else
                {
                    LogError("{ERR-092} [Display] WARNING: Failure getting display UserFriendlyNameLength: %d", (int)hr);
                }

				// Read name

				hr = pclsObj->Get(L"UserFriendlyName", 0, &vtProp, 0, 0);

                if (SUCCEEDED(hr) && userFriendlyNameLen > 0)
                {
                    if (vtProp.vt != VT_NULL && vtProp.parray != NULL)
                    {
                        static const int MaxNameBytes = 64;
                        char userFriendlyName[MaxNameBytes] = { 0 };

                        UINT32* nameArray = (UINT32*)vtProp.parray->pvData;
                        for (int i = 0; i < MaxNameBytes && i < userFriendlyNameLen; ++i)
                        {
                            userFriendlyName[i] = (BYTE)(nameArray[i] & 0xff);
                        }

                        userFriendlyName[sizeof(userFriendlyName)-1] = '\0';
                        userFriendlyNameStr = userFriendlyName;
                    }
                    else
                    {
                        // See: https://developer.oculusvr.com/forums/viewtopic.php?f=34&t=10961
                        // This can happen if someone has an EDID override in the registry.
                        LogError("{ERR-093} [Display] WARNING: Wrong data format for UserFriendlyName");
                    }

                    VariantClear(&vtProp);
                }
                else
                {
                    LogError("{ERR-094} [Display] WARNING: Failure getting display UserFriendlyName: %d", (int)hr);
                }
			}

            found = true;
            pclsObj->Release();
            break;
        }

		pclsObj->Release();
	}

	HMODULE hModule = GetModuleHandleA("wbemuuid");
	if (hModule)
	{
		DisableThreadLibraryCalls(hModule);
	}

	pSvc->Release();
	pLoc->Release();
	pEnumerator->Release();

    if (!found)
    {
        LogError("{ERR-095} [Display] WARNING: Unable to enumerate the rift via WMI (found %d monitors). This is not normally an issue. Running as a user with Administrator privileges has fixed this problem in the past.", enumeratedCount);
        OVR_ASSERT(false);
    }

	return found;
}

#else // OVR_COMPAT_EDID_VIA_WMI

#define NAME_SIZE 128

DEFINE_GUID(GUID_CLASS_MONITOR,
    0x4d36e96e, 0xe325, 0x11ce, 0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1,
    0x03, 0x18);

static void truncateNonalphanum(char* str, int len)
{
    for (int i = 0; i < len; ++i)
    {
        char ch = str[i];

        if ((ch < 'A' || ch > 'Z') &&
            (ch < 'a' || ch > 'z') &&
            (ch < '0' || ch > '9') &&
            ch != ' ')
        {
            str[i] = '\0';
            break;
        }
    }
}

static bool AccessDeviceRegistry(IN HDEVINFO devInfo, IN PSP_DEVINFO_DATA devInfoData,
                                 const WCHAR* displayName, String& serialNumberStr, String& userFriendlyNameStr)
{
    // Match hardware id to display name
    WCHAR hardwareId[128];
    if (!SetupDiGetDeviceRegistryProperty(
        devInfo,
        devInfoData,
        SPDRP_HARDWAREID,
        NULL,
        (PBYTE)hardwareId,
        sizeof(hardwareId),
        NULL))
    {
        LogError("{ERR-096} [Display] WARNING: SetupDiGetDeviceRegistryProperty for SPDRP_HARDWAREID failed. LastErr=%d", GetLastError());
        OVR_ASSERT(false);
        return false;
    }
    hardwareId[127] = 0;

    // If the hardware id did not match,
    if (!wcsstr(hardwareId, displayName))
    {
        // Stop here
        return false;
    }

    // Grab hardware info registry key
    HKEY hDevRegKey = SetupDiOpenDevRegKey(
        devInfo,
        devInfoData,
        DICS_FLAG_GLOBAL,
        0,
        DIREG_DEV,
        KEY_READ); // Only read permissions so it can be run without Administrator privs

    if (hDevRegKey == INVALID_HANDLE_VALUE)
    {
        LogError("{ERR-097} [Display] WARNING: SetupDiOpenDevRegKey failed. LastErr=%d", GetLastError());
        OVR_ASSERT(false);
        return false;
    }

    // Enumerate keys in registry
    bool found = false;

    // For each key,
    for (int i = 0;; i++)
    {
        BYTE EDIDdata[1024];
        DWORD edidsize = sizeof(EDIDdata);

        DWORD dwType, ActualValueNameLength = NAME_SIZE;
        CHAR valueName[NAME_SIZE];

        // Read the key value data
        LSTATUS retValue = RegEnumValueA(
            hDevRegKey,
            i,
            &valueName[0],
            &ActualValueNameLength,
            NULL,
            &dwType,
            EDIDdata,
            &edidsize);

        // If no more items in the enumeration,
        if (retValue == ERROR_NO_MORE_ITEMS)
        {
            // Stop here
            break;
        }

        // If the request failed,
        if (FAILED(retValue))
        {
            LogError("{ERR-098} [Display] WARNING: RegEnumValueA failed to read a key. LastErr=%d", retValue);
            OVR_ASSERT(false);
        }
        else if (0 == strcmp(valueName, "EDID")) // Value is EDID:
        {
            // Tested working for DK1 and DK2:

            char friendlyString[9];
            memcpy(friendlyString, EDIDdata + 77, 8);
            truncateNonalphanum(friendlyString, 8);
            friendlyString[8] = '\0';

            char edidString[14];
            memcpy(edidString, EDIDdata + 95, 13);
            truncateNonalphanum(edidString, 13);
            edidString[13] = '\0';

            serialNumberStr = edidString;
            userFriendlyNameStr = friendlyString;

            found = true;
            break;
        }
    }

    RegCloseKey(hDevRegKey);

    return found;
}

static bool getCompatDisplayEDID(const WCHAR* displayName, String& serialNumberStr, String& userFriendlyNameStr)
{
    HDEVINFO devInfo = NULL;

    devInfo = SetupDiGetClassDevsEx(
        &GUID_CLASS_MONITOR, //class GUID
        NULL, //enumerator
        NULL, //HWND
        DIGCF_PRESENT, // Flags //DIGCF_ALLCLASSES|
        NULL, // device info, create a new one.
        NULL, // machine name, local machine
        NULL);// reserved

    if (NULL == devInfo)
    {
        return false;
    }

    DWORD lastError = 0;

    // For each display,
    for (int i = 0;; i++)
    {
        SP_DEVINFO_DATA devInfoData = {};
        devInfoData.cbSize = sizeof(devInfoData);

        // Grab device info
        if (SetupDiEnumDeviceInfo(devInfo, i, &devInfoData))
        {
            // Access device info from registry
            if (AccessDeviceRegistry(devInfo, &devInfoData, displayName, serialNumberStr, userFriendlyNameStr))
            {
                return true;
            }
        }
        else
        {
            lastError = GetLastError();

            // If no more items found,
            if (lastError != ERROR_NO_MORE_ITEMS)
            {
                LogError("{ERR-099} [Display] WARNING: SetupDiEnumDeviceInfo failed. LastErr=%d", lastError);
                OVR_ASSERT(false);
            }

            break;
        }
    }

    LogError("{ERR-100} [Display] WARNING: SetupDiEnumDeviceInfo did not return the rift display. LastErr=%d", lastError);
    OVR_ASSERT(false);

    return false;
}

#endif // OVR_COMPAT_EDID_VIA_WMI

// This is function that's used 
bool anyRiftsInExtendedMode()
{
	bool result = false;

	MonitorSet monitors;
	monitors.MonitorCount = 0;
	// Get all the monitor handles 
	EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM)&monitors);

	DISPLAY_DEVICE dd, ddm;
	UINT           i, j;

	for( i = 0;
		(ZeroMemory(&dd, sizeof(dd)), dd.cb = sizeof(dd),
		EnumDisplayDevices(0, i, &dd, 0)) != 0;  i++ )
	{
		for( j = 0;
			(ZeroMemory(&ddm, sizeof(ddm)), ddm.cb = sizeof(ddm),
			EnumDisplayDevices(dd.DeviceName, j, &ddm, 0)) != 0;  j++ )
		{
			// Our monitor hardware has string "RTD2205" in it
			// Nate's device "CVT0003"
			if( wcsstr(ddm.DeviceID, L"RTD2205") ||
				wcsstr(ddm.DeviceID, L"CVT0003") ||
				wcsstr(ddm.DeviceID, L"MST0030") ||
				wcsstr(ddm.DeviceID, L"OVR00") ) // Part of Oculus EDID.
			{
				result = true;
			}
		}
	}

	return result;
}

static int discoverExtendedRifts(OVR::Win32::DisplayDesc* descriptorArray, int inputArraySize, bool includeEDID)
{
	static bool reportDiscovery = true;

	int result = 0;

	MonitorSet monitors;
	monitors.MonitorCount = 0;
	// Get all the monitor handles 
	EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM)&monitors);

	DISPLAY_DEVICE dd, ddm;
	UINT           i, j;    

	for (i = 0; 
		(ZeroMemory(&dd, sizeof(dd)), dd.cb = sizeof(dd),
		EnumDisplayDevices(0, i, &dd, 0)) != 0;  i++)
	{
		for (j = 0; 
			(ZeroMemory(&ddm, sizeof(ddm)), ddm.cb = sizeof(ddm),
			EnumDisplayDevices(dd.DeviceName, j, &ddm, 0)) != 0;  j++)
		{
			if( result >= inputArraySize )
				return result;

			// Our monitor hardware has string "RTD2205" in it
			// Nate's device "CVT0003"
			if (wcsstr(ddm.DeviceID, L"RTD2205") || 
				wcsstr(ddm.DeviceID, L"CVT0003") || 
				wcsstr(ddm.DeviceID, L"MST0030") ||
				wcsstr(ddm.DeviceID, L"OVR00") ) // Part of Oculus EDID.
			{
				String   deviceId(ddm.DeviceID);
				String   displayDeviceName(ddm.DeviceName);				
                Vector2i desktopOffset(0, 0);
                Sizei    monitorResolution(1280, 800);   

                // Make a device type guess
                HmdTypeEnum deviceTypeGuess = HmdType_Unknown;
                if (wcsstr(ddm.DeviceID, L"OVR0003"))
                {
                    // DK2 prototypes and variants
                    deviceTypeGuess = HmdType_DK2;
                    // Could also be:
                    // HmdType_CrystalCoveProto
                }
                else if (wcsstr(ddm.DeviceID, L"OVR0002"))
                {   // HD Prototypes
                    deviceTypeGuess = HmdType_DKHDProto;
                    // Could also be:
                    // HmdType_DKHD2Proto
                    // HmdType_DKHDProto566Mi
                }
                else if (wcsstr(ddm.DeviceID, L"OVR0001"))
                {   // DK1
                    deviceTypeGuess = HmdType_DK1;
                }
                else if (wcsstr(ddm.DeviceID, L"OVR00"))
                {   // Future Oculus HMD devices
                    deviceTypeGuess = HmdType_Unknown;
                }
                else
                {
                    deviceTypeGuess = HmdType_DKProto;
                }

				// Find the matching MONITORINFOEX for this device so we can get the 
				// screen coordinates
				MONITORINFOEX info;
				for (int m=0; m < monitors.MonitorCount; m++)
				{
					info.cbSize = sizeof(MONITORINFOEX);
					GetMonitorInfo(monitors.Monitors[m], &info);
					if (_tcsstr(ddm.DeviceName, info.szDevice) == ddm.DeviceName)
					{   // If the device name starts with the monitor name
						// then we found the matching DISPLAY_DEVICE and MONITORINFO
						// so we can gather the monitor coordinates
                        desktopOffset = Vector2i(info.rcMonitor.left, info.rcMonitor.top);
						break;
					}
				}

				WCHAR* instanceBuffer = (WCHAR*)calloc(wcslen(ddm.DeviceID) + 1, sizeof(WCHAR));
				wcscpy_s(instanceBuffer, wcslen(ddm.DeviceID) + 1, ddm.DeviceID);
				WCHAR* instanceName = instanceBuffer;
				WCHAR* nextToken = NULL;
				if (wcstok_s(instanceName, L"\\", &nextToken))
				{
					WCHAR* aToken = wcstok_s(NULL, L"\\", &nextToken);

					if (aToken)
					{
						String serialNumberStr, userFriendlyNameStr;
                        if (!includeEDID || getCompatDisplayEDID(aToken, serialNumberStr, userFriendlyNameStr))
						{
							// Set descriptor
							OVR::Win32::DisplayDesc& desc = descriptorArray[result++];

                            // If not including EDID,
                            if (!includeEDID)
                            {
                                // If DK2 id,
                                if (wcsstr(ddm.DeviceID, L"OVR0003"))
                                {
                                    userFriendlyNameStr = "Rift DK2";
                                }
                                else // Assume DK1 for now:
                                {
                                    userFriendlyNameStr = "Rift DK1";
                                }
                            }

                            desc.DeviceTypeGuess = deviceTypeGuess;
                            desc.DisplayID = displayDeviceName;
							desc.ModelName = userFriendlyNameStr;
							desc.EdidSerialNumber = serialNumberStr;
							desc.LogicalResolutionInPixels = monitorResolution;
							desc.DesktopDisplayOffset = desktopOffset;

							// Hard-coded defaults in case the device doesn't have the data itself.
							// DK2 prototypes (0003) or DK HD Prototypes (0002)                
							if (wcsstr(ddm.DeviceID, L"OVR0003") || wcsstr(ddm.DeviceID, L"OVR0002"))
							{
								desc.LogicalResolutionInPixels = Sizei(1920, 1080);
								desc.NativeResolutionInPixels = Sizei(1080, 1920);
							}
							else
							{
								desc.LogicalResolutionInPixels = monitorResolution;
								desc.NativeResolutionInPixels = monitorResolution;
							}
						}
					}
				}

				if (reportDiscovery)
				{
					// Only report once per run
					OVR_DEBUG_LOG_TEXT(("Display Found %s - %s\n",
						deviceId.ToCStr(), displayDeviceName.ToCStr()));
					reportDiscovery = false;
				}

				free(instanceBuffer);

				break;
			}
		}
	}

	return result;
}


//-------------------------------------------------------------------------------------
// ***** Display 

bool Display::InCompatibilityMode( bool displaySearch )
{
	bool result = false;
	if( displaySearch )
	{
		OVR::Win32::DisplayDesc displayArray[8];

		int extendedRiftCount = discoverExtendedRifts(displayArray, 8, false);
		if( extendedRiftCount )
		{
			result = true;
		}
		else
		{
			result = GlobalDisplayContext.CompatibilityMode;
		}
	}
	else
	{
		result = GlobalDisplayContext.CompatibilityMode;
	}

	return result;
}

#define OVR_FLAG_COMPATIBILITY_MODE 1
#define OVR_FLAG_HIDE_DK1 2

bool Display::Initialize()
{
	HANDLE hDevice = INVALID_HANDLE_VALUE;

    if (GlobalDisplayContext.hDevice == 0)
    {
        hDevice = CreateFile( L"\\\\.\\ovr_video" ,
		                  GENERIC_READ | GENERIC_WRITE, NULL,
		                  NULL, OPEN_EXISTING, NULL, NULL);
    }
    else
    {   // The device has already been created
        hDevice = GlobalDisplayContext.hDevice;
    }

	if (hDevice != NULL && hDevice != INVALID_HANDLE_VALUE)
	{
		GlobalDisplayContext.hDevice             = hDevice;
		GlobalDisplayContext.CompatibilityMode = false;

		DWORD bytesReturned = 0;
		LONG compatiblityResult = OVR_STATUS_SUCCESS;

		BOOL result = DeviceIoControl( hDevice, IOCTL_RIFTMGR_GETCOMPATIBILITYMODE, NULL, 0,
                                       &compatiblityResult, sizeof( LONG ), &bytesReturned, NULL );
		if (result)
		{
            GlobalDisplayContext.CompatibilityMode = (compatiblityResult & OVR_FLAG_COMPATIBILITY_MODE) != 0;
            GlobalDisplayContext.HideDK1Mode = (compatiblityResult & OVR_FLAG_HIDE_DK1) != 0;
        }
		else
		{
			// If calling our driver fails in any way, assume compatibility mode as well
			GlobalDisplayContext.CompatibilityMode = true;
		}

		if (!GlobalDisplayContext.CompatibilityMode)
		{
			Ptr<DisplaySearchHandle> searchHandle = *Display::GetDisplaySearchHandle();

			// If a display is actually connected, bring up the shim layers so we can actually use it
			if (GetDisplayCount(searchHandle) > 0)
			{
				// FIXME: Initializing DX9 with landscape numbers rather than portrait
				GlobalDisplayContext.ExpectedWidth = 1080;
				GlobalDisplayContext.ExpectedHeight = 1920;
			}
			else
			{
				GlobalDisplayContext.CompatibilityMode = true;
			}

		}
	}
	else
	{
		GlobalDisplayContext.CompatibilityMode = true;
	}

	return true;
}

bool Display::GetDriverMode(bool& driverInstalled, bool& compatMode, bool& hideDK1Mode)
{
    if (GlobalDisplayContext.hDevice == NULL)
    {
        driverInstalled = false;
        compatMode = true;
        hideDK1Mode = false;
    }
    else
    {
        driverInstalled = true;
        compatMode = GlobalDisplayContext.CompatibilityMode;
        hideDK1Mode = GlobalDisplayContext.HideDK1Mode;
    }

    return true;
}

bool Display::SetDriverMode(bool compatMode, bool hideDK1Mode)
{
    // If device is not initialized,
    if (GlobalDisplayContext.hDevice == NULL)
    {
        OVR_ASSERT(false);
        return false;
    }

    // If no change,
    if ((compatMode == GlobalDisplayContext.CompatibilityMode) &&
        (hideDK1Mode == GlobalDisplayContext.HideDK1Mode))
    {
        return true;
    }

    LONG mode_flags = 0;
    if (compatMode)
    {
        mode_flags |= OVR_FLAG_COMPATIBILITY_MODE;
    }
    if (hideDK1Mode)
    {
        mode_flags |= OVR_FLAG_HIDE_DK1;
    }

    DWORD bytesReturned = 0;
    LONG err = 1;

    if (!DeviceIoControl(GlobalDisplayContext.hDevice,
                         IOCTL_RIFTMGR_SETCOMPATIBILITYMODE,
                         &mode_flags,
                         sizeof(LONG),
                         &err,
                         sizeof(LONG),
                         &bytesReturned,
                         NULL) ||
        (err != 0 && err != -3))
    {
        LogError("{ERR-001w} [Win32Display] Unable to set device mode to (compat=%d dk1hide=%d): err=%d",
            (int)compatMode, (int)hideDK1Mode, (int)err);
        return false;
    }

    OVR_DEBUG_LOG(("[Win32Display] Set device mode to (compat=%d dk1hide=%d)",
        (int)compatMode, (int)hideDK1Mode));

    GlobalDisplayContext.HideDK1Mode = hideDK1Mode;
    GlobalDisplayContext.CompatibilityMode = compatMode;
    return true;
}

DisplaySearchHandle* Display::GetDisplaySearchHandle()
{
	return new Win32::Win32DisplaySearchHandle();
}

// FIXME: The handle parameter will be used to unify GetDisplayCount and GetDisplay calls
// The handle will be written to the 64-bit value pointed and will store the enumerated
// display list. This will allow the indexes to be meaningful between obtaining
// the count. With a single handle the count should be stable
int Display::GetDisplayCount(DisplaySearchHandle* handle, bool extended, bool applicationOnly, bool extendedEDIDSerials)
{
	static int extendedCount = -1;
	static int applicationCount = -1;

	Win32::Win32DisplaySearchHandle* localHandle = (Win32::Win32DisplaySearchHandle*)handle;
	
	if( localHandle == NULL )
		return 0;

	if( extendedCount == -1 || extended )
	{
        extendedCount = discoverExtendedRifts(localHandle->cachedDescriptorArray, 16, extendedEDIDSerials);
	}

	localHandle->extended = true;
	localHandle->extendedDisplayCount = extendedCount;
	int totalCount = extendedCount;

	if( applicationCount == -1 || applicationOnly )
	{
		applicationCount = getRiftCount(GlobalDisplayContext.hDevice);
		localHandle->application = true;
	}

	totalCount += applicationCount;
	localHandle->applicationDisplayCount = applicationCount;
	localHandle->displayCount = totalCount;

	return totalCount;
}

Ptr<Display> Display::GetDisplay(int index, DisplaySearchHandle* handle)
{
	Ptr<Display> result;

	if( index < 0 )
		return result;

	Win32::Win32DisplaySearchHandle* localHandle = (Win32::Win32DisplaySearchHandle*)handle;

	if( localHandle == NULL )
		return NULL;

	if (localHandle->extended)
	{
		if (index >= 0 && index < (int)localHandle->extendedDisplayCount)
		{
			return *new Win32::Win32DisplayGeneric(localHandle->cachedDescriptorArray[index]);
		}

		index -= localHandle->extendedDisplayCount;
	}

	if(localHandle->application)
	{
		if (index >= 0 && index < (int)getRiftCount(GlobalDisplayContext.hDevice))
		{
            ULONG riftChildId = getRift(GlobalDisplayContext.hDevice, index);
            Win32::DisplayEDID dEdid;

            if (!getEdid(GlobalDisplayContext.hDevice, riftChildId, dEdid))
            {
                return NULL;
            }

            // FIXME: We have the EDID. Let's just use that instead.
            uint32_t nativeWidth = 1080, nativeHeight = 1920;
            uint32_t logicalWidth = 1920, logicalHeight = 1080;
			uint32_t rotation = 0;

            switch (dEdid.ModelNumber)
            {
			case 0:
			case 1:
				nativeWidth = 1280;
				nativeHeight = 800;
				logicalWidth = nativeWidth;
				logicalHeight = nativeHeight;
				break;
			case 2:
			case 3:
			default:
				rotation = 90;
				break;
			}

            HmdTypeEnum deviceTypeGuess = HmdType_Unknown;
            switch (dEdid.ModelNumber)
            {
            case 3: deviceTypeGuess = HmdType_DK2;       break;
            case 2: deviceTypeGuess = HmdType_DKHDProto; break;
            case 1: deviceTypeGuess = HmdType_DK1;       break;
            default: break;
            }

			result = *new Win32::Win32DisplayDriver( 
						deviceTypeGuess,
                        "",
						dEdid.MonitorName,
						dEdid.SerialNumber,
                        Sizei(logicalWidth, logicalHeight),
						Sizei(nativeWidth, nativeHeight),
						Vector2i(0),
                        dEdid,
						GlobalDisplayContext.hDevice,
						riftChildId,
						rotation);
		}
	}
	return result;
}

Display::MirrorMode Win32::Win32DisplayDriver::SetMirrorMode( Display::MirrorMode newMode )
{
	return newMode;
}

static bool SetDisplayPower(HANDLE hDevice, ULONG childId, int mode)
{
    ULONG_PTR longArray[2];

    longArray[0] = childId;
    longArray[1] = mode;

    ULONG localResult = 0;
    DWORD bytesReturned = 0;

    BOOL result = DeviceIoControl(hDevice,
                                  IOCTL_RIFTMGR_DISPLAYPOWER,
                                  longArray,
                                  2 * sizeof(ULONG_PTR),
                                  &localResult,
                                  sizeof(ULONG),
                                  &bytesReturned,
                                  NULL);

    // Note: bytesReturned does not seem to be set
    return result != FALSE /* && bytesReturned == sizeof(ULONG) */ && mode == (int)localResult;
}

bool Win32::Win32DisplayDriver::SetDisplaySleep(bool sleep)
{
    return SetDisplayPower(hDevice, ChildId, sleep ? 2 : 1);
}


} // namespace OVR