1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
8 * Called from the main frame when unloading.
9 * @param {boolean=} opt_exiting True if the app is exiting.
11 function unload(opt_exiting) { Gallery.instance.onUnload(opt_exiting); }
14 * Overrided metadata worker's path.
18 ContentProvider.WORKER_SCRIPT = '/js/metadata_worker.js';
21 * Gallery for viewing and editing image files.
23 * @param {!VolumeManager} volumeManager The VolumeManager instance of the
28 function Gallery(volumeManager) {
30 appWindow: chrome.app.window.current(),
31 onClose: function() { close(); },
32 onMaximize: function() {
33 var appWindow = chrome.app.window.current();
34 if (appWindow.isMaximized())
39 onMinimize: function() { chrome.app.window.current().minimize(); },
40 onAppRegionChanged: function() {},
41 metadataCache: MetadataCache.createFull(volumeManager),
45 displayStringFunction: function() { return ''; },
48 this.container_ = document.querySelector('.gallery');
49 this.document_ = document;
50 this.metadataCache_ = this.context_.metadataCache;
51 this.volumeManager_ = volumeManager;
52 this.selectedEntry_ = null;
53 this.metadataCacheObserverId_ = null;
54 this.onExternallyUnmountedBound_ = this.onExternallyUnmounted_.bind(this);
56 this.dataModel_ = new cr.ui.ArrayDataModel([]);
57 this.selectionModel_ = new cr.ui.ListSelectionModel();
60 this.initListeners_();
64 * Gallery extends cr.EventTarget.
66 Gallery.prototype.__proto__ = cr.EventTarget.prototype;
69 * Tools fade-out timeout in milliseconds.
73 Gallery.FADE_TIMEOUT = 3000;
76 * First time tools fade-out timeout in milliseconds.
80 Gallery.FIRST_FADE_TIMEOUT = 1000;
83 * Time until mosaic is initialized in the background. Used to make gallery
84 * in the slide mode load faster. In miiliseconds.
88 Gallery.MOSAIC_BACKGROUND_INIT_DELAY = 1000;
91 * Types of metadata Gallery uses (to query the metadata cache).
95 Gallery.METADATA_TYPE = 'thumbnail|filesystem|media|streaming|drive';
98 * Initializes listeners.
101 Gallery.prototype.initListeners_ = function() {
102 this.keyDownBound_ = this.onKeyDown_.bind(this);
103 this.document_.body.addEventListener('keydown', this.keyDownBound_);
105 this.inactivityWatcher_ = new MouseInactivityWatcher(
106 this.container_, Gallery.FADE_TIMEOUT, this.hasActiveTool.bind(this));
108 // Search results may contain files from different subdirectories so
109 // the observer is not going to work.
110 if (!this.context_.searchResults && this.context_.curDirEntry) {
111 this.metadataCacheObserverId_ = this.metadataCache_.addObserver(
112 this.context_.curDirEntry,
113 MetadataCache.CHILDREN,
115 this.updateThumbnails_.bind(this));
117 this.volumeManager_.addEventListener(
118 'externally-unmounted', this.onExternallyUnmountedBound_);
122 * Closes gallery when a volume containing the selected item is unmounted.
123 * @param {!Event} event The unmount event.
126 Gallery.prototype.onExternallyUnmounted_ = function(event) {
127 if (!this.selectedEntry_)
130 if (this.volumeManager_.getVolumeInfo(this.selectedEntry_) ===
137 * Unloads the Gallery.
138 * @param {boolean} exiting True if the app is exiting.
140 Gallery.prototype.onUnload = function(exiting) {
141 if (this.metadataCacheObserverId_ !== null)
142 this.metadataCache_.removeObserver(this.metadataCacheObserverId_);
143 this.volumeManager_.removeEventListener(
144 'externally-unmounted', this.onExternallyUnmountedBound_);
145 this.slideMode_.onUnload(exiting);
152 Gallery.prototype.initDom_ = function() {
153 // Initialize the dialog label.
154 cr.ui.dialogs.BaseDialog.OK_LABEL = str('GALLERY_OK_LABEL');
155 cr.ui.dialogs.BaseDialog.CANCEL_LABEL = str('GALLERY_CANCEL_LABEL');
157 var content = util.createChild(this.container_, 'content');
158 content.addEventListener('click', this.onContentClick_.bind(this));
160 this.header_ = util.createChild(this.container_, 'header tool dimmable');
161 this.toolbar_ = util.createChild(this.container_, 'toolbar tool dimmable');
163 var preventDefault = function(event) { event.preventDefault(); };
165 var minimizeButton = util.createChild(this.header_,
166 'minimize-button tool dimmable',
168 minimizeButton.tabIndex = -1;
169 minimizeButton.addEventListener('click', this.onMinimize_.bind(this));
170 minimizeButton.addEventListener('mousedown', preventDefault);
172 var maximizeButton = util.createChild(this.header_,
173 'maximize-button tool dimmable',
175 maximizeButton.tabIndex = -1;
176 maximizeButton.addEventListener('click', this.onMaximize_.bind(this));
177 maximizeButton.addEventListener('mousedown', preventDefault);
179 var closeButton = util.createChild(this.header_,
180 'close-button tool dimmable',
182 closeButton.tabIndex = -1;
183 closeButton.addEventListener('click', this.onClose_.bind(this));
184 closeButton.addEventListener('mousedown', preventDefault);
186 this.filenameSpacer_ = util.createChild(this.toolbar_, 'filename-spacer');
187 this.filenameEdit_ = util.createChild(this.filenameSpacer_,
190 this.filenameEdit_.setAttribute('type', 'text');
191 this.filenameEdit_.addEventListener('blur',
192 this.onFilenameEditBlur_.bind(this));
194 this.filenameEdit_.addEventListener('focus',
195 this.onFilenameFocus_.bind(this));
197 this.filenameEdit_.addEventListener('keydown',
198 this.onFilenameEditKeydown_.bind(this));
200 util.createChild(this.toolbar_, 'button-spacer');
202 this.prompt_ = new ImageEditor.Prompt(this.container_, str);
204 this.modeButton_ = util.createChild(this.toolbar_, 'button mode', 'button');
205 this.modeButton_.addEventListener('click',
206 this.toggleMode_.bind(this, null));
208 this.mosaicMode_ = new MosaicMode(content,
210 this.selectionModel_,
213 this.toggleMode_.bind(this, null));
215 this.slideMode_ = new SlideMode(this.container_,
220 this.selectionModel_,
222 this.toggleMode_.bind(this),
225 this.slideMode_.addEventListener('image-displayed', function() {
226 cr.dispatchSimpleEvent(this, 'image-displayed');
228 this.slideMode_.addEventListener('image-saved', function() {
229 cr.dispatchSimpleEvent(this, 'image-saved');
232 var deleteButton = this.createToolbarButton_('delete', 'GALLERY_DELETE');
233 deleteButton.addEventListener('click', this.delete_.bind(this));
235 this.shareButton_ = this.createToolbarButton_('share', 'GALLERY_SHARE');
236 this.shareButton_.setAttribute('disabled', '');
237 this.shareButton_.addEventListener('click', this.toggleShare_.bind(this));
239 this.shareMenu_ = util.createChild(this.container_, 'share-menu');
240 this.shareMenu_.hidden = true;
241 util.createChild(this.shareMenu_, 'bubble-point');
243 this.dataModel_.addEventListener('splice', this.onSplice_.bind(this));
244 this.dataModel_.addEventListener('content', this.onContentChange_.bind(this));
246 this.selectionModel_.addEventListener('change', this.onSelection_.bind(this));
247 this.slideMode_.addEventListener('useraction', this.onUserAction_.bind(this));
251 * Creates toolbar button.
253 * @param {string} className Class to add.
254 * @param {string} title Button title.
255 * @return {!HTMLElement} Newly created button.
258 Gallery.prototype.createToolbarButton_ = function(className, title) {
259 var button = util.createChild(this.toolbar_, className, 'button');
260 button.title = str(title);
267 * @param {!Array.<Entry>} entries Array of entries.
268 * @param {!Array.<Entry>} selectedEntries Array of selected entries.
270 Gallery.prototype.load = function(entries, selectedEntries) {
272 for (var index = 0; index < entries.length; ++index) {
273 items.push(new Gallery.Item(entries[index]));
275 this.dataModel_.push.apply(this.dataModel_, items);
277 this.selectionModel_.adjustLength(this.dataModel_.length);
279 // Comparing Entries by reference is not safe. Therefore we have to use URLs.
280 var entryIndexesByURLs = {};
281 for (var index = 0; index < entries.length; index++) {
282 entryIndexesByURLs[entries[index].toURL()] = index;
285 for (var i = 0; i !== selectedEntries.length; i++) {
286 var selectedIndex = entryIndexesByURLs[selectedEntries[i].toURL()];
287 if (selectedIndex !== undefined)
288 this.selectionModel_.setIndexSelected(selectedIndex, true);
290 console.error('Cannot select ' + selectedEntries[i]);
293 if (this.selectionModel_.selectedIndexes.length === 0)
296 var mosaic = this.mosaicMode_ && this.mosaicMode_.getMosaic();
298 // Mosaic view should show up if most of the selected files are images.
300 for (var i = 0; i !== selectedEntries.length; i++) {
301 if (FileType.getMediaType(selectedEntries[i]) === 'image')
304 var mostlyImages = imagesCount > (selectedEntries.length / 2.0);
306 var forcedMosaic = (this.context_.pageState &&
307 this.context_.pageState.gallery === 'mosaic');
309 var showMosaic = (mostlyImages && selectedEntries.length > 1) || forcedMosaic;
310 if (mosaic && showMosaic) {
311 this.setCurrentMode_(this.mosaicMode_);
314 this.inactivityWatcher_.check(); // Show the toolbar.
315 cr.dispatchSimpleEvent(this, 'loaded');
317 this.setCurrentMode_(this.slideMode_);
318 var maybeLoadMosaic = function() {
321 cr.dispatchSimpleEvent(this, 'loaded');
323 /* TODO: consider nice blow-up animation for the first image */
324 this.slideMode_.enter(null, function() {
325 // Flash the toolbar briefly to show it is there.
326 this.inactivityWatcher_.kick(Gallery.FIRST_FADE_TIMEOUT);
333 * Handles user's 'Close' action.
336 Gallery.prototype.onClose_ = function() {
337 this.executeWhenReady(this.context_.onClose);
341 * Handles user's 'Maximize' action (Escape or a click on the X icon).
344 Gallery.prototype.onMaximize_ = function() {
345 this.executeWhenReady(this.context_.onMaximize);
349 * Handles user's 'Maximize' action (Escape or a click on the X icon).
352 Gallery.prototype.onMinimize_ = function() {
353 this.executeWhenReady(this.context_.onMinimize);
357 * Executes a function when the editor is done with the modifications.
358 * @param {function} callback Function to execute.
360 Gallery.prototype.executeWhenReady = function(callback) {
361 this.currentMode_.executeWhenReady(callback);
365 * @return {Object} File browser private API.
367 Gallery.getFileBrowserPrivate = function() {
368 return chrome.fileBrowserPrivate || window.top.chrome.fileBrowserPrivate;
372 * @return {boolean} True if some tool is currently active.
374 Gallery.prototype.hasActiveTool = function() {
375 return this.currentMode_.hasActiveTool() ||
376 this.isSharing_() || this.isRenaming_();
380 * External user action event handler.
383 Gallery.prototype.onUserAction_ = function() {
384 this.closeShareMenu_();
385 // Show the toolbar and hide it after the default timeout.
386 this.inactivityWatcher_.kick();
390 * Sets the current mode, update the UI.
391 * @param {Object} mode Current mode.
394 Gallery.prototype.setCurrentMode_ = function(mode) {
395 if (mode !== this.slideMode_ && mode !== this.mosaicMode_)
396 console.error('Invalid Gallery mode');
398 this.currentMode_ = mode;
399 this.container_.setAttribute('mode', this.currentMode_.getName());
400 this.updateSelectionAndState_();
401 this.updateButtons_();
405 * Mode toggle event handler.
406 * @param {function=} opt_callback Callback.
407 * @param {Event=} opt_event Event that caused this call.
410 Gallery.prototype.toggleMode_ = function(opt_callback, opt_event) {
411 if (!this.modeButton_)
414 if (this.changingMode_) // Do not re-enter while changing the mode.
418 this.onUserAction_();
420 this.changingMode_ = true;
422 var onModeChanged = function() {
423 this.changingMode_ = false;
424 if (opt_callback) opt_callback();
427 var tileIndex = Math.max(0, this.selectionModel_.selectedIndex);
429 var mosaic = this.mosaicMode_.getMosaic();
430 var tileRect = mosaic.getTileRect(tileIndex);
432 if (this.currentMode_ === this.slideMode_) {
433 this.setCurrentMode_(this.mosaicMode_);
435 tileRect, this.slideMode_.getSelectedImageRect(), true /* instant */);
436 this.slideMode_.leave(
439 // Animate back to normal position.
445 this.setCurrentMode_(this.slideMode_);
446 this.slideMode_.enter(
449 // Animate to zoomed position.
450 mosaic.transform(tileRect, this.slideMode_.getSelectedImageRect());
458 * Deletes the selected items.
461 Gallery.prototype.delete_ = function() {
462 this.onUserAction_();
464 // Clone the sorted selected indexes array.
465 var indexesToRemove = this.selectionModel_.selectedIndexes.slice();
466 if (!indexesToRemove.length)
469 /* TODO(dgozman): Implement Undo delete, Remove the confirmation dialog. */
471 var itemsToRemove = this.getSelectedItems();
472 var plural = itemsToRemove.length > 1;
473 var param = plural ? itemsToRemove.length : itemsToRemove[0].getFileName();
475 function deleteNext() {
476 if (!itemsToRemove.length)
477 return; // All deleted.
479 // TODO(hirono): Use fileOperationManager.
480 var entry = itemsToRemove.pop().getEntry();
481 entry.remove(deleteNext, function() {
482 util.flog('Error deleting: ' + entry.name, deleteNext);
486 // Prevent the Gallery from handling Esc and Enter.
487 this.document_.body.removeEventListener('keydown', this.keyDownBound_);
488 var restoreListener = function() {
489 this.document_.body.addEventListener('keydown', this.keyDownBound_);
493 var confirm = new cr.ui.dialogs.ConfirmDialog(this.container_);
494 confirm.show(strf(plural ?
495 'GALLERY_CONFIRM_DELETE_SOME' : 'GALLERY_CONFIRM_DELETE_ONE', param),
498 this.selectionModel_.unselectAll();
499 this.selectionModel_.leadIndex = -1;
500 // Remove items from the data model, starting from the highest index.
501 while (indexesToRemove.length)
502 this.dataModel_.splice(indexesToRemove.pop(), 1);
503 // Delete actual files.
507 // Restore the listener after a timeout so that ESC is processed.
508 setTimeout(restoreListener, 0);
513 * @return {Array.<Gallery.Item>} Current selection.
515 Gallery.prototype.getSelectedItems = function() {
516 return this.selectionModel_.selectedIndexes.map(
517 this.dataModel_.item.bind(this.dataModel_));
521 * @return {Array.<Entry>} Array of currently selected entries.
523 Gallery.prototype.getSelectedEntries = function() {
524 return this.selectionModel_.selectedIndexes.map(function(index) {
525 return this.dataModel_.item(index).getEntry();
530 * @return {?Gallery.Item} Current single selection.
532 Gallery.prototype.getSingleSelectedItem = function() {
533 var items = this.getSelectedItems();
534 if (items.length > 1) {
535 console.error('Unexpected multiple selection');
542 * Selection change event handler.
545 Gallery.prototype.onSelection_ = function() {
546 this.updateSelectionAndState_();
547 this.updateShareMenu_();
551 * Data model splice event handler.
554 Gallery.prototype.onSplice_ = function() {
555 this.selectionModel_.adjustLength(this.dataModel_.length);
559 * Content change event handler.
560 * @param {Event} event Event.
563 Gallery.prototype.onContentChange_ = function(event) {
564 var index = this.dataModel_.indexOf(event.item);
565 if (index !== this.selectionModel_.selectedIndex)
566 console.error('Content changed for unselected item');
567 this.updateSelectionAndState_();
573 * @param {Event} event Event.
576 Gallery.prototype.onKeyDown_ = function(event) {
577 var wasSharing = this.isSharing_();
578 this.closeShareMenu_();
580 if (this.currentMode_.onKeyDown(event))
583 switch (util.getKeyModifiers(event) + event.keyIdentifier) {
584 case 'U+0008': // Backspace.
585 // The default handler would call history.back and close the Gallery.
586 event.preventDefault();
589 case 'U+004D': // 'm' switches between Slide and Mosaic mode.
590 this.toggleMode_(null, event);
593 case 'U+0056': // 'v'
594 this.slideMode_.startSlideshow(SlideMode.SLIDESHOW_INTERVAL_FIRST, event);
597 case 'U+007F': // Delete
598 case 'Shift-U+0033': // Shift+'3' (Delete key might be missing).
604 // Name box and rename support.
607 * Updates the UI related to the selected item and the persistent state.
611 Gallery.prototype.updateSelectionAndState_ = function() {
612 var numSelectedItems = this.selectionModel_.selectedIndexes.length;
613 var displayName = '';
614 var selectedEntryURL = null;
616 // If it's selecting something, update the variable values.
617 if (numSelectedItems) {
619 this.dataModel_.item(this.selectionModel_.selectedIndex);
620 this.selectedEntry_ = selectedItem.getEntry();
621 selectedEntryURL = this.selectedEntry_.toURL();
623 if (numSelectedItems === 1) {
624 window.top.document.title = this.selectedEntry_.name;
625 displayName = ImageUtil.getDisplayNameFromName(this.selectedEntry_.name);
626 } else if (this.context_.curDirEntry) {
627 // If the Gallery was opened on search results the search query will not
628 // be recorded in the app state and the relaunch will just open the
629 // gallery in the curDirEntry directory.
630 window.top.document.title = this.context_.curDirEntry.name;
631 displayName = strf('GALLERY_ITEMS_SELECTED', numSelectedItems);
635 window.top.util.updateAppState(
636 null, // Keep the current directory.
637 selectedEntryURL, // Update the selection.
638 {gallery: (this.currentMode_ === this.mosaicMode_ ? 'mosaic' : 'slide')});
640 // We can't rename files in readonly directory.
641 // We can only rename a single file.
642 this.filenameEdit_.disabled = numSelectedItems !== 1 ||
643 this.context_.readonlyDirName;
644 this.filenameEdit_.value = displayName;
648 * Click event handler on filename edit box
651 Gallery.prototype.onFilenameFocus_ = function() {
652 ImageUtil.setAttribute(this.filenameSpacer_, 'renaming', true);
653 this.filenameEdit_.originalValue = this.filenameEdit_.value;
654 setTimeout(this.filenameEdit_.select.bind(this.filenameEdit_), 0);
655 this.onUserAction_();
659 * Blur event handler on filename edit box.
661 * @param {Event} event Blur event.
662 * @return {boolean} if default action should be prevented.
665 Gallery.prototype.onFilenameEditBlur_ = function(event) {
666 if (this.filenameEdit_.value && this.filenameEdit_.value[0] === '.') {
667 this.prompt_.show('GALLERY_FILE_HIDDEN_NAME', 5000);
668 this.filenameEdit_.focus();
669 event.stopPropagation();
670 event.preventDefault();
674 var item = this.getSingleSelectedItem();
676 var oldEntry = item.getEntry();
678 var onFileExists = function() {
679 this.prompt_.show('GALLERY_FILE_EXISTS', 3000);
680 this.filenameEdit_.value = name;
681 this.filenameEdit_.focus();
684 var onSuccess = function() {
685 var event = new Event('content');
687 event.oldEntry = oldEntry;
688 event.metadata = null; // Metadata unchanged.
689 this.dataModel_.dispatchEvent(event);
692 if (this.filenameEdit_.value) {
694 this.filenameEdit_.value, onSuccess, onFileExists);
698 ImageUtil.setAttribute(this.filenameSpacer_, 'renaming', false);
699 this.onUserAction_();
703 * Keydown event handler on filename edit box
706 Gallery.prototype.onFilenameEditKeydown_ = function() {
707 switch (event.keyCode) {
709 this.filenameEdit_.value = this.filenameEdit_.originalValue;
710 this.filenameEdit_.blur();
714 this.filenameEdit_.blur();
717 event.stopPropagation();
721 * @return {boolean} True if file renaming is currently in progress.
724 Gallery.prototype.isRenaming_ = function() {
725 return this.filenameSpacer_.hasAttribute('renaming');
729 * Content area click handler.
732 Gallery.prototype.onContentClick_ = function() {
733 this.closeShareMenu_();
734 this.filenameEdit_.blur();
737 // Share button support.
740 * @return {boolean} True if the Share menu is active.
743 Gallery.prototype.isSharing_ = function() {
744 return !this.shareMenu_.hidden;
748 * Close Share menu if it is open.
751 Gallery.prototype.closeShareMenu_ = function() {
752 if (this.isSharing_())
757 * Share button handler.
760 Gallery.prototype.toggleShare_ = function() {
761 if (!this.shareButton_.hasAttribute('disabled'))
762 this.shareMenu_.hidden = !this.shareMenu_.hidden;
763 this.inactivityWatcher_.check();
767 * Updates available actions list based on the currently selected urls.
770 Gallery.prototype.updateShareMenu_ = function() {
771 var entries = this.getSelectedEntries();
773 function isShareAction(task) {
774 var taskParts = task.taskId.split('|');
775 return taskParts[0] !== chrome.runtime.id;
778 var api = Gallery.getFileBrowserPrivate();
779 var mimeTypes = []; // TODO(kaznacheev) Collect mime types properly.
781 var createShareMenu = function(tasks) {
782 var wasHidden = this.shareMenu_.hidden;
783 this.shareMenu_.hidden = true;
784 var items = this.shareMenu_.querySelectorAll('.item');
785 for (var i = 0; i !== items.length; i++) {
786 items[i].parentNode.removeChild(items[i]);
789 for (var t = 0; t !== tasks.length; t++) {
791 if (!isShareAction(task))
793 // Filter out Files.app tasks.
794 // TODO(hirono): Remove the hack after the files.app's handlers are
796 if (task.taskId.indexOf('hhaomjibdihmijegdhdafkllkbggdgoj|') === 0)
799 var item = util.createChild(this.shareMenu_, 'item');
800 item.textContent = task.title;
801 item.style.backgroundImage = 'url(' + task.iconUrl + ')';
802 item.addEventListener('click', function(taskId) {
803 this.toggleShare_(); // Hide the menu.
804 // TODO(hirono): Use entries instead of URLs.
805 this.executeWhenReady(
806 api.executeTask.bind(
809 util.entriesToURLs(entries),
812 new cr.ui.dialogs.AlertDialog(this.container_);
813 util.isTeleported(window).then(function(teleported) {
815 util.showOpenInOtherDesktopAlert(alertDialog, entries);
818 }.bind(this, task.taskId));
821 var empty = this.shareMenu_.querySelector('.item') === null;
822 ImageUtil.setAttribute(this.shareButton_, 'disabled', empty);
823 this.shareMenu_.hidden = wasHidden || empty;
826 // Create or update the share menu with a list of sharing tasks and show
827 // or hide the share button.
828 // TODO(mtomasz): Pass Entries directly, instead of URLs.
830 createShareMenu([]); // Empty list of tasks, since there is no selection.
832 api.getFileTasks(util.entriesToURLs(entries), mimeTypes, createShareMenu);
836 * Updates thumbnails.
839 Gallery.prototype.updateThumbnails_ = function() {
840 if (this.currentMode_ === this.slideMode_)
841 this.slideMode_.updateThumbnails();
843 if (this.mosaicMode_) {
844 var mosaic = this.mosaicMode_.getMosaic();
845 if (mosaic.isInitialized())
854 Gallery.prototype.updateButtons_ = function() {
855 if (this.modeButton_) {
857 this.currentMode_ === this.slideMode_ ? this.mosaicMode_ :
859 this.modeButton_.title = str(oppositeMode.getTitle());
870 * Initialize the window.
871 * @param {Object} backgroundComponents Background components.
873 window.initialize = function(backgroundComponents) {
874 window.loadTimeData.data = backgroundComponents.stringData;
875 gallery = new Gallery(backgroundComponents.volumeManager);
881 window.loadEntries = function(entries, selectedEntries) {
882 gallery.load(entries, selectedEntries);