forked from humphd/brackets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDragAndDrop.js
More file actions
402 lines (347 loc) · 16.5 KB
/
Copy pathDragAndDrop.js
File metadata and controls
402 lines (347 loc) · 16.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
/*
* Copyright (c) 2013 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, $, FileReader*/
define(function (require, exports, module) {
"use strict";
var Async = require("utils/Async"),
CommandManager = require("command/CommandManager"),
Commands = require("command/Commands"),
Dialogs = require("widgets/Dialogs"),
DefaultDialogs = require("widgets/DefaultDialogs"),
MainViewManager = require("view/MainViewManager"),
FileSystem = require("filesystem/FileSystem"),
FileUtils = require("file/FileUtils"),
ProjectManager = require("project/ProjectManager"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils");
// Bramble specific bits
var _ = require("thirdparty/lodash"),
Filer = require("filesystem/impls/filer/BracketsFiler"),
Path = Filer.Path,
Content = require("filesystem/impls/filer/lib/content"),
LanguageManager = require("language/LanguageManager"),
StartupState = require("bramble/StartupState"),
unzip = require("filesystem/impls/filer/ZipUtils").unzip;
// 3M size limit for imported files
var byteLimit = 3 * 1024 * 1000;
/**
* Returns true if the drag and drop items contains valid drop objects.
* @param {Array.<DataTransferItem>} items Array of items being dragged
* @return {boolean} True if one or more items can be dropped.
*/
function isValidDrop(types) {
if (types) {
for (var i = 0; i < types.length; i++) {
if (types[i] === "Files") {
return true;
}
}
}
return false;
}
function _showErrorDialog(errorFiles) {
function errorToString(err) {
return FileUtils.getFileErrorString(err);
}
if (!errorFiles.length) {
return;
}
var message = Strings.ERROR_OPENING_FILES;
message += "<ul class='dialog-list'>";
errorFiles.forEach(function (info) {
message += "<li><span class='dialog-filename'>" +
StringUtils.breakableUrl(ProjectManager.makeProjectRelativeIfPossible(info.path)) +
"</span> - " + errorToString(info.error) +
"</li>";
});
message += "</ul>";
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_ERROR,
Strings.ERROR_OPENING_FILE_TITLE,
message
);
}
/**
* Open dropped files
* @param {Array.<string>} files Array of files dropped on the application.
* @return {Promise} Promise that is resolved if all files are opened, or rejected
* if there was an error.
*/
function openDroppedFiles(paths) {
var errorFiles = [],
ERR_MULTIPLE_ITEMS_WITH_DIR = {};
return Async.doInParallel(paths, function (path, idx) {
var result = new $.Deferred();
// Only open files.
FileSystem.resolve(path, function (err, item) {
if (!err && item.isFile) {
// If the file is already open, and this isn't the last
// file in the list, return. If this *is* the last file,
// always open it so it gets selected.
if (idx < paths.length - 1) {
if (MainViewManager.findInWorkingSet(MainViewManager.ALL_PANES, path) !== -1) {
result.resolve();
return;
}
}
CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN,
{fullPath: path, silent: true})
.done(function () {
result.resolve();
})
.fail(function (openErr) {
errorFiles.push({path: path, error: openErr});
result.reject();
});
} else if (!err && item.isDirectory && paths.length === 1) {
// One folder was dropped, open it.
ProjectManager.openProject(path)
.done(function () {
result.resolve();
})
.fail(function () {
// User was already notified of the error.
result.reject();
});
} else {
errorFiles.push({path: path, error: err || ERR_MULTIPLE_ITEMS_WITH_DIR});
result.reject();
}
});
return result.promise();
}, false)
.fail(function () {
_showErrorDialog(errorFiles);
});
}
/**
* Attaches global drag & drop handlers to this window. This enables dropping files/folders to open them, and also
* protects the Brackets app from being replaced by the browser trying to load the dropped file in its place.
*/
function attachHandlers() {
function handleDragOver(event) {
event = event.originalEvent || event;
event.stopPropagation();
event.preventDefault();
var dropEffect = "none";
// Don't allow drag-and-drop of files/folders when a modal dialog is showing.
if ($(".modal.instance").length === 0 && isValidDrop(event.dataTransfer.types)) {
dropEffect = "copy";
}
event.dataTransfer.dropEffect = dropEffect;
}
function handleDrop(event) {
event = event.originalEvent || event;
event.stopPropagation();
event.preventDefault();
var pathList = [];
var errorList = [];
function shouldOpenFile(filename, encoding) {
var ext = Path.extname(filename).replace(/^\./, "");
var language = LanguageManager.getLanguageForExtension(ext);
var id = language && language.getId();
var isImage = id === "image" || id === "svg";
return isImage || encoding === "utf8";
}
function handleRegularFile(deferred, file, filename, buffer, encoding) {
file.write(buffer, {encoding: encoding}, function(err) {
if (err) {
deferred.reject(err);
return;
}
// See if this file is worth trying to open in the editor or not
if(shouldOpenFile(filename, encoding)) {
pathList.push(filename);
}
deferred.resolve();
});
}
function handleZipFile(deferred, file, filename, buffer, encoding) {
var basename = Path.basename(filename);
var message = "<p>Do you want to extract the contents of the zip file: <b>" +
basename + "</b>?</p>" +
"<p><em>NOTE: This can take some time.</em><p>";
// TODO: l10n, UX audit
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_INFO,
"Unzip file",
message,
[
{
className : Dialogs.DIALOG_BTN_CLASS_NORMAL,
id : Dialogs.DIALOG_BTN_CANCEL,
text : "No"
},
{
className : Dialogs.DIALOG_BTN_CLASS_PRIMARY,
id : Dialogs.DIALOG_BTN_OK,
text : "Yes"
}
]
)
.done(function(id) {
if (id === Dialogs.DIALOG_BTN_OK) {
// TODO: we need to give a spinner or something to indicate we're working
unzip(buffer, function(err) {
if (err) {
deferred.reject(err);
return;
}
Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_INFO,
"Unzip Completed Successfully",
"Successfully unzipped <b>" + basename + "</b>."
).then(deferred.resolve, deferred.reject);
});
} else {
handleRegularFile(deferred, file, filename, buffer, encoding);
}
});
}
function prepareDropPaths(fileList) {
// Convert FileList object to an Array with all image files first, then CSS
// followed by HTML files at the end, since we need to write any .css, .js, etc.
// resources first such that Blob URLs can be generated for these resources
// prior to rewriting an HTML file.
function rateFileByType(filename) {
var ext = Path.extname(filename);
// We want to end up with: [images, ..., js, ..., css, html]
// since CSS can include images, and HTML can include CSS or JS.
// We also treat .md like an HTML file, since we render them.
if(Content.isHTML(ext) || Content.isMarkdown(ext)) {
return 10;
} else if(Content.isCSS(ext)) {
return 8;
} else if(Content.isImage(ext)) {
return 1;
}
return 3;
}
return _.toArray(fileList).sort(function(a,b) {
a = rateFileByType(a.name);
b = rateFileByType(b.name);
if(a < b) {
return -1;
}
if(a > b) {
return 1;
}
return 0;
});
}
/**
* Determine whether we want to import this file at all. If it's too large
* or not a mime type we care about, reject it.
*/
function rejectImport(item) {
if (item.size > byteLimit) {
return new Error("file exceeds maximum supported size");
}
// If we don't know about this language type, or the OS doesn't think
// it's text, reject it.
var ext = Path.extname(item.name).replace(/^\./, "");
var languageIsSupported = !!LanguageManager.getLanguageForExtension(ext);
var typeIsText = Content.isTextType(item.type);
if (languageIsSupported || typeIsText) {
return null;
}
return new Error("unsupported file type");
}
function maybeImportFile(item) {
var deferred = new $.Deferred();
var reader = new FileReader();
// Check whether we want to import this file at all before we start.
var wasRejected = rejectImport(item);
if (wasRejected) {
setTimeout(function(){
errorList.push({path: item.name, error: wasRejected.message});
deferred.reject(wasRejected);
}, 5);
return deferred.promise();
}
reader.onload = function(e) {
delete reader.onload;
var filename = Path.join(StartupState.project("root"), item.name);
var file = FileSystem.getFileForPath(filename);
// Create a Filer Buffer, and determine the proper encoding. We
// use the extension, and also the OS provided mime type for clues.
var buffer = new Filer.Buffer(e.target.result);
var utf8FromExt = Content.isUTF8Encoded(Path.extname(filename));
var utf8FromOS = Content.isTextType(item.type);
var encoding = utf8FromExt || utf8FromOS ? 'utf8' : null;
if(encoding === 'utf8') {
buffer = buffer.toString();
}
// Special-case .zip files, so we can offer to extract the contents
if(Path.extname(filename) === ".zip") {
handleZipFile(deferred, file, filename, buffer, encoding);
} else {
handleRegularFile(deferred, file, filename, buffer, encoding);
}
};
// Deal with error cases, for example, trying to drop a folder vs. file
reader.onerror = function(e) {
delete reader.onerror;
errorList.push({path: item.name, error: e.target.error.message});
deferred.reject(e.target.error);
};
reader.readAsArrayBuffer(item);
return deferred.promise();
}
var files = event.dataTransfer.files;
if (files && files.length) {
Async.doSequentially(prepareDropPaths(files), maybeImportFile, false)
.done(function() {
openDroppedFiles(pathList);
})
.fail(function() {
_showErrorDialog(errorList);
});
}
}
// For most of the window, only respond if nothing more specific in the UI has already grabbed the event (e.g.
// the Extension Manager drop-to-install zone, or an extension with a drop-to-upload zone in its panel)
$(window.document.body)
.on("dragover", handleDragOver)
.on("drop", handleDrop);
// Over CodeMirror specifically, always pre-empt CodeMirror's drag event handling if files are being dragged - CM stops
// propagation on any drag event it sees, even when it's not a text drag/drop. But allow CM to handle all non-file drag
// events. See bug #10617.
window.document.body.addEventListener("dragover", function (event) {
if ($(event.target).closest(".CodeMirror").length) {
handleDragOver(event);
}
}, true);
window.document.body.addEventListener("drop", function (event) {
if ($(event.target).closest(".CodeMirror").length) {
handleDrop(event);
}
}, true);
}
CommandManager.register(Strings.CMD_OPEN_DROPPED_FILES, Commands.FILE_OPEN_DROPPED_FILES, openDroppedFiles);
// Export public API
exports.attachHandlers = attachHandlers;
exports.isValidDrop = isValidDrop;
exports.openDroppedFiles = openDroppedFiles;
});