1 // Copyright (c) 2012 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 * Namespace for utility functions.
13 * Returns a function that console.log's its arguments, prefixed by |msg|.
15 * @param {string} msg The message prefix to use in the log.
16 * @param {function(...string)=} opt_callback A function to invoke after
18 * @return {function(...string)} Function that logs.
20 util.flog = function(msg, opt_callback) {
22 var ary = Array.apply(null, arguments);
23 console.log(msg + ': ' + ary.join(', '));
25 opt_callback.apply(null, arguments);
30 * Returns a function that throws an exception that includes its arguments
33 * @param {string} msg The message prefix to use in the exception.
34 * @return {function(...string)} Function that throws.
36 util.ferr = function(msg) {
38 var ary = Array.apply(null, arguments);
39 throw new Error(msg + ': ' + ary.join(', '));
44 * @param {string} name File error name.
45 * @return {string} Translated file error string.
47 util.getFileErrorString = function(name) {
48 var candidateMessageFragment;
51 candidateMessageFragment = 'NOT_FOUND';
54 candidateMessageFragment = 'SECURITY';
56 case 'NotReadableError':
57 candidateMessageFragment = 'NOT_READABLE';
59 case 'NoModificationAllowedError':
60 candidateMessageFragment = 'NO_MODIFICATION_ALLOWED';
62 case 'InvalidStateError':
63 candidateMessageFragment = 'INVALID_STATE';
65 case 'InvalidModificationError':
66 candidateMessageFragment = 'INVALID_MODIFICATION';
68 case 'PathExistsError':
69 candidateMessageFragment = 'PATH_EXISTS';
71 case 'QuotaExceededError':
72 candidateMessageFragment = 'QUOTA_EXCEEDED';
76 return loadTimeData.getString('FILE_ERROR_' + candidateMessageFragment) ||
77 loadTimeData.getString('FILE_ERROR_GENERIC');
81 * Mapping table for FileError.code style enum to DOMError.name string.
86 util.FileError = Object.freeze({
87 ABORT_ERR: 'AbortError',
88 INVALID_MODIFICATION_ERR: 'InvalidModificationError',
89 INVALID_STATE_ERR: 'InvalidStateError',
90 NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
91 NOT_FOUND_ERR: 'NotFoundError',
92 NOT_READABLE_ERR: 'NotReadable',
93 PATH_EXISTS_ERR: 'PathExistsError',
94 QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
95 TYPE_MISMATCH_ERR: 'TypeMismatchError',
96 ENCODING_ERR: 'EncodingError',
100 * @param {string} str String to escape.
101 * @return {string} Escaped string.
103 util.htmlEscape = function(str) {
104 return str.replace(/[<>&]/g, function(entity) {
106 case '<': return '<';
107 case '>': return '>';
108 case '&': return '&';
114 * @param {string} str String to unescape.
115 * @return {string} Unescaped string.
117 util.htmlUnescape = function(str) {
118 return str.replace(/&(lt|gt|amp);/g, function(entity) {
120 case '<': return '<';
121 case '>': return '>';
122 case '&': return '&';
128 * Iterates the entries contained by dirEntry, and invokes callback once for
129 * each entry. On completion, successCallback will be invoked.
131 * @param {DirectoryEntry} dirEntry The entry of the directory.
132 * @param {function(Entry, function())} callback Invoked for each entry.
133 * @param {function()} successCallback Invoked on completion.
134 * @param {function(FileError)} errorCallback Invoked if an error is found on
135 * directory entry reading.
137 util.forEachDirEntry = function(
138 dirEntry, callback, successCallback, errorCallback) {
139 var reader = dirEntry.createReader();
140 var iterate = function() {
141 reader.readEntries(function(entries) {
142 if (entries.length == 0) {
149 function(forEachCallback, entry) {
150 // Do not pass index nor entries.
151 callback(entry, forEachCallback);
160 * Reads contents of directory.
161 * @param {DirectoryEntry} root Root entry.
162 * @param {string} path Directory path.
163 * @param {function(Array.<Entry>)} callback List of entries passed to callback.
165 util.readDirectory = function(root, path, callback) {
166 var onError = function(e) {
169 root.getDirectory(path, {create: false}, function(entry) {
170 var reader = entry.createReader();
172 var readNext = function() {
173 reader.readEntries(function(results) {
174 if (results.length == 0) {
178 r.push.apply(r, results);
187 * Utility function to resolve multiple directories with a single call.
189 * The successCallback will be invoked once for each directory object
190 * found. The errorCallback will be invoked once for each
191 * path that could not be resolved.
193 * The successCallback is invoked with a null entry when all paths have
196 * @param {DirEntry} dirEntry The base directory.
197 * @param {Object} params The parameters to pass to the underlying
198 * getDirectory calls.
199 * @param {Array.<string>} paths The list of directories to resolve.
200 * @param {function(!DirEntry)} successCallback The function to invoke for
201 * each DirEntry found. Also invoked once with null at the end of the
203 * @param {function(FileError)} errorCallback The function to invoke
204 * for each path that cannot be resolved.
206 util.getDirectories = function(dirEntry, params, paths, successCallback,
209 // Copy the params array, since we're going to destroy it.
210 params = [].slice.call(params);
212 var onComplete = function() {
213 successCallback(null);
216 var getNextDirectory = function() {
217 var path = paths.shift();
221 dirEntry.getDirectory(
224 successCallback(entry);
237 * Utility function to resolve multiple files with a single call.
239 * The successCallback will be invoked once for each directory object
240 * found. The errorCallback will be invoked once for each
241 * path that could not be resolved.
243 * The successCallback is invoked with a null entry when all paths have
246 * @param {DirEntry} dirEntry The base directory.
247 * @param {Object} params The parameters to pass to the underlying
249 * @param {Array.<string>} paths The list of files to resolve.
250 * @param {function(!FileEntry)} successCallback The function to invoke for
251 * each FileEntry found. Also invoked once with null at the end of the
253 * @param {function(FileError)} errorCallback The function to invoke
254 * for each path that cannot be resolved.
256 util.getFiles = function(dirEntry, params, paths, successCallback,
258 // Copy the params array, since we're going to destroy it.
259 params = [].slice.call(params);
261 var onComplete = function() {
262 successCallback(null);
265 var getNextFile = function() {
266 var path = paths.shift();
273 successCallback(entry);
286 * Resolve a path to either a DirectoryEntry or a FileEntry, regardless of
287 * whether the path is a directory or file.
289 * @param {DirectoryEntry} root The root of the filesystem to search.
290 * @param {string} path The path to be resolved.
291 * @param {function(Entry)} resultCallback Called back when a path is
292 * successfully resolved. Entry will be either a DirectoryEntry or
294 * @param {function(FileError)} errorCallback Called back if an unexpected
295 * error occurs while resolving the path.
297 util.resolvePath = function(root, path, resultCallback, errorCallback) {
298 if (path == '' || path == '/') {
299 resultCallback(root);
304 path, {create: false},
307 if (err.name == util.FileError.TYPE_MISMATCH_ERR) {
308 // Bah. It's a directory, ask again.
310 path, {create: false},
320 * Renames the entry to newName.
321 * @param {Entry} entry The entry to be renamed.
322 * @param {string} newName The new name.
323 * @param {function(Entry)} successCallback Callback invoked when the rename
324 * is successfully done.
325 * @param {function(FileError)} errorCallback Callback invoked when an error
328 util.rename = function(entry, newName, successCallback, errorCallback) {
329 entry.getParent(function(parent) {
330 // Before moving, we need to check if there is an existing entry at
331 // parent/newName, since moveTo will overwrite it.
332 // Note that this way has some timing issue. After existing check,
333 // a new entry may be create on background. However, there is no way not to
334 // overwrite the existing file, unfortunately. The risk should be low,
335 // assuming the unsafe period is very short.
336 (entry.isFile ? parent.getFile : parent.getDirectory).call(
337 parent, newName, {create: false},
339 // The entry with the name already exists.
340 errorCallback(util.createDOMError(util.FileError.PATH_EXISTS_ERR));
343 if (error.name != util.FileError.NOT_FOUND_ERR) {
344 // Unexpected error is found.
345 errorCallback(error);
349 // No existing entry is found.
350 entry.moveTo(parent, newName, successCallback, errorCallback);
356 * Remove a file or a directory.
357 * @param {Entry} entry The entry to remove.
358 * @param {function()} onSuccess The success callback.
359 * @param {function(FileError)} onError The error callback.
361 util.removeFileOrDirectory = function(entry, onSuccess, onError) {
362 if (entry.isDirectory)
363 entry.removeRecursively(onSuccess, onError);
365 entry.remove(onSuccess, onError);
369 * Checks if an entry exists at |relativePath| in |dirEntry|.
370 * If exists, tries to deduplicate the path by inserting parenthesized number,
371 * such as " (1)", before the extension. If it still exists, tries the
372 * deduplication again by increasing the number up to 10 times.
373 * For example, suppose "file.txt" is given, "file.txt", "file (1).txt",
374 * "file (2).txt", ..., "file (9).txt" will be tried.
376 * @param {DirectoryEntry} dirEntry The target directory entry.
377 * @param {string} relativePath The path to be deduplicated.
378 * @param {function(string)} onSuccess Called with the deduplicated path on
380 * @param {function(FileError)} onError Called on error.
382 util.deduplicatePath = function(dirEntry, relativePath, onSuccess, onError) {
383 // The trial is up to 10.
386 // Crack the path into three part. The parenthesized number (if exists) will
387 // be replaced by incremented number for retry. For example, suppose
388 // |relativePath| is "file (10).txt", the second check path will be
390 var match = /^(.*?)(?: \((\d+)\))?(\.[^.]*?)?$/.exec(relativePath);
391 var prefix = match[1];
392 var copyNumber = match[2] ? parseInt(match[2], 10) : 0;
393 var ext = match[3] ? match[3] : '';
395 // The path currently checking the existence.
396 var trialPath = relativePath;
398 var onNotResolved = function(err) {
399 // We expect to be unable to resolve the target file, since we're going
400 // to create it during the copy. However, if the resolve fails with
401 // anything other than NOT_FOUND, that's trouble.
402 if (err.name != util.FileError.NOT_FOUND_ERR) {
407 // Found a path that doesn't exist.
408 onSuccess(trialPath);
411 var numRetry = MAX_RETRY;
412 var onResolved = function(entry) {
413 if (--numRetry == 0) {
414 // Hit the limit of the number of retrial.
415 // Note that we cannot create FileError object directly, so here we use
416 // Object.create instead.
417 onError(util.createDOMError(util.FileError.PATH_EXISTS_ERR));
422 trialPath = prefix + ' (' + copyNumber + ')' + ext;
423 util.resolvePath(dirEntry, trialPath, onResolved, onNotResolved);
426 // Check to see if the target exists.
427 util.resolvePath(dirEntry, trialPath, onResolved, onNotResolved);
431 * Convert a number of bytes into a human friendly format, using the correct
434 * @param {number} bytes The number of bytes.
435 * @return {string} Localized string.
437 util.bytesToString = function(bytes) {
438 // Translation identifiers for size units.
439 var UNITS = ['SIZE_BYTES',
446 // Minimum values for the units above.
454 var str = function(n, u) {
455 // TODO(rginda): Switch to v8Locale's number formatter when it's
457 return strf(u, n.toLocaleString());
460 var fmt = function(s, u) {
461 var rounded = Math.round(bytes / s * 10) / 10;
462 return str(rounded, u);
465 // Less than 1KB is displayed like '80 bytes'.
466 if (bytes < STEPS[1]) {
467 return str(bytes, UNITS[0]);
470 // Up to 1MB is displayed as rounded up number of KBs.
471 if (bytes < STEPS[2]) {
472 var rounded = Math.ceil(bytes / STEPS[1]);
473 return str(rounded, UNITS[1]);
476 // This loop index is used outside the loop if it turns out |bytes|
477 // requires the largest unit.
480 for (i = 2 /* MB */; i < UNITS.length - 1; i++) {
481 if (bytes < STEPS[i + 1])
482 return fmt(STEPS[i], UNITS[i]);
485 return fmt(STEPS[i], UNITS[i]);
489 * Utility function to read specified range of bytes from file
490 * @param {File} file The file to read.
491 * @param {number} begin Starting byte(included).
492 * @param {number} end Last byte(excluded).
493 * @param {function(File, Uint8Array)} callback Callback to invoke.
494 * @param {function(FileError)} onError Error handler.
496 util.readFileBytes = function(file, begin, end, callback, onError) {
497 var fileReader = new FileReader();
498 fileReader.onerror = onError;
499 fileReader.onloadend = function() {
500 callback(file, new ByteReader(fileReader.result));
502 fileReader.readAsArrayBuffer(file.slice(begin, end));
506 * Write a blob to a file.
507 * Truncates the file first, so the previous content is fully overwritten.
508 * @param {FileEntry} entry File entry.
509 * @param {Blob} blob The blob to write.
510 * @param {function(Event)} onSuccess Completion callback. The first argument is
511 * a 'writeend' event.
512 * @param {function(FileError)} onError Error handler.
514 util.writeBlobToFile = function(entry, blob, onSuccess, onError) {
515 var truncate = function(writer) {
516 writer.onerror = onError;
517 writer.onwriteend = write.bind(null, writer);
521 var write = function(writer) {
522 writer.onwriteend = onSuccess;
526 entry.createWriter(truncate, onError);
530 * Returns a string '[Ctrl-][Alt-][Shift-][Meta-]' depending on the event
531 * modifiers. Convenient for writing out conditions in keyboard handlers.
533 * @param {Event} event The keyboard event.
534 * @return {string} Modifiers.
536 util.getKeyModifiers = function(event) {
537 return (event.ctrlKey ? 'Ctrl-' : '') +
538 (event.altKey ? 'Alt-' : '') +
539 (event.shiftKey ? 'Shift-' : '') +
540 (event.metaKey ? 'Meta-' : '');
544 * @param {HTMLElement} element Element to transform.
545 * @param {Object} transform Transform object,
546 * contains scaleX, scaleY and rotate90 properties.
548 util.applyTransform = function(element, transform) {
549 element.style.webkitTransform =
550 transform ? 'scaleX(' + transform.scaleX + ') ' +
551 'scaleY(' + transform.scaleY + ') ' +
552 'rotate(' + transform.rotate90 * 90 + 'deg)' :
557 * Makes filesystem: URL from the path.
558 * @param {string} path File or directory path.
559 * @return {string} URL.
561 util.makeFilesystemUrl = function(path) {
562 path = path.split('/').map(encodeURIComponent).join('/');
563 var prefix = 'external';
564 return 'filesystem:' + chrome.runtime.getURL(prefix + path);
568 * Extracts path from filesystem: URL.
569 * @param {string} url Filesystem URL.
570 * @return {string} The path.
572 util.extractFilePath = function(url) {
574 /^filesystem:[\w-]*:\/\/[\w]*\/(external|persistent|temporary)(\/.*)$/.
576 var path = match && match[2];
577 if (!path) return null;
578 return decodeURIComponent(path);
582 * Traverses a directory tree whose root is the given entry, and invokes
583 * callback for each entry. Upon completion, successCallback will be called.
584 * On error, errorCallback will be called.
586 * @param {Entry} entry The root entry.
587 * @param {function(Entry):boolean} callback Callback invoked for each entry.
588 * If this returns false, entries under it won't be traversed. Note that
589 * its siblings (and their children) will be still traversed.
590 * @param {function()} successCallback Called upon successful completion.
591 * @param {function(error)} errorCallback Called upon error.
593 util.traverseTree = function(entry, callback, successCallback, errorCallback) {
594 if (!callback(entry)) {
599 util.forEachDirEntry(
601 function(child, iterationCallback) {
602 util.traverseTree(child, callback, iterationCallback, errorCallback);
609 * A shortcut function to create a child element with given tag and class.
611 * @param {HTMLElement} parent Parent element.
612 * @param {string=} opt_className Class name.
613 * @param {string=} opt_tag Element tag, DIV is omitted.
614 * @return {Element} Newly created element.
616 util.createChild = function(parent, opt_className, opt_tag) {
617 var child = parent.ownerDocument.createElement(opt_tag || 'div');
619 child.className = opt_className;
620 parent.appendChild(child);
625 * Updates the app state.
627 * @param {string} currentDirectoryURL Currently opened directory as an URL.
628 * If null the value is left unchanged.
629 * @param {string} selectionURL Currently selected entry as an URL. If null the
630 * value is left unchanged.
631 * @param {string|Object=} opt_param Additional parameters, to be stored. If
632 * null, then left unchanged.
634 util.updateAppState = function(currentDirectoryURL, selectionURL, opt_param) {
635 window.appState = window.appState || {};
636 if (opt_param !== undefined && opt_param !== null)
637 window.appState.params = opt_param;
638 if (currentDirectoryURL !== null)
639 window.appState.currentDirectoryURL = currentDirectoryURL;
640 if (selectionURL !== null)
641 window.appState.selectionURL = selectionURL;
646 * Returns a translated string.
648 * Wrapper function to make dealing with translated strings more concise.
649 * Equivalent to loadTimeData.getString(id).
651 * @param {string} id The id of the string to return.
652 * @return {string} The translated string.
655 return loadTimeData.getString(id);
659 * Returns a translated string with arguments replaced.
661 * Wrapper function to make dealing with translated strings more concise.
662 * Equivalent to loadTimeData.getStringF(id, ...).
664 * @param {string} id The id of the string to return.
665 * @param {...string} var_args The values to replace into the string.
666 * @return {string} The translated string with replaced values.
668 function strf(id, var_args) {
669 return loadTimeData.getStringF.apply(loadTimeData, arguments);
673 * Adapter object that abstracts away the the difference between Chrome app APIs
674 * v1 and v2. Is only necessary while the migration to v2 APIs is in progress.
675 * TODO(mtomasz): Clean up this. crbug.com/240606.
679 * @return {boolean} True if Files.app is running as an open files or a select
680 * folder dialog. False otherwise.
682 runningInBrowser: function() {
683 return !window.appID;
687 * @param {function(Object)} callback Function accepting a preference map.
689 getPreferences: function(callback) {
690 chrome.storage.local.get(callback);
694 * @param {string} key Preference name.
695 * @param {function(string)} callback Function accepting the preference value.
697 getPreference: function(key, callback) {
698 chrome.storage.local.get(key, function(items) {
699 callback(items[key]);
704 * @param {string} key Preference name.
705 * @param {string|Object} value Preference value.
706 * @param {function()=} opt_callback Completion callback.
708 setPreference: function(key, value, opt_callback) {
709 if (typeof value != 'string')
710 value = JSON.stringify(value);
714 chrome.storage.local.set(items, opt_callback);
719 * Attach page load handler.
720 * @param {function()} handler Application-specific load handler.
722 util.addPageLoadHandler = function(handler) {
723 document.addEventListener('DOMContentLoaded', function() {
729 * Save app launch data to the local storage.
731 util.saveAppState = function() {
733 util.platform.setPreference(window.appID, window.appState);
737 * AppCache is a persistent timestamped key-value storage backed by
738 * HTML5 local storage.
740 * It is not designed for frequent access. In order to avoid costly
741 * localStorage iteration all data is kept in a single localStorage item.
742 * There is no in-memory caching, so concurrent access is _almost_ safe.
744 * TODO(kaznacheev) Reimplement this based on Indexed DB.
746 util.AppCache = function() {};
751 util.AppCache.KEY = 'AppCache';
754 * Max number of items.
756 util.AppCache.CAPACITY = 100;
761 util.AppCache.LIFETIME = 30 * 24 * 60 * 60 * 1000; // 30 days.
764 * @param {string} key Key.
765 * @param {function(number)} callback Callback accepting a value.
767 util.AppCache.getValue = function(key, callback) {
768 util.AppCache.read_(function(map) {
769 var entry = map[key];
770 callback(entry && entry.value);
777 * @param {string} key Key.
778 * @param {string} value Value. Remove the key if value is null.
779 * @param {number=} opt_lifetime Maximum time to keep an item (in milliseconds).
781 util.AppCache.update = function(key, value, opt_lifetime) {
782 util.AppCache.read_(function(map) {
786 expire: Date.now() + (opt_lifetime || util.AppCache.LIFETIME)
788 } else if (key in map) {
791 return; // Nothing to do.
793 util.AppCache.cleanup_(map);
794 util.AppCache.write_(map);
799 * @param {function(Object)} callback Callback accepting a map of timestamped
803 util.AppCache.read_ = function(callback) {
804 util.platform.getPreference(util.AppCache.KEY, function(json) {
807 callback(JSON.parse(json));
809 // The local storage item somehow got messed up, start fresh.
817 * @param {Object} map A map of timestamped key-value pairs.
820 util.AppCache.write_ = function(map) {
821 util.platform.setPreference(util.AppCache.KEY, JSON.stringify(map));
825 * Remove over-capacity and obsolete items.
827 * @param {Object} map A map of timestamped key-value pairs.
830 util.AppCache.cleanup_ = function(map) {
831 // Sort keys by ascending timestamps.
833 for (var key in map) {
834 if (map.hasOwnProperty(key))
837 keys.sort(function(a, b) { return map[a].expire > map[b].expire });
839 var cutoff = Date.now();
842 while (obsolete < keys.length &&
843 map[keys[obsolete]].expire < cutoff) {
847 var overCapacity = Math.max(0, keys.length - util.AppCache.CAPACITY);
849 var itemsToDelete = Math.max(obsolete, overCapacity);
850 for (var i = 0; i != itemsToDelete; i++) {
858 * @param {Image} image Image element.
859 * @param {string} url Source url.
860 * @param {Object=} opt_options Hash array of options, eg. width, height,
861 * maxWidth, maxHeight, scale, cache.
862 * @param {function()=} opt_isValid Function returning false iff the task
863 * is not valid and should be aborted.
864 * @return {?number} Task identifier or null if fetched immediately from
867 util.loadImage = function(image, url, opt_options, opt_isValid) {
868 return ImageLoaderClient.loadToImage(url,
872 function() { image.onerror(); },
877 * Cancels loading an image.
878 * @param {number} taskId Task identifier returned by util.loadImage().
880 util.cancelLoadImage = function(taskId) {
881 ImageLoaderClient.getInstance().cancel(taskId);
885 * Finds proerty descriptor in the object prototype chain.
886 * @param {Object} object The object.
887 * @param {string} propertyName The property name.
888 * @return {Object} Property descriptor.
890 util.findPropertyDescriptor = function(object, propertyName) {
891 for (var p = object; p; p = Object.getPrototypeOf(p)) {
892 var d = Object.getOwnPropertyDescriptor(p, propertyName);
900 * Calls inherited property setter (useful when property is
902 * @param {Object} object The object.
903 * @param {string} propertyName The property name.
904 * @param {*} value Value to set.
906 util.callInheritedSetter = function(object, propertyName, value) {
907 var d = util.findPropertyDescriptor(Object.getPrototypeOf(object),
909 d.set.call(object, value);
913 * Returns true if the board of the device matches the given prefix.
914 * @param {string} boardPrefix The board prefix to match against.
915 * (ex. "x86-mario". Prefix is used as the actual board name comes with
916 * suffix like "x86-mario-something".
917 * @return {boolean} True if the board of the device matches the given prefix.
919 util.boardIs = function(boardPrefix) {
920 // The board name should be lower-cased, but making it case-insensitive for
921 // backward compatibility just in case.
922 var board = str('CHROMEOS_RELEASE_BOARD');
923 var pattern = new RegExp('^' + boardPrefix, 'i');
924 return board.match(pattern) != null;
928 * Adds an isFocused method to the current window object.
930 util.addIsFocusedMethod = function() {
933 window.addEventListener('focus', function() {
937 window.addEventListener('blur', function() {
942 * @return {boolean} True if focused.
944 window.isFocused = function() {
950 * Makes a redirect to the specified Files.app's window from another window.
951 * @param {number} id Window id.
952 * @param {string} url Target url.
953 * @return {boolean} True if the window has been found. False otherwise.
955 util.redirectMainWindow = function(id, url) {
956 // TODO(mtomasz): Implement this for Apps V2, once the photo importer is
962 * Checks, if the Files.app's window is in a full screen mode.
964 * @param {AppWindow} appWindow App window to be maximized.
965 * @return {boolean} True if the full screen mode is enabled.
967 util.isFullScreen = function(appWindow) {
969 return appWindow.isFullscreen();
971 console.error('App window not passed. Unable to check status of ' +
972 'the full screen mode.');
978 * Toggles the full screen mode.
980 * @param {AppWindow} appWindow App window to be maximized.
981 * @param {boolean} enabled True for enabling, false for disabling.
983 util.toggleFullScreen = function(appWindow, enabled) {
986 appWindow.fullscreen();
993 'App window not passed. Unable to toggle the full screen mode.');
997 * The type of a file operation.
1001 util.FileOperationType = Object.freeze({
1008 * The type of a file operation error.
1012 util.FileOperationErrorType = Object.freeze({
1013 UNEXPECTED_SOURCE_FILE: 0,
1015 FILESYSTEM_ERROR: 2,
1019 * The kind of an entry changed event.
1023 util.EntryChangedKind = Object.freeze({
1029 * Obtains whether an entry is fake or not.
1030 * @param {!Entry|!Object} entry Entry or a fake entry.
1031 * @return {boolean} True if the given entry is fake.
1033 util.isFakeEntry = function(entry) {
1034 return !('getParent' in entry);
1038 * Creates an instance of UserDOMError with given error name that looks like a
1039 * FileError except that it does not have the deprecated FileError.code member.
1041 * TODO(uekawa): remove reference to FileError.
1043 * @param {string} name Error name for the file error.
1044 * @return {UserDOMError} FileError instance
1046 util.createDOMError = function(name) {
1047 return new util.UserDOMError(name);
1051 * Creates a DOMError-like object to be used in place of returning file errors.
1053 * @param {string} name Error name for the file error.
1056 util.UserDOMError = function(name) {
1062 Object.freeze(this);
1065 util.UserDOMError.prototype = {
1067 * @return {string} File error name.
1075 * Compares two entries.
1076 * @param {Entry|Object} entry1 The entry to be compared. Can be a fake.
1077 * @param {Entry|Object} entry2 The entry to be compared. Can be a fake.
1078 * @return {boolean} True if the both entry represents a same file or
1079 * directory. Returns true if both entries are null.
1081 util.isSameEntry = function(entry1, entry2) {
1082 // Currently, we can assume there is only one root.
1083 // When we support multi-file system, we need to look at filesystem, too.
1084 return (entry1 && entry2 && entry1.toURL() === entry2.toURL()) ||
1085 (!entry1 && !entry2);
1089 * Checks if the child entry is a descendant of another entry. If the entries
1090 * point to the same file or directory, then returns false.
1092 * @param {DirectoryEntry|Object} ancestorEntry The ancestor directory entry.
1094 * @param {Entry|Object} childEntry The child entry. Can be a fake.
1095 * @return {boolean} True if the child entry is contained in the ancestor path.
1097 util.isDescendantEntry = function(ancestorEntry, childEntry) {
1098 if (!ancestorEntry.isDirectory)
1101 // TODO(mtomasz): Do not work on URLs. Instead consider comparing file systems
1103 if (util.isSameEntry(ancestorEntry, childEntry))
1105 if (childEntry.toURL().indexOf(ancestorEntry.toURL() + '/') !== 0)
1114 * If the browser is opening, the url is opened in a new tag, otherwise the url
1115 * is opened in a new window.
1117 * @param {string} url URL to visit.
1119 util.visitURL = function(url) {
1124 * Returns normalized current locale, or default locale - 'en'.
1125 * @return {string} Current locale
1127 util.getCurrentLocaleOrDefault = function() {
1128 // chrome.i18n.getMessage('@@ui_locale') can't be used in packed app.
1129 // Instead, we pass it from C++-side with strings.
1130 return str('UI_LOCALE') || 'en';
1134 * Converts array of entries to an array of corresponding URLs.
1135 * @param {Array.<Entry>} entries Input array of entries.
1136 * @return {Array.<string>} Output array of URLs.
1138 util.entriesToURLs = function(entries) {
1139 // TODO(mtomasz): Make all callers use entries instead of URLs, and then
1140 // remove this utility function.
1141 console.warn('Converting entries to URLs is deprecated.');
1142 return entries.map(function(entry) {
1143 return entry.toURL();
1148 * Converts array of URLs to an array of corresponding Entries.
1150 * @param {Array.<string>} urls Input array of URLs.
1151 * @param {function(Array.<Entry>, Array.<URL>)} callback Completion callback
1152 * with array of success Entries and failure URLs.
1154 util.URLsToEntries = function(urls, callback) {
1156 var failureUrl = [];
1159 function(forEachCallback, url) {
1160 webkitResolveLocalFileSystemURL(url, function(entry) {
1164 // Not an error. Possibly, the file is not accessible anymore.
1165 console.warn('Failed to resolve the file with url: ' + url + '.');
1166 failureUrl.push(url);
1170 callback.bind(null, result, failureUrl));
1174 * Returns whether the window is teleported or not.
1175 * @param {DOMWindow} window Window.
1176 * @return {Promise.<boolean>} Whether the window is teleported or not.
1178 util.isTeleported = function(window) {
1179 return new Promise(function(onFulfilled) {
1180 window.chrome.fileBrowserPrivate.getProfiles(function(profiles,
1183 onFullfilled(currentId !== displayedId);
1189 * Sets up and shows the alert to inform a user the task is opened in the
1190 * desktop of the running profile.
1192 * TODO(hirono): Move the function from the util namespace.
1193 * @param {cr.ui.AlertDialog} alertDialog Alert dialog to be shown.
1194 * @param {Array.<Entry>} entries List of opened entries.
1196 util.showOpenInOtherDesktopAlert = function(alertDialog, entries) {
1197 if (!entries.length)
1199 chrome.fileBrowserPrivate.getProfiles(function(profiles,
1204 for (var i = 0; i < profiles.length; i++) {
1205 if (profiles[i].profileId === currentId) {
1206 displayName = profiles[i].displayName;
1211 console.warn('Display name is not found.');
1215 var title = entries.size > 1 ?
1216 entries[0].name + '\u2026' /* ellipsis */ : entries[0].name;
1217 var message = strf(entries.size > 1 ?
1218 'OPEN_IN_OTHER_DESKTOP_MESSAGE_PLURAL' :
1219 'OPEN_IN_OTHER_DESKTOP_MESSAGE',
1224 alertDialog.showWithTitle(title, message);
1229 * Error type of VolumeManager.
1233 util.VolumeError = Object.freeze({
1234 /* Internal errors */
1235 NOT_MOUNTED: 'not_mounted',
1239 UNKNOWN: 'error_unknown',
1240 INTERNAL: 'error_internal',
1241 UNKNOWN_FILESYSTEM: 'error_unknown_filesystem',
1242 UNSUPPORTED_FILESYSTEM: 'error_unsupported_filesystem',
1243 INVALID_ARCHIVE: 'error_invalid_archive',
1244 AUTHENTICATION: 'error_authentication',
1245 PATH_UNMOUNTED: 'error_path_unmounted'
1249 * List of connection types of drive.
1251 * Keep this in sync with the kDriveConnectionType* constants in
1252 * private_api_dirve.cc.
1257 util.DriveConnectionType = Object.freeze({
1258 OFFLINE: 'offline', // Connection is offline or drive is unavailable.
1259 METERED: 'metered', // Connection is metered. Should limit traffic.
1260 ONLINE: 'online' // Connection is online.
1264 * List of reasons of DriveConnectionType.
1266 * Keep this in sync with the kDriveConnectionReason constants in
1267 * private_api_drive.cc.
1272 util.DriveConnectionReason = Object.freeze({
1273 NOT_READY: 'not_ready', // Drive is not ready or authentication is failed.
1274 NO_NETWORK: 'no_network', // Network connection is unavailable.
1275 NO_SERVICE: 'no_service' // Drive service is unavailable.
1279 * The type of each volume.
1283 util.VolumeType = Object.freeze({
1285 DOWNLOADS: 'downloads',
1286 REMOVABLE: 'removable',
1288 CLOUD_DEVICE: 'cloud_device'