-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
directory_model.js
1750 lines (1569 loc) · 56.3 KB
/
directory_model.js
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
// 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.
import {assert} from 'chrome://resources/js/assert.m.js';
import {dispatchSimpleEvent} from 'chrome://resources/js/cr.m.js';
import {NativeEventTarget as EventTarget} from 'chrome://resources/js/cr/event_target.m.js';
import {ListSelectionModel} from 'chrome://resources/js/cr/ui/list_selection_model.m.js';
import {ListSingleSelectionModel} from 'chrome://resources/js/cr/ui/list_single_selection_model.m.js';
import {AsyncUtil} from '../../common/js/async_util.js';
import {GuestOsPlaceholder} from '../../common/js/files_app_entry_types.js';
import {metrics} from '../../common/js/metrics.js';
import {util} from '../../common/js/util.js';
import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js';
import {FileOperationManager} from '../../externs/background/file_operation_manager.js';
import {EntriesChangedEvent} from '../../externs/entries_changed_event.js';
import {FakeEntry, FilesAppDirEntry, FilesAppEntry} from '../../externs/files_app_entry_interfaces.js';
import {PropStatus, State} from '../../externs/ts/state.js';
import {Store} from '../../externs/ts/store.js';
import {VolumeInfo} from '../../externs/volume_info.js';
import {VolumeManager} from '../../externs/volume_manager.js';
import {changeDirectory, searchAction} from '../../state/actions.js';
import {getStore} from '../../state/store.js';
import {constants} from './constants.js';
import {ContentScanner, CrostiniMounter, DirectoryContents, DirectoryContentScanner, DriveMetadataSearchContentScanner, DriveSearchContentScanner, FileFilter, FileListContext, GuestOsMounter, LocalSearchContentScanner, MediaViewContentScanner, RecentContentScanner, TrashContentScanner} from './directory_contents.js';
import {FileListModel} from './file_list_model.js';
import {FileWatcher} from './file_watcher.js';
import {MetadataModel} from './metadata/metadata_model.js';
import {FileListSelectionModel, FileListSingleSelectionModel} from './ui/file_list_selection_model.js';
// If directory files changes too often, don't rescan directory more than once
// per specified interval
const SIMULTANEOUS_RESCAN_INTERVAL = 500;
// Used for operations that require almost instant rescan.
const SHORT_RESCAN_INTERVAL = 100;
/**
* Data model of the file manager.
*/
export class DirectoryModel extends EventTarget {
/**
* @param {boolean} singleSelection True if only one file could be selected
* at the time.
* @param {FileFilter} fileFilter Instance of FileFilter.
* @param {!MetadataModel} metadataModel Metadata model.
* service.
* @param {!VolumeManager} volumeManager The volume manager.
* @param {!FileOperationManager} fileOperationManager File operation manager.
*/
constructor(
singleSelection, fileFilter, metadataModel, volumeManager,
fileOperationManager) {
super();
this.fileListSelection_ = singleSelection ?
new FileListSingleSelectionModel() :
new FileListSelectionModel();
this.runningScan_ = null;
this.pendingScan_ = null;
this.pendingRescan_ = null;
this.rescanTime_ = null;
this.scanFailures_ = 0;
this.changeDirectorySequence_ = 0;
/** @private {?function(Event): void} */
this.onSearchCompleted_ = null;
/** @private {?Function} */
this.onClearSearch_ = null;
/**
* @private {boolean}
*/
this.ignoreCurrentDirectoryDeletion_ = false;
this.directoryChangeQueue_ = new AsyncUtil.Queue();
/**
* Number of running directory change trackers.
* @private {number}
*/
this.numChangeTrackerRunning_ = 0;
this.rescanAggregator_ =
new AsyncUtil.Aggregator(this.rescanSoon.bind(this, true), 500);
this.fileFilter_ = fileFilter;
this.fileFilter_.addEventListener(
'changed', this.onFilterChanged_.bind(this));
this.currentFileListContext_ =
new FileListContext(fileFilter, metadataModel, volumeManager);
this.currentDirContents_ =
new DirectoryContents(this.currentFileListContext_, false, null, () => {
return new DirectoryContentScanner(null);
});
/**
* Empty file list which is used as a dummy for inactive view of file list.
* @private {!FileListModel}
*/
this.emptyFileList_ = new FileListModel(metadataModel);
this.metadataModel_ = metadataModel;
this.volumeManager_ = volumeManager;
this.volumeManager_.volumeInfoList.addEventListener(
'splice', this.onVolumeInfoListUpdated_.bind(this));
/**
* File watcher.
* @private {!FileWatcher}
* @const
*/
this.fileWatcher_ = new FileWatcher();
this.fileWatcher_.addEventListener(
'watcher-directory-changed',
this.onWatcherDirectoryChanged_.bind(this));
// For non-watchable directory (e.g. FakeEntry), we need to subscribe to
// the IOTask and manually refresh.
if (util.isRecentsFilterV2Enabled() || util.isTrashEnabled()) {
chrome.fileManagerPrivate.onIOTaskProgressStatus.addListener(
this.updateFileListAfterIOTask_.bind(this));
}
util.addEventListenerToBackgroundComponent(
fileOperationManager, 'entries-changed',
this.onEntriesChanged_.bind(this));
/** @private {string} */
this.lastSearchQuery_ = '';
/** @private {FilesAppDirEntry} */
this.myFilesEntry_ = null;
/** @private {!Store} */
this.store_ = getStore();
this.store_.subscribe(this);
}
/** @param {!State} state latest state from the store. */
onStateChanged(state) {
const currentEntry = this.getCurrentDirEntry();
const currentURL = currentEntry ? currentEntry.toURL() : null;
let newURL = state.currentDirectory ? state.currentDirectory.key : null;
// If the directory is the same, ignore it.
if (currentURL === newURL) {
return;
}
// When something changed the current directory status to STARTED, Here we
// initiate the actual change and will update to SUCCESS at the end.
if (state.currentDirectory.status == PropStatus.STARTED) {
newURL = /** @type {string} */ (newURL);
const entry =
state.allEntries[newURL] ? state.allEntries[newURL].entry : null;
if (!entry) {
// TODO(lucmult): Fix potential race condition in this await/then.
util.urlToEntry(newURL).then((entry) => {
if (!entry) {
console.error(`Failed to find the new directory key ${newURL}`);
return;
}
// Initiate the directory change.
this.changeDirectoryEntry(/** @type {!DirectoryEntry} */ (entry));
});
return;
}
// Initiate the directory change.
this.changeDirectoryEntry(/** @type {!DirectoryEntry} */ (entry));
}
}
/**
* Disposes the directory model by removing file watchers.
*/
dispose() {
this.fileWatcher_.dispose();
}
/**
* @return {FileListModel} Files in the current directory.
*/
getFileList() {
return this.currentFileListContext_.fileList;
}
/**
* @return {!FileListModel} File list which is always empty.
*/
getEmptyFileList() {
return this.emptyFileList_;
}
/**
* @return {!FileListSelectionModel|!FileListSingleSelectionModel} Selection
* in the fileList.
*/
getFileListSelection() {
return this.fileListSelection_;
}
/**
* Obtains current volume information.
* @return {VolumeInfo}
*/
getCurrentVolumeInfo() {
const entry = this.getCurrentDirEntry();
if (!entry) {
return null;
}
return this.volumeManager_.getVolumeInfo(entry);
}
/**
* @return {?VolumeManagerCommon.RootType} Root type of current root, or null
* if not found.
*/
getCurrentRootType() {
const entry = this.currentDirContents_.getDirectoryEntry();
if (!entry) {
return null;
}
const locationInfo = this.volumeManager_.getLocationInfo(entry);
if (!locationInfo) {
return null;
}
return locationInfo.rootType;
}
/**
* Metadata property names that are expected to be Prefetched.
* @return {!Array<string>}
*/
getPrefetchPropertyNames() {
return this.currentFileListContext_.prefetchPropertyNames;
}
/**
* @return {boolean} True if the current directory is read only. If there is
* no entry set, then returns true.
*/
isReadOnly() {
const currentDirEntry = this.getCurrentDirEntry();
if (currentDirEntry) {
const locationInfo = this.volumeManager_.getLocationInfo(currentDirEntry);
if (locationInfo) {
return locationInfo.isReadOnly;
}
}
return true;
}
/**
* @return {boolean} True if entries in the current directory can be deleted.
* Similar to !isReadOnly() except that we allow items in the read-only
* Trash root to be deleted. If there is no entry set, then returns false.
*/
canDeleteEntries() {
const currentDirEntry = this.getCurrentDirEntry();
if (currentDirEntry &&
currentDirEntry.rootType === VolumeManagerCommon.RootType.TRASH) {
return true;
}
return !this.isReadOnly();
}
/**
* @return {boolean} True if the a scan is active.
*/
isScanning() {
return this.currentDirContents_.isScanning();
}
/**
* @return {boolean} True if search is in progress.
*/
isSearching() {
return this.currentDirContents_.isSearch();
}
/**
* @return {boolean} True if it's on Drive.
*/
isOnDrive() {
return this.isCurrentRootVolumeType_(VolumeManagerCommon.VolumeType.DRIVE);
}
/**
* @return {boolean} True if it's on MTP volume.
*/
isOnMTP() {
return this.isCurrentRootVolumeType_(VolumeManagerCommon.VolumeType.MTP);
}
/**
* @return {boolean} True if the current volume is provided by FuseBox.
*/
isOnFuseBox() {
const info = this.getCurrentVolumeInfo();
return info ? info.diskFileSystemType === 'fusebox' : false;
}
/**
* @return {boolean} True if it's on a Linux native volume.
*/
isOnNative() {
const rootType = this.getCurrentRootType();
return rootType != null && !util.isRecentRootType(rootType) &&
VolumeManagerCommon.VolumeType.isNative(
VolumeManagerCommon.getVolumeTypeFromRootType(rootType));
}
/**
* @param {VolumeManagerCommon.VolumeType} volumeType Volume Type
* @return {boolean} True if current root volume type is equal to specified
* volume type.
* @private
*/
isCurrentRootVolumeType_(volumeType) {
const rootType = this.getCurrentRootType();
return rootType != null && !util.isRecentRootType(rootType) &&
VolumeManagerCommon.getVolumeTypeFromRootType(rootType) === volumeType;
}
/**
* Updates the selection by using the updateFunc and publish the change event.
* If updateFunc returns true, it force to dispatch the change event even if
* the selection index is not changed.
*
* @param {ListSelectionModel|ListSingleSelectionModel} selection
* Selection to be updated.
* @param {function(): boolean} updateFunc Function updating the selection.
* @private
*/
updateSelectionAndPublishEvent_(selection, updateFunc) {
// Begin change.
selection.beginChange();
// If dispatchNeeded is true, we should ensure the change event is
// dispatched.
let dispatchNeeded = updateFunc();
// Check if the change event is dispatched in the endChange function
// or not.
const eventDispatched = () => {
dispatchNeeded = false;
};
selection.addEventListener('change', eventDispatched);
selection.endChange();
selection.removeEventListener('change', eventDispatched);
// If the change event have been already dispatched, dispatchNeeded is
// false.
if (dispatchNeeded) {
const event = new Event('change');
// The selection status (selected or not) is not changed because
// this event is caused by the change of selected item.
event.changes = [];
selection.dispatchEvent(event);
}
}
/**
* Sets to ignore current directory deletion. This method is used to prevent
* going up to the volume root with the deletion of current directory by
* rename operation in directory tree.
* @param {boolean} value True to ignore current directory deletion.
*/
setIgnoringCurrentDirectoryDeletion(value) {
this.ignoreCurrentDirectoryDeletion_ = value;
}
/**
* Invoked when a change in the directory is detected by the watcher.
* @param {Event} event Event object.
* @private
*/
onWatcherDirectoryChanged_(event) {
const directoryEntry = this.getCurrentDirEntry();
if (!this.ignoreCurrentDirectoryDeletion_) {
// If the change is deletion of currentDir, move up to its parent
// directory.
directoryEntry.getDirectory(
directoryEntry.fullPath, {create: false}, () => {}, async () => {
const volumeInfo =
this.volumeManager_.getVolumeInfo(assert(directoryEntry));
if (volumeInfo) {
const displayRoot = await volumeInfo.resolveDisplayRoot();
this.changeDirectoryEntry(displayRoot);
}
});
}
if (event.changedFiles) {
const addedOrUpdatedFileUrls = [];
let deletedFileUrls = [];
event.changedFiles.forEach(change => {
if (change.changes.length === 1 && change.changes[0] === 'delete') {
deletedFileUrls.push(change.url);
} else {
addedOrUpdatedFileUrls.push(change.url);
}
});
util.URLsToEntries(addedOrUpdatedFileUrls)
.then(result => {
deletedFileUrls = deletedFileUrls.concat(result.failureUrls);
// Passing the resolved entries and failed URLs as the removed
// files. The URLs are removed files and they chan't be resolved.
this.partialUpdate_(result.entries, deletedFileUrls);
})
.catch(error => {
console.warn(
'Error in proceeding the changed event.', error,
'Fallback to force-refresh');
this.rescanAggregator_.run();
});
} else {
// Invokes force refresh if the detailed information isn't provided.
// This can occur very frequently (e.g. when copying files into Downloads)
// and rescan is heavy operation, so we keep some interval for each
// rescan.
this.rescanAggregator_.run();
}
}
/**
* Invoked when filters are changed.
* @private
*/
async onFilterChanged_() {
const currentDirectory = this.getCurrentDirEntry();
if (currentDirectory && util.isNativeEntry(currentDirectory) &&
!this.fileFilter_.filter(
/** @type {!DirectoryEntry} */ (currentDirectory))) {
// If the current directory should be hidden in the new filter setting,
// change the current directory to the current volume's root.
const volumeInfo = this.volumeManager_.getVolumeInfo(currentDirectory);
if (volumeInfo) {
const displayRoot = await volumeInfo.resolveDisplayRoot();
this.changeDirectoryEntry(displayRoot);
}
} else {
this.rescanSoon(false);
}
}
/**
* Returns the filter.
* @return {FileFilter} The file filter.
*/
getFileFilter() {
return this.fileFilter_;
}
/**
* @return {DirectoryEntry|FakeEntry|FilesAppDirEntry} Current directory.
*/
getCurrentDirEntry() {
return this.currentDirContents_.getDirectoryEntry();
}
/**
* @public
* @return {string}
*/
getCurrentDirName() {
const dirEntry = this.getCurrentDirEntry();
if (!dirEntry) {
return '';
}
const locationInfo = this.volumeManager_.getLocationInfo(dirEntry);
return util.getEntryLabel(locationInfo, dirEntry);
}
/**
* @return {Array<Entry>} Array of selected entries.
* @private
*/
getSelectedEntries_() {
const indexes = this.fileListSelection_.selectedIndexes;
const fileList = this.getFileList();
if (fileList) {
return indexes.map(i => fileList.item(i));
}
return [];
}
/**
* @param {Array<Entry>} value List of selected entries.
* @private
*/
setSelectedEntries_(value) {
const indexes = [];
const fileList = this.getFileList();
const urls = util.entriesToURLs(value);
for (let i = 0; i < fileList.length; i++) {
if (urls.indexOf(fileList.item(i).toURL()) !== -1) {
indexes.push(i);
}
}
this.fileListSelection_.selectedIndexes = indexes;
}
/**
* @return {Entry} Lead entry.
* @private
*/
getLeadEntry_() {
const index = this.fileListSelection_.leadIndex;
return index >= 0 ?
/** @type {Entry} */ (this.getFileList().item(index)) :
null;
}
/**
* @param {Entry} value The new lead entry.
* @private
*/
setLeadEntry_(value) {
const fileList = this.getFileList();
for (let i = 0; i < fileList.length; i++) {
if (util.isSameEntry(/** @type {Entry} */ (fileList.item(i)), value)) {
this.fileListSelection_.leadIndex = i;
return;
}
}
}
/**
* Schedule rescan with short delay.
* @param {boolean} refresh True to refresh metadata, or false to use cached
* one.
* @param {boolean=} invalidateCache True to invalidate the backend scanning
* result cache. This param only works if the corresponding backend
* scanning supports cache.
*/
rescanSoon(refresh, invalidateCache = false) {
this.scheduleRescan(SHORT_RESCAN_INTERVAL, refresh, invalidateCache);
}
/**
* Schedule rescan with delay. Designed to handle directory change
* notification.
* @param {boolean} refresh True to refresh metadata, or false to use cached
* one.
* @param {boolean=} invalidateCache True to invalidate the backend scanning
* result cache. This param only works if the corresponding backend
* scanning supports cache.
*/
rescanLater(refresh, invalidateCache = false) {
this.scheduleRescan(SIMULTANEOUS_RESCAN_INTERVAL, refresh, invalidateCache);
}
/**
* 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.
* @param {boolean} refresh True to refresh metadata, or false to use cached
* one.
* @param {boolean=} invalidateCache True to invalidate the backend scanning
* result cache. This param only works if the corresponding backend
* scanning supports cache.
*/
scheduleRescan(delay, refresh, invalidateCache = false) {
if (this.rescanTime_) {
if (this.rescanTime_ <= Date.now() + delay) {
return;
}
clearTimeout(this.rescanTimeoutId_);
}
const sequence = this.changeDirectorySequence_;
this.rescanTime_ = Date.now() + delay;
this.rescanTimeoutId_ = setTimeout(() => {
this.rescanTimeoutId_ = null;
if (sequence === this.changeDirectorySequence_) {
this.rescan(refresh, invalidateCache);
}
}, delay);
}
/**
* Cancel a rescan on timeout if it is scheduled.
* @private
*/
clearRescanTimeout_() {
this.rescanTime_ = null;
if (this.rescanTimeoutId_) {
clearTimeout(this.rescanTimeoutId_);
this.rescanTimeoutId_ = null;
}
}
/**
* Rescan current directory. May be called indirectly through rescanLater or
* directly in order to reflect user action. Will first cache all the
* directory contents in an array, then seamlessly substitute the fileList
* contents, preserving the select element etc.
*
* This should be to scan the contents of current directory (or search).
*
* @param {boolean} refresh True to refresh metadata, or false to use cached
* one.
* @param {boolean=} invalidateCache True to invalidate the backend scanning
* result cache. This param only works if the corresponding backend
* scanning supports cache.
*/
rescan(refresh, invalidateCache = false) {
this.clearRescanTimeout_();
if (this.runningScan_) {
this.pendingRescan_ = true;
return;
}
const dirContents = this.currentDirContents_.clone();
dirContents.setFileList(new FileListModel(this.metadataModel_));
dirContents.setMetadataSnapshot(
this.currentDirContents_.createMetadataSnapshot());
const sequence = this.changeDirectorySequence_;
const successCallback = () => {
if (sequence === this.changeDirectorySequence_) {
this.replaceDirectoryContents_(dirContents);
dispatchSimpleEvent(this, 'rescan-completed');
}
};
this.scan_(
dirContents, refresh, invalidateCache, successCallback, () => {},
() => {}, () => {});
}
/**
* Run scan on the current DirectoryContents. The active fileList is cleared
* and the entries are added directly.
*
* This should be used when changing directory or initiating a new search.
*
* @param {DirectoryContents} newDirContents New DirectoryContents instance to
* replace currentDirContents_.
* @param {function(boolean)} callback Callback with result. True if the scan
* is completed successfully, false if the scan is failed.
* @private
*/
clearAndScan_(newDirContents, callback) {
if (this.currentDirContents_.isScanning()) {
this.currentDirContents_.cancelScan();
}
this.currentDirContents_ = newDirContents;
this.clearRescanTimeout_();
if (this.pendingScan_) {
this.pendingScan_ = false;
}
if (this.runningScan_) {
if (this.runningScan_.isScanning()) {
this.runningScan_.cancelScan();
}
this.runningScan_ = null;
}
const sequence = this.changeDirectorySequence_;
let cancelled = false;
const onDone = () => {
if (cancelled) {
return;
}
dispatchSimpleEvent(this, 'scan-completed');
callback(true);
};
/** @param {DOMError} error error. */
const onFailed = error => {
if (cancelled) {
return;
}
const event = new Event('scan-failed');
event.error = error;
this.dispatchEvent(event);
callback(false);
};
const onUpdated = () => {
if (cancelled) {
return;
}
if (this.changeDirectorySequence_ !== sequence) {
cancelled = true;
dispatchSimpleEvent(this, 'scan-cancelled');
callback(false);
return;
}
dispatchSimpleEvent(this, 'scan-updated');
};
const onCancelled = () => {
if (cancelled) {
return;
}
cancelled = true;
dispatchSimpleEvent(this, 'scan-cancelled');
callback(false);
};
// Clear metadata information for the old (no longer visible) items in the
// file list.
const fileList = this.getFileList();
const removedUrls = [];
for (let i = 0; i < fileList.length; i++) {
removedUrls.push(fileList.item(i).toURL());
}
this.metadataModel_.notifyEntriesRemoved(removedUrls);
// Retrieve metadata information for the newly selected directory.
const currentEntry = this.currentDirContents_.getDirectoryEntry();
if (currentEntry) {
const locationInfo = this.volumeManager_.getLocationInfo(currentEntry);
if (locationInfo && locationInfo.isDriveBased) {
chrome.fileManagerPrivate.pollDriveHostedFilePinStates();
}
if (!util.isFakeEntry(currentEntry)) {
this.metadataModel_.get(
[currentEntry],
constants.LIST_CONTAINER_METADATA_PREFETCH_PROPERTY_NAMES.concat(
constants.DLP_METADATA_PREFETCH_PROPERTY_NAMES));
}
}
// Clear the table, and start scanning.
fileList.splice(0, fileList.length);
dispatchSimpleEvent(this, 'scan-started');
this.scan_(
this.currentDirContents_, false, true, onDone, onFailed, onUpdated,
onCancelled);
}
/**
* Similar to clearAndScan_() but instead of passing a `newDirContents`, it
* uses the `currentDirContents_`.
*/
clearCurrentDirAndScan() {
const sequence = ++this.changeDirectorySequence_;
this.directoryChangeQueue_.run(callback => {
if (this.changeDirectorySequence_ !== sequence) {
callback();
return;
}
const newDirContents = this.createDirectoryContents_(
this.currentFileListContext_, assert(this.getCurrentDirEntry()));
this.clearAndScan_(newDirContents, callback);
});
}
/**
* Adds/removes/updates items of file list.
* @param {Array<Entry>} changedEntries Entries of updated/added files.
* @param {Array<string>} removedUrls URLs of removed files.
* @private
*/
partialUpdate_(changedEntries, removedUrls) {
// This update should be included in the current running update.
if (this.pendingScan_) {
return;
}
if (this.runningScan_) {
// Do update after the current scan is finished.
const previousScan = this.runningScan_;
const onPreviousScanCompleted = () => {
previousScan.removeEventListener(
'scan-completed', onPreviousScanCompleted);
// Run the update asynchronously.
Promise.resolve().then(() => {
this.partialUpdate_(changedEntries, removedUrls);
});
};
previousScan.addEventListener('scan-completed', onPreviousScanCompleted);
return;
}
const onFinish = () => {
this.runningScan_ = null;
this.currentDirContents_.removeEventListener(
'scan-completed', onCompleted);
this.currentDirContents_.removeEventListener('scan-failed', onFailure);
this.currentDirContents_.removeEventListener(
'scan-cancelled', onCancelled);
};
const onCompleted = () => {
onFinish();
dispatchSimpleEvent(this, 'rescan-completed');
};
const onFailure = () => {
onFinish();
};
const onCancelled = () => {
onFinish();
};
this.runningScan_ = this.currentDirContents_;
this.currentDirContents_.addEventListener('scan-completed', onCompleted);
this.currentDirContents_.addEventListener('scan-failed', onFailure);
this.currentDirContents_.addEventListener('scan-cancelled', onCancelled);
this.currentDirContents_.update(changedEntries, removedUrls);
}
/**
* Perform a directory contents scan. Should be called only from rescan() and
* clearAndScan_().
*
* @param {DirectoryContents} dirContents DirectoryContents instance on which
* the scan will be run.
* @param {boolean} refresh True to refresh metadata, or false to use cached
* one.
* @param {boolean} invalidateCache True to invalidate scanning result cache.
* @param {function()} successCallback Callback on success.
* @param {function(DOMError)} failureCallback Callback on failure.
* @param {function()} updatedCallback Callback on update. Only on the last
* update, {@code successCallback} is called instead of this.
* @param {function()} cancelledCallback Callback on cancel.
* @private
*/
scan_(
dirContents, refresh, invalidateCache, successCallback, failureCallback,
updatedCallback, cancelledCallback) {
/**
* Runs pending scan if there is one.
*
* @return {boolean} Did pending scan exist.
*/
const maybeRunPendingRescan = () => {
if (this.pendingRescan_) {
this.rescanSoon(refresh);
this.pendingRescan_ = false;
return true;
}
return false;
};
const onFinished = () => {
dirContents.removeEventListener('scan-completed', onSuccess);
dirContents.removeEventListener('scan-updated', updatedCallback);
dirContents.removeEventListener('scan-failed', onFailure);
dirContents.removeEventListener('scan-cancelled', cancelledCallback);
};
const onSuccess = () => {
onFinished();
// Record metric for Downloads directory.
if (!dirContents.isSearch()) {
const locationInfo = this.volumeManager_.getLocationInfo(
assert(dirContents.getDirectoryEntry()));
const volumeInfo = locationInfo && locationInfo.volumeInfo;
if (volumeInfo &&
volumeInfo.volumeType ===
VolumeManagerCommon.VolumeType.DOWNLOADS &&
locationInfo.isRootEntry) {
metrics.recordMediumCount(
'DownloadsCount', dirContents.getFileListLength());
}
}
this.runningScan_ = null;
successCallback();
this.scanFailures_ = 0;
maybeRunPendingRescan();
};
const onFailure = event => {
onFinished();
this.runningScan_ = null;
this.scanFailures_++;
failureCallback(event.error);
if (maybeRunPendingRescan()) {
return;
}
// Do not rescan for Guest OS (including Crostini) errors.
// TODO(crbug/1293229): Guest OS currently reuses the Crostini error
// string, but once it gets its own strings this needs to include both.
if (event.error.name === constants.CROSTINI_CONNECT_ERR) {
return;
}
if (this.scanFailures_ <= 1) {
this.rescanLater(refresh);
}
};
const onCancelled = () => {
onFinished();
cancelledCallback();
};
this.runningScan_ = dirContents;
dirContents.addEventListener('scan-completed', onSuccess);
dirContents.addEventListener('scan-updated', updatedCallback);
dirContents.addEventListener('scan-failed', onFailure);
dirContents.addEventListener('scan-cancelled', onCancelled);
dirContents.scan(refresh, invalidateCache);
}
/**
* @param {DirectoryContents} dirContents DirectoryContents instance. This
* must be a different instance from this.currentDirContents_.
* @private
*/
replaceDirectoryContents_(dirContents) {
console.assert(
this.currentDirContents_ !== dirContents,
'Give directory contents instance must be different from current one.');
dispatchSimpleEvent(this, 'begin-update-files');
this.updateSelectionAndPublishEvent_(this.fileListSelection_, () => {
const selectedEntries = this.getSelectedEntries_();
const selectedIndices = this.fileListSelection_.selectedIndexes;
// Restore leadIndex in case leadName no longer exists.
const leadIndex = this.fileListSelection_.leadIndex;
const leadEntry = this.getLeadEntry_();
const isCheckSelectMode = this.fileListSelection_.getCheckSelectMode();
const previousDirContents = this.currentDirContents_;
this.currentDirContents_ = dirContents;
this.currentDirContents_.replaceContextFileList();
this.setSelectedEntries_(selectedEntries);
this.fileListSelection_.leadIndex = leadIndex;
this.setLeadEntry_(leadEntry);
// If nothing is selected after update, then select file next to the
// latest selection
let forceChangeEvent = false;
if (this.fileListSelection_.selectedIndexes.length == 0 &&
selectedIndices.length != 0) {
const maxIdx = Math.max.apply(null, selectedIndices);
this.selectIndex(
Math.min(
maxIdx - selectedIndices.length + 2,
this.getFileList().length) -
1);
forceChangeEvent = true;
} else if (isCheckSelectMode) {
// Otherwise, ensure check select mode is retained if it was previously
// active.
this.fileListSelection_.setCheckSelectMode(true);
}
return forceChangeEvent;
});
dispatchSimpleEvent(this, 'end-update-files');
}
/**
* Callback when an entry is changed.
* @param {EntriesChangedEvent} event Entry change event.
* @private
*/
async onEntriesChanged_(event) {
const kind = event.kind;
const entries = event.entries;
// TODO(hidehiko): We should update directory model even the search result
// is shown.
const rootType = this.getCurrentRootType();
if ((rootType === VolumeManagerCommon.RootType.DRIVE ||
rootType === VolumeManagerCommon.RootType.DRIVE_SHARED_WITH_ME ||
rootType === VolumeManagerCommon.RootType.DRIVE_RECENT ||
rootType === VolumeManagerCommon.RootType.DRIVE_OFFLINE) &&
this.isSearching()) {
return;
}