forked from sumatrapdfreader/sumatrapdf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWinUtil.cpp
More file actions
executable file
·1629 lines (1408 loc) · 50.8 KB
/
Copy pathWinUtil.cpp
File metadata and controls
executable file
·1629 lines (1408 loc) · 50.8 KB
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 2015 the SumatraPDF project authors (see AUTHORS file).
License: Simplified BSD (see COPYING.BSD) */
#include "BaseUtil.h"
#include "BitManip.h"
#include "FileUtil.h"
#include "WinDynCalls.h"
#include "WinUtil.h"
#include <mlang.h>
#include "DebugLog.h"
static HFONT gDefaultGuiFont = nullptr;
int RectDx(const RECT& r) {
return r.right - r.left;
}
int RectDy(const RECT& r) {
return r.bottom - r.top;
}
POINT MakePoint(long x, long y) {
POINT p = {x, y};
return p;
}
SIZE MakeSize(long dx, long dy) {
SIZE sz = {dx, dy};
return sz;
}
RECT MakeRect(long x, long y, long dx, long dy) {
RECT r;
r.left = x;
r.right = x + dx;
r.top = y;
r.bottom = y + dy;
return r;
}
void Edit_SelectAll(HWND hwnd) {
Edit_SetSel(hwnd, 0, -1);
}
void ListBox_AppendString_NoSort(HWND hwnd, WCHAR* txt) {
ListBox_InsertString(hwnd, -1, txt);
}
void InitAllCommonControls() {
INITCOMMONCONTROLSEX cex = {0};
cex.dwSize = sizeof(INITCOMMONCONTROLSEX);
cex.dwICC = ICC_WIN95_CLASSES | ICC_DATE_CLASSES | ICC_USEREX_CLASSES | ICC_COOL_CLASSES;
InitCommonControlsEx(&cex);
}
void FillWndClassEx(WNDCLASSEX& wcex, const WCHAR* clsName, WNDPROC wndproc) {
ZeroMemory(&wcex, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.hInstance = GetModuleHandle(nullptr);
wcex.hCursor = GetCursor(IDC_ARROW);
wcex.lpszClassName = clsName;
wcex.lpfnWndProc = wndproc;
}
RECT GetClientRect(HWND hwnd) {
RECT r;
GetClientRect(hwnd, &r);
return r;
}
void MoveWindow(HWND hwnd, RectI rect) {
MoveWindow(hwnd, rect.x, rect.y, rect.dx, rect.dy, TRUE);
}
void MoveWindow(HWND hwnd, RECT* r) {
MoveWindow(hwnd, r->left, r->top, RectDx(*r), RectDy(*r), TRUE);
}
void GetOsVersion(OSVERSIONINFOEX& ver) {
ZeroMemory(&ver, sizeof(ver));
ver.dwOSVersionInfoSize = sizeof(ver);
#pragma warning(push)
#pragma warning(disable : 4996) // 'GetVersionEx': was declared deprecated
#pragma warning(disable : 28159) // Consider using 'IsWindows*' instead of 'GetVersionExW'
// see: https://msdn.microsoft.com/en-us/library/windows/desktop/dn424972(v=vs.85).aspx
// starting with Windows 8.1, GetVersionEx will report a wrong version number
// unless the OS's GUID has been explicitly added to the compatibility manifest
BOOL ok = GetVersionEx((OSVERSIONINFO*)&ver);
#pragma warning(pop)
CrashIf(!ok);
}
// For more versions see OsNameFromVer() in CrashHandler.cpp
bool IsWin10() {
OSVERSIONINFOEX ver;
GetOsVersion(ver);
return ver.dwMajorVersion == 10;
}
bool IsWin7() {
OSVERSIONINFOEX ver;
GetOsVersion(ver);
return ver.dwMajorVersion == 6 && ver.dwMinorVersion == 1;
}
/* Vista is major: 6, minor: 0 */
bool IsVistaOrGreater() {
OSVERSIONINFOEX osver = {0};
ULONGLONG condMask = 0;
osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osver.dwMajorVersion = 6;
VER_SET_CONDITION(condMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
return VerifyVersionInfo(&osver, VER_MAJORVERSION, condMask);
}
bool IsRunningInWow64() {
#ifndef _WIN64
BOOL isWow = FALSE;
if (DynIsWow64Process && DynIsWow64Process(GetCurrentProcess(), &isWow)) {
return isWow == TRUE;
}
#endif
return false;
}
// return true if this is 64-bit executable
bool IsProcess64() {
return 8 == sizeof(void*);
}
// return true if running on a 64-bit OS
bool IsOs64() {
// 64-bit processes can only run on a 64-bit OS,
// 32-bit processes run on a 64-bit OS under WOW64
return IsProcess64() || IsRunningInWow64();
}
// return true if OS and our process have the same arch (i.e. both are 32bit
// or both are 64bit)
bool IsProcessAndOsArchSame() {
return IsProcess64() == IsOs64();
}
void LogLastError(DWORD err) {
// allow to set a breakpoint in release builds
if (0 == err)
err = GetLastError();
char* msgBuf = nullptr;
DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD lang = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);
DWORD res = FormatMessageA(flags, nullptr, err, lang, (LPSTR)&msgBuf, 0, nullptr);
if (!res || !msgBuf)
return;
plogf("LogLastError: %s", msgBuf);
LocalFree(msgBuf);
}
void DbgOutLastError(DWORD err) {
if (0 == err) {
err = GetLastError();
}
if (0 == err) {
return;
}
char* msgBuf = nullptr;
DWORD flags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
DWORD lang = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);
DWORD res = FormatMessageA(flags, nullptr, err, lang, (LPSTR)&msgBuf, 0, nullptr);
if (!res || !msgBuf) {
return;
}
OutputDebugStringA(msgBuf);
LocalFree(msgBuf);
}
// return true if a given registry key (path) exists
bool RegKeyExists(HKEY keySub, const WCHAR* keyName) {
HKEY hKey;
LONG res = RegOpenKey(keySub, keyName, &hKey);
if (ERROR_SUCCESS == res) {
RegCloseKey(hKey);
return true;
}
// return true for key that exists even if it's not
// accessible by us
return ERROR_ACCESS_DENIED == res;
}
// called needs to free() the result
WCHAR* ReadRegStr(HKEY keySub, const WCHAR* keyName, const WCHAR* valName) {
WCHAR* val = nullptr;
REGSAM access = KEY_READ;
HKEY hKey;
TryAgainWOW64:
LONG res = RegOpenKeyEx(keySub, keyName, 0, access, &hKey);
if (ERROR_SUCCESS == res) {
DWORD valLen;
res = RegQueryValueEx(hKey, valName, nullptr, nullptr, nullptr, &valLen);
if (ERROR_SUCCESS == res) {
val = AllocArray<WCHAR>(valLen / sizeof(WCHAR) + 1);
res = RegQueryValueEx(hKey, valName, nullptr, nullptr, (LPBYTE)val, &valLen);
if (ERROR_SUCCESS != res)
str::ReplacePtr(&val, nullptr);
}
RegCloseKey(hKey);
}
if (ERROR_FILE_NOT_FOUND == res && HKEY_LOCAL_MACHINE == keySub && KEY_READ == access) {
// try the (non-)64-bit key as well, as HKLM\Software is not shared between 32-bit and
// 64-bit applications per http://msdn.microsoft.com/en-us/library/aa384253(v=vs.85).aspx
#ifdef _WIN64
access = KEY_READ | KEY_WOW64_32KEY;
#else
access = KEY_READ | KEY_WOW64_64KEY;
#endif
goto TryAgainWOW64;
}
return val;
}
bool WriteRegStr(HKEY keySub, const WCHAR* keyName, const WCHAR* valName, const WCHAR* value) {
DWORD cbData = (DWORD)(str::Len(value) + 1) * sizeof(WCHAR);
LSTATUS res = SHSetValueW(keySub, keyName, valName, REG_SZ, (const void*)value, cbData);
return ERROR_SUCCESS == res;
}
bool ReadRegDWORD(HKEY keySub, const WCHAR* keyName, const WCHAR* valName, DWORD& value) {
DWORD size = sizeof(DWORD);
LSTATUS res = SHGetValue(keySub, keyName, valName, nullptr, &value, &size);
return ERROR_SUCCESS == res && sizeof(DWORD) == size;
}
bool WriteRegDWORD(HKEY keySub, const WCHAR* keyName, const WCHAR* valName, DWORD value) {
LSTATUS res = SHSetValueW(keySub, keyName, valName, REG_DWORD, (const void*)&value, sizeof(DWORD));
return ERROR_SUCCESS == res;
}
bool CreateRegKey(HKEY keySub, const WCHAR* keyName) {
HKEY hKey;
LSTATUS res = RegCreateKeyEx(keySub, keyName, 0, nullptr, 0, KEY_WRITE, nullptr, &hKey, nullptr);
if (res != ERROR_SUCCESS)
return false;
RegCloseKey(hKey);
return true;
}
#pragma warning(push)
#pragma warning(disable : 6248) // "Setting a SECURITY_DESCRIPTOR's DACL to nullptr will result in
// an unprotected object"
// try to remove any access restrictions on the key
// by granting everybody all access to this key (nullptr DACL)
static void ResetRegKeyAcl(HKEY keySub, const WCHAR* keyName) {
HKEY hKey;
LONG res = RegOpenKeyEx(keySub, keyName, 0, WRITE_DAC, &hKey);
if (ERROR_SUCCESS != res)
return;
SECURITY_DESCRIPTOR secdesc;
InitializeSecurityDescriptor(&secdesc, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&secdesc, TRUE, nullptr, TRUE);
RegSetKeySecurity(hKey, DACL_SECURITY_INFORMATION, &secdesc);
RegCloseKey(hKey);
}
#pragma warning(pop)
bool DeleteRegKey(HKEY keySub, const WCHAR* keyName, bool resetACLFirst) {
if (resetACLFirst)
ResetRegKeyAcl(keySub, keyName);
LSTATUS res = SHDeleteKeyW(keySub, keyName);
return ERROR_SUCCESS == res || ERROR_FILE_NOT_FOUND == res;
}
WCHAR* GetSpecialFolder(int csidl, bool createIfMissing) {
if (createIfMissing)
csidl = csidl | CSIDL_FLAG_CREATE;
WCHAR path[MAX_PATH] = {0};
HRESULT res = SHGetFolderPath(nullptr, csidl, nullptr, 0, path);
if (S_OK != res)
return nullptr;
return str::Dup(path);
}
void DisableDataExecution() {
// first try the documented SetProcessDEPPolicy
if (DynSetProcessDEPPolicy) {
DynSetProcessDEPPolicy(PROCESS_DEP_ENABLE);
return;
}
// now try undocumented NtSetInformationProcess
if (DynNtSetInformationProcess) {
DWORD depMode = MEM_EXECUTE_OPTION_DISABLE | MEM_EXECUTE_OPTION_DISABLE_ATL;
DynNtSetInformationProcess(GetCurrentProcess(), PROCESS_EXECUTE_FLAGS, &depMode, sizeof(depMode));
}
}
// Code from http://www.halcyon.com/~ast/dload/guicon.htm
// See https://github.com/benvanik/xenia/issues/228 for the VS2015 fix
void RedirectIOToConsole() {
CONSOLE_SCREEN_BUFFER_INFO coninfo;
AllocConsole();
// make buffer big enough to allow scrolling
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = 500;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
// redirect STDIN, STDOUT and STDERR to the console
#if _MSC_VER < 1900
int hConHandle = _open_osfhandle((intptr_t)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
*stdout = *_fdopen(hConHandle, "w");
hConHandle = _open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT);
*stderr = *_fdopen(hConHandle, "w");
hConHandle = _open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT);
*stdin = *_fdopen(hConHandle, "r");
#else
FILE* con;
freopen_s(&con, "CONOUT$", "w", stdout);
freopen_s(&con, "CONOUT$", "w", stderr);
freopen_s(&con, "CONIN$", "r", stdin);
#endif
// make them unbuffered
setvbuf(stdin, nullptr, _IONBF, 0);
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
}
/* Return the full exe path of my own executable.
Caller needs to free() the result. */
WCHAR* GetExePath() {
WCHAR buf[MAX_PATH] = {0};
GetModuleFileName(nullptr, buf, dimof(buf));
// TODO: is normalization needed here at all?
return path::Normalize(buf);
}
/* Return directory where this executable is located.
Caller needs to free()
*/
WCHAR* GetExeDir() {
std::unique_ptr<WCHAR> path(GetExePath());
return path::GetDir(path.get());
}
/*
Returns ${SystemRoot}\system32 directory.
Caller has to free() the result.
*/
WCHAR* GetSystem32Dir() {
WCHAR buf[1024] = {0};
DWORD n = GetEnvironmentVariableW(L"SystemRoot", &buf[0], dimof(buf));
if ((n == 0) || (n >= dimof(buf))) {
CrashIf(true);
return str::Dup(L"c:\\windows\\system32");
}
return path::Join(buf, L"system32");
}
/*
Returns current directory.
Caller has to free() the result.
*/
WCHAR* GetCurrentDir() {
DWORD n = GetCurrentDirectoryW(0, nullptr);
if (0 == n) {
return nullptr;
}
WCHAR* buf = AllocArray<WCHAR>(n + 1);
DWORD res = GetCurrentDirectoryW(n, buf);
if (0 == res) {
return nullptr;
}
CrashIf(res > n);
return buf;
}
void ChangeCurrDirToSystem32() {
auto sysDir = GetSystem32Dir();
SetCurrentDirectoryW(sysDir);
free(sysDir);
}
static ULARGE_INTEGER FileTimeToLargeInteger(const FILETIME& ft) {
ULARGE_INTEGER res;
res.LowPart = ft.dwLowDateTime;
res.HighPart = ft.dwHighDateTime;
return res;
}
/* Return <ft1> - <ft2> in seconds */
int FileTimeDiffInSecs(const FILETIME& ft1, const FILETIME& ft2) {
ULARGE_INTEGER t1 = FileTimeToLargeInteger(ft1);
ULARGE_INTEGER t2 = FileTimeToLargeInteger(ft2);
// diff is in 100 nanoseconds
LONGLONG diff = t1.QuadPart - t2.QuadPart;
diff = diff / (LONGLONG)10000000L;
return (int)diff;
}
WCHAR* ResolveLnk(const WCHAR* path) {
ScopedMem<OLECHAR> olePath(str::Dup(path));
if (!olePath)
return nullptr;
ScopedComPtr<IShellLink> lnk;
if (!lnk.Create(CLSID_ShellLink))
return nullptr;
ScopedComQIPtr<IPersistFile> file(lnk);
if (!file)
return nullptr;
HRESULT hRes = file->Load(olePath, STGM_READ);
if (FAILED(hRes))
return nullptr;
hRes = lnk->Resolve(nullptr, SLR_UPDATE);
if (FAILED(hRes))
return nullptr;
WCHAR newPath[MAX_PATH] = {0};
hRes = lnk->GetPath(newPath, MAX_PATH, nullptr, 0);
if (FAILED(hRes))
return nullptr;
return str::Dup(newPath);
}
bool CreateShortcut(const WCHAR* shortcutPath, const WCHAR* exePath, const WCHAR* args, const WCHAR* description,
int iconIndex) {
ScopedCom com;
ScopedComPtr<IShellLink> lnk;
if (!lnk.Create(CLSID_ShellLink))
return false;
ScopedComQIPtr<IPersistFile> file(lnk);
if (!file)
return false;
HRESULT hr = lnk->SetPath(exePath);
if (FAILED(hr))
return false;
lnk->SetWorkingDirectory(AutoFreeW(path::GetDir(exePath)));
// lnk->SetShowCmd(SW_SHOWNORMAL);
// lnk->SetHotkey(0);
lnk->SetIconLocation(exePath, iconIndex);
if (args)
lnk->SetArguments(args);
if (description)
lnk->SetDescription(description);
hr = file->Save(shortcutPath, TRUE);
return SUCCEEDED(hr);
}
/* adapted from http://blogs.msdn.com/oldnewthing/archive/2004/09/20/231739.aspx */
IDataObject* GetDataObjectForFile(const WCHAR* filePath, HWND hwnd) {
ScopedComPtr<IShellFolder> pDesktopFolder;
HRESULT hr = SHGetDesktopFolder(&pDesktopFolder);
if (FAILED(hr))
return nullptr;
IDataObject* pDataObject = nullptr;
AutoFreeW lpWPath(str::Dup(filePath));
LPITEMIDLIST pidl;
hr = pDesktopFolder->ParseDisplayName(nullptr, nullptr, lpWPath, nullptr, &pidl, nullptr);
if (SUCCEEDED(hr)) {
ScopedComPtr<IShellFolder> pShellFolder;
LPCITEMIDLIST pidlChild;
hr = SHBindToParent(pidl, IID_IShellFolder, (void**)&pShellFolder, &pidlChild);
if (SUCCEEDED(hr)) {
hr = pShellFolder->GetUIObjectOf(hwnd, 1, &pidlChild, IID_IDataObject, nullptr, (void**)&pDataObject);
if (FAILED(hr))
pDataObject = nullptr;
}
CoTaskMemFree(pidl);
}
return pDataObject;
}
// The result value contains major and minor version in the high resp. the low WORD
DWORD GetFileVersion(const WCHAR* path) {
DWORD fileVersion = 0;
DWORD size = GetFileVersionInfoSize(path, nullptr);
ScopedMem<void> versionInfo(malloc(size));
if (versionInfo && GetFileVersionInfo(path, 0, size, versionInfo)) {
VS_FIXEDFILEINFO* fileInfo;
UINT len;
if (VerQueryValue(versionInfo, L"\\", (LPVOID*)&fileInfo, &len))
fileVersion = fileInfo->dwFileVersionMS;
}
return fileVersion;
}
bool LaunchFile(const WCHAR* path, const WCHAR* params, const WCHAR* verb, bool hidden) {
if (!path)
return false;
SHELLEXECUTEINFO sei = {0};
sei.cbSize = sizeof(sei);
sei.fMask = SEE_MASK_FLAG_NO_UI;
sei.lpVerb = verb;
sei.lpFile = path;
sei.lpParameters = params;
sei.nShow = hidden ? SW_HIDE : SW_SHOWNORMAL;
return ShellExecuteEx(&sei);
}
HANDLE LaunchProcess(const WCHAR* cmdLine, const WCHAR* currDir, DWORD flags) {
PROCESS_INFORMATION pi = {0};
STARTUPINFO si = {0};
si.cb = sizeof(si);
// CreateProcess() might modify cmd line argument, so make a copy
// in case caller provides a read-only string
AutoFreeW cmdLineCopy(str::Dup(cmdLine));
if (!CreateProcessW(nullptr, cmdLineCopy, nullptr, nullptr, FALSE, flags, nullptr, currDir, &si, &pi))
return nullptr;
CloseHandle(pi.hThread);
return pi.hProcess;
}
/* Ensure that the rectangle is at least partially in the work area on a
monitor. The rectangle is shifted into the work area if necessary. */
RectI ShiftRectToWorkArea(RectI rect, bool bFully) {
RectI monitor = GetWorkAreaRect(rect);
if (rect.y + rect.dy <= monitor.y || bFully && rect.y < monitor.y)
/* Rectangle is too far above work area */
rect.Offset(0, monitor.y - rect.y);
else if (rect.y >= monitor.y + monitor.dy || bFully && rect.y + rect.dy > monitor.y + monitor.dy)
/* Rectangle is too far below */
rect.Offset(0, monitor.y - rect.y + monitor.dy - rect.dy);
if (rect.x + rect.dx <= monitor.x || bFully && rect.x < monitor.x)
/* Too far left */
rect.Offset(monitor.x - rect.x, 0);
else if (rect.x >= monitor.x + monitor.dx || bFully && rect.x + rect.dx > monitor.x + monitor.dx)
/* Too far right */
rect.Offset(monitor.x - rect.x + monitor.dx - rect.dx, 0);
return rect;
}
RectI GetWorkAreaRect(RectI rect) {
MONITORINFO mi = {0};
mi.cbSize = sizeof mi;
RECT tmpRect = rect.ToRECT();
HMONITOR monitor = MonitorFromRect(&tmpRect, MONITOR_DEFAULTTONEAREST);
BOOL ok = GetMonitorInfo(monitor, &mi);
if (!ok)
SystemParametersInfo(SPI_GETWORKAREA, 0, &mi.rcWork, 0);
return RectI::FromRECT(mi.rcWork);
}
// returns the dimensions the given window has to have in order to be a fullscreen window
RectI GetFullscreenRect(HWND hwnd) {
MONITORINFO mi = {0};
mi.cbSize = sizeof(mi);
if (GetMonitorInfo(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &mi))
return RectI::FromRECT(mi.rcMonitor);
// fall back to the primary monitor
return RectI(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
}
static BOOL CALLBACK GetMonitorRectProc(HMONITOR hMonitor, HDC hdc, LPRECT rcMonitor, LPARAM data) {
UNUSED(hMonitor);
UNUSED(hdc);
RectI* rcAll = (RectI*)data;
*rcAll = rcAll->Union(RectI::FromRECT(*rcMonitor));
return TRUE;
}
// returns the smallest rectangle that covers the entire virtual screen (all monitors)
RectI GetVirtualScreenRect() {
RectI result(0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
EnumDisplayMonitors(nullptr, nullptr, GetMonitorRectProc, (LPARAM)&result);
return result;
}
void PaintRect(HDC hdc, const RectI& rect) {
MoveToEx(hdc, rect.x, rect.y, nullptr);
LineTo(hdc, rect.x + rect.dx - 1, rect.y);
LineTo(hdc, rect.x + rect.dx - 1, rect.y + rect.dy - 1);
LineTo(hdc, rect.x, rect.y + rect.dy - 1);
LineTo(hdc, rect.x, rect.y);
}
void PaintLine(HDC hdc, const RectI& rect) {
MoveToEx(hdc, rect.x, rect.y, nullptr);
LineTo(hdc, rect.x + rect.dx, rect.y + rect.dy);
}
void DrawCenteredText(HDC hdc, const RectI& r, const WCHAR* txt, bool isRTL) {
SetBkMode(hdc, TRANSPARENT);
RECT tmpRect = r.ToRECT();
DrawText(hdc, txt, -1, &tmpRect,
DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX | (isRTL ? DT_RTLREADING : 0));
}
void DrawCenteredText(HDC hdc, const RECT& r, const WCHAR* txt, bool isRTL) {
RectI rc = RectI::FromRECT(r);
DrawCenteredText(hdc, rc, txt, isRTL);
}
/* Return size of a text <txt> in a given <hwnd>, taking into account its font */
SizeI TextSizeInHwnd(HWND hwnd, const WCHAR* txt, HFONT font) {
SIZE sz;
size_t txtLen = str::Len(txt);
HDC dc = GetWindowDC(hwnd);
/* GetWindowDC() returns dc with default state, so we have to first set
window's current font into dc */
if (font == nullptr) {
font = (HFONT)SendMessage(hwnd, WM_GETFONT, 0, 0);
}
HGDIOBJ prev = SelectObject(dc, font);
GetTextExtentPoint32(dc, txt, (int)txtLen, &sz);
SelectObject(dc, prev);
ReleaseDC(hwnd, dc);
return SizeI(sz.cx, sz.cy);
}
// TODO: unify with TextSizeInHwnd
/* Return size of a text <txt> in a given <hwnd>, taking into account its font */
SIZE TextSizeInHwnd2(HWND hwnd, const WCHAR* txt, HFONT font) {
SIZE sz;
size_t txtLen = str::Len(txt);
HDC dc = GetWindowDC(hwnd);
/* GetWindowDC() returns dc with default state, so we have to first set
window's current font into dc */
if (font == nullptr) {
font = (HFONT)SendMessage(hwnd, WM_GETFONT, 0, 0);
}
HGDIOBJ prev = SelectObject(dc, font);
GetTextExtentPoint32(dc, txt, (int)txtLen, &sz);
SelectObject(dc, prev);
ReleaseDC(hwnd, dc);
return sz;
}
/* Return size of a text <txt> in a given <hdc>, taking into account its font */
SizeI TextSizeInDC(HDC hdc, const WCHAR* txt) {
SIZE sz;
size_t txtLen = str::Len(txt);
GetTextExtentPoint32(hdc, txt, (int)txtLen, &sz);
return SizeI(sz.cx, sz.cy);
}
bool IsCursorOverWindow(HWND hwnd) {
POINT pt;
GetCursorPos(&pt);
WindowRect rcWnd(hwnd);
return rcWnd.Contains(PointI(pt.x, pt.y));
}
bool GetCursorPosInHwnd(HWND hwnd, PointI& posOut) {
POINT pt;
if (!GetCursorPos(&pt))
return false;
if (!ScreenToClient(hwnd, &pt))
return false;
posOut = PointI(pt.x, pt.y);
return true;
}
void CenterDialog(HWND hDlg, HWND hParent) {
if (!hParent)
hParent = GetParent(hDlg);
RectI rcDialog = WindowRect(hDlg);
rcDialog.Offset(-rcDialog.x, -rcDialog.y);
RectI rcOwner = WindowRect(hParent ? hParent : GetDesktopWindow());
RectI rcRect = rcOwner;
rcRect.Offset(-rcRect.x, -rcRect.y);
// center dialog on its parent window
rcDialog.Offset(rcOwner.x + (rcRect.x - rcDialog.x + rcRect.dx - rcDialog.dx) / 2,
rcOwner.y + (rcRect.y - rcDialog.y + rcRect.dy - rcDialog.dy) / 2);
// ensure that the dialog is fully visible on one monitor
rcDialog = ShiftRectToWorkArea(rcDialog, true);
SetWindowPos(hDlg, 0, rcDialog.x, rcDialog.y, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
}
/* Get the name of default printer or nullptr if not exists.
The caller needs to free() the result */
WCHAR* GetDefaultPrinterName() {
WCHAR buf[512];
DWORD bufSize = dimof(buf);
if (GetDefaultPrinter(buf, &bufSize))
return str::Dup(buf);
return nullptr;
}
bool CopyTextToClipboard(const WCHAR* text, bool appendOnly) {
CrashIf(!text);
if (!text)
return false;
if (!appendOnly) {
if (!OpenClipboard(nullptr))
return false;
EmptyClipboard();
}
size_t n = str::Len(text) + 1;
HGLOBAL handle = GlobalAlloc(GMEM_MOVEABLE, n * sizeof(WCHAR));
if (handle) {
WCHAR* globalText = (WCHAR*)GlobalLock(handle);
if (globalText) {
str::BufSet(globalText, n, text);
}
GlobalUnlock(handle);
SetClipboardData(CF_UNICODETEXT, handle);
}
if (!appendOnly)
CloseClipboard();
return handle != nullptr;
}
static bool SetClipboardImage(HBITMAP hbmp) {
if (!hbmp)
return false;
BITMAP bmpInfo;
GetObject(hbmp, sizeof(BITMAP), &bmpInfo);
HANDLE h = nullptr;
if (bmpInfo.bmBits != nullptr) {
// GDI+ produced HBITMAPs are DIBs instead of DDBs which
// aren't correctly handled by the clipboard, so create a
// clipboard-safe clone
ScopedGdiObj<HBITMAP> ddbBmp((HBITMAP)CopyImage(hbmp, IMAGE_BITMAP, bmpInfo.bmWidth, bmpInfo.bmHeight, 0));
h = SetClipboardData(CF_BITMAP, ddbBmp);
} else {
h = SetClipboardData(CF_BITMAP, hbmp);
}
return h != nullptr;
}
bool CopyImageToClipboard(HBITMAP hbmp, bool appendOnly) {
if (!appendOnly) {
if (!OpenClipboard(nullptr))
return false;
EmptyClipboard();
}
bool ok = SetClipboardImage(hbmp);
if (!appendOnly)
CloseClipboard();
return ok;
}
void ToggleWindowStyle(HWND hwnd, DWORD flag, bool enable, int type) {
DWORD style = GetWindowLong(hwnd, type);
DWORD newStyle;
if (enable)
newStyle = style | flag;
else
newStyle = style & ~flag;
if (newStyle != style)
SetWindowLong(hwnd, type, newStyle);
}
RectI ChildPosWithinParent(HWND hwnd) {
POINT pt = {0, 0};
ClientToScreen(GetParent(hwnd), &pt);
WindowRect rc(hwnd);
rc.Offset(-pt.x, -pt.y);
return rc;
}
HFONT GetDefaultGuiFont() {
if (!gDefaultGuiFont) {
NONCLIENTMETRICS ncm = {0};
ncm.cbSize = sizeof(ncm);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0);
gDefaultGuiFont = CreateFontIndirect(&ncm.lfMessageFont);
}
return gDefaultGuiFont;
}
long GetDefaultGuiFontSize() {
NONCLIENTMETRICS ncm = {0};
ncm.cbSize = sizeof(ncm);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0);
return -ncm.lfMessageFont.lfHeight;
}
DoubleBuffer::DoubleBuffer(HWND hwnd, RectI rect)
: hTarget(hwnd), rect(rect), hdcBuffer(nullptr), doubleBuffer(nullptr) {
hdcCanvas = ::GetDC(hwnd);
if (rect.IsEmpty())
return;
doubleBuffer = CreateCompatibleBitmap(hdcCanvas, rect.dx, rect.dy);
if (!doubleBuffer)
return;
hdcBuffer = CreateCompatibleDC(hdcCanvas);
if (!hdcBuffer)
return;
if (rect.x != 0 || rect.y != 0) {
SetGraphicsMode(hdcBuffer, GM_ADVANCED);
XFORM ctm = {1.0, 0, 0, 1.0, (float)-rect.x, (float)-rect.y};
SetWorldTransform(hdcBuffer, &ctm);
}
DeleteObject(SelectObject(hdcBuffer, doubleBuffer));
}
DoubleBuffer::~DoubleBuffer() {
DeleteObject(doubleBuffer);
DeleteDC(hdcBuffer);
ReleaseDC(hTarget, hdcCanvas);
}
void DoubleBuffer::Flush(HDC hdc) {
assert(hdc != hdcBuffer);
if (hdcBuffer)
BitBlt(hdc, rect.x, rect.y, rect.dx, rect.dy, hdcBuffer, 0, 0, SRCCOPY);
}
DeferWinPosHelper::DeferWinPosHelper() {
hdwp = ::BeginDeferWindowPos(32);
}
DeferWinPosHelper::~DeferWinPosHelper() {
End();
}
void DeferWinPosHelper::End() {
if (hdwp) {
::EndDeferWindowPos(hdwp);
hdwp = nullptr;
}
}
void DeferWinPosHelper::SetWindowPos(HWND hWnd, HWND hWndInsertAfter, int x, int y, int cx, int cy, UINT uFlags) {
hdwp = ::DeferWindowPos(hdwp, hWnd, hWndInsertAfter, x, y, cx, cy, uFlags);
}
void DeferWinPosHelper::MoveWindow(HWND hWnd, int x, int y, int cx, int cy, BOOL bRepaint) {
UINT uFlags = SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER;
if (!bRepaint)
uFlags |= SWP_NOREDRAW;
this->SetWindowPos(hWnd, 0, x, y, cx, cy, uFlags);
}
void DeferWinPosHelper::MoveWindow(HWND hWnd, RectI r) {
this->MoveWindow(hWnd, r.x, r.y, r.dx, r.dy);
}
namespace win {
namespace menu {
void SetChecked(HMENU m, UINT id, bool isChecked) {
CheckMenuItem(m, id, MF_BYCOMMAND | (isChecked ? MF_CHECKED : MF_UNCHECKED));
}
bool SetEnabled(HMENU m, UINT id, bool isEnabled) {
BOOL ret = EnableMenuItem(m, id, MF_BYCOMMAND | (isEnabled ? MF_ENABLED : MF_GRAYED));
return ret != -1;
}
void Remove(HMENU m, UINT id) {
RemoveMenu(m, id, MF_BYCOMMAND);
}
void Empty(HMENU m) {
while (RemoveMenu(m, 0, MF_BYPOSITION))
;
}
void SetText(HMENU m, UINT id, WCHAR* s) {
MENUITEMINFO mii = {0};
mii.cbSize = sizeof(mii);
mii.fMask = MIIM_STRING;
mii.fType = MFT_STRING;
mii.dwTypeData = s;
mii.cch = (UINT)str::Len(s);
SetMenuItemInfoW(m, id, FALSE, &mii);
}
/* Make a string safe to be displayed as a menu item
(preserving all & so that they don't get swallowed)
if no change is needed, the string is returned as is,
else it's also saved in newResult for automatic freeing */
const WCHAR* ToSafeString(AutoFreeW& s) {
auto str = s.Get();
if (!str::FindChar(str, '&')) {
return str;
}
s.Set(str::Replace(str, L"&", L"&&"));
return s.Get();
}
}
}
HFONT CreateSimpleFont(HDC hdc, const WCHAR* fontName, int fontSize) {
LOGFONT lf = {0};
lf.lfWidth = 0;
lf.lfHeight = -MulDiv(fontSize, GetDeviceCaps(hdc, LOGPIXELSY), USER_DEFAULT_SCREEN_DPI);
lf.lfItalic = FALSE;
lf.lfUnderline = FALSE;
lf.lfStrikeOut = FALSE;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfOutPrecision = OUT_TT_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfPitchAndFamily = DEFAULT_PITCH;
str::BufSet(lf.lfFaceName, dimof(lf.lfFaceName), fontName);
lf.lfWeight = FW_DONTCARE;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
return CreateFontIndirect(&lf);
}
IStream* CreateStreamFromData(const void* data, size_t len) {
if (!data)
return nullptr;
ScopedComPtr<IStream> stream;
if (FAILED(CreateStreamOnHGlobal(nullptr, TRUE, &stream)))
return nullptr;
ULONG written;
if (FAILED(stream->Write(data, (ULONG)len, &written)) || written != len)
return nullptr;
LARGE_INTEGER zero = {0};
stream->Seek(zero, STREAM_SEEK_SET, nullptr);
stream->AddRef();
return stream;
}
static HRESULT GetDataFromStream(IStream* stream, void** data, ULONG* len) {
if (!stream)
return E_INVALIDARG;
STATSTG stat;
HRESULT res = stream->Stat(&stat, STATFLAG_NONAME);
if (FAILED(res))
return res;
if (stat.cbSize.HighPart > 0 || stat.cbSize.LowPart > UINT_MAX - sizeof(WCHAR) - 1)
return E_OUTOFMEMORY;
ULONG n = stat.cbSize.LowPart;
// zero-terminate the stream's content, so that it could be
// used directly as either a char* or a WCHAR* string
char* d = AllocArray<char>(n + sizeof(WCHAR) + 1);
if (!d)
return E_OUTOFMEMORY;
ULONG read;
LARGE_INTEGER zero = {0};
stream->Seek(zero, STREAM_SEEK_SET, nullptr);
res = stream->Read(d, stat.cbSize.LowPart, &read);
if (FAILED(res) || read != n) {
free(d);
return res;
}
*len = n;
*data = d;
return S_OK;
}
void* GetDataFromStream(IStream* stream, size_t* len, HRESULT* res_opt) {
void* data;
ULONG size;
HRESULT res = GetDataFromStream(stream, &data, &size);
if (len)
*len = size;
if (res_opt)
*res_opt = res;
if (FAILED(res))
return nullptr;
return data;
}
bool ReadDataFromStream(IStream* stream, void* buffer, size_t len, size_t offset) {
LARGE_INTEGER off;