summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/file_manager/js/file_copy_manager.js
blob: 24d024d0726840f9aeb91048227c4921d987f868 (plain)
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

function FileCopyManager(root) {
  this.copyTasks_ = [];
  this.cancelObservers_ = [];
  this.cancelRequested_ = false;
  this.root_ = root;
}

FileCopyManager.prototype = {
  __proto__: cr.EventTarget.prototype
};

/**
 * A record of a queued copy operation.
 *
 * Multiple copy operations may be queued at any given time.  Additional
 * Tasks may be added while the queue is being serviced.  Though a
 * cancel operation cancels everything in the queue.
 */
FileCopyManager.Task = function(sourceDirEntry, targetDirEntry) {
  this.sourceDirEntry = sourceDirEntry;
  this.targetDirEntry = targetDirEntry;
  this.originalEntries = null;

  this.pendingDirectories = [];
  this.pendingFiles = [];
  this.pendingBytes = 0;

  this.completedDirectories = [];
  this.completedFiles = [];
  this.completedBytes = 0;

  this.deleteAfterCopy = false;
  this.move = false;
  this.sourceOnGData = false;
  this.targetOnGData = false;

  // If directory already exists, we try to make a copy named 'dir (X)',
  // where X is a number. When we do this, all subsequent copies from
  // inside the subtree should be mapped to the new directory name.
  // For example, if 'dir' was copied as 'dir (1)', then 'dir\file.txt' should
  // become 'dir (1)\file.txt'.
  this.renamedDirectories_ = [];
};

FileCopyManager.Task.prototype.setEntries = function(entries, callback) {
  var self = this;

  function onEntriesRecursed(result) {
    self.pendingDirectories = result.dirEntries;
    self.pendingFiles = result.fileEntries;
    self.pendingBytes = result.fileBytes;
    callback();
  }

  this.originalEntries = entries;
  // When moving directories, FileEntry.moveTo() is used if both source
  // and target are on GData. There is no need to recurse into directories.
  var recurse = !this.move;
  util.recurseAndResolveEntries(entries, recurse, onEntriesRecursed);
};

FileCopyManager.Task.prototype.getNextEntry = function() {
  // We should keep the file in pending list and remove it after complete.
  // Otherwise, if we try to get status in the middle of copying. The returned
  // status is wrong (miss count the pasting item in totalItems).
  if (this.pendingDirectories.length) {
    this.pendingDirectories[0].inProgress = true;
    return this.pendingDirectories[0];
  }

  if (this.pendingFiles.length) {
    this.pendingFiles[0].inProgress = true;
    return this.pendingFiles[0];
  }

  return null;
};

FileCopyManager.Task.prototype.markEntryComplete = function(entry, size) {
  // It is probably not safe to directly remove the first entry in pending list.
  // We need to check if the removed entry (srcEntry) corresponding to the added
  // entry (target entry).
  if (entry.isDirectory && this.pendingDirectories &&
      this.pendingDirectories[0].inProgress) {
    this.completedDirectories.push(entry);
    this.pendingDirectories.shift();
  } else if (this.pendingFiles && this.pendingFiles[0].inProgress) {
    this.completedFiles.push(entry);
    this.completedBytes += size;
    this.pendingBytes -= size;
    this.pendingFiles.shift();
  } else {
    throw new Error('Try to remove a source entry which is not correspond to' +
                    ' the finished target entry');
  }
};

/**
 * Updates copy progress status for the entry.
 *
 * @param {Entry} entry Entry which is being coppied.
 * @param {number} size Number of bytes that has been copied since last update.
 */
FileCopyManager.Task.prototype.updateFileCopyProgress = function(entry, size) {
  if (entry.isFile && this.pendingFiles && this.pendingFiles[0].inProgress) {
    this.completedBytes += size;
    this.pendingBytes -= size;
  }
};

FileCopyManager.Task.prototype.registerRename = function(fromName, toName) {
  this.renamedDirectories_.push({from: fromName + '/', to: toName + '/'});
};

FileCopyManager.Task.prototype.applyRenames = function(path) {
  // Directories are processed in pre-order, so we will store only the first
  // renaming point:
  // x   -> x (1)    -- new directory created.
  // x\y -> x (1)\y  -- no more renames inside the new directory, so
  //                    this one will not be stored.
  // x\y\a.txt       -- only one rename will be applied.
  for (var index = 0; index < this.renamedDirectories_.length; ++index) {
    var rename = this.renamedDirectories_[index];
    if (path.indexOf(rename.from) == 0) {
      path = rename.to + path.substr(rename.from.length);
    }
  }
  return path;
};

/**
 * Error class used to report problems with a copy operation.
 */
FileCopyManager.Error = function(reason, data) {
  this.reason = reason;
  this.code = FileCopyManager.Error[reason];
  this.data = data;
};

FileCopyManager.Error.CANCELLED = 0;
FileCopyManager.Error.UNEXPECTED_SOURCE_FILE = 1;
FileCopyManager.Error.TARGET_EXISTS = 2;
FileCopyManager.Error.FILESYSTEM_ERROR = 3;

// FileCopyManager methods.

FileCopyManager.prototype.getStatus = function() {
  var rv = {
    pendingItems: 0,  // Files + Directories
    pendingFiles: 0,
    pendingDirectories: 0,
    pendingBytes: 0,

    completedItems: 0,  // Files + Directories
    completedFiles: 0,
    completedDirectories: 0,
    completedBytes: 0,

    // If source or target are on gdata we can't use completed bytes to track
    // progress.
    useBytesForPercentage: true
  };

  for (var i = 0; i < this.copyTasks_.length; i++) {
    var task = this.copyTasks_[i];
    rv.pendingFiles += task.pendingFiles.length;
    rv.pendingDirectories += task.pendingDirectories.length;
    rv.pendingBytes += task.pendingBytes;

    rv.completedFiles += task.completedFiles.length;
    rv.completedDirectories += task.completedDirectories.length;
    rv.completedBytes += task.completedBytes;
    if (task.sourceOnGData || task.targetOnGData)
      rv.useBytesForPercentage = false;
  }
  rv.pendingItems = rv.pendingFiles + rv.pendingDirectories;
  rv.completedItems = rv.completedFiles + rv.completedDirectories;

  rv.totalFiles = rv.pendingFiles + rv.completedFiles;
  rv.totalDirectories = rv.pendingDirectories + rv.completedDirectories;
  rv.totalItems = rv.pendingItems + rv.completedItems;
  rv.totalBytes = rv.pendingBytes + rv.completedBytes;

  return rv;
};

/**
 * Get the overall progress data of all queued copy tasks.
 * @return {Object} An object containing the following parameters:
 *    percentage - The percentage (0-1) of finished items.
 *    pendingItems - The number of pending/unfinished items.
 */
FileCopyManager.prototype.getProgress = function() {
  var status = this.getStatus();

  // TODO(tbarzic): We can't use completedBytes and totalBytes to estimate
  // progress if the file is transferred from/to drive for two reasons:
  // 1' completedBytes don't get updated for drive files.
  // 2' There is no way to get completed bytes in real time. If completed bytes
  //    are updated when each item finished and if there is a large item to be
  //    copied, the progress bar would stop moving until the item is finished
  //    and then jump a large portion of the bar.
  //
  // Obviously 2' > 1'.
  var percentage = status.useBytesForPercentage ?
      (status.completedBytes / status.totalBytes) :
      ((status.completedItems + 0.5) / status.totalItems);

  return {
    percentage: percentage,
    pendingItems: status.pendingItems
  };
};

/**
 * Dispatch a simple copy-progress event with reason and optional err data.
 */
FileCopyManager.prototype.sendProgressEvent_ = function(reason, opt_err) {
  var event = new cr.Event('copy-progress');
  event.reason = reason;
  if (opt_err)
    event.error = opt_err;
  this.dispatchEvent(event);
};

/**
 * Dispatch an event of file operation completion (allows to update the UI).
 * @param {string} reason Completed file operation: 'movied|copied|deleted'.
 * @param {Array.<Entry>} affectedEntries deleted ot created entries.
 */
FileCopyManager.prototype.sendOperationEvent_ = function(reason,
                                                         affectedEntries) {
  var event = new cr.Event('copy-operation-complete');
  event.reason = reason;
  event.affectedEntries = affectedEntries;
  this.dispatchEvent(event);
};

/**
 * Completely clear out the copy queue, either because we encountered an error
 * or completed successfully.
 */
FileCopyManager.prototype.resetQueue_ = function() {
  for (var i = 0; i < this.cancelObservers_.length; i++)
    this.cancelObservers_[i]();

  this.copyTasks_ = [];
  this.cancelObservers_ = [];
  this.cancelRequested_ = false;
};

/**
 * Request that the current copy queue be abandoned.
 */
FileCopyManager.prototype.requestCancel = function(opt_callback) {
  this.cancelRequested_ = true;
  if (opt_callback)
    this.cancelObservers_.push(opt_callback);
};

/**
 * Perform the bookeeping required to cancel.
 */
FileCopyManager.prototype.doCancel_ = function() {
  this.sendProgressEvent_('CANCELLED');
  this.resetQueue_();
};

/**
 * Used internally to check if a cancel has been requested, and handle
 * it if so.
 */
FileCopyManager.prototype.maybeCancel_ = function() {
  if (!this.cancelRequested_)
    return false;

  this.doCancel_();
  return true;
};

/**
 * Convert string in clipboard to entries and kick off pasting.
 */
FileCopyManager.prototype.paste = function(clipboard, targetPath,
                                           targetOnGData) {
  var self = this;
  var results = {
    sourceDirEntry: null,
    entries: [],
    isCut: false,
    isOnGData: false
  };

  function onPathError(err) {
    self.sendProgressEvent_('ERROR',
                            new FileCopyManager.Error('FILESYSTEM_ERROR', err));
  }

  function onSourceEntryFound(dirEntry) {
    function onTargetEntryFound(targetEntry) {
      self.queueCopy(results.sourceDirEntry,
            targetEntry,
            results.entries,
            results.isCut,
            results.isOnGData,
            targetOnGData);
    }

    function onComplete() {
      self.root_.getDirectory(targetPath, {},
                              onTargetEntryFound, onPathError);
    }

    function onEntryFound(entry) {
      // When getDirectories/getFiles finish, they call addEntry with null.
      // We dont want to add null to our entries.
      if (entry != null) {
        results.entries.push(entry);
        added++;
        if (added == total)
          onComplete();
      }
    }

    results.sourceDirEntry = dirEntry;
    var directories = [];
    var files = [];

    if (clipboard.directories) {
      directories = clipboard.directories.split('\n');
      directories = directories.filter(function(d) { return d != '' });
    }
    if (clipboard.files) {
      files = clipboard.files.split('\n');
      files = files.filter(function(f) { return f != '' });
    }

    var total = directories.length + files.length;
    var added = 0;

    results.isCut = (clipboard.isCut == 'true');
    results.isOnGData = (clipboard.isOnGData == 'true');

    util.getDirectories(self.root_, {create: false}, directories, onEntryFound,
                        onPathError);
    util.getFiles(self.root_, {create: false}, files, onEntryFound,
                  onPathError);
  }

  if (clipboard.sourceDir) {
    this.root_.getDirectory(clipboard.sourceDir,
                            {create: false},
                            onSourceEntryFound,
                            onPathError);
  } else {
    onSourceEntryFound(null);
  }
};

/**
 * Checks if source and target are on the same root.
 *
 * @param {DirectoryEntry} sourceEntry An entry from the source.
 * @param {DirectoryEntry} targetDirEntry Directory entry for the target.
 * @return {boolean} Whether source and target dir are on the same root.
 */
FileCopyManager.prototype.isOnSameRoot = function(sourceEntry,
                                                  targetDirEntry,
                                                  targetOnGData) {
  return DirectoryModel.getRootPath(sourceEntry.fullPath) ==
         DirectoryModel.getRootPath(targetDirEntry.fullPath);
};

/**
 * Initiate a file copy.
 */
FileCopyManager.prototype.queueCopy = function(sourceDirEntry,
                                               targetDirEntry,
                                               entries,
                                               deleteAfterCopy,
                                               sourceOnGData,
                                               targetOnGData) {
  var self = this;
  var copyTask = new FileCopyManager.Task(sourceDirEntry, targetDirEntry);
  if (deleteAfterCopy) {
    // |sourecDirEntry| may be null, so let's check the root for the first of
    // the entries scheduled to be copied.
    if (this.isOnSameRoot(entries[0], targetDirEntry)) {
      copyTask.move = true;
    } else {
      copyTask.deleteAfterCopy = true;
    }
  }
  copyTask.sourceOnGData = sourceOnGData;
  copyTask.targetOnGData = targetOnGData;
  copyTask.setEntries(entries, function() {
    self.copyTasks_.push(copyTask);
    if (self.copyTasks_.length == 1) {
      // This moved us from 0 to 1 active tasks, let the servicing begin!
      self.serviceAllTasks_();
    } else {
      // Force to update the progress of butter bar when there are new tasks
      // coming while servicing current task.
      self.sendProgressEvent_('PROGRESS');
    }
  });

  return copyTask;
};

/**
 * Service all pending tasks, as well as any that might appear during the
 * copy.
 */
FileCopyManager.prototype.serviceAllTasks_ = function() {
  var self = this;

  function onTaskError(err) {
    self.sendProgressEvent_('ERROR', err);
    self.resetQueue_();
  }

  function onTaskSuccess(task) {
    if (!self.copyTasks_.length) {
      // All tasks have been serviced, clean up and exit.
      self.sendProgressEvent_('SUCCESS');
      self.resetQueue_();
      return;
    }

    // We want to dispatch a PROGRESS event when there are more tasks to serve
    // right after one task finished in the queue. We treat all tasks as one
    // big task logically, so there is only one BEGIN/SUCCESS event pair for
    // these continuous tasks.
    self.sendProgressEvent_('PROGRESS');

    self.serviceNextTask_(onTaskSuccess, onTaskError);
  }

  // If the queue size is 1 after pushing our task, it was empty before,
  // so we need to kick off queue processing and dispatch BEGIN event.

  this.sendProgressEvent_('BEGIN');
  this.serviceNextTask_(onTaskSuccess, onTaskError);
};

/**
 * Service all entries in the next copy task.
 */
FileCopyManager.prototype.serviceNextTask_ = function(
    successCallback, errorCallback) {
  if (this.maybeCancel_())
    return;

  var self = this;
  var task = this.copyTasks_[0];

  function onFilesystemError(err) {
    errorCallback(new FileCopyManager.Error('FILESYSTEM_ERROR', err));
  }

  function onTaskComplete() {
    self.copyTasks_.shift();
    successCallback(task);
  }

  function deleteOriginals() {
    var count = task.originalEntries.length;

    function onEntryDeleted(entry) {
      self.sendOperationEvent_('deleted', [entry]);
      count--;
      if (!count)
        onTaskComplete();
    }

    for (var i = 0; i < task.originalEntries.length; i++) {
      var entry = task.originalEntries[i];
      util.removeFileOrDirectory(
          entry, onEntryDeleted.bind(self, entry), onFilesystemError);
    }
  }

  function onEntryServiced(targetEntry, size) {
    // We should not dispatch a PROGRESS event when there is no pending items
    // in the task.
    if (task.pendingDirectories.length + task.pendingFiles.length == 0) {
      if (task.deleteAfterCopy) {
        deleteOriginals();
      } else {
        onTaskComplete();
      }
      return;
    }

    self.sendProgressEvent_('PROGRESS');

    // We yield a few ms between copies to give the browser a chance to service
    // events (like perhaps the user clicking to cancel the copy, for example).
    setTimeout(function() {
      self.serviceNextTaskEntry_(task, onEntryServiced, errorCallback);
    }, 10);
  }

  this.serviceNextTaskEntry_(task, onEntryServiced, errorCallback);
};

/**
 * Service the next entry in a given task.
 */
FileCopyManager.prototype.serviceNextTaskEntry_ = function(
    task, successCallback, errorCallback) {
  if (this.maybeCancel_())
    return;

  var self = this;
  var sourceEntry = task.getNextEntry();

  if (!sourceEntry) {
    // All entries in this task have been copied.
    successCallback(null);
    return;
  }

  // |sourceEntry.originalSourcePath| is set in util.recurseAndResolveEntries.
  var sourcePath = sourceEntry.originalSourcePath;
  if (sourceEntry.fullPath.substr(0, sourcePath.length) != sourcePath) {
    // We found an entry in the list that is not relative to the base source
    // path, something is wrong.
    return onError('UNEXPECTED_SOURCE_FILE', sourceEntry.fullPath);
  }

  var targetDirEntry = task.targetDirEntry;
  var originalPath = sourceEntry.fullPath.substr(sourcePath.length + 1);

  originalPath = task.applyRenames(originalPath);

  var targetRelativePrefix = originalPath;
  var targetExt = '';
  var index = targetRelativePrefix.lastIndexOf('.');
  if (index != -1) {
    targetExt = targetRelativePrefix.substr(index);
    targetRelativePrefix = targetRelativePrefix.substr(0, index);
  }

  // If file already exists, we try to make a copy named 'file (1).ext'.
  // If file is already named 'file (X).ext', we go with 'file (X+1).ext'.
  // If new name is still occupied, we increase the number up to 10 times.
  var copyNumber = 0;
  var match = /^(.*?)(?: \((\d+)\))?$/.exec(targetRelativePrefix);
  if (match && match[2]) {
    copyNumber = parseInt(match[2], 10);
    targetRelativePrefix = match[1];
  }

  var targetRelativePath = '';
  var renameTries = 0;
  var firstExistingEntry = null;

  function onCopyCompleteBase(entry, size) {
    task.markEntryComplete(entry, size);
    successCallback(entry, size);
  }

  function onCopyComplete(entry, size) {
    self.sendOperationEvent_('copied', [entry]);
    onCopyCompleteBase(entry, size);
  }

  function onCopyProgress(entry, size) {
    task.updateFileCopyProgress(entry, size);
    self.sendProgressEvent_('PROGRESS');
  }

  function onError(reason, data) {
    console.log('serviceNextTaskEntry error: ' + reason + ':', data);
    errorCallback(new FileCopyManager.Error(reason, data));
  }

  function onFilesystemCopyComplete(sourceEntry, targetEntry) {
    // TODO(benchan): We currently do not know the size of data being
    // copied by FileEntry.copyTo(), so task.completedBytes will not be
    // increased. We will address this issue once we need to use
    // task.completedBytes to track the progress.
    self.sendOperationEvent_('copied', [sourceEntry, targetEntry]);
    onCopyCompleteBase(targetEntry, 0);
  }

  function onFilesystemMoveComplete(sourceEntry, targetEntry) {
    self.sendOperationEvent_('moved', [sourceEntry, targetEntry]);
    onCopyCompleteBase(targetEntry, 0);
  }

  function onFilesystemError(err) {
    onError('FILESYSTEM_ERROR', err);
  }

  function onTargetExists(existingEntry) {
    if (!firstExistingEntry)
      firstExistingEntry = existingEntry;
    renameTries++;
    if (renameTries < 10) {
      copyNumber++;
      tryNextCopy();
    } else {
      onError('TARGET_EXISTS', firstExistingEntry);
    }
  }

  /**
   * Resolves the immediate parent directory entry and the file name of a
   * given path, where the path is specified by a directory (not necessarily
   * the immediate parent) and a path (not necessarily the file name) related
   * to that directory. For instance,
   *   Given:
   *     |dirEntry| = DirectoryEntry('/root/dir1')
   *     |relativePath| = 'dir2/file'
   *
   *   Return:
   *     |parentDirEntry| = DirectoryEntry('/root/dir1/dir2')
   *     |fileName| = 'file'
   *
   * @param {DirectoryEntry} dirEntry A directory entry.
   * @param {string} relativePath A path relative to |dirEntry|.
   * @param {function(Entry,string)} A callback for returning the
   *        |parentDirEntry| and |fileName| upon success.
   * @param {function(FileError)} An error callback when there is an error
   *        getting |parentDirEntry|.
   */
  function resolveDirAndBaseName(dirEntry, relativePath,
                                 successCallback, errorCallback) {
    // |intermediatePath| contains the intermediate path components
    // that are appended to |dirEntry| to form |parentDirEntry|.
    var intermediatePath = '';
    var fileName = relativePath;

    // Extract the file name component from |relativePath|.
    var index = relativePath.lastIndexOf('/');
    if (index != -1) {
      intermediatePath = relativePath.substr(0, index);
      fileName = relativePath.substr(index + 1);
    }

    if (intermediatePath == '') {
      successCallback(dirEntry, fileName);
    } else {
      dirEntry.getDirectory(intermediatePath,
                            {create: false},
                            function(entry) {
                              successCallback(entry, fileName);
                            },
                            errorCallback);
    }
  }

  function onTargetNotResolved(err) {
    // We expect to be unable to resolve the target file, since we're going
    // to create it during the copy.  However, if the resolve fails with
    // anything other than NOT_FOUND, that's trouble.
    if (err.code != FileError.NOT_FOUND_ERR)
      return onError('FILESYSTEM_ERROR', err);

    if (task.move) {
      resolveDirAndBaseName(
          targetDirEntry, targetRelativePath,
          function(dirEntry, fileName) {
            sourceEntry.moveTo(dirEntry, fileName,
                               onFilesystemMoveComplete.bind(self, sourceEntry),
                               onFilesystemError);
          },
          onFilesystemError);
      return;
    }

    if (task.sourceOnGData && task.targetOnGData) {
      // TODO(benchan): GDataFileSystem has not implemented directory copy,
      // and thus we only call FileEntry.copyTo() for files. Revisit this
      // code when GDataFileSystem supports directory copy.
      if (!sourceEntry.isDirectory) {
        resolveDirAndBaseName(
            targetDirEntry, targetRelativePath,
            function(dirEntry, fileName) {
              sourceEntry.copyTo(dirEntry, fileName,
                  onFilesystemCopyComplete.bind(self, sourceEntry),
                  onFilesystemError);
            },
            onFilesystemError);
        return;
      }
    }

    // TODO(benchan): Until GDataFileSystem supports FileWriter, we use the
    // transferFile API to copy files into or out from a gdata file system.
    if (sourceEntry.isFile && (task.sourceOnGData || task.targetOnGData)) {
      var sourceFileUrl = sourceEntry.toURL();
      var targetFileUrl = targetDirEntry.toURL() + '/' + targetRelativePath;
      chrome.fileBrowserPrivate.transferFile(
        sourceFileUrl, targetFileUrl,
        function() {
          if (chrome.extension.lastError) {
            console.log(
                'Error copying ' + sourceFileUrl + ' to ' + targetFileUrl);
            onFilesystemError({
              code: chrome.extension.lastError.message,
              toGDrive: task.targetOnGData,
              sourceFileUrl: sourceFileUrl
            });
          } else {
            targetDirEntry.getFile(targetRelativePath, {},
                onFilesystemCopyComplete.bind(self, sourceEntry),
                onFilesystemError);
          }
        });
      return;
    }

    if (sourceEntry.isDirectory) {
      targetDirEntry.getDirectory(
          targetRelativePath,
          {create: true, exclusive: true},
          function(targetEntry) {
            if (targetRelativePath != originalPath) {
              task.registerRename(originalPath, targetRelativePath);
            }
            onCopyComplete(targetEntry);
          },
          util.flog('Error getting dir: ' + targetRelativePath,
                    onFilesystemError));
    } else {
      targetDirEntry.getFile(
          targetRelativePath,
          {create: true, exclusive: true},
          function(targetEntry) {
            self.copyEntry_(sourceEntry, targetEntry,
                            onCopyProgress, onCopyComplete, onError);
          },
          util.flog('Error getting file: ' + targetRelativePath,
                    onFilesystemError));
    }
  }

  function tryNextCopy() {
    targetRelativePath = targetRelativePrefix;
    if (copyNumber > 0) {
      targetRelativePath += ' (' + copyNumber + ')';
    }
    targetRelativePath += targetExt;

    // Check to see if the target exists.  This kicks off the rest of the copy
    // if the target is not found, or raises an error if it does.
    util.resolvePath(targetDirEntry, targetRelativePath, onTargetExists,
                     onTargetNotResolved);
  }

  tryNextCopy();
};

/**
 * Copy the contents of sourceEntry into targetEntry.
 *
 * @private
 * @param {Entry} sourceEntry entry that will be copied.
 * @param {Entry} targetEntry entry to which sourceEntry will be copied.
 * @param {function(Entry, number)} progressCallback function that will be
 *     called when a part of the source entry is copied. It takes |targetEntry|
 *     and size of the last copied chunk as parameters.
 * @param {function(Entry, number)} successCallback function that will be called
 *     the copy operation finishes. It takes |targetEntry| and size of the last
 *     (not previously reported) copied chunk as parameters.
 * @param {function{string, object}} errorCallback function that will be called
 *     if an error is encountered. Takes error type and additional error data
 *     as parameters.
 */
FileCopyManager.prototype.copyEntry_ = function(sourceEntry,
                                                targetEntry,
                                                progressCallback,
                                                successCallback,
                                                errorCallback) {
  if (this.maybeCancel_())
    return;

  self = this;
  function onSourceFileFound(file) {
    function onWriterCreated(writer) {
      var reportedProgress = 0;
      writer.onerror = function(progress) {
        errorCallback('FILESYSTEM_ERROR', writer.error);
      };

      writer.onprogress = function(progress) {
        if (self.maybeCancel_()) {
          // If the copy was canelled, we should abort the operation.
          writer.abort();
          return;
        }
        // |progress.loaded| will contain total amount of data copied by now.
        // |progressCallback| expects data amount delta from the last progress
        // update.
        progressCallback(targetEntry, progress.loaded - reportedProgress);
        reportedProgress = progress.loaded;
      };

      writer.onwriteend = function() {
        successCallback(targetEntry, file.size - reportedProgress);
      };

      writer.write(file);
    }

    targetEntry.createWriter(onWriterCreated, errorCallback);
  }

  sourceEntry.file(onSourceFileFound, errorCallback);
};