This repository was archived by the owner on Sep 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 601
Expand file tree
/
Copy pathappshell_extensions_win.cpp
More file actions
369 lines (302 loc) · 11.3 KB
/
appshell_extensions_win.cpp
File metadata and controls
369 lines (302 loc) · 11.3 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
/*
* Copyright (c) 2012 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.h"
#include <algorithm>
#include <CommDlg.h>
#include <ShlObj.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <sys/stat.h>
// Forward declarations for functions at the bottom of this file
void FixFilename(ExtensionString& filename);
void EscapeJSONString(const std::wstring& str, std::wstring& finalResult);
int ConvertErrnoCode(int errorCode, bool isReading = true);
int ConvertWinErrorCode(int errorCode, bool isReading = true);
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;
}
int32 ShowOpenDialog(bool allowMulitpleSelection,
bool chooseDirectory,
ExtensionString title,
ExtensionString initialDirectory,
ExtensionString fileTypes,
CefRefPtr<CefListValue>& selectedFiles)
{
wchar_t szFile[MAX_PATH];
szFile[0] = 0;
FixFilename(initialDirectory);
// TODO (issue #64) - This method should be using IFileDialog instead of the
/* outdated SHGetPathFromIDList and GetOpenFileName.
Useful function to parse fileTypesStr:
template<class T>
int inline findAndReplaceString(T& source, const T& find, const T& replace)
{
int num=0;
int fLen = find.size();
int rLen = replace.size();
for (int pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
{
num++;
source.replace(pos, fLen, replace);
}
return num;
}
*/
if (chooseDirectory) {
BROWSEINFO bi = {0};
bi.hwndOwner = GetActiveWindow();
bi.lpszTitle = title.c_str();
bi.ulFlags = BIF_NEWDIALOGSTYLE;
bi.lpfn = SetInitialPathCallback;
bi.lParam = (LPARAM)initialDirectory.c_str();
LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
if (pidl != 0) {
if (SHGetPathFromIDList(pidl, szFile)) {
// Add directory path to the result
selectedFiles->SetString(0, szFile);
}
IMalloc* pMalloc = NULL;
SHGetMalloc(&pMalloc);
if (pMalloc) {
pMalloc->Free(pidl);
pMalloc->Release();
}
}
} else {
OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.hwndOwner = GetActiveWindow();
ofn.lStructSize = sizeof(ofn);
ofn.lpstrFile = szFile;
ofn.nMaxFile = MAX_PATH;
// 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 (allowMulitpleSelection)
ofn.Flags |= OFN_ALLOWMULTISELECT;
if (GetOpenFileName(&ofn)) {
if (allowMulitpleSelection) {
// 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') {
selectedFiles->SetString(0, ExtensionString(dir));
} else {
// Multiple files are selected
wchar_t fullPath[MAX_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)
selectedFiles->SetString(fileIndex, ExtensionString(fullPath));
// Go to the start of the next file name
i += file.length() + 1;
}
}
} else {
// If multiple files are not allowed, add the single file
selectedFiles->SetString(0, szFile);
}
}
}
return NO_ERROR;
}
int32 ReadDir(ExtensionString path, CefRefPtr<CefListValue>& directoryContents)
{
FixFilename(path);
path += L"\\*";
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 '..'
if (!wcscmp(ffd.cFileName, L".") || !wcscmp(ffd.cFileName, L".."))
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 GetFileModificationTime(ExtensionString filename, uint32& modtime, bool& isDir)
{
FixFilename(filename);
DWORD dwAttr = GetFileAttributes(filename.c_str());
if (dwAttr == INVALID_FILE_ATTRIBUTES) {
return ConvertWinErrorCode(GetLastError());
}
isDir = ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0);
struct _stat buffer;
if(_wstat(filename.c_str(), &buffer) == -1) {
return ConvertErrnoCode(errno);
}
modtime = buffer.st_mtime;
return NO_ERROR;
}
int32 ReadFile(ExtensionString filename, ExtensionString encoding, std::string& contents)
{
FixFilename(filename);
if (encoding != L"utf8")
return ERR_UNSUPPORTED_ENCODING;
DWORD dwAttr;
dwAttr = GetFileAttributes(filename.c_str());
if (INVALID_FILE_ATTRIBUTES == dwAttr)
return ConvertWinErrorCode(GetLastError());
if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
return ERR_CANT_READ;
HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
int32 error = NO_ERROR;
if (INVALID_HANDLE_VALUE == hFile)
return ConvertWinErrorCode(GetLastError());
DWORD dwFileSize = GetFileSize(hFile, NULL);
DWORD dwBytesRead;
char* buffer = (char*)malloc(dwFileSize);
if (buffer && ReadFile(hFile, buffer, dwFileSize, &dwBytesRead, NULL)) {
contents = std::string(buffer, dwFileSize);
}
else {
if (!buffer)
error = ERR_UNKNOWN;
else
error = ConvertWinErrorCode(GetLastError());
}
CloseHandle(hFile);
if (buffer)
free(buffer);
return error;
}
int32 WriteFile(ExtensionString filename, std::string contents, ExtensionString encoding)
{
FixFilename(filename);
if (encoding != L"utf8")
return ERR_UNSUPPORTED_ENCODING;
HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwBytesWritten;
int error = NO_ERROR;
if (INVALID_HANDLE_VALUE == hFile)
return ConvertWinErrorCode(GetLastError(), false);
// TODO (issue 67) - Should write to temp file and handle encoding
if (!WriteFile(hFile, contents.c_str(), contents.length(), &dwBytesWritten, NULL)) {
error = ConvertWinErrorCode(GetLastError(), false);
}
CloseHandle(hFile);
return error;
}
int32 SetPosixPermissions(ExtensionString filename, int32 mode)
{
FixFilename(filename);
DWORD dwAttr = GetFileAttributes(filename.c_str());
if (dwAttr == INVALID_FILE_ATTRIBUTES)
return ERR_NOT_FOUND;
if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
return NO_ERROR;
bool write = (mode & 0200) != 0;
bool read = (mode & 0400) != 0;
int mask = (write ? _S_IWRITE : 0) | (read ? _S_IREAD : 0);
if (_wchmod(filename.c_str(), mask) == -1) {
return ConvertErrnoCode(errno);
}
return NO_ERROR;
}
int32 DeleteFileOrDirectory(ExtensionString filename)
{
FixFilename(filename);
if (!DeleteFile(filename.c_str()))
return ConvertWinErrorCode(GetLastError());
return NO_ERROR;
}
void FixFilename(ExtensionString& filename)
{
// Convert '/' to '\'
replace(filename.begin(), filename.end(), '/', '\\');
}
// Maps errors from errno.h to the brackets error codes
// found in brackets_extensions.js
int ConvertErrnoCode(int errorCode, bool isReading)
{
switch (errorCode) {
case NO_ERROR:
return NO_ERROR;
case EINVAL:
return ERR_INVALID_PARAMS;
case ENOENT:
return ERR_NOT_FOUND;
default:
return ERR_UNKNOWN;
}
}
// Maps errors from WinError.h to the brackets error codes
// found in brackets_extensions.js
int ConvertWinErrorCode(int errorCode, bool isReading)
{
switch (errorCode) {
case NO_ERROR:
return NO_ERROR;
case ERROR_PATH_NOT_FOUND:
case ERROR_FILE_NOT_FOUND:
return ERR_NOT_FOUND;
case ERROR_ACCESS_DENIED:
return isReading ? ERR_CANT_READ : ERR_CANT_WRITE;
case ERROR_WRITE_PROTECT:
return ERR_CANT_WRITE;
case ERROR_HANDLE_DISK_FULL:
return ERR_OUT_OF_SPACE;
default:
return ERR_UNKNOWN;
}
}