/
WIN32Util.cpp
1598 lines (1384 loc) · 45.8 KB
/
WIN32Util.cpp
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
/*
* Copyright (C) 2005-2012 Team XBMC
* http://www.xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "WIN32Util.h"
#include "settings/GUISettings.h"
#include "Util.h"
#include "utils/URIUtils.h"
#include "storage/cdioSupport.h"
#include "PowrProf.h"
#include "WindowHelper.h"
#include "Application.h"
#include <shlobj.h>
#include "filesystem/SpecialProtocol.h"
#include "my_ntddscsi.h"
#if _MSC_VER > 1400
#include "Setupapi.h"
#endif
#include "storage/MediaManager.h"
#include "windowing/WindowingFactory.h"
#include "guilib/LocalizeStrings.h"
#include "utils/log.h"
#include "utils/StringUtils.h"
#include "DllPaths_win32.h"
#include "FileSystem/File.h"
#include "utils/URIUtils.h"
// default Broadcom registy bits (setup when installing a CrystalHD card)
#define BC_REG_PATH "Software\\Broadcom\\MediaPC"
#define BC_REG_PRODUCT "CrystalHD" // 70012/70015
#define BC_BCM_DLL "bcmDIL.dll"
#define BC_REG_INST_PATH "InstallPath"
#define DLL_ENV_PATH "special://xbmc/system/;" \
"special://xbmc/system/players/dvdplayer/;" \
"special://xbmc/system/players/paplayer/;" \
"special://xbmc/system/cdrip/;" \
"special://xbmc/system/python/;" \
"special://xbmc/system/webserver/;" \
"special://xbmc/"
extern HWND g_hWnd;
using namespace std;
using namespace MEDIA_DETECT;
CWIN32Util::CWIN32Util(void)
{
}
CWIN32Util::~CWIN32Util(void)
{
}
CStdString CWIN32Util::URLEncode(const CURL &url)
{
/* due to smb wanting encoded urls we have to build it manually */
CStdString flat = "smb://";
if(url.GetDomain().length() > 0)
{
flat += url.GetDomain();
flat += ";";
}
/* samba messes up of password is set but no username is set. don't know why yet */
/* probably the url parser that goes crazy */
if(url.GetUserName().length() > 0 /* || url.GetPassWord().length() > 0 */)
{
flat += url.GetUserName();
flat += ":";
flat += url.GetPassWord();
flat += "@";
}
flat += url.GetHostName();
/* okey sadly since a slash is an invalid name we have to tokenize */
std::vector<CStdString> parts;
std::vector<CStdString>::iterator it;
CUtil::Tokenize(url.GetFileName(), parts, "/");
for( it = parts.begin(); it != parts.end(); it++ )
{
flat += "/";
flat += (*it);
}
/* okey options should go here, thou current samba doesn't support any */
return flat;
}
int CWIN32Util::GetDriveStatus(const CStdString &strPath, bool bStatusEx)
{
HANDLE hDevice; // handle to the drive to be examined
int iResult; // results flag
ULONG ulChanges=0;
DWORD dwBytesReturned;
T_SPDT_SBUF sptd_sb; //SCSI Pass Through Direct variable.
byte DataBuf[8]; //Buffer for holding data to/from drive.
CLog::Log(LOGDEBUG, __FUNCTION__": Requesting status for drive %s.", strPath.c_str());
hDevice = CreateFile( strPath.c_str(), // drive
0, // no access to the drive
FILE_SHARE_READ, // share mode
NULL, // default security attributes
OPEN_EXISTING, // disposition
FILE_ATTRIBUTE_READONLY, // file attributes
NULL);
if (hDevice == INVALID_HANDLE_VALUE) // cannot open the drive
{
CLog::Log(LOGERROR, __FUNCTION__": Failed to CreateFile for %s.", strPath.c_str());
return -1;
}
CLog::Log(LOGDEBUG, __FUNCTION__": Requesting media status for drive %s.", strPath.c_str());
iResult = DeviceIoControl((HANDLE) hDevice, // handle to device
IOCTL_STORAGE_CHECK_VERIFY2, // dwIoControlCode
NULL, // lpInBuffer
0, // nInBufferSize
&ulChanges, // lpOutBuffer
sizeof(ULONG), // nOutBufferSize
&dwBytesReturned , // number of bytes returned
NULL ); // OVERLAPPED structure
CloseHandle(hDevice);
if(iResult == 1)
return 2;
// don't request the tray status as we often doesn't need it
if(!bStatusEx)
return 0;
hDevice = CreateFile( strPath.c_str(),
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_READONLY,
NULL);
if (hDevice == INVALID_HANDLE_VALUE)
{
CLog::Log(LOGERROR, __FUNCTION__": Failed to CreateFile2 for %s.", strPath.c_str());
return -1;
}
sptd_sb.sptd.Length=sizeof(SCSI_PASS_THROUGH_DIRECT);
sptd_sb.sptd.PathId=0;
sptd_sb.sptd.TargetId=0;
sptd_sb.sptd.Lun=0;
sptd_sb.sptd.CdbLength=10;
sptd_sb.sptd.SenseInfoLength=MAX_SENSE_LEN;
sptd_sb.sptd.DataIn=SCSI_IOCTL_DATA_IN;
sptd_sb.sptd.DataTransferLength=sizeof(DataBuf);
sptd_sb.sptd.TimeOutValue=2;
sptd_sb.sptd.DataBuffer=(PVOID)&(DataBuf);
sptd_sb.sptd.SenseInfoOffset=sizeof(SCSI_PASS_THROUGH_DIRECT);
sptd_sb.sptd.Cdb[0]=0x4a;
sptd_sb.sptd.Cdb[1]=1;
sptd_sb.sptd.Cdb[2]=0;
sptd_sb.sptd.Cdb[3]=0;
sptd_sb.sptd.Cdb[4]=0x10;
sptd_sb.sptd.Cdb[5]=0;
sptd_sb.sptd.Cdb[6]=0;
sptd_sb.sptd.Cdb[7]=0;
sptd_sb.sptd.Cdb[8]=8;
sptd_sb.sptd.Cdb[9]=0;
sptd_sb.sptd.Cdb[10]=0;
sptd_sb.sptd.Cdb[11]=0;
sptd_sb.sptd.Cdb[12]=0;
sptd_sb.sptd.Cdb[13]=0;
sptd_sb.sptd.Cdb[14]=0;
sptd_sb.sptd.Cdb[15]=0;
ZeroMemory(DataBuf, 8);
ZeroMemory(sptd_sb.SenseBuf, MAX_SENSE_LEN);
//Send the command to drive
CLog::Log(LOGDEBUG, __FUNCTION__": Requesting tray status for drive %s.", strPath.c_str());
iResult = DeviceIoControl((HANDLE) hDevice,
IOCTL_SCSI_PASS_THROUGH_DIRECT,
(PVOID)&sptd_sb, (DWORD)sizeof(sptd_sb),
(PVOID)&sptd_sb, (DWORD)sizeof(sptd_sb),
&dwBytesReturned,
NULL);
CloseHandle(hDevice);
if(iResult)
{
if(DataBuf[5] == 0) // tray close
return 0;
else if(DataBuf[5] == 1) // tray open
return 1;
else
return 2; // tray closed, media present
}
CLog::Log(LOGERROR, __FUNCTION__": Could not determine tray status %d", GetLastError());
return -1;
}
CStdString CWIN32Util::GetLocalPath(const CStdString &strPath)
{
CURL url(strPath);
CStdString strLocalPath = url.GetFileName();
strLocalPath.Replace(url.GetShareName()+"/","");
return strLocalPath;
}
char CWIN32Util::FirstDriveFromMask (ULONG unitmask)
{
char i;
for (i = 0; i < 26; ++i)
{
if (unitmask & 0x1) break;
unitmask = unitmask >> 1;
}
return (i + 'A');
}
bool CWIN32Util::PowerManagement(PowerState State)
{
// SetSuspendState not available in vs2003
#if _MSC_VER > 1400
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
// Get a token for this process.
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
return false;
}
// Get the LUID for the shutdown privilege.
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Get the shutdown privilege for this process.
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
CloseHandle(hToken);
if (GetLastError() != ERROR_SUCCESS)
{
return false;
}
switch (State)
{
case POWERSTATE_HIBERNATE:
CLog::Log(LOGINFO, "Asking Windows to hibernate...");
return SetSuspendState(true,true,false) == TRUE;
break;
case POWERSTATE_SUSPEND:
CLog::Log(LOGINFO, "Asking Windows to suspend...");
return SetSuspendState(false,true,false) == TRUE;
break;
case POWERSTATE_SHUTDOWN:
CLog::Log(LOGINFO, "Shutdown Windows...");
return ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_UPGRADE | SHTDN_REASON_FLAG_PLANNED) == TRUE;
break;
case POWERSTATE_REBOOT:
CLog::Log(LOGINFO, "Rebooting Windows...");
return ExitWindowsEx(EWX_REBOOT | EWX_FORCE, SHTDN_REASON_MAJOR_OPERATINGSYSTEM | SHTDN_REASON_MINOR_UPGRADE | SHTDN_REASON_FLAG_PLANNED) == TRUE;
break;
default:
CLog::Log(LOGERROR, "Unknown PowerState called.");
return false;
break;
}
#else
return false;
#endif
}
int CWIN32Util::BatteryLevel()
{
SYSTEM_POWER_STATUS SystemPowerStatus;
if (GetSystemPowerStatus(&SystemPowerStatus) && SystemPowerStatus.BatteryLifePercent != 255)
return SystemPowerStatus.BatteryLifePercent;
return 0;
}
bool CWIN32Util::XBMCShellExecute(const CStdString &strPath, bool bWaitForScriptExit)
{
CStdString strCommand = strPath;
CStdString strExe = strPath;
CStdString strParams;
CStdString strWorkingDir;
strCommand.Trim();
if (strCommand.IsEmpty())
{
return false;
}
int iIndex = -1;
char split = ' ';
if (strCommand[0] == '\"')
{
split = '\"';
}
iIndex = strCommand.Find(split, 1);
if (iIndex != -1)
{
strExe = strCommand.substr(0, iIndex + 1);
strParams = strCommand.substr(iIndex + 1);
}
strExe.Replace("\"","");
strWorkingDir = strExe;
iIndex = strWorkingDir.ReverseFind('\\');
if(iIndex != -1)
{
strWorkingDir[iIndex+1] = '\0';
}
CStdStringW WstrExe, WstrParams, WstrWorkingDir;
g_charsetConverter.utf8ToW(strExe, WstrExe);
g_charsetConverter.utf8ToW(strParams, WstrParams);
g_charsetConverter.utf8ToW(strWorkingDir, WstrWorkingDir);
bool ret;
SHELLEXECUTEINFOW ShExecInfo = {0};
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFOW);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = NULL;
ShExecInfo.lpFile = WstrExe.c_str();
ShExecInfo.lpParameters = WstrParams.c_str();
ShExecInfo.lpDirectory = WstrWorkingDir.c_str();
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;
g_windowHelper.StopThread();
LockSetForegroundWindow(LSFW_UNLOCK);
ShowWindow(g_hWnd,SW_MINIMIZE);
ret = ShellExecuteExW(&ShExecInfo) == TRUE;
g_windowHelper.SetHANDLE(ShExecInfo.hProcess);
// ShellExecute doesn't return the window of the started process
// we need to gather it from somewhere to allow switch back to XBMC
// when a program is minimized instead of stopped.
//g_windowHelper.SetHWND(ShExecInfo.hwnd);
g_windowHelper.Create();
if(bWaitForScriptExit)
{
// Todo: Pause music and video playback
WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
}
return ret;
}
std::vector<CStdString> CWIN32Util::GetDiskUsage()
{
vector<CStdString> result;
ULARGE_INTEGER ULTotal= { { 0 } };
ULARGE_INTEGER ULTotalFree= { { 0 } };
char* pcBuffer= NULL;
DWORD dwStrLength= GetLogicalDriveStrings( 0, pcBuffer );
if( dwStrLength != 0 )
{
CStdString strRet;
dwStrLength+= 1;
pcBuffer= new char [dwStrLength];
GetLogicalDriveStrings( dwStrLength, pcBuffer );
int iPos= 0;
do
{
CStdString strDrive = pcBuffer + iPos;
if( DRIVE_FIXED == GetDriveType( strDrive.c_str() ) &&
GetDiskFreeSpaceEx( ( strDrive.c_str() ), NULL, &ULTotal, &ULTotalFree ) )
{
strRet.Format("%s %d MB %s",strDrive.c_str(), int(ULTotalFree.QuadPart/(1024*1024)),g_localizeStrings.Get(160));
result.push_back(strRet);
}
iPos += (strlen( pcBuffer + iPos) + 1 );
}while( strlen( pcBuffer + iPos ) > 0 );
}
delete[] pcBuffer;
return result;
}
CStdString CWIN32Util::GetResInfoString()
{
CStdString strRes;
DEVMODE devmode;
ZeroMemory(&devmode, sizeof(devmode));
devmode.dmSize = sizeof(devmode);
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devmode);
strRes.Format("Desktop Resolution: %dx%d %dBit at %dHz",devmode.dmPelsWidth,devmode.dmPelsHeight,devmode.dmBitsPerPel,devmode.dmDisplayFrequency);
return strRes;
}
int CWIN32Util::GetDesktopColorDepth()
{
DEVMODE devmode;
ZeroMemory(&devmode, sizeof(devmode));
devmode.dmSize = sizeof(devmode);
EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devmode);
return (int)devmode.dmBitsPerPel;
}
CStdString CWIN32Util::GetSpecialFolder(int csidl)
{
CStdString strProfilePath;
WCHAR szPath[MAX_PATH];
if(SUCCEEDED(SHGetFolderPathW(NULL,csidl,NULL,0,szPath)))
{
g_charsetConverter.wToUTF8(szPath, strProfilePath);
strProfilePath = UncToSmb(strProfilePath);
}
else
strProfilePath = "";
return strProfilePath;
}
CStdString CWIN32Util::GetSystemPath()
{
return GetSpecialFolder(CSIDL_SYSTEM);
}
CStdString CWIN32Util::GetProfilePath()
{
CStdString strProfilePath;
CStdString strHomePath;
CUtil::GetHomePath(strHomePath);
if(g_application.PlatformDirectoriesEnabled())
strProfilePath = URIUtils::AddFileToFolder(GetSpecialFolder(CSIDL_APPDATA|CSIDL_FLAG_CREATE), "XBMC");
else
strProfilePath = URIUtils::AddFileToFolder(strHomePath , "portable_data");
if (strProfilePath.length() == 0)
strProfilePath = strHomePath;
URIUtils::AddSlashAtEnd(strProfilePath);
return strProfilePath;
}
CStdString CWIN32Util::UncToSmb(const CStdString &strPath)
{
CStdString strRetPath(strPath);
if(strRetPath.Left(2).Equals("\\\\"))
{
strRetPath = "smb:" + strPath;
strRetPath.Replace("\\","/");
}
return strRetPath;
}
CStdString CWIN32Util::SmbToUnc(const CStdString &strPath)
{
CStdString strRetPath(strPath);
if(strRetPath.Left(6).Equals("smb://"))
{
strRetPath.Replace("smb://","\\\\");
strRetPath.Replace("/","\\");
}
return strRetPath;
}
void CWIN32Util::ExtendDllPath()
{
CStdStringW strEnvW;
CStdStringArray vecEnv;
WCHAR wctemp[32768];
if(GetEnvironmentVariableW(L"PATH",wctemp,32767) != 0)
strEnvW = wctemp;
StringUtils::SplitString(DLL_ENV_PATH, ";", vecEnv);
for (int i=0; i<(int)vecEnv.size(); ++i)
{
CStdStringW strFileW;
g_charsetConverter.utf8ToW(CSpecialProtocol::TranslatePath(vecEnv[i]), strFileW, false);
strEnvW.append(L";" + strFileW);
}
if(SetEnvironmentVariableW(L"PATH",strEnvW.c_str())!=0)
CLog::Log(LOGDEBUG,"Setting system env PATH to %S",strEnvW.c_str());
else
CLog::Log(LOGDEBUG,"Can't set system env PATH to %S",strEnvW.c_str());
}
HRESULT CWIN32Util::ToggleTray(const char cDriveLetter)
{
BOOL bRet= FALSE;
DWORD dwReq = 0;
char cDL = cDriveLetter;
if( !cDL )
{
CStdString dvdDevice = g_mediaManager.TranslateDevicePath("");
if(dvdDevice == "")
return S_FALSE;
cDL = dvdDevice[0];
}
CStdString strVolFormat;
strVolFormat.Format( _T("\\\\.\\%c:" ), cDL);
HANDLE hDrive= CreateFile( strVolFormat.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
CStdString strRootFormat;
strRootFormat.Format( _T("%c:\\"), cDL);
if( ( hDrive != INVALID_HANDLE_VALUE || GetLastError() == NO_ERROR) &&
( GetDriveType( strRootFormat ) == DRIVE_CDROM ) )
{
DWORD dwDummy;
dwReq = (GetDriveStatus(strVolFormat, true) == 1) ? IOCTL_STORAGE_LOAD_MEDIA : IOCTL_STORAGE_EJECT_MEDIA;
bRet = DeviceIoControl( hDrive, dwReq, NULL, 0, NULL, 0, &dwDummy, NULL);
CloseHandle( hDrive );
}
// Windows doesn't seem to send always DBT_DEVICEREMOVECOMPLETE
// unmount it here too as it won't hurt
if(dwReq == IOCTL_STORAGE_EJECT_MEDIA && bRet == 1)
{
strRootFormat.Format( _T("%c:"), cDL);
CMediaSource share;
share.strPath = strRootFormat;
share.strName = share.strPath;
g_mediaManager.RemoveAutoSource(share);
}
return bRet? S_OK : S_FALSE;
}
HRESULT CWIN32Util::EjectTray(const char cDriveLetter)
{
char cDL = cDriveLetter;
if( !cDL )
{
CStdString dvdDevice = g_mediaManager.TranslateDevicePath("");
if(dvdDevice == "")
return S_FALSE;
cDL = dvdDevice[0];
}
CStdString strVolFormat;
strVolFormat.Format( _T("\\\\.\\%c:" ), cDL);
if(GetDriveStatus(strVolFormat, true) != 1)
return ToggleTray(cDL);
else
return S_OK;
}
HRESULT CWIN32Util::CloseTray(const char cDriveLetter)
{
char cDL = cDriveLetter;
if( !cDL )
{
CStdString dvdDevice = g_mediaManager.TranslateDevicePath("");
if(dvdDevice == "")
return S_FALSE;
cDL = dvdDevice[0];
}
CStdString strVolFormat;
strVolFormat.Format( _T("\\\\.\\%c:" ), cDL);
if(GetDriveStatus(strVolFormat, true) == 1)
return ToggleTray(cDL);
else
return S_OK;
}
// safe removal of USB drives:
// http://www.codeproject.com/KB/system/RemoveDriveByLetter.aspx
// http://www.techtalkz.com/microsoft-device-drivers/250734-remove-usb-device-c-3.html
#if _MSC_VER > 1400
DEVINST CWIN32Util::GetDrivesDevInstByDiskNumber(long DiskNumber)
{
GUID* guid = (GUID*)(void*)&GUID_DEVINTERFACE_DISK;
// Get device interface info set handle for all devices attached to system
HDEVINFO hDevInfo = SetupDiGetClassDevs(guid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (hDevInfo == INVALID_HANDLE_VALUE)
return 0;
// Retrieve a context structure for a device interface of a device
// information set.
DWORD dwIndex = 0;
SP_DEVICE_INTERFACE_DATA devInterfaceData = {0};
devInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
BOOL bRet = FALSE;
PSP_DEVICE_INTERFACE_DETAIL_DATA pspdidd;
SP_DEVICE_INTERFACE_DATA spdid;
SP_DEVINFO_DATA spdd;
DWORD dwSize;
spdid.cbSize = sizeof(spdid);
while ( true )
{
bRet = SetupDiEnumDeviceInterfaces(hDevInfo, NULL, guid, dwIndex, &devInterfaceData);
if (!bRet)
break;
SetupDiEnumInterfaceDevice(hDevInfo, NULL, guid, dwIndex, &spdid);
dwSize = 0;
SetupDiGetDeviceInterfaceDetail(hDevInfo, &spdid, NULL, 0, &dwSize, NULL);
if ( dwSize )
{
pspdidd = (PSP_DEVICE_INTERFACE_DETAIL_DATA)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwSize);
if ( pspdidd == NULL )
continue;
pspdidd->cbSize = sizeof(*pspdidd);
ZeroMemory((PVOID)&spdd, sizeof(spdd));
spdd.cbSize = sizeof(spdd);
long res = SetupDiGetDeviceInterfaceDetail(hDevInfo, &spdid,
pspdidd, dwSize, &dwSize, &spdd);
if ( res )
{
HANDLE hDrive = CreateFile(pspdidd->DevicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
if ( hDrive != INVALID_HANDLE_VALUE )
{
STORAGE_DEVICE_NUMBER sdn;
DWORD dwBytesReturned = 0;
res = DeviceIoControl(hDrive, IOCTL_STORAGE_GET_DEVICE_NUMBER, NULL, 0, &sdn, sizeof(sdn), &dwBytesReturned, NULL);
if ( res )
{
if ( DiskNumber == (long)sdn.DeviceNumber )
{
CloseHandle(hDrive);
SetupDiDestroyDeviceInfoList(hDevInfo);
return spdd.DevInst;
}
}
CloseHandle(hDrive);
}
}
HeapFree(GetProcessHeap(), 0, pspdidd);
}
dwIndex++;
}
SetupDiDestroyDeviceInfoList(hDevInfo);
return 0;
}
#endif
bool CWIN32Util::EjectDrive(const char cDriveLetter)
{
#if _MSC_VER > 1400
if( !cDriveLetter )
return false;
CStdString strVolFormat;
strVolFormat.Format( _T("\\\\.\\%c:" ), cDriveLetter);
long DiskNumber = -1;
HANDLE hVolume = CreateFile(strVolFormat.c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
if (hVolume == INVALID_HANDLE_VALUE)
return false;
STORAGE_DEVICE_NUMBER sdn;
DWORD dwBytesReturned = 0;
long res = DeviceIoControl(hVolume, IOCTL_STORAGE_GET_DEVICE_NUMBER,NULL, 0, &sdn, sizeof(sdn), &dwBytesReturned, NULL);
CloseHandle(hVolume);
if ( res )
DiskNumber = sdn.DeviceNumber;
else
return false;
DEVINST DevInst = GetDrivesDevInstByDiskNumber(DiskNumber);
if ( DevInst == 0 )
return false;
ULONG Status = 0;
ULONG ProblemNumber = 0;
PNP_VETO_TYPE VetoType = PNP_VetoTypeUnknown;
char VetoName[MAX_PATH];
bool bSuccess = false;
res = CM_Get_Parent(&DevInst, DevInst, 0); // disk's parent, e.g. the USB bridge, the SATA controller....
res = CM_Get_DevNode_Status(&Status, &ProblemNumber, DevInst, 0);
for(int i=0;i<3;i++)
{
res = CM_Request_Device_Eject(DevInst, &VetoType, VetoName, MAX_PATH, 0);
bSuccess = (res==CR_SUCCESS && VetoType==PNP_VetoTypeUnknown);
if ( bSuccess )
break;
}
return bSuccess;
#else
return false;
#endif
}
#ifdef HAS_GL
void CWIN32Util::CheckGLVersion()
{
if(CWIN32Util::HasGLDefaultDrivers())
{
MessageBox(NULL, "MS default OpenGL drivers detected. Please get OpenGL drivers from your video card vendor", "XBMC: Fatal Error", MB_OK|MB_ICONERROR);
exit(1);
}
if(!CWIN32Util::HasReqGLVersion())
{
if(MessageBox(NULL, "Your OpenGL version doesn't meet the XBMC requirements", "XBMC: Warning", MB_OKCANCEL|MB_ICONWARNING) == IDCANCEL)
{
exit(1);
}
}
}
bool CWIN32Util::HasGLDefaultDrivers()
{
unsigned int a=0,b=0;
CStdString strVendor = g_Windowing.GetRenderVendor();
g_Windowing.GetRenderVersion(a, b);
if(strVendor.find("Microsoft")!=strVendor.npos && a==1 && b==1)
return true;
else
return false;
}
bool CWIN32Util::HasReqGLVersion()
{
unsigned int a=0,b=0;
g_Windowing.GetRenderVersion(a, b);
if((a>=2) || (a == 1 && b >= 3))
return true;
else
return false;
}
#endif
BOOL CWIN32Util::IsCurrentUserLocalAdministrator()
{
BOOL b;
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
b = AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup);
if(b)
{
if (!CheckTokenMembership( NULL, AdministratorsGroup, &b))
{
b = FALSE;
}
FreeSid(AdministratorsGroup);
}
return(b);
}
void CWIN32Util::GetDrivesByType(VECSOURCES &localDrives, Drive_Types eDriveType, bool bonlywithmedia)
{
WCHAR* pcBuffer= NULL;
DWORD dwStrLength= GetLogicalDriveStringsW( 0, pcBuffer );
if( dwStrLength != 0 )
{
CMediaSource share;
dwStrLength+= 1;
pcBuffer= new WCHAR [dwStrLength];
GetLogicalDriveStringsW( dwStrLength, pcBuffer );
int iPos= 0;
WCHAR cVolumeName[100];
do{
int nResult = 0;
cVolumeName[0]= L'\0';
CStdStringW strWdrive = pcBuffer + iPos;
UINT uDriveType= GetDriveTypeW( strWdrive.c_str() );
// don't use GetVolumeInformation on fdd's as the floppy controller may be enabled in Bios but
// no floppy HW is attached which causes huge delays.
if(!strWdrive.Left(2).Equals(L"A:") && !strWdrive.Left(2).Equals(L"B:"))
nResult= GetVolumeInformationW( strWdrive.c_str() , cVolumeName, 100, 0, 0, 0, NULL, 25);
if(nResult == 0 && bonlywithmedia)
{
iPos += (wcslen( pcBuffer + iPos) + 1 );
continue;
}
// usb hard drives are reported as DRIVE_FIXED and won't be returned by queries with REMOVABLE_DRIVES set
// so test for usb hard drives
/*if(uDriveType == DRIVE_FIXED)
{
if(IsUsbDevice(strWdrive))
uDriveType = DRIVE_REMOVABLE;
}*/
share.strPath= share.strName= "";
bool bUseDCD= false;
if( uDriveType > DRIVE_UNKNOWN &&
(( eDriveType == ALL_DRIVES && (uDriveType == DRIVE_FIXED || uDriveType == DRIVE_REMOTE || uDriveType == DRIVE_CDROM || uDriveType == DRIVE_REMOVABLE )) ||
( eDriveType == LOCAL_DRIVES && (uDriveType == DRIVE_FIXED || uDriveType == DRIVE_REMOTE)) ||
( eDriveType == REMOVABLE_DRIVES && ( uDriveType == DRIVE_REMOVABLE )) ||
( eDriveType == DVD_DRIVES && ( uDriveType == DRIVE_CDROM ))))
{
//share.strPath = strWdrive;
g_charsetConverter.wToUTF8(strWdrive, share.strPath);
if( cVolumeName[0] != L'\0' )
g_charsetConverter.wToUTF8(cVolumeName, share.strName);
if( uDriveType == DRIVE_CDROM && nResult)
{
// Has to be the same as auto mounted devices
share.strStatus = share.strName;
share.strName = share.strPath;
share.m_iDriveType= CMediaSource::SOURCE_TYPE_LOCAL;
bUseDCD= true;
}
else
{
// Lets show it, like Windows explorer do... TODO: sorting should depend on driver letter
switch(uDriveType)
{
case DRIVE_CDROM:
share.strName.Format( "%s (%s)", share.strPath, g_localizeStrings.Get(218));
break;
case DRIVE_REMOVABLE:
if(share.strName.IsEmpty())
share.strName.Format( "%s (%s)", g_localizeStrings.Get(437), share.strPath);
break;
case DRIVE_UNKNOWN:
share.strName.Format( "%s (%s)", share.strPath, g_localizeStrings.Get(13205));
break;
default:
if(share.strName.empty())
share.strName = share.strPath;
else
share.strName.Format( "%s (%s)", share.strPath, share.strName);
break;
}
}
share.strName.Replace(":\\",":");
share.strPath.Replace(":\\",":");
share.m_ignore= true;
if( !bUseDCD )
{
share.m_iDriveType= (
( uDriveType == DRIVE_FIXED ) ? CMediaSource::SOURCE_TYPE_LOCAL :
( uDriveType == DRIVE_REMOTE ) ? CMediaSource::SOURCE_TYPE_REMOTE :
( uDriveType == DRIVE_CDROM ) ? CMediaSource::SOURCE_TYPE_DVD :
( uDriveType == DRIVE_REMOVABLE ) ? CMediaSource::SOURCE_TYPE_REMOVABLE :
CMediaSource::SOURCE_TYPE_UNKNOWN );
}
AddOrReplace(localDrives, share);
}
iPos += (wcslen( pcBuffer + iPos) + 1 );
} while( wcslen( pcBuffer + iPos ) > 0 );
delete[] pcBuffer;
}
}
std::string CWIN32Util::GetFirstOpticalDrive()
{
VECSOURCES vShare;
std::string strdevice = "\\\\.\\";
CWIN32Util::GetDrivesByType(vShare, DVD_DRIVES);
if(!vShare.empty())
return strdevice.append(vShare.front().strPath);
else
return "";
}
bool CWIN32Util::IsAudioCD(const CStdString& strPath)
{
CStdString strDrive = strPath;
char cVolumenName[256];
char cFSName[256];
URIUtils::AddSlashAtEnd(strDrive);
if(GetVolumeInformation(strDrive.c_str(), cVolumenName, 255, NULL, NULL, NULL, cFSName, 255)==0)
return false;
return (strncmp(cFSName,"CDFS",4)==0 && strncmp(cVolumenName,"Audio CD",4)==0);
}
CStdString CWIN32Util::GetDiskLabel(const CStdString& strPath)
{
CStdString strDrive = strPath;
char cVolumenName[128];
char cFSName[128];
URIUtils::AddSlashAtEnd(strDrive);
if(GetVolumeInformation(strDrive.c_str(), cVolumenName, 127, NULL, NULL, NULL, cFSName, 127)==0)
return "";
return CStdString(cVolumenName).TrimRight(" ");
}
extern "C"
{
FILE *fopen_utf8(const char *_Filename, const char *_Mode)
{
CStdStringW wfilename, wmode;
g_charsetConverter.utf8ToW(_Filename, wfilename, false);
wmode = _Mode;
return _wfopen(wfilename.c_str(), wmode.c_str());
}
}
extern "C" {
/*
* Ported from NetBSD to Windows by Ron Koenderink, 2007
*/
/* $NetBSD: strptime.c,v 1.25 2005/11/29 03:12:00 christos Exp $ */
/*-
* Copyright (c) 1997, 1998, 2005 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code was contributed to The NetBSD Foundation by Klaus Klein.
* Heavily optimised by David Laight
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#if !defined(_WIN32)
#include <sys/cdefs.h>
#endif
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: strptime.c,v 1.25 2005/11/29 03:12:00 christos Exp $");
#endif
#if !defined(_WIN32)
#include "namespace.h"
#include <sys/localedef.h>
#else
typedef unsigned char u_char;
typedef unsigned int uint;