Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support Drag and Drop of Folders as well as files, fixes #668 #659

Merged
merged 7 commits into from
May 8, 2017
20 changes: 14 additions & 6 deletions src/filesystem/impls/filer/ArchiveUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ define(function (require, exports, module) {
var fs = Filer.fs();

// Mac and Windows clutter zip files with extra files/folders we don't need
function _skipFile(filename) {
function skipFile(filename) {
var basename = Path.basename(filename);

// Skip OS X additions we don't care about in the browser fs
Expand Down Expand Up @@ -71,7 +71,7 @@ define(function (require, exports, module) {
return;
}

var root = StartupState.project("root");
var root = options.root || StartupState.project("root");
var destination = Path.resolve(options.destination || root);

function _unzip(data){
Expand All @@ -80,7 +80,7 @@ define(function (require, exports, module) {
var filenames = [];

archive.filter(function(relPath, file) {
if(_skipFile(file.name)) {
if(skipFile(file.name)) {
return;
}

Expand Down Expand Up @@ -206,16 +206,23 @@ define(function (require, exports, module) {
});
}

function untar(tarArchive, callback) {
function untar(tarArchive, options, callback) {
if(typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
callback = callback || function(){};

var untarWorker = new Worker("thirdparty/bitjs/bitjs-untar.min.js");
var root = StartupState.project("root");
var root = options.root || StartupState.project("root");
var pending = null;

function extract(path, data, callback) {
path = Path.resolve(root, path);
var basedir = Path.dirname(path);

if(_skipFile(path)) {
if(skipFile(path)) {
return callback();
}

Expand Down Expand Up @@ -262,6 +269,7 @@ define(function (require, exports, module) {
untarWorker.postMessage({file: tarArchive.buffer});
}

exports.skipFile = skipFile;
exports.archive = archive;
exports.unzip = unzip;
exports.untar = untar;
Expand Down
76 changes: 76 additions & 0 deletions src/filesystem/impls/filer/lib/FileImport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define*/

define(function (require, exports, module) {
"use strict";

var LegacyFileImport = require("filesystem/impls/filer/lib/LegacyFileImport"),
WebKitFileImport = require("filesystem/impls/filer/lib/WebKitFileImport"),
FileSystemCache = require("filesystem/impls/filer/FileSystemCache"),
BrambleStartupState = brackets.getModule("bramble/StartupState");

// 3MB size limit for imported files. If you change this, also change the
// error message we generate in rejectImport() below!
var byteLimit = 3145728;

// 5MB size limit for imported archives (zip & tar)
var archiveByteLimit = 5242880;

/**
* XXXBramble: the Drag and Drop and File APIs are a mess of incompatible
* standards and implementations. This tries to deal with the fact that some
* browsers allow you to drag-and-drop folders, and some don't. All
* browsers we support will do file drag-and-drop, so we want to make sure
* we always allow that.
*
* Currently, dragging folders works in Chrome (13), Edge, Firefox (50)
* but not in IE, Opera, or Safari.
*
* See:
* - https://html.spec.whatwg.org/#the-datatransferitem-interface
* - https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer
* - https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList
* - https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem
* - https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/webkitGetAsEntry
*/
function chooseImportStrategy(source) {
var options = {
byteLimit: byteLimit,
archiveByteLimit: archiveByteLimit
};

if(source instanceof FileList) {
return LegacyFileImport.create(options);
}

if(source instanceof DataTransfer) {
if(window.DataTransferItem &&
window.DataTransferItem.prototype.webkitGetAsEntry &&
window.DataTransferItemList) {
return WebKitFileImport.create(options);
}
return LegacyFileImport.create(options);
}
}

// Support passing a DataTransfer object, or a FileList
exports.import = function(source, parentPath, callback) {
if(!(source instanceof FileList || source instanceof DataTransfer)) {
callback(new Error("[Bramble] expected DataTransfer or FileList to FileImport.import()"));
return;
}

var strategy = chooseImportStrategy(source);

// If we are given a sub-dir within the project, use that. Otherwise use project root.
parentPath = parentPath || BrambleStartupState.project("root");

return strategy.import(source, parentPath, function(err) {
if(err) {
return callback(err);
}
FileSystemCache.refresh(callback);
});
};
});
250 changes: 250 additions & 0 deletions src/filesystem/impls/filer/lib/LegacyFileImport.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
/*
* 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 _ = require("thirdparty/lodash"),
Async = require("utils/Async"),
Dialogs = require("widgets/Dialogs"),
DefaultDialogs = require("widgets/DefaultDialogs"),
FileSystem = require("filesystem/FileSystem"),
FileUtils = require("file/FileUtils"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
Filer = require("filesystem/impls/filer/BracketsFiler"),
Path = Filer.Path,
Content = require("filesystem/impls/filer/lib/content"),
LanguageManager = require("language/LanguageManager"),
StartupState = require("bramble/StartupState"),
ArchiveUtils = require("filesystem/impls/filer/ArchiveUtils"),
FilerUtils = require("filesystem/impls/filer/FilerUtils");

function LegacyFileImport(options) {
this.byteLimit = options.byteLimit;
this.archiveByteLimit = options.archiveByteLimit;
}

// We want event.dataTransfer.files for legacy browsers.
LegacyFileImport.prototype.import = function(source, parentPath, callback) {
var files = source instanceof DataTransfer ? source.files : source;
var byteLimit = this.byteLimit;
var archiveByteLimit = this.archiveByteLimit;
var pathList = [];
var errorList = [];

if (!(files && files.length)) {
return callback();
}

function shouldOpenFile(filename, encoding) {
return Content.isImage(Path.extname(filename)) || encoding === "utf8";
}

function handleRegularFile(deferred, file, filename, buffer, encoding) {
// Don't write thing like .DS_Store, thumbs.db, etc.
if(ArchiveUtils.skipFile(filename)) {
deferred.resolve();
return;
}

file.write(buffer, {encoding: encoding}, function(err) {
if (err) {
errorList.push({path: filename, error: "unable to write file: " + err.message || ""});
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);

ArchiveUtils.unzip(buffer, { root: parentPath }, function(err) {
if (err) {
errorList.push({path: filename, error: Strings.DND_ERROR_UNZIP});
deferred.reject(err);
return;
}

Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_INFO,
Strings.DND_SUCCESS_UNZIP_TITLE,
StringUtils.format(Strings.DND_SUCCESS_UNZIP, basename)
).getPromise().then(deferred.resolve, deferred.reject);
});
}

function handleTarFile(deferred, file, filename, buffer, encoding) {
var basename = Path.basename(filename);

ArchiveUtils.untar(buffer, { root: parentPath }, function(err) {
if (err) {
errorList.push({path: filename, error: Strings.DND_ERROR_UNTAR});
deferred.reject(err);
return;
}

Dialogs.showModalDialog(
DefaultDialogs.DIALOG_ID_INFO,
Strings.DND_SUCCESS_UNTAR_TITLE,
StringUtils.format(Strings.DND_SUCCESS_UNTAR, basename)
).getPromise().then(deferred.resolve, deferred.reject);
});
}

/**
* 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) {
var ext = Path.extname(item.name);
var isArchive = Content.isArchive(ext);
var sizeLimit = isArchive ? archiveByteLimit : byteLimit;
var sizeLimitMb = (sizeLimit / (1024 * 1024)).toString();

if (item.size > sizeLimit) {
return new Error(StringUtils.format(Strings.DND_MAX_SIZE_EXCEEDED, sizeLimitMb));
}

// If we don't know about this language type, or the OS doesn't think
// it's text, reject it.
var isSupported = !!LanguageManager.getLanguageForExtension(FilerUtils.normalizeExtension(ext, true));
var typeIsText = Content.isTextType(item.type);

if (isSupported || typeIsText || isArchive) {
return null;
}
return new Error(Strings.DND_UNSUPPORTED_FILE_TYPE);
}

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;
});
}

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) {
errorList.push({path: item.name, error: wasRejected.message});
deferred.reject(wasRejected);
return deferred.promise();
}

reader.onload = function(e) {
delete reader.onload;

var filename = Path.join(parentPath, item.name);
var file = FileSystem.getFileForPath(filename);
var ext = Path.extname(filename).toLowerCase();

// 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(ext);
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(ext === ".zip") {
handleZipFile(deferred, file, filename, buffer, encoding);
} else if(ext === ".tar") {
handleTarFile(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();
}

Async.doSequentially(prepareDropPaths(files), maybeImportFile, false)
.done(function() {
callback(null, pathList);
})
.fail(function() {
callback(errorList);
});
};

exports.create = function(options) {
return new LegacyFileImport(options);
};
});
Loading