This repository was archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathNativeFileSystem.js
More file actions
1277 lines (1115 loc) · 50.5 KB
/
NativeFileSystem.js
File metadata and controls
1277 lines (1115 loc) · 50.5 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 (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.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50*/
/*global $, define, brackets, InvalidateStateError, window */
/**
* Generally NativeFileSystem mimics the File-System API working draft:
* http://www.w3.org/TR/2011/WD-file-system-api-20110419
*
* A more recent version of the specs can be found at:
* http://www.w3.org/TR/2012/WD-file-system-api-20120417
*
* Other relevant w3 specs related to this API are:
* http://www.w3.org/TR/2011/WD-FileAPI-20111020
* http://www.w3.org/TR/2011/WD-file-writer-api-20110419
* http://www.w3.org/TR/progress-events
*
* The w3 entry point requestFileSystem is replaced with our own requestNativeFileSystem.
*
* The current implementation is incomplete and notably does not
* support the Blob data type and synchronous APIs. DirectoryEntry
* and FileEntry read/write capabilities are mostly implemented, but
* delete is not. File writing is limited to UTF-8 text.
*
*
* Basic usage examples:
*
* - CREATE A DIRECTORY
* var directoryEntry = ... // NativeFileSystem.DirectoryEntry
* directoryEntry.getDirectory(path, {create: true});
*
*
* - CHECK IF A FILE OR FOLDER EXISTS
* NativeFileSystem.resolveNativeFileSystemPath(path
* , function(entry) { console.log("Path for " + entry.name + " resolved"); }
* , function(err) { console.log("Error resolving path: " + err.name); });
*
*
* - READ A FILE
*
* (Using file/NativeFileSystem)
* reader = new NativeFileSystem.FileReader();
* fileEntry.file(function (file) {
* reader.onload = function (event) {
* var text = event.target.result;
* };
*
* reader.onerror = function (event) {
* };
*
* reader.readAsText(file, Encodings.UTF8);
* });
*
* (Using file/FileUtils)
* FileUtils.readAsText(fileEntry).done(function (rawText, readTimestamp) {
* console.log(rawText);
* }).fail(function (err) {
* console.log("Error reading text: " + err.name);
* });
*
*
* - WRITE TO A FILE
*
* (Using file/NativeFileSystem)
* writer = fileEntry.createWriter(function (fileWriter) {
* fileWriter.onwriteend = function (e) {
* };
*
* fileWriter.onerror = function (err) {
* };
*
* fileWriter.write(text);
* });
*
* (Using file/FileUtils)
* FileUtils.writeText(text, fileEntry).done(function () {
* console.log("Text successfully updated");
* }).fail(function (err) {
* console.log("Error writing text: " + err.name);
* ]);
*
*
* - PROMPT THE USER TO SELECT FILES OR FOLDERS WITH OPERATING SYSTEM'S FILE OPEN DIALOG
* NativeFileSystem.showOpenDialog(true, true, "Choose a file...", null, function(files) {}, function(err) {});
*/
define(function (require, exports, module) {
"use strict";
var Async = require("utils/Async"),
NativeFileError = require("file/NativeFileError");
var NativeFileSystem = {
/**
* Amount of time we wait for async calls to return (in milliseconds)
* Not all async calls are wrapped with something that times out and
* calls the error callback. Timeouts are not specified in the W3C spec.
* @const
* @type {number}
*/
ASYNC_TIMEOUT: 2000,
ASYNC_NETWORK_TIMEOUT: 20000, // 20 seconds for reading files from network drive
/**
* Shows a modal dialog for selecting and opening files
*
* @param {boolean} allowMultipleSelection Allows selecting more than one file at a time
* @param {boolean} chooseDirectories Allows directories to be opened
* @param {string} title The title of the dialog
* @param {string} initialPath The folder opened inside the window initially. If initialPath
* is not set, or it doesn't exist, the window would show the last
* browsed folder depending on the OS preferences
* @param {Array.<string>} fileTypes List of extensions that are allowed to be opened. A null value
* allows any extension to be selected.
* @param {function(Array.<string>)} successCallback Callback function for successful operations.
Receives an array with the selected paths as first parameter.
* @param {function(DOMError)=} errorCallback Callback function for error operations.
*/
showOpenDialog: function (allowMultipleSelection,
chooseDirectories,
title,
initialPath,
fileTypes,
successCallback,
errorCallback) {
if (!successCallback) {
return;
}
var files = brackets.fs.showOpenDialog(
allowMultipleSelection,
chooseDirectories,
title,
initialPath,
fileTypes,
function (err, data) {
if (!err) {
successCallback(data);
} else if (errorCallback) {
errorCallback(new NativeFileError(NativeFileSystem._fsErrorToDOMErrorName(err)));
}
}
);
},
/**
* Implementation of w3 requestFileSystem entry point
* @param {string} path Path to a directory. This directory will serve as the root of the
* FileSystem instance.
* @param {function(DirectoryEntry)} successCallback Callback function for successful operations.
* Receives a DirectoryEntry pointing to the path
* @param {function(DOMError)=} errorCallback Callback function for errors, including permission errors.
*/
requestNativeFileSystem: function (path, successCallback, errorCallback) {
brackets.fs.stat(path, function (err, data) {
if (!err) {
successCallback(new NativeFileSystem.FileSystem(path));
} else if (errorCallback) {
errorCallback(new NativeFileError(NativeFileSystem._fsErrorToDOMErrorName(err)));
}
});
},
/**
* NativeFileSystem implementation of LocalFileSystem.resolveLocalFileSystemURL()
*
* @param {string} path A URL referring to a local file in a filesystem accessable via this API.
* @param {function(Entry)} successCallback Callback function for successful operations.
* @param {function(DOMError)=} errorCallback Callback function for error operations.
*/
resolveNativeFileSystemPath: function (path, successCallback, errorCallback) {
brackets.fs.stat(path, function (err, stats) {
if (!err) {
var entry;
if (stats.isDirectory()) {
entry = new NativeFileSystem.DirectoryEntry(path);
} else {
entry = new NativeFileSystem.FileEntry(path);
}
successCallback(entry);
} else if (errorCallback) {
errorCallback(new NativeFileError(NativeFileSystem._fsErrorToDOMErrorName(err)));
}
});
},
/**
* Converts a brackets.fs.ERR_* error code to a NativeFileError.* error name
* @param {number} fsErr A brackets.fs error code
* @return {string} An error name out of the possible NativeFileError.* names
*/
_fsErrorToDOMErrorName: function (fsErr) {
var error;
switch (fsErr) {
// We map ERR_UNKNOWN and ERR_INVALID_PARAMS to SECURITY_ERR,
// since there aren't specific mappings for these.
case brackets.fs.ERR_UNKNOWN:
case brackets.fs.ERR_INVALID_PARAMS:
error = NativeFileError.SECURITY_ERR;
break;
case brackets.fs.ERR_NOT_FOUND:
error = NativeFileError.NOT_FOUND_ERR;
break;
case brackets.fs.ERR_CANT_READ:
error = NativeFileError.NOT_READABLE_ERR;
break;
case brackets.fs.ERR_UNSUPPORTED_ENCODING:
error = NativeFileError.NOT_READABLE_ERR;
break;
case brackets.fs.ERR_CANT_WRITE:
error = NativeFileError.NO_MODIFICATION_ALLOWED_ERR;
break;
case brackets.fs.ERR_OUT_OF_SPACE:
error = NativeFileError.QUOTA_EXCEEDED_ERR;
break;
case brackets.fs.PATH_EXISTS_ERR:
error = NativeFileError.PATH_EXISTS_ERR;
break;
default:
// The HTML file spec says SECURITY_ERR is a catch-all to be used in situations
// not covered by other error codes.
error = NativeFileError.SECURITY_ERR;
}
return error;
}
};
/**
* Static class that contains constants for file
* encoding types.
*/
NativeFileSystem.Encodings = {};
NativeFileSystem.Encodings.UTF8 = "UTF-8";
NativeFileSystem.Encodings.UTF16 = "UTF-16";
/**
* Internal static class that contains constants for file
* encoding types to be used by internal file system
* implementation.
*/
NativeFileSystem._FSEncodings = {};
NativeFileSystem._FSEncodings.UTF8 = "utf8";
NativeFileSystem._FSEncodings.UTF16 = "utf16";
/**
* Converts an IANA encoding name to internal encoding name.
* http://www.iana.org/assignments/character-sets
*
* @param {string} encoding The IANA encoding string.
*/
NativeFileSystem.Encodings._IANAToFS = function (encoding) {
//IANA names are case-insensitive
encoding = encoding.toUpperCase();
switch (encoding) {
case (NativeFileSystem.Encodings.UTF8):
return NativeFileSystem._FSEncodings.UTF8;
case (NativeFileSystem.Encodings.UTF16):
return NativeFileSystem._FSEncodings.UTF16;
default:
return undefined;
}
};
var Encodings = NativeFileSystem.Encodings;
var _FSEncodings = NativeFileSystem._FSEncodings;
/**
* Implementation of w3 Entry interface:
* http://www.w3.org/TR/2011/WD-file-system-api-20110419/#the-entry-interface
*
* Base class for representing entries in a file system (FileEntry or DirectoryEntry)
*
* @constructor
* @param {string} fullPath The full absolute path from the root to the entry
* @param {boolean} isDirectory Indicates that the entry is a directory
* @param {FileSystem} fs File system that contains this entry
*/
NativeFileSystem.Entry = function (fullPath, isDirectory, fs) {
this.isDirectory = isDirectory;
this.isFile = !isDirectory;
if (fullPath) {
// add trailing "/" to directory paths
if (isDirectory && (fullPath.charAt(fullPath.length - 1) !== "/")) {
fullPath = fullPath.concat("/");
}
}
this.fullPath = fullPath;
this.name = null; // default if extraction fails
if (fullPath) {
var pathParts = fullPath.split("/");
// Extract name from the end of the fullPath (account for trailing slash(es))
while (!this.name && pathParts.length) {
this.name = pathParts.pop();
}
}
this.filesystem = fs;
};
/**
* Moves this Entry to a different location on the file system.
* @param {!DirectoryEntry} parent The directory to move the entry to
* @param {string=} newName The new name of the entry. If not specified, defaults to the current name
* @param {function(Array.<Entry>)=} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.Entry.prototype.moveTo = function (parent, newName, successCallback, errorCallback) {
// TODO (issue #241)
// http://www.w3.org/TR/2011/WD-file-system-api-20110419/#widl-Entry-moveTo
};
/**
* Copies this Entry to a different location on the file system.
* @param {!DirectoryEntry} parent The directory to copy the entry to
* @param {string=} newName The new name of the entry. If not specified, defaults to the current name
* @param {function(Array.<Entry>)=} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.Entry.prototype.copyTo = function (parent, newName, successCallback, errorCallback) {
// TODO (issue #241)
// http://www.w3.org/TR/2011/WD-file-system-api-20110419/#widl-Entry-copyTo
};
/**
* Generates a URL that can be used to identify this Entry
* @param {string=} mimeType The mime type to be used to interpret the file for a FileEntry
* @returns {string} A usable URL to identify this Entry in the current filesystem
*/
NativeFileSystem.Entry.prototype.toURL = function (mimeType) {
// TODO (issue #241)
// http://www.w3.org/TR/2011/WD-file-system-api-20110419/#widl-Entry-toURL
// Check updated definition at
// http://www.w3.org/TR/2012/WD-file-system-api-20120417/#widl-Entry-toURL-DOMString
};
/**
* Deletes a file or directory by moving to the trash/recycle bin.
* @param {function()} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.Entry.prototype.remove = function (successCallback, errorCallback) {
var deleteFunc = brackets.fs.moveToTrash || brackets.fs.unlink;
deleteFunc(this.fullPath, function (err) {
if (err === brackets.fs.NO_ERROR) {
successCallback();
} else {
errorCallback(err);
}
});
};
/**
* Look up the parent DirectoryEntry that contains this Entry
* @param {function(Array.<Entry>)} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.Entry.prototype.getParent = function (successCallback, errorCallback) {
// TODO (issue #241)
// http://www.w3.org/TR/2011/WD-file-system-api-20110419/#widl-Entry-remove
};
/**
* Look up metadata about this Entry
* @param {function(Metadata)} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.Entry.prototype.getMetadata = function (successCallBack, errorCallback) {
brackets.fs.stat(this.fullPath, function (err, stat) {
if (err === brackets.fs.NO_ERROR) {
var metadata = new NativeFileSystem.Metadata(stat.mtime);
successCallBack(metadata);
} else {
errorCallback(new NativeFileError(NativeFileSystem._fsErrorToDOMErrorName(err)));
}
});
};
/**
* Implementation of w3 Metadata interface:
* http://www.w3.org/TR/2011/WD-file-system-api-20110419/#the-metadata-interface
*
* Supplies information about the state of a file or directory
* @constructor
* @param {Date} modificationTime Time at which the file or directory was last modified
*/
NativeFileSystem.Metadata = function (modificationTime) {
// modificationTime is read only
this.modificationTime = modificationTime;
};
/**
* Implementation of w3 FileEntry interface:
* http://www.w3.org/TR/2011/WD-file-system-api-20110419/#the-fileentry-interface
*
* A FileEntry represents a file on a file system.
*
* @constructor
* @param {string} name Full path of the file in the file system
* @param {FileSystem} fs File system that contains this entry
* @extends {Entry}
*/
NativeFileSystem.FileEntry = function (name, fs) {
NativeFileSystem.Entry.call(this, name, false, fs);
};
NativeFileSystem.FileEntry.prototype = Object.create(NativeFileSystem.Entry.prototype);
NativeFileSystem.FileEntry.prototype.constructor = NativeFileSystem.FileEntry;
NativeFileSystem.FileEntry.prototype.parentClass = NativeFileSystem.Entry.prototype;
NativeFileSystem.FileEntry.prototype.toString = function () {
return "[FileEntry " + this.fullPath + "]";
};
/**
* Creates a new FileWriter associated with the file that this FileEntry represents.
* @param {function(FileWriter)} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.FileEntry.prototype.createWriter = function (successCallback, errorCallback) {
var fileEntry = this;
/**
* Implementation of w3 FileWriter interface:
* http://www.w3.org/TR/2011/WD-file-writer-api-20110419/#the-filewriter-interface
*
* A FileWriter expands on the FileSaver interface to allow for multiple write actions,
* rather than just saving a single Blob.
*
* @constructor
* @param {Blob} data The Blob of data to be saved to a file
* @extends {FileSaver}
*/
var FileWriter = function (data) {
NativeFileSystem.FileSaver.call(this, data);
// FileWriter private memeber vars
this._length = 0;
this._position = 0;
};
/**
* The length of the file
*/
FileWriter.prototype.length = function () {
return this._length;
};
/**
* The byte offset at which the next write to the file will occur.
*/
FileWriter.prototype.position = function () {
return this._position;
};
/**
* Write the supplied data to the file at position
* @param {string} data The data to write
*/
FileWriter.prototype.write = function (data) {
// TODO (issue #241): handle Blob data instead of string
// http://www.w3.org/TR/2011/WD-file-writer-api-20110419/#widl-FileWriter-write
if (data === null || data === undefined) {
console.error("FileWriter.write() called with null or undefined data.");
}
if (this.readyState === NativeFileSystem.FileSaver.WRITING) {
throw new NativeFileSystem.FileException(NativeFileSystem.FileException.INVALID_STATE_ERR);
}
this._readyState = NativeFileSystem.FileSaver.WRITING;
if (this.onwritestart) {
// TODO (issue #241): progressevent
this.onwritestart();
}
var self = this;
brackets.fs.writeFile(fileEntry.fullPath, data, _FSEncodings.UTF8, function (err) {
if ((err !== brackets.fs.NO_ERROR) && self.onerror) {
var fileError = new NativeFileError(NativeFileSystem._fsErrorToDOMErrorName(err));
// TODO (issue #241): set readonly FileSaver.error attribute
// self._error = fileError;
self.onerror(fileError);
// TODO (issue #241): partial write, update length and position
}
// else {
// TODO (issue #241): After changing data argument to Blob, use
// Blob.size to update position and length upon successful
// completion of a write.
// self.position = ;
// self.length = ;
// }
// DONE is set regardless of error
self._readyState = NativeFileSystem.FileSaver.DONE;
if (self.onwrite) {
// TODO (issue #241): progressevent
self.onwrite();
}
if (self.onwriteend) {
// TODO (issue #241): progressevent
self.onwriteend();
}
});
};
/**
* Seek sets the file position at which the next write will occur
* @param {number} offset An absolute byte offset into the file. If offset is greater than
* length, length is used instead. If offset is less than zero, length
* is added to it, so that it is treated as an offset back from the end
* of the file. If it is still less than zero, zero is used
*/
FileWriter.prototype.seek = function (offset) {
// TODO (issue #241)
// http://www.w3.org/TR/2011/WD-file-writer-api-20110419/#widl-FileWriter-seek
};
/**
* Changes the length of the file to that specified
* @param {number} size The size to which the length of the file is to be adjusted,
* measured in bytes
*/
FileWriter.prototype.truncate = function (size) {
// TODO (issue #241)
// http://www.w3.org/TR/2011/WD-file-writer-api-20110419/#widl-FileWriter-truncate
};
var fileWriter = new FileWriter();
// initialize file length
var result = new $.Deferred();
brackets.fs.readFile(fileEntry.fullPath, _FSEncodings.UTF8, function (err, contents) {
// Ignore "file not found" errors. It's okay if the file doesn't exist yet.
if (err !== brackets.fs.ERR_NOT_FOUND) {
fileWriter._err = err;
}
if (contents) {
fileWriter._length = contents.length;
}
result.resolve();
});
result.done(function () {
if (fileWriter._err && (errorCallback !== undefined)) {
errorCallback(new NativeFileError(NativeFileSystem._fsErrorToDOMErrorName(fileWriter._err)));
} else if (successCallback !== undefined) {
successCallback(fileWriter);
}
});
};
/**
* Returns a File that represents the current state of the file that this FileEntry represents
* @param {function(File)} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.FileEntry.prototype.file = function (successCallback, errorCallback) {
var newFile = new NativeFileSystem.File(this);
successCallback(newFile);
// TODO (issue #241): errorCallback
};
/**
* This class extends the FileException interface described in to add
* several new error codes. Any errors that need to be reported synchronously,
* including all that occur during use of the synchronous filesystem methods,
* are reported using the FileException exception.
*
* @param {?number=} code The code attribute, on getting, must return one of the
* constants of the FileException exception, which must be the most appropriate
* code from the table below.
*/
NativeFileSystem.FileException = function (code) {
this.code = code || 0;
};
// FileException constants
Object.defineProperties(
NativeFileSystem.FileException,
{
NOT_FOUND_ERR: { value: 1, writable: false },
SECURITY_ERR: { value: 2, writable: false },
ABORT_ERR: { value: 3, writable: false },
NOT_READABLE_ERR: { value: 4, writable: false },
ENCODING_ERR: { value: 5, writable: false },
NO_MODIFICATION_ALLOWED_ERR: { value: 6, writable: false },
INVALID_STATE_ERR: { value: 7, writable: false },
SYNTAX_ERR: { value: 8, writable: false },
QUOTA_EXCEEDED_ERR: { value: 10, writable: false }
}
);
/**
* Implementation of w3 FileSaver interface
* http://www.w3.org/TR/2011/WD-file-writer-api-20110419/#the-filesaver-interface
*
* FileSaver provides methods to monitor the asynchronous writing of blobs
* to disk using progress events and event handler attributes.
*
* @constructor
* @param {Blob} data The Blob of data to be saved to a file
*/
NativeFileSystem.FileSaver = function (data) {
// FileSaver private member vars
this._data = data;
this._readyState = NativeFileSystem.FileSaver.INIT;
this._error = null;
};
// FileSaver constants
Object.defineProperties(
NativeFileSystem.FileSaver,
{
INIT: { value: 1, writable: false },
WRITING: { value: 2, writable: false },
DONE: { value: 3, writable: false }
}
);
/**
* The state the FileSaver object is at the moment (INIT, WRITING, DONE)
*/
NativeFileSystem.FileSaver.prototype.readyState = function () {
return this._readyState;
};
/**
* Aborts a saving operation
*/
NativeFileSystem.FileSaver.prototype.abort = function () {
// TODO (issue #241): http://dev.w3.org/2009/dap/file-system/file-writer.html#widl-FileSaver-abort-void
// If readyState is DONE or INIT, terminate this overall series of steps without doing anything else..
if (this._readyState === NativeFileSystem.FileSaver.INIT || this._readyState === NativeFileSystem.FileSaver.DONE) {
return;
}
// TODO (issue #241): Terminate any steps having to do with writing a file.
// Set the error attribute to a FileError object with the code ABORT_ERR.
this._error = new NativeFileError(NativeFileError.ABORT_ERR);
// Set readyState to DONE.
this._readyState = NativeFileSystem.FileSaver.DONE;
/*
TODO (issue #241):
Dispatch a progress event called abort
Dispatch a progress event called writeend
Stop dispatching any further progress events.
Terminate this overall set of steps.
*/
};
/**
* Implementation of w3 DirectoryEntry interface:
* http://www.w3.org/TR/2011/WD-file-system-api-20110419/#the-directoryentry-interface
*
* The DirectoryEntry class represents a directory on a file system.
*
* @constructor
* @param {string} name Full path of the directory in the file system
* @param {FileSystem} fs File system that contains this entry
* @extends {Entry}
*/
NativeFileSystem.DirectoryEntry = function (name, fs) {
NativeFileSystem.Entry.call(this, name, true, fs);
// TODO (issue #241): void removeRecursively (VoidCallback successCallback, optional ErrorCallback errorCallback);
};
NativeFileSystem.DirectoryEntry.prototype = Object.create(NativeFileSystem.Entry.prototype);
NativeFileSystem.DirectoryEntry.prototype.constructor = NativeFileSystem.DirectoryEntry;
NativeFileSystem.DirectoryEntry.prototype.parentClass = NativeFileSystem.Entry.prototype;
NativeFileSystem.DirectoryEntry.prototype.toString = function () {
return "[DirectoryEntry " + this.fullPath + "]";
};
/**
* Creates or looks up a directory
* @param {string} path Either an absolute path or a relative path from this DirectoryEntry
* to the directory to be looked up or created
* @param {{create:?boolean, exclusive:?boolean}=} options Object with the flags "create"
* and "exclusive" to modify the method behavior based on
* http://www.w3.org/TR/2011/WD-file-system-api-20110419/#widl-DirectoryEntry-getDirectory
* @param {function(Entry)=} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.DirectoryEntry.prototype.getDirectory = function (path, options, successCallback, errorCallback) {
var directoryFullPath = path,
filesystem = this.filesystem;
function isRelativePath(path) {
// If the path contains a colons it must be a full path on Windows (colons are
// not valid path characters on mac or in URIs)
if (path.indexOf(":") !== -1) {
return false;
}
// For everyone else, absolute paths start with a "/"
return path[0] !== "/";
}
// resolve relative paths relative to the DirectoryEntry
if (isRelativePath(path)) {
directoryFullPath = this.fullPath + path;
}
var createDirectoryEntry = function () {
if (successCallback) {
successCallback(new NativeFileSystem.DirectoryEntry(directoryFullPath, filesystem));
}
};
var createDirectoryError = function (err) {
if (errorCallback) {
errorCallback(new NativeFileError(NativeFileSystem._fsErrorToDOMErrorName(err)));
}
};
// Use stat() to check if file exists
brackets.fs.stat(directoryFullPath, function (err, stats) {
if ((err === brackets.fs.NO_ERROR)) {
// NO_ERROR implies the path already exists
// throw error if the file the path is not a directory
if (!stats.isDirectory()) {
if (errorCallback) {
errorCallback(new NativeFileError(NativeFileError.TYPE_MISMATCH_ERR));
}
return;
}
// throw error if the file exists but create is exclusive
if (options.create && options.exclusive) {
if (errorCallback) {
errorCallback(new NativeFileError(NativeFileError.PATH_EXISTS_ERR));
}
return;
}
// Create a file entry for the existing directory. If create == true,
// a file entry is created without error.
createDirectoryEntry();
} else if (err === brackets.fs.ERR_NOT_FOUND) {
// ERR_NOT_FOUND implies we write a new, empty file
// create the file
if (options.create) {
// TODO: Pass permissions. The current implementation of fs.makedir() always
// creates the directory with the full permissions available to the current user.
brackets.fs.makedir(directoryFullPath, 0, function (err) {
if (err) {
createDirectoryError(err);
} else {
createDirectoryEntry();
}
});
return;
}
// throw error if file not found and the create == false
if (errorCallback) {
errorCallback(new NativeFileError(NativeFileError.NOT_FOUND_ERR));
}
} else {
// all other brackets.fs.stat() errors
createDirectoryError(err);
}
});
};
/**
* Deletes a directory and all of its contents, if any
* @param {function()} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.DirectoryEntry.prototype.removeRecursively = function (successCallback, errorCallback) {
// TODO (issue #241)
// http://www.w3.org/TR/2011/WD-file-system-api-20110419/#widl-DirectoryEntry-removeRecursively
};
/**
* Creates a new DirectoryReader to read Entries from this Directory
* @returns {DirectoryReader} A DirectoryReader instance to read the Directory's entries
*/
NativeFileSystem.DirectoryEntry.prototype.createReader = function () {
var dirReader = new NativeFileSystem.DirectoryReader();
dirReader._directory = this;
return dirReader;
};
/**
* Creates or looks up a file.
*
* @param {string} path Either an absolute path or a relative path from this
* DirectoryEntry to the file to be looked up or created. It is an error
* to attempt to create a file whose immediate parent does not yet
* exist.
* @param {{create:?boolean, exclusive:?boolean}=} options Object with the flags "create"
* and "exclusive" to modify the method behavior based on
* http://www.w3.org/TR/2011/WD-file-system-api-20110419/#widl-DirectoryEntry-getFile
* @param {function(FileEntry)=} successCallback Callback function for successful operations
* @param {function(DOMError)=} errorCallback Callback function for error operations
*/
NativeFileSystem.DirectoryEntry.prototype.getFile = function (path, options, successCallback, errorCallback) {
var fileFullPath = path,
filesystem = this.filesystem;
function isRelativePath(path) {
// If the path contains a colons it must be a full path on Windows (colons are
// not valid path characters on mac or in URIs)
if (path.indexOf(":") !== -1) {
return false;
}
// For everyone else, absolute paths start with a "/"
return path[0] !== "/";
}
// resolve relative paths relative to the DirectoryEntry
if (isRelativePath(path)) {
fileFullPath = this.fullPath + path;
}
var createFileEntry = function () {
if (successCallback) {
successCallback(new NativeFileSystem.FileEntry(fileFullPath, filesystem));
}
};
var createFileError = function (err) {
if (errorCallback) {
errorCallback(new NativeFileError(NativeFileSystem._fsErrorToDOMErrorName(err)));
}
};
// Use stat() to check if file exists
brackets.fs.stat(fileFullPath, function (err, stats) {
if ((err === brackets.fs.NO_ERROR)) {
// NO_ERROR implies the path already exists
// throw error if the file the path is a directory
if (stats.isDirectory()) {
if (errorCallback) {
errorCallback(new NativeFileError(NativeFileError.TYPE_MISMATCH_ERR));
}
return;
}
// throw error if the file exists but create is exclusive
if (options.create && options.exclusive) {
if (errorCallback) {
errorCallback(new NativeFileError(NativeFileError.PATH_EXISTS_ERR));
}
return;
}
// Create a file entry for the existing file. If create == true,
// a file entry is created without error.
createFileEntry();
} else if (err === brackets.fs.ERR_NOT_FOUND) {
// ERR_NOT_FOUND implies we write a new, empty file
// create the file
if (options.create) {
brackets.fs.writeFile(fileFullPath, "", _FSEncodings.UTF8, function (err) {
if (err) {
createFileError(err);
} else {
createFileEntry();
}
});
return;
}
// throw error if file not found and the create == false
if (errorCallback) {
errorCallback(new NativeFileError(NativeFileError.NOT_FOUND_ERR));
}
} else {
// all other brackets.fs.stat() errors
createFileError(err);
}
});
};
/**
* Implementation of w3 DirectoryReader interface:
* http://www.w3.org/TR/2011/WD-file-system-api-20110419/#the-directoryreader-interface
*
* A DirectoryReader lets a user list files and directories in a directory
*
* @constructor
*/
NativeFileSystem.DirectoryReader = function () {
};
/**
* Read the next block of entries from this directory
* @param {function(Array.<Entry>)} successCallback Callback function for successful operations
* @param {function(DOMError, ?Array.<Entry>)=} errorCallback Callback function for error operations,
* which may include an array of entries that could be read without error
*/
NativeFileSystem.DirectoryReader.prototype.readEntries = function (successCallback, errorCallback) {
if (!this._directory.fullPath) {
errorCallback(new NativeFileError(NativeFileError.PATH_EXISTS_ERR));
return;
}
var rootPath = this._directory.fullPath,
filesystem = this.filesystem,
timeout = NativeFileSystem.ASYNC_TIMEOUT,
networkDetectionResult = new $.Deferred();
if (brackets.fs.isNetworkDrive) {
brackets.fs.isNetworkDrive(rootPath, function (err, remote) {
if (!err && remote) {
timeout = NativeFileSystem.ASYNC_NETWORK_TIMEOUT;
}
networkDetectionResult.resolve();
});
} else {
networkDetectionResult.resolve();
}
networkDetectionResult.done(function () {
brackets.fs.readdir(rootPath, function (err, filelist) {
if (!err) {
var entries = [];
var lastError = null;
// call success immediately if this directory has no files
if (filelist.length === 0) {
successCallback(entries);
return;
}
// stat() to determine type of each entry, then populare entries array with objects
var masterPromise = Async.doInParallel(filelist, function (filename, index) {
var deferred = new $.Deferred();
var itemFullPath = rootPath + filelist[index];
brackets.fs.stat(itemFullPath, function (statErr, statData) {
if (!statErr) {
if (statData.isDirectory()) {
entries[index] = new NativeFileSystem.DirectoryEntry(itemFullPath, filesystem);
} else if (statData.isFile()) {
entries[index] = new NativeFileSystem.FileEntry(itemFullPath, filesystem);