forked from adobe/brackets-app
/
brackets_extensions.mm
479 lines (397 loc) · 16.9 KB
/
brackets_extensions.mm
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
#include "brackets_extensions.h"
#import <Cocoa/Cocoa.h>
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
// Error values. These MUST be in sync with the error values
// in brackets_extensions.js
static const int NO_ERROR = 0;
static const int ERR_UNKNOWN = 1;
static const int ERR_INVALID_PARAMS = 2;
static const int ERR_NOT_FOUND = 3;
static const int ERR_CANT_READ = 4;
static const int ERR_UNSUPPORTED_ENCODING = 5;
static const int ERR_CANT_WRITE = 6;
static const int ERR_OUT_OF_SPACE = 7;
static const int ERR_NOT_FILE = 8;
static const int ERR_NOT_DIRECTORY = 9;
class BracketsExtensionHandler : public CefV8Handler
{
public:
BracketsExtensionHandler() : lastError(0) {}
virtual ~BracketsExtensionHandler() {}
// Execute with the specified argument list and return value. Return true if
// the method was handled.
virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
int errorCode = -1;
if (name == "ShowOpenDialog")
{
// showOpenDialog(allowMultipleSelection, chooseDirectory, title, initialPath, fileTypes)
//
// Inputs:
// allowMultipleSelection - Boolean
// chooseDirectory - Boolean. Choose directory if true, choose file if false
// title - title of the dialog
// initialPath - initial path to display. Pass "" to show default.
// fileTypes - space-delimited string of file extensions, without '.'
//
// Output:
// "" if no file/directory was selected
// JSON-formatted array of full path names if one or more files were selected
//
// Error:
// NO_ERROR
// ERR_INVALID_PARAMS - invalid parameters
errorCode = ExecuteShowOpenDialog(arguments, retval, exception);
}
else if (name == "ReadDir")
{
// ReadDir(path)
//
// Inputs:
// path - full path of directory to be read
//
// Outputs:
// JSON-formatted array of the names of the files in the directory, not including '.' and '..'.
//
// Error:
// NO_ERROR - no error
// ERR_UNKNOWN - unknown error
// ERR_INVALID_PARAMS - invalid parameters
// ERR_NOT_FOUND - directory could not be found
// ERR_CANT_READ - could not read directory
errorCode = ExecuteReadDir(arguments, retval, exception);
}
else if (name == "IsDirectory")
{
// IsDirectory(path)
//
// Inputs:
// path - full path of directory to test
//
// Outputs:
// true if path is a directory, false if error or it is a file
//
// Error:
// NO_ERROR - no error
// ERR_INVALID_PARAMS - invalid parameters
// ERR_NOT_FOUND - file/directory could not be found
errorCode = ExecuteIsDirectory(arguments, retval, exception);
}
else if (name == "ReadFile")
{
// ReadFile(path, encoding)
//
// Inputs:
// path - full path of file to read
// encoding - 'utf8' is the only supported format for now
//
// Output:
// String - contents of the file
//
// Error:
// NO_ERROR - no error
// ERR_UNKNOWN - unknown error
// ERR_INVALID_PARAMS - invalid parameters
// ERR_NOT_FOUND - file could not be found
// ERR_CANT_READ - file could not be read
// ERR_UNSUPPORTED_ENCODING - unsupported encoding value
errorCode = ExecuteReadFile(arguments, retval, exception);
}
else if (name == "WriteFile")
{
// WriteFile(path, data, encoding)
//
// Inputs:
// path - full path of file to write
// data - data to write to file
// encoding - 'utf8' is the only supported format for now
//
// Output:
// none
//
// Error:
// NO_ERROR - no error
// ERR_UNKNOWN - unknown error
// ERR_INVALID_PARAMS - invalid parameters
// ERR_UNSUPPORTED_ENCODING - unsupported encoding value
// ERR_CANT_WRITE - file could not be written
// ERR_OUT_OF_SPACE - no more space for file
errorCode = ExecuteWriteFile(arguments, retval, exception);
}
else if (name == "SetPosixPermissions")
{
// SetPosixPermissions(path, mode)
//
// Inputs:
// path - full path of file or directory
// mode - permissions for file or directory, in numeric format
//
// Output:
// none
//
// Errors
// NO_ERROR - no error
// ERR_UNKNOWN - unknown error
// ERR_INVALID_PARAMS - invalid parameters
// ERR_NOT_FOUND - can't file file/directory
// ERR_UNSUPPORTED_ENCODING - unsupported encoding value
// ERR_CANT_WRITE - permissions could not be written
errorCode = ExecuteSetPosixPermissions(arguments, retval, exception);
}
else if (name == "DeleteFileOrDirectory")
{
// DeleteFileOrDirectory(path)
//
// Inputs:
// path - full path of file or directory
//
// Ouput:
// none
//
// Errors
// NO_ERROR - no error
// ERR_UNKNOWN - unknown error
// ERR_INVALID_PARAMS - invalid parameters
// ERR_NOT_FOUND - can't file file/directory
errorCode = ExecuteDeleteFileOrDirectory(arguments, retval, exception);
}
else if (name == "GetLastError")
{
// Special case private native function to return the last error code.
retval = CefV8Value::CreateInt(lastError);
// Early exit since we are just returning the last error code
return true;
}
if (errorCode != -1)
{
lastError = errorCode;
return true;
}
return false;
}
int ExecuteShowOpenDialog(const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (arguments.size() != 5 || !arguments[2]->IsString() || !arguments[3]->IsString() || !arguments[4]->IsString())
return ERR_INVALID_PARAMS;
// Grab the arguments
bool allowsMultipleSelection = arguments[0]->GetBoolValue();
bool canChooseDirectories = arguments[1]->GetBoolValue();
bool canChooseFiles = !canChooseDirectories;
std::string title = arguments[2]->GetStringValue();
std::string initialPath = arguments[3]->GetStringValue();
std::string fileTypesStr = arguments[4]->GetStringValue();
std::string result = "";
NSArray* allowedFileTypes = nil;
if (fileTypesStr != "")
{
// fileTypesStr is a Space-delimited string
allowedFileTypes =
[[NSString stringWithUTF8String:fileTypesStr.c_str()]
componentsSeparatedByString:@" "];
}
// Initialize the dialog
NSOpenPanel* openPanel = [NSOpenPanel openPanel];
[openPanel setCanChooseFiles:canChooseFiles];
[openPanel setCanChooseDirectories:canChooseDirectories];
[openPanel setAllowsMultipleSelection:allowsMultipleSelection];
[openPanel setTitle: [NSString stringWithUTF8String:title.c_str()]];
if (initialPath != "")
[openPanel setDirectoryURL:[NSURL URLWithString:[NSString stringWithUTF8String:initialPath.c_str()]]];
[openPanel setAllowedFileTypes:allowedFileTypes];
if ([openPanel runModal] == NSOKButton)
{
NSArrayToJSONString([openPanel filenames], result);
}
retval = CefV8Value::CreateString(result);
return NO_ERROR;
}
int ExecuteReadDir(const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (arguments.size() != 1 || !arguments[0]->IsString())
return ERR_INVALID_PARAMS;
std::string pathStr = arguments[0]->GetStringValue();
std::string result = "";
NSString* path = [NSString stringWithUTF8String:pathStr.c_str()];
NSError* error = nil;
NSArray* contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
if (contents != nil)
{
NSArrayToJSONString(contents, result);
retval = CefV8Value::CreateString(result);
return NO_ERROR;
}
return ConvertNSErrorCode(error);
}
int ExecuteIsDirectory(const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (arguments.size() != 1 || !arguments[0]->IsString())
return ERR_INVALID_PARAMS;
std::string pathStr = arguments[0]->GetStringValue();
NSString* path = [NSString stringWithUTF8String:pathStr.c_str()];
BOOL isDirectory;
if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDirectory])
{
retval = CefV8Value::CreateBool(isDirectory);
return NO_ERROR;
}
return ERR_NOT_FOUND;
}
int ExecuteReadFile(const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (arguments.size() != 2 || !arguments[0]->IsString() || !arguments[1]->IsString())
return ERR_INVALID_PARAMS;
std::string pathStr = arguments[0]->GetStringValue();
std::string encodingStr = arguments[1]->GetStringValue();
NSString* path = [NSString stringWithUTF8String:pathStr.c_str()];
NSStringEncoding encoding;
NSError* error = nil;
if (encodingStr == "utf8")
encoding = NSUTF8StringEncoding;
else
return ERR_UNSUPPORTED_ENCODING;
NSString* contents = [NSString stringWithContentsOfFile:path encoding:encoding error:&error];
if (contents)
{
retval = CefV8Value::CreateString([contents UTF8String]);
return NO_ERROR;
}
return ConvertNSErrorCode(error);
}
int ExecuteWriteFile(const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (arguments.size() != 3 || !arguments[0]->IsString() || !arguments[1]->IsString() || !arguments[2]->IsString())
return ERR_INVALID_PARAMS;
std::string pathStr = arguments[0]->GetStringValue();
std::string contentsStr = arguments[1]->GetStringValue();
std::string encodingStr = arguments[2]->GetStringValue();
NSString* path = [NSString stringWithUTF8String:pathStr.c_str()];
NSString* contents = [NSString stringWithUTF8String:contentsStr.c_str()];
NSStringEncoding encoding;
NSError* error = nil;
if (encodingStr == "utf8")
encoding = NSUTF8StringEncoding;
else
return ERR_UNSUPPORTED_ENCODING;
[contents writeToFile:path atomically:YES encoding:encoding error:&error];
return ConvertNSErrorCode(error);
}
int ExecuteSetPosixPermissions(const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (arguments.size() != 2 || !arguments[0]->IsString() || !arguments[1]->IsInt())
return ERR_INVALID_PARAMS;
std::string pathStr = arguments[0]->GetStringValue();
int mode = arguments[1]->GetIntValue();
NSError* error = nil;
NSString* path = [NSString stringWithUTF8String:pathStr.c_str()];
NSDictionary* attrs = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:mode] forKey:NSFilePosixPermissions];
if ([[NSFileManager defaultManager] setAttributes:attrs ofItemAtPath:path error:&error])
return NO_ERROR;
return ConvertNSErrorCode(error);
}
int ExecuteDeleteFileOrDirectory(const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (arguments.size() != 1 || !arguments[0]->IsString())
return ERR_INVALID_PARAMS;
std::string pathStr = arguments[0]->GetStringValue();
NSError* error = nil;
NSString* path = [NSString stringWithUTF8String:pathStr.c_str()];
if ([[NSFileManager defaultManager] removeItemAtPath:path error:&error])
return NO_ERROR;
return ConvertNSErrorCode(error);
}
// Escapes characters that have special meaning in JSON
void EscapeJSONString(const std::string& str, std::string& result) {
result = "";
for(size_t pos = 0; pos != str.size(); ++pos) {
switch(str[pos]) {
case '\a': result.append("\\a"); break;
case '\b': result.append("\\b"); break;
case '\f': result.append("\\f"); break;
case '\n': result.append("\\n"); break;
case '\r': result.append("\\r"); break;
case '\t': result.append("\\t"); break;
case '\v': result.append("\\v"); break;
// Note: single quotes are OK for JSON
case '\"': result.append("\\\""); break; // double quote
case '\\': result.append("\\\\"); break; // backslash
default: result.append( 1, str[pos]); break;
}
}
}
void NSArrayToJSONString(NSArray* array, std::string& result)
{
int numItems = [array count];
std::string escapedStr = "";
result = "[";
std::string item;
for (int i = 0; i < numItems; i++)
{
result += "\"";
item = [[array objectAtIndex:i] UTF8String];
EscapeJSONString(item, escapedStr);
result += escapedStr + "\"";
if (i < numItems - 1)
result += ", ";
}
result += "]";
}
int ConvertNSErrorCode(NSError* error)
{
if (!error)
return NO_ERROR;
switch ([error code])
{
case NSFileNoSuchFileError:
case NSFileReadNoSuchFileError:
return ERR_NOT_FOUND;
break;
case NSFileReadNoPermissionError:
return ERR_CANT_READ;
break;
case NSFileReadInapplicableStringEncodingError:
return ERR_UNSUPPORTED_ENCODING;
break;
case NSFileWriteNoPermissionError:
return ERR_CANT_WRITE;
break;
case NSFileWriteOutOfSpaceError:
return ERR_OUT_OF_SPACE;
break;
}
// Unknown error
return ERR_UNKNOWN;
}
private:
int lastError;
IMPLEMENT_REFCOUNTING(BracketsExtensionHandler);
};
void InitBracketsExtensions()
{
// Register a V8 extension with JavaScript code that calls native
// methods implemented in BracketsExtensionHandler.
// The JavaScript code for the extension lives in Resources/brackets_extensions.js
NSString* sourcePath = [[NSBundle mainBundle] pathForResource:@"brackets_extensions" ofType:@"js"];
NSString* jsSource = [[NSString alloc] initWithContentsOfFile:sourcePath encoding:NSUTF8StringEncoding error:nil];
CefRegisterExtension("brackets", [jsSource UTF8String], new BracketsExtensionHandler());
[jsSource release];
}