Commit 841235c1 authored by Wenzhao Zang's avatar Wenzhao Zang Committed by Commit Bot

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

Remove the |useNewWallpaperPicker| checks, and modify some comments.

Will need follow-up CLs to:
1) Remove the flag in //ash.
2) Take a second pass to check which CSS styles/functions/variables
   are unused.

Bug: 812085
Change-Id: I7faa99c16715360a95feed50b5041d89c8c322a1
Reviewed-on: https://chromium-review.googlesource.com/c/1297308Reviewed-by: default avatarXiaoqian Dai <xdai@chromium.org>
Commit-Queue: Wenzhao (Colin) Zang <wzang@chromium.org>
Cr-Commit-Position: refs/heads/master@{#602432}
parent 16826e3d
...@@ -25,8 +25,7 @@ ...@@ -25,8 +25,7 @@
AccessSyncWallpaperInfoKey: 'wallpaper-sync-info-key', AccessSyncWallpaperInfoKey: 'wallpaper-sync-info-key',
/** /**
* Key to access last changed date of a surprise me wallpaper (on the old * Key to access last changed date of a daily refresh wallpaper in
* picker) or a daily refresh wallpaper (on the new picker) in
* chrome.storage.local or chrome.storage.sync. * chrome.storage.local or chrome.storage.sync.
*/ */
AccessLastSurpriseWallpaperChangedDate: 'wallpaper-last-changed-date-key', AccessLastSurpriseWallpaperChangedDate: 'wallpaper-last-changed-date-key',
...@@ -44,20 +43,19 @@ ...@@ -44,20 +43,19 @@
AccessSyncSurpriseMeEnabledKey: 'sync-surprise-me-enabled-key', AccessSyncSurpriseMeEnabledKey: 'sync-surprise-me-enabled-key',
/** /**
* Key to access the info related to daily refresh feature (on the new * Key to access the info related to daily refresh feature in
* wallpaper picker) in chrome.storage.local. * chrome.storage.local.
*/ */
AccessLocalDailyRefreshInfoKey: 'daily-refresh-info-key', AccessLocalDailyRefreshInfoKey: 'daily-refresh-info-key',
/** /**
* Key to access the info related to daily refresh feature (on the new * Key to access the info related to daily refresh feature in
* wallpaper picker) in chrome.storage.sync. * chrome.storage.sync.
*/ */
AccessSyncDailyRefreshInfoKey: 'sync-daily-refresh-info-key', AccessSyncDailyRefreshInfoKey: 'sync-daily-refresh-info-key',
/** /**
* Key to access the images info (on the new wallpaper picker) in * Key to access the images info in chrome.storage.local.
* chrome.storage.local.
*/ */
AccessLocalImagesInfoKey: 'images-info-key', AccessLocalImagesInfoKey: 'images-info-key',
......
...@@ -7,14 +7,13 @@ var wallpaperPickerWindow = null; ...@@ -7,14 +7,13 @@ var wallpaperPickerWindow = null;
var surpriseWallpaper = null; var surpriseWallpaper = null;
/** /**
* Returns information related to the wallpaper picker. * Returns the highResolutionSuffix.
* @param {function} callback A callback function that takes two values: * @param {function} callback A callback function that takes one value:
* |useNewWallpaperPicker|: if the new wallpaper picker is enabled.
* |highResolutionSuffix|: the suffix to append to the wallpaper urls. * |highResolutionSuffix|: the suffix to append to the wallpaper urls.
*/ */
function getWallpaperPickerInfo(callback) { function getHighResolutionSuffix(callback) {
chrome.wallpaperPrivate.getStrings(strings => { chrome.wallpaperPrivate.getStrings(strings => {
callback(strings['useNewWallpaperPicker'], strings['highResolutionSuffix']); callback(strings['highResolutionSuffix']);
}); });
} }
...@@ -170,45 +169,11 @@ SurpriseWallpaper.prototype.setRandomWallpaper_ = function(dateString) { ...@@ -170,45 +169,11 @@ SurpriseWallpaper.prototype.setRandomWallpaper_ = function(dateString) {
}); });
}; };
getWallpaperPickerInfo((useNewWallpaperPicker, highResolutionSuffix) => { getHighResolutionSuffix(highResolutionSuffix => {
if (useNewWallpaperPicker) this.setRandomWallpaperFromServer_(onSuccess, highResolutionSuffix);
this.setRandomWallpaperFromServer_(onSuccess, highResolutionSuffix);
else
this.setRandomWallpaperFromManifest_(onSuccess, highResolutionSuffix);
}); });
}; };
/**
* Sets wallpaper to be a random one found in the stored manifest file. If the
* wallpaper download fails, retry one hour later. Wallpapers that are disabled
* for surprise me are excluded.
* @param {function} onSuccess The success callback.
* @param {string} suffix The url suffix for high resolution wallpaper.
* @private
*/
SurpriseWallpaper.prototype.setRandomWallpaperFromManifest_ = function(
onSuccess, suffix) {
Constants.WallpaperLocalStorage.get(
Constants.AccessLocalManifestKey, items => {
var manifest = items[Constants.AccessLocalManifestKey];
if (manifest && manifest.wallpaper_list) {
var filtered = manifest.wallpaper_list.filter(function(element) {
// Older version manifest do not have available_for_surprise_me
// field. In this case, no wallpaper should be filtered out.
return element.available_for_surprise_me ||
element.available_for_surprise_me == undefined;
});
var index = Math.floor(Math.random() * filtered.length);
var wallpaper = filtered[index];
var wallpaperUrl = wallpaper.base_url + suffix;
WallpaperUtil.setOnlineWallpaperWithoutPreview(
wallpaperUrl, wallpaper.default_layout,
onSuccess.bind(null, wallpaperUrl, wallpaper.default_layout),
this.retryLater_.bind(this));
}
});
};
/** /**
* Sets wallpaper to be a random one retrieved from the backend service. If the * Sets wallpaper to be a random one retrieved from the backend service. If the
* wallpaper download fails, retry one hour later. * wallpaper download fails, retry one hour later.
...@@ -351,47 +316,33 @@ chrome.app.runtime.onLaunched.addListener(function() { ...@@ -351,47 +316,33 @@ chrome.app.runtime.onLaunched.addListener(function() {
return; return;
} }
getWallpaperPickerInfo((useNewWallpaperPicker, highResolutionSuffix) => { var options = {
var options = frame: 'none',
useNewWallpaperPicker ? innerBounds: {width: 768, height: 512, minWidth: 768, minHeight: 512},
{ resizable: true,
frame: 'none', alphaEnabled: true
innerBounds: {width: 768, height: 512, minWidth: 768, minHeight: 512}, };
resizable: true,
alphaEnabled: true chrome.app.window.create('main.html', options, function(window) {
} : wallpaperPickerWindow = window;
{ chrome.wallpaperPrivate.minimizeInactiveWindows();
frame: 'none', window.onClosed.addListener(function() {
width: 574, wallpaperPickerWindow = null;
height: 420, // In case the app exits unexpectedly during preview.
resizable: false, chrome.wallpaperPrivate.cancelPreviewWallpaper(() => {});
alphaEnabled: true // If the app exits during preview, do not restore the previously active
}; // windows. Continue to show the new wallpaper.
if (!window.contentWindow.document.body.classList.contains(
chrome.app.window.create('main.html', options, function(window) { 'preview-mode')) {
wallpaperPickerWindow = window; chrome.wallpaperPrivate.restoreMinimizedWindows();
chrome.wallpaperPrivate.minimizeInactiveWindows();
window.onClosed.addListener(function() {
wallpaperPickerWindow = null;
// In case the app exits unexpectedly during preview.
chrome.wallpaperPrivate.cancelPreviewWallpaper(() => {});
// If the app exits during preview, do not restore the previously active
// windows. Continue to show the new wallpaper.
if (!window.contentWindow.document.body.classList.contains(
'preview-mode')) {
chrome.wallpaperPrivate.restoreMinimizedWindows();
}
});
if (useNewWallpaperPicker) {
// By design, the new wallpaper picker should never be shown on top of
// another window.
wallpaperPickerWindow.contentWindow.addEventListener(
'focus', function() {
chrome.wallpaperPrivate.minimizeInactiveWindows();
});
} }
WallpaperUtil.testSendMessage('wallpaper-window-created');
}); });
// By design, the wallpaper picker should never be shown on top of
// another window.
wallpaperPickerWindow.contentWindow.addEventListener('focus', function() {
chrome.wallpaperPrivate.minimizeInactiveWindows();
});
WallpaperUtil.testSendMessage('wallpaper-window-created');
}); });
}); });
...@@ -433,7 +384,6 @@ chrome.syncFileSystem.onFileStatusChanged.addListener(function(detail) { ...@@ -433,7 +384,6 @@ chrome.syncFileSystem.onFileStatusChanged.addListener(function(detail) {
chrome.storage.onChanged.addListener(function(changes, namespace) { chrome.storage.onChanged.addListener(function(changes, namespace) {
WallpaperUtil.enabledSyncThemesCallback(function(syncEnabled) { WallpaperUtil.enabledSyncThemesCallback(function(syncEnabled) {
// Daily refresh feature is on the new wallpaper picker only.
var updateDailyRefreshStates = key => { var updateDailyRefreshStates = key => {
if (!changes[key]) if (!changes[key])
return; return;
...@@ -474,17 +424,6 @@ chrome.storage.onChanged.addListener(function(changes, namespace) { ...@@ -474,17 +424,6 @@ chrome.storage.onChanged.addListener(function(changes, namespace) {
if (!wallpaperPickerWindow) if (!wallpaperPickerWindow)
return; return;
var wpDocument = wallpaperPickerWindow.contentWindow.document; var wpDocument = wallpaperPickerWindow.contentWindow.document;
var hideCheckMarkIfNeeded = () => {
getWallpaperPickerInfo(
(useNewWallpaperPicker, highResolutionSuffix) => {
// Do not hide the check mark on the new picker.
if (!useNewWallpaperPicker &&
wpDocument.querySelector('.check')) {
wpDocument.querySelector('.check').style.visibility =
'hidden';
}
});
};
if (!!appName) { if (!!appName) {
chrome.wallpaperPrivate.getStrings(function(strings) { chrome.wallpaperPrivate.getStrings(function(strings) {
...@@ -493,7 +432,6 @@ chrome.storage.onChanged.addListener(function(changes, namespace) { ...@@ -493,7 +432,6 @@ chrome.storage.onChanged.addListener(function(changes, namespace) {
wpDocument.querySelector('#wallpaper-set-by-message').textContent = wpDocument.querySelector('#wallpaper-set-by-message').textContent =
message; message;
wpDocument.querySelector('#wallpaper-grid').classList.add('small'); wpDocument.querySelector('#wallpaper-grid').classList.add('small');
hideCheckMarkIfNeeded();
wpDocument.querySelector('#checkbox').classList.remove('checked'); wpDocument.querySelector('#checkbox').classList.remove('checked');
wpDocument.querySelector('#categories-list').disabled = false; wpDocument.querySelector('#categories-list').disabled = false;
wpDocument.querySelector('#wallpaper-grid').disabled = false; wpDocument.querySelector('#wallpaper-grid').disabled = false;
...@@ -511,7 +449,6 @@ chrome.storage.onChanged.addListener(function(changes, namespace) { ...@@ -511,7 +449,6 @@ chrome.storage.onChanged.addListener(function(changes, namespace) {
if (enable) { if (enable) {
wpDocument.querySelector('#checkbox') wpDocument.querySelector('#checkbox')
.classList.add('checked'); .classList.add('checked');
hideCheckMarkIfNeeded();
} else { } else {
wpDocument.querySelector('#checkbox') wpDocument.querySelector('#checkbox')
.classList.remove('checked'); .classList.remove('checked');
...@@ -519,15 +456,6 @@ chrome.storage.onChanged.addListener(function(changes, namespace) { ...@@ -519,15 +456,6 @@ chrome.storage.onChanged.addListener(function(changes, namespace) {
wpDocument.querySelector('.check').style.visibility = wpDocument.querySelector('.check').style.visibility =
'visible'; 'visible';
} }
getWallpaperPickerInfo(
(useNewWallpaperPicker, highResolutionSuffix) => {
if (!useNewWallpaperPicker) {
wpDocument.querySelector('#wallpaper-grid').disabled =
enable;
wpDocument.querySelector('#categories-list').disabled =
enable;
}
});
}); });
} }
}; };
...@@ -665,13 +593,6 @@ chrome.wallpaperPrivate.onWallpaperChangedBy3rdParty.addListener(function( ...@@ -665,13 +593,6 @@ chrome.wallpaperPrivate.onWallpaperChangedBy3rdParty.addListener(function(
WallpaperUtil.saveWallpaperInfo( WallpaperUtil.saveWallpaperInfo(
fileName, layout, Constants.WallpaperSourceEnum.ThirdParty, appName); fileName, layout, Constants.WallpaperSourceEnum.ThirdParty, appName);
getWallpaperPickerInfo((useNewWallpaperPicker, highResolutionSuffix) => {
// Surprise me/daily refresh should be auto-disabled if wallpaper is changed
// by third-party apps.
if (!useNewWallpaperPicker) {
SurpriseWallpaper.getInstance().disable();
return;
}
WallpaperUtil.saveDailyRefreshInfo( WallpaperUtil.saveDailyRefreshInfo(
{enabled: false, collectionId: null, resumeToken: null}); {enabled: false, collectionId: null, resumeToken: null});
...@@ -681,5 +602,4 @@ chrome.wallpaperPrivate.onWallpaperChangedBy3rdParty.addListener(function( ...@@ -681,5 +602,4 @@ chrome.wallpaperPrivate.onWallpaperChangedBy3rdParty.addListener(function(
{detail: {wallpaperFileName: fileName}}); {detail: {wallpaperFileName: fileName}});
wallpaperPickerWindow.contentWindow.dispatchEvent(event); wallpaperPickerWindow.contentWindow.dispatchEvent(event);
} }
});
}); });
...@@ -391,15 +391,6 @@ WallpaperUtil.setOnlineWallpaperWithoutPreview = function( ...@@ -391,15 +391,6 @@ WallpaperUtil.setOnlineWallpaperWithoutPreview = function(
}); });
}; };
/**
* Gets the suffix to append to the base url of an online wallpaper. The
* requested thumbnail is displayed in the wallpaper picker grid.
*/
WallpaperUtil.getOnlineWallpaperThumbnailSuffix = function() {
return loadTimeData.getBoolean('useNewWallpaperPicker') ? '' :
'_thumbnail.png';
};
/** /**
* Creates a blob of type 'image/png'. * Creates a blob of type 'image/png'.
* @param {string} data The image data. * @param {string} data The image data.
...@@ -427,35 +418,22 @@ WallpaperUtil.displayImage = function(imageElement, data, opt_callback) { ...@@ -427,35 +418,22 @@ WallpaperUtil.displayImage = function(imageElement, data, opt_callback) {
}; };
/** /**
* Sets the value of the surprise me checkbox (or the daily refresh toggle on * Sets the value of the daily refresh toggle.
* the new picker).
* @param {boolean} checked The value used to set the checkbox. * @param {boolean} checked The value used to set the checkbox.
*/ */
WallpaperUtil.setSurpriseMeCheckboxValue = function(checked) { WallpaperUtil.setSurpriseMeCheckboxValue = function(checked) {
if (loadTimeData.getBoolean('useNewWallpaperPicker')) {
document.querySelectorAll('.daily-refresh-slider').forEach(element => { document.querySelectorAll('.daily-refresh-slider').forEach(element => {
element.classList.toggle('checked', checked); element.classList.toggle('checked', checked);
}); });
} else {
$('surprise-me')
.querySelector('#checkbox')
.classList.toggle('checked', checked);
}
}; };
/** /**
* Gets the value of the surprise me checkbox (or the value of the daily refresh * Gets the state of the daily refresh toggle.
* toggle on the new picker).
* @return {boolean} The value of the checkbox. * @return {boolean} The value of the checkbox.
*/ */
WallpaperUtil.getSurpriseMeCheckboxValue = function() { WallpaperUtil.getSurpriseMeCheckboxValue = function() {
if (loadTimeData.getBoolean('useNewWallpaperPicker')) {
return document.querySelector('.daily-refresh-slider') return document.querySelector('.daily-refresh-slider')
.classList.contains('checked'); .classList.contains('checked');
}
return $('surprise-me')
.querySelector('#checkbox')
.classList.contains('checked');
}; };
/** /**
...@@ -475,8 +453,7 @@ WallpaperUtil.displayThumbnail = function(imageElement, url, source) { ...@@ -475,8 +453,7 @@ WallpaperUtil.displayThumbnail = function(imageElement, url, source) {
// operation within |WallpaperThumbnailsGridItem.decorate| hasn't // operation within |WallpaperThumbnailsGridItem.decorate| hasn't
// completed. See http://crbug.com/792829. // completed. See http://crbug.com/792829.
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.open( xhr.open('GET', url, true);
'GET', url + WallpaperUtil.getOnlineWallpaperThumbnailSuffix(), true);
xhr.responseType = 'arraybuffer'; xhr.responseType = 'arraybuffer';
xhr.send(null); xhr.send(null);
xhr.addEventListener('load', function(e) { xhr.addEventListener('load', function(e) {
......
...@@ -70,11 +70,9 @@ cr.define('wallpapers', function() { ...@@ -70,11 +70,9 @@ cr.define('wallpapers', function() {
var div = self.ownerDocument.createElement('div'); var div = self.ownerDocument.createElement('div');
div.textContent = entry; div.textContent = entry;
li.appendChild(div); li.appendChild(div);
if (loadTimeData.getBoolean('useNewWallpaperPicker')) {
li.addEventListener('mousedown', e => { li.addEventListener('mousedown', e => {
e.preventDefault(); e.preventDefault();
}); });
}
return li; return li;
}; };
}, },
......
...@@ -86,21 +86,18 @@ cr.define('wallpapers', function() { ...@@ -86,21 +86,18 @@ cr.define('wallpapers', function() {
} }
var imageEl = cr.doc.createElement('img'); var imageEl = cr.doc.createElement('img');
if (loadTimeData.getBoolean('useNewWallpaperPicker')) { // Do not show the image until |cropImageToFitGrid_| is done.
// On the new picker, do not show the image until |cropImageToFitGrid_| imageEl.style.visibility = 'hidden';
// is done. imageEl.setAttribute('aria-hidden', 'true');
imageEl.style.visibility = 'hidden'; this.setAttribute('aria-label', this.dataItem.ariaLabel);
imageEl.setAttribute('aria-hidden', 'true'); this.tabIndex = 0;
this.setAttribute('aria-label', this.dataItem.ariaLabel); this.addEventListener('keypress', e => {
this.tabIndex = 0; if (e.keyCode == 13)
this.addEventListener('keypress', e => { this.parentNode.selectedItem = this.dataItem;
if (e.keyCode == 13) });
this.parentNode.selectedItem = this.dataItem; this.addEventListener('mousedown', e => {
}); e.preventDefault();
this.addEventListener('mousedown', e => { });
e.preventDefault();
});
}
imageEl.classList.add('thumbnail'); imageEl.classList.add('thumbnail');
cr.defineProperty(imageEl, 'offline', cr.PropertyKind.BOOL_ATTR); cr.defineProperty(imageEl, 'offline', cr.PropertyKind.BOOL_ATTR);
...@@ -119,10 +116,7 @@ cr.define('wallpapers', function() { ...@@ -119,10 +116,7 @@ cr.define('wallpapers', function() {
window.setTimeout(this.callback_.bind(this, this.dataModelId_), 0); window.setTimeout(this.callback_.bind(this, this.dataModelId_), 0);
break; break;
case Constants.WallpaperSourceEnum.Custom: case Constants.WallpaperSourceEnum.Custom:
if (loadTimeData.getBoolean('useNewWallpaperPicker')) this.decorateCustomWallpaper_(imageEl, this.dataItem);
this.decorateCustomWallpaper_(imageEl, this.dataItem);
else
this.decorateCustomWallpaperForOldPicker_(imageEl, this.dataItem);
break; break;
case Constants.WallpaperSourceEnum.OEM: case Constants.WallpaperSourceEnum.OEM:
case Constants.WallpaperSourceEnum.Online: case Constants.WallpaperSourceEnum.Online:
...@@ -141,8 +135,7 @@ cr.define('wallpapers', function() { ...@@ -141,8 +135,7 @@ cr.define('wallpapers', function() {
}, },
/** /**
* Initializes the grid item for custom wallpapers. Used by the new * Initializes the grid item for custom wallpapers.
* wallpaper picker.
* @param {Object} imageElement The image element. * @param {Object} imageElement The image element.
* @param {{filePath: string, baseURL: string, layout: string, * @param {{filePath: string, baseURL: string, layout: string,
* source: string, availableOffline: boolean} * source: string, availableOffline: boolean}
...@@ -181,45 +174,6 @@ cr.define('wallpapers', function() { ...@@ -181,45 +174,6 @@ cr.define('wallpapers', function() {
}); });
}, },
/**
* Initializes the grid item for custom wallpapers. Used by the old
* wallpaper picker (to be deprecated).
* @param {Object} imageElement The image element.
* @param {{filePath: string, baseURL: string, layout: string,
* source: string, availableOffline: boolean}
* dataItem The info related to the wallpaper image.
* @private
*/
decorateCustomWallpaperForOldPicker_(imageElement, dataItem) {
if (dataItem.source != Constants.WallpaperSourceEnum.Custom) {
console.error(
'|decorateCustomWallpaperForOldPicker_| is called but the ' +
'wallpaper source is not custom.');
return;
}
var errorHandler = e => {
console.error('Can not access file system.');
this.callback_(this.dataModelId_);
};
var setURL = fileEntry => {
imageElement.src = fileEntry.toURL();
this.callback_(this.dataModelId_, dataItem.wallpaperId, imageElement);
};
var wallpaperDirectories = WallpaperDirectories.getInstance();
var fallback = () => {
wallpaperDirectories.getDirectory(
Constants.WallpaperDirNameEnum.ORIGINAL, function(dirEntry) {
dirEntry.getFile(
dataItem.baseURL, {create: false}, setURL, errorHandler);
}, errorHandler);
};
var success = dirEntry => {
dirEntry.getFile(dataItem.baseURL, {create: false}, setURL, fallback);
};
wallpaperDirectories.getDirectory(
Constants.WallpaperDirNameEnum.THUMBNAIL, success, errorHandler);
},
/** /**
* Initializes the grid item for online or OEM wallpapers. * Initializes the grid item for online or OEM wallpapers.
* @param {Object} imageElement The image element. * @param {Object} imageElement The image element.
...@@ -248,11 +202,7 @@ cr.define('wallpapers', function() { ...@@ -248,11 +202,7 @@ cr.define('wallpapers', function() {
} else if ( } else if (
dataItem.source == Constants.WallpaperSourceEnum.Online) { dataItem.source == Constants.WallpaperSourceEnum.Online) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.open( xhr.open('GET', dataItem.baseURL, true);
'GET',
dataItem.baseURL +
WallpaperUtil.getOnlineWallpaperThumbnailSuffix(),
true);
xhr.responseType = 'arraybuffer'; xhr.responseType = 'arraybuffer';
xhr.send(null); xhr.send(null);
xhr.addEventListener('load', e => { xhr.addEventListener('load', e => {
...@@ -443,22 +393,9 @@ cr.define('wallpapers', function() { ...@@ -443,22 +393,9 @@ cr.define('wallpapers', function() {
// item is constructed in function itemConstructor below. // item is constructed in function itemConstructor below.
this.pendingItems_ = 0; this.pendingItems_ = 0;
// Only show the spinner on the old wallpaper picker.
if (!this.useNewWallpaperPicker_) {
this.style.visibility = 'hidden';
// If spinner is hidden, schedule to show the spinner after
// ShowSpinnerDelayMs delay. Otherwise, keep it spinning.
if ($('spinner-container').hidden) {
this.spinnerTimeout_ = window.setTimeout(function() {
$('spinner-container').hidden = false;
}, ShowSpinnerDelayMs);
}
}
// Add a daily refresh item as the first element of the grid when // Add a daily refresh item as the first element of the grid when
// showing online wallpapers on the new wallpaper picker. // showing online wallpapers.
if (this.useNewWallpaperPicker_ && if (dataModel.item(0).source == Constants.WallpaperSourceEnum.Online) {
dataModel.item(0).source == Constants.WallpaperSourceEnum.Online) {
dataModel.splice( dataModel.splice(
0, 0, {isDailyRefreshItem: true, availableOffline: false}); 0, 0, {isDailyRefreshItem: true, availableOffline: false});
} }
...@@ -542,10 +479,9 @@ cr.define('wallpapers', function() { ...@@ -542,10 +479,9 @@ cr.define('wallpapers', function() {
if (opt_wallpaperId && opt_thumbnail) if (opt_wallpaperId && opt_thumbnail)
this.thumbnailList_[opt_wallpaperId] = opt_thumbnail; this.thumbnailList_[opt_wallpaperId] = opt_thumbnail;
if (opt_thumbnail && this.useNewWallpaperPicker_) if (opt_thumbnail)
this.cropImageToFitGrid_(opt_thumbnail); this.cropImageToFitGrid_(opt_thumbnail);
// Daily refresh item only exists in new wallpaper picker.
if (this.isShowingDailyRefresh) { if (this.isShowingDailyRefresh) {
var dailyRefreshItemReady = this.dailyRefreshItem && var dailyRefreshItemReady = this.dailyRefreshItem &&
this.dailyRefreshImages.length >= DAILY_REFRESH_IMAGES_NUM; this.dailyRefreshImages.length >= DAILY_REFRESH_IMAGES_NUM;
...@@ -592,10 +528,8 @@ cr.define('wallpapers', function() { ...@@ -592,10 +528,8 @@ cr.define('wallpapers', function() {
window.clearTimeout(this.dailyRefreshTimer_); window.clearTimeout(this.dailyRefreshTimer_);
this.showNextImage_(0); this.showNextImage_(0);
} }
if (this.useNewWallpaperPicker_ && if (this.classList.contains('image-picker-offline'))
this.classList.contains('image-picker-offline')) {
this.highlightOfflineWallpapers(); this.highlightOfflineWallpapers();
}
} }
}, },
...@@ -612,8 +546,6 @@ cr.define('wallpapers', function() { ...@@ -612,8 +546,6 @@ cr.define('wallpapers', function() {
this.checkmark_.tabIndex = 0; this.checkmark_.tabIndex = 0;
this.dataModel = new ArrayDataModel([]); this.dataModel = new ArrayDataModel([]);
this.thumbnailList_ = new ArrayDataModel([]); this.thumbnailList_ = new ArrayDataModel([]);
this.useNewWallpaperPicker_ =
loadTimeData.getBoolean('useNewWallpaperPicker');
var self = this; var self = this;
this.itemConstructor = function(value) { this.itemConstructor = function(value) {
var dataModelId = self.dataModelId_; var dataModelId = self.dataModelId_;
...@@ -768,10 +700,8 @@ cr.define('wallpapers', function() { ...@@ -768,10 +700,8 @@ cr.define('wallpapers', function() {
* the other wallpapers. * the other wallpapers.
*/ */
highlightOfflineWallpapers: function() { highlightOfflineWallpapers: function() {
if (!this.useNewWallpaperPicker_ || if (!this.classList.contains('image-picker-offline'))
!this.classList.contains('image-picker-offline')) {
return; return;
}
chrome.wallpaperPrivate.getOfflineWallpaperList(list => { chrome.wallpaperPrivate.getOfflineWallpaperList(list => {
var offlineWallpaperList = {}; var offlineWallpaperList = {};
...@@ -802,23 +732,21 @@ cr.define('wallpapers', function() { ...@@ -802,23 +732,21 @@ cr.define('wallpapers', function() {
// The active thumbnail maybe deleted in the above redraw(). Sets it again // The active thumbnail maybe deleted in the above redraw(). Sets it again
// to make sure checkmark shows correctly. // to make sure checkmark shows correctly.
this.updateActiveThumb_(); this.updateActiveThumb_();
if (this.useNewWallpaperPicker_) { if (this.dataModel) {
if (this.dataModel) { var scrollUp =
var scrollUp = this.cachedScrollTop_ && this.cachedScrollTop_ > this.scrollTop;
this.cachedScrollTop_ && this.cachedScrollTop_ > this.scrollTop; for (var i = 0; i < this.dataModel.length; ++i) {
for (var i = 0; i < this.dataModel.length; ++i) { if (this.getListItemByIndex(i)) {
if (this.getListItemByIndex(i)) { this.getListItemByIndex(i).classList.toggle(
this.getListItemByIndex(i).classList.toggle( 'first-row',
'first-row', i < this.columns &&
i < this.columns && (this.firstIndex_ == 0 || i != this.firstIndex_ ||
(this.firstIndex_ == 0 || i != this.firstIndex_ || scrollUp));
scrollUp));
}
} }
} }
wallpaperManager.onScrollPositionChanged(this.scrollTop);
this.cachedScrollTop_ = this.scrollTop;
} }
wallpaperManager.onScrollPositionChanged(this.scrollTop);
this.cachedScrollTop_ = this.scrollTop;
} }
}; };
......
...@@ -18,10 +18,6 @@ ...@@ -18,10 +18,6 @@
function WallpaperManager(dialogDom) { function WallpaperManager(dialogDom) {
this.dialogDom_ = dialogDom; this.dialogDom_ = dialogDom;
this.document_ = dialogDom.ownerDocument; this.document_ = dialogDom.ownerDocument;
this.useNewWallpaperPicker_ =
loadTimeData.getBoolean('useNewWallpaperPicker');
this.enableOnlineWallpaper_ = loadTimeData.valueExists('manifestBaseURL') ||
this.useNewWallpaperPicker_;
this.selectedItem_ = null; this.selectedItem_ = null;
this.progressManager_ = new ProgressManager(); this.progressManager_ = new ProgressManager();
this.customWallpaperData_ = null; this.customWallpaperData_ = null;
...@@ -29,45 +25,35 @@ function WallpaperManager(dialogDom) { ...@@ -29,45 +25,35 @@ function WallpaperManager(dialogDom) {
this.wallpaperRequest_ = null; this.wallpaperRequest_ = null;
this.wallpaperDirs_ = WallpaperDirectories.getInstance(); this.wallpaperDirs_ = WallpaperDirectories.getInstance();
this.preDownloadDomInit_(); this.preDownloadDomInit_();
// TODO(wzang): Remove this class.
// Uses the redesigned wallpaper picker if |useNewWallpaperPicker| is true. this.document_.body.classList.add('v2');
//
// The old wallpaper picker fetches the manifest file once, and parse the info // The wallpaper picker has two steps of fetching the online images: it first
// (such as image url) from the file every time when the images need to be // fetches a list of collection names (ie. categories such as Art,
// displayed. // Landscape etc.) via extension API, and then fetches the info specific to
// The new wallpaper picker has two steps: it first fetches a list of // each collection and caches the info in a map.
// collection names (ie. categories such as Art, Landscape etc.) via extension // After the url and relevant info of the images are fetched, it passes the
// API, and then fetches the info specific to each collection and caches the // info to |WallpaperThumbnailsGridItem| to display the images.
// info in a map.
// After the url and relevant info of the images are fetched, the two share // |collectionsInfo_| represents the list of wallpaper collections. Each
// the same path, ie. pass the info to |WallpaperThumbnailsGridItem| for // collection contains the display name and a unique id.
// actual image rendering. this.collectionsInfo_ = null;
this.document_.body.classList.add(this.useNewWallpaperPicker_ ? 'v2' : 'v1'); // |imagesInfoMap_| caches the mapping between each collection id and the
// images that belong to this collection. Each image is represented by a set
if (this.useNewWallpaperPicker_) { // of info including the image url, author name, layout etc. Such info will
// |collectionsInfo_| represents the list of wallpaper collections. Each // be used by |WallpaperThumbnailsGridItem| to display the images.
// collection contains the display name and a unique id. this.imagesInfoMap_ = {};
this.collectionsInfo_ = null; // The total count of images whose info has been fetched.
// |imagesInfoMap_| caches the mapping between each collection id and the this.imagesInfoCount_ = 0;
// images that belong to this collection. Each image is represented by a set // |dailyRefreshInfo_| stores the info related to the daily refresh feature.
// of info including the image url, author name, layout etc. Such info will // Its value should be consistent with the sync/local storage.
// be used by |WallpaperThumbnailsGridItem| to display the images. this.dailyRefreshInfo_ = null;
this.imagesInfoMap_ = {}; // |pendingDailyRefreshInfo_| stores the up-to-date daily refresh info that
// The total count of images whose info has been fetched. // hasn't been confirmed by user (e.g. when user is previewing the image).
this.imagesInfoCount_ = 0; // Its value will either replace |dailyRefreshInfo_| or be discarded.
// |dailyRefreshInfo_| stores the info related to the daily refresh feature this.pendingDailyRefreshInfo_ = null;
// on the new picker. Its value should be consistent with the sync/local this.placeWallpaperPicker_();
// storage. this.getCollectionsInfo_();
this.dailyRefreshInfo_ = null;
// |pendingDailyRefreshInfo_| stores the up-to-date daily refresh info that
// hasn't been confirmed by user (e.g. when user is previewing the image).
// Its value will either replace |dailyRefreshInfo_| or be discarded.
this.pendingDailyRefreshInfo_ = null;
this.placeWallpaperPicker_();
this.getCollectionsInfo_();
} else {
this.fetchManifest_();
}
} }
// Anonymous 'namespace'. // Anonymous 'namespace'.
...@@ -152,80 +138,6 @@ WallpaperManager.initStrings = function(callback) { ...@@ -152,80 +138,6 @@ WallpaperManager.initStrings = function(callback) {
}); });
}; };
/**
* Requests wallpaper manifest file from server.
*/
WallpaperManager.prototype.fetchManifest_ = function() {
var locale = navigator.language;
if (!this.enableOnlineWallpaper_) {
this.postDownloadDomInit_();
return;
}
var urls = [
str('manifestBaseURL') + locale + '.json',
// Fallback url. Use 'en' locale by default.
str('manifestBaseURL') + 'en.json'
];
var asyncFetchManifestFromUrls = function(
urls, func, successCallback, failureCallback) {
var index = 0;
var loop = {
next: function() {
if (index < urls.length) {
func(loop, urls[index]);
index++;
} else {
failureCallback();
}
},
success: function(response) {
successCallback(response);
},
failure: function() {
failureCallback();
}
};
loop.next();
};
var fetchManifestAsync = function(loop, url) {
var xhr = new XMLHttpRequest();
try {
xhr.addEventListener('loadend', function(e) {
if (this.status == 200 && this.responseText != null) {
try {
var manifest = JSON.parse(this.responseText);
loop.success(manifest);
} catch (e) {
loop.failure();
}
} else {
loop.next();
}
});
xhr.open('GET', url, true);
xhr.send(null);
} catch (e) {
loop.failure();
}
};
if (navigator.onLine) {
asyncFetchManifestFromUrls(
urls, fetchManifestAsync, this.onLoadManifestSuccess_.bind(this),
this.onLoadManifestFailed_.bind(this));
} else {
// If device is offline, fetches manifest from local storage.
// TODO(bshe): Always loading the offline manifest first and replacing
// with the online one when available.
this.onLoadManifestFailed_();
}
};
/** /**
* Fetches wallpaper collection info. * Fetches wallpaper collection info.
* @private * @private
...@@ -344,8 +256,7 @@ WallpaperManager.prototype.getCollectionsInfo_ = function() { ...@@ -344,8 +256,7 @@ WallpaperManager.prototype.getCollectionsInfo_ = function() {
}; };
/** /**
* Displays images that belong to the particular collection on the new wallpaper * Displays images that belong to the particular collection.
* picker.
* @param {number} index The index of the collection in |collectionsInfo_| list. * @param {number} index The index of the collection in |collectionsInfo_| list.
* @private * @private
*/ */
...@@ -367,13 +278,10 @@ WallpaperManager.prototype.showCollection_ = function(index) { ...@@ -367,13 +278,10 @@ WallpaperManager.prototype.showCollection_ = function(index) {
/** /**
* Places the main dialog in the center of the screen, and the header bar at the * Places the main dialog in the center of the screen, and the header bar at the
* top. Only used for the new wallpaper picker. * top.
* @private * @private
*/ */
WallpaperManager.prototype.placeWallpaperPicker_ = function() { WallpaperManager.prototype.placeWallpaperPicker_ = function() {
if (!this.useNewWallpaperPicker_)
return;
// Wallpaper preview must always be in full screen. Exit preview if the // Wallpaper preview must always be in full screen. Exit preview if the
// window is not in full screen for any reason (e.g. when device locks). // window is not in full screen for any reason (e.g. when device locks).
if (!chrome.app.window.current().isFullscreen() && this.isDuringPreview_()) if (!chrome.app.window.current().isFullscreen() && this.isDuringPreview_())
...@@ -438,39 +346,10 @@ WallpaperManager.prototype.placeWallpaperPicker_ = function() { ...@@ -438,39 +346,10 @@ WallpaperManager.prototype.placeWallpaperPicker_ = function() {
* @param {string} errroMessage The string to show in the error dialog. * @param {string} errroMessage The string to show in the error dialog.
*/ */
WallpaperManager.prototype.showError_ = function(errorMessage) { WallpaperManager.prototype.showError_ = function(errorMessage) {
if (this.useNewWallpaperPicker_) {
$('message-container').textContent = errorMessage; $('message-container').textContent = errorMessage;
centerElement( centerElement(
$('message-container'), this.document_.body.offsetWidth, null); $('message-container'), this.document_.body.offsetWidth, null);
$('message-container').style.visibility = 'visible'; $('message-container').style.visibility = 'visible';
return;
}
document.querySelector('.error-message').textContent = errorMessage;
$('error-container').hidden = false;
};
/**
* Sets manifest loaded from server. Called after manifest is successfully
* loaded.
* @param {object} manifest The parsed manifest file.
*/
WallpaperManager.prototype.onLoadManifestSuccess_ = function(manifest) {
this.manifest_ = manifest;
WallpaperUtil.saveToLocalStorage(Constants.AccessLocalManifestKey, manifest);
this.postDownloadDomInit_();
};
// Sets manifest to previously saved object if any and shows connection error.
// Called after manifest failed to load.
WallpaperManager.prototype.onLoadManifestFailed_ = function() {
var accessManifestKey = Constants.AccessLocalManifestKey;
var self = this;
Constants.WallpaperLocalStorage.get(accessManifestKey, function(items) {
self.manifest_ = items[accessManifestKey] ? items[accessManifestKey] : null;
self.showError_(str('connectionFailed'));
self.postDownloadDomInit_();
$('wallpaper-grid').classList.add('image-picker-offline');
});
}; };
/** /**
...@@ -521,7 +400,6 @@ WallpaperManager.prototype.preDownloadDomInit_ = function() { ...@@ -521,7 +400,6 @@ WallpaperManager.prototype.preDownloadDomInit_ = function() {
'resize', this.onResize_.bind(this)); 'resize', this.onResize_.bind(this));
this.document_.defaultView.addEventListener( this.document_.defaultView.addEventListener(
'keydown', this.onKeyDown_.bind(this)); 'keydown', this.onKeyDown_.bind(this));
if (this.useNewWallpaperPicker_) {
$('minimize-button').addEventListener('click', function() { $('minimize-button').addEventListener('click', function() {
chrome.app.window.current().minimize(); chrome.app.window.current().minimize();
}); });
...@@ -547,19 +425,6 @@ WallpaperManager.prototype.preDownloadDomInit_ = function() { ...@@ -547,19 +425,6 @@ WallpaperManager.prototype.preDownloadDomInit_ = function() {
}, 500); }, 500);
}; };
}()); }());
} else {
$('window-close-button').addEventListener('click', function() {
window.close();
});
$('learn-more').href = LearnMoreURL;
$('close-error').addEventListener('click', function() {
$('error-container').hidden = true;
});
$('close-wallpaper-selection').addEventListener('click', function() {
$('wallpaper-selection-container').hidden = true;
$('set-wallpaper-layout').disabled = true;
});
}
}; };
/** /**
...@@ -572,11 +437,6 @@ WallpaperManager.prototype.postDownloadDomInit_ = function() { ...@@ -572,11 +437,6 @@ WallpaperManager.prototype.postDownloadDomInit_ = function() {
this.initThumbnailsGrid_(); this.initThumbnailsGrid_();
this.presetCategory_(); this.presetCategory_();
$('file-selector')
.addEventListener('change', this.onFileSelectorChanged_.bind(this));
$('set-wallpaper-layout')
.addEventListener('change', this.onWallpaperLayoutChanged_.bind(this));
// Always prefer the value from local filesystem to avoid the time window // Always prefer the value from local filesystem to avoid the time window
// of setting the third party app name and the third party wallpaper. // of setting the third party app name and the third party wallpaper.
var getThirdPartyAppName = function(callback) { var getThirdPartyAppName = function(callback) {
...@@ -602,91 +462,22 @@ WallpaperManager.prototype.postDownloadDomInit_ = function() { ...@@ -602,91 +462,22 @@ WallpaperManager.prototype.postDownloadDomInit_ = function() {
this.initializeDailyRefreshStates_(); this.initializeDailyRefreshStates_();
if (this.enableOnlineWallpaper_ && !this.useNewWallpaperPicker_) {
this.document_.body.setAttribute('surprise-me-disabled', '');
$('surprise-me').hidden = false;
$('surprise-me')
.addEventListener('click', this.toggleSurpriseMe.bind(this));
WallpaperUtil.enabledSyncThemesCallback(syncEnabled => {
// Surprise me has been moved from local to sync storage, prefer
// values from sync, but if unset check local and update synced pref
// if applicable.
if (syncEnabled) {
Constants.WallpaperSyncStorage.get(
Constants.AccessSyncSurpriseMeEnabledKey, items => {
if (items.hasOwnProperty(
Constants.AccessSyncSurpriseMeEnabledKey)) {
if (items[Constants.AccessSyncSurpriseMeEnabledKey])
this.onSurpriseMeStateChanged_(true /*enabled=*/);
} else {
Constants.WallpaperLocalStorage.get(
Constants.AccessLocalSurpriseMeEnabledKey, items => {
if (items.hasOwnProperty(
Constants.AccessLocalSurpriseMeEnabledKey)) {
WallpaperUtil.saveToSyncStorage(
Constants.AccessSyncSurpriseMeEnabledKey,
items[Constants.AccessLocalSurpriseMeEnabledKey]);
if (items[Constants.AccessLocalSurpriseMeEnabledKey])
this.onSurpriseMeStateChanged_(true /*enabled=*/);
}
});
}
});
} else {
Constants.WallpaperLocalStorage.get(
Constants.AccessLocalSurpriseMeEnabledKey, items => {
if (items.hasOwnProperty(
Constants.AccessLocalSurpriseMeEnabledKey)) {
if (items[Constants.AccessLocalSurpriseMeEnabledKey])
this.onSurpriseMeStateChanged_(true /*enabled=*/);
}
});
}
});
}
if (this.enableOnlineWallpaper_) {
window.addEventListener('offline', () => { window.addEventListener('offline', () => {
$('wallpaper-grid').classList.add('image-picker-offline'); $('wallpaper-grid').classList.add('image-picker-offline');
if (this.useNewWallpaperPicker_) {
this.showError_(str('connectionFailed')); this.showError_(str('connectionFailed'));
$('wallpaper-grid').highlightOfflineWallpapers(); $('wallpaper-grid').highlightOfflineWallpapers();
return;
}
chrome.wallpaperPrivate.getOfflineWallpaperList(lists => {
if (!this.downloadedListMap_)
this.downloadedListMap_ = {};
for (var i = 0; i < lists.length; i++) {
this.downloadedListMap_[lists[i]] = true;
}
var thumbnails = this.document_.querySelectorAll('.thumbnail');
for (var i = 0; i < thumbnails.length; i++) {
var thumbnail = thumbnails[i];
var url = this.wallpaperGrid_.dataModel.item(i).baseURL;
var fileName = getBaseName(url) + str('highResolutionSuffix');
if (this.downloadedListMap_ &&
this.downloadedListMap_.hasOwnProperty(encodeURI(fileName))) {
thumbnail.offline = true;
}
}
});
}); });
window.addEventListener('online', () => { window.addEventListener('online', () => {
if (this.useNewWallpaperPicker_) {
// 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_();
...@@ -768,7 +559,6 @@ WallpaperManager.prototype.presetCategory_ = function() { ...@@ -768,7 +559,6 @@ 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');
if (this.useNewWallpaperPicker_) {
// 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(([
...@@ -786,51 +576,6 @@ WallpaperManager.prototype.presetCategory_ = function() { ...@@ -786,51 +576,6 @@ WallpaperManager.prototype.presetCategory_ = function() {
} }
}); });
this.categoriesList_.selectionModel.selectedIndex = categoryIndex; this.categoriesList_.selectionModel.selectedIndex = categoryIndex;
return;
}
if (!this.enableOnlineWallpaper_ ||
(this.currentWallpaper_ &&
this.currentWallpaper_.indexOf(str('highResolutionSuffix')) == -1)) {
// Custom is the last one in the categories list.
this.categoriesList_.selectionModel.selectedIndex =
this.categoriesList_.dataModel.length - 1;
return;
}
var self = this;
var presetCategoryInner = function() {
// Selects the first category in the categories list of current
// wallpaper as the default selected category when showing wallpaper
// picker UI.
var presetCategory = AllCategoryIndex;
if (self.currentWallpaper_) {
for (var key in self.manifest_.wallpaper_list) {
var url = self.manifest_.wallpaper_list[key].base_url +
str('highResolutionSuffix');
if (url.indexOf(self.currentWallpaper_) != -1 &&
self.manifest_.wallpaper_list[key].categories.length > 0) {
presetCategory = self.manifest_.wallpaper_list[key].categories[0] +
OnlineCategoriesOffset;
break;
}
}
}
self.categoriesList_.selectionModel.selectedIndex = presetCategory;
};
if (navigator.onLine) {
presetCategoryInner();
} else {
// If device is offline, gets the available offline wallpaper list first.
// Wallpapers which are not in the list will display a grayscaled
// thumbnail.
chrome.wallpaperPrivate.getOfflineWallpaperList(function(lists) {
if (!self.downloadedListMap_)
self.downloadedListMap_ = {};
for (var i = 0; i < lists.length; i++)
self.downloadedListMap_[lists[i]] = true;
presetCategoryInner();
});
}
}; };
/** /**
...@@ -839,10 +584,6 @@ WallpaperManager.prototype.presetCategory_ = function() { ...@@ -839,10 +584,6 @@ WallpaperManager.prototype.presetCategory_ = function() {
* @private * @private
*/ */
WallpaperManager.prototype.decorateCurrentWallpaperInfoBar_ = function() { WallpaperManager.prototype.decorateCurrentWallpaperInfoBar_ = function() {
// The info bar only exists in new wallpaper picker.
if (!this.useNewWallpaperPicker_)
return;
var decorateCurrentWallpaperInfoBarImpl = var decorateCurrentWallpaperInfoBarImpl =
currentWallpaperInfo => { currentWallpaperInfo => {
// Initialize the "more options" buttons. // Initialize the "more options" buttons.
...@@ -1009,8 +750,6 @@ WallpaperManager.prototype.initThumbnailsGrid_ = function() { ...@@ -1009,8 +750,6 @@ WallpaperManager.prototype.initThumbnailsGrid_ = function() {
wallpapers.WallpaperThumbnailsGrid.decorate(this.wallpaperGrid_); wallpapers.WallpaperThumbnailsGrid.decorate(this.wallpaperGrid_);
this.wallpaperGrid_.addEventListener('change', this.onChange_.bind(this)); this.wallpaperGrid_.addEventListener('change', this.onChange_.bind(this));
if (!this.useNewWallpaperPicker_)
this.wallpaperGrid_.addEventListener('dblclick', this.onClose_.bind(this));
}; };
/** /**
...@@ -1061,7 +800,6 @@ WallpaperManager.prototype.onWallpaperChanged_ = function( ...@@ -1061,7 +800,6 @@ WallpaperManager.prototype.onWallpaperChanged_ = function(
$('wallpaper-set-by-message').textContent = ''; $('wallpaper-set-by-message').textContent = '';
$('wallpaper-grid').classList.remove('small'); $('wallpaper-grid').classList.remove('small');
if (this.useNewWallpaperPicker_)
this.wallpaperGrid_.checkmark.focus(); this.wallpaperGrid_.checkmark.focus();
// Disables daily refresh if user selects a non-daily wallpaper. // Disables daily refresh if user selects a non-daily wallpaper.
...@@ -1141,20 +879,17 @@ WallpaperManager.prototype.setSelectedCustomWallpaper_ = function( ...@@ -1141,20 +879,17 @@ WallpaperManager.prototype.setSelectedCustomWallpaper_ = function(
selectedItem.baseURL, this.getSelectedLayout_(), imageData, selectedItem.baseURL, this.getSelectedLayout_(), imageData,
optThumbnailData, this.onFileSystemError_.bind(this)); optThumbnailData, this.onFileSystemError_.bind(this));
}; };
if (this.useNewWallpaperPicker_) this.setCustomWallpaperImpl_(selectedItem, successCallback);
this.setCustomWallpaperSelectedOnNewPicker_(selectedItem, successCallback);
else
this.setCustomWallpaperSelectedOnOldPicker_(selectedItem, successCallback);
}; };
/** /**
* Implementation of |setSelectedCustomWallpaper_| for the new wallpaper picker. * Implementation of |setSelectedCustomWallpaper_|.
* @param {Object} selectedItem The selected item in WallpaperThumbnailsGrid's * @param {Object} selectedItem The selected item in WallpaperThumbnailsGrid's
* data model. * data model.
* @param {function} successCallback The success callback. * @param {function} successCallback The success callback.
* @private * @private
*/ */
WallpaperManager.prototype.setCustomWallpaperSelectedOnNewPicker_ = function( WallpaperManager.prototype.setCustomWallpaperImpl_ = function(
selectedItem, successCallback) { selectedItem, successCallback) {
// Read the image data from |filePath| and set the wallpaper with the data. // Read the image data from |filePath| and set the wallpaper with the data.
chrome.wallpaperPrivate.getLocalImageData( chrome.wallpaperPrivate.getLocalImageData(
...@@ -1215,39 +950,6 @@ WallpaperManager.prototype.setCustomWallpaperSelectedOnNewPicker_ = function( ...@@ -1215,39 +950,6 @@ WallpaperManager.prototype.setCustomWallpaperSelectedOnNewPicker_ = function(
}); });
}; };
/**
* TODO(crbug.com/787134): Delete the method after the old picker is deprecated.
*
* Implementation of |setSelectedCustomWallpaper_| for the old wallpaper picker.
* @param {Object} selectedItem The selected item in WallpaperThumbnailsGrid's
* data model.
* @param {function} successCallback The success callback.
* @private
*/
WallpaperManager.prototype.setCustomWallpaperSelectedOnOldPicker_ = function(
selectedItem, successCallback) {
var errorHandler = this.onFileSystemError_.bind(this);
var success = dirEntry => {
dirEntry.getFile(selectedItem.baseURL, {create: false}, fileEntry => {
fileEntry.file(file => {
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.addEventListener('error', errorHandler);
reader.addEventListener('load', e => {
// The thumbnail already exists at this point. There's no need to
// regenerate it.
this.setCustomWallpaperSelectedOnOldPickerImpl_(
e.target.result, selectedItem.layout,
false /*generateThumbnail=*/, selectedItem.baseURL,
successCallback.bind(null, e.target.result), errorHandler);
});
}, errorHandler);
}, errorHandler);
};
this.wallpaperDirs_.getDirectory(
Constants.WallpaperDirNameEnum.ORIGINAL, success, errorHandler);
};
/** /**
* Implementation of |setSelectedWallpaper_| for online wallpapers. * Implementation of |setSelectedWallpaper_| for online wallpapers.
* @param {Object} selectedItem The selected item in WallpaperThumbnailsGrid's * @param {Object} selectedItem The selected item in WallpaperThumbnailsGrid's
...@@ -1555,9 +1257,7 @@ WallpaperManager.prototype.onSelectedItemChanged_ = function() { ...@@ -1555,9 +1257,7 @@ WallpaperManager.prototype.onSelectedItemChanged_ = function() {
return; return;
this.setWallpaperAttribution(this.selectedItem_); this.setWallpaperAttribution(this.selectedItem_);
if (this.selectedItem_.baseURL && if (this.selectedItem_.baseURL) {
(this.useNewWallpaperPicker_ ||
!this.wallpaperGrid_.inProgramSelection)) {
if (this.selectedItem_.source == Constants.WallpaperSourceEnum.Custom) { if (this.selectedItem_.source == Constants.WallpaperSourceEnum.Custom) {
var items = {}; var items = {};
var key = this.selectedItem_.baseURL; var key = this.selectedItem_.baseURL;
...@@ -1580,7 +1280,6 @@ WallpaperManager.prototype.onSelectedItemChanged_ = function() { ...@@ -1580,7 +1280,6 @@ WallpaperManager.prototype.onSelectedItemChanged_ = function() {
* data model. * data model.
*/ */
WallpaperManager.prototype.setWallpaperAttribution = function(selectedItem) { WallpaperManager.prototype.setWallpaperAttribution = function(selectedItem) {
if (this.useNewWallpaperPicker_) {
$('image-title').textContent = ''; $('image-title').textContent = '';
$('wallpaper-description').textContent = ''; $('wallpaper-description').textContent = '';
if (selectedItem) { if (selectedItem) {
...@@ -1598,29 +1297,6 @@ WallpaperManager.prototype.setWallpaperAttribution = function(selectedItem) { ...@@ -1598,29 +1297,6 @@ WallpaperManager.prototype.setWallpaperAttribution = function(selectedItem) {
$('wallpaper-description').textContent = selectedItem.collectionName; $('wallpaper-description').textContent = selectedItem.collectionName;
} }
} }
return;
}
// Only online wallpapers have author and website attributes. All other type
// of wallpapers should not show attributions.
if (!selectedItem ||
selectedItem.source != Constants.WallpaperSourceEnum.Online) {
$('wallpaper-attribute').hidden = true;
$('attribute-image').hidden = true;
$('author-name').textContent = '';
$('author-website').textContent = $('author-website').href = '';
$('attribute-image').src = '';
return;
}
$('author-name').textContent = selectedItem.author;
$('author-website').textContent = $('author-website').href =
selectedItem.authorWebsite;
var img = $('attribute-image');
WallpaperUtil.displayThumbnail(
img, selectedItem.baseURL, selectedItem.source);
img.hidden = false;
$('wallpaper-attribute').hidden = false;
}; };
/** /**
...@@ -1663,71 +1339,14 @@ WallpaperManager.prototype.initCategoriesList_ = function() { ...@@ -1663,71 +1339,14 @@ WallpaperManager.prototype.initCategoriesList_ = function() {
this.categoriesList_.selectionModel.addEventListener( this.categoriesList_.selectionModel.addEventListener(
'change', this.onCategoriesChange_.bind(this)); 'change', this.onCategoriesChange_.bind(this));
if (this.useNewWallpaperPicker_) {
if (this.collectionsInfo_) { if (this.collectionsInfo_) {
for (var colletionInfo of this.collectionsInfo_) for (var colletionInfo of this.collectionsInfo_)
this.categoriesList_.dataModel.push(colletionInfo['collectionName']); this.categoriesList_.dataModel.push(colletionInfo['collectionName']);
} }
} else if (this.enableOnlineWallpaper_ && this.manifest_) {
// Adds all category as first category.
this.categoriesList_.dataModel.push(str('allCategoryLabel'));
for (var key in this.manifest_.categories) {
this.categoriesList_.dataModel.push(this.manifest_.categories[key]);
}
}
// Adds custom category as last category. // Adds custom category as last category.
this.categoriesList_.dataModel.push(str('customCategoryLabel')); this.categoriesList_.dataModel.push(str('customCategoryLabel'));
}; };
/**
* Handles the custom wallpaper which user selected from file manager. Called
* when users select a file.
*/
WallpaperManager.prototype.onFileSelectorChanged_ = function() {
var files = $('file-selector').files;
if (files.length != 1)
console.error('More than one files are selected or no file selected');
if (!files[0].type.match('image/jpeg') && !files[0].type.match('image/png')) {
this.showError_(str('invalidWallpaper'));
return;
}
var layout = this.getSelectedLayout_();
var self = this;
var errorHandler = this.onFileSystemError_.bind(this);
var setSelectedFile = function(file, layout, fileName) {
var success = function(dirEntry) {
dirEntry.getFile(fileName, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.addEventListener('writeend', function(e) {
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.addEventListener('error', errorHandler);
reader.addEventListener('load', function(e) {
self.setCustomWallpaperSelectedOnOldPickerImpl_(
e.target.result, layout, true /*generateThumbnail=*/,
fileName,
function(thumbnail) {
self.saveCustomWallpaperToSyncFS_(
fileName, layout, e.target.result, thumbnail,
errorHandler);
},
function() {
self.removeCustomWallpaper(fileName);
errorHandler();
});
});
});
fileWriter.addEventListener('error', errorHandler);
fileWriter.write(file);
}, errorHandler);
}, errorHandler);
};
self.wallpaperDirs_.getDirectory(
Constants.WallpaperDirNameEnum.ORIGINAL, success, errorHandler);
};
setSelectedFile(files[0], layout, new Date().getTime().toString());
};
/** /**
* Removes wallpaper and thumbnail with fileName from FileSystem. * Removes wallpaper and thumbnail with fileName from FileSystem.
* @param {string} fileName The file name of wallpaper and thumbnail to be * @param {string} fileName The file name of wallpaper and thumbnail to be
...@@ -1756,46 +1375,6 @@ WallpaperManager.prototype.removeCustomWallpaper = function(fileName) { ...@@ -1756,46 +1375,6 @@ WallpaperManager.prototype.removeCustomWallpaper = function(fileName) {
removeFile(fileName); removeFile(fileName);
}; };
/**
* TODO(crbug.com/787134): Delete the method after the old picker is deprecated.
*
* Implementation of |setCustomWallpaperSelectedOnOldPicker_|.
* @param {ArrayBuffer} wallpaper The binary representation of wallpaper.
* @param {string} layout The user selected wallpaper layout.
* @param {boolean} generateThumbnail True if need to generate thumbnail.
* @param {string} fileName The unique file name of wallpaper.
* @param {function(thumbnail):void} success Success callback. If
* generateThumbnail is true, the callback parameter should have the
* generated thumbnail.
* @param {function(e):void} failure Failure callback. Called when there is an
* error from FileSystem.
* @private
*/
WallpaperManager.prototype.setCustomWallpaperSelectedOnOldPickerImpl_ =
function(wallpaper, layout, generateThumbnail, fileName, success, failure) {
var onFinished = opt_thumbnail => {
if (chrome.runtime.lastError != undefined &&
chrome.runtime.lastError.message != str('canceledWallpaper')) {
this.showError_(chrome.runtime.lastError.message);
$('set-wallpaper-layout').disabled = true;
failure();
} else {
success(opt_thumbnail);
}
};
chrome.wallpaperPrivate.setCustomWallpaper(
wallpaper, layout, generateThumbnail, fileName, false /*previewMode=*/,
onFinished);
};
/**
* Handles the layout setting change of custom wallpaper.
*/
WallpaperManager.prototype.onWallpaperLayoutChanged_ = function() {
this.setCustomWallpaperLayout_(this.getSelectedLayout_());
};
/** /**
* Saves the custom wallpaper and thumbnail (if any) to the sync file system. * Saves the custom wallpaper and thumbnail (if any) to the sync file system.
* @param {string} fileName The file name of the wallpaper. * @param {string} fileName The file name of the wallpaper.
...@@ -1851,25 +1430,15 @@ WallpaperManager.prototype.setCustomWallpaperLayout_ = function(newLayout) { ...@@ -1851,25 +1430,15 @@ WallpaperManager.prototype.setCustomWallpaperLayout_ = function(newLayout) {
chrome.wallpaperPrivate.setCustomWallpaperLayout(layout, () => { chrome.wallpaperPrivate.setCustomWallpaperLayout(layout, () => {
if (chrome.runtime.lastError != undefined && if (chrome.runtime.lastError != undefined &&
chrome.runtime.lastError.message != str('canceledWallpaper')) { chrome.runtime.lastError.message != str('canceledWallpaper')) {
if (!this.useNewWallpaperPicker_) { return;
this.showError_(chrome.runtime.lastError.message);
this.removeCustomWallpaper(fileName);
$('set-wallpaper-layout').disabled = true;
}
} else {
WallpaperUtil.saveToLocalStorage(this.currentWallpaper_, layout);
if (this.useNewWallpaperPicker_) {
this.toggleLayoutButtonStates_(layout);
WallpaperUtil.saveWallpaperInfo(
this.currentWallpaper_, layout,
Constants.WallpaperSourceEnum.Custom, '');
} else {
this.onWallpaperChanged_(
this.wallpaperGrid_.activeItem, this.currentWallpaper_);
}
if (onSuccess)
onSuccess();
} }
WallpaperUtil.saveToLocalStorage(this.currentWallpaper_, layout);
this.toggleLayoutButtonStates_(layout);
WallpaperUtil.saveWallpaperInfo(
this.currentWallpaper_, layout, Constants.WallpaperSourceEnum.Custom,
'');
if (onSuccess)
onSuccess();
}); });
}; };
...@@ -1960,166 +1529,43 @@ WallpaperManager.prototype.onCategoriesChange_ = function() { ...@@ -1960,166 +1529,43 @@ WallpaperManager.prototype.onCategoriesChange_ = function() {
var wallpapersDataModel = new cr.ui.ArrayDataModel([]); var wallpapersDataModel = new cr.ui.ArrayDataModel([]);
var selectedItem = null; var selectedItem = null;
// Cancel any ongoing wallpaper request if user clicks on another category. // Cancel any ongoing wallpaper request if user clicks on another category.
if (this.useNewWallpaperPicker_ && this.wallpaperRequest_) { if (this.wallpaperRequest_) {
this.wallpaperRequest_.abort(); this.wallpaperRequest_.abort();
this.wallpaperRequest_ = null; this.wallpaperRequest_ = null;
} }
if (selectedListItem.custom) { if (selectedListItem.custom) {
if (this.useNewWallpaperPicker_) { chrome.wallpaperPrivate.getLocalImagePaths(localImagePaths => {
chrome.wallpaperPrivate.getLocalImagePaths(localImagePaths => { // Show a 'no images' message to user if there's no local image.
// Show a 'no images' message to user if there's no local image. this.updateNoImagesVisibility_(localImagePaths.length == 0);
this.updateNoImagesVisibility_(localImagePaths.length == 0); var wallpapersDataModel = new cr.ui.ArrayDataModel([]);
var wallpapersDataModel = new cr.ui.ArrayDataModel([]); for (var imagePath of localImagePaths) {
for (var imagePath of localImagePaths) {
var wallpaperInfo = {
// The absolute file path, used for retrieving the image data
// if user chooses to set this wallpaper.
filePath: imagePath,
// Used as the file name when saving the wallpaper to local and
// sync storage, which only happens after user chooses to set
// this wallpaper. The name 'baseURL' is for consistency with
// the old wallpaper picker.
// TODO(crbug.com/812085): Rename it to fileName after the new
// wallpaper picker is enabled by default.
baseURL: new Date().getTime().toString(),
layout: Constants.WallpaperThumbnailDefaultLayout,
source: Constants.WallpaperSourceEnum.Custom,
availableOffline: true,
collectionName: str('customCategoryLabel'),
// Use file name as aria-label.
ariaLabel: imagePath.split(/[/\\]/).pop(),
previewable: true
};
wallpapersDataModel.push(wallpaperInfo);
}
// Display the images.
this.wallpaperGrid_.dataModel = wallpapersDataModel;
});
return;
}
this.document_.body.setAttribute('custom', '');
var errorHandler = this.onFileSystemError_.bind(this);
var toArray = function(list) {
return Array.prototype.slice.call(list || [], 0);
};
var self = this;
var processResults = function(entries) {
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var wallpaperInfo = { var wallpaperInfo = {
// Set wallpaperId to null to avoid duplicate thumbnail images, // The absolute file path, used for retrieving the image data if user
// see crbug.com/506135 for details. // chooses to set this wallpaper.
wallpaperId: null, filePath: imagePath,
baseURL: entry.name, // Used as the file name when saving the wallpaper to local and sync
// The layout will be replaced by the actual value saved in // storage, which only happens after user chooses to set this
// local storage when requested later. Layout is not important // wallpaper. The name 'baseURL' is for consistency with the old
// for constructing thumbnails grid, we use the default here // wallpaper picker.
// to speed up the process of constructing. So we do not need to // TODO(crbug.com/812085): Rename it to fileName.
// wait for fetching correct layout. baseURL: new Date().getTime().toString(),
layout: Constants.WallpaperThumbnailDefaultLayout, layout: Constants.WallpaperThumbnailDefaultLayout,
source: Constants.WallpaperSourceEnum.Custom, source: Constants.WallpaperSourceEnum.Custom,
availableOffline: true availableOffline: true,
collectionName: str('customCategoryLabel'),
// Use file name as aria-label.
ariaLabel: imagePath.split(/[/\\]/).pop(),
previewable: true
}; };
wallpapersDataModel.push(wallpaperInfo); wallpapersDataModel.push(wallpaperInfo);
} }
if (loadTimeData.getBoolean('isOEMDefaultWallpaper')) { // Display the images.
var oemDefaultWallpaperElement = { this.wallpaperGrid_.dataModel = wallpapersDataModel;
wallpaperId: null, });
baseURL: 'OemDefaultWallpaper',
layout: Constants.WallpaperThumbnailDefaultLayout,
source: Constants.WallpaperSourceEnum.OEM,
availableOffline: true
};
wallpapersDataModel.push(oemDefaultWallpaperElement);
}
for (var i = 0; i < wallpapersDataModel.length; i++) {
// For custom wallpapers, the file name of |currentWallpaper_|
// includes the first directory level (corresponding to user id hash).
if (getBaseName(self.currentWallpaper_) ==
wallpapersDataModel.item(i).baseURL) {
selectedItem = wallpapersDataModel.item(i);
}
}
var lastElement = {
baseURL: '',
layout: '',
source: Constants.WallpaperSourceEnum.AddNew,
availableOffline: true
};
wallpapersDataModel.push(lastElement);
self.wallpaperGrid_.dataModel = wallpapersDataModel;
if (selectedItem) {
self.wallpaperGrid_.selectedItem = selectedItem;
self.wallpaperGrid_.activeItem = selectedItem;
}
};
var success = function(dirEntry) {
var dirReader = dirEntry.createReader();
var entries = [];
// All of a directory's entries are not guaranteed to return in a single
// call.
var readEntries = function() {
dirReader.readEntries(function(results) {
if (!results.length) {
processResults(entries.sort());
} else {
entries = entries.concat(toArray(results));
readEntries();
}
}, errorHandler);
};
readEntries(); // Start reading dirs.
};
this.wallpaperDirs_.getDirectory(
Constants.WallpaperDirNameEnum.ORIGINAL, success, errorHandler);
} else { } else {
this.document_.body.removeAttribute('custom'); this.document_.body.removeAttribute('custom');
if (this.collectionsInfo_)
if (this.useNewWallpaperPicker_ && this.collectionsInfo_) {
this.showCollection_(selectedIndex); this.showCollection_(selectedIndex);
return;
}
// Need this check for test purpose.
var numOnlineWallpaper = (this.enableOnlineWallpaper_ && this.manifest_) ?
this.manifest_.wallpaper_list.length :
0;
for (var i = 0; i < numOnlineWallpaper; i++) {
if (selectedIndex == AllCategoryIndex ||
this.manifest_.wallpaper_list[i].categories.indexOf(
selectedIndex - OnlineCategoriesOffset) != -1) {
var wallpaperInfo = {
wallpaperId: i,
baseURL: this.manifest_.wallpaper_list[i].base_url,
highResolutionURL: this.manifest_.wallpaper_list[i].base_url +
str('highResolutionSuffix'),
layout: this.manifest_.wallpaper_list[i].default_layout,
source: Constants.WallpaperSourceEnum.Online,
availableOffline: false,
author: this.manifest_.wallpaper_list[i].author,
authorWebsite: this.manifest_.wallpaper_list[i].author_website,
dynamicURL: this.manifest_.wallpaper_list[i].dynamic_url
};
var fileName =
getBaseName(wallpaperInfo.baseURL) + str('highResolutionSuffix');
if (this.downloadedListMap_ &&
this.downloadedListMap_.hasOwnProperty(encodeURI(fileName))) {
wallpaperInfo.availableOffline = true;
}
wallpapersDataModel.push(wallpaperInfo);
if (wallpaperInfo.highResolutionURL == this.currentWallpaper_) {
selectedItem = wallpaperInfo;
}
}
}
this.wallpaperGrid_.dataModel = wallpapersDataModel;
if (selectedItem) {
this.wallpaperGrid_.selectedItem = selectedItem;
this.wallpaperGrid_.activeItem = selectedItem;
}
} }
}; };
...@@ -2152,9 +1598,8 @@ WallpaperManager.prototype.updateSpinnerVisibility_ = function(visible) { ...@@ -2152,9 +1598,8 @@ WallpaperManager.prototype.updateSpinnerVisibility_ = function(visible) {
* @private * @private
*/ */
WallpaperManager.prototype.shouldPreviewWallpaper_ = function() { WallpaperManager.prototype.shouldPreviewWallpaper_ = function() {
return this.useNewWallpaperPicker_ && return chrome.app.window.current().isFullscreen() ||
(chrome.app.window.current().isFullscreen() || chrome.app.window.current().isMaximized();
chrome.app.window.current().isMaximized());
}; };
/** /**
...@@ -2181,13 +1626,9 @@ WallpaperManager.prototype.onScrollPositionChanged = function(scrollTop) { ...@@ -2181,13 +1626,9 @@ WallpaperManager.prototype.onScrollPositionChanged = function(scrollTop) {
* @private * @private
*/ */
WallpaperManager.prototype.getSelectedLayout_ = function() { WallpaperManager.prototype.getSelectedLayout_ = function() {
if (this.useNewWallpaperPicker_) {
return this.currentlySelectedLayout_ ? return this.currentlySelectedLayout_ ?
this.currentlySelectedLayout_ : this.currentlySelectedLayout_ :
Constants.WallpaperThumbnailDefaultLayout; Constants.WallpaperThumbnailDefaultLayout;
}
var setWallpaperLayout = $('set-wallpaper-layout');
return setWallpaperLayout.options[setWallpaperLayout.selectedIndex].value;
}; };
/** /**
...@@ -2203,13 +1644,10 @@ WallpaperManager.prototype.toggleLayoutButtonStates_ = function(layout) { ...@@ -2203,13 +1644,10 @@ WallpaperManager.prototype.toggleLayoutButtonStates_ = function(layout) {
/** /**
* Fetches the info related to the daily refresh feature and updates the UI for * Fetches the info related to the daily refresh feature and updates the UI for
* the items. Only used by the new wallpaper picker. * the items.
* @private * @private
*/ */
WallpaperManager.prototype.initializeDailyRefreshStates_ = function() { WallpaperManager.prototype.initializeDailyRefreshStates_ = function() {
if (!this.useNewWallpaperPicker_)
return;
var initializeDailyRefreshStatesImpl = dailyRefreshInfo => { var initializeDailyRefreshStatesImpl = dailyRefreshInfo => {
if (dailyRefreshInfo) { if (dailyRefreshInfo) {
this.dailyRefreshInfo_ = dailyRefreshInfo; this.dailyRefreshInfo_ = dailyRefreshInfo;
......
...@@ -5,7 +5,6 @@ ...@@ -5,7 +5,6 @@
var TestConstants = { var TestConstants = {
isPowerwashed: 0, isPowerwashed: 0,
isUsingNewWallpaperPicker: false,
wallpaperUrl: 'https://test.com/test.jpg', wallpaperUrl: 'https://test.com/test.jpg',
highResolutionSuffix: 'suffix', highResolutionSuffix: 'suffix',
// A dummy string which is used to mock an image. // A dummy string which is used to mock an image.
...@@ -269,7 +268,6 @@ var chrome = { ...@@ -269,7 +268,6 @@ var chrome = {
wallpaperPrivate: { wallpaperPrivate: {
getStrings: function(callback) { getStrings: function(callback) {
callback({ callback({
useNewWallpaperPicker: TestConstants.isUsingNewWallpaperPicker,
highResolutionSuffix: TestConstants.highResolutionSuffix highResolutionSuffix: TestConstants.highResolutionSuffix
}); });
}, },
...@@ -292,12 +290,7 @@ var chrome = { ...@@ -292,12 +290,7 @@ var chrome = {
{imageUrl: TestConstants.wallpaperUrl}, null /*nextResumeToken=*/); {imageUrl: TestConstants.wallpaperUrl}, null /*nextResumeToken=*/);
} }
}, },
runtime: {lastError: null}, runtime: {lastError: null}
commandLinePrivate: {
hasSwitch: function(arg, callback) {
callback(TestConstants.isUsingNewWallpaperPicker);
}
}
}; };
(function (exports) { (function (exports) {
......
...@@ -123,12 +123,11 @@ function testSyncOnlineWallpaper() { ...@@ -123,12 +123,11 @@ function testSyncOnlineWallpaper() {
// Test the surprise wallpaper's UMA stats is recorded correctly. // Test the surprise wallpaper's UMA stats is recorded correctly.
function testSurpriseWallpaper() { function testSurpriseWallpaper() {
TestConstants.isUsingNewWallpaperPicker = false;
var mockSetWallpaperIfExists = mockController.createFunctionMock( var mockSetWallpaperIfExists = mockController.createFunctionMock(
chrome.wallpaperPrivate, 'setWallpaperIfExists'); chrome.wallpaperPrivate, 'setWallpaperIfExists');
mockSetWallpaperIfExists.addExpectation( mockSetWallpaperIfExists.addExpectation(
TestConstants.wallpaperUrl + TestConstants.highResolutionSuffix, 'dummy', TestConstants.wallpaperUrl + TestConstants.highResolutionSuffix,
false /*previewMode=*/); 'CENTER_CROPPED', false /*previewMode=*/);
mockSetWallpaperIfExists.callbackData = [true]; mockSetWallpaperIfExists.callbackData = [true];
var mockRecordWallpaperUMA = mockController.createFunctionMock( var mockRecordWallpaperUMA = mockController.createFunctionMock(
...@@ -137,15 +136,4 @@ function testSurpriseWallpaper() { ...@@ -137,15 +136,4 @@ function testSurpriseWallpaper() {
var dateString = new Date().toDateString(); var dateString = new Date().toDateString();
SurpriseWallpaper.getInstance().setRandomWallpaper_(dateString); SurpriseWallpaper.getInstance().setRandomWallpaper_(dateString);
// Repeat the above process for the new wallpaper picker. Test that the UMA
// stats is also recorded correctly.
TestConstants.isUsingNewWallpaperPicker = true;
mockSetWallpaperIfExists.addExpectation(
TestConstants.wallpaperUrl + TestConstants.highResolutionSuffix,
'CENTER_CROPPED', false /*previewMode=*/);
mockRecordWallpaperUMA.addExpectation(Constants.WallpaperSourceEnum.Daily);
var dateString = new Date().toDateString();
SurpriseWallpaper.getInstance().setRandomWallpaper_(dateString);
} }
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