summaryrefslogtreecommitdiffstats
path: root/chrome/browser/resources/file_manager/js/directory_model.js
blob: f7457aec01ebe88b9b4adaa4f7c96df3daff9527 (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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
// 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.

// If directory files changes too often, don't rescan directory more than once
// per specified interval
const SIMULTANEOUS_RESCAN_INTERVAL = 1000;

/**
 * Data model of the file manager.
 *
 * @param {DirectoryEntry} root File system root.
 * @param {boolean} singleSelection True if only one file could be seletet
 *                                  at the time.
 */
function DirectoryModel(root, singleSelection) {
  this.root_ = root;
  this.fileList_ = new cr.ui.ArrayDataModel([]);
  this.fileListSelection_ = singleSelection ?
      new cr.ui.ListSingleSelectionModel() : new cr.ui.ListSelectionModel();

  this.runningScan_ = null;
  this.pendingScan_ = null;
  this.rescanTimeout_ = undefined;
  this.scanFailures_ = 0;

  // DirectoryEntry representing the current directory of the dialog.
  this.currentDirEntry_ = root;

  this.fileList_.prepareSort = this.prepareSort_.bind(this);
  this.autoSelectIndex_ = 0;

  this.rootsList_ = new cr.ui.ArrayDataModel([]);
  this.rootsListSelection_ = new cr.ui.ListSingleSelectionModel();
  this.rootsListSelection_.addEventListener(
      'change', this.onRootsSelectionChanged_.bind(this));

  // True if we should filter out files that start with a dot.
  this.filterHidden_ = true;

  // Readonly status for removable volumes.
  this.readonly_ = false;
}

/**
 * The name of the directory containing externally
 * mounted removable storage volumes.
 */
DirectoryModel.REMOVABLE_DIRECTORY = 'removable';

/**
 * The name of the directory containing externally
 * mounted archive file volumes.
 */
DirectoryModel.ARCHIVE_DIRECTORY = 'archive';

/**
 * Type of a root directory.
 * @enum
 */
DirectoryModel.RootType = {
  DOWNLOADS: 'downloads',
  ARCHIVE: 'archive',
  REMOVABLE: 'removable',
  GDATA: 'gdata'
};

/**
* The name of the downloads directory.
*/
DirectoryModel.DOWNLOADS_DIRECTORY = 'Downloads';

/**
* The name of the gdata provider directory.
*/
DirectoryModel.GDATA_DIRECTORY = 'gdata';

DirectoryModel.prototype = {
  __proto__: cr.EventTarget.prototype,

  /**
   * Files in the current directory.
   * @type {cr.ui.ArrayDataModel}
   */
  get fileList() {
    return this.fileList_;
  },

  /**
   * Selection in the fileList.
   * @type {cr.ui.ListSelectionModel|cr.ui.ListSingleSelectionModel}
   */
  get fileListSelection() {
    return this.fileListSelection_;
  },

  /**
   * Top level Directories from user perspective.
   * @type {cr.ui.ArrayDataModel}
   */
  get rootsList() {
    return this.rootsList_;
  },

  /**
   * Selection in the rootsList.
   * @type {cr.ui.ListSingleSelectionModel}
   */
  get rootsListSelection() {
    return this.rootsListSelection_;
  },

  /**
   * Root path for the current directory (parent directory is not navigatable
   * for the user).
   * @type {string}
   */
  get rootPath() {
    return DirectoryModel.getRootPath(this.currentEntry.fullPath);
  },

  get rootType() {
    return DirectoryModel.getRootType(this.currentEntry.fullPath);
  },

  /**
   * True if current directory is read only. Value may be set
   * for directories on a removable device.
   * @type {boolean}
   */
  get readonly() {
    switch (this.rootType) {
      case DirectoryModel.RootType.REMOVABLE:
        return this.readonly_;
      case DirectoryModel.RootType.ARCHIVE:
        return true;
      case DirectoryModel.RootType.DOWNLOADS:
        return false;
      case DirectoryModel.RootType.GDATA:
        return false;
      default:
        return true;
    }
  },

  set readonly(value) {
    if (this.rootType == DirectoryModel.RootType.REMOVABLE) {
      this.readonly_ = !!value;
    }
  },

  get isSystemDirectoy() {
    var path = this.currentEntry.fullPath;
    return path == '/' ||
           path == '/' + DirectoryModel.REMOVABLE_DIRECTORY ||
           path == '/' + DirectoryModel.ARCHIVE_DIRECTORY;
  },

  get filterHidden() {
    return this.filterHidden_;
  },

  set filterHidden(value) {
    if (this.filterHidden_ != value) {
      this.filterHidden_ = value;
      this.rescan();
    }
  },

  /**
   * Current directory.
   * @type {DirectoryEntry}
   */
  get currentEntry() {
    return this.currentDirEntry_;
  },

  set autoSelectIndex(value) {
    this.autoSelectIndex_ = value;
  },

  /**
   * Names of selected files.
   * @type {Array.<string>}
   */
  get selectedNames() {
    var indexes = this.fileListSelection_.selectedIndexes;
    var dataModel = this.fileList_;
    if (dataModel) {
      return indexes.map(function(i) {
        return dataModel.item(i).name;
      });
    }
    return [];
  },

  set selectedNames(value) {
    var indexes = [];
    var dataModel = this.fileList_;

    function safeKey(key) {
      // The transformation must:
      // 1. Never generate a reserved name ('__proto__')
      // 2. Keep different keys different.
      return '#' + key;
    }

    var hash = {};

    for (var i = 0; i < value.length; i++)
      hash[safeKey(value[i])] = 1;

    for (var i = 0; i < dataModel.length; i++) {
      if (hash.hasOwnProperty(safeKey(dataModel.item(i).name)))
        indexes.push(i);
    }
    this.fileListSelection_.selectedIndexes = indexes;
  },

  /**
   * Lead item file name.
   * @type {string?}
   */
  get leadName() {
    var index = this.fileListSelection_.leadIndex;
    return index >= 0 && this.fileList_.item(index).name;
  },

  set leadName(value) {
    for (var i = 0; i < this.fileList_.length; i++) {
      if (this.fileList_.item(i).name == value) {
        this.fileListSelection_.leadIndex = i;
        return;
      }
    }
  },

  /**
   * Schedule rescan with delay. If another rescan has been scheduled does
   * nothing. Designed to handle directory change notification. File operation
   * may cause a few notifications what should cause a single refresh.
   */
  rescanLater: function() {
    if (this.rescanTimeout_)
      return;  // Rescan already scheduled.

    var self = this;
    function onTimeout() {
      self.rescanTimeout_ = undefined;
      self.rescan();
    }
    this.rescanTimeout_ = setTimeout(onTimeout, SIMULTANEOUS_RESCAN_INTERVAL);
  },

  /**
   * Rescan current directory. May be called indirectly through rescanLater or
   * directly in order to reflect user action.
   */
  rescan: function() {
    if (this.rescanTimeout_) {
      clearTimeout(this.rescanTimeout_);
      this.rescanTimeout_ = undefined;
    }

    var fileList = [];
    var successCallback = (function() {
      this.replaceFileList_(fileList);
      cr.dispatchSimpleEvent(this, 'rescan-completed');
    }).bind(this);

    if (this.runningScan_) {
      if (!this.pendingScan_)
        this.pendingScan_ = this.createScanner_(fileList, successCallback);
      return;
    }

    this.runningScan_ = this.createScanner_(fileList, successCallback);
    this.runningScan_.run();
  },

  createScanner_: function(list, successCallback) {
    var self = this;
    function onSuccess() {
      self.scanFailures_ = 0;
      successCallback();
      if (self.pendingScan_) {
        self.runningScan_ = self.pendingScan_;
        self.pendingScan_ = null;
        self.runningScan_.run();
      } else {
        self.runningScan_ = null;
      }
    }

    function onFailure() {
      self.scanFailures_++;
      if (self.scanFailures_ <= 1)
        self.rescanLater();
    }

    return new DirectoryModel.Scanner(
        this.currentDirEntry_,
        list,
        onSuccess,
        onFailure,
        this.prefetchCacheForSorting_.bind(this),
        this.filterHidden_);
  },

  replaceFileList_: function(entries) {
    cr.dispatchSimpleEvent(this, 'begin-update-files');
    this.fileListSelection_.beginChange();

    var selectedNames = this.selectedNames;
    // Restore leadIndex in case leadName no longer exists.
    var leadIndex = this.fileListSelection_.leadIndex;
    var leadName = this.leadName;

    var spliceArgs = [].slice.call(entries);
    spliceArgs.unshift(0, this.fileList_.length);
    this.fileList_.splice.apply(this.fileList_, spliceArgs);

    this.selectedNames = selectedNames;
    this.fileListSelection_.leadIndex = leadIndex;
    this.leadName = leadName;
    this.fileListSelection_.endChange();
    cr.dispatchSimpleEvent(this, 'end-update-files');
  },

  /**
   * Cancels waiting and scheduled rescans and starts new scan.
   *
   * If the scan completes successfully on the first attempt, the callback will
   * be invoked and a 'scan-completed' event will be dispatched.  If the scan
   * fails for any reason, we'll periodically retry until it succeeds (and then
   * send a 'rescan-complete' event) or is cancelled or replaced by another
   * scan.
   *
   * @param {Function} callback Called if scan completes on the first attempt.
   *   Note that this will NOT be called if the scan fails but later succeeds.
   */
  scan_: function(callback) {
    if (this.rescanTimeout_) {
      clearTimeout(this.rescanTimeout_);
      this.rescanTimeout_ = 0;
    }
    if (this.runningScan_)
      this.runningScan_.cancel();
    this.pendingScan_ = null;

    var onDone = function() {
      cr.dispatchSimpleEvent(this, 'scan-completed');
      callback();
    }.bind(this);

    // Clear the table first.
    this.fileList_.splice(0, this.fileList_.length);
    cr.dispatchSimpleEvent(this, 'scan-started');
    this.runningScan_ = this.createScanner_(this.fileList_, onDone);
    this.runningScan_.run();
  },

  prefetchCacheForSorting_: function(entries, callback) {
    var field = this.fileList_.sortStatus.field;
    if (field) {
      this.prepareSortEntries_(entries, field, callback);
    } else {
      callback();
      return;
    }
  },

  /**
   * Delete the list of files and directories from filesystem and
   * update the file list.
   * @param {Array.<Entry>} entries Entries to delete.
   * @param {Function} opt_callback Called when finished.
   */
  deleteEntries: function(entries, opt_callback) {
    var downcount = entries.length + 1;

    var onComplete = opt_callback ? function() {
      if (--downcount == 0)
        opt_callback();
    } : function() {};

    const fileList = this.fileList_;
    for (var i = 0; i < entries.length; i++) {
      var entry = entries[i];

      var onSuccess = function(removedEntry) {
        var index = fileList.indexOf(removedEntry);
        if (index >= 0)
          fileList.splice(index, 1);
        onComplete();
      }.bind(null, entry);

      util.removeFileOrDirectory(
          entry,
          onSuccess,
          util.flog('Error deleting ' + entry.fullPath, onComplete));
    }
    onComplete();
  },

  /**
   * Rename the entry in the filesystem and update the file list.
   * @param {Entry} entry Entry to rename.
   * @param {string} newName
   * @param {Function} errorCallback Called on error.
   * @param {Function} opt_successCallback Called on success.
   */
  renameEntry: function(entry, newName, errorCallback, opt_successCallback) {
    var self = this;
    function onSuccess(newEntry) {
      self.prefetchCacheForSorting_([newEntry], function() {
        const fileList = self.fileList_;
        var index = fileList.indexOf(entry);
        if (index >= 0)
          fileList.splice(index, 1, newEntry);
        self.selectEntry(newName);
        // If the entry doesn't exist in the list it mean that it updated from
        // outside (probably by directory rescan).
        if (opt_successCallback)
          opt_successCallback();
      });
    }
    entry.moveTo(this.currentEntry, newName,
                 onSuccess, errorCallback);
  },

  /**
   * Checks if current directory contains a file or directory with this name.
   * @param {string} newName Name to check.
   * @param {function(boolean, boolean?)} callback Called when the result's
   *     available. First parameter is true if the entry exists and second
   *     is true if it's a file.
   */
  doesExist: function(newName, callback) {
    util.resolvePath(this.currentEntry, newName,
        function(entry) {
          callback(true, entry.isFile);
        },
        callback.bind(window, false));
  },

  /**
   * Creates directory and updates the file list.
   */
  createDirectory: function(name, successCallback, errorCallback) {
    const self = this;
    function onSuccess(newEntry) {
      self.prefetchCacheForSorting_([newEntry], function() {
        const fileList = self.fileList_;
        var existing = fileList.slice().filter(
            function(e) { return e.name == name; });

        if (existing.length) {
          self.selectEntry(name);
          successCallback(existing[0]);
        } else {
          self.fileListSelection.beginChange();
          fileList.splice(0, 0, newEntry);
          self.selectEntry(name);
          self.fileListSelection.endChange();
          successCallback(newEntry);
        }
      });
    }

    this.currentEntry.getDirectory(name, {create: true, exclusive: true},
                                   onSuccess, errorCallback);
  },

  /**
   * Canges directory. Causes 'directory-change' event.
   *
   * @param {string} path New current directory path.
   */
  changeDirectory: function(path) {
    var onDirectoryResolved = function(dirEntry) {
      var autoSelect = this.selectIndex.bind(this, this.autoSelectIndex_);
      this.changeDirectoryEntry_(dirEntry, autoSelect, false);
    }.bind(this);

    this.readonly_ = false;
    if (path == '/')
      return onDirectoryResolved(this.root_);

    this.root_.getDirectory(
        path, {create: false},
        onDirectoryResolved,
        function(error) {
          // TODO(serya): We should show an alert.
          console.error('Error changing directory to: ' + path + ', ' + error);
        });
  },

  /**
   * Change the current directory to the directory represented by a
   * DirectoryEntry.
   *
   * Dispatches the 'directory-changed' event when the directory is successfully
   * changed.
   *
   * @param {DirectoryEntry} dirEntry The absolute path to the new directory.
   * @param {function} action Action executed if the directory loads
   *    successfully.  By default selects the first item (unless it's a save
   *    dialog).
   * @param {boolean} initial True if it comes from setupPath and
   *                          false if caused by an user action.
   */
  changeDirectoryEntry_: function(dirEntry, action, initial) {
    var current = this.currentEntry;
    this.currentDirEntry_ = dirEntry;
    function onRescanComplete() {
      action();
      // For tests that open the dialog to empty directories, everything
      // is loaded at this point.
      chrome.test.sendMessage('directory-change-complete');
    }
    this.updateRootsListSelection_();
    this.scan_(onRescanComplete);

    var e = new cr.Event('directory-changed');
    e.previousDirEntry = this.currentEntry;
    e.newDirEntry = dirEntry;
    e.initial = initial;
    this.dispatchEvent(e);
  },

  /**
   * Change the state of the model to reflect the specified path (either a
   * file or directory).
   *
   * @param {string} path The root path to use
   * @param {Function=} opt_loadedCallback Invoked when the entire directory
   *     has been loaded and any default file selected.  If there are any
   *     errors loading the directory this will not get called (even if the
   *     directory loads OK on retry later).
   * @param {Function=} opt_pathResolveCallback Invoked as soon as the path has
   *     been resolved, and called with the base and leaf portions of the path
   *     name, and a flag indicating if the entry exists.
   */
  setupPath: function(path, opt_loadedCallback, opt_pathResolveCallback) {
    // Split the dirname from the basename.
    var ary = path.match(/^(?:(.*)\/)?([^\/]*)$/);
    var autoSelect = function() {
          this.selectIndex(this.autoSelectIndex_);
          if (opt_loadedCallback)
            opt_loadedCallback();
    }.bind(this);

    if (!ary) {
      console.warn('Unable to split default path: ' + path);
      this.changeDirectoryEntry_(this.root_, autoSelect, true);
      return;
    }

    var baseName = ary[1];
    var leafName = ary[2];

    function resolveCallback(exists) {
      if (opt_pathResolveCallback)
        opt_pathResolveCallback(baseName, leafName, exists);
    }

    function onLeafFound(baseDirEntry, leafEntry) {
      if (leafEntry.isDirectory) {
        baseName = path;
        leafName = '';
        resolveCallback(true);
        this.changeDirectoryEntry_(leafEntry, autoSelect, true);
        return;
      }

      resolveCallback(true);
      // Leaf is an existing file, cd to its parent directory and select it.
      this.changeDirectoryEntry_(baseDirEntry,
                                 function() {
                                   this.selectEntry(leafEntry.name);
                                   if (opt_loadedCallback)
                                     opt_loadedCallback();
                                 }.bind(this),
                                 false /*HACK*/);
      // TODO(kaznacheev): Fix history.replaceState for the File Browser and
      // change the last parameter back to |true|. Passing |false| makes things
      // less ugly for now.
    }

    function onLeafError(baseDirEntry, err) {
      resolveCallback(false);
      // Usually, leaf does not exist, because it's just a suggested file name.
      if (err != FileError.NOT_FOUND_ERR)
        console.log('Unexpected error resolving default leaf: ' + err);
      this.changeDirectoryEntry_(baseDirEntry, autoSelect, true);
    }

    var onBaseError = function(err) {
      resolveCallback(false);
      console.log('Unexpected error resolving default base "' +
                  baseName + '": ' + err);
      if (path != '/' + DirectoryModel.DOWNLOADS_DIRECTORY) {
        // Can't find the provided path, let's go to default one instead.
        this.setupDefaultPath(opt_loadedCallback);
      } else {
        // Well, we can't find the downloads dir. Let's just show something,
        // or we will get an infinite recursion.
        this.changeDirectoryEntry_(this.root_, opt_loadedCallback, true);
      }
    }.bind(this);

    var onBaseFound = function(baseDirEntry) {
      if (!leafName) {
        // Default path is just a directory, cd to it and we're done.
        this.changeDirectoryEntry_(baseDirEntry, autoSelect, true);
        return;
      }

      util.resolvePath(this.root_, path,
                       onLeafFound.bind(this, baseDirEntry),
                       onLeafError.bind(this, baseDirEntry));
    }.bind(this);

    var root = this.root_;
    if (baseName) {
      root.getDirectory(
          baseName, {create: false}, onBaseFound, onBaseError);
    } else {
      this.getDefaultDirectory_(function(defaultDir) {
        baseName = defaultDir;
        root.getDirectory(
            baseName, {create: false}, onBaseFound, onBaseError);
      });
    }
  },

  setupDefaultPath: function(opt_callback) {
    this.getDefaultDirectory_(function(path) {
      this.setupPath(path, opt_callback);
    }.bind(this));
  },

  getDefaultDirectory_: function(callback) {
    function onGetDirectoryComplete(entries, error) {
      if (entries.length > 0)
        callback(entries[0].fullPath);
      else
        callback('/' + DirectoryModel.DOWNLOADS_DIRECTORY);
    }

    // No preset given, find a good place to start.
    // Check for removable devices, if there are none, go to Downloads.
    util.readDirectory(this.root_, DirectoryModel.REMOVABLE_DIRECTORY,
                       onGetDirectoryComplete);
  },

  selectEntry: function(name) {
    var dm = this.fileList_;
    for (var i = 0; i < dm.length; i++) {
      if (dm.item(i).name == name) {
        this.selectIndex(i);
        return;
      }
    }
  },

  selectIndex: function(index) {
    // this.focusCurrentList_();
    if (index >= this.fileList_.length)
      return;

    // If a list bound with the model it will do scrollIndexIntoView(index).
    this.fileListSelection_.selectedIndex = index;
  },

  /**
   * Cache necessary data before a sort happens.
   *
   * This is called by the table code before a sort happens, so that we can
   * go fetch data for the sort field that we may not have yet.
   */
  prepareSort_: function(field, callback) {
    this.prepareSortEntries_(this.fileList_.slice(), field, callback);
  },

  prepareSortEntries_: function(entries, field, callback) {
    var cacheFunction;

    if (field == 'name' || field == 'cachedMtime_') {
      // Mtime is the tie-breaker for a name sort, so we need to resolve
      // it for both mtime and name sorts.
      cacheFunction = this.cacheEntryDateAndSize;
    } else if (field == 'cachedSize_') {
      cacheFunction = this.cacheEntryDateAndSize;
    } else if (field == 'type') {
      cacheFunction = this.cacheEntryFileType;
    } else if (field == 'cachedIconType_') {
      cacheFunction = this.cacheEntryIconType;
    } else {
      setTimeout(callback, 0);
      return;
    }

    // Start one fake wait to prevent calling the callback twice.
    var waitCount = 1;
    for (var i = 0; i < entries.length ; i++) {
      var entry = entries[i];
      if (!(field in entry)) {
        waitCount++;
        cacheFunction(entry, onCacheDone, onCacheDone);
      }
    }
    onCacheDone();  // Finish the fake callback.

    function onCacheDone() {
      waitCount--;
      // If all caching functions finished synchronously or entries.length = 0
      // call the callback synchronously.
      if (waitCount == 0)
        setTimeout(callback, 0);
    }
  },

  /**
   * Get root entries asynchronously. Invokes callback
   * when have finished.
   */
  resolveRoots_: function(callback) {
    var groups = {
      downloads: null,
      archives: null,
      removables: null,
      gdata: null
    };

    metrics.startInterval('Load.Roots');
    function done() {
      for (var i in groups)
        if (!groups[i])
          return;

      callback(groups.downloads.
               concat(groups.archives).
               concat(groups.removables).
               concat(groups.gdata));
      metrics.recordInterval('Load.Roots');
    }

    function append(index, values, opt_error) {
      groups[index] = values;
      done();
    }

    function onDownloads(entry) {
      groups.downloads = [entry];
      done();
    }

    function onDownloadsError(error) {
      groups.downloads = [];
      done();
    }

    function onGData(entry) {
      console.log('onGData');
      console.log(entry);
      groups.gdata = [entry];
      done();
    }

    function onGDataError(error) {
      console.log('onGDataError');
      console.log(error);
      groups.gdata = [];
      done();
    }

    var root = this.root_;
    root.getDirectory(DirectoryModel.DOWNLOADS_DIRECTORY, { create: false },
                      onDownloads, onDownloadsError);
    util.readDirectory(root, DirectoryModel.ARCHIVE_DIRECTORY,
                       append.bind(this, 'archives'));
    util.readDirectory(root, DirectoryModel.REMOVABLE_DIRECTORY,
                       append.bind(this, 'removables'));
    root.getDirectory(DirectoryModel.GDATA_DIRECTORY, { create: false },
                      onGData, onGDataError);
  },

  updateRoots: function(opt_callback) {
    console.log('directoryModel_.updateRoots');
    var self = this;
    this.resolveRoots_(function(rootEntries) {
      console.log('rootsList_ = ');
      console.log(self.rootsList_);
      var dm = self.rootsList_;
      var args = [0, dm.length].concat(rootEntries);
      dm.splice.apply(dm, args);

      self.updateRootsListSelection_();

      if (opt_callback)
        opt_callback();
    });
  },

  onRootsSelectionChanged_: function(event) {
    var root = this.rootsList.item(this.rootsListSelection.selectedIndex);
    var current = this.currentEntry.fullPath;
    if (root && this.rootPath != root.fullPath)
      this.changeDirectory(root.fullPath);
  },

  updateRootsListSelection_: function() {
    var roots = this.rootsList_;
    var rootPath = this.rootPath;
    for (var index = 0; index < roots.length; index++) {
      if (roots.item(index).fullPath == rootPath) {
        this.rootsListSelection.selectedIndex = index;
        return;
      }
    }
    this.rootsListSelection.selectedIndex = -1;
  }
};

DirectoryModel.getRootPath = function(path) {
  var type = DirectoryModel.getRootType(path);

  if (type == DirectoryModel.RootType.DOWNLOADS)
    return '/' + DirectoryModel.DOWNLOADS_DIRECTORY;
  if (type == DirectoryModel.RootType.GDATA)
    return '/' + DirectoryModel.GDATA_DIRECTORY;

  function subdir(dir) {
    var end = path.indexOf('/', dir.length + 2);
    return end == -1 ? path : path.substr(0, end);
  }

  if (type == DirectoryModel.RootType.ARCHIVE)
    return subdir(DirectoryModel.ARCHIVE_DIRECTORY);
  if (type == DirectoryModel.REMOVABLE_DIRECTORY)
    return subdir(DirectoryModel.REMOVABLE_DIRECTORY);
  return '/';
};

DirectoryModel.getRootType = function(path) {
  function isTop(dir) {
    return path.substr(1, dir.length) == dir;
  }

  if (isTop(DirectoryModel.DOWNLOADS_DIRECTORY))
    return DirectoryModel.RootType.DOWNLOADS;
  else if (isTop(DirectoryModel.GDATA_DIRECTORY))
    return DirectoryModel.RootType.GDATA;
  else if (isTop(DirectoryModel.ARCHIVE_DIRECTORY))
    return DirectoryModel.RootType.ARCHIVE;
  else if(isTop(DirectoryModel.REMOVABLE_DIRECTORY))
    return DirectoryModel.RootType.REMOVABLE;
  return '';
};

DirectoryModel.isRootPath = function(path) {
  if (path[path.length - 1] == '/')
    path = path.substring(0, path.length - 1);
  return DirectoryModel.getRootPath(path) == path;
};

/**
 * @constructor
 * @param {DirectoryEntry} dir Directory to scan.
 * @param {Array.<Entry>|cr.ui.ArrayDataModel} list Target to put the files.
 * @param {Function} successCallback Callback to call when (and if) scan
 *     successfully completed.
 * @param {Function} errorCallback Callback to call in case of IO error.
 * @param {function(Array.<Entry>):void, Function)} preprocessChunk
 *     Callback to preprocess each chunk of files.
 * @param {boolean} filterHidden True if files started with dots are ignored.
 */
DirectoryModel.Scanner = function(dir, list, successCallback, errorCallback,
                                  preprocessChunk, filterHidden) {
  this.cancelled_ = false;
  this.list_ = list;
  this.dir_ = dir;
  this.reader_ = null;
  this.filterHidden_ = !!filterHidden;
  this.preprocessChunk_ = preprocessChunk;
  this.successCallback_ = successCallback;
  this.errorCallback_ = errorCallback;
};

DirectoryModel.Scanner.prototype = {
  __proto__: cr.EventTarget.prototype,

  cancel: function() {
    this.cancelled_ = true;
  },

  run: function() {
    metrics.startInterval('DirectoryScan');

    this.reader_ = this.dir_.createReader();
    this.readNextChunk_();
  },

  readNextChunk_: function() {
    this.reader_.readEntries(this.onChunkComplete_.bind(this),
                             this.errorCallback_);
  },

  onChunkComplete_: function(entries) {
    if (this.cancelled_)
      return;

    if (entries.length == 0) {
      this.successCallback_();
      this.recordMetrics_();
      return;
    }

    // Splice takes the to-be-spliced-in array as individual parameters,
    // rather than as an array, so we need to perform some acrobatics...
    var spliceArgs = [].slice.call(entries);

    // Hide files that start with a dot ('.').
    // TODO(rginda): User should be able to override this. Support for other
    // commonly hidden patterns might be nice too.
    if (this.filterHidden_) {
      spliceArgs = spliceArgs.filter(function(e) {
        return e.name.substr(0, 1) != '.';
      });
    }

    var self = this;
    self.preprocessChunk_(spliceArgs, function() {
      spliceArgs.unshift(0, 0);  // index, deleteCount
      self.list_.splice.apply(self.list_, spliceArgs);

      // Keep reading until entries.length is 0.
      self.readNextChunk_();
    });
  },

  recordMetrics_: function() {
    metrics.recordInterval('DirectoryScan');
    if (this.dir_.fullPath ==
        '/' + DirectoryModel.DOWNLOADS_DIRECTORY) {
      metrics.recordMediumCount("DownloadsCount", this.list_.length);
    }
  }
};