1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
8 * Utilities for FileOperationManager.
10 var fileOperationUtil = {};
13 * Simple wrapper for util.deduplicatePath. On error, this method translates
14 * the FileError to FileOperationManager.Error object.
16 * @param {DirectoryEntry} dirEntry The target directory entry.
17 * @param {string} relativePath The path to be deduplicated.
18 * @param {function(string)} successCallback Callback run with the deduplicated
20 * @param {function(FileOperationManager.Error)} errorCallback Callback run on
23 fileOperationUtil.deduplicatePath = function(
24 dirEntry, relativePath, successCallback, errorCallback) {
26 dirEntry, relativePath, successCallback,
28 var onFileSystemError = function(error) {
29 errorCallback(new FileOperationManager.Error(
30 util.FileOperationErrorType.FILESYSTEM_ERROR, error));
33 if (err.name == util.FileError.PATH_EXISTS_ERR) {
34 // Failed to uniquify the file path. There should be an existing
35 // entry, so return the error with it.
37 dirEntry, relativePath,
39 errorCallback(new FileOperationManager.Error(
40 util.FileOperationErrorType.TARGET_EXISTS, entry));
45 onFileSystemError(err);
50 * Traverses files/subdirectories of the given entry, and returns them.
51 * In addition, this method annotate the size of each entry. The result will
52 * include the entry itself.
54 * @param {Entry} entry The root Entry for traversing.
55 * @param {function(Array.<Entry>)} successCallback Called when the traverse
56 * is successfully done with the array of the entries.
57 * @param {function(FileError)} errorCallback Called on error with the first
58 * occurred error (i.e. following errors will just be discarded).
60 fileOperationUtil.resolveRecursively = function(
61 entry, successCallback, errorCallback) {
64 var numRunningTasks = 0;
66 var maybeInvokeCallback = function() {
67 // If there still remain some running tasks, wait their finishing.
68 if (numRunningTasks > 0)
74 successCallback(result);
77 // The error handling can be shared.
78 var onError = function(fileError) {
79 // If this is the first error, remember it.
83 maybeInvokeCallback();
86 var process = function(entry) {
89 if (entry.isDirectory) {
90 // The size of a directory is 1 bytes here, so that the progress bar
91 // will work smoother.
92 // TODO(hidehiko): Remove this hack.
95 // Recursively traverse children.
96 var reader = entry.createReader();
98 function processSubEntries(subEntries) {
99 if (error || subEntries.length == 0) {
100 // If an error is found already, or this is the completion
101 // callback, then finish the process.
103 maybeInvokeCallback();
107 for (var i = 0; i < subEntries.length; i++)
108 process(subEntries[i]);
110 // Continue to read remaining children.
111 reader.readEntries(processSubEntries, onError);
115 // For a file, annotate the file size.
116 entry.getMetadata(function(metadata) {
117 entry.size = metadata.size;
119 maybeInvokeCallback();
128 * Copies source to parent with the name newName recursively.
129 * This should work very similar to FileSystem API's copyTo. The difference is;
130 * - The progress callback is supported.
131 * - The cancellation is supported.
133 * @param {Entry} source The entry to be copied.
134 * @param {DirectoryEntry} parent The entry of the destination directory.
135 * @param {string} newName The name of copied file.
136 * @param {function(Entry, Entry)} entryChangedCallback
137 * Callback invoked when an entry is created with the source Entry and
138 * the destination Entry.
139 * @param {function(Entry, number)} progressCallback Callback invoked
140 * periodically during the copying. It takes the source Entry and the
141 * processed bytes of it.
142 * @param {function(Entry)} successCallback Callback invoked when the copy
143 * is successfully done with the Entry of the created entry.
144 * @param {function(FileError)} errorCallback Callback invoked when an error
146 * @return {function()} Callback to cancel the current file copy operation.
147 * When the cancel is done, errorCallback will be called. The returned
148 * callback must not be called more than once.
150 fileOperationUtil.copyTo = function(
151 source, parent, newName, entryChangedCallback, progressCallback,
152 successCallback, errorCallback) {
154 var pendingCallbacks = [];
156 // Makes the callback called in order they were invoked.
157 var callbackQueue = new AsyncUtil.Queue();
159 var onCopyProgress = function(progressCopyId, status) {
160 callbackQueue.run(function(callback) {
161 if (copyId === null) {
162 // If the copyId is not yet available, wait for it.
163 pendingCallbacks.push(
164 onCopyProgress.bind(null, progressCopyId, status));
169 // This is not what we're interested in.
170 if (progressCopyId != copyId) {
175 switch (status.type) {
176 case 'begin_copy_entry':
180 case 'end_copy_entry':
181 // TODO(mtomasz): Convert URL to Entry in custom bindings.
183 [status.destinationUrl], function(destinationEntries) {
184 entryChangedCallback(source, destinationEntries[0] || null);
190 progressCallback(source, status.size);
195 chrome.fileBrowserPrivate.onCopyProgress.removeListener(
197 // TODO(mtomasz): Convert URL to Entry in custom bindings.
199 [status.destinationUrl], function(destinationEntries) {
200 successCallback(destinationEntries[0] || null);
206 chrome.fileBrowserPrivate.onCopyProgress.removeListener(
208 errorCallback(util.createDOMError(status.error.name));
213 // Found unknown state. Cancel the task, and return an error.
214 console.error('Unknown progress type: ' + status.type);
215 chrome.fileBrowserPrivate.onCopyProgress.removeListener(
217 chrome.fileBrowserPrivate.cancelCopy(copyId);
218 errorCallback(util.createDOMError(
219 util.FileError.INVALID_STATE_ERR));
225 // Register the listener before calling startCopy. Otherwise some events
227 chrome.fileBrowserPrivate.onCopyProgress.addListener(onCopyProgress);
229 // Then starts the copy.
230 // TODO(mtomasz): Convert URL to Entry in custom bindings.
231 chrome.fileBrowserPrivate.startCopy(
232 source.toURL(), parent.toURL(), newName, function(startCopyId) {
233 // last error contains the FileError code on error.
234 if (chrome.runtime.lastError) {
235 // Unsubscribe the progress listener.
236 chrome.fileBrowserPrivate.onCopyProgress.removeListener(
238 errorCallback(util.createDOMError(chrome.runtime.lastError));
242 copyId = startCopyId;
243 for (var i = 0; i < pendingCallbacks.length; i++) {
244 pendingCallbacks[i]();
249 // If copyId is not yet available, wait for it.
250 if (copyId == null) {
251 pendingCallbacks.push(function() {
252 chrome.fileBrowserPrivate.cancelCopy(copyId);
257 chrome.fileBrowserPrivate.cancelCopy(copyId);
262 * Thin wrapper of chrome.fileBrowserPrivate.zipSelection to adapt its
263 * interface similar to copyTo().
265 * @param {Array.<Entry>} sources The array of entries to be archived.
266 * @param {DirectoryEntry} parent The entry of the destination directory.
267 * @param {string} newName The name of the archive to be created.
268 * @param {function(FileEntry)} successCallback Callback invoked when the
269 * operation is successfully done with the entry of the created archive.
270 * @param {function(FileError)} errorCallback Callback invoked when an error
273 fileOperationUtil.zipSelection = function(
274 sources, parent, newName, successCallback, errorCallback) {
275 // TODO(mtomasz): Pass Entries instead of URLs. Entries can be converted to
276 // URLs in custom bindings.
277 chrome.fileBrowserPrivate.zipSelection(
279 util.entriesToURLs(sources),
280 newName, function(success) {
282 // Failed to create a zip archive.
284 util.createDOMError(util.FileError.INVALID_MODIFICATION_ERR));
288 // Returns the created entry via callback.
290 newName, {create: false}, successCallback, errorCallback);
297 function FileOperationManager() {
298 this.copyTasks_ = [];
299 this.deleteTasks_ = [];
300 this.taskIdCounter_ = 0;
301 this.eventRouter_ = new FileOperationManager.EventRouter();
307 * Manages Event dispatching.
308 * Currently this can send three types of events: "copy-progress",
309 * "copy-operation-completed" and "delete".
311 * TODO(hidehiko): Reorganize the event dispatching mechanism.
313 * @extends {cr.EventTarget}
315 FileOperationManager.EventRouter = function() {
319 * Extends cr.EventTarget.
321 FileOperationManager.EventRouter.prototype.__proto__ = cr.EventTarget.prototype;
324 * Dispatches a simple "copy-progress" event with reason and current
325 * FileOperationManager status. If it is an ERROR event, error should be set.
327 * @param {string} reason Event type. One of "BEGIN", "PROGRESS", "SUCCESS",
328 * "ERROR" or "CANCELLED". TODO(hidehiko): Use enum.
329 * @param {Object} status Current FileOperationManager's status. See also
330 * FileOperationManager.Task.getStatus().
331 * @param {string} taskId ID of task related with the event.
332 * @param {FileOperationManager.Error=} opt_error The info for the error. This
333 * should be set iff the reason is "ERROR".
335 FileOperationManager.EventRouter.prototype.sendProgressEvent = function(
336 reason, status, taskId, opt_error) {
337 var event = new Event('copy-progress');
338 event.reason = reason;
339 event.status = status;
340 event.taskId = taskId;
342 event.error = opt_error;
343 this.dispatchEvent(event);
347 * Dispatches an event to notify that an entry is changed (created or deleted).
348 * @param {util.EntryChangedKind} kind The enum to represent if the entry is
349 * created or deleted.
350 * @param {Entry} entry The changed entry.
352 FileOperationManager.EventRouter.prototype.sendEntryChangedEvent = function(
354 var event = new Event('entry-changed');
357 this.dispatchEvent(event);
361 * Dispatches an event to notify entries are changed for delete task.
363 * @param {string} reason Event type. One of "BEGIN", "PROGRESS", "SUCCESS",
364 * or "ERROR". TODO(hidehiko): Use enum.
365 * @param {DeleteTask} task Delete task related with the event.
367 FileOperationManager.EventRouter.prototype.sendDeleteEvent = function(
369 var event = new Event('delete');
370 event.reason = reason;
371 event.taskId = task.taskId;
372 event.entries = task.entries;
373 event.totalBytes = task.totalBytes;
374 event.processedBytes = task.processedBytes;
375 this.dispatchEvent(event);
379 * A record of a queued copy operation.
381 * Multiple copy operations may be queued at any given time. Additional
382 * Tasks may be added while the queue is being serviced. Though a
383 * cancel operation cancels everything in the queue.
385 * @param {util.FileOperationType} operationType The type of this operation.
386 * @param {Array.<Entry>} sourceEntries Array of source entries.
387 * @param {DirectoryEntry} targetDirEntry Target directory.
390 FileOperationManager.Task = function(
391 operationType, sourceEntries, targetDirEntry) {
392 this.operationType = operationType;
393 this.sourceEntries = sourceEntries;
394 this.targetDirEntry = targetDirEntry;
397 * An array of map from url to Entry being processed.
398 * @type {Array.<Object<string, Entry>>}
400 this.processingEntries = null;
403 * Total number of bytes to be processed. Filled in initialize().
409 * Total number of already processed bytes. Updated periodically.
412 this.processedBytes = 0;
415 * Index of the progressing entry in sourceEntries.
419 this.processingSourceIndex_ = 0;
422 * Set to true when cancel is requested.
425 this.cancelRequested_ = false;
428 * Callback to cancel the running process.
429 * @private {function()}
431 this.cancelCallback_ = null;
433 // TODO(hidehiko): After we support recursive copy, we don't need this.
434 // If directory already exists, we try to make a copy named 'dir (X)',
435 // where X is a number. When we do this, all subsequent copies from
436 // inside the subtree should be mapped to the new directory name.
437 // For example, if 'dir' was copied as 'dir (1)', then 'dir\file.txt' should
438 // become 'dir (1)\file.txt'.
439 this.renamedDirectories_ = [];
443 * @param {function()} callback When entries resolved.
445 FileOperationManager.Task.prototype.initialize = function(callback) {
449 * Requests cancellation of this task.
450 * When the cancellation is done, it is notified via callbacks of run().
452 FileOperationManager.Task.prototype.requestCancel = function() {
453 this.cancelRequested_ = true;
454 if (this.cancelCallback_) {
455 this.cancelCallback_();
456 this.cancelCallback_ = null;
461 * Runs the task. Sub classes must implement this method.
463 * @param {function(util.EntryChangedKind, Entry)} entryChangedCallback
464 * Callback invoked when an entry is changed.
465 * @param {function()} progressCallback Callback invoked periodically during
467 * @param {function()} successCallback Callback run on success.
468 * @param {function(FileOperationManager.Error)} errorCallback Callback run on
471 FileOperationManager.Task.prototype.run = function(
472 entryChangedCallback, progressCallback, successCallback, errorCallback) {
476 * Get states of the task.
477 * TOOD(hirono): Removes this method and sets a task to progress events.
478 * @return {object} Status object.
480 FileOperationManager.Task.prototype.getStatus = function() {
481 var processingEntry = this.sourceEntries[this.processingSourceIndex_];
483 operationType: this.operationType,
484 numRemainingItems: this.sourceEntries.length - this.processingSourceIndex_,
485 totalBytes: this.totalBytes,
486 processedBytes: this.processedBytes,
487 processingEntryName: processingEntry ? processingEntry.name : ''
492 * Obtains the number of total processed bytes.
493 * @return {number} Number of total processed bytes.
496 FileOperationManager.Task.prototype.calcProcessedBytes_ = function() {
498 for (var i = 0; i < this.processingSourceIndex_ + 1; i++) {
499 var entryMap = this.processingEntries[i];
502 for (var name in entryMap) {
503 bytes += i < this.processingSourceIndex_ ?
504 entryMap[name].size : entryMap[name].processedBytes;
511 * Task to copy entries.
513 * @param {Array.<Entry>} sourceEntries Array of source entries.
514 * @param {DirectoryEntry} targetDirEntry Target directory.
515 * @param {boolean} deleteAfterCopy Whether the delete original files after
518 * @extends {FileOperationManager.Task}
520 FileOperationManager.CopyTask = function(sourceEntries,
523 FileOperationManager.Task.call(
526 util.FileOperationType.MOVE : util.FileOperationType.COPY,
529 this.deleteAfterCopy = deleteAfterCopy;
533 * Extends FileOperationManager.Task.
535 FileOperationManager.CopyTask.prototype.__proto__ =
536 FileOperationManager.Task.prototype;
539 * Initializes the CopyTask.
540 * @param {function()} callback Called when the initialize is completed.
542 FileOperationManager.CopyTask.prototype.initialize = function(callback) {
543 var group = new AsyncUtil.Group();
544 // Correct all entries to be copied for status update.
545 this.processingEntries = [];
546 for (var i = 0; i < this.sourceEntries.length; i++) {
547 group.add(function(index, callback) {
548 fileOperationUtil.resolveRecursively(
549 this.sourceEntries[index],
550 function(resolvedEntries) {
551 var resolvedEntryMap = {};
552 for (var j = 0; j < resolvedEntries.length; ++j) {
553 var entry = resolvedEntries[j];
554 entry.processedBytes = 0;
555 resolvedEntryMap[entry.toURL()] = entry;
557 this.processingEntries[index] = resolvedEntryMap;
562 'Failed to resolve for copy: %s', error.name);
568 group.run(function() {
571 for (var i = 0; i < this.processingEntries.length; i++) {
572 for (var entryURL in this.processingEntries[i])
573 this.totalBytes += this.processingEntries[i][entryURL].size;
581 * Copies all entries to the target directory.
582 * Note: this method contains also the operation of "Move" due to historical
585 * @param {function(util.EntryChangedKind, Entry)} entryChangedCallback
586 * Callback invoked when an entry is changed.
587 * @param {function()} progressCallback Callback invoked periodically during
589 * @param {function()} successCallback On success.
590 * @param {function(FileOperationManager.Error)} errorCallback On error.
593 FileOperationManager.CopyTask.prototype.run = function(
594 entryChangedCallback, progressCallback, successCallback, errorCallback) {
595 // TODO(hidehiko): We should be able to share the code to iterate on entries
596 // with serviceMoveTask_().
597 if (this.sourceEntries.length == 0) {
602 // TODO(hidehiko): Delete after copy is the implementation of Move.
603 // Migrate the part into MoveTask.run().
604 var deleteOriginals = function() {
605 var count = this.sourceEntries.length;
607 var onEntryDeleted = function(entry) {
608 entryChangedCallback(util.EntryChangedKind.DELETED, entry);
614 var onFilesystemError = function(err) {
615 errorCallback(new FileOperationManager.Error(
616 util.FileOperationErrorType.FILESYSTEM_ERROR, err));
619 for (var i = 0; i < this.sourceEntries.length; i++) {
620 var entry = this.sourceEntries[i];
621 util.removeFileOrDirectory(
622 entry, onEntryDeleted.bind(null, entry), onFilesystemError);
628 function(callback, entry, index) {
629 if (this.cancelRequested_) {
630 errorCallback(new FileOperationManager.Error(
631 util.FileOperationErrorType.FILESYSTEM_ERROR,
632 util.createDOMError(util.FileError.ABORT_ERR)));
637 entry, this.targetDirEntry,
638 function(sourceEntry, destinationEntry) {
639 // The destination entry may be null, if the copied file got
640 // deleted just after copying.
641 if (destinationEntry) {
642 entryChangedCallback(
643 util.EntryChangedKind.CREATED, destinationEntry);
646 function(sourceEntry, size) {
647 var sourceEntryURL = sourceEntry.toURL();
649 this.processingEntries[index][sourceEntryURL];
650 if (processedEntry) {
651 this.processedBytes += size - processedEntry.processedBytes;
652 processedEntry.processedBytes = size;
657 // Update current source index and processing bytes.
658 this.processingSourceIndex_ = index + 1;
659 this.processedBytes = this.calcProcessedBytes_();
665 if (this.deleteAfterCopy) {
675 * Copies the source entry to the target directory.
677 * @param {Entry} sourceEntry An entry to be copied.
678 * @param {DirectoryEntry} destinationEntry The entry which will contain the
680 * @param {function(Entry, Entry} entryChangedCallback
681 * Callback invoked when an entry is created with the source Entry and
682 * the destination Entry.
683 * @param {function(Entry, number)} progressCallback Callback invoked
684 * periodically during the copying.
685 * @param {function()} successCallback On success.
686 * @param {function(FileOperationManager.Error)} errorCallback On error.
689 FileOperationManager.CopyTask.prototype.processEntry_ = function(
690 sourceEntry, destinationEntry, entryChangedCallback, progressCallback,
691 successCallback, errorCallback) {
692 fileOperationUtil.deduplicatePath(
693 destinationEntry, sourceEntry.name,
694 function(destinationName) {
695 if (this.cancelRequested_) {
696 errorCallback(new FileOperationManager.Error(
697 util.FileOperationErrorType.FILESYSTEM_ERROR,
698 util.createDOMError(util.FileError.ABORT_ERR)));
701 this.cancelCallback_ = fileOperationUtil.copyTo(
702 sourceEntry, destinationEntry, destinationName,
703 entryChangedCallback, progressCallback,
705 this.cancelCallback_ = null;
709 this.cancelCallback_ = null;
710 errorCallback(new FileOperationManager.Error(
711 util.FileOperationErrorType.FILESYSTEM_ERROR, error));
718 * Task to move entries.
720 * @param {Array.<Entry>} sourceEntries Array of source entries.
721 * @param {DirectoryEntry} targetDirEntry Target directory.
723 * @extends {FileOperationManager.Task}
725 FileOperationManager.MoveTask = function(sourceEntries, targetDirEntry) {
726 FileOperationManager.Task.call(
727 this, util.FileOperationType.MOVE, sourceEntries, targetDirEntry);
731 * Extends FileOperationManager.Task.
733 FileOperationManager.MoveTask.prototype.__proto__ =
734 FileOperationManager.Task.prototype;
737 * Initializes the MoveTask.
738 * @param {function()} callback Called when the initialize is completed.
740 FileOperationManager.MoveTask.prototype.initialize = function(callback) {
741 // This may be moving from search results, where it fails if we
742 // move parent entries earlier than child entries. We should
743 // process the deepest entry first. Since move of each entry is
744 // done by a single moveTo() call, we don't need to care about the
745 // recursive traversal order.
746 this.sourceEntries.sort(function(entry1, entry2) {
747 return entry2.toURL().length - entry1.toURL().length;
750 this.processingEntries = [];
751 for (var i = 0; i < this.sourceEntries.length; i++) {
752 var processingEntryMap = {};
753 var entry = this.sourceEntries[i];
755 // The move should be done with updating the metadata. So here we assume
756 // all the file size is 1 byte. (Avoiding 0, so that progress bar can
758 // TODO(hidehiko): Remove this hack.
760 processingEntryMap[entry.toURL()] = entry;
761 this.processingEntries[i] = processingEntryMap;
768 * Moves all entries in the task.
770 * @param {function(util.EntryChangedKind, Entry)} entryChangedCallback
771 * Callback invoked when an entry is changed.
772 * @param {function()} progressCallback Callback invoked periodically during
774 * @param {function()} successCallback On success.
775 * @param {function(FileOperationManager.Error)} errorCallback On error.
778 FileOperationManager.MoveTask.prototype.run = function(
779 entryChangedCallback, progressCallback, successCallback, errorCallback) {
780 if (this.sourceEntries.length == 0) {
787 function(callback, entry, index) {
788 if (this.cancelRequested_) {
789 errorCallback(new FileOperationManager.Error(
790 util.FileOperationErrorType.FILESYSTEM_ERROR,
791 util.createDOMError(util.FileError.ABORT_ERR)));
795 FileOperationManager.MoveTask.processEntry_(
796 entry, this.targetDirEntry, entryChangedCallback,
798 // Update current source index.
799 this.processingSourceIndex_ = index + 1;
800 this.processedBytes = this.calcProcessedBytes_();
812 * Moves the sourceEntry to the targetDirEntry in this task.
814 * @param {Entry} sourceEntry An entry to be moved.
815 * @param {DirectoryEntry} destinationEntry The entry of the destination
817 * @param {function(util.EntryChangedKind, Entry)} entryChangedCallback
818 * Callback invoked when an entry is changed.
819 * @param {function()} successCallback On success.
820 * @param {function(FileOperationManager.Error)} errorCallback On error.
823 FileOperationManager.MoveTask.processEntry_ = function(
824 sourceEntry, destinationEntry, entryChangedCallback, successCallback,
826 fileOperationUtil.deduplicatePath(
829 function(destinationName) {
831 destinationEntry, destinationName,
832 function(movedEntry) {
833 entryChangedCallback(util.EntryChangedKind.CREATED, movedEntry);
834 entryChangedCallback(util.EntryChangedKind.DELETED, sourceEntry);
838 errorCallback(new FileOperationManager.Error(
839 util.FileOperationErrorType.FILESYSTEM_ERROR, error));
846 * Task to create a zip archive.
848 * @param {Array.<Entry>} sourceEntries Array of source entries.
849 * @param {DirectoryEntry} targetDirEntry Target directory.
850 * @param {DirectoryEntry} zipBaseDirEntry Base directory dealt as a root
853 * @extends {FileOperationManager.Task}
855 FileOperationManager.ZipTask = function(
856 sourceEntries, targetDirEntry, zipBaseDirEntry) {
857 FileOperationManager.Task.call(
858 this, util.FileOperationType.ZIP, sourceEntries, targetDirEntry);
859 this.zipBaseDirEntry = zipBaseDirEntry;
863 * Extends FileOperationManager.Task.
865 FileOperationManager.ZipTask.prototype.__proto__ =
866 FileOperationManager.Task.prototype;
870 * Initializes the ZipTask.
871 * @param {function()} callback Called when the initialize is completed.
873 FileOperationManager.ZipTask.prototype.initialize = function(callback) {
874 var resolvedEntryMap = {};
875 var group = new AsyncUtil.Group();
876 for (var i = 0; i < this.sourceEntries.length; i++) {
877 group.add(function(index, callback) {
878 fileOperationUtil.resolveRecursively(
879 this.sourceEntries[index],
881 for (var j = 0; j < entries.length; j++)
882 resolvedEntryMap[entries[j].toURL()] = entries[j];
889 group.run(function() {
890 // For zip archiving, all the entries are processed at once.
891 this.processingEntries = [resolvedEntryMap];
894 for (var url in resolvedEntryMap)
895 this.totalBytes += resolvedEntryMap[url].size;
902 * Runs a zip file creation task.
904 * @param {function(util.EntryChangedKind, Entry)} entryChangedCallback
905 * Callback invoked when an entry is changed.
906 * @param {function()} progressCallback Callback invoked periodically during
908 * @param {function()} successCallback On complete.
909 * @param {function(FileOperationManager.Error)} errorCallback On error.
912 FileOperationManager.ZipTask.prototype.run = function(
913 entryChangedCallback, progressCallback, successCallback, errorCallback) {
914 // TODO(hidehiko): we should localize the name.
915 var destName = 'Archive';
916 if (this.sourceEntries.length == 1) {
917 var entryName = this.sourceEntries[0].name;
918 var i = entryName.lastIndexOf('.');
919 destName = ((i < 0) ? entryName : entryName.substr(0, i));
922 fileOperationUtil.deduplicatePath(
923 this.targetDirEntry, destName + '.zip',
925 // TODO: per-entry zip progress update with accurate byte count.
926 // For now just set completedBytes to same value as totalBytes so
927 // that the progress bar is full.
928 this.processedBytes = this.totalBytes;
931 // The number of elements in processingEntries is 1. See also
934 for (var url in this.processingEntries[0])
935 entries.push(this.processingEntries[0][url]);
937 fileOperationUtil.zipSelection(
939 this.zipBaseDirEntry,
942 entryChangedCallback(util.EntryChangedKind.CREATE, entry);
946 errorCallback(new FileOperationManager.Error(
947 util.FileOperationErrorType.FILESYSTEM_ERROR, error));
954 * Error class used to report problems with a copy operation.
955 * If the code is UNEXPECTED_SOURCE_FILE, data should be a path of the file.
956 * If the code is TARGET_EXISTS, data should be the existing Entry.
957 * If the code is FILESYSTEM_ERROR, data should be the FileError.
959 * @param {util.FileOperationErrorType} code Error type.
960 * @param {string|Entry|FileError} data Additional data.
963 FileOperationManager.Error = function(code, data) {
968 // FileOperationManager methods.
971 * Adds an event listener for the tasks.
972 * @param {string} type The name of the event.
973 * @param {function(Event)} handler The handler for the event.
974 * This is called when the event is dispatched.
976 FileOperationManager.prototype.addEventListener = function(type, handler) {
977 this.eventRouter_.addEventListener(type, handler);
981 * Removes an event listener for the tasks.
982 * @param {string} type The name of the event.
983 * @param {function(Event)} handler The handler to be removed.
985 FileOperationManager.prototype.removeEventListener = function(type, handler) {
986 this.eventRouter_.removeEventListener(type, handler);
990 * Says if there are any tasks in the queue.
991 * @return {boolean} True, if there are any tasks.
993 FileOperationManager.prototype.hasQueuedTasks = function() {
994 return this.copyTasks_.length > 0 || this.deleteTasks_.length > 0;
998 * Completely clear out the copy queue, either because we encountered an error
999 * or completed successfully.
1003 FileOperationManager.prototype.resetQueue_ = function() {
1004 this.copyTasks_ = [];
1008 * Requests the specified task to be canceled.
1009 * @param {string} taskId ID of task to be canceled.
1011 FileOperationManager.prototype.requestTaskCancel = function(taskId) {
1013 for (var i = 0; i < this.copyTasks_.length; i++) {
1014 task = this.copyTasks_[i];
1015 if (task.taskId !== taskId)
1017 task.requestCancel();
1018 // If the task is not on progress, remove it immediately.
1020 this.eventRouter_.sendProgressEvent('CANCELED',
1023 this.copyTasks_.splice(i, 1);
1026 for (var i = 0; i < this.deleteTasks_.length; i++) {
1027 task = this.deleteTasks_[i];
1028 if (task.taskId !== taskId)
1030 task.cancelRequested = true;
1031 // If the task is not on progress, remove it immediately.
1033 this.eventRouter_.sendDeleteEvent('CANCELED', task);
1034 this.deleteTasks_.splice(i, 1);
1042 * @param {Array.<Entry>} sourceEntries Entries of the source files.
1043 * @param {DirectoryEntry} targetEntry The destination entry of the target
1045 * @param {boolean} isMove True if the operation is "move", otherwise (i.e.
1046 * if the operation is "copy") false.
1048 FileOperationManager.prototype.paste = function(
1049 sourceEntries, targetEntry, isMove) {
1050 // Do nothing if sourceEntries is empty.
1051 if (sourceEntries.length === 0)
1054 var filteredEntries = [];
1055 var resolveGroup = new AsyncUtil.Queue();
1058 for (var index = 0; index < sourceEntries.length; index++) {
1059 var sourceEntry = sourceEntries[index];
1060 resolveGroup.run(function(sourceEntry, callback) {
1061 sourceEntry.getParent(function(inParentEntry) {
1062 if (!util.isSameEntry(inParentEntry, targetEntry))
1063 filteredEntries.push(sourceEntry);
1067 'Failed to resolve the parent for: ' + sourceEntry.toURL());
1068 // Even if the parent is not available, try to move it.
1069 filteredEntries.push(sourceEntry);
1072 }.bind(this, sourceEntry));
1075 // Always copy all of the files.
1076 filteredEntries = sourceEntries;
1079 resolveGroup.run(function(callback) {
1080 // Do nothing, if we have no entries to be pasted.
1081 if (filteredEntries.length === 0)
1084 this.queueCopy_(targetEntry, filteredEntries, isMove);
1089 * Checks if the move operation is available between the given two locations.
1090 * This method uses the volume manager, which is lazily created, therefore the
1091 * result is returned asynchronously.
1093 * @param {DirectoryEntry} sourceEntry An entry from the source.
1094 * @param {DirectoryEntry} targetDirEntry Directory entry for the target.
1095 * @param {function(boolean)} callback Callback with result whether the entries
1096 * can be directly moved.
1099 FileOperationManager.prototype.isMovable_ = function(
1100 sourceEntry, targetDirEntry, callback) {
1101 VolumeManager.getInstance(function(volumeManager) {
1102 var sourceLocationInfo = volumeManager.getLocationInfo(sourceEntry);
1103 var targetDirLocationInfo = volumeManager.getLocationInfo(targetDirEntry);
1105 sourceLocationInfo && targetDirLocationInfo &&
1106 sourceLocationInfo.volumeInfo === targetDirLocationInfo.volumeInfo);
1111 * Initiate a file copy. When copying files, null can be specified as source
1114 * @param {DirectoryEntry} targetDirEntry Target directory.
1115 * @param {Array.<Entry>} entries Entries to copy.
1116 * @param {boolean} isMove In case of move.
1119 FileOperationManager.prototype.queueCopy_ = function(
1120 targetDirEntry, entries, isMove) {
1121 var createTask = function(task) {
1122 task.taskId = this.generateTaskId_();
1123 task.initialize(function() {
1124 this.copyTasks_.push(task);
1125 this.eventRouter_.sendProgressEvent(
1126 'BEGIN', task.getStatus(), task.taskId);
1127 if (this.copyTasks_.length === 1)
1128 this.serviceAllTasks_();
1134 // When moving between different volumes, moving is implemented as a copy
1135 // and delete. This is because moving between volumes is slow, and moveTo()
1136 // is not cancellable nor provides progress feedback.
1137 this.isMovable_(entries[0], targetDirEntry, function(isMovable) {
1139 createTask(new FileOperationManager.MoveTask(entries, targetDirEntry));
1142 new FileOperationManager.CopyTask(entries, targetDirEntry, true));
1147 new FileOperationManager.CopyTask(entries, targetDirEntry, false));
1152 * Service all pending tasks, as well as any that might appear during the
1157 FileOperationManager.prototype.serviceAllTasks_ = function() {
1158 if (!this.copyTasks_.length) {
1159 // All tasks have been serviced, clean up and exit.
1160 chrome.power.releaseKeepAwake();
1165 // Prevent the system from sleeping while copy is in progress.
1166 chrome.power.requestKeepAwake('system');
1168 var onTaskProgress = function() {
1169 this.eventRouter_.sendProgressEvent('PROGRESS',
1170 this.copyTasks_[0].getStatus(),
1171 this.copyTasks_[0].taskId);
1174 var onEntryChanged = function(kind, entry) {
1175 this.eventRouter_.sendEntryChangedEvent(kind, entry);
1178 var onTaskError = function(err) {
1179 var task = this.copyTasks_.shift();
1180 var reason = err.data.name === util.FileError.ABORT_ERR ?
1181 'CANCELED' : 'ERROR';
1182 this.eventRouter_.sendProgressEvent(reason,
1186 this.serviceAllTasks_();
1189 var onTaskSuccess = function() {
1190 // The task at the front of the queue is completed. Pop it from the queue.
1191 var task = this.copyTasks_.shift();
1192 this.eventRouter_.sendProgressEvent('SUCCESS',
1195 this.serviceAllTasks_();
1198 var nextTask = this.copyTasks_[0];
1199 this.eventRouter_.sendProgressEvent('PROGRESS',
1200 nextTask.getStatus(),
1202 nextTask.run(onEntryChanged, onTaskProgress, onTaskSuccess, onTaskError);
1206 * Timeout before files are really deleted (to allow undo).
1208 FileOperationManager.DELETE_TIMEOUT = 30 * 1000;
1211 * Schedules the files deletion.
1213 * @param {Array.<Entry>} entries The entries.
1215 FileOperationManager.prototype.deleteEntries = function(entries) {
1216 // TODO(hirono): Make FileOperationManager.DeleteTask.
1217 var task = Object.seal({
1219 taskId: this.generateTaskId_(),
1223 cancelRequested: false
1226 // Obtains entry size and sum them up.
1227 var group = new AsyncUtil.Group();
1228 for (var i = 0; i < task.entries.length; i++) {
1229 group.add(function(entry, callback) {
1230 entry.getMetadata(function(metadata) {
1231 var index = task.entries.indexOf(entries);
1232 task.entrySize[entry.toURL()] = metadata.size;
1233 task.totalBytes += metadata.size;
1236 // Fail to obtain the metadata. Use fake value 1.
1237 task.entrySize[entry.toURL()] = 1;
1238 task.totalBytes += 1;
1241 }.bind(this, task.entries[i]));
1244 // Add a delete task.
1245 group.run(function() {
1246 this.deleteTasks_.push(task);
1247 this.eventRouter_.sendDeleteEvent('BEGIN', task);
1248 if (this.deleteTasks_.length === 1)
1249 this.serviceAllDeleteTasks_();
1254 * Service all pending delete tasks, as well as any that might appear during the
1257 * Must not be called if there is an in-flight delete task.
1261 FileOperationManager.prototype.serviceAllDeleteTasks_ = function() {
1262 this.serviceDeleteTask_(
1263 this.deleteTasks_[0],
1265 this.deleteTasks_.shift();
1266 if (this.deleteTasks_.length)
1267 this.serviceAllDeleteTasks_();
1272 * Performs the deletion.
1274 * @param {Object} task The delete task (see deleteEntries function).
1275 * @param {function()} callback Callback run on task end.
1278 FileOperationManager.prototype.serviceDeleteTask_ = function(task, callback) {
1279 var queue = new AsyncUtil.Queue();
1281 // Delete each entry.
1283 var deleteOneEntry = function(inCallback) {
1284 if (!task.entries.length || task.cancelRequested || error) {
1288 this.eventRouter_.sendDeleteEvent('PROGRESS', task);
1289 util.removeFileOrDirectory(
1292 this.eventRouter_.sendEntryChangedEvent(
1293 util.EntryChangedKind.DELETED, task.entries[0]);
1294 task.processedBytes += task.entrySize[task.entries[0].toURL()];
1295 task.entries.shift();
1296 deleteOneEntry(inCallback);
1303 queue.run(deleteOneEntry);
1305 // Send an event and finish the async steps.
1306 queue.run(function(inCallback) {
1310 else if (task.cancelRequested)
1311 reason = 'CANCELED';
1314 this.eventRouter_.sendDeleteEvent(reason, task);
1321 * Creates a zip file for the selection of files.
1323 * @param {Entry} dirEntry The directory containing the selection.
1324 * @param {Array.<Entry>} selectionEntries The selected entries.
1326 FileOperationManager.prototype.zipSelection = function(
1327 dirEntry, selectionEntries) {
1328 var zipTask = new FileOperationManager.ZipTask(
1329 selectionEntries, dirEntry, dirEntry);
1330 zipTask.taskId = this.generateTaskId_(this.copyTasks_);
1332 zipTask.initialize(function() {
1333 this.copyTasks_.push(zipTask);
1334 this.eventRouter_.sendProgressEvent('BEGIN',
1335 zipTask.getStatus(),
1337 if (this.copyTasks_.length == 1)
1338 this.serviceAllTasks_();
1343 * Generates new task ID.
1345 * @return {string} New task ID.
1348 FileOperationManager.prototype.generateTaskId_ = function() {
1349 return 'file-operation-' + this.taskIdCounter_++;