This repository has been archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 614
/
appshell_extensions_win.cpp
2455 lines (2050 loc) · 79.2 KB
/
appshell_extensions_win.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) 2012 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#include "appshell_extensions_platform.h"
#include "appshell/appshell_helpers.h"
#include "native_menu_model.h"
#include <algorithm>
#include <CommDlg.h>
#include <Psapi.h>
#include <ShellAPI.h>
#include <ShlObj.h>
#include <Shlwapi.h>
#include <Shobjidl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <windows.h>
#include <intrin.h>
#include <iphlpapi.h>
#include "config.h"
#include <codecvt>
#define CLOSING_PROP L"CLOSING"
#define UNICODE_MINUS 0x2212
#define UNICODE_LEFT_ARROW 0x2190
#define UNICODE_DOWN_ARROW 0x2193
#define UTF8_BOM "\xEF\xBB\xBF"
// Forward declarations for functions at the bottom of this file
void ConvertToNativePath(ExtensionString& filename);
void ConvertToUnixPath(ExtensionString& filename);
void RemoveTrailingSlash(ExtensionString& filename);
int ConvertErrnoCode(int errorCode, bool isReading = true);
int ConvertWinErrorCode(int errorCode, bool isReading = true);
static std::wstring GetPathToLiveBrowser();
static bool ConvertToShortPathName(std::wstring & path);
time_t FiletimeToTime(FILETIME const& ft);
// Redraw timeout variables. See the comment above ScheduleMenuRedraw for details.
const DWORD kMenuRedrawTimeout = 100;
UINT_PTR redrawTimerId = NULL;
CefRefPtr<CefBrowser> redrawBrowser;
extern HINSTANCE hInst;
extern HACCEL hAccelTable;
extern std::wstring gFilesToOpen;
// constants
#define MAX_LOADSTRING 100
///////////////////////////////////////////////////////////////////////////////
// LiveBrowserMgrWin
class LiveBrowserMgrWin
{
public:
static LiveBrowserMgrWin* GetInstance();
static void Shutdown();
bool IsChromeWindow(HWND hwnd);
bool IsAnyChromeWindowsRunning();
void CloseLiveBrowserKillTimers();
void CloseLiveBrowserFireCallback(int valToSend);
static BOOL CALLBACK EnumChromeWindowsCallback(HWND hwnd, LPARAM userParam);
static void CALLBACK CloseLiveBrowserTimerCallback( HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime);
static void CALLBACK CloseLiveBrowserAsyncCallback( HWND hwnd, UINT uMsg, ULONG_PTR dwData, LRESULT lResult );
CefRefPtr<CefProcessMessage> GetCloseCallback() { return m_closeLiveBrowserCallback; }
UINT GetCloseHeartbeatTimerId() { return m_closeLiveBrowserHeartbeatTimerId; }
UINT GetCloseTimeoutTimerId() { return m_closeLiveBrowserTimeoutTimerId; }
void SetCloseCallback(CefRefPtr<CefProcessMessage> closeLiveBrowserCallback)
{ m_closeLiveBrowserCallback = closeLiveBrowserCallback; }
void SetBrowser(CefRefPtr<CefBrowser> browser)
{ m_browser = browser; }
void SetCloseHeartbeatTimerId(UINT closeLiveBrowserHeartbeatTimerId)
{ m_closeLiveBrowserHeartbeatTimerId = closeLiveBrowserHeartbeatTimerId; }
void SetCloseTimeoutTimerId(UINT closeLiveBrowserTimeoutTimerId)
{ m_closeLiveBrowserTimeoutTimerId = closeLiveBrowserTimeoutTimerId; }
private:
// private so this class cannot be instantiated externally
LiveBrowserMgrWin();
virtual ~LiveBrowserMgrWin();
UINT m_closeLiveBrowserHeartbeatTimerId;
UINT m_closeLiveBrowserTimeoutTimerId;
CefRefPtr<CefProcessMessage> m_closeLiveBrowserCallback;
CefRefPtr<CefBrowser> m_browser;
static LiveBrowserMgrWin* s_instance;
};
LiveBrowserMgrWin::LiveBrowserMgrWin()
: m_closeLiveBrowserHeartbeatTimerId(0)
, m_closeLiveBrowserTimeoutTimerId(0)
{
}
LiveBrowserMgrWin::~LiveBrowserMgrWin()
{
}
LiveBrowserMgrWin* LiveBrowserMgrWin::GetInstance()
{
if (!s_instance)
s_instance = new LiveBrowserMgrWin();
return s_instance;
}
void LiveBrowserMgrWin::Shutdown()
{
delete s_instance;
s_instance = NULL;
}
bool LiveBrowserMgrWin::IsChromeWindow(HWND hwnd)
{
if( !hwnd ) {
return false;
}
//Find the path that opened this window
DWORD processId = 0;
::GetWindowThreadProcessId(hwnd, &processId);
HANDLE processHandle = ::OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId);
if( !processHandle ) {
return false;
}
DWORD modulePathBufSize = MAX_UNC_PATH+1;
WCHAR modulePathBuf[MAX_UNC_PATH+1];
DWORD modulePathSize = ::GetModuleFileNameEx(processHandle, NULL, modulePathBuf, modulePathBufSize );
::CloseHandle(processHandle);
processHandle = NULL;
std::wstring modulePath(modulePathBuf, modulePathSize);
//See if this path is the same as what we want to launch
std::wstring appPath = GetPathToLiveBrowser();
if( !ConvertToShortPathName(modulePath) || !ConvertToShortPathName(appPath) ) {
return false;
}
if(0 != _wcsicmp(appPath.c_str(), modulePath.c_str()) ){
return false;
}
//looks good
return true;
}
struct EnumChromeWindowsCallbackData
{
bool closeWindow;
int numberOfFoundWindows;
};
BOOL CALLBACK LiveBrowserMgrWin::EnumChromeWindowsCallback(HWND hwnd, LPARAM userParam)
{
if( !hwnd || !s_instance) {
return FALSE;
}
EnumChromeWindowsCallbackData* cbData = reinterpret_cast<EnumChromeWindowsCallbackData*>(userParam);
if(!cbData) {
return FALSE;
}
if (!s_instance->IsChromeWindow(hwnd)) {
return TRUE;
}
cbData->numberOfFoundWindows++;
//This window belongs to the instance of the browser we're interested in, tell it to close
if( cbData->closeWindow ) {
::SendMessageCallback(hwnd, WM_CLOSE, NULL, NULL, CloseLiveBrowserAsyncCallback, NULL);
}
return TRUE;
}
bool LiveBrowserMgrWin::IsAnyChromeWindowsRunning()
{
EnumChromeWindowsCallbackData cbData = {0};
cbData.numberOfFoundWindows = 0;
cbData.closeWindow = false;
::EnumWindows(EnumChromeWindowsCallback, (LPARAM)&cbData);
return( cbData.numberOfFoundWindows != 0 );
}
void LiveBrowserMgrWin::CloseLiveBrowserKillTimers()
{
if (m_closeLiveBrowserHeartbeatTimerId) {
::KillTimer(NULL, m_closeLiveBrowserHeartbeatTimerId);
m_closeLiveBrowserHeartbeatTimerId = 0;
}
if (m_closeLiveBrowserTimeoutTimerId) {
::KillTimer(NULL, m_closeLiveBrowserTimeoutTimerId);
m_closeLiveBrowserTimeoutTimerId = 0;
}
}
void LiveBrowserMgrWin::CloseLiveBrowserFireCallback(int valToSend)
{
CefRefPtr<CefListValue> responseArgs = m_closeLiveBrowserCallback->GetArgumentList();
// kill the timers
CloseLiveBrowserKillTimers();
// Set common response args (callbackId and error)
responseArgs->SetInt(1, valToSend);
// Send response
m_browser->SendProcessMessage(PID_RENDERER, m_closeLiveBrowserCallback);
// Clear state
m_closeLiveBrowserCallback = NULL;
m_browser = NULL;
}
void CALLBACK LiveBrowserMgrWin::CloseLiveBrowserTimerCallback( HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime)
{
if( !s_instance ) {
::KillTimer(NULL, idEvent);
return;
}
int retVal = NO_ERROR;
if( s_instance->IsAnyChromeWindowsRunning() )
{
retVal = ERR_UNKNOWN;
//if this is the heartbeat timer, wait for another beat
if (idEvent == s_instance->m_closeLiveBrowserHeartbeatTimerId) {
return;
}
}
//notify back to the app
s_instance->CloseLiveBrowserFireCallback(retVal);
}
void CALLBACK LiveBrowserMgrWin::CloseLiveBrowserAsyncCallback( HWND hwnd, UINT uMsg, ULONG_PTR dwData, LRESULT lResult )
{
if( !s_instance ) {
return;
}
//If there are no more versions of chrome, then fire the callback
if( !s_instance->IsAnyChromeWindowsRunning() ) {
s_instance->CloseLiveBrowserFireCallback(NO_ERROR);
}
else if(s_instance->m_closeLiveBrowserHeartbeatTimerId == 0){
//start a heartbeat timer to see if it closes after the message returned
s_instance->m_closeLiveBrowserHeartbeatTimerId = ::SetTimer(NULL, 0, 30, CloseLiveBrowserTimerCallback);
}
}
LiveBrowserMgrWin* LiveBrowserMgrWin::s_instance = NULL;
static int CALLBACK SetInitialPathCallback(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
if (BFFM_INITIALIZED == uMsg && NULL != lpData)
{
SendMessage(hWnd, BFFM_SETSELECTION, TRUE, lpData);
}
return 0;
}
static std::wstring GetPathToLiveBrowser()
{
HKEY hKey;
// First, look at the "App Paths" registry key for a "chrome.exe" entry. This only
// checks for installs for all users. If Chrome is only installed for the current user,
// we fall back to the code below.
if (ERROR_SUCCESS == RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe",
0, KEY_READ, &hKey)) {
wchar_t wpath[MAX_UNC_PATH] = {0};
DWORD length = MAX_UNC_PATH;
RegQueryValueEx(hKey, NULL, NULL, NULL, (LPBYTE)wpath, &length);
RegCloseKey(hKey);
return std::wstring(wpath);
}
// We didn't get an "App Paths" entry. This could be because Chrome was only installed for
// the current user, or because Chrome isn't installed at all.
// Look for Chrome.exe at C:\Users\{USERNAME}\AppData\Local\Google\Chrome\Application\chrome.exe
TCHAR localAppPath[MAX_UNC_PATH] = {0};
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, localAppPath);
std::wstring appPath(localAppPath);
appPath += L"\\Google\\Chrome\\Application\\chrome.exe";
return appPath;
}
static bool ConvertToShortPathName(std::wstring & path)
{
DWORD shortPathBufSize = MAX_UNC_PATH+1;
WCHAR shortPathBuf[MAX_UNC_PATH+1];
DWORD finalShortPathSize = ::GetShortPathName(path.c_str(), shortPathBuf, shortPathBufSize);
if( finalShortPathSize == 0 ) {
return false;
}
path.assign(shortPathBuf, finalShortPathSize);
return true;
}
int32 OpenLiveBrowser(ExtensionString argURL, bool enableRemoteDebugging)
{
std::wstring appPath = GetPathToLiveBrowser();
std::wstring args = appPath;
if (enableRemoteDebugging) {
std::wstring profilePath(appshell::AppGetSupportDirectory());
profilePath += L"\\live-dev-profile";
args += L" --user-data-dir=\"";
args += profilePath;
args += L"\" --disk-cache-size=250000000 --no-first-run --no-default-browser-check --disable-default-apps --allow-file-access-from-files --remote-debugging-port=9222 ";
} else {
args += L" ";
}
args += argURL;
// Args must be mutable
int argsBufSize = args.length() +1;
std::vector<WCHAR> argsBuf;
argsBuf.resize(argsBufSize);
wcscpy(&argsBuf[0], args.c_str());
STARTUPINFO si = {0};
si.cb = sizeof(si);
PROCESS_INFORMATION pi = {0};
// Launch cmd.exe and pass in the arguments
if (!CreateProcess(NULL, &argsBuf[0], NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
return ConvertWinErrorCode(GetLastError());
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return NO_ERROR;
}
void CloseLiveBrowser(CefRefPtr<CefBrowser> browser, CefRefPtr<CefProcessMessage> response)
{
LiveBrowserMgrWin* liveBrowserMgr = LiveBrowserMgrWin::GetInstance();
if (liveBrowserMgr->GetCloseCallback() != NULL) {
// We can only handle a single async callback at a time. If there is already one that hasn't fired then
// we kill it now and get ready for the next.
liveBrowserMgr->CloseLiveBrowserFireCallback(ERR_UNKNOWN);
}
liveBrowserMgr->SetCloseCallback(response);
liveBrowserMgr->SetBrowser(browser);
EnumChromeWindowsCallbackData cbData = {0};
cbData.numberOfFoundWindows = 0;
cbData.closeWindow = true;
::EnumWindows(LiveBrowserMgrWin::EnumChromeWindowsCallback, (LPARAM)&cbData);
if (cbData.numberOfFoundWindows == 0) {
liveBrowserMgr->CloseLiveBrowserFireCallback(NO_ERROR);
} else if (liveBrowserMgr->GetCloseCallback()) {
// set a timeout for up to 10 seconds to close the browser
liveBrowserMgr->SetCloseTimeoutTimerId( ::SetTimer(NULL, 0, 10 * 1000, LiveBrowserMgrWin::CloseLiveBrowserTimerCallback) );
}
}
static BOOL ResolveAppPathCommon(const ExtensionString& lpszKey, const ExtensionString& lpszVal, ExtensionString& appPath)
{
HKEY keyRoot = NULL;
BOOL result = FALSE;
ULONG regKey(REG_SZ);
if (::RegOpenKeyEx(HKEY_CLASSES_ROOT, lpszKey.c_str(), 0, KEY_QUERY_VALUE, &keyRoot) == ERROR_SUCCESS)
{
TCHAR editorPath[255];
ULONG fTypeSize = 255;
if (::RegQueryValueEx(keyRoot, lpszVal.c_str(), NULL, ®Key, (LPBYTE)editorPath, &fTypeSize) == ERROR_SUCCESS)
{
if (editorPath != L"")
{
appPath = editorPath;
//appPath = appPath.substr(appPath.find_last_of(L"/\\") + 1);
int iExe = appPath.find(L".exe");
if (iExe == -1)
iExe = appPath.find(L".EXE");
if (iExe != -1)
appPath = appPath.substr(0, iExe+4);
if (appPath[0] == '\"')
appPath = appPath.substr(1);
result = TRUE;
}
}
::RegCloseKey(keyRoot);
}
return result;
}
static BOOL ResolveAppPathFromProgID(const ExtensionString& lpszProgID, ExtensionString& appPath)
{
ExtensionString key = lpszProgID + L"\\shell\\open\\command";
if (!ResolveAppPathCommon(key, L"", appPath))
{
key = lpszProgID + L"\\Application";
if (ResolveAppPathCommon(key, L"AppUserModelID", appPath)) {
appPath = appPath.substr(0, appPath.find(L"_"));
return true;
}
return false;
}
return true;
}
BOOL GetShellDefaultOpenWithProgPath(const ExtensionString& fileExt, ExtensionString &appPath)
{
HKEY extKey = NULL;
ExtensionString key = fileExt;
BOOL result = FALSE;
ULONG regKey(REG_SZ);
if (fileExt.empty())
return false;
if (fileExt[0] != '.')
key = L"." + fileExt;
key = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\" + key + L"\\UserChoice";
if (::RegOpenKeyEx(HKEY_CURRENT_USER, key.c_str(), 0, KEY_QUERY_VALUE, &extKey) == ERROR_SUCCESS)
{
TCHAR editorPath[255];
ULONG fTypeSize = 255;
if (::RegQueryValueEx(extKey, L"Progid", NULL, ®Key, (LPBYTE)editorPath, &fTypeSize) == ERROR_SUCCESS)
{
result = ResolveAppPathFromProgID(editorPath, appPath);
}
::RegCloseKey(extKey);
}
return result;
}
BOOL GetLegacyWin32SystemEditor(const ExtensionString& fileExt, ExtensionString &appPath)
{
HKEY rootKey;
ULONG regKey(REG_SZ);
ExtensionString key = fileExt;
if (fileExt.empty())
return false;
if (fileExt[0] != '.')
key = L"." + key;
// find the key for the file extension
if (RegOpenKeyEx(HKEY_CLASSES_ROOT, key.c_str(), 0, KEY_QUERY_VALUE, &rootKey) == ERROR_SUCCESS)
{
TCHAR nextKeyStr[255];
ULONG strSize = 255;
// get the value of the key
if (RegQueryValueEx(rootKey, L"", NULL, ®Key,
(LPBYTE)nextKeyStr, &strSize) == ERROR_SUCCESS)
{
RegCloseKey(rootKey);
return ResolveAppPathFromProgID(nextKeyStr, appPath);
}
RegCloseKey(rootKey);
}
key = key + L"\\OpenWithProgids";
HKEY extKey;
// find the key for the file extension
if (RegOpenKeyEx(HKEY_CLASSES_ROOT, key.c_str(), 0, KEY_QUERY_VALUE | KEY_READ, &extKey) == ERROR_SUCCESS)
{
TCHAR subKeyStr[255];
ULONG subKeySize = 255;
DWORD index = 0;
LONG err = RegEnumValue(extKey, index, subKeyStr, &subKeySize,
0, 0, 0, NULL);
if (err != ERROR_NO_MORE_ITEMS)
{
RegCloseKey(extKey);
return ResolveAppPathFromProgID(subKeyStr, appPath);
}
RegCloseKey(extKey);
}
return FALSE;
}
int32 getSystemDefaultApp(const ExtensionString& fileTypes, ExtensionString& fileTypesWithdefaultApp)
{
wchar_t* nextPtr;
wchar_t delim[] = L",";
std::vector<ExtensionString> extArray;
ExtensionString separator = L"##";
wchar_t* token = std::wcstok((wchar_t*)fileTypes.c_str(), delim, &nextPtr);
while (token) {
extArray.push_back(token);
token = wcstok(NULL, delim, &nextPtr);
}
for (std::vector<ExtensionString>::const_iterator it = extArray.begin(); it != extArray.end(); ++it) {
ExtensionString appPath;
BOOL result = GetShellDefaultOpenWithProgPath(*it, appPath);
if (!result)
result = GetLegacyWin32SystemEditor(*it, appPath);
if (result)
fileTypesWithdefaultApp = fileTypesWithdefaultApp + *it + separator + appPath + L",";
}
return NO_ERROR;
}
int32 OpenURLInDefaultBrowser(ExtensionString url)
{
DWORD result = (DWORD)ShellExecute(NULL, L"open", url.c_str(), NULL, NULL, SW_SHOWNORMAL);
// If the result > 32, the function suceeded. If the result is <= 32, it is an
// error code.
if (result <= 32)
return ConvertWinErrorCode(result);
return NO_ERROR;
}
int32 ShowOpenDialog(bool allowMultipleSelection,
bool chooseDirectory,
ExtensionString title,
ExtensionString initialDirectory,
ExtensionString fileTypes,
CefRefPtr<CefListValue>& selectedFiles)
{
wchar_t szFile[MAX_UNC_PATH];
szFile[0] = 0;
// Windows common file dialogs can handle Windows path only, not Unix path.
// ofn.lpstrInitialDir also needs Windows path on XP and not Unix path.
ConvertToNativePath(initialDirectory);
if (chooseDirectory) {
IFileDialog *pfd;
if (SUCCEEDED(CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd)))) {
// configure the dialog to Select Folders only
DWORD dwOptions;
if (SUCCEEDED(pfd->GetOptions(&dwOptions))) {
pfd->SetOptions(dwOptions | FOS_PICKFOLDERS | FOS_DONTADDTORECENT);
IShellItem *shellItem = NULL;
if (SUCCEEDED(SHCreateItemFromParsingName(initialDirectory.c_str(), 0, IID_IShellItem, reinterpret_cast<void**>(&shellItem))))
pfd->SetFolder(shellItem);
pfd->SetTitle(title.c_str());
if (SUCCEEDED(pfd->Show(GetActiveWindow()))) {
IShellItem *psi;
if (SUCCEEDED(pfd->GetResult(&psi))) {
LPWSTR lpwszName = NULL;
if(SUCCEEDED(psi->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING, (LPWSTR*)&lpwszName))) {
// Add directory path to the result
std::wstring wstrName(lpwszName);
ExtensionString pathName(wstrName);
ConvertToUnixPath(pathName);
selectedFiles->SetString(0, pathName);
::CoTaskMemFree(lpwszName);
}
psi->Release();
}
}
if (shellItem != NULL)
shellItem->Release();
}
pfd->Release();
}
} else {
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.hwndOwner = GetActiveWindow();
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_UNC_PATH;
ofn.lpstrTitle = title.c_str();
// TODO (issue #65) - Use passed in file types. Note, when fileTypesStr is null, all files should be shown
/* findAndReplaceString( fileTypesStr, std::string(" "), std::string(";*."));
LPCWSTR allFilesFilter = L"All Files\0*.*\0\0";*/
ofn.lpstrFilter = L"All Files\0*.*\0Web Files\0*.js;*.css;*.htm;*.html\0\0";
ofn.lpstrInitialDir = initialDirectory.c_str();
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER;
if (allowMultipleSelection)
ofn.Flags |= OFN_ALLOWMULTISELECT;
if (GetOpenFileName(&ofn)) {
if (allowMultipleSelection) {
// Multiple selection encodes the files differently
// If multiple files are selected, the first null terminator
// signals end of directory that the files are all in
std::wstring dir(szFile);
// Check for two null terminators, which signal that only one file
// was selected
if (szFile[dir.length() + 1] == '\0') {
ExtensionString filePath(dir);
ConvertToUnixPath(filePath);
selectedFiles->SetString(0, filePath);
} else {
// Multiple files are selected
wchar_t fullPath[MAX_UNC_PATH];
for (int i = (dir.length() + 1), fileIndex = 0; ; fileIndex++) {
// Get the next file name
std::wstring file(&szFile[i]);
// Two adjacent null characters signal the end of the files
if (file.length() == 0)
break;
// The filename is relative to the directory that was specified as
// the first string
if (PathCombine(fullPath, dir.c_str(), file.c_str()) != NULL) {
ExtensionString filePath(fullPath);
ConvertToUnixPath(filePath);
selectedFiles->SetString(fileIndex, filePath);
}
// Go to the start of the next file name
i += file.length() + 1;
}
}
} else {
// If multiple files are not allowed, add the single file
std::wstring filePath(szFile);
ConvertToUnixPath(filePath);
selectedFiles->SetString(0, filePath);
}
}
}
return NO_ERROR;
}
int32 ShowSaveDialog(ExtensionString title,
ExtensionString initialDirectory,
ExtensionString proposedNewFilename,
ExtensionString& absoluteFilepath)
{
ConvertToNativePath(initialDirectory); // Windows common file dlgs require Windows-style paths
// call Windows common file-saveas dialog to prompt for a filename in a writeable location
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.hwndOwner = GetActiveWindow();
ofn.lStructSize = sizeof(ofn);
wchar_t szFile[MAX_UNC_PATH];
wcscpy(szFile, proposedNewFilename.c_str());
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_UNC_PATH;
ofn.lpstrFilter = L"All Files\0*.*\0Web Files\0*.js;*.css;*.htm;*.html\0Text Files\0*.txt\0\0";
ofn.lpstrInitialDir = initialDirectory.c_str();
ofn.Flags = OFN_ENABLESIZING | OFN_NOREADONLYRETURN | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST | OFN_EXPLORER;
if (GetSaveFileName(&ofn)) {
// return the validated filename using Unix-style paths
absoluteFilepath = ofn.lpstrFile;
ConvertToUnixPath(absoluteFilepath);
}
return NO_ERROR;
}
int32 IsNetworkDrive(ExtensionString path, bool& isRemote)
{
if (path.length() == 0) {
return ERR_INVALID_PARAMS;
}
DWORD dwAttr;
dwAttr = GetFileAttributes(path.c_str());
if (INVALID_FILE_ATTRIBUTES == dwAttr)
return ConvertWinErrorCode(GetLastError());
ExtensionString drive = path.substr(0, path.find('/') + 1);
isRemote = GetDriveType(drive.c_str()) == DRIVE_REMOTE;
return NO_ERROR;
}
int32 ReadDir(ExtensionString path, CefRefPtr<CefListValue>& directoryContents)
{
if (path.length() && path[path.length() - 1] != '/')
path += '/';
path += '*';
// Convert to native path to ensure that FindFirstFile and FindNextFile
// function correctly for all paths including paths to a network drive.
ConvertToNativePath(path);
WIN32_FIND_DATA ffd;
HANDLE hFind = FindFirstFile(path.c_str(), &ffd);
std::vector<ExtensionString> resultFiles;
std::vector<ExtensionString> resultDirs;
if (hFind != INVALID_HANDLE_VALUE) {
do {
// Ignore '.' and '..' and system files
if (!wcscmp(ffd.cFileName, L".") || !wcscmp(ffd.cFileName, L"..") ||
(ffd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM))
continue;
// Collect file and directory names separately
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
resultDirs.push_back(ExtensionString(ffd.cFileName));
} else {
resultFiles.push_back(ExtensionString(ffd.cFileName));
}
}
while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
}
else {
return ConvertWinErrorCode(GetLastError());
}
// On Windows, list directories first, then files
size_t i, total = 0;
for (i = 0; i < resultDirs.size(); i++)
directoryContents->SetString(total++, resultDirs[i]);
for (i = 0; i < resultFiles.size(); i++)
directoryContents->SetString(total++, resultFiles[i]);
return NO_ERROR;
}
int32 MakeDir(ExtensionString path, int32 mode)
{
// TODO (issue #1759): honor mode
ConvertToNativePath(path);
int err = SHCreateDirectoryEx(NULL, path.c_str(), NULL);
return ConvertWinErrorCode(err);
}
int32 Rename(ExtensionString oldName, ExtensionString newName)
{
if (!MoveFile(oldName.c_str(), newName.c_str()))
return ConvertWinErrorCode(GetLastError());
return NO_ERROR;
}
// function prototype for GetFinalPathNameByHandleW(), which is unavailable on Windows XP and earlier
typedef DWORD (WINAPI *PFNGFPNBH)(
_In_ HANDLE hFile,
_Out_ LPTSTR lpszFilePath,
_In_ DWORD cchFilePath,
_In_ DWORD dwFlags
);
int32 GetFileInfo(ExtensionString filename, uint32& modtime, bool& isDir, double& size, ExtensionString& realPath)
{
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesEx(filename.c_str(), GetFileExInfoStandard, &fad)) {
return ConvertWinErrorCode(GetLastError());
}
DWORD dwAttr = fad.dwFileAttributes;
isDir = ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0);
modtime = FiletimeToTime(fad.ftLastWriteTime);
LARGE_INTEGER size_tmp;
size_tmp.HighPart = fad.nFileSizeHigh;
size_tmp.LowPart = fad.nFileSizeLow;
size = size_tmp.QuadPart;
realPath = L"";
if (dwAttr & FILE_ATTRIBUTE_REPARSE_POINT) {
// conditionally call GetFinalPathNameByHandleW() if it's available -- Windows Vista or later
HMODULE hDLL = ::GetModuleHandle(TEXT("kernel32.dll"));
PFNGFPNBH pfn = (hDLL != NULL) ? (PFNGFPNBH)::GetProcAddress(hDLL, "GetFinalPathNameByHandleW") : NULL;
if (pfn != NULL) {
HANDLE hFile;
hFile = ::CreateFileW(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
wchar_t pathBuffer[MAX_UNC_PATH + 1];
DWORD nChars;
nChars = (*pfn)(hFile, pathBuffer, MAX_UNC_PATH, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
if (nChars && nChars <= MAX_UNC_PATH) {
// Path returned by GetFilePathNameByHandle starts with "\\?\". Remove from returned value.
realPath = &pathBuffer[4];
// UNC paths start with UNC. Update here, if needed.
if (realPath.find(L"UNC") == 0) {
realPath = L"\\" + ExtensionString(&pathBuffer[7]);
}
ConvertToUnixPath(realPath);
}
::CloseHandle(hFile);
}
// Note: all realPath errors are ignored. If the realPath can't be determined, it should not make the
// stat fail.
}
}
return NO_ERROR;
}
const int BOMLength = 3;
enum CheckedState { CS_UNKNOWN, CS_NO, CS_YES };
typedef struct UTFValidationState {
UTFValidationState () {
data = NULL;
dataLen = 0;
utf1632 = CS_UNKNOWN;
preserveBOM = true;
}
char* data;
DWORD dataLen;
CheckedState utf1632;
bool preserveBOM;
} UTFValidationState;
bool hasBOM(UTFValidationState& validationState)
{
return ((validationState.dataLen >= BOMLength) && (validationState.data[0] == (char)0xEF) && (validationState.data[1] == (char)0xBB) && (validationState.data[2] == (char)0xBF));
}
bool hasUTF16_32(UTFValidationState& validationState)
{
if (validationState.utf1632 == CS_UNKNOWN) {
int flags = IS_TEXT_UNICODE_UNICODE_MASK|IS_TEXT_UNICODE_REVERSE_MASK;
// Check to see if buffer is UTF-16 or UTF-32 with or without a BOM
BOOL test = IsTextUnicode(validationState.data, validationState.dataLen, &flags);
validationState.utf1632 = (test ? CS_YES : CS_NO);
}
return (validationState.utf1632 == CS_YES);
}
void RemoveBOM(UTFValidationState& validationState)
{
if (!validationState.preserveBOM) {
validationState.dataLen -= BOMLength;
CopyMemory (validationState.data, validationState.data+3, validationState.dataLen);
}
}
bool GetBufferAsUTF8(UTFValidationState& validationState)
{
if (validationState.dataLen == 0) {
return true;
}
// if we know it's UTF-16 or UTF-32 then bail
if (hasUTF16_32(validationState)) {
return false;
}
// See if we can convert the data to UNICODE from UTF-8
// if the data isn't UTF-8, this will fail and the result will be 0
int outBuffSize = (validationState.dataLen + 1) * 2;
wchar_t* outBuffer = new wchar_t[outBuffSize];
int result = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, validationState.data, validationState.dataLen, outBuffer, outBuffSize);
delete []outBuffer;
if ((result > 0) && hasBOM(validationState)) {
RemoveBOM(validationState);
}
return (result > 0);
}
bool IsUTFLeadByte(char data)
{
return (((data & 0xF8) == 0xF0) || // 4 BYTE
((data & 0xF0) == 0xE0) || // 3 BYTE
((data & 0xE0) == 0xC0)); // 2 BYTE
}
// we can't validate something that's smaller than 12 bytes
const int kMinValidationLength = 12;
bool quickTestBufferForUTF8(UTFValidationState& validationState)
{
if (validationState.dataLen < kMinValidationLength) {
// we really don't know so just assume it's valid
return true;
}
// if we know it's UTF-16 or UTF-32 then bail
if (hasUTF16_32(validationState)) {
return false;
}
// If it has a UTF-8 BOM, then
// assume it's UTF8
if (hasBOM(validationState)) {
return true;
}
// find the last lead byte and truncate
// the buffer beforehand and check that to avoid
// checking a malformed data stream
for (int i = 1; i < 4; i++) {
int index = (validationState.dataLen - i);
if ((index > 0) && (IsUTFLeadByte(validationState.data[index]))){
validationState.dataLen = index;
break;
}
}
// this will check to see if the we have valid
// UTF8 data in the sample data. This should tell
// us if it's binary or not but doesn't necessarily
// tell us if the file is valid UTF8
return (GetBufferAsUTF8(validationState));
}
typedef std::map<std::string, long> CharSetMap;
// Mapping of CharSet to CodePage
CharSetMap charSetMap =
{
// Below mappings are listed on website