Commit 5d75b735 authored by Wenzhao Zang's avatar Wenzhao Zang Committed by Commit Bot

cros: Clean up old wallpaper picker code (Part III)

Remove more dead code.

Bug: 812085
Change-Id: I1ba634e3fb41d61511736dc7c057a5bbc5903c78
Reviewed-on: https://chromium-review.googlesource.com/c/1300315
Commit-Queue: Wenzhao (Colin) Zang <wzang@chromium.org>
Reviewed-by: default avatarXiaoqian Dai <xdai@chromium.org>
Cr-Commit-Position: refs/heads/master@{#604772}
parent 2ebd2c83
...@@ -127,20 +127,6 @@ body.v1 { ...@@ -127,20 +127,6 @@ body.v1 {
position: relative; position: relative;
} }
#spinner-container {
-webkit-box-align: center;
-webkit-box-pack: center;
background: url(chrome://resources/images/throbber_medium.svg) center/32px
no-repeat;
display: -webkit-box;
height: 287px;
padding-bottom: 15px;
padding-top: 5px;
position: absolute;
top: 0;
width: 100%;
}
#wallpaper-set-by-message { #wallpaper-set-by-message {
height: 30px; height: 30px;
padding-inline-end: 5px; padding-inline-end: 5px;
......
...@@ -4,11 +4,6 @@ ...@@ -4,11 +4,6 @@
/** @const */ var Constants = { /** @const */ var Constants = {
/**
* Key to access wallpaper rss in chrome.storage.local.
*/
AccessLocalRssKey: 'wallpaper-picker-surprise-rss-key',
/** /**
* Key to access wallpaper manifest in chrome.storage.local. * Key to access wallpaper manifest in chrome.storage.local.
*/ */
...@@ -59,18 +54,6 @@ ...@@ -59,18 +54,6 @@
*/ */
AccessLocalImagesInfoKey: 'images-info-key', AccessLocalImagesInfoKey: 'images-info-key',
/**
* URL to get latest wallpaper RSS feed.
*/
WallpaperRssURL: 'https://storage.googleapis.com/' +
'chromeos-wallpaper-public/wallpaper.rss',
/**
* cros-wallpaper namespace URI.
*/
WallpaperNameSpaceURI: 'http://commondatastorage.googleapis.com/' +
'chromeos-wallpaper-public/cros-wallpaper-uri',
/** /**
* Wallpaper sources enum. * Wallpaper sources enum.
*/ */
...@@ -80,7 +63,6 @@ ...@@ -80,7 +63,6 @@
OEM: 'OEM', OEM: 'OEM',
Custom: 'CUSTOM', Custom: 'CUSTOM',
ThirdParty: 'THIRDPARTY', ThirdParty: 'THIRDPARTY',
AddNew: 'ADDNEW',
Default: 'DEFAULT' Default: 'DEFAULT'
}, },
......
...@@ -30,103 +30,15 @@ SurpriseWallpaper.getInstance = function() { ...@@ -30,103 +30,15 @@ SurpriseWallpaper.getInstance = function() {
return surpriseWallpaper; return surpriseWallpaper;
}; };
/**
* Tries to change wallpaper to a new one in the background. May fail due to a
* network issue.
*/
SurpriseWallpaper.prototype.tryChangeWallpaper = function() {
var self = this;
var onFailure = function(status) {
if (status != 404)
self.fallbackToLocalRss_();
else
self.updateRandomWallpaper_();
};
// Try to fetch newest rss as document from server first. If the requested
// URL is not found (404 error), set a random wallpaper displayed in the
// wallpaper picker. If any other error occurs, proceed with local copy of
// rss.
WallpaperUtil.fetchURL(Constants.WallpaperRssURL, 'document', function(xhr) {
WallpaperUtil.saveToLocalStorage(
Constants.AccessLocalRssKey,
new XMLSerializer().serializeToString(xhr.responseXML));
self.updateSurpriseWallpaper(xhr.responseXML);
}, onFailure);
};
/** /**
* Retries changing the wallpaper 1 hour later. This is called when fetching the * Retries changing the wallpaper 1 hour later. This is called when fetching the
* rss or wallpaper from server fails. * wallpaper from server fails.
* @private * @private
*/ */
SurpriseWallpaper.prototype.retryLater_ = function() { SurpriseWallpaper.prototype.retryLater_ = function() {
chrome.alarms.create('RetryAlarm', {delayInMinutes: 60}); chrome.alarms.create('RetryAlarm', {delayInMinutes: 60});
}; };
/**
* Fetches the cached rss feed from local storage in the event of being unable
* to download the online feed.
* @private
*/
SurpriseWallpaper.prototype.fallbackToLocalRss_ = function() {
var self = this;
Constants.WallpaperLocalStorage.get(
Constants.AccessLocalRssKey, function(items) {
var rssString = items[Constants.AccessLocalRssKey];
if (rssString) {
self.updateSurpriseWallpaper(
new DOMParser().parseFromString(rssString, 'text/xml'));
} else {
self.updateSurpriseWallpaper();
}
});
};
/**
* Starts to change wallpaper. Called after rss is fetched.
* @param {Document=} opt_rss The fetched rss document. If opt_rss is null, uses
* a random wallpaper.
*/
SurpriseWallpaper.prototype.updateSurpriseWallpaper = function(opt_rss) {
if (opt_rss) {
var items = opt_rss.querySelectorAll('item');
var date = new Date(new Date().toDateString()).getTime();
for (var i = 0; i < items.length; i++) {
item = items[i];
var disableDate =
new Date(item.getElementsByTagNameNS(
Constants.WallpaperNameSpaceURI, 'disableDate')[0]
.textContent)
.getTime();
var enableDate =
new Date(item.getElementsByTagNameNS(
Constants.WallpaperNameSpaceURI, 'enableDate')[0]
.textContent)
.getTime();
var regionsString = item.getElementsByTagNameNS(
Constants.WallpaperNameSpaceURI, 'regions')[0]
.textContent;
var regions = regionsString.split(', ');
if (enableDate <= date && disableDate > date &&
regions.indexOf(navigator.language) != -1) {
var self = this;
this.setWallpaperFromRssItem_(
item, function() {},
function(status) {
if (status != 404)
self.retryLater_();
else
self.updateRandomWallpaper_();
});
return;
}
}
}
// No surprise wallpaper for today at current locale or fetching rss feed
// fails. Fallback to use a random one from wallpaper server.
this.updateRandomWallpaper_();
};
/** /**
* Sets a new random wallpaper if one has not already been set today. * Sets a new random wallpaper if one has not already been set today.
* @private * @private
...@@ -241,41 +153,6 @@ SurpriseWallpaper.prototype.setRandomWallpaperFromServer_ = function( ...@@ -241,41 +153,6 @@ SurpriseWallpaper.prototype.setRandomWallpaperFromServer_ = function(
WallpaperUtil.getDailyRefreshInfo(onDailyRefreshInfoReturned.bind(null)); WallpaperUtil.getDailyRefreshInfo(onDailyRefreshInfoReturned.bind(null));
}; };
/**
* Sets wallpaper to the wallpaper specified by item from rss. If downloading
* the wallpaper fails, retry one hour later.
* @param {Element} item The wallpaper rss item element.
* @param {function} onSuccess Success callback.
* @param {function} onFailure Failure callback.
* @private
*/
SurpriseWallpaper.prototype.setWallpaperFromRssItem_ = function(
item, onSuccess, onFailure) {
var url = item.querySelector('link').textContent;
var layout =
item.getElementsByTagNameNS(Constants.WallpaperNameSpaceURI, 'layout')[0]
.textContent;
var self = this;
WallpaperUtil.fetchURL(url, 'arraybuffer', function(xhr) {
if (xhr.response != null) {
chrome.wallpaperPrivate.setCustomWallpaper(
xhr.response, layout, false /*generateThumbnail=*/,
'surprise_wallpaper', false /*previewMode=*/, onSuccess);
WallpaperUtil.saveWallpaperInfo(
url, layout, Constants.WallpaperSourceEnum.Daily, '');
var dateString = new Date().toDateString();
WallpaperUtil.saveToLocalStorage(
Constants.AccessLastSurpriseWallpaperChangedDate, dateString,
function() {
WallpaperUtil.saveToSyncStorage(
Constants.AccessLastSurpriseWallpaperChangedDate, dataString);
});
} else {
self.updateRandomWallpaper_();
}
}, onFailure);
};
/** /**
* Disables the wallpaper surprise me feature. Clear all alarms and states. * Disables the wallpaper surprise me feature. Clear all alarms and states.
*/ */
...@@ -296,7 +173,7 @@ SurpriseWallpaper.prototype.disable = function() { ...@@ -296,7 +173,7 @@ SurpriseWallpaper.prototype.disable = function() {
SurpriseWallpaper.prototype.next = function() { SurpriseWallpaper.prototype.next = function() {
var nextUpdate = this.nextUpdateTime(new Date()); var nextUpdate = this.nextUpdateTime(new Date());
chrome.alarms.create({when: nextUpdate}); chrome.alarms.create({when: nextUpdate});
this.tryChangeWallpaper(); this.updateRandomWallpaper_();
}; };
/** /**
......
...@@ -34,7 +34,6 @@ ...@@ -34,7 +34,6 @@
// <include src="constants.js"> // <include src="constants.js">
// <include src="util.js"> // <include src="util.js">
// <include src="progress_manager.js"> // <include src="progress_manager.js">
// <include src="wallpaper_directories.js">
// <include src="wallpaper_categories_list.js"> // <include src="wallpaper_categories_list.js">
// <include src="wallpaper_images_grid.js"> // <include src="wallpaper_images_grid.js">
// <include src="wallpaper_manager.js"> // <include src="wallpaper_manager.js">
......
// Copyright (c) 2013 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.
/**
* Wallpaper file system quota.
*/
/** @const */ var WallpaperQuota = 1024 * 1024 * 100;
var wallpaperDirectories = null;
/**
* Manages custom wallpaper related directories in wallpaper's sandboxed
* FileSystem.
* @constructor
*/
function WallpaperDirectories() {
this.wallpaperDirs_ = {};
this.wallpaperDirs_[Constants.WallpaperDirNameEnum.ORIGINAL] = null;
this.wallpaperDirs_[Constants.WallpaperDirNameEnum.THUMBNAIL] = null;
}
/**
* Gets WallpaperDirectories instance. In case is hasn't been initialized, a new
* instance is created.
* @return {WallpaperDirectories} A WallpaperDirectories instance.
*/
WallpaperDirectories.getInstance = function() {
if (wallpaperDirectories === null)
wallpaperDirectories = new WallpaperDirectories();
return wallpaperDirectories;
};
WallpaperDirectories.prototype = {
/**
* Returns all custom wallpaper related directory entries.
*/
get wallpaperDirs() {
return this.wallpaperDirs_;
},
/**
* If dirName is not requested, gets the directory entry of dirName and cache
* the result. Calls success callback if success.
* @param {string} dirName The directory name of requested directory entry.
* @param {function(DirectoryEntry):void} success Call success with requested
* DirectoryEntry.
* @param {function(e):void} failure Call failure when failed to get the
* requested directory.
*/
requestDir: function(dirName, success, failure) {
if (dirName != Constants.WallpaperDirNameEnum.ORIGINAL &&
dirName != Constants.WallpaperDirNameEnum.THUMBNAIL) {
console.error('Error: Unknow directory name.');
var e = new Error();
e.code = FileError.NOT_FOUND_ERR;
failure(e);
return;
}
var self = this;
window.webkitRequestFileSystem(
window.PERSISTENT, WallpaperQuota, function(fs) {
fs.root.getDirectory(dirName, {create: true}, function(dirEntry) {
self.wallpaperDirs_[dirName] = dirEntry;
success(dirEntry);
}, failure);
}, failure);
},
/**
* Gets DirectoryEntry associated with dirName from cache. If not in cache try
* to request it from FileSystem.
* @param {string} dirName The directory name of requested directory entry.
* @param {function(DirectoryEntry):void} success Call success with requested
* DirectoryEntry.
* @param {function(e):void} failure Call failure when failed to get the
* requested directory.
*/
getDirectory: function(dirName, success, failure) {
if (this.wallpaperDirs[dirName])
success(this.wallpaperDirs[dirName]);
else
this.requestDir(dirName, success, failure);
}
};
...@@ -8,7 +8,6 @@ cr.define('wallpapers', function() { ...@@ -8,7 +8,6 @@ cr.define('wallpapers', function() {
/** @const */ var GridItem = cr.ui.GridItem; /** @const */ var GridItem = cr.ui.GridItem;
/** @const */ var GridSelectionController = cr.ui.GridSelectionController; /** @const */ var GridSelectionController = cr.ui.GridSelectionController;
/** @const */ var ListSingleSelectionModel = cr.ui.ListSingleSelectionModel; /** @const */ var ListSingleSelectionModel = cr.ui.ListSingleSelectionModel;
/** @const */ var ShowSpinnerDelayMs = 500;
/** /**
* The number of images that appear in the slideshow of the daily refresh * The number of images that appear in the slideshow of the daily refresh
...@@ -105,16 +104,6 @@ cr.define('wallpapers', function() { ...@@ -105,16 +104,6 @@ cr.define('wallpapers', function() {
this.appendChild(imageEl); this.appendChild(imageEl);
switch (this.dataItem.source) { switch (this.dataItem.source) {
case Constants.WallpaperSourceEnum.AddNew:
this.id = 'add-new';
this.addEventListener('click', function(e) {
if (!WallpaperUtil.getSurpriseMeCheckboxValue())
$('wallpaper-selection-container').hidden = false;
});
// Delay dispatching the completion callback until all items have
// begun loading and are tracked.
window.setTimeout(this.callback_.bind(this, this.dataModelId_), 0);
break;
case Constants.WallpaperSourceEnum.Custom: case Constants.WallpaperSourceEnum.Custom:
this.decorateCustomWallpaper_(imageEl, this.dataItem); this.decorateCustomWallpaper_(imageEl, this.dataItem);
break; break;
...@@ -283,12 +272,6 @@ cr.define('wallpapers', function() { ...@@ -283,12 +272,6 @@ cr.define('wallpapers', function() {
return this.checkmark_; return this.checkmark_;
}, },
/**
* ID of spinner delay timer.
* @private
*/
spinnerTimeout_: 0,
/** /**
* The timer of the slideshow of the daily refresh item. * The timer of the slideshow of the daily refresh item.
* @private * @private
...@@ -399,9 +382,6 @@ cr.define('wallpapers', function() { ...@@ -399,9 +382,6 @@ cr.define('wallpapers', function() {
dataModel.splice( dataModel.splice(
0, 0, {isDailyRefreshItem: true, availableOffline: false}); 0, 0, {isDailyRefreshItem: true, availableOffline: false});
} }
} else {
// Sets dataModel to null should hide spinner immediately.
$('spinner-container').hidden = true;
} }
var parentSetter = cr.ui.Grid.prototype.__lookupSetter__('dataModel'); var parentSetter = cr.ui.Grid.prototype.__lookupSetter__('dataModel');
...@@ -520,9 +500,6 @@ cr.define('wallpapers', function() { ...@@ -520,9 +500,6 @@ cr.define('wallpapers', function() {
if (this.pendingItems_ == 0) { if (this.pendingItems_ == 0) {
this.style.visibility = 'visible'; this.style.visibility = 'visible';
window.clearTimeout(this.spinnerTimeout_);
this.spinnerTimeout_ = 0;
$('spinner-container').hidden = true;
// Start the slideshow. // Start the slideshow.
if (this.dailyRefreshItem) { if (this.dailyRefreshItem) {
window.clearTimeout(this.dailyRefreshTimer_); window.clearTimeout(this.dailyRefreshTimer_);
...@@ -604,17 +581,6 @@ cr.define('wallpapers', function() { ...@@ -604,17 +581,6 @@ cr.define('wallpapers', function() {
this.inProgramSelection_ = false; this.inProgramSelection_ = false;
}, },
/**
* Forces re-display, size re-calculation and focuses grid.
*/
updateAndFocus: function() {
// Recalculate the measured item size.
this.measured_ = null;
this.columns = 0;
this.redraw();
this.focus();
},
/** /**
* Shows a checkmark on the active thumbnail and clears previous active one * Shows a checkmark on the active thumbnail and clears previous active one
* if any. Note if wallpaper was not set successfully, checkmark should not * if any. Note if wallpaper was not set successfully, checkmark should not
......
...@@ -23,7 +23,6 @@ function WallpaperManager(dialogDom) { ...@@ -23,7 +23,6 @@ function WallpaperManager(dialogDom) {
this.customWallpaperData_ = null; this.customWallpaperData_ = null;
this.currentWallpaper_ = null; this.currentWallpaper_ = null;
this.wallpaperRequest_ = null; this.wallpaperRequest_ = null;
this.wallpaperDirs_ = WallpaperDirectories.getInstance();
this.preDownloadDomInit_(); this.preDownloadDomInit_();
// TODO(wzang): Remove this class. // TODO(wzang): Remove this class.
this.document_.body.classList.add('v2'); this.document_.body.classList.add('v2');
...@@ -60,30 +59,6 @@ function WallpaperManager(dialogDom) { ...@@ -60,30 +59,6 @@ function WallpaperManager(dialogDom) {
// TODO(bshe): Get rid of anonymous namespace. // TODO(bshe): Get rid of anonymous namespace.
(function() { (function() {
/**
* URL of the learn more page for wallpaper picker.
*
* @const
*/
var LearnMoreURL =
'https://support.google.com/chromebook/?p=wallpaper_fileerror&hl=' +
navigator.language;
/**
* Index of the All category. It is the first category in wallpaper picker.
*
* @const
*/
var AllCategoryIndex = 0;
/**
* Index offset of categories parsed from manifest. The All category is added
* before them. So the offset is 1.
*
* @const
*/
var OnlineCategoriesOffset = 1;
/** /**
* The following values should be kept in sync with the style sheet. * The following values should be kept in sync with the style sheet.
*/ */
...@@ -103,15 +78,6 @@ function str(id) { ...@@ -103,15 +78,6 @@ function str(id) {
return loadTimeData.getString(id); return loadTimeData.getString(id);
} }
/**
* Returns the base name for |file_path|.
* @param {string} file_path The path of the file.
* @return {string} The base name of the file.
*/
function getBaseName(file_path) {
return file_path.substring(file_path.lastIndexOf('/') + 1);
}
/** /**
* Helper function to center the element. * Helper function to center the element.
* @param {Object} element The element to be centered. * @param {Object} element The element to be centered.
...@@ -352,44 +318,6 @@ WallpaperManager.prototype.showError_ = function(errorMessage) { ...@@ -352,44 +318,6 @@ WallpaperManager.prototype.showError_ = function(errorMessage) {
$('message-container').style.visibility = 'visible'; $('message-container').style.visibility = 'visible';
}; };
/**
* Toggle surprise me feature of wallpaper picker. It fires an storage
* onChanged event. Event handler for that event is in event_page.js.
*/
WallpaperManager.prototype.toggleSurpriseMe = function() {
var shouldEnable = !WallpaperUtil.getSurpriseMeCheckboxValue();
var onSuccess = () => {
if (chrome.runtime.lastError == null) {
if (shouldEnable) {
// Hides the wallpaper set by message if there is any.
$('wallpaper-set-by-message').textContent = '';
} else if (this.wallpaperGrid_.activeItem) {
// Unchecking the "Surprise me" checkbox falls back to the previous
// wallpaper before "Surprise me" was turned on.
this.setSelectedWallpaper_(this.wallpaperGrid_.activeItem);
this.onWallpaperChanged_(
this.wallpaperGrid_.activeItem, this.currentWallpaper_);
}
this.onSurpriseMeStateChanged_(shouldEnable);
} else {
// TODO(bshe): show error message to user.
console.error('Failed to save surprise me option to chrome storage.');
}
};
// To prevent the onChanged event being fired twice, we only save the value
// to sync storage if the sync theme is enabled, otherwise save it to local
// storage.
WallpaperUtil.enabledSyncThemesCallback(syncEnabled => {
if (syncEnabled)
WallpaperUtil.saveToSyncStorage(
Constants.AccessSyncSurpriseMeEnabledKey, shouldEnable, onSuccess);
else
WallpaperUtil.saveToLocalStorage(
Constants.AccessLocalSurpriseMeEnabledKey, shouldEnable, onSuccess);
});
};
/** /**
* One-time initialization of various DOM nodes. Fetching manifest or the * One-time initialization of various DOM nodes. Fetching manifest or the
* collection info may take a long time due to slow connection. Dom nodes that * collection info may take a long time due to slow connection. Dom nodes that
...@@ -462,95 +390,28 @@ WallpaperManager.prototype.postDownloadDomInit_ = function() { ...@@ -462,95 +390,28 @@ WallpaperManager.prototype.postDownloadDomInit_ = function() {
this.initializeDailyRefreshStates_(); this.initializeDailyRefreshStates_();
window.addEventListener('offline', () => { window.addEventListener('offline', () => {
$('wallpaper-grid').classList.add('image-picker-offline'); $('wallpaper-grid').classList.add('image-picker-offline');
this.showError_(str('connectionFailed')); this.showError_(str('connectionFailed'));
$('wallpaper-grid').highlightOfflineWallpapers(); $('wallpaper-grid').highlightOfflineWallpapers();
}); });
window.addEventListener('online', () => { window.addEventListener('online', () => {
// Fetch the collection info (if not yet) when device gets online. // Fetch the collection info (if not yet) when device gets online.
if (!this.collectionsInfo_) if (!this.collectionsInfo_)
this.getCollectionsInfo_(); this.getCollectionsInfo_();
// Force refreshing the images. // Force refreshing the images.
this.wallpaperGrid_.dataModel = null; this.wallpaperGrid_.dataModel = null;
this.onCategoriesChange_(); this.onCategoriesChange_();
$('message-container').style.visibility = 'hidden'; $('message-container').style.visibility = 'hidden';
this.downloadedListMap_ = null; this.downloadedListMap_ = null;
$('wallpaper-grid').classList.remove('image-picker-offline'); $('wallpaper-grid').classList.remove('image-picker-offline');
}); });
this.decorateCurrentWallpaperInfoBar_(); this.decorateCurrentWallpaperInfoBar_();
this.onResize_(); this.onResize_();
this.initContextMenuAndCommand_();
WallpaperUtil.testSendMessage('launched'); WallpaperUtil.testSendMessage('launched');
}; };
/**
* One-time initialization of context menu and command.
*/
WallpaperManager.prototype.initContextMenuAndCommand_ = function() {
this.wallpaperContextMenu_ = $('wallpaper-context-menu');
cr.ui.Menu.decorate(this.wallpaperContextMenu_);
cr.ui.contextMenuHandler.setContextMenu(
this.wallpaperGrid_, this.wallpaperContextMenu_);
var commands = this.dialogDom_.querySelectorAll('command');
for (var i = 0; i < commands.length; i++)
cr.ui.Command.decorate(commands[i]);
var doc = this.document_;
doc.addEventListener('command', this.onCommand_.bind(this));
doc.addEventListener('canExecute', this.onCommandCanExecute_.bind(this));
};
/**
* Handles a command being executed.
* @param {Event} event A command event.
*/
WallpaperManager.prototype.onCommand_ = function(event) {
if (event.command.id == 'delete') {
var wallpaperGrid = this.wallpaperGrid_;
var selectedIndex = wallpaperGrid.selectionModel.selectedIndex;
var item = wallpaperGrid.dataModel.item(selectedIndex);
if (!item || item.source != Constants.WallpaperSourceEnum.Custom)
return;
this.removeCustomWallpaper(item.baseURL);
wallpaperGrid.dataModel.splice(selectedIndex, 1);
// Calculate the number of remaining custom wallpapers. The add new button
// in data model needs to be excluded.
var customWallpaperCount = wallpaperGrid.dataModel.length - 1;
if (customWallpaperCount == 0) {
// Active custom wallpaper is also copied in chronos data dir. It needs
// to be deleted.
chrome.wallpaperPrivate.resetWallpaper();
this.onWallpaperChanged_(null, null);
} else {
selectedIndex = Math.min(selectedIndex, customWallpaperCount - 1);
wallpaperGrid.selectionModel.selectedIndex = selectedIndex;
}
event.cancelBubble = true;
}
};
/**
* Decides if a command can be executed on current target.
* @param {Event} event A command event.
*/
WallpaperManager.prototype.onCommandCanExecute_ = function(event) {
switch (event.command.id) {
case 'delete':
var wallpaperGrid = this.wallpaperGrid_;
var selectedIndex = wallpaperGrid.selectionModel.selectedIndex;
var item = wallpaperGrid.dataModel.item(selectedIndex);
if (selectedIndex != this.wallpaperGrid_.dataModel.length - 1 && item &&
item.source == Constants.WallpaperSourceEnum.Custom) {
event.canExecute = true;
break;
}
default:
event.canExecute = false;
}
};
/** /**
* Preset to the category which contains current wallpaper. * Preset to the category which contains current wallpaper.
*/ */
...@@ -559,23 +420,21 @@ WallpaperManager.prototype.presetCategory_ = function() { ...@@ -559,23 +420,21 @@ WallpaperManager.prototype.presetCategory_ = function() {
// custom wallpaper file name. // custom wallpaper file name.
this.currentWallpaper_ = str('currentWallpaper'); this.currentWallpaper_ = str('currentWallpaper');
this.currentWallpaperLayout_ = str('currentWallpaperLayout'); this.currentWallpaperLayout_ = str('currentWallpaperLayout');
// The default category is the last one (the custom category). // The default category is the last one (the custom category).
var categoryIndex = this.categoriesList_.dataModel.length - 1; var categoryIndex = this.categoriesList_.dataModel.length - 1;
Object.entries(this.imagesInfoMap_).forEach(([ Object.entries(this.imagesInfoMap_).forEach(([collectionId, imagesInfo]) => {
collectionId, imagesInfo for (var i = 0; i < imagesInfo.length; ++i) {
]) => { if (this.currentWallpaper_.includes(imagesInfo.item(i).baseURL)) {
for (var i = 0; i < imagesInfo.length; ++i) { for (var index = 0; index < this.collectionsInfo_.length; ++index) {
if (this.currentWallpaper_.includes(imagesInfo.item(i).baseURL)) { // Find the index of the category which the current wallpaper
for (var index = 0; index < this.collectionsInfo_.length; ++index) { // belongs to based on the collection id.
// Find the index of the category which the current wallpaper if (this.collectionsInfo_[index]['collectionId'] == collectionId)
// belongs to based on the collection id. categoryIndex = index;
if (this.collectionsInfo_[index]['collectionId'] == collectionId)
categoryIndex = index;
}
} }
} }
}); }
this.categoriesList_.selectionModel.selectedIndex = categoryIndex; });
this.categoriesList_.selectionModel.selectedIndex = categoryIndex;
}; };
/** /**
...@@ -875,9 +734,7 @@ WallpaperManager.prototype.setSelectedCustomWallpaper_ = function( ...@@ -875,9 +734,7 @@ WallpaperManager.prototype.setSelectedCustomWallpaper_ = function(
var successCallback = (imageData, optThumbnailData) => { var successCallback = (imageData, optThumbnailData) => {
this.onWallpaperChanged_(selectedItem, selectedItem.baseURL); this.onWallpaperChanged_(selectedItem, selectedItem.baseURL);
this.saveCustomWallpaperToSyncFS_( WallpaperUtil.storeWallpaperToSyncFS(selectedItem.baseURL, imageData);
selectedItem.baseURL, this.getSelectedLayout_(), imageData,
optThumbnailData, this.onFileSystemError_.bind(this));
}; };
this.setCustomWallpaperImpl_(selectedItem, successCallback); this.setCustomWallpaperImpl_(selectedItem, successCallback);
}; };
...@@ -1180,26 +1037,6 @@ WallpaperManager.prototype.onPreviewModeStarted_ = function( ...@@ -1180,26 +1037,6 @@ WallpaperManager.prototype.onPreviewModeStarted_ = function(
$('message-container').style.visibility = 'hidden'; $('message-container').style.visibility = 'hidden';
}; };
/*
* Removes the oldest custom wallpaper. If the oldest one is set as current
* wallpaper, removes the second oldest one to free some space. This should
* only be called when exceeding wallpaper quota.
*/
WallpaperManager.prototype.removeOldestWallpaper_ = function() {
// Custom wallpapers should already sorted when put to the data model. The
// last element is the add new button, need to exclude it as well.
var oldestIndex = this.wallpaperGrid_.dataModel.length - 2;
var item = this.wallpaperGrid_.dataModel.item(oldestIndex);
if (!item || item.source != Constants.WallpaperSourceEnum.Custom)
return;
if (item.baseURL == this.currentWallpaper_)
item = this.wallpaperGrid_.dataModel.item(--oldestIndex);
if (item) {
this.removeCustomWallpaper(item.baseURL);
this.wallpaperGrid_.dataModel.splice(oldestIndex, 1);
}
};
/* /*
* Shows a success message and closes the window. * Shows a success message and closes the window.
* @private * @private
...@@ -1217,43 +1054,11 @@ WallpaperManager.prototype.showSuccessMessageAndQuit_ = function() { ...@@ -1217,43 +1054,11 @@ WallpaperManager.prototype.showSuccessMessageAndQuit_ = function() {
}, 800); }, 800);
}; };
/*
* Shows an error message to user and log the failed reason in console.
*/
WallpaperManager.prototype.onFileSystemError_ = function(e) {
var msg = '';
switch (e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
// Instead of simply remove oldest wallpaper, we should consider a
// better way to handle this situation. See crbug.com/180890.
this.removeOldestWallpaper_();
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
}
console.error('Error: ' + msg);
this.showError_(str('accessFileFailure'));
};
/** /**
* Handles changing of selectedItem in wallpaper manager. * Handles changing of selectedItem in wallpaper manager.
*/ */
WallpaperManager.prototype.onSelectedItemChanged_ = function() { WallpaperManager.prototype.onSelectedItemChanged_ = function() {
if (!this.selectedItem_ || this.selectedItem_.source == 'ADDNEW') if (!this.selectedItem_)
return; return;
this.setWallpaperAttribution(this.selectedItem_); this.setWallpaperAttribution(this.selectedItem_);
...@@ -1347,78 +1152,6 @@ WallpaperManager.prototype.initCategoriesList_ = function() { ...@@ -1347,78 +1152,6 @@ WallpaperManager.prototype.initCategoriesList_ = function() {
this.categoriesList_.dataModel.push(str('customCategoryLabel')); this.categoriesList_.dataModel.push(str('customCategoryLabel'));
}; };
/**
* Removes wallpaper and thumbnail with fileName from FileSystem.
* @param {string} fileName The file name of wallpaper and thumbnail to be
* removed.
*/
WallpaperManager.prototype.removeCustomWallpaper = function(fileName) {
var errorHandler = this.onFileSystemError_.bind(this);
var self = this;
var removeFile = function(fileName) {
var success = function(dirEntry) {
dirEntry.getFile(fileName, {create: false}, function(fileEntry) {
fileEntry.remove(function() {
WallpaperUtil.deleteWallpaperFromSyncFS(fileName);
}, errorHandler);
}, errorHandler);
};
// Removes copy of original.
self.wallpaperDirs_.getDirectory(
Constants.WallpaperDirNameEnum.ORIGINAL, success, errorHandler);
// Removes generated thumbnail.
self.wallpaperDirs_.getDirectory(
Constants.WallpaperDirNameEnum.THUMBNAIL, success, errorHandler);
};
removeFile(fileName);
};
/**
* Saves the custom wallpaper and thumbnail (if any) to the sync file system.
* @param {string} fileName The file name of the wallpaper.
* @param {string} layout The desired layout of the wallpaper.
* @param {string} wallpaperData The data of the full-size wallpaper.
* @param {?string} optThumbnailData The data of the thumbnail-size wallpaper.
* @param {?function} optErrorCallbacka The error callback. Must be non-null if
* optThumbnailData is non-null.
* @private
*/
WallpaperManager.prototype.saveCustomWallpaperToSyncFS_ = function(
fileName, layout, wallpaperData, optThumbnailData, optErrorCallback) {
WallpaperUtil.storeWallpaperToSyncFS(fileName, wallpaperData);
if (!optThumbnailData)
return;
WallpaperUtil.storeWallpaperToSyncFS(
fileName + Constants.CustomWallpaperThumbnailSuffix, optThumbnailData);
var success = dirEntry => {
dirEntry.getFile(fileName, {create: true}, fileEntry => {
fileEntry.createWriter(fileWriter => {
fileWriter.onwriteend = e => {
$('set-wallpaper-layout').disabled = false;
var wallpaperInfo = {
baseURL: fileName,
layout: layout,
source: Constants.WallpaperSourceEnum.Custom,
availableOffline: true
};
this.wallpaperGrid_.dataModel.splice(0, 0, wallpaperInfo);
this.wallpaperGrid_.selectedItem = wallpaperInfo;
this.onWallpaperChanged_(wallpaperInfo, fileName);
WallpaperUtil.saveToLocalStorage(this.currentWallpaper_, layout);
};
fileWriter.onerror = optErrorCallback;
fileWriter.write(WallpaperUtil.createPngBlob(optThumbnailData));
}, optErrorCallback);
}, optErrorCallback);
};
this.wallpaperDirs_.getDirectory(
Constants.WallpaperDirNameEnum.THUMBNAIL, success, optErrorCallback);
};
/** /**
* Updates the layout of the currently set custom wallpaper. No-op if the * Updates the layout of the currently set custom wallpaper. No-op if the
* current wallpaper is not a custom wallpaper. * current wallpaper is not a custom wallpaper.
......
...@@ -43,7 +43,6 @@ found in the LICENSE file. ...@@ -43,7 +43,6 @@ found in the LICENSE file.
<script src="js/constants.js"></script> <script src="js/constants.js"></script>
<script src="js/util.js"></script> <script src="js/util.js"></script>
<script src="js/progress_manager.js"></script> <script src="js/progress_manager.js"></script>
<script src="js/wallpaper_directories.js"></script>
<script src="js/wallpaper_categories_list.js"></script> <script src="js/wallpaper_categories_list.js"></script>
<script src="js/wallpaper_images_grid.js"></script> <script src="js/wallpaper_images_grid.js"></script>
<script src="js/wallpaper_manager.js"></script> <script src="js/wallpaper_manager.js"></script>
...@@ -56,11 +55,6 @@ found in the LICENSE file. ...@@ -56,11 +55,6 @@ found in the LICENSE file.
shortcut="Delete"></command> shortcut="Delete"></command>
</commands> </commands>
<cr-menu id="wallpaper-context-menu" class="chrome-menu"
visibleif="custom surprise-me-disabled">
<cr-menu-item command="#delete"></cr-menu-item>
</cr-menu>
<div id="error-container" class="overlay-container" hidden> <div id="error-container" class="overlay-container" hidden>
<div class="page"> <div class="page">
<div id="close-error" class="close"></div> <div id="close-error" class="close"></div>
...@@ -134,7 +128,6 @@ found in the LICENSE file. ...@@ -134,7 +128,6 @@ found in the LICENSE file.
</div> </div>
</div> </div>
<grid id="wallpaper-grid" class="image-picker" tabIndex="-1"></grid> <grid id="wallpaper-grid" class="image-picker" tabIndex="-1"></grid>
<div id="spinner-container" hidden></div>
<div class="progress-bar" hidden> <div class="progress-bar" hidden>
<div class="progress-track"></div> <div class="progress-track"></div>
</div> </div>
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment