diff --git a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabUma.java b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabUma.java index 653d42a..58cbce3 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/tab/TabUma.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/tab/TabUma.java
@@ -160,10 +160,6 @@ recordLongTimesHistogram100("Tabs.StateTransfer.Time_Active_Inactive", delta); } else if (prevState == TAB_STATE_ACTIVE && newState == TAB_STATE_CLOSED) { recordLongTimesHistogram100("Tabs.StateTransfer.Time_Active_Closed", delta); - } else if (prevState == TAB_STATE_INACTIVE && newState == TAB_STATE_ACTIVE) { - recordLongTimesHistogram100("Tabs.StateTransfer.Time_Inactive_Active", delta); - } else if (prevState == TAB_STATE_INACTIVE && newState == TAB_STATE_CLOSED) { - recordLongTimesHistogram100("Tabs.StateTransfer.Time_Inactive_Close", delta); } if (prevState == TAB_STATE_INITIAL) {
diff --git a/chrome/browser/first_run/first_run_internal_win.cc b/chrome/browser/first_run/first_run_internal_win.cc index 1429c63f0..1da4593 100644 --- a/chrome/browser/first_run/first_run_internal_win.cc +++ b/chrome/browser/first_run/first_run_internal_win.cc
@@ -17,7 +17,8 @@ #include "base/process/kill.h" #include "base/process/launch.h" #include "base/process/process.h" -#include "base/threading/sequenced_worker_pool.h" +#include "base/task_scheduler/post_task.h" +#include "base/task_scheduler/task_traits.h" #include "base/time/time.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" @@ -107,15 +108,13 @@ void DoPostImportPlatformSpecificTasks(Profile* /* profile */) { // Trigger the Active Setup command for system-level Chromes to finish // configuring this user's install (e.g. per-user shortcuts). - // Delay the task slightly to give Chrome launch I/O priority while also - // making sure shortcuts are created promptly to avoid annoying the user by - // re-creating shortcuts they previously deleted. - static const int64_t kTiggerActiveSetupDelaySeconds = 5; if (!InstallUtil::IsPerUserInstall()) { - content::BrowserThread::GetBlockingPool()->PostDelayedTask( + content::BrowserThread::PostAfterStartupTask( FROM_HERE, - base::Bind(&InstallUtil::TriggerActiveSetupCommand), - base::TimeDelta::FromSeconds(kTiggerActiveSetupDelaySeconds)); + base::CreateTaskRunnerWithTraits( + {base::MayBlock(), base::TaskPriority::BACKGROUND, + base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}), + base::BindOnce(&InstallUtil::TriggerActiveSetupCommand)); } }
diff --git a/chrome/browser/net/predictor.cc b/chrome/browser/net/predictor.cc index 56681844..0f7a3d1 100644 --- a/chrome/browser/net/predictor.cc +++ b/chrome/browser/net/predictor.cc
@@ -252,7 +252,7 @@ UrlInfo::ResolutionMotivation motivation(UrlInfo::EARLY_LOAD_MOTIVATED); const int kConnectionsNeeded = 1; PreconnectUrl(canonicalized_url, first_party_for_cookies, motivation, - kConnectionsNeeded, kAllowCredentialsOnPreconnectByDefault); + kAllowCredentialsOnPreconnectByDefault, kConnectionsNeeded); PredictFrameSubresources(canonicalized_url.GetWithEmptyPath(), first_party_for_cookies); }
diff --git a/chrome/browser/resources/about_conflicts.js b/chrome/browser/resources/about_conflicts.js index e8eb92ea..08984983 100644 --- a/chrome/browser/resources/about_conflicts.js +++ b/chrome/browser/resources/about_conflicts.js
@@ -3,15 +3,14 @@ // found in the LICENSE file. /** -* This variable structure is here to document the structure that the template -* expects to correctly populate the page. -*/ + * This variable structure is here to document the structure that the template + * expects to correctly populate the page. + */ var moduleListDataFormat = { - 'moduleList': [ - { + 'moduleList': [{ 'type': 'The type of module found', 'type_description': - 'The type of module (string), defaults to blank for regular modules', + 'The type of module (string), defaults to blank for regular modules', 'status': 'The module status', 'location': 'The module path, not including filename', 'name': 'The name of the module', @@ -22,16 +21,15 @@ 'recommended_action': 'The help tips bitmask', 'possible_resolution': 'The help tips in string form', 'help_url': 'The link to the Help Center article' - } -] + }] }; /** -* Takes the |moduleListData| input argument which represents data about -* the currently available modules and populates the html jstemplate -* with that data. It expects an object structure like the above. -* @param {Object} moduleListData Information about available modules. -*/ + * Takes the |moduleListData| input argument which represents data about + * the currently available modules and populates the html jstemplate + * with that data. It expects an object structure like the above. + * @param {Object} moduleListData Information about available modules. + */ function renderTemplate(moduleListData) { // This is the javascript code that processes the template: var input = new JsEvalContext(moduleListData); @@ -40,19 +38,19 @@ } /** -* Asks the C++ ConflictsDOMHandler to get details about the available modules -* and return detailed data about the configuration. The ConflictsDOMHandler -* should reply to returnModuleList() (below). -*/ + * Asks the C++ ConflictsDOMHandler to get details about the available modules + * and return detailed data about the configuration. The ConflictsDOMHandler + * should reply to returnModuleList() (below). + */ function requestModuleListData() { chrome.send('requestModuleList'); } /** -* Called by the WebUI to re-populate the page with data representing the -* current state of installed modules. -* @param {Object} moduleListData Information about available modules. -*/ + * Called by the WebUI to re-populate the page with data representing the + * current state of installed modules. + * @param {Object} moduleListData Information about available modules. + */ function returnModuleList(moduleListData) { renderTemplate(moduleListData); $('loading-message').style.visibility = 'hidden';
diff --git a/chrome/browser/resources/about_flash.js b/chrome/browser/resources/about_flash.js index 9734542..5b213955 100644 --- a/chrome/browser/resources/about_flash.js +++ b/chrome/browser/resources/about_flash.js
@@ -3,11 +3,11 @@ // found in the LICENSE file. /** -* Takes the |moduleListData| input argument which represents data about -* the currently available modules and populates the html jstemplate -* with that data. It expects an object structure like the above. -* @param {Object} moduleListData Information about available modules -*/ + * Takes the |moduleListData| input argument which represents data about + * the currently available modules and populates the html jstemplate + * with that data. It expects an object structure like the above. + * @param {Object} moduleListData Information about available modules + */ function renderTemplate(moduleListData) { // This is the javascript code that processes the template: var input = new JsEvalContext(moduleListData); @@ -16,18 +16,18 @@ } /** -* Asks the C++ FlashUIDOMHandler to get details about the Flash and return -* the data in returnFlashInfo() (below). -*/ + * Asks the C++ FlashUIDOMHandler to get details about the Flash and return + * the data in returnFlashInfo() (below). + */ function requestFlashInfo() { chrome.send('requestFlashInfo'); } /** -* Called by the WebUI to re-populate the page with data representing the -* current state of Flash. -* @param {Object} moduleListData Information about available modules. -*/ + * Called by the WebUI to re-populate the page with data representing the + * current state of Flash. + * @param {Object} moduleListData Information about available modules. + */ function returnFlashInfo(moduleListData) { $('loading-message').style.visibility = 'hidden'; $('body-container').style.visibility = 'visible';
diff --git a/chrome/browser/resources/about_invalidations.js b/chrome/browser/resources/about_invalidations.js index 0aaf8379..46cbefed 100644 --- a/chrome/browser/resources/about_invalidations.js +++ b/chrome/browser/resources/about_invalidations.js
@@ -47,7 +47,7 @@ for (var i = 0; i < keys.length; i++) { sortedInvalidations.push(tableObjects[keys[i]]); } - var wrapped = { objectsidtable: sortedInvalidations }; + var wrapped = {objectsidtable: sortedInvalidations}; jstProcess(new JsEvalContext(wrapped), $('objectsid-table-div')); } @@ -59,11 +59,11 @@ */ function updateInvalidatorState(newState, lastChangedTime) { var logMessage = nowTimeString() + - 'Invalidations service state changed to ' + quote(newState); + 'Invalidations service state changed to ' + quote(newState); appendToLog(logMessage); - $('invalidations-state').textContent = newState + ' (since ' + - new Date(lastChangedTime) + ')'; + $('invalidations-state').textContent = + newState + ' (since ' + new Date(lastChangedTime) + ')'; } /** @@ -75,13 +75,10 @@ for (var i = 0; i < allInvalidations.length; i++) { var inv = allInvalidations[i]; if (inv.hasOwnProperty('objectId')) { - var logMessage = nowTimeString() + - 'Received Invalidation with type ' + - quote(inv.objectId.name) + - ' version ' + - quote((inv.isUnknownVersion ? 'Unknown' : inv.version)) + - ' with payload ' + - quote(inv.payload); + var logMessage = nowTimeString() + 'Received Invalidation with type ' + + quote(inv.objectId.name) + ' version ' + + quote((inv.isUnknownVersion ? 'Unknown' : inv.version)) + + ' with payload ' + quote(inv.payload); appendToLog(logMessage); var isInvalidation = true; @@ -106,8 +103,7 @@ var totalCount = oId.objectId.totalCount || 0; var key = source + '-' + name; var time = new Date(); - var version = oId.isUnknownVersion ? '?' : - oId.version; + var version = oId.isUnknownVersion ? '?' : oId.version; var payload = ''; if (oId.hasOwnProperty('payload')) payload = oId.payload; @@ -169,7 +165,7 @@ } // Reenable those ObjectsIds still registered with this registrar. for (var i = 0; i < allIds.length; i++) { - var oId = { objectId: allIds[i], registrar: registrar }; + var oId = {objectId: allIds[i], registrar: registrar}; var isInvalidation = false; logToTable(oId, isInvalidation); }
diff --git a/chrome/browser/resources/about_nacl.js b/chrome/browser/resources/about_nacl.js index 09519e1..7bbc87c 100644 --- a/chrome/browser/resources/about_nacl.js +++ b/chrome/browser/resources/about_nacl.js
@@ -5,38 +5,38 @@ var nacl = nacl || {}; (function() { - /** - * Takes the |moduleListData| input argument which represents data about - * the currently available modules and populates the html jstemplate - * with that data. It expects an object structure like the above. - * @param {Object} moduleListData Information about available modules - */ - function renderTemplate(moduleListData) { - // Process the template. - var input = new JsEvalContext(moduleListData); - var output = $('naclInfoTemplate'); - jstProcess(input, output); - } +/** + * Takes the |moduleListData| input argument which represents data about + * the currently available modules and populates the html jstemplate + * with that data. It expects an object structure like the above. + * @param {Object} moduleListData Information about available modules + */ +function renderTemplate(moduleListData) { + // Process the template. + var input = new JsEvalContext(moduleListData); + var output = $('naclInfoTemplate'); + jstProcess(input, output); +} - /** - * Asks the C++ NaClUIDOMHandler to get details about the NaCl and return - * the data in returnNaClInfo() (below). - */ - function requestNaClInfo() { - chrome.send('requestNaClInfo'); - } +/** + * Asks the C++ NaClUIDOMHandler to get details about the NaCl and return + * the data in returnNaClInfo() (below). + */ +function requestNaClInfo() { + chrome.send('requestNaClInfo'); +} - /** - * Called by the WebUI to re-populate the page with data representing the - * current state of NaCl. - * @param {Object} moduleListData Information about available modules - */ - nacl.returnNaClInfo = function(moduleListData) { - $('loading-message').hidden = 'hidden'; - $('body-container').hidden = ''; - renderTemplate(moduleListData); - }; +/** + * Called by the WebUI to re-populate the page with data representing the + * current state of NaCl. + * @param {Object} moduleListData Information about available modules + */ +nacl.returnNaClInfo = function(moduleListData) { + $('loading-message').hidden = 'hidden'; + $('body-container').hidden = ''; + renderTemplate(moduleListData); +}; - // Get data and have it displayed upon loading. - document.addEventListener('DOMContentLoaded', requestNaClInfo); +// Get data and have it displayed upon loading. +document.addEventListener('DOMContentLoaded', requestNaClInfo); })();
diff --git a/chrome/browser/resources/about_sys/about_sys.js b/chrome/browser/resources/about_sys/about_sys.js index f6d50fb..363a86a 100644 --- a/chrome/browser/resources/about_sys/about_sys.js +++ b/chrome/browser/resources/about_sys/about_sys.js
@@ -107,7 +107,7 @@ if (parseSystemLog(this.result)) { // Reset table title and status $('tableTitle').textContent = - loadTimeData.getStringF('logFileTableTitle', file.name); + loadTimeData.getStringF('logFileTableTitle', file.name); $('status').textContent = ''; } else { showError(file.name); @@ -135,7 +135,7 @@ var delimiter = lines[i].indexOf('='); if (delimiter <= 0) { if (i == lines.length - 1) - break; + break; // If '=' is missing here, format is wrong. return false; } @@ -151,8 +151,7 @@ // If these change, we should check for both the old and new versions. if (value == '<multiline>') { // Skip start delimiter. - if (i == len - 1 || - lines[++i].indexOf(DELIM_START) == -1) + if (i == len - 1 || lines[++i].indexOf(DELIM_START) == -1) return false; ++i;
diff --git a/chrome/browser/resources/about_voicesearch.js b/chrome/browser/resources/about_voicesearch.js index 7cf90a6a..bcf8cbd 100644 --- a/chrome/browser/resources/about_voicesearch.js +++ b/chrome/browser/resources/about_voicesearch.js
@@ -2,36 +2,36 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. - /** - * Takes the |moduleListData| input argument which represents data about - * the currently available modules and populates the html jstemplate - * with that data. It expects an object structure like the above. - * @param {Object} moduleListData Information about available modules - */ - function renderTemplate(moduleListData) { - var input = new JsEvalContext(moduleListData); - var output = $('voice-search-info-template'); - jstProcess(input, output); - } +/** + * Takes the |moduleListData| input argument which represents data about + * the currently available modules and populates the html jstemplate + * with that data. It expects an object structure like the above. + * @param {Object} moduleListData Information about available modules + */ +function renderTemplate(moduleListData) { + var input = new JsEvalContext(moduleListData); + var output = $('voice-search-info-template'); + jstProcess(input, output); +} - /** - * Asks the C++ VoiceSearchUIDOMHandler to get details about voice search and - * return the data in returnVoiceSearchInfo() (below). - */ - function requestVoiceSearchInfo() { - chrome.send('requestVoiceSearchInfo'); - } +/** + * Asks the C++ VoiceSearchUIDOMHandler to get details about voice search and + * return the data in returnVoiceSearchInfo() (below). + */ +function requestVoiceSearchInfo() { + chrome.send('requestVoiceSearchInfo'); +} - /** - * Called by the WebUI to re-populate the page with data representing the - * current state of voice search. - * @param {Object} moduleListData Information about available modules. - */ - function returnVoiceSearchInfo(moduleListData) { - $('loading-message').hidden = true; - $('body-container').hidden = false; - renderTemplate(moduleListData); - } +/** + * Called by the WebUI to re-populate the page with data representing the + * current state of voice search. + * @param {Object} moduleListData Information about available modules. + */ +function returnVoiceSearchInfo(moduleListData) { + $('loading-message').hidden = true; + $('body-container').hidden = false; + renderTemplate(moduleListData); +} - // Get data and have it displayed upon loading. - document.addEventListener('DOMContentLoaded', requestVoiceSearchInfo); +// Get data and have it displayed upon loading. +document.addEventListener('DOMContentLoaded', requestVoiceSearchInfo);
diff --git a/chrome/browser/resources/app_list/start_page.js b/chrome/browser/resources/app_list/start_page.js index 428e81bf..2a01e13 100644 --- a/chrome/browser/resources/app_list/start_page.js +++ b/chrome/browser/resources/app_list/start_page.js
@@ -114,5 +114,7 @@ }; }); -document.addEventListener('contextmenu', function(e) { e.preventDefault(); }); +document.addEventListener('contextmenu', function(e) { + e.preventDefault(); +}); document.addEventListener('DOMContentLoaded', appList.startPage.initialize);
diff --git a/chrome/browser/resources/bluetooth_internals/adapter_broker.js b/chrome/browser/resources/bluetooth_internals/adapter_broker.js index f6bff00..37c8fb82 100644 --- a/chrome/browser/resources/bluetooth_internals/adapter_broker.js +++ b/chrome/browser/resources/bluetooth_internals/adapter_broker.js
@@ -89,8 +89,7 @@ */ setClient: function(adapterClient) { adapterClient.binding = new interfaces.Bindings.Binding( - interfaces.BluetoothAdapter.AdapterClient, - adapterClient); + interfaces.BluetoothAdapter.AdapterClient, adapterClient); this.adapter_.setClient( adapterClient.binding.createInterfacePtrAndBind()); @@ -185,11 +184,8 @@ * @param {!interfaces.BluetoothDevice.DeviceInfo} deviceInfo */ deviceAdded: function(deviceInfo) { - var event = new CustomEvent('deviceadded', { - detail: { - deviceInfo: deviceInfo - } - }); + var event = + new CustomEvent('deviceadded', {detail: {deviceInfo: deviceInfo}}); this.adapterBroker_.dispatchEvent(event); }, @@ -198,11 +194,8 @@ * @param {!interfaces.BluetoothDevice.DeviceInfo} deviceInfo */ deviceChanged: function(deviceInfo) { - var event = new CustomEvent('devicechanged', { - detail: { - deviceInfo: deviceInfo - } - }); + var event = + new CustomEvent('devicechanged', {detail: {deviceInfo: deviceInfo}}); this.adapterBroker_.dispatchEvent(event); }, @@ -211,11 +204,8 @@ * @param {!interfaces.BluetoothDevice.DeviceInfo} deviceInfo */ deviceRemoved: function(deviceInfo) { - var event = new CustomEvent('deviceremoved', { - detail: { - deviceInfo: deviceInfo - } - }); + var event = + new CustomEvent('deviceremoved', {detail: {deviceInfo: deviceInfo}}); this.adapterBroker_.dispatchEvent(event); }, }; @@ -228,23 +218,27 @@ * rejects if Bluetooth is not supported. */ function getAdapterBroker() { - if (adapterBroker) return Promise.resolve(adapterBroker); + if (adapterBroker) + return Promise.resolve(adapterBroker); - return interfaces.setupInterfaces().then(function(adapter) { - var adapterFactory = new interfaces.BluetoothAdapter.AdapterFactoryPtr( - interfaces.FrameInterfaces.getInterface( - interfaces.BluetoothAdapter.AdapterFactory.name)); + return interfaces.setupInterfaces() + .then(function(adapter) { + var adapterFactory = + new interfaces.BluetoothAdapter.AdapterFactoryPtr( + interfaces.FrameInterfaces.getInterface( + interfaces.BluetoothAdapter.AdapterFactory.name)); - // Get an Adapter service. - return adapterFactory.getAdapter(); - }).then(function(response) { - if (!response.adapter.ptr.isBound()) { - throw new Error('Bluetooth Not Supported on this platform.'); - } + // Get an Adapter service. + return adapterFactory.getAdapter(); + }) + .then(function(response) { + if (!response.adapter.ptr.isBound()) { + throw new Error('Bluetooth Not Supported on this platform.'); + } - adapterBroker = new AdapterBroker(response.adapter); - return adapterBroker; - }); + adapterBroker = new AdapterBroker(response.adapter); + return adapterBroker; + }); } return {
diff --git a/chrome/browser/resources/bluetooth_internals/adapter_page.js b/chrome/browser/resources/bluetooth_internals/adapter_page.js index cf2ad13..98d296a 100644 --- a/chrome/browser/resources/bluetooth_internals/adapter_page.js +++ b/chrome/browser/resources/bluetooth_internals/adapter_page.js
@@ -10,13 +10,13 @@ /** @const */ var Page = cr.ui.pageManager.Page; var PROPERTY_NAMES = { - address: 'Address', - name: 'Name', - initialized: 'Initialized', - present: 'Present', - powered: 'Powered', - discoverable: 'Discoverable', - discovering: 'Discovering', + address: 'Address', + name: 'Name', + initialized: 'Initialized', + present: 'Present', + powered: 'Powered', + discoverable: 'Discoverable', + discovering: 'Discovering', }; /**
diff --git a/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js b/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js index e46d742c..6eedc5a8 100644 --- a/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js +++ b/chrome/browser/resources/bluetooth_internals/bluetooth_internals.js
@@ -93,7 +93,8 @@ function makeDeviceDetailsPage(deviceInfo) { var deviceDetailsPageId = 'devices/' + deviceInfo.address.toLowerCase(); var deviceDetailsPage = PageManager.registeredPages[deviceDetailsPageId]; - if (deviceDetailsPage) return deviceDetailsPage; + if (deviceDetailsPage) + return deviceDetailsPage; var pageSection = document.createElement('section'); pageSection.hidden = true; @@ -101,8 +102,8 @@ $('page-container').appendChild(pageSection); deviceDetailsPage = new DeviceDetailsPage(deviceDetailsPageId, deviceInfo); - deviceDetailsPage.pageDiv.addEventListener('connectionchanged', - function(event) { + deviceDetailsPage.pageDiv.addEventListener( + 'connectionchanged', function(event) { devices.updateConnectionStatus( event.detail.address, event.detail.status); }); @@ -111,8 +112,8 @@ devices.addOrUpdate(event.detail.info); }); - deviceDetailsPage.pageDiv.addEventListener('forgetpressed', - function(event) { + deviceDetailsPage.pageDiv.addEventListener( + 'forgetpressed', function(event) { PageManager.showPageByName(devicesPage.name); removeDeviceDetailsPage(event.detail.address); }); @@ -139,7 +140,8 @@ function updateDeviceDetailsPage(address) { var detailPageId = 'devices/' + address.toLowerCase(); var page = PageManager.registeredPages[detailPageId]; - if (page) page.redraw(); + if (page) + page.redraw(); } function updateStoppedDiscoverySession() { @@ -191,8 +193,8 @@ devicesPage.setDevices(devices); devicesPage.pageDiv.addEventListener('inspectpressed', function(event) { - var detailsPage = makeDeviceDetailsPage( - devices.getByAddress(event.detail.address)); + var detailsPage = + makeDeviceDetailsPage(devices.getByAddress(event.detail.address)); PageManager.showPageByName(detailsPage.name); }); @@ -214,8 +216,7 @@ } devicesPage.setScanStatus(devices_page.ScanStatus.ON); - Snackbar.show( - 'Failed to stop discovery session', SnackbarType.ERROR); + Snackbar.show('Failed to stop discovery session', SnackbarType.ERROR); userRequestedScanStop = false; }); @@ -223,26 +224,31 @@ } devicesPage.setScanStatus(devices_page.ScanStatus.STARTING); - adapterBroker.startDiscoverySession().then(function(session) { - discoverySession = session; + adapterBroker.startDiscoverySession() + .then(function(session) { + discoverySession = session; - discoverySession.ptr.setConnectionErrorHandler(function() { - updateStoppedDiscoverySession(); - Snackbar.show('Discovery session ended', SnackbarType.WARNING); - }); + discoverySession.ptr.setConnectionErrorHandler(function() { + updateStoppedDiscoverySession(); + Snackbar.show('Discovery session ended', SnackbarType.WARNING); + }); - devicesPage.setScanStatus(devices_page.ScanStatus.ON); - }).catch(function(error) { - devicesPage.setScanStatus(devices_page.ScanStatus.OFF); - Snackbar.show('Failed to start discovery session', SnackbarType.ERROR); - console.error(error); - }); + devicesPage.setScanStatus(devices_page.ScanStatus.ON); + }) + .catch(function(error) { + devicesPage.setScanStatus(devices_page.ScanStatus.OFF); + Snackbar.show( + 'Failed to start discovery session', SnackbarType.ERROR); + console.error(error); + }); }); } function setupPages() { sidebarObj = new window.sidebar.Sidebar($('sidebar')); - $('menu-btn').addEventListener('click', function() { sidebarObj.open(); }); + $('menu-btn').addEventListener('click', function() { + sidebarObj.open(); + }); PageManager.addObserver(sidebarObj); PageManager.addObserver(new PageObserver()); @@ -272,15 +278,21 @@ setupPages(); adapter_broker.getAdapterBroker() - .then(function(broker) { adapterBroker = broker; }) - .then(function() { return adapterBroker.getInfo(); }) - .then(setupAdapterSystem) - .then(function() { return adapterBroker.getDevices(); }) - .then(setupDeviceSystem) - .catch(function(error) { - Snackbar.show(error.message, SnackbarType.ERROR); - console.error(error); - }); + .then(function(broker) { + adapterBroker = broker; + }) + .then(function() { + return adapterBroker.getInfo(); + }) + .then(setupAdapterSystem) + .then(function() { + return adapterBroker.getDevices(); + }) + .then(setupDeviceSystem) + .catch(function(error) { + Snackbar.show(error.message, SnackbarType.ERROR); + console.error(error); + }); } return {
diff --git a/chrome/browser/resources/bluetooth_internals/characteristic_list.js b/chrome/browser/resources/bluetooth_internals/characteristic_list.js index 17f4ebab..71d93b8 100644 --- a/chrome/browser/resources/bluetooth_internals/characteristic_list.js +++ b/chrome/browser/resources/bluetooth_internals/characteristic_list.js
@@ -91,24 +91,24 @@ this.propertiesFieldSet_.setObject({ broadcast: (this.info.properties & Property.BROADCAST) > 0, read: (this.info.properties & Property.READ) > 0, - write_without_response: (this.info.properties & - Property.WRITE_WITHOUT_RESPONSE) > 0, + write_without_response: + (this.info.properties & Property.WRITE_WITHOUT_RESPONSE) > 0, write: (this.info.properties & Property.WRITE) > 0, notify: (this.info.properties & Property.NOTIFY) > 0, indicate: (this.info.properties & Property.INDICATE) > 0, - authenticated_signed_writes: (this.info.properties & - Property.AUTHENTICATED_SIGNED_WRITES) > 0, - extended_properties: (this.info.properties & - Property.EXTENDED_PROPERTIES) > 0, + authenticated_signed_writes: + (this.info.properties & Property.AUTHENTICATED_SIGNED_WRITES) > 0, + extended_properties: + (this.info.properties & Property.EXTENDED_PROPERTIES) > 0, reliable_write: (this.info.properties & Property.RELIABLE_WRITE) > 0, - writable_auxiliaries: (this.info.properties & - Property.WRITABLE_AUXILIARIES) > 0, - read_encrypted: (this.info.properties & Property.READ_ENCRYPTED) > 0, - write_encrypted: (this.info.properties & Property.WRITE_ENCRYPTED) > 0, - read_encrypted_authenticated: (this.info.properties & - Property.READ_ENCRYPTED_AUTHENTICATED) > 0, - write_encrypted_authenticated: (this.info.properties & - Property.WRITE_ENCRYPTED_AUTHENTICATED) > 0, + writable_auxiliaries: + (this.info.properties & Property.WRITABLE_AUXILIARIES) > 0, + read_encrypted: (this.info.properties & Property.READ_ENCRYPTED) > 0, + write_encrypted: (this.info.properties & Property.WRITE_ENCRYPTED) > 0, + read_encrypted_authenticated: + (this.info.properties & Property.READ_ENCRYPTED_AUTHENTICATED) > 0, + write_encrypted_authenticated: + (this.info.properties & Property.WRITE_ENCRYPTED_AUTHENTICATED) > 0, }); /** @private {!value_control.ValueControl} */ @@ -225,20 +225,23 @@ this.serviceId_ = serviceId; this.characteristicsRequested_ = true; - device_broker.connectToDevice(deviceAddress).then(function(device) { - return device.getCharacteristics(serviceId); - }.bind(this)).then(function(response) { - this.setData(new ArrayDataModel(response.characteristics || [])); - this.setSpinnerShowing(false); - this.characteristicsRequested_ = false; - }.bind(this)).catch(function(error) { - this.characteristicsRequested_ = false; - Snackbar.show( - deviceAddress + ': ' + error.message, SnackbarType.ERROR, 'Retry', - function() { - this.load(deviceAddress, serviceId); - }.bind(this)); - }.bind(this)); + device_broker.connectToDevice(deviceAddress) + .then(function(device) { + return device.getCharacteristics(serviceId); + }.bind(this)) + .then(function(response) { + this.setData(new ArrayDataModel(response.characteristics || [])); + this.setSpinnerShowing(false); + this.characteristicsRequested_ = false; + }.bind(this)) + .catch(function(error) { + this.characteristicsRequested_ = false; + Snackbar.show( + deviceAddress + ': ' + error.message, SnackbarType.ERROR, + 'Retry', function() { + this.load(deviceAddress, serviceId); + }.bind(this)); + }.bind(this)); }, };
diff --git a/chrome/browser/resources/bluetooth_internals/device_broker.js b/chrome/browser/resources/bluetooth_internals/device_broker.js index 6018133..5704e5a 100644 --- a/chrome/browser/resources/bluetooth_internals/device_broker.js +++ b/chrome/browser/resources/bluetooth_internals/device_broker.js
@@ -29,27 +29,27 @@ if (deviceOrPromise !== null) return Promise.resolve(deviceOrPromise); - var promise = adapter_broker.getAdapterBroker().then( - function(adapterBroker) { - return adapterBroker.connectToDevice(address); - }).then(function(device) { - connectedDevices.set(address, device); + var promise = adapter_broker.getAdapterBroker() + .then(function(adapterBroker) { + return adapterBroker.connectToDevice(address); + }) + .then(function(device) { + connectedDevices.set(address, device); - device.ptr.setConnectionErrorHandler(function() { - connectedDevices.delete(address); - }); + device.ptr.setConnectionErrorHandler(function() { + connectedDevices.delete(address); + }); - return device; - }).catch(function(error) { - connectedDevices.delete(address); - throw error; - }); + return device; + }) + .catch(function(error) { + connectedDevices.delete(address); + throw error; + }); connectedDevices.set(address, promise); return promise; } - return { - connectToDevice: connectToDevice - }; + return {connectToDevice: connectToDevice}; });
diff --git a/chrome/browser/resources/bluetooth_internals/device_collection.js b/chrome/browser/resources/bluetooth_internals/device_collection.js index 9fdc743..7245f26 100644 --- a/chrome/browser/resources/bluetooth_internals/device_collection.js +++ b/chrome/browser/resources/bluetooth_internals/device_collection.js
@@ -65,7 +65,7 @@ // on |deviceInfo|. The rssi property may be null, so it must be // re-assigned. Object.assign(oldDeviceInfo, deviceInfo); - oldDeviceInfo.rssi = { value: rssi }; + oldDeviceInfo.rssi = {value: rssi}; this.updateIndex(this.indexOf(oldDeviceInfo)); } else { deviceInfo.connectionStatus = ConnectionStatus.DISCONNECTED;
diff --git a/chrome/browser/resources/bluetooth_internals/device_details_page.js b/chrome/browser/resources/bluetooth_internals/device_details_page.js index 3077fb5..7a573910 100644 --- a/chrome/browser/resources/bluetooth_internals/device_details_page.js +++ b/chrome/browser/resources/bluetooth_internals/device_details_page.js
@@ -58,23 +58,21 @@ /** @private {?HTMLElement} */ this.connectBtn_ = null; - this.pageDiv.appendChild( - document.importNode($('device-details-template').content, - true /* deep */)); + this.pageDiv.appendChild(document.importNode( + $('device-details-template').content, true /* deep */)); - this.pageDiv.querySelector('.device-details').appendChild( - this.deviceFieldSet_); + this.pageDiv.querySelector('.device-details') + .appendChild(this.deviceFieldSet_); this.pageDiv.querySelector('.services').appendChild(this.serviceList_); - this.pageDiv.querySelector('.forget').addEventListener( - 'click', function() { - this.disconnect(); - this.pageDiv.dispatchEvent(new CustomEvent('forgetpressed', { - detail: { - address: this.deviceInfo.address, - }, - })); - }.bind(this)); + this.pageDiv.querySelector('.forget').addEventListener('click', function() { + this.disconnect(); + this.pageDiv.dispatchEvent(new CustomEvent('forgetpressed', { + detail: { + address: this.deviceInfo.address, + }, + })); + }.bind(this)); this.connectBtn_ = this.pageDiv.querySelector('.disconnect'); this.connectBtn_.addEventListener('click', function() { @@ -95,8 +93,8 @@ this.updateConnectionStatus_( device_collection.ConnectionStatus.CONNECTING); - device_broker.connectToDevice(this.deviceInfo.address).then( - function(devicePtr) { + device_broker.connectToDevice(this.deviceInfo.address) + .then(function(devicePtr) { this.devicePtr_ = devicePtr; this.updateConnectionStatus_( @@ -104,12 +102,14 @@ // Fetch services asynchronously. return this.devicePtr_.getServices(); - }.bind(this)).then(function(response) { + }.bind(this)) + .then(function(response) { this.deviceInfo.services = response.services; this.serviceList_.load(this.deviceInfo.address); this.redraw(); this.fireDeviceInfoChanged_(); - }.bind(this)).catch(function(error) { + }.bind(this)) + .catch(function(error) { // If a connection error occurs while fetching the services, the // devicePtr reference must be removed. if (this.devicePtr_) { @@ -128,7 +128,8 @@ /** Disconnects the page from the Bluetooth device. */ disconnect: function() { - if (!this.devicePtr_) return; + if (!this.devicePtr_) + return; this.devicePtr_.disconnect(); this.devicePtr_ = null;
diff --git a/chrome/browser/resources/bluetooth_internals/device_table.js b/chrome/browser/resources/bluetooth_internals/device_table.js index b177864f..0068e27 100644 --- a/chrome/browser/resources/bluetooth_internals/device_table.js +++ b/chrome/browser/resources/bluetooth_internals/device_table.js
@@ -27,8 +27,8 @@ /** @private {?Array<device_collection.Device>} */ this.devices_ = null; - return document.importNode($('table-template').content.children[0], - true /* deep */); + return document.importNode( + $('table-template').content.children[0], true /* deep */); }); DeviceTable.prototype = { @@ -140,7 +140,8 @@ for (var i = 0; i < this.headers_.length; i++) { // Skip the LINKS column. It has no data-field attribute. - if (i === COLUMNS.LINKS) continue; + if (i === COLUMNS.LINKS) + continue; row.insertCell(); } @@ -201,7 +202,8 @@ // Update the properties based on the header field path. for (var i = 0; i < this.headers_.length; i++) { // Skip the LINKS column. It has no data-field attribute. - if (i === COLUMNS.LINKS) continue; + if (i === COLUMNS.LINKS) + continue; var header = this.headers_[i]; var propName = header.dataset.field;
diff --git a/chrome/browser/resources/bluetooth_internals/expandable_list.js b/chrome/browser/resources/bluetooth_internals/expandable_list.js index 8f172561e..05309cf 100644 --- a/chrome/browser/resources/bluetooth_internals/expandable_list.js +++ b/chrome/browser/resources/bluetooth_internals/expandable_list.js
@@ -30,8 +30,7 @@ this.classList.add('expandable-list-item'); this.briefContent_ = document.createElement('div'); this.briefContent_.classList.add('brief-content'); - this.briefContent_.addEventListener( - 'click', this.onExpand_.bind(this)); + this.briefContent_.addEventListener('click', this.onExpand_.bind(this)); this.appendChild(this.briefContent_); this.expandedContent_ = document.createElement('div');
diff --git a/chrome/browser/resources/bluetooth_internals/interfaces.js b/chrome/browser/resources/bluetooth_internals/interfaces.js index 20eb2b8b..5bec864 100644 --- a/chrome/browser/resources/bluetooth_internals/interfaces.js +++ b/chrome/browser/resources/bluetooth_internals/interfaces.js
@@ -9,11 +9,13 @@ cr.define('interfaces', function() { /** - * Overriden by tests to give them a chance to setup a fake Mojo browser proxy - * before any other code executes. - * @return {!Promise} A promise firing once necessary setup has been completed. - */ - var setupFn = window.setupFn || function() { return Promise.resolve(); }; + * Overriden by tests to give them a chance to setup a fake Mojo browser proxy + * before any other code executes. + * @return {!Promise} A promise firing once necessary setup has been completed. + */ + var setupFn = window.setupFn || function() { + return Promise.resolve(); + }; /** * Sets up Mojo interfaces and adds them to window.interfaces. @@ -22,17 +24,18 @@ function setupInterfaces() { return setupFn().then(function() { return importModules([ - 'content/public/renderer/frame_interfaces', - 'device/bluetooth/public/interfaces/adapter.mojom', - 'device/bluetooth/public/interfaces/device.mojom', - 'mojo/public/js/bindings', - ]).then(function([frameInterfaces, bluetoothAdapter, bluetoothDevice, - bindings]) { - interfaces.BluetoothAdapter = bluetoothAdapter; - interfaces.BluetoothDevice = bluetoothDevice; - interfaces.Bindings = bindings; - interfaces.FrameInterfaces = frameInterfaces; - }); + 'content/public/renderer/frame_interfaces', + 'device/bluetooth/public/interfaces/adapter.mojom', + 'device/bluetooth/public/interfaces/device.mojom', + 'mojo/public/js/bindings', + ]) + .then(function( + [frameInterfaces, bluetoothAdapter, bluetoothDevice, bindings]) { + interfaces.BluetoothAdapter = bluetoothAdapter; + interfaces.BluetoothDevice = bluetoothDevice; + interfaces.Bindings = bindings; + interfaces.FrameInterfaces = frameInterfaces; + }); }); }
diff --git a/chrome/browser/resources/bluetooth_internals/service_list.js b/chrome/browser/resources/bluetooth_internals/service_list.js index 0512e54..60df110 100644 --- a/chrome/browser/resources/bluetooth_internals/service_list.js +++ b/chrome/browser/resources/bluetooth_internals/service_list.js
@@ -147,18 +147,22 @@ this.deviceAddress_ = deviceAddress; this.servicesRequested_ = true; - device_broker.connectToDevice(this.deviceAddress_).then( - function(device) { + device_broker.connectToDevice(this.deviceAddress_) + .then(function(device) { return device.getServices(); - }.bind(this)).then(function(response) { + }.bind(this)) + .then(function(response) { this.setData(new ArrayDataModel(response.services)); this.setSpinnerShowing(false); this.servicesRequested_ = false; - }.bind(this)).catch(function(error) { + }.bind(this)) + .catch(function(error) { this.servicesRequested_ = false; Snackbar.show( deviceAddress + ': ' + error.message, SnackbarType.ERROR, - 'Retry', function() { this.load(deviceAddress); }.bind(this)); + 'Retry', function() { + this.load(deviceAddress); + }.bind(this)); }.bind(this)); }, };
diff --git a/chrome/browser/resources/bluetooth_internals/sidebar.js b/chrome/browser/resources/bluetooth_internals/sidebar.js index 9071614..4fb3076 100644 --- a/chrome/browser/resources/bluetooth_internals/sidebar.js +++ b/chrome/browser/resources/bluetooth_internals/sidebar.js
@@ -35,8 +35,11 @@ this.overlayDiv_ = this.sidebarDiv_.querySelector('.overlay'); this.overlayDiv_.addEventListener('click', this.close.bind(this)); - window.matchMedia('screen and (max-width: 600px)').addListener( - function(query) { if (!query.matches) this.close(); }.bind(this)); + window.matchMedia('screen and (max-width: 600px)') + .addListener(function(query) { + if (!query.matches) + this.close(); + }.bind(this)); } Sidebar.prototype = { @@ -109,7 +112,5 @@ }, }; - return { - Sidebar: Sidebar - }; + return {Sidebar: Sidebar}; });
diff --git a/chrome/browser/resources/bluetooth_internals/snackbar.js b/chrome/browser/resources/bluetooth_internals/snackbar.js index 54db660f..c074ac8 100644 --- a/chrome/browser/resources/bluetooth_internals/snackbar.js +++ b/chrome/browser/resources/bluetooth_internals/snackbar.js
@@ -72,7 +72,8 @@ this.actionLink_.textContent = options.actionText || 'Dismiss'; this.actionLink_.addEventListener('click', function() { - if (options.action) options.action(); + if (options.action) + options.action(); this.dismiss(); }.bind(this)); }, @@ -82,8 +83,10 @@ */ show: function() { this.classList.add('open'); - if (Snackbar.hasContentFocus_) this.startTimeout_(); - else this.stopTimeout_(); + if (Snackbar.hasContentFocus_) + this.startTimeout_(); + else + this.stopTimeout_(); document.addEventListener('contentfocus', this.boundStartTimeout_); document.addEventListener('contentblur', this.boundStopTimeout_); @@ -224,8 +227,10 @@ * dismissing. */ Snackbar.dismiss = function(clearQueue) { - if (clearQueue) Snackbar.queue_ = []; - if (Snackbar.current_) return Snackbar.current_.dismiss(); + if (clearQueue) + Snackbar.queue_ = []; + if (Snackbar.current_) + return Snackbar.current_.dismiss(); return Promise.resolve(); };
diff --git a/chrome/browser/resources/bluetooth_internals/value_control.js b/chrome/browser/resources/bluetooth_internals/value_control.js index 9146e59..04b5a4aa 100644 --- a/chrome/browser/resources/bluetooth_internals/value_control.js +++ b/chrome/browser/resources/bluetooth_internals/value_control.js
@@ -341,29 +341,33 @@ readValue_: function() { this.readBtn_.disabled = true; - device_broker.connectToDevice(this.deviceAddress_).then(function(device) { - if (this.descriptorId_) { - return device.readValueForDescriptor( - this.serviceId_, this.characteristicId_, this.descriptorId_); - } + device_broker.connectToDevice(this.deviceAddress_) + .then(function(device) { + if (this.descriptorId_) { + return device.readValueForDescriptor( + this.serviceId_, this.characteristicId_, this.descriptorId_); + } - return device.readValueForCharacteristic( - this.serviceId_, this.characteristicId_); - }.bind(this)).then(function(response) { - this.readBtn_.disabled = false; + return device.readValueForCharacteristic( + this.serviceId_, this.characteristicId_); + }.bind(this)) + .then(function(response) { + this.readBtn_.disabled = false; - if (response.result === interfaces.BluetoothDevice.GattResult.SUCCESS) { - this.setValue(response.value); - Snackbar.show( - this.deviceAddress_ + ': Read succeeded', SnackbarType.SUCCESS); - return; - } + if (response.result === + interfaces.BluetoothDevice.GattResult.SUCCESS) { + this.setValue(response.value); + Snackbar.show( + this.deviceAddress_ + ': Read succeeded', + SnackbarType.SUCCESS); + return; + } - var errorString = this.getErrorString_(response.result); - Snackbar.show( - this.deviceAddress_ + ': ' + errorString, SnackbarType.ERROR, - 'Retry', this.readValue_.bind(this)); - }.bind(this)); + var errorString = this.getErrorString_(response.result); + Snackbar.show( + this.deviceAddress_ + ': ' + errorString, SnackbarType.ERROR, + 'Retry', this.readValue_.bind(this)); + }.bind(this)); }, /** @@ -376,29 +380,34 @@ writeValue_: function() { this.writeBtn_.disabled = true; - device_broker.connectToDevice(this.deviceAddress_).then(function(device) { - if (this.descriptorId_) { - return device.writeValueForDescriptor( - this.serviceId_, this.characteristicId_, this.descriptorId_, - this.value_.getArray()); - } + device_broker.connectToDevice(this.deviceAddress_) + .then(function(device) { + if (this.descriptorId_) { + return device.writeValueForDescriptor( + this.serviceId_, this.characteristicId_, this.descriptorId_, + this.value_.getArray()); + } - return device.writeValueForCharacteristic( - this.serviceId_, this.characteristicId_, this.value_.getArray()); - }.bind(this)).then(function(response) { - this.writeBtn_.disabled = false; + return device.writeValueForCharacteristic( + this.serviceId_, this.characteristicId_, + this.value_.getArray()); + }.bind(this)) + .then(function(response) { + this.writeBtn_.disabled = false; - if (response.result === interfaces.BluetoothDevice.GattResult.SUCCESS) { - Snackbar.show( - this.deviceAddress_ + ': Write succeeded', SnackbarType.SUCCESS); - return; - } + if (response.result === + interfaces.BluetoothDevice.GattResult.SUCCESS) { + Snackbar.show( + this.deviceAddress_ + ': Write succeeded', + SnackbarType.SUCCESS); + return; + } - var errorString = this.getErrorString_(response.result); - Snackbar.show( - this.deviceAddress_ + ': ' + errorString, SnackbarType.ERROR, - 'Retry', this.writeValue_.bind(this)); - }.bind(this)); + var errorString = this.getErrorString_(response.result); + Snackbar.show( + this.deviceAddress_ + ': ' + errorString, SnackbarType.ERROR, + 'Retry', this.writeValue_.bind(this)); + }.bind(this)); }, };
diff --git a/chrome/browser/resources/cast/cast.js b/chrome/browser/resources/cast/cast.js index 57c4a16..02e5305 100644 --- a/chrome/browser/resources/cast/cast.js +++ b/chrome/browser/resources/cast/cast.js
@@ -21,14 +21,12 @@ if (newHash !== oldHash) { window.location.hash = newHash; } - }).observe(extensionView, { - attributes: true - }); + }).observe(extensionView, {attributes: true}); window.addEventListener('hashchange', function() { var newHash = window.location.hash.substr(1); - var extensionViewSrcParts = splitUrlOnHash( - extensionView.getAttribute('src')); + var extensionViewSrcParts = + splitUrlOnHash(extensionView.getAttribute('src')); if (newHash !== extensionViewSrcParts[1]) { extensionView.load(extensionViewSrcParts[0] + '#' + newHash); } @@ -36,6 +34,6 @@ extensionView.load( 'chrome-extension://' + loadTimeData.getString('extensionId') + - '/cast_setup/index.html#' + window.location.hash.substr(1) || 'devices'); + '/cast_setup/index.html#' + window.location.hash.substr(1) || + 'devices'); }); -
diff --git a/chrome/browser/resources/certificate_viewer.js b/chrome/browser/resources/certificate_viewer.js index e95a1d9d..447534b0 100644 --- a/chrome/browser/resources/certificate_viewer.js +++ b/chrome/browser/resources/certificate_viewer.js
@@ -52,9 +52,10 @@ function oneShot(fn) { var fired = false; return function() { - if (fired) return; - fired = true; - fn(); + if (fired) + return; + fired = true; + fn(); }; } @@ -130,17 +131,15 @@ * @param {Object} tree Dictionary describing the tree structure. * @return {cr.ui.TreeItem} Tree node corresponding to the input dictionary. */ - function constructTree(tree) - { + function constructTree(tree) { var treeItem = new cr.ui.TreeItem({ - label: tree.label, - detail: {payload: tree.payload ? tree.payload : {}, - children: {} - }}); + label: tree.label, + detail: {payload: tree.payload ? tree.payload : {}, children: {}} + }); if (tree.children) { for (var i = 0; i < tree.children.length; i++) { - treeItem.add(treeItem.detail.children[i] = - constructTree(tree.children[i])); + treeItem.add( + treeItem.detail.children[i] = constructTree(tree.children[i])); } } return treeItem; @@ -175,8 +174,8 @@ function getCertificateFields(certFields) { clearCertificateFields(); var treeItem = $('cert-fields'); - treeItem.add(treeItem.detail.children['root'] = - constructTree(certFields[0])); + treeItem.add( + treeItem.detail.children['root'] = constructTree(certFields[0])); revealTree(treeItem); // Ensure the list is scrolled to the top by selecting the first item. treeItem.children[0].selected = true;
diff --git a/chrome/browser/resources/connection_manager.js b/chrome/browser/resources/connection_manager.js index baa3737..12cb0487 100644 --- a/chrome/browser/resources/connection_manager.js +++ b/chrome/browser/resources/connection_manager.js
@@ -3,11 +3,9 @@ // found in the LICENSE file. -function chromeos() { -} +function chromeos() {} -chromeos.connectionManager = function() { -}; +chromeos.connectionManager = function() {}; chromeos.connectionManager.transaction_status_callback_ = null; chromeos.connectionManager.parent_page_url_ = 'chrome://mobilesetup'; @@ -25,4 +23,3 @@ }; window.parent.postMessage(msg, chromeos.connectionManager.parent_page_url_); }; -
diff --git a/chrome/browser/resources/cryptotoken/appid.js b/chrome/browser/resources/cryptotoken/appid.js index 5e2cb7d..4b05cbc 100644 --- a/chrome/browser/resources/cryptotoken/appid.js +++ b/chrome/browser/resources/cryptotoken/appid.js
@@ -20,8 +20,7 @@ if (trustedFacets) { var versionBlock; for (i = 0; versionBlock = trustedFacets[i]; i++) { - if (versionBlock['version'] && - versionBlock['version']['major'] == 1 && + if (versionBlock['version'] && versionBlock['version']['major'] == 1 && versionBlock['version']['minor'] == 0) { urls = versionBlock['ids']; break; @@ -80,8 +79,8 @@ * @param {string=} opt_logMsgUrl A log message URL. * @return {Promise<boolean>} A promise for the result of the check */ -AppIdChecker.prototype.checkAppIds = - function(timer, origin, appIds, allowHttp, opt_logMsgUrl) {}; +AppIdChecker.prototype.checkAppIds = function( + timer, origin, appIds, allowHttp, opt_logMsgUrl) {}; /** * An interface to create an AppIdChecker. @@ -114,8 +113,8 @@ * @param {string=} opt_logMsgUrl A log message URL. * @return {Promise<boolean>} A promise for the result of the check */ -XhrAppIdChecker.prototype.checkAppIds = - function(timer, origin, appIds, allowHttp, opt_logMsgUrl) { +XhrAppIdChecker.prototype.checkAppIds = function( + timer, origin, appIds, allowHttp, opt_logMsgUrl) { if (this.timer_) { // Can't use the same object to check appIds more than once. return Promise.resolve(false); @@ -170,8 +169,8 @@ var self = this; return p.then(function(allowedOrigins) { if (allowedOrigins.indexOf(self.origin_) == -1) { - console.warn(UTIL_fmt('Origin ' + self.origin_ + - ' not allowed by app id ' + appId)); + console.warn(UTIL_fmt( + 'Origin ' + self.origin_ + ' not allowed by app id ' + appId)); return false; } return true; @@ -215,7 +214,7 @@ var p = this.fetcher_.fetch(appId); var self = this; return p.then(getOriginsFromJson, function(rc_) { - var rc = /** @type {number} */(rc_); + var rc = /** @type {number} */ (rc_); console.log(UTIL_fmt('fetching ' + appId + ' failed: ' + rc)); if (!(rc >= 400 && rc < 500) && !self.timer_.expired()) { // Retry
diff --git a/chrome/browser/resources/cryptotoken/b64.js b/chrome/browser/resources/cryptotoken/b64.js index d3c1e805..e4a26f5 100644 --- a/chrome/browser/resources/cryptotoken/b64.js +++ b/chrome/browser/resources/cryptotoken/b64.js
@@ -4,7 +4,8 @@ // WebSafeBase64Escape and Unescape. function B64_encode(bytes, opt_length) { - if (!opt_length) opt_length = bytes.length; + if (!opt_length) + opt_length = bytes.length; var b64out = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; var result = ''; @@ -32,7 +33,8 @@ // Normal base64 encode; not websafe, including padding. function base64_encode(bytes, opt_length) { - if (!opt_length) opt_length = bytes.length; + if (!opt_length) + opt_length = bytes.length; var b64out = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var result = ''; @@ -55,18 +57,18 @@ var i = (accu >> (shift - 6)) & 63; result += b64out.charAt(i); } - while (result.length % 4) result += '='; + while (result.length % 4) + result += '='; return result; } -var B64_inmap = -[ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 0, 0, - 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 0, 0, 0, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 64, - 0, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, - 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 0, 0, 0, 0, 0 +var B64_inmap = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 0, 0, + 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 0, 0, 0, 0, 0, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 0, 0, 0, 0, 64, + 0, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 0, 0, 0, 0, 0 ]; function B64_decode(string) { @@ -75,7 +77,8 @@ var shift = 0; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); - if (c < 32 || c > 127 || !B64_inmap[c - 32]) return []; + if (c < 32 || c > 127 || !B64_inmap[c - 32]) + return []; accu <<= 6; accu |= (B64_inmap[c - 32] - 1); shift += 6;
diff --git a/chrome/browser/resources/cryptotoken/countdowntimer.js b/chrome/browser/resources/cryptotoken/countdowntimer.js index 4e07ddb..63175c1 100644 --- a/chrome/browser/resources/cryptotoken/countdowntimer.js +++ b/chrome/browser/resources/cryptotoken/countdowntimer.js
@@ -43,14 +43,12 @@ this.remainingMillis = timeoutMillis; this.cb = cb; if (this.remainingMillis > CountdownTimer.TIMER_INTERVAL_MILLIS) { - this.timeoutId = - this.sysTimer_.setInterval(this.timerTick.bind(this), - CountdownTimer.TIMER_INTERVAL_MILLIS); + this.timeoutId = this.sysTimer_.setInterval( + this.timerTick.bind(this), CountdownTimer.TIMER_INTERVAL_MILLIS); } else { // Set a one-shot timer for the last interval. - this.timeoutId = - this.sysTimer_.setTimeout( - this.timerTick.bind(this), this.remainingMillis); + this.timeoutId = this.sysTimer_.setTimeout( + this.timerTick.bind(this), this.remainingMillis); } return true; }; @@ -114,8 +112,7 @@ * @param {function()=} opt_cb Called back when the countdown expires. * @return {!Countdown} The timer. */ -CountdownTimerFactory.prototype.createTimer = - function(timeoutMillis, opt_cb) { +CountdownTimerFactory.prototype.createTimer = function(timeoutMillis, opt_cb) { return new CountdownTimer(this.sysTimer_, timeoutMillis, opt_cb); }; @@ -177,9 +174,9 @@ * @param {number=} opt_attenuationSeconds Attenuation value in seconds. * @return {!Countdown} A countdown timer. */ -function createAttenuatedTimer(timerFactory, timeoutValueSeconds, - opt_attenuationSeconds) { - timeoutValueSeconds = attenuateTimeoutInSeconds(timeoutValueSeconds, - opt_attenuationSeconds); +function createAttenuatedTimer( + timerFactory, timeoutValueSeconds, opt_attenuationSeconds) { + timeoutValueSeconds = + attenuateTimeoutInSeconds(timeoutValueSeconds, opt_attenuationSeconds); return timerFactory.createTimer(timeoutValueSeconds * 1000); }
diff --git a/chrome/browser/resources/cryptotoken/cryptotokenapprovedorigins.js b/chrome/browser/resources/cryptotoken/cryptotokenapprovedorigins.js index 8b4f838c..9b3bc10 100644 --- a/chrome/browser/resources/cryptotoken/cryptotokenapprovedorigins.js +++ b/chrome/browser/resources/cryptotoken/cryptotokenapprovedorigins.js
@@ -27,31 +27,31 @@ * the type allows undefined. * @return {Promise<boolean>} A promise for the result of the check. */ -CryptoTokenApprovedOrigin.prototype.isApprovedOrigin = - function(origin, opt_tabId) { +CryptoTokenApprovedOrigin.prototype.isApprovedOrigin = function( + origin, opt_tabId) { return new Promise(function(resolve, reject) { - if (opt_tabId === undefined) { + if (opt_tabId === undefined) { + resolve(false); + return; + } + var tabId = /** @type {number} */ (opt_tabId); + tabInForeground(tabId).then(function(result) { + if (!result) { resolve(false); return; } - var tabId = /** @type {number} */ (opt_tabId); - tabInForeground(tabId).then(function(result) { - if (!result) { + if (!chrome.tabs || !chrome.tabs.get) { + reject(); + return; + } + chrome.tabs.get(tabId, function(tab) { + if (chrome.runtime.lastError) { resolve(false); return; } - if (!chrome.tabs || !chrome.tabs.get) { - reject(); - return; - } - chrome.tabs.get(tabId, function(tab) { - if (chrome.runtime.lastError) { - resolve(false); - return; - } - var tabOrigin = getOriginFromUrl(tab.url); - resolve(tabOrigin == origin); - }); + var tabOrigin = getOriginFromUrl(tab.url); + resolve(tabOrigin == origin); }); + }); }); };
diff --git a/chrome/browser/resources/cryptotoken/cryptotokenbackground.js b/chrome/browser/resources/cryptotoken/cryptotokenbackground.js index 4b8c3004b..610f3dc 100644 --- a/chrome/browser/resources/cryptotoken/cryptotokenbackground.js +++ b/chrome/browser/resources/cryptotoken/cryptotokenbackground.js
@@ -27,17 +27,13 @@ var xhrTextFetcher = new XhrTextFetcher(); return new FactoryRegistry( new XhrAppIdCheckerFactory(xhrTextFetcher), - new CryptoTokenApprovedOrigin(), - new CountdownTimerFactory(windowTimer), - new CryptoTokenOriginChecker(), - new UsbHelper(), - windowTimer, + new CryptoTokenApprovedOrigin(), new CountdownTimerFactory(windowTimer), + new CryptoTokenOriginChecker(), new UsbHelper(), windowTimer, xhrTextFetcher); })(); var DEVICE_FACTORY_REGISTRY = new DeviceFactoryRegistry( - new UsbGnubbyFactory(gnubbies), - FACTORY_REGISTRY.getCountdownFactory(), + new UsbGnubbyFactory(gnubbies), FACTORY_REGISTRY.getCountdownFactory(), new GoogleCorpIndividualAttestation()); /** @@ -107,8 +103,8 @@ responseCallback = defaultResponseCallback.bind(null, request, sendResponse); } - var closeable = handleWebPageRequest(/** @type {Object} */(request), - sender, responseCallback); + var closeable = handleWebPageRequest( + /** @type {Object} */ (request), sender, responseCallback); return closeable; }
diff --git a/chrome/browser/resources/cryptotoken/cryptotokenorigincheck.js b/chrome/browser/resources/cryptotoken/cryptotokenorigincheck.js index 3e4ac5e..8f41de0 100644 --- a/chrome/browser/resources/cryptotoken/cryptotokenorigincheck.js +++ b/chrome/browser/resources/cryptotoken/cryptotokenorigincheck.js
@@ -16,8 +16,7 @@ * @implements OriginChecker * @constructor */ -function CryptoTokenOriginChecker() { -} +function CryptoTokenOriginChecker() {} /** * Checks whether the origin is allowed to claim the app ids. @@ -41,8 +40,7 @@ * @return {Promise<boolean>} A promise for the result of the check * @private */ -CryptoTokenOriginChecker.prototype.checkAppId_ = - function(origin, appId) { +CryptoTokenOriginChecker.prototype.checkAppId_ = function(origin, appId) { return new Promise(function(resolve, reject) { if (!chrome.cryptotokenPrivate) { reject();
diff --git a/chrome/browser/resources/cryptotoken/devicefactoryregistry.js b/chrome/browser/resources/cryptotoken/devicefactoryregistry.js index c1f4bee5..9919598 100644 --- a/chrome/browser/resources/cryptotoken/devicefactoryregistry.js +++ b/chrome/browser/resources/cryptotoken/devicefactoryregistry.js
@@ -15,8 +15,8 @@ * attestation implementation. * @constructor */ -function DeviceFactoryRegistry(gnubbyFactory, countdownFactory, - individualAttestation) { +function DeviceFactoryRegistry( + gnubbyFactory, countdownFactory, individualAttestation) { /** @private {!GnubbyFactory} */ this.gnubbyFactory_ = gnubbyFactory; /** @private {!CountdownFactory} */
diff --git a/chrome/browser/resources/cryptotoken/enroller.js b/chrome/browser/resources/cryptotoken/enroller.js index 42b7c20..94ae1d4 100644 --- a/chrome/browser/resources/cryptotoken/enroller.js +++ b/chrome/browser/resources/cryptotoken/enroller.js
@@ -21,8 +21,8 @@ var closeable = null; function sendErrorResponse(error) { - var response = makeU2fErrorResponse(request, error.errorCode, - error.errorMessage); + var response = + makeU2fErrorResponse(request, error.errorCode, error.errorMessage); sendResponseOnce(sentResponse, closeable, response, sendResponse); } @@ -65,16 +65,16 @@ // not before. var watchdogTimeoutValueSeconds = attenuateTimeoutInSeconds( timeoutValueSeconds, MINIMUM_TIMEOUT_ATTENUATION_SECONDS / 2); - var watchdog = new WatchdogRequestHandler(watchdogTimeoutValueSeconds, - timeout); + var watchdog = + new WatchdogRequestHandler(watchdogTimeoutValueSeconds, timeout); var wrappedErrorCb = watchdog.wrapCallback(sendErrorResponse); var wrappedSuccessCb = watchdog.wrapCallback(sendSuccessResponse); var timer = createAttenuatedTimer( FACTORY_REGISTRY.getCountdownFactory(), timeoutValueSeconds); var logMsgUrl = request['logMsgUrl']; - var enroller = new Enroller(timer, sender, sendErrorResponse, - sendSuccessResponse, logMsgUrl); + var enroller = new Enroller( + timer, sender, sendErrorResponse, sendSuccessResponse, logMsgUrl); watchdog.setCloseable(/** @type {!Closeable} */ (enroller)); closeable = watchdog; @@ -182,8 +182,8 @@ * @param {string=} opt_clientData The client data, if available. * @return {Object} The responseData object. */ -function makeEnrollResponseData(enrollChallenge, u2fVersion, registrationData, - opt_clientData) { +function makeEnrollResponseData( + enrollChallenge, u2fVersion, registrationData, opt_clientData) { var responseData = {}; responseData['registrationData'] = registrationData; // Echo the used challenge back in the reply. @@ -278,8 +278,8 @@ * existing enrollments for this user and appId. * @param {string=} opt_appId The app id for the entire request. */ -Enroller.prototype.doEnroll = function(enrollChallenges, signChallenges, - opt_appId) { +Enroller.prototype.doEnroll = function( + enrollChallenges, signChallenges, opt_appId) { /** @private {Array<EnrollChallenge>} */ this.enrollChallenges_ = enrollChallenges; /** @private {Array<SignChallenge>} */ @@ -287,13 +287,17 @@ /** @private {(string|undefined)} */ this.appId_ = opt_appId; var self = this; - getTabIdWhenPossible(this.sender_).then(function() { - if (self.done_) return; - self.approveOrigin_(); - }, function() { - self.close(); - self.notifyError_({errorCode: ErrorCodes.BAD_REQUEST}); - }); + getTabIdWhenPossible(this.sender_) + .then( + function() { + if (self.done_) + return; + self.approveOrigin_(); + }, + function() { + self.close(); + self.notifyError_({errorCode: ErrorCodes.BAD_REQUEST}); + }); }; /** @@ -306,7 +310,8 @@ FACTORY_REGISTRY.getApprovedOrigins() .isApprovedOrigin(this.sender_.origin, this.sender_.tabId) .then(function(result) { - if (self.done_) return; + if (self.done_) + return; if (!result) { // Origin not approved: rather than give an explicit indication to // the web page, let a timeout occur. @@ -346,9 +351,8 @@ // If the request didn't contain a sign challenge, provide one. The value // doesn't matter. var defaultSignChallenge = ''; - var encodedSignChallenges = - encodeSignChallenges(this.signChallenges_, defaultSignChallenge, - this.appId_); + var encodedSignChallenges = encodeSignChallenges( + this.signChallenges_, defaultSignChallenge, this.appId_); var request = { type: 'enroll_helper_request', enrollChallenges: encodedEnrollChallenges, @@ -378,7 +382,8 @@ } var self = this; this.checkAppIds_(enrollAppIds, function(result) { - if (self.done_) return; + if (self.done_) + return; if (result) { self.handler_ = FACTORY_REGISTRY.getRequestHelper().getHandler(request); if (self.handler_) { @@ -434,8 +439,8 @@ * @return {!Array<EnrollHelperChallenge>} The encoded enroll challenges. * @private */ -Enroller.prototype.encodeEnrollChallenges_ = function(enrollChallenges, - opt_appId) { +Enroller.prototype.encodeEnrollChallenges_ = function( + enrollChallenges, opt_appId) { var challenges = []; for (var i = 0; i < enrollChallenges.length; i++) { var enrollChallenge = enrollChallenges[i]; @@ -459,8 +464,7 @@ // Replace the challenge with the hash of the browser data. modifiedChallenge['challenge'] = B64_encode(sha256HashOfString(browserData)); - this.browserData_[version] = - B64_encode(UTIL_StringToBytes(browserData)); + this.browserData_[version] = B64_encode(UTIL_StringToBytes(browserData)); challenges.push(Enroller.encodeEnrollChallenge_( /** @type {EnrollChallenge} */ (modifiedChallenge), opt_appId)); } else { @@ -502,8 +506,8 @@ return; } var appIdChecker = FACTORY_REGISTRY.getAppIdCheckerFactory().create(); - appIdChecker. - checkAppIds( + appIdChecker + .checkAppIds( this.timer_.clone(), this.sender_.origin, appIds, this.allowHttp_, this.logMsgUrl_) .then(cb); @@ -538,8 +542,8 @@ * @param {string|undefined} opt_browserData Browser data used * @private */ -Enroller.prototype.notifySuccess_ = - function(u2fVersion, info, opt_browserData) { +Enroller.prototype.notifySuccess_ = function( + u2fVersion, info, opt_browserData) { if (this.done_) return; this.close(); @@ -555,8 +559,9 @@ Enroller.prototype.helperComplete_ = function(reply) { if (reply.code) { var reportedError = mapDeviceStatusCodeToU2fError(reply.code); - console.log(UTIL_fmt('helper reported ' + reply.code.toString(16) + - ', returning ' + reportedError.errorCode)); + console.log(UTIL_fmt( + 'helper reported ' + reply.code.toString(16) + ', returning ' + + reportedError.errorCode)); this.notifyError_(reportedError); } else { console.log(UTIL_fmt('Gnubby enrollment succeeded!!!!!')); @@ -568,8 +573,8 @@ browserData = this.browserData_[reply.version]; } - this.notifySuccess_(/** @type {string} */ (reply.version), - /** @type {string} */ (reply.enrollData), - browserData); + this.notifySuccess_( + /** @type {string} */ (reply.version), + /** @type {string} */ (reply.enrollData), browserData); } };
diff --git a/chrome/browser/resources/cryptotoken/factoryregistry.js b/chrome/browser/resources/cryptotoken/factoryregistry.js index e0f5d29..d5866e8 100644 --- a/chrome/browser/resources/cryptotoken/factoryregistry.js +++ b/chrome/browser/resources/cryptotoken/factoryregistry.js
@@ -18,8 +18,9 @@ * @param {!TextFetcher} textFetcher A text fetcher. * @constructor */ -function FactoryRegistry(appIdCheckerFactory, approvedOrigins, countdownFactory, - originChecker, requestHelper, sysTimer, textFetcher) { +function FactoryRegistry( + appIdCheckerFactory, approvedOrigins, countdownFactory, originChecker, + requestHelper, sysTimer, textFetcher) { /** @private {!AppIdCheckerFactory} */ this.appIdCheckerFactory_ = appIdCheckerFactory; /** @private {!ApprovedOrigins} */
diff --git a/chrome/browser/resources/cryptotoken/generichelper.js b/chrome/browser/resources/cryptotoken/generichelper.js index 2944610..ea56f5ab 100644 --- a/chrome/browser/resources/cryptotoken/generichelper.js +++ b/chrome/browser/resources/cryptotoken/generichelper.js
@@ -42,7 +42,7 @@ * @param {RequestHandlerFactory} factory A factory that can produce a handler * for a request of a given type. */ -GenericRequestHelper.prototype.registerHandlerFactory = - function(type, factory) { +GenericRequestHelper.prototype.registerHandlerFactory = function( + type, factory) { this.handlerFactories_[type] = factory; };
diff --git a/chrome/browser/resources/cryptotoken/gnubbies.js b/chrome/browser/resources/cryptotoken/gnubbies.js index cbb92cb..d6c10791 100644 --- a/chrome/browser/resources/cryptotoken/gnubbies.js +++ b/chrome/browser/resources/cryptotoken/gnubbies.js
@@ -30,11 +30,7 @@ * @const * @enum {number} */ -var GnubbyEnumerationTypes = { - ANY: 0, - VID_PID: 1, - FIDO_U2F: 2 -}; +var GnubbyEnumerationTypes = {ANY: 0, VID_PID: 1, FIDO_U2F: 2}; /** * @typedef {{ @@ -87,7 +83,8 @@ * @return {boolean} Whether the device is a shared access device. */ Gnubbies.prototype.isSharedAccess = function(id) { - if (!this.impl_.hasOwnProperty(id.namespace)) return false; + if (!this.impl_.hasOwnProperty(id.namespace)) + return false; return this.impl_[id.namespace].isSharedAccess; }; @@ -247,9 +244,8 @@ opt_timeoutMillis + Gnubbies.INACTIVITY_TIMEOUT_MARGIN_MILLIS : Gnubbies.INACTIVITY_TIMEOUT_MARGIN_MILLIS; if (!this.inactivityTimer) { - this.inactivityTimer = - new CountdownTimer( - Gnubbies.SYS_TIMER_, millis, this.inactivityTimeout_.bind(this)); + this.inactivityTimer = new CountdownTimer( + Gnubbies.SYS_TIMER_, millis, this.inactivityTimeout_.bind(this)); } else if (millis > this.inactivityTimer.millisecondsUntilExpired()) { this.inactivityTimer.clearTimeout(); this.inactivityTimer.setTimeout(millis, this.inactivityTimeout_.bind(this)); @@ -265,7 +261,8 @@ for (var namespace in this.openDevs_) { for (var dev in this.openDevs_[namespace]) { var deviceId = Number(dev); - console.warn(namespace + ' device ' + deviceId + + console.warn( + namespace + ' device ' + deviceId + ' still open after inactivity, closing'); this.openDevs_[namespace][deviceId].destroy(); } @@ -288,10 +285,14 @@ if (gnubby.closing) { // Device is closing or already closed. self.removeClient(gnubby, who); - if (cb) { cb(-GnubbyDevice.NODEVICE); } + if (cb) { + cb(-GnubbyDevice.NODEVICE); + } } else { gnubby.registerClient(who); - if (cb) { cb(-GnubbyDevice.OK, gnubby); } + if (cb) { + cb(-GnubbyDevice.OK, gnubby); + } } } @@ -319,7 +320,9 @@ if (!dev) { // Index out of bounds. Device does not exist in current enumeration. this.removeClient(null, who); - if (cb) { cb(-GnubbyDevice.NODEVICE); } + if (cb) { + cb(-GnubbyDevice.NODEVICE); + } return; }
diff --git a/chrome/browser/resources/cryptotoken/gnubby-u2f.js b/chrome/browser/resources/cryptotoken/gnubby-u2f.js index 47ac6f6..d0335ec9 100644 --- a/chrome/browser/resources/cryptotoken/gnubby-u2f.js +++ b/chrome/browser/resources/cryptotoken/gnubby-u2f.js
@@ -42,23 +42,22 @@ * @param {boolean=} opt_individualAttestation Request the individual * attestation cert rather than the batch one. */ -Gnubby.prototype.enroll = function(challenge, appIdHash, cb, - opt_individualAttestation) { +Gnubby.prototype.enroll = function( + challenge, appIdHash, cb, opt_individualAttestation) { var p1 = Gnubby.P1_TUP_REQUIRED | Gnubby.P1_TUP_CONSUME; if (opt_individualAttestation) { p1 |= Gnubby.P1_INDIVIDUAL_KEY; } - var apdu = new Uint8Array( - [0x00, - Gnubby.U2F_ENROLL, - p1, - 0x00, 0x00, 0x00, - challenge.length + appIdHash.length]); - var u8 = new Uint8Array(apdu.length + challenge.length + - appIdHash.length + 2); - for (var i = 0; i < apdu.length; ++i) u8[i] = apdu[i]; - for (var i = 0; i < challenge.length; ++i) u8[i + apdu.length] = - challenge[i]; + var apdu = new Uint8Array([ + 0x00, Gnubby.U2F_ENROLL, p1, 0x00, 0x00, 0x00, + challenge.length + appIdHash.length + ]); + var u8 = + new Uint8Array(apdu.length + challenge.length + appIdHash.length + 2); + for (var i = 0; i < apdu.length; ++i) + u8[i] = apdu[i]; + for (var i = 0; i < challenge.length; ++i) + u8[i + apdu.length] = challenge[i]; for (var i = 0; i < appIdHash.length; ++i) { u8[i + apdu.length + challenge.length] = appIdHash[i]; } @@ -75,8 +74,8 @@ * @param {boolean=} opt_nowink Request signature without winking * (e.g. during enroll) */ -Gnubby.prototype.sign = function(challengeHash, appIdHash, keyHandle, cb, - opt_nowink) { +Gnubby.prototype.sign = function( + challengeHash, appIdHash, keyHandle, cb, opt_nowink) { var self = this; // The sign command's format is ever-so-slightly different between V1 and V2, // so get this gnubby's version prior to sending it. @@ -87,17 +86,15 @@ } var version = UTIL_BytesToString(new Uint8Array(opt_data || [])); var apduDataLen = - challengeHash.length + appIdHash.length + keyHandle.length; + challengeHash.length + appIdHash.length + keyHandle.length; if (version != Gnubby.U2F_V1) { // The V2 sign command includes a length byte for the key handle. apduDataLen++; } - var apdu = new Uint8Array( - [0x00, - Gnubby.U2F_SIGN, - Gnubby.P1_TUP_REQUIRED | Gnubby.P1_TUP_CONSUME, - 0x00, 0x00, 0x00, - apduDataLen]); + var apdu = new Uint8Array([ + 0x00, Gnubby.U2F_SIGN, Gnubby.P1_TUP_REQUIRED | Gnubby.P1_TUP_CONSUME, + 0x00, 0x00, 0x00, apduDataLen + ]); if (opt_nowink) { // A signature request that does not want winking. // These are used during enroll to figure out whether a gnubby was already @@ -107,9 +104,10 @@ apdu[2] |= Gnubby.P1_TUP_TESTONLY; } var u8 = new Uint8Array(apdu.length + apduDataLen + 2); - for (var i = 0; i < apdu.length; ++i) u8[i] = apdu[i]; - for (var i = 0; i < challengeHash.length; ++i) u8[i + apdu.length] = - challengeHash[i]; + for (var i = 0; i < apdu.length; ++i) + u8[i] = apdu[i]; + for (var i = 0; i < challengeHash.length; ++i) + u8[i + apdu.length] = challengeHash[i]; for (var i = 0; i < appIdHash.length; ++i) { u8[i + apdu.length + challengeHash.length] = appIdHash[i]; } @@ -128,7 +126,8 @@ * @param {function(...)} cb Callback */ Gnubby.prototype.version = function(cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; if (this.version_) { cb(-GnubbyDevice.OK, this.version_); return; @@ -142,8 +141,8 @@ cb(rc, data); } - var apdu = new Uint8Array([0x00, Gnubby.U2F_VERSION, 0x00, 0x00, 0x00, - 0x00, 0x00]); + var apdu = + new Uint8Array([0x00, Gnubby.U2F_VERSION, 0x00, 0x00, 0x00, 0x00, 0x00]); this.apduReply(apdu.buffer, function(rc, data) { if (rc == 0x6d00) { // Command not implemented. Pretend this is v1. @@ -155,8 +154,8 @@ if (rc == 0x6700) { // Wrong length. Try with non-ISO 7816-4-conforming layout defined in // earlier U2F drafts. - apdu = new Uint8Array([0x00, Gnubby.U2F_VERSION, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00]); + apdu = new Uint8Array( + [0x00, Gnubby.U2F_VERSION, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); self.apduReply(apdu.buffer, gotResponse); return; }
diff --git a/chrome/browser/resources/cryptotoken/gnubby.js b/chrome/browser/resources/cryptotoken/gnubby.js index 410ec29..28910ce 100644 --- a/chrome/browser/resources/cryptotoken/gnubby.js +++ b/chrome/browser/resources/cryptotoken/gnubby.js
@@ -49,10 +49,9 @@ * @return {string} hexadecimal string. */ Gnubby.hexCid = function(cid) { - var tmp = [(cid >>> 24) & 255, - (cid >>> 16) & 255, - (cid >>> 8) & 255, - (cid >>> 0) & 255]; + var tmp = [ + (cid >>> 24) & 255, (cid >>> 16) & 255, (cid >>> 8) & 255, (cid >>> 0) & 255 + ]; return UTIL_BytesToHex(tmp); }; @@ -172,10 +171,9 @@ // Wait a bit in case simpleton client tries open next gnubby. // Without delay, gnubbies would drop all idle devices, before client // gets to the next one. - window.setTimeout( - function() { - Gnubby.gnubbies_.removeClient(dev, self); - }, 300); + window.setTimeout(function() { + Gnubby.gnubbies_.removeClient(dev, self); + }, 300); } }; @@ -186,11 +184,13 @@ Gnubby.prototype.closeWhenIdle = function(cb) { if (!this.inUse_()) { this.close(); - if (cb) cb(); + if (cb) + cb(); return; } this.closingWhenIdle = true; - if (cb) this.notifyOnClose.push(cb); + if (cb) + this.notifyOnClose.push(cb); }; /** @@ -222,7 +222,8 @@ Gnubby.prototype.notifyFrame_ = function(cb) { if (this.rxframes.length != 0) { // Already have frames; continue. - if (cb) window.setTimeout(cb, 0); + if (cb) + window.setTimeout(cb, 0); } else { this.rxcb = cb; } @@ -235,7 +236,8 @@ * frames from its device. */ Gnubby.prototype.receivedFrame = function(frame) { - if (this.closed) return false; // No longer interested. + if (this.closed) + return false; // No longer interested. if (!this.checkCID_(frame)) { // Not for me, ignore. @@ -247,7 +249,8 @@ // Callback self in case we were waiting. Once. var cb = this.rxcb; this.rxcb = null; - if (cb) window.setTimeout(cb, 0); + if (cb) + window.setTimeout(cb, 0); return true; }; @@ -264,7 +267,8 @@ * @private */ Gnubby.prototype.readFrame_ = function() { - if (this.rxframes.length == 0) throw 'rxframes empty!'; + if (this.rxframes.length == 0) + throw 'rxframes empty!'; var frame = this.rxframes.shift(); return frame; @@ -277,8 +281,14 @@ * @private */ Gnubby.prototype.read_ = function(cmd, timeout, cb) { - if (this.closed) { cb(-GnubbyDevice.GONE); return; } - if (!this.dev) { cb(-GnubbyDevice.GONE); return; } + if (this.closed) { + cb(-GnubbyDevice.GONE); + return; + } + if (!this.dev) { + cb(-GnubbyDevice.GONE); + return; + } var tid = null; // timeout timer id. var callback = cb; @@ -304,16 +314,19 @@ var c = callback; if (c) { callback = null; - window.setTimeout(function() { c(a, b); }, 0); + window.setTimeout(function() { + c(a, b); + }, 0); } - if (self.closingWhenIdle) self.idleClose_(); + if (self.closingWhenIdle) + self.idleClose_(); } function read_timeout() { - if (!callback || !tid) return; // Already done. + if (!callback || !tid) + return; // Already done. - console.error(UTIL_fmt( - '[' + Gnubby.hexCid(self.cid) + '] timeout!')); + console.error(UTIL_fmt('[' + Gnubby.hexCid(self.cid) + '] timeout!')); if (self.dev) { self.dev.destroy(); // Stop pretending this thing works. @@ -325,7 +338,8 @@ } function cont_frame() { - if (!callback || !tid) return; // Already done. + if (!callback || !tid) + return; // Already done. var f = new Uint8Array(self.readFrame_()); var rcmd = f[4]; @@ -376,7 +390,8 @@ } function init_frame() { - if (!callback || !tid) return; // Already done. + if (!callback || !tid) + return; // Already done. var f = new Uint8Array(self.readFrame_()); @@ -439,13 +454,13 @@ }; /** - * @const - */ + * @const + */ Gnubby.NOTIFICATION_CID = 0; /** - * @const - */ + * @const + */ Gnubby.BROADCAST_CID = (0xff << 24) | (0xff << 16) | (0xff << 8) | 0xff; /** @@ -455,12 +470,8 @@ */ Gnubby.prototype.checkCID_ = function(frame) { var f = new Uint8Array(frame); - var c = (f[0] << 24) | - (f[1] << 16) | - (f[2] << 8) | - (f[3]); - return c === this.cid || - c === Gnubby.NOTIFICATION_CID; + var c = (f[0] << 24) | (f[1] << 16) | (f[2] << 8) | (f[3]); + return c === this.cid || c === Gnubby.NOTIFICATION_CID; }; /** @@ -470,8 +481,10 @@ * @private */ Gnubby.prototype.write_ = function(cmd, data) { - if (this.closed) return; - if (!this.dev) return; + if (this.closed) + return; + if (!this.dev) + return; this.commandPending = true; @@ -520,8 +533,10 @@ Gnubby.defaultCallback = function(rc, data) { var msg = 'defaultCallback(' + rc; if (data) { - if (typeof data == 'string') msg += ', ' + data; - else msg += ', ' + UTIL_BytesToHex(new Uint8Array(data)); + if (typeof data == 'string') + msg += ', ' + data; + else + msg += ', ' + UTIL_BytesToHex(new Uint8Array(data)); } msg += ')'; console.log(UTIL_fmt(msg)); @@ -535,7 +550,8 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.sync = function(cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; if (this.closed) { cb(-GnubbyDevice.GONE); return; @@ -549,7 +565,8 @@ function returnValue(rc) { done = true; window.setTimeout(cb.bind(null, rc), 0); - if (self.closingWhenIdle) self.idleClose_(); + if (self.closingWhenIdle) + self.idleClose_(); } function callback(rc, opt_frame) { @@ -569,13 +586,15 @@ } function syncSentinelEquals(f) { - return (f[4] == GnubbyDevice.CMD_SYNC && + return ( + f[4] == GnubbyDevice.CMD_SYNC && (f.length == 7 || /* fw pre-0.2.1 bug: does not echo sentinel */ f[7] == self.synccnt)); } function syncCompletionAction(rc, opt_frame) { - if (rc) console.warn(UTIL_fmt('sync failed: ' + rc)); + if (rc) + console.warn(UTIL_fmt('sync failed: ' + rc)); returnValue(rc); } @@ -591,16 +610,15 @@ } function initSentinelEquals(f) { - return (f[4] == GnubbyDevice.CMD_INIT && - f.length >= nonce.length + 7 && + return ( + f[4] == GnubbyDevice.CMD_INIT && f.length >= nonce.length + 7 && UTIL_equalArrays(f.subarray(7, nonce.length + 7), nonce)); } function initCmdUnsupported(rc) { // Different firmwares fail differently on different inputs, so treat any // of the following errors as indicating the INIT command isn't supported. - return rc == -GnubbyDevice.INVALID_CMD || - rc == -GnubbyDevice.INVALID_PAR || + return rc == -GnubbyDevice.INVALID_CMD || rc == -GnubbyDevice.INVALID_PAR || rc == -GnubbyDevice.INVALID_LEN; } @@ -626,10 +644,8 @@ } // Accept the provided cid. var offs = HEADER_LENGTH + nonce.length; - self.cid = (opt_frame[offs] << 24) | - (opt_frame[offs + 1] << 16) | - (opt_frame[offs + 2] << 8) | - opt_frame[offs + 3]; + self.cid = (opt_frame[offs] << 24) | (opt_frame[offs + 1] << 16) | + (opt_frame[offs + 2] << 8) | opt_frame[offs + 3]; returnValue(rc); } @@ -637,8 +653,7 @@ var f = new Uint8Array(self.readFrame_()); // Stop on errors and return them. - if (f[4] == GnubbyDevice.CMD_ERROR && - f[5] == 0 && f[6] == 1) { + if (f[4] == GnubbyDevice.CMD_ERROR && f[5] == 0 && f[6] == 1) { if (f[7] == GnubbyDevice.BUSY) { // Not spec but some devices do this; retry. sendSentinel(); @@ -665,7 +680,8 @@ } function timeoutLoop() { - if (done) return; + if (done) + return; if (trycount == 0) { // Failed. @@ -720,7 +736,8 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.blink = function(data, cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; if (typeof data == 'number') { var d = new Uint8Array([data]); data = d.buffer; @@ -733,7 +750,8 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.lock = function(data, cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; if (typeof data == 'number') { var d = new Uint8Array([data]); data = d.buffer; @@ -745,28 +763,30 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.unlock = function(cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; var data = new Uint8Array([0]); - this.exchange_(GnubbyDevice.CMD_LOCK, data.buffer, - Gnubby.NORMAL_TIMEOUT, cb); + this.exchange_(GnubbyDevice.CMD_LOCK, data.buffer, Gnubby.NORMAL_TIMEOUT, cb); }; /** Request system information data. * @param {?function(...)} cb Callback */ Gnubby.prototype.sysinfo = function(cb) { - if (!cb) cb = Gnubby.defaultCallback; - this.exchange_(GnubbyDevice.CMD_SYSINFO, new ArrayBuffer(0), - Gnubby.NORMAL_TIMEOUT, cb); + if (!cb) + cb = Gnubby.defaultCallback; + this.exchange_( + GnubbyDevice.CMD_SYSINFO, new ArrayBuffer(0), Gnubby.NORMAL_TIMEOUT, cb); }; /** Send wink command * @param {?function(...)} cb Callback */ Gnubby.prototype.wink = function(cb) { - if (!cb) cb = Gnubby.defaultCallback; - this.exchange_(GnubbyDevice.CMD_WINK, new ArrayBuffer(0), - Gnubby.NORMAL_TIMEOUT, cb); + if (!cb) + cb = Gnubby.defaultCallback; + this.exchange_( + GnubbyDevice.CMD_WINK, new ArrayBuffer(0), Gnubby.NORMAL_TIMEOUT, cb); }; /** Send DFU (Device firmware upgrade) command @@ -774,7 +794,8 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.dfu = function(data, cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; this.exchange_(GnubbyDevice.CMD_DFU, data, Gnubby.NORMAL_TIMEOUT, cb); }; @@ -783,7 +804,8 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.ping = function(data, cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; if (typeof data == 'number') { var d = new Uint8Array(data); window.crypto.getRandomValues(d); @@ -797,7 +819,8 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.apdu = function(data, cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; this.exchange_(GnubbyDevice.CMD_APDU, data, Gnubby.MAX_TIMEOUT, cb); }; @@ -805,9 +828,10 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.reset = function(cb) { - if (!cb) cb = Gnubby.defaultCallback; - this.exchange_(GnubbyDevice.CMD_ATR, new ArrayBuffer(0), - Gnubby.MAX_TIMEOUT, cb); + if (!cb) + cb = Gnubby.defaultCallback; + this.exchange_( + GnubbyDevice.CMD_ATR, new ArrayBuffer(0), Gnubby.MAX_TIMEOUT, cb); }; // byte args[3] = [delay-in-ms before disabling interrupts, @@ -818,10 +842,11 @@ * @param {?function(...)} cb Callback */ Gnubby.prototype.usb_test = function(args, cb) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; var u8 = new Uint8Array(args); - this.exchange_(GnubbyDevice.CMD_USB_TEST, u8.buffer, - Gnubby.NORMAL_TIMEOUT, cb); + this.exchange_( + GnubbyDevice.CMD_USB_TEST, u8.buffer, Gnubby.NORMAL_TIMEOUT, cb); }; /** APDU command with reply @@ -830,7 +855,8 @@ * @param {boolean=} opt_nowink Do not wink */ Gnubby.prototype.apduReply = function(request, cb, opt_nowink) { - if (!cb) cb = Gnubby.defaultCallback; + if (!cb) + cb = Gnubby.defaultCallback; var self = this; this.apdu(request, function(rc, data) { @@ -846,7 +872,9 @@ rc = r8[r8.length - 2] * 256 + r8[r8.length - 1]; // wink gnubby at hand if it needs touching. if (rc == 0x6985 && !opt_nowink) { - self.wink(function() { cb(rc); }); + self.wink(function() { + cb(rc); + }); return; } }
diff --git a/chrome/browser/resources/cryptotoken/gnubbyfactory.js b/chrome/browser/resources/cryptotoken/gnubbyfactory.js index 5be99d6..aca6c6d 100644 --- a/chrome/browser/resources/cryptotoken/gnubbyfactory.js +++ b/chrome/browser/resources/cryptotoken/gnubbyfactory.js
@@ -17,8 +17,7 @@ * Enumerates gnubbies. * @param {function(number, Array<GnubbyDeviceId>)} cb Enumerate callback */ -GnubbyFactory.prototype.enumerate = function(cb) { -}; +GnubbyFactory.prototype.enumerate = function(cb) {}; /** @typedef {function(number, Gnubby=)} */ var FactoryOpenCallback; @@ -36,9 +35,8 @@ * that can be used to cancel this pending open operation. Opening device * might take long time or be resource-hungry. */ -GnubbyFactory.prototype.openGnubby = - function(which, forEnroll, cb, opt_appIdHash, opt_logMsgUrl, opt_caller) { -}; +GnubbyFactory.prototype.openGnubby = function( + which, forEnroll, cb, opt_appIdHash, opt_logMsgUrl, opt_caller) {}; /** * Called during enrollment to check whether a gnubby known not to be enrolled @@ -50,6 +48,5 @@ * @param {FactoryOpenCallback} cb Called with the result of the prerequisite * check. (A non-zero status indicates failure.) */ -GnubbyFactory.prototype.notEnrolledPrerequisiteCheck = - function(gnubby, appIdHash, cb) { -}; +GnubbyFactory.prototype.notEnrolledPrerequisiteCheck = function( + gnubby, appIdHash, cb) {};
diff --git a/chrome/browser/resources/cryptotoken/googlecorpindividualattest.js b/chrome/browser/resources/cryptotoken/googlecorpindividualattest.js index 57732fc0..43420b49 100644 --- a/chrome/browser/resources/cryptotoken/googlecorpindividualattest.js +++ b/chrome/browser/resources/cryptotoken/googlecorpindividualattest.js
@@ -36,6 +36,5 @@ * Hash of the app ID used by Google employee accounts. * @const */ -GoogleCorpIndividualAttestation.GOOGLE_CORP_APP_ID_HASH = - B64_encode(sha256HashOfString( - GoogleCorpIndividualAttestation.GOOGLE_CORP_APP_ID)); +GoogleCorpIndividualAttestation.GOOGLE_CORP_APP_ID_HASH = B64_encode( + sha256HashOfString(GoogleCorpIndividualAttestation.GOOGLE_CORP_APP_ID));
diff --git a/chrome/browser/resources/cryptotoken/hidgnubbydevice.js b/chrome/browser/resources/cryptotoken/hidgnubbydevice.js index 55a449e..7fdca9e 100644 --- a/chrome/browser/resources/cryptotoken/hidgnubbydevice.js +++ b/chrome/browser/resources/cryptotoken/hidgnubbydevice.js
@@ -23,10 +23,10 @@ this.id = id; this.txqueue = []; this.clients = []; - this.lockCID = 0; // channel ID of client holding a lock, if != 0. - this.lockMillis = 0; // current lock period. - this.lockTID = null; // timer id of lock timeout. - this.closing = false; // device to be closed by receive loop. + this.lockCID = 0; // channel ID of client holding a lock, if != 0. + this.lockMillis = 0; // current lock period. + this.lockTID = null; // timer id of lock timeout. + this.closing = false; // device to be closed by receive loop. this.updating = false; // device firmware is in final stage of updating. } @@ -38,13 +38,14 @@ /** Destroys this low-level device instance. */ HidGnubbyDevice.prototype.destroy = function() { - if (!this.dev) return; // Already dead. + if (!this.dev) + return; // Already dead. function closeLowLevelDevice(dev) { chrome.hid.disconnect(dev.connectionId, function() { if (chrome.runtime.lastError) { - console.warn(UTIL_fmt('Device ' + dev.connectionId + - ' couldn\'t be disconnected:')); + console.warn(UTIL_fmt( + 'Device ' + dev.connectionId + ' couldn\'t be disconnected:')); console.warn(UTIL_fmt(chrome.runtime.lastError.message)); return; } @@ -63,15 +64,16 @@ // // Use magic CID 0 to address all. this.publishFrame_(new Uint8Array([ - 0, 0, 0, 0, // broadcast CID - GnubbyDevice.CMD_ERROR, - 0, 1, // length - GnubbyDevice.GONE]).buffer); + 0, 0, 0, 0, // broadcast CID + GnubbyDevice.CMD_ERROR, 0, 1, // length + GnubbyDevice.GONE + ]).buffer); // Set all clients to closed status and remove them. while (this.clients.length != 0) { var client = this.clients.shift(); - if (client) client.closed = true; + if (client) + client.closed = true; } if (this.lockTID) { @@ -123,11 +125,11 @@ remaining.push(client); } else { changes = true; - console.log(UTIL_fmt( - '[' + Gnubby.hexCid(client.cid) + '] left?')); + console.log(UTIL_fmt('[' + Gnubby.hexCid(client.cid) + '] left?')); } } - if (changes) this.clients = remaining; + if (changes) + this.clients = remaining; }; /** @@ -136,7 +138,8 @@ */ HidGnubbyDevice.prototype.registerClient = function(who) { for (var i = 0; i < this.clients.length; ++i) { - if (this.clients[i] === who) return; // Already registered. + if (this.clients[i] === who) + return; // Already registered. } this.clients.push(who); if (this.clients.length == 1) { @@ -154,11 +157,13 @@ */ HidGnubbyDevice.prototype.deregisterClient = function(who) { var current = this.clients; - if (current.length == 0) return -1; + if (current.length == 0) + return -1; this.clients = []; for (var i = 0; i < current.length; ++i) { var client = current[i]; - if (client !== who) this.clients.push(client); + if (client !== who) + this.clients.push(client); } return this.clients.length; }; @@ -168,7 +173,8 @@ * @return {boolean} Whether this device has who as a client. */ HidGnubbyDevice.prototype.hasClient = function(who) { - if (this.clients.length == 0) return false; + if (this.clients.length == 0) + return false; for (var i = 0; i < this.clients.length; ++i) { if (who === this.clients[i]) return true; @@ -181,8 +187,9 @@ * @private */ HidGnubbyDevice.prototype.readLoop_ = function() { - //console.log(UTIL_fmt('entering readLoop')); - if (!this.dev) return; + // console.log(UTIL_fmt('entering readLoop')); + if (!this.dev) + return; if (this.closing) { this.destroy(); @@ -211,24 +218,25 @@ } var self = this; - chrome.hid.receive( - this.dev.connectionId, - function(report_id, data) { - if (chrome.runtime.lastError || !data) { - console.log(UTIL_fmt('receive got lastError:')); - console.log(UTIL_fmt(chrome.runtime.lastError.message)); - window.setTimeout(function() { self.destroy(); }, 0); - return; - } - var u8 = new Uint8Array(data); - console.log(UTIL_fmt('<' + UTIL_BytesToHex(u8))); - - self.publishFrame_(data); - - // Read more. - window.setTimeout(function() { self.readLoop_(); }, 0); + chrome.hid.receive(this.dev.connectionId, function(report_id, data) { + if (chrome.runtime.lastError || !data) { + console.log(UTIL_fmt('receive got lastError:')); + console.log(UTIL_fmt(chrome.runtime.lastError.message)); + window.setTimeout(function() { + self.destroy(); + }, 0); + return; } - ); + var u8 = new Uint8Array(data); + console.log(UTIL_fmt('<' + UTIL_BytesToHex(u8))); + + self.publishFrame_(data); + + // Read more. + window.setTimeout(function() { + self.readLoop_(); + }, 0); + }); }; /** @@ -244,17 +252,13 @@ if (this.lockCID != cid) { // Some other channel has active lock. - if (cmd != GnubbyDevice.CMD_SYNC && - cmd != GnubbyDevice.CMD_INIT) { + if (cmd != GnubbyDevice.CMD_SYNC && cmd != GnubbyDevice.CMD_INIT) { // Anything but SYNC|INIT gets an immediate busy. - var busy = new Uint8Array( - [(cid >> 24) & 255, - (cid >> 16) & 255, - (cid >> 8) & 255, - cid & 255, - GnubbyDevice.CMD_ERROR, - 0, 1, // length - GnubbyDevice.BUSY]); + var busy = new Uint8Array([ + (cid >> 24) & 255, (cid >> 16) & 255, (cid >> 8) & 255, cid & 255, + GnubbyDevice.CMD_ERROR, 0, 1, // length + GnubbyDevice.BUSY + ]); // Log the synthetic busy too. console.log(UTIL_fmt('<' + UTIL_BytesToHex(busy))); this.publishFrame_(busy.buffer); @@ -299,14 +303,12 @@ // (re)set the lock timeout if we still hold it. if (this.lockCID) { var self = this; - this.lockTID = window.setTimeout( - function() { - console.warn(UTIL_fmt( - 'lock for CID ' + Gnubby.hexCid(cid) + ' expired!')); - self.lockTID = null; - self.lockCID = 0; - }, - this.lockMillis); + this.lockTID = window.setTimeout(function() { + console.warn( + UTIL_fmt('lock for CID ' + Gnubby.hexCid(cid) + ' expired!')); + self.lockTID = null; + self.lockCID = 0; + }, this.lockMillis); } } }; @@ -319,8 +321,10 @@ * @param {ArrayBuffer|Uint8Array} data Command arguments */ HidGnubbyDevice.prototype.queueCommand = function(cid, cmd, data) { - if (!this.dev) return; - if (!this.checkLock_(cid, cmd)) return; + if (!this.dev) + return; + if (!this.checkLock_(cid, cmd)) + return; var u8 = new Uint8Array(data); var f = new Uint8Array(64); @@ -377,7 +381,8 @@ this.updateLock_(cid, cmd, arg); var wasEmpty = (this.txqueue.length == 0); this.txqueue.push(frame); - if (wasEmpty) this.writePump_(); + if (wasEmpty) + this.writePump_(); }; /** @@ -385,9 +390,11 @@ * @private */ HidGnubbyDevice.prototype.writePump_ = function() { - if (!this.dev) return; // Ignore. + if (!this.dev) + return; // Ignore. - if (this.txqueue.length == 0) return; // Done with current queue. + if (this.txqueue.length == 0) + return; // Done with current queue. var frame = this.txqueue[0]; @@ -396,12 +403,16 @@ if (chrome.runtime.lastError) { console.log(UTIL_fmt('send got lastError:')); console.log(UTIL_fmt(chrome.runtime.lastError.message)); - window.setTimeout(function() { self.destroy(); }, 0); + window.setTimeout(function() { + self.destroy(); + }, 0); return; } self.txqueue.shift(); // drop sent frame from queue. if (self.txqueue.length != 0) { - window.setTimeout(function() { self.writePump_(); }, 0); + window.setTimeout(function() { + self.writePump_(); + }, 0); } } @@ -409,7 +420,7 @@ // See whether this requires scrubbing before logging. var alternateLog = Gnubby.hasOwnProperty('redactRequestLog') && - Gnubby['redactRequestLog'](u8); + Gnubby['redactRequestLog'](u8); if (alternateLog) { console.log(UTIL_fmt('>' + alternateLog)); } else { @@ -424,9 +435,7 @@ chrome.hid.send( this.dev.connectionId, 0, // report Id. Must be 0 for our use. - u8f.buffer, - transferComplete - ); + u8f.buffer, transferComplete); }; /** @@ -436,7 +445,7 @@ * @const */ HidGnubbyDevice.HID_VID_PIDS = [ - {'vendorId': 4176, 'productId': 512} // Google-specific Yubico HID + {'vendorId': 4176, 'productId': 512} // Google-specific Yubico HID ]; /** @@ -485,8 +494,8 @@ if (opt_type == GnubbyEnumerationTypes.VID_PID) { enumerated(f1d0Filter, []); } else { - chrome.hid.getDevices({filters: [f1d0Filter]}, - enumerated.bind(null, f1d0Filter)); + chrome.hid.getDevices( + {filters: [f1d0Filter]}, enumerated.bind(null, f1d0Filter)); } // Pass 2: vid/pid-based enumeration, for legacy devices. If FIDO devices // are asked for, "implement" this pass by providing it the empty list.
diff --git a/chrome/browser/resources/cryptotoken/individualattest.js b/chrome/browser/resources/cryptotoken/individualattest.js index ed6ea91..2fd77d2 100644 --- a/chrome/browser/resources/cryptotoken/individualattest.js +++ b/chrome/browser/resources/cryptotoken/individualattest.js
@@ -20,5 +20,5 @@ * @return {boolean} Whether to request the individual attestation certificate * for this app id. */ -IndividualAttestation.prototype.requestIndividualAttestation = - function(appIdHash) {}; +IndividualAttestation.prototype.requestIndividualAttestation = function( + appIdHash) {};
diff --git a/chrome/browser/resources/cryptotoken/inherits.js b/chrome/browser/resources/cryptotoken/inherits.js index 5fafea41..299058c 100644 --- a/chrome/browser/resources/cryptotoken/inherits.js +++ b/chrome/browser/resources/cryptotoken/inherits.js
@@ -12,8 +12,7 @@ // Closure. function inherits(childCtor, parentCtor) { /** @constructor */ - function tempCtor() { - } + function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.prototype = new tempCtor; childCtor.prototype.constructor = childCtor;
diff --git a/chrome/browser/resources/cryptotoken/multiplesigner.js b/chrome/browser/resources/cryptotoken/multiplesigner.js index 1c4ffc2..1fa9903 100644 --- a/chrome/browser/resources/cryptotoken/multiplesigner.js +++ b/chrome/browser/resources/cryptotoken/multiplesigner.js
@@ -41,8 +41,8 @@ * @param {string=} opt_logMsgUrl A URL to post log messages to. * @constructor */ -function MultipleGnubbySigner(forEnroll, allCompleteCb, gnubbyCompleteCb, - timeoutMillis, opt_logMsgUrl) { +function MultipleGnubbySigner( + forEnroll, allCompleteCb, gnubbyCompleteCb, timeoutMillis, opt_logMsgUrl) { /** @private {boolean} */ this.forEnroll_ = forEnroll; /** @private {function(boolean)} */ @@ -63,11 +63,11 @@ /** @private {!Object<string, GnubbyTracker>} */ this.gnubbies_ = {}; /** @private {Countdown} */ - this.timer_ = DEVICE_FACTORY_REGISTRY.getCountdownFactory() - .createTimer(timeoutMillis); + this.timer_ = + DEVICE_FACTORY_REGISTRY.getCountdownFactory().createTimer(timeoutMillis); /** @private {Countdown} */ - this.reenumerateTimer_ = DEVICE_FACTORY_REGISTRY.getCountdownFactory() - .createTimer(timeoutMillis); + this.reenumerateTimer_ = + DEVICE_FACTORY_REGISTRY.getCountdownFactory().createTimer(timeoutMillis); } /** @@ -183,8 +183,8 @@ * there are no devices present. * @private */ -MultipleGnubbySigner.prototype.maybeReEnumerateGnubbies_ = - function(activeScan) { +MultipleGnubbySigner.prototype.maybeReEnumerateGnubbies_ = function( + activeScan) { if (this.reenumerateTimer_.expired()) { // If the timer is expired, call timeout_ if there aren't any still-running // gnubbies. (If there are some still running, the last will call timeout_ @@ -231,21 +231,13 @@ // Can't add the same gnubby twice. return false; } - var tracker = { - index: index, - errorStatus: 0, - stillGoing: false, - signer: null - }; + var tracker = {index: index, errorStatus: 0, stillGoing: false, signer: null}; tracker.signer = new SingleGnubbySigner( - gnubbyId, - this.forEnroll_, - this.signCompletedCallback_.bind(this, tracker), - this.timer_.clone(), + gnubbyId, this.forEnroll_, + this.signCompletedCallback_.bind(this, tracker), this.timer_.clone(), this.logMsgUrl_); this.gnubbies_[index] = tracker; - this.gnubbies_[index].stillGoing = - tracker.signer.doSign(this.challenges_); + this.gnubbies_[index].stillGoing = tracker.signer.doSign(this.challenges_); if (!this.gnubbies_[index].errorStatus) { this.gnubbies_[index].errorStatus = 0; } @@ -259,12 +251,11 @@ * @param {SingleSignerResult} result The result of the sign operation. * @private */ -MultipleGnubbySigner.prototype.signCompletedCallback_ = - function(tracker, result) { - console.log( - UTIL_fmt((result.code ? 'failure.' : 'success!') + - ' gnubby ' + tracker.index + - ' got code ' + result.code.toString(16))); +MultipleGnubbySigner.prototype.signCompletedCallback_ = function( + tracker, result) { + console.log(UTIL_fmt( + (result.code ? 'failure.' : 'success!') + ' gnubby ' + tracker.index + + ' got code ' + result.code.toString(16))); if (!tracker.stillGoing) { console.log(UTIL_fmt('gnubby ' + tracker.index + ' no longer running!')); // Shouldn't ever happen? Disregard. @@ -317,7 +308,8 @@ * @private */ MultipleGnubbySigner.prototype.timeout_ = function(anyPending) { - if (this.complete_) return; + if (this.complete_) + return; this.complete_ = true; // Defer notifying the caller that all are complete, in case the caller is // doing work in response to a gnubbyFound callback and has an inconsistent @@ -336,10 +328,11 @@ * outcome. * @private */ -MultipleGnubbySigner.prototype.notifyGnubbyComplete_ = - function(tracker, result, moreExpected) { - console.log(UTIL_fmt('gnubby ' + tracker.index + ' complete (' + - result.code.toString(16) + ')')); +MultipleGnubbySigner.prototype.notifyGnubbyComplete_ = function( + tracker, result, moreExpected) { + console.log(UTIL_fmt( + 'gnubby ' + tracker.index + ' complete (' + result.code.toString(16) + + ')')); var signResult = { 'code': result.code, 'gnubby': result.gnubby,
diff --git a/chrome/browser/resources/cryptotoken/requesthelper.js b/chrome/browser/resources/cryptotoken/requesthelper.js index 2c8052f..410fc02 100644 --- a/chrome/browser/resources/cryptotoken/requesthelper.js +++ b/chrome/browser/resources/cryptotoken/requesthelper.js
@@ -73,9 +73,6 @@ } else { type = opt_defaultType || 'unknown_type_reply'; } - var reply = { - 'type': type, - 'code': /** @type {number} */ (code) - }; + var reply = {'type': type, 'code': /** @type {number} */ (code)}; return reply; }
diff --git a/chrome/browser/resources/cryptotoken/requestqueue.js b/chrome/browser/resources/cryptotoken/requestqueue.js index a787e59..356a777 100644 --- a/chrome/browser/resources/cryptotoken/requestqueue.js +++ b/chrome/browser/resources/cryptotoken/requestqueue.js
@@ -85,7 +85,8 @@ this.head_ = token; this.tail_ = token; } else { - if (!this.tail_) throw 'Non-empty list missing tail'; + if (!this.tail_) + throw 'Non-empty list missing tail'; this.tail_.next = token; token.prev = this.tail_; this.tail_ = token; @@ -182,8 +183,8 @@ * @param {Countdown} timer Countdown timer * @return {QueuedRequestToken} A token for the request. */ -OriginKeyedRequestQueue.prototype.queueRequest = - function(appId, origin, beginCb, timer) { +OriginKeyedRequestQueue.prototype.queueRequest = function( + appId, origin, beginCb, timer) { var key = appId + ' ' + origin; if (!this.requests_.hasOwnProperty(key)) { this.requests_[key] = new RequestQueue(this.sysTimer_);
diff --git a/chrome/browser/resources/cryptotoken/sha256.js b/chrome/browser/resources/cryptotoken/sha256.js index ac9dbde4..9a0aded 100644 --- a/chrome/browser/resources/cryptotoken/sha256.js +++ b/chrome/browser/resources/cryptotoken/sha256.js
@@ -17,25 +17,22 @@ this._W = new Array(64); this._pad = new Array(64); this._k = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]; + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, + 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, + 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, + 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, + 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, + 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ]; this._pad[0] = 0x80; - for (var i = 1; i < 64; ++i) this._pad[i] = 0; + for (var i = 1; i < 64; ++i) + this._pad[i] = 0; this.reset(); } @@ -43,8 +40,9 @@ /** Reset the hasher */ SHA256.prototype.reset = function() { this._chain = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, + 0x1f83d9ab, 0x5be0cd19 + ]; this._inbuf = 0; this._total = 0; @@ -57,14 +55,14 @@ var W = this._W; var k = this._k; - function _rotr(w, r) { return ((w << (32 - r)) | (w >>> r)); } + function _rotr(w, r) { + return ((w << (32 - r)) | (w >>> r)); + } // get 16 big endian words for (var i = 0; i < 64; i += 4) { - var w = (buf[i] << 24) | - (buf[i + 1] << 16) | - (buf[i + 2] << 8) | - (buf[i + 3]); + var w = + (buf[i] << 24) | (buf[i + 1] << 16) | (buf[i + 2] << 8) | (buf[i + 3]); W[i / 4] = w; } @@ -116,7 +114,8 @@ * @param {Array<number>|Uint8Array} bytes The data * @param {number=} opt_length How many bytes to hash, if not all */ SHA256.prototype.update = function(bytes, opt_length) { - if (!opt_length) opt_length = bytes.length; + if (!opt_length) + opt_length = bytes.length; this._total += opt_length; for (var n = 0; n < opt_length; ++n) {
diff --git a/chrome/browser/resources/cryptotoken/signer.js b/chrome/browser/resources/cryptotoken/signer.js index 6a0fe53c..5a887719 100644 --- a/chrome/browser/resources/cryptotoken/signer.js +++ b/chrome/browser/resources/cryptotoken/signer.js
@@ -12,8 +12,8 @@ var gnubbySignRequestQueue; function initRequestQueue() { - gnubbySignRequestQueue = new OriginKeyedRequestQueue( - FACTORY_REGISTRY.getSystemTimer()); + gnubbySignRequestQueue = + new OriginKeyedRequestQueue(FACTORY_REGISTRY.getSystemTimer()); } /** @@ -29,15 +29,16 @@ var queuedSignRequest; function sendErrorResponse(error) { - sendResponseOnce(sentResponse, queuedSignRequest, + sendResponseOnce( + sentResponse, queuedSignRequest, makeU2fErrorResponse(request, error.errorCode, error.errorMessage), sendResponse); } function sendSuccessResponse(challenge, info, browserData) { var responseData = makeU2fSignResponseDataFromChallenge(challenge); - addSignatureAndBrowserDataToResponseData(responseData, info, browserData, - 'clientData'); + addSignatureAndBrowserDataToResponseData( + responseData, info, browserData, 'clientData'); var response = makeU2fSuccessResponse(request, responseData); sendResponseOnce(sentResponse, queuedSignRequest, response, sendResponse); } @@ -52,9 +53,8 @@ return null; } - queuedSignRequest = - validateAndEnqueueSignRequest( - sender, request, sendErrorResponse, sendSuccessResponse); + queuedSignRequest = validateAndEnqueueSignRequest( + sender, request, sendErrorResponse, sendSuccessResponse); return queuedSignRequest; } @@ -64,9 +64,7 @@ * @return {Object} The responseData object. */ function makeU2fSignResponseDataFromChallenge(challenge) { - var responseData = { - 'keyHandle': challenge['keyHandle'] - }; + var responseData = {'keyHandle': challenge['keyHandle']}; return responseData; } @@ -78,8 +76,8 @@ * @param {string} browserDataName The name of the browser data key in the * responseData object. */ -function addSignatureAndBrowserDataToResponseData(responseData, signatureData, - browserData, browserDataName) { +function addSignatureAndBrowserDataToResponseData( + responseData, signatureData, browserData, browserDataName) { responseData[browserDataName] = B64_encode(UTIL_StringToBytes(browserData)); responseData['signatureData'] = signatureData; } @@ -107,8 +105,8 @@ // The typecast is necessary because getSignChallenges can return undefined. // On the other hand, a valid sign request can't contain an undefined sign // challenge list, so the typecast is safe. - var signChallenges = /** @type {!Array<SignChallenge>} */ ( - getSignChallenges(request)); + var signChallenges = + /** @type {!Array<SignChallenge>} */ (getSignChallenges(request)); var appId; if (request['appId']) { appId = request['appId']; @@ -125,8 +123,8 @@ // Attenuate watchdog timeout value less than the signer's timeout, so the // watchdog only fires after the signer could reasonably have called back, // not before. - timeoutValueSeconds = attenuateTimeoutInSeconds(timeoutValueSeconds, - MINIMUM_TIMEOUT_ATTENUATION_SECONDS / 2); + timeoutValueSeconds = attenuateTimeoutInSeconds( + timeoutValueSeconds, MINIMUM_TIMEOUT_ATTENUATION_SECONDS / 2); var watchdog = new WatchdogRequestHandler(timeoutValueSeconds, timeout); var wrappedErrorCb = watchdog.wrapCallback(errorCb); var wrappedSuccessCb = watchdog.wrapCallback(successCb); @@ -137,14 +135,15 @@ // Queue sign requests from the same origin, to protect against simultaneous // sign-out on many tabs resulting in repeated sign-in requests. - var queuedSignRequest = new QueuedSignRequest(signChallenges, - timer, sender, wrappedErrorCb, wrappedSuccessCb, request['challenge'], - appId, logMsgUrl); + var queuedSignRequest = new QueuedSignRequest( + signChallenges, timer, sender, wrappedErrorCb, wrappedSuccessCb, + request['challenge'], appId, logMsgUrl); if (!gnubbySignRequestQueue) { initRequestQueue(); } - var requestToken = gnubbySignRequestQueue.queueRequest(appId, sender.origin, - queuedSignRequest.begin.bind(queuedSignRequest), timer); + var requestToken = gnubbySignRequestQueue.queueRequest( + appId, sender.origin, queuedSignRequest.begin.bind(queuedSignRequest), + timer); queuedSignRequest.setToken(requestToken); watchdog.setCloseable(queuedSignRequest); @@ -167,8 +166,8 @@ if (!hasAppId && (!signChallenges || !signChallenges.length)) { return false; } - return isValidSignChallengeArray(signChallenges, !hasDefaultChallenge, - !hasAppId); + return isValidSignChallengeArray( + signChallenges, !hasDefaultChallenge, !hasAppId); } /** @@ -185,8 +184,9 @@ * @constructor * @implements {Closeable} */ -function QueuedSignRequest(signChallenges, timer, sender, errorCb, - successCb, opt_defaultChallenge, opt_appId, opt_logMsgUrl) { +function QueuedSignRequest( + signChallenges, timer, sender, errorCb, successCb, opt_defaultChallenge, + opt_appId, opt_logMsgUrl) { /** @private {!Array<SignChallenge>} */ this.signChallenges_ = signChallenges; /** @private {Countdown} */ @@ -211,7 +211,8 @@ /** Closes this sign request. */ QueuedSignRequest.prototype.close = function() { - if (this.closed_) return; + if (this.closed_) + return; var hadBegunSigning = false; if (this.begun_ && this.signer_) { this.signer_.close(); @@ -249,11 +250,11 @@ } this.begun_ = true; this.setToken(token); - this.signer_ = new Signer(this.timer_, this.sender_, - this.signerFailed_.bind(this), this.signerSucceeded_.bind(this), - this.logMsgUrl_); - if (!this.signer_.setChallenges(this.signChallenges_, this.defaultChallenge_, - this.appId_)) { + this.signer_ = new Signer( + this.timer_, this.sender_, this.signerFailed_.bind(this), + this.signerSucceeded_.bind(this), this.logMsgUrl_); + if (!this.signer_.setChallenges( + this.signChallenges_, this.defaultChallenge_, this.appId_)) { token.complete(); this.errorCb_({errorCode: ErrorCodes.BAD_REQUEST}); } @@ -278,8 +279,8 @@ * @param {string} browserData Browser data JSON * @private */ -QueuedSignRequest.prototype.signerSucceeded_ = - function(challenge, info, browserData) { +QueuedSignRequest.prototype.signerSucceeded_ = function( + challenge, info, browserData) { this.token_.complete(); this.successCb_(challenge, info, browserData); }; @@ -318,8 +319,8 @@ // Allow http appIds for http origins. (Broken, but the caller deserves // what they get.) /** @private {boolean} */ - this.allowHttp_ = this.sender_.origin ? - this.sender_.origin.indexOf('http://') == 0 : false; + this.allowHttp_ = + this.sender_.origin ? this.sender_.origin.indexOf('http://') == 0 : false; /** @private {Closeable} */ this.handler_ = null; } @@ -332,8 +333,8 @@ * @param {string=} opt_appId The app id for the entire request. * @return {boolean} Whether the challenges could be set. */ -Signer.prototype.setChallenges = function(signChallenges, opt_defaultChallenge, - opt_appId) { +Signer.prototype.setChallenges = function( + signChallenges, opt_defaultChallenge, opt_appId) { if (this.challengesSet_ || this.done_) return false; if (this.timer_.expired()) { @@ -385,16 +386,13 @@ */ Signer.prototype.originChecked_ = function(appIds, result) { if (!result) { - var error = { - errorCode: ErrorCodes.BAD_REQUEST, - errorMessage: 'bad appId' - }; + var error = {errorCode: ErrorCodes.BAD_REQUEST, errorMessage: 'bad appId'}; this.notifyError_(error); return; } var appIdChecker = FACTORY_REGISTRY.getAppIdCheckerFactory().create(); - appIdChecker. - checkAppIds( + appIdChecker + .checkAppIds( this.timer_.clone(), this.sender_.origin, /** @type {!Array<string>} */ (appIds), this.allowHttp_, this.logMsgUrl_) @@ -409,10 +407,7 @@ */ Signer.prototype.appIdChecked_ = function(result) { if (!result) { - var error = { - errorCode: ErrorCodes.BAD_REQUEST, - errorMessage: 'bad appId' - }; + var error = {errorCode: ErrorCodes.BAD_REQUEST, errorMessage: 'bad appId'}; this.notifyError_(error); return; } @@ -443,22 +438,21 @@ } var keyHandle = challenge['keyHandle']; - var browserData = - makeSignBrowserData(serverChallenge, this.sender_.origin, - this.sender_.tlsChannelId); + var browserData = makeSignBrowserData( + serverChallenge, this.sender_.origin, this.sender_.tlsChannelId); this.browserData_[keyHandle] = browserData; this.serverChallenges_[keyHandle] = challenge; } - var encodedChallenges = encodeSignChallenges(this.signChallenges_, - this.defaultChallenge_, this.appId_, this.getChallengeHash_.bind(this)); + var encodedChallenges = encodeSignChallenges( + this.signChallenges_, this.defaultChallenge_, this.appId_, + this.getChallengeHash_.bind(this)); var timeoutSeconds = this.timer_.millisecondsUntilExpired() / 1000.0; - var request = makeSignHelperRequest(encodedChallenges, timeoutSeconds, - this.logMsgUrl_); - this.handler_ = - FACTORY_REGISTRY.getRequestHelper() - .getHandler(/** @type {HelperRequest} */ (request)); + var request = + makeSignHelperRequest(encodedChallenges, timeoutSeconds, this.logMsgUrl_); + this.handler_ = FACTORY_REGISTRY.getRequestHelper().getHandler( + /** @type {HelperRequest} */ (request)); if (!this.handler_) return false; return this.handler_.run(this.helperComplete_.bind(this)); @@ -541,8 +535,9 @@ if (reply.code) { var reportedError = mapDeviceStatusCodeToU2fError(reply.code); - console.log(UTIL_fmt('helper reported ' + reply.code.toString(16) + - ', returning ' + reportedError.errorCode)); + console.log(UTIL_fmt( + 'helper reported ' + reply.code.toString(16) + ', returning ' + + reportedError.errorCode)); this.notifyError_(reportedError); } else { if (this.logMsgUrl_ && opt_source) { @@ -555,7 +550,7 @@ // Notify with server-provided challenge, not the encoded one: the // server-provided challenge contains additional fields it relies on. var serverChallenge = this.serverChallenges_[key]; - this.notifySuccess_(serverChallenge, reply.responseData.signatureData, - browserData); + this.notifySuccess_( + serverChallenge, reply.responseData.signatureData, browserData); } };
diff --git a/chrome/browser/resources/cryptotoken/singlesigner.js b/chrome/browser/resources/cryptotoken/singlesigner.js index 9d53505..f9e46f0 100644 --- a/chrome/browser/resources/cryptotoken/singlesigner.js +++ b/chrome/browser/resources/cryptotoken/singlesigner.js
@@ -50,8 +50,8 @@ * @param {string=} opt_logMsgUrl A URL to post log messages to. * @constructor */ -function SingleGnubbySigner(gnubbyId, forEnroll, completeCb, timer, - opt_logMsgUrl) { +function SingleGnubbySigner( + gnubbyId, forEnroll, completeCb, timer, opt_logMsgUrl) { /** @private {GnubbyDeviceId} */ this.gnubbyId_ = gnubbyId; /** @private {SingleGnubbySigner.State} */ @@ -115,7 +115,8 @@ this.openCanceller_(); } - if (!this.gnubby_) return; + if (!this.gnubby_) + return; this.state_ = SingleGnubbySigner.State.CLOSING; this.gnubby_.closeWhenIdle(this.closed_.bind(this)); }; @@ -194,11 +195,8 @@ if (this.state_ == SingleGnubbySigner.State.INIT) { this.state_ = SingleGnubbySigner.State.OPENING; this.openCanceller_ = DEVICE_FACTORY_REGISTRY.getGnubbyFactory().openGnubby( - this.gnubbyId_, - this.forEnroll_, - this.openCallback_.bind(this), - appIdHash, - this.logMsgUrl_, + this.gnubbyId_, this.forEnroll_, this.openCallback_.bind(this), + appIdHash, this.logMsgUrl_, 'singlesigner.js:SingleGnubbySigner.prototype.open_'); } }; @@ -242,13 +240,11 @@ var self = this; window.setTimeout(function() { if (self.gnubby_) { - this.openCanceller_ = DEVICE_FACTORY_REGISTRY - .getGnubbyFactory().openGnubby( - self.gnubbyId_, - self.forEnroll_, - self.openCallback_.bind(self), - self.logMsgUrl_, - 'singlesigner.js:SingleGnubbySigner.prototype.openCallback_'); + this.openCanceller_ = + DEVICE_FACTORY_REGISTRY.getGnubbyFactory().openGnubby( + self.gnubbyId_, self.forEnroll_, + self.openCallback_.bind(self), self.logMsgUrl_, + 'singlesigner.js:SingleGnubbySigner.prototype.openCallback_'); } }, SingleGnubbySigner.OPEN_DELAY_MILLIS); } else { @@ -336,9 +332,9 @@ this.signCallback_(challengeIndex, DeviceStatusCodes.WRONG_DATA_STATUS); } else { var nowink = false; - this.gnubby_.sign(challengeHash, appIdHash, keyHandle, - this.signCallback_.bind(this, challengeIndex), - nowink); + this.gnubby_.sign( + challengeHash, appIdHash, keyHandle, + this.signCallback_.bind(this, challengeIndex), nowink); } }; @@ -348,7 +344,8 @@ * for this gnubby. */ SingleGnubbySigner.signErrorIndicatesInvalidKeyHandle = function(code) { - return (code == DeviceStatusCodes.WRONG_DATA_STATUS || + return ( + code == DeviceStatusCodes.WRONG_DATA_STATUS || code == DeviceStatusCodes.WRONG_LENGTH_STATUS || code == DeviceStatusCodes.INVALID_DATA_STATUS); }; @@ -360,10 +357,11 @@ * @param {ArrayBuffer=} opt_info Optional result data * @private */ -SingleGnubbySigner.prototype.signCallback_ = - function(challengeIndex, code, opt_info) { - console.log(UTIL_fmt('gnubby ' + JSON.stringify(this.gnubbyId_) + - ', challenge ' + challengeIndex + ' yielded ' + code.toString(16))); +SingleGnubbySigner.prototype.signCallback_ = function( + challengeIndex, code, opt_info) { + console.log(UTIL_fmt( + 'gnubby ' + JSON.stringify(this.gnubbyId_) + ', challenge ' + + challengeIndex + ' yielded ' + code.toString(16))); if (this.state_ != SingleGnubbySigner.State.SIGNING) { console.log(UTIL_fmt('already done!')); // We're done, the caller's no longer interested. @@ -399,7 +397,8 @@ // Lower bound on the minimum length, signature length can vary. var MIN_SIGNATURE_LENGTH = 7; if (!opt_info || opt_info.byteLength < MIN_SIGNATURE_LENGTH) { - console.error(UTIL_fmt('Got short response to sign request (' + + console.error(UTIL_fmt( + 'Got short response to sign request (' + (opt_info ? opt_info.byteLength : 0) + ' bytes), WTF?')); } if (this.forEnroll_) { @@ -462,7 +461,7 @@ this.state_ = SingleGnubbySigner.State.COMPLETE; var logFn = opt_warn ? console.warn.bind(console) : console.log.bind(console); logFn(UTIL_fmt('failed (' + code.toString(16) + ')')); - var result = { code: code }; + var result = {code: code}; if (!this.forEnroll_ && SingleGnubbySigner.signErrorIndicatesInvalidKeyHandle(code)) { // When a device yields an idempotent bad key handle error to all sign @@ -486,11 +485,11 @@ * @param {ArrayBuffer=} opt_info Optional result data * @private */ -SingleGnubbySigner.prototype.goToSuccess_ = - function(code, opt_challenge, opt_info) { +SingleGnubbySigner.prototype.goToSuccess_ = function( + code, opt_challenge, opt_info) { this.state_ = SingleGnubbySigner.State.COMPLETE; console.log(UTIL_fmt('success (' + code.toString(16) + ')')); - var result = { code: code, gnubby: this.gnubby_ }; + var result = {code: code, gnubby: this.gnubby_}; if (opt_challenge || opt_info) { if (opt_challenge) { result['challenge'] = opt_challenge;
diff --git a/chrome/browser/resources/cryptotoken/textfetcher.js b/chrome/browser/resources/cryptotoken/textfetcher.js index d6e1884..103fa8b9 100644 --- a/chrome/browser/resources/cryptotoken/textfetcher.js +++ b/chrome/browser/resources/cryptotoken/textfetcher.js
@@ -28,8 +28,7 @@ * @constructor * @implements {TextFetcher} */ -function XhrTextFetcher() { -} +function XhrTextFetcher() {} /** * @param {string} url The URL to fetch.
diff --git a/chrome/browser/resources/cryptotoken/usbenrollhandler.js b/chrome/browser/resources/cryptotoken/usbenrollhandler.js index cf113d2..e9bdcc11 100644 --- a/chrome/browser/resources/cryptotoken/usbenrollhandler.js +++ b/chrome/browser/resources/cryptotoken/usbenrollhandler.js
@@ -37,21 +37,18 @@ * @return {boolean} Whether this handler could be run. */ UsbEnrollHandler.prototype.run = function(cb) { - var timeoutMillis = - this.request_.timeoutSeconds ? + var timeoutMillis = this.request_.timeoutSeconds ? this.request_.timeoutSeconds * 1000 : UsbEnrollHandler.DEFAULT_TIMEOUT_MILLIS; /** @private {Countdown} */ - this.timer_ = DEVICE_FACTORY_REGISTRY.getCountdownFactory().createTimer( - timeoutMillis); + this.timer_ = + DEVICE_FACTORY_REGISTRY.getCountdownFactory().createTimer(timeoutMillis); this.enrollChallenges = this.request_.enrollChallenges; /** @private {RequestHandlerCallback} */ this.cb_ = cb; this.signer_ = new MultipleGnubbySigner( - true /* forEnroll */, - this.signerCompleted_.bind(this), - this.signerFoundGnubby_.bind(this), - timeoutMillis, + true /* forEnroll */, this.signerCompleted_.bind(this), + this.signerFoundGnubby_.bind(this), timeoutMillis, this.request_.logMsgUrl); return this.signer_.doSign(this.request_.signData); }; @@ -91,15 +88,15 @@ * results from more gnubbies. * @private */ -UsbEnrollHandler.prototype.signerFoundGnubby_ = - function(signResult, moreExpected) { +UsbEnrollHandler.prototype.signerFoundGnubby_ = function( + signResult, moreExpected) { if (!signResult.code) { // If the signer reports a gnubby can sign, report this immediately to the // caller, as the gnubby is already enrolled. Map ok to WRONG_DATA, so the // caller knows what to do. this.notifyError_(DeviceStatusCodes.WRONG_DATA_STATUS); } else if (SingleGnubbySigner.signErrorIndicatesInvalidKeyHandle( - signResult.code)) { + signResult.code)) { var gnubby = signResult['gnubby']; // A valid helper request contains at least one enroll challenge, so use // the app id hash from the first challenge. @@ -118,8 +115,8 @@ * @param {Gnubby=} opt_gnubby The gnubby whose prerequisites were checked. * @private */ -UsbEnrollHandler.prototype.gnubbyPrerequisitesChecked_ = - function(rc, opt_gnubby) { +UsbEnrollHandler.prototype.gnubbyPrerequisitesChecked_ = function( + rc, opt_gnubby) { if (rc || this.timer_.expired()) { // Do nothing: // If the timer is expired, the signerCompleted_ callback will indicate @@ -212,10 +209,10 @@ } var challengeValue = B64_decode(challenge['challengeHash']); var appIdHash = challenge['appIdHash']; - var individualAttest = - DEVICE_FACTORY_REGISTRY.getIndividualAttestation(). - requestIndividualAttestation(appIdHash); - gnubby.enroll(challengeValue, B64_decode(appIdHash), + var individualAttest = DEVICE_FACTORY_REGISTRY.getIndividualAttestation() + .requestIndividualAttestation(appIdHash); + gnubby.enroll( + challengeValue, B64_decode(appIdHash), this.enrollCallback_.bind(this, gnubby, version), individualAttest); }; @@ -242,25 +239,25 @@ * @param {ArrayBuffer=} infoArray Returned data * @private */ -UsbEnrollHandler.prototype.enrollCallback_ = - function(gnubby, version, code, infoArray) { +UsbEnrollHandler.prototype.enrollCallback_ = function( + gnubby, version, code, infoArray) { if (this.notified_) { // Enroll completed after previous success or failure. Disregard. return; } switch (code) { case -GnubbyDevice.GONE: - // Close this gnubby. - this.removeWaitingGnubby_(gnubby); - if (!this.waitingForTouchGnubbies_.length) { - // Last enroll attempt is complete and last gnubby is gone. - this.anyGnubbiesFound_ = false; - if (this.timer_.expired()) { - this.notifyError_(DeviceStatusCodes.TIMEOUT_STATUS); - } else if (this.signer_) { - this.signer_.reScanDevices(); - } + // Close this gnubby. + this.removeWaitingGnubby_(gnubby); + if (!this.waitingForTouchGnubbies_.length) { + // Last enroll attempt is complete and last gnubby is gone. + this.anyGnubbiesFound_ = false; + if (this.timer_.expired()) { + this.notifyError_(DeviceStatusCodes.TIMEOUT_STATUS); + } else if (this.signer_) { + this.signer_.reScanDevices(); } + } break; case DeviceStatusCodes.WAIT_TOUCH_STATUS: @@ -275,8 +272,8 @@ this.removeWaitingGnubby_(gnubby); if (!this.waitingForTouchGnubbies_.length) { // Last enroll attempt is complete: return this error. - console.log(UTIL_fmt('timeout (' + code.toString(16) + - ') enrolling')); + console.log( + UTIL_fmt('timeout (' + code.toString(16) + ') enrolling')); this.notifyError_(DeviceStatusCodes.TIMEOUT_STATUS); } } else { @@ -314,10 +311,7 @@ return; this.notified_ = true; this.close(); - var reply = { - 'type': 'enroll_helper_reply', - 'code': code - }; + var reply = {'type': 'enroll_helper_reply', 'code': code}; this.cb_(reply); };
diff --git a/chrome/browser/resources/cryptotoken/usbgnubbydevice.js b/chrome/browser/resources/cryptotoken/usbgnubbydevice.js index b97cf9bb..aeaaf85d 100644 --- a/chrome/browser/resources/cryptotoken/usbgnubbydevice.js +++ b/chrome/browser/resources/cryptotoken/usbgnubbydevice.js
@@ -27,10 +27,10 @@ this.outEndpoint = outEndpoint; this.txqueue = []; this.clients = []; - this.lockCID = 0; // channel ID of client holding a lock, if != 0. - this.lockMillis = 0; // current lock period. - this.lockTID = null; // timer id of lock timeout. - this.closing = false; // device to be closed by receive loop. + this.lockCID = 0; // channel ID of client holding a lock, if != 0. + this.lockMillis = 0; // current lock period. + this.lockTID = null; // timer id of lock timeout. + this.closing = false; // device to be closed by receive loop. this.updating = false; // device firmware is in final stage of updating. this.inTransferPending = false; this.outTransferPending = false; @@ -47,16 +47,16 @@ function closeLowLevelDevice(dev) { chrome.usb.releaseInterface(dev, 0, function() { if (chrome.runtime.lastError) { - console.warn(UTIL_fmt('Device ' + dev.handle + - ' couldn\'t be released:')); + console.warn( + UTIL_fmt('Device ' + dev.handle + ' couldn\'t be released:')); console.warn(UTIL_fmt(chrome.runtime.lastError.message)); return; } console.log(UTIL_fmt('Device ' + dev.handle + ' released')); chrome.usb.closeDevice(dev, function() { if (chrome.runtime.lastError) { - console.warn(UTIL_fmt('Device ' + dev.handle + - ' couldn\'t be closed:')); + console.warn( + UTIL_fmt('Device ' + dev.handle + ' couldn\'t be closed:')); console.warn(UTIL_fmt(chrome.runtime.lastError.message)); return; } @@ -65,7 +65,8 @@ }); } - if (!this.dev) return; // Already dead. + if (!this.dev) + return; // Already dead. this.gnubbies_.removeOpenDevice( {namespace: UsbGnubbyDevice.NAMESPACE, device: this.id}); @@ -78,15 +79,16 @@ // // Use magic CID 0 to address all. this.publishFrame_(new Uint8Array([ - 0, 0, 0, 0, // broadcast CID - GnubbyDevice.CMD_ERROR, - 0, 1, // length - GnubbyDevice.GONE]).buffer); + 0, 0, 0, 0, // broadcast CID + GnubbyDevice.CMD_ERROR, 0, 1, // length + GnubbyDevice.GONE + ]).buffer); // Set all clients to closed status and remove them. while (this.clients.length != 0) { var client = this.clients.shift(); - if (client) client.closed = true; + if (client) + client.closed = true; } if (this.lockTID) { @@ -136,11 +138,11 @@ remaining.push(client); } else { changes = true; - console.log(UTIL_fmt( - '[' + Gnubby.hexCid(client.cid) + '] left?')); + console.log(UTIL_fmt('[' + Gnubby.hexCid(client.cid) + '] left?')); } } - if (changes) this.clients = remaining; + if (changes) + this.clients = remaining; }; /** @@ -148,8 +150,10 @@ * @private */ UsbGnubbyDevice.prototype.readyToUse_ = function() { - if (this.closing) return false; - if (!this.dev) return false; + if (this.closing) + return false; + if (!this.dev) + return false; return true; }; @@ -159,20 +163,25 @@ * @private */ UsbGnubbyDevice.prototype.readOneReply_ = function() { - if (!this.readyToUse_()) return; // No point in continuing. - if (this.updating) return; // Do not bother waiting for final update reply. + if (!this.readyToUse_()) + return; // No point in continuing. + if (this.updating) + return; // Do not bother waiting for final update reply. var self = this; function inTransferComplete(x) { self.inTransferPending = false; - if (!self.readyToUse_()) return; // No point in continuing. + if (!self.readyToUse_()) + return; // No point in continuing. if (chrome.runtime.lastError) { console.warn(UTIL_fmt('in bulkTransfer got lastError: ')); console.warn(UTIL_fmt(chrome.runtime.lastError.message)); - window.setTimeout(function() { self.destroy(); }, 0); + window.setTimeout(function() { + self.destroy(); + }, 0); return; } @@ -183,25 +192,25 @@ self.publishFrame_(x.data); // Write another pending request, if any. - window.setTimeout( - function() { - self.txqueue.shift(); // Drop sent frame from queue. - self.writeOneRequest_(); - }, - 0); + window.setTimeout(function() { + self.txqueue.shift(); // Drop sent frame from queue. + self.writeOneRequest_(); + }, 0); } else { console.log(UTIL_fmt('no x.data!')); console.log(x); - window.setTimeout(function() { self.destroy(); }, 0); + window.setTimeout(function() { + self.destroy(); + }, 0); } } if (this.inTransferPending == false) { this.inTransferPending = true; chrome.usb.bulkTransfer( - /** @type {!chrome.usb.ConnectionHandle} */(this.dev), - { direction: 'in', endpoint: this.inEndpoint, length: 2048 }, - inTransferComplete); + /** @type {!chrome.usb.ConnectionHandle} */ (this.dev), + {direction: 'in', endpoint: this.inEndpoint, length: 2048}, + inTransferComplete); } else { throw 'inTransferPending!'; } @@ -213,7 +222,8 @@ */ UsbGnubbyDevice.prototype.registerClient = function(who) { for (var i = 0; i < this.clients.length; ++i) { - if (this.clients[i] === who) return; // Already registered. + if (this.clients[i] === who) + return; // Already registered. } this.clients.push(who); }; @@ -227,11 +237,13 @@ */ UsbGnubbyDevice.prototype.deregisterClient = function(who) { var current = this.clients; - if (current.length == 0) return -1; + if (current.length == 0) + return -1; this.clients = []; for (var i = 0; i < current.length; ++i) { var client = current[i]; - if (client !== who) this.clients.push(client); + if (client !== who) + this.clients.push(client); } return this.clients.length; }; @@ -241,7 +253,8 @@ * @return {boolean} Whether this device has who as a client. */ UsbGnubbyDevice.prototype.hasClient = function(who) { - if (this.clients.length == 0) return false; + if (this.clients.length == 0) + return false; for (var i = 0; i < this.clients.length; ++i) { if (who === this.clients[i]) return true; @@ -254,9 +267,11 @@ * @private */ UsbGnubbyDevice.prototype.writeOneRequest_ = function() { - if (!this.readyToUse_()) return; // No point in continuing. + if (!this.readyToUse_()) + return; // No point in continuing. - if (this.txqueue.length == 0) return; // Nothing to send. + if (this.txqueue.length == 0) + return; // Nothing to send. var frame = this.txqueue[0]; @@ -264,23 +279,28 @@ function OutTransferComplete(x) { self.outTransferPending = false; - if (!self.readyToUse_()) return; // No point in continuing. + if (!self.readyToUse_()) + return; // No point in continuing. if (chrome.runtime.lastError) { console.warn(UTIL_fmt('out bulkTransfer lastError: ')); console.warn(UTIL_fmt(chrome.runtime.lastError.message)); - window.setTimeout(function() { self.destroy(); }, 0); + window.setTimeout(function() { + self.destroy(); + }, 0); return; } - window.setTimeout(function() { self.readOneReply_(); }, 0); + window.setTimeout(function() { + self.readOneReply_(); + }, 0); } var u8 = new Uint8Array(frame); // See whether this requires scrubbing before logging. var alternateLog = Gnubby.hasOwnProperty('redactRequestLog') && - Gnubby['redactRequestLog'](u8); + Gnubby['redactRequestLog'](u8); if (alternateLog) { console.log(UTIL_fmt('>' + alternateLog)); } else { @@ -290,8 +310,8 @@ if (this.outTransferPending == false) { this.outTransferPending = true; chrome.usb.bulkTransfer( - /** @type {!chrome.usb.ConnectionHandle} */(this.dev), - { direction: 'out', endpoint: this.outEndpoint, data: frame }, + /** @type {!chrome.usb.ConnectionHandle} */ (this.dev), + {direction: 'out', endpoint: this.outEndpoint, data: frame}, OutTransferComplete); } else { throw 'outTransferPending!'; @@ -311,17 +331,13 @@ if (this.lockCID != cid) { // Some other channel has active lock. - if (cmd != GnubbyDevice.CMD_SYNC && - cmd != GnubbyDevice.CMD_INIT) { + if (cmd != GnubbyDevice.CMD_SYNC && cmd != GnubbyDevice.CMD_INIT) { // Anything but SYNC|INIT gets an immediate busy. - var busy = new Uint8Array( - [(cid >> 24) & 255, - (cid >> 16) & 255, - (cid >> 8) & 255, - cid & 255, - GnubbyDevice.CMD_ERROR, - 0, 1, // length - GnubbyDevice.BUSY]); + var busy = new Uint8Array([ + (cid >> 24) & 255, (cid >> 16) & 255, (cid >> 8) & 255, cid & 255, + GnubbyDevice.CMD_ERROR, 0, 1, // length + GnubbyDevice.BUSY + ]); // Log the synthetic busy too. console.log(UTIL_fmt('<' + UTIL_BytesToHex(busy))); this.publishFrame_(busy.buffer); @@ -366,14 +382,12 @@ // (re)set the lock timeout if we still hold it. if (this.lockCID) { var self = this; - this.lockTID = window.setTimeout( - function() { - console.warn(UTIL_fmt( - 'lock for CID ' + Gnubby.hexCid(cid) + ' expired!')); - self.lockTID = null; - self.lockCID = 0; - }, - this.lockMillis); + this.lockTID = window.setTimeout(function() { + console.warn( + UTIL_fmt('lock for CID ' + Gnubby.hexCid(cid) + ' expired!')); + self.lockTID = null; + self.lockCID = 0; + }, this.lockMillis); } } }; @@ -386,8 +400,10 @@ * @param {ArrayBuffer|Uint8Array} data Command argument data */ UsbGnubbyDevice.prototype.queueCommand = function(cid, cmd, data) { - if (!this.dev) return; - if (!this.checkLock_(cid, cmd)) return; + if (!this.dev) + return; + if (!this.checkLock_(cid, cmd)) + return; var u8 = new Uint8Array(data); var frame = new Uint8Array(u8.length + 7); @@ -407,14 +423,15 @@ var wasEmpty = (this.txqueue.length == 0); this.txqueue.push(frame.buffer); - if (wasEmpty) this.writeOneRequest_(); + if (wasEmpty) + this.writeOneRequest_(); }; /** * @const */ UsbGnubbyDevice.WINUSB_VID_PIDS = [ - {'vendorId': 4176, 'productId': 529} // Yubico WinUSB + {'vendorId': 4176, 'productId': 529} // Yubico WinUSB ]; /** @@ -538,8 +555,8 @@ if (enumeratedBy) { dev.enumeratedBy = enumeratedBy; } - var gnubby = new UsbGnubbyDevice(gnubbies, nonNullHandle, which, - inEndpoint, outEndpoint); + var gnubby = new UsbGnubbyDevice( + gnubbies, nonNullHandle, which, inEndpoint, outEndpoint); cb(-GnubbyDevice.OK, gnubby); }); });
diff --git a/chrome/browser/resources/cryptotoken/usbgnubbyfactory.js b/chrome/browser/resources/cryptotoken/usbgnubbyfactory.js index 20c6410..dd35395 100644 --- a/chrome/browser/resources/cryptotoken/usbgnubbyfactory.js +++ b/chrome/browser/resources/cryptotoken/usbgnubbyfactory.js
@@ -31,8 +31,8 @@ * @return {undefined} no open canceller needed for this type of gnubby * @override */ -UsbGnubbyFactory.prototype.openGnubby = - function(which, forEnroll, cb, opt_appIdHash, opt_logMsgUrl, opt_caller) { +UsbGnubbyFactory.prototype.openGnubby = function( + which, forEnroll, cb, opt_appIdHash, opt_logMsgUrl, opt_caller) { var gnubby = new Gnubby(); gnubby.open(which, GnubbyEnumerationTypes.ANY, function(rc) { if (rc) { @@ -61,7 +61,7 @@ * @param {FactoryOpenCallback} cb Called with the result of the prerequisite * check. (A non-zero status indicates failure.) */ -UsbGnubbyFactory.prototype.notEnrolledPrerequisiteCheck = - function(gnubby, appIdHash, cb) { +UsbGnubbyFactory.prototype.notEnrolledPrerequisiteCheck = function( + gnubby, appIdHash, cb) { cb(DeviceStatusCodes.OK_STATUS, gnubby); };
diff --git a/chrome/browser/resources/cryptotoken/usbsignhandler.js b/chrome/browser/resources/cryptotoken/usbsignhandler.js index 57d2358..7493ced 100644 --- a/chrome/browser/resources/cryptotoken/usbsignhandler.js +++ b/chrome/browser/resources/cryptotoken/usbsignhandler.js
@@ -49,16 +49,13 @@ // Fail a sign request with an empty set of challenges. return false; } - var timeoutMillis = - this.request_.timeoutSeconds ? + var timeoutMillis = this.request_.timeoutSeconds ? this.request_.timeoutSeconds * 1000 : UsbSignHandler.DEFAULT_TIMEOUT_MILLIS; /** @private {MultipleGnubbySigner} */ this.signer_ = new MultipleGnubbySigner( - false /* forEnroll */, - this.signerCompleted_.bind(this), - this.signerFoundGnubby_.bind(this), - timeoutMillis, + false /* forEnroll */, this.signerCompleted_.bind(this), + this.signerFoundGnubby_.bind(this), timeoutMillis, this.request_.logMsgUrl); return this.signer_.doSign(this.request_.signData); }; @@ -88,8 +85,8 @@ * results. * @private */ -UsbSignHandler.prototype.signerFoundGnubby_ = - function(signResult, moreExpected) { +UsbSignHandler.prototype.signerFoundGnubby_ = function( + signResult, moreExpected) { this.anyGnubbiesFound_ = true; if (!signResult.code) { var gnubby = signResult['gnubby']; @@ -97,7 +94,7 @@ var info = new Uint8Array(signResult['info']); this.notifySuccess_(gnubby, challenge, info); } else if (SingleGnubbySigner.signErrorIndicatesInvalidKeyHandle( - signResult.code)) { + signResult.code)) { var gnubby = signResult['gnubby']; this.notEnrolledGnubbies_.push(gnubby); this.sendBogusEnroll_(gnubby); @@ -115,31 +112,25 @@ /** @const */ UsbSignHandler.BOGUS_APP_ID_HASH = [ - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, - 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, + 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41 ]; /** @const */ UsbSignHandler.BOGUS_CHALLENGE_V1 = [ - 0x04, 0xA2, 0x24, 0x7D, 0x5C, 0x0B, 0x76, 0xF1, - 0xDC, 0xCD, 0x44, 0xAF, 0x91, 0x9A, 0xA2, 0x3F, - 0x3F, 0xBA, 0x65, 0x9F, 0x06, 0x78, 0x82, 0xFB, - 0x93, 0x4B, 0xBF, 0x86, 0x55, 0x95, 0x66, 0x46, - 0x76, 0x90, 0xDC, 0xE1, 0xE8, 0x6C, 0x86, 0x86, - 0xC3, 0x03, 0x4E, 0x65, 0x52, 0x4C, 0x32, 0x6F, - 0xB6, 0x44, 0x0D, 0x50, 0xF9, 0x16, 0xC0, 0xA3, - 0xDA, 0x31, 0x4B, 0xD3, 0x3F, 0x94, 0xA5, 0xF1, - 0xD3 + 0x04, 0xA2, 0x24, 0x7D, 0x5C, 0x0B, 0x76, 0xF1, 0xDC, 0xCD, 0x44, 0xAF, 0x91, + 0x9A, 0xA2, 0x3F, 0x3F, 0xBA, 0x65, 0x9F, 0x06, 0x78, 0x82, 0xFB, 0x93, 0x4B, + 0xBF, 0x86, 0x55, 0x95, 0x66, 0x46, 0x76, 0x90, 0xDC, 0xE1, 0xE8, 0x6C, 0x86, + 0x86, 0xC3, 0x03, 0x4E, 0x65, 0x52, 0x4C, 0x32, 0x6F, 0xB6, 0x44, 0x0D, 0x50, + 0xF9, 0x16, 0xC0, 0xA3, 0xDA, 0x31, 0x4B, 0xD3, 0x3F, 0x94, 0xA5, 0xF1, 0xD3 ]; /** @const */ UsbSignHandler.BOGUS_CHALLENGE_V2 = [ - 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, - 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, - 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, - 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42 + 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, + 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, + 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42 ]; /** @@ -241,10 +232,7 @@ return; this.notified_ = true; this.close(); - var reply = { - 'type': 'sign_helper_reply', - 'code': code - }; + var reply = {'type': 'sign_helper_reply', 'code': code}; this.cb_(reply); };
diff --git a/chrome/browser/resources/cryptotoken/util.js b/chrome/browser/resources/cryptotoken/util.js index e5c6233..73ede95 100644 --- a/chrome/browser/resources/cryptotoken/util.js +++ b/chrome/browser/resources/cryptotoken/util.js
@@ -34,7 +34,8 @@ * @return {string} result. */ function UTIL_BytesToHex(b) { - if (!b) return '(null)'; + if (!b) + return '(null)'; var hexchars = '0123456789ABCDEF'; var hexrep = new Array(b.length * 2); @@ -51,7 +52,8 @@ var hexrep = new Array(b.length * stride); for (var i = 0; i < b.length; ++i) { - if (sep) hexrep[i * stride + 0] = sep; + if (sep) + hexrep[i * stride + 0] = sep; hexrep[i * stride + stride - 2] = hexchars.charAt((b[i] >> 4) & 15); hexrep[i * stride + stride - 1] = hexchars.charAt(b[i] & 15); } @@ -62,7 +64,8 @@ var hexchars = '0123456789ABCDEFabcdef'; var res = new Uint8Array(h.length / 2); for (var i = 0; i < h.length; i += 2) { - if (hexchars.indexOf(h.substring(i, i + 1)) == -1) break; + if (hexchars.indexOf(h.substring(i, i + 1)) == -1) + break; res[i / 2] = parseInt(h.substring(i, i + 2), 16); } return res; @@ -72,15 +75,18 @@ var hexchars = '0123456789ABCDEFabcdef'; var res = new Array(h.length / 2); for (var i = 0; i < h.length; i += 2) { - if (hexchars.indexOf(h.substring(i, i + 1)) == -1) break; + if (hexchars.indexOf(h.substring(i, i + 1)) == -1) + break; res[i / 2] = parseInt(h.substring(i, i + 2), 16); } return res; } function UTIL_equalArrays(a, b) { - if (!a || !b) return false; - if (a.length != b.length) return false; + if (!a || !b) + return false; + if (a.length != b.length) + return false; var accu = 0; for (var i = 0; i < a.length; ++i) accu |= a[i] ^ b[i]; @@ -88,11 +94,15 @@ } function UTIL_ltArrays(a, b) { - if (a.length < b.length) return true; - if (a.length > b.length) return false; + if (a.length < b.length) + return true; + if (a.length > b.length) + return false; for (var i = 0; i < a.length; ++i) { - if (a[i] < b[i]) return true; - if (a[i] > b[i]) return false; + if (a[i] < b[i]) + return true; + if (a[i] > b[i]) + return false; } return false; } @@ -124,7 +134,8 @@ var tmp = new Array(a); var rnd = new Uint8Array(a); window.crypto.getRandomValues(rnd); // Yay! - for (var i = 0; i < a; ++i) tmp[i] = rnd[i] & 255; + for (var i = 0; i < a; ++i) + tmp[i] = rnd[i] & 255; return tmp; } @@ -169,25 +180,34 @@ * @return {{'r': !Array<number>, 's': !Array<number>}|null} */ function UTIL_Asn1SignatureToJson(a) { - if (a.length < 6) return null; // Too small to be valid - if (a[0] != UTIL_ASN_SEQUENCE) return null; + if (a.length < 6) + return null; // Too small to be valid + if (a[0] != UTIL_ASN_SEQUENCE) + return null; var l = a[1] & 255; - if (l & 0x80) return null; // SEQ.size too large - if (a.length != 2 + l) return null; // SEQ size does not match input + if (l & 0x80) + return null; // SEQ.size too large + if (a.length != 2 + l) + return null; // SEQ size does not match input function parseInt(off) { - if (a[off] != UTIL_ASN_INT) return null; + if (a[off] != UTIL_ASN_INT) + return null; var l = a[off + 1] & 255; - if (l & 0x80) return null; // INT.size too large - if (off + 2 + l > a.length) return null; // Out of bounds + if (l & 0x80) + return null; // INT.size too large + if (off + 2 + l > a.length) + return null; // Out of bounds return a.slice(off + 2, off + 2 + l); } var r = parseInt(2); - if (!r) return null; + if (!r) + return null; var s = parseInt(2 + 2 + r.length); - if (!s) return null; + if (!s) + return null; return {'r': r, 's': s}; } @@ -228,7 +248,8 @@ } function UTIL_prepend_zero(s, n) { - if (s.length == n) return s; + if (s.length == n) + return s; var l = s.length; for (var i = 0; i < n - l; ++i) { s = '0' + s;
diff --git a/chrome/browser/resources/cryptotoken/webrequest.js b/chrome/browser/resources/cryptotoken/webrequest.js index 6c77e3f..dc8f7a63 100644 --- a/chrome/browser/resources/cryptotoken/webrequest.js +++ b/chrome/browser/resources/cryptotoken/webrequest.js
@@ -22,7 +22,8 @@ function getOriginFromUrl(url) { var re = new RegExp('^(https?://)[^/]*/?'); var originarray = re.exec(url); - if (originarray == null) return originarray; + if (originarray == null) + return originarray; var origin = originarray[0]; while (origin.charAt(origin.length - 1) == '/') { origin = origin.substring(0, origin.length - 1); @@ -95,8 +96,8 @@ * each challenge. * @return {boolean} Whether the array appears valid. */ -function isValidSignChallengeArray(signChallenges, challengeValueRequired, - appIdRequired) { +function isValidSignChallengeArray( + signChallenges, challengeValueRequired, appIdRequired) { for (var i = 0; i < signChallenges.length; i++) { var incomingChallenge = signChallenges[i]; if (challengeValueRequired && @@ -125,15 +126,14 @@ return handleU2fSignRequest(sender, request, sendResponse); case MessageTypes.U2F_GET_API_VERSION_REQUEST: - sendResponse( - makeU2fGetApiVersionResponse(request, JS_API_VERSION, - MessageTypes.U2F_GET_API_VERSION_RESPONSE)); + sendResponse(makeU2fGetApiVersionResponse( + request, JS_API_VERSION, MessageTypes.U2F_GET_API_VERSION_RESPONSE)); return null; default: - sendResponse( - makeU2fErrorResponse(request, ErrorCodes.BAD_REQUEST, undefined, - MessageTypes.U2F_REGISTER_RESPONSE)); + sendResponse(makeU2fErrorResponse( + request, ErrorCodes.BAD_REQUEST, undefined, + MessageTypes.U2F_REGISTER_RESPONSE)); return null; } } @@ -153,7 +153,7 @@ } else { type = opt_defaultType; } - var reply = { 'type': type }; + var reply = {'type': type}; if (request && request.requestId) { reply.requestId = request.requestId; } @@ -299,9 +299,9 @@ */ function makeBrowserData(type, serverChallenge, origin, opt_tlsChannelId) { var browserData = { - 'typ' : type, - 'challenge' : serverChallenge, - 'origin' : origin + 'typ': type, + 'challenge': serverChallenge, + 'origin': origin }; if (BROWSER_SUPPORTS_TLS_CHANNEL_ID) { browserData['cid_pubkey'] = tlsChannelIdValue(opt_tlsChannelId); @@ -364,8 +364,9 @@ * used. * @return {!Array<SignHelperChallenge>} The sign challenges, encoded. */ -function encodeSignChallenges(signChallenges, opt_defaultChallenge, - opt_defaultAppId, opt_challengeHashFunction) { +function encodeSignChallenges( + signChallenges, opt_defaultChallenge, opt_defaultAppId, + opt_challengeHashFunction) { function encodedSha256(keyHandle, challenge) { return B64_encode(sha256HashOfString(challenge)); }
diff --git a/chrome/browser/resources/cryptotoken/webrequestsender.js b/chrome/browser/resources/cryptotoken/webrequestsender.js index 329a6ab4..69767762 100644 --- a/chrome/browser/resources/cryptotoken/webrequestsender.js +++ b/chrome/browser/resources/cryptotoken/webrequestsender.js
@@ -29,9 +29,7 @@ if (!origin) { return null; } - var sender = { - origin: origin - }; + var sender = {origin: origin}; if (messageSender.tlsChannelId) { sender.tlsChannelId = messageSender.tlsChannelId; } @@ -75,45 +73,52 @@ return Promise.resolve(true); } else { return new Promise(function(resolve, reject) { - chrome.tabs.query({active: true, lastFocusedWindow: true}, - function(tabs) { + chrome.tabs.query( + {active: true, lastFocusedWindow: true}, function(tabs) { if (!tabs.length) { // Safety check. reject(false); return; } var tab = tabs[0]; - tabMatchesOrigin(tab, sender.origin).then(function(tabId) { - sender.tabId = tabId; - resolve(true); - }, function() { - // Didn't match? Check if the debugger is open. - if (tab.url.indexOf('chrome-devtools://') != 0) { - reject(false); - return; - } - // Debugger active: find first tab with the sender's origin. - chrome.tabs.query({active: true}, function(tabs) { - if (!tabs.length) { - // Safety check. - reject(false); - return; - } - var numRejected = 0; - for (var i = 0; i < tabs.length; i++) { - tab = tabs[i]; - tabMatchesOrigin(tab, sender.origin).then(function(tabId) { - sender.tabId = tabId; - resolve(true); - }, function() { - if (++numRejected >= tabs.length) { - // None matches: reject. - reject(false); - } - }); - } - }); - }); + tabMatchesOrigin(tab, sender.origin) + .then( + function(tabId) { + sender.tabId = tabId; + resolve(true); + }, + function() { + // Didn't match? Check if the debugger is open. + if (tab.url.indexOf('chrome-devtools://') != 0) { + reject(false); + return; + } + // Debugger active: find first tab with the sender's + // origin. + chrome.tabs.query({active: true}, function(tabs) { + if (!tabs.length) { + // Safety check. + reject(false); + return; + } + var numRejected = 0; + for (var i = 0; i < tabs.length; i++) { + tab = tabs[i]; + tabMatchesOrigin(tab, sender.origin) + .then( + function(tabId) { + sender.tabId = tabId; + resolve(true); + }, + function() { + if (++numRejected >= tabs.length) { + // None matches: reject. + reject(false); + } + }); + } + }); + }); }); }); } @@ -127,26 +132,26 @@ */ function tabInForeground(tabId) { return new Promise(function(resolve, reject) { - if (!chrome.tabs || !chrome.tabs.get) { - reject(); + if (!chrome.tabs || !chrome.tabs.get) { + reject(); + return; + } + if (!chrome.windows || !chrome.windows.get) { + reject(); + return; + } + chrome.tabs.get(tabId, function(tab) { + if (chrome.runtime.lastError) { + resolve(false); return; } - if (!chrome.windows || !chrome.windows.get) { - reject(); + if (!tab.active) { + resolve(false); return; } - chrome.tabs.get(tabId, function(tab) { - if (chrome.runtime.lastError) { - resolve(false); - return; - } - if (!tab.active) { - resolve(false); - return; - } - chrome.windows.get(tab.windowId, function(aWindow) { - resolve(aWindow && aWindow.focused); - }); - }); + chrome.windows.get(tab.windowId, function(aWindow) { + resolve(aWindow && aWindow.focused); + }); + }); }); }
diff --git a/chrome/browser/resources/cryptotoken/window-timer.js b/chrome/browser/resources/cryptotoken/window-timer.js index 4f99d67..b5ad2a6 100644 --- a/chrome/browser/resources/cryptotoken/window-timer.js +++ b/chrome/browser/resources/cryptotoken/window-timer.js
@@ -14,8 +14,7 @@ * @constructor * @implements {SystemTimer} */ -function WindowTimer() { -} +function WindowTimer() {} /** * Sets a single-shot timer.
diff --git a/chrome/browser/resources/device_log_ui/device_log_ui.js b/chrome/browser/resources/device_log_ui/device_log_ui.js index acee79a..7472d8e6f 100644 --- a/chrome/browser/resources/device_log_ui/device_log_ui.js +++ b/chrome/browser/resources/device_log_ui/device_log_ui.js
@@ -63,10 +63,7 @@ else timestamp = logEntry['timestampshort']; textWrapper.textContent = loadTimeData.getStringF( - 'logEntryFormat', - timestamp, - fileinfo, - logEntry['event']); + 'logEntryFormat', timestamp, fileinfo, logEntry['event']); res.appendChild(createTypeTag(type)); res.appendChild(createLevelTag(level)); res.appendChild(textWrapper); @@ -97,7 +94,7 @@ var getLogCallback = function(data) { try { createEventLog(JSON.parse(data)); - } catch(e) { + } catch (e) { var container = $('log-container'); container.textContent = 'No log entries'; } @@ -148,7 +145,5 @@ requestLog(); }); - return { - getLogCallback: getLogCallback - }; + return {getLogCallback: getLogCallback}; })();
diff --git a/chrome/browser/resources/domain_reliability_internals.js b/chrome/browser/resources/domain_reliability_internals.js index aecd472..8d475fb4 100644 --- a/chrome/browser/resources/domain_reliability_internals.js +++ b/chrome/browser/resources/domain_reliability_internals.js
@@ -20,5 +20,5 @@ }; }); -document.addEventListener('DOMContentLoaded', - DomainReliabilityInternals.initialize); +document.addEventListener( + 'DOMContentLoaded', DomainReliabilityInternals.initialize);
diff --git a/chrome/browser/resources/engagement/site_engagement.js b/chrome/browser/resources/engagement/site_engagement.js index ae922df..c70ff186 100644 --- a/chrome/browser/resources/engagement/site_engagement.js +++ b/chrome/browser/resources/engagement/site_engagement.js
@@ -15,201 +15,209 @@ return pageIsPopulatedPromise; } -define('main', [ - 'chrome/browser/engagement/site_engagement_details.mojom', - 'content/public/renderer/frame_interfaces', -], (siteEngagementMojom, frameInterfaces) => { - return () => { - var uiHandler = new siteEngagementMojom.SiteEngagementDetailsProviderPtr( - frameInterfaces.getInterface( - siteEngagementMojom.SiteEngagementDetailsProvider.name)); +define( + 'main', + [ + 'chrome/browser/engagement/site_engagement_details.mojom', + 'content/public/renderer/frame_interfaces', + ], + (siteEngagementMojom, frameInterfaces) => { + return () => { + var uiHandler = + new siteEngagementMojom.SiteEngagementDetailsProviderPtr( + frameInterfaces.getInterface( + siteEngagementMojom.SiteEngagementDetailsProvider.name)); - var engagementTableBody = $('engagement-table-body'); - var updateInterval = null; - var info = null; - var sortKey = 'total_score'; - var sortReverse = true; + var engagementTableBody = $('engagement-table-body'); + var updateInterval = null; + var info = null; + var sortKey = 'total_score'; + var sortReverse = true; - // Set table header sort handlers. - var engagementTableHeader = $('engagement-table-header'); - var headers = engagementTableHeader.children; - for (var i = 0; i < headers.length; i++) { - headers[i].addEventListener('click', (e) => { - var newSortKey = e.target.getAttribute('sort-key'); - if (sortKey == newSortKey) { - sortReverse = !sortReverse; - } else { - sortKey = newSortKey; - sortReverse = false; + // Set table header sort handlers. + var engagementTableHeader = $('engagement-table-header'); + var headers = engagementTableHeader.children; + for (var i = 0; i < headers.length; i++) { + headers[i].addEventListener('click', (e) => { + var newSortKey = e.target.getAttribute('sort-key'); + if (sortKey == newSortKey) { + sortReverse = !sortReverse; + } else { + sortKey = newSortKey; + sortReverse = false; + } + var oldSortColumn = document.querySelector('.sort-column'); + oldSortColumn.classList.remove('sort-column'); + e.target.classList.add('sort-column'); + if (sortReverse) + e.target.setAttribute('sort-reverse', ''); + else + e.target.removeAttribute('sort-reverse'); + renderTable(); + }); } - var oldSortColumn = document.querySelector('.sort-column'); - oldSortColumn.classList.remove('sort-column'); - e.target.classList.add('sort-column'); - if (sortReverse) - e.target.setAttribute('sort-reverse', ''); - else - e.target.removeAttribute('sort-reverse'); - renderTable(); - }); - } - /** - * Creates a single row in the engagement table. - * @param {SiteEngagementDetails} info The info to create the row from. - * @return {HTMLElement} - */ - function createRow(info) { - var originCell = createElementWithClassName('td', 'origin-cell'); - originCell.textContent = info.origin.url; + /** + * Creates a single row in the engagement table. + * @param {SiteEngagementDetails} info The info to create the row from. + * @return {HTMLElement} + */ + function createRow(info) { + var originCell = createElementWithClassName('td', 'origin-cell'); + originCell.textContent = info.origin.url; - var baseScoreInput = createElementWithClassName('input', - 'base-score-input'); - baseScoreInput.addEventListener( - 'change', handleBaseScoreChange.bind(undefined, info.origin)); - baseScoreInput.addEventListener('focus', disableAutoupdate); - baseScoreInput.addEventListener('blur', enableAutoupdate); - baseScoreInput.value = info.base_score; + var baseScoreInput = + createElementWithClassName('input', 'base-score-input'); + baseScoreInput.addEventListener( + 'change', handleBaseScoreChange.bind(undefined, info.origin)); + baseScoreInput.addEventListener('focus', disableAutoupdate); + baseScoreInput.addEventListener('blur', enableAutoupdate); + baseScoreInput.value = info.base_score; - var baseScoreCell = createElementWithClassName('td', 'base-score-cell'); - baseScoreCell.appendChild(baseScoreInput); + var baseScoreCell = + createElementWithClassName('td', 'base-score-cell'); + baseScoreCell.appendChild(baseScoreInput); - var bonusScoreCell = createElementWithClassName('td', 'bonus-score-cell'); - bonusScoreCell.textContent = info.bonus_score; + var bonusScoreCell = + createElementWithClassName('td', 'bonus-score-cell'); + bonusScoreCell.textContent = info.bonus_score; - var totalScoreCell = createElementWithClassName('td', 'total-score-cell'); - totalScoreCell.textContent = info.total_score; + var totalScoreCell = + createElementWithClassName('td', 'total-score-cell'); + totalScoreCell.textContent = info.total_score; - var engagementBar = createElementWithClassName('div', 'engagement-bar'); - engagementBar.style.width = (info.total_score * 4) + 'px'; + var engagementBar = + createElementWithClassName('div', 'engagement-bar'); + engagementBar.style.width = (info.total_score * 4) + 'px'; - var engagementBarCell = - createElementWithClassName('td', 'engagement-bar-cell'); - engagementBarCell.appendChild(engagementBar); + var engagementBarCell = + createElementWithClassName('td', 'engagement-bar-cell'); + engagementBarCell.appendChild(engagementBar); - var row = document.createElement('tr'); - row.appendChild(originCell); - row.appendChild(baseScoreCell); - row.appendChild(bonusScoreCell); - row.appendChild(totalScoreCell); - row.appendChild(engagementBarCell); + var row = document.createElement('tr'); + row.appendChild(originCell); + row.appendChild(baseScoreCell); + row.appendChild(bonusScoreCell); + row.appendChild(totalScoreCell); + row.appendChild(engagementBarCell); - // Stores correspondent engagementBarCell to change it's length on - // scoreChange event. - baseScoreInput.barCellRef = engagementBar; - return row; - } + // Stores correspondent engagementBarCell to change it's length on + // scoreChange event. + baseScoreInput.barCellRef = engagementBar; + return row; + } - function disableAutoupdate() { - if (updateInterval) - clearInterval(updateInterval); - updateInterval = null; - } + function disableAutoupdate() { + if (updateInterval) + clearInterval(updateInterval); + updateInterval = null; + } - function enableAutoupdate() { - if (updateInterval) - clearInterval(updateInterval); - updateInterval = setInterval(updateEngagementTable, 5000); - } + function enableAutoupdate() { + if (updateInterval) + clearInterval(updateInterval); + updateInterval = setInterval(updateEngagementTable, 5000); + } - /** - * Sets the base engagement score when a score input is changed. - * Resets the length of engagement-bar-cell to match the new score. - * Also resets the update interval. - * @param {string} origin The origin of the engagement score to set. - * @param {Event} e - */ - function handleBaseScoreChange(origin, e) { - var baseScoreInput = e.target; - uiHandler.setSiteEngagementBaseScoreForUrl(origin, baseScoreInput.value); - baseScoreInput.barCellRef.style.width = (baseScoreInput.value * 4) + 'px'; - baseScoreInput.blur(); - enableAutoupdate(); - } + /** + * Sets the base engagement score when a score input is changed. + * Resets the length of engagement-bar-cell to match the new score. + * Also resets the update interval. + * @param {string} origin The origin of the engagement score to set. + * @param {Event} e + */ + function handleBaseScoreChange(origin, e) { + var baseScoreInput = e.target; + uiHandler.setSiteEngagementBaseScoreForUrl( + origin, baseScoreInput.value); + baseScoreInput.barCellRef.style.width = + (baseScoreInput.value * 4) + 'px'; + baseScoreInput.blur(); + enableAutoupdate(); + } - /** - * Remove all rows from the engagement table. - */ - function clearTable() { - engagementTableBody.innerHTML = ''; - } + /** + * Remove all rows from the engagement table. + */ + function clearTable() { + engagementTableBody.innerHTML = ''; + } - /** - * Sort the engagement info based on |sortKey| and |sortReverse|. - */ - function sortInfo() { - info.sort((a, b) => { - return (sortReverse ? -1 : 1) * - compareTableItem(sortKey, a, b); - }); - } + /** + * Sort the engagement info based on |sortKey| and |sortReverse|. + */ + function sortInfo() { + info.sort((a, b) => { + return (sortReverse ? -1 : 1) * compareTableItem(sortKey, a, b); + }); + } - /** - * Compares two SiteEngagementDetails objects based on |sortKey|. - * @param {string} sortKey The name of the property to sort by. - * @return {number} A negative number if |a| should be ordered before |b|, a - * positive number otherwise. - */ - function compareTableItem(sortKey, a, b) { - var val1 = a[sortKey]; - var val2 = b[sortKey]; + /** + * Compares two SiteEngagementDetails objects based on |sortKey|. + * @param {string} sortKey The name of the property to sort by. + * @return {number} A negative number if |a| should be ordered before |b|, a + * positive number otherwise. + */ + function compareTableItem(sortKey, a, b) { + var val1 = a[sortKey]; + var val2 = b[sortKey]; - // Compare the hosts of the origin ignoring schemes. - if (sortKey == 'origin') - return new URL(val1.url).host > new URL(val2.url).host ? 1 : -1; + // Compare the hosts of the origin ignoring schemes. + if (sortKey == 'origin') + return new URL(val1.url).host > new URL(val2.url).host ? 1 : -1; - if (sortKey == 'base_score' || - sortKey == 'bonus_score' || - sortKey == 'total_score') { - return val1 - val2; - } + if (sortKey == 'base_score' || sortKey == 'bonus_score' || + sortKey == 'total_score') { + return val1 - val2; + } - assertNotReached('Unsupported sort key: ' + sortKey); - return 0; - } + assertNotReached('Unsupported sort key: ' + sortKey); + return 0; + } - /** - * Rounds the supplied value to two decimal places of accuracy. - * @param {number} score - * @return {number} - */ - function roundScore(score) { - return Number(Math.round(score * 100) / 100); - } + /** + * Rounds the supplied value to two decimal places of accuracy. + * @param {number} score + * @return {number} + */ + function roundScore(score) { + return Number(Math.round(score * 100) / 100); + } - /** - * Regenerates the engagement table from |info|. - */ - function renderTable() { - clearTable(); - sortInfo(); + /** + * Regenerates the engagement table from |info|. + */ + function renderTable() { + clearTable(); + sortInfo(); - info.forEach((info) => { - // Round all scores to 2 decimal places. - info.base_score = roundScore(info.base_score); - info.installed_bonus = roundScore(info.installed_bonus); - info.notifications_bonus = roundScore(info.notifications_bonus); - info.total_score = roundScore(info.total_score); + info.forEach((info) => { + // Round all scores to 2 decimal places. + info.base_score = roundScore(info.base_score); + info.installed_bonus = roundScore(info.installed_bonus); + info.notifications_bonus = roundScore(info.notifications_bonus); + info.total_score = roundScore(info.total_score); - // Collate the bonuses into a value for the bonus_score column. - info.bonus_score = info.installed_bonus + info.notifications_bonus; + // Collate the bonuses into a value for the bonus_score column. + info.bonus_score = info.installed_bonus + info.notifications_bonus; - engagementTableBody.appendChild(createRow(info)); - }); - } + engagementTableBody.appendChild(createRow(info)); + }); + } - /** - * Retrieve site engagement info and render the engagement table. - */ - function updateEngagementTable() { - // Populate engagement table. - uiHandler.getSiteEngagementDetails().then((response) => { - info = response.info; - renderTable(info); - resolvePageIsPopulated(); - }); - } + /** + * Retrieve site engagement info and render the engagement table. + */ + function updateEngagementTable() { + // Populate engagement table. + uiHandler.getSiteEngagementDetails().then((response) => { + info = response.info; + renderTable(info); + resolvePageIsPopulated(); + }); + } - updateEngagementTable(); - enableAutoupdate(); - }; -}); + updateEngagementTable(); + enableAutoupdate(); + }; + });
diff --git a/chrome/browser/resources/feedback/js/data.js b/chrome/browser/resources/feedback/js/data.js index b1cf0e9..98a801e 100644 --- a/chrome/browser/resources/feedback/js/data.js +++ b/chrome/browser/resources/feedback/js/data.js
@@ -12,7 +12,4 @@ * The status of sending the feedback report as defined in feedback_private.idl. * @enum {string} */ -var ReportStatus = { - SUCCESS: 'success', - DELAYED: 'delayed' -}; +var ReportStatus = {SUCCESS: 'success', DELAYED: 'delayed'};
diff --git a/chrome/browser/resources/feedback/js/event_handler.js b/chrome/browser/resources/feedback/js/event_handler.js index 534f66b..ec5de87 100644 --- a/chrome/browser/resources/feedback/js/event_handler.js +++ b/chrome/browser/resources/feedback/js/event_handler.js
@@ -26,58 +26,59 @@ // echo -n 'abcdefghijklmnopqrstuvwxyzabcdef' | sha1sum | \ // awk '{print toupper($1)}' var whitelistedExtensionIds = [ - '12E618C3C6E97495AAECF2AC12DEB082353241C6', // QuickOffice - '3727DD3E564B6055387425027AD74C58784ACC15', // QuickOffice - '2FC374607C2DF285634B67C64A2E356C607091C3', // QuickOffice - '2843C1E82A9B6C6FB49308FDDF4E157B6B44BC2B', // G+ Photos - '5B5DA6D054D10DB917AF7D9EAE3C56044D1B0B03', // G+ Photos - '986913085E3E3C3AFDE9B7A943149C4D3F4C937B', // Feedback Extension - '7AE714FFD394E073F0294CFA134C9F91DB5FBAA4', // Connectivity Diagnostics - 'C7DA3A55C2355F994D3FDDAD120B426A0DF63843', // Connectivity Diagnostics - '75E3CFFFC530582C583E4690EF97C70B9C8423B7', // Connectivity Diagnostics - '32A1BA997F8AB8DE29ED1BA94AAF00CF2A3FEFA7', // Connectivity Diagnostics - 'A291B26E088FA6BA53FFD72F0916F06EBA7C585A', // Chrome OS Recovery Tool - 'D7986543275120831B39EF28D1327552FC343960', // Chrome OS Recovery Tool - '8EBDF73405D0B84CEABB8C7513C9B9FA9F1DC2CE', // GetHelp app. - '97B23E01B2AA064E8332EE43A7A85C628AADC3F2', // Chrome Remote Desktop Dev - '9E527CDA9D7C50844E8A5DB964A54A640AE48F98', // Chrome Remote Desktop Stable - 'DF52618D0B040D8A054D8348D2E84DDEEE5974E7', // Chrome Remote Desktop QA - '269D721F163E587BC53C6F83553BF9CE2BB143CD', // Chrome Remote Desktop QA backup - 'C449A798C495E6CF7D6AF10162113D564E67AD12', // Chrome Remote Desktop Apps V2 - '981974CD1832B87BE6B21BE78F7249BB501E0DE6', // Play Movies Dev - '32FD7A816E47392C92D447707A89EB07EEDE6FF7', // Play Movies Nightly - '3F3CEC4B9B2B5DC2F820CE917AABDF97DB2F5B49', // Play Movies Beta - 'F92FAC70AB68E1778BF62D9194C25979596AA0E6', // Play Movies Stable - '0F585FB1D0FDFBEBCE1FEB5E9DFFB6DA476B8C9B', // Hangouts Extension - '2D22CDB6583FD0A13758AEBE8B15E45208B4E9A7', // Hangouts Extension - '49DA0B9CCEEA299186C6E7226FD66922D57543DC', // Hangouts Extension - 'E7E2461CE072DF036CF9592740196159E2D7C089', // Hangouts Extension - 'A74A4D44C7CFCD8844830E6140C8D763E12DD8F3', // Hangouts Extension - '312745D9BF916161191143F6490085EEA0434997', // Hangouts Extension - '53041A2FA309EECED01FFC751E7399186E860B2C', // Hangouts Extension - '0F42756099D914A026DADFA182871C015735DD95', // Hangouts Extension - '1B7734733E207CCE5C33BFAA544CA89634BF881F', // GLS nightly - 'E2ACA3D943A3C96310523BCDFD8C3AF68387E6B7', // GLS stable - 'BA007D8D52CC0E2632EFCA03ACD003B0F613FD71', // http://crbug.com/470411 - '5260FA31DE2007A837B7F7B0EB4A47CE477018C8', // http://crbug.com/470411 - '4F4A25F31413D9B9F80E61D096DEB09082515267', // http://crbug.com/470411 - 'FBA0DE4D3EFB5485FC03760F01F821466907A743', // http://crbug.com/470411 - 'E216473E4D15C5FB14522D32C5F8DEAAB2CECDC6', // http://crbug.com/470411 - '676A08383D875E51CE4C2308D875AE77199F1413', // http://crbug.com/473845 - '869A23E11B308AF45A68CC386C36AADA4BE44A01', // http://crbug.com/473845 - 'E9CE07C7EDEFE70B9857B312E88F94EC49FCC30F', // http://crbug.com/473845 - 'A4577D8C2AF4CF26F40CBCA83FFA4251D6F6C8F8', // http://crbug.com/478929 - 'A8208CCC87F8261AFAEB6B85D5E8D47372DDEA6B', // http://crbug.com/478929 + '12E618C3C6E97495AAECF2AC12DEB082353241C6', // QuickOffice + '3727DD3E564B6055387425027AD74C58784ACC15', // QuickOffice + '2FC374607C2DF285634B67C64A2E356C607091C3', // QuickOffice + '2843C1E82A9B6C6FB49308FDDF4E157B6B44BC2B', // G+ Photos + '5B5DA6D054D10DB917AF7D9EAE3C56044D1B0B03', // G+ Photos + '986913085E3E3C3AFDE9B7A943149C4D3F4C937B', // Feedback Extension + '7AE714FFD394E073F0294CFA134C9F91DB5FBAA4', // Connectivity Diagnostics + 'C7DA3A55C2355F994D3FDDAD120B426A0DF63843', // Connectivity Diagnostics + '75E3CFFFC530582C583E4690EF97C70B9C8423B7', // Connectivity Diagnostics + '32A1BA997F8AB8DE29ED1BA94AAF00CF2A3FEFA7', // Connectivity Diagnostics + 'A291B26E088FA6BA53FFD72F0916F06EBA7C585A', // Chrome OS Recovery Tool + 'D7986543275120831B39EF28D1327552FC343960', // Chrome OS Recovery Tool + '8EBDF73405D0B84CEABB8C7513C9B9FA9F1DC2CE', // GetHelp app. + '97B23E01B2AA064E8332EE43A7A85C628AADC3F2', // Chrome Remote Desktop Dev + '9E527CDA9D7C50844E8A5DB964A54A640AE48F98', // Chrome Remote Desktop Stable + 'DF52618D0B040D8A054D8348D2E84DDEEE5974E7', // Chrome Remote Desktop QA + '269D721F163E587BC53C6F83553BF9CE2BB143CD', // Chrome Remote Desktop QA + // backup + 'C449A798C495E6CF7D6AF10162113D564E67AD12', // Chrome Remote Desktop Apps V2 + '981974CD1832B87BE6B21BE78F7249BB501E0DE6', // Play Movies Dev + '32FD7A816E47392C92D447707A89EB07EEDE6FF7', // Play Movies Nightly + '3F3CEC4B9B2B5DC2F820CE917AABDF97DB2F5B49', // Play Movies Beta + 'F92FAC70AB68E1778BF62D9194C25979596AA0E6', // Play Movies Stable + '0F585FB1D0FDFBEBCE1FEB5E9DFFB6DA476B8C9B', // Hangouts Extension + '2D22CDB6583FD0A13758AEBE8B15E45208B4E9A7', // Hangouts Extension + '49DA0B9CCEEA299186C6E7226FD66922D57543DC', // Hangouts Extension + 'E7E2461CE072DF036CF9592740196159E2D7C089', // Hangouts Extension + 'A74A4D44C7CFCD8844830E6140C8D763E12DD8F3', // Hangouts Extension + '312745D9BF916161191143F6490085EEA0434997', // Hangouts Extension + '53041A2FA309EECED01FFC751E7399186E860B2C', // Hangouts Extension + '0F42756099D914A026DADFA182871C015735DD95', // Hangouts Extension + '1B7734733E207CCE5C33BFAA544CA89634BF881F', // GLS nightly + 'E2ACA3D943A3C96310523BCDFD8C3AF68387E6B7', // GLS stable + 'BA007D8D52CC0E2632EFCA03ACD003B0F613FD71', // http://crbug.com/470411 + '5260FA31DE2007A837B7F7B0EB4A47CE477018C8', // http://crbug.com/470411 + '4F4A25F31413D9B9F80E61D096DEB09082515267', // http://crbug.com/470411 + 'FBA0DE4D3EFB5485FC03760F01F821466907A743', // http://crbug.com/470411 + 'E216473E4D15C5FB14522D32C5F8DEAAB2CECDC6', // http://crbug.com/470411 + '676A08383D875E51CE4C2308D875AE77199F1413', // http://crbug.com/473845 + '869A23E11B308AF45A68CC386C36AADA4BE44A01', // http://crbug.com/473845 + 'E9CE07C7EDEFE70B9857B312E88F94EC49FCC30F', // http://crbug.com/473845 + 'A4577D8C2AF4CF26F40CBCA83FFA4251D6F6C8F8', // http://crbug.com/478929 + 'A8208CCC87F8261AFAEB6B85D5E8D47372DDEA6B', // http://crbug.com/478929 // TODO (ntang) Remove the following 2 hashes by 12/31/2017. - 'B620CF4203315F9F2E046EDED22C7571A935958D', // http://crbug.com/510270 - 'B206D8716769728278D2D300349C6CB7D7DE2EF9', // http://crbug.com/510270 - 'EFCF5358672FEE04789FD2EC3638A67ADEDB6C8C', // http://crbug.com/514696 - 'FAD85BC419FE00995D196312F53448265EFA86F1', // http://crbug.com/516527 - 'F33B037DEDA65F226B7409C2ADB0CF3F8565AB03', // http://crbug.com/541769 - '969C788BCBC82FBBE04A17360CA165C23A419257', // http://crbug.com/541769 - '3BC3740BFC58F06088B300274B4CFBEA20136342', // http://crbug.com/541769 - '2B6C6A4A5940017146F3E58B7F90116206E84685', // http://crbug.com/642141 - '96FF2FFA5C9173C76D47184B3E86D267B37781DE', // http://crbug.com/642141 + 'B620CF4203315F9F2E046EDED22C7571A935958D', // http://crbug.com/510270 + 'B206D8716769728278D2D300349C6CB7D7DE2EF9', // http://crbug.com/510270 + 'EFCF5358672FEE04789FD2EC3638A67ADEDB6C8C', // http://crbug.com/514696 + 'FAD85BC419FE00995D196312F53448265EFA86F1', // http://crbug.com/516527 + 'F33B037DEDA65F226B7409C2ADB0CF3F8565AB03', // http://crbug.com/541769 + '969C788BCBC82FBBE04A17360CA165C23A419257', // http://crbug.com/541769 + '3BC3740BFC58F06088B300274B4CFBEA20136342', // http://crbug.com/541769 + '2B6C6A4A5940017146F3E58B7F90116206E84685', // http://crbug.com/642141 + '96FF2FFA5C9173C76D47184B3E86D267B37781DE', // http://crbug.com/642141 ]; /** @@ -177,17 +178,17 @@ /** @const */ var ID = this.id_; /** @const */ var FLOW = this.feedbackInfo_.flow; - chrome.feedbackPrivate.sendFeedback(this.feedbackInfo_, - function(result) { - if (result == ReportStatus.SUCCESS) { - console.log('Feedback: Report sent for request with ID ' + ID); - if (FLOW != chrome.feedbackPrivate.FeedbackFlow.LOGIN) - window.open(FEEDBACK_LANDING_PAGE, '_blank'); - } else { - console.log('Feedback: Report for request with ID ' + ID + - ' will be sent later.'); - } - }); + chrome.feedbackPrivate.sendFeedback(this.feedbackInfo_, function(result) { + if (result == ReportStatus.SUCCESS) { + console.log('Feedback: Report sent for request with ID ' + ID); + if (FLOW != chrome.feedbackPrivate.FeedbackFlow.LOGIN) + window.open(FEEDBACK_LANDING_PAGE, '_blank'); + } else { + console.log( + 'Feedback: Report for request with ID ' + ID + + ' will be sent later.'); + } + }); } /** @@ -211,18 +212,18 @@ * start feedback UI callback. */ function senderWhitelisted(id, startFeedbackCallback, feedbackInfo) { - crypto.subtle.digest('SHA-1', new TextEncoder().encode(id)).then( - function(hashBuffer) { - var hashString = ''; - var hashView = new Uint8Array(hashBuffer); - for (var i = 0; i < hashView.length; ++i) { - var n = hashView[i]; - hashString += n < 0x10 ? '0' : ''; - hashString += n.toString(16); - } - if (whitelistedExtensionIds.indexOf(hashString.toUpperCase()) != -1) - startFeedbackCallback(feedbackInfo); - }); + crypto.subtle.digest('SHA-1', new TextEncoder().encode(id)) + .then(function(hashBuffer) { + var hashString = ''; + var hashView = new Uint8Array(hashBuffer); + for (var i = 0; i < hashView.length; ++i) { + var n = hashView[i]; + hashString += n < 0x10 ? '0' : ''; + hashString += n.toString(16); + } + if (whitelistedExtensionIds.indexOf(hashString.toUpperCase()) != -1) + startFeedbackCallback(feedbackInfo); + }); } /** @@ -258,15 +259,17 @@ win.show(); return; } - chrome.app.window.create('html/default.html', { - frame: feedbackInfo.useSystemWindowFrame ? 'chrome' : 'none', - id: FEEDBACK_DEFAULT_WINDOW_ID, - innerBounds: { - minWidth: FEEDBACK_WIDTH, - minHeight: FEEDBACK_HEIGHT, + chrome.app.window.create( + 'html/default.html', { + frame: feedbackInfo.useSystemWindowFrame ? 'chrome' : 'none', + id: FEEDBACK_DEFAULT_WINDOW_ID, + innerBounds: { + minWidth: FEEDBACK_WIDTH, + minHeight: FEEDBACK_HEIGHT, + }, + hidden: true, + resizable: false }, - hidden: true, - resizable: false }, function(appWindow) { var request = new FeedbackRequest(feedbackInfo);
diff --git a/chrome/browser/resources/feedback/js/feedback.js b/chrome/browser/resources/feedback/js/feedback.js index fa861c8..76f6e26 100644 --- a/chrome/browser/resources/feedback/js/feedback.js +++ b/chrome/browser/resources/feedback/js/feedback.js
@@ -160,8 +160,10 @@ $('send-report-button').disabled = true; console.log('Feedback: Sending report'); if (!feedbackInfo.attachedFile && attachedFileBlob) { - feedbackInfo.attachedFile = { name: $('attach-file').value, - data: attachedFileBlob }; + feedbackInfo.attachedFile = { + name: $('attach-file').value, + data: attachedFileBlob + }; } feedbackInfo.description = $('description-text').value; @@ -170,17 +172,16 @@ var useSystemInfo = false; var useHistograms = false; - if ($('sys-info-checkbox') != null && - $('sys-info-checkbox').checked) { + if ($('sys-info-checkbox') != null && $('sys-info-checkbox').checked) { // Send histograms along with system info. useSystemInfo = useHistograms = true; } -// <if expr="chromeos"> + // <if expr="chromeos"> if ($('performance-info-checkbox') == null || !($('performance-info-checkbox').checked)) { feedbackInfo.traceId = null; } -// </if> + // </if> feedbackInfo.sendHistograms = useHistograms; @@ -256,8 +257,8 @@ // We get the height by adding the titlebar height and the content height + // margins. We can't get the margins for the content-pane here by using // style.margin - the variable seems to not exist. - var height = $('title-bar').scrollHeight + - $('content-pane').scrollHeight + CONTENT_MARGIN_HEIGHT; + var height = $('title-bar').scrollHeight + $('content-pane').scrollHeight + + CONTENT_MARGIN_HEIGHT; var minHeight = FEEDBACK_MIN_HEIGHT; if (feedbackInfo.flow == chrome.feedbackPrivate.FeedbackFlow.LOGIN) @@ -284,7 +285,9 @@ * Close the window after 100ms delay. */ function scheduleWindowClose() { - setTimeout(function() { window.close();}, 100); + setTimeout(function() { + window.close(); + }, 100); } /** @@ -346,8 +349,10 @@ var screenshotDataUrl = screenshotCanvas.toDataURL('image/png'); $('screenshot-image').src = screenshotDataUrl; - $('screenshot-image').classList.toggle('wide-screen', - $('screenshot-image').width > MAX_SCREENSHOT_WIDTH); + $('screenshot-image') + .classList.toggle( + 'wide-screen', + $('screenshot-image').width > MAX_SCREENSHOT_WIDTH); feedbackInfo.screenshot = dataUrlToBlob(screenshotDataUrl); }); @@ -360,8 +365,8 @@ optionElement.text = email; optionElement.selected = true; // Make sure the "Report anonymously" option comes last. - $('user-email-drop-down').insertBefore(optionElement, - $('anonymous-user-option')); + $('user-email-drop-down') + .insertBefore(optionElement, $('anonymous-user-option')); // Now we can unhide the user email section: $('user-email').hidden = false; @@ -387,14 +392,14 @@ $('attach-file-note').hidden = true; } -// <if expr="chromeos"> + // <if expr="chromeos"> if (feedbackInfo.traceId && ($('performance-info-area'))) { $('performance-info-area').hidden = false; $('performance-info-checkbox').checked = true; performanceFeedbackChanged(); $('performance-info-link').onclick = openSlowTraceWindow; } -// </if> + // </if> chrome.feedbackPrivate.getStrings(feedbackInfo.flow, function(strings) { loadTimeData.data = strings; i18nTemplate.process(document, loadTimeData); @@ -409,32 +414,33 @@ return; } chrome.app.window.create( - '/html/sys_info.html', { - frame: 'chrome', - id: SYSINFO_WINDOW_ID, - width: 640, - height: 400, - hidden: false, - resizable: true - }, function(appWindow) { - // Define functions for the newly created window. + '/html/sys_info.html', { + frame: 'chrome', + id: SYSINFO_WINDOW_ID, + width: 640, + height: 400, + hidden: false, + resizable: true + }, + function(appWindow) { + // Define functions for the newly created window. - // Gets the full system information for the new window. - appWindow.contentWindow.getFullSystemInfo = - function(callback) { - if (isSystemInfoReady) { - callback(feedbackInfo.systemInformation); - return; - } + // Gets the full system information for the new window. + appWindow.contentWindow.getFullSystemInfo = function( + callback) { + if (isSystemInfoReady) { + callback(feedbackInfo.systemInformation); + return; + } - sysInfoPageOnSysInfoReadyCallback = callback; - }; + sysInfoPageOnSysInfoReadyCallback = callback; + }; - // Returns the loadTimeData for the new window. - appWindow.contentWindow.getLoadTimeData = function() { - return loadTimeData; - }; - }); + // Returns the loadTimeData for the new window. + appWindow.contentWindow.getLoadTimeData = function() { + return loadTimeData; + }; + }); }; } if ($('histograms-url')) { @@ -457,10 +463,10 @@ $('send-report-button').onclick = sendReport; $('cancel-button').onclick = cancel; $('remove-attached-file').onclick = clearAttachedFile; -// <if expr="chromeos"> - $('performance-info-checkbox').addEventListener( - 'change', performanceFeedbackChanged); -// </if> + // <if expr="chromeos"> + $('performance-info-checkbox') + .addEventListener('change', performanceFeedbackChanged); + // </if> }); }
diff --git a/chrome/browser/resources/feedback/js/take_screenshot.js b/chrome/browser/resources/feedback/js/take_screenshot.js index 53e4170..3f09972 100644 --- a/chrome/browser/resources/feedback/js/take_screenshot.js +++ b/chrome/browser/resources/feedback/js/take_screenshot.js
@@ -30,25 +30,22 @@ }, false); navigator.webkitGetUserMedia( - { - video: { - mandatory: { - chromeMediaSource: 'screen', - maxWidth: 4096, - maxHeight: 2560 + { + video: { + mandatory: + {chromeMediaSource: 'screen', maxWidth: 4096, maxHeight: 2560} } - } - }, - function(stream) { - if (stream) { - screenshotStream = stream; - video.src = window.URL.createObjectURL(screenshotStream); - video.play(); - } - }, - function(err) { - console.error('takeScreenshot failed: ' + - err.name + '; ' + err.message + '; ' + err.constraintName); - } - ); + }, + function(stream) { + if (stream) { + screenshotStream = stream; + video.src = window.URL.createObjectURL(screenshotStream); + video.play(); + } + }, + function(err) { + console.error( + 'takeScreenshot failed: ' + err.name + '; ' + err.message + '; ' + + err.constraintName); + }); }
diff --git a/chrome/browser/resources/gaia_auth_host/authenticator.js b/chrome/browser/resources/gaia_auth_host/authenticator.js index 381a7df..1dfc4c5f 100644 --- a/chrome/browser/resources/gaia_auth_host/authenticator.js +++ b/chrome/browser/resources/gaia_auth_host/authenticator.js
@@ -44,20 +44,13 @@ * chrome/browser/ui/webui/inline_login_ui.cc. * @enum {number} */ - var AuthMode = { - DEFAULT: 0, - OFFLINE: 1, - DESKTOP: 2 - }; + var AuthMode = {DEFAULT: 0, OFFLINE: 1, DESKTOP: 2}; /** * Enum for the authorization type. * @enum {number} */ - var AuthFlow = { - DEFAULT: 0, - SAML: 1 - }; + var AuthFlow = {DEFAULT: 0, SAML: 1}; /** * Supported Authenticator params. @@ -83,15 +76,15 @@ // not called before dispatching |authCopleted|. // Default is |true|. 'flow', // One of 'default', 'enterprise', or 'theftprotection'. - 'enterpriseDomain', // Domain in which hosting device is (or should be) - // enrolled. - 'emailDomain', // Value used to prefill domain for email. - 'chromeType', // Type of Chrome OS device, e.g. "chromebox". - 'clientVersion', // Version of the Chrome build. - 'platformVersion', // Version of the OS build. - 'releaseChannel', // Installation channel. - 'endpointGen', // Current endpoint generation. - 'gapsCookie', // GAPS cookie + 'enterpriseDomain', // Domain in which hosting device is (or should be) + // enrolled. + 'emailDomain', // Value used to prefill domain for email. + 'chromeType', // Type of Chrome OS device, e.g. "chromebox". + 'clientVersion', // Version of the Chrome build. + 'platformVersion', // Version of the OS build. + 'releaseChannel', // Installation channel. + 'endpointGen', // Current endpoint generation. + 'gapsCookie', // GAPS cookie // The email fields allow for the following possibilities: // @@ -126,8 +119,7 @@ this.isLoaded_ = false; this.email_ = null; this.password_ = null; - this.gaiaId_ = null, - this.sessionIndex_ = null; + this.gaiaId_ = null, this.sessionIndex_ = null; this.chooseWhatToSync_ = false; this.skipForNow_ = false; this.authFlow = AuthFlow.DEFAULT; @@ -156,43 +148,32 @@ this.missingGaiaInfoCallback = null; this.needPassword = true; this.samlHandler_.addEventListener( - 'insecureContentBlocked', - this.onInsecureContentBlocked_.bind(this)); + 'insecureContentBlocked', this.onInsecureContentBlocked_.bind(this)); this.samlHandler_.addEventListener( - 'authPageLoaded', - this.onAuthPageLoaded_.bind(this)); + 'authPageLoaded', this.onAuthPageLoaded_.bind(this)); this.samlHandler_.addEventListener( - 'videoEnabled', - this.onVideoEnabled_.bind(this)); + 'videoEnabled', this.onVideoEnabled_.bind(this)); this.samlHandler_.addEventListener( - 'apiPasswordAdded', - this.onSamlApiPasswordAdded_.bind(this)); + 'apiPasswordAdded', this.onSamlApiPasswordAdded_.bind(this)); this.webview_.addEventListener('droplink', this.onDropLink_.bind(this)); - this.webview_.addEventListener( - 'newwindow', this.onNewWindow_.bind(this)); + this.webview_.addEventListener('newwindow', this.onNewWindow_.bind(this)); this.webview_.addEventListener( 'contentload', this.onContentLoad_.bind(this)); - this.webview_.addEventListener( - 'loadabort', this.onLoadAbort_.bind(this)); - this.webview_.addEventListener( - 'loadstop', this.onLoadStop_.bind(this)); - this.webview_.addEventListener( - 'loadcommit', this.onLoadCommit_.bind(this)); + this.webview_.addEventListener('loadabort', this.onLoadAbort_.bind(this)); + this.webview_.addEventListener('loadstop', this.onLoadStop_.bind(this)); + this.webview_.addEventListener('loadcommit', this.onLoadCommit_.bind(this)); this.webview_.request.onCompleted.addListener( this.onRequestCompleted_.bind(this), - {urls: ['<all_urls>'], types: ['main_frame']}, - ['responseHeaders']); + {urls: ['<all_urls>'], types: ['main_frame']}, ['responseHeaders']); this.webview_.request.onHeadersReceived.addListener( this.onHeadersReceived_.bind(this), {urls: ['<all_urls>'], types: ['main_frame', 'xmlhttprequest']}, ['responseHeaders']); window.addEventListener( 'message', this.onMessageFromWebview_.bind(this), false); - window.addEventListener( - 'focus', this.onFocus_.bind(this), false); - window.addEventListener( - 'popstate', this.onPopState_.bind(this), false); + window.addEventListener('focus', this.onFocus_.bind(this), false); + window.addEventListener('popstate', this.onPopState_.bind(this), false); } Authenticator.prototype = Object.create(cr.EventTarget.prototype); @@ -255,8 +236,8 @@ this.reloadUrl_ = data.frameUrl || this.initialFrameUrl_; // Don't block insecure content for desktop flow because it lands on // http. Otherwise, block insecure content as long as gaia is https. - this.samlHandler_.blockInsecureContent = authMode != AuthMode.DESKTOP && - this.idpOrigin_.startsWith('https://'); + this.samlHandler_.blockInsecureContent = + authMode != AuthMode.DESKTOP && this.idpOrigin_.startsWith('https://'); this.needPassword = !('needPassword' in data) || data.needPassword; if (this.isNewGaiaFlow) { @@ -292,11 +273,12 @@ if (data.doSamlRedirect) { var url = this.idpOrigin_ + SAML_REDIRECTION_PATH; url = appendParam(url, 'domain', data.enterpriseDomain); - url = appendParam(url, 'continue', data.gaiaUrl + - 'o/oauth2/programmatic_auth?hl=' + data.hl + - '&scope=https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthLogin&' + - 'client_id=' + encodeURIComponent(data.clientId) + - '&access_type=offline'); + url = appendParam( + url, 'continue', + data.gaiaUrl + 'o/oauth2/programmatic_auth?hl=' + data.hl + + '&scope=https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthLogin&' + + 'client_id=' + encodeURIComponent(data.clientId) + + '&access_type=offline'); return url; } @@ -404,11 +386,11 @@ }; /** - * Manually updates the history. Invoked upon completion of a webview - * navigation. - * @param {string} url Request URL. - * @private - */ + * Manually updates the history. Invoked upon completion of a webview + * navigation. + * @param {string} url Request URL. + * @private + */ Authenticator.prototype.updateHistoryState_ = function(url) { if (history.state && history.state.url != url) history.pushState({url: url}, ''); @@ -469,8 +451,7 @@ // URL will contain a source=3 field. var location = decodeURIComponent(header.value); this.chooseWhatToSync_ = !!location.match(/(\?|&)source=3($|&)/); - } else if ( - this.isNewGaiaFlow && headerName == SET_COOKIE_HEADER) { + } else if (this.isNewGaiaFlow && headerName == SET_COOKIE_HEADER) { var headerValue = header.value; if (headerValue.startsWith(OAUTH_CODE_COOKIE + '=')) { this.oauthCode_ = @@ -525,8 +506,8 @@ for (var i = 0, l = headers.length; i < l; ++i) { if (headers[i].name == COOKIE_HEADER) { - headers[i].value = this.updateCookieValue_(headers[i].value, - GAPS_COOKIE, gapsCookie); + headers[i].value = this.updateCookieValue_( + headers[i].value, GAPS_COOKIE, gapsCookie); found = true; break; } @@ -537,9 +518,7 @@ } this.gapsCookieSent_ = true; } - return { - requestHeaders: details.requestHeaders - }; + return {requestHeaders: details.requestHeaders}; }; /** @@ -556,19 +535,13 @@ } // EAFE passes back auth code via message. - if (this.useEafe_ && - typeof e.data == 'object' && + if (this.useEafe_ && typeof e.data == 'object' && e.data.hasOwnProperty('authorizationCode')) { assert(!this.oauthCode_); this.oauthCode_ = e.data.authorizationCode; - this.dispatchEvent( - new CustomEvent('authCompleted', - { - detail: { - authCodeOnly: true, - authCode: this.oauthCode_ - } - })); + this.dispatchEvent(new CustomEvent( + 'authCompleted', + {detail: {authCodeOnly: true, authCode: this.oauthCode_}})); return; } @@ -596,8 +569,7 @@ this.chooseWhatToSync_ = msg.chooseWhatToSync; // We need to dispatch only first event, before user enters password. - this.dispatchEvent( - new CustomEvent('attemptLogin', {detail: msg.email})); + this.dispatchEvent(new CustomEvent('attemptLogin', {detail: msg.email})); } else if (msg.method == 'dialogShown') { this.dispatchEvent(new Event('dialogShown')); } else if (msg.method == 'dialogHidden') { @@ -625,10 +597,11 @@ // does not expect it to be called immediately. // TODO(xiyuan): Change to synchronous call when iframe based code // is removed. - var invokeConfirmPassword = (function() { - this.confirmPasswordCallback(this.email_, - this.samlHandler_.scrapedPasswordCount); - }).bind(this); + var invokeConfirmPassword = + (function() { + this.confirmPasswordCallback( + this.email_, this.samlHandler_.scrapedPasswordCount); + }).bind(this); window.setTimeout(invokeConfirmPassword, 0); return; } @@ -683,8 +656,8 @@ if (this.confirmPasswordCallback) { // Confirm scraped password. The flow follows in // verifyConfirmedPassword. - this.confirmPasswordCallback(this.email_, - this.samlHandler_.scrapedPasswordCount); + this.confirmPasswordCallback( + this.email_, this.samlHandler_.scrapedPasswordCount); return; } } @@ -707,8 +680,9 @@ * @private */ Authenticator.prototype.onAuthCompleted_ = function() { - assert(this.skipForNow_ || - (this.email_ && this.gaiaId_ && this.sessionIndex_)); + assert( + this.skipForNow_ || + (this.email_ && this.gaiaId_ && this.sessionIndex_)); this.dispatchEvent(new CustomEvent( 'authCompleted', // TODO(rsorokin): get rid of the stub values. @@ -831,8 +805,8 @@ * @private */ Authenticator.prototype.onLoadAbort_ = function(e) { - this.dispatchEvent(new CustomEvent('loadAbort', - {detail: {error: e.reason, src: e.url}})); + this.dispatchEvent( + new CustomEvent('loadAbort', {detail: {error: e.reason, src: e.url}})); }; /** @@ -847,12 +821,12 @@ if (this.useEafe_) { // An arbitrary small timeout for delivering the initial message. var EAFE_INITIAL_MESSAGE_DELAY_IN_MS = 500; - window.setTimeout((function() { - var msg = { - 'clientId': this.clientId_ - }; - this.webview_.contentWindow.postMessage(msg, this.idpOrigin_); - }).bind(this), EAFE_INITIAL_MESSAGE_DELAY_IN_MS); + window.setTimeout( + (function() { + var msg = {'clientId': this.clientId_}; + this.webview_.contentWindow.postMessage(msg, this.idpOrigin_); + }).bind(this), + EAFE_INITIAL_MESSAGE_DELAY_IN_MS); } };
diff --git a/chrome/browser/resources/gaia_auth_host/post_message_channel.js b/chrome/browser/resources/gaia_auth_host/post_message_channel.js index b20300d..1239a89 100644 --- a/chrome/browser/resources/gaia_auth_host/post_message_channel.js +++ b/chrome/browser/resources/gaia_auth_host/post_message_channel.js
@@ -16,10 +16,7 @@ * Allowed origins of the hosting page. * @type {Array<string>} */ - var ALLOWED_ORIGINS = [ - 'chrome://oobe', - 'chrome://chrome-signin' - ]; + var ALLOWED_ORIGINS = ['chrome://oobe', 'chrome://chrome-signin']; /** @const */ var PORT_MESSAGE = 'post-message-port-message'; @@ -149,7 +146,9 @@ * @private */ getProxyPortForwardHandler_: function(proxyPort) { - return function(msg) { proxyPort.postMessage(msg); }; + return function(msg) { + proxyPort.postMessage(msg); + }; }, /** @@ -161,8 +160,8 @@ */ createProxyPort: function( channelId, channelName, targetWindow, targetOrigin) { - var port = this.createPort( - channelId, channelName, targetWindow, targetOrigin); + var port = + this.createPort(channelId, channelName, targetWindow, targetOrigin); port.onMessage.addListener(this.getProxyPortForwardHandler_(port)); return port; }, @@ -213,8 +212,7 @@ * Window 'message' handler. */ onMessage_: function(e) { - if (typeof e.data != 'object' || - !e.data.hasOwnProperty('type')) { + if (typeof e.data != 'object' || !e.data.hasOwnProperty('type')) { return; } @@ -233,8 +231,8 @@ var channelName = e.data.channelName; if (this.isDaemon) { - var port = this.createPort( - channelId, channelName, e.source, e.origin); + var port = + this.createPort(channelId, channelName, e.source, e.origin); this.onConnect.dispatch(port); } else { this.createProxyPort(channelId, channelName, e.source, e.origin); @@ -248,14 +246,14 @@ this.upperOrigin = e.origin; for (var i = 0; i < this.deferredUpperWindowMessages_.length; ++i) { - this.upperWindow.postMessage(this.deferredUpperWindowMessages_[i], - this.upperOrigin); + this.upperWindow.postMessage( + this.deferredUpperWindowMessages_[i], this.upperOrigin); } this.deferredUpperWindowMessages_ = []; for (var i = 0; i < this.deferredUpperWindowPorts_.length; ++i) { - this.deferredUpperWindowPorts_[i].setTarget(this.upperWindow, - this.upperOrigin); + this.deferredUpperWindowPorts_[i].setTarget( + this.upperWindow, this.upperOrigin); } this.deferredUpperWindowPorts_ = []; } @@ -306,11 +304,9 @@ return; } - this.targetWindow.postMessage({ - type: PORT_MESSAGE, - channelId: this.channelId, - payload: msg - }, this.targetOrigin); + this.targetWindow.postMessage( + {type: PORT_MESSAGE, channelId: this.channelId, payload: msg}, + this.targetOrigin); }, handleWindowMessage: function(e) { @@ -342,9 +338,7 @@ * @param {DOMWindow} webViewContentWindow Content window of the webview. */ PostMessageChannel.init = function(webViewContentWindow) { - webViewContentWindow.postMessage({ - type: CHANNEL_INIT_MESSAGE - }, '*'); + webViewContentWindow.postMessage({type: CHANNEL_INIT_MESSAGE}, '*'); }; /**
diff --git a/chrome/browser/resources/gaia_auth_host/saml_handler.js b/chrome/browser/resources/gaia_auth_host/saml_handler.js index 48b195b..9212e58 100644 --- a/chrome/browser/resources/gaia_auth_host/saml_handler.js +++ b/chrome/browser/resources/gaia_auth_host/saml_handler.js
@@ -143,17 +143,14 @@ this.webview_.addEventListener( 'contentload', this.onContentLoad_.bind(this)); - this.webview_.addEventListener( - 'loadabort', this.onLoadAbort_.bind(this)); - this.webview_.addEventListener( - 'loadcommit', this.onLoadCommit_.bind(this)); + this.webview_.addEventListener('loadabort', this.onLoadAbort_.bind(this)); + this.webview_.addEventListener('loadcommit', this.onLoadCommit_.bind(this)); this.webview_.addEventListener( 'permissionrequest', this.onPermissionRequest_.bind(this)); this.webview_.request.onBeforeRequest.addListener( this.onInsecureRequest.bind(this), - {urls: ['http://*/*', 'file://*/*', 'ftp://*/*']}, - ['blocking']); + {urls: ['http://*/*', 'file://*/*', 'ftp://*/*']}, ['blocking']); this.webview_.request.onHeadersReceived.addListener( this.onHeadersReceived_.bind(this), {urls: ['<all_urls>'], types: ['main_frame', 'xmlhttprequest']}, @@ -162,9 +159,7 @@ this.webview_.addContentScripts([{ name: 'samlInjected', matches: ['http://*/*', 'https://*/*'], - js: { - code: injectedJs - }, + js: {code: injectedJs}, all_frames: true, run_at: 'document_start' }]); @@ -290,8 +285,8 @@ if (!this.blockInsecureContent) return {}; var strippedUrl = stripParams(details.url); - this.dispatchEvent(new CustomEvent('insecureContentBlocked', - {detail: {url: strippedUrl}})); + this.dispatchEvent(new CustomEvent( + 'insecureContentBlocked', {detail: {url: strippedUrl}})); return {cancel: true}; }, @@ -318,8 +313,8 @@ // requests will be coming from the IdP. Append a cookie to the // current |headers| that marks the point at which the redirect // occurred. - headers.push({name: 'Set-Cookie', - value: 'google-accounts-saml-start=now'}); + headers.push( + {name: 'Set-Cookie', value: 'google-accounts-saml-start=now'}); return {responseHeaders: headers}; } else if (action == 'end') { this.pendingIsSamlPage_ = false; @@ -344,8 +339,8 @@ // ignored by Chrome in cookie headers, causing the modified headers // to actually set the original cookies. var otherHeaders = []; - var cookies = [{name: 'Set-Cookie', - value: 'google-accounts-saml-end=now'}]; + var cookies = + [{name: 'Set-Cookie', value: 'google-accounts-saml-end=now'}]; for (var j = 0; j < headers.length; ++j) { if (headers[j].name.toLowerCase().startsWith('set-cookie')) { var header = headers[j]; @@ -373,8 +368,7 @@ var channel = Channel.create(); channel.init(port); - channel.registerMessage( - 'apiCall', this.onAPICall_.bind(this, channel)); + channel.registerMessage('apiCall', this.onAPICall_.bind(this, channel)); channel.registerMessage( 'updatePassword', this.onUpdatePassword_.bind(this, channel)); channel.registerMessage( @@ -384,18 +378,19 @@ }, sendInitializationSuccess_: function(channel) { - channel.send({name: 'apiResponse', response: { - result: 'initialized', - version: this.apiVersion_, - keyTypes: API_KEY_TYPES - }}); + channel.send({ + name: 'apiResponse', + response: { + result: 'initialized', + version: this.apiVersion_, + keyTypes: API_KEY_TYPES + } + }); }, sendInitializationFailure_: function(channel) { - channel.send({ - name: 'apiResponse', - response: {result: 'initialization_failed'} - }); + channel.send( + {name: 'apiResponse', response: {result: 'initialization_failed'}}); }, /** @@ -413,8 +408,8 @@ return; } - this.apiVersion_ = Math.min(call.requestedVersion, - MAX_API_VERSION_VERSION); + this.apiVersion_ = + Math.min(call.requestedVersion, MAX_API_VERSION_VERSION); this.apiInitialized_ = true; this.sendInitializationSuccess_(channel); return; @@ -446,11 +441,13 @@ onPageLoaded_: function(channel, msg) { this.authDomain = extractDomain(msg.url); - this.dispatchEvent(new CustomEvent( - 'authPageLoaded', - {detail: {url: url, - isSAMLPage: this.isSamlPage_, - domain: this.authDomain}})); + this.dispatchEvent(new CustomEvent('authPageLoaded', { + detail: { + url: url, + isSAMLPage: this.isSamlPage_, + domain: this.authDomain + } + })); }, onPermissionRequest_: function(permissionEvent) { @@ -467,7 +464,5 @@ }, }; - return { - SamlHandler: SamlHandler - }; + return {SamlHandler: SamlHandler}; });
diff --git a/chrome/browser/resources/gaia_auth_host/saml_injected.js b/chrome/browser/resources/gaia_auth_host/saml_injected.js index f79c626..ed1468e6 100644 --- a/chrome/browser/resources/gaia_auth_host/saml_injected.js +++ b/chrome/browser/resources/gaia_auth_host/saml_injected.js
@@ -15,204 +15,196 @@ */ (function() { - function APICallForwarder() { - } +function APICallForwarder() {} + +/** + * The credential passing API is used by sending messages to the SAML page's + * |window| object. This class forwards API calls from the SAML page to a + * background script and API responses from the background script to the SAML + * page. Communication with the background script occurs via a |Channel|. + */ +APICallForwarder.prototype = { + // Channel to which API calls are forwarded. + channel_: null, /** - * The credential passing API is used by sending messages to the SAML page's - * |window| object. This class forwards API calls from the SAML page to a - * background script and API responses from the background script to the SAML - * page. Communication with the background script occurs via a |Channel|. + * Initialize the API call forwarder. + * @param {!Object} channel Channel to which API calls should be forwarded. */ - APICallForwarder.prototype = { - // Channel to which API calls are forwarded. - channel_: null, + init: function(channel) { + this.channel_ = channel; + this.channel_.registerMessage( + 'apiResponse', this.onAPIResponse_.bind(this)); - /** - * Initialize the API call forwarder. - * @param {!Object} channel Channel to which API calls should be forwarded. - */ - init: function(channel) { - this.channel_ = channel; - this.channel_.registerMessage('apiResponse', - this.onAPIResponse_.bind(this)); + window.addEventListener('message', this.onMessage_.bind(this)); + }, - window.addEventListener('message', this.onMessage_.bind(this)); - }, - - onMessage_: function(event) { - if (event.source != window || - typeof event.data != 'object' || - !event.data.hasOwnProperty('type') || - event.data.type != 'gaia_saml_api') { - return; - } - // Forward API calls to the background script. - this.channel_.send({name: 'apiCall', call: event.data.call}); - }, - - onAPIResponse_: function(msg) { - // Forward API responses to the SAML page. - window.postMessage({type: 'gaia_saml_api_reply', response: msg.response}, - '/'); + onMessage_: function(event) { + if (event.source != window || typeof event.data != 'object' || + !event.data.hasOwnProperty('type') || + event.data.type != 'gaia_saml_api') { + return; } - }; + // Forward API calls to the background script. + this.channel_.send({name: 'apiCall', call: event.data.call}); + }, + + onAPIResponse_: function(msg) { + // Forward API responses to the SAML page. + window.postMessage( + {type: 'gaia_saml_api_reply', response: msg.response}, '/'); + } +}; + +/** + * A class to scrape password from type=password input elements under a given + * docRoot and send them back via a Channel. + */ +function PasswordInputScraper() {} + +PasswordInputScraper.prototype = { + // URL of the page. + pageURL_: null, + + // Channel to send back changed password. + channel_: null, + + // An array to hold password fields. + passwordFields_: null, + + // An array to hold cached password values. + passwordValues_: null, + + // A MutationObserver to watch for dynamic password field creation. + passwordFieldsObserver: null, /** - * A class to scrape password from type=password input elements under a given - * docRoot and send them back via a Channel. + * Initialize the scraper with given channel and docRoot. Note that the + * scanning for password fields happens inside the function and does not + * handle DOM tree changes after the call returns. + * @param {!Object} channel The channel to send back password. + * @param {!string} pageURL URL of the page. + * @param {!HTMLElement} docRoot The root element of the DOM tree that + * contains the password fields of interest. */ - function PasswordInputScraper() { - } + init: function(channel, pageURL, docRoot) { + this.pageURL_ = pageURL; + this.channel_ = channel; - PasswordInputScraper.prototype = { - // URL of the page. - pageURL_: null, + this.passwordFields_ = []; + this.passwordValues_ = []; - // Channel to send back changed password. - channel_: null, + this.findAndTrackChildren(docRoot); - // An array to hold password fields. - passwordFields_: null, + this.passwordFieldsObserver = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + Array.prototype.forEach.call(mutation.addedNodes, function(addedNode) { + if (addedNode.nodeType != Node.ELEMENT_NODE) + return; - // An array to hold cached password values. - passwordValues_: null, - - // A MutationObserver to watch for dynamic password field creation. - passwordFieldsObserver: null, - - /** - * Initialize the scraper with given channel and docRoot. Note that the - * scanning for password fields happens inside the function and does not - * handle DOM tree changes after the call returns. - * @param {!Object} channel The channel to send back password. - * @param {!string} pageURL URL of the page. - * @param {!HTMLElement} docRoot The root element of the DOM tree that - * contains the password fields of interest. - */ - init: function(channel, pageURL, docRoot) { - this.pageURL_ = pageURL; - this.channel_ = channel; - - this.passwordFields_ = []; - this.passwordValues_ = []; - - this.findAndTrackChildren(docRoot); - - this.passwordFieldsObserver = new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - Array.prototype.forEach.call( - mutation.addedNodes, - function(addedNode) { - if (addedNode.nodeType != Node.ELEMENT_NODE) - return; - - if (addedNode.matches('input[type=password]')) { - this.trackPasswordField(addedNode); - } else { - this.findAndTrackChildren(addedNode); - } - }.bind(this)); + if (addedNode.matches('input[type=password]')) { + this.trackPasswordField(addedNode); + } else { + this.findAndTrackChildren(addedNode); + } }.bind(this)); }.bind(this)); - this.passwordFieldsObserver.observe(docRoot, - {subtree: true, childList: true}); - }, + }.bind(this)); + this.passwordFieldsObserver.observe( + docRoot, {subtree: true, childList: true}); + }, - /** - * Find and track password fields that are descendants of the given element. - * @param {!HTMLElement} element The parent element to search from. - */ - findAndTrackChildren: function(element) { - Array.prototype.forEach.call( - element.querySelectorAll('input[type=password]'), function(field) { - this.trackPasswordField(field); - }.bind(this)); - }, + /** + * Find and track password fields that are descendants of the given element. + * @param {!HTMLElement} element The parent element to search from. + */ + findAndTrackChildren: function(element) { + Array.prototype.forEach.call( + element.querySelectorAll('input[type=password]'), function(field) { + this.trackPasswordField(field); + }.bind(this)); + }, - /** - * Start tracking value changes of the given password field if it is - * not being tracked yet. - * @param {!HTMLInputElement} passworField The password field to track. - */ - trackPasswordField: function(passwordField) { - var existing = this.passwordFields_.filter(function(element) { - return element === passwordField; - }); - if (existing.length != 0) - return; + /** + * Start tracking value changes of the given password field if it is + * not being tracked yet. + * @param {!HTMLInputElement} passworField The password field to track. + */ + trackPasswordField: function(passwordField) { + var existing = this.passwordFields_.filter(function(element) { + return element === passwordField; + }); + if (existing.length != 0) + return; - var index = this.passwordFields_.length; - var fieldId = passwordField.id || passwordField.name || ''; - passwordField.addEventListener( - 'input', this.onPasswordChanged_.bind(this, index, fieldId)); - this.passwordFields_.push(passwordField); - this.passwordValues_.push(passwordField.value); - }, + var index = this.passwordFields_.length; + var fieldId = passwordField.id || passwordField.name || ''; + passwordField.addEventListener( + 'input', this.onPasswordChanged_.bind(this, index, fieldId)); + this.passwordFields_.push(passwordField); + this.passwordValues_.push(passwordField.value); + }, - /** - * Check if the password field at |index| has changed. If so, sends back - * the updated value. - */ - maybeSendUpdatedPassword: function(index, fieldId) { - var newValue = this.passwordFields_[index].value; - if (newValue == this.passwordValues_[index]) - return; + /** + * Check if the password field at |index| has changed. If so, sends back + * the updated value. + */ + maybeSendUpdatedPassword: function(index, fieldId) { + var newValue = this.passwordFields_[index].value; + if (newValue == this.passwordValues_[index]) + return; - this.passwordValues_[index] = newValue; + this.passwordValues_[index] = newValue; - // Use an invalid char for URL as delimiter to concatenate page url, - // password field index and id to construct a unique ID for the password - // field. - var passwordId = this.pageURL_.split('#')[0].split('?')[0] + - '|' + index + '|' + fieldId; - this.channel_.send({ - name: 'updatePassword', - id: passwordId, - password: newValue - }); - }, + // Use an invalid char for URL as delimiter to concatenate page url, + // password field index and id to construct a unique ID for the password + // field. + var passwordId = + this.pageURL_.split('#')[0].split('?')[0] + '|' + index + '|' + fieldId; + this.channel_.send( + {name: 'updatePassword', id: passwordId, password: newValue}); + }, - /** - * Handles 'change' event in the scraped password fields. - * @param {number} index The index of the password fields in - * |passwordFields_|. - * @param {string} fieldId The id or name of the password field or blank. - */ - onPasswordChanged_: function(index, fieldId) { - this.maybeSendUpdatedPassword(index, fieldId); - } + /** + * Handles 'change' event in the scraped password fields. + * @param {number} index The index of the password fields in + * |passwordFields_|. + * @param {string} fieldId The id or name of the password field or blank. + */ + onPasswordChanged_: function(index, fieldId) { + this.maybeSendUpdatedPassword(index, fieldId); + } +}; + +function onGetSAMLFlag(channel, isSAMLPage) { + if (!isSAMLPage) + return; + var pageURL = window.location.href; + + channel.send({name: 'pageLoaded', url: pageURL}); + + var initPasswordScraper = function() { + var passwordScraper = new PasswordInputScraper(); + passwordScraper.init(channel, pageURL, document.documentElement); }; - function onGetSAMLFlag(channel, isSAMLPage) { - if (!isSAMLPage) - return; - var pageURL = window.location.href; - - channel.send({name: 'pageLoaded', url: pageURL}); - - var initPasswordScraper = function() { - var passwordScraper = new PasswordInputScraper(); - passwordScraper.init(channel, pageURL, document.documentElement); - }; - - if (document.readyState == 'loading') { - window.addEventListener('readystatechange', function listener(event) { - if (document.readyState == 'loading') - return; - initPasswordScraper(); - window.removeEventListener(event.type, listener, true); - }, true); - } else { + if (document.readyState == 'loading') { + window.addEventListener('readystatechange', function listener(event) { + if (document.readyState == 'loading') + return; initPasswordScraper(); - } + window.removeEventListener(event.type, listener, true); + }, true); + } else { + initPasswordScraper(); } +} - var channel = Channel.create(); - channel.connect('injected'); - channel.sendWithCallback({name: 'getSAMLFlag'}, - onGetSAMLFlag.bind(undefined, channel)); +var channel = Channel.create(); +channel.connect('injected'); +channel.sendWithCallback( + {name: 'getSAMLFlag'}, onGetSAMLFlag.bind(undefined, channel)); - var apiCallForwarder = new APICallForwarder(); - apiCallForwarder.init(channel); +var apiCallForwarder = new APICallForwarder(); +apiCallForwarder.init(channel); })();
diff --git a/chrome/browser/resources/hangout_services/thunk.js b/chrome/browser/resources/hangout_services/thunk.js index e2a966d..43f12df 100644 --- a/chrome/browser/resources/hangout_services/thunk.js +++ b/chrome/browser/resources/hangout_services/thunk.js
@@ -2,211 +2,205 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -chrome.runtime.onMessageExternal.addListener( - function(message, sender, sendResponse) { - function doSendResponse(value, errorString) { - var error = null; - if (errorString) { - error = {}; - error['name'] = 'ComponentExtensionError'; - error['message'] = errorString; - } +chrome.runtime.onMessageExternal.addListener(function( + message, sender, sendResponse) { + function doSendResponse(value, errorString) { + var error = null; + if (errorString) { + error = {}; + error['name'] = 'ComponentExtensionError'; + error['message'] = errorString; + } - var errorMessage = error || chrome.extension.lastError; - sendResponse({'value': value, 'error': errorMessage}); + var errorMessage = error || chrome.extension.lastError; + sendResponse({'value': value, 'error': errorMessage}); + } + + function getHost(url) { + if (!url) + return ''; + // Use the DOM to parse the URL. Since we don't add the anchor to + // the page, this is the only reference to it and it will be + // deleted once it's gone out of scope. + var a = document.createElement('a'); + a.href = url; + var origin = a.protocol + '//' + a.hostname; + if (a.port != '') + origin = origin + ':' + a.port; + origin = origin + '/'; + return origin; + } + + try { + var requestInfo = {}; + + // Set the tab ID. If it's passed in the message, use that. + // Otherwise use the sender information. + if (message['tabId']) { + requestInfo['tabId'] = +message['tabId']; + if (isNaN(requestInfo['tabId'])) { + throw new Error( + 'Cannot convert tab ID string to integer: ' + message['tabId']); } + } else if (sender.tab) { + requestInfo['tabId'] = sender.tab.id; + } - function getHost(url) { - if (!url) - return ''; - // Use the DOM to parse the URL. Since we don't add the anchor to - // the page, this is the only reference to it and it will be - // deleted once it's gone out of scope. - var a = document.createElement('a'); - a.href = url; - var origin = a.protocol + '//' + a.hostname; - if (a.port != '') - origin = origin + ':' + a.port; - origin = origin + '/'; - return origin; - } + if (sender.guestProcessId) { + requestInfo['guestProcessId'] = sender.guestProcessId; + } - try { - var requestInfo = {}; + var method = message['method']; - // Set the tab ID. If it's passed in the message, use that. - // Otherwise use the sender information. - if (message['tabId']) { - requestInfo['tabId'] = +message['tabId']; - if (isNaN(requestInfo['tabId'])) { - throw new Error('Cannot convert tab ID string to integer: ' + - message['tabId']); - } - } else if (sender.tab) { - requestInfo['tabId'] = sender.tab.id; - } + // Set the origin. If a URL is passed in the message, use that. + // Otherwise use the sender information. + var origin; + if (message['winUrl']) { + origin = getHost(message['winUrl']); + } else { + origin = getHost(sender.url); + } - if (sender.guestProcessId) { - requestInfo['guestProcessId'] = sender.guestProcessId; - } - - var method = message['method']; - - // Set the origin. If a URL is passed in the message, use that. - // Otherwise use the sender information. - var origin; - if (message['winUrl']) { - origin = getHost(message['winUrl']); - } else { - origin = getHost(sender.url); - } - - if (method == 'cpu.getInfo') { - chrome.system.cpu.getInfo(doSendResponse); - return true; - } else if (method == 'logging.setMetadata') { - var metaData = message['metaData']; - chrome.webrtcLoggingPrivate.setMetaData( - requestInfo, origin, metaData, doSendResponse); - return true; - } else if (method == 'logging.start') { - chrome.webrtcLoggingPrivate.start( - requestInfo, origin, doSendResponse); - return true; - } else if (method == 'logging.uploadOnRenderClose') { - chrome.webrtcLoggingPrivate.setUploadOnRenderClose( - requestInfo, origin, true); - doSendResponse(); - return false; - } else if (method == 'logging.noUploadOnRenderClose') { - chrome.webrtcLoggingPrivate.setUploadOnRenderClose( - requestInfo, origin, false); - doSendResponse(); - return false; - } else if (method == 'logging.stop') { - chrome.webrtcLoggingPrivate.stop( - requestInfo, origin, doSendResponse); - return true; - } else if (method == 'logging.upload') { - chrome.webrtcLoggingPrivate.upload( - requestInfo, origin, doSendResponse); - return true; - } else if (method == 'logging.uploadStored') { - var logId = message['logId']; - chrome.webrtcLoggingPrivate.uploadStored( - requestInfo, origin, logId, doSendResponse); - return true; - } else if (method == 'logging.stopAndUpload') { - // Stop everything and upload. This is allowed to be called even if - // logs have already been stopped or not started. Therefore, ignore - // any errors along the way, but store them, so that if upload fails - // they are all reported back. - // Stop incoming and outgoing RTP dumps separately, otherwise - // stopRtpDump will fail and not stop anything if either type has not - // been started. - var errors = []; - chrome.webrtcLoggingPrivate.stopRtpDump( - requestInfo, origin, true /* incoming */, false /* outgoing */, - function() { + if (method == 'cpu.getInfo') { + chrome.system.cpu.getInfo(doSendResponse); + return true; + } else if (method == 'logging.setMetadata') { + var metaData = message['metaData']; + chrome.webrtcLoggingPrivate.setMetaData( + requestInfo, origin, metaData, doSendResponse); + return true; + } else if (method == 'logging.start') { + chrome.webrtcLoggingPrivate.start(requestInfo, origin, doSendResponse); + return true; + } else if (method == 'logging.uploadOnRenderClose') { + chrome.webrtcLoggingPrivate.setUploadOnRenderClose( + requestInfo, origin, true); + doSendResponse(); + return false; + } else if (method == 'logging.noUploadOnRenderClose') { + chrome.webrtcLoggingPrivate.setUploadOnRenderClose( + requestInfo, origin, false); + doSendResponse(); + return false; + } else if (method == 'logging.stop') { + chrome.webrtcLoggingPrivate.stop(requestInfo, origin, doSendResponse); + return true; + } else if (method == 'logging.upload') { + chrome.webrtcLoggingPrivate.upload(requestInfo, origin, doSendResponse); + return true; + } else if (method == 'logging.uploadStored') { + var logId = message['logId']; + chrome.webrtcLoggingPrivate.uploadStored( + requestInfo, origin, logId, doSendResponse); + return true; + } else if (method == 'logging.stopAndUpload') { + // Stop everything and upload. This is allowed to be called even if + // logs have already been stopped or not started. Therefore, ignore + // any errors along the way, but store them, so that if upload fails + // they are all reported back. + // Stop incoming and outgoing RTP dumps separately, otherwise + // stopRtpDump will fail and not stop anything if either type has not + // been started. + var errors = []; + chrome.webrtcLoggingPrivate.stopRtpDump( + requestInfo, origin, true /* incoming */, false /* outgoing */, + function() { appendLastErrorMessage(errors); chrome.webrtcLoggingPrivate.stopRtpDump( requestInfo, origin, false /* incoming */, true /* outgoing */, function() { - appendLastErrorMessage(errors); - chrome.webrtcLoggingPrivate.stop( - requestInfo, origin, function() { - appendLastErrorMessage(errors); - chrome.webrtcLoggingPrivate.upload( - requestInfo, origin, - function(uploadValue) { - var errorMessage = null; - // If upload fails, report all previous errors. Otherwise, - // throw them away. - if (chrome.extension.lastError !== undefined) { - appendLastErrorMessage(errors); - errorMessage = errors.join('; '); - } - doSendResponse(uploadValue, errorMessage); + appendLastErrorMessage(errors); + chrome.webrtcLoggingPrivate.stop( + requestInfo, origin, function() { + appendLastErrorMessage(errors); + chrome.webrtcLoggingPrivate.upload( + requestInfo, origin, function(uploadValue) { + var errorMessage = null; + // If upload fails, report all previous errors. + // Otherwise, throw them away. + if (chrome.extension.lastError !== undefined) { + appendLastErrorMessage(errors); + errorMessage = errors.join('; '); + } + doSendResponse(uploadValue, errorMessage); + }); + }); }); - }); - }); }); - return true; - } else if (method == 'logging.store') { - var logId = message['logId']; - chrome.webrtcLoggingPrivate.store( - requestInfo, origin, logId, doSendResponse); - return true; - } else if (method == 'logging.discard') { - chrome.webrtcLoggingPrivate.discard( - requestInfo, origin, doSendResponse); - return true; - } else if (method == 'getSinks') { - chrome.webrtcAudioPrivate.getSinks(doSendResponse); - return true; - } else if (method == 'getAssociatedSink') { - var sourceId = message['sourceId']; - chrome.webrtcAudioPrivate.getAssociatedSink( - origin, sourceId, doSendResponse); - return true; - } else if (method == 'isExtensionEnabled') { - // This method is necessary because there may be more than one - // version of this extension, under different extension IDs. By - // first calling this method on the extension ID, the client can - // check if it's loaded; if it's not, the extension system will - // call the callback with no arguments and set - // chrome.runtime.lastError. - doSendResponse(); - return false; - } else if (method == 'getNaclArchitecture') { - chrome.runtime.getPlatformInfo(function(obj) { - doSendResponse(obj.nacl_arch); - }); - return true; - } else if (method == 'logging.startRtpDump') { - var incoming = message['incoming'] || false; - var outgoing = message['outgoing'] || false; - chrome.webrtcLoggingPrivate.startRtpDump( - requestInfo, origin, incoming, outgoing, doSendResponse); - return true; - } else if (method == 'logging.stopRtpDump') { - var incoming = message['incoming'] || false; - var outgoing = message['outgoing'] || false; - chrome.webrtcLoggingPrivate.stopRtpDump( - requestInfo, origin, incoming, outgoing, doSendResponse); - return true; - } else if (method == 'logging.startAudioDebugRecordings') { - var seconds = message['seconds'] || 0; - chrome.webrtcLoggingPrivate.startAudioDebugRecordings( - requestInfo, origin, seconds, doSendResponse); - return true; - } else if (method == 'logging.stopAudioDebugRecordings') { - chrome.webrtcLoggingPrivate.stopAudioDebugRecordings( - requestInfo, origin, doSendResponse); - return true; - } else if (method == 'logging.startWebRtcEventLogging') { - var seconds = message['seconds'] || 0; - chrome.webrtcLoggingPrivate.startWebRtcEventLogging( - requestInfo, origin, seconds, doSendResponse); - return true; - } else if (method == 'logging.stopWebRtcEventLogging') { - chrome.webrtcLoggingPrivate.stopWebRtcEventLogging( - requestInfo, origin, doSendResponse); - return true; - } else if (method == 'setAudioExperiments') { - var experiments = message['experiments']; - chrome.webrtcAudioPrivate.setAudioExperiments( - requestInfo, origin, experiments); - doSendResponse(); - return false; - } - - throw new Error('Unknown method: ' + method); - } catch (e) { - doSendResponse(null, e.name + ': ' + e.message); - } + return true; + } else if (method == 'logging.store') { + var logId = message['logId']; + chrome.webrtcLoggingPrivate.store( + requestInfo, origin, logId, doSendResponse); + return true; + } else if (method == 'logging.discard') { + chrome.webrtcLoggingPrivate.discard(requestInfo, origin, doSendResponse); + return true; + } else if (method == 'getSinks') { + chrome.webrtcAudioPrivate.getSinks(doSendResponse); + return true; + } else if (method == 'getAssociatedSink') { + var sourceId = message['sourceId']; + chrome.webrtcAudioPrivate.getAssociatedSink( + origin, sourceId, doSendResponse); + return true; + } else if (method == 'isExtensionEnabled') { + // This method is necessary because there may be more than one + // version of this extension, under different extension IDs. By + // first calling this method on the extension ID, the client can + // check if it's loaded; if it's not, the extension system will + // call the callback with no arguments and set + // chrome.runtime.lastError. + doSendResponse(); + return false; + } else if (method == 'getNaclArchitecture') { + chrome.runtime.getPlatformInfo(function(obj) { + doSendResponse(obj.nacl_arch); + }); + return true; + } else if (method == 'logging.startRtpDump') { + var incoming = message['incoming'] || false; + var outgoing = message['outgoing'] || false; + chrome.webrtcLoggingPrivate.startRtpDump( + requestInfo, origin, incoming, outgoing, doSendResponse); + return true; + } else if (method == 'logging.stopRtpDump') { + var incoming = message['incoming'] || false; + var outgoing = message['outgoing'] || false; + chrome.webrtcLoggingPrivate.stopRtpDump( + requestInfo, origin, incoming, outgoing, doSendResponse); + return true; + } else if (method == 'logging.startAudioDebugRecordings') { + var seconds = message['seconds'] || 0; + chrome.webrtcLoggingPrivate.startAudioDebugRecordings( + requestInfo, origin, seconds, doSendResponse); + return true; + } else if (method == 'logging.stopAudioDebugRecordings') { + chrome.webrtcLoggingPrivate.stopAudioDebugRecordings( + requestInfo, origin, doSendResponse); + return true; + } else if (method == 'logging.startWebRtcEventLogging') { + var seconds = message['seconds'] || 0; + chrome.webrtcLoggingPrivate.startWebRtcEventLogging( + requestInfo, origin, seconds, doSendResponse); + return true; + } else if (method == 'logging.stopWebRtcEventLogging') { + chrome.webrtcLoggingPrivate.stopWebRtcEventLogging( + requestInfo, origin, doSendResponse); + return true; + } else if (method == 'setAudioExperiments') { + var experiments = message['experiments']; + chrome.webrtcAudioPrivate.setAudioExperiments( + requestInfo, origin, experiments); + doSendResponse(); + return false; } -); + + throw new Error('Unknown method: ' + method); + } catch (e) { + doSendResponse(null, e.name + ': ' + e.message); + } +}); // If Hangouts connects with a port named 'onSinksChangedListener', we // will register a listener and send it a message {'eventName': @@ -218,8 +212,7 @@ chrome.webrtcAudioPrivate.onSinksChanged.addListener(clientListener); port.onDisconnect.addListener(function() { - chrome.webrtcAudioPrivate.onSinksChanged.removeListener( - clientListener); + chrome.webrtcAudioPrivate.onSinksChanged.removeListener(clientListener); }); } @@ -287,8 +280,9 @@ browserProcessCpu = process.cpu; } else if (process.type == 'gpu') { gpuProcessCpu = process.cpu; - } else if ((process.type == 'plugin' || process.type == 'nacl') && - process.title.toLowerCase().indexOf('hangouts') > 0) { + } else if ( + (process.type == 'plugin' || process.type == 'nacl') && + process.title.toLowerCase().indexOf('hangouts') > 0) { pluginProcessCpu = process.cpu; } }
diff --git a/chrome/browser/resources/hotword/audio_client.js b/chrome/browser/resources/hotword/audio_client.js index 25d227a9..552dd49 100644 --- a/chrome/browser/resources/hotword/audio_client.js +++ b/chrome/browser/resources/hotword/audio_client.js
@@ -13,364 +13,363 @@ */ (function() { - /** - * @constructor - */ - var AudioClient = function() { - /** @private {Element} */ - this.speechOverlay_ = null; +/** + * @constructor + */ +var AudioClient = function() { + /** @private {Element} */ + this.speechOverlay_ = null; - /** @private {number} */ + /** @private {number} */ + this.checkSpeechUiRetries_ = 0; + + /** + * Port used to communicate with the audio manager. + * @private {?Port} + */ + this.port_ = null; + + /** + * Keeps track of the effects of different commands. Used to verify that + * proper UIs are shown to the user. + * @private {Object<AudioClient.CommandToPage, Object>} + */ + this.uiStatus_ = null; + + /** + * Bound function used to handle commands sent from the page to this script. + * @private {Function} + */ + this.handleCommandFromPageFunc_ = null; +}; + +/** + * Messages sent to the page to control the voice search UI. + * @enum {string} + */ +AudioClient.CommandToPage = { + HOTWORD_VOICE_TRIGGER: 'vt', + HOTWORD_STARTED: 'hs', + HOTWORD_ENDED: 'hd', + HOTWORD_TIMEOUT: 'ht', + HOTWORD_ERROR: 'he' +}; + +/** + * Messages received from the page used to indicate voice search state. + * @enum {string} + */ +AudioClient.CommandFromPage = { + SPEECH_START: 'ss', + SPEECH_END: 'se', + SPEECH_RESET: 'sr', + SHOWING_HOTWORD_START: 'shs', + SHOWING_ERROR_MESSAGE: 'sem', + SHOWING_TIMEOUT_MESSAGE: 'stm', + CLICKED_RESUME: 'hcc', + CLICKED_RESTART: 'hcr', + CLICKED_DEBUG: 'hcd' +}; + +/** + * Errors that are sent to the hotword extension. + * @enum {string} + */ +AudioClient.Error = { + NO_SPEECH_UI: 'ac1', + NO_HOTWORD_STARTED_UI: 'ac2', + NO_HOTWORD_TIMEOUT_UI: 'ac3', + NO_HOTWORD_ERROR_UI: 'ac4' +}; + +/** + * @const {string} + * @private + */ +AudioClient.HOTWORD_EXTENSION_ID_ = 'nbpagnldghgfoolbancepceaanlmhfmd'; + +/** + * Number of times to retry checking a transient error. + * @const {number} + * @private + */ +AudioClient.MAX_RETRIES = 3; + +/** + * Delay to wait in milliseconds before rechecking for any transient errors. + * @const {number} + * @private + */ +AudioClient.RETRY_TIME_MS_ = 2000; + +/** + * DOM ID for the speech UI overlay. + * @const {string} + * @private + */ +AudioClient.SPEECH_UI_OVERLAY_ID_ = 'spch'; + +/** + * @const {string} + * @private + */ +AudioClient.HELP_CENTER_URL_ = + 'https://support.google.com/chrome/?p=ui_hotword_search'; + +/** + * @const {string} + * @private + */ +AudioClient.CLIENT_PORT_NAME_ = 'chwcpn'; + +/** + * Existence of the Audio Client. + * @const {string} + * @private + */ +AudioClient.EXISTS_ = 'chwace'; + +/** + * Checks for the presence of speech overlay UI DOM elements. + * @private + */ +AudioClient.prototype.checkSpeechOverlayUi_ = function() { + if (!this.speechOverlay_) { + window.setTimeout( + this.delayedCheckSpeechOverlayUi_.bind(this), + AudioClient.RETRY_TIME_MS_); + } else { this.checkSpeechUiRetries_ = 0; + } +}; - /** - * Port used to communicate with the audio manager. - * @private {?Port} - */ - this.port_ = null; - - /** - * Keeps track of the effects of different commands. Used to verify that - * proper UIs are shown to the user. - * @private {Object<AudioClient.CommandToPage, Object>} - */ - this.uiStatus_ = null; - - /** - * Bound function used to handle commands sent from the page to this script. - * @private {Function} - */ - this.handleCommandFromPageFunc_ = null; - }; - - /** - * Messages sent to the page to control the voice search UI. - * @enum {string} - */ - AudioClient.CommandToPage = { - HOTWORD_VOICE_TRIGGER: 'vt', - HOTWORD_STARTED: 'hs', - HOTWORD_ENDED: 'hd', - HOTWORD_TIMEOUT: 'ht', - HOTWORD_ERROR: 'he' - }; - - /** - * Messages received from the page used to indicate voice search state. - * @enum {string} - */ - AudioClient.CommandFromPage = { - SPEECH_START: 'ss', - SPEECH_END: 'se', - SPEECH_RESET: 'sr', - SHOWING_HOTWORD_START: 'shs', - SHOWING_ERROR_MESSAGE: 'sem', - SHOWING_TIMEOUT_MESSAGE: 'stm', - CLICKED_RESUME: 'hcc', - CLICKED_RESTART: 'hcr', - CLICKED_DEBUG: 'hcd' - }; - - /** - * Errors that are sent to the hotword extension. - * @enum {string} - */ - AudioClient.Error = { - NO_SPEECH_UI: 'ac1', - NO_HOTWORD_STARTED_UI: 'ac2', - NO_HOTWORD_TIMEOUT_UI: 'ac3', - NO_HOTWORD_ERROR_UI: 'ac4' - }; - - /** - * @const {string} - * @private - */ - AudioClient.HOTWORD_EXTENSION_ID_ = 'nbpagnldghgfoolbancepceaanlmhfmd'; - - /** - * Number of times to retry checking a transient error. - * @const {number} - * @private - */ - AudioClient.MAX_RETRIES = 3; - - /** - * Delay to wait in milliseconds before rechecking for any transient errors. - * @const {number} - * @private - */ - AudioClient.RETRY_TIME_MS_ = 2000; - - /** - * DOM ID for the speech UI overlay. - * @const {string} - * @private - */ - AudioClient.SPEECH_UI_OVERLAY_ID_ = 'spch'; - - /** - * @const {string} - * @private - */ - AudioClient.HELP_CENTER_URL_ = - 'https://support.google.com/chrome/?p=ui_hotword_search'; - - /** - * @const {string} - * @private - */ - AudioClient.CLIENT_PORT_NAME_ = 'chwcpn'; - - /** - * Existence of the Audio Client. - * @const {string} - * @private - */ - AudioClient.EXISTS_ = 'chwace'; - - /** - * Checks for the presence of speech overlay UI DOM elements. - * @private - */ - AudioClient.prototype.checkSpeechOverlayUi_ = function() { - if (!this.speechOverlay_) { - window.setTimeout( - this.delayedCheckSpeechOverlayUi_.bind(this), - AudioClient.RETRY_TIME_MS_); +/** + * Function called to check for the speech UI overlay after some time has + * passed since an initial check. Will either retry triggering the speech + * or sends an error message depending on the number of retries. + * @private + */ +AudioClient.prototype.delayedCheckSpeechOverlayUi_ = function() { + this.speechOverlay_ = + document.getElementById(AudioClient.SPEECH_UI_OVERLAY_ID_); + if (!this.speechOverlay_) { + if (this.checkSpeechUiRetries_++ < AudioClient.MAX_RETRIES) { + this.sendCommandToPage_(AudioClient.CommandToPage.VOICE_TRIGGER); + this.checkSpeechOverlayUi_(); } else { - this.checkSpeechUiRetries_ = 0; + this.sendCommandToExtension_(AudioClient.Error.NO_SPEECH_UI); } - }; + } else { + this.checkSpeechUiRetries_ = 0; + } +}; - /** - * Function called to check for the speech UI overlay after some time has - * passed since an initial check. Will either retry triggering the speech - * or sends an error message depending on the number of retries. - * @private - */ - AudioClient.prototype.delayedCheckSpeechOverlayUi_ = function() { - this.speechOverlay_ = - document.getElementById(AudioClient.SPEECH_UI_OVERLAY_ID_); - if (!this.speechOverlay_) { - if (this.checkSpeechUiRetries_++ < AudioClient.MAX_RETRIES) { - this.sendCommandToPage_(AudioClient.CommandToPage.VOICE_TRIGGER); +/** + * Checks that the triggered UI is actually displayed. + * @param {AudioClient.CommandToPage} command Command that was send. + * @private + */ +AudioClient.prototype.checkUi_ = function(command) { + this.uiStatus_[command].timeoutId = window.setTimeout( + this.failedCheckUi_.bind(this, command), AudioClient.RETRY_TIME_MS_); +}; + +/** + * Function called when the UI verification is not called in time. Will either + * retry the command or sends an error message, depending on the number of + * retries for the command. + * @param {AudioClient.CommandToPage} command Command that was sent. + * @private + */ +AudioClient.prototype.failedCheckUi_ = function(command) { + if (this.uiStatus_[command].tries++ < AudioClient.MAX_RETRIES) { + this.sendCommandToPage_(command); + this.checkUi_(command); + } else { + this.sendCommandToExtension_(this.uiStatus_[command].error); + } +}; + +/** + * Confirm that an UI element has been shown. + * @param {AudioClient.CommandToPage} command UI to confirm. + * @private + */ +AudioClient.prototype.verifyUi_ = function(command) { + if (this.uiStatus_[command].timeoutId) { + window.clearTimeout(this.uiStatus_[command].timeoutId); + this.uiStatus_[command].timeoutId = null; + this.uiStatus_[command].tries = 0; + } +}; + +/** + * Sends a command to the audio manager. + * @param {string} commandStr command to send to plugin. + * @private + */ +AudioClient.prototype.sendCommandToExtension_ = function(commandStr) { + if (this.port_) + this.port_.postMessage({'cmd': commandStr}); +}; + +/** + * Handles a message from the audio manager. + * @param {{cmd: string}} commandObj Command from the audio manager. + * @private + */ +AudioClient.prototype.handleCommandFromExtension_ = function(commandObj) { + var command = commandObj['cmd']; + if (command) { + switch (command) { + case AudioClient.CommandToPage.HOTWORD_VOICE_TRIGGER: + this.sendCommandToPage_(command); this.checkSpeechOverlayUi_(); - } else { - this.sendCommandToExtension_(AudioClient.Error.NO_SPEECH_UI); - } - } else { - this.checkSpeechUiRetries_ = 0; + break; + case AudioClient.CommandToPage.HOTWORD_STARTED: + this.sendCommandToPage_(command); + this.checkUi_(command); + break; + case AudioClient.CommandToPage.HOTWORD_ENDED: + this.sendCommandToPage_(command); + break; + case AudioClient.CommandToPage.HOTWORD_TIMEOUT: + this.sendCommandToPage_(command); + this.checkUi_(command); + break; + case AudioClient.CommandToPage.HOTWORD_ERROR: + this.sendCommandToPage_(command); + this.checkUi_(command); + break; } - }; + } +}; - /** - * Checks that the triggered UI is actually displayed. - * @param {AudioClient.CommandToPage} command Command that was send. - * @private - */ - AudioClient.prototype.checkUi_ = function(command) { - this.uiStatus_[command].timeoutId = window.setTimeout( - this.failedCheckUi_.bind(this, command), AudioClient.RETRY_TIME_MS_); - }; +/** + * @param {AudioClient.CommandToPage} commandStr Command to send. + * @private + */ +AudioClient.prototype.sendCommandToPage_ = function(commandStr) { + window.postMessage({'type': commandStr}, '*'); +}; - /** - * Function called when the UI verification is not called in time. Will either - * retry the command or sends an error message, depending on the number of - * retries for the command. - * @param {AudioClient.CommandToPage} command Command that was sent. - * @private - */ - AudioClient.prototype.failedCheckUi_ = function(command) { - if (this.uiStatus_[command].tries++ < AudioClient.MAX_RETRIES) { - this.sendCommandToPage_(command); - this.checkUi_(command); - } else { - this.sendCommandToExtension_(this.uiStatus_[command].error); +/** + * Handles a message from the html window. + * @param {!MessageEvent} messageEvent Message event from the window. + * @private + */ +AudioClient.prototype.handleCommandFromPage_ = function(messageEvent) { + if (messageEvent.source == window && messageEvent.data.type) { + var command = messageEvent.data.type; + switch (command) { + case AudioClient.CommandFromPage.SPEECH_START: + this.speechActive_ = true; + this.sendCommandToExtension_(command); + break; + case AudioClient.CommandFromPage.SPEECH_END: + this.speechActive_ = false; + this.sendCommandToExtension_(command); + break; + case AudioClient.CommandFromPage.SPEECH_RESET: + this.speechActive_ = false; + this.sendCommandToExtension_(command); + break; + case 'SPEECH_RESET': // Legacy, for embedded NTP. + this.speechActive_ = false; + this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_END); + break; + case AudioClient.CommandFromPage.CLICKED_RESUME: + this.sendCommandToExtension_(command); + break; + case AudioClient.CommandFromPage.CLICKED_RESTART: + this.sendCommandToExtension_(command); + break; + case AudioClient.CommandFromPage.CLICKED_DEBUG: + window.open(AudioClient.HELP_CENTER_URL_, '_blank'); + break; + case AudioClient.CommandFromPage.SHOWING_HOTWORD_START: + this.verifyUi_(AudioClient.CommandToPage.HOTWORD_STARTED); + break; + case AudioClient.CommandFromPage.SHOWING_ERROR_MESSAGE: + this.verifyUi_(AudioClient.CommandToPage.HOTWORD_ERROR); + break; + case AudioClient.CommandFromPage.SHOWING_TIMEOUT_MESSAGE: + this.verifyUi_(AudioClient.CommandToPage.HOTWORD_TIMEOUT); + break; } + } +}; + +/** + * Initialize the content script. + */ +AudioClient.prototype.initialize = function() { + if (AudioClient.EXISTS_ in window) + return; + window[AudioClient.EXISTS_] = true; + + // UI verification object. + this.uiStatus_ = {}; + this.uiStatus_[AudioClient.CommandToPage.HOTWORD_STARTED] = { + timeoutId: null, + tries: 0, + error: AudioClient.Error.NO_HOTWORD_STARTED_UI + }; + this.uiStatus_[AudioClient.CommandToPage.HOTWORD_TIMEOUT] = { + timeoutId: null, + tries: 0, + error: AudioClient.Error.NO_HOTWORD_TIMEOUT_UI + }; + this.uiStatus_[AudioClient.CommandToPage.HOTWORD_ERROR] = { + timeoutId: null, + tries: 0, + error: AudioClient.Error.NO_HOTWORD_ERROR_UI }; - /** - * Confirm that an UI element has been shown. - * @param {AudioClient.CommandToPage} command UI to confirm. - * @private - */ - AudioClient.prototype.verifyUi_ = function(command) { - if (this.uiStatus_[command].timeoutId) { - window.clearTimeout(this.uiStatus_[command].timeoutId); - this.uiStatus_[command].timeoutId = null; - this.uiStatus_[command].tries = 0; - } - }; + this.handleCommandFromPageFunc_ = this.handleCommandFromPage_.bind(this); + window.addEventListener('message', this.handleCommandFromPageFunc_, false); + this.initPort_(); +}; - /** - * Sends a command to the audio manager. - * @param {string} commandStr command to send to plugin. - * @private - */ - AudioClient.prototype.sendCommandToExtension_ = function(commandStr) { - if (this.port_) - this.port_.postMessage({'cmd': commandStr}); - }; +/** + * Initialize the communications port with the audio manager. This + * function will be also be called again if the audio-manager + * disconnects for some reason (such as the extension + * background.html page being reloaded). + * @private + */ +AudioClient.prototype.initPort_ = function() { + this.port_ = chrome.runtime.connect( + AudioClient.HOTWORD_EXTENSION_ID_, + {'name': AudioClient.CLIENT_PORT_NAME_}); + // Note that this listen may have to be destroyed manually if AudioClient + // is ever destroyed on this tab. + this.port_.onDisconnect.addListener( + (function(e) { + if (this.handleCommandFromPageFunc_) { + window.removeEventListener( + 'message', this.handleCommandFromPageFunc_, false); + } + delete window[AudioClient.EXISTS_]; + }).bind(this)); - /** - * Handles a message from the audio manager. - * @param {{cmd: string}} commandObj Command from the audio manager. - * @private - */ - AudioClient.prototype.handleCommandFromExtension_ = function(commandObj) { - var command = commandObj['cmd']; - if (command) { - switch (command) { - case AudioClient.CommandToPage.HOTWORD_VOICE_TRIGGER: - this.sendCommandToPage_(command); - this.checkSpeechOverlayUi_(); - break; - case AudioClient.CommandToPage.HOTWORD_STARTED: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - case AudioClient.CommandToPage.HOTWORD_ENDED: - this.sendCommandToPage_(command); - break; - case AudioClient.CommandToPage.HOTWORD_TIMEOUT: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - case AudioClient.CommandToPage.HOTWORD_ERROR: - this.sendCommandToPage_(command); - this.checkUi_(command); - break; - } - } - }; + // See note above. + this.port_.onMessage.addListener(this.handleCommandFromExtension_.bind(this)); - /** - * @param {AudioClient.CommandToPage} commandStr Command to send. - * @private - */ - AudioClient.prototype.sendCommandToPage_ = function(commandStr) { - window.postMessage({'type': commandStr}, '*'); - }; + if (this.speechActive_) { + this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_START); + } else { + // It's possible for this script to be injected into the page after it has + // completed loaded (i.e. when prerendering). In this case, this script + // won't receive a SPEECH_RESET from the page to forward onto the + // extension. To make up for this, always send a SPEECH_RESET. This means + // in most cases, the extension will receive SPEECH_RESET twice, one from + // this sendCommandToExtension_ and the one forwarded from the page. But + // that's OK and the extension can handle it. + this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_RESET); + } +}; - /** - * Handles a message from the html window. - * @param {!MessageEvent} messageEvent Message event from the window. - * @private - */ - AudioClient.prototype.handleCommandFromPage_ = function(messageEvent) { - if (messageEvent.source == window && messageEvent.data.type) { - var command = messageEvent.data.type; - switch (command) { - case AudioClient.CommandFromPage.SPEECH_START: - this.speechActive_ = true; - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.SPEECH_END: - this.speechActive_ = false; - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.SPEECH_RESET: - this.speechActive_ = false; - this.sendCommandToExtension_(command); - break; - case 'SPEECH_RESET': // Legacy, for embedded NTP. - this.speechActive_ = false; - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_END); - break; - case AudioClient.CommandFromPage.CLICKED_RESUME: - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.CLICKED_RESTART: - this.sendCommandToExtension_(command); - break; - case AudioClient.CommandFromPage.CLICKED_DEBUG: - window.open(AudioClient.HELP_CENTER_URL_, '_blank'); - break; - case AudioClient.CommandFromPage.SHOWING_HOTWORD_START: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_STARTED); - break; - case AudioClient.CommandFromPage.SHOWING_ERROR_MESSAGE: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_ERROR); - break; - case AudioClient.CommandFromPage.SHOWING_TIMEOUT_MESSAGE: - this.verifyUi_(AudioClient.CommandToPage.HOTWORD_TIMEOUT); - break; - } - } - }; - - /** - * Initialize the content script. - */ - AudioClient.prototype.initialize = function() { - if (AudioClient.EXISTS_ in window) - return; - window[AudioClient.EXISTS_] = true; - - // UI verification object. - this.uiStatus_ = {}; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_STARTED] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_STARTED_UI - }; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_TIMEOUT] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_TIMEOUT_UI - }; - this.uiStatus_[AudioClient.CommandToPage.HOTWORD_ERROR] = { - timeoutId: null, - tries: 0, - error: AudioClient.Error.NO_HOTWORD_ERROR_UI - }; - - this.handleCommandFromPageFunc_ = this.handleCommandFromPage_.bind(this); - window.addEventListener('message', this.handleCommandFromPageFunc_, false); - this.initPort_(); - }; - - /** - * Initialize the communications port with the audio manager. This - * function will be also be called again if the audio-manager - * disconnects for some reason (such as the extension - * background.html page being reloaded). - * @private - */ - AudioClient.prototype.initPort_ = function() { - this.port_ = chrome.runtime.connect( - AudioClient.HOTWORD_EXTENSION_ID_, - {'name': AudioClient.CLIENT_PORT_NAME_}); - // Note that this listen may have to be destroyed manually if AudioClient - // is ever destroyed on this tab. - this.port_.onDisconnect.addListener( - (function(e) { - if (this.handleCommandFromPageFunc_) { - window.removeEventListener( - 'message', this.handleCommandFromPageFunc_, false); - } - delete window[AudioClient.EXISTS_]; - }).bind(this)); - - // See note above. - this.port_.onMessage.addListener( - this.handleCommandFromExtension_.bind(this)); - - if (this.speechActive_) { - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_START); - } else { - // It's possible for this script to be injected into the page after it has - // completed loaded (i.e. when prerendering). In this case, this script - // won't receive a SPEECH_RESET from the page to forward onto the - // extension. To make up for this, always send a SPEECH_RESET. This means - // in most cases, the extension will receive SPEECH_RESET twice, one from - // this sendCommandToExtension_ and the one forwarded from the page. But - // that's OK and the extension can handle it. - this.sendCommandToExtension_(AudioClient.CommandFromPage.SPEECH_RESET); - } - }; - - // Initializes as soon as the code is ready, do not wait for the page. - new AudioClient().initialize(); +// Initializes as soon as the code is ready, do not wait for the page. +new AudioClient().initialize(); })();
diff --git a/chrome/browser/resources/hotword/manager.js b/chrome/browser/resources/hotword/manager.js index 54f3fce..f4ac147 100644 --- a/chrome/browser/resources/hotword/manager.js +++ b/chrome/browser/resources/hotword/manager.js
@@ -3,48 +3,48 @@ // found in the LICENSE file. (function() { - 'use strict'; +'use strict'; - /** - * @fileoverview This extension provides hotword triggering capabilites to - * Chrome. - * - * This extension contains all the JavaScript for loading and managing the - * hotword detector. The hotword detector and language model data will be - * provided by a shared module loaded from the web store. - * - * IMPORTANT! Whenever adding new events, the extension version number MUST be - * incremented. - */ +/** + * @fileoverview This extension provides hotword triggering capabilites to + * Chrome. + * + * This extension contains all the JavaScript for loading and managing the + * hotword detector. The hotword detector and language model data will be + * provided by a shared module loaded from the web store. + * + * IMPORTANT! Whenever adding new events, the extension version number MUST be + * incremented. + */ - // Hotwording state. - var stateManager = new hotword.StateManager(); - var pageAudioManager = new hotword.PageAudioManager(stateManager); - var alwaysOnManager = new hotword.AlwaysOnManager(stateManager); - var launcherManager = new hotword.LauncherManager(stateManager); - var trainingManager = new hotword.TrainingManager(stateManager); +// Hotwording state. +var stateManager = new hotword.StateManager(); +var pageAudioManager = new hotword.PageAudioManager(stateManager); +var alwaysOnManager = new hotword.AlwaysOnManager(stateManager); +var launcherManager = new hotword.LauncherManager(stateManager); +var trainingManager = new hotword.TrainingManager(stateManager); - // Detect when hotword settings have changed. - chrome.hotwordPrivate.onEnabledChanged.addListener(function() { - stateManager.updateStatus(); - }); +// Detect when hotword settings have changed. +chrome.hotwordPrivate.onEnabledChanged.addListener(function() { + stateManager.updateStatus(); +}); - // Detect a request to delete the speaker model. - chrome.hotwordPrivate.onDeleteSpeakerModel.addListener(function() { - hotword.TrainingManager.handleDeleteSpeakerModel(); - }); +// Detect a request to delete the speaker model. +chrome.hotwordPrivate.onDeleteSpeakerModel.addListener(function() { + hotword.TrainingManager.handleDeleteSpeakerModel(); +}); - // Detect a request for the speaker model existence. - chrome.hotwordPrivate.onSpeakerModelExists.addListener(function() { - hotword.TrainingManager.handleSpeakerModelExists(); - }); +// Detect a request for the speaker model existence. +chrome.hotwordPrivate.onSpeakerModelExists.addListener(function() { + hotword.TrainingManager.handleSpeakerModelExists(); +}); - // Detect when the shared module containing the NaCL module and language model - // is installed. - chrome.management.onInstalled.addListener(function(info) { - if (info.id == hotword.constants.SHARED_MODULE_ID) { - hotword.debug('Shared module installed, reloading extension.'); - chrome.runtime.reload(); - } - }); +// Detect when the shared module containing the NaCL module and language model +// is installed. +chrome.management.onInstalled.addListener(function(info) { + if (info.id == hotword.constants.SHARED_MODULE_ID) { + hotword.debug('Shared module installed, reloading extension.'); + chrome.runtime.reload(); + } +}); }());
diff --git a/chrome/browser/resources/hotword/nacl_manager.js b/chrome/browser/resources/hotword/nacl_manager.js index 85394f4..015399f3 100644 --- a/chrome/browser/resources/hotword/nacl_manager.js +++ b/chrome/browser/resources/hotword/nacl_manager.js
@@ -228,11 +228,11 @@ }; /** - * Checks whether the file at the given path exists. - * @param {!string} path Path to a file. Can be any valid URL. - * @return {boolean} True if the patch exists. - * @private - */ + * Checks whether the file at the given path exists. + * @param {!string} path Path to a file. Can be any valid URL. + * @return {boolean} True if the patch exists. + * @private + */ NaClManager.prototype.fileExists_ = function(path) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', path, false); @@ -248,11 +248,11 @@ }; /** - * Creates and returns a list of possible languages to check for hotword - * support. - * @return {!Array<string>} Array of languages. - * @private - */ + * Creates and returns a list of possible languages to check for hotword + * support. + * @return {!Array<string>} Array of languages. + * @private + */ NaClManager.prototype.getPossibleLanguages_ = function() { // Create array used to search first for language-country, if not found then // search for language, if not found then no language (empty string). @@ -273,11 +273,11 @@ }; /** - * Creates a NaCl plugin object and attaches it to the page. - * @param {!string} src Location of the plugin. - * @return {!HTMLEmbedElement} NaCl plugin DOM object. - * @private - */ + * Creates a NaCl plugin object and attaches it to the page. + * @param {!string} src Location of the plugin. + * @return {!HTMLEmbedElement} NaCl plugin DOM object. + * @private + */ NaClManager.prototype.createPlugin_ = function(src) { var plugin = /** @type {HTMLEmbedElement} */ (document.createElement('embed')); @@ -288,11 +288,11 @@ }; /** - * Initializes the NaCl manager. - * @param {!string} naclArch Either 'arm', 'x86-32' or 'x86-64'. - * @param {!MediaStream} stream A stream containing an audio source track. - * @return {boolean} True if the successful. - */ + * Initializes the NaCl manager. + * @param {!string} naclArch Either 'arm', 'x86-32' or 'x86-64'. + * @param {!MediaStream} stream A stream containing an audio source track. + * @return {boolean} True if the successful. + */ NaClManager.prototype.initialize = function(naclArch, stream) { assert( this.recognizerState_ == ManagerState_.UNINITIALIZED, @@ -377,7 +377,8 @@ */ NaClManager.prototype.waitForMessage_ = function(timeout, message) { assert( - this.expectingMessage_ == null, 'Cannot wait for message: ' + message + + this.expectingMessage_ == null, + 'Cannot wait for message: ' + message + ', already waiting for message ' + this.expectingMessage_); this.setTimeout_(function() { this.recognizerState_ = ManagerState_.ERROR;
diff --git a/chrome/browser/resources/hotword_audio_verification/event_page.js b/chrome/browser/resources/hotword_audio_verification/event_page.js index f63ae57..ea379d3 100644 --- a/chrome/browser/resources/hotword_audio_verification/event_page.js +++ b/chrome/browser/resources/hotword_audio_verification/event_page.js
@@ -22,9 +22,6 @@ 'resizable': false, 'hidden': true, 'id': appId, - 'innerBounds': { - 'width': 784, - 'height': 448 - } + 'innerBounds': {'width': 784, 'height': 448} }); });
diff --git a/chrome/browser/resources/hotword_audio_verification/flow.js b/chrome/browser/resources/hotword_audio_verification/flow.js index 9c0c4b0..c222114 100644 --- a/chrome/browser/resources/hotword_audio_verification/flow.js +++ b/chrome/browser/resources/hotword_audio_verification/flow.js
@@ -4,566 +4,563 @@ (function() { - // Correspond to steps in the hotword opt-in flow. - /** @const */ var START = 'start-container'; - /** @const */ var AUDIO_HISTORY = 'audio-history-container'; - /** @const */ var SPEECH_TRAINING = 'speech-training-container'; - /** @const */ var FINISH = 'finish-container'; +// Correspond to steps in the hotword opt-in flow. +/** @const */ var START = 'start-container'; +/** @const */ var AUDIO_HISTORY = 'audio-history-container'; +/** @const */ var SPEECH_TRAINING = 'speech-training-container'; +/** @const */ var FINISH = 'finish-container'; + +/** + * These flows correspond to the three LaunchModes as defined in + * chrome/browser/search/hotword_service.h and should be kept in sync + * with them. + * @const + */ +var FLOWS = [ + [START, SPEECH_TRAINING, FINISH], + [START, AUDIO_HISTORY, SPEECH_TRAINING, FINISH], [SPEECH_TRAINING, FINISH] +]; + +/** + * The launch mode. This enum needs to be kept in sync with that of + * the same name in hotword_service.h. + * @enum {number} + */ +var LaunchMode = {HOTWORD_ONLY: 0, HOTWORD_AND_AUDIO_HISTORY: 1, RETRAIN: 2}; + +/** + * The training state. + * @enum {string} + */ +var TrainingState = { + RESET: 'reset', + TIMEOUT: 'timeout', + ERROR: 'error', +}; + +/** + * Class to control the page flow of the always-on hotword and + * Audio History opt-in process. + * @constructor + */ +function Flow() { + this.currentStepIndex_ = -1; + this.currentFlow_ = []; /** - * These flows correspond to the three LaunchModes as defined in - * chrome/browser/search/hotword_service.h and should be kept in sync - * with them. - * @const + * The mode that this app was launched in. + * @private {LaunchMode} */ - var FLOWS = [ - [START, SPEECH_TRAINING, FINISH], - [START, AUDIO_HISTORY, SPEECH_TRAINING, FINISH], - [SPEECH_TRAINING, FINISH] - ]; + this.launchMode_ = LaunchMode.HOTWORD_AND_AUDIO_HISTORY; /** - * The launch mode. This enum needs to be kept in sync with that of - * the same name in hotword_service.h. - * @enum {number} + * Whether this flow is currently in the process of training a voice model. + * @private {boolean} */ - var LaunchMode = { - HOTWORD_ONLY: 0, - HOTWORD_AND_AUDIO_HISTORY: 1, - RETRAIN: 2 - }; + this.training_ = false; /** - * The training state. - * @enum {string} + * The current training state. + * @private {?TrainingState} */ - var TrainingState = { - RESET: 'reset', - TIMEOUT: 'timeout', - ERROR: 'error', - }; + this.trainingState_ = null; /** - * Class to control the page flow of the always-on hotword and - * Audio History opt-in process. - * @constructor + * Whether an expected hotword trigger has been received, indexed by + * training step. + * @private {boolean[]} */ - function Flow() { - this.currentStepIndex_ = -1; - this.currentFlow_ = []; + this.hotwordTriggerReceived_ = []; - /** - * The mode that this app was launched in. - * @private {LaunchMode} - */ - this.launchMode_ = LaunchMode.HOTWORD_AND_AUDIO_HISTORY; + /** + * Prefix of the element ids for the page that is currently training. + * @private {string} + */ + this.trainingPagePrefix_ = 'speech-training'; - /** - * Whether this flow is currently in the process of training a voice model. - * @private {boolean} - */ - this.training_ = false; + /** + * Whether the speaker model for this flow has been finalized. + * @private {boolean} + */ + this.speakerModelFinalized_ = false; - /** - * The current training state. - * @private {?TrainingState} - */ - this.trainingState_ = null; + /** + * ID of the currently active timeout. + * @private {?number} + */ + this.timeoutId_ = null; - /** - * Whether an expected hotword trigger has been received, indexed by - * training step. - * @private {boolean[]} - */ - this.hotwordTriggerReceived_ = []; + /** + * Listener for the speakerModelSaved event. + * @private {Function} + */ + this.speakerModelFinalizedListener_ = + this.onSpeakerModelFinalized_.bind(this); - /** - * Prefix of the element ids for the page that is currently training. - * @private {string} - */ - this.trainingPagePrefix_ = 'speech-training'; + /** + * Listener for the hotword trigger event. + * @private {Function} + */ + this.hotwordTriggerListener_ = this.handleHotwordTrigger_.bind(this); - /** - * Whether the speaker model for this flow has been finalized. - * @private {boolean} - */ - this.speakerModelFinalized_ = false; + // Listen for the user locking the screen. + chrome.idle.onStateChanged.addListener( + this.handleIdleStateChanged_.bind(this)); - /** - * ID of the currently active timeout. - * @private {?number} - */ - this.timeoutId_ = null; + // Listen for hotword settings changes. This used to detect when the user + // switches to a different profile. + if (chrome.hotwordPrivate.onEnabledChanged) { + chrome.hotwordPrivate.onEnabledChanged.addListener( + this.handleEnabledChanged_.bind(this)); + } +} - /** - * Listener for the speakerModelSaved event. - * @private {Function} - */ - this.speakerModelFinalizedListener_ = - this.onSpeakerModelFinalized_.bind(this); +/** + * Advances the current step. Begins training if the speech-training + * page has been reached. + */ +Flow.prototype.advanceStep = function() { + this.currentStepIndex_++; + if (this.currentStepIndex_ < this.currentFlow_.length) { + if (this.currentFlow_[this.currentStepIndex_] == SPEECH_TRAINING) + this.startTraining(); + this.showStep_.apply(this); + } +}; - /** - * Listener for the hotword trigger event. - * @private {Function} - */ - this.hotwordTriggerListener_ = - this.handleHotwordTrigger_.bind(this); +/** + * Gets the appropriate flow and displays its first page. + */ +Flow.prototype.startFlow = function() { + if (chrome.hotwordPrivate && chrome.hotwordPrivate.getLaunchState) + chrome.hotwordPrivate.getLaunchState(this.startFlowForMode_.bind(this)); +}; - // Listen for the user locking the screen. - chrome.idle.onStateChanged.addListener( - this.handleIdleStateChanged_.bind(this)); +/** + * Starts the training process. + */ +Flow.prototype.startTraining = function() { + // Don't start a training session if one already exists. + if (this.training_) + return; - // Listen for hotword settings changes. This used to detect when the user - // switches to a different profile. - if (chrome.hotwordPrivate.onEnabledChanged) { - chrome.hotwordPrivate.onEnabledChanged.addListener( - this.handleEnabledChanged_.bind(this)); - } + this.training_ = true; + + if (chrome.hotwordPrivate.onHotwordTriggered && + !chrome.hotwordPrivate.onHotwordTriggered.hasListener( + this.hotwordTriggerListener_)) { + chrome.hotwordPrivate.onHotwordTriggered.addListener( + this.hotwordTriggerListener_); } - /** - * Advances the current step. Begins training if the speech-training - * page has been reached. - */ - Flow.prototype.advanceStep = function() { - this.currentStepIndex_++; - if (this.currentStepIndex_ < this.currentFlow_.length) { - if (this.currentFlow_[this.currentStepIndex_] == SPEECH_TRAINING) - this.startTraining(); - this.showStep_.apply(this); - } + this.waitForHotwordTrigger_(0); + if (chrome.hotwordPrivate.startTraining) + chrome.hotwordPrivate.startTraining(); +}; + +/** + * Stops the training process. + */ +Flow.prototype.stopTraining = function() { + if (!this.training_) + return; + + this.training_ = false; + if (chrome.hotwordPrivate.onHotwordTriggered) { + chrome.hotwordPrivate.onHotwordTriggered.removeListener( + this.hotwordTriggerListener_); + } + if (chrome.hotwordPrivate.stopTraining) + chrome.hotwordPrivate.stopTraining(); +}; + +/** + * Attempts to enable audio history for the signed-in account. + */ +Flow.prototype.enableAudioHistory = function() { + // Update UI + $('audio-history-agree').disabled = true; + $('audio-history-cancel').disabled = true; + + $('audio-history-error').hidden = true; + $('audio-history-wait').hidden = false; + + if (chrome.hotwordPrivate.setAudioHistoryEnabled) { + chrome.hotwordPrivate.setAudioHistoryEnabled( + true, this.onAudioHistoryRequestCompleted_.bind(this)); + } +}; + +// ---- private methods: + +/** + * Shows an error if the audio history setting was not enabled successfully. + * @private + */ +Flow.prototype.handleAudioHistoryError_ = function() { + $('audio-history-agree').disabled = false; + $('audio-history-cancel').disabled = false; + + $('audio-history-wait').hidden = true; + $('audio-history-error').hidden = false; + + // Set a timeout before focusing the Enable button so that screenreaders + // have time to announce the error first. + this.setTimeout_(function() { + $('audio-history-agree').focus(); + }.bind(this), 50); +}; + +/** + * Callback for when an audio history request completes. + * @param {chrome.hotwordPrivate.AudioHistoryState} state The audio history + * request state. + * @private + */ +Flow.prototype.onAudioHistoryRequestCompleted_ = function(state) { + if (!state.success || !state.enabled) { + this.handleAudioHistoryError_(); + return; + } + + this.advanceStep(); +}; + +/** + * Shows an error if the speaker model has not been finalized. + * @private + */ +Flow.prototype.handleSpeakerModelFinalizedError_ = function() { + if (!this.training_) + return; + + if (this.speakerModelFinalized_) + return; + + this.updateTrainingState_(TrainingState.ERROR); + this.stopTraining(); +}; + +/** + * Handles the speaker model finalized event. + * @private + */ +Flow.prototype.onSpeakerModelFinalized_ = function() { + this.speakerModelFinalized_ = true; + if (chrome.hotwordPrivate.onSpeakerModelSaved) { + chrome.hotwordPrivate.onSpeakerModelSaved.removeListener( + this.speakerModelFinalizedListener_); + } + this.stopTraining(); + this.setTimeout_(this.finishFlow_.bind(this), 2000); +}; + +/** + * Completes the training process. + * @private + */ +Flow.prototype.finishFlow_ = function() { + if (chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled) { + chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled( + true, this.advanceStep.bind(this)); + } +}; + +/** + * Handles a user clicking on the retry button. + */ +Flow.prototype.handleRetry = function() { + if (!(this.trainingState_ == TrainingState.TIMEOUT || + this.trainingState_ == TrainingState.ERROR)) + return; + + this.startTraining(); + this.updateTrainingState_(TrainingState.RESET); +}; + +// ---- private methods: + +/** + * Completes the training process. + * @private + */ +Flow.prototype.finalizeSpeakerModel_ = function() { + if (!this.training_) + return; + + // Listen for the success event from the NaCl module. + if (chrome.hotwordPrivate.onSpeakerModelSaved && + !chrome.hotwordPrivate.onSpeakerModelSaved.hasListener( + this.speakerModelFinalizedListener_)) { + chrome.hotwordPrivate.onSpeakerModelSaved.addListener( + this.speakerModelFinalizedListener_); + } + + this.speakerModelFinalized_ = false; + this.setTimeout_(this.handleSpeakerModelFinalizedError_.bind(this), 30000); + if (chrome.hotwordPrivate.finalizeSpeakerModel) + chrome.hotwordPrivate.finalizeSpeakerModel(); +}; + +/** + * Returns the current training step. + * @param {string} curStepClassName The name of the class of the current + * training step. + * @return {Object} The current training step, its index, and an array of + * all training steps. Any of these can be undefined. + * @private + */ +Flow.prototype.getCurrentTrainingStep_ = function(curStepClassName) { + var steps = + $(this.trainingPagePrefix_ + '-training').querySelectorAll('.train'); + var curStep = + $(this.trainingPagePrefix_ + '-training').querySelector('.listening'); + + return { + current: curStep, + index: Array.prototype.indexOf.call(steps, curStep), + steps: steps }; +}; - /** - * Gets the appropriate flow and displays its first page. - */ - Flow.prototype.startFlow = function() { - if (chrome.hotwordPrivate && chrome.hotwordPrivate.getLaunchState) - chrome.hotwordPrivate.getLaunchState(this.startFlowForMode_.bind(this)); - }; +/** + * Updates the training state. + * @param {TrainingState} state The training state. + * @private + */ +Flow.prototype.updateTrainingState_ = function(state) { + this.trainingState_ = state; + this.updateErrorUI_(); +}; - /** - * Starts the training process. - */ - Flow.prototype.startTraining = function() { - // Don't start a training session if one already exists. - if (this.training_) - return; +/** + * Waits two minutes and then checks for a training error. + * @param {number} index The index of the training step. + * @private + */ +Flow.prototype.waitForHotwordTrigger_ = function(index) { + if (!this.training_) + return; - this.training_ = true; + this.hotwordTriggerReceived_[index] = false; + this.setTimeout_(this.handleTrainingTimeout_.bind(this, index), 120000); +}; - if (chrome.hotwordPrivate.onHotwordTriggered && - !chrome.hotwordPrivate.onHotwordTriggered.hasListener( - this.hotwordTriggerListener_)) { - chrome.hotwordPrivate.onHotwordTriggered.addListener( - this.hotwordTriggerListener_); +/** + * Checks for and handles a training error. + * @param {number} index The index of the training step. + * @private + */ +Flow.prototype.handleTrainingTimeout_ = function(index) { + if (this.hotwordTriggerReceived_[index]) + return; + + this.timeoutTraining_(); +}; + +/** + * Times out training and updates the UI to show a "retry" message, if + * currently training. + * @private + */ +Flow.prototype.timeoutTraining_ = function() { + if (!this.training_) + return; + + this.clearTimeout_(); + this.updateTrainingState_(TrainingState.TIMEOUT); + this.stopTraining(); +}; + +/** + * Sets a timeout. If any timeout is active, clear it. + * @param {Function} func The function to invoke when the timeout occurs. + * @param {number} delay Timeout delay in milliseconds. + * @private + */ +Flow.prototype.setTimeout_ = function(func, delay) { + this.clearTimeout_(); + this.timeoutId_ = setTimeout(function() { + this.timeoutId_ = null; + func(); + }, delay); +}; + +/** + * Clears any currently active timeout. + * @private + */ +Flow.prototype.clearTimeout_ = function() { + if (this.timeoutId_ != null) { + clearTimeout(this.timeoutId_); + this.timeoutId_ = null; + } +}; + +/** + * Updates the training error UI. + * @private + */ +Flow.prototype.updateErrorUI_ = function() { + if (!this.training_) + return; + + var trainingSteps = this.getCurrentTrainingStep_('listening'); + var steps = trainingSteps.steps; + + $(this.trainingPagePrefix_ + '-toast').hidden = + this.trainingState_ != TrainingState.TIMEOUT; + if (this.trainingState_ == TrainingState.RESET) { + // We reset the training to begin at the first step. + // The first step is reset to 'listening', while the rest + // are reset to 'not-started'. + var prompt = loadTimeData.getString('trainingFirstPrompt'); + for (var i = 0; i < steps.length; ++i) { + steps[i].classList.remove('recorded'); + if (i == 0) { + steps[i].classList.remove('not-started'); + steps[i].classList.add('listening'); + } else { + steps[i].classList.add('not-started'); + if (i == steps.length - 1) + prompt = loadTimeData.getString('trainingLastPrompt'); + else + prompt = loadTimeData.getString('trainingMiddlePrompt'); + } + steps[i].querySelector('.text').textContent = prompt; } - this.waitForHotwordTrigger_(0); - if (chrome.hotwordPrivate.startTraining) - chrome.hotwordPrivate.startTraining(); - }; - - /** - * Stops the training process. - */ - Flow.prototype.stopTraining = function() { - if (!this.training_) - return; - - this.training_ = false; - if (chrome.hotwordPrivate.onHotwordTriggered) { - chrome.hotwordPrivate.onHotwordTriggered. - removeListener(this.hotwordTriggerListener_); + // Reset the buttonbar. + $(this.trainingPagePrefix_ + '-processing').hidden = true; + $(this.trainingPagePrefix_ + '-wait').hidden = false; + $(this.trainingPagePrefix_ + '-error').hidden = true; + $(this.trainingPagePrefix_ + '-retry').hidden = true; + } else if (this.trainingState_ == TrainingState.TIMEOUT) { + var curStep = trainingSteps.current; + if (curStep) { + curStep.classList.remove('listening'); + curStep.classList.add('not-started'); } - if (chrome.hotwordPrivate.stopTraining) - chrome.hotwordPrivate.stopTraining(); - }; - /** - * Attempts to enable audio history for the signed-in account. - */ - Flow.prototype.enableAudioHistory = function() { - // Update UI - $('audio-history-agree').disabled = true; - $('audio-history-cancel').disabled = true; + // Set a timeout before focusing the Retry button so that screenreaders + // have time to announce the timeout first. + this.setTimeout_(function() { + $(this.trainingPagePrefix_ + '-toast').children[1].focus(); + }.bind(this), 50); + } else if (this.trainingState_ == TrainingState.ERROR) { + // Update the buttonbar. + $(this.trainingPagePrefix_ + '-wait').hidden = true; + $(this.trainingPagePrefix_ + '-error').hidden = false; + $(this.trainingPagePrefix_ + '-retry').hidden = false; + $(this.trainingPagePrefix_ + '-processing').hidden = false; - $('audio-history-error').hidden = true; - $('audio-history-wait').hidden = false; - - if (chrome.hotwordPrivate.setAudioHistoryEnabled) { - chrome.hotwordPrivate.setAudioHistoryEnabled( - true, this.onAudioHistoryRequestCompleted_.bind(this)); - } - }; - - // ---- private methods: - - /** - * Shows an error if the audio history setting was not enabled successfully. - * @private - */ - Flow.prototype.handleAudioHistoryError_ = function() { - $('audio-history-agree').disabled = false; - $('audio-history-cancel').disabled = false; - - $('audio-history-wait').hidden = true; - $('audio-history-error').hidden = false; - - // Set a timeout before focusing the Enable button so that screenreaders + // Set a timeout before focusing the Retry button so that screenreaders // have time to announce the error first. this.setTimeout_(function() { - $('audio-history-agree').focus(); + $(this.trainingPagePrefix_ + '-retry').children[0].focus(); }.bind(this), 50); - }; + } +}; - /** - * Callback for when an audio history request completes. - * @param {chrome.hotwordPrivate.AudioHistoryState} state The audio history - * request state. - * @private - */ - Flow.prototype.onAudioHistoryRequestCompleted_ = function(state) { - if (!state.success || !state.enabled) { - this.handleAudioHistoryError_(); - return; - } +/** + * Handles a hotword trigger event and updates the training UI. + * @private + */ +Flow.prototype.handleHotwordTrigger_ = function() { + var trainingSteps = this.getCurrentTrainingStep_('listening'); - this.advanceStep(); - }; + if (!trainingSteps.current) + return; - /** - * Shows an error if the speaker model has not been finalized. - * @private - */ - Flow.prototype.handleSpeakerModelFinalizedError_ = function() { - if (!this.training_) - return; + var index = trainingSteps.index; + this.hotwordTriggerReceived_[index] = true; - if (this.speakerModelFinalized_) - return; + trainingSteps.current.querySelector('.text').textContent = + loadTimeData.getString('trainingRecorded'); + trainingSteps.current.classList.remove('listening'); + trainingSteps.current.classList.add('recorded'); - this.updateTrainingState_(TrainingState.ERROR); - this.stopTraining(); - }; + if (trainingSteps.steps[index + 1]) { + trainingSteps.steps[index + 1].classList.remove('not-started'); + trainingSteps.steps[index + 1].classList.add('listening'); + this.waitForHotwordTrigger_(index + 1); + return; + } - /** - * Handles the speaker model finalized event. - * @private - */ - Flow.prototype.onSpeakerModelFinalized_ = function() { - this.speakerModelFinalized_ = true; - if (chrome.hotwordPrivate.onSpeakerModelSaved) { - chrome.hotwordPrivate.onSpeakerModelSaved.removeListener( - this.speakerModelFinalizedListener_); - } - this.stopTraining(); - this.setTimeout_(this.finishFlow_.bind(this), 2000); - }; + // Only the last step makes it here. + var buttonElem = $(this.trainingPagePrefix_ + '-processing').hidden = false; + this.finalizeSpeakerModel_(); +}; - /** - * Completes the training process. - * @private - */ - Flow.prototype.finishFlow_ = function() { - if (chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled) { - chrome.hotwordPrivate.setHotwordAlwaysOnSearchEnabled(true, - this.advanceStep.bind(this)); - } - }; - - /** - * Handles a user clicking on the retry button. - */ - Flow.prototype.handleRetry = function() { - if (!(this.trainingState_ == TrainingState.TIMEOUT || - this.trainingState_ == TrainingState.ERROR)) - return; - - this.startTraining(); - this.updateTrainingState_(TrainingState.RESET); - }; - - // ---- private methods: - - /** - * Completes the training process. - * @private - */ - Flow.prototype.finalizeSpeakerModel_ = function() { - if (!this.training_) - return; - - // Listen for the success event from the NaCl module. - if (chrome.hotwordPrivate.onSpeakerModelSaved && - !chrome.hotwordPrivate.onSpeakerModelSaved.hasListener( - this.speakerModelFinalizedListener_)) { - chrome.hotwordPrivate.onSpeakerModelSaved.addListener( - this.speakerModelFinalizedListener_); - } - - this.speakerModelFinalized_ = false; - this.setTimeout_(this.handleSpeakerModelFinalizedError_.bind(this), 30000); - if (chrome.hotwordPrivate.finalizeSpeakerModel) - chrome.hotwordPrivate.finalizeSpeakerModel(); - }; - - /** - * Returns the current training step. - * @param {string} curStepClassName The name of the class of the current - * training step. - * @return {Object} The current training step, its index, and an array of - * all training steps. Any of these can be undefined. - * @private - */ - Flow.prototype.getCurrentTrainingStep_ = function(curStepClassName) { - var steps = - $(this.trainingPagePrefix_ + '-training').querySelectorAll('.train'); - var curStep = - $(this.trainingPagePrefix_ + '-training').querySelector('.listening'); - - return {current: curStep, - index: Array.prototype.indexOf.call(steps, curStep), - steps: steps}; - }; - - /** - * Updates the training state. - * @param {TrainingState} state The training state. - * @private - */ - Flow.prototype.updateTrainingState_ = function(state) { - this.trainingState_ = state; - this.updateErrorUI_(); - }; - - /** - * Waits two minutes and then checks for a training error. - * @param {number} index The index of the training step. - * @private - */ - Flow.prototype.waitForHotwordTrigger_ = function(index) { - if (!this.training_) - return; - - this.hotwordTriggerReceived_[index] = false; - this.setTimeout_(this.handleTrainingTimeout_.bind(this, index), 120000); - }; - - /** - * Checks for and handles a training error. - * @param {number} index The index of the training step. - * @private - */ - Flow.prototype.handleTrainingTimeout_ = function(index) { - if (this.hotwordTriggerReceived_[index]) - return; - +/** + * Handles a chrome.idle.onStateChanged event and times out the training if + * the state is "locked". + * @param {!string} state State, one of "active", "idle", or "locked". + * @private + */ +Flow.prototype.handleIdleStateChanged_ = function(state) { + if (state == 'locked') this.timeoutTraining_(); - }; +}; - /** - * Times out training and updates the UI to show a "retry" message, if - * currently training. - * @private - */ - Flow.prototype.timeoutTraining_ = function() { - if (!this.training_) - return; +/** + * Handles a chrome.hotwordPrivate.onEnabledChanged event and times out + * training if the user is no longer the active user (user switches profiles). + * @private + */ +Flow.prototype.handleEnabledChanged_ = function() { + if (chrome.hotwordPrivate.getStatus) { + chrome.hotwordPrivate.getStatus(function(status) { + if (status.userIsActive) + return; - this.clearTimeout_(); - this.updateTrainingState_(TrainingState.TIMEOUT); - this.stopTraining(); - }; - - /** - * Sets a timeout. If any timeout is active, clear it. - * @param {Function} func The function to invoke when the timeout occurs. - * @param {number} delay Timeout delay in milliseconds. - * @private - */ - Flow.prototype.setTimeout_ = function(func, delay) { - this.clearTimeout_(); - this.timeoutId_ = setTimeout(function() { - this.timeoutId_ = null; - func(); - }, delay); - }; - - /** - * Clears any currently active timeout. - * @private - */ - Flow.prototype.clearTimeout_ = function() { - if (this.timeoutId_ != null) { - clearTimeout(this.timeoutId_); - this.timeoutId_ = null; - } - }; - - /** - * Updates the training error UI. - * @private - */ - Flow.prototype.updateErrorUI_ = function() { - if (!this.training_) - return; - - var trainingSteps = this.getCurrentTrainingStep_('listening'); - var steps = trainingSteps.steps; - - $(this.trainingPagePrefix_ + '-toast').hidden = - this.trainingState_ != TrainingState.TIMEOUT; - if (this.trainingState_ == TrainingState.RESET) { - // We reset the training to begin at the first step. - // The first step is reset to 'listening', while the rest - // are reset to 'not-started'. - var prompt = loadTimeData.getString('trainingFirstPrompt'); - for (var i = 0; i < steps.length; ++i) { - steps[i].classList.remove('recorded'); - if (i == 0) { - steps[i].classList.remove('not-started'); - steps[i].classList.add('listening'); - } else { - steps[i].classList.add('not-started'); - if (i == steps.length - 1) - prompt = loadTimeData.getString('trainingLastPrompt'); - else - prompt = loadTimeData.getString('trainingMiddlePrompt'); - } - steps[i].querySelector('.text').textContent = prompt; - } - - // Reset the buttonbar. - $(this.trainingPagePrefix_ + '-processing').hidden = true; - $(this.trainingPagePrefix_ + '-wait').hidden = false; - $(this.trainingPagePrefix_ + '-error').hidden = true; - $(this.trainingPagePrefix_ + '-retry').hidden = true; - } else if (this.trainingState_ == TrainingState.TIMEOUT) { - var curStep = trainingSteps.current; - if (curStep) { - curStep.classList.remove('listening'); - curStep.classList.add('not-started'); - } - - // Set a timeout before focusing the Retry button so that screenreaders - // have time to announce the timeout first. - this.setTimeout_(function() { - $(this.trainingPagePrefix_ + '-toast').children[1].focus(); - }.bind(this), 50); - } else if (this.trainingState_ == TrainingState.ERROR) { - // Update the buttonbar. - $(this.trainingPagePrefix_ + '-wait').hidden = true; - $(this.trainingPagePrefix_ + '-error').hidden = false; - $(this.trainingPagePrefix_ + '-retry').hidden = false; - $(this.trainingPagePrefix_ + '-processing').hidden = false; - - // Set a timeout before focusing the Retry button so that screenreaders - // have time to announce the error first. - this.setTimeout_(function() { - $(this.trainingPagePrefix_ + '-retry').children[0].focus(); - }.bind(this), 50); - } - }; - - /** - * Handles a hotword trigger event and updates the training UI. - * @private - */ - Flow.prototype.handleHotwordTrigger_ = function() { - var trainingSteps = this.getCurrentTrainingStep_('listening'); - - if (!trainingSteps.current) - return; - - var index = trainingSteps.index; - this.hotwordTriggerReceived_[index] = true; - - trainingSteps.current.querySelector('.text').textContent = - loadTimeData.getString('trainingRecorded'); - trainingSteps.current.classList.remove('listening'); - trainingSteps.current.classList.add('recorded'); - - if (trainingSteps.steps[index + 1]) { - trainingSteps.steps[index + 1].classList.remove('not-started'); - trainingSteps.steps[index + 1].classList.add('listening'); - this.waitForHotwordTrigger_(index + 1); - return; - } - - // Only the last step makes it here. - var buttonElem = $(this.trainingPagePrefix_ + '-processing').hidden = false; - this.finalizeSpeakerModel_(); - }; - - /** - * Handles a chrome.idle.onStateChanged event and times out the training if - * the state is "locked". - * @param {!string} state State, one of "active", "idle", or "locked". - * @private - */ - Flow.prototype.handleIdleStateChanged_ = function(state) { - if (state == 'locked') this.timeoutTraining_(); - }; + }.bind(this)); + } +}; - /** - * Handles a chrome.hotwordPrivate.onEnabledChanged event and times out - * training if the user is no longer the active user (user switches profiles). - * @private - */ - Flow.prototype.handleEnabledChanged_ = function() { - if (chrome.hotwordPrivate.getStatus) { - chrome.hotwordPrivate.getStatus(function(status) { - if (status.userIsActive) - return; +/** + * Gets and starts the appropriate flow for the launch mode. + * @param {chrome.hotwordPrivate.LaunchState} state Launch state of the + * Hotword Audio Verification App. + * @private + */ +Flow.prototype.startFlowForMode_ = function(state) { + this.launchMode_ = state.launchMode; + assert( + state.launchMode >= 0 && state.launchMode < FLOWS.length, + 'Invalid Launch Mode.'); + this.currentFlow_ = FLOWS[state.launchMode]; + if (state.launchMode == LaunchMode.HOTWORD_ONLY) { + $('intro-description-audio-history-enabled').hidden = false; + } else if (state.launchMode == LaunchMode.HOTWORD_AND_AUDIO_HISTORY) { + $('intro-description').hidden = false; + } - this.timeoutTraining_(); - }.bind(this)); - } - }; + this.advanceStep(); +}; - /** - * Gets and starts the appropriate flow for the launch mode. - * @param {chrome.hotwordPrivate.LaunchState} state Launch state of the - * Hotword Audio Verification App. - * @private - */ - Flow.prototype.startFlowForMode_ = function(state) { - this.launchMode_ = state.launchMode; - assert(state.launchMode >= 0 && state.launchMode < FLOWS.length, - 'Invalid Launch Mode.'); - this.currentFlow_ = FLOWS[state.launchMode]; - if (state.launchMode == LaunchMode.HOTWORD_ONLY) { - $('intro-description-audio-history-enabled').hidden = false; - } else if (state.launchMode == LaunchMode.HOTWORD_AND_AUDIO_HISTORY) { - $('intro-description').hidden = false; - } +/** + * Displays the current step. If the current step is not the first step, + * also hides the previous step. Focuses the current step's first button. + * @private + */ +Flow.prototype.showStep_ = function() { + var currentStepId = this.currentFlow_[this.currentStepIndex_]; + var currentStep = document.getElementById(currentStepId); + currentStep.hidden = false; - this.advanceStep(); - }; + cr.ui.setInitialFocus(currentStep); - /** - * Displays the current step. If the current step is not the first step, - * also hides the previous step. Focuses the current step's first button. - * @private - */ - Flow.prototype.showStep_ = function() { - var currentStepId = this.currentFlow_[this.currentStepIndex_]; - var currentStep = document.getElementById(currentStepId); - currentStep.hidden = false; + var previousStep = null; + if (this.currentStepIndex_ > 0) + previousStep = this.currentFlow_[this.currentStepIndex_ - 1]; - cr.ui.setInitialFocus(currentStep); + if (previousStep) + document.getElementById(previousStep).hidden = true; - var previousStep = null; - if (this.currentStepIndex_ > 0) - previousStep = this.currentFlow_[this.currentStepIndex_ - 1]; + chrome.app.window.current().show(); +}; - if (previousStep) - document.getElementById(previousStep).hidden = true; - - chrome.app.window.current().show(); - }; - - window.Flow = Flow; +window.Flow = Flow; })();
diff --git a/chrome/browser/resources/identity_internals.js b/chrome/browser/resources/identity_internals.js index 3fc17de..bdd44ac 100644 --- a/chrome/browser/resources/identity_internals.js +++ b/chrome/browser/resources/identity_internals.js
@@ -34,8 +34,8 @@ 'extensionName', this.data_.extensionName, 'extension-name')); tbody.appendChild(this.createEntry_( 'extensionId', this.data_.extensionId, 'extension-id')); - tbody.appendChild(this.createEntry_( - 'tokenStatus', this.data_.status, 'token-status')); + tbody.appendChild( + this.createEntry_('tokenStatus', this.data_.status, 'token-status')); tbody.appendChild(this.createEntry_( 'expirationTime', this.data_.expirationTime, 'expiration-time')); tbody.appendChild(this.createEntryForScopes_()); @@ -113,8 +113,9 @@ var revokeButton = this.ownerDocument.createElement('button'); revokeButton.classList.add('revoke-button'); revokeButton.addEventListener('click', function() { - chrome.send('identityInternalsRevokeToken', - [this.data_.extensionId, this.data_.accessToken]); + chrome.send( + 'identityInternalsRevokeToken', + [this.data_.extensionId, this.data_.accessToken]); }.bind(this)); revokeButton.textContent = loadTimeData.getString('revoke'); return revokeButton;
diff --git a/chrome/browser/resources/identity_scope_approval_dialog/background.js b/chrome/browser/resources/identity_scope_approval_dialog/background.js index 4139360a..0215c41f 100644 --- a/chrome/browser/resources/identity_scope_approval_dialog/background.js +++ b/chrome/browser/resources/identity_scope_approval_dialog/background.js
@@ -11,24 +11,17 @@ * if the mode is 'interactive'. */ function showAuthDialog(key, url, mode) { - var options = { - frame: 'none', - id: key, - minWidth: 1024, - minHeight: 768, - hidden: true - }; - chrome.app.window.create('scope_approval_dialog.html', - options, - function(win) { - win.contentWindow.addEventListener('load', function(event) { - var windowParam; - if (mode == 'interactive') - windowParam = win; - win.contentWindow.loadAuthUrlAndShowWindow(url, windowParam); - }); - }); + var options = + {frame: 'none', id: key, minWidth: 1024, minHeight: 768, hidden: true}; + chrome.app.window.create( + 'scope_approval_dialog.html', options, function(win) { + win.contentWindow.addEventListener('load', function(event) { + var windowParam; + if (mode == 'interactive') + windowParam = win; + win.contentWindow.loadAuthUrlAndShowWindow(url, windowParam); + }); + }); } chrome.identityPrivate.onWebFlowRequest.addListener(showAuthDialog); -
diff --git a/chrome/browser/resources/identity_scope_approval_dialog/scope_approval_dialog.js b/chrome/browser/resources/identity_scope_approval_dialog/scope_approval_dialog.js index 8c204c2..5bc4b2cca 100644 --- a/chrome/browser/resources/identity_scope_approval_dialog/scope_approval_dialog.js +++ b/chrome/browser/resources/identity_scope_approval_dialog/scope_approval_dialog.js
@@ -20,14 +20,16 @@ }); // Request a customized view from GAIA. - webview.request.onBeforeSendHeaders.addListener(function(details) { - headers = details.requestHeaders || []; - headers.push({'name': 'X-Browser-View', - 'value': 'embedded'}); - return { requestHeaders: headers }; - }, { - urls: ['https://accounts.google.com/*'], - }, ['blocking', 'requestHeaders']); + webview.request.onBeforeSendHeaders.addListener( + function(details) { + headers = details.requestHeaders || []; + headers.push({'name': 'X-Browser-View', 'value': 'embedded'}); + return {requestHeaders: headers}; + }, + { + urls: ['https://accounts.google.com/*'], + }, + ['blocking', 'requestHeaders']); if (!url.toLowerCase().startsWith('https://accounts.google.com/')) document.querySelector('.titlebar').classList.add('titlebar-border'); @@ -51,4 +53,3 @@ document.title = strings['window-title']; }); }); -
diff --git a/chrome/browser/resources/inline_login/inline_login.js b/chrome/browser/resources/inline_login/inline_login.js index 17f1c43..a29c409 100644 --- a/chrome/browser/resources/inline_login/inline_login.js +++ b/chrome/browser/resources/inline_login/inline_login.js
@@ -21,8 +21,8 @@ var authReadyFired; /** - * Whether the login UI is loaded for signing in primary account. - */ + * Whether the login UI is loaded for signing in primary account. + */ var isLoginPrimaryAccount; function onResize(e) { @@ -77,9 +77,11 @@ // TODO(rogerta): in when using webview, the |completeLogin| argument // is ignored. See addEventListener() call above. authExtHost.load(data.authMode, data, completeLogin); - $('contents').classList.toggle('loading', - data.authMode != cr.login.GaiaAuthHost.AuthMode.DESKTOP || - data.constrained == '1'); + $('contents') + .classList.toggle( + 'loading', + data.authMode != cr.login.GaiaAuthHost.AuthMode.DESKTOP || + data.constrained == '1'); isLoginPrimaryAccount = data.isLoginPrimaryAccount; } @@ -114,19 +116,20 @@ } function showBackButton() { - $('navigation-button').icon = isRTL() ? 'icons:arrow-forward' : 'icons:arrow-back'; - $('navigation-button').setAttribute( - 'aria-label', loadTimeData.getString('accessibleBackButtonLabel')); + $('navigation-button') + .setAttribute( + 'aria-label', loadTimeData.getString('accessibleBackButtonLabel')); } function showCloseButton() { $('navigation-button').icon = 'icons:close'; $('navigation-button').classList.add('enabled'); - $('navigation-button').setAttribute( - 'aria-label', loadTimeData.getString('accessibleCloseButtonLabel')); + $('navigation-button') + .setAttribute( + 'aria-label', loadTimeData.getString('accessibleCloseButtonLabel')); } function navigationButtonClicked() {
diff --git a/chrome/browser/resources/inspect/inspect.js b/chrome/browser/resources/inspect/inspect.js index 512552b7..64288b83 100644 --- a/chrome/browser/resources/inspect/inspect.js +++ b/chrome/browser/resources/inspect/inspect.js
@@ -15,11 +15,11 @@ (function() { var queryParams = window.location.search; if (!queryParams) - return; + return; var params = queryParams.substring(1).split('&'); for (var i = 0; i < params.length; ++i) { - var pair = params[i].split('='); - queryParamsObject[pair[0]] = pair[1]; + var pair = params[i].split('='); + queryParamsObject[pair[0]] = pair[1]; } if ('trace' in queryParamsObject || 'tracing' in queryParamsObject) { @@ -55,7 +55,7 @@ var element = $(element_id); var elements = element.querySelectorAll('.row:not(.additional)'); for (var i = 0; i != elements.length; i++) - element.removeChild(elements[i]); + element.removeChild(elements[i]); } function onload() { @@ -163,9 +163,8 @@ function updateBrowserVisibility(browserSection) { var icon = browserSection.querySelector('.used-for-port-forwarding'); browserSection.hidden = !browserSection.querySelector('.open') && - !browserSection.querySelector('.row') && - !browserInspector && - (!icon || icon.hidden); + !browserSection.querySelector('.row') && !browserInspector && + (!icon || icon.hidden); } function updateUsernameVisibility(deviceSection) { @@ -207,7 +206,7 @@ function insertBrowser(browserList, browser) { for (var sibling = browserList.firstElementChild; sibling; - sibling = sibling.nextElementSibling) { + sibling = sibling.nextElementSibling) { if (browserCompare(browser, sibling)) { browserList.insertBefore(browser, sibling); return; @@ -225,7 +224,9 @@ section.remove(); } - var newDeviceIds = devices.map(function(d) { return d.id; }); + var newDeviceIds = devices.map(function(d) { + return d.id; + }); Array.prototype.forEach.call( deviceList.querySelectorAll('.device'), removeObsolete.bind(null, newDeviceIds)); @@ -277,12 +278,14 @@ deviceSection.querySelector('.device-name').textContent = device.adbModel; deviceSection.querySelector('.device-auth').textContent = - device.adbConnected ? '' : 'Pending authentication: please accept ' + - 'debugging session on the device.'; + device.adbConnected ? '' : + 'Pending authentication: please accept ' + + 'debugging session on the device.'; var browserList = deviceSection.querySelector('.browsers'); - var newBrowserIds = - device.browsers.map(function(b) { return b.id; }); + var newBrowserIds = device.browsers.map(function(b) { + return b.id; + }); Array.prototype.forEach.call( browserList.querySelectorAll('.browser'), removeObsolete.bind(null, newBrowserIds)); @@ -359,8 +362,10 @@ browserHeader.appendChild(link); link.addEventListener( 'click', - sendCommand.bind(null, 'inspect-browser', browser.source, - browser.id, browserInspector), false); + sendCommand.bind( + null, 'inspect-browser', browser.source, browser.id, + browserInspector), + false); } pageList = document.createElement('div'); @@ -374,24 +379,27 @@ var page = browser.pages[p]; // Attached targets have no unique id until Chrome 26. For such // targets it is impossible to activate existing DevTools window. - page.hasNoUniqueId = page.attached && - majorChromeVersion && majorChromeVersion < MIN_VERSION_TARGET_ID; + page.hasNoUniqueId = page.attached && majorChromeVersion && + majorChromeVersion < MIN_VERSION_TARGET_ID; var row = addTargetToList(page, pageList, ['name', 'url']); if (page['description']) addWebViewDetails(row, page); else addFavicon(row, page); if (majorChromeVersion >= MIN_VERSION_TAB_ACTIVATE) { - addActionLink(row, 'focus tab', + addActionLink( + row, 'focus tab', sendTargetCommand.bind(null, 'activate', page), false); } if (majorChromeVersion) { - addActionLink(row, 'reload', - sendTargetCommand.bind(null, 'reload', page), page.attached); + addActionLink( + row, 'reload', sendTargetCommand.bind(null, 'reload', page), + page.attached); } if (majorChromeVersion >= MIN_VERSION_TAB_CLOSE) { - addActionLink(row, 'close', - sendTargetCommand.bind(null, 'close', page), false); + addActionLink( + row, 'close', sendTargetCommand.bind(null, 'close', page), + false); } } } @@ -433,15 +441,15 @@ function addToWorkersList(data) { var row = addTargetToList(data, $('workers-list'), ['name', 'description', 'url']); - addActionLink(row, 'terminate', - sendTargetCommand.bind(null, 'close', data), false); + addActionLink( + row, 'terminate', sendTargetCommand.bind(null, 'close', data), false); } function addToServiceWorkersList(data) { - var row = addTargetToList( - data, $('service-workers-list'), ['name', 'description', 'url']); - addActionLink(row, 'terminate', - sendTargetCommand.bind(null, 'close', data), false); + var row = addTargetToList( + data, $('service-workers-list'), ['name', 'description', 'url']); + addActionLink( + row, 'terminate', sendTargetCommand.bind(null, 'close', data), false); } function addToOthersList(data) { @@ -491,7 +499,7 @@ } function addWebViewDescription(row, webview) { - var viewStatus = { visibility: '', position: '', size: '' }; + var viewStatus = {visibility: '', position: '', size: ''}; if (!webview.empty) { if (webview.attached && !webview.visible) viewStatus.visibility = 'hidden'; @@ -502,7 +510,7 @@ viewStatus.visibility = 'empty'; } if (webview.attached) { - viewStatus.position = + viewStatus.position = 'at (' + webview.screenX + ', ' + webview.screenY + ')'; } @@ -592,11 +600,13 @@ subrowBox.appendChild(actionBox); if (data.isAdditional) { - addActionLink(row, 'inspect', - sendCommand.bind(null, 'inspect-additional', data.url), false); + addActionLink( + row, 'inspect', sendCommand.bind(null, 'inspect-additional', data.url), + false); row.classList.add('additional'); } else if (!data.hasCustomInspectAction) { - addActionLink(row, 'inspect', sendTargetCommand.bind(null, 'inspect', data), + addActionLink( + row, 'inspect', sendTargetCommand.bind(null, 'inspect', data), data.hasNoUniqueId || data.adbAttachedForeign); } @@ -626,21 +636,20 @@ } function initSettings() { - checkboxSendsCommand('discover-usb-devices-enable', - 'set-discover-usb-devices-enabled'); + checkboxSendsCommand( + 'discover-usb-devices-enable', 'set-discover-usb-devices-enabled'); checkboxSendsCommand('port-forwarding-enable', 'set-port-forwarding-enabled'); - checkboxSendsCommand('discover-tcp-devices-enable', - 'set-discover-tcp-targets-enabled'); + checkboxSendsCommand( + 'discover-tcp-devices-enable', 'set-discover-tcp-targets-enabled'); - $('port-forwarding-config-open').addEventListener( - 'click', openPortForwardingConfig); - $('tcp-discovery-config-open').addEventListener( - 'click', openTargetsConfig); + $('port-forwarding-config-open') + .addEventListener('click', openPortForwardingConfig); + $('tcp-discovery-config-open').addEventListener('click', openTargetsConfig); $('config-dialog-close').addEventListener('click', function() { $('config-dialog').commit(true); }); - $('node-frontend').addEventListener( - 'click', sendCommand.bind(null, 'open-node-frontend')); + $('node-frontend') + .addEventListener('click', sendCommand.bind(null, 'open-node-frontend')); } function checkboxHandler(command, event) { @@ -713,7 +722,6 @@ defaultFocus.focus(); else doneButton.focus(); - } function openPortForwardingConfig() { @@ -721,8 +729,8 @@ var line = document.createElement('div'); line.className = 'port-forwarding-pair config-list-row'; - var portInput = createConfigField(port, 'port preselected', - 'Port', validatePort); + var portInput = + createConfigField(port, 'port preselected', 'Port', validatePort); line.appendChild(portInput); var locationInput = createConfigField( @@ -740,10 +748,9 @@ sendCommand('set-port-forwarding-config', config); } - openConfigDialog('port-forwarding', - commitPortForwardingConfig, - createPortForwardingConfigLine, - window.portForwardingConfig); + openConfigDialog( + 'port-forwarding', commitPortForwardingConfig, + createPortForwardingConfigLine, window.portForwardingConfig); } function openTargetsConfig() { @@ -767,10 +774,9 @@ sendCommand('set-tcp-discovery-config', entries); } - openConfigDialog('target-discovery', - commitTargetDiscoveryConfig, - createTargetDiscoveryConfigLine, - window.targetDiscoveryConfig); + openConfigDialog( + 'target-discovery', commitTargetDiscoveryConfig, + createTargetDiscoveryConfigLine, window.targetDiscoveryConfig); } function filterList(fieldSelectors, callback) { @@ -780,9 +786,8 @@ var values = []; for (var selector of fieldSelectors) { var input = line.querySelector(selector); - var value = input.classList.contains('invalid') ? - input.lastValidValue : - input.value; + var value = input.classList.contains('invalid') ? input.lastValidValue : + input.value; if (!value) break; values.push(value); @@ -825,10 +830,8 @@ function appendRow(list, lineFactory, key, value) { var line = lineFactory(key, value); line.lastElementChild.addEventListener('keydown', function(e) { - if (e.key == 'Tab' && - !hasKeyModifiers(e) && - line.classList.contains('fresh') && - !line.classList.contains('empty')) { + if (e.key == 'Tab' && !hasKeyModifiers(e) && + line.classList.contains('fresh') && !line.classList.contains('empty')) { // Tabbing forward on the fresh line, try create a new empty one. if (commitFreshLineIfValid(true)) e.preventDefault(); @@ -845,10 +848,8 @@ }); line.appendChild(lineDelete); - line.addEventListener( - 'click', selectLine.bind(null, line, true)); - line.addEventListener( - 'focus', selectLine.bind(null, line, true)); + line.addEventListener('click', selectLine.bind(null, line, true)); + line.addEventListener('focus', selectLine.bind(null, line, true)); checkEmptyLine(line); if (!key && !value)
diff --git a/chrome/browser/resources/instant/instant.js b/chrome/browser/resources/instant/instant.js index 67c9d0f1d..2cb4b97 100644 --- a/chrome/browser/resources/instant/instant.js +++ b/chrome/browser/resources/instant/instant.js
@@ -6,7 +6,9 @@ // the only function needed. This allows this file to be loaded // in a browser directly for layout and some testing purposes. // eslint-disable-next-line no-restricted-properties -var $ = function(id) { return document.getElementById(id); }; +var $ = function(id) { + return document.getElementById(id); +}; /** * WebUI for configuring instant.* preference values used by @@ -57,15 +59,19 @@ var input = createElementWithClass('input', 'row-input'); input.type = field.type; input.id = field.key; - input.title = "Default Value: " + field.default; - if (field.size) input.size = field.size; + input.title = 'Default Value: ' + field.default; + if (field.size) + input.size = field.size; input.min = field.min || 0; - if (field.max) input.max = field.max; - if (field.step) input.step = field.step; + if (field.max) + input.max = field.max; + if (field.step) + input.step = field.step; row.appendChild(input); var units = createElementWithClass('div', 'row-units'); - if (field.units) units.innerHTML = field.units; + if (field.units) + units.innerHTML = field.units; row.appendChild(units); $('instant-form').appendChild(row); @@ -79,8 +85,8 @@ for (var i = 0; i < FIELDS.length; i++) { var field = FIELDS[i]; $(field.key).onchange = (function(key) { - setPreferenceValue(key); - }).bind(null, field.key); + setPreferenceValue(key); + }).bind(null, field.key); } }
diff --git a/chrome/browser/resources/local_discovery/local_discovery.js b/chrome/browser/resources/local_discovery/local_discovery.js index cdad0b5..6906a94 100644 --- a/chrome/browser/resources/local_discovery/local_discovery.js +++ b/chrome/browser/resources/local_discovery/local_discovery.js
@@ -103,12 +103,9 @@ } this.registerButton = fillDeviceDescription( - this.domElement, - this.info.display_name, - this.info.description, - this.info.type, - loadTimeData.getString('serviceRegister'), - this.showRegister.bind(this, this.info.type)); + this.domElement, this.info.display_name, this.info.description, + this.info.type, loadTimeData.getString('serviceRegister'), + this.showRegister.bind(this, this.info.type)); this.setRegisterEnabled(this.registerEnabled); }, @@ -127,8 +124,9 @@ register: function() { recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_CONFIRMED); chrome.send('registerDevice', [this.info.service_name]); - setRegisterPage(isPrinter(this.info.type) ? - 'register-printer-page-adding1' : 'register-device-page-adding1'); + setRegisterPage( + isPrinter(this.info.type) ? 'register-printer-page-adding1' : + 'register-device-page-adding1'); }, /** * Show registrtation UI for device. @@ -136,9 +134,9 @@ showRegister: function() { recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_CLICKED); $('register-message').textContent = loadTimeData.getStringF( - isPrinter(this.info.type) ? 'registerPrinterConfirmMessage' : - 'registerDeviceConfirmMessage', - this.info.display_name); + isPrinter(this.info.type) ? 'registerPrinterConfirmMessage' : + 'registerDeviceConfirmMessage', + this.info.display_name); $('register-continue-button').onclick = this.register.bind(this); showRegisterOverlay(); }, @@ -167,8 +165,7 @@ __proto__: cr.ui.FocusManager.prototype, /** @override */ getFocusParent: function() { - return document.querySelector('#overlay .showing') || - $('main-page'); + return document.querySelector('#overlay .showing') || $('main-page'); } }; @@ -182,8 +179,8 @@ } else if (numberPrinters == 1) { return loadTimeData.getString('printersOnNetworkOne'); } else { - return loadTimeData.getStringF('printersOnNetworkMultiple', - numberPrinters); + return loadTimeData.getStringF( + 'printersOnNetworkMultiple', numberPrinters); } } @@ -197,12 +194,8 @@ * @param {function()?} button_action Action for button. * @return {HTMLElement} The button (for enabling/disabling/rebinding) */ - function fillDeviceDescription(device_dom_element, - name, - description, - type, - button_text, - button_action) { + function fillDeviceDescription( + device_dom_element, name, description, type, button_text, button_action) { device_dom_element.classList.add('device'); if (isPrinter(type)) device_dom_element.classList.add('printer'); @@ -268,7 +261,7 @@ */ function onRegistrationFailed() { $('error-message').textContent = - loadTimeData.getString('addingErrorMessage'); + loadTimeData.getString('addingErrorMessage'); setRegisterPage('register-page-error'); recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_FAILURE); } @@ -278,7 +271,7 @@ */ function onRegistrationCanceledPrinter() { $('error-message').textContent = - loadTimeData.getString('addingCanceledMessage'); + loadTimeData.getString('addingCanceledMessage'); setRegisterPage('register-page-error'); recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_CANCEL_ON_PRINTER); } @@ -288,7 +281,7 @@ */ function onRegistrationTimeout() { $('error-message').textContent = - loadTimeData.getString('addingTimeoutMessage'); + loadTimeData.getString('addingTimeoutMessage'); setRegisterPage('register-page-error'); recordUmaEvent(DEVICES_PAGE_EVENTS.REGISTER_TIMEOUT); } @@ -356,11 +349,11 @@ description = device.description; } - fillDeviceDescription(devicesDomElement, device.display_name, - description, device.type, - loadTimeData.getString('manageDevice'), - isPrinter(device.type) ? - manageCloudDevice.bind(null, device.id) : null); + fillDeviceDescription( + devicesDomElement, device.display_name, description, device.type, + loadTimeData.getString('manageDevice'), + isPrinter(device.type) ? manageCloudDevice.bind(null, device.id) : + null); return devicesDomElement; } @@ -413,15 +406,14 @@ $('register-login-promo').hidden = true; } else { $('no-printers-message').hidden = true; - $('register-login-promo').hidden = isUserLoggedIn || - isUserSupervisedOrOffTheRecord; + $('register-login-promo').hidden = + isUserLoggedIn || isUserSupervisedOrOffTheRecord; } if (!($('register-login-promo').hidden) || - !($('cloud-devices-login-promo').hidden) || - !($('register-overlay-login-promo').hidden)) { + !($('cloud-devices-login-promo').hidden) || + !($('register-overlay-login-promo').hidden)) { chrome.send( - 'metricsHandler:recordAction', - ['Signin_Impression_FromDevicesPage']); + 'metricsHandler:recordAction', ['Signin_Impression_FromDevicesPage']); } } @@ -484,13 +476,14 @@ } /** - * Record an event in the UMA histogram. - * @param {number} eventId The id of the event to be recorded. - * @private - */ + * Record an event in the UMA histogram. + * @param {number} eventId The id of the event to be recorded. + * @private + */ function recordUmaEvent(eventId) { - chrome.send('metricsHandler:recordInHistogram', - ['LocalDiscovery.DevicesPage', eventId, DEVICES_PAGE_EVENTS.MAX_EVENT]); + chrome.send( + 'metricsHandler:recordInHistogram', + ['LocalDiscovery.DevicesPage', eventId, DEVICES_PAGE_EVENTS.MAX_EVENT]); } /** @@ -524,12 +517,12 @@ isUserLoggedIn = userLoggedIn; isUserSupervisedOrOffTheRecord = userSupervisedOrOffTheRecord; - $('cloud-devices-login-promo').hidden = isUserLoggedIn || - isUserSupervisedOrOffTheRecord; - $('register-overlay-login-promo').hidden = isUserLoggedIn || - isUserSupervisedOrOffTheRecord; - $('register-continue-button').disabled = !isUserLoggedIn || - isUserSupervisedOrOffTheRecord; + $('cloud-devices-login-promo').hidden = + isUserLoggedIn || isUserSupervisedOrOffTheRecord; + $('register-overlay-login-promo').hidden = + isUserLoggedIn || isUserSupervisedOrOffTheRecord; + $('register-continue-button').disabled = + !isUserLoggedIn || isUserSupervisedOrOffTheRecord; $('my-devices-container').hidden = userSupervisedOrOffTheRecord; @@ -565,7 +558,7 @@ function registerOverlayLoginButtonClicked() { recordUmaEvent( - DEVICES_PAGE_EVENTS.LOG_IN_STARTED_FROM_REGISTER_OVERLAY_PROMO); + DEVICES_PAGE_EVENTS.LOG_IN_STARTED_FROM_REGISTER_OVERLAY_PROMO); openSignInPage(); } @@ -583,10 +576,10 @@ $('cloudPrintConnectorLabel').textContent = label; if (disabled || !allowed) { $('cloudPrintConnectorSetupButton').textContent = - loadTimeData.getString('cloudPrintConnectorDisabledButton'); + loadTimeData.getString('cloudPrintConnectorDisabledButton'); } else { $('cloudPrintConnectorSetupButton').textContent = - loadTimeData.getString('cloudPrintConnectorEnabledButton'); + loadTimeData.getString('cloudPrintConnectorEnabledButton'); } $('cloudPrintConnectorSetupButton').disabled = !allowed; @@ -594,7 +587,7 @@ $('cloudPrintConnectorSetupButton').onclick = function(event) { // Disable the button, set its text to the intermediate state. $('cloudPrintConnectorSetupButton').textContent = - loadTimeData.getString('cloudPrintConnectorEnablingButton'); + loadTimeData.getString('cloudPrintConnectorEnablingButton'); $('cloudPrintConnectorSetupButton').disabled = true; chrome.send('showCloudPrintSetupDialog'); }; @@ -629,31 +622,28 @@ [].forEach.call( document.querySelectorAll('.register-cancel'), function(button) { - button.addEventListener('click', cancelRegistration); - }); + button.addEventListener('click', cancelRegistration); + }); [].forEach.call( document.querySelectorAll('.confirm-code'), function(button) { - button.addEventListener('click', confirmCode); - }); + button.addEventListener('click', confirmCode); + }); $('register-error-exit').addEventListener('click', cancelRegistration); - $('cloud-devices-retry-link').addEventListener('click', - retryLoadCloudDevices); + $('cloud-devices-retry-link') + .addEventListener('click', retryLoadCloudDevices); - $('cloud-devices-login-link').addEventListener( - 'click', - cloudDevicesLoginButtonClicked); + $('cloud-devices-login-link') + .addEventListener('click', cloudDevicesLoginButtonClicked); - $('register-login-link').addEventListener( - 'click', - registerLoginButtonClicked); + $('register-login-link') + .addEventListener('click', registerLoginButtonClicked); - $('register-overlay-login-button').addEventListener( - 'click', - registerOverlayLoginButtonClicked); + $('register-overlay-login-button') + .addEventListener('click', registerOverlayLoginButtonClicked); if (loadTimeData.valueExists('backButtonURL')) { $('back-link').hidden = false;
diff --git a/chrome/browser/resources/local_ntp/instant_iframe_validation.js b/chrome/browser/resources/local_ntp/instant_iframe_validation.js index 822350d..a557dc6 100644 --- a/chrome/browser/resources/local_ntp/instant_iframe_validation.js +++ b/chrome/browser/resources/local_ntp/instant_iframe_validation.js
@@ -16,8 +16,8 @@ function convertToHexColor(color) { // Color must be a number, finite, with no fractional part, in the correct // range for an RGB hex color. - if (isFinite(color) && Math.floor(color) == color && - color >= 0 && color <= 0xffffff) { + if (isFinite(color) && Math.floor(color) == color && color >= 0 && + color <= 0xffffff) { var hexColor = color.toString(16); // Pads with initial zeros and # (e.g. for 'ff' yields '#0000ff'). return '#000000'.substr(0, 7 - hexColor.length) + hexColor; @@ -48,11 +48,8 @@ isValidRBGAComponent(rgbaColor[1]) && isValidRBGAComponent(rgbaColor[2]) && isValidRBGAComponent(rgbaColor[3])) { - return 'rgba(' + - rgbaColor[0] + ',' + - rgbaColor[1] + ',' + - rgbaColor[2] + ',' + - rgbaColor[3] / 255 + ')'; + return 'rgba(' + rgbaColor[0] + ',' + rgbaColor[1] + ',' + rgbaColor[2] + + ',' + rgbaColor[3] / 255 + ')'; } return null; }
diff --git a/chrome/browser/resources/local_ntp/most_visited_single.js b/chrome/browser/resources/local_ntp/most_visited_single.js index fe7cc9e..f829663 100644 --- a/chrome/browser/resources/local_ntp/most_visited_single.js +++ b/chrome/browser/resources/local_ntp/most_visited_single.js
@@ -2,7 +2,7 @@ * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ - // Single iframe for NTP tiles. +// Single iframe for NTP tiles. (function() { 'use strict'; @@ -117,9 +117,8 @@ * @param {number} tileType The type from TileVisualType. */ function logMostVisitedImpression(tileIndex, tileSource, tileType) { - chrome.embeddedSearch.newTabPage.logMostVisitedImpression(tileIndex, - tileSource, - tileType); + chrome.embeddedSearch.newTabPage.logMostVisitedImpression( + tileIndex, tileSource, tileType); } /** @@ -129,9 +128,8 @@ * @param {number} tileType The type from TileVisualType. */ function logMostVisitedNavigation(tileIndex, tileSource, tileType) { - chrome.embeddedSearch.newTabPage.logMostVisitedNavigation(tileIndex, - tileSource, - tileType); + chrome.embeddedSearch.newTabPage.logMostVisitedNavigation( + tileIndex, tileSource, tileType); } /** @@ -207,31 +205,41 @@ var themeStyle = []; if (info.tileBorderColor) { - themeStyle.push('.mv-tile {' + + themeStyle.push( + '.mv-tile {' + 'border: 1px solid ' + info.tileBorderColor + '; }'); } if (info.tileHoverBorderColor) { - themeStyle.push('.mv-tile:hover {' + + themeStyle.push( + '.mv-tile:hover {' + 'border-color: ' + info.tileHoverBorderColor + '; }'); } if (info.isThemeDark) { - themeStyle.push('.mv-tile, .mv-empty-tile { ' + + themeStyle.push( + '.mv-tile, .mv-empty-tile { ' + 'background: rgb(51,51,51); }'); - themeStyle.push('.mv-thumb.failed-img { ' + + themeStyle.push( + '.mv-thumb.failed-img { ' + 'background-color: #555; }'); - themeStyle.push('.mv-thumb.failed-img::after { ' + + themeStyle.push( + '.mv-thumb.failed-img::after { ' + 'border-color: #333; }'); - themeStyle.push('.mv-x { ' + + themeStyle.push( + '.mv-x { ' + 'background: linear-gradient(to left, ' + 'rgb(51,51,51) 60%, transparent); }'); - themeStyle.push('html[dir=rtl] .mv-x { ' + + themeStyle.push( + 'html[dir=rtl] .mv-x { ' + 'background: linear-gradient(to right, ' + 'rgb(51,51,51) 60%, transparent); }'); - themeStyle.push('.mv-x::after { ' + + themeStyle.push( + '.mv-x::after { ' + 'background-color: rgba(255,255,255,0.7); }'); - themeStyle.push('.mv-x:hover::after { ' + + themeStyle.push( + '.mv-x:hover::after { ' + 'background-color: #fff; }'); - themeStyle.push('.mv-x:active::after { ' + + themeStyle.push( + '.mv-x:active::after { ' + 'background-color: rgba(255,255,255,0.5); }'); } if (info.tileTitleColor) { @@ -247,8 +255,8 @@ * and 'tilesVisible' messages from the host page. */ var hideOverflowTiles = function(data) { - var tileAndEmptyTileList = document.querySelectorAll( - '#mv-tiles .mv-tile,#mv-tiles .mv-empty-tile'); + var tileAndEmptyTileList = + document.querySelectorAll('#mv-tiles .mv-tile,#mv-tiles .mv-empty-tile'); for (var i = 0; i < tileAndEmptyTileList.length; ++i) { tileAndEmptyTileList[i].classList.toggle('hidden', i >= data.maxVisible); } @@ -358,11 +366,12 @@ var blacklistTile = function(tile) { tile.classList.add('blacklisted'); tile.addEventListener('transitionend', function(ev) { - if (ev.propertyName != 'width') return; + if (ev.propertyName != 'width') + return; - window.parent.postMessage({cmd: 'tileBlacklisted', - tid: Number(tile.getAttribute('data-tid'))}, - DOMAIN_ORIGIN); + window.parent.postMessage( + {cmd: 'tileBlacklisted', tid: Number(tile.getAttribute('data-tid'))}, + DOMAIN_ORIGIN); }); }; @@ -373,7 +382,7 @@ */ var isSchemeAllowed = function(url) { return url.startsWith('http://') || url.startsWith('https://') || - url.startsWith('ftp://') || url.startsWith('chrome-extension://'); + url.startsWith('ftp://') || url.startsWith('chrome-extension://'); }; @@ -421,8 +430,8 @@ event.preventDefault(); event.stopPropagation(); blacklistTile(this); - } else if (event.keyCode == 13 /* ENTER */ || - event.keyCode == 32 /* SPACE */) { + } else if ( + event.keyCode == 13 /* ENTER */ || event.keyCode == 32 /* SPACE */) { event.preventDefault(); this.click(); } else if (event.keyCode >= 37 && event.keyCode <= 40 /* ARROWS */) { @@ -431,15 +440,15 @@ return (event.keyCode == 37 /* LEFT */ && origin.offsetTop == target.offsetTop && origin.offsetLeft > target.offsetLeft) || - (event.keyCode == 38 /* UP */ && - origin.offsetTop > target.offsetTop && - origin.offsetLeft == target.offsetLeft) || - (event.keyCode == 39 /* RIGHT */ && - origin.offsetTop == target.offsetTop && - origin.offsetLeft < target.offsetLeft) || - (event.keyCode == 40 /* DOWN */ && - origin.offsetTop < target.offsetTop && - origin.offsetLeft == target.offsetLeft); + (event.keyCode == 38 /* UP */ && + origin.offsetTop > target.offsetTop && + origin.offsetLeft == target.offsetLeft) || + (event.keyCode == 39 /* RIGHT */ && + origin.offsetTop == target.offsetTop && + origin.offsetLeft < target.offsetLeft) || + (event.keyCode == 40 /* DOWN */ && + origin.offsetTop < target.offsetTop && + origin.offsetLeft == target.offsetLeft); }; var nonEmptyTiles = document.querySelectorAll('#mv-tiles .mv-tile'); @@ -533,7 +542,8 @@ queryArgs = {}; for (var i = 0; i < query.length; ++i) { var val = query[i].split('='); - if (val[0] == '') continue; + if (val[0] == '') + continue; queryArgs[decodeURIComponent(val[0])] = decodeURIComponent(val[1]); }
diff --git a/chrome/browser/resources/local_ntp/most_visited_title.js b/chrome/browser/resources/local_ntp/most_visited_title.js index 7729c1c..f25e46d5 100644 --- a/chrome/browser/resources/local_ntp/most_visited_title.js +++ b/chrome/browser/resources/local_ntp/most_visited_title.js
@@ -11,8 +11,7 @@ 'use strict'; fillMostVisited(window.location, function(params, data) { - document.body.appendChild( - createMostVisitedLink( - params, data.url, data.title, data.title, data.direction)); + document.body.appendChild(createMostVisitedLink( + params, data.url, data.title, data.title, data.direction)); }); });
diff --git a/chrome/browser/resources/local_ntp/most_visited_util.js b/chrome/browser/resources/local_ntp/most_visited_util.js index d7dc58d8..63a6f03 100644 --- a/chrome/browser/resources/local_ntp/most_visited_util.js +++ b/chrome/browser/resources/local_ntp/most_visited_util.js
@@ -12,13 +12,13 @@ /** - * The different types of events that are logged from the NTP. The multi-iframe - * version of the NTP does *not* actually log any statistics anymore; this is - * only required as a workaround for crbug.com/698675. - * Note: Keep in sync with common/ntp_logging_events.h - * @enum {number} - * @const - */ + * The different types of events that are logged from the NTP. The multi-iframe + * version of the NTP does *not* actually log any statistics anymore; this is + * only required as a workaround for crbug.com/698675. + * Note: Keep in sync with common/ntp_logging_events.h + * @enum {number} + * @const + */ var NTP_LOGGING_EVENT_TYPE = { NTP_ALL_TILES_RECEIVED: 12, }; @@ -121,8 +121,8 @@ event.keyCode == 8 /* BACKSPACE */) { event.preventDefault(); window.parent.postMessage('tileBlacklisted,' + params.pos, DOMAIN_ORIGIN); - } else if (event.keyCode == 13 /* ENTER */ || - event.keyCode == 32 /* SPACE */) { + } else if ( + event.keyCode == 13 /* ENTER */ || event.keyCode == 32 /* SPACE */) { // Event target is the <a> tag. Send a click event on it, which will // trigger the 'click' event registered above. event.preventDefault(); @@ -239,8 +239,7 @@ if (isFinite(params.dummy) && parseInt(params.dummy, 10)) { data.dummy = true; } - if (/^javascript:/i.test(data.url) || - /^javascript:/i.test(data.thumbnailUrl)) + if (/^javascript:/i.test(data.url) || /^javascript:/i.test(data.thumbnailUrl)) return; if (data.direction) document.body.dir = data.direction;
diff --git a/chrome/browser/resources/local_state/local_state.js b/chrome/browser/resources/local_state/local_state.js index 3011af5..76656ac4 100644 --- a/chrome/browser/resources/local_state/local_state.js +++ b/chrome/browser/resources/local_state/local_state.js
@@ -20,9 +20,7 @@ $('content').textContent = localState; } - return { - setLocalState: setLocalState - }; + return {setLocalState: setLocalState}; }); // When the page loads, request the JSON local state data from C++.
diff --git a/chrome/browser/resources/md_downloads/action_service.js b/chrome/browser/resources/md_downloads/action_service.js index c355712..7dec7ee 100644 --- a/chrome/browser/resources/md_downloads/action_service.js +++ b/chrome/browser/resources/md_downloads/action_service.js
@@ -8,7 +8,9 @@ * @return {function(string):void} A chrome.send() callback with curried name. */ function chromeSendWithId(chromeSendName) { - return function(id) { chrome.send(chromeSendName, [id]); }; + return function(id) { + chrome.send(chromeSendName, [id]); + }; } /** @constructor */ @@ -21,13 +23,17 @@ * @param {string} s * @return {string} |s| without whitespace at the beginning or end. */ - function trim(s) { return s.trim(); } + function trim(s) { + return s.trim(); + } /** * @param {string|undefined} value * @return {boolean} Whether |value| is truthy. */ - function truthy(value) { return !!value; } + function truthy(value) { + return !!value; + } /** * @param {string} searchText Input typed by the user into a search box.
diff --git a/chrome/browser/resources/md_downloads/downloads.js b/chrome/browser/resources/md_downloads/downloads.js index 9f934af..fe3834c0 100644 --- a/chrome/browser/resources/md_downloads/downloads.js +++ b/chrome/browser/resources/md_downloads/downloads.js
@@ -5,10 +5,9 @@ window.addEventListener('load', function() { downloads.Manager.onLoad().then(function() { requestIdleCallback(function() { - chrome.send('metricsHandler:recordTime', [ - 'Download.ResultsRenderedTime', - window.performance.now() - ]); + chrome.send( + 'metricsHandler:recordTime', + ['Download.ResultsRenderedTime', window.performance.now()]); document.fonts.load('bold 12px Roboto'); }); });
diff --git a/chrome/browser/resources/md_downloads/item.js b/chrome/browser/resources/md_downloads/item.js index 00a3716..47b216a1 100644 --- a/chrome/browser/resources/md_downloads/item.js +++ b/chrome/browser/resources/md_downloads/item.js
@@ -106,7 +106,7 @@ /** @private */ computeCompletelyOnDisk_: function() { return this.data.state == downloads.States.COMPLETE && - !this.data.file_externally_removed; + !this.data.file_externally_removed; }, /** @private */ @@ -141,18 +141,18 @@ var fileName = data.file_name; switch (data.danger_type) { case downloads.DangerType.DANGEROUS_FILE: - return loadTimeData.getString('dangerFileDesc'); + return loadTimeData.getString('dangerFileDesc'); case downloads.DangerType.DANGEROUS_URL: case downloads.DangerType.DANGEROUS_CONTENT: case downloads.DangerType.DANGEROUS_HOST: - return loadTimeData.getString('dangerDownloadDesc'); + return loadTimeData.getString('dangerDownloadDesc'); case downloads.DangerType.UNCOMMON_CONTENT: - return loadTimeData.getString('dangerUncommonDesc'); + return loadTimeData.getString('dangerUncommonDesc'); case downloads.DangerType.POTENTIALLY_UNWANTED: - return loadTimeData.getString('dangerSettingsDesc'); + return loadTimeData.getString('dangerSettingsDesc'); } break; @@ -167,8 +167,8 @@ /** @private */ computeIsActive_: function() { return this.data.state != downloads.States.CANCELLED && - this.data.state != downloads.States.INTERRUPTED && - !this.data.file_externally_removed; + this.data.state != downloads.States.INTERRUPTED && + !this.data.file_externally_removed; }, /** @private */ @@ -209,7 +209,7 @@ /** @private */ computeShowCancel_: function() { return this.data.state == downloads.States.IN_PROGRESS || - this.data.state == downloads.States.PAUSED; + this.data.state == downloads.States.PAUSED; }, /** @private */ @@ -228,7 +228,8 @@ case downloads.States.COMPLETE: return this.data.file_externally_removed ? - loadTimeData.getString('statusRemoved') : ''; + loadTimeData.getString('statusRemoved') : + ''; } return '';
diff --git a/chrome/browser/resources/md_downloads/manager.js b/chrome/browser/resources/md_downloads/manager.js index ec56d51..b3ebe46 100644 --- a/chrome/browser/resources/md_downloads/manager.js +++ b/chrome/browser/resources/md_downloads/manager.js
@@ -29,7 +29,9 @@ /** @private {!Array<!downloads.Data>} */ items_: { type: Array, - value: function() { return []; }, + value: function() { + return []; + }, }, /** @private */ @@ -120,7 +122,7 @@ * @private */ onCanExecute_: function(e) { - e = /** @type {cr.ui.CanExecuteEvent} */(e); + e = /** @type {cr.ui.CanExecuteEvent} */ (e); switch (e.command.id) { case 'undo-command': e.canExecute = this.$.toolbar.canUndo(); @@ -209,7 +211,7 @@ updateItem_: function(index, data) { this.set('items_.' + index, data); this.updateHideDates_(index, index); - var list = /** @type {!IronListElement} */(this.$['downloads-list']); + var list = /** @type {!IronListElement} */ (this.$['downloads-list']); list.updateSizeForItem(index); }, }); @@ -220,7 +222,7 @@ /** @return {!downloads.Manager} */ Manager.get = function() { - return /** @type {!downloads.Manager} */( + return /** @type {!downloads.Manager} */ ( queryRequiredElement('downloads-manager')); };
diff --git a/chrome/browser/resources/md_feedback/feedback.js b/chrome/browser/resources/md_feedback/feedback.js index 61695ad..895f993 100644 --- a/chrome/browser/resources/md_feedback/feedback.js +++ b/chrome/browser/resources/md_feedback/feedback.js
@@ -9,7 +9,6 @@ * with this UI. */ Feedback.UI = class { - /** * Populates the feedback form with data. *
diff --git a/chrome/browser/resources/md_feedback/feedback_container.js b/chrome/browser/resources/md_feedback/feedback_container.js index 5b1f8bf2..05f7dcee 100644 --- a/chrome/browser/resources/md_feedback/feedback_container.js +++ b/chrome/browser/resources/md_feedback/feedback_container.js
@@ -29,8 +29,8 @@ ready: function() { // Retrieves the feedback privacy note text, if it exists. On non-official // branded builds, the string is not defined. - this.$.privacyNote.innerHTML = - loadTimeData.valueExists('privacyNote') ? - loadTimeData.getString('privacyNote') : ''; + this.$.privacyNote.innerHTML = loadTimeData.valueExists('privacyNote') ? + loadTimeData.getString('privacyNote') : + ''; }, });
diff --git a/chrome/browser/resources/md_user_manager/control_bar.js b/chrome/browser/resources/md_user_manager/control_bar.js index 2c2b238..5e22faf 100644 --- a/chrome/browser/resources/md_user_manager/control_bar.js +++ b/chrome/browser/resources/md_user_manager/control_bar.js
@@ -6,7 +6,7 @@ * @fileoverview 'control-bar' is the horizontal bar at the bottom of the user * manager screen. */ - Polymer({ +Polymer({ is: 'control-bar', behaviors: [ @@ -18,19 +18,13 @@ * True if 'Browse as Guest' button is displayed. * @type {boolean} */ - showGuest: { - type: Boolean, - value: false - }, + showGuest: {type: Boolean, value: false}, /** * True if 'Add Person' button is displayed. * @type {boolean} */ - showAddPerson: { - type: Boolean, - value: false - }, + showAddPerson: {type: Boolean, value: false}, /** @private {!signin.ProfileBrowserProxy} */ browserProxy_: Object, @@ -58,15 +52,14 @@ * @private */ onLaunchGuestTap_: function(event) { - this.browserProxy_.areAllProfilesLocked().then( - function(allProfilesLocked) { - if (!allProfilesLocked || this.isForceSigninEnabled_) { - this.browserProxy_.launchGuestUser(); - } else { - document.querySelector('error-dialog').show( - this.i18n('browseAsGuestAllProfilesLockedError')); - } - }.bind(this)); + this.browserProxy_.areAllProfilesLocked().then(function(allProfilesLocked) { + if (!allProfilesLocked || this.isForceSigninEnabled_) { + this.browserProxy_.launchGuestUser(); + } else { + document.querySelector('error-dialog') + .show(this.i18n('browseAsGuestAllProfilesLockedError')); + } + }.bind(this)); }, /** @@ -75,15 +68,14 @@ * @private */ onAddUserTap_: function(event) { - this.browserProxy_.areAllProfilesLocked().then( - function(allProfilesLocked) { - if (!allProfilesLocked || this.isForceSigninEnabled_) { - // Event is caught by user-manager-pages. - this.fire('change-page', {page: 'create-user-page'}); - } else { - document.querySelector('error-dialog').show( - this.i18n('addProfileAllProfilesLockedError')); - } - }.bind(this)); + this.browserProxy_.areAllProfilesLocked().then(function(allProfilesLocked) { + if (!allProfilesLocked || this.isForceSigninEnabled_) { + // Event is caught by user-manager-pages. + this.fire('change-page', {page: 'create-user-page'}); + } else { + document.querySelector('error-dialog') + .show(this.i18n('addProfileAllProfilesLockedError')); + } + }.bind(this)); } });
diff --git a/chrome/browser/resources/md_user_manager/create_profile.js b/chrome/browser/resources/md_user_manager/create_profile.js index a9a1557..5934ee2 100644 --- a/chrome/browser/resources/md_user_manager/create_profile.js +++ b/chrome/browser/resources/md_user_manager/create_profile.js
@@ -20,20 +20,14 @@ Polymer({ is: 'create-profile', - behaviors: [ - I18nBehavior, - WebUIListenerBehavior - ], + behaviors: [I18nBehavior, WebUIListenerBehavior], properties: { /** * The current profile name. * @private {string} */ - profileName_: { - type: String, - value: '' - }, + profileName_: {type: String, value: ''}, /** * The list of available profile icon Urls and labels. @@ -41,71 +35,52 @@ */ availableIcons_: { type: Array, - value: function() { return []; } + value: function() { + return []; + } }, /** * The currently selected profile icon URL. May be a data URL. * @private {string} */ - profileIconUrl_: { - type: String, - value: '' - }, + profileIconUrl_: {type: String, value: ''}, /** * True if the existing supervised users are being loaded. * @private {boolean} */ - loadingSupervisedUsers_: { - type: Boolean, - value: false - }, + loadingSupervisedUsers_: {type: Boolean, value: false}, /** * True if a profile is being created or imported. * @private {boolean} */ - createInProgress_: { - type: Boolean, - value: false - }, + createInProgress_: {type: Boolean, value: false}, /** * True if the error/warning message is displaying. * @private {boolean} */ - isMessageVisble_: { - type: Boolean, - value: false - }, + isMessageVisble_: {type: Boolean, value: false}, /** * The current error/warning message. * @private {string} */ - message_: { - type: String, - value: '' - }, + message_: {type: String, value: ''}, /** * if true, a desktop shortcut will be created for the new profile. * @private {boolean} */ - createShortcut_: { - type: Boolean, - value: true - }, + createShortcut_: {type: Boolean, value: true}, /** * True if the new profile is a supervised profile. * @private {boolean} */ - isSupervised_: { - type: Boolean, - value: false - }, + isSupervised_: {type: Boolean, value: false}, /** * The list of usernames and profile paths for currently signed-in users. @@ -113,17 +88,16 @@ */ signedInUsers_: { type: Array, - value: function() { return []; } + value: function() { + return []; + } }, /** * Index of the selected signed-in user. * @private {number} */ - signedInUserIndex_: { - type: Number, - value: NO_USER_SELECTED - }, + signedInUserIndex_: {type: Number, value: NO_USER_SELECTED}, /** @private {!signin.ProfileBrowserProxy} */ browserProxy_: Object, @@ -152,10 +126,8 @@ } }, - listeners: { - 'tap': 'onTap_', - 'importUserPopup.import': 'onImportUserPopupImport_' - }, + listeners: + {'tap': 'onTap_', 'importUserPopup.import': 'onImportUserPopupImport_'}, /** @override */ created: function() { @@ -165,17 +137,17 @@ /** @override */ ready: function() { this.addWebUIListener( - 'create-profile-success', this.handleSuccess_.bind(this)); + 'create-profile-success', this.handleSuccess_.bind(this)); this.addWebUIListener( - 'create-profile-warning', this.handleMessage_.bind(this)); + 'create-profile-warning', this.handleMessage_.bind(this)); this.addWebUIListener( - 'create-profile-error', this.handleMessage_.bind(this)); + 'create-profile-error', this.handleMessage_.bind(this)); this.addWebUIListener( - 'profile-icons-received', this.handleProfileIcons_.bind(this)); + 'profile-icons-received', this.handleProfileIcons_.bind(this)); this.addWebUIListener( - 'profile-defaults-received', this.handleProfileDefaults_.bind(this)); + 'profile-defaults-received', this.handleProfileDefaults_.bind(this)); this.addWebUIListener( - 'signedin-users-received', this.handleSignedInUsers_.bind(this)); + 'signedin-users-received', this.handleSignedInUsers_.bind(this)); this.browserProxy_.getAvailableIcons(); this.browserProxy_.getSignedInUsers(); @@ -271,8 +243,9 @@ this.hideMessage_(); this.loadingSupervisedUsers_ = true; this.browserProxy_.getExistingSupervisedUsers(signedInUser.profilePath) - .then(this.showImportSupervisedUserPopup_.bind(this), - this.handleMessage_.bind(this)); + .then( + this.showImportSupervisedUserPopup_.bind(this), + this.handleMessage_.bind(this)); } }, @@ -294,8 +267,9 @@ this.hideMessage_(); this.loadingSupervisedUsers_ = true; this.browserProxy_.getExistingSupervisedUsers(signedInUser.profilePath) - .then(this.createProfileIfValidSupervisedUser_.bind(this), - this.handleMessage_.bind(this)); + .then( + this.createProfileIfValidSupervisedUser_.bind(this), + this.handleMessage_.bind(this)); } }, @@ -309,8 +283,8 @@ showImportSupervisedUserPopup_: function(supervisedUsers) { this.loadingSupervisedUsers_ = false; if (supervisedUsers.length > 0) { - this.$.importUserPopup.show(this.signedInUser_(this.signedInUserIndex_), - supervisedUsers); + this.$.importUserPopup.show( + this.signedInUser_(this.signedInUserIndex_), supervisedUsers); } else { this.handleMessage_(this.i18nAdvanced('noSupervisedUserImportText')); } @@ -339,14 +313,14 @@ for (var j = i + 1; j < supervisedUsers.length; ++j) { if (supervisedUsers[j].name == this.profileName_) { nameIsUnique = false; - allOnCurrentDevice = allOnCurrentDevice && - supervisedUsers[j].onCurrentDevice; + allOnCurrentDevice = + allOnCurrentDevice && supervisedUsers[j].onCurrentDevice; } } var opts = { 'substitutions': - [HTMLEscape(elide(this.profileName_, /* maxLength */ 50))], + [HTMLEscape(elide(this.profileName_, /* maxLength */ 50))], 'attrs': { 'id': function(node, value) { return node.tagName == 'A'; @@ -389,8 +363,8 @@ } this.hideMessage_(); this.createInProgress_ = true; - var createShortcut = this.isProfileShortcutsEnabled_ && - this.createShortcut_; + var createShortcut = + this.isProfileShortcutsEnabled_ && this.createShortcut_; this.browserProxy_.createProfile( this.profileName_, this.profileIconUrl_, createShortcut, this.isSupervised_, '', custodianProfilePath); @@ -439,8 +413,9 @@ handleSuccess_: function(profileInfo) { this.createInProgress_ = false; if (profileInfo.showConfirmation) { - this.fire('change-page', {page: 'supervised-create-confirm-page', - data: profileInfo}); + this.fire( + 'change-page', + {page: 'supervised-create-confirm-page', data: profileInfo}); } else { this.fire('change-page', {page: 'user-pods-page'}); } @@ -476,7 +451,7 @@ i18nAllowIDAttr_: function(id) { var opts = { 'attrs': { - 'id' : function(node, value) { + 'id': function(node, value) { return node.tagName == 'A'; } } @@ -515,15 +490,14 @@ * @return {boolean} * @private */ - isSaveDisabled_: function(createInProgress, - loadingSupervisedUsers, - profileName) { + isSaveDisabled_: function( + createInProgress, loadingSupervisedUsers, profileName) { // TODO(mahmadi): Figure out a way to add 'paper-input-extracted' as a // dependency and cast to PaperInputElement instead. /** @type {{validate: function():boolean}} */ var nameInput = this.$.nameInput; return createInProgress || loadingSupervisedUsers || !profileName || - !nameInput.validate(); + !nameInput.validate(); }, /** @@ -535,9 +509,8 @@ * @return {boolean} * @private */ - isImportUserLinkHidden_: function(createInProgress, - loadingSupervisedUsers, - signedInUserIndex) { + isImportUserLinkHidden_: function( + createInProgress, loadingSupervisedUsers, signedInUserIndex) { return createInProgress || loadingSupervisedUsers || !this.signedInUser_(signedInUserIndex); },
diff --git a/chrome/browser/resources/md_user_manager/error_dialog.js b/chrome/browser/resources/md_user_manager/error_dialog.js index 7794fa5..70d8acd 100644 --- a/chrome/browser/resources/md_user_manager/error_dialog.js +++ b/chrome/browser/resources/md_user_manager/error_dialog.js
@@ -15,10 +15,7 @@ * The message shown in the dialog. * @private {string} */ - message_: { - type: String, - value: '' - } + message_: {type: String, value: ''} }, /**
diff --git a/chrome/browser/resources/md_user_manager/import_supervised_user.js b/chrome/browser/resources/md_user_manager/import_supervised_user.js index c572419..27491fa 100644 --- a/chrome/browser/resources/md_user_manager/import_supervised_user.js +++ b/chrome/browser/resources/md_user_manager/import_supervised_user.js
@@ -27,7 +27,9 @@ */ signedInUser_: { type: Object, - value: function() { return null; } + value: function() { + return null; + } }, /** @@ -36,17 +38,16 @@ */ supervisedUsers_: { type: Array, - value: function() { return []; } + value: function() { + return []; + } }, /** * Index of the selected supervised user. * @private {number} */ - supervisedUserIndex_: { - type: Number, - value: NO_USER_SELECTED - } + supervisedUserIndex_: {type: Number, value: NO_USER_SELECTED} }, /** override */ @@ -97,8 +98,9 @@ if (this.signedInUser_ && supervisedUser) { this.$.dialog.close(); // Event is caught by create-profile. - this.fire('import', {supervisedUser: supervisedUser, - signedInUser: this.signedInUser_}); + this.fire( + 'import', + {supervisedUser: supervisedUser, signedInUser: this.signedInUser_}); } } });
diff --git a/chrome/browser/resources/md_user_manager/profile_browser_proxy.js b/chrome/browser/resources/md_user_manager/profile_browser_proxy.js index 1712a8a..cfc9a4d 100644 --- a/chrome/browser/resources/md_user_manager/profile_browser_proxy.js +++ b/chrome/browser/resources/md_user_manager/profile_browser_proxy.js
@@ -75,8 +75,9 @@ * @param {string} custodianProfilePath Profile path of the custodian if * the new profile is supervised. */ - createProfile: function(profileName, profileIconUrl, createShortcut, - isSupervised, supervisedUserId, custodianProfilePath) { + createProfile: function( + profileName, profileIconUrl, createShortcut, isSupervised, + supervisedUserId, custodianProfilePath) { assertNotReached(); }, @@ -177,11 +178,13 @@ }, /** @override */ - createProfile: function(profileName, profileIconUrl, createShortcut, - isSupervised, supervisedUserId, custodianProfilePath) { - chrome.send('createProfile', - [profileName, profileIconUrl, createShortcut, isSupervised, - supervisedUserId, custodianProfilePath]); + createProfile: function( + profileName, profileIconUrl, createShortcut, isSupervised, + supervisedUserId, custodianProfilePath) { + chrome.send('createProfile', [ + profileName, profileIconUrl, createShortcut, isSupervised, + supervisedUserId, custodianProfilePath + ]); }, /** @override */
diff --git a/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.js b/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.js index 69a041f6..e5ba99e7 100644 --- a/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.js +++ b/chrome/browser/resources/md_user_manager/supervised_user_create_confirm.js
@@ -90,8 +90,8 @@ * @private */ titleText_: function(profileInfo) { - return this.i18n('supervisedUserCreatedTitle', - this.elideProfileName_(profileInfo)); + return this.i18n( + 'supervisedUserCreatedTitle', this.elideProfileName_(profileInfo)); }, /** @@ -117,8 +117,8 @@ * @private */ switchUserText_: function(profileInfo) { - return this.i18n('supervisedUserCreatedSwitch', - this.elideProfileName_(profileInfo)); + return this.i18n( + 'supervisedUserCreatedSwitch', this.elideProfileName_(profileInfo)); }, /**
diff --git a/chrome/browser/resources/md_user_manager/supervised_user_learn_more.js b/chrome/browser/resources/md_user_manager/supervised_user_learn_more.js index 394a559..2f7b88b 100644 --- a/chrome/browser/resources/md_user_manager/supervised_user_learn_more.js +++ b/chrome/browser/resources/md_user_manager/supervised_user_learn_more.js
@@ -15,9 +15,7 @@ browserProxy_: Object }, - listeners: { - 'tap': 'onTap_' - }, + listeners: {'tap': 'onTap_'}, /** @override */ created: function() {
diff --git a/chrome/browser/resources/md_user_manager/user_manager.js b/chrome/browser/resources/md_user_manager/user_manager.js index 3c0cedc..943309524 100644 --- a/chrome/browser/resources/md_user_manager/user_manager.js +++ b/chrome/browser/resources/md_user_manager/user_manager.js
@@ -24,7 +24,7 @@ * Manages initialization of screens, transitions, and error messages. * @constructor * @extends {DisplayManager} - */ + */ function UserManager() {} cr.addSingletonGetter(UserManager); @@ -95,8 +95,8 @@ * displayed. */ UserManager.showUserManagerScreen = function(showGuest, showAddPerson) { - UserManager.getInstance().showScreen({id: 'account-picker', - data: {disableAddUser: false}}); + UserManager.getInstance().showScreen( + {id: 'account-picker', data: {disableAddUser: false}}); // Hide control options if the user does not have the right permissions. var controlBar = document.querySelector('control-bar'); controlBar.showGuest = showGuest; @@ -104,13 +104,15 @@ // Disable the context menu, as the Print/Inspect element items don't // make sense when displayed as a widget. - document.addEventListener('contextmenu', function(e) {e.preventDefault();}); + document.addEventListener('contextmenu', function(e) { + e.preventDefault(); + }); if (window.location.hash == '#tutorial') document.querySelector('user-manager-tutorial').startTutorial(); else if (window.location.hash == '#create-user') { - document.querySelector('user-manager-pages').setSelectedPage( - 'create-user-page'); + document.querySelector('user-manager-pages') + .setSelectedPage('create-user-page'); } }; @@ -164,9 +166,7 @@ }; // Export - return { - UserManager: UserManager - }; + return {UserManager: UserManager}; }); // Alias to Oobe for use in src/ui/login/account_picker/user_pod_row.js @@ -177,8 +177,7 @@ disableTextSelectAndDrag(function(e) { var src = e.target; return src instanceof HTMLTextAreaElement || - src instanceof HTMLInputElement && - /text|password|search/.test(src.type); + src instanceof HTMLInputElement && /text|password|search/.test(src.type); }); document.addEventListener('DOMContentLoaded', cr.ui.UserManager.initialize);
diff --git a/chrome/browser/resources/md_user_manager/user_manager_dialog.js b/chrome/browser/resources/md_user_manager/user_manager_dialog.js index 6db1a35..31721ac 100644 --- a/chrome/browser/resources/md_user_manager/user_manager_dialog.js +++ b/chrome/browser/resources/md_user_manager/user_manager_dialog.js
@@ -12,16 +12,10 @@ properties: { /** @override */ - noCancelOnOutsideClick: { - type: Boolean, - value: true - }, + noCancelOnOutsideClick: {type: Boolean, value: true}, /** @override */ - withBackdrop: { - type: Boolean, - value: true - }, + withBackdrop: {type: Boolean, value: true}, /** * The first node that can receive focus. @@ -29,7 +23,9 @@ */ firstFocusableNode: { type: Object, - value: function() { return this.$.close; }, + value: function() { + return this.$.close; + }, observer: 'firstFocusableNodeChanged_' }, @@ -39,7 +35,9 @@ */ lastFocusableNode: { type: Object, - value: function() { return this.$.close; }, + value: function() { + return this.$.close; + }, observer: 'lastFocusableNodeChanged_' } },
diff --git a/chrome/browser/resources/md_user_manager/user_manager_pages.js b/chrome/browser/resources/md_user_manager/user_manager_pages.js index fb08ddc..39b932f 100644 --- a/chrome/browser/resources/md_user_manager/user_manager_pages.js +++ b/chrome/browser/resources/md_user_manager/user_manager_pages.js
@@ -14,24 +14,16 @@ * ID of the currently selected page. * @private {string} */ - selectedPage_: { - type: String, - value: 'user-pods-page' - }, + selectedPage_: {type: String, value: 'user-pods-page'}, /** * Data passed to the currently selected page. * @private {?Object} */ - pageData_: { - type: Object, - value: null - } + pageData_: {type: Object, value: null} }, - listeners: { - 'change-page': 'onChangePage_' - }, + listeners: {'change-page': 'onChangePage_'}, /** * Handler for the change-page event.
diff --git a/chrome/browser/resources/md_user_manager/user_manager_tutorial.js b/chrome/browser/resources/md_user_manager/user_manager_tutorial.js index a9da577..1001781 100644 --- a/chrome/browser/resources/md_user_manager/user_manager_tutorial.js +++ b/chrome/browser/resources/md_user_manager/user_manager_tutorial.js
@@ -25,29 +25,19 @@ * True if the tutorial is currently hidden. * @private {boolean} */ - hidden_: { - type: Boolean, - value: true - }, + hidden_: {type: Boolean, value: true}, /** * Current tutorial step ID. * @type {string} */ - currentStep_: { - type: String, - value: '' - }, + currentStep_: {type: String, value: ''}, /** * Enum values for the step IDs. * @private {TutorialSteps} */ - steps_: { - readOnly: true, - type: Object, - value: TutorialSteps - } + steps_: {readOnly: true, type: Object, value: TutorialSteps} }, /**
diff --git a/chrome/browser/resources/media/webrtc_logs.js b/chrome/browser/resources/media/webrtc_logs.js index 83d48ad..e665ab6 100644 --- a/chrome/browser/resources/media/webrtc_logs.js +++ b/chrome/browser/resources/media/webrtc_logs.js
@@ -15,8 +15,8 @@ * @param {string} version The browser version. */ function updateWebRtcLogsList(uploads, version) { - $('log-banner').textContent = loadTimeData.getStringF('webrtcLogCountFormat', - uploads.length); + $('log-banner').textContent = + loadTimeData.getStringF('webrtcLogCountFormat', uploads.length); var logSection = $('log-list'); @@ -29,9 +29,8 @@ var logBlock = document.createElement('div'); var title = document.createElement('h3'); - title.textContent = - loadTimeData.getStringF('webrtcLogHeaderFormat', - upload['capture_time']); + title.textContent = loadTimeData.getStringF( + 'webrtcLogHeaderFormat', upload['capture_time']); logBlock.appendChild(title); var localFileLine = document.createElement('p'); @@ -54,30 +53,24 @@ loadTimeData.getString('webrtcLogNotUploadedMessage'); } else { uploadLine.textContent = - loadTimeData.getStringF('webrtcLogUploadTimeFormat', - upload['upload_time']) + '. ' + - loadTimeData.getStringF('webrtcLogReportIdFormat', - upload['id']) + '. '; + loadTimeData.getStringF( + 'webrtcLogUploadTimeFormat', upload['upload_time']) + + '. ' + + loadTimeData.getStringF('webrtcLogReportIdFormat', upload['id']) + + '. '; var link = document.createElement('a'); var commentLines = [ - 'Chrome Version: ' + version, - // TODO(tbreisacher): fill in the OS automatically? - 'Operating System: e.g., "Windows 7", "Mac OSX 10.6"', - '', - 'URL (if applicable) where the problem occurred:', - '', - 'Can you reproduce this problem?', - '', - 'What steps will reproduce this problem? (or if it\'s not ' + - 'reproducible, what were you doing just before the problem)?', - '', - '1.', '2.', '3.', - '', - '*Please note that issues filed with no information filled in ' + - 'above will be marked as WontFix*', - '', - '****DO NOT CHANGE BELOW THIS LINE****', - 'report_id:' + upload.id + 'Chrome Version: ' + version, + // TODO(tbreisacher): fill in the OS automatically? + 'Operating System: e.g., "Windows 7", "Mac OSX 10.6"', '', + 'URL (if applicable) where the problem occurred:', '', + 'Can you reproduce this problem?', '', + 'What steps will reproduce this problem? (or if it\'s not ' + + 'reproducible, what were you doing just before the problem)?', + '', '1.', '2.', '3.', '', + '*Please note that issues filed with no information filled in ' + + 'above will be marked as WontFix*', + '', '****DO NOT CHANGE BELOW THIS LINE****', 'report_id:' + upload.id ]; var params = { template: 'Defect report from user',
diff --git a/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.js b/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.js index 4698589d..28633c8a4 100644 --- a/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.js +++ b/chrome/browser/resources/media_router/elements/issue_banner/issue_banner.js
@@ -115,7 +115,7 @@ */ onClickOptAction_: function(event) { this.fireIssueActionClick_( - /** @type {number} */(this.issue.secondaryActionType)); + /** @type {number} */ (this.issue.secondaryActionType)); }, /** @@ -128,14 +128,13 @@ var defaultText = ''; var secondaryText = ''; if (this.issue) { - defaultText = - this.i18n(this.actionTypeToButtonTextResource_[ - this.issue.defaultActionType]); + defaultText = this.i18n( + this.actionTypeToButtonTextResource_[this.issue.defaultActionType]); if (this.issue.secondaryActionType !== undefined) { - secondaryText = - this.i18n(this.actionTypeToButtonTextResource_[ - this.issue.secondaryActionType]); + secondaryText = this.i18n( + this.actionTypeToButtonTextResource_[this.issue + .secondaryActionType]); } }
diff --git a/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js b/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js index 155bc820..6ccebfcc 100644 --- a/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js +++ b/chrome/browser/resources/media_router/elements/media_router_container/media_router_container.js
@@ -447,13 +447,17 @@ that.putSearchAtBottom_(); } }; - this.importHref('chrome://resources/polymer/v1_0/neon-animation/' + - 'web-animations.html', onload); - this.importHref(this.resolveUrl( - '../issue_banner/issue_banner.html'), onload); - this.importHref(this.resolveUrl( - '../media_router_search_highlighter/' + - 'media_router_search_highlighter.html'), onload); + this.importHref( + 'chrome://resources/polymer/v1_0/neon-animation/' + + 'web-animations.html', + onload); + this.importHref( + this.resolveUrl('../issue_banner/issue_banner.html'), onload); + this.importHref( + this.resolveUrl( + '../media_router_search_highlighter/' + + 'media_router_search_highlighter.html'), + onload); // If this is not on a Mac platform, remove the placeholder. See // onFocus_() for more details. ready() is only called once, so no need @@ -497,7 +501,8 @@ // Only set |userOptedIntoCloudServices| if the user was shown the cloud // services preferences option. var userOptedIntoCloudServices = this.showFirstRunFlowCloudPref ? - this.$$('#first-run-cloud-checkbox').checked : undefined; + this.$$('#first-run-cloud-checkbox').checked : + undefined; this.fire('acknowledge-first-run-flow', { optedIntoCloudServices: userOptedIntoCloudServices, }); @@ -730,8 +735,8 @@ */ computeHeaderHidden_: function(view, issue) { return view == media_router.MediaRouterView.ROUTE_DETAILS || - (view == media_router.MediaRouterView.SINK_LIST && - !!issue && issue.isBlocking); + (view == media_router.MediaRouterView.SINK_LIST && !!issue && + issue.isBlocking); }, /** @@ -748,7 +753,8 @@ return this.i18n('issueHeaderText'); case media_router.MediaRouterView.ROUTE_DETAILS: return this.currentRoute_ && this.sinkMap_[this.currentRoute_.sinkId] ? - this.sinkMap_[this.currentRoute_.sinkId].name : ''; + this.sinkMap_[this.currentRoute_.sinkId].name : + ''; case media_router.MediaRouterView.SINK_LIST: case media_router.MediaRouterView.FILTER: return this.headerText; @@ -793,9 +799,10 @@ * @private */ computeIssueBannerShown_: function(view, issue) { - return !!issue && (view == media_router.MediaRouterView.SINK_LIST || - view == media_router.MediaRouterView.FILTER || - view == media_router.MediaRouterView.ISSUE); + return !!issue && + (view == media_router.MediaRouterView.SINK_LIST || + view == media_router.MediaRouterView.FILTER || + view == media_router.MediaRouterView.ISSUE); }, /** @@ -808,7 +815,7 @@ */ computeNoMatchesHidden_: function(searchResultsToShow, isSearchListHidden) { return isSearchListHidden || this.searchInputText_.length == 0 || - searchResultsToShow.length != 0; + searchResultsToShow.length != 0; }, /** @@ -1109,8 +1116,8 @@ computeTotalSearchHeight_: function( deviceMissing, noMatches, results, searchOffsetHeight, maxHeight) { var contentHeight = deviceMissing.offsetHeight + - ((noMatches.hasAttribute('hidden')) ? - results.offsetHeight : noMatches.offsetHeight); + ((noMatches.hasAttribute('hidden')) ? results.offsetHeight : + noMatches.offsetHeight); return Math.min(contentHeight, maxHeight) + searchOffsetHeight; }, @@ -1156,13 +1163,12 @@ var searchResultsToShow = []; for (var i = 0; i < this.sinksToShow_.length; ++i) { var matchSubstrings = this.computeSearchMatches_( - searchInputText, - this.sinksToShow_[i].name); + searchInputText, this.sinksToShow_[i].name); if (!matchSubstrings) { continue; } - searchResultsToShow.push({sinkItem: this.sinksToShow_[i], - substrings: matchSubstrings}); + searchResultsToShow.push( + {sinkItem: this.sinksToShow_[i], substrings: matchSubstrings}); } searchResultsToShow.sort(this.compareSearchMatches_); @@ -1179,17 +1185,24 @@ // the pseudo sink for the search will be treated like a real sink because // it will actually be in |sinksToShow_| until a real sink is returned by // search. So the filter here shouldn't treat it like a pseudo sink. - searchResultsToShow = this.pseudoSinks_.filter(function(pseudoSink) { - return (!pendingPseudoSink || pseudoSink.id != pendingPseudoSink.id) && - !searchResultsToShow.find(function(searchResult) { - return searchResult.sinkItem.name == searchInputText && - searchResult.sinkItem.iconType == pseudoSink.iconType; - }); - }).map(function(pseudoSink) { - pseudoSink.name = searchInputText; - return {sinkItem: pseudoSink, - substrings: [[0, searchInputText.length - 1]]}; - }).concat(searchResultsToShow); + searchResultsToShow = + this.pseudoSinks_ + .filter(function(pseudoSink) { + return (!pendingPseudoSink || + pseudoSink.id != pendingPseudoSink.id) && + !searchResultsToShow.find(function(searchResult) { + return searchResult.sinkItem.name == searchInputText && + searchResult.sinkItem.iconType == pseudoSink.iconType; + }); + }) + .map(function(pseudoSink) { + pseudoSink.name = searchInputText; + return { + sinkItem: pseudoSink, + substrings: [[0, searchInputText.length - 1]] + }; + }) + .concat(searchResultsToShow); this.searchResultsToShow_ = searchResultsToShow; }, @@ -1226,8 +1239,10 @@ */ getElementVerticalPadding_: function(element) { var style = window.getComputedStyle(element); - return [parseInt(style.getPropertyValue('padding-bottom'), 10) || 0, - parseInt(style.getPropertyValue('padding-top'), 10) || 0]; + return [ + parseInt(style.getPropertyValue('padding-bottom'), 10) || 0, + parseInt(style.getPropertyValue('padding-top'), 10) || 0 + ]; }, /** @@ -1238,7 +1253,8 @@ */ getFirstRunFlowCloudPrefText_: function() { return loadTimeData.valueExists('firstRunFlowCloudPrefText') ? - this.i18n('firstRunFlowCloudPrefText') : ''; + this.i18n('firstRunFlowCloudPrefText') : + ''; }, /** @@ -1457,34 +1473,55 @@ // This GroupEffect does the reverse of |moveSearchToTop_|. It fades the // sink list in while sliding the search input and search results list down. // The dialog height is also adjusted smoothly to the sink list height. - var deviceMissingEffect = new KeyframeEffect(deviceMissing, - [{'marginBottom': searchInitialOffsetHeight}, - {'marginBottom': searchFinalOffsetHeight}], + var deviceMissingEffect = new KeyframeEffect( + deviceMissing, + [ + {'marginBottom': searchInitialOffsetHeight}, + {'marginBottom': searchFinalOffsetHeight} + ], timing); - var listEffect = new KeyframeEffect(list, - [{'opacity': '0'}, {'opacity': '1'}], + var listEffect = + new KeyframeEffect(list, [{'opacity': '0'}, {'opacity': '1'}], timing); + var resultsEffect = new KeyframeEffect( + resultsContainer, + [ + { + 'top': resultsInitialTop + 'px', + 'paddingTop': resultsContainer.style['padding-top'] + }, + {'top': '100%', 'paddingTop': '0px'} + ], timing); - var resultsEffect = new KeyframeEffect(resultsContainer, - [{'top': resultsInitialTop + 'px', - 'paddingTop': resultsContainer.style['padding-top']}, - {'top': '100%', 'paddingTop': '0px'}], + var searchEffect = new KeyframeEffect( + search, + [ + { + 'top': searchInitialTop + 'px', + 'marginTop': '0px', + 'paddingBottom': searchInitialPaddingBottom + 'px', + 'paddingTop': searchInitialPaddingTop + 'px' + }, + { + 'top': '100%', + 'marginTop': '-' + searchFinalOffsetHeight + 'px', + 'paddingBottom': searchFinalPaddingBottom + 'px', + 'paddingTop': searchFinalPaddingTop + 'px' + } + ], timing); - var searchEffect = new KeyframeEffect(search, - [{'top': searchInitialTop + 'px', 'marginTop': '0px', - 'paddingBottom': searchInitialPaddingBottom + 'px', - 'paddingTop': searchInitialPaddingTop + 'px'}, - {'top': '100%', 'marginTop': '-' + searchFinalOffsetHeight + 'px', - 'paddingBottom': searchFinalPaddingBottom + 'px', - 'paddingTop': searchFinalPaddingTop + 'px'}], + var viewEffect = new KeyframeEffect( + view, + [ + {'height': initialHeight + 'px', 'paddingBottom': '0px'}, { + 'height': finalHeight + 'px', + 'paddingBottom': searchFinalOffsetHeight + 'px' + } + ], timing); - var viewEffect = new KeyframeEffect(view, - [{'height': initialHeight + 'px', 'paddingBottom': '0px'}, - {'height': finalHeight + 'px', - 'paddingBottom': searchFinalOffsetHeight + 'px'}], - timing); - var player = document.timeline.play(new GroupEffect(hasList ? - [listEffect, resultsEffect, searchEffect, viewEffect] : - [deviceMissingEffect, resultsEffect, searchEffect, viewEffect])); + var player = document.timeline.play(new GroupEffect( + hasList ? + [listEffect, resultsEffect, searchEffect, viewEffect] : + [deviceMissingEffect, resultsEffect, searchEffect, viewEffect])); var that = this; var finalizeAnimation = function() { @@ -1560,34 +1597,55 @@ // This GroupEffect will cause the sink list to fade out while the search // input and search results list slide up. The dialog will also resize // smoothly to the new search result list height. - var deviceMissingEffect = new KeyframeEffect(deviceMissing, - [{'marginBottom': searchInitialOffsetHeight}, - {'marginBottom': searchFinalOffsetHeight}], + var deviceMissingEffect = new KeyframeEffect( + deviceMissing, + [ + {'marginBottom': searchInitialOffsetHeight}, + {'marginBottom': searchFinalOffsetHeight} + ], timing); - var listEffect = new KeyframeEffect(list, - [{'opacity': '1'}, {'opacity': '0'}], + var listEffect = + new KeyframeEffect(list, [{'opacity': '1'}, {'opacity': '0'}], timing); + var resultsEffect = new KeyframeEffect( + resultsContainer, + [ + {'top': '100%', 'paddingTop': '0px'}, { + 'top': searchFinalTop + 'px', + 'paddingTop': searchFinalOffsetHeight + 'px' + } + ], timing); - var resultsEffect = new KeyframeEffect(resultsContainer, - [{'top': '100%', 'paddingTop': '0px'}, - {'top': searchFinalTop + 'px', - 'paddingTop': searchFinalOffsetHeight + 'px'}], + var searchEffect = new KeyframeEffect( + search, + [ + { + 'top': '100%', + 'marginTop': '-' + searchInitialOffsetHeight + 'px', + 'paddingBottom': searchInitialPaddingBottom + 'px', + 'paddingTop': searchInitialPaddingTop + 'px' + }, + { + 'top': searchFinalTop + 'px', + 'marginTop': '0px', + 'paddingBottom': searchFinalPaddingBottom + 'px', + 'paddingTop': searchFinalPaddingTop + 'px' + } + ], timing); - var searchEffect = new KeyframeEffect(search, - [{'top': '100%', 'marginTop': '-' + searchInitialOffsetHeight + 'px', - 'paddingBottom': searchInitialPaddingBottom + 'px', - 'paddingTop': searchInitialPaddingTop + 'px'}, - {'top': searchFinalTop + 'px', 'marginTop': '0px', - 'paddingBottom': searchFinalPaddingBottom + 'px', - 'paddingTop': searchFinalPaddingTop + 'px'}], + var viewEffect = new KeyframeEffect( + view, + [ + { + 'height': initialHeight + 'px', + 'paddingBottom': searchInitialOffsetHeight + 'px' + }, + {'height': finalHeight + 'px', 'paddingBottom': '0px'} + ], timing); - var viewEffect = new KeyframeEffect(view, - [{'height': initialHeight + 'px', - 'paddingBottom': searchInitialOffsetHeight + 'px'}, - {'height': finalHeight + 'px', 'paddingBottom': '0px'}], - timing); - var player = document.timeline.play(new GroupEffect(hasList ? - [listEffect, resultsEffect, searchEffect, viewEffect] : - [deviceMissingEffect, resultsEffect, searchEffect, viewEffect])); + var player = document.timeline.play(new GroupEffect( + hasList ? + [listEffect, resultsEffect, searchEffect, viewEffect] : + [deviceMissingEffect, resultsEffect, searchEffect, viewEffect])); var that = this; var finalizeAnimation = function() { @@ -1716,9 +1774,9 @@ // Regardless of whether the route is for display, it was resolved // successfully. - this.fire('report-resolved-route', { - outcome: media_router.MediaRouterRouteCreationOutcome.SUCCESS - }); + this.fire( + 'report-resolved-route', + {outcome: media_router.MediaRouterRouteCreationOutcome.SUCCESS}); if (isForDisplay) { this.showRouteDetails_(route); @@ -1764,8 +1822,8 @@ // handled on the C++ side instead of the JS side on non-mac platforms, // which uses toolkit-views. Handle the expected behavior on all platforms // here. - if (e.key == media_router.KEY_ESC && !e.shiftKey && - !e.ctrlKey && !e.altKey && !e.metaKey) { + if (e.key == media_router.KEY_ESC && !e.shiftKey && !e.ctrlKey && + !e.altKey && !e.metaKey) { // When searching, allow ESC as a mechanism to leave the filter view. if (this.currentView_ == media_router.MediaRouterView.FILTER) { // If the user tabbed to an item in the search results, or otherwise has @@ -1912,15 +1970,22 @@ this.searchUseBottomPadding = this.shouldSearchUseBottomPadding_(deviceMissing); var resultsPadding = this.computeElementVerticalPadding_(results); - var finalHeight = this.computeTotalSearchHeight_(deviceMissing, noMatches, - results, search.offsetHeight, this.sinkListMaxHeight_ + resultsPadding); + var finalHeight = this.computeTotalSearchHeight_( + deviceMissing, noMatches, results, search.offsetHeight, + this.sinkListMaxHeight_ + resultsPadding); if (finalHeight != view.offsetHeight) { - var viewEffect = new KeyframeEffect(view, - [{'height': view.offsetHeight + 'px'}, - {'height': finalHeight + 'px'}], - {duration: - this.computeAnimationDuration_(finalHeight - view.offsetHeight), - easing: 'ease-in-out', fill: 'forwards'}); + var viewEffect = new KeyframeEffect( + view, + [ + {'height': view.offsetHeight + 'px'}, + {'height': finalHeight + 'px'} + ], + { + duration: + this.computeAnimationDuration_(finalHeight - view.offsetHeight), + easing: 'ease-in-out', + fill: 'forwards' + }); var player = document.timeline.play(viewEffect); if (this.heightAdjustmentPlayer_) { this.heightAdjustmentPlayer_.cancel(); @@ -2120,7 +2185,7 @@ if (this.shownCastModeValue_ != media_router.CastModeType.AUTO) { updatedSinkList = updatedSinkList.filter(function(element) { return (element.castModes & this.shownCastModeValue_) || - this.sinkToRouteMap_[element.id]; + this.sinkToRouteMap_[element.id]; }, this); } @@ -2131,7 +2196,8 @@ if (this.sinksToShow_) { for (var i = this.sinksToShow_.length - 1; i >= 0; i--) { var index = updatedSinkList.findIndex(function(updatedSink) { - return this.sinksToShow_[i].id == updatedSink.id; }.bind(this)); + return this.sinksToShow_[i].id == updatedSink.id; + }.bind(this)); if (index < 0) { // Remove any sinks that are no longer discovered. this.sinksToShow_.splice(i, 1); @@ -2344,7 +2410,8 @@ // Allow one launch at a time. var selectedCastModeValue = this.shownCastModeValue_ == media_router.CastModeType.AUTO ? - sink.castModes & -sink.castModes : this.shownCastModeValue_; + sink.castModes & -sink.castModes : + this.shownCastModeValue_; if (sink.isPseudoSink) { this.pseudoSinkSearchState_ = new PseudoSinkSearchState(sink); this.fire('search-sinks-and-create-route', { @@ -2463,11 +2530,13 @@ // element can have a fractional height. So we use getBoundingClientRect() // to avoid rounding errors. var firstRunFlowHeight = this.$$('#first-run-flow') && - this.$$('#first-run-flow').style.display != 'none' ? - this.$$('#first-run-flow').getBoundingClientRect().height : 0; + this.$$('#first-run-flow').style.display != 'none' ? + this.$$('#first-run-flow').getBoundingClientRect().height : + 0; var issueHeight = this.$$('#issue-banner') && - this.$$('#issue-banner').style.display != 'none' ? - this.$$('#issue-banner').offsetHeight : 0; + this.$$('#issue-banner').style.display != 'none' ? + this.$$('#issue-banner').offsetHeight : + 0; var search = this.$$('#sink-search'); var hasSearch = this.hasConditionalElement_(search); var searchHeight = hasSearch ? search.offsetHeight : 0;
diff --git a/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js b/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js index 599c99f..1c375cb 100644 --- a/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js +++ b/chrome/browser/resources/media_router/elements/media_router_header/media_router_header.js
@@ -99,8 +99,8 @@ attached: function() { // isRTL() only works after i18n_template.js runs to set <html dir>. // Set the back button icon based on text direction. - this.arrowDropIcon_ = isRTL() ? - 'media-router:arrow-forward' : 'media-router:arrow-back'; + this.arrowDropIcon_ = + isRTL() ? 'media-router:arrow-forward' : 'media-router:arrow-back'; }, /** @@ -110,7 +110,8 @@ */ computeArrowDropIcon_: function(view) { return view == media_router.MediaRouterView.CAST_MODE_LIST ? - 'media-router:arrow-drop-up' : 'media-router:arrow-drop-down'; + 'media-router:arrow-drop-up' : + 'media-router:arrow-drop-down'; }, /** @@ -131,7 +132,7 @@ computeArrowDropTitle_: function(view) { return view == media_router.MediaRouterView.CAST_MODE_LIST ? this.i18n('viewDeviceListButtonTitle') : - this.i18n('viewCastModeListButtonTitle'); + this.i18n('viewCastModeListButtonTitle'); }, /** @@ -205,8 +206,8 @@ this.$$('#header').style.height = this.showEmail && !this.isEmptyOrWhitespace_(this.userEmail) ? - this.headerWithEmailHeight_ + 'px' : - this.headerWithoutEmailHeight_ + 'px'; + this.headerWithEmailHeight_ + 'px' : + this.headerWithoutEmailHeight_ + 'px'; // Only fire if height actually changed. if (currentHeight != this.offsetHeight) { @@ -225,7 +226,8 @@ updateHeaderCursorStyle_: function(view) { this.$$('#header-text').style.cursor = view == media_router.MediaRouterView.SINK_LIST || - view == media_router.MediaRouterView.CAST_MODE_LIST ? - 'pointer' : 'auto'; + view == media_router.MediaRouterView.CAST_MODE_LIST ? + 'pointer' : + 'auto'; }, });
diff --git a/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.js b/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.js index a38aa7f9..b3d8e17 100644 --- a/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.js +++ b/chrome/browser/resources/media_router/elements/media_router_search_highlighter/media_router_search_highlighter.js
@@ -65,13 +65,12 @@ var text = ''; for (var i = 0; i < data.highlightedText.length; ++i) { if (data.plainText[i]) { - text += - HTMLEscape(/** @type {!string} */ (data.plainText[i])); + text += HTMLEscape(/** @type {!string} */ (data.plainText[i])); } if (data.highlightedText[i]) { text += '<span class="highlight">' + HTMLEscape(/** @type {!string} */ (data.highlightedText[i])) + - '</span>'; + '</span>'; } } this.$.text.innerHTML = text;
diff --git a/chrome/browser/resources/media_router/media_router.js b/chrome/browser/resources/media_router/media_router.js index cd65124..9ff13ec 100644 --- a/chrome/browser/resources/media_router/media_router.js +++ b/chrome/browser/resources/media_router/media_router.js
@@ -28,40 +28,40 @@ container = /** @type {!MediaRouterContainerElement} */ ($('media-router-container')); - media_router.ui.setElements(container, - /** @type {!MediaRouterHeaderElement} */(container.header)); + media_router.ui.setElements( + container, + /** @type {!MediaRouterHeaderElement} */ (container.header)); - container.addEventListener('acknowledge-first-run-flow', - onAcknowledgeFirstRunFlow); + container.addEventListener( + 'acknowledge-first-run-flow', onAcknowledgeFirstRunFlow); container.addEventListener('back-click', onNavigateToSinkList); container.addEventListener('cast-mode-selected', onCastModeSelected); - container.addEventListener('change-route-source-click', - onChangeRouteSourceClick); + container.addEventListener( + 'change-route-source-click', onChangeRouteSourceClick); container.addEventListener('close-dialog', onCloseDialog); container.addEventListener('close-route', onCloseRoute); container.addEventListener('create-route', onCreateRoute); container.addEventListener('issue-action-click', onIssueActionClick); container.addEventListener('join-route-click', onJoinRouteClick); - container.addEventListener('navigate-sink-list-to-details', - onNavigateToDetails); - container.addEventListener('navigate-to-cast-mode-list', - onNavigateToCastMode); + container.addEventListener( + 'navigate-sink-list-to-details', onNavigateToDetails); + container.addEventListener( + 'navigate-to-cast-mode-list', onNavigateToCastMode); container.addEventListener( 'select-local-media-file', onSelectLocalMediaFile); container.addEventListener('report-filter', onFilter); container.addEventListener('report-initial-action', onInitialAction); - container.addEventListener('report-initial-action-close', - onInitialActionClose); + container.addEventListener( + 'report-initial-action-close', onInitialActionClose); container.addEventListener('report-route-creation', onReportRouteCreation); - container.addEventListener('report-sink-click-time', - onSinkClickTimeReported); + container.addEventListener( + 'report-sink-click-time', onSinkClickTimeReported); container.addEventListener('report-sink-count', onSinkCountReported); - container.addEventListener('report-resolved-route', - onReportRouteCreationOutcome); - container.addEventListener('request-initial-data', - onRequestInitialData); - container.addEventListener('search-sinks-and-create-route', - onSearchSinksAndCreateRoute); + container.addEventListener( + 'report-resolved-route', onReportRouteCreationOutcome); + container.addEventListener('request-initial-data', onRequestInitialData); + container.addEventListener( + 'search-sinks-and-create-route', onSearchSinksAndCreateRoute); container.addEventListener('show-initial-state', onShowInitialState); container.addEventListener('sink-click', onSinkClick); @@ -210,9 +210,8 @@ function onIssueActionClick(event) { /** @type {{id: number, actionType: number, helpPageId: number}} */ var detail = event.detail; - media_router.browserApi.actOnIssue(detail.id, - detail.actionType, - detail.helpPageId); + media_router.browserApi.actOnIssue( + detail.id, detail.actionType, detail.helpPageId); container.issue = null; } @@ -228,8 +227,8 @@ function onCreateRoute(event) { /** @type {{sinkId: string, selectedCastModeValue: number}} */ var detail = event.detail; - media_router.browserApi.requestRoute(detail.sinkId, - detail.selectedCastModeValue); + media_router.browserApi.requestRoute( + detail.sinkId, detail.selectedCastModeValue); } /**
diff --git a/chrome/browser/resources/media_router/media_router_data.js b/chrome/browser/resources/media_router/media_router_data.js index 53d5b4ce..e5d2c8c 100644 --- a/chrome/browser/resources/media_router/media_router_data.js +++ b/chrome/browser/resources/media_router/media_router_data.js
@@ -137,9 +137,9 @@ * Placeholder object for AUTO cast mode. See comment in CastModeType. * @const {!media_router.CastMode} */ - var AUTO_CAST_MODE = new CastMode(media_router.CastModeType.AUTO, - loadTimeData.getString('autoCastMode'), - null, false); + var AUTO_CAST_MODE = new CastMode( + media_router.CastModeType.AUTO, loadTimeData.getString('autoCastMode'), + null, false); /** * @param {number} id The ID of this issue. @@ -154,9 +154,9 @@ * @constructor * @struct */ - var Issue = function(id, title, message, defaultActionType, - secondaryActionType, routeId, isBlocking, - helpPageId) { + var Issue = function( + id, title, message, defaultActionType, secondaryActionType, routeId, + isBlocking, helpPageId) { /** @type {number} */ this.id = id; @@ -196,8 +196,8 @@ * @constructor * @struct */ - var Route = function(id, sinkId, description, tabId, isLocal, canJoin, - customControllerPath) { + var Route = function( + id, sinkId, description, tabId, isLocal, canJoin, customControllerPath) { /** @type {string} */ this.id = id; @@ -290,8 +290,8 @@ * @constructor * @struct */ - var Sink = function(id, name, description, domain, iconType, status, - castModes) { + var Sink = function( + id, name, description, domain, iconType, status, castModes) { /** @type {string} */ this.id = id;
diff --git a/chrome/browser/resources/net_internals/details_view.js b/chrome/browser/resources/net_internals/details_view.js index 1b1792f..adf0184 100644 --- a/chrome/browser/resources/net_internals/details_view.js +++ b/chrome/browser/resources/net_internals/details_view.js
@@ -62,7 +62,8 @@ var p = addNode(div, 'p'); addNodeWithText( - p, 'h4', sourceEntry.getSourceId() + ': ' + + p, 'h4', + sourceEntry.getSourceId() + ': ' + sourceEntry.getSourceTypeString()); if (sourceEntry.getDescription())
diff --git a/chrome/browser/resources/net_internals/log_util.js b/chrome/browser/resources/net_internals/log_util.js index 40ac3b2..623bc27 100644 --- a/chrome/browser/resources/net_internals/log_util.js +++ b/chrome/browser/resources/net_internals/log_util.js
@@ -271,8 +271,5 @@ } // Exports. - return { - createLogDumpAsync: createLogDumpAsync, - loadLogFile: loadLogFile - }; + return {createLogDumpAsync: createLogDumpAsync, loadLogFile: loadLogFile}; })();
diff --git a/chrome/browser/resources/net_internals/log_view_painter.js b/chrome/browser/resources/net_internals/log_view_painter.js index 54cc6d8..6210fab 100644 --- a/chrome/browser/resources/net_internals/log_view_painter.js +++ b/chrome/browser/resources/net_internals/log_view_painter.js
@@ -10,262 +10,261 @@ // Start of anonymous namespace. (function() { - 'use strict'; +'use strict'; - function canCollapseBeginWithEnd(beginEntry) { - return beginEntry && beginEntry.isBegin() && beginEntry.end && - beginEntry.end.index == beginEntry.index + 1 && - (!beginEntry.orig.params || !beginEntry.end.orig.params); +function canCollapseBeginWithEnd(beginEntry) { + return beginEntry && beginEntry.isBegin() && beginEntry.end && + beginEntry.end.index == beginEntry.index + 1 && + (!beginEntry.orig.params || !beginEntry.end.orig.params); +} + +/** + * Creates a TablePrinter for use by the above two functions. baseTime is + * the time relative to which other times are displayed. + */ +createLogEntryTablePrinter = function( + logEntries, privacyStripping, baseTime, logCreationTime) { + var entries = LogGroupEntry.createArrayFrom(logEntries); + var tablePrinter = new TablePrinter(); + var parameterOutputter = new ParameterOutputter(tablePrinter); + + if (entries.length == 0) + return tablePrinter; + + var startTime = timeutil.convertTimeTicksToTime(entries[0].orig.time); + + for (var i = 0; i < entries.length; ++i) { + var entry = entries[i]; + + // Avoid printing the END for a BEGIN that was immediately before, unless + // both have extra parameters. + if (!entry.isEnd() || !canCollapseBeginWithEnd(entry.begin)) { + var entryTime = timeutil.convertTimeTicksToTime(entry.orig.time); + addRowWithTime(tablePrinter, entryTime - baseTime, startTime - baseTime); + + for (var j = entry.getDepth(); j > 0; --j) + tablePrinter.addCell(' '); + + var eventText = getTextForEvent(entry); + // Get the elapsed time, and append it to the event text. + if (entry.isBegin()) { + var dt = '?'; + // Definite time. + if (entry.end) { + dt = entry.end.orig.time - entry.orig.time; + } else if (logCreationTime != undefined) { + dt = (logCreationTime - entryTime) + '+'; + } + eventText += ' [dt=' + dt + ']'; + } + + var mainCell = tablePrinter.addCell(eventText); + mainCell.allowOverflow = true; + } + + // Output the extra parameters. + if (typeof entry.orig.params == 'object') { + // Those 5 skipped cells are: two for "t=", and three for "st=". + tablePrinter.setNewRowCellIndent(5 + entry.getDepth()); + writeParameters(entry.orig, privacyStripping, parameterOutputter); + + tablePrinter.setNewRowCellIndent(0); + } } + // If viewing a saved log file, add row with just the time the log was + // created, if the event never completed. + var lastEntry = entries[entries.length - 1]; + // If the last entry has a non-zero depth or is a begin event, the source is + // still active. + var isSourceActive = lastEntry.getDepth() != 0 || lastEntry.isBegin(); + if (logCreationTime != undefined && isSourceActive) { + addRowWithTime( + tablePrinter, logCreationTime - baseTime, startTime - baseTime); + } + + return tablePrinter; +}; + +/** + * Adds a new row to the given TablePrinter, and adds five cells containing + * information about the time an event occured. + * Format is '[t=<time of the event in ms>] [st=<ms since the source + * started>]'. + * @param {TablePrinter} tablePrinter The table printer to add the cells to. + * @param {number} eventTime The time the event occured, in milliseconds, + * relative to some base time. + * @param {number} startTime The time the first event for the source occured, + * relative to the same base time as eventTime. + */ +function addRowWithTime(tablePrinter, eventTime, startTime) { + tablePrinter.addRow(); + tablePrinter.addCell('t='); + var tCell = tablePrinter.addCell(eventTime); + tCell.alignRight = true; + tablePrinter.addCell(' [st='); + var stCell = tablePrinter.addCell(eventTime - startTime); + stCell.alignRight = true; + tablePrinter.addCell('] '); +} + +/** + * |hexString| must be a string of hexadecimal characters with no whitespace, + * whose length is a multiple of two. Writes multiple lines to |out| with + * the hexadecimal characters from |hexString| on the left, in groups of + * two, and their corresponding ASCII characters on the right. + * + * 16 bytes will be placed on each line of the output string, split into two + * columns of 8. + */ +function writeHexString(hexString, out) { + var asciiCharsPerLine = 16; + // Number of transferred bytes in a line of output. Length of a + // line is roughly 4 times larger. + var hexCharsPerLine = 2 * asciiCharsPerLine; + for (var i = 0; i < hexString.length; i += hexCharsPerLine) { + var hexLine = ''; + var asciiLine = ''; + for (var j = i; j < i + hexCharsPerLine && j < hexString.length; j += 2) { + // Split into two columns of 8 bytes each. + if (j == i + hexCharsPerLine / 2) + hexLine += ' '; + var hex = hexString.substr(j, 2); + hexLine += hex + ' '; + var charCode = parseInt(hex, 16); + // For ASCII codes 32 though 126, display the corresponding + // characters. Use a space for nulls, and a period for + // everything else. + if (charCode >= 0x20 && charCode <= 0x7E) { + asciiLine += String.fromCharCode(charCode); + } else if (charCode == 0x00) { + asciiLine += ' '; + } else { + asciiLine += '.'; + } + } + + // Make the ASCII text for the last line of output align with the previous + // lines. + hexLine += + makeRepeatedString(' ', 3 * asciiCharsPerLine + 1 - hexLine.length); + out.writeLine(' ' + hexLine + ' ' + asciiLine); + } +} + +/** + * Wrapper around a TablePrinter to simplify outputting lines of text for + * event + * parameters. + */ +var ParameterOutputter = (function() { /** - * Creates a TablePrinter for use by the above two functions. baseTime is - * the time relative to which other times are displayed. + * @constructor */ - createLogEntryTablePrinter = function( - logEntries, privacyStripping, baseTime, logCreationTime) { - var entries = LogGroupEntry.createArrayFrom(logEntries); - var tablePrinter = new TablePrinter(); - var parameterOutputter = new ParameterOutputter(tablePrinter); + function ParameterOutputter(tablePrinter) { + this.tablePrinter_ = tablePrinter; + } - if (entries.length == 0) - return tablePrinter; + ParameterOutputter.prototype = { + /** + * Outputs a single line. + */ + writeLine: function(line) { + this.tablePrinter_.addRow(); + var cell = this.tablePrinter_.addCell(line); + cell.allowOverflow = true; + return cell; + }, - var startTime = timeutil.convertTimeTicksToTime(entries[0].orig.time); + /** + * Outputs a key=value line which looks like: + * + * --> key = value + */ + writeArrowKeyValue: function(key, value, link) { + var cell = this.writeLine(kArrow + key + ' = ' + value); + cell.link = link; + }, - for (var i = 0; i < entries.length; ++i) { - var entry = entries[i]; + /** + * Outputs a key= line which looks like: + * + * --> key = + */ + writeArrowKey: function(key) { + this.writeLine(kArrow + key + ' ='); + }, - // Avoid printing the END for a BEGIN that was immediately before, unless - // both have extra parameters. - if (!entry.isEnd() || !canCollapseBeginWithEnd(entry.begin)) { - var entryTime = timeutil.convertTimeTicksToTime(entry.orig.time); - addRowWithTime( - tablePrinter, entryTime - baseTime, startTime - baseTime); + /** + * Outputs multiple lines, each indented by numSpaces. + * For instance if numSpaces=8 it might look like this: + * + * line 1 + * line 2 + * line 3 + */ + writeSpaceIndentedLines: function(numSpaces, lines) { + var prefix = makeRepeatedString(' ', numSpaces); + for (var i = 0; i < lines.length; ++i) + this.writeLine(prefix + lines[i]); + }, - for (var j = entry.getDepth(); j > 0; --j) - tablePrinter.addCell(' '); + /** + * Outputs multiple lines such that the first line has + * an arrow pointing at it, and subsequent lines + * align with the first one. For example: + * + * --> line 1 + * line 2 + * line 3 + */ + writeArrowIndentedLines: function(lines) { + if (lines.length == 0) + return; - var eventText = getTextForEvent(entry); - // Get the elapsed time, and append it to the event text. - if (entry.isBegin()) { - var dt = '?'; - // Definite time. - if (entry.end) { - dt = entry.end.orig.time - entry.orig.time; - } else if (logCreationTime != undefined) { - dt = (logCreationTime - entryTime) + '+'; - } - eventText += ' [dt=' + dt + ']'; - } + this.writeLine(kArrow + lines[0]); - var mainCell = tablePrinter.addCell(eventText); - mainCell.allowOverflow = true; - } - - // Output the extra parameters. - if (typeof entry.orig.params == 'object') { - // Those 5 skipped cells are: two for "t=", and three for "st=". - tablePrinter.setNewRowCellIndent(5 + entry.getDepth()); - writeParameters(entry.orig, privacyStripping, parameterOutputter); - - tablePrinter.setNewRowCellIndent(0); - } + for (var i = 1; i < lines.length; ++i) + this.writeLine(kArrowIndentation + lines[i]); } - - // If viewing a saved log file, add row with just the time the log was - // created, if the event never completed. - var lastEntry = entries[entries.length - 1]; - // If the last entry has a non-zero depth or is a begin event, the source is - // still active. - var isSourceActive = lastEntry.getDepth() != 0 || lastEntry.isBegin(); - if (logCreationTime != undefined && isSourceActive) { - addRowWithTime( - tablePrinter, logCreationTime - baseTime, startTime - baseTime); - } - - return tablePrinter; }; - /** - * Adds a new row to the given TablePrinter, and adds five cells containing - * information about the time an event occured. - * Format is '[t=<time of the event in ms>] [st=<ms since the source - * started>]'. - * @param {TablePrinter} tablePrinter The table printer to add the cells to. - * @param {number} eventTime The time the event occured, in milliseconds, - * relative to some base time. - * @param {number} startTime The time the first event for the source occured, - * relative to the same base time as eventTime. - */ - function addRowWithTime(tablePrinter, eventTime, startTime) { - tablePrinter.addRow(); - tablePrinter.addCell('t='); - var tCell = tablePrinter.addCell(eventTime); - tCell.alignRight = true; - tablePrinter.addCell(' [st='); - var stCell = tablePrinter.addCell(eventTime - startTime); - stCell.alignRight = true; - tablePrinter.addCell('] '); + var kArrow = ' --> '; + var kArrowIndentation = ' '; + + return ParameterOutputter; +})(); // end of ParameterOutputter + +/** + * Formats the parameters for |entry| and writes them to |out|. + * Certain event types have custom pretty printers. Everything else will + * default to a JSON-like format. + */ +function writeParameters(entry, privacyStripping, out) { + if (privacyStripping) { + // If privacy stripping is enabled, remove data as needed. + entry = stripPrivacyInfo(entry); + } else { + // If headers are in an object, convert them to an array for better + // display. + entry = reformatHeaders(entry); } - /** - * |hexString| must be a string of hexadecimal characters with no whitespace, - * whose length is a multiple of two. Writes multiple lines to |out| with - * the hexadecimal characters from |hexString| on the left, in groups of - * two, and their corresponding ASCII characters on the right. - * - * 16 bytes will be placed on each line of the output string, split into two - * columns of 8. - */ - function writeHexString(hexString, out) { - var asciiCharsPerLine = 16; - // Number of transferred bytes in a line of output. Length of a - // line is roughly 4 times larger. - var hexCharsPerLine = 2 * asciiCharsPerLine; - for (var i = 0; i < hexString.length; i += hexCharsPerLine) { - var hexLine = ''; - var asciiLine = ''; - for (var j = i; j < i + hexCharsPerLine && j < hexString.length; j += 2) { - // Split into two columns of 8 bytes each. - if (j == i + hexCharsPerLine / 2) - hexLine += ' '; - var hex = hexString.substr(j, 2); - hexLine += hex + ' '; - var charCode = parseInt(hex, 16); - // For ASCII codes 32 though 126, display the corresponding - // characters. Use a space for nulls, and a period for - // everything else. - if (charCode >= 0x20 && charCode <= 0x7E) { - asciiLine += String.fromCharCode(charCode); - } else if (charCode == 0x00) { - asciiLine += ' '; - } else { - asciiLine += '.'; - } - } + // Use any parameter writer available for this event type. + var paramsWriter = getParameterWriterForEventType(entry.type); + var consumedParams = {}; + if (paramsWriter) + paramsWriter(entry, out, consumedParams); - // Make the ASCII text for the last line of output align with the previous - // lines. - hexLine += - makeRepeatedString(' ', 3 * asciiCharsPerLine + 1 - hexLine.length); - out.writeLine(' ' + hexLine + ' ' + asciiLine); - } + // Write any un-consumed parameters. + for (var k in entry.params) { + if (consumedParams[k]) + continue; + defaultWriteParameter(k, entry.params[k], out); } +} - /** - * Wrapper around a TablePrinter to simplify outputting lines of text for - * event - * parameters. - */ - var ParameterOutputter = (function() { - /** - * @constructor - */ - function ParameterOutputter(tablePrinter) { - this.tablePrinter_ = tablePrinter; - } - - ParameterOutputter.prototype = { - /** - * Outputs a single line. - */ - writeLine: function(line) { - this.tablePrinter_.addRow(); - var cell = this.tablePrinter_.addCell(line); - cell.allowOverflow = true; - return cell; - }, - - /** - * Outputs a key=value line which looks like: - * - * --> key = value - */ - writeArrowKeyValue: function(key, value, link) { - var cell = this.writeLine(kArrow + key + ' = ' + value); - cell.link = link; - }, - - /** - * Outputs a key= line which looks like: - * - * --> key = - */ - writeArrowKey: function(key) { - this.writeLine(kArrow + key + ' ='); - }, - - /** - * Outputs multiple lines, each indented by numSpaces. - * For instance if numSpaces=8 it might look like this: - * - * line 1 - * line 2 - * line 3 - */ - writeSpaceIndentedLines: function(numSpaces, lines) { - var prefix = makeRepeatedString(' ', numSpaces); - for (var i = 0; i < lines.length; ++i) - this.writeLine(prefix + lines[i]); - }, - - /** - * Outputs multiple lines such that the first line has - * an arrow pointing at it, and subsequent lines - * align with the first one. For example: - * - * --> line 1 - * line 2 - * line 3 - */ - writeArrowIndentedLines: function(lines) { - if (lines.length == 0) - return; - - this.writeLine(kArrow + lines[0]); - - for (var i = 1; i < lines.length; ++i) - this.writeLine(kArrowIndentation + lines[i]); - } - }; - - var kArrow = ' --> '; - var kArrowIndentation = ' '; - - return ParameterOutputter; - })(); // end of ParameterOutputter - - /** - * Formats the parameters for |entry| and writes them to |out|. - * Certain event types have custom pretty printers. Everything else will - * default to a JSON-like format. - */ - function writeParameters(entry, privacyStripping, out) { - if (privacyStripping) { - // If privacy stripping is enabled, remove data as needed. - entry = stripPrivacyInfo(entry); - } else { - // If headers are in an object, convert them to an array for better - // display. - entry = reformatHeaders(entry); - } - - // Use any parameter writer available for this event type. - var paramsWriter = getParameterWriterForEventType(entry.type); - var consumedParams = {}; - if (paramsWriter) - paramsWriter(entry, out, consumedParams); - - // Write any un-consumed parameters. - for (var k in entry.params) { - if (consumedParams[k]) - continue; - defaultWriteParameter(k, entry.params[k], out); - } - } - - /** +/** * Finds a writer to format the parameters for events of type |eventType|. * * @return {function} The returned function "writer" can be invoked @@ -275,493 +274,492 @@ * consumed. If no writer is available for |eventType| then * returns null. */ - function getParameterWriterForEventType(eventType) { - switch (eventType) { - case EventType.HTTP_TRANSACTION_SEND_REQUEST_HEADERS: - case EventType.HTTP_TRANSACTION_SEND_TUNNEL_HEADERS: - case EventType.TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS: - return writeParamsForRequestHeaders; +function getParameterWriterForEventType(eventType) { + switch (eventType) { + case EventType.HTTP_TRANSACTION_SEND_REQUEST_HEADERS: + case EventType.HTTP_TRANSACTION_SEND_TUNNEL_HEADERS: + case EventType.TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS: + return writeParamsForRequestHeaders; - case EventType.PROXY_CONFIG_CHANGED: - return writeParamsForProxyConfigChanged; + case EventType.PROXY_CONFIG_CHANGED: + return writeParamsForProxyConfigChanged; - case EventType.CERT_VERIFIER_JOB: - case EventType.SSL_CERTIFICATES_RECEIVED: - return writeParamsForCertificates; - case EventType.CERT_CT_COMPLIANCE_CHECKED: - case EventType.EV_CERT_CT_COMPLIANCE_CHECKED: - return writeParamsForCheckedCertificates; - } - return null; + case EventType.CERT_VERIFIER_JOB: + case EventType.SSL_CERTIFICATES_RECEIVED: + return writeParamsForCertificates; + case EventType.CERT_CT_COMPLIANCE_CHECKED: + case EventType.EV_CERT_CT_COMPLIANCE_CHECKED: + return writeParamsForCheckedCertificates; + } + return null; +} + +/** + * Default parameter writer that outputs a visualization of field named |key| + * with value |value| to |out|. + */ +function defaultWriteParameter(key, value, out) { + if (key == 'headers' && value instanceof Array) { + out.writeArrowIndentedLines(value); + return; } - /** - * Default parameter writer that outputs a visualization of field named |key| - * with value |value| to |out|. - */ - function defaultWriteParameter(key, value, out) { - if (key == 'headers' && value instanceof Array) { - out.writeArrowIndentedLines(value); - return; - } - - // For transferred bytes, display the bytes in hex and ASCII. - if (key == 'hex_encoded_bytes' && typeof value == 'string') { - out.writeArrowKey(key); - writeHexString(value, out); - return; - } - - // Handle source_dependency entries - add link and map source type to - // string. - if (key == 'source_dependency' && typeof value == 'object') { - var link = '#events&s=' + value.id; - var valueStr = value.id + ' (' + EventSourceTypeNames[value.type] + ')'; - out.writeArrowKeyValue(key, valueStr, link); - return; - } - - if (key == 'net_error' && typeof value == 'number') { - var valueStr = value + ' (' + netErrorToString(value) + ')'; - out.writeArrowKeyValue(key, valueStr); - return; - } - - if (key == 'quic_error' && typeof value == 'number') { - var valueStr = value + ' (' + quicErrorToString(value) + ')'; - out.writeArrowKeyValue(key, valueStr); - return; - } - - if (key == 'quic_crypto_handshake_message' && typeof value == 'string') { - var lines = value.split('\n'); - out.writeArrowIndentedLines(lines); - return; - } - - if (key == 'quic_rst_stream_error' && typeof value == 'number') { - var valueStr = value + ' (' + quicRstStreamErrorToString(value) + ')'; - out.writeArrowKeyValue(key, valueStr); - return; - } - - if (key == 'load_flags' && typeof value == 'number') { - var valueStr = value + ' (' + getLoadFlagSymbolicString(value) + ')'; - out.writeArrowKeyValue(key, valueStr); - return; - } - - if (key == 'load_state' && typeof value == 'number') { - var valueStr = value + ' (' + getKeyWithValue(LoadState, value) + ')'; - out.writeArrowKeyValue(key, valueStr); - return; - } - - if (key == 'sdch_problem_code' && typeof value == 'number') { - var valueStr = value + ' (' + sdchProblemCodeToString(value) + ')'; - out.writeArrowKeyValue(key, valueStr); - return; - } - - // Otherwise just default to JSON formatting of the value. - out.writeArrowKeyValue(key, JSON.stringify(value)); + // For transferred bytes, display the bytes in hex and ASCII. + if (key == 'hex_encoded_bytes' && typeof value == 'string') { + out.writeArrowKey(key); + writeHexString(value, out); + return; } - /** - * Returns the set of LoadFlags that make up the integer |loadFlag|. - * For example: getLoadFlagSymbolicString( - */ - function getLoadFlagSymbolicString(loadFlag) { - return getSymbolicString( - loadFlag, LoadFlag, getKeyWithValue(LoadFlag, loadFlag)); + // Handle source_dependency entries - add link and map source type to + // string. + if (key == 'source_dependency' && typeof value == 'object') { + var link = '#events&s=' + value.id; + var valueStr = value.id + ' (' + EventSourceTypeNames[value.type] + ')'; + out.writeArrowKeyValue(key, valueStr, link); + return; } - /** - * Returns the set of CertStatusFlags that make up the integer - * |certStatusFlag| - */ - function getCertStatusFlagSymbolicString(certStatusFlag) { - return getSymbolicString(certStatusFlag, CertStatusFlag, ''); + if (key == 'net_error' && typeof value == 'number') { + var valueStr = value + ' (' + netErrorToString(value) + ')'; + out.writeArrowKeyValue(key, valueStr); + return; } - /** - * Returns a string representing the flags composing the given bitmask. - */ - function getSymbolicString(bitmask, valueToName, zeroName) { - var matchingFlagNames = []; - - for (var k in valueToName) { - if (bitmask & valueToName[k]) - matchingFlagNames.push(k); - } - - // If no flags were matched, returns a special value. - if (matchingFlagNames.length == 0) - return zeroName; - - return matchingFlagNames.join(' | '); + if (key == 'quic_error' && typeof value == 'number') { + var valueStr = value + ' (' + quicErrorToString(value) + ')'; + out.writeArrowKeyValue(key, valueStr); + return; } - /** - * TODO(eroman): get rid of this, as it is only used by 1 callsite. - * - * Indent |lines| by |start|. - * - * For example, if |start| = ' -> ' and |lines| = ['line1', 'line2', 'line3'] - * the output will be: - * - * " -> line1\n" + - * " line2\n" + - * " line3" - */ - function indentLines(start, lines) { - return start + lines.join('\n' + makeRepeatedString(' ', start.length)); + if (key == 'quic_crypto_handshake_message' && typeof value == 'string') { + var lines = value.split('\n'); + out.writeArrowIndentedLines(lines); + return; } - /** - * If entry.param.headers exists and is an object other than an array, - * converts - * it into an array and returns a new entry. Otherwise, just returns the - * original entry. - */ - function reformatHeaders(entry) { - // If there are no headers, or it is not an object other than an array, - // return |entry| without modification. - if (!entry.params || entry.params.headers === undefined || - typeof entry.params.headers != 'object' || - entry.params.headers instanceof Array) { - return entry; - } + if (key == 'quic_rst_stream_error' && typeof value == 'number') { + var valueStr = value + ' (' + quicRstStreamErrorToString(value) + ')'; + out.writeArrowKeyValue(key, valueStr); + return; + } - // Duplicate the top level object, and |entry.params|, so the original - // object - // will not be modified. - entry = shallowCloneObject(entry); - entry.params = shallowCloneObject(entry.params); + if (key == 'load_flags' && typeof value == 'number') { + var valueStr = value + ' (' + getLoadFlagSymbolicString(value) + ')'; + out.writeArrowKeyValue(key, valueStr); + return; + } - // Convert headers to an array. - var headers = []; - for (var key in entry.params.headers) - headers.push(key + ': ' + entry.params.headers[key]); - entry.params.headers = headers; + if (key == 'load_state' && typeof value == 'number') { + var valueStr = value + ' (' + getKeyWithValue(LoadState, value) + ')'; + out.writeArrowKeyValue(key, valueStr); + return; + } + if (key == 'sdch_problem_code' && typeof value == 'number') { + var valueStr = value + ' (' + sdchProblemCodeToString(value) + ')'; + out.writeArrowKeyValue(key, valueStr); + return; + } + + // Otherwise just default to JSON formatting of the value. + out.writeArrowKeyValue(key, JSON.stringify(value)); +} + +/** + * Returns the set of LoadFlags that make up the integer |loadFlag|. + * For example: getLoadFlagSymbolicString( + */ +function getLoadFlagSymbolicString(loadFlag) { + return getSymbolicString( + loadFlag, LoadFlag, getKeyWithValue(LoadFlag, loadFlag)); +} + +/** + * Returns the set of CertStatusFlags that make up the integer + * |certStatusFlag| + */ +function getCertStatusFlagSymbolicString(certStatusFlag) { + return getSymbolicString(certStatusFlag, CertStatusFlag, ''); +} + +/** + * Returns a string representing the flags composing the given bitmask. + */ +function getSymbolicString(bitmask, valueToName, zeroName) { + var matchingFlagNames = []; + + for (var k in valueToName) { + if (bitmask & valueToName[k]) + matchingFlagNames.push(k); + } + + // If no flags were matched, returns a special value. + if (matchingFlagNames.length == 0) + return zeroName; + + return matchingFlagNames.join(' | '); +} + +/** + * TODO(eroman): get rid of this, as it is only used by 1 callsite. + * + * Indent |lines| by |start|. + * + * For example, if |start| = ' -> ' and |lines| = ['line1', 'line2', 'line3'] + * the output will be: + * + * " -> line1\n" + + * " line2\n" + + * " line3" + */ +function indentLines(start, lines) { + return start + lines.join('\n' + makeRepeatedString(' ', start.length)); +} + +/** + * If entry.param.headers exists and is an object other than an array, + * converts + * it into an array and returns a new entry. Otherwise, just returns the + * original entry. + */ +function reformatHeaders(entry) { + // If there are no headers, or it is not an object other than an array, + // return |entry| without modification. + if (!entry.params || entry.params.headers === undefined || + typeof entry.params.headers != 'object' || + entry.params.headers instanceof Array) { return entry; } - /** - * Removes a cookie or unencrypted login information from a single HTTP header - * line, if present, and returns the modified line. Otherwise, just returns - * the original line. - * - * Note: this logic should be kept in sync with - * net::ElideHeaderValueForNetLog in net/http/http_log_util.cc. - */ - function stripCookieOrLoginInfo(line) { - var patterns = [ - // Cookie patterns - /^set-cookie: /i, /^set-cookie2: /i, /^cookie: /i, + // Duplicate the top level object, and |entry.params|, so the original + // object + // will not be modified. + entry = shallowCloneObject(entry); + entry.params = shallowCloneObject(entry.params); - // Unencrypted authentication patterns - /^authorization: \S*\s*/i, /^proxy-authorization: \S*\s*/i - ]; + // Convert headers to an array. + var headers = []; + for (var key in entry.params.headers) + headers.push(key + ': ' + entry.params.headers[key]); + entry.params.headers = headers; - // Prefix will hold the first part of the string that contains no private - // information. If null, no part of the string contains private - // information. - var prefix = null; - for (var i = 0; i < patterns.length; i++) { - var match = patterns[i].exec(line); - if (match != null) { - prefix = match[0]; - break; - } + return entry; +} + +/** + * Removes a cookie or unencrypted login information from a single HTTP header + * line, if present, and returns the modified line. Otherwise, just returns + * the original line. + * + * Note: this logic should be kept in sync with + * net::ElideHeaderValueForNetLog in net/http/http_log_util.cc. + */ +function stripCookieOrLoginInfo(line) { + var patterns = [ + // Cookie patterns + /^set-cookie: /i, /^set-cookie2: /i, /^cookie: /i, + + // Unencrypted authentication patterns + /^authorization: \S*\s*/i, /^proxy-authorization: \S*\s*/i + ]; + + // Prefix will hold the first part of the string that contains no private + // information. If null, no part of the string contains private + // information. + var prefix = null; + for (var i = 0; i < patterns.length; i++) { + var match = patterns[i].exec(line); + if (match != null) { + prefix = match[0]; + break; } - - // Look for authentication information from data received from the server in - // multi-round Negotiate authentication. - if (prefix === null) { - var challengePatterns = - [/^www-authenticate: (\S*)\s*/i, /^proxy-authenticate: (\S*)\s*/i]; - for (var i = 0; i < challengePatterns.length; i++) { - var match = challengePatterns[i].exec(line); - if (!match) - continue; - - // If there's no data after the scheme name, do nothing. - if (match[0].length == line.length) - break; - - // Ignore lines with commas, as they may contain lists of schemes, and - // the information we want to hide is Base64 encoded, so has no commas. - if (line.indexOf(',') >= 0) - break; - - // Ignore Basic and Digest authentication challenges, as they contain - // public information. - if (/^basic$/i.test(match[1]) || /^digest$/i.test(match[1])) - break; - - prefix = match[0]; - break; - } - } - - if (prefix) { - var suffix = line.slice(prefix.length); - // If private information has already been removed, keep the line as-is. - // This is often the case when viewing a loaded log. - if (suffix.search(/^\[[0-9]+ bytes were stripped\]$/) == -1) { - return prefix + '[' + suffix.length + ' bytes were stripped]'; - } - } - - return line; } - /** - * Remove debug data from HTTP/2 GOAWAY frame due to privacy considerations, - * see - * https://httpwg.github.io/specs/rfc7540.html#GOAWAY. - * - * Note: this logic should be kept in sync with - * net::ElideGoAwayDebugDataForNetLog in net/http/http_log_util.cc. - */ - function stripGoAwayDebugData(value) { - return '[' + value.length + ' bytes were stripped]'; + // Look for authentication information from data received from the server in + // multi-round Negotiate authentication. + if (prefix === null) { + var challengePatterns = + [/^www-authenticate: (\S*)\s*/i, /^proxy-authenticate: (\S*)\s*/i]; + for (var i = 0; i < challengePatterns.length; i++) { + var match = challengePatterns[i].exec(line); + if (!match) + continue; + + // If there's no data after the scheme name, do nothing. + if (match[0].length == line.length) + break; + + // Ignore lines with commas, as they may contain lists of schemes, and + // the information we want to hide is Base64 encoded, so has no commas. + if (line.indexOf(',') >= 0) + break; + + // Ignore Basic and Digest authentication challenges, as they contain + // public information. + if (/^basic$/i.test(match[1]) || /^digest$/i.test(match[1])) + break; + + prefix = match[0]; + break; + } } - /** - * If |entry| has headers, returns a copy of |entry| with all cookie and - * unencrypted login text removed. Otherwise, returns original |entry| - * object. - * This is needed so that JSON log dumps can be made without affecting the - * source data. Converts headers stored in objects to arrays. - */ - stripPrivacyInfo = function(entry) { - if (!entry.params) { - return entry; + if (prefix) { + var suffix = line.slice(prefix.length); + // If private information has already been removed, keep the line as-is. + // This is often the case when viewing a loaded log. + if (suffix.search(/^\[[0-9]+ bytes were stripped\]$/) == -1) { + return prefix + '[' + suffix.length + ' bytes were stripped]'; } + } - if (entry.type == EventType.HTTP2_SESSION_GOAWAY && - entry.params.debug_data != undefined) { - // Duplicate the top level object, and |entry.params|. All other fields - // are - // just pointers to the original values, as they won't be modified, other - // than |entry.params.debug_data|. - entry = shallowCloneObject(entry); - entry.params = shallowCloneObject(entry.params); - entry.params.debug_data = stripGoAwayDebugData(entry.params.debug_data); - return entry; - } + return line; +} - if (entry.params.headers === undefined || - !(entry.params.headers instanceof Object)) { - return entry; - } +/** + * Remove debug data from HTTP/2 GOAWAY frame due to privacy considerations, + * see + * https://httpwg.github.io/specs/rfc7540.html#GOAWAY. + * + * Note: this logic should be kept in sync with + * net::ElideGoAwayDebugDataForNetLog in net/http/http_log_util.cc. + */ +function stripGoAwayDebugData(value) { + return '[' + value.length + ' bytes were stripped]'; +} - // Make sure entry's headers are in an array. - entry = reformatHeaders(entry); +/** + * If |entry| has headers, returns a copy of |entry| with all cookie and + * unencrypted login text removed. Otherwise, returns original |entry| + * object. + * This is needed so that JSON log dumps can be made without affecting the + * source data. Converts headers stored in objects to arrays. + */ +stripPrivacyInfo = function(entry) { + if (!entry.params) { + return entry; + } - // Duplicate the top level object, and |entry.params|. All other fields are + if (entry.type == EventType.HTTP2_SESSION_GOAWAY && + entry.params.debug_data != undefined) { + // Duplicate the top level object, and |entry.params|. All other fields + // are // just pointers to the original values, as they won't be modified, other - // than - // |entry.params.headers|. + // than |entry.params.debug_data|. entry = shallowCloneObject(entry); entry.params = shallowCloneObject(entry.params); - - entry.params.headers = entry.params.headers.map(stripCookieOrLoginInfo); + entry.params.debug_data = stripGoAwayDebugData(entry.params.debug_data); return entry; - }; - - /** - * Outputs the request header parameters of |entry| to |out|. - */ - function writeParamsForRequestHeaders(entry, out, consumedParams) { - var params = entry.params; - - if (!(typeof params.line == 'string') || - !(params.headers instanceof Array)) { - // Unrecognized params. - return; - } - - // Strip the trailing CRLF that params.line contains. - var lineWithoutCRLF = params.line.replace(/\r\n$/g, ''); - out.writeArrowIndentedLines([lineWithoutCRLF].concat(params.headers)); - - consumedParams.line = true; - consumedParams.headers = true; } - function writeCertificateParam( - certs_container, out, consumedParams, paramName) { - if (certs_container.certificates instanceof Array) { - var certs = - certs_container.certificates.reduce(function(previous, current) { - return previous.concat(current.split('\n')); - }, new Array()); - out.writeArrowKey(paramName); - out.writeSpaceIndentedLines(8, certs); - consumedParams[paramName] = true; - } + if (entry.params.headers === undefined || + !(entry.params.headers instanceof Object)) { + return entry; } - /** - * Outputs the certificate parameters of |entry| to |out|. - */ - function writeParamsForCertificates(entry, out, consumedParams) { - writeCertificateParam(entry.params, out, consumedParams, 'certificates'); + // Make sure entry's headers are in an array. + entry = reformatHeaders(entry); - if (typeof(entry.params.verified_cert) == 'object') - writeCertificateParam( - entry.params.verified_cert, out, consumedParams, 'verified_cert'); + // Duplicate the top level object, and |entry.params|. All other fields are + // just pointers to the original values, as they won't be modified, other + // than + // |entry.params.headers|. + entry = shallowCloneObject(entry); + entry.params = shallowCloneObject(entry.params); - if (typeof(entry.params.cert_status) == 'number') { - var valueStr = entry.params.cert_status + ' (' + - getCertStatusFlagSymbolicString(entry.params.cert_status) + ')'; - out.writeArrowKeyValue('cert_status', valueStr); - consumedParams.cert_status = true; - } + entry.params.headers = entry.params.headers.map(stripCookieOrLoginInfo); + return entry; +}; + +/** + * Outputs the request header parameters of |entry| to |out|. + */ +function writeParamsForRequestHeaders(entry, out, consumedParams) { + var params = entry.params; + + if (!(typeof params.line == 'string') || !(params.headers instanceof Array)) { + // Unrecognized params. + return; } - function writeParamsForCheckedCertificates(entry, out, consumedParams) { - if (typeof(entry.params.certificate) == 'object') - writeCertificateParam( - entry.params.certificate, out, consumedParams, 'certificate'); + // Strip the trailing CRLF that params.line contains. + var lineWithoutCRLF = params.line.replace(/\r\n$/g, ''); + out.writeArrowIndentedLines([lineWithoutCRLF].concat(params.headers)); + + consumedParams.line = true; + consumedParams.headers = true; +} + +function writeCertificateParam( + certs_container, out, consumedParams, paramName) { + if (certs_container.certificates instanceof Array) { + var certs = + certs_container.certificates.reduce(function(previous, current) { + return previous.concat(current.split('\n')); + }, new Array()); + out.writeArrowKey(paramName); + out.writeSpaceIndentedLines(8, certs); + consumedParams[paramName] = true; + } +} + +/** + * Outputs the certificate parameters of |entry| to |out|. + */ +function writeParamsForCertificates(entry, out, consumedParams) { + writeCertificateParam(entry.params, out, consumedParams, 'certificates'); + + if (typeof(entry.params.verified_cert) == 'object') + writeCertificateParam( + entry.params.verified_cert, out, consumedParams, 'verified_cert'); + + if (typeof(entry.params.cert_status) == 'number') { + var valueStr = entry.params.cert_status + ' (' + + getCertStatusFlagSymbolicString(entry.params.cert_status) + ')'; + out.writeArrowKeyValue('cert_status', valueStr); + consumedParams.cert_status = true; + } +} + +function writeParamsForCheckedCertificates(entry, out, consumedParams) { + if (typeof(entry.params.certificate) == 'object') + writeCertificateParam( + entry.params.certificate, out, consumedParams, 'certificate'); +} + +function writeParamsForProxyConfigChanged(entry, out, consumedParams) { + var params = entry.params; + + if (typeof params.new_config != 'object') { + // Unrecognized params. + return; } - function writeParamsForProxyConfigChanged(entry, out, consumedParams) { - var params = entry.params; + if (typeof params.old_config == 'object') { + var oldConfigString = proxySettingsToString(params.old_config); + // The previous configuration may not be present in the case of + // the initial proxy settings fetch. + out.writeArrowKey('old_config'); - if (typeof params.new_config != 'object') { - // Unrecognized params. - return; - } + out.writeSpaceIndentedLines(8, oldConfigString.split('\n')); - if (typeof params.old_config == 'object') { - var oldConfigString = proxySettingsToString(params.old_config); - // The previous configuration may not be present in the case of - // the initial proxy settings fetch. - out.writeArrowKey('old_config'); - - out.writeSpaceIndentedLines(8, oldConfigString.split('\n')); - - consumedParams.old_config = true; - } - - var newConfigString = proxySettingsToString(params.new_config); - out.writeArrowKey('new_config'); - out.writeSpaceIndentedLines(8, newConfigString.split('\n')); - - consumedParams.new_config = true; + consumedParams.old_config = true; } - function getTextForEvent(entry) { - var text = ''; + var newConfigString = proxySettingsToString(params.new_config); + out.writeArrowKey('new_config'); + out.writeSpaceIndentedLines(8, newConfigString.split('\n')); - if (entry.isBegin() && canCollapseBeginWithEnd(entry)) { - // Don't prefix with '+' if we are going to collapse the END event. - text = ' '; - } else if (entry.isBegin()) { - text = '+' + text; - } else if (entry.isEnd()) { - text = '-' + text; - } else { - text = ' '; - } + consumedParams.new_config = true; +} - text += EventTypeNames[entry.orig.type]; - return text; +function getTextForEvent(entry) { + var text = ''; + + if (entry.isBegin() && canCollapseBeginWithEnd(entry)) { + // Don't prefix with '+' if we are going to collapse the END event. + text = ' '; + } else if (entry.isBegin()) { + text = '+' + text; + } else if (entry.isEnd()) { + text = '-' + text; + } else { + text = ' '; } - proxySettingsToString = function(config) { - if (!config) - return ''; + text += EventTypeNames[entry.orig.type]; + return text; +} - // TODO(eroman): if |config| has unexpected properties, print it as JSON - // rather than hide them. +proxySettingsToString = function(config) { + if (!config) + return ''; - function getProxyListString(proxies) { - // Older versions of Chrome would set these values as strings, whereas - // newer - // logs use arrays. - // TODO(eroman): This behavior changed in M27. Support for older logs can - // safely be removed circa M29. - if (Array.isArray(proxies)) { - var listString = proxies.join(', '); - if (proxies.length > 1) - return '[' + listString + ']'; - return listString; - } - return proxies; + // TODO(eroman): if |config| has unexpected properties, print it as JSON + // rather than hide them. + + function getProxyListString(proxies) { + // Older versions of Chrome would set these values as strings, whereas + // newer + // logs use arrays. + // TODO(eroman): This behavior changed in M27. Support for older logs can + // safely be removed circa M29. + if (Array.isArray(proxies)) { + var listString = proxies.join(', '); + if (proxies.length > 1) + return '[' + listString + ']'; + return listString; } + return proxies; + } - // The proxy settings specify up to three major fallback choices - // (auto-detect, custom pac url, or manual settings). - // We enumerate these to a list so we can later number them. - var modes = []; + // The proxy settings specify up to three major fallback choices + // (auto-detect, custom pac url, or manual settings). + // We enumerate these to a list so we can later number them. + var modes = []; - // Output any automatic settings. - if (config.auto_detect) - modes.push(['Auto-detect']); - if (config.pac_url) - modes.push(['PAC script: ' + config.pac_url]); + // Output any automatic settings. + if (config.auto_detect) + modes.push(['Auto-detect']); + if (config.pac_url) + modes.push(['PAC script: ' + config.pac_url]); - // Output any manual settings. - if (config.single_proxy || config.proxy_per_scheme) { - var lines = []; + // Output any manual settings. + if (config.single_proxy || config.proxy_per_scheme) { + var lines = []; - if (config.single_proxy) { - lines.push('Proxy server: ' + getProxyListString(config.single_proxy)); - } else if (config.proxy_per_scheme) { - for (var urlScheme in config.proxy_per_scheme) { - if (urlScheme != 'fallback') { - lines.push( - 'Proxy server for ' + urlScheme.toUpperCase() + ': ' + - getProxyListString(config.proxy_per_scheme[urlScheme])); - } - } - if (config.proxy_per_scheme.fallback) { + if (config.single_proxy) { + lines.push('Proxy server: ' + getProxyListString(config.single_proxy)); + } else if (config.proxy_per_scheme) { + for (var urlScheme in config.proxy_per_scheme) { + if (urlScheme != 'fallback') { lines.push( - 'Proxy server for everything else: ' + - getProxyListString(config.proxy_per_scheme.fallback)); + 'Proxy server for ' + urlScheme.toUpperCase() + ': ' + + getProxyListString(config.proxy_per_scheme[urlScheme])); } } + if (config.proxy_per_scheme.fallback) { + lines.push( + 'Proxy server for everything else: ' + + getProxyListString(config.proxy_per_scheme.fallback)); + } + } - // Output any proxy bypass rules. - if (config.bypass_list) { - if (config.reverse_bypass) { - lines.push('Reversed bypass list: '); - } else { - lines.push('Bypass list: '); - } - - for (var i = 0; i < config.bypass_list.length; ++i) - lines.push(' ' + config.bypass_list[i]); + // Output any proxy bypass rules. + if (config.bypass_list) { + if (config.reverse_bypass) { + lines.push('Reversed bypass list: '); + } else { + lines.push('Bypass list: '); } - modes.push(lines); + for (var i = 0; i < config.bypass_list.length; ++i) + lines.push(' ' + config.bypass_list[i]); } - var result = []; - if (modes.length < 1) { - // If we didn't find any proxy settings modes, we are using DIRECT. - result.push('Use DIRECT connections.'); - } else if (modes.length == 1) { - // If there was just one mode, don't bother numbering it. - result.push(modes[0].join('\n')); - } else { - // Otherwise concatenate all of the modes into a numbered list - // (which correspond with the fallback order). - for (var i = 0; i < modes.length; ++i) - result.push(indentLines('(' + (i + 1) + ') ', modes[i])); - } + modes.push(lines); + } - if (config.source != undefined && config.source != 'UNKNOWN') - result.push('Source: ' + config.source); + var result = []; + if (modes.length < 1) { + // If we didn't find any proxy settings modes, we are using DIRECT. + result.push('Use DIRECT connections.'); + } else if (modes.length == 1) { + // If there was just one mode, don't bother numbering it. + result.push(modes[0].join('\n')); + } else { + // Otherwise concatenate all of the modes into a numbered list + // (which correspond with the fallback order). + for (var i = 0; i < modes.length; ++i) + result.push(indentLines('(' + (i + 1) + ') ', modes[i])); + } - return result.join('\n'); - }; + if (config.source != undefined && config.source != 'UNKNOWN') + result.push('Source: ' + config.source); - // End of anonymous namespace. + return result.join('\n'); +}; + +// End of anonymous namespace. })();
diff --git a/chrome/browser/resources/net_internals/main.js b/chrome/browser/resources/net_internals/main.js index dbe70a9..2ab766d6 100644 --- a/chrome/browser/resources/net_internals/main.js +++ b/chrome/browser/resources/net_internals/main.js
@@ -226,7 +226,7 @@ if (!parsed) return; - if (parsed.tabHash == "#export") { + if (parsed.tabHash == '#export') { // The #export tab was removed in M60, after having been // deprecated since M58. In case anyone *still* has URLs // bookmarked to this, inform them and redirect. @@ -237,10 +237,10 @@ // page load (confirm() is synchronous). setTimeout(() => { var navigateToNetExport = confirm( - "#export was removed\nDo you want to navigate to " + - "chrome://net-export/ instead?"); + '#export was removed\nDo you want to navigate to ' + + 'chrome://net-export/ instead?'); if (navigateToNetExport) { - window.location.href = "chrome://net-export"; + window.location.href = 'chrome://net-export'; return; } });
diff --git a/chrome/browser/resources/net_internals/modules_view.js b/chrome/browser/resources/net_internals/modules_view.js index f02a53d..48cd50a3 100644 --- a/chrome/browser/resources/net_internals/modules_view.js +++ b/chrome/browser/resources/net_internals/modules_view.js
@@ -104,8 +104,8 @@ /** * Returns protocol type of a layered service provider as a string. */ - ModulesView.getLayeredServiceProviderProtocolType = - function(serviceProvider) { + ModulesView.getLayeredServiceProviderProtocolType = function( + serviceProvider) { return tryGetValueWithKey(PROTOCOL_TYPE, serviceProvider.socket_protocol); };
diff --git a/chrome/browser/resources/network_speech_synthesis/tts_extension.js b/chrome/browser/resources/network_speech_synthesis/tts_extension.js index 38f2201..727b1fb 100644 --- a/chrome/browser/resources/network_speech_synthesis/tts_extension.js +++ b/chrome/browser/resources/network_speech_synthesis/tts_extension.js
@@ -30,8 +30,7 @@ * @const * @private */ - SPEECH_SERVER_URL_: - 'https://www.google.com/speech-api/v2/synthesize?' + + SPEECH_SERVER_URL_: 'https://www.google.com/speech-api/v2/synthesize?' + 'enc=mpeg&client=chromium', /** @@ -147,39 +146,37 @@ var voiceName = this.LANG_AND_GENDER_TO_VOICE_NAME_[key]; var url = this.SPEECH_SERVER_URL_; - chrome.systemPrivate.getApiKey((function(key) { - url += '&key=' + key; - url += '&text=' + encodeURIComponent(utterance); - url += '&lang=' + lang.toLowerCase(); + chrome.systemPrivate.getApiKey( + (function(key) { + url += '&key=' + key; + url += '&text=' + encodeURIComponent(utterance); + url += '&lang=' + lang.toLowerCase(); - if (voiceName) - url += '&name=' + voiceName; + if (voiceName) + url += '&name=' + voiceName; - if (options.rate) { - // Input rate is between 0.1 and 10.0 with a default of 1.0. - // Output speed is between 0.0 and 1.0 with a default of 0.5. - url += '&speed=' + (options.rate / 2.0); - } + if (options.rate) { + // Input rate is between 0.1 and 10.0 with a default of 1.0. + // Output speed is between 0.0 and 1.0 with a default of 0.5. + url += '&speed=' + (options.rate / 2.0); + } - if (options.pitch) { - // Input pitch is between 0.0 and 2.0 with a default of 1.0. - // Output pitch is between 0.0 and 1.0 with a default of 0.5. - url += '&pitch=' + (options.pitch / 2.0); - } + if (options.pitch) { + // Input pitch is between 0.0 and 2.0 with a default of 1.0. + // Output pitch is between 0.0 and 1.0 with a default of 0.5. + url += '&pitch=' + (options.pitch / 2.0); + } - // This begins loading the audio but does not play it. - // When enough of the audio has loaded to begin playback, - // the 'canplaythrough' handler will call this.onStart_, - // which sends a start event to the ttsEngine callback and - // then begins playing audio. - this.audioElement_.src = url; - }).bind(this)); + // This begins loading the audio but does not play it. + // When enough of the audio has loaded to begin playback, + // the 'canplaythrough' handler will call this.onStart_, + // which sends a start event to the ttsEngine callback and + // then begins playing audio. + this.audioElement_.src = url; + }).bind(this)); } catch (err) { console.error(String(err)); - callback({ - 'type': 'error', - 'errorMessage': String(err) - }); + callback({'type': 'error', 'errorMessage': String(err)}); this.currentUtterance_ = null; } }, @@ -220,10 +217,7 @@ this.audioElement_.volume = this.currentUtterance_.options.volume; } this.audioElement_.play(); - this.currentUtterance_.callback({ - 'type': 'start', - 'charIndex': 0 - }); + this.currentUtterance_.callback({'type': 'start', 'charIndex': 0}); } },
diff --git a/chrome/browser/resources/ntp4/apps_page.js b/chrome/browser/resources/ntp4/apps_page.js index 270dfec..b7679ce9 100644 --- a/chrome/browser/resources/ntp4/apps_page.js +++ b/chrome/browser/resources/ntp4/apps_page.js
@@ -21,7 +21,7 @@ SAME_APPS_PANE: 0, OTHER_APPS_PANE: 1, MOST_VISITED_PANE: 2, // Deprecated. - BOOKMARKS_PANE: 3, // Deprecated. + BOOKMARKS_PANE: 3, // Deprecated. OUTSIDE_NTP: 4 }; var DRAG_SOURCE_LIMIT = DRAG_SOURCE.OUTSIDE_NTP + 1; @@ -56,8 +56,8 @@ var self = this; this.forAllLaunchTypes_(function(launchTypeButton, id) { - launchTypeButton.addEventListener('activate', - self.onLaunchTypeChanged_.bind(self)); + launchTypeButton.addEventListener( + 'activate', self.onLaunchTypeChanged_.bind(self)); }); this.launchTypeMenuSeparator_ = cr.ui.MenuItem.createSeparator(); @@ -67,18 +67,18 @@ if (loadTimeData.getBoolean('canShowAppInfoDialog')) { this.appinfo_ = this.appendMenuItem_('appinfodialog'); - this.appinfo_.addEventListener('activate', - this.onShowAppInfo_.bind(this)); + this.appinfo_.addEventListener( + 'activate', this.onShowAppInfo_.bind(this)); } else { this.details_ = this.appendMenuItem_('appdetails'); - this.details_.addEventListener('activate', - this.onShowDetails_.bind(this)); + this.details_.addEventListener( + 'activate', this.onShowDetails_.bind(this)); } - this.options_.addEventListener('activate', - this.onShowOptions_.bind(this)); - this.uninstall_.addEventListener('activate', - this.onUninstall_.bind(this)); + this.options_.addEventListener( + 'activate', this.onShowOptions_.bind(this)); + this.uninstall_.addEventListener( + 'activate', this.onUninstall_.bind(this)); if (!cr.isChromeOS) { this.createShortcutSeparator_ = @@ -115,10 +115,10 @@ */ forAllLaunchTypes_: function(f) { // Order matters: index matches launchType id. - var launchTypes = [this.launchPinnedTab_, - this.launchRegularTab_, - this.launchFullscreen_, - this.launchNewWindow_]; + var launchTypes = [ + this.launchPinnedTab_, this.launchRegularTab_, this.launchFullscreen_, + this.launchNewWindow_ + ]; for (var i = 0; i < launchTypes.length; ++i) { if (!launchTypes[i]) @@ -152,7 +152,8 @@ launchTypeButton == launchTypeWindow) || (loadTimeData.getBoolean('enableNewBookmarkApps') && launchTypeButton != launchTypeWindow); - if (!launchTypeButton.hidden) hasLaunchType = true; + if (!launchTypeButton.hidden) + hasLaunchType = true; }); this.launchTypeMenuSeparator_.hidden = @@ -189,7 +190,8 @@ // open as window and open as tab. if (loadTimeData.getBoolean('enableNewBookmarkApps')) { targetLaunchType = this.launchNewWindow_.checked ? - this.launchRegularTab_ : this.launchNewWindow_; + this.launchRegularTab_ : + this.launchNewWindow_; } this.forAllLaunchTypes_(function(launchTypeButton, id) { if (launchTypeButton == targetLaunchType) { @@ -262,8 +264,8 @@ this.appContents_.id = ''; this.appendChild(this.appContents_); - this.appImgContainer_ = /** @type {HTMLElement} */( - this.querySelector('.app-img-container')); + this.appImgContainer_ = + /** @type {HTMLElement} */ (this.querySelector('.app-img-container')); this.appImg_ = this.appImgContainer_.querySelector('img'); this.setIcon(); @@ -272,7 +274,7 @@ // The app's full name is shown in the tooltip, whereas the short name // is used for the label. - var appSpan = /** @type {HTMLElement} */( + var appSpan = /** @type {HTMLElement} */ ( this.appContents_.querySelector('.title')); appSpan.textContent = this.appData_.title; appSpan.title = this.appData_.full_name; @@ -289,8 +291,8 @@ }); if (!this.appData_.kioskMode) { - this.appContents_.addEventListener('contextmenu', - cr.ui.contextMenuHandler); + this.appContents_.addEventListener( + 'contextmenu', cr.ui.contextMenuHandler); } this.addEventListener('mousedown', this.onMousedown_, true); @@ -373,12 +375,13 @@ * @private */ onClick_: function(e) { - if (/** @type {MouseEvent} */(e).button > 1) + if (/** @type {MouseEvent} */ (e).button > 1) return; - chrome.send('launchApp', - [this.appId, APP_LAUNCH.NTP_APPS_MAXIMIZED, 'chrome-ntp-icon', - e.button, e.altKey, e.ctrlKey, e.metaKey, e.shiftKey]); + chrome.send('launchApp', [ + this.appId, APP_LAUNCH.NTP_APPS_MAXIMIZED, 'chrome-ntp-icon', e.button, + e.altKey, e.ctrlKey, e.metaKey, e.shiftKey + ]); // Don't allow the click to trigger a link or anything e.preventDefault(); @@ -391,9 +394,10 @@ */ onKeydown_: function(e) { if (e.key == 'Enter') { - chrome.send('launchApp', - [this.appId, APP_LAUNCH.NTP_APPS_MAXIMIZED, '', - 0, e.altKey, e.ctrlKey, e.metaKey, e.shiftKey]); + chrome.send('launchApp', [ + this.appId, APP_LAUNCH.NTP_APPS_MAXIMIZED, '', 0, e.altKey, e.ctrlKey, + e.metaKey, e.shiftKey + ]); e.preventDefault(); e.stopPropagation(); } @@ -429,8 +433,8 @@ e.preventDefault(); if (e.button == 2 || - !findAncestorByClass(/** @type {Element} */(e.target), - 'launch-click-target')) { + !findAncestorByClass( + /** @type {Element} */ (e.target), 'launch-click-target')) { this.appContents_.classList.add('suppress-active'); } else { this.appContents_.classList.remove('suppress-active'); @@ -455,11 +459,17 @@ * The data and preferences for this app. * @type {Object} */ - set appData(data) { this.appData_ = data; }, - get appData() { return this.appData_; }, + set appData(data) { + this.appData_ = data; + }, + get appData() { + return this.appData_; + }, /** @type {string} */ - get appId() { return this.appData_.id; }, + get appId() { + return this.appData_.id; + }, /** * Returns a pointer to the context menu for this app. All apps share the @@ -478,7 +488,9 @@ * the user can drag it onto the trash and expect something to happen). * @return {boolean} True if the app can be uninstalled. */ - canBeRemoved: function() { return this.appData_.mayDisable; }, + canBeRemoved: function() { + return this.appData_.mayDisable; + }, /** * Uninstalls the app after it's been dropped on the trash. @@ -630,8 +642,8 @@ return true; if (!e.dataTransfer || !e.dataTransfer.types) return false; - return Array.prototype.indexOf.call(e.dataTransfer.types, - 'text/uri-list') != -1; + return Array.prototype.indexOf.call( + e.dataTransfer.types, 'text/uri-list') != -1; }, /** @override */ @@ -645,8 +657,8 @@ var samePageDrag = originalPage == this; sourceId = samePageDrag ? DRAG_SOURCE.SAME_APPS_PANE : DRAG_SOURCE.OTHER_APPS_PANE; - this.tileGrid_.insertBefore(currentlyDraggingTile, - this.tileElements_[index]); + this.tileGrid_.insertBefore( + currentlyDraggingTile, this.tileElements_[index]); this.tileMoved(currentlyDraggingTile); if (!samePageDrag) { originalPage.fireRemovedEvent(currentlyDraggingTile, index, true); @@ -659,7 +671,8 @@ } assert(sourceId != -1); - chrome.send('metricsHandler:recordInHistogram', + chrome.send( + 'metricsHandler:recordInHistogram', ['NewTabPage.AppsPageDragSource', sourceId, DRAG_SOURCE_LIMIT]); },
diff --git a/chrome/browser/resources/ntp4/dot_list.js b/chrome/browser/resources/ntp4/dot_list.js index 779dcda..df9c0d3 100644 --- a/chrome/browser/resources/ntp4/dot_list.js +++ b/chrome/browser/resources/ntp4/dot_list.js
@@ -73,7 +73,5 @@ } }; - return { - DotList: DotList - }; + return {DotList: DotList}; });
diff --git a/chrome/browser/resources/ntp4/md_incognito_tab.js b/chrome/browser/resources/ntp4/md_incognito_tab.js index 4a367030..4b246225 100644 --- a/chrome/browser/resources/ntp4/md_incognito_tab.js +++ b/chrome/browser/resources/ntp4/md_incognito_tab.js
@@ -13,7 +13,7 @@ var fontSize = window.getComputedStyle(document.body).fontSize; var maxWidth = localStorage[fontSize] || (bulletpoints[0].offsetWidth + bulletpoints[1].offsetWidth + - 40 /* margin */ + 2 /* offsetWidths may be rounded down */); + 40 /* margin */ + 2 /* offsetWidths may be rounded down */); // Save the data for quicker access when the NTP is reloaded. Note that since // we're in the Incognito mode, the local storage is ephemeral and the data @@ -29,7 +29,7 @@ if (tooWide) maxWidth = MAX_ALLOWED_WIDTH; - content.style.maxWidth = maxWidth + "px"; + content.style.maxWidth = maxWidth + 'px'; } window.addEventListener('load', recomputeLayoutWidth); @@ -44,8 +44,8 @@ /** @param {!{hasCustomBackground: boolean}} themeData */ themeChanged: function(themeData) { - document.documentElement.setAttribute('hascustombackground', - themeData.hasCustomBackground); + document.documentElement.setAttribute( + 'hascustombackground', themeData.hasCustomBackground); $('incognitothemecss').href = 'chrome://theme/css/incognito_new_tab_theme.css?' + Date.now(); },
diff --git a/chrome/browser/resources/ntp4/nav_dot.js b/chrome/browser/resources/ntp4/nav_dot.js index 9c7e853..86b47e5 100644 --- a/chrome/browser/resources/ntp4/nav_dot.js +++ b/chrome/browser/resources/ntp4/nav_dot.js
@@ -60,8 +60,8 @@ this.addEventListener('transitionend', this.onTransitionEnd_); this.input_.addEventListener('blur', this.onInputBlur_.bind(this)); - this.input_.addEventListener('mousedown', - this.onInputMouseDown_.bind(this)); + this.input_.addEventListener( + 'mousedown', this.onInputMouseDown_.bind(this)); this.input_.addEventListener('keydown', this.onInputKeyDown_.bind(this)); if (animate) {
diff --git a/chrome/browser/resources/ntp4/new_tab.js b/chrome/browser/resources/ntp4/new_tab.js index 708f256..8fdb477f1 100644 --- a/chrome/browser/resources/ntp4/new_tab.js +++ b/chrome/browser/resources/ntp4/new_tab.js
@@ -58,16 +58,15 @@ var pageSwitcherStart; var pageSwitcherEnd; if (loadTimeData.getValue('showApps')) { - pageSwitcherStart = /** @type {!ntp.PageSwitcher} */( + pageSwitcherStart = /** @type {!ntp.PageSwitcher} */ ( getRequiredElement('page-switcher-start')); - pageSwitcherEnd = /** @type {!ntp.PageSwitcher} */( + pageSwitcherEnd = /** @type {!ntp.PageSwitcher} */ ( getRequiredElement('page-switcher-end')); } - this.initialize(getRequiredElement('page-list'), - getRequiredElement('dot-list'), - getRequiredElement('card-slider-frame'), - getRequiredElement('trash'), - pageSwitcherStart, pageSwitcherEnd); + this.initialize( + getRequiredElement('page-list'), getRequiredElement('dot-list'), + getRequiredElement('card-slider-frame'), getRequiredElement('trash'), + pageSwitcherStart, pageSwitcherEnd); } // TODO(dbeam): NewTabView is now the only extender of PageListView; these @@ -82,10 +81,13 @@ if (loadTimeData.getBoolean('showApps')) { sectionsToWaitFor++; if (loadTimeData.getBoolean('showAppLauncherPromo')) { - $('app-launcher-promo-close-button').addEventListener('click', - function() { chrome.send('stopShowingAppLauncherPromo'); }); - $('apps-promo-learn-more').addEventListener('click', - function() { chrome.send('onLearnMore'); }); + $('app-launcher-promo-close-button') + .addEventListener('click', function() { + chrome.send('stopShowingAppLauncherPromo'); + }); + $('apps-promo-learn-more').addEventListener('click', function() { + chrome.send('onLearnMore'); + }); } } measureNavDots(); @@ -101,10 +103,10 @@ var webStoreLink = loadTimeData.getString('webStoreLink'); var url = appendParam(webStoreLink, 'utm_source', 'chrome-ntp-launcher'); $('chrome-web-store-link').href = url; - $('chrome-web-store-link').addEventListener('auxclick', - onChromeWebStoreButtonClick); - $('chrome-web-store-link').addEventListener('click', - onChromeWebStoreButtonClick); + $('chrome-web-store-link') + .addEventListener('auxclick', onChromeWebStoreButtonClick); + $('chrome-web-store-link') + .addEventListener('click', onChromeWebStoreButtonClick); } // We need to wait for all the footer menu setup to be completed before @@ -158,10 +160,10 @@ */ function onChromeWebStoreButtonClick(e) { if (e.button > 1) - return; // Ignore buttons other than left and middle. - chrome.send('recordAppLaunchByURL', - [encodeURIComponent(this.href), - ntp.APP_LAUNCH.NTP_WEBSTORE_FOOTER]); + return; // Ignore buttons other than left and middle. + chrome.send( + 'recordAppLaunchByURL', + [encodeURIComponent(this.href), ntp.APP_LAUNCH.NTP_WEBSTORE_FOOTER]); } /** @@ -302,8 +304,8 @@ */ function showSyncLoginUI(e) { var rect = e.currentTarget.getBoundingClientRect(); - chrome.send('showSyncLoginUI', - [rect.left, rect.top, rect.width, rect.height]); + chrome.send( + 'showSyncLoginUI', [rect.left, rect.top, rect.width, rect.height]); } /**
diff --git a/chrome/browser/resources/ntp4/page_list_view.js b/chrome/browser/resources/ntp4/page_list_view.js index 64a0a73a9..ceb69d5 100644 --- a/chrome/browser/resources/ntp4/page_list_view.js +++ b/chrome/browser/resources/ntp4/page_list_view.js
@@ -49,8 +49,7 @@ * @constructor * @extends {Object} */ - function PageListView() { - } + function PageListView() {} PageListView.prototype = { /** @@ -138,8 +137,9 @@ * @param {!ntp.PageSwitcher|undefined} opt_pageSwitcherEnd Optional end * page switcher button. */ - initialize: function(pageList, dotList, cardSliderFrame, opt_trash, - opt_pageSwitcherStart, opt_pageSwitcherEnd) { + initialize: function( + pageList, dotList, cardSliderFrame, opt_trash, opt_pageSwitcherStart, + opt_pageSwitcherEnd) { this.pageList = pageList; this.dotList = dotList; @@ -174,8 +174,8 @@ // Initialize the cardSlider without any cards at the moment. this.sliderFrame = cardSliderFrame; - this.cardSlider = new cr.ui.CardSlider(this.sliderFrame, this.pageList, - this.sliderFrame.offsetWidth); + this.cardSlider = new cr.ui.CardSlider( + this.sliderFrame, this.pageList, this.sliderFrame.offsetWidth); // Prevent touch events from triggering any sort of native scrolling if // there are multiple cards in the slider frame. @@ -192,7 +192,7 @@ // because it needs to be called before the card slider's handler. cardSliderFrame.addEventListener('mousewheel', function(e) { if (cardSlider.currentCardValue.handleMouseWheel(e)) { - e.preventDefault(); // Prevent default scroll behavior. + e.preventDefault(); // Prevent default scroll behavior. e.stopImmediatePropagation(); // Prevent horizontal card flipping. } }); @@ -201,21 +201,21 @@ loadTimeData.getBoolean('isSwipeTrackingFromScrollEventsEnabled')); // Handle events from the card slider. - this.pageList.addEventListener('cardSlider:card_changed', - this.onCardChanged_.bind(this)); - this.pageList.addEventListener('cardSlider:card_added', - this.onCardAdded_.bind(this)); - this.pageList.addEventListener('cardSlider:card_removed', - this.onCardRemoved_.bind(this)); + this.pageList.addEventListener( + 'cardSlider:card_changed', this.onCardChanged_.bind(this)); + this.pageList.addEventListener( + 'cardSlider:card_added', this.onCardAdded_.bind(this)); + this.pageList.addEventListener( + 'cardSlider:card_removed', this.onCardRemoved_.bind(this)); // Ensure the slider is resized appropriately with the window. window.addEventListener('resize', this.onWindowResize_.bind(this)); // Update apps when online state changes. - window.addEventListener('online', - this.updateOfflineEnabledApps_.bind(this)); - window.addEventListener('offline', - this.updateOfflineEnabledApps_.bind(this)); + window.addEventListener( + 'online', this.updateOfflineEnabledApps_.bind(this)); + window.addEventListener( + 'offline', this.updateOfflineEnabledApps_.bind(this)); }, /** @@ -238,13 +238,13 @@ } // If we're appending an AppsPage and it's a temporary page, animate it. - var animate = page instanceof ntp.AppsPage && - page.classList.contains('temporary'); + var animate = + page instanceof ntp.AppsPage && page.classList.contains('temporary'); // Make a deep copy of the dot template to add a new one. var newDot = new ntp.NavDot(page, title, titleIsEditable, animate); page.navigationDot = newDot; - this.dotList.insertBefore(newDot, - opt_refNode ? opt_refNode.navigationDot : null); + this.dotList.insertBefore( + newDot, opt_refNode ? opt_refNode.navigationDot : null); // Set a tab index on the first dot. if (this.dotList.dots.length == 1) newDot.tabIndex = 3; @@ -260,7 +260,7 @@ appMoved: function(appData) { assert(loadTimeData.getBoolean('showApps')); - var app = /** @type {ntp.App} */($(appData.id)); + var app = /** @type {ntp.App} */ ($(appData.id)); assert(app, 'trying to move an app that doesn\'t exist'); app.remove(false); @@ -279,7 +279,7 @@ appRemoved: function(appData, isUninstall, fromPage) { assert(loadTimeData.getBoolean('showApps')); - var app = /** @type {ntp.App} */($(appData.id)); + var app = /** @type {ntp.App} */ ($(appData.id)); assert(app, 'trying to remove an app that doesn\'t exist'); if (!isUninstall) @@ -350,8 +350,9 @@ // Sort by launch ordinal apps.sort(function(a, b) { - return a.app_launch_ordinal > b.app_launch_ordinal ? 1 : - a.app_launch_ordinal < b.app_launch_ordinal ? -1 : 0; + return a.app_launch_ordinal > b.app_launch_ordinal ? + 1 : + a.app_launch_ordinal < b.app_launch_ordinal ? -1 : 0; }); // An app to animate (in case it was just installed). @@ -359,11 +360,14 @@ // If there are any pages after the apps, add new pages before them. var lastAppsPage = (this.appsPages.length > 0) ? - this.appsPages[this.appsPages.length - 1] : null; + this.appsPages[this.appsPages.length - 1] : + null; var lastAppsPageIndex = (lastAppsPage != null) ? - Array.prototype.indexOf.call(this.tilePages, lastAppsPage) : -1; + Array.prototype.indexOf.call(this.tilePages, lastAppsPage) : + -1; var nextPageAfterApps = lastAppsPageIndex != -1 ? - this.tilePages[lastAppsPageIndex + 1] : null; + this.tilePages[lastAppsPageIndex + 1] : + null; // Add the apps, creating pages as necessary for (var i = 0; i < apps.length; i++) { @@ -375,12 +379,12 @@ pageName = pageNames[this.appsPages.length]; var origPageCount = this.appsPages.length; - this.appendTilePage(new ntp.AppsPage(), pageName, true, - nextPageAfterApps); + this.appendTilePage( + new ntp.AppsPage(), pageName, true, nextPageAfterApps); // Confirm that appsPages is a live object, updated when a new page is // added (otherwise we'd have an infinite loop) - assert(this.appsPages.length == origPageCount + 1, - 'expected new page'); + assert( + this.appsPages.length == origPageCount + 1, 'expected new page'); } if (app.id == this.highlightAppId) @@ -427,9 +431,9 @@ if (pageIndex >= this.appsPages.length) { while (pageIndex >= this.appsPages.length) { - this.appendTilePage(new ntp.AppsPage(), - loadTimeData.getString('appDefaultPageName'), - true); + this.appendTilePage( + new ntp.AppsPage(), loadTimeData.getString('appDefaultPageName'), + true); } this.updateSliderCards(); } @@ -489,14 +493,13 @@ * the Slider knows about the new elements. */ updateSliderCards: function() { - var pageNo = Math.max(0, Math.min(this.cardSlider.currentCard, - this.tilePages.length - 1)); - this.cardSlider.setCards(Array.prototype.slice.call(this.tilePages), - pageNo); + var pageNo = Math.max( + 0, Math.min(this.cardSlider.currentCard, this.tilePages.length - 1)); + this.cardSlider.setCards( + Array.prototype.slice.call(this.tilePages), pageNo); if (loadTimeData.getBoolean('showApps')) { - this.cardSlider.selectCardByValue( - this.appsPages[Math.min(this.shownPageIndex, - this.appsPages.length - 1)]); + this.cardSlider.selectCardByValue(this.appsPages[Math.min( + this.shownPageIndex, this.appsPages.length - 1)]); } }, @@ -525,7 +528,7 @@ * Invoked whenever some app is released */ leaveRearrangeMode: function() { - var tempPage = /** @type {ntp.AppsPage} */( + var tempPage = /** @type {ntp.AppsPage} */ ( document.querySelector('.tile-page.temporary')); if (tempPage) { var dot = tempPage.navigationDot; @@ -534,8 +537,8 @@ this.removeTilePageAndDot_(tempPage, true); } else { tempPage.classList.remove('temporary'); - this.saveAppPageName(tempPage, - loadTimeData.getString('appDefaultPageName')); + this.saveAppPageName( + tempPage, loadTimeData.getString('appDefaultPageName')); } } @@ -568,21 +571,20 @@ var page = this.cardSlider.currentCardValue; - this.pageSwitcherStart.hidden = !page || - (this.cardSlider.currentCard == 0); + this.pageSwitcherStart.hidden = + !page || (this.cardSlider.currentCard == 0); this.pageSwitcherEnd.hidden = !page || (this.cardSlider.currentCard == this.cardSlider.cardCount - 1); if (!page) return; - var pageSwitcherLeft = isRTL() ? this.pageSwitcherEnd : - this.pageSwitcherStart; - var pageSwitcherRight = isRTL() ? this.pageSwitcherStart : - this.pageSwitcherEnd; + var pageSwitcherLeft = + isRTL() ? this.pageSwitcherEnd : this.pageSwitcherStart; + var pageSwitcherRight = + isRTL() ? this.pageSwitcherStart : this.pageSwitcherEnd; var scrollbarWidth = page.scrollbarWidth; - pageSwitcherLeft.style.width = - (page.sideMargin + 13) + 'px'; + pageSwitcherLeft.style.width = (page.sideMargin + 13) + 'px'; pageSwitcherLeft.style.left = '0'; pageSwitcherRight.style.width = (page.sideMargin - scrollbarWidth + 13) + 'px'; @@ -736,9 +738,9 @@ else return; - var cardIndex = - (this.cardSlider.currentCard + direction + - this.cardSlider.cardCount) % this.cardSlider.cardCount; + var cardIndex = (this.cardSlider.currentCard + direction + + this.cardSlider.cardCount) % + this.cardSlider.cardCount; this.cardSlider.selectCard(cardIndex, true); e.stopPropagation(); @@ -766,7 +768,5 @@ }, }; - return { - PageListView: PageListView - }; + return {PageListView: PageListView}; });
diff --git a/chrome/browser/resources/ntp4/page_switcher.js b/chrome/browser/resources/ntp4/page_switcher.js index 5babba48..f32f6edca 100644 --- a/chrome/browser/resources/ntp4/page_switcher.js +++ b/chrome/browser/resources/ntp4/page_switcher.js
@@ -13,8 +13,7 @@ * @constructor * @extends {HTMLButtonElement} */ - function PageSwitcher() { - } + function PageSwitcher() {} PageSwitcher.prototype = { __proto__: HTMLButtonElement.prototype, @@ -72,7 +71,8 @@ var currentPageTitle = currentDot.displayTitle; var nextPageTitle = nextDot.displayTitle; var msgName = (currentPageTitle == nextPageTitle) ? - 'page_switcher_same_title' : 'page_switcher_change_title'; + 'page_switcher_same_title' : + 'page_switcher_change_title'; var ariaLabel = loadTimeData.getStringF(msgName, nextPageTitle); this.setAttribute('aria-label', ariaLabel); },
diff --git a/chrome/browser/resources/ntp4/tile_page.js b/chrome/browser/resources/ntp4/tile_page.js index d1cead7c..3c48c361 100644 --- a/chrome/browser/resources/ntp4/tile_page.js +++ b/chrome/browser/resources/ntp4/tile_page.js
@@ -120,14 +120,14 @@ this.dragClone.style.right = ''; this.dragClone.classList.add('drag-representation'); $('card-slider-frame').appendChild(this.dragClone); - this.eventTracker.add(this.dragClone, 'transitionend', - this.onDragCloneTransitionEnd_.bind(this)); + this.eventTracker.add( + this.dragClone, 'transitionend', + this.onDragCloneTransitionEnd_.bind(this)); this.classList.add('dragging'); // offsetLeft is mirrored in RTL. Un-mirror it. - var offsetLeft = isRTL() ? - this.parentNode.clientWidth - this.offsetLeft : - this.offsetLeft; + var offsetLeft = isRTL() ? this.parentNode.clientWidth - this.offsetLeft : + this.offsetLeft; this.dragOffsetX = e.x - offsetLeft - this.parentNode.offsetLeft; this.dragOffsetY = e.y - this.offsetTop - // Unlike offsetTop, this value takes scroll position into account. @@ -180,17 +180,15 @@ this.dragClone.hidden = false; // The tile's contents may have moved following the respositioning; // adjust for that. - var contentDiffX = this.dragClone.firstChild.offsetLeft - - this.firstChild.offsetLeft; - var contentDiffY = this.dragClone.firstChild.offsetTop - - this.firstChild.offsetTop; + var contentDiffX = + this.dragClone.firstChild.offsetLeft - this.firstChild.offsetLeft; + var contentDiffY = + this.dragClone.firstChild.offsetTop - this.firstChild.offsetTop; this.dragClone.style.left = - toCssPx(this.gridX + this.parentNode.offsetLeft - - contentDiffX); - this.dragClone.style.top = - toCssPx(this.gridY + - this.parentNode.getBoundingClientRect().top - - contentDiffY); + toCssPx(this.gridX + this.parentNode.offsetLeft - contentDiffX); + this.dragClone.style.top = toCssPx( + this.gridY + this.parentNode.getBoundingClientRect().top - + contentDiffY); } else if (this.dragClone.hidden) { this.finalizeDrag_(); } else { @@ -238,8 +236,8 @@ if (isRTL()) x *= -1; - this.doppleganger_.style.transform = 'translate(' + x + 'px, ' + - y + 'px)'; + this.doppleganger_.style.transform = + 'translate(' + x + 'px, ' + y + 'px)'; }, /** @@ -378,25 +376,20 @@ TilePage.initGridValues = function(grid) { // The amount of space we need to display a narrow grid (all narrow grids // are this size). - grid.narrowWidth = - grid.minTileWidth * tileWidthFraction(grid.minColCount, - grid.tileSpacingFraction); + grid.narrowWidth = grid.minTileWidth * + tileWidthFraction(grid.minColCount, grid.tileSpacingFraction); // The minimum amount of space we need to display a wide grid. - grid.minWideWidth = - grid.minTileWidth * tileWidthFraction(grid.maxColCount, - grid.tileSpacingFraction); + grid.minWideWidth = grid.minTileWidth * + tileWidthFraction(grid.maxColCount, grid.tileSpacingFraction); // The largest we will ever display a wide grid. - grid.maxWideWidth = - grid.maxTileWidth * tileWidthFraction(grid.maxColCount, - grid.tileSpacingFraction); + grid.maxWideWidth = grid.maxTileWidth * + tileWidthFraction(grid.maxColCount, grid.tileSpacingFraction); // Tile-related pixel values for the narrow display. - grid.narrowTileValues = tileValuesForGrid(grid.narrowWidth, - grid.minColCount, - grid.tileSpacingFraction); + grid.narrowTileValues = tileValuesForGrid( + grid.narrowWidth, grid.minColCount, grid.tileSpacingFraction); // Tile-related pixel values for the minimum narrow display. - grid.wideTileValues = tileValuesForGrid(grid.minWideWidth, - grid.maxColCount, - grid.tileSpacingFraction); + grid.wideTileValues = tileValuesForGrid( + grid.minWideWidth, grid.maxColCount, grid.tileSpacingFraction); }; TilePage.prototype = { @@ -431,7 +424,8 @@ this.tileGrid_.className = 'tile-grid'; this.tileGrid_.style.minWidth = this.gridValues_.narrowWidth + 'px'; this.tileGrid_.setAttribute('role', 'menu'); - this.tileGrid_.setAttribute('aria-label', + this.tileGrid_.setAttribute( + 'aria-label', loadTimeData.getString( 'tile_grid_screenreader_accessible_description')); @@ -453,8 +447,8 @@ this.eventTracker = new EventTracker(); this.eventTracker.add(window, 'resize', this.onResize_.bind(this)); - this.addEventListener('DOMNodeInsertedIntoDocument', - this.onNodeInsertedIntoDocument_); + this.addEventListener( + 'DOMNodeInsertedIntoDocument', this.onNodeInsertedIntoDocument_); this.content_.addEventListener('scroll', this.onScroll_.bind(this)); @@ -522,8 +516,9 @@ // |opt_animate| argument, but that's not necesarilly applicable to // removing a tilePage. Selecting a different card in an animated way and // deleting the card afterward is probably a better choice. - assert(typeof arguments[0] != 'boolean', - 'This function takes no |opt_animate| argument.'); + assert( + typeof arguments[0] != 'boolean', + 'This function takes no |opt_animate| argument.'); this.tearDown_(); this.parentNode.removeChild(this); }, @@ -680,15 +675,14 @@ * @private */ handleMouseDown_: function(e) { - var focusable = findAncestorByClass(/** @type {Element} */(e.target), - 'focusable'); + var focusable = + findAncestorByClass(/** @type {Element} */ (e.target), 'focusable'); if (focusable) { this.focusElementIndex_ = - Array.prototype.indexOf.call(this.focusableElements_, - focusable); + Array.prototype.indexOf.call(this.focusableElements_, focusable); this.updateFocusElement_(); } - }, + }, /** * Handle arrow key focus nav. @@ -717,9 +711,8 @@ // Look through all focusable elements. Find the first one that is // in the same column. var direction = e.key == 'ArrowUp' ? -1 : 1; - var currentIndex = - Array.prototype.indexOf.call(this.focusableElements_, - this.currentFocusElement_); + var currentIndex = Array.prototype.indexOf.call( + this.focusableElements_, this.currentFocusElement_); var newFocusIdx = wrap(currentIndex + direction); var tile = this.currentFocusElement_.parentNode; for (;; newFocusIdx = wrap(newFocusIdx + direction)) { @@ -754,8 +747,8 @@ return; } - this.focusElementIndex_ = Math.min(this.focusableElements_.length - 1, - this.focusElementIndex_); + this.focusElementIndex_ = + Math.min(this.focusableElements_.length - 1, this.focusElementIndex_); this.focusElementIndex_ = Math.max(0, this.focusElementIndex_); var newFocusElement = this.focusableElements_[this.focusElementIndex_]; @@ -800,17 +793,16 @@ var numRowTiles = wide ? grid.maxColCount : grid.minColCount; var effectiveGridWidth = wide ? - Math.min(Math.max(availableSpace, grid.minWideWidth), - grid.maxWideWidth) : + Math.min( + Math.max(availableSpace, grid.minWideWidth), grid.maxWideWidth) : grid.narrowWidth; - var realTileValues = tileValuesForGrid(effectiveGridWidth, numRowTiles, - grid.tileSpacingFraction); + var realTileValues = tileValuesForGrid( + effectiveGridWidth, numRowTiles, grid.tileSpacingFraction); // leftMargin centers the grid within the avaiable space. var minMargin = wide ? MIN_WIDE_MARGIN : 0; - var leftMargin = - Math.max(minMargin, - (this.tileGrid_.clientWidth - effectiveGridWidth) / 2); + var leftMargin = Math.max( + minMargin, (this.tileGrid_.clientWidth - effectiveGridWidth) / 2); var rowHeight = this.heightForWidth(realTileValues.tileWidth) + realTileValues.interTileSpacing; @@ -873,19 +865,19 @@ var realY = row * layout.rowHeight; // Calculate the portion of the tile's position that should be animated. - var animatedTileValues = layout.wide ? - grid.wideTileValues : grid.narrowTileValues; + var animatedTileValues = + layout.wide ? grid.wideTileValues : grid.narrowTileValues; // Animate the difference between three-wide and six-wide. var animatedLeftMargin = this.getAnimatedLeftMargin_(); var animatedX = col * animatedTileValues.offsetX + animatedLeftMargin; - var animatedY = row * (this.heightForWidth(animatedTileValues.tileWidth) + - animatedTileValues.interTileSpacing); + var animatedY = row * + (this.heightForWidth(animatedTileValues.tileWidth) + + animatedTileValues.interTileSpacing); var tile = this.tileElements_[index]; tile.setGridPosition(animatedX, animatedY); - tile.firstChild.setBounds(layout.tileWidth, - realX - animatedX, - realY - animatedY); + tile.firstChild.setBounds( + layout.tileWidth, realX - animatedX, realY - animatedY); // This code calculates whether the tile needs to show a clone of itself // wrapped around the other side of the tile grid. @@ -894,8 +886,9 @@ var offTheLeft = col == -1 || (col == 0 && tile.hasDoppleganger()); if (this.isCurrentDragTarget && (offTheRight || offTheLeft)) { var sign = offTheRight ? 1 : -1; - tile.showDoppleganger(-layout.numRowTiles * layout.colWidth * sign, - layout.rowHeight * sign); + tile.showDoppleganger( + -layout.numRowTiles * layout.colWidth * sign, + layout.rowHeight * sign); } else { tile.clearDoppleganger(); } @@ -923,8 +916,8 @@ var layout = this.layoutValues_; var gridClientRect = this.tileGrid_.getBoundingClientRect(); - var col = Math.floor((x - gridClientRect.left - layout.leftMargin) / - layout.colWidth); + var col = Math.floor( + (x - gridClientRect.left - layout.leftMargin) / layout.colWidth); if (col < 0 || col >= layout.numRowTiles) return -1; @@ -969,22 +962,21 @@ var leftMargin = this.layoutValues_.leftMargin; // The fade distance is the space between tiles. - var fadeDistance = (this.gridValues_.tileSpacingFraction * - this.layoutValues_.tileWidth); + var fadeDistance = + (this.gridValues_.tileSpacingFraction * this.layoutValues_.tileWidth); fadeDistance = Math.min(leftMargin, fadeDistance); // On Skia we don't use any fade because it works very poorly. See // http://crbug.com/99373 if (!cr.isMac) fadeDistance = 1; - var gradient = - '-webkit-linear-gradient(left,' + - 'transparent, ' + - 'transparent ' + (leftMargin - fadeDistance) + 'px, ' + - 'black ' + leftMargin + 'px, ' + - 'black ' + (this.tileGrid_.clientWidth - leftMargin) + 'px, ' + - 'transparent ' + (this.tileGrid_.clientWidth - leftMargin + - fadeDistance) + 'px, ' + - 'transparent)'; + var gradient = '-webkit-linear-gradient(left,' + + 'transparent, ' + + 'transparent ' + (leftMargin - fadeDistance) + 'px, ' + + 'black ' + leftMargin + 'px, ' + + 'black ' + (this.tileGrid_.clientWidth - leftMargin) + 'px, ' + + 'transparent ' + + (this.tileGrid_.clientWidth - leftMargin + fadeDistance) + 'px, ' + + 'transparent)'; this.tileGrid_.style.WebkitMaskBoxImage = gradient; }, @@ -1096,8 +1088,8 @@ if (this.scrollbarUpdate_) return; - this.scrollbarUpdate_ = window.setTimeout( - this.doUpdateScrollbars_.bind(this), 0); + this.scrollbarUpdate_ = + window.setTimeout(this.doUpdateScrollbars_.bind(this), 0); }, /** @@ -1122,8 +1114,8 @@ var thumbTop = content.offsetTop + content.scrollTop / adjustedScrollHeight * content.clientHeight; - var thumbHeight = content.clientHeight / adjustedScrollHeight * - this.clientHeight; + var thumbHeight = + content.clientHeight / adjustedScrollHeight * this.clientHeight; this.scrollbar_.style.top = thumbTop + 'px'; this.scrollbar_.style.height = thumbHeight + 'px'; @@ -1158,8 +1150,8 @@ this.classList.add('animating-tile-page'); this.withinPageDrag_ = this.contains(currentlyDraggingTile); - this.dragItemIndex_ = this.withinPageDrag_ ? - currentlyDraggingTile.index : this.tileElements_.length; + this.dragItemIndex_ = this.withinPageDrag_ ? currentlyDraggingTile.index : + this.tileElements_.length; this.currentDropIndex_ = this.dragItemIndex_; // The new tile may change the number of rows, hence the top margin @@ -1189,16 +1181,15 @@ var index = this.currentDropIndex_; // Only change data if this was not a 'null drag'. if (!((index == this.dragItemIndex_) && this.withinPageDrag_)) { - var adjustedIndex = this.currentDropIndex_ + - (index > this.dragItemIndex_ ? 1 : 0); + var adjustedIndex = + this.currentDropIndex_ + (index > this.dragItemIndex_ ? 1 : 0); if (this.withinPageDrag_) { this.tileGrid_.insertBefore( - currentlyDraggingTile, - this.tileElements_[adjustedIndex]); + currentlyDraggingTile, this.tileElements_[adjustedIndex]); this.tileMoved(currentlyDraggingTile, this.dragItemIndex_); } else { - var originalPage = currentlyDraggingTile ? - currentlyDraggingTile.tilePage : null; + var originalPage = + currentlyDraggingTile ? currentlyDraggingTile.tilePage : null; this.addDragData(e.dataTransfer, adjustedIndex); if (originalPage) originalPage.cleanupDrag(); @@ -1301,8 +1292,7 @@ * @param {Node} draggedTile The tile that was dropped. * @param {number} prevIndex The previous index of the tile. */ - tileMoved: function(draggedTile, prevIndex) { - }, + tileMoved: function(draggedTile, prevIndex) {}, /** * Sets the drop effect on |dataTransfer| to the desired value (e.g.
diff --git a/chrome/browser/resources/offline_pages/offline_internals.js b/chrome/browser/resources/offline_pages/offline_internals.js index 0f03bcf..705eb4ac 100644 --- a/chrome/browser/resources/offline_pages/offline_internals.js +++ b/chrome/browser/resources/offline_pages/offline_internals.js
@@ -178,7 +178,7 @@ browserProxy.getRequestQueue().then(fillRequestQueue); } - /** + /** * Callback for prefetch actions. * @param {string} info The result of performing the prefetch actions. */ @@ -191,14 +191,12 @@ * TODO(chili): Create a CSV writer that can abstract out the line joining. */ function download() { - var json = JSON.stringify({ - offlinePages: offlinePages, - savePageRequests: savePageRequests - }, null, 2); + var json = JSON.stringify( + {offlinePages: offlinePages, savePageRequests: savePageRequests}, null, + 2); window.open( - 'data:application/json,' + encodeURIComponent(json), - 'dump.json'); + 'data:application/json,' + encodeURIComponent(json), 'dump.json'); } /** @@ -307,21 +305,20 @@ var counter = saveUrls.length; $('save-url-state').textContent = ''; for (let i = 0; i < saveUrls.length; i++) { - browserProxy.addToRequestQueue(saveUrls[i]) - .then(function(state) { - if (state) { - $('save-url-state').textContent += - saveUrls[i] + ' has been added to queue.\n'; - $('url').value = ''; - counter--; - if (counter == 0) { - browserProxy.getRequestQueue().then(fillRequestQueue); - } - } else { - $('save-url-state').textContent += - saveUrls[i] + ' failed to be added to queue.\n'; - } - }); + browserProxy.addToRequestQueue(saveUrls[i]).then(function(state) { + if (state) { + $('save-url-state').textContent += + saveUrls[i] + ' has been added to queue.\n'; + $('url').value = ''; + counter--; + if (counter == 0) { + browserProxy.getRequestQueue().then(fillRequestQueue); + } + } else { + $('save-url-state').textContent += + saveUrls[i] + ' failed to be added to queue.\n'; + } + }); } }; $('schedule-nwake').onclick = function() { @@ -331,12 +328,12 @@ browserProxy.cancelNwake().then(setPrefetchResult); }; $('generate-page-bundle').onclick = function() { - browserProxy.generatePageBundle($('generate-urls').value). - then(setPrefetchResult); + browserProxy.generatePageBundle($('generate-urls').value) + .then(setPrefetchResult); }; $('get-operation').onclick = function() { - browserProxy.getOperation($('operation-name').value). - then(setPrefetchResult); + browserProxy.getOperation($('operation-name').value) + .then(setPrefetchResult); }; if (!incognito) refreshAll();
diff --git a/chrome/browser/resources/omnibox/omnibox.js b/chrome/browser/resources/omnibox/omnibox.js index 6e82ebf..f97d788 100644 --- a/chrome/browser/resources/omnibox/omnibox.js +++ b/chrome/browser/resources/omnibox/omnibox.js
@@ -18,426 +18,428 @@ */ (function() { - /** - * Register our event handlers. - */ - function initialize() { - $('omnibox-input-form').addEventListener( - 'submit', startOmniboxQuery, false); - $('prevent-inline-autocomplete').addEventListener( - 'change', startOmniboxQuery); - $('prefer-keyword').addEventListener('change', startOmniboxQuery); - $('page-classification').addEventListener('change', startOmniboxQuery); - $('show-details').addEventListener('change', refresh); - $('show-incomplete-results').addEventListener('change', refresh); - $('show-all-providers').addEventListener('change', refresh); - } +/** + * Register our event handlers. + */ +function initialize() { + $('omnibox-input-form').addEventListener('submit', startOmniboxQuery, false); + $('prevent-inline-autocomplete') + .addEventListener('change', startOmniboxQuery); + $('prefer-keyword').addEventListener('change', startOmniboxQuery); + $('page-classification').addEventListener('change', startOmniboxQuery); + $('show-details').addEventListener('change', refresh); + $('show-incomplete-results').addEventListener('change', refresh); + $('show-all-providers').addEventListener('change', refresh); +} - /** - * @type {OmniboxResultMojo} an array of all autocomplete results we've seen - * for this query. We append to this list once for every call to - * handleNewAutocompleteResult. See omnibox.mojom for details.. - */ - var progressiveAutocompleteResults = []; +/** + * @type {OmniboxResultMojo} an array of all autocomplete results we've seen + * for this query. We append to this list once for every call to + * handleNewAutocompleteResult. See omnibox.mojom for details.. + */ +var progressiveAutocompleteResults = []; - /** - * @type {number} the value for cursor position we sent with the most - * recent request. We need to remember this in order to display it - * in the output; otherwise it's hard or impossible to determine - * from screen captures or print-to-PDFs. - */ - var cursorPositionUsed = -1; +/** + * @type {number} the value for cursor position we sent with the most + * recent request. We need to remember this in order to display it + * in the output; otherwise it's hard or impossible to determine + * from screen captures or print-to-PDFs. + */ +var cursorPositionUsed = -1; - /** - * Extracts the input text from the text field and sends it to the - * C++ portion of chrome to handle. The C++ code will iteratively - * call handleNewAutocompleteResult as results come in. - */ - function startOmniboxQuery(event) { - // First, clear the results of past calls (if any). - progressiveAutocompleteResults = []; - // Then, call chrome with a five-element list: - // - first element: the value in the text box - // - second element: the location of the cursor in the text box - // - third element: the value of prevent-inline-autocomplete - // - forth element: the value of prefer-keyword - // - fifth element: the value of page-classification - cursorPositionUsed = $('input-text').selectionEnd; - browserProxy.startOmniboxQuery( - $('input-text').value, - cursorPositionUsed, - $('prevent-inline-autocomplete').checked, - $('prefer-keyword').checked, - parseInt($('page-classification').value)); - // Cancel the submit action. i.e., don't submit the form. (We handle - // display the results solely with Javascript.) - event.preventDefault(); - } +/** + * Extracts the input text from the text field and sends it to the + * C++ portion of chrome to handle. The C++ code will iteratively + * call handleNewAutocompleteResult as results come in. + */ +function startOmniboxQuery(event) { + // First, clear the results of past calls (if any). + progressiveAutocompleteResults = []; + // Then, call chrome with a five-element list: + // - first element: the value in the text box + // - second element: the location of the cursor in the text box + // - third element: the value of prevent-inline-autocomplete + // - forth element: the value of prefer-keyword + // - fifth element: the value of page-classification + cursorPositionUsed = $('input-text').selectionEnd; + browserProxy.startOmniboxQuery( + $('input-text').value, cursorPositionUsed, + $('prevent-inline-autocomplete').checked, $('prefer-keyword').checked, + parseInt($('page-classification').value)); + // Cancel the submit action. i.e., don't submit the form. (We handle + // display the results solely with Javascript.) + event.preventDefault(); +} - /** - * Returns a simple object with information about how to display an - * autocomplete result data field. - * @param {string} header the label for the top of the column/table. - * @param {string} urlLabelForHeader the URL that the header should point - * to (if non-empty). - * @param {string} propertyName the name of the property in the autocomplete - * result record that we lookup. - * @param {boolean} displayAlways whether the property should be displayed - * regardless of whether we're in detailed more. - * @param {string} tooltip a description of the property that will be - * presented as a tooltip when the mouse is hovered over the column title. - * @constructor - */ - function PresentationInfoRecord(header, url, propertyName, displayAlways, - tooltip) { - this.header = header; - this.urlLabelForHeader = url; - this.propertyName = propertyName; - this.displayAlways = displayAlways; - this.tooltip = tooltip; - } +/** + * Returns a simple object with information about how to display an + * autocomplete result data field. + * @param {string} header the label for the top of the column/table. + * @param {string} urlLabelForHeader the URL that the header should point + * to (if non-empty). + * @param {string} propertyName the name of the property in the autocomplete + * result record that we lookup. + * @param {boolean} displayAlways whether the property should be displayed + * regardless of whether we're in detailed more. + * @param {string} tooltip a description of the property that will be + * presented as a tooltip when the mouse is hovered over the column title. + * @constructor + */ +function PresentationInfoRecord( + header, url, propertyName, displayAlways, tooltip) { + this.header = header; + this.urlLabelForHeader = url; + this.propertyName = propertyName; + this.displayAlways = displayAlways; + this.tooltip = tooltip; +} - /** - * A constant that's used to decide what autocomplete result - * properties to output in what order. This is an array of - * PresentationInfoRecord() objects; for details see that - * function. - * @type {Array<Object>} - * @const - */ - var PROPERTY_OUTPUT_ORDER = [ - new PresentationInfoRecord('Provider', '', 'providerName', true, - 'The AutocompleteProvider suggesting this result.'), - new PresentationInfoRecord('Type', '', 'type', true, - 'The type of the result.'), - new PresentationInfoRecord('Relevance', '', 'relevance', true, - 'The result score. Higher is more relevant.'), - new PresentationInfoRecord('Contents', '', 'contents', true, - 'The text that is presented identifying the result.'), - new PresentationInfoRecord( - 'Can Be Default', '', 'allowedToBeDefaultMatch', false, - 'A green checkmark indicates that the result can be the default ' + - 'match (i.e., can be the match that pressing enter in the omnibox ' + - 'navigates to).'), - new PresentationInfoRecord('Starred', '', 'starred', false, - 'A green checkmark indicates that the result has been bookmarked.'), - new PresentationInfoRecord('Description', '', 'description', false, - 'The page title of the result.'), - new PresentationInfoRecord('URL', '', 'destinationUrl', true, - 'The URL for the result.'), - new PresentationInfoRecord('Fill Into Edit', '', 'fillIntoEdit', false, - 'The text shown in the omnibox when the result is selected.'), - new PresentationInfoRecord( - 'Inline Autocompletion', '', 'inlineAutocompletion', false, - 'The text shown in the omnibox as a blue highlight selection ' + - 'following the cursor, if this match is shown inline.'), - new PresentationInfoRecord('Del', '', 'deletable', false, - 'A green checkmark indicates that the result can be deleted from ' + - 'the visit history.'), - new PresentationInfoRecord('Prev', '', 'fromPrevious', false, ''), - new PresentationInfoRecord( - 'Tran', - 'http://code.google.com/codesearch#OAMlx_jo-ck/src/content/public/' + - 'common/page_transition_types.h&exact_package=chromium&l=24', - 'transition', false, - 'How the user got to the result.'), - new PresentationInfoRecord( - 'Done', '', 'providerDone', false, - 'A green checkmark indicates that the provider is done looking for ' + - 'more results.'), - new PresentationInfoRecord( - 'Associated Keyword', '', 'associatedKeyword', false, - 'If non-empty, a "press tab to search" hint will be shown and will ' + - 'engage this keyword.'), - new PresentationInfoRecord( - 'Keyword', '', 'keyword', false, - 'The keyword of the search engine to be used.'), - new PresentationInfoRecord( - 'Duplicates', '', 'duplicates', false, - 'The number of matches that have been marked as duplicates of this ' + - 'match.'), - new PresentationInfoRecord( - 'Additional Info', '', 'additionalInfo', false, - 'Provider-specific information about the result.') - ]; +/** + * A constant that's used to decide what autocomplete result + * properties to output in what order. This is an array of + * PresentationInfoRecord() objects; for details see that + * function. + * @type {Array<Object>} + * @const + */ +var PROPERTY_OUTPUT_ORDER = [ + new PresentationInfoRecord( + 'Provider', '', 'providerName', true, + 'The AutocompleteProvider suggesting this result.'), + new PresentationInfoRecord( + 'Type', '', 'type', true, 'The type of the result.'), + new PresentationInfoRecord( + 'Relevance', '', 'relevance', true, + 'The result score. Higher is more relevant.'), + new PresentationInfoRecord( + 'Contents', '', 'contents', true, + 'The text that is presented identifying the result.'), + new PresentationInfoRecord( + 'Can Be Default', '', 'allowedToBeDefaultMatch', false, + 'A green checkmark indicates that the result can be the default ' + + 'match (i.e., can be the match that pressing enter in the omnibox ' + + 'navigates to).'), + new PresentationInfoRecord( + 'Starred', '', 'starred', false, + 'A green checkmark indicates that the result has been bookmarked.'), + new PresentationInfoRecord( + 'Description', '', 'description', false, 'The page title of the result.'), + new PresentationInfoRecord( + 'URL', '', 'destinationUrl', true, 'The URL for the result.'), + new PresentationInfoRecord( + 'Fill Into Edit', '', 'fillIntoEdit', false, + 'The text shown in the omnibox when the result is selected.'), + new PresentationInfoRecord( + 'Inline Autocompletion', '', 'inlineAutocompletion', false, + 'The text shown in the omnibox as a blue highlight selection ' + + 'following the cursor, if this match is shown inline.'), + new PresentationInfoRecord( + 'Del', '', 'deletable', false, + 'A green checkmark indicates that the result can be deleted from ' + + 'the visit history.'), + new PresentationInfoRecord('Prev', '', 'fromPrevious', false, ''), + new PresentationInfoRecord( + 'Tran', + 'http://code.google.com/codesearch#OAMlx_jo-ck/src/content/public/' + + 'common/page_transition_types.h&exact_package=chromium&l=24', + 'transition', false, 'How the user got to the result.'), + new PresentationInfoRecord( + 'Done', '', 'providerDone', false, + 'A green checkmark indicates that the provider is done looking for ' + + 'more results.'), + new PresentationInfoRecord( + 'Associated Keyword', '', 'associatedKeyword', false, + 'If non-empty, a "press tab to search" hint will be shown and will ' + + 'engage this keyword.'), + new PresentationInfoRecord( + 'Keyword', '', 'keyword', false, + 'The keyword of the search engine to be used.'), + new PresentationInfoRecord( + 'Duplicates', '', 'duplicates', false, + 'The number of matches that have been marked as duplicates of this ' + + 'match.'), + new PresentationInfoRecord( + 'Additional Info', '', 'additionalInfo', false, + 'Provider-specific information about the result.') +]; - /** - * Returns an HTML Element of type table row that contains the - * headers we'll use for labeling the columns. If we're in - * detailedMode, we use all the headers. If not, we only use ones - * marked displayAlways. - */ - function createAutocompleteResultTableHeader() { - var row = document.createElement('tr'); - var inDetailedMode = $('show-details').checked; - for (var i = 0; i < PROPERTY_OUTPUT_ORDER.length; i++) { - if (inDetailedMode || PROPERTY_OUTPUT_ORDER[i].displayAlways) { - var headerCell = document.createElement('th'); - if (PROPERTY_OUTPUT_ORDER[i].urlLabelForHeader != '') { - // Wrap header text in URL. - var linkNode = document.createElement('a'); - linkNode.href = PROPERTY_OUTPUT_ORDER[i].urlLabelForHeader; - linkNode.textContent = PROPERTY_OUTPUT_ORDER[i].header; - headerCell.appendChild(linkNode); - } else { - // Output header text without a URL. - headerCell.textContent = PROPERTY_OUTPUT_ORDER[i].header; - headerCell.className = 'table-header'; - headerCell.title = PROPERTY_OUTPUT_ORDER[i].tooltip; - } - row.appendChild(headerCell); - } - } - return row; - } - - /** - * @param {AutocompleteMatchMojo} autocompleteSuggestion the particular - * autocomplete suggestion we're in the process of displaying. - * @param {string} propertyName the particular property of the autocomplete - * suggestion that should go in this cell. - * @return {HTMLTableCellElement} that contains the value within this - * autocompleteSuggestion associated with propertyName. - */ - function createCellForPropertyAndRemoveProperty(autocompleteSuggestion, - propertyName) { - var cell = document.createElement('td'); - if (propertyName in autocompleteSuggestion) { - if (propertyName == 'additionalInfo') { - // |additionalInfo| embeds a two-column table of provider-specific data - // within this cell. |additionalInfo| is an array of - // AutocompleteAdditionalInfo. - var additionalInfoTable = document.createElement('table'); - for (var i = 0; i < autocompleteSuggestion[propertyName].length; i++) { - var additionalInfo = autocompleteSuggestion[propertyName][i]; - var additionalInfoRow = document.createElement('tr'); - - // Set the title (name of property) cell text. - var propertyCell = document.createElement('td'); - propertyCell.textContent = additionalInfo.key + ':'; - propertyCell.className = 'additional-info-property'; - additionalInfoRow.appendChild(propertyCell); - - // Set the value of the property cell text. - var valueCell = document.createElement('td'); - valueCell.textContent = additionalInfo.value; - valueCell.className = 'additional-info-value'; - additionalInfoRow.appendChild(valueCell); - - additionalInfoTable.appendChild(additionalInfoRow); - } - cell.appendChild(additionalInfoTable); - } else if (typeof autocompleteSuggestion[propertyName] == 'boolean') { - // If this is a boolean, display a checkmark or an X instead of - // the strings true or false. - if (autocompleteSuggestion[propertyName]) { - cell.className = 'check-mark'; - cell.textContent = '✔'; - } else { - cell.className = 'x-mark'; - cell.textContent = '✗'; - } +/** + * Returns an HTML Element of type table row that contains the + * headers we'll use for labeling the columns. If we're in + * detailedMode, we use all the headers. If not, we only use ones + * marked displayAlways. + */ +function createAutocompleteResultTableHeader() { + var row = document.createElement('tr'); + var inDetailedMode = $('show-details').checked; + for (var i = 0; i < PROPERTY_OUTPUT_ORDER.length; i++) { + if (inDetailedMode || PROPERTY_OUTPUT_ORDER[i].displayAlways) { + var headerCell = document.createElement('th'); + if (PROPERTY_OUTPUT_ORDER[i].urlLabelForHeader != '') { + // Wrap header text in URL. + var linkNode = document.createElement('a'); + linkNode.href = PROPERTY_OUTPUT_ORDER[i].urlLabelForHeader; + linkNode.textContent = PROPERTY_OUTPUT_ORDER[i].header; + headerCell.appendChild(linkNode); } else { - var text = String(autocompleteSuggestion[propertyName]); - // If it's a URL wrap it in an href. - var re = /^(http|https|ftp|chrome|file):\/\//; - if (re.test(text)) { - var aCell = document.createElement('a'); - aCell.textContent = text; - aCell.href = text; - cell.appendChild(aCell); - } else { - // All other data types (integer, strings, etc.) display their - // normal toString() output. - cell.textContent = autocompleteSuggestion[propertyName]; - } + // Output header text without a URL. + headerCell.textContent = PROPERTY_OUTPUT_ORDER[i].header; + headerCell.className = 'table-header'; + headerCell.title = PROPERTY_OUTPUT_ORDER[i].tooltip; } - } // else: if propertyName is undefined, we leave the cell blank - return cell; + row.appendChild(headerCell); + } + } + return row; +} + +/** + * @param {AutocompleteMatchMojo} autocompleteSuggestion the particular + * autocomplete suggestion we're in the process of displaying. + * @param {string} propertyName the particular property of the autocomplete + * suggestion that should go in this cell. + * @return {HTMLTableCellElement} that contains the value within this + * autocompleteSuggestion associated with propertyName. + */ +function createCellForPropertyAndRemoveProperty( + autocompleteSuggestion, propertyName) { + var cell = document.createElement('td'); + if (propertyName in autocompleteSuggestion) { + if (propertyName == 'additionalInfo') { + // |additionalInfo| embeds a two-column table of provider-specific data + // within this cell. |additionalInfo| is an array of + // AutocompleteAdditionalInfo. + var additionalInfoTable = document.createElement('table'); + for (var i = 0; i < autocompleteSuggestion[propertyName].length; i++) { + var additionalInfo = autocompleteSuggestion[propertyName][i]; + var additionalInfoRow = document.createElement('tr'); + + // Set the title (name of property) cell text. + var propertyCell = document.createElement('td'); + propertyCell.textContent = additionalInfo.key + ':'; + propertyCell.className = 'additional-info-property'; + additionalInfoRow.appendChild(propertyCell); + + // Set the value of the property cell text. + var valueCell = document.createElement('td'); + valueCell.textContent = additionalInfo.value; + valueCell.className = 'additional-info-value'; + additionalInfoRow.appendChild(valueCell); + + additionalInfoTable.appendChild(additionalInfoRow); + } + cell.appendChild(additionalInfoTable); + } else if (typeof autocompleteSuggestion[propertyName] == 'boolean') { + // If this is a boolean, display a checkmark or an X instead of + // the strings true or false. + if (autocompleteSuggestion[propertyName]) { + cell.className = 'check-mark'; + cell.textContent = '✔'; + } else { + cell.className = 'x-mark'; + cell.textContent = '✗'; + } + } else { + var text = String(autocompleteSuggestion[propertyName]); + // If it's a URL wrap it in an href. + var re = /^(http|https|ftp|chrome|file):\/\//; + if (re.test(text)) { + var aCell = document.createElement('a'); + aCell.textContent = text; + aCell.href = text; + cell.appendChild(aCell); + } else { + // All other data types (integer, strings, etc.) display their + // normal toString() output. + cell.textContent = autocompleteSuggestion[propertyName]; + } + } + } // else: if propertyName is undefined, we leave the cell blank + return cell; +} + +/** + * Appends some human-readable information about the provided + * autocomplete result to the HTML node with id omnibox-debug-text. + * The current human-readable form is a few lines about general + * autocomplete result statistics followed by a table with one line + * for each autocomplete match. The input parameter is an OmniboxResultMojo. + */ +function addResultToOutput(result) { + var output = $('omnibox-debug-text'); + var inDetailedMode = $('show-details').checked; + var showIncompleteResults = $('show-incomplete-results').checked; + var showPerProviderResults = $('show-all-providers').checked; + + // Always output cursor position. + var p = document.createElement('p'); + p.textContent = 'cursor position = ' + cursorPositionUsed; + output.appendChild(p); + + // Output the result-level features in detailed mode and in + // show incomplete results mode. We do the latter because without + // these result-level features, one can't make sense of each + // batch of results. + if (inDetailedMode || showIncompleteResults) { + var p1 = document.createElement('p'); + p1.textContent = + 'elapsed time = ' + result.timeSinceOmniboxStartedMs + 'ms'; + output.appendChild(p1); + var p2 = document.createElement('p'); + p2.textContent = 'all providers done = ' + result.done; + output.appendChild(p2); + var p3 = document.createElement('p'); + p3.textContent = 'host = ' + result.host; + if ('isTypedHost' in result) { + // Only output the isTypedHost information if available. (It may + // be missing if the history database lookup failed.) + p3.textContent = + p3.textContent + ' has isTypedHost = ' + result.isTypedHost; + } + output.appendChild(p3); } - /** - * Appends some human-readable information about the provided - * autocomplete result to the HTML node with id omnibox-debug-text. - * The current human-readable form is a few lines about general - * autocomplete result statistics followed by a table with one line - * for each autocomplete match. The input parameter is an OmniboxResultMojo. - */ - function addResultToOutput(result) { - var output = $('omnibox-debug-text'); - var inDetailedMode = $('show-details').checked; + // Combined results go after the lines below. + var group = document.createElement('a'); + group.className = 'group-separator'; + group.textContent = 'Combined results.'; + output.appendChild(group); + + // Add combined/merged result table. + var p = document.createElement('p'); + p.appendChild(addResultTableToOutput(result.combinedResults)); + output.appendChild(p); + + // Move forward only if you want to display per provider results. + if (!showPerProviderResults) { + return; + } + + // Individual results go after the lines below. + var group = document.createElement('a'); + group.className = 'group-separator'; + group.textContent = 'Results for individual providers.'; + output.appendChild(group); + + // Add the per-provider result tables with labels. We do not append the + // combined/merged result table since we already have the per provider + // results. + for (var i = 0; i < result.resultsByProvider.length; i++) { + var providerResults = result.resultsByProvider[i]; + // If we have no results we do not display anything. + if (providerResults.results.length == 0) { + continue; + } + var p = document.createElement('p'); + p.appendChild(addResultTableToOutput(providerResults.results)); + output.appendChild(p); + } +} + +/** + * @param {Object} result an array of AutocompleteMatchMojos. + * @return {HTMLTableCellElement} that is a user-readable HTML + * representation of this object. + */ +function addResultTableToOutput(result) { + var inDetailedMode = $('show-details').checked; + // Create a table to hold all the autocomplete items. + var table = document.createElement('table'); + table.className = 'autocomplete-results-table'; + table.appendChild(createAutocompleteResultTableHeader()); + // Loop over every autocomplete item and add it as a row in the table. + for (var i = 0; i < result.length; i++) { + var autocompleteSuggestion = result[i]; + var row = document.createElement('tr'); + // Loop over all the columns/properties and output either them + // all (if we're in detailed mode) or only the ones marked displayAlways. + // Keep track of which properties we displayed. + var displayedProperties = {}; + for (var j = 0; j < PROPERTY_OUTPUT_ORDER.length; j++) { + if (inDetailedMode || PROPERTY_OUTPUT_ORDER[j].displayAlways) { + row.appendChild(createCellForPropertyAndRemoveProperty( + autocompleteSuggestion, PROPERTY_OUTPUT_ORDER[j].propertyName)); + displayedProperties[PROPERTY_OUTPUT_ORDER[j].propertyName] = true; + } + } + + // Now, if we're in detailed mode, add all the properties that + // haven't already been output. (We know which properties have + // already been output because we delete the property when we output + // it. The only way we have properties left at this point if + // we're in detailed mode and we're getting back properties + // not listed in PROPERTY_OUTPUT_ORDER. Perhaps someone added + // something to the C++ code but didn't bother to update this + // Javascript? In any case, we want to display them.) + if (inDetailedMode) { + for (var key in autocompleteSuggestion) { + if (!displayedProperties[key] && + typeof autocompleteSuggestion[key] != 'function') { + var cell = document.createElement('td'); + cell.textContent = key + '=' + autocompleteSuggestion[key]; + row.appendChild(cell); + } + } + } + + table.appendChild(row); + } + return table; +} + +/* Repaints the page based on the contents of the array + * progressiveAutocompleteResults, which represents consecutive + * autocomplete results. We only display the last (most recent) + * entry unless we're asked to display incomplete results. For an + * example of the output, play with chrome://omnibox/ + */ +function refresh() { + // Erase whatever is currently being displayed. + var output = $('omnibox-debug-text'); + output.innerHTML = ''; + + if (progressiveAutocompleteResults.length > 0) { // if we have results + // Display the results. var showIncompleteResults = $('show-incomplete-results').checked; - var showPerProviderResults = $('show-all-providers').checked; - - // Always output cursor position. - var p = document.createElement('p'); - p.textContent = 'cursor position = ' + cursorPositionUsed; - output.appendChild(p); - - // Output the result-level features in detailed mode and in - // show incomplete results mode. We do the latter because without - // these result-level features, one can't make sense of each - // batch of results. - if (inDetailedMode || showIncompleteResults) { - var p1 = document.createElement('p'); - p1.textContent = 'elapsed time = ' + - result.timeSinceOmniboxStartedMs + 'ms'; - output.appendChild(p1); - var p2 = document.createElement('p'); - p2.textContent = 'all providers done = ' + result.done; - output.appendChild(p2); - var p3 = document.createElement('p'); - p3.textContent = 'host = ' + result.host; - if ('isTypedHost' in result) { - // Only output the isTypedHost information if available. (It may - // be missing if the history database lookup failed.) - p3.textContent = p3.textContent + ' has isTypedHost = ' + - result.isTypedHost; - } - output.appendChild(p3); - } - - // Combined results go after the lines below. - var group = document.createElement('a'); - group.className = 'group-separator'; - group.textContent = 'Combined results.'; - output.appendChild(group); - - // Add combined/merged result table. - var p = document.createElement('p'); - p.appendChild(addResultTableToOutput(result.combinedResults)); - output.appendChild(p); - - // Move forward only if you want to display per provider results. - if (!showPerProviderResults) { - return; - } - - // Individual results go after the lines below. - var group = document.createElement('a'); - group.className = 'group-separator'; - group.textContent = 'Results for individual providers.'; - output.appendChild(group); - - // Add the per-provider result tables with labels. We do not append the - // combined/merged result table since we already have the per provider - // results. - for (var i = 0; i < result.resultsByProvider.length; i++) { - var providerResults = result.resultsByProvider[i]; - // If we have no results we do not display anything. - if (providerResults.results.length == 0) { - continue; - } - var p = document.createElement('p'); - p.appendChild(addResultTableToOutput(providerResults.results)); - output.appendChild(p); + var startIndex = + showIncompleteResults ? 0 : progressiveAutocompleteResults.length - 1; + for (var i = startIndex; i < progressiveAutocompleteResults.length; i++) { + addResultToOutput(progressiveAutocompleteResults[i]); } } +} - /** - * @param {Object} result an array of AutocompleteMatchMojos. - * @return {HTMLTableCellElement} that is a user-readable HTML - * representation of this object. - */ - function addResultTableToOutput(result) { - var inDetailedMode = $('show-details').checked; - // Create a table to hold all the autocomplete items. - var table = document.createElement('table'); - table.className = 'autocomplete-results-table'; - table.appendChild(createAutocompleteResultTableHeader()); - // Loop over every autocomplete item and add it as a row in the table. - for (var i = 0; i < result.length; i++) { - var autocompleteSuggestion = result[i]; - var row = document.createElement('tr'); - // Loop over all the columns/properties and output either them - // all (if we're in detailed mode) or only the ones marked displayAlways. - // Keep track of which properties we displayed. - var displayedProperties = {}; - for (var j = 0; j < PROPERTY_OUTPUT_ORDER.length; j++) { - if (inDetailedMode || PROPERTY_OUTPUT_ORDER[j].displayAlways) { - row.appendChild(createCellForPropertyAndRemoveProperty( - autocompleteSuggestion, PROPERTY_OUTPUT_ORDER[j].propertyName)); - displayedProperties[PROPERTY_OUTPUT_ORDER[j].propertyName] = true; - } - } +// NOTE: Need to keep a global reference to the |pageImpl| such that it is not +// garbage collected, which causes the pipe to close and future calls from C++ +// to JS to get dropped. +var pageImpl = null; +var browserProxy = null; - // Now, if we're in detailed mode, add all the properties that - // haven't already been output. (We know which properties have - // already been output because we delete the property when we output - // it. The only way we have properties left at this point if - // we're in detailed mode and we're getting back properties - // not listed in PROPERTY_OUTPUT_ORDER. Perhaps someone added - // something to the C++ code but didn't bother to update this - // Javascript? In any case, we want to display them.) - if (inDetailedMode) { - for (var key in autocompleteSuggestion) { - if (!displayedProperties[key] && - typeof autocompleteSuggestion[key] != 'function') { - var cell = document.createElement('td'); - cell.textContent = key + '=' + autocompleteSuggestion[key]; - row.appendChild(cell); - } - } - } +function initializeProxies() { + browserProxy = new mojom.OmniboxPageHandlerPtr; + Mojo.bindInterface( + mojom.OmniboxPageHandler.name, mojo.makeRequest(browserProxy).handle); - table.appendChild(row); - } - return table; - } + /** @constructor */ + var OmniboxPageImpl = function(request) { + this.binding_ = new mojo.Binding(mojom.OmniboxPage, this, request); + }; - /* Repaints the page based on the contents of the array - * progressiveAutocompleteResults, which represents consecutive - * autocomplete results. We only display the last (most recent) - * entry unless we're asked to display incomplete results. For an - * example of the output, play with chrome://omnibox/ - */ - function refresh() { - // Erase whatever is currently being displayed. - var output = $('omnibox-debug-text'); - output.innerHTML = ''; + OmniboxPageImpl.prototype = { + /** @override */ + handleNewAutocompleteResult: function(result) { + progressiveAutocompleteResults.push(result); + refresh(); + }, + }; - if (progressiveAutocompleteResults.length > 0) { // if we have results - // Display the results. - var showIncompleteResults = $('show-incomplete-results').checked; - var startIndex = showIncompleteResults ? 0 : - progressiveAutocompleteResults.length - 1; - for (var i = startIndex; i < progressiveAutocompleteResults.length; i++) { - addResultToOutput(progressiveAutocompleteResults[i]); - } - } - } + var client = new mojom.OmniboxPagePtr; + pageImpl = new OmniboxPageImpl(mojo.makeRequest(client)); + browserProxy.setClientPage(client); +} - // NOTE: Need to keep a global reference to the |pageImpl| such that it is not - // garbage collected, which causes the pipe to close and future calls from C++ - // to JS to get dropped. - var pageImpl = null; - var browserProxy = null; - - function initializeProxies() { - browserProxy = new mojom.OmniboxPageHandlerPtr; - Mojo.bindInterface(mojom.OmniboxPageHandler.name, - mojo.makeRequest(browserProxy).handle); - - /** @constructor */ - var OmniboxPageImpl = function(request) { - this.binding_ = new mojo.Binding(mojom.OmniboxPage, this, request); - }; - - OmniboxPageImpl.prototype = { - /** @override */ - handleNewAutocompleteResult: function(result) { - progressiveAutocompleteResults.push(result); - refresh(); - }, - }; - - var client = new mojom.OmniboxPagePtr; - pageImpl = new OmniboxPageImpl(mojo.makeRequest(client)); - browserProxy.setClientPage(client); - } - - document.addEventListener('DOMContentLoaded', function() { - initializeProxies(); - initialize(); - }); +document.addEventListener('DOMContentLoaded', function() { + initializeProxies(); + initialize(); +}); })();
diff --git a/chrome/browser/resources/policy.js b/chrome/browser/resources/policy.js index afdfb2f9..7865939 100644 --- a/chrome/browser/resources/policy.js +++ b/chrome/browser/resources/policy.js
@@ -9,8 +9,9 @@ * @return {boolean} True if this is the mobile version. */ var isMobilePage = function() { - return document.defaultView.getComputedStyle(document.querySelector( - '.scope-column')).display == 'none'; + return document.defaultView + .getComputedStyle(document.querySelector('.scope-column')) + .display == 'none'; }; /** @@ -31,8 +32,7 @@ /** * Initialization function for the cr.ui framework. */ - decorate: function() { - }, + decorate: function() {}, /** * Populate the box with the given cloud policy status. @@ -52,20 +52,20 @@ // Populate the device naming information. // Populate the asset identifier. var assetId = this.querySelector('.asset-id'); - assetId.textContent = status.assetId || - loadTimeData.getString('notSpecified'); + assetId.textContent = + status.assetId || loadTimeData.getString('notSpecified'); assetId.parentElement.hidden = false; // Populate the device location. var location = this.querySelector('.location'); - location.textContent = status.location || - loadTimeData.getString('notSpecified'); + location.textContent = + status.location || loadTimeData.getString('notSpecified'); location.parentElement.hidden = false; // Populate the directory API ID. var directoryApiId = this.querySelector('.directory-api-id'); - directoryApiId.textContent = status.directoryApiId || - loadTimeData.getString('notSpecified'); + directoryApiId.textContent = + status.directoryApiId || loadTimeData.getString('notSpecified'); directoryApiId.parentElement.hidden = false; } else { // For user policy, set the appropriate title and populate the topmost @@ -107,8 +107,8 @@ */ decorate: function() { this.updateToggleExpandedValueText_(); - this.querySelector('.toggle-expanded-value').addEventListener( - 'click', this.toggleExpandedValue_.bind(this)); + this.querySelector('.toggle-expanded-value') + .addEventListener('click', this.toggleExpandedValue_.bind(this)); }, /** @@ -128,12 +128,11 @@ // Populate the remaining columns with policy scope, level and value if a // value has been set. Otherwise, leave them blank. if (value) { - this.querySelector('.scope').textContent = - loadTimeData.getString(value.scope == 'user' ? - 'scopeUser' : 'scopeDevice'); - this.querySelector('.level').textContent = - loadTimeData.getString(value.level == 'recommended' ? - 'levelRecommended' : 'levelMandatory'); + this.querySelector('.scope').textContent = loadTimeData.getString( + value.scope == 'user' ? 'scopeUser' : 'scopeDevice'); + this.querySelector('.level').textContent = loadTimeData.getString( + value.level == 'recommended' ? 'levelRecommended' : + 'levelMandatory'); this.querySelector('.source').textContent = loadTimeData.getString(value.source); this.querySelector('.value').textContent = value.value; @@ -164,7 +163,8 @@ /** @const */ var HIDDEN_COLUMNS_IN_MOBILE_VERSION = 2; var expandedValue = this.querySelector('.expanded-value'); - expandedValue.setAttribute('colspan', + expandedValue.setAttribute( + 'colspan', expandedValue.colSpan - HIDDEN_COLUMNS_IN_MOBILE_VERSION); } }, @@ -211,7 +211,8 @@ this.querySelector('.toggle-expanded-value').textContent = loadTimeData.getString( this.classList.contains('show-overflowed-value') ? - 'hideExpandedValue' : 'showExpandedValue'); + 'hideExpandedValue' : + 'showExpandedValue'); }, /** @@ -310,8 +311,7 @@ var policies = this.getElementsByTagName('tbody'); for (var i = 0; i < policies.length; i++) { var policy = policies[i]; - policy.hidden = - policy.unset && !showUnset || + policy.hidden = policy.unset && !showUnset || policy.name.toLowerCase().indexOf(this.filterPattern_) == -1; } if (this.querySelector('tbody:not([hidden])')) @@ -351,8 +351,7 @@ * A singelton object that handles communication between browser and WebUI. * @constructor */ - function Page() { - } + function Page() {} // Make Page a singleton. cr.addSingletonGetter(Page); @@ -377,8 +376,9 @@ if (names.hasOwnProperty('extensionPolicyNames')) { for (var ext in names.extensionPolicyNames) { - var table = page.appendNewTable('extension-' + ext, - names.extensionPolicyNames[ext].name, 'ID: ' + ext); + var table = page.appendNewTable( + 'extension-' + ext, names.extensionPolicyNames[ext].name, + 'ID: ' + ext); table.setPolicyNames(names.extensionPolicyNames[ext].policyNames); } } @@ -459,7 +459,7 @@ chrome.send('initialized'); }, - /** + /** * Creates a new policy table section, adds the section to the page, * and returns the new table from that section. * @param {string} id The key for storing the new table in policyTables. @@ -468,8 +468,8 @@ * @return {Element} The newly created table. */ appendNewTable: function(id, label_title, label_content) { - var newSection = this.createPolicyTableSection(id, label_title, - label_content); + var newSection = + this.createPolicyTableSection(id, label_title, label_content); this.mainSection.appendChild(newSection); return this.policyTables[id]; }, @@ -520,13 +520,13 @@ var newTable = window.document.createElement('table'); var tableHead = window.document.createElement('thead'); var tableRow = window.document.createElement('tr'); - var tableHeadings = ['Scope', 'Level', 'Source', 'Name', 'Value', - 'Status']; + var tableHeadings = + ['Scope', 'Level', 'Source', 'Name', 'Value', 'Status']; for (var i = 0; i < tableHeadings.length; i++) { var tableHeader = window.document.createElement('th'); tableHeader.classList.add(tableHeadings[i].toLowerCase() + '-column'); - tableHeader.textContent = loadTimeData.getString('header' + - tableHeadings[i]); + tableHeader.textContent = + loadTimeData.getString('header' + tableHeadings[i]); tableRow.appendChild(tableHeader); } tableHead.appendChild(tableRow); @@ -568,9 +568,7 @@ }, }; - return { - Page: Page - }; + return {Page: Page}; }); // Have the main initialization function be called when the page finishes
diff --git a/chrome/browser/resources/predictors/autocomplete_action_predictor.js b/chrome/browser/resources/predictors/autocomplete_action_predictor.js index ebdad5c..80fe506 100644 --- a/chrome/browser/resources/predictors/autocomplete_action_predictor.js +++ b/chrome/browser/resources/predictors/autocomplete_action_predictor.js
@@ -54,9 +54,10 @@ if (!filter.checked || entry.confidence > 0) { var row = document.createElement('tr'); - row.className = (entry.confidence > 0.8 ? 'action-prerender' : - (entry.confidence > 0.5 ? 'action-preconnect' : - 'action-none')); + row.className = + (entry.confidence > 0.8 ? + 'action-prerender' : + (entry.confidence > 0.5 ? 'action-preconnect' : 'action-none')); row.appendChild(document.createElement('td')).textContent = entry.user_text; @@ -74,5 +75,5 @@ $('countBanner').textContent = 'Entries: ' + databaseSection.children.length; } -document.addEventListener('DOMContentLoaded', - requestAutocompleteActionPredictorDb); +document.addEventListener( + 'DOMContentLoaded', requestAutocompleteActionPredictorDb);
diff --git a/chrome/browser/resources/predictors/resource_prefetch_predictor.js b/chrome/browser/resources/predictors/resource_prefetch_predictor.js index f2815e6d..cc318433 100644 --- a/chrome/browser/resources/predictors/resource_prefetch_predictor.js +++ b/chrome/browser/resources/predictors/resource_prefetch_predictor.js
@@ -75,8 +75,8 @@ row.appendChild(t); } - row.className = resource.is_prefetchable ? 'action-prerender' - : 'action-none'; + row.className = + resource.is_prefetchable ? 'action-prerender' : 'action-none'; row.appendChild(document.createElement('td')).textContent = truncateString(resource.resource_url); @@ -99,5 +99,5 @@ } } -document.addEventListener('DOMContentLoaded', - requestResourcePrefetchPredictorDb); +document.addEventListener( + 'DOMContentLoaded', requestResourcePrefetchPredictorDb);
diff --git a/chrome/browser/resources/profiler/profiler.js b/chrome/browser/resources/profiler/profiler.js index 423392e..81b1250b8 100644 --- a/chrome/browser/resources/profiler/profiler.js +++ b/chrome/browser/resources/profiler/profiler.js
@@ -30,8 +30,7 @@ /** * @constructor */ - function BrowserBridge() { - } + function BrowserBridge() {} BrowserBridge.prototype = { //-------------------------------------------------------------------------- @@ -182,7 +181,9 @@ }; return { - create: function(key) { return new Aggregator(key); } + create: function(key) { + return new Aggregator(key); + } }; })(); @@ -210,7 +211,9 @@ }; return { - create: function(key) { return new Aggregator(key); } + create: function(key) { + return new Aggregator(key); + } }; })(); @@ -318,7 +321,9 @@ }; return { - create: function(key) { return new Aggregator(key); } + create: function(key) { + return new Aggregator(key); + } }; })(); @@ -328,15 +333,14 @@ // Custom comparator for thread names (sorts main thread and IO thread // higher than would happen lexicographically.) - var threadNameComparator = - createLexicographicComparatorWithExceptions([ - 'CrBrowserMain', - 'Chrome_IOThread', - 'Chrome_FileThread', - 'Chrome_HistoryThread', - 'Chrome_DBThread', - 'Still_Alive', - ]); + var threadNameComparator = createLexicographicComparatorWithExceptions([ + 'CrBrowserMain', + 'Chrome_IOThread', + 'Chrome_FileThread', + 'Chrome_HistoryThread', + 'Chrome_DBThread', + 'Still_Alive', + ]); function diffFuncForCount(a, b) { return b - a; @@ -492,8 +496,8 @@ cellAlignment: 'right', sortDescending: true, textPrinter: formatNumberAsText, - aggregator: AvgDiffAggregator.create(KEY_MEMORY_ALLOCATED_BYTES, - KEY_MEMORY_FREED_BYTES, KEY_COUNT), + aggregator: AvgDiffAggregator.create( + KEY_MEMORY_ALLOCATED_BYTES, KEY_MEMORY_FREED_BYTES, KEY_COUNT), }; KEY_PROPERTIES[KEY_MEMORY_ALLOC_OPS] = { @@ -758,7 +762,7 @@ var orig = x.toFixed(0); var parts = []; - for (var end = orig.length; end > 0; ) { + for (var end = orig.length; end > 0;) { var chunk = Math.min(end, 3); parts.push(orig.substr(end - chunk, chunk)); end -= chunk; @@ -850,7 +854,7 @@ */ function deleteValuesFromArray(array, valuesToDelete) { var valueSet = arrayToSet(valuesToDelete); - for (var i = 0; i < array.length; ) { + for (var i = 0; i < array.length;) { if (valueSet[array[i]]) { array.splice(i, 1); } else { @@ -866,7 +870,7 @@ // Build up set of each entry in array. var seenSoFar = {}; - for (var i = 0; i < array.length; ) { + for (var i = 0; i < array.length;) { var value = array[i]; if (seenSoFar[value]) { array.splice(i, 1); @@ -922,8 +926,7 @@ * slashes or backslashes. */ function getFilenameFromPath(path) { - var lastSlash = Math.max(path.lastIndexOf('/'), - path.lastIndexOf('\\')); + var lastSlash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); if (lastSlash == -1) return path; @@ -980,7 +983,7 @@ e[KEY_MEMORY_AVG_FREE_OPS] = e[KEY_MEMORY_FREE_OPS] / e[KEY_COUNT]; e[KEY_MEMORY_AVG_NET_BYTES] = (e[KEY_MEMORY_ALLOCATED_BYTES] - e[KEY_MEMORY_FREED_BYTES]) / - e[KEY_COUNT]; + e[KEY_COUNT]; } } @@ -1039,8 +1042,8 @@ * flat list. Otherwise the result will be a dictionary, where each row * has a unique key. */ - function mergeRows(origRows, mergeKeys, mergeSimilarThreads, - outputAsDictionary) { + function mergeRows( + origRows, mergeKeys, mergeSimilarThreads, outputAsDictionary) { // Define a translation function for each property. Normally we copy over // properties as-is, but if we have been asked to "merge similar threads" we // we will remap the thread names that end in a numeric suffix. @@ -1058,7 +1061,9 @@ return value; }; } else { - propertyGetterFunc = function(row, key) { return row[key]; }; + propertyGetterFunc = function(row, key) { + return row[key]; + }; } // Determine which sets of properties a row needs to match on to be @@ -1126,10 +1131,10 @@ // final row. var COMPUTED_AGGREGATE_KEYS = [KEY_AVG_QUEUE_TIME, KEY_AVG_RUN_TIME]; if (loadTimeData.getBoolean('enableMemoryTaskProfiler')) { - COMPUTED_AGGREGATE_KEYS = COMPUTED_AGGREGATE_KEYS.concat([ - KEY_MEMORY_AVG_ALLOC_OPS, - KEY_MEMORY_AVG_FREE_OPS, - KEY_MEMORY_AVG_NET_BYTES]); + COMPUTED_AGGREGATE_KEYS = COMPUTED_AGGREGATE_KEYS.concat([ + KEY_MEMORY_AVG_ALLOC_OPS, KEY_MEMORY_AVG_FREE_OPS, + KEY_MEMORY_AVG_NET_BYTES + ]); } // These are the keys which determine row equality. Since we are not doing @@ -1235,8 +1240,8 @@ var link = addNode(td, 'a', filename + ' [' + linenumber + ']'); link.href = 'https://code.google.com/p/chromium/codesearch#search/&q=' + - encodeURIComponent(filename) + ':' + linenumber + - '&sq=package:chromium&type=cs'; + encodeURIComponent(filename) + ':' + linenumber + + '&sq=package:chromium&type=cs'; link.target = '_blank'; return; } @@ -1509,11 +1514,9 @@ // Explain that what is being shown is the difference between two // snapshots. - summaryDiv.innerText = - 'Showing the difference between snapshots #' + - selectedSnapshots[0] + ' and #' + - selectedSnapshots[1] + ' (' + timeDeltaInSeconds + - ' seconds worth of data)'; + summaryDiv.innerText = 'Showing the difference between snapshots #' + + selectedSnapshots[0] + ' and #' + selectedSnapshots[1] + ' (' + + timeDeltaInSeconds + ' seconds worth of data)'; } else { // This shouldn't be possible... throw 'Unexpected number of selected snapshots'; @@ -1531,31 +1534,24 @@ // between two snapshots, or just displaying a single snapshot. if (selectedSnapshots.length == 1) { var snapshot = this.snapshots_[selectedSnapshots[0]]; - this.mergedData_ = mergeRows(snapshot.flatData, - mergeColumns, - shouldMergeSimilarThreads, - false); + this.mergedData_ = mergeRows( + snapshot.flatData, mergeColumns, shouldMergeSimilarThreads, false); } else if (selectedSnapshots.length == 2) { var snapshot1 = this.snapshots_[selectedSnapshots[0]]; var snapshot2 = this.snapshots_[selectedSnapshots[1]]; // Merge the data for snapshot1. - var mergedRows1 = mergeRows(snapshot1.flatData, - mergeColumns, - shouldMergeSimilarThreads, - true); + var mergedRows1 = mergeRows( + snapshot1.flatData, mergeColumns, shouldMergeSimilarThreads, true); // Merge the data for snapshot2. - var mergedRows2 = mergeRows(snapshot2.flatData, - mergeColumns, - shouldMergeSimilarThreads, - true); + var mergedRows2 = mergeRows( + snapshot2.flatData, mergeColumns, shouldMergeSimilarThreads, true); // Do a diff between the two snapshots. - this.mergedData_ = subtractSnapshots(mergedRows1, - mergedRows2, - mergeColumns); + this.mergedData_ = + subtractSnapshots(mergedRows1, mergedRows2, mergeColumns); } else { throw 'Unexpected number of selected snapshots'; } @@ -1723,8 +1719,8 @@ this.drawAggregateRow_(thead, data.aggregates, columns); this.drawTableHeader_(thead, columns); this.drawTableBody_(tbody, data.rows, columns, limit); - this.drawTruncationRow_(tbody, data.rows.length, limit, columns.length, - groupKey); + this.drawTruncationRow_( + tbody, data.rows.length, limit, columns.length, groupKey); }, drawTableHeader_: function(thead, columns) { @@ -1939,9 +1935,10 @@ saveSnapshots_: function() { var snapshots = []; for (var i = 0; i < this.snapshots_.length; ++i) { - snapshots.push({ data: this.snapshots_[i].origData, - timestamp: Math.floor( - this.snapshots_[i].time / 1000) }); + snapshots.push({ + data: this.snapshots_[i].origData, + timestamp: Math.floor(this.snapshots_[i].time / 1000) + }); } var dump = { @@ -1951,8 +1948,8 @@ }; var dumpText = JSON.stringify(dump, null, ' '); - var textBlob = new Blob([dumpText], - { type: 'octet/stream', endings: 'native' }); + var textBlob = + new Blob([dumpText], {type: 'octet/stream', endings: 'native'}); var blobUrl = window.URL.createObjectURL(textBlob); $(DOWNLOAD_ANCHOR_ID).href = blobUrl; $(DOWNLOAD_ANCHOR_ID).click(); @@ -2011,8 +2008,8 @@ for (var i = 0; i < content.snapshots.length; ++i) { var snapshot = content.snapshots[i]; - this.snapshots_.push({flatData: [], origData: [], - time: snapshot.timestamp * 1000}); + this.snapshots_.push( + {flatData: [], origData: [], time: snapshot.timestamp * 1000}); this.addSnapshotToList_(this.snapshots_.length - 1); var snapshotData = snapshot.data; for (var j = 0; j < snapshotData.length; ++j) { @@ -2092,7 +2089,9 @@ // was just checked, then uncheck one of the earlier ones so we only have // 2. var checked = this.getSelectedSnapshotBoxes_(); - checked.sort(function(a, b) { return b.__time - a.__time; }); + checked.sort(function(a, b) { + return b.__time - a.__time; + }); if (checked.length > 2) { for (var i = 2; i < checked.length; ++i) checked[i].checked = false; @@ -2310,9 +2309,7 @@ for (var i = 0; i < groupKey1.length; ++i) { var comparison = compareValuesForKey( - groupKey1[i].key, - groupKey1[i].value, - groupKey2[i].value); + groupKey1[i].key, groupKey1[i].value, groupKey2[i].value); if (comparison != 0) return comparison; @@ -2361,8 +2358,7 @@ var groupKey = []; for (var i = 0; i < groupings.length; ++i) { - var entry = {key: groupings[i], - value: e[groupings[i]]}; + var entry = {key: groupings[i], value: e[groupings[i]]}; groupKey.push(entry); }
diff --git a/chrome/browser/resources/quota_internals/event_handler.js b/chrome/browser/resources/quota_internals/event_handler.js index a718545..5505ea9 100644 --- a/chrome/browser/resources/quota_internals/event_handler.js +++ b/chrome/browser/resources/quota_internals/event_handler.js
@@ -106,8 +106,7 @@ if (segments.length > 1) { var UNIT = [' B', ' KB', ' MB', ' GB', ' TB', ' PB']; result = segments[0] + '.' + segments[1].slice(0, 2) + - UNIT[Math.min(segments.length, UNIT.length) - 1] + - ' (' + result + ')'; + UNIT[Math.min(segments.length, UNIT.length) - 1] + ' (' + result + ')'; } return result; @@ -202,10 +201,8 @@ var treeViewObject = getTreeViewObject(); var storageObject = treeViewObject.detail.children[type]; if (!storageObject) { - storageObject = new cr.ui.TreeItem({ - label: type, - detail: {payload: {}, children: {}} - }); + storageObject = + new cr.ui.TreeItem({label: type, detail: {payload: {}, children: {}}}); storageObject.mayHaveChildren_ = true; treeViewObject.detail.children[type] = storageObject; treeViewObject.add(storageObject); @@ -224,10 +221,8 @@ var storageObject = getStorageObject(type); var hostObject = storageObject.detail.children[host]; if (!hostObject) { - hostObject = new cr.ui.TreeItem({ - label: host, - detail: {payload: {}, children: {}} - }); + hostObject = + new cr.ui.TreeItem({label: host, detail: {payload: {}, children: {}}}); hostObject.mayHaveChildren_ = true; storageObject.detail.children[host] = hostObject; storageObject.add(hostObject); @@ -247,10 +242,8 @@ var hostObject = getHostObject(type, host); var originObject = hostObject.detail.children[origin]; if (!originObject) { - originObject = new cr.ui.TreeItem({ - label: origin, - detail: {payload: {}, children: {}} - }); + originObject = new cr.ui.TreeItem( + {label: origin, detail: {payload: {}, children: {}}}); originObject.mayHaveChildren_ = false; hostObject.detail.children[origin] = originObject; hostObject.add(originObject); @@ -303,7 +296,6 @@ storageObject.reveal(); if (getTreeViewObject().selectedItem == storageObject) updateDescription(); - } /** @@ -340,7 +332,6 @@ hostObject.reveal(); if (getTreeViewObject().selectedItem == hostObject) updateDescription(); - } } @@ -410,8 +401,7 @@ statistics[key] = entry; } entry.detail = data[key]; - entry.innerHTML = - '<td>' + stringToText_(key) + '</td>' + + entry.innerHTML = '<td>' + stringToText_(key) + '</td>' + '<td>' + stringToText_(entry.detail) + '</td>'; localize_(entry); } @@ -427,20 +417,15 @@ tbody.innerHTML = ''; if (item) { - var keyAndLabel = [['type', 'Storage Type'], - ['host', 'Host Name'], - ['origin', 'Origin URL'], - ['usage', 'Total Storage Usage', numBytesToText_], - ['unlimitedUsage', 'Usage of Unlimited Origins', - numBytesToText_], - ['quota', 'Quota', numBytesToText_], - ['inUse', 'Origin is in use?'], - ['usedCount', 'Used count'], - ['lastAccessTime', 'Last Access Time', - dateToText], - ['lastModifiedTime', 'Last Modified Time', - dateToText] - ]; + var keyAndLabel = [ + ['type', 'Storage Type'], ['host', 'Host Name'], ['origin', 'Origin URL'], + ['usage', 'Total Storage Usage', numBytesToText_], + ['unlimitedUsage', 'Usage of Unlimited Origins', numBytesToText_], + ['quota', 'Quota', numBytesToText_], ['inUse', 'Origin is in use?'], + ['usedCount', 'Used count'], + ['lastAccessTime', 'Last Access Time', dateToText], + ['lastModifiedTime', 'Last Modified Time', dateToText] + ]; for (var i = 0; i < keyAndLabel.length; ++i) { var key = keyAndLabel[i][0]; var label = keyAndLabel[i][1]; @@ -451,8 +436,7 @@ var normalize = keyAndLabel[i][2] || stringToText_; var row = cr.doc.createElement('tr'); - row.innerHTML = - '<td>' + label + '</td>' + + row.innerHTML = '<td>' + label + '</td>' + '<td>' + normalize(entry) + '</td>'; localize_(row); tbody.appendChild(row); @@ -501,30 +485,23 @@ function dump() { var separator = '========\n'; - $('dump-field').textContent = - separator + - 'Summary\n' + - separator + + $('dump-field').textContent = separator + 'Summary\n' + separator + JSON.stringify({availableSpace: availableSpace}, null, 2) + '\n' + - separator + - 'Usage And Quota\n' + - separator + - JSON.stringify(dumpTreeToObj(), null, 2) + '\n' + - separator + - 'Misc Statistics\n' + - separator + + separator + 'Usage And Quota\n' + separator + + JSON.stringify(dumpTreeToObj(), null, 2) + '\n' + separator + + 'Misc Statistics\n' + separator + JSON.stringify(dumpStatisticsToObj(), null, 2); } function onLoad() { cr.ui.decorate('tabbox', cr.ui.TabBox); - cr.quota.onAvailableSpaceUpdated.addEventListener('update', - handleAvailableSpace); + cr.quota.onAvailableSpaceUpdated.addEventListener( + 'update', handleAvailableSpace); cr.quota.onGlobalInfoUpdated.addEventListener('update', handleGlobalInfo); cr.quota.onPerHostInfoUpdated.addEventListener('update', handlePerHostInfo); - cr.quota.onPerOriginInfoUpdated.addEventListener('update', - handlePerOriginInfo); + cr.quota.onPerOriginInfoUpdated.addEventListener( + 'update', handlePerOriginInfo); cr.quota.onStatisticsUpdated.addEventListener('update', handleStatistics); cr.quota.requestInfo();
diff --git a/chrome/browser/resources/sandbox_internals/sandbox_internals.js b/chrome/browser/resources/sandbox_internals/sandbox_internals.js index 02479b5..81c4ad5 100644 --- a/chrome/browser/resources/sandbox_internals/sandbox_internals.js +++ b/chrome/browser/resources/sandbox_internals/sandbox_internals.js
@@ -3,137 +3,138 @@ // found in the LICENSE file. (function() { - let GOOD = 'good'; - let BAD = 'bad'; - let INFO = 'info'; +let GOOD = 'good'; +let BAD = 'bad'; +let INFO = 'info'; - /** - * Adds a row to the sandbox status table. - * @param {string} name The name of the status item. - * @param {string} value The status of the item. - * @param {string?} cssClass A CSS class to apply to the row. - * @return {Element} The newly added TR. - */ - function addStatusRow(name, value, cssClass) { - let row = cr.doc.createElement('tr'); +/** + * Adds a row to the sandbox status table. + * @param {string} name The name of the status item. + * @param {string} value The status of the item. + * @param {string?} cssClass A CSS class to apply to the row. + * @return {Element} The newly added TR. + */ +function addStatusRow(name, value, cssClass) { + let row = cr.doc.createElement('tr'); - let nameCol = row.appendChild(cr.doc.createElement('td')); - let valueCol = row.appendChild(cr.doc.createElement('td')); + let nameCol = row.appendChild(cr.doc.createElement('td')); + let valueCol = row.appendChild(cr.doc.createElement('td')); - nameCol.textContent = name; - valueCol.textContent = value; + nameCol.textContent = name; + valueCol.textContent = value; - if (cssClass != null) { - nameCol.classList.add(cssClass); - valueCol.classList.add(cssClass); - } - - $('sandbox-status').appendChild(row); - return row; + if (cssClass != null) { + nameCol.classList.add(cssClass); + valueCol.classList.add(cssClass); } - /** - * Adds a status row that reports either Yes or No. - * @param {string} name The name of the status item. - * @param {boolean} result The status (good/bad) result. - * @return {Element} The newly added TR. - */ - function addGoodBadRow(name, result) { - return addStatusRow(name, result ? 'Yes' : 'No', result ? GOOD : BAD); - } + $('sandbox-status').appendChild(row); + return row; +} - /** - * Reports the overall sandbox status evaluation message. - * @param {boolean} - */ - function setEvaluation(result) { - let message = result ? 'You are adequately sandboxed.' - : 'You are NOT adequately sandboxed.'; - $('evaluation').innerText = message; - } +/** + * Adds a status row that reports either Yes or No. + * @param {string} name The name of the status item. + * @param {boolean} result The status (good/bad) result. + * @return {Element} The newly added TR. + */ +function addGoodBadRow(name, result) { + return addStatusRow(name, result ? 'Yes' : 'No', result ? GOOD : BAD); +} - /** - * Main page handler for Android. - */ - function androidHandler() { - chrome.getAndroidSandboxStatus((status) => { - var isIsolated = false; - var isTsync = false; - var isChromeSeccomp = false; +/** + * Reports the overall sandbox status evaluation message. + * @param {boolean} + */ +function setEvaluation(result) { + let message = result ? 'You are adequately sandboxed.' : + 'You are NOT adequately sandboxed.'; + $('evaluation').innerText = message; +} - addStatusRow('PID', status.pid, INFO); - addStatusRow('UID', status.uid, INFO); - isIsolated = status.secontext.indexOf(':isolated_app:') != -1; - addStatusRow('SELinux Context', status.secontext, - isIsolated ? GOOD : BAD); +/** + * Main page handler for Android. + */ +function androidHandler() { + chrome.getAndroidSandboxStatus((status) => { + var isIsolated = false; + var isTsync = false; + var isChromeSeccomp = false; - let procStatus = status.procStatus.split('\n'); - for (let line of procStatus) { - if (line.startsWith('Seccomp')) { - var value = line.split(':')[1].trim(); - var cssClass = BAD; - if (value == '2') { - value = 'Yes - TSYNC (' + line + ')'; - cssClass = GOOD; - isTsync = true; - } else if (value == '1') { - value = 'Yes (' + line + ')'; - } else { - value = line; - } - addStatusRow('Seccomp-BPF Enabled (Kernel)', value, cssClass); - break; + addStatusRow('PID', status.pid, INFO); + addStatusRow('UID', status.uid, INFO); + isIsolated = status.secontext.indexOf(':isolated_app:') != -1; + addStatusRow('SELinux Context', status.secontext, isIsolated ? GOOD : BAD); + + let procStatus = status.procStatus.split('\n'); + for (let line of procStatus) { + if (line.startsWith('Seccomp')) { + var value = line.split(':')[1].trim(); + var cssClass = BAD; + if (value == '2') { + value = 'Yes - TSYNC (' + line + ')'; + cssClass = GOOD; + isTsync = true; + } else if (value == '1') { + value = 'Yes (' + line + ')'; + } else { + value = line; } + addStatusRow('Seccomp-BPF Enabled (Kernel)', value, cssClass); + break; } - - var seccompStatus = 'Unknown'; - switch (status.seccompStatus) { - case 0: - seccompStatus = 'Not Supported'; - break; - case 1: - seccompStatus = 'Run-time Detection Failed'; - break; - case 2: - seccompStatus = 'Disabled by Field Trial'; - break; - case 3: - seccompStatus = 'Enabled by Field Trial (not started)'; - break; - case 4: - seccompStatus = 'Sandbox Started'; - isChromeSeccomp = true; - break; - } - addStatusRow('Seccomp-BPF Enabled (Chrome)', seccompStatus, - status.seccompStatus == 4 ? GOOD : BAD); - - addStatusRow('Android Build ID', status.androidBuildId, INFO); - - setEvaluation(isIsolated && isTsync && isChromeSeccomp); - }); - } - - /** - * Main page handler for desktop Linux. - */ - function linuxHandler() { - addGoodBadRow('SUID Sandbox', loadTimeData.getBoolean('suid')); - addGoodBadRow('Namespace Sandbox', loadTimeData.getBoolean('userNs')); - addGoodBadRow('PID namespaces', loadTimeData.getBoolean('pidNs')); - addGoodBadRow('Network namespaces', loadTimeData.getBoolean('netNs')); - addGoodBadRow('Seccomp-BPF sandbox', loadTimeData.getBoolean('seccompBpf')); - addGoodBadRow('Seccomp-BPF sandbox supports TSYNC', - loadTimeData.getBoolean('seccompTsync')); - addGoodBadRow('Yama LSM Enforcing', loadTimeData.getBoolean('yama')); - setEvaluation(loadTimeData.getBoolean('sandboxGood')); - } - - document.addEventListener('DOMContentLoaded', () => { - if (cr.isAndroid) { - androidHandler(); - } else { - linuxHandler(); } + + var seccompStatus = 'Unknown'; + switch (status.seccompStatus) { + case 0: + seccompStatus = 'Not Supported'; + break; + case 1: + seccompStatus = 'Run-time Detection Failed'; + break; + case 2: + seccompStatus = 'Disabled by Field Trial'; + break; + case 3: + seccompStatus = 'Enabled by Field Trial (not started)'; + break; + case 4: + seccompStatus = 'Sandbox Started'; + isChromeSeccomp = true; + break; + } + addStatusRow( + 'Seccomp-BPF Enabled (Chrome)', seccompStatus, + status.seccompStatus == 4 ? GOOD : BAD); + + addStatusRow('Android Build ID', status.androidBuildId, INFO); + + setEvaluation(isIsolated && isTsync && isChromeSeccomp); }); +} + +/** + * Main page handler for desktop Linux. + */ +function linuxHandler() { + addGoodBadRow('SUID Sandbox', loadTimeData.getBoolean('suid')); + addGoodBadRow('Namespace Sandbox', loadTimeData.getBoolean('userNs')); + addGoodBadRow('PID namespaces', loadTimeData.getBoolean('pidNs')); + addGoodBadRow('Network namespaces', loadTimeData.getBoolean('netNs')); + addGoodBadRow('Seccomp-BPF sandbox', loadTimeData.getBoolean('seccompBpf')); + addGoodBadRow( + 'Seccomp-BPF sandbox supports TSYNC', + loadTimeData.getBoolean('seccompTsync')); + addGoodBadRow('Yama LSM Enforcing', loadTimeData.getBoolean('yama')); + setEvaluation(loadTimeData.getBoolean('sandboxGood')); +} + +document.addEventListener('DOMContentLoaded', () => { + if (cr.isAndroid) { + androidHandler(); + } else { + linuxHandler(); + } +}); })();
diff --git a/chrome/browser/resources/set_as_default_browser.js b/chrome/browser/resources/set_as_default_browser.js index 34f83a90..254704b5 100644 --- a/chrome/browser/resources/set_as_default_browser.js +++ b/chrome/browser/resources/set_as_default_browser.js
@@ -3,14 +3,14 @@ // found in the LICENSE file. (function() { - // Since all we want here is forwarding of certain commands, all can be done - // in the anonymous function's scope. +// Since all we want here is forwarding of certain commands, all can be done +// in the anonymous function's scope. - function wireUpWindow() { - $('launch-button').addEventListener('click', function() { - chrome.send('SetAsDefaultBrowser:LaunchSetDefaultBrowserFlow'); - }); - } +function wireUpWindow() { + $('launch-button').addEventListener('click', function() { + chrome.send('SetAsDefaultBrowser:LaunchSetDefaultBrowserFlow'); + }); +} - window.addEventListener('DOMContentLoaded', wireUpWindow); +window.addEventListener('DOMContentLoaded', wireUpWindow); })();
diff --git a/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js b/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js index 84ecd498..46c5895 100644 --- a/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js +++ b/chrome/browser/resources/signin/signin_email_confirmation/signin_email_confirmation.js
@@ -9,8 +9,8 @@ var args = JSON.parse(chrome.getVariableValue('dialogArguments')); var lastEmail = args.lastEmail; var newEmail = args.newEmail; - $('dialogTitle').textContent = loadTimeData.getStringF( - 'signinEmailConfirmationTitle', lastEmail); + $('dialogTitle').textContent = + loadTimeData.getStringF('signinEmailConfirmationTitle', lastEmail); $('createNewUserRadioButtonSubtitle').textContent = loadTimeData.getStringF( 'signinEmailConfirmationCreateProfileButtonSubtitle', newEmail); $('startSyncRadioButtonSubtitle').textContent = loadTimeData.getStringF( @@ -54,5 +54,5 @@ }; }); -document.addEventListener('DOMContentLoaded', - signin.emailConfirmation.initialize); +document.addEventListener( + 'DOMContentLoaded', signin.emailConfirmation.initialize);
diff --git a/chrome/browser/resources/snippets_internals.js b/chrome/browser/resources/snippets_internals.js index 9f36642..d9718326 100644 --- a/chrome/browser/resources/snippets_internals.js +++ b/chrome/browser/resources/snippets_internals.js
@@ -50,8 +50,7 @@ function receiveContentSuggestions(categoriesList) { lastSuggestions = categoriesList; - displayList(categoriesList, 'content-suggestions', - 'hidden-toggler'); + displayList(categoriesList, 'content-suggestions', 'hidden-toggler'); var clearCachedButtons = document.getElementsByClassName('submit-clear-cached-suggestions'); @@ -89,7 +88,8 @@ var id = parseInt(event.currentTarget.getAttribute('category-id'), 10); var table = $('dismissed-suggestions-' + id); table.classList.toggle('hidden'); - chrome.send('toggleDismissedSuggestions', + chrome.send( + 'toggleDismissedSuggestions', [id, !table.classList.contains('hidden')]); } @@ -119,7 +119,8 @@ function receiveLastRemoteSuggestionsBackgroundFetchTime( lastRemoteSuggestionsBackgroundFetchTime) { - receiveProperty('last-background-fetch-time-label', + receiveProperty( + 'last-background-fetch-time-label', lastRemoteSuggestionsBackgroundFetchTime); } @@ -156,8 +157,10 @@ display = 'none'; } - if ($(domId + '-empty')) $(domId + '-empty').textContent = text; - if ($(domId + '-clear')) $(domId + '-clear').style.display = display; + if ($(domId + '-empty')) + $(domId + '-empty').textContent = text; + if ($(domId + '-clear')) + $(domId + '-clear').style.display = display; var links = document.getElementsByClassName(toggleClass); for (var link of links) { @@ -178,5 +181,5 @@ }; }); -document.addEventListener('DOMContentLoaded', - chrome.SnippetsInternals.initialize); +document.addEventListener( + 'DOMContentLoaded', chrome.SnippetsInternals.initialize);
diff --git a/chrome/browser/resources/standalone/standalone_hack.js b/chrome/browser/resources/standalone/standalone_hack.js index c7d3c335..c830a6c 100644 --- a/chrome/browser/resources/standalone/standalone_hack.js +++ b/chrome/browser/resources/standalone/standalone_hack.js
@@ -34,38 +34,32 @@ */ chrome.send = (function() { var users = [ - { - name: 'Alan Beaker', - emailAddress: 'beaker@chromium.org', - imageUrl: '../../app/theme/avatar_beaker.png', - canRemove: false - }, - { - name: 'Alex Briefcase', - emailAddress: 'briefcase@chromium.org', - imageUrl: '../../app/theme/avatar_briefcase.png', - canRemove: true - }, - { - name: 'Alex Circles', - emailAddress: 'circles@chromium.org', - imageUrl: '../../app/theme/avatar_circles.png', - canRemove: true - }, - { - name: 'Guest', - emailAddress: '', - imageUrl: '', - canRemove: false - } + { + name: 'Alan Beaker', + emailAddress: 'beaker@chromium.org', + imageUrl: '../../app/theme/avatar_beaker.png', + canRemove: false + }, + { + name: 'Alex Briefcase', + emailAddress: 'briefcase@chromium.org', + imageUrl: '../../app/theme/avatar_briefcase.png', + canRemove: true + }, + { + name: 'Alex Circles', + emailAddress: 'circles@chromium.org', + imageUrl: '../../app/theme/avatar_circles.png', + canRemove: true + }, + {name: 'Guest', emailAddress: '', imageUrl: '', canRemove: false} ]; /** * Invoke the getAppsCallback function with a snapshot of the current app * database. */ - function sendGetUsersCallback() - { + function sendGetUsersCallback() { // We don't want to hand out our array directly because the NTP will // assume it owns the array and is free to modify it. For now we make a // one-level deep copy of the array (since cloning the whole thing is @@ -97,7 +91,9 @@ * @return {number} The index in apps for an object with the specified ID. */ function getUserIndex(name) { - var i = indexOfPred(apps, function(e) { return e.name === name;}); + var i = indexOfPred(apps, function(e) { + return e.name === name; + }); if (i == -1) alert('Error: got unexpected App ID'); return i; @@ -226,14 +222,14 @@ if (typeof Element !== 'undefined' && !Element.prototype.hasOwnProperty('classList')) { (function() { - var classListProp = 'classList', - protoProp = 'prototype', - elemCtrProto = Element[protoProp], - objCtr = Object, - strTrim = String[protoProp].trim || function() { + var classListProp = 'classList', protoProp = 'prototype', + elemCtrProto = Element[protoProp], objCtr = Object, + strTrim = String[protoProp].trim || + function() { return this.replace(/^\s+|\s+$/g, ''); }, - arrIndexOf = Array[protoProp].indexOf || function(item) { + arrIndexOf = Array[protoProp].indexOf || + function(item) { for (var i = 0, len = this.length; i < len; i++) { if (i in this && this[i] === item) { return i; @@ -243,29 +239,29 @@ }, // Vendors: please allow content code to instantiate DOMExceptions /** @constructor */ - DOMEx = function(type, message) { + DOMEx = + function(type, message) { this.name = type; this.code = DOMException[type]; this.message = message; }, - checkTokenAndGetIndex = function(classList, token) { + checkTokenAndGetIndex = + function(classList, token) { if (token === '') { throw new DOMEx( - 'SYNTAX_ERR', - 'An invalid or illegal string was specified' - ); + 'SYNTAX_ERR', 'An invalid or illegal string was specified'); } if (/\s/.test(token)) { throw new DOMEx( 'INVALID_CHARACTER_ERR', - 'String contains an invalid character' - ); + 'String contains an invalid character'); } return arrIndexOf.call(classList, token); }, /** @constructor * @extends {Array} */ - ClassList = function(elem) { + ClassList = + function(elem) { var trimmedClasses = strTrim.call(elem.className), classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []; @@ -346,18 +342,15 @@ * @suppress {duplicate} */ Function.prototype.bind = function(selfObj, var_args) { - var slice = [].slice, - args = slice.call(arguments, 1), - self = this, + var slice = [].slice, args = slice.call(arguments, 1), self = this, /** @constructor */ - nop = function() {}, - bound = function() { - return self.apply(this instanceof nop ? this : (selfObj || {}), - args.concat(slice.call(arguments))); + nop = function() {}, bound = function() { + return self.apply( + this instanceof nop ? this : (selfObj || {}), + args.concat(slice.call(arguments))); }; nop.prototype = self.prototype; bound.prototype = new nop(); return bound; }; } -
diff --git a/chrome/browser/resources/supervised_user_internals.js b/chrome/browser/resources/supervised_user_internals.js index de5a370..beb982ac 100644 --- a/chrome/browser/resources/supervised_user_internals.js +++ b/chrome/browser/resources/supervised_user_internals.js
@@ -46,7 +46,9 @@ // Hack: Schedule another refresh after a while. // TODO(treib): Get rid of this once we're properly notified of all // relevant changes. - setTimeout(function() { chrome.send('getBasicInfo'); }, 5000); + setTimeout(function() { + chrome.send('getBasicInfo'); + }, 5000); } function receiveUserSettings(settings) { @@ -62,10 +64,7 @@ // This is not done recursively, values are passed as their JSON // representation. var kvpairs = Object.keys(settings).map(function(key) { - return { - key: key, - value: JSON.stringify(settings[key], null, 2) - }; + return {key: key, value: JSON.stringify(settings[key], null, 2)}; }); jstProcess(new JsEvalContext({settings: kvpairs}), $('user-settings')); @@ -110,7 +109,7 @@ // the scrollbar alone. var shouldScrollDown = isScrolledToBottom(container); - jstProcess(new JsEvalContext({ results: filteringResults }), container); + jstProcess(new JsEvalContext({results: filteringResults}), container); if (shouldScrollDown) scrollToBottom(container); @@ -127,5 +126,5 @@ }; }); -document.addEventListener('DOMContentLoaded', - chrome.supervised_user_internals.initialize); +document.addEventListener( + 'DOMContentLoaded', chrome.supervised_user_internals.initialize);
diff --git a/chrome/browser/resources/sync_file_system_internals/dump_database.js b/chrome/browser/resources/sync_file_system_internals/dump_database.js index 1f0b9f27..95ac9b7 100644 --- a/chrome/browser/resources/sync_file_system_internals/dump_database.js +++ b/chrome/browser/resources/sync_file_system_internals/dump_database.js
@@ -6,85 +6,85 @@ * Handles DumpDatabase tab for syncfs-internals. */ var DumpDatabase = (function() { -'use strict'; + 'use strict'; -var DumpDatabase = {}; + var DumpDatabase = {}; -/** - * Get the database dump. - */ -function getDatabaseDump() { - chrome.send('getDatabaseDump'); -} + /** + * Get the database dump. + */ + function getDatabaseDump() { + chrome.send('getDatabaseDump'); + } -/** - * Creates an element named |elementName| containing the content |text|. - * @param {string} elementName Name of the new element to be created. - * @param {string} text Text to be contained in the new element. - * @return {HTMLElement} The newly created HTML element. - */ -function createElementFromText(elementName, text) { - var element = document.createElement(elementName); - element.appendChild(document.createTextNode(text)); - return element; -} + /** + * Creates an element named |elementName| containing the content |text|. + * @param {string} elementName Name of the new element to be created. + * @param {string} text Text to be contained in the new element. + * @return {HTMLElement} The newly created HTML element. + */ + function createElementFromText(elementName, text) { + var element = document.createElement(elementName); + element.appendChild(document.createTextNode(text)); + return element; + } -/** - * Creates a table by filling |header| and |body|. - * @param {HTMLElement} div The outer container of the table to be renderered. - * @param {HTMLElement} header The table header element to be fillied by - * this function. - * @param {HTMLElement} body The table body element to be filled by this - * function. - * @param {Array} databaseDump List of dictionaries for the database dump. - * The first element must have metadata of the entry. - * The remaining elements must be dictionaries for the database dump, - * which can be iterated using the 'keys' fields given by the first - * element. - */ -function createDatabaseDumpTable(div, header, body, databaseDump) { - var metadata = databaseDump.shift(); - div.appendChild(createElementFromText('h3', metadata['title'])); + /** + * Creates a table by filling |header| and |body|. + * @param {HTMLElement} div The outer container of the table to be renderered. + * @param {HTMLElement} header The table header element to be fillied by + * this function. + * @param {HTMLElement} body The table body element to be filled by this + * function. + * @param {Array} databaseDump List of dictionaries for the database dump. + * The first element must have metadata of the entry. + * The remaining elements must be dictionaries for the database dump, + * which can be iterated using the 'keys' fields given by the first + * element. + */ + function createDatabaseDumpTable(div, header, body, databaseDump) { + var metadata = databaseDump.shift(); + div.appendChild(createElementFromText('h3', metadata['title'])); - var tr = document.createElement('tr'); - for (var i = 0; i < metadata.keys.length; ++i) - tr.appendChild(createElementFromText('td', metadata.keys[i])); - header.appendChild(tr); - - for (var i = 0; i < databaseDump.length; i++) { - var entry = databaseDump[i]; var tr = document.createElement('tr'); - for (var k = 0; k < metadata.keys.length; ++k) - tr.appendChild(createElementFromText('td', entry[metadata.keys[k]])); - body.appendChild(tr); + for (var i = 0; i < metadata.keys.length; ++i) + tr.appendChild(createElementFromText('td', metadata.keys[i])); + header.appendChild(tr); + + for (var i = 0; i < databaseDump.length; i++) { + var entry = databaseDump[i]; + var tr = document.createElement('tr'); + for (var k = 0; k < metadata.keys.length; ++k) + tr.appendChild(createElementFromText('td', entry[metadata.keys[k]])); + body.appendChild(tr); + } } -} -/** - * Handles callback from onGetDatabaseDump. - * @param {Array} databaseDump List of lists for the database dump. - */ -DumpDatabase.onGetDatabaseDump = function(databaseDump) { - var placeholder = $('dump-database-placeholder'); - placeholder.innerHTML = ''; - for (var i = 0; i < databaseDump.length; ++i) { - var div = document.createElement('div'); - var table = document.createElement('table'); - var header = document.createElement('thead'); - var body = document.createElement('tbody'); - createDatabaseDumpTable(div, header, body, databaseDump[i]); - table.appendChild(header); - table.appendChild(body); - div.appendChild(table); - placeholder.appendChild(div); + /** + * Handles callback from onGetDatabaseDump. + * @param {Array} databaseDump List of lists for the database dump. + */ + DumpDatabase.onGetDatabaseDump = function(databaseDump) { + var placeholder = $('dump-database-placeholder'); + placeholder.innerHTML = ''; + for (var i = 0; i < databaseDump.length; ++i) { + var div = document.createElement('div'); + var table = document.createElement('table'); + var header = document.createElement('thead'); + var body = document.createElement('tbody'); + createDatabaseDumpTable(div, header, body, databaseDump[i]); + table.appendChild(header); + table.appendChild(body); + div.appendChild(table); + placeholder.appendChild(div); + } + }; + + function main() { + getDatabaseDump(); + $('refresh-database-dump').addEventListener('click', getDatabaseDump); } -}; -function main() { - getDatabaseDump(); - $('refresh-database-dump').addEventListener('click', getDatabaseDump); -} - -document.addEventListener('DOMContentLoaded', main); -return DumpDatabase; + document.addEventListener('DOMContentLoaded', main); + return DumpDatabase; })();
diff --git a/chrome/browser/resources/sync_file_system_internals/extension_statuses.js b/chrome/browser/resources/sync_file_system_internals/extension_statuses.js index 0b805ae..99c78ba 100644 --- a/chrome/browser/resources/sync_file_system_internals/extension_statuses.js +++ b/chrome/browser/resources/sync_file_system_internals/extension_statuses.js
@@ -6,56 +6,56 @@ * Handles the Extension ID -> SyncStatus tab for syncfs-internals. */ var ExtensionStatuses = (function() { -'use strict'; + 'use strict'; -var ExtensionStatuses = {}; + var ExtensionStatuses = {}; -/** - * Get initial map of extension statuses (pending batch sync, enabled and - * disabled). - */ -function getExtensionStatuses() { - chrome.send('getExtensionStatuses'); -} - -// TODO(calvinlo): Move to helper file so it doesn't need to be duplicated. -/** - * Creates an element named |elementName| containing the content |text|. - * @param {string} elementName Name of the new element to be created. - * @param {string} text Text to be contained in the new element. - * @return {HTMLElement} The newly created HTML element. - */ -function createElementFromText(elementName, text) { - var element = document.createElement(elementName); - element.appendChild(document.createTextNode(text)); - return element; -} - -/** - * Handles callback from onGetExtensionStatuses. - * @param {Array} list of dictionaries containing 'extensionName', - * 'extensionID, 'status'. - */ -ExtensionStatuses.onGetExtensionStatuses = function(extensionStatuses) { - var itemContainer = $('extension-entries'); - itemContainer.textContent = ''; - - for (var i = 0; i < extensionStatuses.length; i++) { - var originEntry = extensionStatuses[i]; - var tr = document.createElement('tr'); - tr.appendChild(createElementFromText('td', originEntry.extensionName)); - tr.appendChild(createElementFromText('td', originEntry.extensionID)); - tr.appendChild(createElementFromText('td', originEntry.status)); - itemContainer.appendChild(tr); + /** + * Get initial map of extension statuses (pending batch sync, enabled and + * disabled). + */ + function getExtensionStatuses() { + chrome.send('getExtensionStatuses'); } -}; -function main() { - getExtensionStatuses(); - $('refresh-extensions-statuses').addEventListener('click', - getExtensionStatuses); -} + // TODO(calvinlo): Move to helper file so it doesn't need to be duplicated. + /** + * Creates an element named |elementName| containing the content |text|. + * @param {string} elementName Name of the new element to be created. + * @param {string} text Text to be contained in the new element. + * @return {HTMLElement} The newly created HTML element. + */ + function createElementFromText(elementName, text) { + var element = document.createElement(elementName); + element.appendChild(document.createTextNode(text)); + return element; + } -document.addEventListener('DOMContentLoaded', main); -return ExtensionStatuses; + /** + * Handles callback from onGetExtensionStatuses. + * @param {Array} list of dictionaries containing 'extensionName', + * 'extensionID, 'status'. + */ + ExtensionStatuses.onGetExtensionStatuses = function(extensionStatuses) { + var itemContainer = $('extension-entries'); + itemContainer.textContent = ''; + + for (var i = 0; i < extensionStatuses.length; i++) { + var originEntry = extensionStatuses[i]; + var tr = document.createElement('tr'); + tr.appendChild(createElementFromText('td', originEntry.extensionName)); + tr.appendChild(createElementFromText('td', originEntry.extensionID)); + tr.appendChild(createElementFromText('td', originEntry.status)); + itemContainer.appendChild(tr); + } + }; + + function main() { + getExtensionStatuses(); + $('refresh-extensions-statuses') + .addEventListener('click', getExtensionStatuses); + } + + document.addEventListener('DOMContentLoaded', main); + return ExtensionStatuses; })();
diff --git a/chrome/browser/resources/sync_file_system_internals/file_metadata.js b/chrome/browser/resources/sync_file_system_internals/file_metadata.js index 11c0e34..cc9eae5 100644 --- a/chrome/browser/resources/sync_file_system_internals/file_metadata.js +++ b/chrome/browser/resources/sync_file_system_internals/file_metadata.js
@@ -6,132 +6,133 @@ * WebUI to monitor File Metadata per Extension ID. */ var FileMetadata = (function() { -'use strict'; + 'use strict'; -var FileMetadata = {}; + var FileMetadata = {}; -/** - * Gets extension data so the select drop down can be filled. - */ -function getExtensions() { - chrome.send('getExtensions'); -} - -/** - * Renders result of getFileMetadata as a table. - * @param {Array} list of dictionaries containing 'extensionName', - * 'extensionID', 'status'. - */ -FileMetadata.onGetExtensions = function(extensionStatuses) { - var select = $('extensions-select'); - - // Record existing drop down extension ID. If it's still there after the - // refresh then keep it as the selected value. - var oldSelectedExtension = getSelectedExtensionId(); - - select.textContent = ''; - for (var i = 0; i < extensionStatuses.length; i++) { - var originEntry = extensionStatuses[i]; - var tr = document.createElement('tr'); - var title = originEntry.extensionName + ' [' + originEntry.status + ']'; - select.options.add(new Option(title, originEntry.extensionID)); - - // If option was the previously only selected, make it selected again. - if (originEntry.extensionID != oldSelectedExtension) - continue; - select.options[select.options.length - 1].selected = true; + /** + * Gets extension data so the select drop down can be filled. + */ + function getExtensions() { + chrome.send('getExtensions'); } - // After drop down has been loaded with options, file metadata can be loaded - getFileMetadata(); -}; + /** + * Renders result of getFileMetadata as a table. + * @param {Array} list of dictionaries containing 'extensionName', + * 'extensionID', 'status'. + */ + FileMetadata.onGetExtensions = function(extensionStatuses) { + var select = $('extensions-select'); -/** - * @return {string} extension ID that's currently selected in drop down box. - */ -function getSelectedExtensionId() { - var dropDown = $('extensions-select').options; - if (dropDown.selectedIndex >= 0) - return dropDown[dropDown.selectedIndex].value; + // Record existing drop down extension ID. If it's still there after the + // refresh then keep it as the selected value. + var oldSelectedExtension = getSelectedExtensionId(); - return null; -} + select.textContent = ''; + for (var i = 0; i < extensionStatuses.length; i++) { + var originEntry = extensionStatuses[i]; + var tr = document.createElement('tr'); + var title = originEntry.extensionName + ' [' + originEntry.status + ']'; + select.options.add(new Option(title, originEntry.extensionID)); -/** - * Get File Metadata depending on which extension is selected from the drop down - * if any. - */ -function getFileMetadata() { - var dropDown = $('extensions-select'); - if (dropDown.options.length === 0) { - $('file-metadata-header').textContent = ''; - $('file-metadata-entries').textContent = 'No file metadata available.'; - return; + // If option was the previously only selected, make it selected again. + if (originEntry.extensionID != oldSelectedExtension) + continue; + select.options[select.options.length - 1].selected = true; + } + + // After drop down has been loaded with options, file metadata can be loaded + getFileMetadata(); + }; + + /** + * @return {string} extension ID that's currently selected in drop down box. + */ + function getSelectedExtensionId() { + var dropDown = $('extensions-select').options; + if (dropDown.selectedIndex >= 0) + return dropDown[dropDown.selectedIndex].value; + + return null; } - var selectedExtensionId = getSelectedExtensionId(); - chrome.send('getFileMetadata', [selectedExtensionId]); -} + /** + * Get File Metadata depending on which extension is selected from the drop + * down if any. + */ + function getFileMetadata() { + var dropDown = $('extensions-select'); + if (dropDown.options.length === 0) { + $('file-metadata-header').textContent = ''; + $('file-metadata-entries').textContent = 'No file metadata available.'; + return; + } -/** - * Renders result of getFileMetadata as a table. - */ -FileMetadata.onGetFileMetadata = function(fileMetadataMap) { - var header = $('file-metadata-header'); - // Only draw the header if it hasn't been drawn yet - if (header.children.length === 0) { - var tr = document.createElement('tr'); - tr.appendChild(createElementFromText('td', 'Type')); - tr.appendChild(createElementFromText('td', 'Status')); - tr.appendChild(createElementFromText('td', 'Path', {width: '250px'})); - tr.appendChild(createElementFromText('td', 'Details')); - header.appendChild(tr); + var selectedExtensionId = getSelectedExtensionId(); + chrome.send('getFileMetadata', [selectedExtensionId]); } - // Add row entries. - var itemContainer = $('file-metadata-entries'); - itemContainer.textContent = ''; - for (var i = 0; i < fileMetadataMap.length; i++) { - var metadatEntry = fileMetadataMap[i]; - var tr = document.createElement('tr'); - tr.appendChild(createFileIconCell(metadatEntry.type)); - tr.appendChild(createElementFromText('td', metadatEntry.status)); - tr.appendChild(createElementFromText('td', metadatEntry.path)); - tr.appendChild(createElementFromDictionary('td', metadatEntry.details)); - itemContainer.appendChild(tr); - } -}; + /** + * Renders result of getFileMetadata as a table. + */ + FileMetadata.onGetFileMetadata = function(fileMetadataMap) { + var header = $('file-metadata-header'); + // Only draw the header if it hasn't been drawn yet + if (header.children.length === 0) { + var tr = document.createElement('tr'); + tr.appendChild(createElementFromText('td', 'Type')); + tr.appendChild(createElementFromText('td', 'Status')); + tr.appendChild(createElementFromText('td', 'Path', {width: '250px'})); + tr.appendChild(createElementFromText('td', 'Details')); + header.appendChild(tr); + } -/** - * @param {string} file type string. - * @return {HTMLElement} TD with file or folder icon depending on type. - */ -function createFileIconCell(type) { - var img = document.createElement('div'); - var lowerType = type.toLowerCase(); - if (lowerType == 'file') { - img.style.content = cr.icon.getImage('chrome://theme/IDR_DEFAULT_FAVICON'); - } else if (lowerType == 'folder') { - img.style.content = cr.icon.getImage('chrome://theme/IDR_FOLDER_CLOSED'); - img.className = 'folder-image'; + // Add row entries. + var itemContainer = $('file-metadata-entries'); + itemContainer.textContent = ''; + for (var i = 0; i < fileMetadataMap.length; i++) { + var metadatEntry = fileMetadataMap[i]; + var tr = document.createElement('tr'); + tr.appendChild(createFileIconCell(metadatEntry.type)); + tr.appendChild(createElementFromText('td', metadatEntry.status)); + tr.appendChild(createElementFromText('td', metadatEntry.path)); + tr.appendChild(createElementFromDictionary('td', metadatEntry.details)); + itemContainer.appendChild(tr); + } + }; + + /** + * @param {string} file type string. + * @return {HTMLElement} TD with file or folder icon depending on type. + */ + function createFileIconCell(type) { + var img = document.createElement('div'); + var lowerType = type.toLowerCase(); + if (lowerType == 'file') { + img.style.content = + cr.icon.getImage('chrome://theme/IDR_DEFAULT_FAVICON'); + } else if (lowerType == 'folder') { + img.style.content = cr.icon.getImage('chrome://theme/IDR_FOLDER_CLOSED'); + img.className = 'folder-image'; + } + + var imgWrapper = document.createElement('div'); + imgWrapper.appendChild(img); + + var td = document.createElement('td'); + td.className = 'file-icon-cell'; + td.appendChild(imgWrapper); + td.appendChild(document.createTextNode(type)); + return td; } - var imgWrapper = document.createElement('div'); - imgWrapper.appendChild(img); + function main() { + getExtensions(); + $('refresh-metadata-button').addEventListener('click', getExtensions); + $('extensions-select').addEventListener('change', getFileMetadata); + } - var td = document.createElement('td'); - td.className = 'file-icon-cell'; - td.appendChild(imgWrapper); - td.appendChild(document.createTextNode(type)); - return td; -} - -function main() { - getExtensions(); - $('refresh-metadata-button').addEventListener('click', getExtensions); - $('extensions-select').addEventListener('change', getFileMetadata); -} - -document.addEventListener('DOMContentLoaded', main); -return FileMetadata; + document.addEventListener('DOMContentLoaded', main); + return FileMetadata; })();
diff --git a/chrome/browser/resources/sync_file_system_internals/sync_service.js b/chrome/browser/resources/sync_file_system_internals/sync_service.js index 299abc57..8772f4c 100644 --- a/chrome/browser/resources/sync_file_system_internals/sync_service.js +++ b/chrome/browser/resources/sync_file_system_internals/sync_service.js
@@ -6,91 +6,91 @@ * WebUI to monitor the Sync File System Service. */ var SyncService = (function() { -'use strict'; + 'use strict'; -var SyncService = {}; + var SyncService = {}; -/** - * Request Sync Service Status. - */ -function getServiceStatus() { - chrome.send('getServiceStatus'); -} - -/** - * Called when service status is initially retrieved or updated via events. - * @param {string} Service status enum as a string. - */ -SyncService.onGetServiceStatus = function(statusString) { - $('service-status').textContent = statusString; -}; - -/** - * Request Google Drive Notification Source. e.g. XMPP or polling. - */ -function getNotificationSource() { - chrome.send('getNotificationSource'); -} - -/** - * Handles callback from getNotificationSource. - * @param {string} Notification source as a string. - */ -SyncService.onGetNotificationSource = function(sourceString) { - $('notification-source').textContent = sourceString; -}; - -// Keeps track of the last log event seen so it's not reprinted. -var lastLogEventId = -1; - -/** - * Request debug log. - */ -function getLog() { - chrome.send('getLog', [lastLogEventId]); -} - -/** - * Clear old logs. - */ -function clearLogs() { - chrome.send('clearLogs'); - $('log-entries').innerHTML = ''; -} - -/** - * Handles callback from getUpdateLog. - * @param {Array} list List of dictionaries containing 'id', 'time', 'logEvent'. - */ -SyncService.onGetLog = function(logEntries) { - var itemContainer = $('log-entries'); - for (var i = 0; i < logEntries.length; i++) { - var logEntry = logEntries[i]; - var tr = document.createElement('tr'); - var error = /ERROR/.test(logEntry.logEvent) ? ' error' : ''; - tr.appendChild(createElementFromText('td', logEntry.time, - {'class': 'log-time'})); - tr.appendChild(createElementFromText('td', logEntry.logEvent, - {'class': 'log-event' + error})); - itemContainer.appendChild(tr); - - lastLogEventId = logEntry.id; + /** + * Request Sync Service Status. + */ + function getServiceStatus() { + chrome.send('getServiceStatus'); } -}; -/** - * Get initial sync service values and set listeners to get updated values. - */ -function main() { - cr.ui.decorate('tabbox', cr.ui.TabBox); - $('clear-log-button').addEventListener('click', clearLogs); - getServiceStatus(); - getNotificationSource(); + /** + * Called when service status is initially retrieved or updated via events. + * @param {string} Service status enum as a string. + */ + SyncService.onGetServiceStatus = function(statusString) { + $('service-status').textContent = statusString; + }; - // TODO: Look for a way to push entries to the page when necessary. - window.setInterval(getLog, 1000); -} + /** + * Request Google Drive Notification Source. e.g. XMPP or polling. + */ + function getNotificationSource() { + chrome.send('getNotificationSource'); + } -document.addEventListener('DOMContentLoaded', main); -return SyncService; + /** + * Handles callback from getNotificationSource. + * @param {string} Notification source as a string. + */ + SyncService.onGetNotificationSource = function(sourceString) { + $('notification-source').textContent = sourceString; + }; + + // Keeps track of the last log event seen so it's not reprinted. + var lastLogEventId = -1; + + /** + * Request debug log. + */ + function getLog() { + chrome.send('getLog', [lastLogEventId]); + } + + /** + * Clear old logs. + */ + function clearLogs() { + chrome.send('clearLogs'); + $('log-entries').innerHTML = ''; + } + + /** + * Handles callback from getUpdateLog. + * @param {Array} list List of dictionaries containing 'id', 'time', 'logEvent'. + */ + SyncService.onGetLog = function(logEntries) { + var itemContainer = $('log-entries'); + for (var i = 0; i < logEntries.length; i++) { + var logEntry = logEntries[i]; + var tr = document.createElement('tr'); + var error = /ERROR/.test(logEntry.logEvent) ? ' error' : ''; + tr.appendChild( + createElementFromText('td', logEntry.time, {'class': 'log-time'})); + tr.appendChild(createElementFromText( + 'td', logEntry.logEvent, {'class': 'log-event' + error})); + itemContainer.appendChild(tr); + + lastLogEventId = logEntry.id; + } + }; + + /** + * Get initial sync service values and set listeners to get updated values. + */ + function main() { + cr.ui.decorate('tabbox', cr.ui.TabBox); + $('clear-log-button').addEventListener('click', clearLogs); + getServiceStatus(); + getNotificationSource(); + + // TODO: Look for a way to push entries to the page when necessary. + window.setInterval(getLog, 1000); + } + + document.addEventListener('DOMContentLoaded', main); + return SyncService; })();
diff --git a/chrome/browser/resources/sync_file_system_internals/task_log.js b/chrome/browser/resources/sync_file_system_internals/task_log.js index 5379754..a0eb22a 100644 --- a/chrome/browser/resources/sync_file_system_internals/task_log.js +++ b/chrome/browser/resources/sync_file_system_internals/task_log.js
@@ -3,56 +3,56 @@ // found in the LICENSE file. var TaskLog = (function() { -'use strict'; + 'use strict'; -var nextTaskLogSeq = 1; -var TaskLog = {}; + var nextTaskLogSeq = 1; + var TaskLog = {}; -function observeTaskLog() { - chrome.send('observeTaskLog'); -} + function observeTaskLog() { + chrome.send('observeTaskLog'); + } -/** - * Handles per-task log event. - * @param {Object} taskLog a dictionary containing 'duration', - * 'task_description', 'result_description' and 'details'. - */ -TaskLog.onTaskLogRecorded = function(taskLog) { - var details = document.createElement('td'); - details.classList.add('task-log-details'); + /** + * Handles per-task log event. + * @param {Object} taskLog a dictionary containing 'duration', + * 'task_description', 'result_description' and 'details'. + */ + TaskLog.onTaskLogRecorded = function(taskLog) { + var details = document.createElement('td'); + details.classList.add('task-log-details'); - var label = document.createElement('label'); - details.appendChild(label); + var label = document.createElement('label'); + details.appendChild(label); - var collapseCheck = document.createElement('input'); - collapseCheck.setAttribute('type', 'checkbox'); - collapseCheck.classList.add('task-log-collapse-check'); - label.appendChild(collapseCheck); + var collapseCheck = document.createElement('input'); + collapseCheck.setAttribute('type', 'checkbox'); + collapseCheck.classList.add('task-log-collapse-check'); + label.appendChild(collapseCheck); - var ul = document.createElement('ul'); - for (var i = 0; i < taskLog.details.length; ++i) - ul.appendChild(createElementFromText('li', taskLog.details[i])); - label.appendChild(ul); + var ul = document.createElement('ul'); + for (var i = 0; i < taskLog.details.length; ++i) + ul.appendChild(createElementFromText('li', taskLog.details[i])); + label.appendChild(ul); - var tr = document.createElement('tr'); - tr.appendChild(createElementFromText( - 'td', taskLog.duration, {'class': 'task-log-duration'})); - tr.appendChild(createElementFromText( - 'td', taskLog.task_description, {'class': 'task-log-description'})); - tr.appendChild(createElementFromText( - 'td', taskLog.result_description, {'class': 'task-log-result'})); - tr.appendChild(details); + var tr = document.createElement('tr'); + tr.appendChild(createElementFromText( + 'td', taskLog.duration, {'class': 'task-log-duration'})); + tr.appendChild(createElementFromText( + 'td', taskLog.task_description, {'class': 'task-log-description'})); + tr.appendChild(createElementFromText( + 'td', taskLog.result_description, {'class': 'task-log-result'})); + tr.appendChild(details); - $('task-log-entries').appendChild(tr); -}; + $('task-log-entries').appendChild(tr); + }; -/** - * Get initial sync service values and set listeners to get updated values. - */ -function main() { - observeTaskLog(); -} + /** + * Get initial sync service values and set listeners to get updated values. + */ + function main() { + observeTaskLog(); + } -document.addEventListener('DOMContentLoaded', main); -return TaskLog; + document.addEventListener('DOMContentLoaded', main); + return TaskLog; })();
diff --git a/chrome/browser/resources/translate_internals/translate_internals.js b/chrome/browser/resources/translate_internals/translate_internals.js index 6e159def..6c33ca4 100644 --- a/chrome/browser/resources/translate_internals/translate_internals.js +++ b/chrome/browser/resources/translate_internals/translate_internals.js
@@ -3,496 +3,498 @@ // found in the LICENSE file. (function() { - 'use strict'; +'use strict'; - cr.define('cr.translateInternals', function() { +cr.define('cr.translateInternals', function() { - var detectionLogs = []; - - /** - * Initializes UI and sends a message to the browser for - * initialization. - */ - function initialize() { - cr.ui.decorate('tabbox', cr.ui.TabBox); - chrome.send('requestInfo'); - - var button = $('detection-logs-dump'); - button.addEventListener('click', onDetectionLogsDump); - - var tabpanelNodeList = document.getElementsByTagName('tabpanel'); - var tabpanels = Array.prototype.slice.call(tabpanelNodeList, 0); - var tabpanelIds = tabpanels.map(function(tab) { - return tab.id; - }); - - var tabNodeList = document.getElementsByTagName('tab'); - var tabs = Array.prototype.slice.call(tabNodeList, 0); - tabs.forEach(function(tab) { - tab.onclick = function(e) { - var tabbox = document.querySelector('tabbox'); - var tabpanel = tabpanels[tabbox.selectedIndex]; - var hash = tabpanel.id.match(/(?:^tabpanel-)(.+)/)[1]; - window.location.hash = hash; - }; - }); - - var activateTabByHash = function() { - var hash = window.location.hash; - - // Remove the first character '#'. - hash = hash.substring(1); - - var id = 'tabpanel-' + hash; - if (tabpanelIds.indexOf(id) == -1) - return; - - $(id).selected = true; - }; - - window.onhashchange = activateTabByHash; - activateTabByHash(); - } - - /* - * Creates a button to dismiss an item. - * - * @param {Function} func Callback called when the button is clicked. - */ - function createDismissingButton(func) { - var button = document.createElement('button'); - button.textContent = 'X'; - button.classList.add('dismissing'); - button.addEventListener('click', function(e) { - e.preventDefault(); - func(); - }, false); - return button; - } - - /** - * Creates a new LI element with a button to dismiss the item. - * - * @param {string} text The lable of the LI element. - * @param {Function} func Callback called when the button is clicked. - */ - function createLIWithDismissingButton(text, func) { - var span = document.createElement('span'); - span.textContent = text; - - var li = document.createElement('li'); - li.appendChild(span); - li.appendChild(createDismissingButton(func)); - return li; - } - - /** - * Formats the language name to a human-readable text. For example, if - * |langCode| is 'en', this may return 'en (English)'. - * - * @param {string} langCode ISO 639 language code. - * @return {string} The formatted string. - */ - function formatLanguageCode(langCode) { - var key = 'language-' + langCode; - if (loadTimeData.valueExists(key)) { - var langName = loadTimeData.getString(key); - return langCode + ' (' + langName + ')'; - } - - return langCode; - } - - /** - * Formats the error type to a human-readable text. - * - * @param {string} error Translation error type from the browser. - * @return {string} The formatted string. - */ - function formatTranslateErrorsType(error) { - // This list is from chrome/common/translate/translate_errors.h. - // If this header file is updated, the below list also should be updated. - var errorStrs = { - 0: 'None', - 1: 'Network', - 2: 'Initialization Error', - 3: 'Unknown Language', - 4: 'Unsupported Language', - 5: 'Identical Languages', - 6: 'Translation Error', - 7: 'Translation Timeout', - 8: 'Unexpected Script Error', - 9: 'Bad Origin', - 10: 'Script Load Error', - }; - - if (error < 0 || errorStrs.length <= error) { - console.error('Invalid error code:', error); - return 'Invalid Error Code'; - } - return errorStrs[error]; - } - - /** - * Handles the message of 'prefsUpdated' from the browser. - * - * @param {Object} detail the object which represents pref values. - */ - function onPrefsUpdated(detail) { - var ul; - - ul = document.querySelector('#prefs-blocked-languages ul'); - ul.innerHTML = ''; - - if ('translate_blocked_languages' in detail) { - var langs = detail['translate_blocked_languages']; - - langs.forEach(function(langCode) { - var text = formatLanguageCode(langCode); - - var li = createLIWithDismissingButton(text, function() { - chrome.send('removePrefItem', - ['blocked_languages', langCode]); - }); - ul.appendChild(li); - }); - } - - ul = document.querySelector('#prefs-language-blacklist ul'); - ul.innerHTML = ''; - - if ('translate_language_blacklist' in detail) { - var langs = detail['translate_language_blacklist']; - - langs.forEach(function(langCode) { - var text = formatLanguageCode(langCode); - - var li = createLIWithDismissingButton(text, function() { - chrome.send('removePrefItem', - ['language_blacklist', langCode]); - }); - ul.appendChild(li); - }); - } - - ul = document.querySelector('#prefs-site-blacklist ul'); - ul.innerHTML = ''; - - if ('translate_site_blacklist' in detail) { - var sites = detail['translate_site_blacklist']; - - sites.forEach(function(site) { - var li = createLIWithDismissingButton(site, function() { - chrome.send('removePrefItem', ['site_blacklist', site]); - }); - ul.appendChild(li); - }); - } - - ul = document.querySelector('#prefs-whitelists ul'); - ul.innerHTML = ''; - - if ('translate_whitelists' in detail) { - var pairs = detail['translate_whitelists']; - - Object.keys(pairs).forEach(function(fromLangCode) { - var toLangCode = pairs[fromLangCode]; - var text = formatLanguageCode(fromLangCode) + ' \u2192 ' + - formatLanguageCode(toLangCode); - - var li = createLIWithDismissingButton(text, function() { - chrome.send('removePrefItem', - ['whitelists', fromLangCode, toLangCode]); - }); - ul.appendChild(li); - }); - } - - var p = $('prefs-too-often-denied'); - p.classList.toggle('prefs-setting-disabled', - !detail['translate_too_often_denied']); - p.appendChild(createDismissingButton( - chrome.send.bind(null, 'removePrefItem', ['too_often_denied']))); - - p = document.querySelector('#prefs-dump p'); - var content = JSON.stringify(detail, null, 2); - p.textContent = content; - } - - /** - * Handles the message of 'supportedLanguagesUpdated' from the browser. - * - * @param {Object} details the object which represents the supported - * languages by the Translate server. - */ - function onSupportedLanguagesUpdated(details) { - var span = - $('prefs-supported-languages-last-updated').querySelector('span'); - span.textContent = formatDate(new Date(details['last_updated'])); - - var ul = $('prefs-supported-languages-languages'); - ul.innerHTML = ''; - var languages = details['languages']; - for (var i = 0; i < languages.length; i++) { - var language = languages[i]; - var li = document.createElement('li'); - - var text = formatLanguageCode(language); - li.innerText = text; - - ul.appendChild(li); - } - } - - /** - * Handles the message of 'countryUpdated' from the browser. - * - * @param {Object} details the object containing the country - * information. - */ - function onCountryUpdated(details) { - var p; - p = $('country-override'); - - p.innerHTML = ''; - - if ('country' in details) { - var country = details['country']; - - var h2 = $('override-variations-country'); - h2.title = ( - 'Changing this value will override the permanent country stored ' + - 'by variations. Normally, this value gets automatically updated ' + - 'with a new value received from the variations server when ' + - 'Chrome is updated.'); - - var input = document.createElement('input'); - input.type = 'text'; - input.value = country; - - var button = document.createElement('button'); - button.textContent = 'update'; - button.addEventListener('click', function() { - chrome.send('overrideCountry', [input.value]); - }, false); - p.appendChild(input); - p.appendChild(document.createElement('br')); - p.appendChild(button); - - if ('update' in details && details['update']) { - var div1 = document.createElement('div'); - div1.textContent = 'Permanent stored country updated.'; - var div2 = document.createElement('div'); - div2.textContent = ('You will need to restart your browser ' + - 'for the changes to take effect.'); - p.appendChild(div1); - p.appendChild(div2); - } - } else { - p.textContent = 'Could not load country info from Variations.'; - } - } - - /** - * Adds '0's to |number| as a string. |width| is length of the string - * including '0's. - * - * @param {string} number The number to be converted into a string. - * @param {number} width The width of the returned string. - * @return {string} The formatted string. - */ - function padWithZeros(number, width) { - var numberStr = number.toString(); - var restWidth = width - numberStr.length; - if (restWidth <= 0) - return numberStr; - - return Array(restWidth + 1).join('0') + numberStr; - } - - /** - * Formats |date| as a Date object into a string. The format is like - * '2006-01-02 15:04:05'. - * - * @param {Date} date Date to be formatted. - * @return {string} The formatted string. - */ - function formatDate(date) { - var year = date.getFullYear(); - var month = date.getMonth() + 1; - var day = date.getDate(); - var hour = date.getHours(); - var minute = date.getMinutes(); - var second = date.getSeconds(); - - var yearStr = padWithZeros(year, 4); - var monthStr = padWithZeros(month, 2); - var dayStr = padWithZeros(day, 2); - var hourStr = padWithZeros(hour, 2); - var minuteStr = padWithZeros(minute, 2); - var secondStr = padWithZeros(second, 2); - - var str = yearStr + '-' + monthStr + '-' + dayStr + ' ' + - hourStr + ':' + minuteStr + ':' + secondStr; - - return str; - } - - /** - * Appends a new TD element to the specified element. - * - * @param {string} parent The element to which a new TD element is appended. - * @param {string} content The text content of the element. - * @param {string} className The class name of the element. - */ - function appendTD(parent, content, className) { - var td = document.createElement('td'); - td.textContent = content; - td.className = className; - parent.appendChild(td); - } - - /** - * Handles the message of 'languageDetectionInfoAdded' from the - * browser. - * - * @param {Object} detail The object which represents the logs. - */ - function onLanguageDetectionInfoAdded(detail) { - detectionLogs.push(detail); - - var tr = document.createElement('tr'); - - appendTD(tr, formatDate(new Date(detail['time'])), 'detection-logs-time'); - appendTD(tr, detail['url'], 'detection-logs-url'); - appendTD(tr, formatLanguageCode(detail['content_language']), - 'detection-logs-content-language'); - appendTD(tr, formatLanguageCode(detail['cld_language']), - 'detection-logs-cld-language'); - appendTD(tr, detail['is_cld_reliable'], 'detection-logs-is-cld-reliable'); - appendTD(tr, detail['has_notranslate'], 'detection-logs-has-notranslate'); - appendTD(tr, formatLanguageCode(detail['html_root_language']), - 'detection-logs-html-root-language'); - appendTD(tr, formatLanguageCode(detail['adopted_language']), - 'detection-logs-adopted-language'); - appendTD(tr, formatLanguageCode(detail['content']), - 'detection-logs-content'); - - // TD (and TR) can't use the CSS property 'max-height', so DIV - // in the content is needed. - var contentTD = tr.querySelector('.detection-logs-content'); - var div = document.createElement('div'); - div.textContent = contentTD.textContent; - contentTD.textContent = ''; - contentTD.appendChild(div); - - var tabpanel = $('tabpanel-detection-logs'); - var tbody = tabpanel.getElementsByTagName('tbody')[0]; - tbody.appendChild(tr); - } - - /** - * Handles the message of 'translateErrorDetailsAdded' from the - * browser. - * - * @param {Object} details The object which represents the logs. - */ - function onTranslateErrorDetailsAdded(details) { - var tr = document.createElement('tr'); - - appendTD(tr, formatDate(new Date(details['time'])), 'error-logs-time'); - appendTD(tr, details['url'], 'error-logs-url'); - appendTD( - tr, - details['error'] + ': ' + formatTranslateErrorsType(details['error']), - 'error-logs-error'); - - var tabpanel = $('tabpanel-error-logs'); - var tbody = tabpanel.getElementsByTagName('tbody')[0]; - tbody.appendChild(tr); - } - - /** - * Handles the message of 'translateEventDetailsAdded' from the browser. - * - * @param {Object} details The object which contains event information. - */ - function onTranslateEventDetailsAdded(details) { - var tr = document.createElement('tr'); - appendTD(tr, formatDate(new Date(details['time'])), 'event-logs-time'); - appendTD(tr, details['filename'] + ': ' + details['line'], - 'event-logs-place'); - appendTD(tr, details['message'], 'event-logs-message'); - - var tbody = $('tabpanel-event-logs').getElementsByTagName('tbody')[0]; - tbody.appendChild(tr); - } - - /** - * The callback entry point from the browser. This function will be - * called by the browser. - * - * @param {string} message The name of the sent message. - * @param {Object} details The argument of the sent message. - */ - function messageHandler(message, details) { - switch (message) { - case 'languageDetectionInfoAdded': - onLanguageDetectionInfoAdded(details); - break; - case 'prefsUpdated': - onPrefsUpdated(details); - break; - case 'supportedLanguagesUpdated': - onSupportedLanguagesUpdated(details); - break; - case 'countryUpdated': - onCountryUpdated(details); - break; - case 'translateErrorDetailsAdded': - onTranslateErrorDetailsAdded(details); - break; - case 'translateEventDetailsAdded': - onTranslateEventDetailsAdded(details); - break; - default: - console.error('Unknown message:', message); - break; - } - } - - /** - * The callback of button#detetion-logs-dump. - */ - function onDetectionLogsDump() { - var data = JSON.stringify(detectionLogs); - var blob = new Blob([data], {'type': 'text/json'}); - var url = URL.createObjectURL(blob); - var filename = 'translate_internals_detect_logs_dump.json'; - - var a = document.createElement('a'); - a.setAttribute('href', url); - a.setAttribute('download', filename); - - var event = document.createEvent('MouseEvent'); - event.initMouseEvent('click', true, true, window, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, null); - a.dispatchEvent(event); - } - - return { - initialize: initialize, - messageHandler: messageHandler, - }; - }); + var detectionLogs = []; /** - * The entry point of the UI. + * Initializes UI and sends a message to the browser for + * initialization. */ - function main() { - cr.doc.addEventListener('DOMContentLoaded', - cr.translateInternals.initialize); + function initialize() { + cr.ui.decorate('tabbox', cr.ui.TabBox); + chrome.send('requestInfo'); + + var button = $('detection-logs-dump'); + button.addEventListener('click', onDetectionLogsDump); + + var tabpanelNodeList = document.getElementsByTagName('tabpanel'); + var tabpanels = Array.prototype.slice.call(tabpanelNodeList, 0); + var tabpanelIds = tabpanels.map(function(tab) { + return tab.id; + }); + + var tabNodeList = document.getElementsByTagName('tab'); + var tabs = Array.prototype.slice.call(tabNodeList, 0); + tabs.forEach(function(tab) { + tab.onclick = function(e) { + var tabbox = document.querySelector('tabbox'); + var tabpanel = tabpanels[tabbox.selectedIndex]; + var hash = tabpanel.id.match(/(?:^tabpanel-)(.+)/)[1]; + window.location.hash = hash; + }; + }); + + var activateTabByHash = function() { + var hash = window.location.hash; + + // Remove the first character '#'. + hash = hash.substring(1); + + var id = 'tabpanel-' + hash; + if (tabpanelIds.indexOf(id) == -1) + return; + + $(id).selected = true; + }; + + window.onhashchange = activateTabByHash; + activateTabByHash(); } - main(); + /* + * Creates a button to dismiss an item. + * + * @param {Function} func Callback called when the button is clicked. + */ + function createDismissingButton(func) { + var button = document.createElement('button'); + button.textContent = 'X'; + button.classList.add('dismissing'); + button.addEventListener('click', function(e) { + e.preventDefault(); + func(); + }, false); + return button; + } + + /** + * Creates a new LI element with a button to dismiss the item. + * + * @param {string} text The lable of the LI element. + * @param {Function} func Callback called when the button is clicked. + */ + function createLIWithDismissingButton(text, func) { + var span = document.createElement('span'); + span.textContent = text; + + var li = document.createElement('li'); + li.appendChild(span); + li.appendChild(createDismissingButton(func)); + return li; + } + + /** + * Formats the language name to a human-readable text. For example, if + * |langCode| is 'en', this may return 'en (English)'. + * + * @param {string} langCode ISO 639 language code. + * @return {string} The formatted string. + */ + function formatLanguageCode(langCode) { + var key = 'language-' + langCode; + if (loadTimeData.valueExists(key)) { + var langName = loadTimeData.getString(key); + return langCode + ' (' + langName + ')'; + } + + return langCode; + } + + /** + * Formats the error type to a human-readable text. + * + * @param {string} error Translation error type from the browser. + * @return {string} The formatted string. + */ + function formatTranslateErrorsType(error) { + // This list is from chrome/common/translate/translate_errors.h. + // If this header file is updated, the below list also should be updated. + var errorStrs = { + 0: 'None', + 1: 'Network', + 2: 'Initialization Error', + 3: 'Unknown Language', + 4: 'Unsupported Language', + 5: 'Identical Languages', + 6: 'Translation Error', + 7: 'Translation Timeout', + 8: 'Unexpected Script Error', + 9: 'Bad Origin', + 10: 'Script Load Error', + }; + + if (error < 0 || errorStrs.length <= error) { + console.error('Invalid error code:', error); + return 'Invalid Error Code'; + } + return errorStrs[error]; + } + + /** + * Handles the message of 'prefsUpdated' from the browser. + * + * @param {Object} detail the object which represents pref values. + */ + function onPrefsUpdated(detail) { + var ul; + + ul = document.querySelector('#prefs-blocked-languages ul'); + ul.innerHTML = ''; + + if ('translate_blocked_languages' in detail) { + var langs = detail['translate_blocked_languages']; + + langs.forEach(function(langCode) { + var text = formatLanguageCode(langCode); + + var li = createLIWithDismissingButton(text, function() { + chrome.send('removePrefItem', ['blocked_languages', langCode]); + }); + ul.appendChild(li); + }); + } + + ul = document.querySelector('#prefs-language-blacklist ul'); + ul.innerHTML = ''; + + if ('translate_language_blacklist' in detail) { + var langs = detail['translate_language_blacklist']; + + langs.forEach(function(langCode) { + var text = formatLanguageCode(langCode); + + var li = createLIWithDismissingButton(text, function() { + chrome.send('removePrefItem', ['language_blacklist', langCode]); + }); + ul.appendChild(li); + }); + } + + ul = document.querySelector('#prefs-site-blacklist ul'); + ul.innerHTML = ''; + + if ('translate_site_blacklist' in detail) { + var sites = detail['translate_site_blacklist']; + + sites.forEach(function(site) { + var li = createLIWithDismissingButton(site, function() { + chrome.send('removePrefItem', ['site_blacklist', site]); + }); + ul.appendChild(li); + }); + } + + ul = document.querySelector('#prefs-whitelists ul'); + ul.innerHTML = ''; + + if ('translate_whitelists' in detail) { + var pairs = detail['translate_whitelists']; + + Object.keys(pairs).forEach(function(fromLangCode) { + var toLangCode = pairs[fromLangCode]; + var text = formatLanguageCode(fromLangCode) + ' \u2192 ' + + formatLanguageCode(toLangCode); + + var li = createLIWithDismissingButton(text, function() { + chrome.send( + 'removePrefItem', ['whitelists', fromLangCode, toLangCode]); + }); + ul.appendChild(li); + }); + } + + var p = $('prefs-too-often-denied'); + p.classList.toggle( + 'prefs-setting-disabled', !detail['translate_too_often_denied']); + p.appendChild(createDismissingButton( + chrome.send.bind(null, 'removePrefItem', ['too_often_denied']))); + + p = document.querySelector('#prefs-dump p'); + var content = JSON.stringify(detail, null, 2); + p.textContent = content; + } + + /** + * Handles the message of 'supportedLanguagesUpdated' from the browser. + * + * @param {Object} details the object which represents the supported + * languages by the Translate server. + */ + function onSupportedLanguagesUpdated(details) { + var span = + $('prefs-supported-languages-last-updated').querySelector('span'); + span.textContent = formatDate(new Date(details['last_updated'])); + + var ul = $('prefs-supported-languages-languages'); + ul.innerHTML = ''; + var languages = details['languages']; + for (var i = 0; i < languages.length; i++) { + var language = languages[i]; + var li = document.createElement('li'); + + var text = formatLanguageCode(language); + li.innerText = text; + + ul.appendChild(li); + } + } + + /** + * Handles the message of 'countryUpdated' from the browser. + * + * @param {Object} details the object containing the country + * information. + */ + function onCountryUpdated(details) { + var p; + p = $('country-override'); + + p.innerHTML = ''; + + if ('country' in details) { + var country = details['country']; + + var h2 = $('override-variations-country'); + h2.title = + ('Changing this value will override the permanent country stored ' + + 'by variations. Normally, this value gets automatically updated ' + + 'with a new value received from the variations server when ' + + 'Chrome is updated.'); + + var input = document.createElement('input'); + input.type = 'text'; + input.value = country; + + var button = document.createElement('button'); + button.textContent = 'update'; + button.addEventListener('click', function() { + chrome.send('overrideCountry', [input.value]); + }, false); + p.appendChild(input); + p.appendChild(document.createElement('br')); + p.appendChild(button); + + if ('update' in details && details['update']) { + var div1 = document.createElement('div'); + div1.textContent = 'Permanent stored country updated.'; + var div2 = document.createElement('div'); + div2.textContent = + ('You will need to restart your browser ' + + 'for the changes to take effect.'); + p.appendChild(div1); + p.appendChild(div2); + } + } else { + p.textContent = 'Could not load country info from Variations.'; + } + } + + /** + * Adds '0's to |number| as a string. |width| is length of the string + * including '0's. + * + * @param {string} number The number to be converted into a string. + * @param {number} width The width of the returned string. + * @return {string} The formatted string. + */ + function padWithZeros(number, width) { + var numberStr = number.toString(); + var restWidth = width - numberStr.length; + if (restWidth <= 0) + return numberStr; + + return Array(restWidth + 1).join('0') + numberStr; + } + + /** + * Formats |date| as a Date object into a string. The format is like + * '2006-01-02 15:04:05'. + * + * @param {Date} date Date to be formatted. + * @return {string} The formatted string. + */ + function formatDate(date) { + var year = date.getFullYear(); + var month = date.getMonth() + 1; + var day = date.getDate(); + var hour = date.getHours(); + var minute = date.getMinutes(); + var second = date.getSeconds(); + + var yearStr = padWithZeros(year, 4); + var monthStr = padWithZeros(month, 2); + var dayStr = padWithZeros(day, 2); + var hourStr = padWithZeros(hour, 2); + var minuteStr = padWithZeros(minute, 2); + var secondStr = padWithZeros(second, 2); + + var str = yearStr + '-' + monthStr + '-' + dayStr + ' ' + hourStr + ':' + + minuteStr + ':' + secondStr; + + return str; + } + + /** + * Appends a new TD element to the specified element. + * + * @param {string} parent The element to which a new TD element is appended. + * @param {string} content The text content of the element. + * @param {string} className The class name of the element. + */ + function appendTD(parent, content, className) { + var td = document.createElement('td'); + td.textContent = content; + td.className = className; + parent.appendChild(td); + } + + /** + * Handles the message of 'languageDetectionInfoAdded' from the + * browser. + * + * @param {Object} detail The object which represents the logs. + */ + function onLanguageDetectionInfoAdded(detail) { + detectionLogs.push(detail); + + var tr = document.createElement('tr'); + + appendTD(tr, formatDate(new Date(detail['time'])), 'detection-logs-time'); + appendTD(tr, detail['url'], 'detection-logs-url'); + appendTD( + tr, formatLanguageCode(detail['content_language']), + 'detection-logs-content-language'); + appendTD( + tr, formatLanguageCode(detail['cld_language']), + 'detection-logs-cld-language'); + appendTD(tr, detail['is_cld_reliable'], 'detection-logs-is-cld-reliable'); + appendTD(tr, detail['has_notranslate'], 'detection-logs-has-notranslate'); + appendTD( + tr, formatLanguageCode(detail['html_root_language']), + 'detection-logs-html-root-language'); + appendTD( + tr, formatLanguageCode(detail['adopted_language']), + 'detection-logs-adopted-language'); + appendTD( + tr, formatLanguageCode(detail['content']), 'detection-logs-content'); + + // TD (and TR) can't use the CSS property 'max-height', so DIV + // in the content is needed. + var contentTD = tr.querySelector('.detection-logs-content'); + var div = document.createElement('div'); + div.textContent = contentTD.textContent; + contentTD.textContent = ''; + contentTD.appendChild(div); + + var tabpanel = $('tabpanel-detection-logs'); + var tbody = tabpanel.getElementsByTagName('tbody')[0]; + tbody.appendChild(tr); + } + + /** + * Handles the message of 'translateErrorDetailsAdded' from the + * browser. + * + * @param {Object} details The object which represents the logs. + */ + function onTranslateErrorDetailsAdded(details) { + var tr = document.createElement('tr'); + + appendTD(tr, formatDate(new Date(details['time'])), 'error-logs-time'); + appendTD(tr, details['url'], 'error-logs-url'); + appendTD( + tr, + details['error'] + ': ' + formatTranslateErrorsType(details['error']), + 'error-logs-error'); + + var tabpanel = $('tabpanel-error-logs'); + var tbody = tabpanel.getElementsByTagName('tbody')[0]; + tbody.appendChild(tr); + } + + /** + * Handles the message of 'translateEventDetailsAdded' from the browser. + * + * @param {Object} details The object which contains event information. + */ + function onTranslateEventDetailsAdded(details) { + var tr = document.createElement('tr'); + appendTD(tr, formatDate(new Date(details['time'])), 'event-logs-time'); + appendTD( + tr, details['filename'] + ': ' + details['line'], 'event-logs-place'); + appendTD(tr, details['message'], 'event-logs-message'); + + var tbody = $('tabpanel-event-logs').getElementsByTagName('tbody')[0]; + tbody.appendChild(tr); + } + + /** + * The callback entry point from the browser. This function will be + * called by the browser. + * + * @param {string} message The name of the sent message. + * @param {Object} details The argument of the sent message. + */ + function messageHandler(message, details) { + switch (message) { + case 'languageDetectionInfoAdded': + onLanguageDetectionInfoAdded(details); + break; + case 'prefsUpdated': + onPrefsUpdated(details); + break; + case 'supportedLanguagesUpdated': + onSupportedLanguagesUpdated(details); + break; + case 'countryUpdated': + onCountryUpdated(details); + break; + case 'translateErrorDetailsAdded': + onTranslateErrorDetailsAdded(details); + break; + case 'translateEventDetailsAdded': + onTranslateEventDetailsAdded(details); + break; + default: + console.error('Unknown message:', message); + break; + } + } + + /** + * The callback of button#detetion-logs-dump. + */ + function onDetectionLogsDump() { + var data = JSON.stringify(detectionLogs); + var blob = new Blob([data], {'type': 'text/json'}); + var url = URL.createObjectURL(blob); + var filename = 'translate_internals_detect_logs_dump.json'; + + var a = document.createElement('a'); + a.setAttribute('href', url); + a.setAttribute('download', filename); + + var event = document.createEvent('MouseEvent'); + event.initMouseEvent( + 'click', true, true, window, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, null); + a.dispatchEvent(event); + } + + return { + initialize: initialize, + messageHandler: messageHandler, + }; +}); + +/** + * The entry point of the UI. + */ +function main() { + cr.doc.addEventListener('DOMContentLoaded', cr.translateInternals.initialize); +} + +main(); })();
diff --git a/chrome/browser/resources/usb_internals/usb_internals.js b/chrome/browser/resources/usb_internals/usb_internals.js index 889706e..1b324a4d 100644 --- a/chrome/browser/resources/usb_internals/usb_internals.js +++ b/chrome/browser/resources/usb_internals/usb_internals.js
@@ -7,70 +7,71 @@ */ (function() { - // Connection to the UsbInternalsPageHandler instance running in the browser - // process. - let pageHandler = null; +// Connection to the UsbInternalsPageHandler instance running in the browser +// process. +let pageHandler = null; - function refreshDeviceList() { - pageHandler.getTestDevices().then(function(response) { - let tableBody = $('test-device-list'); - tableBody.innerHTML = ''; - for (let device of response.devices) { - let row = document.createElement('tr'); - let name = document.createElement('td'); - let serialNumber = document.createElement('td'); - let landingPage = document.createElement('td'); - let remove = document.createElement('td'); - let removeButton = document.createElement('button'); - name.textContent = device.name; - serialNumber.textContent = device.serial_number; - landingPage.textContent = device.landing_page.url; - removeButton.addEventListener('click', function() { - pageHandler.removeDeviceForTesting(device.guid) - .then(refreshDeviceList); - }); - removeButton.textContent = 'Remove'; - row.appendChild(name); - row.appendChild(serialNumber); - row.appendChild(landingPage); - remove.appendChild(removeButton); - row.appendChild(remove); - tableBody.appendChild(row); - } - }); - } - - function addTestDevice(event) { - pageHandler.addDeviceForTesting( - $('test-device-name').value, - $('test-device-serial').value, - $('test-device-landing-page').value).then(function(response) { - if (response.success) - refreshDeviceList(); - $('add-test-device-result').textContent = response.message; - $('add-test-device-result').className = - response.success ? 'action-success' : 'action-failure'; - }); - event.preventDefault(); - } - - function initializeProxies() { - return importModules([ - 'chrome/browser/ui/webui/usb_internals/usb_internals.mojom', - 'content/public/renderer/frame_interfaces', - ]).then(function(modules) { - let mojom = modules[0]; - let frameInterfaces = modules[1]; - - pageHandler = new mojom.UsbInternalsPageHandlerPtr( - frameInterfaces.getInterface(mojom.UsbInternalsPageHandler.name)); - }); - } - - document.addEventListener('DOMContentLoaded', function() { - initializeProxies().then(function() { - $('add-test-device-form').addEventListener('submit', addTestDevice); - refreshDeviceList(); - }); +function refreshDeviceList() { + pageHandler.getTestDevices().then(function(response) { + let tableBody = $('test-device-list'); + tableBody.innerHTML = ''; + for (let device of response.devices) { + let row = document.createElement('tr'); + let name = document.createElement('td'); + let serialNumber = document.createElement('td'); + let landingPage = document.createElement('td'); + let remove = document.createElement('td'); + let removeButton = document.createElement('button'); + name.textContent = device.name; + serialNumber.textContent = device.serial_number; + landingPage.textContent = device.landing_page.url; + removeButton.addEventListener('click', function() { + pageHandler.removeDeviceForTesting(device.guid).then(refreshDeviceList); + }); + removeButton.textContent = 'Remove'; + row.appendChild(name); + row.appendChild(serialNumber); + row.appendChild(landingPage); + remove.appendChild(removeButton); + row.appendChild(remove); + tableBody.appendChild(row); + } }); +} + +function addTestDevice(event) { + pageHandler + .addDeviceForTesting( + $('test-device-name').value, $('test-device-serial').value, + $('test-device-landing-page').value) + .then(function(response) { + if (response.success) + refreshDeviceList(); + $('add-test-device-result').textContent = response.message; + $('add-test-device-result').className = + response.success ? 'action-success' : 'action-failure'; + }); + event.preventDefault(); +} + +function initializeProxies() { + return importModules([ + 'chrome/browser/ui/webui/usb_internals/usb_internals.mojom', + 'content/public/renderer/frame_interfaces', + ]) + .then(function(modules) { + let mojom = modules[0]; + let frameInterfaces = modules[1]; + + pageHandler = new mojom.UsbInternalsPageHandlerPtr( + frameInterfaces.getInterface(mojom.UsbInternalsPageHandler.name)); + }); +} + +document.addEventListener('DOMContentLoaded', function() { + initializeProxies().then(function() { + $('add-test-device-form').addEventListener('submit', addTestDevice); + refreshDeviceList(); + }); +}); })();
diff --git a/chrome/browser/resources/user_actions/user_actions.js b/chrome/browser/resources/user_actions/user_actions.js index 0064d66..4b884d3 100644 --- a/chrome/browser/resources/user_actions/user_actions.js +++ b/chrome/browser/resources/user_actions/user_actions.js
@@ -32,7 +32,5 @@ table.appendChild(tr); } - return { - observeUserAction: observeUserAction - }; + return {observeUserAction: observeUserAction}; });
diff --git a/chrome/browser/resources/webapks/about_webapks.js b/chrome/browser/resources/webapks/about_webapks.js index 9d5fb8f..72f4b9b 100644 --- a/chrome/browser/resources/webapks/about_webapks.js +++ b/chrome/browser/resources/webapks/about_webapks.js
@@ -81,8 +81,8 @@ addWebApkField(webApkList, 'Package name: ', webApkInfo.packageName); addWebApkField( - webApkList, 'Shell APK version: ', "" + webApkInfo.shellApkVersion); - addWebApkField(webApkList, 'Version code: ', "" + webApkInfo.versionCode); + webApkList, 'Shell APK version: ', '' + webApkInfo.shellApkVersion); + addWebApkField(webApkList, 'Version code: ', '' + webApkInfo.versionCode); addWebApkField(webApkList, 'URI: ', webApkInfo.uri); addWebApkField(webApkList, 'Scope: ', webApkInfo.scope); addWebApkField(webApkList, 'Manifest URL: ', webApkInfo.manifestUrl);
diff --git a/chrome/browser/resources/welcome/welcome.js b/chrome/browser/resources/welcome/welcome.js index 72569810..fbfcfd4 100644 --- a/chrome/browser/resources/welcome/welcome.js +++ b/chrome/browser/resources/welcome/welcome.js
@@ -20,18 +20,18 @@ var logo = document.querySelector('.logo-icon'); logo.onclick = function(e) { - logo.animate({ - transform: ['none', 'rotate(-10turn)'], - }, /** @type {!KeyframeEffectOptions} */({ - duration: 500, - easing: 'cubic-bezier(1, 0, 0, 1)', - })); + logo.animate( + { + transform: ['none', 'rotate(-10turn)'], + }, + /** @type {!KeyframeEffectOptions} */ ({ + duration: 500, + easing: 'cubic-bezier(1, 0, 0, 1)', + })); }; } - return { - initialize: initialize - }; + return {initialize: initialize}; }); document.addEventListener('DOMContentLoaded', welcome.initialize);
diff --git a/chrome/browser/resources/welcome/win10/inline.js b/chrome/browser/resources/welcome/win10/inline.js index bef49ae4..df67df5 100644 --- a/chrome/browser/resources/welcome/win10/inline.js +++ b/chrome/browser/resources/welcome/win10/inline.js
@@ -16,7 +16,7 @@ // TODO(pmonette): Remove these checks when they are no longer needed. /** @const */ var VARIANT_KEY = 'variant'; - var VariantTypeMap = { 'defaultonly': false, 'combined': true }; + var VariantTypeMap = {'defaultonly': false, 'combined': true}; var params = new URLSearchParams(location.search.slice(1)); if (params.has(VARIANT_KEY) && params.get(VARIANT_KEY) in VariantTypeMap) this.isCombined = VariantTypeMap[params.get(VARIANT_KEY)]; @@ -30,8 +30,8 @@ ready: function() { this.isCombined = false; // Asynchronously check if Chrome is pinned to the taskbar. - cr.sendWithPromise('getPinnedToTaskbarState').then( - this.receivePinnedState_.bind(this)); + cr.sendWithPromise('getPinnedToTaskbarState') + .then(this.receivePinnedState_.bind(this)); }, computeClasses: function(isCombined) { @@ -52,8 +52,8 @@ var sections = this.shadowRoot.querySelectorAll('.section.expandable'); sections.forEach(function(section) { var isExpanded = section.classList.toggle('expanded'); - section.querySelector('[role~="button"]').setAttribute( - 'aria-expanded', isExpanded); + section.querySelector('[role~="button"]') + .setAttribute('aria-expanded', isExpanded); }); } });
diff --git a/chrome/browser/resources/welcome/win10/sectioned.js b/chrome/browser/resources/welcome/win10/sectioned.js index 9d5e07f7..09137e9 100644 --- a/chrome/browser/resources/welcome/win10/sectioned.js +++ b/chrome/browser/resources/welcome/win10/sectioned.js
@@ -50,30 +50,25 @@ // Asynchronously check if Chrome is pinned to the taskbar. - cr.sendWithPromise('getPinnedToTaskbarState').then( - function(isPinnedToTaskbar) { - // Allow overriding of the result via a query parameter. - // TODO(pmonette): Remove these checks when they are no longer needed. - /** @const */ var VARIANT_KEY = 'variant'; - var VariantType = { - DEFAULT_ONLY: 'defaultonly', - COMBINED: 'combined' - }; - var params = new URLSearchParams(location.search.slice(1)); - if (params.has(VARIANT_KEY)) { - if (params.get(VARIANT_KEY) === VariantType.DEFAULT_ONLY) - app.isCombined = false; - else if (params.get(VARIANT_KEY) === VariantType.COMBINED) - app.isCombined = true; - } else { - app.isCombined = !isPinnedToTaskbar; - } - }); + cr.sendWithPromise('getPinnedToTaskbarState') + .then(function(isPinnedToTaskbar) { + // Allow overriding of the result via a query parameter. + // TODO(pmonette): Remove these checks when they are no longer needed. + /** @const */ var VARIANT_KEY = 'variant'; + var VariantType = {DEFAULT_ONLY: 'defaultonly', COMBINED: 'combined'}; + var params = new URLSearchParams(location.search.slice(1)); + if (params.has(VARIANT_KEY)) { + if (params.get(VARIANT_KEY) === VariantType.DEFAULT_ONLY) + app.isCombined = false; + else if (params.get(VARIANT_KEY) === VariantType.COMBINED) + app.isCombined = true; + } else { + app.isCombined = !isPinnedToTaskbar; + } + }); } - return { - initialize: initialize - }; + return {initialize: initialize}; }); document.addEventListener('DOMContentLoaded', sectioned.initialize);
diff --git a/chrome/installer/setup/install.cc b/chrome/installer/setup/install.cc index f6d9fd3..23da2c2 100644 --- a/chrome/installer/setup/install.cc +++ b/chrome/installer/setup/install.cc
@@ -643,8 +643,7 @@ work_item_list->Rollback(); } - UpdateOsUpgradeBeacon(installer_state.system_install(), - BrowserDistribution::GetDistribution()); + UpdateOsUpgradeBeacon(); // Update the per-user default browser beacon. For user-level installs this // can be done directly; whereas it requires triggering Active Setup for each
diff --git a/chrome/installer/util/beacons.cc b/chrome/installer/util/beacons.cc index 7e0925d..b8cd911 100644 --- a/chrome/installer/util/beacons.cc +++ b/chrome/installer/util/beacons.cc
@@ -9,10 +9,8 @@ #include "base/memory/ptr_util.h" #include "base/win/registry.h" #include "base/win/win_util.h" -#include "chrome/installer/util/app_registration_data.h" -#include "chrome/installer/util/browser_distribution.h" -#include "chrome/installer/util/install_util.h" -#include "chrome/installer/util/shell_util.h" +#include "chrome/install_static/install_details.h" +#include "chrome/install_static/install_util.h" void UpdateDefaultBrowserBeaconForPath(const base::FilePath& chrome_exe) { // Getting Chrome's default state causes the beacon to be updated via a call @@ -21,70 +19,49 @@ } void UpdateDefaultBrowserBeaconWithState( - BrowserDistribution* distribution, ShellUtil::DefaultState default_state) { - const bool system_install = !InstallUtil::IsPerUserInstall(); - const AppRegistrationData& registration_data = - distribution->GetAppRegistrationData(); switch (default_state) { case ShellUtil::NOT_DEFAULT: - installer_util::MakeFirstNotDefaultBeacon(system_install, - registration_data)->Update(); + installer_util::MakeFirstNotDefaultBeacon()->Update(); break; case ShellUtil::IS_DEFAULT: - installer_util::MakeLastWasDefaultBeacon(system_install, - registration_data)->Update(); - installer_util::MakeFirstNotDefaultBeacon(system_install, - registration_data)->Remove(); + installer_util::MakeLastWasDefaultBeacon()->Update(); + installer_util::MakeFirstNotDefaultBeacon()->Remove(); break; case ShellUtil::UNKNOWN_DEFAULT: break; } } -void UpdateOsUpgradeBeacon(bool system_install, - BrowserDistribution* distribution) { - installer_util::MakeLastOsUpgradeBeacon( - system_install, distribution->GetAppRegistrationData())->Update(); +void UpdateOsUpgradeBeacon() { + installer_util::MakeLastOsUpgradeBeacon()->Update(); } namespace installer_util { -std::unique_ptr<Beacon> MakeLastOsUpgradeBeacon( - bool system_install, - const AppRegistrationData& registration_data) { +std::unique_ptr<Beacon> MakeLastOsUpgradeBeacon() { return base::MakeUnique<Beacon>(L"LastOsUpgrade", Beacon::BeaconType::LAST, - Beacon::BeaconScope::PER_INSTALL, - system_install, registration_data); + Beacon::BeaconScope::PER_INSTALL); } -std::unique_ptr<Beacon> MakeLastWasDefaultBeacon( - bool system_install, - const AppRegistrationData& registration_data) { +std::unique_ptr<Beacon> MakeLastWasDefaultBeacon() { return base::MakeUnique<Beacon>(L"LastWasDefault", Beacon::BeaconType::LAST, - Beacon::BeaconScope::PER_USER, system_install, - registration_data); + Beacon::BeaconScope::PER_USER); } -std::unique_ptr<Beacon> MakeFirstNotDefaultBeacon( - bool system_install, - const AppRegistrationData& registration_data) { +std::unique_ptr<Beacon> MakeFirstNotDefaultBeacon() { return base::MakeUnique<Beacon>(L"FirstNotDefault", Beacon::BeaconType::FIRST, - Beacon::BeaconScope::PER_USER, system_install, - registration_data); + Beacon::BeaconScope::PER_USER); } // Beacon ---------------------------------------------------------------------- -Beacon::Beacon(base::StringPiece16 name, - BeaconType type, - BeaconScope scope, - bool system_install, - const AppRegistrationData& registration_data) +Beacon::Beacon(base::StringPiece16 name, BeaconType type, BeaconScope scope) : type_(type), - root_(system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER), + root_(install_static::IsSystemInstall() ? HKEY_LOCAL_MACHINE + : HKEY_CURRENT_USER), scope_(scope) { - Initialize(name, system_install, registration_data); + Initialize(name); } Beacon::~Beacon() { @@ -129,17 +106,19 @@ return base::Time::FromInternalValue(now); } -void Beacon::Initialize(base::StringPiece16 name, - bool system_install, - const AppRegistrationData& registration_data) { +void Beacon::Initialize(base::StringPiece16 name) { + const install_static::InstallDetails& install_details = + install_static::InstallDetails::Get(); + // When possible, beacons are located in the app's ClientState key. Per-user // beacons for a per-machine install are located in a beacon-specific sub-key // of the app's ClientStateMedium key. - if (!system_install || scope_ == BeaconScope::PER_INSTALL) { - key_path_ = registration_data.GetStateKey(); + if (scope_ == BeaconScope::PER_INSTALL || + !install_static::IsSystemInstall()) { + key_path_ = install_details.GetClientStateKeyPath(); value_name_ = name.as_string(); } else { - key_path_ = registration_data.GetStateMediumKey(); + key_path_ = install_details.GetClientStateMediumKeyPath(); key_path_.push_back(L'\\'); key_path_.append(name.data(), name.size()); // This should never fail. If it does, the beacon will be written in the
diff --git a/chrome/installer/util/beacons.h b/chrome/installer/util/beacons.h index 2a49ec1..7ba7b7a 100644 --- a/chrome/installer/util/beacons.h +++ b/chrome/installer/util/beacons.h
@@ -15,9 +15,6 @@ #include "base/time/time.h" #include "chrome/installer/util/shell_util.h" -class AppRegistrationData; -class BrowserDistribution; - namespace base { class FilePath; } @@ -28,33 +25,25 @@ // Updates the last was default or first not default beacon for the current user // based on |default_state|. -void UpdateDefaultBrowserBeaconWithState(BrowserDistribution* distribution, - ShellUtil::DefaultState default_state); +void UpdateDefaultBrowserBeaconWithState(ShellUtil::DefaultState default_state); // Updates the last OS upgrade beacon for the install. -void UpdateOsUpgradeBeacon(bool system_install, - BrowserDistribution* distribution); +void UpdateOsUpgradeBeacon(); namespace installer_util { class Beacon; // Returns a Beacon representing the last time the machine's OS was ugpraded. -std::unique_ptr<Beacon> MakeLastOsUpgradeBeacon( - bool system_install, - const AppRegistrationData& registration_data); +std::unique_ptr<Beacon> MakeLastOsUpgradeBeacon(); // Returns a Beacon representing the last time Chrome was the user's default // browser. -std::unique_ptr<Beacon> MakeLastWasDefaultBeacon( - bool system_install, - const AppRegistrationData& registration_data); +std::unique_ptr<Beacon> MakeLastWasDefaultBeacon(); // Returns a Beacon representing the first time Chrome was not the user's // default browser. -std::unique_ptr<Beacon> MakeFirstNotDefaultBeacon( - bool system_install, - const AppRegistrationData& registration_data); +std::unique_ptr<Beacon> MakeFirstNotDefaultBeacon(); // A named beacon stored in the registry representing the first or last time at // which some event took place. A beacon may apply to a per-user event or a @@ -76,14 +65,7 @@ PER_INSTALL, }; - // Creates a beacon named |name| for the product identified by - // |registration_data| installed as either a per-user or a per-machine app - // according to |system_install|. - Beacon(base::StringPiece16 name, - BeaconType type, - BeaconScope scope, - bool system_install, - const AppRegistrationData& registration_data); + Beacon(base::StringPiece16 name, BeaconType type, BeaconScope scope); ~Beacon(); // Updates the beacon. For a type LAST beacon, the current time is written @@ -99,9 +81,7 @@ private: // Initializes the key_path_ and value_name_ fields of the beacon. - void Initialize(base::StringPiece16 name, - bool system_install, - const AppRegistrationData& registration_data); + void Initialize(base::StringPiece16 name); // The type of beacon. const BeaconType type_;
diff --git a/chrome/installer/util/beacons_unittest.cc b/chrome/installer/util/beacons_unittest.cc index 4f3e7dc..6e4ad1b4 100644 --- a/chrome/installer/util/beacons_unittest.cc +++ b/chrome/installer/util/beacons_unittest.cc
@@ -16,9 +16,7 @@ #include "chrome/install_static/install_details.h" #include "chrome/install_static/install_modes.h" #include "chrome/install_static/test/scoped_install_details.h" -#include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/install_util.h" -#include "chrome/installer/util/test_app_registration_data.h" #include "chrome/installer/util/util_constants.h" #include "testing/gtest/include/gtest/gtest.h" @@ -40,11 +38,8 @@ : beacon_type_(::testing::get<0>(GetParam())), beacon_scope_(::testing::get<1>(GetParam())), system_install_(::testing::get<2>(GetParam())), - beacon_(kBeaconName, - beacon_type_, - beacon_scope_, - system_install_, - app_registration_data_) {} + scoped_install_details_(system_install_), + beacon_(kBeaconName, beacon_type_, beacon_scope_) {} void SetUp() override { // Override the registry so that tests can freely push state to it. @@ -54,13 +49,17 @@ registry_override_manager_.OverrideRegistry(HKEY_LOCAL_MACHINE)); } - TestAppRegistrationData app_registration_data_; + BeaconType beacon_type() const { return beacon_type_; } + BeaconScope beacon_scope() const { return beacon_scope_; } + bool system_install() const { return system_install_; } + Beacon* beacon() { return &beacon_; } + + private: BeaconType beacon_type_; BeaconScope beacon_scope_; bool system_install_; + install_static::ScopedInstallDetails scoped_install_details_; Beacon beacon_; - - private: registry_util::RegistryOverrideManager registry_override_manager_; }; @@ -69,16 +68,16 @@ // Nothing in the regsitry, so the beacon should not exist. TEST_P(BeaconTest, GetNonExistant) { - ASSERT_TRUE(beacon_.Get().is_null()); + ASSERT_TRUE(beacon()->Get().is_null()); } // Updating and then getting the beacon should return a value, and that it is // within range. TEST_P(BeaconTest, UpdateAndGet) { base::Time before(base::Time::Now()); - beacon_.Update(); + beacon()->Update(); base::Time after(base::Time::Now()); - base::Time beacon_time(beacon_.Get()); + base::Time beacon_time(beacon()->Get()); ASSERT_FALSE(beacon_time.is_null()); ASSERT_LE(before, beacon_time); ASSERT_GE(after, beacon_time); @@ -87,39 +86,42 @@ // Tests that updating a first beacon only updates it the first time, but doing // so for a last beacon always updates. TEST_P(BeaconTest, UpdateTwice) { - beacon_.Update(); - base::Time beacon_time(beacon_.Get()); + beacon()->Update(); + base::Time beacon_time(beacon()->Get()); base::PlatformThread::Sleep(TestTimeouts::tiny_timeout()); - beacon_.Update(); - if (beacon_type_ == BeaconType::FIRST) { - ASSERT_EQ(beacon_time, beacon_.Get()); + beacon()->Update(); + if (beacon_type() == BeaconType::FIRST) { + ASSERT_EQ(beacon_time, beacon()->Get()); } else { - ASSERT_NE(beacon_time, beacon_.Get()); + ASSERT_NE(beacon_time, beacon()->Get()); } } // Tests that the beacon is written into the proper location in the registry. TEST_P(BeaconTest, Location) { - beacon_.Update(); - HKEY right_root = system_install_ ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - HKEY wrong_root = system_install_ ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE; + beacon()->Update(); + const install_static::InstallDetails& install_details = + install_static::InstallDetails::Get(); + HKEY right_root = system_install() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + HKEY wrong_root = system_install() ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE; base::string16 right_key; base::string16 wrong_key; base::string16 value_name; - if (beacon_scope_ == BeaconScope::PER_INSTALL || !system_install_) { + if (beacon_scope() == BeaconScope::PER_INSTALL || !system_install()) { value_name = kBeaconName; - right_key = app_registration_data_.GetStateKey(); - wrong_key = app_registration_data_.GetStateMediumKey(); + right_key = install_details.GetClientStateKeyPath(); + wrong_key = install_details.GetClientStateMediumKeyPath(); } else { ASSERT_TRUE(base::win::GetUserSidString(&value_name)); right_key = - app_registration_data_.GetStateMediumKey() + L"\\" + kBeaconName; - wrong_key = app_registration_data_.GetStateKey(); + install_details.GetClientStateMediumKeyPath() + L"\\" + kBeaconName; + wrong_key = install_details.GetClientStateKeyPath(); } +#if defined(GOOGLE_CHROME_BUILD) // Keys should not exist in the wrong root or in the right root but wrong key. ASSERT_FALSE(base::win::RegKey(wrong_root, right_key.c_str(), KEY_READ).Valid()) << right_key; @@ -127,6 +129,17 @@ KEY_READ).Valid()) << wrong_key; ASSERT_FALSE(base::win::RegKey(right_root, wrong_key.c_str(), KEY_READ).Valid()) << wrong_key; +#else + // The tests above are skipped for Chromium builds because they fail for two + // reasons: + // - ClientState and ClientStateMedium are both Software\Chromium. + // - the registry override manager does its virtualization into + // Software\Chromium, so it always exists. + + // Silence unused variable warnings. + ignore_result(wrong_root); +#endif + // The right key should exist. base::win::RegKey key(right_root, right_key.c_str(), KEY_READ); ASSERT_TRUE(key.Valid()) << right_key; @@ -167,15 +180,9 @@ registry_override_manager_.OverrideRegistry(HKEY_CURRENT_USER)); ASSERT_NO_FATAL_FAILURE( registry_override_manager_.OverrideRegistry(HKEY_LOCAL_MACHINE)); - - // Ensure that IsPerUserInstall returns the proper value. - ASSERT_EQ(!system_install_, InstallUtil::IsPerUserInstall()); - - distribution_ = BrowserDistribution::GetDistribution(); } bool system_install_ = false; - BrowserDistribution* distribution_ = nullptr; private: std::unique_ptr<install_static::ScopedInstallDetails> scoped_install_details_; @@ -184,36 +191,34 @@ // Tests that the default browser beacons work as expected. TEST_P(DefaultBrowserBeaconTest, All) { - std::unique_ptr<Beacon> last_was_default(MakeLastWasDefaultBeacon( - system_install_, distribution_->GetAppRegistrationData())); - std::unique_ptr<Beacon> first_not_default(MakeFirstNotDefaultBeacon( - system_install_, distribution_->GetAppRegistrationData())); + std::unique_ptr<Beacon> last_was_default(MakeLastWasDefaultBeacon()); + std::unique_ptr<Beacon> first_not_default(MakeFirstNotDefaultBeacon()); ASSERT_TRUE(last_was_default->Get().is_null()); ASSERT_TRUE(first_not_default->Get().is_null()); // Chrome is not default. - UpdateDefaultBrowserBeaconWithState(distribution_, ShellUtil::NOT_DEFAULT); + UpdateDefaultBrowserBeaconWithState(ShellUtil::NOT_DEFAULT); ASSERT_TRUE(last_was_default->Get().is_null()); ASSERT_FALSE(first_not_default->Get().is_null()); // Then it is. - UpdateDefaultBrowserBeaconWithState(distribution_, ShellUtil::IS_DEFAULT); + UpdateDefaultBrowserBeaconWithState(ShellUtil::IS_DEFAULT); ASSERT_FALSE(last_was_default->Get().is_null()); ASSERT_TRUE(first_not_default->Get().is_null()); // It still is. - UpdateDefaultBrowserBeaconWithState(distribution_, ShellUtil::IS_DEFAULT); + UpdateDefaultBrowserBeaconWithState(ShellUtil::IS_DEFAULT); ASSERT_FALSE(last_was_default->Get().is_null()); ASSERT_TRUE(first_not_default->Get().is_null()); // Now it's not again. - UpdateDefaultBrowserBeaconWithState(distribution_, ShellUtil::NOT_DEFAULT); + UpdateDefaultBrowserBeaconWithState(ShellUtil::NOT_DEFAULT); ASSERT_FALSE(last_was_default->Get().is_null()); ASSERT_FALSE(first_not_default->Get().is_null()); // And it still isn't. - UpdateDefaultBrowserBeaconWithState(distribution_, ShellUtil::NOT_DEFAULT); + UpdateDefaultBrowserBeaconWithState(ShellUtil::NOT_DEFAULT); ASSERT_FALSE(last_was_default->Get().is_null()); ASSERT_FALSE(first_not_default->Get().is_null()); }
diff --git a/chrome/installer/util/shell_util.cc b/chrome/installer/util/shell_util.cc index e68c01e..dc51efd 100644 --- a/chrome/installer/util/shell_util.cc +++ b/chrome/installer/util/shell_util.cc
@@ -1811,8 +1811,7 @@ static const wchar_t* const kChromeProtocols[] = { L"http", L"https" }; DefaultState default_state = ProbeProtocolHandlers( chrome_exe, kChromeProtocols, arraysize(kChromeProtocols)); - UpdateDefaultBrowserBeaconWithState(BrowserDistribution::GetDistribution(), - default_state); + UpdateDefaultBrowserBeaconWithState(default_state); return default_state; }
diff --git a/ios/build/bots/tests/common_tests.json b/ios/build/bots/tests/common_tests.json index 36a06e25..60929cc 100644 --- a/ios/build/bots/tests/common_tests.json +++ b/ios/build/bots/tests/common_tests.json
@@ -37,6 +37,9 @@ "app": "net_unittests" }, { + "app": "services_unittests" + }, + { "app": "skia_unittests" }, {
diff --git a/ios/build/tools/setup-gn.config b/ios/build/tools/setup-gn.config index 57a9716..79fe76e 100644 --- a/ios/build/tools/setup-gn.config +++ b/ios/build/tools/setup-gn.config
@@ -30,8 +30,9 @@ filter_4 = "//ios/*" filter_5 = "//ios_internal/*" filter_6 = "//net:net_unittests" -filter_7 = "//skia:skia_unittests" -filter_8 = "//sql:sql_unittests" -filter_9 = "//ui/base:ui_base_unittests" -filter_a = "//ui/gfx:gfx_unittests" -filter_b = "//url:url_unittests" +filter_7 = "//services:services_unittests" +filter_8 = "//skia:skia_unittests" +filter_9 = "//sql:sql_unittests" +filter_a = "//ui/base:ui_base_unittests" +filter_b = "//ui/gfx:gfx_unittests" +filter_c = "//url:url_unittests"
diff --git a/third_party/WebKit/LayoutTests/SmokeTests b/third_party/WebKit/LayoutTests/SmokeTests index 2ddbae26..54b91096 100644 --- a/third_party/WebKit/LayoutTests/SmokeTests +++ b/third_party/WebKit/LayoutTests/SmokeTests
@@ -7,25 +7,8 @@ animations/responsive/offset-rotate-responsive.html animations/svg-attribute-composition/svg-bias-composition.html animations/svg-attribute-interpolation/svg-numOctaves-interpolation.html -bluetooth/characteristic/notifications/concurrent-stops.html -bluetooth/characteristic/readValue/gen-gatt-op-device-disconnects-before.html -bluetooth/characteristic/readValue/service-is-removed.html -bluetooth/characteristic/startNotifications/gen-gatt-op-device-disconnects-during-success.html -bluetooth/characteristic/stopNotifications/device-reconnects-during-success.html -bluetooth/characteristic/writeValue/characteristic-is-removed.html -bluetooth/descriptor/characteristic-same-object.html -bluetooth/descriptor/writeValue/gen-io-op-disconnect-called-during-error.html bluetooth/idl/idl-NavigatorBluetooth.html bluetooth/requestDevice/canonicalizeFilter/no-arguments.html -bluetooth/requestDevice/chooser/device-removed.html -bluetooth/requestDevice/name-missing-device-from-name-prefix-filter.html -bluetooth/server/disconnect/disconnect-fires-event.html -bluetooth/server/getPrimaryServices/delayed-discovery-no-permission-present-service-with-uuid.html -bluetooth/server/getPrimaryServices/device-goes-out-of-range.html -bluetooth/server/getPrimaryServices/disconnect-called-during-success-with-uuid.html -bluetooth/service/device-same-object.html -bluetooth/service/getCharacteristics/disconnect-called-during.html -bluetooth/service/getCharacteristics/service-is-removed-with-uuid.html canvas/feimage-with-foreignobject-taint-canvas-2.html canvas/philip/tests/2d.text.font.default.html compositing/animation/animated-composited-inside-hidden.html
diff --git a/third_party/WebKit/LayoutTests/TestExpectations b/third_party/WebKit/LayoutTests/TestExpectations index f8d19d1..80196b95 100644 --- a/third_party/WebKit/LayoutTests/TestExpectations +++ b/third_party/WebKit/LayoutTests/TestExpectations
@@ -1518,6 +1518,7 @@ crbug.com/582836 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/variables/variable-font-face-02.html [ Failure ] crbug.com/553838 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-break-inside-001a.html [ Failure ] +crbug.com/553838 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-005a.html [ Failure Pass ] crbug.com/553838 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-006.html [ Failure ] crbug.com/553838 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-006a.html [ Failure ] crbug.com/553838 external/wpt/css/vendor-imports/mozilla/mozilla-central-reftests/writing-modes-3/text-combine-upright-compression-007.html [ Failure ] @@ -1762,6 +1763,8 @@ crbug.com/399507 virtual/threaded/inspector/tracing/timeline-paint/layer-tree.html [ Skip ] +crbug.com/635909 inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints.html [ NeedsManualRebaseline Timeout ] + crbug.com/636424 [ Win7 Debug ] editing/selection/modify_move/move-by-word-visually-crash-test-5.html [ Pass Timeout ] crbug.com/638618 inspector/editor/text-editor-search-switch-editor.html [ Skip ] @@ -1907,7 +1910,7 @@ crbug.com/626703 external/wpt/web-nfc/idlharness.https.html [ Skip ] crbug.com/723741 virtual/threaded/animations/svg-attribute-composition/svg-startOffset-composition.html [ Failure Pass ] -crbug.com/723741 virtual/threaded/inspector/tracing/idle-callback.html [ Failure Pass ] +crbug.com/723741 virtual/threaded/inspector/tracing/idle-callback.html [ Failure Pass Timeout ] crbug.com/723826 http/tests/security/w3c/cross-origin-objects.html [ Failure Pass ] crbug.com/723826 virtual/mojo-loading/http/tests/security/w3c/cross-origin-objects.html [ Failure Pass ]
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/dom/reflection-tabular-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/html/dom/reflection-tabular-expected.txt index b3d57fb..100c512 100644 --- a/third_party/WebKit/LayoutTests/external/wpt/html/dom/reflection-tabular-expected.txt +++ b/third_party/WebKit/LayoutTests/external/wpt/html/dom/reflection-tabular-expected.txt
@@ -30,15 +30,21 @@ PASS colgroup.hidden: 33 tests PASS colgroup.accessKey: 32 tests PASS colgroup.tabIndex: 24 tests -PASS colgroup.span: 11 tests +PASS colgroup.span: 8 tests +FAIL colgroup.span: setAttribute() to 2147483647 assert_equals: IDL get expected 1000 but got 8190 +FAIL colgroup.span: setAttribute() to 2147483648 assert_equals: IDL get expected 1000 but got 8190 +FAIL colgroup.span: setAttribute() to 4294967295 assert_equals: IDL get expected 1000 but got 8190 FAIL colgroup.span: setAttribute() to 4294967296 assert_equals: IDL get expected 1000 but got 1 -PASS colgroup.span: 44 tests +PASS colgroup.span: 43 tests +FAIL colgroup.span: setAttribute() to 1001 assert_equals: IDL get expected 1000 but got 1001 FAIL colgroup.span: IDL set to 0 assert_equals: getAttribute() expected "0" but got "1" -PASS colgroup.span: 3 tests +PASS colgroup.span: 2 tests +FAIL colgroup.span: IDL set to 2147483647 assert_equals: IDL get expected 1000 but got 8190 FAIL colgroup.span: IDL set to "-0" assert_equals: getAttribute() expected "0" but got "1" FAIL colgroup.span: IDL set to 2147483648 assert_equals: getAttribute() expected "1" but got "0" FAIL colgroup.span: IDL set to 4294967295 assert_equals: getAttribute() expected "1" but got "0" -PASS colgroup.span: 2 tests +PASS colgroup.span: IDL set to 1000 +FAIL colgroup.span: IDL set to 1001 assert_equals: IDL get expected 1000 but got 1001 PASS colgroup.align: 32 tests PASS colgroup.ch (<colgroup char>): 32 tests PASS colgroup.chOff (<colgroup charoff>): 32 tests @@ -51,15 +57,21 @@ PASS col.hidden: 33 tests PASS col.accessKey: 32 tests PASS col.tabIndex: 24 tests -PASS col.span: 11 tests +PASS col.span: 8 tests +FAIL col.span: setAttribute() to 2147483647 assert_equals: IDL get expected 1000 but got 8190 +FAIL col.span: setAttribute() to 2147483648 assert_equals: IDL get expected 1000 but got 8190 +FAIL col.span: setAttribute() to 4294967295 assert_equals: IDL get expected 1000 but got 8190 FAIL col.span: setAttribute() to 4294967296 assert_equals: IDL get expected 1000 but got 1 -PASS col.span: 44 tests +PASS col.span: 43 tests +FAIL col.span: setAttribute() to 1001 assert_equals: IDL get expected 1000 but got 1001 FAIL col.span: IDL set to 0 assert_equals: getAttribute() expected "0" but got "1" -PASS col.span: 3 tests +PASS col.span: 2 tests +FAIL col.span: IDL set to 2147483647 assert_equals: IDL get expected 1000 but got 8190 FAIL col.span: IDL set to "-0" assert_equals: getAttribute() expected "0" but got "1" FAIL col.span: IDL set to 2147483648 assert_equals: getAttribute() expected "1" but got "0" FAIL col.span: IDL set to 4294967295 assert_equals: getAttribute() expected "1" but got "0" -PASS col.span: 2 tests +PASS col.span: IDL set to 1000 +FAIL col.span: IDL set to 1001 assert_equals: IDL get expected 1000 but got 1001 PASS col.align: 32 tests PASS col.ch (<col char>): 32 tests PASS col.chOff (<col charoff>): 32 tests @@ -117,12 +129,20 @@ PASS td.hidden: 33 tests PASS td.accessKey: 32 tests PASS td.tabIndex: 24 tests -PASS td.colSpan: 11 tests +PASS td.colSpan: 8 tests +FAIL td.colSpan: setAttribute() to 2147483647 assert_equals: IDL get expected 1000 but got 8190 +FAIL td.colSpan: setAttribute() to 2147483648 assert_equals: IDL get expected 1000 but got 8190 +FAIL td.colSpan: setAttribute() to 4294967295 assert_equals: IDL get expected 1000 but got 8190 FAIL td.colSpan: setAttribute() to 4294967296 assert_equals: IDL get expected 1000 but got 1 -PASS td.colSpan: 49 tests +PASS td.colSpan: 43 tests +FAIL td.colSpan: setAttribute() to 1001 assert_equals: IDL get expected 1000 but got 1001 +PASS td.colSpan: 3 tests +FAIL td.colSpan: IDL set to 2147483647 assert_equals: IDL get expected 1000 but got 8190 +PASS td.colSpan: IDL set to "-0" FAIL td.colSpan: IDL set to 2147483648 assert_equals: getAttribute() expected "1" but got "0" FAIL td.colSpan: IDL set to 4294967295 assert_equals: getAttribute() expected "1" but got "0" -PASS td.colSpan: 2 tests +PASS td.colSpan: IDL set to 1000 +FAIL td.colSpan: IDL set to 1001 assert_equals: IDL get expected 1000 but got 1001 PASS td.rowSpan: 6 tests FAIL td.rowSpan: setAttribute() to 0 assert_equals: IDL get expected 0 but got 1 PASS td.rowSpan: 4 tests @@ -155,12 +175,20 @@ PASS th.hidden: 33 tests PASS th.accessKey: 32 tests PASS th.tabIndex: 24 tests -PASS th.colSpan: 11 tests +PASS th.colSpan: 8 tests +FAIL th.colSpan: setAttribute() to 2147483647 assert_equals: IDL get expected 1000 but got 8190 +FAIL th.colSpan: setAttribute() to 2147483648 assert_equals: IDL get expected 1000 but got 8190 +FAIL th.colSpan: setAttribute() to 4294967295 assert_equals: IDL get expected 1000 but got 8190 FAIL th.colSpan: setAttribute() to 4294967296 assert_equals: IDL get expected 1000 but got 1 -PASS th.colSpan: 49 tests +PASS th.colSpan: 43 tests +FAIL th.colSpan: setAttribute() to 1001 assert_equals: IDL get expected 1000 but got 1001 +PASS th.colSpan: 3 tests +FAIL th.colSpan: IDL set to 2147483647 assert_equals: IDL get expected 1000 but got 8190 +PASS th.colSpan: IDL set to "-0" FAIL th.colSpan: IDL set to 2147483648 assert_equals: getAttribute() expected "1" but got "0" FAIL th.colSpan: IDL set to 4294967295 assert_equals: getAttribute() expected "1" but got "0" -PASS th.colSpan: 2 tests +PASS th.colSpan: IDL set to 1000 +FAIL th.colSpan: IDL set to 1001 assert_equals: IDL get expected 1000 but got 1001 PASS th.rowSpan: 6 tests FAIL th.rowSpan: setAttribute() to 0 assert_equals: IDL get expected 0 but got 1 PASS th.rowSpan: 4 tests
diff --git a/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/processing-model-1/col-span-limits-expected.txt b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/processing-model-1/col-span-limits-expected.txt new file mode 100644 index 0000000..c26568a --- /dev/null +++ b/third_party/WebKit/LayoutTests/external/wpt/html/semantics/tabular-data/processing-model-1/col-span-limits-expected.txt
@@ -0,0 +1,5 @@ +This is a testharness.js-based test. +PASS col span of 1000 must work +FAIL col span of 1001 must be treated as 1000 assert_equals: table3 width expected 51 but got 53 +Harness: the test ran to completion. +
diff --git a/third_party/WebKit/LayoutTests/html/tabular_data/col_span-expected.txt b/third_party/WebKit/LayoutTests/html/tabular_data/col_span-expected.txt index ddcbba3..e34c777 100644 --- a/third_party/WebKit/LayoutTests/html/tabular_data/col_span-expected.txt +++ b/third_party/WebKit/LayoutTests/html/tabular_data/col_span-expected.txt
@@ -21,9 +21,9 @@ PASS spanAttributeEffect(" 7") is 7 PASS spanAttributeEffect(arabicIndicDigitOne) is 1 PASS spanAttributeEffect("2" + arabicIndicDigitOne) is 2 -PASS spanAttributeEffect("2147483647") is 1000 -PASS spanAttributeEffect("2147483648") is 1000 -PASS spanAttributeEffect("4294967295") is 1000 +PASS spanAttributeEffect("2147483647") is 8190 +PASS spanAttributeEffect("2147483648") is 8190 +PASS spanAttributeEffect("4294967295") is 8190 PASS spanAttributeEffect("4294967296") is 1 PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/html/tabular_data/col_span.html b/third_party/WebKit/LayoutTests/html/tabular_data/col_span.html index 0999ded..632ea91f 100644 --- a/third_party/WebKit/LayoutTests/html/tabular_data/col_span.html +++ b/third_party/WebKit/LayoutTests/html/tabular_data/col_span.html
@@ -41,9 +41,9 @@ shouldBe('spanAttributeEffect(arabicIndicDigitOne)', '1'); shouldBe('spanAttributeEffect("2" + arabicIndicDigitOne)', '2'); -shouldBe('spanAttributeEffect("2147483647")', '1000'); -shouldBe('spanAttributeEffect("2147483648")', '1000'); -shouldBe('spanAttributeEffect("4294967295")', '1000'); +shouldBe('spanAttributeEffect("2147483647")', '8190'); +shouldBe('spanAttributeEffect("2147483648")', '8190'); +shouldBe('spanAttributeEffect("4294967295")', '8190'); shouldBe('spanAttributeEffect("4294967296")', '1'); </script> </body>
diff --git a/third_party/WebKit/LayoutTests/html/tabular_data/td_colspan-expected.txt b/third_party/WebKit/LayoutTests/html/tabular_data/td_colspan-expected.txt index 53babaf..9655954 100644 --- a/third_party/WebKit/LayoutTests/html/tabular_data/td_colspan-expected.txt +++ b/third_party/WebKit/LayoutTests/html/tabular_data/td_colspan-expected.txt
@@ -21,8 +21,8 @@ PASS colspanAttributeEffect(" 7") is 7 PASS colspanAttributeEffect(arabicIndicDigitOne) is 1 PASS colspanAttributeEffect("2" + arabicIndicDigitOne) is 2 -PASS colspanAttributeEffect("2147483647") is 1000 -PASS colspanAttributeEffect("4294967295") is 1000 +PASS colspanAttributeEffect("2147483647") is 8190 +PASS colspanAttributeEffect("4294967295") is 8190 PASS colspanAttributeEffect("4294967296") is 1 PASS successfullyParsed is true
diff --git a/third_party/WebKit/LayoutTests/html/tabular_data/td_colspan.html b/third_party/WebKit/LayoutTests/html/tabular_data/td_colspan.html index 3237c91..54f7411 100644 --- a/third_party/WebKit/LayoutTests/html/tabular_data/td_colspan.html +++ b/third_party/WebKit/LayoutTests/html/tabular_data/td_colspan.html
@@ -41,8 +41,8 @@ shouldBe('colspanAttributeEffect(arabicIndicDigitOne)', '1'); shouldBe('colspanAttributeEffect("2" + arabicIndicDigitOne)', '2'); -shouldBe('colspanAttributeEffect("2147483647")', '1000'); -shouldBe('colspanAttributeEffect("4294967295")', '1000'); +shouldBe('colspanAttributeEffect("2147483647")', '8190'); +shouldBe('colspanAttributeEffect("4294967295")', '8190'); shouldBe('colspanAttributeEffect("4294967296")', '1'); </script> </body>
diff --git a/third_party/WebKit/LayoutTests/http/tests/worklet/webexposed/global-interface-listing-paint-worklet-expected.txt b/third_party/WebKit/LayoutTests/http/tests/worklet/webexposed/global-interface-listing-paint-worklet-expected.txt index f82d91be..4211f9f9 100644 --- a/third_party/WebKit/LayoutTests/http/tests/worklet/webexposed/global-interface-listing-paint-worklet-expected.txt +++ b/third_party/WebKit/LayoutTests/http/tests/worklet/webexposed/global-interface-listing-paint-worklet-expected.txt
@@ -55,7 +55,6 @@ CONSOLE MESSAGE: line 147: method constructor CONSOLE MESSAGE: line 147: method toString CONSOLE MESSAGE: line 147: interface CSSTransformComponent -CONSOLE MESSAGE: line 147: method asMatrix CONSOLE MESSAGE: line 147: method constructor CONSOLE MESSAGE: line 147: method is2D CONSOLE MESSAGE: line 147: method toString
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints-expected.txt b/third_party/WebKit/LayoutTests/inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints-expected.txt index 198105c..145f4ee 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints-expected.txt +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints-expected.txt
@@ -8,8 +8,6 @@ * 0) Framework.appendChild (framework.js:72) 1) appendElement (frameworks-dom-xhr-event-breakpoints.html:14) 2) (:1) - [setTimeout] - 0) (:1) Paused on subtree modificationsdiv#rootElementChild div#rootElement added Running: testXHRBreakpoint @@ -17,8 +15,6 @@ * 0) Framework.sendXHR (framework.js:79) 1) sendXHR (frameworks-dom-xhr-event-breakpoints.html:19) 2) (:1) - [setTimeout] - 0) (:1) Paused on XMLHttpRequestfile:///foo?a=b Running: testEventListenerBreakpoint @@ -28,8 +24,6 @@ * 2) Framework_eventListener (framework.js:86) 3) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:37) 4) (:1) - [setTimeout] - 0) (:1) Executing Resume... Call stack: @@ -38,8 +32,6 @@ * 2) Framework_eventListener (framework.js:86) 3) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:43) 4) (:1) - [setTimeout] - 0) (:1) Executing Resume... @@ -48,15 +40,11 @@ Call stack: 0) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:33) 1) (:1) - [setTimeout] - 0) (:1) Executing StepOver... Call stack: 0) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:34) 1) (:1) - [setTimeout] - 0) (:1) Executing StepOver... Executing StepOver... @@ -67,8 +55,6 @@ * 2) Framework_eventListener (framework.js:86) 3) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:37) 4) (:1) - [setTimeout] - 0) (:1) Executing StepOut... Executing StepOver... @@ -81,8 +67,6 @@ * 2) Framework_eventListener (framework.js:86) 3) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:43) 4) (:1) - [setTimeout] - 0) (:1) Executing StepOver... Executing StepOver... @@ -90,8 +74,6 @@ Call stack: 0) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:44) 1) (:1) - [setTimeout] - 0) (:1) Executing Resume... @@ -103,8 +85,6 @@ * 2) Framework_eventListener (framework.js:86) 3) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:37) 4) (:1) - [setTimeout] - 0) (:1) Executing StepOut... Executing StepOut... @@ -114,15 +94,11 @@ * 2) Framework_eventListener (framework.js:86) 3) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:43) 4) (:1) - [setTimeout] - 0) (:1) Executing StepOut... Call stack: 0) addListenerAndClick (frameworks-dom-xhr-event-breakpoints.html:44) 1) (:1) - [setTimeout] - 0) (:1) Executing Resume... @@ -137,23 +113,17 @@ 5) inner (frameworks-dom-xhr-event-breakpoints.html:64) 6) addFewBlackboxedListenersAndClick (frameworks-dom-xhr-event-breakpoints.html:70) 7) (:1) - [setTimeout] - 0) (:1) Executing StepOut... Call stack: 0) inner (frameworks-dom-xhr-event-breakpoints.html:65) 1) addFewBlackboxedListenersAndClick (frameworks-dom-xhr-event-breakpoints.html:70) 2) (:1) - [setTimeout] - 0) (:1) Executing StepOut... Call stack: 0) addFewBlackboxedListenersAndClick (frameworks-dom-xhr-event-breakpoints.html:71) 1) (:1) - [setTimeout] - 0) (:1) Executing Resume...
diff --git a/third_party/WebKit/LayoutTests/inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints.html b/third_party/WebKit/LayoutTests/inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints.html index c06b9b0c..df20996 100644 --- a/third_party/WebKit/LayoutTests/inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints.html +++ b/third_party/WebKit/LayoutTests/inspector/sources/debugger-frameworks/frameworks-dom-xhr-event-breakpoints.html
@@ -81,32 +81,28 @@ function testDOMBreakpoint(next) { InspectorTest.nodeWithId("rootElement", step1); - var rootElement; + function step1(node) { - rootElement = node; - InspectorTest.domDebuggerModel.setDOMBreakpoint(node, SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified); + var pane = Components.domBreakpointsSidebarPane; + pane._setBreakpoint(node, Components.DOMBreakpointsSidebarPane.BreakpointTypes.SubtreeModified, true); InspectorTest.evaluateInPageWithTimeout("appendElement('rootElement', 'childElement')"); - InspectorTest.waitUntilPausedAndDumpStackAndResume(step2); - } - - function step2() - { - InspectorTest.domDebuggerModel.removeDOMBreakpoint(rootElement, SDK.DOMDebuggerModel.DOMBreakpoint.Type.SubtreeModified); - next(); + InspectorTest.waitUntilPausedAndDumpStackAndResume(next); } }, function testXHRBreakpoint(next) { - SDK.domDebuggerManager.addXHRBreakpoint("foo", true); + var pane = self.runtime.sharedInstance(Sources.XHRBreakpointsSidebarPane); + pane._setBreakpoint("foo", true); InspectorTest.evaluateInPageWithTimeout("sendXHR('file:///foo?a=b')"); InspectorTest.waitUntilPausedAndDumpStackAndResume(next); }, function testEventListenerBreakpoint(next) { - InspectorTest.setEventListenerBreakpoint("listener:click", true); + var pane = self.runtime.sharedInstance(Sources.EventListenerBreakpointsSidebarPane); + pane._setBreakpoint("listener:click"); InspectorTest.evaluateInPageWithTimeout("addListenerAndClick(false)"); InspectorTest.waitUntilPausedAndPerformSteppingActions([ "Print", "Resume", @@ -116,7 +112,8 @@ function testSteppingThroughEventListenerBreakpoint(next) { - InspectorTest.setEventListenerBreakpoint("listener:click", true); + var pane = self.runtime.sharedInstance(Sources.EventListenerBreakpointsSidebarPane); + pane._setBreakpoint("listener:click"); InspectorTest.evaluateInPageWithTimeout("addListenerAndClick(true)"); InspectorTest.waitUntilPausedAndPerformSteppingActions([ "StepOver", "Print", @@ -130,7 +127,8 @@ function testSteppingOutOnEventListenerBreakpoint(next) { - InspectorTest.setEventListenerBreakpoint("listener:click", true); + var pane = self.runtime.sharedInstance(Sources.EventListenerBreakpointsSidebarPane); + pane._setBreakpoint("listener:click"); InspectorTest.evaluateInPageWithTimeout("addListenerAndClick(true)"); InspectorTest.waitUntilPausedAndPerformSteppingActions([ "StepOut", "Print", // should be in testElementClicked() @@ -142,7 +140,8 @@ function testSteppingOutOnEventListenerBreakpointAllBlackboxedButOne(next) { - InspectorTest.setEventListenerBreakpoint("listener:click", true); + var pane = self.runtime.sharedInstance(Sources.EventListenerBreakpointsSidebarPane); + pane._setBreakpoint("listener:click"); InspectorTest.evaluateInPageWithTimeout("addFewBlackboxedListenersAndClick(true)"); InspectorTest.waitUntilPausedAndPerformSteppingActions([ "StepOut", "Print", @@ -154,8 +153,8 @@ function tearDown(next) { - InspectorTest.setEventListenerBreakpoint("listener:click", false); - SDK.domDebuggerManager.toggleXHRBreakpoint("foo", false); + self.runtime.sharedInstance(Sources.XHRBreakpointsSidebarPane)._removeBreakpoint("foo"); + self.runtime.sharedInstance(Sources.EventListenerBreakpointsSidebarPane)._removeBreakpoint("listener:click"); next(); } ]);
diff --git a/third_party/WebKit/LayoutTests/typedcssom/cssMatrixComponent.html b/third_party/WebKit/LayoutTests/typedcssom/cssMatrixComponent.html index 80c5c1c2..64dcc944 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/cssMatrixComponent.html +++ b/third_party/WebKit/LayoutTests/typedcssom/cssMatrixComponent.html
@@ -110,18 +110,4 @@ assert_throws(new TypeError(), () => { new CSSMatrixComponent(undefined); }); }, "invalid number of arguments to the constructor throws"); -for (let params of testParams) { - test(() => { - var attributeValues = attributeValues2D.concat(attributeValues3D); - var inputAsMatrix = params.input.asMatrix(); - for (var j = 0; j < attributeValues.length; ++j) { - var attribute = attributeValues[j]; - assert_equals(inputAsMatrix[attribute], params.input[attribute]); - } - assert_equals(inputAsMatrix.is2D(), params.input.is2D()); - assert_equals(inputAsMatrix.toString(), params.input.toString()); - }, "asMatrix has all the same properties as the original " + - "CSSMatrixComponent for " + params.cssText); -} - </script>
diff --git a/third_party/WebKit/LayoutTests/typedcssom/cssScale.html b/third_party/WebKit/LayoutTests/typedcssom/cssScale.html index 45daef7..82c084d 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/cssScale.html +++ b/third_party/WebKit/LayoutTests/typedcssom/cssScale.html
@@ -107,14 +107,15 @@ for (let params of testParams) { test(() => { var input = params.input; - var inputAsMatrix = input.asMatrix(); - assert_equals(inputAsMatrix.is2D(), input.is2D()); + var transformValue = new CSSTransformValue([input]); + var inputAsMatrix = transformValue.toMatrix(); + assert_equals(inputAsMatrix.is2D, input.is2D()); var expectedMatrix = input.is2D() ? new DOMMatrixReadOnly([input.x, 0, 0, input.y, 0, 0]) : new DOMMatrixReadOnly( [input.x, 0, 0, 0, 0, input.y, 0, 0, 0, 0, input.z, 0, 0, 0, 0, 1]); - assert_matrix_approx_equals(inputAsMatrix.matrix, expectedMatrix, EPSILON); + assert_matrix_approx_equals(inputAsMatrix, expectedMatrix, EPSILON); }, "asMatrix is constructed correctly for " + params.cssText); }
diff --git a/third_party/WebKit/LayoutTests/typedcssom/cssSkew-expected.txt b/third_party/WebKit/LayoutTests/typedcssom/cssSkew-expected.txt index f2d679d..06f497f6 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/cssSkew-expected.txt +++ b/third_party/WebKit/LayoutTests/typedcssom/cssSkew-expected.txt
@@ -1,10 +1,10 @@ This is a testharness.js-based test. -PASS (ax, ay) value is correct for skew(0deg, 0deg) -PASS (ax, ay) value is correct for skew(1deg, 2deg) -PASS (ax, ay) value is correct for skew(-2deg, -4deg) -PASS (ax, ay) value is correct for skew(3.4deg, 2.7deg) -PASS (ax, ay) value is correct for skew(1rad, 0deg) -PASS (ax, ay) value is correct for skew(0deg, 1rad) +PASS (ax, ay) values are correct for skew(0deg, 0deg) +PASS (ax, ay) values are correct for skew(1deg, 2deg) +PASS (ax, ay) values are correct for skew(-2deg, -4deg) +PASS (ax, ay) values are correct for skew(3.4deg, 2.7deg) +PASS (ax, ay) values are correct for skew(1rad, 0deg) +PASS (ax, ay) values are correct for skew(0deg, 1rad) PASS is2D value is correct for skew(0deg, 0deg) PASS is2D value is correct for skew(1deg, 2deg) PASS is2D value is correct for skew(-2deg, -4deg) @@ -18,12 +18,12 @@ FAIL toString is correct for skew(1rad, 0deg) assert_equals: expected "skew(1rad, 0deg)" but got "" FAIL toString is correct for skew(0deg, 1rad) assert_equals: expected "skew(0deg, 1rad)" but got "" PASS Invalid arguments to constructor throws an exception. -FAIL asMatrix is constructed correctly for skew(0deg, 0deg) Cannot read property 'is2D' of null -FAIL asMatrix is constructed correctly for skew(1deg, 2deg) Cannot read property 'is2D' of null -FAIL asMatrix is constructed correctly for skew(-2deg, -4deg) Cannot read property 'is2D' of null -FAIL asMatrix is constructed correctly for skew(3.4deg, 2.7deg) Cannot read property 'is2D' of null -FAIL asMatrix is constructed correctly for skew(1rad, 0deg) Cannot read property 'is2D' of null -FAIL asMatrix is constructed correctly for skew(0deg, 1rad) Cannot read property 'is2D' of null +PASS asMatrix is constructed correctly for skew(0deg, 0deg) +FAIL asMatrix is constructed correctly for skew(1deg, 2deg) assert_approx_equals: expected 0.03492076949174773 +/- 0.000001 but got 0 +FAIL asMatrix is constructed correctly for skew(-2deg, -4deg) assert_approx_equals: expected -0.06992681194351041 +/- 0.000001 but got 0 +FAIL asMatrix is constructed correctly for skew(3.4deg, 2.7deg) assert_approx_equals: expected 0.04715880287748047 +/- 0.000001 but got 0 +FAIL asMatrix is constructed correctly for skew(1rad, 0deg) assert_approx_equals: expected 1.5574077246549023 +/- 0.000001 but got 0 +FAIL asMatrix is constructed correctly for skew(0deg, 1rad) assert_approx_equals: expected 1.5574077246549023 +/- 0.000001 but got 0 PASS Setting ax and ay with valid CSSUnitValues PASS Setting ax with invalid values PASS Setting ay with invalid values
diff --git a/third_party/WebKit/LayoutTests/typedcssom/cssSkew.html b/third_party/WebKit/LayoutTests/typedcssom/cssSkew.html index 25ce2514e..4e9ac49 100644 --- a/third_party/WebKit/LayoutTests/typedcssom/cssSkew.html +++ b/third_party/WebKit/LayoutTests/typedcssom/cssSkew.html
@@ -1,6 +1,7 @@ <!DOCTYPE html> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> +<script src="resources/comparisons.js"></script> <script> var EPSILON = 1e-6; // float epsilon @@ -62,7 +63,7 @@ assert_equals(params.input.ax.unit, params.ax.unit); assert_approx_equals(params.input.ay.value, params.ay.value, EPSILON); assert_equals(params.input.ay.unit, params.ay.unit); - }, "(ax, ay) value is correct for " + params.cssText); + }, "(ax, ay) values are correct for " + params.cssText); } for (let params of testParams) { @@ -90,24 +91,18 @@ for (let params of testParams) { test(() => { var input = params.input; - var inputAsMatrix = input.asMatrix(); - assert_true(inputAsMatrix.is2D()); - var tanAx = tanUnitValue(input.ax.degrees); - var tanAy = tanUnitValue(input.ay.degrees); - var expectedMatrix = new CSSMatrixComponent( - new DOMMatrixReadOnly([1, tanAy, tanAx, 1, 0, 0])); - for (var attribute in expectedMatrix) { - if (attribute == "matrix") { - assert_matrix_approx_equals( - inputAsMatrix[attribute], expectedMatrix[attribute], epsilon); - } else { - assert_equals(inputAsMatrix[attribute], expectedMatrix[attribute]); - } - } + var transformValue = new CSSTransformValue([input]); + var inputAsMatrix = transformValue.toMatrix(); + assert_true(inputAsMatrix.is2D); + + var tanAx = tanUnitValue(input.ax); + var tanAy = tanUnitValue(input.ay); + var expectedMatrix = new DOMMatrixReadOnly([1, tanAy, tanAx, 1, 0, 0]); + assert_matrix_approx_equals(inputAsMatrix, expectedMatrix, EPSILON); }, "asMatrix is constructed correctly for " + params.cssText); } -test(function() { +test(() => { var skew = new CSSSkew( new CSSUnitValue(1, 'deg'), new CSSUnitValue(2, 'deg')); skew.ax = new CSSUnitValue(3, 'deg');
diff --git a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt index 22f8ae8..9b7e867 100644 --- a/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/virtual/service-worker-navigation-preload-disabled/webexposed/global-interface-listing-expected.txt
@@ -782,7 +782,6 @@ method constructor interface CSSTransformComponent attribute @@toStringTag - method asMatrix method constructor method is2D method toString
diff --git a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt index a0f6f0de..f1136b1 100644 --- a/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt +++ b/third_party/WebKit/LayoutTests/webexposed/global-interface-listing-expected.txt
@@ -782,7 +782,6 @@ method constructor interface CSSTransformComponent attribute @@toStringTag - method asMatrix method constructor method is2D method toString
diff --git a/third_party/WebKit/Source/core/BUILD.gn b/third_party/WebKit/Source/core/BUILD.gn index b2d8eab67..69324ba4 100644 --- a/third_party/WebKit/Source/core/BUILD.gn +++ b/third_party/WebKit/Source/core/BUILD.gn
@@ -1278,6 +1278,7 @@ "html/HTMLMediaElementTest.cpp", "html/HTMLOutputElementTest.cpp", "html/HTMLSelectElementTest.cpp", + "html/HTMLSlotElementTest.cpp", "html/HTMLTableRowElementTest.cpp", "html/HTMLTextAreaElementTest.cpp", "html/HTMLVideoElementPersistentTest.cpp",
diff --git a/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h b/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h index 2dc0a6c..c29d85a 100644 --- a/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h +++ b/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h
@@ -593,87 +593,6 @@ } template <> -inline CSSIdentifierValue::CSSIdentifierValue(EBoxPack e) - : CSSValue(kIdentifierClass) { - switch (e) { - case EBoxPack::kStart: - value_id_ = CSSValueStart; - break; - case EBoxPack::kCenter: - value_id_ = CSSValueCenter; - break; - case EBoxPack::kEnd: - value_id_ = CSSValueEnd; - break; - case EBoxPack::kJustify: - value_id_ = CSSValueJustify; - break; - } -} - -template <> -inline EBoxPack CSSIdentifierValue::ConvertTo() const { - switch (value_id_) { - case CSSValueStart: - return EBoxPack::kStart; - case CSSValueEnd: - return EBoxPack::kEnd; - case CSSValueCenter: - return EBoxPack::kCenter; - case CSSValueJustify: - return EBoxPack::kJustify; - default: - break; - } - - NOTREACHED(); - return EBoxPack::kJustify; -} - -template <> -inline CSSIdentifierValue::CSSIdentifierValue(EBoxAlignment e) - : CSSValue(kIdentifierClass) { - switch (e) { - case EBoxAlignment::kStretch: - value_id_ = CSSValueStretch; - break; - case EBoxAlignment::kStart: - value_id_ = CSSValueStart; - break; - case EBoxAlignment::kCenter: - value_id_ = CSSValueCenter; - break; - case EBoxAlignment::kBend: - value_id_ = CSSValueEnd; - break; - case EBoxAlignment::kBaseline: - value_id_ = CSSValueBaseline; - break; - } -} - -template <> -inline EBoxAlignment CSSIdentifierValue::ConvertTo() const { - switch (value_id_) { - case CSSValueStretch: - return EBoxAlignment::kStretch; - case CSSValueStart: - return EBoxAlignment::kStart; - case CSSValueEnd: - return EBoxAlignment::kBend; - case CSSValueCenter: - return EBoxAlignment::kCenter; - case CSSValueBaseline: - return EBoxAlignment::kBaseline; - default: - break; - } - - NOTREACHED(); - return EBoxAlignment::kStretch; -} - -template <> inline CSSIdentifierValue::CSSIdentifierValue(BackgroundEdgeOrigin e) : CSSValue(kIdentifierClass) { switch (e) { @@ -712,64 +631,6 @@ } template <> -inline CSSIdentifierValue::CSSIdentifierValue(EBoxLines e) - : CSSValue(kIdentifierClass) { - switch (e) { - case EBoxLines::kSingle: - value_id_ = CSSValueSingle; - break; - case EBoxLines::kMultiple: - value_id_ = CSSValueMultiple; - break; - } -} - -template <> -inline EBoxLines CSSIdentifierValue::ConvertTo() const { - switch (value_id_) { - case CSSValueSingle: - return EBoxLines::kSingle; - case CSSValueMultiple: - return EBoxLines::kMultiple; - default: - break; - } - - NOTREACHED(); - return EBoxLines::kSingle; -} - -template <> -inline CSSIdentifierValue::CSSIdentifierValue(EBoxOrient e) - : CSSValue(kIdentifierClass) { - switch (e) { - case EBoxOrient::kHorizontal: - value_id_ = CSSValueHorizontal; - break; - case EBoxOrient::kVertical: - value_id_ = CSSValueVertical; - break; - } -} - -template <> -inline EBoxOrient CSSIdentifierValue::ConvertTo() const { - switch (value_id_) { - case CSSValueHorizontal: - case CSSValueInlineAxis: - return EBoxOrient::kHorizontal; - case CSSValueVertical: - case CSSValueBlockAxis: - return EBoxOrient::kVertical; - default: - break; - } - - NOTREACHED(); - return EBoxOrient::kHorizontal; -} - -template <> inline CSSIdentifierValue::CSSIdentifierValue(EFlexDirection e) : CSSValue(kIdentifierClass) { switch (e) {
diff --git a/third_party/WebKit/Source/core/css/CSSProperties.json5 b/third_party/WebKit/Source/core/css/CSSProperties.json5 index a50c99a..d7c367ec 100644 --- a/third_party/WebKit/Source/core/css/CSSProperties.json5 +++ b/third_party/WebKit/Source/core/css/CSSProperties.json5
@@ -1915,7 +1915,7 @@ api_class: "CSSPropertyAPIPerspective", converter: "ConvertPerspective", interpolable: true, - field_template: "storage_only", + field_template: "primitive", type_name: "float", field_group: "rare-non-inherited", default_value: "0.0", @@ -1924,8 +1924,9 @@ name: "perspective-origin", converter: "ConvertPosition", interpolable: true, - field_template: "storage_only", + field_template: "external", type_name: "LengthPoint", + include_paths: ["platform/LengthPoint.h"], field_group: "rare-non-inherited", default_value: "LengthPoint(Length(50.0, kPercent), Length(50.0, kPercent))", }, @@ -2614,7 +2615,7 @@ converter: "ConvertTransformOrigin", getter: "GetTransformOrigin", interpolable: true, - field_template: "storage_only", + field_template: "external", type_name: "TransformOrigin", field_group: "rare-non-inherited->transform", default_value: "TransformOrigin(Length(50.0, kPercent), Length(50.0, kPercent), 0)", @@ -2772,12 +2773,14 @@ field_group: "inherited", default_value: "0", }, + // For valid values of box-align see + // http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#alignment { name: "-webkit-box-align", type_name: "EBoxAlignment", - field_template: "storage_only", - default_value: "EBoxAlignment::kStretch", - field_size: 3, + field_template: "keyword", + keywords: ["stretch", "start", "center", "end", "baseline"], + default_value: "stretch", field_group: "rare-non-inherited->deprecated-flexible-box", }, { @@ -2815,9 +2818,9 @@ { name: "-webkit-box-lines", type_name: "EBoxLines", - field_template: "storage_only", - default_value: "EBoxLines::kSingle", - field_size: 1, + field_template: "keyword", + keywords: ["single", "multiple"], + default_value: "single", field_group: "rare-non-inherited->deprecated-flexible-box", }, { @@ -2832,17 +2835,17 @@ { name: "-webkit-box-orient", type_name: "EBoxOrient", - field_template: "storage_only", - default_value: "EBoxOrient::kHorizontal", - field_size: 1, + field_template: "keyword", + keywords: ["horizontal", "vertical"], + default_value: "horizontal", field_group: "rare-non-inherited->deprecated-flexible-box", }, { name: "-webkit-box-pack", type_name: "EBoxPack", - field_template: "storage_only", - default_value: "EBoxPack::kStart", - field_size: 2, + field_template: "keyword", + keywords: ["start", "center", "end", "justify"], + default_value: "start", field_group: "rare-non-inherited->deprecated-flexible-box", }, {
diff --git a/third_party/WebKit/Source/core/css/CSSValueIDMappings.h b/third_party/WebKit/Source/core/css/CSSValueIDMappings.h index 71405f6..b063980 100644 --- a/third_party/WebKit/Source/core/css/CSSValueIDMappings.h +++ b/third_party/WebKit/Source/core/css/CSSValueIDMappings.h
@@ -34,6 +34,16 @@ } template <> +inline EBoxOrient CssValueIDToPlatformEnum(CSSValueID v) { + if (v == CSSValueInlineAxis) + return EBoxOrient::kHorizontal; + if (v == CSSValueBlockAxis) + return EBoxOrient::kVertical; + + return detail::cssValueIDToPlatformEnumGenerated<EBoxOrient>(v); +} + +template <> inline ETextCombine CssValueIDToPlatformEnum(CSSValueID v) { if (v == CSSValueHorizontal) // -webkit-text-combine return ETextCombine::kAll;
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.cpp b/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.cpp index 2fb9e7d..3ad9133 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.cpp
@@ -4,8 +4,6 @@ #include "core/css/cssom/CSSMatrixComponent.h" -#include <cmath> -#include <memory> #include "core/css/CSSPrimitiveValue.h" #include "platform/wtf/MathExtras.h" @@ -41,89 +39,10 @@ return result; } -CSSMatrixComponent* CSSMatrixComponent::Perspective(double length) { - DOMMatrix* matrix = DOMMatrix::Create(); - - if (length != 0) - matrix->setM34(-1 / length); - return new CSSMatrixComponent(matrix, kPerspectiveType); -} - -CSSMatrixComponent* CSSMatrixComponent::Rotate(double angle) { - DOMMatrix* matrix = DOMMatrix::Create(); - - matrix->rotateSelf(angle); - return new CSSMatrixComponent(matrix, kRotationType); -} - -CSSMatrixComponent* CSSMatrixComponent::Rotate3d(double angle, - double x, - double y, - double z) { - DOMMatrix* matrix = DOMMatrix::Create(); - - matrix->rotateAxisAngleSelf(x, y, z, angle); - return new CSSMatrixComponent(matrix, kRotation3DType); -} - -CSSMatrixComponent* CSSMatrixComponent::Scale(double x, double y) { - DOMMatrix* matrix = DOMMatrix::Create(); - - matrix->setM11(x); - matrix->setM22(y); - return new CSSMatrixComponent(matrix, kScaleType); -} - -CSSMatrixComponent* CSSMatrixComponent::Scale3d(double x, double y, double z) { - DOMMatrix* matrix = DOMMatrix::Create(); - - matrix->setM11(x); - matrix->setM22(y); - matrix->setM33(z); - return new CSSMatrixComponent(matrix, kScale3DType); -} - -CSSMatrixComponent* CSSMatrixComponent::Skew(double ax, double ay) { - double tan_ax = std::tan(deg2rad(ax)); - double tan_ay = std::tan(deg2rad(ay)); - - DOMMatrix* matrix = DOMMatrix::Create(); - - matrix->setM12(tan_ay); - matrix->setM21(tan_ax); - return new CSSMatrixComponent(matrix, kSkewType); -} - -CSSMatrixComponent* CSSMatrixComponent::Translate(double x, double y) { - DOMMatrix* matrix = DOMMatrix::Create(); - - matrix->setM41(x); - matrix->setM42(y); - return new CSSMatrixComponent(matrix, kTranslationType); -} - -CSSMatrixComponent* CSSMatrixComponent::Translate3d(double x, - double y, - double z) { - DOMMatrix* matrix = DOMMatrix::Create(); - - matrix->setM41(x); - matrix->setM42(y); - matrix->setM43(z); - return new CSSMatrixComponent(matrix, kTranslation3DType); -} - CSSMatrixComponent::CSSMatrixComponent(DOMMatrixReadOnly* matrix) : CSSTransformComponent() { matrix_ = DOMMatrix::Create(matrix); is2d_ = matrix->is2D(); } -CSSMatrixComponent::CSSMatrixComponent(DOMMatrixReadOnly* matrix, - TransformComponentType from_type) - : CSSTransformComponent() { - matrix_ = DOMMatrix::Create(matrix); - is2d_ = Is2DComponentType(from_type); -} - } // namespace blink
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.h b/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.h index 4e8f35f..cd4f45f 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSMatrixComponent.h
@@ -5,10 +5,8 @@ #ifndef CSSMatrixComponent_h #define CSSMatrixComponent_h -#include <memory> #include "core/css/cssom/CSSTransformComponent.h" #include "core/geometry/DOMMatrix.h" -#include "platform/transforms/TransformationMatrix.h" namespace blink { @@ -33,29 +31,10 @@ return is2d_ ? kMatrixType : kMatrix3DType; } - // Bindings require a non const return value. - CSSMatrixComponent* asMatrix() const override { - return const_cast<CSSMatrixComponent*>(this); - } + DOMMatrix* AsMatrix() const override { return matrix(); } CSSFunctionValue* ToCSSValue() const override; - static CSSMatrixComponent* Perspective(double length); - - static CSSMatrixComponent* Rotate(double angle); - static CSSMatrixComponent* Rotate3d(double angle, - double x, - double y, - double z); - - static CSSMatrixComponent* Scale(double x, double y); - static CSSMatrixComponent* Scale3d(double x, double y, double z); - - static CSSMatrixComponent* Skew(double x, double y); - - static CSSMatrixComponent* Translate(double x, double y); - static CSSMatrixComponent* Translate3d(double x, double y, double z); - DEFINE_INLINE_VIRTUAL_TRACE() { visitor->Trace(matrix_); CSSTransformComponent::Trace(visitor); @@ -63,7 +42,6 @@ private: CSSMatrixComponent(DOMMatrixReadOnly*); - CSSMatrixComponent(DOMMatrixReadOnly*, TransformComponentType); Member<DOMMatrix> matrix_; bool is2d_;
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSPerspective.h b/third_party/WebKit/Source/core/css/cssom/CSSPerspective.h index eb49ef5..ab30ff0 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSPerspective.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSPerspective.h
@@ -11,6 +11,7 @@ namespace blink { +class DOMMatrix; class ExceptionState; class CORE_EXPORT CSSPerspective : public CSSTransformComponent { @@ -28,8 +29,8 @@ TransformComponentType GetType() const override { return kPerspectiveType; } - // TODO: Implement asMatrix for CSSPerspective. - CSSMatrixComponent* asMatrix() const override { return nullptr; } + // TODO: Implement AsMatrix for CSSPerspective. + DOMMatrix* AsMatrix() const override { return nullptr; } CSSFunctionValue* ToCSSValue() const override;
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSRotation.h b/third_party/WebKit/Source/core/css/cssom/CSSRotation.h index f4d1827e..6c3f75d 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSRotation.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSRotation.h
@@ -5,12 +5,13 @@ #ifndef CSSRotation_h #define CSSRotation_h -#include "core/css/cssom/CSSMatrixComponent.h" #include "core/css/cssom/CSSNumericValue.h" #include "core/css/cssom/CSSTransformComponent.h" namespace blink { +class DOMMatrix; + class CORE_EXPORT CSSRotation final : public CSSTransformComponent { WTF_MAKE_NONCOPYABLE(CSSRotation); DEFINE_WRAPPERTYPEINFO(); @@ -42,7 +43,7 @@ return is2d_ ? kRotationType : kRotation3DType; } - CSSMatrixComponent* asMatrix() const override { + DOMMatrix* AsMatrix() const override { return nullptr; // TODO(meade): Implement. // return is2d_
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSScale.h b/third_party/WebKit/Source/core/css/cssom/CSSScale.h index 5f15568..bbe6e67 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSScale.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSScale.h
@@ -5,8 +5,8 @@ #ifndef CSSScale_h #define CSSScale_h -#include "core/css/cssom/CSSMatrixComponent.h" #include "core/css/cssom/CSSTransformComponent.h" +#include "core/geometry/DOMMatrix.h" namespace blink { @@ -35,9 +35,9 @@ return is2d_ ? kScaleType : kScale3DType; } - CSSMatrixComponent* asMatrix() const override { - return is2d_ ? CSSMatrixComponent::Scale(x_, y_) - : CSSMatrixComponent::Scale3d(x_, y_, z_); + DOMMatrix* AsMatrix() const override { + DOMMatrix* result = DOMMatrix::Create(); + return result->scaleSelf(x_, y_, z_); } CSSFunctionValue* ToCSSValue() const override;
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSSkew.cpp b/third_party/WebKit/Source/core/css/cssom/CSSSkew.cpp index 2849bd19..8f931aa2 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSSkew.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSSkew.cpp
@@ -4,6 +4,7 @@ #include "core/css/cssom/CSSSkew.h" +#include "bindings/core/v8/ExceptionState.h" #include "core/css/CSSFunctionValue.h" #include "core/css/CSSPrimitiveValue.h" #include "core/css/cssom/CSSNumericValue.h"
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSSkew.h b/third_party/WebKit/Source/core/css/cssom/CSSSkew.h index 462f6dc..e55cf42c 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSSkew.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSSkew.h
@@ -5,15 +5,16 @@ #ifndef CSSSkew_h #define CSSSkew_h -#include "core/css/cssom/CSSMatrixComponent.h" #include "core/css/cssom/CSSNumericValue.h" #include "core/css/cssom/CSSTransformComponent.h" namespace blink { +class ExceptionState; + // Represents a skew value in a CSSTransformValue used for properties like // "transform". -// See CSSSkew.idl for more documentation about this class. +// See CSSSkew.idl for more information about this class. class CORE_EXPORT CSSSkew final : public CSSTransformComponent { WTF_MAKE_NONCOPYABLE(CSSSkew); DEFINE_WRAPPERTYPEINFO(); @@ -33,15 +34,14 @@ void setAx(CSSNumericValue*, ExceptionState&); void setAy(CSSNumericValue*, ExceptionState&); - CSSMatrixComponent* asMatrix() const override { + // Internal methods - from CSSTransformComponent. + TransformComponentType GetType() const override { return kSkewType; } + DOMMatrix* AsMatrix() const override { return nullptr; // TODO(meade): Reimplement this once the number/unit types // are re-implemented. // return CSSMatrixComponent::Skew(ax_->degrees(), ay_->degrees()); } - - // Internal methods - from CSSTransformComponent. - TransformComponentType GetType() const override { return kSkewType; } CSSFunctionValue* ToCSSValue() const override; DEFINE_INLINE_VIRTUAL_TRACE() {
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.h b/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.h index 5b2226e..f607337 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.h
@@ -12,7 +12,7 @@ namespace blink { -class CSSMatrixComponent; +class DOMMatrix; class CORE_EXPORT CSSTransformComponent : public GarbageCollectedFinalized<CSSTransformComponent>, @@ -58,7 +58,7 @@ } virtual CSSFunctionValue* ToCSSValue() const = 0; - virtual CSSMatrixComponent* asMatrix() const = 0; + virtual DOMMatrix* AsMatrix() const = 0; DEFINE_INLINE_VIRTUAL_TRACE() {}
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.idl b/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.idl index eab33b4b..17090dd 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.idl +++ b/third_party/WebKit/Source/core/css/cssom/CSSTransformComponent.idl
@@ -12,5 +12,4 @@ ] interface CSSTransformComponent { stringifier; boolean is2D(); - CSSMatrixComponent asMatrix(); };
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSTransformValue.cpp b/third_party/WebKit/Source/core/css/cssom/CSSTransformValue.cpp index 4c9c44a9..e73f121 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSTransformValue.cpp +++ b/third_party/WebKit/Source/core/css/cssom/CSSTransformValue.cpp
@@ -5,7 +5,6 @@ #include "core/css/cssom/CSSTransformValue.h" #include "core/css/CSSValueList.h" -#include "core/css/cssom/CSSMatrixComponent.h" #include "core/css/cssom/CSSTransformComponent.h" #include "core/geometry/DOMMatrix.h" @@ -39,9 +38,9 @@ DOMMatrix* CSSTransformValue::toMatrix() const { DOMMatrix* matrix = DOMMatrix::Create(); for (size_t i = 0; i < transform_components_.size(); i++) { - CSSMatrixComponent* matrixComponent = transform_components_[i]->asMatrix(); + DOMMatrix* matrixComponent = transform_components_[i]->AsMatrix(); if (matrixComponent) { - matrix->multiplySelf(matrixComponent->matrix()); + matrix->multiplySelf(matrixComponent); } } return matrix;
diff --git a/third_party/WebKit/Source/core/css/cssom/CSSTranslation.h b/third_party/WebKit/Source/core/css/cssom/CSSTranslation.h index d4e2d2b..db64940 100644 --- a/third_party/WebKit/Source/core/css/cssom/CSSTranslation.h +++ b/third_party/WebKit/Source/core/css/cssom/CSSTranslation.h
@@ -10,6 +10,7 @@ namespace blink { class CSSNumericValue; +class DOMMatrix; class ExceptionState; class CORE_EXPORT CSSTranslation final : public CSSTransformComponent { @@ -39,8 +40,8 @@ return Is2D() ? kTranslationType : kTranslation3DType; } - // TODO: Implement asMatrix for CSSTranslation. - CSSMatrixComponent* asMatrix() const override { return nullptr; } + // TODO: Implement AsMatrix for CSSTranslation. + DOMMatrix* AsMatrix() const override { return nullptr; } CSSFunctionValue* ToCSSValue() const override;
diff --git a/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp b/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp index 54d3b49..0f3e1d22 100644 --- a/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp +++ b/third_party/WebKit/Source/core/html/HTMLSlotElement.cpp
@@ -30,6 +30,7 @@ #include "core/html/HTMLSlotElement.h" +#include <array> #include "core/HTMLNames.h" #include "core/dom/NodeTraversal.h" #include "core/dom/StyleChangeReason.h" @@ -47,6 +48,10 @@ using namespace HTMLNames; +namespace { +constexpr size_t kLCSTableSizeLimit = 16; +} + inline HTMLSlotElement::HTMLSlotElement(Document& document) : HTMLElement(slotTag, document) { UseCounter::Count(document, WebFeature::kHTMLSlotElement); @@ -113,8 +118,6 @@ } void HTMLSlotElement::ClearDistribution() { - // TODO(hayato): Figure out when to call - // lazyReattachDistributedNodesIfNeeded() assigned_nodes_.clear(); distributed_nodes_.clear(); distributed_indices_.clear(); @@ -276,14 +279,58 @@ } } +void HTMLSlotElement::LazyReattachDistributedNodesByDynamicProgramming( + const HeapVector<Member<Node>>& nodes1, + const HeapVector<Member<Node>>& nodes2) { + // Use dynamic programming to minimize the number of nodes being reattached. + using LCSTable = + std::array<std::array<size_t, kLCSTableSizeLimit>, kLCSTableSizeLimit>; + using Backtrack = std::pair<size_t, size_t>; + using BacktrackTable = + std::array<std::array<Backtrack, kLCSTableSizeLimit>, kLCSTableSizeLimit>; + + DEFINE_STATIC_LOCAL(LCSTable*, lcs_table, (new LCSTable)); + DEFINE_STATIC_LOCAL(BacktrackTable*, backtrack_table, (new BacktrackTable)); + + FillLongestCommonSubsequenceDynamicProgrammingTable( + nodes1, nodes2, *lcs_table, *backtrack_table); + + size_t r = nodes1.size(); + size_t c = nodes2.size(); + while (r > 0 && c > 0) { + Backtrack backtrack = (*backtrack_table)[r][c]; + if (backtrack == std::make_pair(r - 1, c - 1)) { + DCHECK_EQ(nodes1[r - 1], nodes2[c - 1]); + } else if (backtrack == std::make_pair(r - 1, c)) { + nodes1[r - 1]->LazyReattachIfAttached(); + } else { + DCHECK(backtrack == std::make_pair(r, c - 1)); + nodes2[c - 1]->LazyReattachIfAttached(); + } + std::tie(r, c) = backtrack; + } + if (r > 0) { + for (size_t i = 0; i < r; ++i) + nodes1[i]->LazyReattachIfAttached(); + } else if (c > 0) { + for (size_t i = 0; i < c; ++i) + nodes2[i]->LazyReattachIfAttached(); + } +} + void HTMLSlotElement::LazyReattachDistributedNodesIfNeeded() { - // TODO(hayato): Figure out an exact condition where reattach is required - if (old_distributed_nodes_ != distributed_nodes_) { - for (auto& node : old_distributed_nodes_) - node->LazyReattachIfAttached(); - for (auto& node : distributed_nodes_) - node->LazyReattachIfAttached(); - probe::didPerformSlotDistribution(this); + if (old_distributed_nodes_ == distributed_nodes_) + return; + probe::didPerformSlotDistribution(this); + + if (old_distributed_nodes_.size() + 1 > kLCSTableSizeLimit || + distributed_nodes_.size() + 1 > kLCSTableSizeLimit) { + // Since DP takes O(N^2), we don't use DP if the size is larger than the + // pre-defined limit. + LazyReattachDistributedNodesNaive(); + } else { + LazyReattachDistributedNodesByDynamicProgramming(old_distributed_nodes_, + distributed_nodes_); } old_distributed_nodes_.clear(); } @@ -301,6 +348,14 @@ CheckSlotChange(SlotChangeType::kSuppressSlotChangeEvent); } +void HTMLSlotElement::LazyReattachDistributedNodesNaive() { + // TODO(hayato): Use some heuristic to avoid reattaching all nodes + for (auto& node : old_distributed_nodes_) + node->LazyReattachIfAttached(); + for (auto& node : distributed_nodes_) + node->LazyReattachIfAttached(); +} + void HTMLSlotElement::DidSlotChange(SlotChangeType slot_change_type) { DCHECK(SupportsDistribution()); if (slot_change_type == SlotChangeType::kSignalSlotChangeEvent)
diff --git a/third_party/WebKit/Source/core/html/HTMLSlotElement.h b/third_party/WebKit/Source/core/html/HTMLSlotElement.h index 53e4ba7..0711e87 100644 --- a/third_party/WebKit/Source/core/html/HTMLSlotElement.h +++ b/third_party/WebKit/Source/core/html/HTMLSlotElement.h
@@ -117,11 +117,56 @@ bool HasSlotableChild() const; + void LazyReattachDistributedNodesNaive(); + + static void LazyReattachDistributedNodesByDynamicProgramming( + const HeapVector<Member<Node>>&, + const HeapVector<Member<Node>>&); + HeapVector<Member<Node>> assigned_nodes_; HeapVector<Member<Node>> distributed_nodes_; HeapVector<Member<Node>> old_distributed_nodes_; HeapHashMap<Member<const Node>, size_t> distributed_indices_; bool slotchange_event_enqueued_ = false; + + // TODO(hayato): Move this to more appropriate directory (e.g. platform/wtf) + // if there are more than one usages. + template <typename Container, typename LCSTable, typename BacktrackTable> + static void FillLongestCommonSubsequenceDynamicProgrammingTable( + const Container& seq1, + const Container& seq2, + LCSTable& lcs_table, + BacktrackTable& backtrack_table) { + const size_t rows = seq1.size(); + const size_t columns = seq2.size(); + + DCHECK_GT(lcs_table.size(), rows); + DCHECK_GT(lcs_table[0].size(), columns); + DCHECK_GT(backtrack_table.size(), rows); + DCHECK_GT(backtrack_table[0].size(), columns); + + for (size_t r = 0; r <= rows; ++r) + lcs_table[r][0] = 0; + for (size_t c = 0; c <= columns; ++c) + lcs_table[0][c] = 0; + + for (size_t r = 1; r <= rows; ++r) { + for (size_t c = 1; c <= columns; ++c) { + if (seq1[r - 1] == seq2[c - 1]) { + lcs_table[r][c] = lcs_table[r - 1][c - 1] + 1; + backtrack_table[r][c] = std::make_pair(r - 1, c - 1); + } else if (lcs_table[r - 1][c] > lcs_table[r][c - 1]) { + lcs_table[r][c] = lcs_table[r - 1][c]; + backtrack_table[r][c] = std::make_pair(r - 1, c); + } else { + lcs_table[r][c] = lcs_table[r][c - 1]; + backtrack_table[r][c] = std::make_pair(r, c - 1); + } + } + } + } + + friend class HTMLSlotElementTest; }; } // namespace blink
diff --git a/third_party/WebKit/Source/core/html/HTMLSlotElementTest.cpp b/third_party/WebKit/Source/core/html/HTMLSlotElementTest.cpp new file mode 100644 index 0000000..1f05e6e --- /dev/null +++ b/third_party/WebKit/Source/core/html/HTMLSlotElementTest.cpp
@@ -0,0 +1,131 @@ +// Copyright 2017 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. + +#include "core/html/HTMLSlotElement.h" + +#include <array> + +#include "testing/gtest/include/gtest/gtest.h" + +namespace blink { + +namespace { +constexpr int kTableSize = 16; +using Seq = std::vector<char>; +using Backtrack = std::pair<size_t, size_t>; +} + +class HTMLSlotElementTest : public testing::Test { + protected: + HTMLSlotElementTest() {} + Seq LongestCommonSubsequence(const Seq& seq1, const Seq& seq2); + std::array<std::array<size_t, kTableSize>, kTableSize> lcs_table_; + std::array<std::array<Backtrack, kTableSize>, kTableSize> backtrack_table_; +}; + +std::vector<char> HTMLSlotElementTest::LongestCommonSubsequence( + const Seq& seq1, + const Seq& seq2) { + HTMLSlotElement::FillLongestCommonSubsequenceDynamicProgrammingTable( + seq1, seq2, lcs_table_, backtrack_table_); + Seq lcs; + size_t r = seq1.size(); + size_t c = seq2.size(); + while (r > 0 && c > 0) { + Backtrack backtrack = backtrack_table_[r][c]; + if (backtrack == std::make_pair(r - 1, c - 1)) { + DCHECK_EQ(seq1[r - 1], seq2[c - 1]); + lcs.push_back(seq1[r - 1]); + } + std::tie(r, c) = backtrack; + } + std::reverse(lcs.begin(), lcs.end()); + EXPECT_EQ(lcs_table_[seq1.size()][seq2.size()], lcs.size()); + return lcs; +} + +TEST_F(HTMLSlotElementTest, LongestCommonSubsequence) { + const Seq kEmpty; + { + Seq seq1{}; + Seq seq2{}; + EXPECT_EQ(kEmpty, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{'a'}; + Seq seq2{}; + EXPECT_EQ(kEmpty, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{}; + Seq seq2{'a'}; + EXPECT_EQ(kEmpty, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{'a'}; + Seq seq2{'a'}; + EXPECT_EQ(Seq{'a'}, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{'a', 'b'}; + Seq seq2{'a'}; + EXPECT_EQ(Seq{'a'}, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{'a', 'b'}; + Seq seq2{'b', 'a'}; + EXPECT_TRUE(LongestCommonSubsequence(seq1, seq2) == Seq{'a'} || + LongestCommonSubsequence(seq1, seq2) == Seq{'b'}); + } + { + Seq seq1{'a', 'b', 'c', 'd'}; + Seq seq2{}; + EXPECT_EQ(kEmpty, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{'a', 'b', 'c', 'd'}; + Seq seq2{'1', 'a', 'b', 'd'}; + Seq lcs{'a', 'b', 'd'}; + EXPECT_EQ(lcs, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{'a', 'b', 'c', 'd'}; + Seq seq2{'b', 'a', 'c'}; + Seq lcs1{'a', 'c'}; + Seq lcs2{'b', 'c'}; + EXPECT_TRUE(LongestCommonSubsequence(seq1, seq2) == lcs1 || + LongestCommonSubsequence(seq1, seq2) == lcs2); + } + { + Seq seq1{'a', 'b', 'c', 'd'}; + Seq seq2{'1', 'b', '2', 'd', '1'}; + Seq lcs{'b', 'd'}; + EXPECT_EQ(lcs, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{'a', 'b', 'c', 'd'}; + Seq seq2{'a', 'd'}; + Seq lcs{'a', 'd'}; + EXPECT_EQ(lcs, LongestCommonSubsequence(seq1, seq2)); + } + { + Seq seq1{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; + Seq seq2{'g', 'a', 'b', '1', 'd', '2', '3', 'h', '4'}; + Seq lcs{'a', 'b', 'd', 'h'}; + EXPECT_EQ(lcs, LongestCommonSubsequence(seq1, seq2)); + } +} + +TEST_F(HTMLSlotElementTest, TableSizeLimit) { + Seq seq1; + // If we use kTableSize here, it should hit DCHECK(). + std::fill_n(std::back_inserter(seq1), kTableSize - 1, 'a'); + Seq seq2; + std::fill_n(std::back_inserter(seq2), kTableSize - 1, 'a'); + Seq lcs; + std::fill_n(std::back_inserter(lcs), kTableSize - 1, 'a'); + EXPECT_EQ(lcs, LongestCommonSubsequence(seq1, seq2)); +} + +} // namespace blink
diff --git a/third_party/WebKit/Source/core/html/HTMLTableCellElement.h b/third_party/WebKit/Source/core/html/HTMLTableCellElement.h index cb02550..de45ef51 100644 --- a/third_party/WebKit/Source/core/html/HTMLTableCellElement.h +++ b/third_party/WebKit/Source/core/html/HTMLTableCellElement.h
@@ -50,11 +50,15 @@ const AtomicString& Headers() const; void setRowSpan(unsigned); - // Public so that HTMLTableColElement can use MaxColSpan. MaxRowSpan is only - // used by this class but keeping them together seems desirable. - // https://html.spec.whatwg.org/#dom-tdth-colspan - static unsigned MaxColSpan() { return 1000u; } - // https://html.spec.whatwg.org/#dom-tdth-rowspan + // Rowspan: match Firefox's limit of 65,534. Edge has a higher limit, at + // least 2^17. + // Colspan: Firefox uses a limit of 1,000 for colspan and resets the value to + // 1. + // TODO(dgrogan): Change these to HTML's new specified behavior when + // https://github.com/whatwg/html/issues/1198 is resolved. + // Public so that HTMLColElement can use maxColSpan. maxRowSpan is only used + // by this class but keeping them together seems desirable. + static unsigned MaxColSpan() { return 8190u; } static unsigned MaxRowSpan() { return 65534u; } private:
diff --git a/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp b/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp index 0b07bd9..34d3fd84 100644 --- a/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutDeprecatedFlexibleBox.cpp
@@ -596,7 +596,7 @@ child_y += child->MarginTop() + (max_ascent - ascent); break; } - case EBoxAlignment::kBend: + case EBoxAlignment::kEnd: child_y += ContentHeight() - child->MarginBottom() - child->Size().Height(); break; @@ -870,7 +870,7 @@ 2) .ClampNegativeToZero(); break; - case EBoxAlignment::kBend: + case EBoxAlignment::kEnd: if (!Style()->IsLeftToRightDirection()) { child_x += child->MarginLeft(); } else {
diff --git a/third_party/WebKit/Source/core/layout/LayoutTableCellTest.cpp b/third_party/WebKit/Source/core/layout/LayoutTableCellTest.cpp index 07a57bc..8ae6c8c 100644 --- a/third_party/WebKit/Source/core/layout/LayoutTableCellTest.cpp +++ b/third_party/WebKit/Source/core/layout/LayoutTableCellTest.cpp
@@ -90,12 +90,12 @@ TEST_F(LayoutTableCellTest, ResetColspanIfTooBig) { SetBodyInnerHTML("<table><td id='cell' colspan='14000'></td></table>"); - ASSERT_EQ(GetCellByElementId("cell")->ColSpan(), 1000U); + ASSERT_EQ(GetCellByElementId("cell")->ColSpan(), 8190U); } TEST_F(LayoutTableCellTest, DoNotResetColspanJustBelowBoundary) { - SetBodyInnerHTML("<table><td id='cell' colspan='1000'></td></table>"); - ASSERT_EQ(GetCellByElementId("cell")->ColSpan(), 1000U); + SetBodyInnerHTML("<table><td id='cell' colspan='8190'></td></table>"); + ASSERT_EQ(GetCellByElementId("cell")->ColSpan(), 8190U); } TEST_F(LayoutTableCellTest, ResetRowspanIfTooBig) {
diff --git a/third_party/WebKit/Source/core/style/ComputedStyle.h b/third_party/WebKit/Source/core/style/ComputedStyle.h index ea878fe..4d036c5 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyle.h +++ b/third_party/WebKit/Source/core/style/ComputedStyle.h
@@ -779,30 +779,6 @@ SET_NESTED_VAR(rare_non_inherited_data_, flexible_box_data_, flex_wrap_, w); } - // -webkit-box-align - // For valid values of box-align see - // http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/#alignment - static EBoxAlignment InitialBoxAlign() { return EBoxAlignment::kStretch; } - EBoxAlignment BoxAlign() const { - return static_cast<EBoxAlignment>( - rare_non_inherited_data_->deprecated_flexible_box_data_->box_align_); - } - void SetBoxAlign(EBoxAlignment a) { - SET_NESTED_VAR(rare_non_inherited_data_, deprecated_flexible_box_data_, - box_align_, static_cast<unsigned>(a)); - } - - // -webkit-box-lines - static EBoxLines InitialBoxLines() { return EBoxLines::kSingle; } - EBoxLines BoxLines() const { - return static_cast<EBoxLines>( - rare_non_inherited_data_->deprecated_flexible_box_data_->box_lines_); - } - void SetBoxLines(EBoxLines lines) { - SET_NESTED_VAR(rare_non_inherited_data_, deprecated_flexible_box_data_, - box_lines_, static_cast<unsigned>(lines)); - } - // -webkit-box-ordinal-group static unsigned InitialBoxOrdinalGroup() { return 1; } unsigned BoxOrdinalGroup() const { @@ -815,28 +791,6 @@ std::min(std::numeric_limits<unsigned>::max() - 1, og)); } - // -webkit-box-orient - static EBoxOrient InitialBoxOrient() { return EBoxOrient::kHorizontal; } - EBoxOrient BoxOrient() const { - return static_cast<EBoxOrient>( - rare_non_inherited_data_->deprecated_flexible_box_data_->box_orient_); - } - void SetBoxOrient(EBoxOrient o) { - SET_NESTED_VAR(rare_non_inherited_data_, deprecated_flexible_box_data_, - box_orient_, static_cast<unsigned>(o)); - } - - // -webkit-box-pack - static EBoxPack InitialBoxPack() { return EBoxPack::kStart; } - EBoxPack BoxPack() const { - return static_cast<EBoxPack>( - rare_non_inherited_data_->deprecated_flexible_box_data_->box_pack_); - } - void SetBoxPack(EBoxPack p) { - SET_NESTED_VAR(rare_non_inherited_data_, deprecated_flexible_box_data_, - box_pack_, static_cast<unsigned>(p)); - } - // -webkit-box-reflect static StyleReflection* InitialBoxReflect() { return 0; } StyleReflection* BoxReflect() const { @@ -1007,24 +961,6 @@ SET_VAR(rare_non_inherited_data_, outline_.offset_, v); } - // perspective (aka -webkit-perspective) - static float InitialPerspective() { return 0; } - float Perspective() const { return rare_non_inherited_data_->perspective_; } - void SetPerspective(float p) { - SET_VAR(rare_non_inherited_data_, perspective_, p); - } - - // perspective-origin (aka -webkit-perspective-origin) - static LengthPoint InitialPerspectiveOrigin() { - return LengthPoint(Length(50.0, kPercent), Length(50.0, kPercent)); - } - const LengthPoint& PerspectiveOrigin() const { - return rare_non_inherited_data_->perspective_origin_; - } - void SetPerspectiveOrigin(const LengthPoint& p) { - SET_VAR(rare_non_inherited_data_, perspective_origin_, p); - } - // -webkit-perspective-origin-x static Length InitialPerspectiveOriginX() { return Length(50.0, kPercent); } const Length& PerspectiveOriginX() const { return PerspectiveOrigin().X(); } @@ -1052,18 +988,6 @@ transform_operations_, ops); } - // transform-origin (aka -webkit-transform-origin) - static TransformOrigin InitialTransformOrigin() { - return TransformOrigin(Length(50.0, kPercent), Length(50.0, kPercent), 0); - } - const TransformOrigin& GetTransformOrigin() const { - return rare_non_inherited_data_->transform_data_->transform_origin_; - } - void SetTransformOrigin(const TransformOrigin& o) { - SET_NESTED_VAR(rare_non_inherited_data_, transform_data_, transform_origin_, - o); - } - // -webkit-transform-origin-x static Length InitialTransformOriginX() { return Length(50.0, kPercent); } const Length& TransformOriginX() const { return GetTransformOrigin().X(); }
diff --git a/third_party/WebKit/Source/core/style/ComputedStyleConstants.h b/third_party/WebKit/Source/core/style/ComputedStyleConstants.h index 24b2fb5..4f52a19 100644 --- a/third_party/WebKit/Source/core/style/ComputedStyleConstants.h +++ b/third_party/WebKit/Source/core/style/ComputedStyleConstants.h
@@ -148,13 +148,6 @@ // CSS Mask Source Types enum EMaskSourceType { kMaskAlpha, kMaskLuminance }; -// Deprecated Flexible Box Properties - -enum class EBoxPack { kStart, kCenter, kEnd, kJustify }; -enum class EBoxAlignment { kStretch, kStart, kCenter, kBend, kBaseline }; -enum class EBoxOrient { kHorizontal, kVertical }; -enum class EBoxLines { kSingle, kMultiple }; - // CSS3 Flexbox Properties enum class EFlexDirection { kRow, kRowReverse, kColumn, kColumnReverse };
diff --git a/third_party/WebKit/Source/modules/quota/BUILD.gn b/third_party/WebKit/Source/modules/quota/BUILD.gn index fcd9e3c..7e2c269b 100644 --- a/third_party/WebKit/Source/modules/quota/BUILD.gn +++ b/third_party/WebKit/Source/modules/quota/BUILD.gn
@@ -25,8 +25,6 @@ "StorageQuotaCallback.h", "StorageQuotaClient.cpp", "StorageQuotaClient.h", - "StorageQuotaClientImpl.cpp", - "StorageQuotaClientImpl.h", "StorageUsageCallback.h", "WorkerNavigatorStorageQuota.cpp", "WorkerNavigatorStorageQuota.h",
diff --git a/third_party/WebKit/Source/modules/quota/StorageQuotaClient.cpp b/third_party/WebKit/Source/modules/quota/StorageQuotaClient.cpp index c3fac27..feb8b76 100644 --- a/third_party/WebKit/Source/modules/quota/StorageQuotaClient.cpp +++ b/third_party/WebKit/Source/modules/quota/StorageQuotaClient.cpp
@@ -31,11 +31,43 @@ #include "StorageQuotaClient.h" #include "core/dom/Document.h" +#include "core/dom/ExecutionContext.h" +#include "core/dom/TaskRunnerHelper.h" +#include "core/frame/WebLocalFrameBase.h" #include "core/page/Page.h" #include "core/workers/WorkerGlobalScope.h" +#include "modules/quota/DeprecatedStorageQuotaCallbacksImpl.h" +#include "modules/quota/StorageErrorCallback.h" +#include "modules/quota/StorageQuotaCallback.h" +#include "public/platform/WebStorageQuotaType.h" +#include "public/web/WebFrameClient.h" namespace blink { +StorageQuotaClient::StorageQuotaClient() {} + +StorageQuotaClient::~StorageQuotaClient() {} + +void StorageQuotaClient::RequestQuota(ScriptState* script_state, + WebStorageQuotaType storage_type, + unsigned long long new_quota_in_bytes, + StorageQuotaCallback* success_callback, + StorageErrorCallback* error_callback) { + ExecutionContext* execution_context = ExecutionContext::From(script_state); + DCHECK(execution_context); + DCHECK(execution_context->IsDocument()) + << "Quota requests are not supported in workers"; + + Document* document = ToDocument(execution_context); + WebLocalFrameBase* web_frame = + WebLocalFrameBase::FromFrame(document->GetFrame()); + StorageQuotaCallbacks* callbacks = + DeprecatedStorageQuotaCallbacksImpl::Create(success_callback, + error_callback); + web_frame->Client()->RequestStorageQuota(storage_type, new_quota_in_bytes, + callbacks); +} + const char* StorageQuotaClient::SupplementName() { return "StorageQuotaClient"; }
diff --git a/third_party/WebKit/Source/modules/quota/StorageQuotaClient.h b/third_party/WebKit/Source/modules/quota/StorageQuotaClient.h index 3c5a2887..93705d5 100644 --- a/third_party/WebKit/Source/modules/quota/StorageQuotaClient.h +++ b/third_party/WebKit/Source/modules/quota/StorageQuotaClient.h
@@ -33,6 +33,7 @@ #include "core/page/Page.h" #include "modules/ModulesExport.h" +#include "modules/quota/StorageQuotaClient.h" #include "platform/Supplementable.h" #include "platform/heap/Handle.h" #include "platform/wtf/Forward.h" @@ -45,21 +46,30 @@ class StorageErrorCallback; class StorageQuotaCallback; -class StorageQuotaClient : public Supplement<Page> { +class MODULES_EXPORT StorageQuotaClient + : public GarbageCollectedFinalized<StorageQuotaClient>, + public Supplement<Page> { WTF_MAKE_NONCOPYABLE(StorageQuotaClient); + USING_GARBAGE_COLLECTED_MIXIN(StorageQuotaClient); public: - StorageQuotaClient() {} - virtual ~StorageQuotaClient() {} + static StorageQuotaClient* Create() { return new StorageQuotaClient(); } - virtual void RequestQuota(ScriptState*, - WebStorageQuotaType, - unsigned long long new_quota_in_bytes, - StorageQuotaCallback*, - StorageErrorCallback*) = 0; + virtual ~StorageQuotaClient(); + + void RequestQuota(ScriptState*, + WebStorageQuotaType, + unsigned long long new_quota_in_bytes, + StorageQuotaCallback*, + StorageErrorCallback*); static const char* SupplementName(); static StorageQuotaClient* From(ExecutionContext*); + + DEFINE_INLINE_VIRTUAL_TRACE() { Supplement<Page>::Trace(visitor); } + + private: + StorageQuotaClient(); }; MODULES_EXPORT void ProvideStorageQuotaClientTo(Page&, StorageQuotaClient*);
diff --git a/third_party/WebKit/Source/modules/quota/StorageQuotaClientImpl.cpp b/third_party/WebKit/Source/modules/quota/StorageQuotaClientImpl.cpp deleted file mode 100644 index a257a6a..0000000 --- a/third_party/WebKit/Source/modules/quota/StorageQuotaClientImpl.cpp +++ /dev/null
@@ -1,70 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#include "modules/quota/StorageQuotaClientImpl.h" - -#include "core/dom/Document.h" -#include "core/dom/ExecutionContext.h" -#include "core/dom/TaskRunnerHelper.h" -#include "core/frame/WebLocalFrameBase.h" -#include "modules/quota/DeprecatedStorageQuotaCallbacksImpl.h" -#include "modules/quota/StorageErrorCallback.h" -#include "modules/quota/StorageQuotaCallback.h" -#include "public/platform/WebStorageQuotaType.h" -#include "public/web/WebFrameClient.h" - -namespace blink { - -StorageQuotaClientImpl::StorageQuotaClientImpl() {} - -StorageQuotaClientImpl::~StorageQuotaClientImpl() {} - -void StorageQuotaClientImpl::RequestQuota( - ScriptState* script_state, - WebStorageQuotaType storage_type, - unsigned long long new_quota_in_bytes, - StorageQuotaCallback* success_callback, - StorageErrorCallback* error_callback) { - ExecutionContext* execution_context = ExecutionContext::From(script_state); - DCHECK(execution_context); - DCHECK(execution_context->IsDocument()) - << "Quota requests are not supported in workers"; - - Document* document = ToDocument(execution_context); - WebLocalFrameBase* web_frame = - WebLocalFrameBase::FromFrame(document->GetFrame()); - StorageQuotaCallbacks* callbacks = - DeprecatedStorageQuotaCallbacksImpl::Create(success_callback, - error_callback); - web_frame->Client()->RequestStorageQuota(storage_type, new_quota_in_bytes, - callbacks); -} - -} // namespace blink
diff --git a/third_party/WebKit/Source/modules/quota/StorageQuotaClientImpl.h b/third_party/WebKit/Source/modules/quota/StorageQuotaClientImpl.h deleted file mode 100644 index b639bea8..0000000 --- a/third_party/WebKit/Source/modules/quota/StorageQuotaClientImpl.h +++ /dev/null
@@ -1,67 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the - * distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived from - * this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef StorageQuotaClientImpl_h -#define StorageQuotaClientImpl_h - -#include "modules/ModulesExport.h" -#include "modules/quota/StorageQuotaClient.h" -#include "platform/wtf/Forward.h" - -namespace blink { - -// TODO(sashab): Merge this into StorageQuotaClient. -class MODULES_EXPORT StorageQuotaClientImpl - : public GarbageCollectedFinalized<StorageQuotaClientImpl>, - NON_EXPORTED_BASE(public StorageQuotaClient) { - USING_GARBAGE_COLLECTED_MIXIN(StorageQuotaClientImpl); - - public: - static StorageQuotaClientImpl* Create() { - return new StorageQuotaClientImpl(); - } - - ~StorageQuotaClientImpl() override; - - void RequestQuota(ScriptState*, - WebStorageQuotaType, - unsigned long long new_quota_in_bytes, - StorageQuotaCallback*, - StorageErrorCallback*) override; - - DEFINE_INLINE_VIRTUAL_TRACE() { StorageQuotaClient::Trace(visitor); } - - private: - StorageQuotaClientImpl(); -}; - -} // namespace blink - -#endif // StorageQuotaClientImpl_h
diff --git a/third_party/WebKit/Source/modules/storage/BUILD.gn b/third_party/WebKit/Source/modules/storage/BUILD.gn index bef863f..af41ab6 100644 --- a/third_party/WebKit/Source/modules/storage/BUILD.gn +++ b/third_party/WebKit/Source/modules/storage/BUILD.gn
@@ -16,9 +16,8 @@ "Storage.h", "StorageArea.cpp", "StorageArea.h", + "StorageClient.cpp", "StorageClient.h", - "StorageClientImpl.cpp", - "StorageClientImpl.h", "StorageEvent.cpp", "StorageEvent.h", "StorageNamespace.cpp",
diff --git a/third_party/WebKit/Source/modules/storage/StorageClientImpl.cpp b/third_party/WebKit/Source/modules/storage/StorageClient.cpp similarity index 88% rename from third_party/WebKit/Source/modules/storage/StorageClientImpl.cpp rename to third_party/WebKit/Source/modules/storage/StorageClient.cpp index c58aea55..6a237dac 100644 --- a/third_party/WebKit/Source/modules/storage/StorageClientImpl.cpp +++ b/third_party/WebKit/Source/modules/storage/StorageClient.cpp
@@ -23,7 +23,7 @@ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include "modules/storage/StorageClientImpl.h" +#include "modules/storage/StorageClient.h" #include <memory> #include "core/exported/WebViewBase.h" @@ -43,19 +43,18 @@ STATIC_ASSERT_MATCHING_ENUM(kSessionStorage, ContentSettingsClient::StorageType::kSession); -StorageClientImpl::StorageClientImpl(WebViewBase* web_view) - : web_view_(web_view) {} +StorageClient::StorageClient(WebViewBase* web_view) : web_view_(web_view) {} std::unique_ptr<StorageNamespace> -StorageClientImpl::CreateSessionStorageNamespace() { +StorageClient::CreateSessionStorageNamespace() { if (!web_view_->Client()) return nullptr; return WTF::WrapUnique(new StorageNamespace( WTF::WrapUnique(web_view_->Client()->CreateSessionStorageNamespace()))); } -bool StorageClientImpl::CanAccessStorage(LocalFrame* frame, - StorageType type) const { +bool StorageClient::CanAccessStorage(LocalFrame* frame, + StorageType type) const { DCHECK(frame->GetContentSettingsClient()); return frame->GetContentSettingsClient()->AllowStorage( static_cast<ContentSettingsClient::StorageType>(type));
diff --git a/third_party/WebKit/Source/modules/storage/StorageClient.h b/third_party/WebKit/Source/modules/storage/StorageClient.h index da80c63..eb2f40a7 100644 --- a/third_party/WebKit/Source/modules/storage/StorageClient.h +++ b/third_party/WebKit/Source/modules/storage/StorageClient.h
@@ -5,19 +5,26 @@ #ifndef StorageClient_h #define StorageClient_h -#include "modules/storage/StorageArea.h" #include <memory> +#include "modules/ModulesExport.h" +#include "modules/storage/StorageArea.h" +#include "modules/storage/StorageClient.h" namespace blink { class StorageNamespace; +class WebViewBase; -class StorageClient { +class MODULES_EXPORT StorageClient { public: - virtual ~StorageClient() {} + explicit StorageClient(WebViewBase*); + ~StorageClient() {} - virtual std::unique_ptr<StorageNamespace> CreateSessionStorageNamespace() = 0; - virtual bool CanAccessStorage(LocalFrame*, StorageType) const = 0; + std::unique_ptr<StorageNamespace> CreateSessionStorageNamespace(); + bool CanAccessStorage(LocalFrame*, StorageType) const; + + private: + WebViewBase* web_view_; }; } // namespace blink
diff --git a/third_party/WebKit/Source/modules/storage/StorageClientImpl.h b/third_party/WebKit/Source/modules/storage/StorageClientImpl.h deleted file mode 100644 index 7d3c920..0000000 --- a/third_party/WebKit/Source/modules/storage/StorageClientImpl.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 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. - -#ifndef StorageClientImpl_h -#define StorageClientImpl_h - -#include <memory> -#include "modules/ModulesExport.h" -#include "modules/storage/StorageClient.h" - -namespace blink { - -class WebViewBase; - -// TODO(sashab): Merge this into StorageClient. -class MODULES_EXPORT StorageClientImpl - : NON_EXPORTED_BASE(public StorageClient) { - public: - explicit StorageClientImpl(WebViewBase*); - - std::unique_ptr<StorageNamespace> CreateSessionStorageNamespace() override; - bool CanAccessStorage(LocalFrame*, StorageType) const override; - - private: - WebViewBase* web_view_; -}; - -} // namespace blink - -#endif // StorageClientImpl_h
diff --git a/third_party/WebKit/Source/platform/BUILD.gn b/third_party/WebKit/Source/platform/BUILD.gn index 1f3e9914..55e3de9 100644 --- a/third_party/WebKit/Source/platform/BUILD.gn +++ b/third_party/WebKit/Source/platform/BUILD.gn
@@ -572,6 +572,7 @@ "exported/WebHTTPLoadInfo.cpp", "exported/WebImage.cpp", "exported/WebImageGenerator.cpp", + "exported/WebInputEvent.cpp", "exported/WebMediaConstraints.cpp", "exported/WebMediaDeviceInfo.cpp", "exported/WebMediaPlayerClient.cpp",
diff --git a/third_party/WebKit/Source/web/WebInputEvent.cpp b/third_party/WebKit/Source/platform/exported/WebInputEvent.cpp similarity index 100% rename from third_party/WebKit/Source/web/WebInputEvent.cpp rename to third_party/WebKit/Source/platform/exported/WebInputEvent.cpp
diff --git a/third_party/WebKit/Source/web/BUILD.gn b/third_party/WebKit/Source/web/BUILD.gn index 6ae0715..459112d7 100644 --- a/third_party/WebKit/Source/web/BUILD.gn +++ b/third_party/WebKit/Source/web/BUILD.gn
@@ -63,7 +63,6 @@ "WebHelperPluginImpl.cpp", "WebHelperPluginImpl.h", "WebHitTestResult.cpp", - "WebInputEvent.cpp", "WebKit.cpp", "WebLeakDetector.cpp", "WebLocalFrameImpl.cpp",
diff --git a/third_party/WebKit/Source/web/WebViewImpl.cpp b/third_party/WebKit/Source/web/WebViewImpl.cpp index 34ca4911..c90140f 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.cpp +++ b/third_party/WebKit/Source/web/WebViewImpl.cpp
@@ -104,7 +104,7 @@ #include "modules/compositorworker/CompositorWorkerProxyClientImpl.h" #include "modules/credentialmanager/CredentialManagerClient.h" #include "modules/encryptedmedia/MediaKeysController.h" -#include "modules/quota/StorageQuotaClientImpl.h" +#include "modules/quota/StorageQuotaClient.h" #include "modules/speech/SpeechRecognitionClientProxy.h" #include "modules/storage/StorageNamespaceController.h" #include "modules/webdatabase/DatabaseClient.h" @@ -392,7 +392,7 @@ ProvideContextFeaturesTo(*page_, ContextFeaturesClientImpl::Create()); ProvideDatabaseClientTo(*page_, new DatabaseClient); - ProvideStorageQuotaClientTo(*page_, StorageQuotaClientImpl::Create()); + ProvideStorageQuotaClientTo(*page_, StorageQuotaClient::Create()); page_->SetValidationMessageClient(ValidationMessageClientImpl::Create(*this)); StorageNamespaceController::ProvideStorageNamespaceTo(*page_, &storage_client_impl_);
diff --git a/third_party/WebKit/Source/web/WebViewImpl.h b/third_party/WebKit/Source/web/WebViewImpl.h index c7102683..42c02dc4 100644 --- a/third_party/WebKit/Source/web/WebViewImpl.h +++ b/third_party/WebKit/Source/web/WebViewImpl.h
@@ -41,7 +41,7 @@ #include "core/page/EditorClient.h" #include "core/page/EventWithHitTestResults.h" #include "core/page/PageWidgetDelegate.h" -#include "modules/storage/StorageClientImpl.h" +#include "modules/storage/StorageClient.h" #include "platform/animation/CompositorAnimationTimeline.h" #include "platform/geometry/IntPoint.h" #include "platform/geometry/IntRect.h" @@ -592,7 +592,7 @@ ContextMenuClient context_menu_client_; EditorClient editor_client_; SpellCheckerClientImpl spell_checker_client_impl_; - StorageClientImpl storage_client_impl_; + StorageClient storage_client_impl_; WebSize size_; // If true, automatically resize the layout view around its content.
diff --git a/third_party/WebKit/Tools/Scripts/common.vpython b/third_party/WebKit/Tools/Scripts/common.vpython deleted file mode 100644 index bab683a..0000000 --- a/third_party/WebKit/Tools/Scripts/common.vpython +++ /dev/null
@@ -1,29 +0,0 @@ -# vpython config for webkitpy -# -# This file lists Python dependencies that are required by files -# in this directory and below. See vpython docs at: -# https://github.com/luci/luci-go/tree/master/vpython - -python_version: "2.7" - -# The Android port in webkitpy.layout depends on devil.android, -# which depends on psutil. - -wheel: < - name: "infra/python/wheels/psutil/${platform}_${py_python}_${py_abi}" - version: "version:5.2.2" -> - -# On Windows, webkitpy.layout_tests.port.server_process depends on -# win32pipe and win32file, which are provided by pywin32. - -wheel: < - name: "infra/python/wheels/pywin32/${platform}_${py_python}" - version: "version:219" - match_tag: < - platform: "win32" - > - match_tag: < - platform: "win_amd64" - > ->
diff --git a/tools/perf/benchmarks/image_decoding.py b/tools/perf/benchmarks/image_decoding.py index c1681f3..7c897723 100644 --- a/tools/perf/benchmarks/image_decoding.py +++ b/tools/perf/benchmarks/image_decoding.py
@@ -23,3 +23,6 @@ def ShouldDisable(cls, possible_browser): # crbug.com/667501 return possible_browser.platform.GetDeviceTypeName() == 'Nexus 7' + + def GetExpectations(self): + return page_sets.ImageDecodingMeasurementStoryExpectations()
diff --git a/tools/perf/benchmarks/jetstream.py b/tools/perf/benchmarks/jetstream.py index b594f50b..c7724e7 100644 --- a/tools/perf/benchmarks/jetstream.py +++ b/tools/perf/benchmarks/jetstream.py
@@ -93,3 +93,9 @@ make_javascript_deterministic=False, name='http://browserbench.org/JetStream/')) return ps + + def GetExpectations(self): + class StoryExpectations(story.expectations.StoryExpectations): + def SetExpectations(self): + pass # http://browserbench.org/JetStream/ not disabled. + return StoryExpectations()
diff --git a/tools/perf/benchmarks/kraken.py b/tools/perf/benchmarks/kraken.py index 521c27e..d495391 100644 --- a/tools/perf/benchmarks/kraken.py +++ b/tools/perf/benchmarks/kraken.py
@@ -139,6 +139,10 @@ name='http://krakenbenchmark.mozilla.org/kraken-1.1/driver.html')) return ps - @classmethod - def ShouldDisable(cls, possible_browser): - return cls.IsSvelte(possible_browser) # http://crbug.com/624411 + def GetExpectations(self): + class StoryExpectations(story.expectations.StoryExpectations): + def SetExpectations(self): + self.DisableStory( + 'http://krakenbenchmark.mozilla.org/kraken-1.1/driver.html', + [story.expectations.ANDROID_SVELTE], 'crbug.com/624411') + return StoryExpectations()
diff --git a/tools/perf/page_sets/image_decoding_measurement.py b/tools/perf/page_sets/image_decoding_measurement.py index c192afe7..68dc390 100644 --- a/tools/perf/page_sets/image_decoding_measurement.py +++ b/tools/perf/page_sets/image_decoding_measurement.py
@@ -36,3 +36,8 @@ for url in urls_list: self.AddStory(ImageDecodingMeasurementPage(url, self, url.split('/')[-1])) + +class ImageDecodingMeasurementStoryExpectations( + story.expectations.StoryExpectations): + def SetExpectations(self): + pass # Nothing disabled.
diff --git a/ui/keyboard/resources/inputview_adapter.js b/ui/keyboard/resources/inputview_adapter.js index 0e17539..c9f78ec 100644 --- a/ui/keyboard/resources/inputview_adapter.js +++ b/ui/keyboard/resources/inputview_adapter.js
@@ -144,6 +144,15 @@ Controller.prototype.getSpatialData_ = function() {}; } +/** + * Return the most recently used US layout. By default, this will return the + * compact layout. + */ +function getDefaultUsLayout() { + return window.localStorage['vkDefaultLayoutIsFull'] + ? 'us' : 'us.compact.qwerty'; +} + // Plug in for API calls. function registerInputviewApi() { @@ -380,7 +389,7 @@ }); } - var keyset = params['id'] || 'us.compact.qwerty'; + var keyset = params['id'] || getDefaultUsLayout(); var languageCode = params['language'] || 'en'; var passwordLayout = params['passwordLayout'] || 'us'; var name = params['name'] || 'English';