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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
|
// 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
var SIMULTANEOUS_RESCAN_INTERVAL = 1000;
// Used for operations that require almost instant rescan.
var SHORT_RESCAN_INTERVAL = 100;
/**
* Data model of the file manager.
*
* @constructor
* @param {DirectoryEntry} root File system root.
* @param {boolean} singleSelection True if only one file could be selected
* at the time.
* @param {MetadataCache} metadataCache The metadata cache service.
* @param {VolumeManager} volumeManager The volume manager.
* @param {boolean} isGDataEnabled True if GDATA enabled (initial value).
*/
function DirectoryModel(root, singleSelection,
metadataCache, volumeManager, isGDataEnabled) {
this.root_ = root;
this.metadataCache_ = metadataCache;
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;
this.gDataEnabled_ = isGDataEnabled;
// DirectoryEntry representing the current directory of the dialog.
this.currentDirEntry_ = root;
this.fileList_.prepareSort = this.prepareSort_.bind(this);
this.rootsList_ = new cr.ui.ArrayDataModel([]);
this.rootsListSelection_ = new cr.ui.ListSingleSelectionModel();
this.rootsListSelection_.addEventListener(
'change', this.onRootChange_.bind(this));
/**
* A map root.fullPath -> currentDirectory.fullPath.
* @private
* @type {Object.<string, string>}
*/
this.currentDirByRoot_ = {};
// The map 'name' -> callback. Callbacks are function(entry) -> boolean.
this.filters_ = {};
this.setFilterHidden(true);
this.volumeManager_ = volumeManager;
/**
* Is search in progress.
* @private
* @type {boolean}
*/
this.isSearching_ = 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 = 'drive';
/**
* Fake entry to be used in currentDirEntry_ when current directory is
* unmounted GDATA.
* @private
*/
DirectoryModel.fakeGDataEntry_ = {
fullPath: '/' + DirectoryModel.GDATA_DIRECTORY
};
/**
* DirectoryModel extends cr.EventTarget.
*/
DirectoryModel.prototype.__proto__ = cr.EventTarget.prototype;
/**
* Fills the root list and starts tracking changes.
*/
DirectoryModel.prototype.start = function() {
var volumesChangeHandler = this.onMountChanged_.bind(this);
this.volumeManager_.addEventListener('change', volumesChangeHandler);
this.updateRoots_();
};
/**
* @return {cr.ui.ArrayDataModel} Files in the current directory.
*/
DirectoryModel.prototype.getFileList = function() {
return this.fileList_;
};
/**
* @return {MetadataCache} Metadata cache.
*/
DirectoryModel.prototype.getMetadataCache = function() {
return this.metadataCache_;
};
/**
* Sets whether GDATA appears in the roots list and
* if it could be used as current directory.
* @param {boolead} enabled True if GDATA enabled.
*/
DirectoryModel.prototype.setGDataEnabled = function(enabled) {
if (this.gDataEnabled_ == enabled)
return;
this.gDataEnabled_ = enabled;
this.updateRoots_();
if (!enabled && this.getCurrentRootType() == DirectoryModel.RootType.GDATA)
this.changeDirectory(this.getDefaultDirectory());
};
/**
* Sort the file list.
* @param {string} sortField Sort field.
* @param {string} sortDirection "asc" or "desc".
*/
DirectoryModel.prototype.sortFileList = function(sortField, sortDirection) {
this.fileList_.sort(sortField, sortDirection);
};
/**
* @return {cr.ui.ListSelectionModel|cr.ui.ListSingleSelectionModel} Selection
* in the fileList.
*/
DirectoryModel.prototype.getFileListSelection = function() {
return this.fileListSelection_;
};
/**
* @return {DirectoryModel.RootType} Root type of current root.
*/
DirectoryModel.prototype.getRootType = function() {
return DirectoryModel.getRootType(this.currentDirEntry_.fullPath);
};
/**
* @return {string} Root name.
*/
DirectoryModel.prototype.getRootName = function() {
return DirectoryModel.getRootName(this.currentDirEntry_.fullPath);
};
/**
* @return {boolean} on True if offline.
*/
DirectoryModel.prototype.isOffline = function() {
return this.offline_;
};
/**
* @param {boolean} offline True if offline.
*/
DirectoryModel.prototype.setOffline = function(offline) {
this.offline_ = offline;
};
/**
* @return {boolean} True if current directory is read only.
*/
DirectoryModel.prototype.isReadOnly = function() {
return this.isPathReadOnly(this.getCurrentRootPath());
};
/**
* @return {boolean} True if search is in progress.
*/
DirectoryModel.prototype.isSearching = function() {
return this.isSearching_;
};
/**
* @param {string} path Path to check.
* @return {boolean} True if the |path| is read only.
*/
DirectoryModel.prototype.isPathReadOnly = function(path) {
switch (DirectoryModel.getRootType(path)) {
case DirectoryModel.RootType.REMOVABLE:
return !!this.volumeManager_.isReadOnly(DirectoryModel.getRootPath(path));
case DirectoryModel.RootType.ARCHIVE:
return true;
case DirectoryModel.RootType.DOWNLOADS:
return false;
case DirectoryModel.RootType.GDATA:
return this.isOffline();
default:
return true;
}
};
/**
* @return {boolean} If the files with names starting with "." are not shown.
*/
DirectoryModel.prototype.isFilterHiddenOn = function() {
return !!this.filters_['hidden'];
};
/**
* @param {boolean} value Whether files with leading "." are hidden.
*/
DirectoryModel.prototype.setFilterHidden = function(value) {
if (value) {
this.addFilter('hidden',
function(e) {return e.name.substr(0, 1) != '.';});
} else {
this.removeFilter('hidden');
}
};
/**
* @return {DirectoryEntry} Current directory.
*/
DirectoryModel.prototype.getCurrentDirEntry = function() {
return this.currentDirEntry_;
};
/**
* @return {string} Path for the current directory.
*/
DirectoryModel.prototype.getCurrentDirPath = function() {
return this.currentDirEntry_.fullPath;
};
/**
* @private
* @return {Array.<string>} File paths of selected files.
*/
DirectoryModel.prototype.getSelectedPaths_ = function() {
var indexes = this.fileListSelection_.selectedIndexes;
var dataModel = this.fileList_;
if (dataModel) {
return indexes.map(function(i) {
return dataModel.item(i).fullPath;
});
}
return [];
};
/**
* @private
* @param {Array.<string>} value List of file paths of selected files.
*/
DirectoryModel.prototype.setSelectedPaths_ = function(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).fullPath)))
indexes.push(i);
}
this.fileListSelection_.selectedIndexes = indexes;
};
/**
* @private
* @return {string} Lead item file path.
*/
DirectoryModel.prototype.getLeadPath_ = function() {
var index = this.fileListSelection_.leadIndex;
return index >= 0 && this.fileList_.item(index).fullPath;
};
/**
* @private
* @param {string} value The name of new lead index.
*/
DirectoryModel.prototype.setLeadPath_ = function(value) {
for (var i = 0; i < this.fileList_.length; i++) {
if (this.fileList_.item(i).fullPath == value) {
this.fileListSelection_.leadIndex = i;
return;
}
}
};
/**
* @return {cr.ui.ArrayDataModel} The list of roots.
*/
DirectoryModel.prototype.getRootsList = function() {
return this.rootsList_;
};
/**
* @return {Entry} Directory entry of the current root.
*/
DirectoryModel.prototype.getCurrentRootDirEntry = function() {
return this.rootsList_.item(this.rootsListSelection_.selectedIndex);
};
/**
* @return {string} Root path for the current directory (parent directory is
* not navigatable for the user).
*/
DirectoryModel.prototype.getCurrentRootPath = function() {
return DirectoryModel.getRootPath(this.currentDirEntry_.fullPath);
};
/**
* @return {DirectoryModel.RootType} A root type.
*/
DirectoryModel.prototype.getCurrentRootType = function() {
return DirectoryModel.getRootType(this.currentDirEntry_.fullPath);
};
/**
* @return {cr.ui.ListSingleSelectionModel} Root list selection model.
*/
DirectoryModel.prototype.getRootsListSelectionModel = function() {
return this.rootsListSelection_;
};
/**
* Add a filter for directory contents.
* @param {string} name An identifier of the filter (used when removing it).
* @param {function(Entry):boolean} filter Hide file if false.
*/
DirectoryModel.prototype.addFilter = function(name, filter) {
this.filters_[name] = filter;
this.rescanSoon();
};
/**
* Remove one of the directory contents filters, specified by name.
* @param {string} name Identifier of a filter.
*/
DirectoryModel.prototype.removeFilter = function(name) {
if (this.filters_[name])
delete this.filters_[name];
this.rescanSoon();
};
/**
* Schedule rescan with short delay.
*/
DirectoryModel.prototype.rescanSoon = function() {
this.scheduleRescan(SHORT_RESCAN_INTERVAL);
};
/**
* Schedule rescan with delay. Designed to handle directory change
* notification.
*/
DirectoryModel.prototype.rescanLater = function() {
this.scheduleRescan(SIMULTANEOUS_RESCAN_INTERVAL);
};
/**
* Schedule rescan with delay. If another rescan has been scheduled does
* nothing. File operation may cause a few notifications what should cause
* a single refresh.
* @param {number} delay Delay in ms after which the rescan will be performed.
*/
DirectoryModel.prototype.scheduleRescan = function(delay) {
if (this.rescanTimeout_ && this.rescanTimeout_ <= delay)
return; // Rescan already scheduled.
var self = this;
function onTimeout() {
self.rescanTimeout_ = undefined;
self.rescan();
}
this.rescanTimeout_ = setTimeout(onTimeout, delay);
};
/**
* Rescan current directory. May be called indirectly through rescanLater or
* directly in order to reflect user action.
*/
DirectoryModel.prototype.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_) {
this.pendingScan_ = this.createScanner_(fileList, successCallback);
return;
}
this.runningScan_ = this.createScanner_(fileList, successCallback);
this.runningScan_.run();
};
/**
* @private
* @param {Array.<Entry>|cr.ui.ArrayDataModel} list File list.
* @param {function} successCallback Callback on success.
* @return {DirectoryModel.Scanner} New Scanner instance.
*/
DirectoryModel.prototype.createScanner_ = function(list, successCallback) {
var self = this;
/**
* Runs pending scan if there is one.
*
* @return {boolean} Did pending scan exist.
*/
function maybeRunPendingScan() {
if (self.pendingScan_) {
self.runningScan_ = self.pendingScan_;
self.pendingScan_ = null;
self.runningScan_.run();
return true;
}
self.runningScan_ = null;
return false;
}
function onSuccess() {
successCallback();
self.scanFailures_ = 0;
maybeRunPendingScan();
}
function onFailure() {
self.scanFailures_++;
if (maybeRunPendingScan())
return;
if (self.scanFailures_ <= 1)
self.rescanLater();
}
if (!this.isSearching() ||
this.getCurrentRootType() != DirectoryModel.RootType.GDATA) {
return new DirectoryModel.Scanner(
this.getCurrentDirEntry(),
list,
onSuccess,
onFailure,
this.prefetchCacheForSorting_.bind(this),
this.filters_);
} else {
return new DirectoryModel.GDataSearchScanner(
this.searchQuery_,
list,
onSuccess,
onFailure,
this.prefetchCacheForSorting_.bind(this),
this.filters_);
}
};
/**
* @private
* @param {Array.<Entry>} entries List of files.
*/
DirectoryModel.prototype.replaceFileList_ = function(entries) {
cr.dispatchSimpleEvent(this, 'begin-update-files');
this.fileListSelection_.beginChange();
var selectedPaths = this.getSelectedPaths_();
// Restore leadIndex in case leadName no longer exists.
var leadIndex = this.fileListSelection_.leadIndex;
var leadPath = this.getLeadPath_();
var spliceArgs = [].slice.call(entries);
spliceArgs.unshift(0, this.fileList_.length);
this.fileList_.splice.apply(this.fileList_, spliceArgs);
this.setSelectedPaths_(selectedPaths);
this.fileListSelection_.leadIndex = leadIndex;
this.setLeadPath_(leadPath);
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.
*
* @private
* @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.
*/
DirectoryModel.prototype.scan_ = function(callback) {
if (this.rescanTimeout_) {
clearTimeout(this.rescanTimeout_);
this.rescanTimeout_ = 0;
}
if (this.pendingScan_) {
this.pendingScan_ = null;
}
if (this.runningScan_) {
this.runningScan_.cancel();
this.runningScan_ = 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();
};
/**
* @private
* @param {Array.<Entry>} entries Files.
* @param {function} callback Callback on done.
*/
DirectoryModel.prototype.prefetchCacheForSorting_ = function(entries,
callback) {
var field = this.fileList_.sortStatus.field;
if (field) {
this.prepareSortEntries_(entries, field, callback);
} else {
callback();
}
};
/**
* 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.
*/
DirectoryModel.prototype.deleteEntries = function(entries, opt_callback) {
var downcount = entries.length + 1;
var onComplete = opt_callback ? function() {
if (--downcount == 0)
opt_callback();
} : function() {};
var 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();
};
/**
* @param {string} name Filename.
*/
DirectoryModel.prototype.onEntryChanged = function(name) {
var currentEntry = this.getCurrentDirEntry();
var dm = this.fileList_;
var self = this;
function onEntryFound(entry) {
// Do nothing if current directory changed during async operations.
if (self.getCurrentDirEntry() != currentEntry)
return;
self.prefetchCacheForSorting_([entry], function() {
// Do nothing if current directory changed during async operations.
if (self.getCurrentDirEntry() != currentEntry)
return;
var index = self.findIndexByName_(name);
if (index >= 0)
dm.splice(index, 1, entry);
else
dm.splice(dm.length, 0, entry);
});
};
function onError(err) {
// Do nothing if current directory changed during async operations.
if (self.currentDirEntry_ != currentEntry)
return;
if (err.code != FileError.NOT_FOUND_ERR) {
self.rescanLater();
return;
}
var index = self.findIndexByName_(name);
if (index >= 0)
dm.splice(index, 1);
};
util.resolvePath(currentEntry, name, onEntryFound, onError);
};
/**
* @private
* @param {string} name Filename.
* @return {number} The index in the fileList.
*/
DirectoryModel.prototype.findIndexByName_ = function(name) {
var dm = this.fileList_;
for (var i = 0; i < dm.length; i++)
if (dm.item(i).name == name)
return i;
return -1;
};
/**
* Rename the entry in the filesystem and update the file list.
* @param {Entry} entry Entry to rename.
* @param {string} newName New name.
* @param {function} errorCallback Called on error.
* @param {function} opt_successCallback Called on success.
*/
DirectoryModel.prototype.renameEntry = function(entry, newName,
errorCallback,
opt_successCallback) {
var self = this;
function onSuccess(newEntry) {
self.prefetchCacheForSorting_([newEntry], function() {
var index = self.findIndexByName_(entry.name);
if (index >= 0)
self.fileList_.splice(index, 1, newEntry);
self.selectEntry(newEntry.name);
// 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();
});
}
function onParentFound(parentEntry) {
entry.moveTo(parentEntry, newName, onSuccess, errorCallback);
}
entry.getParent(onParentFound, errorCallback);
};
/**
* Checks if current directory contains a file or directory with this name.
* @param {string} entry Entry to which newName will be given.
* @param {string} name 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.
*/
DirectoryModel.prototype.doesExist = function(entry, name, callback) {
function onParentFound(parentEntry) {
util.resolvePath(parentEntry, name,
function(foundEntry) {
callback(true, foundEntry.isFile);
},
callback.bind(window, false));
}
entry.getParent(onParentFound, callback.bind(window, false));
};
/**
* Creates directory and updates the file list.
*
* @param {string} name Directory name.
* @param {function} successCallback Callback on success.
* @param {function} errorCallback Callback on failure.
*/
DirectoryModel.prototype.createDirectory = function(name, successCallback,
errorCallback) {
var self = this;
function onSuccess(newEntry) {
self.prefetchCacheForSorting_([newEntry], function() {
var 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.currentDirEntry_.getDirectory(name, {create: true, exclusive: true},
onSuccess, errorCallback);
};
/**
* Changes directory. Causes 'directory-change' event.
*
* @param {string} path New current directory path.
*/
DirectoryModel.prototype.changeDirectory = function(path) {
this.resolveDirectory(path, function(directoryEntry) {
this.changeDirectoryEntry_(false, directoryEntry);
}.bind(this), function(error) {
console.error('Error changing directory to ' + path + ': ', error);
});
};
/**
* Resolves absolute directory path. Handles GData stub.
* @param {string} path Path to the directory.
* @param {function(DirectoryEntry} successCallback Success callback.
* @param {function(FileError} errorCallback Error callback.
*/
DirectoryModel.prototype.resolveDirectory = function(path, successCallback,
errorCallback) {
if (DirectoryModel.getRootType(path) == DirectoryModel.RootType.GDATA) {
if (!this.isGDataMounted_()) {
if (path == DirectoryModel.fakeGDataEntry_.fullPath)
successCallback(DirectoryModel.fakeGDataEntry_);
else // Subdirectory.
errorCallback({ code: FileError.NOT_FOUND_ERR });
return;
}
}
if (path == '/') {
successCallback(this.root_);
return;
}
this.root_.getDirectory(path, {create: false},
successCallback, errorCallback);
};
/**
* Handler for root item being clicked.
* @private
* @param {Entry} entry Entry to navigate to.
* @param {Event} event The event.
*/
DirectoryModel.prototype.onRootChange_ = function(entry, event) {
var newRootDir = this.getCurrentRootDirEntry();
if (newRootDir)
this.changeRoot(newRootDir.fullPath);
};
/**
* Changes directory. If path points to a root (except current one)
* then directory changed to the last used one for the root.
*
* @param {string} path New current directory path or new root.
*/
DirectoryModel.prototype.changeRoot = function(path) {
if (this.getCurrentRootPath() == path)
return;
if (this.currentDirByRoot_[path]) {
this.resolveDirectory(
this.currentDirByRoot_[path],
this.changeDirectoryEntry_.bind(this, false),
this.changeDirectory.bind(this, path));
} else {
this.changeDirectory(path);
}
};
/**
* Change the current directory to the directory represented by a
* DirectoryEntry.
*
* Dispatches the 'directory-changed' event when the directory is successfully
* changed.
*
* @private
* @param {boolean} initial True if it comes from setupPath and
* false if caused by an user action.
* @param {DirectoryEntry} dirEntry The absolute path to the new directory.
* @param {function} opt_callback Executed if the directory loads successfully.
*/
DirectoryModel.prototype.changeDirectoryEntry_ = function(initial, dirEntry,
opt_callback) {
if (dirEntry == DirectoryModel.fakeGDataEntry_)
this.volumeManager_.mountGData(function() {}, function() {});
this.clearSearch_();
var previous = this.currentDirEntry_;
this.currentDirEntry_ = dirEntry;
function onRescanComplete() {
if (opt_callback)
opt_callback();
// 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);
this.currentDirByRoot_[this.getCurrentRootPath()] = dirEntry.fullPath;
var e = new cr.Event('directory-changed');
e.previousDirEntry = previous;
e.newDirEntry = dirEntry;
e.initial = initial;
this.dispatchEvent(e);
};
/**
* Creates an object wich could say wether directory has changed while it has
* been active or not. Designed for long operations that should be canncelled
* if the used change current directory.
* @return {Object} Created object.
*/
DirectoryModel.prototype.createDirectoryChangeTracker = function() {
var tracker = {
dm_: this,
active_: false,
hasChanged: false,
exceptInitialChange: false,
start: function() {
if (!this.active_) {
this.dm_.addEventListener('directory-changed',
this.onDirectoryChange_);
this.active_ = true;
this.hasChanged = false;
}
},
stop: function() {
if (this.active_) {
this.dm_.removeEventListener('directory-changed',
this.onDirectoryChange_);
active_ = false;
}
},
onDirectoryChange_: function(event) {
// this == tracker.dm_ here.
if (tracker.exceptInitialChange && event.initial)
return;
tracker.stop();
tracker.hasChanged = true;
}
};
return tracker;
};
/**
* 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). Will NOT be called if another
* directory change happened while setupPath was in progress.
* @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. Will be called even
* if another directory change happened while setupPath was in progress,
* but will pass |false| as |exist| parameter.
*/
DirectoryModel.prototype.setupPath = function(path, opt_loadedCallback,
opt_pathResolveCallback) {
var tracker = this.createDirectoryChangeTracker();
tracker.start();
var self = this;
function resolveCallback(directoryPath, fileName, exists) {
tracker.stop();
if (!opt_pathResolveCallback)
return;
opt_pathResolveCallback(directoryPath, fileName,
exists && !tracker.hasChanged);
}
function changeDirectoryEntry(directoryEntry, initial, opt_callback) {
tracker.stop();
if (!tracker.hasChanged)
self.changeDirectoryEntry_(initial, directoryEntry, opt_callback);
}
var INITIAL = true;
var EXISTS = true;
function changeToDefault() {
var def = self.getDefaultDirectory();
self.resolveDirectory(def, function(directoryEntry) {
resolveCallback(def, '', !EXISTS);
changeDirectoryEntry(directoryEntry, INITIAL);
}, function(error) {
console.error('Failed to resolve default directory: ' + def, error);
resolveCallback('/', '', !EXISTS);
});
}
function noParentDirectory(error) {
console.log('Can\'t resolve parent directory: ' + path, error);
changeToDefault();
}
if (DirectoryModel.isSystemDirectory(path)) {
changeToDefault();
return;
}
this.resolveDirectory(path, function(directoryEntry) {
resolveCallback(directoryEntry.fullPath, '', !EXISTS);
changeDirectoryEntry(directoryEntry, INITIAL);
}, function(error) {
// Usually, leaf does not exist, because it's just a suggested file name.
var fileExists = error.code == FileError.TYPE_MISMATCH_ERR;
if (fileExists || error.code == FileError.NOT_FOUND_ERR) {
var nameDelimiter = path.lastIndexOf('/');
var parentDirectoryPath = path.substr(0, nameDelimiter);
if (DirectoryModel.isSystemDirectory(parentDirectoryPath)) {
changeToDefault();
return;
}
self.resolveDirectory(parentDirectoryPath,
function(parentDirectoryEntry) {
var fileName = path.substr(nameDelimiter + 1);
resolveCallback(parentDirectoryEntry.fullPath, fileName, fileExists);
changeDirectoryEntry(parentDirectoryEntry,
!INITIAL /*HACK*/,
function() {
self.selectEntry(fileName);
if (opt_loadedCallback)
opt_loadedCallback();
});
// TODO(kaznacheev): Fix history.replaceState for the File Browser and
// change !INITIAL to INITIAL. Passing |false| makes things
// less ugly for now.
}, noParentDirectory);
} else {
// Unexpected errors.
console.error('Directory resolving error: ', error);
changeToDefault();
}
});
};
/**
* @param {function} opt_callback Callback on done.
*/
DirectoryModel.prototype.setupDefaultPath = function(opt_callback) {
this.setupPath(this.getDefaultDirectory(), opt_callback);
};
/**
* @return {string} The default directory.
*/
DirectoryModel.prototype.getDefaultDirectory = function() {
return '/' + DirectoryModel.DOWNLOADS_DIRECTORY;
};
/**
* @param {string} name Filename.
*/
DirectoryModel.prototype.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;
}
}
};
/**
* @param {number} index Index of file.
*/
DirectoryModel.prototype.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.
* @private
* @param {string} field Sort field.
* @param {function} callback Called when done.
*/
DirectoryModel.prototype.prepareSort_ = function(field, callback) {
this.prepareSortEntries_(this.fileList_.slice(), field, callback);
};
/**
* @private
* @param {Array.<Entry>} entries Files.
* @param {string} field Sort field.
* @param {function} callback Called when done.
*/
DirectoryModel.prototype.prepareSortEntries_ = function(entries, field,
callback) {
this.metadataCache_.get(entries, 'filesystem', function(properties) {
callback();
});
};
/**
* Get root entries asynchronously.
* @private
* @param {function(Array.<Entry>)} callback Called when roots are resolved.
*/
DirectoryModel.prototype.resolveRoots_ = function(callback) {
var groups = {
downloads: null,
archives: null,
removables: null,
gdata: null
};
var self = this;
metrics.startInterval('Load.Roots');
function done() {
for (var i in groups)
if (!groups[i])
return;
callback(groups.downloads.
concat(groups.gdata).
concat(groups.archives).
concat(groups.removables));
metrics.recordInterval('Load.Roots');
}
function append(index, values, opt_error) {
groups[index] = values;
done();
}
function appendSingle(index, entry) {
groups[index] = [entry];
done();
}
function onSingleError(index, error, defaultValue) {
groups[index] = defaultValue || [];
done();
}
var root = this.root_;
function readSingle(dir, index, opt_defaultValue) {
root.getDirectory(dir, { create: false },
appendSingle.bind(this, index),
onSingleError.bind(this, index, opt_defaultValue));
}
readSingle(DirectoryModel.DOWNLOADS_DIRECTORY, 'downloads');
util.readDirectory(root, DirectoryModel.ARCHIVE_DIRECTORY,
append.bind(this, 'archives'));
util.readDirectory(root, DirectoryModel.REMOVABLE_DIRECTORY,
append.bind(this, 'removables'));
if (this.gDataEnabled_) {
var fake = [DirectoryModel.fakeGDataEntry_];
if (this.isGDataMounted_())
readSingle(DirectoryModel.GDATA_DIRECTORY, 'gdata', fake);
else
groups.gdata = fake;
} else {
groups.gdata = [];
}
};
/**
* Updates the roots list.
* @private
*/
DirectoryModel.prototype.updateRoots_ = function() {
var self = this;
this.resolveRoots_(function(rootEntries) {
var dm = self.rootsList_;
var args = [0, dm.length].concat(rootEntries);
dm.splice.apply(dm, args);
self.updateRootsListSelection_();
});
};
/**
* Find roots list item by root path.
*
* @param {string} path Root path.
* @return {number} Index of the item.
* @private
*/
DirectoryModel.prototype.findRootsListItem_ = function(path) {
var roots = this.rootsList_;
for (var index = 0; index < roots.length; index++) {
if (roots.item(index).fullPath == path)
return index;
}
return -1;
};
/**
* @private
*/
DirectoryModel.prototype.updateRootsListSelection_ = function() {
var rootPath = DirectoryModel.getRootPath(this.currentDirEntry_.fullPath);
this.rootsListSelection_.selectedIndex = this.findRootsListItem_(rootPath);
};
/**
* @return {true} True if GDATA mounted.
* @private
*/
DirectoryModel.prototype.isGDataMounted_ = function() {
return this.volumeManager_.isMounted('/' + DirectoryModel.GDATA_DIRECTORY);
};
/**
* Handler for the VolumeManager's event.
* @private
*/
DirectoryModel.prototype.onMountChanged_ = function() {
this.updateRoots_();
var rootType = this.getCurrentRootType();
if ((rootType == DirectoryModel.RootType.ARCHIVE ||
rootType == DirectoryModel.RootType.REMOVABLE) &&
!this.volumeManager_.isMounted(this.getCurrentRootPath())) {
this.changeDirectory(this.getDefaultDirectory());
}
if (rootType != DirectoryModel.RootType.GDATA)
return;
var mounted = this.isGDataMounted_();
if (this.currentDirEntry_ == DirectoryModel.fakeGDataEntry_) {
if (mounted) {
// Change fake entry to real one and rescan.
function onGotDirectory(entry) {
if (this.currentDirEntry_ == DirectoryModel.fakeGDataEntry_) {
this.currentDirEntry_ = entry;
this.rescan();
}
}
this.root_.getDirectory('/' + DirectoryModel.GDATA_DIRECTORY, {},
onGotDirectory.bind(this));
}
} else if (!mounted) {
// Current entry unmounted. replace with fake one.
if (this.currentDirEntry_.fullPath ==
DirectoryModel.fakeGDataEntry_.fullPath) {
// Replace silently and rescan.
this.currentDirEntry_ = DirectoryModel.fakeGDataEntry_;
this.rescan();
} else {
this.changeDirectoryEntry_(false, DirectoryModel.fakeGDataEntry_);
}
}
};
/**
* @param {string} path Path
* @return {boolean} If current directory is system.
*/
DirectoryModel.isSystemDirectory = function(path) {
path = path.replace(/\/+$/, '');
return path == '/' + DirectoryModel.REMOVABLE_DIRECTORY ||
path == '/' + DirectoryModel.ARCHIVE_DIRECTORY;
};
/**
* Performs search and displays results. The search type is dependent on the
* current directory. If we are currently on gdata, server side content search
* over gdata mount point. If the current directory is not on the gdata, file
* name search over current directory wil be performed.
*
* @param {string} query Query that will be searched for.
* @param {function} onSearchRescan Function that will be called when the search
* directory is rescanned (i.e. search results are displayed)
* @param {function} onClearSearch Function to be called when search state gets
* cleared.
*/
DirectoryModel.prototype.search = function(query,
onSearchRescan,
onClearSearch) {
if (!query) {
if (this.isSearching_)
this.clearSearch_();
return;
}
this.isSearching_ = true;
// If we alreaqdy have event listener for an old search, we have to remove it.
if (this.onSearchRescan_)
this.removeEventListener('rescan-completed', this.onSearchRescan_);
this.onSearchRescan_ = onSearchRescan;
this.onClearSearch_ = onClearSearch;
this.addEventListener('rescan-completed', this.onSearchRescan_);
// If we are offline, let's fallback to file name search inside dir.
if (this.getRootType() == DirectoryModel.RootType.GDATA &&
!this.isOffline()) {
var self = this;
this.searchQuery_ = query;
this.rescanSoon();
} else {
var queryLC = query.toLowerCase();
this.addFilter(
'searchbox',
function(e) {
return e.name.toLowerCase().indexOf(queryLC) > -1;
});
}
};
/**
* Clears any state set by previous searches.
* @private
*/
DirectoryModel.prototype.clearSearch_ = function() {
if (!this.isSearching_)
return;
this.searchQuery_ = null;
this.isSearching_ = false;
// This will trigger rescan.
this.removeFilter('searchbox');
if (this.onSearchRescan_) {
this.removeEventListener('rescan-completed', this.onSearchRescan_);
this.onSearchRescan_ = null;
}
if (this.onClearSearch_) {
this.onClearSearch_();
this.onClearSearch_ = null;
}
};
/**
* @param {string} path Any path.
* @return {string} The root path.
*/
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 '/';
};
/**
* @param {string} path Any path.
* @return {string} The name of the root.
*/
DirectoryModel.getRootName = function(path) {
var root = DirectoryModel.getRootPath(path);
var index = root.lastIndexOf('/');
return index == -1 ? root : root.substring(index + 1);
};
/**
* @param {string} path A path.
* @return {DirectoryModel.RootType} A root type.
*/
DirectoryModel.getRootType = function(path) {
function isTop(dir) {
return path.substr(1, dir.length) == dir;
}
if (isTop(DirectoryModel.DOWNLOADS_DIRECTORY))
return DirectoryModel.RootType.DOWNLOADS;
if (isTop(DirectoryModel.GDATA_DIRECTORY))
return DirectoryModel.RootType.GDATA;
if (isTop(DirectoryModel.ARCHIVE_DIRECTORY))
return DirectoryModel.RootType.ARCHIVE;
if (isTop(DirectoryModel.REMOVABLE_DIRECTORY))
return DirectoryModel.RootType.REMOVABLE;
return '';
};
/**
* @param {string} path A path.
* @return {boolean} True if it is a path to the root.
*/
DirectoryModel.isRootPath = function(path) {
if (path[path.length - 1] == '/')
path = path.substring(0, path.length - 1);
return DirectoryModel.getRootPath(path) == path;
};
/**
* @constructor
* @extends cr.EventTarget
* @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 {Object.<string, function(Entry):Boolean>} filters The map of filters
* for file entries.
*/
DirectoryModel.Scanner = function(dir, list, successCallback, errorCallback,
preprocessChunk, filters) {
this.cancelled_ = false;
this.list_ = list;
this.dir_ = dir;
this.reader_ = null;
this.filters_ = filters;
this.preprocessChunk_ = preprocessChunk;
this.successCallback_ = successCallback;
this.errorCallback_ = errorCallback;
};
/**
* Extends EventTarget.
*/
DirectoryModel.Scanner.prototype.__proto__ = cr.EventTarget.prototype;
/**
* Cancel scanner.
*/
DirectoryModel.Scanner.prototype.cancel = function() {
this.cancelled_ = true;
};
/**
* Start scanner.
*/
DirectoryModel.Scanner.prototype.run = function() {
if (this.dir_ == DirectoryModel.fakeGDataEntry_) {
if (!this.cancelled_)
this.successCallback_();
return;
}
metrics.startInterval('DirectoryScan');
this.reader_ = this.dir_.createReader();
this.readNextChunk_();
};
/**
* @private
*/
DirectoryModel.Scanner.prototype.readNextChunk_ = function() {
this.reader_.readEntries(this.onChunkComplete_.bind(this),
this.errorCallback_);
};
/**
* @private
* @param {Array.<Entry>} entries File list.
*/
DirectoryModel.Scanner.prototype.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);
for (var filterName in this.filters_) {
spliceArgs = spliceArgs.filter(this.filters_[filterName]);
}
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_();
});
};
/**
* @private
*/
DirectoryModel.Scanner.prototype.recordMetrics_ = function() {
metrics.recordInterval('DirectoryScan');
if (this.dir_.fullPath ==
'/' + DirectoryModel.DOWNLOADS_DIRECTORY) {
metrics.recordMediumCount('DownloadsCount', this.list_.length);
}
};
/**
* @constructor
* @extends cr.EventTarget
* @param {string} query Query to use in search.
* @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 {Object.<string, function(Entry):Boolean>} filters The map of filters
* for file entries.
*/
DirectoryModel.GDataSearchScanner = function(query, list, successCallback,
errorCallback, preprocessChunk, filters) {
this.query_ = query;
this.cancelled_ = false;
this.list_ = list;
this.filters_ = filters;
this.preprocessChunk_ = preprocessChunk;
this.successCallback_ = successCallback;
this.errorCallback_ = errorCallback;
};
/**
* Extends EventTarget.
*/
DirectoryModel.GDataSearchScanner.prototype.__proto__ =
cr.EventTarget.prototype;
/**
* Cancel scanner.
*/
DirectoryModel.GDataSearchScanner.prototype.cancel = function() {
this.cancelled_ = true;
};
/**
* Start scanner.
*/
DirectoryModel.GDataSearchScanner.prototype.run = function() {
chrome.fileBrowserPrivate.searchGData(this.query_,
this.onChunkComplete_.bind(this));
};
/**
* @private
* @param {Array.<Entry>} entries File list.
*/
DirectoryModel.GDataSearchScanner.prototype.onChunkComplete_ =
function(entries) {
if (this.cancelled_)
return;
if (!entries) {
this.errorCallback_();
return;
}
if (entries.length == 0) {
this.successCallback_();
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);
for (var filterName in this.filters_) {
spliceArgs = spliceArgs.filter(this.filters_[filterName]);
}
var self = this;
self.preprocessChunk_(spliceArgs, function() {
spliceArgs.unshift(0, 0); // index, deleteCount
self.list_.splice.apply(self.list_, spliceArgs);
self.successCallback_();
});
};
/**
* @constructor
* @param {DirectoryEntry} root Root entry.
* @param {DirectoryModel} directoryModel Model to watch.
* @param {VolumeManager} volumeManager Manager to watch.
*/
function FileWatcher(root, directoryModel, volumeManager) {
this.root_ = root;
this.dm_ = directoryModel;
this.vm_ = volumeManager;
this.watchedDirectoryEntry_ = null;
this.updateWatchedDirectoryBound_ =
this.updateWatchedDirectory_.bind(this);
this.onFileChangedBound_ =
this.onFileChanged_.bind(this);
}
/**
* Starts watching.
*/
FileWatcher.prototype.start = function() {
chrome.fileBrowserPrivate.onFileChanged.addListener(
this.onFileChangedBound_);
this.dm_.addEventListener('directory-changed',
this.updateWatchedDirectoryBound_);
this.vm_.addEventListener('change',
this.updateWatchedDirectoryBound_);
this.updateWatchedDirectory_();
};
/**
* Stops watching (must be called before page unload).
*/
FileWatcher.prototype.stop = function() {
chrome.fileBrowserPrivate.onFileChanged.removeListener(
this.onFileChangedBound_);
this.dm_.removeEventListener('directory-changed',
this.updateWatchedDirectoryBound_);
this.vm_.removeEventListener('change',
this.updateWatchedDirectoryBound_);
if (this.watchedDirectoryEntry_)
this.changeWatchedEntry(null);
};
/**
* @param {Object} event chrome.fileBrowserPrivate.onFileChanged event.
* @private
*/
FileWatcher.prototype.onFileChanged_ = function(event) {
if (encodeURI(event.fileUrl) == this.watchedDirectoryEntry_.toURL())
this.onFileInWatchedDirectoryChanged();
};
/**
* Called when file in the watched directory changed.
*/
FileWatcher.prototype.onFileInWatchedDirectoryChanged = function() {
this.dm_.rescanLater();
};
/**
* Called when directory changed or volumes mounted/unmounted.
* @private
*/
FileWatcher.prototype.updateWatchedDirectory_ = function() {
var current = this.watchedDirectoryEntry_;
switch (this.dm_.getCurrentRootType()) {
case DirectoryModel.RootType.GDATA:
if (!this.vm_.isMounted('/' + DirectoryModel.GDATA_DIRECTORY))
break;
case DirectoryModel.RootType.DOWNLOADS:
case DirectoryModel.RootType.REMOVABLE:
if (!current || current.fullPath != this.dm_.getCurrentDirPath()) {
// TODO(serya): Changed in readonly removable directoried don't
// need to be tracked.
this.root_.getDirectory(this.dm_.getCurrentDirPath(), {},
this.changeWatchedEntry.bind(this),
this.changeWatchedEntry.bind(this, null));
}
return;
}
if (current)
this.changeWatchedEntry(null);
};
/**
* @param {Entry?} entry Null if no directory need to be watched or
* directory to watch.
*/
FileWatcher.prototype.changeWatchedEntry = function(entry) {
if (this.watchedDirectoryEntry_) {
chrome.fileBrowserPrivate.removeFileWatch(
this.watchedDirectoryEntry_.toURL(),
function(result) {
if (!result) {
console.log('Failed to remove file watch');
}
});
}
this.watchedDirectoryEntry_ = entry;
if (this.watchedDirectoryEntry_) {
chrome.fileBrowserPrivate.addFileWatch(
this.watchedDirectoryEntry_.toURL(),
function(result) {
if (!result) {
console.log('Failed to add file watch');
if (this.watchedDirectoryEntry_ == entry)
this.watchedDirectoryEntry_ = null;
}
}.bind(this));
}
};
/**
* @return {DirectoryEntry} Current watched directory entry.
*/
FileWatcher.prototype.getWatchedDirectoryEntry = function() {
return this.watchedDirectoryEntry_;
};
|