diff --git a/Cargo.lock b/Cargo.lock index 4a8e04aaa4df..65e09fd3840e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1064,20 +1064,20 @@ dependencies = [ [[package]] name = "gl_generator" -version = "0.9.0" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "khronos_api 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "khronos_api 3.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "gleam" -version = "0.6.3" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "gl_generator 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1251,7 +1251,7 @@ dependencies = [ [[package]] name = "khronos_api" -version = "2.2.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -2948,7 +2948,7 @@ dependencies = [ "dwrote 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "freetype 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2992,7 +2992,7 @@ dependencies = [ "euclid 0.19.3 (registry+https://github.com/rust-lang/crates.io-index)", "foreign-types 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "nsstring 0.1.0", "rayon 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3065,11 +3065,8 @@ dependencies = [ [[package]] name = "xml-rs" -version = "0.7.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", -] [[package]] name = "xpcom" @@ -3221,8 +3218,8 @@ dependencies = [ "checksum fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" "checksum gcc 0.3.54 (registry+https://github.com/rust-lang/crates.io-index)" = "5e33ec290da0d127825013597dbdfc28bee4964690c7ce1166cbc2a7bd08b1bb" "checksum generic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ef25c5683767570c2bbd7deba372926a55eaae9982d7726ee2a1050239d45b9d" -"checksum gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a795170cbd85b5a7baa58d6d7525cae6a03e486859860c220f7ebbbdd379d0a" -"checksum gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2260952cc0393ca6f183e1a91a035c65c85ddb02505f3d53e5a775eb05946f44" +"checksum gl_generator 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a0ffaf173cf76c73a73e080366bf556b4776ece104b06961766ff11449f38604" +"checksum gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "4b47f5b15742aee359c7895ab98cf2cceecc89bb4feb6f4e42f802d7899877da" "checksum glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "8be18de09a56b60ed0edf84bc9df007e30040691af7acd1c41874faac5895bfb" "checksum goblin 0.0.17 (registry+https://github.com/rust-lang/crates.io-index)" = "5911d7df7b8f65ab676c5327b50acea29d3c6a1a4ad05e444cf5dce321b26db2" "checksum h2 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "a27e7ed946e8335bdf9a191bc1b9b14a03ba822d013d2f58437f4fabcbd7fc2c" @@ -3237,7 +3234,7 @@ dependencies = [ "checksum itertools 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "b07332223953b5051bceb67e8c4700aa65291535568e1f12408c43c4a42c0394" "checksum itoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c069bbec61e1ca5a596166e55dfe4773ff745c3d16b700013bcaff9a6df2c682" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" -"checksum khronos_api 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "037ab472c33f67b5fbd3e9163a2645319e5356fcd355efa6d4eb7fff4bbcb554" +"checksum khronos_api 3.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "62237e6d326bd5871cd21469323bf096de81f1618cd82cbaf5d87825335aeb49" "checksum lalrpop 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9f7014afd5642680074fd5dcc624d544f9eabfa281cba2c3ac56c3db6d21ad1b" "checksum lalrpop-snap 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0b85aa455529344133d7ecaaac04c01ed87f459deeaa0fe5422885e2095d8cdc" "checksum lalrpop-util 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2400aeebcd11259370d038c24821b93218dd2f33a53f53e9c8fcccca70be6696" @@ -3407,6 +3404,6 @@ dependencies = [ "checksum wincolor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "eeb06499a3a4d44302791052df005d5232b927ed1a9658146d842165c4de7767" "checksum winreg 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a27a759395c1195c4cc5cda607ef6f8f6498f64e78f7900f5de0a127a424704a" "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" -"checksum xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c1cb601d29fe2c2ac60a2b2e5e293994d87a1f6fa9687a31a15270f909be9c2" +"checksum xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "541b12c998c5b56aa2b4e6f18f03664eef9a4fd0a246a55594efae6cc2d964b5" "checksum yaml-rust 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "57ab38ee1a4a266ed033496cf9af1828d8d6e6c1cfa5f643a2809effcae4d628" "checksum zip 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "36b9e08fb518a65cf7e08a1e482573eb87a2f4f8c6619316612a3c1f162fe822" diff --git a/browser/base/content/browser.js b/browser/base/content/browser.js index ebc87513ca0f..4efe270fe9e9 100644 --- a/browser/base/content/browser.js +++ b/browser/base/content/browser.js @@ -3,9 +3,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/* eslint-env mozilla/browser-window */ -/* globals StatusPanel */ - ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); ChromeUtils.import("resource://gre/modules/Services.jsm"); ChromeUtils.import("resource://gre/modules/AppConstants.jsm"); diff --git a/browser/base/content/browser.xul b/browser/base/content/browser.xul index a4c09032a246..d642ff3fe24b 100644 --- a/browser/base/content/browser.xul +++ b/browser/base/content/browser.xul @@ -88,6 +88,20 @@ xmlns="http://www.w3.org/1999/xhtml" #endif > Services.scriptloader.loadSubScript("chrome://global/content/contentAreaUtils.js", this); + Services.scriptloader.loadSubScript("chrome://browser/content/browser-captivePortal.js", this); + Services.scriptloader.loadSubScript("chrome://browser/content/browser-compacttheme.js", this); + Services.scriptloader.loadSubScript("chrome://browser/content/browser-contentblocking.js", this); +#ifdef MOZ_DATA_REPORTING + Services.scriptloader.loadSubScript("chrome://browser/content/browser-data-submission-info-bar.js", this); +#endif +#ifndef MOZILLA_OFFICIAL + Services.scriptloader.loadSubScript("chrome://browser/content/browser-development-helpers.js", this); +#endif + Services.scriptloader.loadSubScript("chrome://browser/content/browser-media.js", this); + Services.scriptloader.loadSubScript("chrome://browser/content/browser-pageActions.js", this); + Services.scriptloader.loadSubScript("chrome://browser/content/browser-plugins.js", this); + Services.scriptloader.loadSubScript("chrome://browser/content/browser-sidebar.js", this); + Services.scriptloader.loadSubScript("chrome://browser/content/browser-tabsintitlebar.js", this); Services.scriptloader.loadSubScript("chrome://browser/content/tabbrowser.js", this); Services.scriptloader.loadSubScript("chrome://browser/content/search/searchbar.js", this); @@ -735,7 +749,7 @@ xmlns="http://www.w3.org/1999/xhtml" # shared with other top level windows in macWindow.inc.xul. #include browser-menubar.inc - + #include titlebar-items.inc.xul diff --git a/browser/base/content/global-scripts.inc b/browser/base/content/global-scripts.inc index 7d2c65260e91..1dc8c9f6e9eb 100644 --- a/browser/base/content/global-scripts.inc +++ b/browser/base/content/global-scripts.inc @@ -3,6 +3,10 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. +# JS files which are needed by browser.xul but no other top level windows to +# support MacOS specific features should be loaded directly from browser.xul +# rather than this file. + # If you update this list, you may need to add a mapping within the following # file so that ESLint works correctly: # tools/lint/eslint/eslint-plugin-mozilla/lib/environments/browser-window.js @@ -16,28 +20,12 @@ Components.utils.import("resource://gre/modules/Services.jsm"); for (let script of [ "chrome://browser/content/browser.js", - - "chrome://browser/content/browser-captivePortal.js", - "chrome://browser/content/browser-compacttheme.js", - "chrome://browser/content/browser-contentblocking.js", - "chrome://browser/content/browser-media.js", - "chrome://browser/content/browser-pageActions.js", "chrome://browser/content/browser-places.js", - "chrome://browser/content/browser-plugins.js", - "chrome://browser/content/browser-sidebar.js", - "chrome://browser/content/browser-tabsintitlebar.js", - "chrome://global/content/globalOverlay.js", "chrome://browser/content/utilityOverlay.js", #ifdef XP_MACOSX "chrome://global/content/macWindowMenu.js", #endif -#ifdef MOZ_DATA_REPORTING - "chrome://browser/content/browser-data-submission-info-bar.js", -#endif -#ifndef MOZILLA_OFFICIAL - "chrome://browser/content/browser-development-helpers.js", -#endif ]) { Services.scriptloader.loadSubScript(script, this); } diff --git a/browser/base/content/tabbrowser.js b/browser/base/content/tabbrowser.js index b2fed97f25aa..1ea01bf19ce8 100644 --- a/browser/base/content/tabbrowser.js +++ b/browser/base/content/tabbrowser.js @@ -3,8 +3,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -/* eslint-env mozilla/browser-window */ - { // start private scope for gBrowser /** diff --git a/browser/base/content/titlebar-items.inc.xul b/browser/base/content/titlebar-items.inc.xul index 6bf23f6bdb36..6e74ecd7ada4 100644 --- a/browser/base/content/titlebar-items.inc.xul +++ b/browser/base/content/titlebar-items.inc.xul @@ -2,7 +2,7 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. - + diff --git a/browser/base/content/urlbarBindings.xml b/browser/base/content/urlbarBindings.xml index 36d6dbeaa646..4f8614fa8c39 100644 --- a/browser/base/content/urlbarBindings.xml +++ b/browser/base/content/urlbarBindings.xml @@ -1937,7 +1937,7 @@ file, You can obtain one at http://mozilla.org/MPL/2.0/. - new window.SearchOneOffs( + new SearchOneOffs( document.getAnonymousElementByAttribute(this, "anonid", "one-off-search-buttons")); diff --git a/browser/components/extensions/parent/ext-browser.js b/browser/components/extensions/parent/ext-browser.js index 97006791c990..d552c1256989 100644 --- a/browser/components/extensions/parent/ext-browser.js +++ b/browser/components/extensions/parent/ext-browser.js @@ -488,7 +488,7 @@ class TabTracker extends TabTrackerBase { // If the tab is already be destroyed, do nothing. return; } - this.emitActivated(nativeTab); + this.emitActivated(nativeTab, event.detail.previousTab); }); break; @@ -571,11 +571,14 @@ class TabTracker extends TabTrackerBase { * * @param {NativeTab} nativeTab * The tab element which has been activated. + * @param {NativeTab} previousTab + * The tab element which was previously activated. * @private */ - emitActivated(nativeTab) { + emitActivated(nativeTab, previousTab = undefined) { this.emit("tab-activated", { tabId: this.getId(nativeTab), + previousTabId: previousTab && !previousTab.closing ? this.getId(previousTab) : undefined, windowId: windowTracker.getId(nativeTab.ownerGlobal)}); } @@ -777,6 +780,11 @@ class Tab extends TabBase { return this.url && this.url.startsWith(READER_MODE_PREFIX); } + get successorTabId() { + const {successor} = this.nativeTab; + return successor ? tabTracker.getId(successor) : -1; + } + /** * Converts session store data to an object compatible with the return value * of the convert() method, representing that data. diff --git a/browser/components/extensions/parent/ext-tabs.js b/browser/components/extensions/parent/ext-tabs.js index e58092974fba..4ef7113208ad 100644 --- a/browser/components/extensions/parent/ext-tabs.js +++ b/browser/components/extensions/parent/ext-tabs.js @@ -31,6 +31,8 @@ XPCOMUtils.defineLazyPreferenceGetter(this, "gMultiSelectEnabled", MULTISELECT_P const TAB_HIDE_CONFIRMED_TYPE = "tabHideNotification"; +const TAB_ID_NONE = -1; + XPCOMUtils.defineLazyGetter(this, "tabHidePopup", () => { return new ExtensionControlledPopup({ @@ -727,6 +729,19 @@ this.tabs = class extends ExtensionAPI { } tabTracker.setOpener(nativeTab, opener); } + if (updateProperties.successorTabId !== null) { + let successor = null; + if (updateProperties.successorTabId !== TAB_ID_NONE) { + successor = tabTracker.getTab(updateProperties.successorTabId, null); + if (!successor) { + throw new ExtensionError("Invalid successorTabId"); + } + if (successor.ownerDocument !== nativeTab.ownerDocument) { + throw new ExtensionError("Successor tab must be in the same window as the tab being updated"); + } + } + tabbrowser.setSuccessor(nativeTab, successor); + } return tabManager.convert(nativeTab); }, @@ -1240,6 +1255,57 @@ this.tabs = class extends ExtensionAPI { tab.linkedBrowser.messageManager.sendAsyncMessage("Reader:ToggleReaderMode"); }, + moveInSuccession(tabIds, tabId, options) { + const {insert, append} = options || {}; + const tabIdSet = new Set(tabIds); + if (tabIdSet.size !== tabIds.length) { + throw new ExtensionError("IDs must not occur more than once in tabIds"); + } + if ((append || insert) && tabIdSet.has(tabId)) { + throw new ExtensionError("Value of tabId must not occur in tabIds if append or insert is true"); + } + + const referenceTab = tabTracker.getTab(tabId, null); + let referenceWindow = referenceTab && referenceTab.ownerGlobal; + let previousTab, lastSuccessor; + if (append) { + previousTab = referenceTab; + lastSuccessor = (insert && referenceTab && referenceTab.successor) || null; + } else { + lastSuccessor = referenceTab; + } + + let firstTab; + for (const tabId of tabIds) { + const tab = tabTracker.getTab(tabId, null); + if (tab === null) { + continue; + } + if (referenceWindow === null) { + referenceWindow = tab.ownerGlobal; + } else if (tab.ownerGlobal !== referenceWindow) { + continue; + } + referenceWindow.gBrowser.replaceInSuccession(tab, tab.successor); + if (append && tab === lastSuccessor) { + lastSuccessor = tab.successor; + } + if (previousTab) { + referenceWindow.gBrowser.setSuccessor(previousTab, tab); + } else { + firstTab = tab; + } + previousTab = tab; + } + + if (previousTab) { + if (!append && insert && lastSuccessor !== null) { + referenceWindow.gBrowser.replaceInSuccession(lastSuccessor, firstTab); + } + referenceWindow.gBrowser.setSuccessor(previousTab, lastSuccessor); + } + }, + show(tabIds) { if (!Services.prefs.getBoolPref(TABHIDE_PREFNAME, false)) { throw new ExtensionError(`tabs.show is currently experimental and must be enabled with the ${TABHIDE_PREFNAME} preference.`); diff --git a/browser/components/extensions/schemas/tabs.json b/browser/components/extensions/schemas/tabs.json index 6a7f8ae95dd4..30de1bc10dda 100644 --- a/browser/components/extensions/schemas/tabs.json +++ b/browser/components/extensions/schemas/tabs.json @@ -102,7 +102,8 @@ "isArticle": {"type": "boolean", "optional": true, "description": "Whether the document in the tab can be rendered in reader mode."}, "isInReaderMode": {"type": "boolean", "optional": true, "description": "Whether the document in the tab is being rendered in reader mode."}, "sharingState": {"$ref": "SharingState", "optional": true, "description": "Current tab sharing state for screen, microphone and camera."}, - "attention": {"type": "boolean", "optional": true, "description": "Whether the tab is drawing attention."} + "attention": {"type": "boolean", "optional": true, "description": "Whether the tab is drawing attention."}, + "successorTabId": {"type": "integer", "optional": true, "minimum": -1, "description": "The ID of this tab's successor, if any; $(ref:tabs.TAB_ID_NONE) otherwise."} } }, { @@ -888,6 +889,12 @@ "type": "boolean", "optional": true, "description": "Whether the load should replace the current history entry for the tab." + }, + "successorTabId": { + "type": "integer", + "minimum": -1, + "optional": true, + "description": "The ID of this tab's successor. If specified, the successor tab must be in the same window as this tab." } } }, @@ -1396,6 +1403,48 @@ ] } ] + }, + { + "name": "moveInSuccession", + "type": "function", + "async": true, + "description": "Removes an array of tabs from their lines of succession and prepends or appends them in a chain to another tab.", + "parameters": [ + { + "name": "tabIds", + "type": "array", + "items": { "type": "integer", "minimum": 0 }, + "minItems": 1, + "description": "An array of tab IDs to move in the line of succession. For each tab in the array, the tab's current predecessors will have their successor set to the tab's current successor, and each tab will then be set to be the successor of the previous tab in the array. Any tabs not in the same window as the tab indicated by the second argument (or the first tab in the array, if no second argument) will be skipped." + }, + { + "name": "tabId", + "type": "integer", + "optional": true, + "default": -1, + "minimum": -1, + "description": "The ID of a tab to set as the successor of the last tab in the array, or $(ref:tabs.TAB_ID_NONE) to leave the last tab without a successor. If options.append is true, then this tab is made the predecessor of the first tab in the array instead." + }, + { + "name": "options", + "type": "object", + "optional": true, + "properties": { + "append": { + "type": "boolean", + "optional": true, + "default": false, + "description": "Whether to move the tabs before (false) or after (true) tabId in the succession. Defaults to false." + }, + "insert": { + "type": "boolean", + "optional": true, + "default": false, + "description": "Whether to link up the current predecessors or successor (depending on options.append) of tabId to the other side of the chain after it is prepended or appended. If true, one of the following happens: if options.append is false, the first tab in the array is set as the successor of any current predecessors of tabId; if options.append is true, the current successor of tabId is set as the successor of the last tab in the array. Defaults to false." + } + } + } + ] } ], "events": [ @@ -1585,6 +1634,12 @@ "minimum": 0, "description": "The ID of the tab that has become active." }, + "previousTabId": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The ID of the tab that was previously active, if that tab is still open." + }, "windowId": { "type": "integer", "minimum": 0, diff --git a/browser/components/extensions/test/browser/browser-common.ini b/browser/components/extensions/test/browser/browser-common.ini index 95fbb8890349..62d5d0703641 100644 --- a/browser/components/extensions/test/browser/browser-common.ini +++ b/browser/components/extensions/test/browser/browser-common.ini @@ -222,6 +222,7 @@ skip-if = (verify && !debug && (os == 'mac')) skip-if = os == 'mac' # Save as PDF not supported on Mac OS X [browser_ext_tabs_sendMessage.js] [browser_ext_tabs_sharingState.js] +[browser_ext_tabs_successors.js] [browser_ext_tabs_cookieStoreId.js] [browser_ext_tabs_update.js] [browser_ext_tabs_update_highlighted.js] diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_events.js b/browser/components/extensions/test/browser/browser_ext_tabs_events.js index 94b6854bf510..6f61c672c7b6 100644 --- a/browser/components/extensions/test/browser/browser_ext_tabs_events.js +++ b/browser/components/extensions/test/browser/browser_ext_tabs_events.js @@ -374,8 +374,9 @@ add_task(async function testTabCreateRelated() { }); add_task(async function testLastTabRemoval() { + const CLOSE_WINDOW_PREF = "browser.tabs.closeWindowWithLastTab"; await SpecialPowers.pushPrefEnv({set: [ - ["browser.tabs.closeWindowWithLastTab", false], + [CLOSE_WINDOW_PREF, false], ]}); async function background() { @@ -409,4 +410,82 @@ add_task(async function testLastTabRemoval() { await extension.unload(); await BrowserTestUtils.closeWindow(newWin); + SpecialPowers.clearUserPref(CLOSE_WINDOW_PREF); +}); + +add_task(async function testTabActivationEvent() { + async function background() { + function makeExpectable() { + let expectation = null, resolver = null; + const expectable = param => { + if (expectation === null) { + browser.test.fail("unexpected call to expectable"); + } else { + try { + resolver(expectation(param)); + } catch (e) { + resolver(Promise.reject(e)); + } finally { + expectation = null; + } + } + }; + expectable.expect = e => { + expectation = e; + return new Promise(r => { resolver = r; }); + }; + return expectable; + } + try { + const listener = makeExpectable(); + browser.tabs.onActivated.addListener(listener); + + const [, {tabs: [tab1]}] = await Promise.all([ + listener.expect(info => { + browser.test.assertEq(undefined, info.previousTabId, "previousTabId should not be defined when window is first opened"); + }), + browser.windows.create({url: "about:blank"}), + ]); + const [, tab2] = await Promise.all([ + listener.expect(info => { + browser.test.assertEq(tab1.id, info.previousTabId, "Got expected previousTabId"); + }), + browser.tabs.create({url: "about:blank"}), + ]); + + await Promise.all([ + listener.expect(info => { + browser.test.assertEq(tab1.id, info.tabId, "Got expected tabId"); + browser.test.assertEq(tab2.id, info.previousTabId, "Got expected previousTabId"); + }), + browser.tabs.update(tab1.id, {active: true}), + ]); + + await Promise.all([ + listener.expect(info => { + browser.test.assertEq(tab2.id, info.tabId, "Got expected tabId"); + browser.test.assertEq(undefined, info.previousTabId, "previousTabId should not be defined when previous tab was closed"); + }), + browser.tabs.remove(tab1.id), + ]); + + await browser.tabs.remove(tab2.id); + + browser.test.notifyPass("tabs-events"); + } catch (e) { + browser.test.fail(`${e} :: ${e.stack}`); + browser.test.notifyFail("tabs-events"); + } + } + + let extension = ExtensionTestUtils.loadExtension({ + manifest: { + "permissions": ["tabs"], + }, + background, + }); + + await extension.startup(); + await extension.awaitFinish("tabs-events"); + await extension.unload(); }); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_successors.js b/browser/components/extensions/test/browser/browser_ext_tabs_successors.js new file mode 100644 index 000000000000..16cfb73105a4 --- /dev/null +++ b/browser/components/extensions/test/browser/browser_ext_tabs_successors.js @@ -0,0 +1,212 @@ +/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */ +/* vim: set sts=2 sw=2 et tw=80: */ +"use strict"; + +async function background(tabCount, testFn) { + try { + const {TAB_ID_NONE} = browser.tabs; + const tabIds = await Promise.all(Array.from({length: tabCount}, () => browser.tabs.create({url: "about:blank"}).then(t => t.id))); + + const toTabIds = i => tabIds[i]; + + const setSuccessors = mapping => Promise.all(mapping.map((succ, i) => + browser.tabs.update(tabIds[i], {successorTabId: tabIds[succ]}))); + + const verifySuccessors = async function(mapping, name) { + const promises = [], expected = []; + for (let i = 0; i < mapping.length; i++) { + if (mapping[i] !== undefined) { + promises.push(browser.tabs.get(tabIds[i]).then(t => t.successorTabId)); + expected.push(mapping[i] === TAB_ID_NONE ? TAB_ID_NONE : tabIds[mapping[i]]); + } + } + const results = await Promise.all(promises); + for (let i = 0; i < results.length; i++) { + browser.test.assertEq(expected[i], results[i], `${name}: successorTabId of tab ${i} in mapping should be ${expected[i]}`); + } + }; + + await testFn({TAB_ID_NONE, tabIds, toTabIds, setSuccessors, verifySuccessors}); + + browser.test.notifyPass("background-script"); + } catch (e) { + browser.test.fail(`${e} :: ${e.stack}`); + browser.test.notifyFail("background-script"); + } +} + +async function runTabTest(tabCount, testFn) { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + "permissions": ["tabs"], + }, + background: `(${background})(${tabCount}, ${testFn});`, + }); + + await extension.startup(); + await extension.awaitFinish("background-script"); + await extension.unload(); +} + +add_task(function testTabSuccessors() { + return runTabTest(3, async function({TAB_ID_NONE, tabIds}) { + const anotherWindow = await browser.windows.create({url: "about:blank"}); + + browser.test.assertEq(TAB_ID_NONE, (await browser.tabs.get(tabIds[0])).successorTabId, "Tabs default to an undefined successor"); + + // Basic getting and setting + + await browser.tabs.update(tabIds[0], {successorTabId: tabIds[1]}); + browser.test.assertEq(tabIds[1], (await browser.tabs.get(tabIds[0])).successorTabId, "tabs.update assigned the correct successor"); + + await browser.tabs.update(tabIds[0], {successorTabId: browser.tabs.TAB_ID_NONE}); + browser.test.assertEq(TAB_ID_NONE, (await browser.tabs.get(tabIds[0])).successorTabId, "tabs.update cleared successor"); + + await browser.tabs.update(tabIds[0], {successorTabId: tabIds[1]}); + await browser.tabs.update(tabIds[0], {successorTabId: tabIds[0]}); + browser.test.assertEq(TAB_ID_NONE, (await browser.tabs.get(tabIds[0])).successorTabId, "Setting a tab as its own successor clears the successor instead"); + + // Validation tests + + await browser.test.assertRejects( + browser.tabs.update(tabIds[0], {successorTabId: 1e8}), + /Invalid successorTabId/, + "tabs.update should throw with an invalid successor tab ID"); + + await browser.test.assertRejects( + browser.tabs.update(tabIds[0], {successorTabId: anotherWindow.tabs[0].id}), + /Successor tab must be in the same window as the tab being updated/, + "tabs.update should throw with a successor tab ID from another window"); + + // Make sure the successor is truly being assigned + + await browser.tabs.update(tabIds[0], {successorTabId: tabIds[2], active: true}); + await browser.tabs.remove(tabIds[0]); + browser.test.assertEq(tabIds[2], (await browser.tabs.query({active: true}))[0].id); + + + return browser.tabs.remove([tabIds[1], tabIds[2], anotherWindow.tabs[0].id]); + }); +}); + +add_task(function testMoveInSuccession_appendFalse() { + return runTabTest(8, async function({TAB_ID_NONE, tabIds, toTabIds, setSuccessors, verifySuccessors}) { + await browser.tabs.moveInSuccession([1, 0].map(toTabIds), tabIds[0]); + await verifySuccessors([TAB_ID_NONE, 0], "scenario 1"); + + await browser.tabs.moveInSuccession([0, 1, 2, 3].map(toTabIds), tabIds[0]); + await verifySuccessors([1, 2, 3, 0], "scenario 2"); + + await browser.tabs.moveInSuccession([1, 0].map(toTabIds), tabIds[0]); + await verifySuccessors([TAB_ID_NONE, 0], "scenario 1 after tab 0 has a successor"); + + await browser.tabs.update(tabIds[7], {successorTabId: tabIds[0]}); + await browser.tabs.moveInSuccession([4, 5, 6, 7].map(toTabIds)); + await verifySuccessors(new Array(4).concat([5, 6, 7, TAB_ID_NONE]), "scenario 4"); + + await setSuccessors([7, 2, 3, 4, 3, 6, 7, 5]); + await browser.tabs.moveInSuccession([4, 6, 3, 2].map(toTabIds), tabIds[7]); + await verifySuccessors([7, TAB_ID_NONE, 7, 2, 6, 7, 3, 5], "scenario 5"); + + await setSuccessors([7, 2, 3, 4, 3, 6, 7, 5]); + await browser.tabs.moveInSuccession([4, 6, 3, 2].map(toTabIds), tabIds[7], {insert: true}); + await verifySuccessors([4, TAB_ID_NONE, 7, 2, 6, 4, 3, 5], "insert = true"); + + await setSuccessors([1, 2, 3, 4, 0]); + await browser.tabs.moveInSuccession([3, 1, 2].map(toTabIds), tabIds[0], {insert: true}); + await verifySuccessors([4, 2, 0, 1, 3], "insert = true, part 2"); + + await browser.tabs.moveInSuccession([tabIds[0], tabIds[1], 1e8, tabIds[2]]); + await verifySuccessors([1, 2, TAB_ID_NONE], "unknown tab ID"); + + browser.test.assertTrue(await browser.tabs.moveInSuccession([1e8]).then(() => true, () => false), "When all tab IDs are unknown, tabs.moveInSuccession should not throw"); + + // Validation tests + + await browser.test.assertRejects( + browser.tabs.moveInSuccession([tabIds[0], tabIds[1], tabIds[0]]), + /IDs must not occur more than once in tabIds/, + "tabs.moveInSuccession should throw when a tab is referenced more than once in tabIds"); + + await browser.test.assertRejects( + browser.tabs.moveInSuccession([tabIds[0], tabIds[1]], tabIds[0], {insert: true}), + /Value of tabId must not occur in tabIds if append or insert is true/, + "tabs.moveInSuccession should throw when tabId occurs in tabIds and insert is true"); + + + return browser.tabs.remove(tabIds); + }); +}); + +add_task(function testMoveInSuccession_appendTrue() { + return runTabTest(8, async function({TAB_ID_NONE, tabIds, toTabIds, setSuccessors, verifySuccessors}) { + await browser.tabs.moveInSuccession([1].map(toTabIds), tabIds[0], {append: true}); + await verifySuccessors([1, TAB_ID_NONE], "scenario 1"); + + await browser.tabs.update(tabIds[3], {successorTabId: tabIds[4]}); + await browser.tabs.moveInSuccession([1, 2, 3].map(toTabIds), tabIds[0], {append: true}); + await verifySuccessors([1, 2, 3, TAB_ID_NONE], "scenario 2"); + + await browser.tabs.update(tabIds[0], {successorTabId: tabIds[1]}); + await browser.tabs.moveInSuccession([1e8], tabIds[0], {append: true}); + browser.test.assertEq(TAB_ID_NONE, (await browser.tabs.get(tabIds[0])).successorTabId, "If no tabs get appended after the reference tab, it should lose its successor"); + + await setSuccessors([7, 2, 3, 4, 3, 6, 7, 5]); + await browser.tabs.moveInSuccession([4, 6, 3, 2].map(toTabIds), tabIds[7], {append: true}); + await verifySuccessors([7, TAB_ID_NONE, TAB_ID_NONE, 2, 6, 7, 3, 4], "scenario 3"); + + await setSuccessors([7, 2, 3, 4, 3, 6, 7, 5]); + await browser.tabs.moveInSuccession([4, 6, 3, 2].map(toTabIds), tabIds[7], {append: true, insert: true}); + await verifySuccessors([7, TAB_ID_NONE, 5, 2, 6, 7, 3, 4], "insert = true"); + + await browser.tabs.moveInSuccession([0, 4].map(toTabIds), tabIds[7], {append: true, insert: true}); + await verifySuccessors([4, undefined, undefined, undefined, 6, undefined, undefined, 0], "insert = true, part 2"); + + await setSuccessors([1, 2, 3, 4, 0]); + await browser.tabs.moveInSuccession([3, 1, 2].map(toTabIds), tabIds[0], {append: true, insert: true}); + await verifySuccessors([3, 2, 4, 1, 0], "insert = true, part 3"); + + await browser.tabs.update(tabIds[0], {successorTabId: tabIds[1]}); + await browser.tabs.moveInSuccession([1e8], tabIds[0], {append: true, insert: true}); + browser.test.assertEq(tabIds[1], (await browser.tabs.get(tabIds[0])).successorTabId, "If no tabs get inserted after the reference tab, it should keep its successor"); + + // Validation tests + + await browser.test.assertRejects( + browser.tabs.moveInSuccession([tabIds[0], tabIds[1]], tabIds[0], {append: true}), + /Value of tabId must not occur in tabIds if append or insert is true/, + "tabs.moveInSuccession should throw when tabId occurs in tabIds and insert is true"); + + + return browser.tabs.remove(tabIds); + }); +}); + +add_task(function testMoveInSuccession_ignoreTabsInOtherWindows() { + return runTabTest(2, async function({TAB_ID_NONE, tabIds, toTabIds, setSuccessors, verifySuccessors}) { + const anotherWindow = await browser.windows.create({url: Array.from({length: 3}, () => "about:blank")}); + tabIds.push(...anotherWindow.tabs.map(t => t.id)); + + await setSuccessors([1, 0, 3, 4, 2]); + await browser.tabs.moveInSuccession([1, 3, 2].map(toTabIds), tabIds[4]); + await verifySuccessors([1, 0, 4, 2, TAB_ID_NONE], "first tab in another window"); + + await setSuccessors([1, 0, 3, 4, 2]); + await browser.tabs.moveInSuccession([3, 1, 2].map(toTabIds), tabIds[4]); + await verifySuccessors([1, 0, 4, 2, TAB_ID_NONE], "middle tab in another window"); + + await setSuccessors([1, 0, 3, 4, 2]); + await browser.tabs.moveInSuccession([3, 1, 2].map(toTabIds)); + await verifySuccessors([1, 0, TAB_ID_NONE, 2, TAB_ID_NONE], "using the first tab to determine the window"); + + await setSuccessors([1, 0, 3, 4, 2]); + await browser.tabs.moveInSuccession([1, 3, 2].map(toTabIds), tabIds[4], {append: true}); + await verifySuccessors([1, 0, TAB_ID_NONE, 2, 3], "first tab in another window, appending"); + + await setSuccessors([1, 0, 3, 4, 2]); + await browser.tabs.moveInSuccession([3, 1, 2].map(toTabIds), tabIds[4], {append: true}); + await verifySuccessors([1, 0, TAB_ID_NONE, 2, 3], "middle tab in another window, appending"); + + return browser.tabs.remove(tabIds); + }); +}); diff --git a/browser/components/extensions/test/browser/browser_ext_tabs_update_highlighted.js b/browser/components/extensions/test/browser/browser_ext_tabs_update_highlighted.js index 1c4943da86a2..ca881c86cc3f 100644 --- a/browser/components/extensions/test/browser/browser_ext_tabs_update_highlighted.js +++ b/browser/components/extensions/test/browser/browser_ext_tabs_update_highlighted.js @@ -80,7 +80,7 @@ add_task(async function test_update_highlighted() { await expectResults(async () => { await browser.tabs.update(tab1, {highlighted: true}); return {active: tab1, highlighted: [tab1, tab2], events: [ - ["onActivated", {tabId: tab1, windowId}], + ["onActivated", {tabId: tab1, previousTabId: tab2, windowId}], ["onHighlighted", {tabIds: [tab1, tab2], windowId}], ]}; }, "highlighting non-highlighted tab"); @@ -93,7 +93,7 @@ add_task(async function test_update_highlighted() { await expectResults(async () => { await browser.tabs.update(tab1, {highlighted: false}); return {active: tab2, highlighted: [tab2], events: [ - ["onActivated", {tabId: tab2, windowId}], + ["onActivated", {tabId: tab2, previousTabId: tab1, windowId}], ["onHighlighted", {tabIds: [tab2], windowId}], ]}; }, "unhighlighting active tab with multiselection"); @@ -101,7 +101,7 @@ add_task(async function test_update_highlighted() { await expectResults(async () => { await browser.tabs.update(tab1, {highlighted: true}); return {active: tab1, highlighted: [tab1, tab2], events: [ - ["onActivated", {tabId: tab1, windowId}], + ["onActivated", {tabId: tab1, previousTabId: tab2, windowId}], ["onHighlighted", {tabIds: [tab1, tab2], windowId}], ]}; }, "highlighting non-highlighted tab"); @@ -123,7 +123,7 @@ add_task(async function test_update_highlighted() { await expectResults(async () => { await browser.tabs.update(tab2, {highlighted: true, active: true}); return {active: tab2, highlighted: [tab2], events: [ - ["onActivated", {tabId: tab2, windowId}], + ["onActivated", {tabId: tab2, previousTabId: tab1, windowId}], ["onHighlighted", {tabIds: [tab2], windowId}], ]}; }, "highlighting and activating inactive highlighted tab"); @@ -131,7 +131,7 @@ add_task(async function test_update_highlighted() { await expectResults(async () => { await browser.tabs.update(tab1, {active: true, highlighted: true}); return {active: tab1, highlighted: [tab1], events: [ - ["onActivated", {tabId: tab1, windowId}], + ["onActivated", {tabId: tab1, previousTabId: tab2, windowId}], ["onHighlighted", {tabIds: [tab1], windowId}], ]}; }, "highlighting and activating non-highlighted tab"); diff --git a/browser/components/extensions/test/mochitest/test_ext_all_apis.html b/browser/components/extensions/test/mochitest/test_ext_all_apis.html index 4fd70c8a85e8..1732f4d3836f 100644 --- a/browser/components/extensions/test/mochitest/test_ext_all_apis.html +++ b/browser/components/extensions/test/mochitest/test_ext_all_apis.html @@ -36,6 +36,7 @@ let expectedBackgroundApisTargetSpecific = [ "tabs.highlight", "tabs.insertCSS", "tabs.move", + "tabs.moveInSuccession", "tabs.onActivated", "tabs.onAttached", "tabs.onCreated", diff --git a/browser/components/search/content/search-one-offs.js b/browser/components/search/content/search-one-offs.js index 4ab221b46405..9d77a5fb04f5 100644 --- a/browser/components/search/content/search-one-offs.js +++ b/browser/components/search/content/search-one-offs.js @@ -7,8 +7,6 @@ /* eslint-env mozilla/browser-window */ /* globals XULCommandEvent */ -{ - class SearchOneOffs { constructor(container) { this.container = container; @@ -1236,5 +1234,3 @@ class SearchOneOffs { window.SearchOneOffs = SearchOneOffs; -} - diff --git a/browser/components/search/content/search.xml b/browser/components/search/content/search.xml index 0e4b49689ab7..b679c5444d80 100644 --- a/browser/components/search/content/search.xml +++ b/browser/components/search/content/search.xml @@ -471,7 +471,7 @@ - new window.SearchOneOffs( + new SearchOneOffs( document.getAnonymousElementByAttribute(this, "anonid", "search-one-off-buttons")); diff --git a/browser/components/search/content/searchbar.js b/browser/components/search/content/searchbar.js index fcc71ac73f54..33eb6811b233 100644 --- a/browser/components/search/content/searchbar.js +++ b/browser/components/search/content/searchbar.js @@ -4,7 +4,6 @@ "use strict"; -/* eslint-env mozilla/browser-window */ /* globals XULCommandEvent */ // This is loaded into chrome windows with the subscript loader. Wrap in diff --git a/browser/modules/ContentSearch.jsm b/browser/modules/ContentSearch.jsm index 95fc0dd9f1b5..e608f503a3f1 100644 --- a/browser/modules/ContentSearch.jsm +++ b/browser/modules/ContentSearch.jsm @@ -273,11 +273,10 @@ var ContentSearch = { let ok = SearchSuggestionController.engineOffersSuggestions(engine); controller.maxLocalResults = ok ? MAX_LOCAL_SUGGESTIONS : MAX_SUGGESTIONS; controller.maxRemoteResults = ok ? MAX_SUGGESTIONS : 0; - let priv = PrivateBrowsingUtils.isBrowserPrivate(browser); // fetch() rejects its promise if there's a pending request, but since we // process our event queue serially, there's never a pending request. this._currentSuggestion = { controller, target: browser }; - let suggestions = await controller.fetch(searchString, priv, engine); + let suggestions = await controller.fetch(searchString, engine); this._currentSuggestion = null; // suggestions will be null if the request was cancelled diff --git a/browser/modules/ExtensionsUI.jsm b/browser/modules/ExtensionsUI.jsm index c94f5f78aba1..8a6f6f049e5d 100644 --- a/browser/modules/ExtensionsUI.jsm +++ b/browser/modules/ExtensionsUI.jsm @@ -365,7 +365,7 @@ var ExtensionsUI = { let popupOptions = { hideClose: true, popupIconURL: icon || DEFAULT_EXTENSION_ICON, - persistent: false, + persistent: true, removeOnDismissal: true, eventCallback(topic) { if (topic == "removed") { diff --git a/browser/themes/shared/controlcenter/panel.inc.css b/browser/themes/shared/controlcenter/panel.inc.css index 5e0c3684ff9a..ffa0052167b6 100644 --- a/browser/themes/shared/controlcenter/panel.inc.css +++ b/browser/themes/shared/controlcenter/panel.inc.css @@ -144,6 +144,10 @@ margin-bottom: 2px !important; } +.identity-popup-preferences-button:-moz-locale-dir(rtl) { + background-position: center left; +} + .identity-popup-preferences-button > .toolbarbutton-text { display: none; } diff --git a/devtools/client/debugger/test/mochitest/head.js b/devtools/client/debugger/test/mochitest/head.js index d2018ffb4db6..6126e24c138a 100644 --- a/devtools/client/debugger/test/mochitest/head.js +++ b/devtools/client/debugger/test/mochitest/head.js @@ -152,30 +152,6 @@ function removeAddon(aAddon) { return deferred.promise; } -function getTargetActorForUrl(aClient, aUrl) { - let deferred = promise.defer(); - - aClient.listTabs().then(aResponse => { - let targetActor = aResponse.tabs.filter(aGrip => aGrip.url == aUrl).pop(); - deferred.resolve(targetActor); - }); - - return deferred.promise; -} - -async function attachTargetActorForUrl(aClient, aUrl) { - let grip = await getTargetActorForUrl(aClient, aUrl); - let [ response, front ] = await aClient.attachTarget(grip.actor); - return [grip, response, front]; -} - -async function attachThreadActorForUrl(aClient, aUrl) { - let [grip, response] = await attachTargetActorForUrl(aClient, aUrl); - let [response2, threadClient] = await aClient.attachThread(response.threadActor); - await threadClient.resume(); - return threadClient; -} - // Override once from shared-head, as some tests depend on trying native DOM listeners // before EventEmitter. Since this directory is deprecated, there's little value in // resolving the descrepency here. @@ -908,7 +884,7 @@ function findTab(tabs, url) { function attachTarget(client, tab) { info("Attaching to tab with url '" + tab.url + "'."); - return client.attachTarget(tab.actor); + return client.attachTarget(tab); } function listWorkers(targetFront) { @@ -1090,29 +1066,3 @@ function waitForDispatch(panel, type, eventRepeat = 1) { } }); } - -async function initWorkerDebugger(TAB_URL, WORKER_URL) { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - let client = new DebuggerClient(DebuggerServer.connectPipe()); - await connect(client); - - let tab = await addTab(TAB_URL); - let { tabs } = await listTabs(client); - let [, targetFront] = await attachTarget(client, findTab(tabs, TAB_URL)); - - await createWorkerInTab(tab, WORKER_URL); - - let { workers } = await listWorkers(targetFront); - let workerTargetFront = findWorker(workers, WORKER_URL); - - let toolbox = await gDevTools.showToolbox(TargetFactory.forWorker(workerTargetFront), - "jsdebugger", - Toolbox.HostType.WINDOW); - - let debuggerPanel = toolbox.getCurrentPanel(); - let gDebugger = debuggerPanel.panelWin; - - return {client, tab, targetFront, workerTargetFront, toolbox, gDebugger}; -} diff --git a/devtools/client/framework/target.js b/devtools/client/framework/target.js index de53f5b2e9a4..366e42201b56 100644 --- a/devtools/client/framework/target.js +++ b/devtools/client/framework/target.js @@ -529,7 +529,7 @@ Target.prototype = { // The call to attachTarget is to be removed once all Target are having a front // passed as contructor's argument. if (!this.activeTab) { - const [, targetFront] = await this._client.attachTarget(this.form.actor); + const [, targetFront] = await this._client.attachTarget(this.form); this.activeTab = targetFront; } else { await this.activeTab.attach(); diff --git a/devtools/client/framework/test/browser_toolbox_tool_remote_reopen.js b/devtools/client/framework/test/browser_toolbox_tool_remote_reopen.js index 2ac413195acb..a59ca298390f 100644 --- a/devtools/client/framework/test/browser_toolbox_tool_remote_reopen.js +++ b/devtools/client/framework/test/browser_toolbox_tool_remote_reopen.js @@ -6,7 +6,6 @@ "use strict"; const { DebuggerServer } = require("devtools/server/main"); -const { DebuggerClient } = require("devtools/shared/client/debugger-client"); // Bug 1277805: Too slow for debug runs requestLongerTimeout(2); @@ -60,36 +59,13 @@ function runTools(target) { })(); } -function getClient() { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - const transport = DebuggerServer.connectPipe(); - const client = new DebuggerClient(transport); - - return client.connect().then(() => client); -} - -function getTarget(client) { - return new Promise(resolve => { - client.listTabs().then(tabList => { - const target = TargetFactory.forRemoteTab({ - client: client, - form: tabList.tabs[tabList.selected], - chrome: false, - }); - resolve(target); - }); - }); -} - function test() { (async function() { toggleAllTools(true); - await addTab("about:blank"); + const tab = await addTab("about:blank"); - const client = await getClient(); - const target = await getTarget(client); + const target = await TargetFactory.forTab(tab); + const { client } = target; await runTools(target); const rootFronts = [...client.mainRoot.fronts.values()]; diff --git a/devtools/client/shared/test/browser_dbg_WorkerTargetActor.attach.js b/devtools/client/shared/test/browser_dbg_WorkerTargetActor.attach.js index 9a60d7f28e8a..936fbcdddf91 100644 --- a/devtools/client/shared/test/browser_dbg_WorkerTargetActor.attach.js +++ b/devtools/client/shared/test/browser_dbg_WorkerTargetActor.attach.js @@ -26,15 +26,10 @@ function test() { const oldMaxTotalViewers = SpecialPowers.getIntPref(MAX_TOTAL_VIEWERS); SpecialPowers.setIntPref(MAX_TOTAL_VIEWERS, 10); - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - const client = new DebuggerClient(DebuggerServer.connectPipe()); - yield connect(client); - const tab = yield addTab(TAB1_URL); - const { tabs } = yield listTabs(client); - const [, targetFront] = yield attachTarget(client, findTab(tabs, TAB1_URL)); + const target = yield TargetFactory.forTab(tab); + yield target.attach(); + const targetFront = target.activeTab; yield listWorkers(targetFront); // If a page still has pending network requests, it will not be moved into @@ -71,7 +66,7 @@ function test() { yield workerTargetFront1.attach(); is(workerTargetFront1.isClosed, false, "worker in tab 1 should not be closed"); - yield close(client); + yield target.destroy(); SpecialPowers.setIntPref(MAX_TOTAL_VIEWERS, oldMaxTotalViewers); finish(); }); diff --git a/devtools/client/shared/test/browser_dbg_debugger-statement.js b/devtools/client/shared/test/browser_dbg_debugger-statement.js index ad83ef980aea..49fb6c97c550 100644 --- a/devtools/client/shared/test/browser_dbg_debugger-statement.js +++ b/devtools/client/shared/test/browser_dbg_debugger-statement.js @@ -15,82 +15,53 @@ Services.scriptloader.loadSubScript( "chrome://mochitests/content/browser/devtools/client/shared/test/helper_workers.js", this); -var { DebuggerServer } = require("devtools/server/main"); -var { DebuggerClient } = require("devtools/shared/client/debugger-client"); - const TAB_URL = TEST_URI_ROOT + "doc_inline-debugger-statement.html"; -var gClient; -var gTab; +add_task(async () => { + const tab = await addTab(TAB_URL); + const target = await TargetFactory.forTab(tab); + await target.attach(); + const { client } = target; + const targetFront = target.activeTab; -function test() { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); + const threadClient = await testEarlyDebuggerStatement(client, tab, targetFront); + await testDebuggerStatement(client, tab, threadClient); - const transport = DebuggerServer.connectPipe(); - gClient = new DebuggerClient(transport); - gClient.connect().then(([aType, aTraits]) => { - is(aType, "browser", - "Root actor should identify itself as a browser."); - - addTab(TAB_URL) - .then(tab => { - gTab = tab; - return attachTargetActorForUrl(gClient, TAB_URL); - }) - .then(testEarlyDebuggerStatement) - .then(testDebuggerStatement) - .then(() => gClient.close()) - .then(finish) - .catch(error => { - ok(false, "Got an error: " + error.message + "\n" + error.stack); - }); - }); -} - -function testEarlyDebuggerStatement([aGrip, aResponse]) { - const deferred = getDeferredPromise().defer(); + await target.destroy(); +}); +async function testEarlyDebuggerStatement(client, tab, targetFront) { const onPaused = function(event, packet) { ok(false, "Pause shouldn't be called before we've attached!"); - deferred.reject(); }; - gClient.addListener("paused", onPaused); + client.addListener("paused", onPaused); // This should continue without nesting an event loop and calling // the onPaused hook, because we haven't attached yet. - callInTab(gTab, "runDebuggerStatement"); + callInTab(tab, "runDebuggerStatement"); - gClient.removeListener("paused", onPaused); + client.removeListener("paused", onPaused); // Now attach and resume... - gClient.request({ to: aResponse.threadActor, type: "attach" }, () => { - gClient.request({ to: aResponse.threadActor, type: "resume" }, () => { - ok(true, "Pause wasn't called before we've attached."); - deferred.resolve([aGrip, aResponse]); - }); - }); + const [, threadClient] = await targetFront.attachThread(); + await threadClient.resume(); + ok(true, "Pause wasn't called before we've attached."); - return deferred.promise; + return threadClient; } -function testDebuggerStatement([aGrip, aResponse]) { - const deferred = getDeferredPromise().defer(); - - gClient.addListener("paused", (event, packet) => { - gClient.request({ to: aResponse.threadActor, type: "resume" }, () => { +async function testDebuggerStatement(client, tab, threadClient) { + const onPaused = new Promise(resolve => { + client.addListener("paused", async (event, packet) => { + await threadClient.resume(); ok(true, "The pause handler was triggered on a debugger statement."); - deferred.resolve(); + resolve(); }); }); // Reach around the debugging protocol and execute the debugger statement. - callInTab(gTab, "runDebuggerStatement"); + callInTab(tab, "runDebuggerStatement"); - return deferred.promise; + return onPaused; } - -registerCleanupFunction(function() { - gClient = null; -}); diff --git a/devtools/client/shared/test/browser_dbg_event-listeners-01.js b/devtools/client/shared/test/browser_dbg_event-listeners-01.js index 761b0bb0a63d..df8bb71a7e2c 100644 --- a/devtools/client/shared/test/browser_dbg_event-listeners-01.js +++ b/devtools/client/shared/test/browser_dbg_event-listeners-01.js @@ -15,28 +15,14 @@ Services.scriptloader.loadSubScript( "chrome://mochitests/content/browser/devtools/client/shared/test/helper_workers.js", this); -var { DebuggerServer } = require("devtools/server/main"); -var { DebuggerClient } = require("devtools/shared/client/debugger-client"); - const TAB_URL = TEST_URI_ROOT + "doc_event-listeners-01.html"; add_task(async function() { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - const transport = DebuggerServer.connectPipe(); - const client = new DebuggerClient(transport); - const [type] = await client.connect(); - - Assert.equal(type, "browser", - "Root actor should identify itself as a browser."); - const tab = await addTab(TAB_URL); - const threadClient = await attachThreadActorForUrl(client, TAB_URL); + const { client, threadClient } = await attachThreadActorForTab(tab); + await pauseDebuggee(tab, client, threadClient); await testEventListeners(client, threadClient); - - await client.close(); }); function pauseDebuggee(tab, client, threadClient) { diff --git a/devtools/client/shared/test/browser_dbg_event-listeners-02.js b/devtools/client/shared/test/browser_dbg_event-listeners-02.js index 0edaf7cdd061..de3fb19d0458 100644 --- a/devtools/client/shared/test/browser_dbg_event-listeners-02.js +++ b/devtools/client/shared/test/browser_dbg_event-listeners-02.js @@ -16,27 +16,14 @@ Services.scriptloader.loadSubScript( "chrome://mochitests/content/browser/devtools/client/shared/test/helper_workers.js", this); -var { DebuggerServer } = require("devtools/server/main"); -var { DebuggerClient } = require("devtools/shared/client/debugger-client"); - const TAB_URL = TEST_URI_ROOT + "doc_event-listeners-03.html"; add_task(async function() { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - const transport = DebuggerServer.connectPipe(); - const client = new DebuggerClient(transport); - const [type] = await client.connect(); - - Assert.equal(type, "browser", - "Root actor should identify itself as a browser."); - const tab = await addTab(TAB_URL); - const threadClient = await attachThreadActorForUrl(client, TAB_URL); + const { client, threadClient } = await attachThreadActorForTab(tab); + await pauseDebuggee(tab, client, threadClient); await testEventListeners(client, threadClient); - await client.close(); }); function pauseDebuggee(tab, client, threadClient) { diff --git a/devtools/client/shared/test/browser_dbg_event-listeners-03.js b/devtools/client/shared/test/browser_dbg_event-listeners-03.js index fad9958a03f0..e227ddfc90cc 100644 --- a/devtools/client/shared/test/browser_dbg_event-listeners-03.js +++ b/devtools/client/shared/test/browser_dbg_event-listeners-03.js @@ -16,43 +16,20 @@ Services.scriptloader.loadSubScript( "chrome://mochitests/content/browser/devtools/client/shared/test/helper_workers.js", this); -var { DebuggerServer } = require("devtools/server/main"); -var { DebuggerClient } = require("devtools/shared/client/debugger-client"); - const TAB_URL = TEST_URI_ROOT + "doc_native-event-handler.html"; -var gClient; -var gTab; +add_task(async () => { + const tab = await addTab(TAB_URL); + const { client, threadClient } = await attachThreadActorForTab(tab); -function test() { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); + await pauseDebuggee(client, tab, threadClient); + await testEventListeners(threadClient); +}); - const transport = DebuggerServer.connectPipe(); - gClient = new DebuggerClient(transport); - gClient.connect().then(([aType, aTraits]) => { - is(aType, "browser", - "Root actor should identify itself as a browser."); - - addTab(TAB_URL) - .then((tab) => { - gTab = tab; - return attachThreadActorForUrl(gClient, TAB_URL); - }) - .then(pauseDebuggee) - .then(testEventListeners) - .then(() => gClient.close()) - .then(finish) - .catch(error => { - ok(false, "Got an error: " + error.message + "\n" + error.stack); - }); - }); -} - -function pauseDebuggee(threadClient) { +function pauseDebuggee(client, tab, threadClient) { const deferred = getDeferredPromise().defer(); - gClient.addOneTimeListener("paused", (event, packet) => { + client.addOneTimeListener("paused", (event, packet) => { is(packet.type, "paused", "We should now be paused."); is(packet.why.type, "debuggerStatement", @@ -61,7 +38,7 @@ function pauseDebuggee(threadClient) { deferred.resolve(threadClient); }); - generateMouseClickInTab(gTab, "content.document.querySelector('button')"); + generateMouseClickInTab(tab, "content.document.querySelector('button')"); return deferred.promise; } @@ -86,7 +63,3 @@ function testEventListeners(threadClient) { return deferred.promise; } - -registerCleanupFunction(function() { - gClient = null; -}); diff --git a/devtools/client/shared/test/browser_dbg_listtabs-01.js b/devtools/client/shared/test/browser_dbg_listtabs-01.js index 0e1d9a778541..61dc8aa251c9 100644 --- a/devtools/client/shared/test/browser_dbg_listtabs-01.js +++ b/devtools/client/shared/test/browser_dbg_listtabs-01.js @@ -44,9 +44,9 @@ function testFirstTab() { return addTab(TAB1_URL).then(tab => { gTab1 = tab; - return getTargetActorForUrl(gClient, TAB1_URL).then(grip => { - ok(grip, "Should find a target actor for the first tab."); - gTab1Actor = grip.actor; + return getTargetActorForUrl(gClient, TAB1_URL).then(form => { + ok(form, "Should find a target actor for the first tab."); + gTab1Actor = form.actor; }); }); } @@ -67,8 +67,8 @@ function testSecondTab() { function testRemoveTab() { return removeTab(gTab1).then(() => { - return getTargetActorForUrl(gClient, TAB1_URL).then(grip => { - ok(!grip, "Shouldn't find a target actor for the first tab anymore."); + return getTargetActorForUrl(gClient, TAB1_URL).then(form => { + ok(!form, "Shouldn't find a target actor for the first tab anymore."); }); }); } @@ -100,13 +100,8 @@ registerCleanupFunction(function() { gClient = null; }); -function getTargetActorForUrl(client, url) { - const deferred = promise.defer(); - - client.listTabs().then(response => { - const targetActor = response.tabs.filter(grip => grip.url == url).pop(); - deferred.resolve(targetActor); - }); - - return deferred.promise; +async function getTargetActorForUrl(client, url) { + const { tabs } = await client.listTabs(); + const targetActor = tabs.filter(form => form.url == url).pop(); + return targetActor; } diff --git a/devtools/client/shared/test/browser_dbg_listtabs-03.js b/devtools/client/shared/test/browser_dbg_listtabs-03.js index 2d735b52ff0a..c06633c3e2e3 100644 --- a/devtools/client/shared/test/browser_dbg_listtabs-03.js +++ b/devtools/client/shared/test/browser_dbg_listtabs-03.js @@ -29,7 +29,7 @@ add_task(async function test() { const tabGrip = tabs.filter(a => a.url == TAB1_URL).pop(); ok(tabGrip, "Should have an actor for the tab"); - let [response, targetFront] = await client.attachTarget(tabGrip.actor); + let [response, targetFront] = await client.attachTarget(tabGrip); is(response.type, "tabAttached", "Should have attached"); response = await client.listTabs(); @@ -41,7 +41,7 @@ add_task(async function test() { const newGrip = tabs.filter(a => a.url == TAB1_URL).pop(); is(newGrip.actor, tabGrip.actor, "Should have the same actor for the same tab"); - [response, targetFront] = await client.attachTarget(tabGrip.actor); + [response, targetFront] = await client.attachTarget(tabGrip); is(response.type, "tabAttached", "Should have attached"); response = await targetFront.detach(); is(response.type, "detached", "Should have detached"); diff --git a/devtools/client/shared/test/browser_dbg_listworkers.js b/devtools/client/shared/test/browser_dbg_listworkers.js index 679fcef2ceb5..3277aeb4be61 100644 --- a/devtools/client/shared/test/browser_dbg_listworkers.js +++ b/devtools/client/shared/test/browser_dbg_listworkers.js @@ -17,23 +17,15 @@ Services.scriptloader.loadSubScript( "chrome://mochitests/content/browser/devtools/client/shared/test/helper_workers.js", this); -var { DebuggerServer } = require("devtools/server/main"); -var { DebuggerClient } = require("devtools/shared/client/debugger-client"); - var TAB_URL = EXAMPLE_URL + "doc_listworkers-tab.html"; var WORKER1_URL = "code_listworkers-worker1.js"; var WORKER2_URL = "code_listworkers-worker2.js"; add_task(async function test() { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - const client = new DebuggerClient(DebuggerServer.connectPipe()); - await connect(client); - const tab = await addTab(TAB_URL); - const { tabs } = await listTabs(client); - const [, targetFront] = await attachTarget(client, findTab(tabs, TAB_URL)); + const target = await TargetFactory.forTab(tab); + await target.attach(); + const targetFront = target.activeTab; let { workers } = await listWorkers(targetFront); is(workers.length, 0); @@ -74,6 +66,6 @@ add_task(async function test() { ({ workers } = await listWorkers(targetFront)); is(workers.length, 0); - await close(client); + await target.destroy(); finish(); }); diff --git a/devtools/client/shared/test/browser_dbg_navigation.js b/devtools/client/shared/test/browser_dbg_navigation.js index b39ed1e70f90..bbb28dc832ef 100644 --- a/devtools/client/shared/test/browser_dbg_navigation.js +++ b/devtools/client/shared/test/browser_dbg_navigation.js @@ -9,35 +9,19 @@ * Check tab attach/navigation. */ -var { DebuggerServer } = require("devtools/server/main"); -var { DebuggerClient } = require("devtools/shared/client/debugger-client"); - const TAB1_URL = EXAMPLE_URL + "doc_empty-tab-01.html"; const TAB2_FILE = "doc_empty-tab-02.html"; const TAB2_URL = EXAMPLE_URL + TAB2_FILE; -var gClient; +add_task(async () => { + const tab = await addTab(TAB1_URL); + const target = await TargetFactory.forTab(tab); + await target.attach(); + const targetFront = target.activeTab; -function test() { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - const transport = DebuggerServer.connectPipe(); - gClient = new DebuggerClient(transport); - gClient.connect().then(([aType, aTraits]) => { - is(aType, "browser", - "Root actor should identify itself as a browser."); - - addTab(TAB1_URL) - .then(() => attachTargetActorForUrl(gClient, TAB1_URL)) - .then(testNavigate) - .then(testDetach) - .then(finish) - .catch(error => { - ok(false, "Got an error: " + error.message + "\n" + error.stack); - }); - }); -} + await testNavigate(targetFront); + await testDetach(target); +}); function testNavigate(targetFront) { const outstanding = [promise.defer(), promise.defer()]; @@ -59,40 +43,16 @@ function testNavigate(targetFront) { }); BrowserTestUtils.loadURI(gBrowser.selectedBrowser, TAB2_URL); - return promise.all(outstanding.map(e => e.promise)) - .then(() => targetFront); + return promise.all(outstanding.map(e => e.promise)); } -async function testDetach(targetFront) { - const onDetached = targetFront.once("tabDetached"); +async function testDetach(target) { + // We can't listen for tabDetached at it is received by Target first + // and target is destroyed + const onDetached = target.once("close"); removeTab(gBrowser.selectedTab); - const packet = await onDetached; + await onDetached; ok(true, "Got a tab detach notification."); - is(packet.from, targetFront.actorID, - "tab detach message comes from the expected actor"); - - return gClient.close(); -} - -registerCleanupFunction(function() { - gClient = null; -}); - -async function attachTargetActorForUrl(client, url) { - const grip = await getTargetActorForUrl(client, url); - const [, targetFront] = await client.attachTarget(grip.actor); - return targetFront; -} - -function getTargetActorForUrl(client, url) { - const deferred = promise.defer(); - - client.listTabs().then(response => { - const targetActor = response.tabs.filter(grip => grip.url == url).pop(); - deferred.resolve(targetActor); - }); - - return deferred.promise; } diff --git a/devtools/client/shared/test/browser_dbg_target-scoped-actor-01.js b/devtools/client/shared/test/browser_dbg_target-scoped-actor-01.js index 63f1470a25fb..8d9e14394a44 100644 --- a/devtools/client/shared/test/browser_dbg_target-scoped-actor-01.js +++ b/devtools/client/shared/test/browser_dbg_target-scoped-actor-01.js @@ -9,17 +9,11 @@ * Check target-scoped actor lifetimes. */ -var { DebuggerServer } = require("devtools/server/main"); -var { DebuggerClient } = require("devtools/shared/client/debugger-client"); - const ACTORS_URL = EXAMPLE_URL + "testactors.js"; const TAB_URL = EXAMPLE_URL + "doc_empty-tab-01.html"; add_task(async function test() { - await addTab(TAB_URL); - - DebuggerServer.init(); - DebuggerServer.registerAllActors(); + const tab = await addTab(TAB_URL); await registerActorInContentProcess(ACTORS_URL, { prefix: "testOne", @@ -27,40 +21,23 @@ add_task(async function test() { type: { target: true }, }); - const transport = DebuggerServer.connectPipe(); - const client = new DebuggerClient(transport); - const [ type ] = await client.connect(); - is(type, "browser", "Root actor should identify itself as a browser."); + const target = await TargetFactory.forTab(tab); + await target.attach(); + const { client } = target; + const targetFront = target.activeTab; + const form = targetFront.targetForm; - const [ grip ] = await attachTargetActorForUrl(client, TAB_URL); - await testTargetScopedActor(client, grip); + await testTargetScopedActor(client, form); await removeTab(gBrowser.selectedTab); - await client.close(); + await target.destroy(); }); -async function testTargetScopedActor(client, grip) { - ok(grip.testOneActor, +async function testTargetScopedActor(client, form) { + ok(form.testOneActor, "Found the test target-scoped actor."); - ok(grip.testOneActor.includes("testOne"), + ok(form.testOneActor.includes("testOne"), "testOneActor's actorPrefix should be used."); - const response = await client.request({ to: grip.testOneActor, type: "ping" }); + const response = await client.request({ to: form.testOneActor, type: "ping" }); is(response.pong, "pong", "Actor should respond to requests."); } - -async function attachTargetActorForUrl(client, url) { - const grip = await getTargetActorForUrl(client, url); - const [ response ] = await client.attachTarget(grip.actor); - return [grip, response]; -} - -function getTargetActorForUrl(client, url) { - const deferred = promise.defer(); - - client.listTabs().then(response => { - const targetActor = response.tabs.filter(grip => grip.url == url).pop(); - deferred.resolve(targetActor); - }); - - return deferred.promise; -} diff --git a/devtools/client/shared/test/browser_dbg_target-scoped-actor-02.js b/devtools/client/shared/test/browser_dbg_target-scoped-actor-02.js index 9fb9cfb60eab..87a1ac5e5cf2 100644 --- a/devtools/client/shared/test/browser_dbg_target-scoped-actor-02.js +++ b/devtools/client/shared/test/browser_dbg_target-scoped-actor-02.js @@ -9,17 +9,11 @@ * Check target-scoped actor lifetimes. */ -var { DebuggerServer } = require("devtools/server/main"); -var { DebuggerClient } = require("devtools/shared/client/debugger-client"); - const ACTORS_URL = EXAMPLE_URL + "testactors.js"; const TAB_URL = EXAMPLE_URL + "doc_empty-tab-01.html"; add_task(async function() { - await addTab(TAB_URL); - - DebuggerServer.init(); - DebuggerServer.registerAllActors(); + const tab = await addTab(TAB_URL); await registerActorInContentProcess(ACTORS_URL, { prefix: "testOne", @@ -27,51 +21,33 @@ add_task(async function() { type: { target: true }, }); - const transport = DebuggerServer.connectPipe(); - const client = new DebuggerClient(transport); - const [type] = await client.connect(); - is(type, "browser", - "Root actor should identify itself as a browser."); + const target = await TargetFactory.forTab(tab); + await target.attach(); + const { client } = target; + const targetFront = target.activeTab; + const form = targetFront.targetForm; - const [grip] = await attachTargetActorForUrl(client, TAB_URL); - await testTargetScopedActor(client, grip); - await closeTab(client, grip); - await client.close(); + await testTargetScopedActor(client, form); + await closeTab(client, form); + await target.destroy(); }); -async function testTargetScopedActor(client, grip) { - ok(grip.testOneActor, +async function testTargetScopedActor(client, form) { + ok(form.testOneActor, "Found the test target-scoped actor."); - ok(grip.testOneActor.includes("testOne"), + ok(form.testOneActor.includes("testOne"), "testOneActor's actorPrefix should be used."); - const response = await client.request({ to: grip.testOneActor, type: "ping" }); + const response = await client.request({ to: form.testOneActor, type: "ping" }); is(response.pong, "pong", "Actor should respond to requests."); } -async function closeTab(client, grip) { +async function closeTab(client, form) { await removeTab(gBrowser.selectedTab); await Assert.rejects( - client.request({ to: grip.testOneActor, type: "ping" }), - err => err.message === `'ping' active request packet to '${grip.testOneActor}' ` + + client.request({ to: form.testOneActor, type: "ping" }), + err => err.message === `'ping' active request packet to '${form.testOneActor}' ` + `can't be sent as the connection just closed.`, "testOneActor went away."); } - -async function attachTargetActorForUrl(client, url) { - const grip = await getTargetActorForUrl(client, url); - const [ response ] = await client.attachTarget(grip.actor); - return [grip, response]; -} - -function getTargetActorForUrl(client, url) { - const deferred = promise.defer(); - - client.listTabs().then(response => { - const targetActor = response.tabs.filter(grip => grip.url == url).pop(); - deferred.resolve(targetActor); - }); - - return deferred.promise; -} diff --git a/devtools/client/shared/test/browser_dbg_worker-window.js b/devtools/client/shared/test/browser_dbg_worker-window.js index 51c8e79b0e2c..44f759686680 100644 --- a/devtools/client/shared/test/browser_dbg_worker-window.js +++ b/devtools/client/shared/test/browser_dbg_worker-window.js @@ -15,15 +15,10 @@ const WORKER_URL = "code_WorkerTargetActor.attachThread-worker.js"; add_task(async function() { await pushPrefs(["devtools.scratchpad.enabled", true]); - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - const client = new DebuggerClient(DebuggerServer.connectPipe()); - await connect(client); - const tab = await addTab(TAB_URL); - const { tabs } = await listTabs(client); - const [, targetFront] = await attachTarget(client, findTab(tabs, TAB_URL)); + const target = await TargetFactory.forTab(tab); + await target.attach(); + const targetFront = target.activeTab; await listWorkers(targetFront); await createWorkerInTab(tab, WORKER_URL); @@ -56,7 +51,7 @@ add_task(async function() { terminateWorkerInTab(tab, WORKER_URL); await waitForWorkerClose(workerTargetFront); - await close(client); + await target.destroy(); await toolbox.destroy(); }); diff --git a/devtools/client/shared/test/helper_workers.js b/devtools/client/shared/test/helper_workers.js index 890488bf16ad..3ef998582f11 100644 --- a/devtools/client/shared/test/helper_workers.js +++ b/devtools/client/shared/test/helper_workers.js @@ -116,7 +116,7 @@ function findTab(tabs, url) { function attachTarget(client, tab) { info("Attaching to tab with url '" + tab.url + "'."); - return client.attachTarget(tab.actor); + return client.attachTarget(tab); } function listWorkers(targetFront) { @@ -172,15 +172,11 @@ function getSplitConsole(toolbox, win) { } async function initWorkerDebugger(TAB_URL, WORKER_URL) { - DebuggerServer.init(); - DebuggerServer.registerAllActors(); - - const client = new DebuggerClient(DebuggerServer.connectPipe()); - await connect(client); - const tab = await addTab(TAB_URL); - const { tabs } = await listTabs(client); - const [, targetFront] = await attachTarget(client, findTab(tabs, TAB_URL)); + const target = await TargetFactory.forTab(tab); + await target.attach(); + const { client } = target; + const targetFront = target.activeTab; await createWorkerInTab(tab, WORKER_URL); @@ -242,28 +238,13 @@ this.removeTab = function removeTab(tab, win) { return deferred.promise; }; -async function attachTargetActorForUrl(client, url) { - const grip = await getTargetActorForUrl(client, url); - const [ response, front ] = await client.attachTarget(grip.actor); - return [grip, response, front]; -} - -async function attachThreadActorForUrl(client, url) { - const [, response] = await attachTargetActorForUrl(client, url); - const [, threadClient] = await client.attachThread(response.threadActor); +async function attachThreadActorForTab(tab) { + const target = await TargetFactory.forTab(tab); + await target.attach(); + const targetFront = target.activeTab; + const [, threadClient] = await targetFront.attachThread(); await threadClient.resume(); - return threadClient; -} - -function getTargetActorForUrl(client, url) { - const deferred = getDeferredPromise().defer(); - - client.listTabs().then(response => { - const targetActor = response.tabs.filter(grip => grip.url == url).pop(); - deferred.resolve(targetActor); - }); - - return deferred.promise; + return { client: target.client, threadClient }; } function pushPrefs(...aPrefs) { diff --git a/devtools/docs/backend/client-api.md b/devtools/docs/backend/client-api.md index acd25c0c5dea..f59b7e9b02d7 100644 --- a/devtools/docs/backend/client-api.md +++ b/devtools/docs/backend/client-api.md @@ -78,7 +78,7 @@ function attachToTab() { let tab = response.tabs[response.selected]; // Attach to the tab. - client.attachTarget(tab.actor).then(([response, targetFront]) => { + client.attachTarget(tab).then(([response, targetFront]) => { if (!targetFront) { return; } @@ -186,7 +186,7 @@ function debugTab() { // Find the active tab. let tab = response.tabs[response.selected]; // Attach to the tab. - client.attachTarget(tab.actor).then(([response, targetFront]) => { + client.attachTarget(tab).then(([response, targetFront]) => { if (!targetFront) { return; } diff --git a/devtools/server/tests/browser/browser_navigateEvents.js b/devtools/server/tests/browser/browser_navigateEvents.js index cb787241a4f1..d432c171b176 100644 --- a/devtools/server/tests/browser/browser_navigateEvents.js +++ b/devtools/server/tests/browser/browser_navigateEvents.js @@ -95,20 +95,15 @@ function onMessage({ data }) { assertEvent(data.event, data.data); } -async function connectAndAttachTab() { - // Ensure having a minimal server - initDebuggerServer(); - - // Connect to this tab - const transport = DebuggerServer.connectPipe(); - const client = new DebuggerClient(transport); - const form = await connectDebuggerClient(client); - const actorID = form.actor; - const [, targetFront ] = await client.attachTarget(actorID); +async function connectAndAttachTab(tab) { + const target = await TargetFactory.forTab(tab); + await target.attach(); + const targetFront = target.activeTab; + const actorID = targetFront.targetForm.actor; targetFront.on("tabNavigated", function(packet) { assertEvent("tabNavigated", packet); }); - return { client, actorID }; + return { target, actorID }; } add_task(async function() { @@ -125,7 +120,8 @@ add_task(async function() { // Listen for messages sent by the content task browser.messageManager.addMessageListener("devtools-test:event", onMessage); - const { client, actorID } = await connectAndAttachTab(); + const tab = gBrowser.getTabForBrowser(browser); + const { target, actorID } = await connectAndAttachTab(tab); await ContentTask.spawn(browser, [actorID], async function(actorId) { const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm", {}); const { DebuggerServer } = require("devtools/server/main"); @@ -170,7 +166,7 @@ add_task(async function() { // Cleanup browser.messageManager.removeMessageListener("devtools-test:event", onMessage); - await client.close(); + await target.destroy(); Services.obs.addObserver(httpObserver, "http-on-modify-request"); DebuggerServer.destroy(); }); diff --git a/devtools/server/tests/browser/browser_spawn_actor_in_parent.js b/devtools/server/tests/browser/browser_spawn_actor_in_parent.js index 749d8aa3c3c3..dbedd5775dc7 100644 --- a/devtools/server/tests/browser/browser_spawn_actor_in_parent.js +++ b/devtools/server/tests/browser/browser_spawn_actor_in_parent.js @@ -13,7 +13,7 @@ const ACTOR_URL = "chrome://mochitests/content/browser/devtools/server/tests/bro const { InContentFront, InParentFront } = require(ACTOR_URL); add_task(async function() { - await addTab("data:text/html;charset=utf-8,foo"); + const browser = await addTab("data:text/html;charset=utf-8,foo"); info("Register target-scoped actor in the content process"); await registerActorInContentProcess(ACTOR_URL, { @@ -22,9 +22,13 @@ add_task(async function() { type: { target: true }, }); - initDebuggerServer(); - const client = new DebuggerClient(DebuggerServer.connectPipe()); - const form = await connectDebuggerClient(client); + const tab = gBrowser.getTabForBrowser(browser); + const target = await TargetFactory.forTab(tab); + await target.attach(); + const targetFront = target.activeTab; + const { client } = target; + const form = targetFront.targetForm; + const inContentFront = InContentFront(client, form); const isInContent = await inContentFront.isInContent(); ok(isInContent, "ContentActor really runs in the content process"); @@ -43,6 +47,6 @@ add_task(async function() { ok(conn, "`conn`, first contructor argument is a DebuggerServerConnection instance"); is(mm, "ChromeMessageSender", "`mm`, last constructor argument is a message manager"); - await client.close(); + await target.destroy(); gBrowser.removeCurrentTab(); }); diff --git a/devtools/server/tests/browser/browser_webextension_inspected_window.js b/devtools/server/tests/browser/browser_webextension_inspected_window.js index 5f6eb33be338..a987b3a0f821 100644 --- a/devtools/server/tests/browser/browser_webextension_inspected_window.js +++ b/devtools/server/tests/browser/browser_webextension_inspected_window.js @@ -26,7 +26,7 @@ async function setup(pageUrl) { const { client, form } = target; - const [, targetFront] = await client.attachTarget(form.actor); + const [, targetFront] = await client.attachTarget(form); const [, consoleClient] = await client.attachConsole(form.consoleActor, []); diff --git a/devtools/server/tests/browser/head.js b/devtools/server/tests/browser/head.js index 2329348d4696..5870e32ec597 100644 --- a/devtools/server/tests/browser/head.js +++ b/devtools/server/tests/browser/head.js @@ -116,15 +116,6 @@ async function initInspectorFront(url) { return {inspector, walker, target}; } -/** - * Gets the RootActor form from a DebuggerClient. - * @param {DebuggerClient} client - * @return {RootActor} Resolves when connected. - */ -function getRootForm(client) { - return client.listTabs(); -} - /** * Wait until a DebuggerClient is connected. * @param {DebuggerClient} client @@ -136,21 +127,6 @@ function waitUntilClientConnected(client) { }); } -/** - * Connect a debugger client. - * - * @param {DebuggerClient} - * @return {Promise} Resolves to the targetActor form for the selected tab when the client - * is connected. - */ -function connectDebuggerClient(client) { - return client.connect() - .then(() => client.listTabs()) - .then(tabs => { - return tabs.tabs[tabs.selected]; - }); -} - /** * Wait for eventName on target. * @param {Object} target An observable object that either supports on/off or diff --git a/devtools/server/tests/mochitest/test_device.html b/devtools/server/tests/mochitest/test_device.html index fa0b5c2bb637..deea1dcaa945 100644 --- a/devtools/server/tests/mochitest/test_device.html +++ b/devtools/server/tests/mochitest/test_device.html @@ -27,53 +27,51 @@ window.onload = function() { const client = new DebuggerClient(DebuggerServer.connectPipe()); client.connect().then(function onConnect() { - client.listTabs().then(function onListTabs(response) { - return client.mainRoot.getFront("device"); - }).then(function(d) { - let desc; - const appInfo = Services.appinfo; - const utils = window.windowUtils; + return client.mainRoot.getFront("device"); + }).then(function(d) { + let desc; + const appInfo = Services.appinfo; + const utils = window.windowUtils; - const localDesc = { - appid: appInfo.ID, - vendor: appInfo.vendor, - name: appInfo.name, - version: appInfo.version, - appbuildid: appInfo.appBuildID, - platformbuildid: appInfo.platformBuildID, - platformversion: appInfo.platformVersion, - geckobuildid: appInfo.platformBuildID, - geckoversion: appInfo.platformVersion, - useragent: window.navigator.userAgent, - locale: Services.locale.appLocaleAsLangTag, - os: appInfo.OS, - processor: appInfo.XPCOMABI.split("-")[0], - compiler: appInfo.XPCOMABI.split("-")[1], - dpi: utils.displayDPI, - width: window.screen.width, - height: window.screen.height, - }; + const localDesc = { + appid: appInfo.ID, + vendor: appInfo.vendor, + name: appInfo.name, + version: appInfo.version, + appbuildid: appInfo.appBuildID, + platformbuildid: appInfo.platformBuildID, + platformversion: appInfo.platformVersion, + geckobuildid: appInfo.platformBuildID, + geckoversion: appInfo.platformVersion, + useragent: window.navigator.userAgent, + locale: Services.locale.appLocaleAsLangTag, + os: appInfo.OS, + processor: appInfo.XPCOMABI.split("-")[0], + compiler: appInfo.XPCOMABI.split("-")[1], + dpi: utils.displayDPI, + width: window.screen.width, + height: window.screen.height, + }; - function checkValues() { - for (const key in localDesc) { - is(desc[key], localDesc[key], "valid field (" + key + ")"); - } - - const currProfD = Services.dirsvc.get("ProfD", Ci.nsIFile); - const profileDir = currProfD.path; - ok(profileDir.includes(desc.profile.length > 0 && desc.profile), - "valid profile name"); - - client.close().then(() => { - DebuggerServer.destroy(); - SimpleTest.finish(); - }); + function checkValues() { + for (const key in localDesc) { + is(desc[key], localDesc[key], "valid field (" + key + ")"); } - d.getDescription().then(function(v) { - desc = v; - }).then(checkValues); - }); + const currProfD = Services.dirsvc.get("ProfD", Ci.nsIFile); + const profileDir = currProfD.path; + ok(profileDir.includes(desc.profile.length > 0 && desc.profile), + "valid profile name"); + + client.close().then(() => { + DebuggerServer.destroy(); + SimpleTest.finish(); + }); + } + + d.getDescription().then(function(v) { + desc = v; + }).then(checkValues); }); }; diff --git a/devtools/server/tests/mochitest/test_preference.html b/devtools/server/tests/mochitest/test_preference.html index 8681fa01757f..2d7bdc011e60 100644 --- a/devtools/server/tests/mochitest/test_preference.html +++ b/devtools/server/tests/mochitest/test_preference.html @@ -27,75 +27,73 @@ function runTests() { const client = new DebuggerClient(DebuggerServer.connectPipe()); client.connect().then(function onConnect() { - client.listTabs().then(function onListTabs(response) { - return client.mainRoot.getFront("preference"); - }).then(function(p) { - const prefs = {}; + return client.mainRoot.getFront("preference"); + }).then(function(p) { + const prefs = {}; - const localPref = { - boolPref: true, - intPref: 0x1234, - charPref: "Hello World", + const localPref = { + boolPref: true, + intPref: 0x1234, + charPref: "Hello World", + }; + + function checkValues() { + is(prefs.boolPref, localPref.boolPref, "read/write bool pref"); + is(prefs.intPref, localPref.intPref, "read/write int pref"); + is(prefs.charPref, localPref.charPref, "read/write string pref"); + + ["test.all.bool", "test.all.int", "test.all.string"].forEach(function(key) { + let expectedValue; + switch (Services.prefs.getPrefType(key)) { + case Ci.nsIPrefBranch.PREF_STRING: + expectedValue = Services.prefs.getCharPref(key); + break; + case Ci.nsIPrefBranch.PREF_INT: + expectedValue = Services.prefs.getIntPref(key); + break; + case Ci.nsIPrefBranch.PREF_BOOL: + expectedValue = Services.prefs.getBoolPref(key); + break; + default: + ok(false, "unexpected pref type (" + key + ")"); + break; + } + + is(prefs.allPrefs[key].value, expectedValue, + "valid preference value (" + key + ")"); + is(prefs.allPrefs[key].hasUserValue, Services.prefs.prefHasUserValue(key), + "valid hasUserValue (" + key + ")"); + }); + + ["test.bool", "test.int", "test.string"].forEach(function(key) { + ok(!prefs.allPrefs.hasOwnProperty(key), "expect no pref (" + key + ")"); + is(Services.prefs.getPrefType(key), Ci.nsIPrefBranch.PREF_INVALID, + "pref (" + key + ") is clear"); + }); + + client.close().then(() => { + DebuggerServer.destroy(); + SimpleTest.finish(); + }); + } + + function updatePrefsProperty(key) { + return function(value) { + prefs[key] = value; }; + } - function checkValues() { - is(prefs.boolPref, localPref.boolPref, "read/write bool pref"); - is(prefs.intPref, localPref.intPref, "read/write int pref"); - is(prefs.charPref, localPref.charPref, "read/write string pref"); - - ["test.all.bool", "test.all.int", "test.all.string"].forEach(function(key) { - let expectedValue; - switch (Services.prefs.getPrefType(key)) { - case Ci.nsIPrefBranch.PREF_STRING: - expectedValue = Services.prefs.getCharPref(key); - break; - case Ci.nsIPrefBranch.PREF_INT: - expectedValue = Services.prefs.getIntPref(key); - break; - case Ci.nsIPrefBranch.PREF_BOOL: - expectedValue = Services.prefs.getBoolPref(key); - break; - default: - ok(false, "unexpected pref type (" + key + ")"); - break; - } - - is(prefs.allPrefs[key].value, expectedValue, - "valid preference value (" + key + ")"); - is(prefs.allPrefs[key].hasUserValue, Services.prefs.prefHasUserValue(key), - "valid hasUserValue (" + key + ")"); - }); - - ["test.bool", "test.int", "test.string"].forEach(function(key) { - ok(!prefs.allPrefs.hasOwnProperty(key), "expect no pref (" + key + ")"); - is(Services.prefs.getPrefType(key), Ci.nsIPrefBranch.PREF_INVALID, - "pref (" + key + ") is clear"); - }); - - client.close().then(() => { - DebuggerServer.destroy(); - SimpleTest.finish(); - }); - } - - function updatePrefsProperty(key) { - return function(value) { - prefs[key] = value; - }; - } - - p.getAllPrefs().then(updatePrefsProperty("allPrefs")) - .then(() => p.setBoolPref("test.bool", localPref.boolPref)) - .then(() => p.setIntPref("test.int", localPref.intPref)) - .then(() => p.setCharPref("test.string", localPref.charPref)) - .then(() => p.getBoolPref("test.bool")).then(updatePrefsProperty("boolPref")) - .then(() => p.getIntPref("test.int")).then(updatePrefsProperty("intPref")) - .then(() => p.getCharPref("test.string")).then(updatePrefsProperty("charPref")) - .then(() => p.clearUserPref("test.bool")) - .then(() => p.clearUserPref("test.int")) - .then(() => p.clearUserPref("test.string")) - .then(checkValues); - }); + p.getAllPrefs().then(updatePrefsProperty("allPrefs")) + .then(() => p.setBoolPref("test.bool", localPref.boolPref)) + .then(() => p.setIntPref("test.int", localPref.intPref)) + .then(() => p.setCharPref("test.string", localPref.charPref)) + .then(() => p.getBoolPref("test.bool")).then(updatePrefsProperty("boolPref")) + .then(() => p.getIntPref("test.int")).then(updatePrefsProperty("intPref")) + .then(() => p.getCharPref("test.string")).then(updatePrefsProperty("charPref")) + .then(() => p.clearUserPref("test.bool")) + .then(() => p.clearUserPref("test.int")) + .then(() => p.clearUserPref("test.string")) + .then(checkValues); }); } diff --git a/devtools/server/tests/mochitest/webconsole-helpers.js b/devtools/server/tests/mochitest/webconsole-helpers.js index 327e4c958dfe..5521d22be614 100644 --- a/devtools/server/tests/mochitest/webconsole-helpers.js +++ b/devtools/server/tests/mochitest/webconsole-helpers.js @@ -2,8 +2,8 @@ "use strict"; const {require} = ChromeUtils.import("resource://devtools/shared/Loader.jsm", {}); -const {DebuggerClient} = require("devtools/shared/client/debugger-client"); const {DebuggerServer} = require("devtools/server/main"); +const {TargetFactory} = require("devtools/client/framework/target"); const Services = require("Services"); @@ -35,37 +35,24 @@ if (!DebuggerServer.initialized) { * the opened tab and disconnect its debugger client. */ async function attachURL(url) { - let win = window.open(url, "_blank"); - let client = null; - - const cleanup = async function() { - if (client) { - await client.close(); - client = null; - } - if (win) { - win.close(); - win = null; - } - }; - SimpleTest.registerCleanupFunction(cleanup); - - client = new DebuggerClient(DebuggerServer.connectPipe()); - await client.connect(); - const {tabs} = await client.listTabs(); - const attachedTab = tabs.find(tab => tab.url === url); - - if (!attachedTab) { - throw new Error(`Could not find a tab matching URL ${url}`); - } - - const [, targetFront] = await client.attachTarget(attachedTab.actor); - const [, consoleClient] = await client.attachConsole(attachedTab.consoleActor, []); + const tab = await addTab(url); + const target = await TargetFactory.forTab(tab); + const { client } = target; + const { consoleActor } = target.form; + const [, consoleClient] = await client.attachConsole(consoleActor, []); return { - tab: attachedTab, - targetFront, consoleClient, - cleanup, }; } + +/** + * Naive implementaion of addTab working from a mochitest-chrome test. + */ +async function addTab(url) { + const { gBrowser } = Services.wm.getMostRecentWindow("navigator:browser"); + const {BrowserTestUtils} = require("resource://testing-common/BrowserTestUtils.jsm"); + const tab = gBrowser.selectedTab = BrowserTestUtils.addTab(gBrowser, url); + await BrowserTestUtils.browserLoaded(tab.linkedBrowser); + return tab; +} diff --git a/devtools/server/tests/unit/head_dbg.js b/devtools/server/tests/unit/head_dbg.js index 78b911df74ac..8d38ef116f1a 100644 --- a/devtools/server/tests/unit/head_dbg.js +++ b/devtools/server/tests/unit/head_dbg.js @@ -149,7 +149,7 @@ function findTab(tabs, title) { function attachTarget(client, tab) { dump("Attaching to tab with title '" + tab.title + "'.\n"); - return client.attachTarget(tab.actor); + return client.attachTarget(tab); } function waitForNewSource(threadClient, url) { @@ -327,7 +327,7 @@ function getTestTab(client, title, callback) { // response packet and a TargetFront instance referring to that tab. function attachTestTab(client, title, callback) { getTestTab(client, title, function(tab) { - client.attachTarget(tab.actor).then(([response, targetFront]) => { + client.attachTarget(tab).then(([response, targetFront]) => { callback(response, targetFront); }); }); diff --git a/devtools/shared/client/debugger-client.js b/devtools/shared/client/debugger-client.js index e62d46322f06..2a7d20590ce8 100644 --- a/devtools/shared/client/debugger-client.js +++ b/devtools/shared/client/debugger-client.js @@ -357,13 +357,14 @@ DebuggerClient.prototype = { * Instantiates a new ThreadActor that can be later attached to in order to * debug JS sources in the document. * - * @param string targetActor - * The target actor ID for the tab to attach. + * @param string targetActorForm + * The target actor form for the tab to attach. */ - attachTarget: async function(targetActor) { - let front = this._frontPool.actor(targetActor); + attachTarget: async function(targetActorForm) { + const actorID = targetActorForm.actor; + let front = this._frontPool.actor(actorID); if (!front) { - front = new BrowsingContextTargetFront(this, { actor: targetActor }); + front = new BrowsingContextTargetFront(this, targetActorForm); this._frontPool.manage(front); } diff --git a/devtools/shared/webconsole/test/common.js b/devtools/shared/webconsole/test/common.js index 57e0077dbbd2..6056274d47a7 100644 --- a/devtools/shared/webconsole/test/common.js +++ b/devtools/shared/webconsole/test/common.js @@ -26,100 +26,91 @@ function initDebuggerServer() { DebuggerServer.allowChromeProcess = true; } -function connectToDebugger() { +async function connectToDebugger() { initCommon(); initDebuggerServer(); const transport = DebuggerServer.connectPipe(); const client = new DebuggerClient(transport); - const dbgState = { dbgClient: client }; - return new Promise(resolve => { - client.connect().then(response => resolve([dbgState, response])); - }); + await client.connect(); + return client; } -function attachConsole(listeners, callback) { - _attachConsole(listeners, callback); +async function attachConsole(listeners, callback) { + const { state, response } = await _attachConsole(listeners); + callback(state, response); } -function attachConsoleToTab(listeners, callback) { - _attachConsole(listeners, callback, true); +async function attachConsoleToTab(listeners, callback) { + const { state, response } = await _attachConsole(listeners, true); + callback(state, response); } -function attachConsoleToWorker(listeners, callback) { - _attachConsole(listeners, callback, true, true); +async function attachConsoleToWorker(listeners, callback) { + const { state, response } = await _attachConsole(listeners, true, true); + callback(state, response); } var _attachConsole = async function( - listeners, callback, attachToTab, attachToWorker + listeners, attachToTab, attachToWorker ) { - function _onAttachConsole(state, [response, webConsoleClient]) { - state.client = webConsoleClient; + try { + const client = await connectToDebugger(); - callback(state, response); - } - function _onAttachError(state, response) { - console.error("attachConsole failed: " + response.error + " " + - response.message); - callback(state, response); - } - - function waitForMessage(target) { - return new Promise(resolve => { - target.addEventListener("message", resolve, { once: true }); - }); - } - - let [state, response] = await connectToDebugger(); - if (response.error) { - console.error("client.connect() failed: " + response.error + " " + - response.message); - callback(state, response); - return; - } - - if (!attachToTab) { - const front = await state.dbgClient.mainRoot.getMainProcess(); - await front.attach(); - const consoleActor = front.targetForm.consoleActor; - state.actor = consoleActor; - state.dbgClient.attachConsole(consoleActor, listeners) - .then(_onAttachConsole.bind(null, state), _onAttachError.bind(null, state)); - return; - } - response = await state.dbgClient.listTabs(); - if (response.error) { - console.error("listTabs failed: " + response.error + " " + - response.message); - callback(state, response); - return; - } - const tab = response.tabs[response.selected]; - const [, targetFront] = await state.dbgClient.attachTarget(tab.actor); - if (attachToWorker) { - const workerName = "console-test-worker.js#" + new Date().getTime(); - const worker = new Worker(workerName); - // Keep a strong reference to the Worker to avoid it being - // GCd during the test (bug 1237492). - // eslint-disable-next-line camelcase - state._worker_ref = worker; - await waitForMessage(worker); - - const { workers } = await targetFront.listWorkers(); - const workerTargetFront = workers.filter(w => w.url == workerName)[0]; - if (!workerTargetFront) { - console.error("listWorkers failed. Unable to find the worker actor\n"); - return; + function waitForMessage(target) { + return new Promise(resolve => { + target.addEventListener("message", resolve, { once: true }); + }); } - await workerTargetFront.attach(); - await workerTargetFront.attachThread({}); - state.actor = workerTargetFront.targetForm.consoleActor; - state.dbgClient.attachConsole(workerTargetFront.targetForm.consoleActor, listeners) - .then(_onAttachConsole.bind(null, state), _onAttachError.bind(null, state)); - } else { - state.actor = tab.consoleActor; - state.dbgClient.attachConsole(tab.consoleActor, listeners) - .then(_onAttachConsole.bind(null, state), _onAttachError.bind(null, state)); + + // Fetch the console actor out of the expected target + // ParentProcessTarget / WorkerTarget / FrameTarget + let consoleActor, worker; + if (!attachToTab) { + const front = await client.mainRoot.getMainProcess(); + await front.attach(); + consoleActor = front.targetForm.consoleActor; + } else { + const form = await client.getTab(); + const [, targetFront] = await client.attachTarget(form.tab); + if (attachToWorker) { + const workerName = "console-test-worker.js#" + new Date().getTime(); + worker = new Worker(workerName); + await waitForMessage(worker); + + const { workers } = await targetFront.listWorkers(); + const workerTargetFront = workers.filter(w => w.url == workerName)[0]; + if (!workerTargetFront) { + console.error("listWorkers failed. Unable to find the worker actor\n"); + return null; + } + await workerTargetFront.attach(); + await workerTargetFront.attachThread({}); + consoleActor = workerTargetFront.targetForm.consoleActor; + } else { + consoleActor = targetFront.targetForm.consoleActor; + } + } + + // Instantiate the WebConsoleClient + const [ response, webConsoleClient ] = await client.attachConsole(consoleActor, + listeners); + return { + state: { + dbgClient: client, + client: webConsoleClient, + actor: consoleActor, + // Keep a strong reference to the Worker to avoid it being + // GCd during the test (bug 1237492). + // eslint-disable-next-line camelcase + _worker_ref: worker, + }, + response, + }; + } catch (error) { + console.error(`attachConsole failed: ${error.error} ${error.message} - ` + + error.stack); } + return null; }; function closeDebugger(state, callback) { diff --git a/dom/base/nsDOMWindowUtils.cpp b/dom/base/nsDOMWindowUtils.cpp index cd7fe5e04d67..76cb4c0a4a89 100644 --- a/dom/base/nsDOMWindowUtils.cpp +++ b/dom/base/nsDOMWindowUtils.cpp @@ -286,6 +286,19 @@ nsDOMWindowUtils::GetWebRenderBridge() return nullptr; } +NS_IMETHODIMP +nsDOMWindowUtils::SyncFlushCompositor() +{ + if (nsIWidget* widget = GetWidget()) { + if (LayerManager* lm = widget->GetLayerManager()) { + if (KnowsCompositor* kc = lm->AsKnowsCompositor()) { + kc->SyncWithCompositor(); + } + } + } + return NS_OK; +} + NS_IMETHODIMP nsDOMWindowUtils::GetImageAnimationMode(uint16_t *aMode) { diff --git a/dom/canvas/WebGL2ContextFramebuffers.cpp b/dom/canvas/WebGL2ContextFramebuffers.cpp index 3589f92b35ab..53353cfa8b69 100644 --- a/dom/canvas/WebGL2ContextFramebuffers.cpp +++ b/dom/canvas/WebGL2ContextFramebuffers.cpp @@ -239,10 +239,6 @@ WebGLContext::ValidateInvalidateFramebuffer(GLenum target, //// - if (!fb) { - mDefaultFB_IsInvalid = true; - mResolvedDefaultFB = nullptr; - } return true; } diff --git a/dom/html/nsIFormProcessor.h b/dom/html/nsIFormProcessor.h index edc1fd10be75..ed868ee47f5d 100644 --- a/dom/html/nsIFormProcessor.h +++ b/dom/html/nsIFormProcessor.h @@ -52,9 +52,12 @@ public: * every form submission. * * @param aElement element which the attribute/value pair is submitted for - * @param aName value of the form element name attribute about to be submitted - * @param aValue On entry it contains the value about to be submitted for aName. - * On exit it contains the value which will actually be submitted for aName. + * @param aName value of the form element name attribute about to be + * submitted + * @param aValue On entry it contains the value about to be submitted + * for aName. + * On exit it contains the value which will actually be + * submitted for aName. * */ virtual nsresult ProcessValue(mozilla::dom::Element* aElement, @@ -75,8 +78,10 @@ public: * content which comes from a source other than the document (i.e. a local database) * * @param aFormType Type of form to get content for. - * @param aOptions List of nsStrings which define the contents for the form element - * @param aAttr Attribute to be attached to the form element. It is used to identify + * @param aOptions List of nsStrings which define the contents for the + * form element + * @param aAttr Attribute to be attached to the form element. It is + * used to identify * the form element contains non-standard content. */ diff --git a/dom/indexedDB/Key.cpp b/dom/indexedDB/Key.cpp index 61ab7d226263..3a58ba077739 100644 --- a/dom/indexedDB/Key.cpp +++ b/dom/indexedDB/Key.cpp @@ -54,7 +54,8 @@ namespace indexedDB { When encoding strings, we use variable-size encoding per the following table Chars 0 - 7E are encoded as 0xxxxxxx with 1 added - Chars 7F - (3FFF+7F) are encoded as 10xxxxxx xxxxxxxx with 7F subtracted + Chars 7F - (3FFF+7F) are encoded as 10xxxxxx xxxxxxxx with 7F + subtracted Chars (3FFF+80) - FFFF are encoded as 11xxxxxx xxxxxxxx xx000000 This ensures that the first byte is never encoded as 0, which means that the diff --git a/dom/interfaces/base/nsIDOMWindowUtils.idl b/dom/interfaces/base/nsIDOMWindowUtils.idl index a6ea19fdd48c..0bbf69ef3403 100644 --- a/dom/interfaces/base/nsIDOMWindowUtils.idl +++ b/dom/interfaces/base/nsIDOMWindowUtils.idl @@ -1994,6 +1994,8 @@ interface nsIDOMWindowUtils : nsISupports { const long DIRECTION_LTR = 0; const long DIRECTION_RTL = 1; const long DIRECTION_NOT_SET = 2; + + void syncFlushCompositor(); }; [scriptable, uuid(c694e359-7227-4392-a138-33c0cc1f15a6)] diff --git a/dom/media/DOMMediaStream.h b/dom/media/DOMMediaStream.h index 80d20f8c72ab..64f3b634f28b 100644 --- a/dom/media/DOMMediaStream.h +++ b/dom/media/DOMMediaStream.h @@ -152,7 +152,8 @@ class Pledge; * * DOMStream A * Input Owned Playback - * t1 ---------> t1 <- MediaStreamTrack X (removed) + * t1 ---------> t1 <- MediaStreamTrack X + * (removed) * (pointing to t1 in A) * t2 ---------> t2 ------------> t2 <- MediaStreamTrack Y * \ (pointing to t2 in A) @@ -160,7 +161,8 @@ class Pledge; * \ / (pointing to t1 in B) * DOMStream B \ / * Input \ Owned / Playback - * t1 ---^-----> t1 --- <- MediaStreamTrack Z (removed) + * t1 ---^-----> t1 --- <- MediaStreamTrack Z + * (removed) * \ \ (pointing to t1 in B) * \ \ * DOMStream A' \ \ diff --git a/dom/media/webaudio/blink/DynamicsCompressorKernel.cpp b/dom/media/webaudio/blink/DynamicsCompressorKernel.cpp index c09b775450f2..83c7e1a60f9b 100644 --- a/dom/media/webaudio/blink/DynamicsCompressorKernel.cpp +++ b/dom/media/webaudio/blink/DynamicsCompressorKernel.cpp @@ -276,7 +276,8 @@ void DynamicsCompressorKernel::process(float* sourceChannels[], float y4 = releaseFrames * releaseZone4; // All of these coefficients were derived for 4th order polynomial curve fitting where the y values - // match the evenly spaced x values as follows: (y1 : x == 0, y2 : x == 1, y3 : x == 2, y4 : x == 3) + // match the evenly spaced x values as follows: + // (y1 : x == 0, y2 : x == 1, y3 : x == 2, y4 : x == 3) float kA = 0.9999999999999998f*y1 + 1.8432219684323923e-16f*y2 - 1.9373394351676423e-16f*y3 + 8.824516011816245e-18f*y4; float kB = -1.5788320352845888f*y1 + 2.3305837032074286f*y2 - 0.9141194204840429f*y3 + 0.1623677525612032f*y4; float kC = 0.5334142869106424f*y1 - 1.272736789213631f*y2 + 0.9258856042207512f*y3 - 0.18656310191776226f*y4; diff --git a/dom/media/webaudio/blink/HRTFDatabase.h b/dom/media/webaudio/blink/HRTFDatabase.h index f15e1d60309e..ea8059f4aaa4 100644 --- a/dom/media/webaudio/blink/HRTFDatabase.h +++ b/dom/media/webaudio/blink/HRTFDatabase.h @@ -42,10 +42,12 @@ class HRTFDatabase { public: static nsReturnRef create(float sampleRate); + // clang-format off // getKernelsFromAzimuthElevation() returns a left and right ear kernel, and an interpolated left and right frame delay for the given azimuth and elevation. // azimuthBlend must be in the range 0 -> 1. // Valid values for azimuthIndex are 0 -> HRTFElevation::NumberOfTotalAzimuths - 1 (corresponding to angles of 0 -> 360). // Valid values for elevationAngle are MinElevation -> MaxElevation. + // clang-format on void getKernelsFromAzimuthElevation(double azimuthBlend, unsigned azimuthIndex, double elevationAngle, HRTFKernel* &kernelL, HRTFKernel* &kernelR, double& frameDelayL, double& frameDelayR); // Returns the number of different azimuth angles. diff --git a/dom/media/webaudio/blink/HRTFKernel.h b/dom/media/webaudio/blink/HRTFKernel.h index c9bd97ec9fa5..140adbd39625 100644 --- a/dom/media/webaudio/blink/HRTFKernel.h +++ b/dom/media/webaudio/blink/HRTFKernel.h @@ -43,7 +43,8 @@ using mozilla::FFTBlock; // HRTFKernel is a frequency-domain representation of an impulse-response used as part of the spatialized panning system. // For a given azimuth / elevation angle there will be one HRTFKernel for the left ear transfer function, and one for the right ear. // The leading delay (average group delay) for each impulse response is extracted: -// m_fftFrame is the frequency-domain representation of the impulse response with the delay removed +// m_fftFrame is the frequency-domain representation of the impulse +// response with the delay removed // m_frameDelay is the leading delay of the original impulse response. class HRTFKernel { public: diff --git a/dom/media/webaudio/blink/IIRFilter.cpp b/dom/media/webaudio/blink/IIRFilter.cpp index 992d7bfaacd5..f30b603f6749 100644 --- a/dom/media/webaudio/blink/IIRFilter.cpp +++ b/dom/media/webaudio/blink/IIRFilter.cpp @@ -117,7 +117,8 @@ void IIRFilter::getFrequencyResponse(int nFrequencies, const float* frequency, f // // H(z) = sum(b[k]*z^(-k), k, 0, M) / sum(a[k]*z^(-k), k, 0, N); // - // The desired frequency response is H(exp(j*omega)), where omega is in [0, 1). + // The desired frequency response is H(exp(j*omega)), where omega is in + // [0, 1). // // Let P(x) = sum(c[k]*x^k, k, 0, P) be a polynomial of order P. Then each of the sums in H(z) // is equivalent to evaluating a polynomial at the point 1/z. diff --git a/dom/plugins/base/npapi.h b/dom/plugins/base/npapi.h index bec12b42d61c..5e8635542de9 100644 --- a/dom/plugins/base/npapi.h +++ b/dom/plugins/base/npapi.h @@ -63,6 +63,7 @@ #define NP_VERSION_MINOR 29 +/* clang-format off */ /* The OS/2 version of Netscape uses RC_DATA to define the mime types, file extensions, etc that are required. Use a vertical bar to separate types, end types with \0. @@ -88,6 +89,7 @@ RCDATA NP_INFO_LegalCopyright { "Copyright Netscape Communications \251 1996\ RCDATA NP_INFO_OriginalFilename { "NVAPI32.DLL" } RCDATA NP_INFO_ProductName { "NPAVI32 Dynamic Link Library\0" } */ +/* clang-format on */ /* RC_DATA types for version info - required */ #define NP_INFO_ProductVersion 1 #define NP_INFO_MIMEType 2 diff --git a/dom/plugins/base/nsPluginLogging.h b/dom/plugins/base/nsPluginLogging.h index b29bf1952c76..542c70047150 100644 --- a/dom/plugins/base/nsPluginLogging.h +++ b/dom/plugins/base/nsPluginLogging.h @@ -31,8 +31,9 @@ // 2. You can combine logs and levels by separating them with a comma: // My favorite Win32 Example: SET MOZ_LOG=Plugin:5,PluginNPP:5,PluginNPN:5 -// 3. Instead of output going to the console, you can log to a file. Additionally, set the -// MOZ_LOG_FILE environment variable to point to the full path of a file. +// 3. Instead of output going to the console, you can log to a file. +// Additionally, set the MOZ_LOG_FILE environment variable to point to the +// full path of a file. // My favorite Win32 Example: SET MOZ_LOG_FILE=c:\temp\pluginLog.txt // 4. For complete information see the Gecko Developer guide: diff --git a/dom/plugins/ipc/FunctionBroker.h b/dom/plugins/ipc/FunctionBroker.h index 471dd7172db2..f6561c34db97 100644 --- a/dom/plugins/ipc/FunctionBroker.h +++ b/dom/plugins/ipc/FunctionBroker.h @@ -54,7 +54,8 @@ * Use a subclass instead of a typedef if you need to maintain data or state. * * Step 2: Add an instance of that object to the FunctionHookList in - * AddFunctionHook(FunctionHookList&) or AddBrokeredFunctionHook(FunctionHookList&). + * AddFunctionHook(FunctionHookList&) or + * AddBrokeredFunctionHook(FunctionHookList&). * This typically just means calling the constructor with the correct info. * At a minimum, this means supplying the names of the DLL and method to * broker, and a pointer to the original version of the method. @@ -81,7 +82,9 @@ * parameters are sent/returned. This example tells InternetWriteFileFB to * return its third parameter: * template<> template<> - * struct InternetWriteFileFB::Response::Info::ShouldMarshal<3> { static const bool value = true; }; + * struct InternetWriteFileFB::Response::Info::ShouldMarshal<3> { + * static const bool value = true; + * }; * By default, all parameters have ShouldMarshal set in the request phase * and only the return value (parameter -1) has it set in the response phase. * @@ -113,13 +116,16 @@ * length. Something like: * * typedef RequestHandler HookedFuncDelegateReq; + * int HOOK_CALL (nsDependentCSubstring)> + * HookedFuncDelegateReq; * * template<> - * void HookedFuncFB::Request::Marshal(IpdlTuple& aTuple, const void*& aBuf, const int& aBufLen) + * void HookedFuncFB::Request::Marshal(IpdlTuple& aTuple, const void*& aBuf, + * const int& aBufLen) * { * MOZ_ASSERT(nWritten); - * HookedFuncDelegateReq::Marshal(aTuple, nsDependentCSubstring(aBuf, aBufLen)); + * HookedFuncDelegateReq::Marshal(aTuple, + * nsDependentCSubstring(aBuf, aBufLen)); * } * * template<> diff --git a/dom/plugins/test/testplugin/nptest.cpp b/dom/plugins/test/testplugin/nptest.cpp index 047558289b50..238ebc5a5812 100644 --- a/dom/plugins/test/testplugin/nptest.cpp +++ b/dom/plugins/test/testplugin/nptest.cpp @@ -2456,7 +2456,8 @@ convertPointY(NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVaria static bool streamTest(NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result) { - // .streamTest(url, doPost, postData, writeCallback, notifyCallback, redirectCallback, allowRedirects, postFile = false) + // .streamTest(url, doPost, postData, writeCallback, notifyCallback, + // redirectCallback, allowRedirects, postFile = false) if (!(7 <= argCount && argCount <= 8)) return false; diff --git a/dom/presentation/PresentationSessionInfo.cpp b/dom/presentation/PresentationSessionInfo.cpp index 7a7e0f88ebca..9999fce8125e 100644 --- a/dom/presentation/PresentationSessionInfo.cpp +++ b/dom/presentation/PresentationSessionInfo.cpp @@ -1144,7 +1144,8 @@ PresentationControllingInfo::NotifyData(const nsACString& aData, bool aIsBinary) * During presentation session establishment, the receiver expects the following * after trying to launch the app by notifying "presentation-launch-receiver": * (The order between step 2 and 3 is not guaranteed.) - * 1. |Observe| of |nsIObserver| is called with "presentation-receiver-launched". + * 1. |Observe| of |nsIObserver| is called with + * "presentation-receiver-launched". * Then start listen to document |STATE_TRANSFERRING| event. * 2. |NotifyResponderReady| is called to indicate the receiver page is ready * for presentation use. diff --git a/dom/promise/PromiseWorkerProxy.h b/dom/promise/PromiseWorkerProxy.h index 94dfcb3f4e0a..9f5f46cc86bd 100644 --- a/dom/promise/PromiseWorkerProxy.h +++ b/dom/promise/PromiseWorkerProxy.h @@ -29,7 +29,8 @@ class WorkerPrivate; // 1. Create a Promise on the worker thread and return it to the content // script: // -// RefPtr promise = Promise::Create(workerPrivate->GlobalScope(), aRv); +// RefPtr promise = +// Promise::Create(workerPrivate->GlobalScope(), aRv); // if (aRv.Failed()) { // return nullptr; // } @@ -79,7 +80,8 @@ class WorkerPrivate; // worker. // // RefPtr runnable = -// new FinishTaskWorkerRunnable(proxy->GetWorkerPrivate(), proxy, result); +// new FinishTaskWorkerRunnable(proxy->GetWorkerPrivate(), proxy, +// result); // if (!r->Dispatch()) { // // Worker is alive but not Running any more, so the Promise can't // // be resolved, give up. The proxy will get Release()d at some diff --git a/dom/security/nsCSPContext.cpp b/dom/security/nsCSPContext.cpp index 2d35953216b3..76ba9aa45831 100644 --- a/dom/security/nsCSPContext.cpp +++ b/dom/security/nsCSPContext.cpp @@ -549,10 +549,12 @@ nsCSPContext::GetAllowsInline(nsContentPolicyType aContentType, * * @param violationType: the VIOLATION_TYPE_* constant (partial symbol) * such as INLINE_SCRIPT - * @param contentPolicyType: a constant from nsIContentPolicy such as TYPE_STYLESHEET + * @param contentPolicyType: a constant from nsIContentPolicy such as + * TYPE_STYLESHEET * @param nonceOrHash: for NONCE and HASH violations, it's the nonce or content * string. For other violations, it is an empty string. - * @param keyword: the keyword corresponding to violation (UNSAFE_INLINE for most) + * @param keyword: the keyword corresponding to violation (UNSAFE_INLINE for + * most) * @param observerTopic: the observer topic string to send with the CSP * observer notifications. * diff --git a/dom/security/nsCSPParser.h b/dom/security/nsCSPParser.h index 03d6c075657d..b0b274f5d63a 100644 --- a/dom/security/nsCSPParser.h +++ b/dom/security/nsCSPParser.h @@ -123,7 +123,8 @@ class nsCSPParser { * are stored in mTokens, for example: * mTokens = [ [ script-src, http://www.example.com, 'self' ], ... ] * - * When parsing starts, mCurdir always holds the currently processed array of strings. + * When parsing starts, mCurdir always holds the currently processed array of + * strings. * In our example: * mCurDir = [ script-src, http://www.example.com, 'self' ] * @@ -133,20 +134,22 @@ class nsCSPParser { * mCurToken = script-src * which allows to do simple string comparisons to see if mCurToken is a valid directive. * - * Continuing parsing, the parser consumes the next string of that array, resetting: + * Continuing parsing, the parser consumes the next string of that array, + * resetting: * mCurToken = "http://www.example.com" * ^ ^ * mCurChar mEndChar (points *after* the 'm') * mCurValue = "" * - * After calling advance() the first time, helpers would hold the following values: + * After calling advance() the first time, helpers would hold the following + * values: * mCurToken = "http://www.example.com" * ^ ^ * mCurChar mEndChar (points *after* the 'm') * mCurValue = "h" * - * We continue parsing till all strings of one directive are consumed, then we reset - * mCurDir to hold the next array of strings and start the process all over. + * We continue parsing till all strings of one directive are consumed, then we + * reset mCurDir to hold the next array of strings and start the process all over. */ const char16_t* mCurChar; diff --git a/dom/security/nsMixedContentBlocker.cpp b/dom/security/nsMixedContentBlocker.cpp index 6843636ead63..4d63f418c013 100644 --- a/dom/security/nsMixedContentBlocker.cpp +++ b/dom/security/nsMixedContentBlocker.cpp @@ -642,9 +642,10 @@ nsMixedContentBlocker::ShouldLoad(bool aHadInsecureImageRedirect, // In this case we use aRequestingLocation to set requestingLocation. // b) TYPE_CSP_REPORT which does not provide a context. In this case we // use aRequestingLocation to set requestingLocation. - // c) content scripts from addon code that do not provide aRequestingContext - // or aRequestingLocation, but do provide aRequestPrincipal. - // If aRequestPrincipal is an expanded principal, we allow the load. + // c) content scripts from addon code that do not provide + // aRequestingContext or aRequestingLocation, but do provide + // aRequestPrincipal. If aRequestPrincipal is an expanded principal, + // we allow the load. // 4) If we still end up not having a requestingLocation, we reject the load. nsCOMPtr principal; diff --git a/dom/security/test/gtest/TestCSPParser.cpp b/dom/security/test/gtest/TestCSPParser.cpp index c73ff8fc8f2d..6ae92b96f0c0 100644 --- a/dom/security/test/gtest/TestCSPParser.cpp +++ b/dom/security/test/gtest/TestCSPParser.cpp @@ -179,6 +179,7 @@ TEST(CSPParser, Directives) { static const PolicyTest policies[] = { + // clang-format off { "connect-src xn--mnchen-3ya.de", "connect-src http://xn--mnchen-3ya.de"}, { "default-src http://www.example.com", @@ -221,6 +222,7 @@ TEST(CSPParser, Directives) "worker-src https://example.com" }, { "worker-src http://worker.com; frame-src http://frame.com; child-src http://child.com", "worker-src http://worker.com; frame-src http://frame.com; child-src http://child.com" }, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); @@ -233,6 +235,7 @@ TEST(CSPParser, Keywords) { static const PolicyTest policies[] = { + // clang-format off { "script-src 'self'", "script-src 'self'" }, { "script-src 'unsafe-inline'", @@ -245,18 +248,20 @@ TEST(CSPParser, Keywords) "script-src 'none'" }, { "img-src 'none'; script-src 'unsafe-eval' 'unsafe-inline'; default-src 'self'", "img-src 'none'; script-src 'unsafe-eval' 'unsafe-inline'; default-src 'self'" }, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 1))); } -// ============================= TestIgnoreUpperLowerCasePolicies ======================== +// =================== TestIgnoreUpperLowerCasePolicies ============== TEST(CSPParser, IgnoreUpperLowerCasePolicies) { static const PolicyTest policies[] = { + // clang-format off { "script-src 'SELF'", "script-src 'self'" }, { "sCriPt-src 'Unsafe-Inline'", @@ -289,18 +294,20 @@ TEST(CSPParser, IgnoreUpperLowerCasePolicies) "sandbox allow-forms"}, { "require-SRI-for sCript stYle", "require-sri-for script style"}, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 1))); } -// ============================= TestPaths ======================== +// ========================= TestPaths =============================== TEST(CSPParser, Paths) { static const PolicyTest policies[] = { + // clang-format off { "script-src http://www.example.com", "script-src http://www.example.com" }, { "script-src http://www.example.com/", @@ -387,18 +394,20 @@ TEST(CSPParser, Paths) "script-src http://www.example.com:88/.js" }, { "script-src https://foo.com/_abc/abc_/_/_a_b_c_", "script-src https://foo.com/_abc/abc_/_/_a_b_c_" } + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 1))); } -// ============================= TestSimplePolicies ======================== +// ======================== TestSimplePolicies ======================= TEST(CSPParser, SimplePolicies) { static const PolicyTest policies[] = { + // clang-format off { "default-src *", "default-src *" }, { "default-src https:", @@ -463,18 +472,20 @@ TEST(CSPParser, SimplePolicies) "upgrade-insecure-requests" }, { "sandbox allow-scripts allow-forms ", "sandbox allow-scripts allow-forms" }, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 1))); } -// ============================= TestPoliciesWithInvalidSrc ======================== +// =================== TestPoliciesWithInvalidSrc ==================== TEST(CSPParser, PoliciesWithInvalidSrc) { static const PolicyTest policies[] = { + // clang-format off { "script-src 'self'; SCRIPT-SRC http://www.example.com", "script-src 'self'" }, { "script-src 'none' test.com; script-src example.com", @@ -557,6 +568,7 @@ TEST(CSPParser, PoliciesWithInvalidSrc) "require-sri-for script"}, { "sandbox foo", "sandbox"}, + // clang-format on }; // amount of tests - 1, because the latest should be ignored. @@ -564,12 +576,13 @@ TEST(CSPParser, PoliciesWithInvalidSrc) ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 1))); } -// ============================= TestBadPolicies ======================== +// ============================= TestBadPolicies ======================= TEST(CSPParser, BadPolicies) { static const PolicyTest policies[] = { + // clang-format off { "script-sr 'self", "" }, { "", "" }, { "; ; ; ; ; ; ;", "" }, @@ -580,18 +593,20 @@ TEST(CSPParser, BadPolicies) { "require-sri-for foo", ""}, { "report-uri", ""}, { "report-uri http://:foo", ""}, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 0))); } -// ============================= TestGoodGeneratedPolicies ======================== +// ======================= TestGoodGeneratedPolicies ================= TEST(CSPParser, GoodGeneratedPolicies) { static const PolicyTest policies[] = { + // clang-format off { "default-src 'self'; img-src *", "default-src 'self'; img-src *" }, { "report-uri /policy", @@ -808,18 +823,20 @@ TEST(CSPParser, GoodGeneratedPolicies) "default-src 'self'; frame-ancestors 'self'" }, { "frame-ancestors http://bar.com/foo.png", "frame-ancestors http://bar.com/foo.png" }, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 1))); } -// ============================= TestBadGeneratedPolicies ======================== +// ==================== TestBadGeneratedPolicies ==================== TEST(CSPParser, BadGeneratedPolicies) { static const PolicyTest policies[] = { + // clang-format off { "foo.*.bar", ""}, { "foo!bar.com", ""}, { "x.*.a.com", ""}, @@ -834,13 +851,14 @@ TEST(CSPParser, BadGeneratedPolicies) { "http://other:pass1@self.com/foo", ""}, { "http://user1:pass1@self.com/foo", ""}, { "http://username:password@self.com/bar", ""}, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 0))); } -// ============ TestGoodGeneratedPoliciesForPathHandling ============ +// ============ TestGoodGeneratedPoliciesForPathHandling ============= TEST(CSPParser, GoodGeneratedPoliciesForPathHandling) { @@ -849,6 +867,7 @@ TEST(CSPParser, GoodGeneratedPoliciesForPathHandling) static const PolicyTest policies[] = { + // clang-format off { "img-src http://test1.example.com", "img-src http://test1.example.com" }, { "img-src http://test1.example.com/", @@ -957,18 +976,20 @@ TEST(CSPParser, GoodGeneratedPoliciesForPathHandling) "img-src https://test1.example.com/abc////////////def/" }, { "img-src https://test1.example.com/abc////////////", "img-src https://test1.example.com/abc////////////" }, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 1))); } -// ============ TestBadGeneratedPoliciesForPathHandling ============ +// ============== TestBadGeneratedPoliciesForPathHandling ============ TEST(CSPParser, BadGeneratedPoliciesForPathHandling) { static const PolicyTest policies[] = { + // clang-format off { "img-src test1.example.com:88path-1/", "img-src 'none'" }, { "img-src test1.example.com:80.js", @@ -983,13 +1004,14 @@ TEST(CSPParser, BadGeneratedPoliciesForPathHandling) "img-src 'none'" }, { "img-src http://test1.example.com:80abc", "img-src 'none'" }, + // clang-format on }; uint32_t policyCount = sizeof(policies) / sizeof(PolicyTest); ASSERT_TRUE(NS_SUCCEEDED(runTestSuite(policies, policyCount, 1))); } -// ============================= TestFuzzyPolicies ======================== +// ======================== TestFuzzyPolicies ======================== // Use a policy, eliminate one character at a time, // and feed it as input to the parser. @@ -1010,7 +1032,7 @@ TEST(CSPParser, ShorteningPolicies) } } -// ============================= TestFuzzyPolicies ======================== +// ============================= TestFuzzyPolicies =================== // We generate kFuzzyRuns inputs by (pseudo) randomly picking from the 128 // ASCII characters; feed them to the parser and verfy that the parser @@ -1045,7 +1067,7 @@ TEST(CSPParser, FuzzyPolicies) #endif -// ============================= TestFuzzyPoliciesIncDir ======================== +// ======================= TestFuzzyPoliciesIncDir =================== // In a similar fashion as in TestFuzzyPolicies, we again (pseudo) randomly // generate input for the parser, but this time also include a valid directive @@ -1085,7 +1107,7 @@ TEST(CSPParser, FuzzyPoliciesIncDir) #endif -// ============================= TestFuzzyPoliciesIncDirLimASCII ============== +// ====================== TestFuzzyPoliciesIncDirLimASCII ============ // Same as TestFuzzyPoliciesIncDir() but using limited ASCII, // which represents more likely input. diff --git a/dom/serviceworkers/ServiceWorkerManager.cpp b/dom/serviceworkers/ServiceWorkerManager.cpp index bab00c4defe3..880a818169e6 100644 --- a/dom/serviceworkers/ServiceWorkerManager.cpp +++ b/dom/serviceworkers/ServiceWorkerManager.cpp @@ -2757,12 +2757,12 @@ ServiceWorkerManager::RemoveRegistration(ServiceWorkerRegistrationInfo* aRegistr { // Note, we do not need to call mActor->SendUnregister() here. There are a few // ways we can get here: - // 1) Through a normal unregister which calls SendUnregister() in the unregister - // job Start() method. + // 1) Through a normal unregister which calls SendUnregister() in the + // unregister job Start() method. // 2) Through origin storage being purged. These result in ForceUnregister() // starting unregister jobs which in turn call SendUnregister(). - // 3) Through the failure to install a new service worker. Since we don't store - // the registration until install succeeds, we do not need to call + // 3) Through the failure to install a new service worker. Since we don't + // store the registration until install succeeds, we do not need to call // SendUnregister here. // Assert these conditions by testing for pending uninstall (cases 1 and 2) or // null workers (case 3). diff --git a/dom/websocket/WebSocket.h b/dom/websocket/WebSocket.h index 4dbaabd5fdbb..3c375cd91568 100644 --- a/dom/websocket/WebSocket.h +++ b/dom/websocket/WebSocket.h @@ -128,7 +128,8 @@ public: // WebIDL interface: // webIDL: readonly attribute DOMString protocol; void GetProtocol(nsAString& aResult); - // webIDL: void close(optional unsigned short code, optional DOMString reason): + // webIDL: void close(optional unsigned short code, + // optional DOMString reason): void Close(const Optional& aCode, const Optional& aReason, ErrorResult& aRv); diff --git a/dom/xbl/nsXBLBinding.cpp b/dom/xbl/nsXBLBinding.cpp index f97f83720c2d..0118823e2397 100644 --- a/dom/xbl/nsXBLBinding.cpp +++ b/dom/xbl/nsXBLBinding.cpp @@ -97,7 +97,7 @@ static const JSClass gPrototypeJSClass = { &gPrototypeJSClassOps }; -// Implementation ///////////////////////////////////////////////////////////////// +// Implementation ////////////////////////////////////////////////////////////// // Constructors/Destructors nsXBLBinding::nsXBLBinding(nsXBLPrototypeBinding* aBinding) @@ -808,7 +808,7 @@ nsXBLBinding::GetServoStyles() const return mPrototypeBinding->GetServoStyles(); } -// Internal helper methods //////////////////////////////////////////////////////////////// +// Internal helper methods ///////////////////////////////////////////////////// // Get or create a WeakMap object on a given XBL-hosting global. // diff --git a/dom/xbl/nsXBLPrototypeBinding.cpp b/dom/xbl/nsXBLPrototypeBinding.cpp index 9fe2e83d0b6e..016eb47c4127 100644 --- a/dom/xbl/nsXBLPrototypeBinding.cpp +++ b/dom/xbl/nsXBLPrototypeBinding.cpp @@ -52,7 +52,7 @@ using namespace mozilla; using namespace mozilla::dom; -// Helper Classes ===================================================================== +// Helper Classes ============================================================== // nsXBLAttributeEntry and helpers. This class is used to efficiently handle // attribute changes in anonymous content. @@ -105,7 +105,7 @@ nsXBLAttributeEntry::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const // ============================================================================= -// Implementation ///////////////////////////////////////////////////////////////// +// Implementation ////////////////////////////////////////////////////////////// // Constructors/Destructors nsXBLPrototypeBinding::nsXBLPrototypeBinding() @@ -456,7 +456,7 @@ nsXBLPrototypeBinding::ImplementsInterface(REFNSIID aIID) const return !!mInterfaceTable.GetWeak(aIID); } -// Internal helpers /////////////////////////////////////////////////////////////////////// +// Internal helpers //////////////////////////////////////////////////////////// Element* nsXBLPrototypeBinding::GetImmediateChild(nsAtom* aTag) diff --git a/dom/xbl/nsXBLService.cpp b/dom/xbl/nsXBLService.cpp index 40c1e46b7da3..6ea26fcd791d 100644 --- a/dom/xbl/nsXBLService.cpp +++ b/dom/xbl/nsXBLService.cpp @@ -346,7 +346,7 @@ nsXBLStreamListener::HandleEvent(Event* aEvent) return rv; } -// Implementation ///////////////////////////////////////////////////////////////// +// Implementation ////////////////////////////////////////////////////////////// // Implement our nsISupports methods NS_IMPL_ISUPPORTS(nsXBLService, nsISupportsWeakReference) @@ -717,7 +717,7 @@ nsXBLService::DetachGlobalKeyHandler(EventTarget* aTarget) return NS_OK; } -// Internal helper methods //////////////////////////////////////////////////////////////// +// Internal helper methods ///////////////////////////////////////////////////// nsresult nsXBLService::BindingReady(nsIContent* aBoundElement, diff --git a/dom/xslt/base/txList.h b/dom/xslt/base/txList.h index 66c7893fad46..3662c9f21e10 100644 --- a/dom/xslt/base/txList.h +++ b/dom/xslt/base/txList.h @@ -135,7 +135,8 @@ public: void* remove(); /** - * Resets the current location within the txList to the beginning of the txList + * Resets the current location within the txList to the beginning of the + * txList **/ void reset(); diff --git a/dom/xslt/xpath/txBooleanResult.cpp b/dom/xslt/xpath/txBooleanResult.cpp index 8eb91bb8eb00..3e94289f5ef6 100644 --- a/dom/xslt/xpath/txBooleanResult.cpp +++ b/dom/xslt/xpath/txBooleanResult.cpp @@ -11,7 +11,8 @@ /** * Creates a new BooleanResult with the value of the given bool parameter - * @param boolean the bool to use for initialization of this BooleanResult's value + * @param boolean the bool to use for initialization of this BooleanResult's + * value **/ BooleanResult::BooleanResult(bool boolean) : txAExprResult(nullptr) diff --git a/editor/libeditor/HTMLEditorDocumentCommands.cpp b/editor/libeditor/HTMLEditorDocumentCommands.cpp index 91512306ca42..6729e991a4a1 100644 --- a/editor/libeditor/HTMLEditorDocumentCommands.cpp +++ b/editor/libeditor/HTMLEditorDocumentCommands.cpp @@ -567,7 +567,8 @@ SetDocumentStateCommand::GetCommandStateParams(const char* aCommandName, * 2. Implement an nsIObserve object, e.g: * * void Observe( - * in nsISupports aSubject, // The nsICommandManager calling this Observer + * in nsISupports aSubject, // The nsICommandManager calling this + * // Observer * in string aTopic, // command name, e.g.:"obs_documentCreated" * // or "obs_documentWillBeDestroyed" in wstring aData ); // ignored (set to "command_status_changed") @@ -578,7 +579,8 @@ SetDocumentStateCommand::GetCommandStateParams(const char* aCommandName, * trigger the notification of this observer by something like: * * nsCOMPtr commandManager = mDocShell->GetCommandManager(); - * nsCOMPtr commandUpdater = do_QueryInterface(commandManager); + * nsCOMPtr commandUpdater = + * do_QueryInterface(commandManager); * NS_ENSURE_TRUE(commandUpdater, NS_ERROR_FAILURE); * commandUpdater->CommandStatusChanged(obs_documentCreated); * diff --git a/editor/libeditor/HTMLTableEditor.cpp b/editor/libeditor/HTMLTableEditor.cpp index 57af21416c28..39ff5645d888 100644 --- a/editor/libeditor/HTMLTableEditor.cpp +++ b/editor/libeditor/HTMLTableEditor.cpp @@ -78,7 +78,7 @@ public: } // This is needed to abort the caret reset in the destructor - // when one method yields control to another + // when one method yields control to another void CancelSetCaret() { mHTMLEditor = nullptr; @@ -1835,7 +1835,7 @@ HTMLEditor::SelectBlockOfCells(Element* aStartCell, } // We can only select a block if within the same table, - // so do nothing if not within one table + // so do nothing if not within one table if (table != endTable) { return NS_OK; } @@ -1851,11 +1851,11 @@ HTMLEditor::SelectBlockOfCells(Element* aStartCell, } // Suppress nsISelectionListener notification - // until all selection changes are finished + // until all selection changes are finished SelectionBatcher selectionBatcher(SelectionRefPtr()); // Examine all cell nodes in current selection and - // remove those outside the new block cell region + // remove those outside the new block cell region int32_t minColumn = std::min(startCellIndexes.mColumn, endCellIndexes.mColumn); int32_t minRow = @@ -1958,7 +1958,7 @@ HTMLEditor::SelectAllTableCells() } // Suppress nsISelectionListener notification - // until all selection changes are finished + // until all selection changes are finished SelectionBatcher selectionBatcher(SelectionRefPtr()); // It is now safe to clear the selection @@ -2040,12 +2040,12 @@ HTMLEditor::SelectTableRow() return error.StealNSResult(); } - //Note: At this point, we could get first and last cells in row, - // then call SelectBlockOfCells, but that would take just - // a little less code, so the following is more efficient + // Note: At this point, we could get first and last cells in row, + // then call SelectBlockOfCells, but that would take just + // a little less code, so the following is more efficient // Suppress nsISelectionListener notification - // until all selection changes are finished + // until all selection changes are finished SelectionBatcher selectionBatcher(SelectionRefPtr()); // It is now safe to clear the selection @@ -2125,7 +2125,7 @@ HTMLEditor::SelectTableColumn() } // Suppress nsISelectionListener notification - // until all selection changes are finished + // until all selection changes are finished SelectionBatcher selectionBatcher(SelectionRefPtr()); // It is now safe to clear the selection @@ -2217,7 +2217,7 @@ HTMLEditor::SplitTableCell() int32_t rowSpanBelow, colSpanAfter; // Split up cell row-wise first into rowspan=1 above, and the rest below, - // whittling away at the cell below until no more extra span + // whittling away at the cell below until no more extra span for (rowSpanBelow = actualRowSpan-1; rowSpanBelow >= 0; rowSpanBelow--) { // We really split row-wise only if we had rowspan > 1 if (rowSpanBelow > 0) { @@ -2298,7 +2298,7 @@ HTMLEditor::SplitCellIntoColumns(Element* aTable, } // Insert new cell after using the remaining span - // and always get the new cell so we can copy the background color; + // and always get the new cell so we can copy the background color; RefPtr newCellElement; rv = InsertCell(cellData.mElement, cellData.mEffectiveRowSpan, aColSpanRight, true, false, @@ -2394,8 +2394,8 @@ HTMLEditor::SplitCellIntoRows(Element* aTable, break; } // If cell found is AFTER desired new cell colum, - // we have multiple cells with rowspan > 1 that - // prevented us from finding a cell to insert after... + // we have multiple cells with rowspan > 1 that + // prevented us from finding a cell to insert after... if (cellDataAtInsertionPoint.mFirst.mColumn > cellData.mFirst.mColumn) { // ... so instead insert before the cell we found insertAfter = false; @@ -2410,9 +2410,9 @@ HTMLEditor::SplitCellIntoRows(Element* aTable, if (!cellElementAtInsertionPoint && lastCellFound) { // Edge case where we didn't find a cell to insert after - // or before because column(s) before desired column - // and all columns after it are spanned from above. - // We can insert after the last cell we found + // or before because column(s) before desired column + // and all columns after it are spanned from above. + // We can insert after the last cell we found cellElementAtInsertionPoint = std::move(lastCellFound); insertAfter = true; // Should always be true, but let's be sure } @@ -2424,7 +2424,7 @@ HTMLEditor::SplitCellIntoRows(Element* aTable, } // Insert new cell after using the remaining span - // and always get the new cell so we can copy the background color; + // and always get the new cell so we can copy the background color; RefPtr newCell; rv = InsertCell(cellElementAtInsertionPoint, aRowSpanBelow, cellData.mEffectiveColSpan, @@ -2522,8 +2522,8 @@ HTMLEditor::JoinTableCells(bool aMergeNonContiguousContents) AutoTransactionsConserveSelection dontChangeSelection(*this); // Note: We dont' use AutoSelectionSetterAfterTableEdit here so the selection - // is retained after joining. This leaves the target cell selected - // as well as the "non-contiguous" cells, so user can see what happened. + // is retained after joining. This leaves the target cell selected + // as well as the "non-contiguous" cells, so user can see what happened. ErrorResult error; CellAndIndexes firstSelectedCell(*this, *SelectionRefPtr(), error); @@ -2544,7 +2544,7 @@ HTMLEditor::JoinTableCells(bool aMergeNonContiguousContents) if (joinSelectedCells) { // We have selected cells: Join just contiguous cells - // and just merge contents if not contiguous + // and just merge contents if not contiguous TableSize tableSize(*this, *table, error); if (NS_WARN_IF(error.Failed())) { return error.StealNSResult(); @@ -2561,10 +2561,10 @@ HTMLEditor::JoinTableCells(bool aMergeNonContiguousContents) } // This defines the last indexes along the "edges" - // of the contiguous block of cells, telling us - // that we can join adjacent cells to the block + // of the contiguous block of cells, telling us + // that we can join adjacent cells to the block // Start with same as the first values, - // then expand as we find adjacent selected cells + // then expand as we find adjacent selected cells int32_t lastRowIndex = firstSelectedCell.mIndexes.mRow; int32_t lastColIndex = firstSelectedCell.mIndexes.mColumn; @@ -2621,7 +2621,7 @@ HTMLEditor::JoinTableCells(bool aMergeNonContiguousContents) if (cellData.mCurrent.mRow > firstSelectedCell.mIndexes.mRow + 1 && cellData.mCurrent.mColumn <= lastColIndex) { // Cell is in a column less than current right border in - // the third or higher selected row, so stop block at the previous row + // the third or higher selected row, so stop block at the previous row lastRowIndex = std::max(0, cellData.mCurrent.mRow - 1); lastRowIsSet = true; } @@ -2643,7 +2643,7 @@ HTMLEditor::JoinTableCells(bool aMergeNonContiguousContents) if (colIndex < lastColIndex) { // (don't think we ever get here?) // Cell is in a column less than current right boundary, - // so stop block at the previous row + // so stop block at the previous row lastRowIndex = std::max(0, rowIndex - 1); } else { // Go on to examine next row @@ -2654,7 +2654,7 @@ HTMLEditor::JoinTableCells(bool aMergeNonContiguousContents) lastColIndex = std::min(lastColIndex, lastColInRow); } else { // No selected cells in this row -- stop at row above - // and leave last column at its previous value + // and leave last column at its previous value lastRowIndex = std::max(0, rowIndex - 1); } } @@ -2687,14 +2687,14 @@ HTMLEditor::JoinTableCells(bool aMergeNonContiguousContents) cellData.mCurrent.mColumn <= lastColIndex) { // We are within the join region // Problem: It is very tricky to delete cells as we merge, - // since that will upset the cellmap - // Instead, build a list of cells to delete and do it later + // since that will upset the cellmap + // Instead, build a list of cells to delete and do it later NS_ASSERTION(!cellData.IsSpannedFromOtherRow(), "JoinTableCells: StartRowIndex is in row above"); if (cellData.mEffectiveColSpan > 1) { - //Check if cell "hangs" off the boundary because of colspan > 1 - // Use split methods to chop off excess + // Check if cell "hangs" off the boundary because of colspan > 1 + // Use split methods to chop off excess int32_t extraColSpan = cellData.mFirst.mColumn + cellData.mEffectiveColSpan - (lastColIndex + 1); @@ -2844,7 +2844,7 @@ HTMLEditor::JoinTableCells(bool aMergeNonContiguousContents) // Merged cell is "shorter" // (there are cells(s) below it that are row-spanned by target cell) // We could try splitting those cells, but that's REAL messy, - // so the safest thing to do is NOT really join the cells + // so the safest thing to do is NOT really join the cells return NS_OK; } @@ -2884,7 +2884,7 @@ HTMLEditor::MergeCells(RefPtr aTargetCell, if (!IsEmptyCell(aCellToMerge)) { // Get index of last child in target cell // If we fail or don't have children, - // we insert at index 0 + // we insert at index 0 int32_t insertIndex = 0; // Start inserting just after last child @@ -3984,7 +3984,7 @@ HTMLEditor::SetSelectionAfterTableEdit(Element* aTable, // Set the caret to deepest first child // but don't go into nested tables // TODO: Should we really be placing the caret at the END - // of the cell content? + // of the cell content? CollapseSelectionToDeepestNonTableFirstChild(cell); return; } diff --git a/editor/spellchecker/TextServicesDocument.cpp b/editor/spellchecker/TextServicesDocument.cpp index 03821759cb47..97aba5f3a35c 100644 --- a/editor/spellchecker/TextServicesDocument.cpp +++ b/editor/spellchecker/TextServicesDocument.cpp @@ -845,7 +845,8 @@ TextServicesDocument::SetSelection(int32_t aOffset, nsresult rv = SetSelectionInternal(aOffset, aLength, true); //**** KDEBUG **** - // printf("\n * Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset); + // printf("\n * Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, + // mSelStartOffset, mSelEndIndex, mSelEndOffset); //**** KDEBUG **** return rv; @@ -1110,7 +1111,8 @@ TextServicesDocument::DeleteSelection() //**** KDEBUG **** // printf("\n---- After Delete\n"); - // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset); + // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, + // mSelStartOffset, mSelEndIndex, mSelEndOffset); // PrintOffsetTable(); //**** KDEBUG **** @@ -1274,7 +1276,8 @@ TextServicesDocument::InsertText(const nsString* aText) //**** KDEBUG **** // printf("\n---- After Insert\n"); - // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset); + // printf("Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, + // mSelStartOffset, mSelEndIndex, mSelEndOffset); // PrintOffsetTable(); //**** KDEBUG **** @@ -1690,6 +1693,7 @@ TextServicesDocument::IsBlockNode(nsIContent* aContent) nsAtom *atom = aContent->NodeInfo()->NameAtom(); + // clang-format off return (nsGkAtoms::a != atom && nsGkAtoms::address != atom && nsGkAtoms::big != atom && @@ -1716,6 +1720,7 @@ TextServicesDocument::IsBlockNode(nsIContent* aContent) nsGkAtoms::u != atom && nsGkAtoms::var != atom && nsGkAtoms::wbr != atom); + // clang-format on } // static @@ -1836,7 +1841,8 @@ TextServicesDocument::SetSelectionInternal(int32_t aOffset, mSelEndOffset = mSelStartOffset; //**** KDEBUG **** - // printf("\n* Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset); + // printf("\n* Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, + // mSelStartOffset, mSelEndIndex, mSelEndOffset); //**** KDEBUG **** return NS_OK; @@ -1878,7 +1884,8 @@ TextServicesDocument::SetSelectionInternal(int32_t aOffset, } //**** KDEBUG **** - // printf("\n * Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, mSelStartOffset, mSelEndIndex, mSelEndOffset); + // printf("\n * Sel: (%2d, %4d) (%2d, %4d)\n", mSelStartIndex, + // mSelStartOffset, mSelEndIndex, mSelEndOffset); //**** KDEBUG **** return NS_OK; diff --git a/extensions/cookie/nsPermissionManager.cpp b/extensions/cookie/nsPermissionManager.cpp index 5940a5344255..3e9c5caff937 100644 --- a/extensions/cookie/nsPermissionManager.cpp +++ b/extensions/cookie/nsPermissionManager.cpp @@ -103,10 +103,10 @@ static int32_t sPreloadPermissionCount = 0; // Permissions which are in this list are considered to have a "" permission // key, even if their principal would not normally have that key. static const char* kPreloadPermissions[] = { - // NOTE: These permissions are the different nsContentBlocker permissions for - // allowing or denying certain content types from being loaded. Every - // permission listed in the `kTypeString` array in nsContentBlocker.cpp should - // appear in this list. + // NOTE: These permissions are the different nsContentBlocker permissions + // for allowing or denying certain content types from being loaded. Every + // permission listed in the `kTypeString` array in nsContentBlocker.cpp + // should appear in this list. "other", "script", "image", diff --git a/extensions/spellcheck/src/mozPersonalDictionary.cpp b/extensions/spellcheck/src/mozPersonalDictionary.cpp index e66fc3aad56e..9ec7fd7d0b43 100644 --- a/extensions/spellcheck/src/mozPersonalDictionary.cpp +++ b/extensions/spellcheck/src/mozPersonalDictionary.cpp @@ -32,7 +32,7 @@ /** * This is the most braindead implementation of a personal dictionary possible. * There is not much complexity needed, though. It could be made much faster, - * and probably should, but I don't see much need for more in terms of interface. + * and probably should, but I don't see much need for more in terms of interface. * * Allowing personal words to be associated with only certain dictionaries maybe. * diff --git a/gfx/2d/2D.h b/gfx/2d/2D.h index b568c2ccbeb8..11704fb6b4ed 100644 --- a/gfx/2d/2D.h +++ b/gfx/2d/2D.h @@ -349,7 +349,8 @@ public: Matrix mMatrix; //!< Transforms the pattern into user space IntRect mSamplingRect; /**< Rect that must not be sampled outside of, - or an empty rect if none has been specified. */ + or an empty rect if none has been + specified. */ }; class StoredPattern; @@ -956,7 +957,8 @@ public: * Creates a UnscaledFont using the font corresponding to the index. * * @param aIndex index for the font within the resource. - * @param aInstanceData pointer to read-only buffer of any available instance data. + * @param aInstanceData pointer to read-only buffer of any available instance + * data. * @param aInstanceDataLength the size of the instance data. * @return an already_addrefed UnscaledFont, containing nullptr if failed. */ @@ -1040,8 +1042,10 @@ public: * applying scaling. No sampling happens outside the source. * * @param aSurface Source surface to draw - * @param aDest Destination rectangle that this drawing operation should draw to - * @param aSource Source rectangle in aSurface coordinates, this area of aSurface + * @param aDest Destination rectangle that this drawing operation should draw + * to + * @param aSource Source rectangle in aSurface coordinates, this area of + * aSurface * will be stretched to the size of aDest. * @param aOptions General draw options that are applied to the operation * @param aSurfOptions DrawSurface options that are applied @@ -1466,7 +1470,8 @@ public: * filters. * * aScaledFont The scaled font used when drawing. - * aGlyphIndices An array of indices for the glyphs whose the metrics are wanted + * aGlyphIndices An array of indices for the glyphs whose the metrics are + * wanted * aNumGlyphs The amount of elements in aGlyphIndices * aGlyphMetrics The glyph metrics */ @@ -1724,9 +1729,11 @@ public: * * @param aData Pointer to the data * @param aSize Size of the TrueType data - * @param aBackendType Type of the reference DrawTarget the font should be created for. + * @param aBackendType Type of the reference DrawTarget the font should be + * created for. * @param aFontType Type of NativeFontResource that should be created. - * @param aFontContext Optional native font context to be used to create the NativeFontResource. + * @param aFontContext Optional native font context to be used to create the + * NativeFontResource. * @return a NativeFontResource of nullptr if failed. */ static already_AddRefed diff --git a/gfx/2d/Blur.cpp b/gfx/2d/Blur.cpp index 9866faaa65a3..9e9e6f604ba1 100644 --- a/gfx/2d/Blur.cpp +++ b/gfx/2d/Blur.cpp @@ -214,9 +214,11 @@ BoxBlurRow(const uint8_t* aInput, * Box blur involves looking at one pixel, and setting its value to the average * of its neighbouring pixels. This is meant to provide a 3-pass approximation of a * Gaussian blur. - * @param aTranspose Whether to transpose the buffer when reading and writing to it. + * @param aTranspose Whether to transpose the buffer when reading and writing + * to it. * @param aData The buffer to be blurred. - * @param aLobes The number of pixels to blend on the left and right for each of 3 passes. + * @param aLobes The number of pixels to blend on the left and right for each of + * 3 passes. * @param aWidth The number of columns in the buffers. * @param aRows The number of rows in the buffers. * @param aStride The stride of the buffer. diff --git a/gfx/2d/DrawTargetSkia.cpp b/gfx/2d/DrawTargetSkia.cpp index 7fdc27463259..a24899543832 100644 --- a/gfx/2d/DrawTargetSkia.cpp +++ b/gfx/2d/DrawTargetSkia.cpp @@ -1055,7 +1055,8 @@ GfxMatrixToCGAffineTransform(const Matrix &m) * We cannot cancel out (2) and (3) as we have to apply the clips and transforms * of DrawTargetSkia between (2) and (3). * - * Consider the example letter P, drawn at (0, 20) in CG coordinates in a (100, 100) rect. + * Consider the example letter P, drawn at (0, 20) in CG coordinates in a + * (100, 100) rect. * Again, going right to left of the transforms. We'd get: * * 1) The letter P drawn at (0, -20) due to the inversion of the Y axis diff --git a/gfx/2d/DrawTargetWrapAndRecord.h b/gfx/2d/DrawTargetWrapAndRecord.h index c75f1a51848e..c734662450ac 100644 --- a/gfx/2d/DrawTargetWrapAndRecord.h +++ b/gfx/2d/DrawTargetWrapAndRecord.h @@ -320,7 +320,8 @@ private: * We have to call CreateSimilarDrawTarget on mFinalDT up front and pass it in * as it can fail. * - * @param aDT DrawTargetWrapAndRecord on which CreateSimilarDrawTarget was called + * @param aDT DrawTargetWrapAndRecord on which CreateSimilarDrawTarget was + * called * @param aSimilarDT Similar DrawTarget created from aDT.mFinalDT. */ DrawTargetWrapAndRecord(const DrawTargetWrapAndRecord *aDT, diff --git a/gfx/2d/FilterProcessingSIMD-inl.h b/gfx/2d/FilterProcessingSIMD-inl.h index c17d047cac52..4dd8db35078c 100644 --- a/gfx/2d/FilterProcessingSIMD-inl.h +++ b/gfx/2d/FilterProcessingSIMD-inl.h @@ -247,12 +247,14 @@ template inline i32x4_t BlendAlphaOfFourPixels(i16x8_t s_rrrraaaa1234, i16x8_t d_rrrraaaa1234) { + // clang-format off // We're using MulAdd16x8x2To32x4, so we need to interleave our factors // appropriately. The calculation is rewritten as follows: // resultAlpha[0] * 255 = 255 * 255 - (255 - sourceAlpha[0]) * (255 - destAlpha[0]) // = 255 * 255 + (255 - sourceAlpha[0]) * (destAlpha[0] - 255) // = (255 - 0) * (510 - 255) + (255 - sourceAlpha[0]) * (destAlpha[0] - 255) // = MulAdd(255 - IntLv(0, sourceAlpha), IntLv(510, destAlpha) - 255)[0] + // clang-format on i16x8_t zeroInterleavedWithSourceAlpha = simd::InterleaveHi16(simd::FromI16(0), s_rrrraaaa1234); i16x8_t fiveTenInterleavedWithDestAlpha = simd::InterleaveHi16(simd::FromI16(510), d_rrrraaaa1234); i16x8_t f1 = simd::Sub16(simd::FromI16(255), zeroInterleavedWithSourceAlpha); @@ -517,13 +519,15 @@ ColorMatrixMultiply(i16x8_t p, i16x8_t rows_bg, i16x8_t rows_ra, const i32x4_t& // int16_t bg[8] = { b, g, b, g, b, g, b, g }; i16x8_t bg = simd::ShuffleHi16<1,0,1,0>(simd::ShuffleLo16<1,0,1,0>(p)); - // int32_t prodsum_bg[4] = { b * bB + g * gB, b * bG + g * gG, b * bR + g * gR, b * bA + g * gA } + // int32_t prodsum_bg[4] = + // { b * bB + g * gB, b * bG + g * gG, b * bR + g * gR, b * bA + g * gA } i32x4_t prodsum_bg = simd::MulAdd16x8x2To32x4(bg, rows_bg); sum = simd::Add32(sum, prodsum_bg); // uint16_t ra[8] = { r, a, r, a, r, a, r, a }; i16x8_t ra = simd::ShuffleHi16<3,2,3,2>(simd::ShuffleLo16<3,2,3,2>(p)); - // int32_t prodsum_ra[4] = { r * rB + a * aB, r * rG + a * aG, r * rR + a * aR, r * rA + a * aA } + // int32_t prodsum_ra[4] = + // { r * rB + a * aB, r * rG + a * aG, r * rR + a * aR, r * rA + a * aA } i32x4_t prodsum_ra = simd::MulAdd16x8x2To32x4(ra, rows_ra); sum = simd::Add32(sum, prodsum_ra); diff --git a/gfx/2d/HelpersD2D.h b/gfx/2d/HelpersD2D.h index 04237f04340b..fe64166ece1b 100644 --- a/gfx/2d/HelpersD2D.h +++ b/gfx/2d/HelpersD2D.h @@ -583,6 +583,7 @@ CreatePartialBitmapForSurface(DataSourceSurface *aSurface, const Matrix &aDestin // Limit the uploadRect as much as possible without supporting discontiguous uploads // + // clang-format off // region we will paint from // uploadRect // .---------------. .---------------. resulting uploadRect @@ -591,6 +592,7 @@ CreatePartialBitmapForSurface(DataSourceSurface *aSurface, const Matrix &aDestin // | | | ----> | | | | ----> | | // | '---------' '----' '----' '---------------' // '---------------' '---------------' + // clang-format on // // diff --git a/gfx/2d/JobScheduler_posix.cpp b/gfx/2d/JobScheduler_posix.cpp index 78c583f9c557..90323a2eaa6f 100644 --- a/gfx/2d/JobScheduler_posix.cpp +++ b/gfx/2d/JobScheduler_posix.cpp @@ -32,15 +32,18 @@ public: // XXX - temporarily disabled, see bug 1209039 // // // Call this from the thread itself because of Mac. -//#ifdef XP_MACOSX -// pthread_setname_np(aName); -//#elif defined(__DragonFly__) || defined(__FreeBSD__) || defined(__OpenBSD__) -// pthread_set_name_np(mThread, aName); -//#elif defined(__NetBSD__) -// pthread_setname_np(mThread, "%s", (void*)aName); -//#else -// pthread_setname_np(mThread, aName); -//#endif +/* +#ifdef XP_MACOSX + pthread_setname_np(aName); +#elif defined(__DragonFly__) || defined(__FreeBSD__) || \ + defined(__OpenBSD__) + pthread_set_name_np(mThread, aName); +#elif defined(__NetBSD__) + pthread_setname_np(mThread, "%s", (void*)aName); +#else + pthread_setname_np(mThread, aName); +#endif +*/ } protected: diff --git a/gfx/2d/Logging.h b/gfx/2d/Logging.h index d2d23eb12dd5..98dcb1499e6a 100644 --- a/gfx/2d/Logging.h +++ b/gfx/2d/Logging.h @@ -758,7 +758,8 @@ typedef Log CriticalLog; // This is a shortcut for errors we want logged in crash reports/about support // but we do not want asserting. These are available in all builds, so it is -// not worth trying to do magic to avoid matching the syntax of gfxCriticalError. +// not worth trying to do magic to avoid matching the syntax of +// gfxCriticalError. // So, this one is used as // gfxCriticalNote << "Something to report and not assert"; // while the critical error is diff --git a/gfx/2d/Path.cpp b/gfx/2d/Path.cpp index 4b912f8c140a..8fab62463358 100644 --- a/gfx/2d/Path.cpp +++ b/gfx/2d/Path.cpp @@ -340,14 +340,17 @@ FindInflectionApproximationRange(BezierControlPoints aControlPoints, * curve is degenerate in such a way that it is best approximated by a straight * line. * - * The below algorithm was written by Jeff Muizelaar , explanation follows: + * The below algorithm was written by Jeff Muizelaar , + * explanation follows: * * The lower inflection point is returned in aT1, the higher one in aT2. In the * case of a single inflection point this will be in aT1. * - * The method is inspired by the algorithm in "analysis of in?ection points for planar cubic bezier curve" + * The method is inspired by the algorithm in "analysis of in?ection points for + * planar cubic bezier curve" * - * Here are some differences between this algorithm and versions discussed elsewhere in the literature: + * Here are some differences between this algorithm and versions discussed + * elsewhere in the literature: * * zhang et. al compute a0, d0 and e0 incrementally using the follow formula: * @@ -360,9 +363,11 @@ FindInflectionApproximationRange(BezierControlPoints aControlPoints, * Point e0 = d1 - d0 * - * this avoids any multiplications and may or may not be faster than the approach take below. + * this avoids any multiplications and may or may not be faster than the + * approach take below. * - * "fast, precise flattening of cubic bezier path and ofset curves" by hain et. al + * "fast, precise flattening of cubic bezier path and ofset curves" by hain et. + * al * Point a = CP1 + 3 * CP2 - 3 * CP3 + CP4 * Point b = 3 * CP1 - 6 * CP2 + 3 * CP3 * Point c = -3 * CP1 + 3 * CP2 diff --git a/gfx/2d/Swizzle.cpp b/gfx/2d/Swizzle.cpp index 99cc85037e11..d69410cc8481 100644 --- a/gfx/2d/Swizzle.cpp +++ b/gfx/2d/Swizzle.cpp @@ -209,10 +209,11 @@ PremultiplyFallback(const uint8_t* aSrc, int32_t aSrcGap, if (aSwapRB) { rb = (rb >> 16) | (rb << 16); } - // Approximate the multiply by alpha and divide by 255 which is essentially: + // Approximate the multiply by alpha and divide by 255 which is + // essentially: // c = c*a + 255; c = (c + (c >> 8)) >> 8; - // However, we omit the final >> 8 to fold it with the final shift into place - // depending on desired output format. + // However, we omit the final >> 8 to fold it with the final shift into + // place depending on desired output format. rb = rb*a + 0x00FF00FF; rb = (rb + ((rb >> 8) & 0x00FF00FF)) & 0xFF00FF00; diff --git a/gfx/2d/SwizzleNEON.cpp b/gfx/2d/SwizzleNEON.cpp index 487577e89b0c..e4f4040765e1 100644 --- a/gfx/2d/SwizzleNEON.cpp +++ b/gfx/2d/SwizzleNEON.cpp @@ -184,14 +184,15 @@ UnpremultiplyVector_NEON(const uint16x8_t& aSrc) // lo1 lo1 lo2 lo2 lo3 lo3 lo4 lo4 and hi1 hi1 hi2 hi2 hi3 hi3 hi4 hi4 uint16x8x2_t q1234lohi = vtrnq_u16(q1234, q1234); - // VQDMULH is a signed multiply that doubles (*2) the result, then takes the high word. - // To work around the signedness and the doubling, the low portion of the reciprocal only - // stores the lower 15 bits, which fits in a signed 16 bit integer. The high 9 bit portion - // is effectively also doubled by 2 as a side-effect of being shifted for storage. Thus the - // output scale of doing a normal multiply by the high portion and the VQDMULH by the low - // portion are both doubled and can be safely added together. The resulting sum just needs - // to be halved (via VHADD) to thus cancel out the doubling. All this combines to produce - // a reciprocal multiply of the form: + // VQDMULH is a signed multiply that doubles (*2) the result, then takes the + // high word. To work around the signedness and the doubling, the low + // portion of the reciprocal only stores the lower 15 bits, which fits in a + // signed 16 bit integer. The high 9 bit portion is effectively also doubled + // by 2 as a side-effect of being shifted for storage. Thus the output scale + // of doing a normal multiply by the high portion and the VQDMULH by the low + // portion are both doubled and can be safely added together. The resulting + // sum just needs to be halved (via VHADD) to thus cancel out the doubling. + // All this combines to produce a reciprocal multiply of the form: // rb = ((rb * hi) + ((rb * lo * 2) >> 16)) / 2 rb = vhaddq_u16( diff --git a/gfx/gl/ForceDiscreteGPUHelperCGL.h b/gfx/gl/ForceDiscreteGPUHelperCGL.h index 9ede68e9daa1..4f4914b95fa5 100644 --- a/gfx/gl/ForceDiscreteGPUHelperCGL.h +++ b/gfx/gl/ForceDiscreteGPUHelperCGL.h @@ -20,7 +20,8 @@ public: ForceDiscreteGPUHelperCGL() : mPixelFormatObj(nullptr) { - // the code in this function is taken from Chromium, src/ui/gfx/gl/gl_context_cgl.cc, r122013 + // the code in this function is taken from Chromium, + // src/ui/gfx/gl/gl_context_cgl.cc, r122013 // BSD-style license, (c) The Chromium Authors CGLPixelFormatAttribute attribs[1]; attribs[0] = static_cast(0); diff --git a/gfx/gl/GLContextProviderWGL.cpp b/gfx/gl/GLContextProviderWGL.cpp index d20ff7384b93..03dbe0188dc1 100644 --- a/gfx/gl/GLContextProviderWGL.cpp +++ b/gfx/gl/GLContextProviderWGL.cpp @@ -176,6 +176,7 @@ WGLLibrary::EnsureInitialized() // Now we can grab all the other symbols that we couldn't without having // a context current. + // clang-format off const GLLibraryLoader::SymLoadStruct reqExtSymbols[] = { { (PRFuncPtr*)&mSymbols.fCreatePbuffer, { "wglCreatePbufferARB", "wglCreatePbufferEXT", nullptr } }, { (PRFuncPtr*)&mSymbols.fDestroyPbuffer, { "wglDestroyPbufferARB", "wglDestroyPbufferEXT", nullptr } }, @@ -188,6 +189,7 @@ WGLLibrary::EnsureInitialized() SYMBOL(GetExtensionsStringARB), END_OF_SYMBOLS }; + // clang-format on if (!GLLibraryLoader::LoadSymbols(mOGLLibrary, reqExtSymbols, lookupFunc)) { NS_WARNING("reqExtSymbols missing"); return false; diff --git a/gfx/webrender_bindings/Cargo.toml b/gfx/webrender_bindings/Cargo.toml index f5e2086e20b8..63c0bfacded9 100644 --- a/gfx/webrender_bindings/Cargo.toml +++ b/gfx/webrender_bindings/Cargo.toml @@ -9,7 +9,7 @@ rayon = "1" thread_profiler = "0.1.1" euclid = { version = "0.19.3", features = ["serde"] } app_units = "0.7" -gleam = "0.6.3" +gleam = "0.6.8" log = "0.4" nsstring = { path = "../../servo/support/gecko/nsstring" } bincode = "1.0" diff --git a/gfx/webrender_bindings/revision.txt b/gfx/webrender_bindings/revision.txt index dcfb8aed9e27..b88a384db04b 100644 --- a/gfx/webrender_bindings/revision.txt +++ b/gfx/webrender_bindings/revision.txt @@ -1 +1 @@ -195582a8dc5b9c6d26d54ce8d70060ccc8f423d8 +586af96c22c8b05722534e98703bfb47f1d270a1 diff --git a/gfx/wr/Cargo.lock b/gfx/wr/Cargo.lock index ed92a1bb2b59..a191172d3a9c 100644 --- a/gfx/wr/Cargo.lock +++ b/gfx/wr/Cargo.lock @@ -118,7 +118,7 @@ name = "cgl" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -308,7 +308,7 @@ name = "direct-composition" version = "0.1.0" dependencies = [ "euclid 0.19.3 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", "mozangle 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "webrender 0.57.2", "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", @@ -472,11 +472,21 @@ dependencies = [ ] [[package]] -name = "gleam" -version = "0.6.3" +name = "gl_generator" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "khronos_api 3.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "gleam" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "gl_generator 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -608,6 +618,11 @@ name = "khronos_api" version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "khronos_api" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "lazy_static" version = "0.2.11" @@ -1473,7 +1488,7 @@ dependencies = [ "dwrote 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "freetype 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.20.1 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1503,7 +1518,7 @@ dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.3 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", "glutin 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "rayon 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "webrender 0.57.2", @@ -1603,7 +1618,7 @@ dependencies = [ "env_logger 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.3 (registry+https://github.com/rust-lang/crates.io-index)", "font-loader 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)", "glutin 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.20.1 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1664,6 +1679,11 @@ dependencies = [ "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "xml-rs" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "yaml-rust" version = "0.3.5" @@ -1733,8 +1753,9 @@ dependencies = [ "checksum fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" "checksum gdi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0912515a8ff24ba900422ecda800b52f4016a56251922d397c576bf92c690518" "checksum gif 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ff3414b424657317e708489d2857d9575f4403698428b040b609b9d1c1a84a2c" +"checksum gl_generator 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a0ffaf173cf76c73a73e080366bf556b4776ece104b06961766ff11449f38604" "checksum gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a795170cbd85b5a7baa58d6d7525cae6a03e486859860c220f7ebbbdd379d0a" -"checksum gleam 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2260952cc0393ca6f183e1a91a035c65c85ddb02505f3d53e5a775eb05946f44" +"checksum gleam 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "4b47f5b15742aee359c7895ab98cf2cceecc89bb4feb6f4e42f802d7899877da" "checksum glutin 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a70c5fe78efbd5a3b243a804ea1032053c584510f8822819f94cfb29b2100317" "checksum half 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d5c5f71a723d10dfc58927cbed37c3071a50afc7f073d86fd7d3e5727db890f" "checksum httparse 1.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "c2f407128745b78abc95c0ffbe4e5d37427fdc0d45470710cfef8c44522a2e37" @@ -1748,6 +1769,7 @@ dependencies = [ "checksum jpeg-decoder 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "0dfe27a6c0dabd772d0f9b9f8701c4ca12c4d1eebcadf2be1f6f70396f6a1434" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" "checksum khronos_api 2.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "037ab472c33f67b5fbd3e9163a2645319e5356fcd355efa6d4eb7fff4bbcb554" +"checksum khronos_api 3.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "62237e6d326bd5871cd21469323bf096de81f1618cd82cbaf5d87825335aeb49" "checksum lazy_static 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73" "checksum lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c8f31047daa365f19be14b47c29df4f7c3b581832407daabe6ae77397619237d" "checksum lazycell 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a6f08839bc70ef4a3fe1d566d5350f519c5912ea86be0df1740a7d247c7fc0ef" @@ -1860,5 +1882,6 @@ dependencies = [ "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" "checksum x11-dl 2.17.5 (registry+https://github.com/rust-lang/crates.io-index)" = "3235540540fde1ae074c8df49054166c0e070407f1c6e1ee17b8c87c2c7bcc7d" "checksum xml-rs 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c1cb601d29fe2c2ac60a2b2e5e293994d87a1f6fa9687a31a15270f909be9c2" +"checksum xml-rs 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "541b12c998c5b56aa2b4e6f18f03664eef9a4fd0a246a55594efae6cc2d964b5" "checksum yaml-rust 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e66366e18dc58b46801afbf2ca7661a9f59cc8c5962c29892b6039b4f86fa992" "checksum yaml-rust 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "95acf0db5515d07da9965ec0e0ba6cc2d825e2caeb7303b66ca441729801254e" diff --git a/gfx/wr/servo-tidy.toml b/gfx/wr/servo-tidy.toml index 395bfe0ec1d2..8b2632910435 100644 --- a/gfx/wr/servo-tidy.toml +++ b/gfx/wr/servo-tidy.toml @@ -8,12 +8,15 @@ check-alphabetical-order = false packages = [ "crossbeam-epoch", "crossbeam-utils", + "gl_generator", + "khronos_api", "lazy_static", "log", "rand", "winapi", "core-graphics", "core-text", + "xml-rs", "yaml-rust", ] diff --git a/gfx/wr/webrender/Cargo.toml b/gfx/wr/webrender/Cargo.toml index bcf67b01de5b..4edbc04e8564 100644 --- a/gfx/wr/webrender/Cargo.toml +++ b/gfx/wr/webrender/Cargo.toml @@ -26,7 +26,7 @@ bitflags = "1.0" byteorder = "1.0" cfg-if = "0.1.2" fxhash = "0.2.1" -gleam = "0.6.3" +gleam = "0.6.8" image = { optional = true, version = "0.20" } lazy_static = "1" log = "0.4" diff --git a/gfx/wr/webrender/src/device/gl.rs b/gfx/wr/webrender/src/device/gl.rs index 43a6559c52ee..1e14d5e63522 100644 --- a/gfx/wr/webrender/src/device/gl.rs +++ b/gfx/wr/webrender/src/device/gl.rs @@ -857,6 +857,9 @@ pub struct Device { /// format, we fall back to glTexImage*. texture_storage_usage: TexStorageUsage, + /// Whether the function glCopyImageSubData is available. + supports_copy_image_sub_data: bool, + // GL extensions extensions: Vec, } @@ -1024,6 +1027,9 @@ impl Device { ) }; + let supports_copy_image_sub_data = supports_extension(&extensions, "GL_EXT_copy_image") || + supports_extension(&extensions, "GL_ARB_copy_image"); + // Explicitly set some global states to the values we expect. gl.disable(gl::FRAMEBUFFER_SRGB); gl.disable(gl::MULTISAMPLE); @@ -1066,6 +1072,7 @@ impl Device { frame_id: GpuFrameId(0), extensions, texture_storage_usage, + supports_copy_image_sub_data } } @@ -1621,15 +1628,27 @@ impl Device { debug_assert!(dst.size.height >= src.size.height); debug_assert!(dst.layer_count >= src.layer_count); - // Note that zip() truncates to the shorter of the two iterators. - let rect = DeviceIntRect::new(DeviceIntPoint::zero(), src.get_dimensions().to_i32()); - for (read_fbo, draw_fbo) in src.fbos.iter().zip(&dst.fbos) { - self.bind_read_target_impl(*read_fbo); - self.bind_draw_target_impl(*draw_fbo); - self.blit_render_target(rect, rect); + if self.supports_copy_image_sub_data { + assert_ne!(src.id, dst.id, + "glCopyImageSubData's behaviour is undefined if src and dst images are identical and the rectangles overlap."); + unsafe { + self.gl.copy_image_sub_data(src.id, src.target, 0, + 0, 0, 0, + dst.id, dst.target, 0, + 0, 0, 0, + src.size.width as _, src.size.height as _, src.layer_count); + } + } else { + // Note that zip() truncates to the shorter of the two iterators. + let rect = DeviceIntRect::new(DeviceIntPoint::zero(), src.get_dimensions().to_i32()); + for (read_fbo, draw_fbo) in src.fbos.iter().zip(&dst.fbos) { + self.bind_read_target_impl(*read_fbo); + self.bind_draw_target_impl(*draw_fbo); + self.blit_render_target(rect, rect); + } + self.reset_draw_target(); + self.reset_read_target(); } - self.reset_draw_target(); - self.reset_read_target(); } /// Notifies the device that the contents of a render target are no longer diff --git a/layout/tools/reftest/reftest-content.js b/layout/tools/reftest/reftest-content.js index 630a8c84f0d6..9495071f805b 100644 --- a/layout/tools/reftest/reftest-content.js +++ b/layout/tools/reftest/reftest-content.js @@ -693,9 +693,7 @@ function WaitForTestEnd(contentRootElement, inPrintMode, spellCheckedElements) { }; os.addObserver(flushWaiter, "apz-repaints-flushed"); - var willSnapshot = (gCurrentTestType != TYPE_SCRIPT) && - (gCurrentTestType != TYPE_LOAD) && - (gCurrentTestType != TYPE_PRINT); + var willSnapshot = IsSnapshottableTestType(); var noFlush = !(contentRootElement && contentRootElement.classList.contains("reftest-no-flush")); @@ -754,6 +752,17 @@ function WaitForTestEnd(contentRootElement, inPrintMode, spellCheckedElements) { } CheckLayerAssertions(contentRootElement); } + + if (!IsSnapshottableTestType()) { + // If we're not snapshotting the test, at least do a sync round-trip + // to the compositor to ensure that all the rendering messages + // related to this test get processed. Otherwise problems triggered + // by this test may only manifest as failures in a later test. + LogInfo("MakeProgress: Doing sync flush to compositor"); + gFailureReason = "timed out while waiting for sync compositor flush" + windowUtils().syncFlushCompositor(); + } + LogInfo("MakeProgress: Completed"); state = STATE_COMPLETED; gFailureReason = "timed out while taking snapshot (bug in harness?)"; @@ -1094,14 +1103,19 @@ function LogInfo(str) } } +function IsSnapshottableTestType() +{ + // Script, load-only, and PDF-print tests do not need any snapshotting. + return !(gCurrentTestType == TYPE_SCRIPT || + gCurrentTestType == TYPE_LOAD || + gCurrentTestType == TYPE_PRINT); +} + const SYNC_DEFAULT = 0x0; const SYNC_ALLOW_DISABLE = 0x1; function SynchronizeForSnapshot(flags) { - if (gCurrentTestType == TYPE_SCRIPT || - gCurrentTestType == TYPE_LOAD || - gCurrentTestType == TYPE_PRINT) { - // Script, load-only, and PDF-print tests do not need any snapshotting. + if (!IsSnapshottableTestType()) { return; } diff --git a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java index d6f627dc91a4..3f3c6a8a29fe 100644 --- a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java +++ b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java @@ -899,9 +899,9 @@ public abstract class GeckoApp extends GeckoActivity } @Override - public void onContextMenu(final GeckoSession session, final int screenX, - final int screenY, final String uri, - int elementType, final String elementSrc) { + public void onContextMenu(final GeckoSession session, + final int screenX, final int screenY, + final GeckoSession.ContentDelegate.ContextElement element) { } @Override diff --git a/mobile/android/base/java/org/mozilla/gecko/Tabs.java b/mobile/android/base/java/org/mozilla/gecko/Tabs.java index dd386f3b2956..59c4fd20d56f 100644 --- a/mobile/android/base/java/org/mozilla/gecko/Tabs.java +++ b/mobile/android/base/java/org/mozilla/gecko/Tabs.java @@ -343,8 +343,11 @@ public class Tabs implements BundleEventListener { } // Pass a message to Gecko to update tab state in BrowserApp. - final GeckoBundle data = new GeckoBundle(1); + final GeckoBundle data = new GeckoBundle(2); data.putInt("id", tab.getId()); + if (oldTab != null && mTabs.containsKey(oldTab.getId())) { + data.putInt("previousTabId", oldTab.getId()); + } mEventDispatcher.dispatch("Tab:Selected", data); EventDispatcher.getInstance().dispatch("Tab:Selected", data); return tab; diff --git a/mobile/android/base/java/org/mozilla/gecko/customtabs/CustomTabsActivity.java b/mobile/android/base/java/org/mozilla/gecko/customtabs/CustomTabsActivity.java index aea0c9c1d03c..74a1cd5b54bb 100644 --- a/mobile/android/base/java/org/mozilla/gecko/customtabs/CustomTabsActivity.java +++ b/mobile/android/base/java/org/mozilla/gecko/customtabs/CustomTabsActivity.java @@ -695,11 +695,12 @@ public class CustomTabsActivity extends AppCompatActivity } @Override - public void onContextMenu(GeckoSession session, int screenX, int screenY, - final String uri, int elementType, - final String elementSrc) { - - final String content = uri != null ? uri : elementSrc != null ? elementSrc : ""; + public void onContextMenu(final GeckoSession session, + int screenX, int screenY, + final ContextElement element) { + final String content = element.linkUri != null + ? element.linkUri + : element.srcUri != null ? element.srcUri : ""; final Uri validUri = WebApps.getValidURL(content); if (validUri == null) { return; diff --git a/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java b/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java index fbb70cc6fa67..dc40ce9d26da 100644 --- a/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java +++ b/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java @@ -352,9 +352,12 @@ public class WebAppActivity extends AppCompatActivity } @Override // GeckoSession.ContentDelegate - public void onContextMenu(GeckoSession session, int screenX, int screenY, - String uri, int elementType, String elementSrc) { - final String content = uri != null ? uri : elementSrc != null ? elementSrc : ""; + public void onContextMenu(final GeckoSession session, + int screenX, int screenY, + final ContextElement element) { + final String content = element.linkUri != null + ? element.linkUri + : element.srcUri != null ? element.srcUri : ""; final Uri validUri = WebApps.getValidURL(content); if (validUri == null) { return; diff --git a/mobile/android/chrome/geckoview/GeckoViewContentChild.js b/mobile/android/chrome/geckoview/GeckoViewContentChild.js index 7e4c4f320daa..a913083d2542 100644 --- a/mobile/android/chrome/geckoview/GeckoViewContentChild.js +++ b/mobile/android/chrome/geckoview/GeckoViewContentChild.js @@ -257,31 +257,37 @@ class GeckoViewContentChild extends GeckoViewChildModule { switch (aEvent.type) { case "contextmenu": - function nearestParentHref(node) { - while (node && !node.href) { - node = node.parentNode; + function nearestParentAttribute(aNode, aAttribute) { + while (aNode && aNode.hasAttribute && + !aNode.hasAttribute(aAttribute)) { + aNode = aNode.parentNode; } - return node && node.href; + return aNode && aNode.getAttribute && aNode.getAttribute(aAttribute); } const node = aEvent.composedTarget; - const hrefNode = nearestParentHref(node); + const uri = nearestParentAttribute(node, "href"); + const title = nearestParentAttribute(node, "title"); + const alt = nearestParentAttribute(node, "alt"); const elementType = ChromeUtils.getClassName(node); const isImage = elementType === "HTMLImageElement"; const isMedia = elementType === "HTMLVideoElement" || elementType === "HTMLAudioElement"; + const elementSrc = (isImage || isMedia) && (node.currentSrc || node.src); - if (hrefNode || isImage || isMedia) { - this.eventDispatcher.sendRequest({ + if (uri || isImage || isMedia) { + const msg = { type: "GeckoView:ContextMenu", screenX: aEvent.screenX, screenY: aEvent.screenY, - uri: hrefNode, + uri, + title, + alt, elementType, - elementSrc: (isImage || isMedia) - ? node.currentSrc || node.src - : null, - }); + elementSrc: elementSrc || null, + }; + + this.eventDispatcher.sendRequest(msg); aEvent.preventDefault(); } break; diff --git a/mobile/android/components/extensions/ext-tabs.js b/mobile/android/components/extensions/ext-tabs.js index 5529932a4fdd..47cdd85b95c6 100644 --- a/mobile/android/components/extensions/ext-tabs.js +++ b/mobile/android/components/extensions/ext-tabs.js @@ -96,7 +96,11 @@ this.tabs = class extends ExtensionAPI { onActivated: makeGlobalEvent(context, "tabs.onActivated", "Tab:Selected", (fire, data) => { let tab = tabManager.get(data.id); - fire.async({tabId: tab.id, windowId: tab.windowId}); + fire.async({ + tabId: tab.id, + previousTabId: data.previousTabId, + windowId: tab.windowId, + }); }), onCreated: new EventManager({ @@ -332,7 +336,7 @@ this.tabs = class extends ExtensionAPI { // Not sure what to do here? Which tab should we select? } } - // FIXME: highlighted/selected, muted, pinned, openerTabId + // FIXME: highlighted/selected, muted, pinned, openerTabId, successorTabId return tabManager.convert(nativeTab); }, diff --git a/mobile/android/components/extensions/ext-utils.js b/mobile/android/components/extensions/ext-utils.js index 2d615bac5101..9cd431ecfe8c 100644 --- a/mobile/android/components/extensions/ext-utils.js +++ b/mobile/android/components/extensions/ext-utils.js @@ -550,6 +550,10 @@ class Tab extends TabBase { return "complete"; } + get successorTabId() { + return -1; + } + get width() { return this.browser.clientWidth; } diff --git a/mobile/android/components/extensions/schemas/tabs.json b/mobile/android/components/extensions/schemas/tabs.json index cd5bcc6519e6..a237d7f98aae 100644 --- a/mobile/android/components/extensions/schemas/tabs.json +++ b/mobile/android/components/extensions/schemas/tabs.json @@ -101,7 +101,8 @@ "isArticle": {"type": "boolean", "optional": true, "description": "Whether the document in the tab can be rendered in reader mode."}, "isInReaderMode": {"type": "boolean", "optional": true, "description": "Whether the document in the tab is being rendered in reader mode."}, "sharingState": {"$ref": "SharingState", "optional": true, "description": "Current tab sharing state for screen, microphone and camera."}, - "attention": {"type": "boolean", "optional": true, "description": "Whether the tab is drawing attention."} + "attention": {"type": "boolean", "optional": true, "description": "Whether the tab is drawing attention."}, + "successorTabId": {"type": "integer", "optional": true, "minimum": -1, "description": "The ID of this tab's successor, if any; $(ref:tabs.TAB_ID_NONE) otherwise."} } }, { @@ -1209,6 +1210,12 @@ "minimum": 0, "description": "The ID of the tab that has become active." }, + "previousTabId": { + "type": "integer", + "minimum": 0, + "optional": true, + "description": "The ID of the tab that was previously active, if that tab is still open." + }, "windowId": { "type": "integer", "minimum": 0, diff --git a/mobile/android/components/extensions/test/mochitest/test_ext_tabs_events.html b/mobile/android/components/extensions/test/mochitest/test_ext_tabs_events.html index 63a5c1a329a2..f61ed3190af8 100644 --- a/mobile/android/components/extensions/test/mochitest/test_ext_tabs_events.html +++ b/mobile/android/components/extensions/test/mochitest/test_ext_tabs_events.html @@ -150,6 +150,86 @@ add_task(async function testTabRemovalEvent() { await extension.awaitFinish("tabs-events"); await extension.unload(); }); + +add_task(async function testTabActivationEvent() { + async function background() { + function makeExpectable() { + let expectation = null, resolver = null; + const expectable = param => { + if (expectation === null) { + browser.test.fail("unexpected call to expectable"); + } else { + try { + resolver(expectation(param)); + } catch (e) { + resolver(Promise.reject(e)); + } finally { + expectation = null; + } + } + }; + expectable.expect = e => { + expectation = e; + return new Promise(r => { resolver = r; }); + }; + return expectable; + } + try { + const listener = makeExpectable(); + browser.tabs.onActivated.addListener(listener); + + const [tab0] = await browser.tabs.query({active: true}); + const [, tab1] = await Promise.all([ + listener.expect(info => { + browser.test.assertEq(tab0.id, info.previousTabId, "Got expected previousTabId"); + }), + browser.tabs.create({url: "about:blank"}), + ]); + const [, tab2] = await Promise.all([ + listener.expect(info => { + browser.test.assertEq(tab1.id, info.previousTabId, "Got expected previousTabId"); + }), + browser.tabs.create({url: "about:blank"}), + ]); + + await Promise.all([ + listener.expect(info => { + browser.test.assertEq(tab1.id, info.tabId, "Got expected tabId"); + browser.test.assertEq(tab2.id, info.previousTabId, "Got expected previousTabId"); + }), + browser.tabs.update(tab1.id, {active: true}), + ]); + + await Promise.all([ + listener.expect(info => { + browser.test.assertEq(tab2.id, info.tabId, "Got expected tabId"); + browser.test.assertEq(undefined, info.previousTabId, "previousTabId should not be defined when previous tab was closed"); + }), + browser.tabs.remove(tab1.id), + ]); + + browser.tabs.onActivated.removeListener(listener); + await browser.tabs.remove(tab2.id); + + browser.test.notifyPass("tabs-events"); + } catch (e) { + browser.test.fail(`${e} :: ${e.stack}`); + browser.test.notifyFail("tabs-events"); + } + } + + let extension = ExtensionTestUtils.loadExtension({ + manifest: { + "permissions": ["tabs"], + }, + + background, + }); + + await extension.startup(); + await extension.awaitFinish("tabs-events"); + await extension.unload(); +}); diff --git a/mobile/android/geckoview/CHANGELOG.md b/mobile/android/geckoview/CHANGELOG.md index 19be60209eb1..73b921ce40ea 100644 --- a/mobile/android/geckoview/CHANGELOG.md +++ b/mobile/android/geckoview/CHANGELOG.md @@ -21,5 +21,8 @@ classifier. - Added a `protected` empty constructor to all field-only classes so that apps can mock these classes in tests. +- Added `ContentDelegate.ContextElement` to extend the information passed to + `ContentDelegate#onContextMenu`. Extended information includes the element's + title and alt attributes. -[api-version]: 723adca536354bfa81afb83da5045ea6de8aa602 +[api-version]: 8cfd04a09e7a242b3da22ccdd55c88a2aca2ba6d diff --git a/mobile/android/geckoview/api.txt b/mobile/android/geckoview/api.txt index e5904700a320..17b9800941a5 100644 --- a/mobile/android/geckoview/api.txt +++ b/mobile/android/geckoview/api.txt @@ -322,20 +322,22 @@ package org.mozilla.geckoview { public static interface GeckoSession.ContentDelegate { method public void onCloseRequest(org.mozilla.geckoview.GeckoSession); - method public void onContextMenu(org.mozilla.geckoview.GeckoSession, int, int, java.lang.String, int, java.lang.String); + method public void onContextMenu(org.mozilla.geckoview.GeckoSession, int, int, org.mozilla.geckoview.GeckoSession.ContentDelegate.ContextElement); method public void onCrash(org.mozilla.geckoview.GeckoSession); method public void onExternalResponse(org.mozilla.geckoview.GeckoSession, org.mozilla.geckoview.GeckoSession.WebResponseInfo); method public void onFirstComposite(org.mozilla.geckoview.GeckoSession); method public void onFocusRequest(org.mozilla.geckoview.GeckoSession); method public void onFullScreen(org.mozilla.geckoview.GeckoSession, boolean); method public void onTitleChange(org.mozilla.geckoview.GeckoSession, java.lang.String); - field public static final int ELEMENT_TYPE_AUDIO = 3; - field public static final int ELEMENT_TYPE_IMAGE = 1; - field public static final int ELEMENT_TYPE_NONE = 0; - field public static final int ELEMENT_TYPE_VIDEO = 2; } - public static interface GeckoSession.ContentDelegate.ElementType implements java.lang.annotation.Annotation { + public static final class GeckoSession.ContentDelegate.ContextElement { + ctor protected ContextElement(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String); + field public final java.lang.String altText; + field public final java.lang.String linkUri; + field public final java.lang.String srcUri; + field public final java.lang.String title; + field public final int type; } public static final class GeckoSession.FinderResult { diff --git a/mobile/android/geckoview/src/androidTest/assets/www/badVideoPath.html b/mobile/android/geckoview/src/androidTest/assets/www/badVideoPath.html new file mode 100644 index 000000000000..d8f21a1263c2 --- /dev/null +++ b/mobile/android/geckoview/src/androidTest/assets/www/badVideoPath.html @@ -0,0 +1,8 @@ + + Bad Video Path + + + + diff --git a/mobile/android/geckoview/src/androidTest/assets/www/mp4.html b/mobile/android/geckoview/src/androidTest/assets/www/mp4.html new file mode 100644 index 000000000000..d775f6728962 --- /dev/null +++ b/mobile/android/geckoview/src/androidTest/assets/www/mp4.html @@ -0,0 +1,8 @@ + + MP4 Video + + + + diff --git a/mobile/android/geckoview/src/androidTest/assets/www/ogg.html b/mobile/android/geckoview/src/androidTest/assets/www/ogg.html new file mode 100644 index 000000000000..cb840639c65c --- /dev/null +++ b/mobile/android/geckoview/src/androidTest/assets/www/ogg.html @@ -0,0 +1,8 @@ + + OGG Video + + + + diff --git a/mobile/android/geckoview/src/androidTest/assets/www/videos/gizmo.webm b/mobile/android/geckoview/src/androidTest/assets/www/videos/gizmo.webm new file mode 100644 index 000000000000..518531a93f5c Binary files /dev/null and b/mobile/android/geckoview/src/androidTest/assets/www/videos/gizmo.webm differ diff --git a/mobile/android/geckoview/src/androidTest/assets/www/videos/short.mp4 b/mobile/android/geckoview/src/androidTest/assets/www/videos/short.mp4 new file mode 100644 index 000000000000..a674b7eb6808 Binary files /dev/null and b/mobile/android/geckoview/src/androidTest/assets/www/videos/short.mp4 differ diff --git a/mobile/android/geckoview/src/androidTest/assets/www/videos/video.ogg b/mobile/android/geckoview/src/androidTest/assets/www/videos/video.ogg new file mode 100644 index 000000000000..ac7ece3519ac Binary files /dev/null and b/mobile/android/geckoview/src/androidTest/assets/www/videos/video.ogg differ diff --git a/mobile/android/geckoview/src/androidTest/assets/www/webm.html b/mobile/android/geckoview/src/androidTest/assets/www/webm.html new file mode 100644 index 000000000000..d57aba250169 --- /dev/null +++ b/mobile/android/geckoview/src/androidTest/assets/www/webm.html @@ -0,0 +1,8 @@ + + WebM Video + + + + diff --git a/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/BaseSessionTest.kt b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/BaseSessionTest.kt index 4e30c1cec123..3f3a9a84b7cb 100644 --- a/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/BaseSessionTest.kt +++ b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/BaseSessionTest.kt @@ -41,6 +41,10 @@ open class BaseSessionTest(noErrorCollector: Boolean = false) { const val SAVE_STATE_PATH = "/assets/www/saveState.html" const val TITLE_CHANGE_HTML_PATH = "/assets/www/titleChange.html" const val TRACKERS_PATH = "/assets/www/trackers.html" + const val VIDEO_OGG_PATH = "/assets/www/ogg.html" + const val VIDEO_MP4_PATH = "/assets/www/mp4.html" + const val VIDEO_WEBM_PATH = "/assets/www/webm.html" + const val VIDEO_BAD_PATH = "/assets/www/badVideoPath.html" const val UNKNOWN_HOST_URI = "http://www.test.invalid/" const val FULLSCREEN_PATH = "/assets/www/fullscreen.html" } diff --git a/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/MediaElementTest.kt b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/MediaElementTest.kt new file mode 100644 index 000000000000..7a2ce72afaa1 --- /dev/null +++ b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/MediaElementTest.kt @@ -0,0 +1,413 @@ +/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- + * Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +package org.mozilla.geckoview.test + +import org.mozilla.geckoview.GeckoSession +import org.mozilla.geckoview.MediaElement +import org.mozilla.geckoview.test.rule.GeckoSessionTestRule.AssertCalled +import org.mozilla.geckoview.test.rule.GeckoSessionTestRule.TimeoutMillis +import org.mozilla.geckoview.test.rule.GeckoSessionTestRule.WithDevToolsAPI +import org.mozilla.geckoview.test.util.Callbacks + +import android.support.test.filters.MediumTest +import android.support.test.runner.AndroidJUnit4 +import org.hamcrest.Matchers.* +import org.junit.Assume.assumeThat +import org.junit.Ignore +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +@TimeoutMillis(45000) +@MediumTest +class MediaElementTest : BaseSessionTest() { + + interface MediaElementDelegate : MediaElement.Delegate { + override fun onPlaybackStateChange(mediaElement: MediaElement, mediaState: Int) {} + override fun onReadyStateChange(mediaElement: MediaElement, readyState: Int) {} + override fun onMetadataChange(mediaElement: MediaElement, metaData: MediaElement.Metadata) {} + override fun onLoadProgress(mediaElement: MediaElement, progressInfo: MediaElement.LoadProgressInfo) {} + override fun onVolumeChange(mediaElement: MediaElement, volume: Double, muted: Boolean) {} + override fun onTimeChange(mediaElement: MediaElement, time: Double) {} + override fun onPlaybackRateChange(mediaElement: MediaElement, rate: Double) {} + override fun onFullscreenChange(mediaElement: MediaElement, fullscreen: Boolean) {} + override fun onError(mediaElement: MediaElement, errorCode: Int) {} + } + + private fun setupPrefsAndDelegates(path: String) { + sessionRule.setPrefsUntilTestEnd(mapOf( + "media.autoplay.enabled.user-gestures-needed" to false, + "media.autoplay.default" to 0, + "media.autoplay.ask-permission" to false, + "full-screen-api.allow-trusted-requests-only" to false)) + + sessionRule.session.loadTestPath(path) + sessionRule.waitUntilCalled(object : Callbacks.MediaDelegate { + @AssertCalled + override fun onMediaAdd(session: GeckoSession, element: MediaElement) { + sessionRule.addExternalDelegateUntilTestEnd( + MediaElementDelegate::class, + element::setDelegate, + { element.delegate = null }, + object : MediaElementDelegate {}) + } + }) + } + + private fun waitUntilVideoReady(path: String, waitState: Int = MediaElement.MEDIA_READY_STATE_HAVE_ENOUGH_DATA): MediaElement { + setupPrefsAndDelegates(path) + var ready = false + var result: MediaElement? = null + while (!ready) { + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onReadyStateChange(mediaElement: MediaElement, readyState: Int) { + if (readyState == waitState) { + ready = true + result = mediaElement + } + } + }) + } + if (result == null) { + throw IllegalStateException("No MediaElement Found") + } + return result!! + } + + private fun waitForPlaybackStateChange(waitState: Int, lambda: (element: MediaElement, state: Int) -> Unit = { _: MediaElement, _: Int -> }) { + var waiting = true + while (waiting) { + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onPlaybackStateChange(mediaElement: MediaElement, mediaState: Int) { + if (mediaState == waitState) { + waiting = false + lambda(mediaElement, mediaState) + } + } + }) + } + } + + private fun waitForMetadata(path: String): MediaElement.Metadata? { + setupPrefsAndDelegates(path) + var meta: MediaElement.Metadata? = null + while (meta == null) { + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onMetadataChange(mediaElement: MediaElement, metaData: MediaElement.Metadata) { + meta = metaData + } + }) + } + return meta + } + + private fun playMedia(path: String) { + val mediaElement = waitUntilVideoReady(path) + mediaElement.play() + waitForPlaybackStateChange(MediaElement.MEDIA_STATE_PLAY) + waitForPlaybackStateChange(MediaElement.MEDIA_STATE_PLAYING) + } + + private fun playMediaFromScript(path: String) { + waitUntilVideoReady(path) + sessionRule.evaluateJS(mainSession, "$('video').play()") + waitForPlaybackStateChange(MediaElement.MEDIA_STATE_PLAY) + waitForPlaybackStateChange(MediaElement.MEDIA_STATE_PLAYING) + } + + private fun pauseMedia(path: String) { + val mediaElement = waitUntilVideoReady(path) + mediaElement.play() + waitForPlaybackStateChange(MediaElement.MEDIA_STATE_PLAYING) { element: MediaElement, _: Int -> + element.pause() + } + waitForPlaybackStateChange(MediaElement.MEDIA_STATE_PAUSE) + } + + private fun timeMedia(path: String, limit: Double) { + val mediaElement = waitUntilVideoReady(path) + mediaElement.play() + var waiting = true + while (waiting) { + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onTimeChange(mediaElement: MediaElement, time: Double) { + if (time > limit) { + waiting = false + } + } + }) + } + } + + private fun seekMedia(path: String, seek: Double) { + val media = waitUntilVideoReady(path) + media.seek(seek) + var waiting = true + // Sometimes we get a MediaElement.MEDIA_STATE_SUSPEND state change. So just wait until + // the test receives the SEEKING state change or time out. + while (waiting) { + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onPlaybackStateChange(mediaElement: MediaElement, mediaState: Int) { + if (mediaState == MediaElement.MEDIA_STATE_SEEKING) { + waiting = false + } + } + }) + } + waiting = true + while (waiting) { + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onTimeChange(mediaElement: MediaElement, time: Double) { + if (time >= seek) { + waiting = false + } + } + }) + } + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onPlaybackStateChange(mediaElement: MediaElement, mediaState: Int) { + assertThat("Done seeking", mediaState, equalTo(MediaElement.MEDIA_STATE_SEEKED)) + } + }) + } + + private fun fullscreenMedia(path: String) { + waitUntilVideoReady(path) + sessionRule.evaluateJS(mainSession, "$('video').requestFullscreen()") + var waiting = true + while (waiting) { + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onFullscreenChange(mediaElement: MediaElement, fullscreen: Boolean) { + if (fullscreen) { + waiting = false + } + } + }) + } + } + + @WithDevToolsAPI + @Test + fun oggPlayMedia() { + playMedia(VIDEO_OGG_PATH) + } + + @WithDevToolsAPI + @Test + fun oggPlayMediaFromScript() { + playMediaFromScript(VIDEO_OGG_PATH) + } + + @WithDevToolsAPI + @Test + fun oggPauseMedia() { + pauseMedia(VIDEO_OGG_PATH) + } + + @WithDevToolsAPI + @Test + fun oggTimeMedia() { + timeMedia(VIDEO_OGG_PATH, 2.0) + } + + @WithDevToolsAPI + @Test + fun oggMetadataMedia() { + val meta = waitForMetadata(VIDEO_OGG_PATH) + assertThat("Current source is set", meta?.currentSource, equalTo("resource://android/assets/www/videos/video.ogg")) + assertThat("Width is set", meta?.width, equalTo(320L)) + assertThat("Height is set", meta?.height, equalTo(240L)) + assertThat("Video is seekable", meta?.isSeekable, equalTo(true)) + // Disabled duration test for Bug 1510393 + // assertThat("Duration is set", meta?.duration, closeTo(4.0, 0.1)) + assertThat("Contains one video track", meta?.videoTrackCount, equalTo(1)) + assertThat("Contains one audio track", meta?.audioTrackCount, equalTo(0)) + } + + @WithDevToolsAPI + @Test + fun oggSeekMedia() { + seekMedia(VIDEO_OGG_PATH, 2.0) + } + + @WithDevToolsAPI + @Test + fun oggFullscreenMedia() { + fullscreenMedia(VIDEO_OGG_PATH) + } + + @WithDevToolsAPI + @Test + fun webmPlayMedia() { + playMedia(VIDEO_WEBM_PATH) + } + + @WithDevToolsAPI + @Test + fun webmPlayMediaFromScript() { + playMediaFromScript(VIDEO_WEBM_PATH) + } + + @WithDevToolsAPI + @Test + fun webmPauseMedia() { + pauseMedia(VIDEO_WEBM_PATH) + } + + @WithDevToolsAPI + @Test + fun webmTimeMedia() { + timeMedia(VIDEO_WEBM_PATH, 0.2) + } + + @WithDevToolsAPI + @Test + fun webmMetadataMedia() { + val meta = waitForMetadata(VIDEO_WEBM_PATH) + assertThat("Current source is set", meta?.currentSource, equalTo("resource://android/assets/www/videos/gizmo.webm")) + assertThat("Width is set", meta?.width, equalTo(560L)) + assertThat("Height is set", meta?.height, equalTo(320L)) + assertThat("Video is seekable", meta?.isSeekable, equalTo(true)) + assertThat("Duration is set", meta?.duration, closeTo(5.6, 0.1)) + assertThat("Contains one video track", meta?.videoTrackCount, equalTo(1)) + assertThat("Contains one audio track", meta?.audioTrackCount, equalTo(1)) + } + + @WithDevToolsAPI + @Test + fun webmSeekMedia() { + seekMedia(VIDEO_WEBM_PATH, 0.2) + } + + @WithDevToolsAPI + @Test + fun webmFullscreenMedia() { + fullscreenMedia(VIDEO_WEBM_PATH) + } + + private fun waitForVolumeChange(volumeLevel: Double, isMuted: Boolean) { + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onVolumeChange(mediaElement: MediaElement, volume: Double, muted: Boolean) { + assertThat("Volume was set", volume, closeTo(volumeLevel, 0.0001)) + assertThat("Not muted", muted, equalTo(isMuted)) + } + }) + } + + @WithDevToolsAPI + @Test + fun webmVolumeMedia() { + val media = waitUntilVideoReady(VIDEO_WEBM_PATH) + val volumeLevel = 0.5 + val volumeLevel2 = 0.75 + media.setVolume(volumeLevel) + waitForVolumeChange(volumeLevel, false) + media.setMuted(true) + waitForVolumeChange(volumeLevel, true) + media.setVolume(volumeLevel2) + waitForVolumeChange(volumeLevel2, true) + media.setMuted(false) + waitForVolumeChange(volumeLevel2, false) + } + + // NOTE: All MP4 tests are disabled on automation by Bug 1503952 + @WithDevToolsAPI + @Test + fun mp4PlayMedia() { + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + playMedia(VIDEO_MP4_PATH) + } + + @WithDevToolsAPI + @Test + fun mp4PlayMediaFromScript() { + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + playMediaFromScript(VIDEO_MP4_PATH) + } + + @WithDevToolsAPI + @Test + fun mp4PauseMedia() { + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + pauseMedia(VIDEO_MP4_PATH) + } + + @WithDevToolsAPI + @Test + fun mp4TimeMedia() { + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + timeMedia(VIDEO_MP4_PATH, 0.2) + } + + @WithDevToolsAPI + @Test + fun mp4MetadataMedia() { + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + val meta = waitForMetadata(VIDEO_MP4_PATH) + assertThat("Current source is set", meta?.currentSource, equalTo("resource://android/assets/www/videos/short.mp4")) + assertThat("Width is set", meta?.width, equalTo(320L)) + assertThat("Height is set", meta?.height, equalTo(240L)) + assertThat("Video is seekable", meta?.isSeekable, equalTo(true)) + assertThat("Duration is set", meta?.duration, closeTo(0.5, 0.1)) + assertThat("Contains one video track", meta?.videoTrackCount, equalTo(1)) + assertThat("Contains one audio track", meta?.audioTrackCount, equalTo(1)) + } + + @WithDevToolsAPI + @Test + fun mp4SeekMedia() { + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + seekMedia(VIDEO_MP4_PATH, 0.2) + } + + @WithDevToolsAPI + @Test + fun mp4FullscreenMedia() { + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + fullscreenMedia(VIDEO_MP4_PATH) + } + + @WithDevToolsAPI + @Test + fun mp4VolumeMedia() { + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + val media = waitUntilVideoReady(VIDEO_MP4_PATH) + val volumeLevel = 0.5 + val volumeLevel2 = 0.75 + media.setVolume(volumeLevel) + waitForVolumeChange(volumeLevel, false) + media.setMuted(true) + waitForVolumeChange(volumeLevel, true) + media.setVolume(volumeLevel2) + waitForVolumeChange(volumeLevel2, true) + media.setMuted(false) + waitForVolumeChange(volumeLevel2, false) + } + + @Ignore + @WithDevToolsAPI + @Test + fun badMediaPath() { + // Disabled on automation by Bug 1503957 + assumeThat(sessionRule.env.isAutomation, equalTo(false)) + setupPrefsAndDelegates(VIDEO_BAD_PATH) + sessionRule.waitForPageStop() + sessionRule.waitUntilCalled(object : MediaElementDelegate { + @AssertCalled + override fun onError(mediaElement: MediaElement, errorCode: Int) { + assertThat("Got media error", errorCode, equalTo(MediaElement.MEDIA_ERROR_NETWORK_NO_SOURCE)) + } + }) + } +} diff --git a/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/TestRunnerActivity.java b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/TestRunnerActivity.java index 5e1742af5fc1..dd0fd0ff1722 100644 --- a/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/TestRunnerActivity.java +++ b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/TestRunnerActivity.java @@ -94,7 +94,8 @@ public class TestRunnerActivity extends Activity { } @Override - public void onContextMenu(GeckoSession session, int screenX, int screenY, String uri, int elementType, String elementSrc) { + public void onContextMenu(GeckoSession session, int screenX, int screenY, + ContextElement element) { } diff --git a/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/util/Callbacks.kt b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/util/Callbacks.kt index 0d0408684a45..be71c94127de 100644 --- a/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/util/Callbacks.kt +++ b/mobile/android/geckoview/src/androidTest/java/org/mozilla/geckoview/test/util/Callbacks.kt @@ -9,6 +9,7 @@ import org.mozilla.geckoview.AllowOrDeny import org.mozilla.geckoview.GeckoResponse import org.mozilla.geckoview.GeckoResult import org.mozilla.geckoview.GeckoSession +import org.mozilla.geckoview.GeckoSession.ContentDelegate.ContextElement import org.mozilla.geckoview.GeckoSession.NavigationDelegate.LoadRequest import org.mozilla.geckoview.MediaElement import org.mozilla.geckoview.WebRequestError @@ -38,7 +39,9 @@ class Callbacks private constructor() { override fun onFullScreen(session: GeckoSession, fullScreen: Boolean) { } - override fun onContextMenu(session: GeckoSession, screenX: Int, screenY: Int, uri: String, elementType: Int, elementSrc: String) { + override fun onContextMenu(session: GeckoSession, + screenX: Int, screenY: Int, + element: ContextElement) { } override fun onExternalResponse(session: GeckoSession, response: GeckoSession.WebResponseInfo) { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/GeckoSession.java b/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/GeckoSession.java index 994c47a9f250..c5034d4b94a2 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/GeckoSession.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/geckoview/GeckoSession.java @@ -364,15 +364,19 @@ public class GeckoSession implements Parcelable { close(); delegate.onCrash(GeckoSession.this); } else if ("GeckoView:ContextMenu".equals(event)) { - final int type = getContentElementType( - message.getString("elementType")); + final ContentDelegate.ContextElement elem = + new ContentDelegate.ContextElement( + message.getString("uri"), + message.getString("title"), + message.getString("alt"), + message.getString("elementType"), + message.getString("elementSrc")); delegate.onContextMenu(GeckoSession.this, message.getInt("screenX"), message.getInt("screenY"), - message.getString("uri"), - type, - message.getString("elementSrc")); + elem); + } else if ("GeckoView:DOMTitleChanged".equals(event)) { delegate.onTitleChange(GeckoSession.this, message.getString("title")); @@ -2498,17 +2502,6 @@ public class GeckoSession implements Parcelable { void onSecurityChange(GeckoSession session, SecurityInformation securityInfo); } - private static int getContentElementType(final String name) { - if ("HTMLImageElement".equals(name)) { - return ContentDelegate.ELEMENT_TYPE_IMAGE; - } else if ("HTMLVideoElement".equals(name)) { - return ContentDelegate.ELEMENT_TYPE_VIDEO; - } else if ("HTMLAudioElement".equals(name)) { - return ContentDelegate.ELEMENT_TYPE_AUDIO; - } - return ContentDelegate.ELEMENT_TYPE_NONE; - } - /** * WebResponseInfo contains information about a single web response. */ @@ -2557,14 +2550,6 @@ public class GeckoSession implements Parcelable { } public interface ContentDelegate { - @IntDef({ELEMENT_TYPE_NONE, ELEMENT_TYPE_IMAGE, ELEMENT_TYPE_VIDEO, - ELEMENT_TYPE_AUDIO}) - /* package */ @interface ElementType {} - static final int ELEMENT_TYPE_NONE = 0; - static final int ELEMENT_TYPE_IMAGE = 1; - static final int ELEMENT_TYPE_VIDEO = 2; - static final int ELEMENT_TYPE_AUDIO = 3; - /** * A page title was discovered in the content or updated after the content * loaded. @@ -2596,6 +2581,69 @@ public class GeckoSession implements Parcelable { */ void onFullScreen(GeckoSession session, boolean fullScreen); + /** + * Element details for onContextMenu callbacks. + */ + public static final class ContextElement { + @IntDef({TYPE_NONE, TYPE_IMAGE, TYPE_VIDEO, TYPE_AUDIO}) + /* package */ @interface Type {} + static final int TYPE_NONE = 0; + static final int TYPE_IMAGE = 1; + static final int TYPE_VIDEO = 2; + static final int TYPE_AUDIO = 3; + + + /** + * The link URI (href) of the element. + */ + public final @Nullable String linkUri; + + /** + * The title text of the element. + */ + public final @Nullable String title; + + /** + * The alternative text (alt) for the element. + */ + public final @Nullable String altText; + + /** + * The type of the element. + * One of the {@link ContextElement#TYPE_NONE} flags. + */ + public final @Type int type; + + /** + * The source URI (src) of the element. + * Set for (nested) media elements. + */ + public final @Nullable String srcUri; + + protected ContextElement( + final @Nullable String linkUri, + final @Nullable String title, + final @Nullable String altText, + final @NonNull String typeStr, + final @Nullable String srcUri) { + this.linkUri = linkUri; + this.title = title; + this.altText = altText; + this.type = getType(typeStr); + this.srcUri = srcUri; + } + + private static int getType(final String name) { + if ("HTMLImageElement".equals(name)) { + return TYPE_IMAGE; + } else if ("HTMLVideoElement".equals(name)) { + return TYPE_VIDEO; + } else if ("HTMLAudioElement".equals(name)) { + return TYPE_AUDIO; + } + return TYPE_NONE; + } + } /** * A user has initiated the context menu via long-press. @@ -2605,16 +2653,11 @@ public class GeckoSession implements Parcelable { * @param session The GeckoSession that initiated the callback. * @param screenX The screen coordinates of the press. * @param screenY The screen coordinates of the press. - * @param uri The URI of the pressed link, set for links and - * image-links. - * @param elementType The type of the pressed element. - * One of the {@link ContentDelegate#ELEMENT_TYPE_NONE} flags. - * @param elementSrc The source URI of the pressed element, set for - * (nested) images and media elements. + * @param element The details for the pressed element. */ - void onContextMenu(GeckoSession session, int screenX, int screenY, - String uri, @ElementType int elementType, - String elementSrc); + void onContextMenu(@NonNull GeckoSession session, + int screenX, int screenY, + @NonNull ContextElement element); /** * This is fired when there is a response that cannot be handled diff --git a/mobile/android/geckoview_example/src/main/java/org/mozilla/geckoview_example/GeckoViewActivity.java b/mobile/android/geckoview_example/src/main/java/org/mozilla/geckoview_example/GeckoViewActivity.java index 570bc574cc57..273e49d4b015 100644 --- a/mobile/android/geckoview_example/src/main/java/org/mozilla/geckoview_example/GeckoViewActivity.java +++ b/mobile/android/geckoview_example/src/main/java/org/mozilla/geckoview_example/GeckoViewActivity.java @@ -476,12 +476,16 @@ public class GeckoViewActivity extends AppCompatActivity { } @Override - public void onContextMenu(GeckoSession session, int screenX, int screenY, - String uri, int elementType, String elementSrc) { + public void onContextMenu(final GeckoSession session, + int screenX, int screenY, + final ContextElement element) { Log.d(LOGTAG, "onContextMenu screenX=" + screenX + - " screenY=" + screenY + " uri=" + uri + - " elementType=" + elementType + - " elementSrc=" + elementSrc); + " screenY=" + screenY + + " type=" + element.type + + " linkUri=" + element.linkUri + + " title=" + element.title + + " alt=" + element.altText + + " srcUri=" + element.srcUri); } @Override diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js index 391d990a1aa5..68bd1e98c4e2 100644 --- a/modules/libpref/init/all.js +++ b/modules/libpref/init/all.js @@ -1440,11 +1440,7 @@ pref("dom.event.clipboardevents.enabled", true); pref("dom.event.highrestimestamp.enabled", true); pref("dom.event.coalesce_mouse_move", true); -#if defined(NIGHTLY_BUILD) pref("dom.ua_widget.enabled", true); -#else -pref("dom.ua_widget.enabled", false); -#endif pref("javascript.enabled", true); pref("javascript.options.strict", false); @@ -1953,8 +1949,6 @@ pref("network.sts.max_time_for_pr_close_during_shutdown", 5000); pref("network.sts.pollable_event_timeout", 6); // Enable/disable sni encryption. -// Currently this does not work even if the pref is true, the nss part is -// missing. pref("network.security.esni.enabled", false); // 2147483647 == PR_INT32_MAX == ~2 GB diff --git a/netwerk/protocol/ftp/nsFtpConnectionThread.cpp b/netwerk/protocol/ftp/nsFtpConnectionThread.cpp index 9b013cdc3dbf..e496bcd3e035 100644 --- a/netwerk/protocol/ftp/nsFtpConnectionThread.cpp +++ b/netwerk/protocol/ftp/nsFtpConnectionThread.cpp @@ -1474,7 +1474,10 @@ nsFtpState::R_pasv() { if (newDataConn) { mDataTransport->Close(NS_ERROR_ABORT); mDataTransport = nullptr; - mDataStream = nullptr; + if (mDataStream) { + mDataStream->CloseWithStatus(NS_ERROR_ABORT); + mDataStream = nullptr; + } } } @@ -2126,7 +2129,10 @@ nsFtpState::CloseWithStatus(nsresult status) mDataTransport = nullptr; } - mDataStream = nullptr; + if (mDataStream) { + mDataStream->CloseWithStatus(NS_ERROR_ABORT); + mDataStream = nullptr; + } return nsBaseContentStream::CloseWithStatus(status); } diff --git a/python/mozboot/mozboot/archlinux.py b/python/mozboot/mozboot/archlinux.py index 3c0a0254413c..2dfd6cf7f4e5 100644 --- a/python/mozboot/mozboot/archlinux.py +++ b/python/mozboot/mozboot/archlinux.py @@ -11,10 +11,11 @@ import subprocess import glob from mozboot.base import BaseBootstrapper -from mozboot.linux_common import NodeInstall, StyloInstall +from mozboot.linux_common import NodeInstall, StyloInstall, ClangStaticAnalysisInstall -class ArchlinuxBootstrapper(NodeInstall, StyloInstall, BaseBootstrapper): +class ArchlinuxBootstrapper(NodeInstall, StyloInstall, + ClangStaticAnalysisInstall, BaseBootstrapper): '''Archlinux experimental bootstrapper.''' SYSTEM_PACKAGES = [ diff --git a/python/mozboot/mozboot/base.py b/python/mozboot/mozboot/base.py index 9a6597f183c5..2a3ff60a2370 100644 --- a/python/mozboot/mozboot/base.py +++ b/python/mozboot/mozboot/base.py @@ -253,6 +253,14 @@ class BaseBootstrapper(object): '%s does not yet implement suggest_mobile_android_artifact_mode_mozconfig()' % __name__) + def ensure_clang_static_analysis_package(self, checkout_root): + ''' + Install the clang static analysis package + ''' + raise NotImplementedError( + '%s does not yet implement ensure_clang_static_analysis_package()' + % __name__) + def ensure_stylo_packages(self, state_dir, checkout_root): ''' Install any necessary packages needed for Stylo development. @@ -268,6 +276,24 @@ class BaseBootstrapper(object): '%s does not yet implement ensure_node_packages()' % __name__) + def install_toolchain_static_analysis(self, checkout_root): + mach_binary = os.path.join(checkout_root, 'mach') + mach_binary = os.path.abspath(mach_binary) + if not os.path.exists(mach_binary): + raise ValueError("mach not found at %s" % mach_binary) + + if not sys.executable: + raise ValueError("cannot determine path to Python executable") + + cmd = [sys.executable, mach_binary, 'static-analysis', 'install', + '--force', '--minimal-install'] + + from subprocess import CalledProcessError + try: + subprocess.check_call(cmd) + except CalledProcessError as e: + print(e.output) + def install_toolchain_artifact(self, state_dir, checkout_root, toolchain_job): mach_binary = os.path.join(checkout_root, 'mach') mach_binary = os.path.abspath(mach_binary) diff --git a/python/mozboot/mozboot/bootstrap.py b/python/mozboot/mozboot/bootstrap.py index 1c3b7637f75d..391db3bb9fc5 100644 --- a/python/mozboot/mozboot/bootstrap.py +++ b/python/mozboot/mozboot/bootstrap.py @@ -368,7 +368,7 @@ class Bootstrapper(object): checkout_root): # Install the clang packages needed for building the style system, as # well as the version of NodeJS that we currently support. - + # Also install the clang static-analysis package by default # The best place to install our packages is in the state directory # we have. We should have created one above in non-interactive mode. if not state_dir_available: @@ -380,6 +380,7 @@ class Bootstrapper(object): sys.exit(1) self.instance.state_dir = state_dir + self.instance.ensure_clang_static_analysis_package(checkout_root) self.instance.ensure_stylo_packages(state_dir, checkout_root) self.instance.ensure_node_packages(state_dir, checkout_root) diff --git a/python/mozboot/mozboot/centosfedora.py b/python/mozboot/mozboot/centosfedora.py index 9b2cba52629c..2c3f21b0e43a 100644 --- a/python/mozboot/mozboot/centosfedora.py +++ b/python/mozboot/mozboot/centosfedora.py @@ -7,10 +7,11 @@ from __future__ import absolute_import import platform from mozboot.base import BaseBootstrapper -from mozboot.linux_common import NodeInstall, StyloInstall +from mozboot.linux_common import NodeInstall, StyloInstall, ClangStaticAnalysisInstall -class CentOSFedoraBootstrapper(NodeInstall, StyloInstall, BaseBootstrapper): +class CentOSFedoraBootstrapper(NodeInstall, StyloInstall, + ClangStaticAnalysisInstall, BaseBootstrapper): def __init__(self, distro, version, dist_id, **kwargs): BaseBootstrapper.__init__(self, **kwargs) diff --git a/python/mozboot/mozboot/debian.py b/python/mozboot/mozboot/debian.py index 5052bef7e941..562b9aec40c6 100644 --- a/python/mozboot/mozboot/debian.py +++ b/python/mozboot/mozboot/debian.py @@ -5,7 +5,7 @@ from __future__ import absolute_import, print_function from mozboot.base import BaseBootstrapper -from mozboot.linux_common import NodeInstall, StyloInstall +from mozboot.linux_common import NodeInstall, StyloInstall, ClangStaticAnalysisInstall MERCURIAL_INSTALL_PROMPT = ''' @@ -28,7 +28,8 @@ Choice: '''.strip() -class DebianBootstrapper(NodeInstall, StyloInstall, BaseBootstrapper): +class DebianBootstrapper(NodeInstall, StyloInstall, ClangStaticAnalysisInstall, + BaseBootstrapper): # These are common packages for all Debian-derived distros (such as # Ubuntu). COMMON_PACKAGES = [ diff --git a/python/mozboot/mozboot/freebsd.py b/python/mozboot/mozboot/freebsd.py index 26dd904055e2..7fcca8d31007 100644 --- a/python/mozboot/mozboot/freebsd.py +++ b/python/mozboot/mozboot/freebsd.py @@ -66,6 +66,10 @@ class FreeBSDBootstrapper(BaseBootstrapper): # TODO: Figure out what not to install for artifact mode self.pkg_install(*self.browser_packages) + def ensure_clang_static_analysis_package(self, checkout_root): + # TODO: we don't ship clang base static analysis for this platform + pass + def ensure_stylo_packages(self, state_dir, checkout_root): # Clang / llvm already installed as browser package self.pkg_install('rust-cbindgen') diff --git a/python/mozboot/mozboot/gentoo.py b/python/mozboot/mozboot/gentoo.py index 93f6f33ffe52..19dd72039648 100644 --- a/python/mozboot/mozboot/gentoo.py +++ b/python/mozboot/mozboot/gentoo.py @@ -5,7 +5,7 @@ from __future__ import absolute_import from mozboot.base import BaseBootstrapper -from mozboot.linux_common import NodeInstall, StyloInstall +from mozboot.linux_common import NodeInstall, StyloInstall, ClangStaticAnalysisInstall try: from urllib2 import urlopen @@ -16,7 +16,8 @@ import re import subprocess -class GentooBootstrapper(NodeInstall, StyloInstall, BaseBootstrapper): +class GentooBootstrapper(NodeInstall, StyloInstall, ClangStaticAnalysisInstall, + BaseBootstrapper): def __init__(self, version, dist_id, **kwargs): BaseBootstrapper.__init__(self, **kwargs) diff --git a/python/mozboot/mozboot/linux_common.py b/python/mozboot/mozboot/linux_common.py index 6d955cf09bb3..248bb33f4c1e 100644 --- a/python/mozboot/mozboot/linux_common.py +++ b/python/mozboot/mozboot/linux_common.py @@ -26,3 +26,11 @@ class NodeInstall(object): def ensure_node_packages(self, state_dir, checkout_root): from mozboot import node self.install_toolchain_artifact(state_dir, checkout_root, node.LINUX) + + +class ClangStaticAnalysisInstall(object): + def __init__(self, **kwargs): + pass + + def ensure_clang_static_analysis_package(self, checkout_root): + self.install_toolchain_static_analysis(checkout_root) diff --git a/python/mozboot/mozboot/mozillabuild.py b/python/mozboot/mozboot/mozillabuild.py index 95c8d215b4e8..825fe24ba0d5 100644 --- a/python/mozboot/mozboot/mozillabuild.py +++ b/python/mozboot/mozboot/mozillabuild.py @@ -45,6 +45,9 @@ class MozillaBuildBootstrapper(BaseBootstrapper): def install_mobile_android_artifact_mode_packages(self): pass + def ensure_clang_static_analysis_package(self, checkout_root): + self.install_toolchain_static_analysis(checkout_root) + def ensure_stylo_packages(self, state_dir, checkout_root): from mozboot import stylo self.install_toolchain_artifact(state_dir, checkout_root, stylo.WINDOWS_CLANG) diff --git a/python/mozboot/mozboot/openbsd.py b/python/mozboot/mozboot/openbsd.py index 7cfe14888811..c962aee2dd8b 100644 --- a/python/mozboot/mozboot/openbsd.py +++ b/python/mozboot/mozboot/openbsd.py @@ -47,6 +47,10 @@ class OpenBSDBootstrapper(BaseBootstrapper): # we use -z because there's no other way to say "any autoconf-2.13" self.run_as_root(['pkg_add', '-z'] + self.browser_packages) + def ensure_clang_static_analysis_package(self, checkout_root): + # TODO: we don't ship clang base static analysis for this platform + pass + def ensure_stylo_packages(self, state_dir, checkout_root): # Clang / llvm already installed as browser package self.run_as_root(['pkg_add', 'cbindgen']) diff --git a/python/mozboot/mozboot/osx.py b/python/mozboot/mozboot/osx.py index bd8412f10b60..0197acdb9c99 100644 --- a/python/mozboot/mozboot/osx.py +++ b/python/mozboot/mozboot/osx.py @@ -504,6 +504,9 @@ class OSXBootstrapper(BaseBootstrapper): return active_name.lower() + def ensure_clang_static_analysis_package(self, checkout_root): + self.install_toolchain_static_analysis(checkout_root) + def ensure_stylo_packages(self, state_dir, checkout_root): from mozboot import stylo # We installed clang via homebrew earlier. diff --git a/python/mozboot/mozboot/windows.py b/python/mozboot/mozboot/windows.py index 5973ba1d8b10..a85fc3cf2493 100644 --- a/python/mozboot/mozboot/windows.py +++ b/python/mozboot/mozboot/windows.py @@ -72,6 +72,9 @@ class WindowsBootstrapper(BaseBootstrapper): def install_mobile_android_artifact_mode_packages(self): raise NotImplementedError('We do not support building Android on Windows. Sorry!') + def ensure_clang_static_analysis_package(self, checkout_root): + self.install_toolchain_static_analysis(checkout_root) + def ensure_stylo_packages(self, state_dir, checkout_root): from mozboot import stylo self.install_toolchain_artifact(state_dir, checkout_root, stylo.WINDOWS_CLANG) diff --git a/security/ct/BTInclusionProof.h b/security/ct/BTTypes.h similarity index 60% rename from security/ct/BTInclusionProof.h rename to security/ct/BTTypes.h index ace843842b6c..01867aa42439 100644 --- a/security/ct/BTInclusionProof.h +++ b/security/ct/BTTypes.h @@ -4,8 +4,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef BTInclusionProof_h -#define BTInclusionProof_h +#ifndef BTTypes_h +#define BTTypes_h #include @@ -35,6 +35,30 @@ struct InclusionProofDataV2 std::vector inclusionPath; }; +// Represents a Signed Tree Head as per RFC 6962-bis. All extensions are +// ignored. The signature field covers the data in the tree_head field. +// +// struct { +// LogID log_id; +// TreeHeadDataV2 tree_head; +// opaque signature<0..2^16-1>; +// } SignedTreeHeadDataV2; +// +// struct { +// uint64 timestamp; +// uint64 tree_size; +// NodeHash root_hash; +// Extension sth_extensions<0..2^16-1>; +// } TreeHeadDataV2; + +struct SignedTreeHeadDataV2 +{ + Buffer logId; + uint64_t timestamp; + uint64_t treeSize; + Buffer rootHash; +}; + } } // namespace mozilla:ct -#endif // BTInclusionProof_h +#endif // BTTypes_h diff --git a/security/ct/BTVerifier.cpp b/security/ct/BTVerifier.cpp index 61559c789977..6dc14f385e8e 100644 --- a/security/ct/BTVerifier.cpp +++ b/security/ct/BTVerifier.cpp @@ -20,17 +20,154 @@ using namespace mozilla::pkix; typedef mozilla::pkix::Result Result; -// Members of a Inclusion Proof struct +// Common prefix lengths static const size_t kLogIdPrefixLengthBytes = 1; -static const size_t kProofTreeSizeLength = 8; -static const size_t kLeafIndexLength = 8; -static const size_t kInclusionPathLengthBytes = 2; +static const size_t kBTTreeSizeLength = 8; static const size_t kNodeHashPrefixLengthBytes = 1; +// Members of a SignedTreeHeadDataV2 struct +static const size_t kSTHTimestampLength = 8; +static const size_t kSTHExtensionsLengthBytes = 2; +static const size_t kSTHSignatureLengthBytes = 2; + +// Members of a Inclusion Proof struct +static const size_t kLeafIndexLength = 8; +static const size_t kInclusionPathLengthBytes = 2; + +static Result +GetDigestAlgorithmLengthAndIdentifier(DigestAlgorithm digestAlgorithm, + /* out */ size_t& digestAlgorithmLength, + /* out */ SECOidTag& digestAlgorithmId) +{ + switch (digestAlgorithm) { + case DigestAlgorithm::sha512: + digestAlgorithmLength = SHA512_LENGTH; + digestAlgorithmId = SEC_OID_SHA512; + return Success; + case DigestAlgorithm::sha256: + digestAlgorithmLength = SHA256_LENGTH; + digestAlgorithmId = SEC_OID_SHA256; + return Success; + default: + return pkix::Result::FATAL_ERROR_INVALID_ARGS; + } +} + Result -DecodeInclusionProof(pkix::Reader& reader, InclusionProofDataV2& output) +DecodeAndVerifySignedTreeHead(Input signerSubjectPublicKeyInfo, + DigestAlgorithm digestAlgorithm, + der::PublicKeyAlgorithm publicKeyAlgorithm, + Input signedTreeHeadInput, + /* out */ SignedTreeHeadDataV2& signedTreeHead) +{ + SignedTreeHeadDataV2 result; + Reader reader(signedTreeHeadInput); + + Input logId; + Result rv = ReadVariableBytes(reader, logId); + if (rv != Success) { + return rv; + } + InputToBuffer(logId, result.logId); + + // This is the beginning of the data covered by the signature. + Reader::Mark signedDataMark = reader.GetMark(); + + rv = ReadUint(reader, result.timestamp); + if (rv != Success) { + return rv; + } + + rv = ReadUint(reader, result.treeSize); + if (rv != Success) { + return rv; + } + + Input hash; + rv = ReadVariableBytes(reader, hash); + if (rv != Success) { + return rv; + } + InputToBuffer(hash, result.rootHash); + + // We ignore any extensions, but we have to read them. + Input extensionsInput; + rv = ReadVariableBytes(reader, extensionsInput); + if (rv != Success) { + return rv; + } + + Input signedDataInput; + rv = reader.GetInput(signedDataMark, signedDataInput); + if (rv != Success) { + return rv; + } + + SECOidTag unusedDigestAlgorithmId; + size_t digestAlgorithmLength; + rv = GetDigestAlgorithmLengthAndIdentifier(digestAlgorithm, + digestAlgorithmLength, + unusedDigestAlgorithmId); + if (rv != Success) { + return rv; + } + + uint8_t digestBuf[MAX_DIGEST_SIZE_IN_BYTES]; + rv = DigestBufNSS(signedDataInput, digestAlgorithm, digestBuf, + digestAlgorithmLength); + if (rv != Success) { + return rv; + } + + Input digestInput; + rv = digestInput.Init(digestBuf, digestAlgorithmLength); + if (rv != Success) { + return rv; + } + + Input signatureInput; + rv = ReadVariableBytes(reader, signatureInput); + if (rv != Success) { + return rv; + } + + SignedDigest signedDigest = { digestInput, digestAlgorithm, signatureInput }; + switch (publicKeyAlgorithm) { + case der::PublicKeyAlgorithm::ECDSA: + rv = VerifyECDSASignedDigestNSS(signedDigest, signerSubjectPublicKeyInfo, + nullptr); + break; + case der::PublicKeyAlgorithm::RSA_PKCS1: + case der::PublicKeyAlgorithm::Uninitialized: + default: + return Result::FATAL_ERROR_INVALID_ARGS; + } + if (rv != Success) { + // VerifyECDSASignedDigestNSS eventually calls VFY_VerifyDigestDirect, which + // can set the PR error code to SEC_ERROR_PKCS7_KEYALG_MISMATCH if the type + // of key decoded from the SPKI does not match the given signature + // algorithm. mozilla::pkix does not have a corresponding Result value and + // turns this error code into Result::ERROR_UNKNOWN_ERROR. Since this is + // uninformative, we'll turn that result into a bad signature error. + if (rv == Result::ERROR_UNKNOWN_ERROR) { + return Result::ERROR_BAD_SIGNATURE; + } + return rv; + } + + if (!reader.AtEnd()) { + return pkix::Result::ERROR_BAD_DER; + } + + signedTreeHead = std::move(result); + return Success; +} + +Result +DecodeInclusionProof(Input input, InclusionProofDataV2& output) { InclusionProofDataV2 result; + Reader reader(input); Input logId; Result rv = ReadVariableBytes(reader, logId); @@ -38,7 +175,7 @@ DecodeInclusionProof(pkix::Reader& reader, InclusionProofDataV2& output) return rv; } - rv = ReadUint(reader, result.treeSize); + rv = ReadUint(reader, result.treeSize); if (rv != Success) { return rv; } @@ -82,7 +219,7 @@ DecodeInclusionProof(pkix::Reader& reader, InclusionProofDataV2& output) inclusionPath.push_back(std::move(hashBuffer)); } - if (!reader.AtEnd()){ + if (!reader.AtEnd()) { return pkix::Result::ERROR_BAD_DER; } @@ -151,25 +288,6 @@ NodeHash(const Buffer& left, const Buffer& right, size_t digestAlgorithmLength, return CommonFinishDigest(context, digestAlgorithmLength, calculatedHash); } -static Result -GetDigestAlgorithmLengthAndIdentifier(DigestAlgorithm digestAlgorithm, - /* out */ size_t& digestAlgorithmLength, - /* out */ SECOidTag& digestAlgorithmId) -{ - switch (digestAlgorithm) { - case DigestAlgorithm::sha512: - digestAlgorithmLength = SHA512_LENGTH; - digestAlgorithmId = SEC_OID_SHA512; - return Success; - case DigestAlgorithm::sha256: - digestAlgorithmLength = SHA256_LENGTH; - digestAlgorithmId = SEC_OID_SHA256; - return Success; - default: - return pkix::Result::FATAL_ERROR_INVALID_ARGS; - } -} - // This algorithm is specified by: // https://tools.ietf.org/html/draft-ietf-trans-rfc6962-bis-28#section-2.1.3.2 Result diff --git a/security/ct/BTVerifier.h b/security/ct/BTVerifier.h index 3a2772f878dc..7993d2f979c0 100644 --- a/security/ct/BTVerifier.h +++ b/security/ct/BTVerifier.h @@ -7,16 +7,27 @@ #ifndef BTVerifier_h #define BTVerifier_h -#include "BTInclusionProof.h" +#include "BTTypes.h" #include "mozpkix/Input.h" #include "mozpkix/Result.h" +#include "mozpkix/pkixder.h" #include "mozpkix/pkixtypes.h" namespace mozilla { namespace ct { +// Given an encoded subject public key info, a digest algorithm, a public key +// algorithm, and an encoded signed tree head (SignedTreeHeadV2 as defined in +// RFC 6962-bis), decodes and verifies the STH. Currently only ECDSA keys are +// supported. SHA-256 and SHA-512 are supported, but according to the +// specification only SHA-256 should be supported at this time. +pkix::Result DecodeAndVerifySignedTreeHead( + pkix::Input signerSubjectPublicKeyInfo, pkix::DigestAlgorithm digestAlgorithm, + pkix::der::PublicKeyAlgorithm publicKeyAlg, pkix::Input signedTreeHeadInput, + SignedTreeHeadDataV2& signedTreeHead); + // Decodes an Inclusion Proof (InclusionProofDataV2 as defined in RFC // 6962-bis). This consumes the entirety of the input. -pkix::Result DecodeInclusionProof(pkix::Reader& input, +pkix::Result DecodeInclusionProof(pkix::Input input, InclusionProofDataV2& output); // Given a decoded Inclusion Proof (InclusionProofDataV2 as per RFC 6962-bis), // the corresponding leaf data entry, and the expected root hash, returns diff --git a/security/ct/CTLogVerifier.cpp b/security/ct/CTLogVerifier.cpp index 51fe86db5803..aeadca3a853e 100644 --- a/security/ct/CTLogVerifier.cpp +++ b/security/ct/CTLogVerifier.cpp @@ -238,21 +238,6 @@ CTLogVerifier::Verify(const LogEntry& entry, return VerifySignature(serializedData, sct.signature.signatureData); } -Result -CTLogVerifier::VerifySignedTreeHead(const SignedTreeHead& sth) -{ - if (!SignatureParametersMatch(sth.signature)) { - return Result::FATAL_ERROR_INVALID_ARGS; - } - - Buffer serializedData; - Result rv = EncodeTreeHeadSignature(sth, serializedData); - if (rv != Success) { - return rv; - } - return VerifySignature(serializedData, sth.signature.signatureData); -} - bool CTLogVerifier::SignatureParametersMatch(const DigitallySigned& signature) { diff --git a/security/ct/CTLogVerifier.h b/security/ct/CTLogVerifier.h index f74aee608f6a..ce3239338ba5 100644 --- a/security/ct/CTLogVerifier.h +++ b/security/ct/CTLogVerifier.h @@ -12,7 +12,6 @@ #include "CTLog.h" #include "CTUtils.h" #include "SignedCertificateTimestamp.h" -#include "SignedTreeHead.h" #include "mozpkix/Input.h" #include "mozpkix/Result.h" #include "mozpkix/pkix.h" @@ -58,10 +57,6 @@ public: pkix::Result Verify(const LogEntry& entry, const SignedCertificateTimestamp& sct); - // Verifies the signature in |sth|. - // |sth| must be signed by the verifier's log. - pkix::Result VerifySignedTreeHead(const SignedTreeHead& sth); - // Returns true if the signature and hash algorithms in |signature| // match those of the log. bool SignatureParametersMatch(const DigitallySigned& signature); diff --git a/security/ct/CTSerialization.cpp b/security/ct/CTSerialization.cpp index 6c62058d5a4a..0b02fba1255d 100644 --- a/security/ct/CTSerialization.cpp +++ b/security/ct/CTSerialization.cpp @@ -395,35 +395,6 @@ EncodeV1SCTSignedData(uint64_t timestamp, Input serializedLogEntry, return WriteVariableBytes(extensions, output); } -Result -EncodeTreeHeadSignature(const SignedTreeHead& signedTreeHead, - Buffer& output) -{ - Result rv = WriteUint( - static_cast(signedTreeHead.version), output); - if (rv != Success) { - return rv; - } - rv = WriteUint( - static_cast(SignatureType::TreeHash), output); - if (rv != Success) { - return rv; - } - rv = WriteTimeSinceEpoch(signedTreeHead.timestamp, output); - if (rv != Success) { - return rv; - } - rv = WriteUint(signedTreeHead.treeSize, output); - if (rv != Success) { - return rv; - } - if (signedTreeHead.sha256RootHash.size() != kSthRootHashLength) { - return Result::FATAL_ERROR_INVALID_ARGS; - } - WriteEncodedBytes(signedTreeHead.sha256RootHash, output); - return Success; -} - Result DecodeSCTList(Input input, Reader& listReader) { diff --git a/security/ct/CTSerialization.h b/security/ct/CTSerialization.h index d3c5e5ec8c09..9bacf1a94550 100644 --- a/security/ct/CTSerialization.h +++ b/security/ct/CTSerialization.h @@ -12,7 +12,6 @@ #include "mozpkix/Input.h" #include "mozpkix/Result.h" #include "SignedCertificateTimestamp.h" -#include "SignedTreeHead.h" // Utility functions for encoding/decoding structures used by Certificate // Transparency to/from the TLS wire format encoding. @@ -42,12 +41,6 @@ pkix::Result EncodeV1SCTSignedData(uint64_t timestamp, pkix::Input extensions, Buffer& output); -// Encodes the data signed by a Signed Tree Head (STH) |signedTreeHead| into -// |output|. The signature included in the |signedTreeHead| can then be -// verified over these bytes. -pkix::Result EncodeTreeHeadSignature(const SignedTreeHead& signedTreeHead, - Buffer& output); - // Decodes a list of Signed Certificate Timestamps // (SignedCertificateTimestampList as defined in RFC6962). This list // is typically obtained from the CT extension in a certificate. diff --git a/security/ct/SignedTreeHead.h b/security/ct/SignedTreeHead.h deleted file mode 100644 index 47231d17f871..000000000000 --- a/security/ct/SignedTreeHead.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set ts=8 sts=2 et sw=2 tw=80: */ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef SignedTreeHead_h -#define SignedTreeHead_h - -#include "SignedCertificateTimestamp.h" - -namespace mozilla { namespace ct { - -// Signed Tree Head as defined in section 3.5. of RFC-6962. -struct SignedTreeHead -{ - // Version enum in RFC 6962, Section 3.2. Note that while in the current - // RFC the STH and SCT share the versioning scheme, there are plans in - // RFC-6962-bis to use separate versions, so using a separate scheme here. - enum class Version { V1 = 0, }; - - Version version; - uint64_t timestamp; - uint64_t treeSize; - Buffer sha256RootHash; - DigitallySigned signature; -}; - -} } // namespace mozilla::ct - -#endif // SignedTreeHead_h diff --git a/security/ct/moz.build b/security/ct/moz.build index 43ecb19072a9..cff5d75e7614 100644 --- a/security/ct/moz.build +++ b/security/ct/moz.build @@ -8,14 +8,13 @@ with Files("**"): BUG_COMPONENT = ("Core", "Security: PSM") EXPORTS += [ - 'BTInclusionProof.h', + 'BTTypes.h', 'BTVerifier.h', 'Buffer.h', 'CTLog.h', 'CTPolicyEnforcer.h', 'CTVerifyResult.h', 'SignedCertificateTimestamp.h', - 'SignedTreeHead.h', ] UNIFIED_SOURCES += [ diff --git a/security/ct/tests/gtest/BTSerializationTest.cpp b/security/ct/tests/gtest/BTSerializationTest.cpp index e5376f33db52..06087153dd52 100644 --- a/security/ct/tests/gtest/BTSerializationTest.cpp +++ b/security/ct/tests/gtest/BTSerializationTest.cpp @@ -53,10 +53,8 @@ TEST_F(BTSerializationTest, DecodesInclusionProof) Buffer expectedLogId = { 0x01, 0x00 }; Input encodedProofInput = InputForBuffer(mTestInclusionProof); - Reader encodedProofReader(encodedProofInput); - InclusionProofDataV2 ipr; - ASSERT_EQ(Success, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(Success, DecodeInclusionProof(encodedProofInput, ipr)); EXPECT_EQ(expectedLogId, ipr.logId); EXPECT_EQ(expectedTreeSize, ipr.treeSize); EXPECT_EQ(expectedLeafIndex, ipr.leafIndex); @@ -68,90 +66,70 @@ TEST_F(BTSerializationTest, DecodesInclusionProof) TEST_F(BTSerializationTest, FailsDecodingInclusionProofUnexpectedData) { Input encodedProofInput = InputForBuffer(mTestInclusionProofUnexpectedData); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingInvalidHashSize) { Input encodedProofInput = InputForBuffer(mTestInclusionProofInvalidHashSize); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingInvalidHash) { Input encodedProofInput = InputForBuffer(mTestInclusionProofInvalidHash); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingMissingLogId) { Input encodedProofInput = InputForBuffer(mTestInclusionProofMissingLogId); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingNullPathLength) { Input encodedProofInput = InputForBuffer(mTestInclusionProofNullPathLength); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingPathLengthTooSmall) { Input encodedProofInput = InputForBuffer(mTestInclusionProofPathLengthTooSmall); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingPathLengthTooLarge) { Input encodedProofInput = InputForBuffer(mTestInclusionProofPathLengthTooLarge); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingNullTreeSize) { Input encodedProofInput = InputForBuffer(mTestInclusionProofNullTreeSize); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingLeafIndexOutOfBounds) { Input encodedProofInput = InputForBuffer(mTestInclusionProofLeafIndexOutOfBounds); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } TEST_F(BTSerializationTest, FailsDecodingExtraData) { Input encodedProofInput = InputForBuffer(mTestInclusionProofExtraData); - Reader encodedProofReader(encodedProofInput); InclusionProofDataV2 ipr; - - ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(pkix::Result::ERROR_BAD_DER, DecodeInclusionProof(encodedProofInput, ipr)); } } } // namespace mozilla::ct diff --git a/security/ct/tests/gtest/BTSignedTreeHeadTest.cpp b/security/ct/tests/gtest/BTSignedTreeHeadTest.cpp new file mode 100644 index 000000000000..8788db0d97bd --- /dev/null +++ b/security/ct/tests/gtest/BTSignedTreeHeadTest.cpp @@ -0,0 +1,269 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "BTVerifier.h" +#include "CTTestUtils.h" +#include "gtest/gtest.h" + +#include "nss.h" + +namespace mozilla { namespace ct { + +using namespace pkix; + +struct BTSignedTreeHeadTestParams +{ + const char* mSubjectPublicKeyInfoHex; + pkix::DigestAlgorithm mDigestAlgorithm; + pkix::der::PublicKeyAlgorithm mPublicKeyAlgorithm; + const char* mSignedTreeHeadHex; + + pkix::Result mExpectedSignedTreeHeadResult; + uint64_t mExpectedTimestamp; + uint64_t mExpectedTreeSize; + const char* mExpectedRootHashHex; +}; + +class BTSignedTreeHeadTest + : public ::testing::Test + , public ::testing::WithParamInterface +{ + void SetUp() override + { + if (!NSS_IsInitialized()) { + if (NSS_NoDB_Init(nullptr) != SECSuccess) { + abort(); + } + } + } +}; + +namespace ValidSTH { +#include "valid-sth.inc" +} +namespace ValidWithExtensionSTH { +#include "valid-with-extension-sth.inc" +} +namespace ValidSecp521r1SHA512STH { +#include "valid-secp521r1-sha512-sth.inc" +} +namespace SignatureCoversLogIDSTH { +#include "signature-covers-log-id-sth.inc" +} +namespace WrongSPKISTH { +#include "wrong-spki-sth.inc" +} +namespace WrongSigningKeySTH { +#include "wrong-signing-key-sth.inc" +} +namespace MissingLogIDSTH { +#include "missing-log-id-sth.inc" +} +namespace MissingTimestampSTH { +#include "missing-timestamp-sth.inc" +} +namespace MissingTreeSizeSTH { +#include "missing-tree-size-sth.inc" +} +namespace MissingRootHashSTH { +#include "missing-root-hash-sth.inc" +} +namespace MissingExtensionsSTH { +#include "missing-extensions-sth.inc" +} +namespace TruncatedLogIDSTH { +#include "truncated-log-id-sth.inc" +} +namespace TruncatedTimestampSTH { +#include "truncated-timestamp-sth.inc" +} +namespace TruncatedTreeSizeSTH { +#include "truncated-tree-size-sth.inc" +} +namespace TruncatedRootHashSTH { +#include "truncated-root-hash-sth.inc" +} +namespace TruncatedExtensionSTH { +#include "truncated-extension-sth.inc" +} +namespace RSASignerRSASPKISTH { +#include "rsa-signer-rsa-spki-sth.inc" +} +namespace RSASignerECSPKISTH { +#include "rsa-signer-ec-spki-sth.inc" +} +namespace ECSignerRSASPKISTH { +#include "ec-signer-rsa-spki-sth.inc" +} + +static const char* kValidRootHashHex = + "d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc"; + +static const char* kValidRootHashSHA512Hex = + "374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6c" + "c69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387"; + +static const BTSignedTreeHeadTestParams BT_SIGNED_TREE_HEAD_TEST_PARAMS[] = +{ + { ValidSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, ValidSTH::kSTHHex, Success, + 1541189938000, 7, kValidRootHashHex }, + { ValidSTH::kSPKIHex, pkix::DigestAlgorithm::sha512, + pkix::der::PublicKeyAlgorithm::ECDSA, ValidSTH::kSTHHex, + Result::ERROR_BAD_SIGNATURE, 0, 0, nullptr }, + { ValidSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::RSA_PKCS1, ValidSTH::kSTHHex, + Result::FATAL_ERROR_INVALID_ARGS, 0, 0, nullptr }, + { ValidWithExtensionSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, ValidWithExtensionSTH::kSTHHex, + Success, 1541189938000, 7, kValidRootHashHex }, + { ValidSecp521r1SHA512STH::kSPKIHex, pkix::DigestAlgorithm::sha512, + pkix::der::PublicKeyAlgorithm::ECDSA, ValidSecp521r1SHA512STH::kSTHHex, + Success, 1542136309473 , 731393445, kValidRootHashSHA512Hex }, + { ValidSecp521r1SHA512STH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, ValidSecp521r1SHA512STH::kSTHHex, + Result::ERROR_BAD_SIGNATURE, 0, 0, nullptr}, + { ValidSTH::kSPKIHex, pkix::DigestAlgorithm::sha512, + pkix::der::PublicKeyAlgorithm::ECDSA, ValidSecp521r1SHA512STH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr}, + { SignatureCoversLogIDSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, SignatureCoversLogIDSTH::kSTHHex, + Result::ERROR_BAD_SIGNATURE, 0, 0, nullptr }, + { WrongSPKISTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, WrongSPKISTH::kSTHHex, + Result::ERROR_BAD_SIGNATURE, 0, 0, nullptr }, + { WrongSigningKeySTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, WrongSigningKeySTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { MissingLogIDSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, MissingLogIDSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { MissingTimestampSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, MissingTimestampSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { MissingTreeSizeSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, MissingTreeSizeSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { MissingRootHashSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, MissingRootHashSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { MissingExtensionsSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, MissingExtensionsSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { TruncatedLogIDSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, TruncatedLogIDSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { TruncatedTimestampSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, TruncatedTimestampSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { TruncatedTreeSizeSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, TruncatedTreeSizeSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { TruncatedRootHashSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, TruncatedRootHashSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { TruncatedExtensionSTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, TruncatedExtensionSTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { RSASignerRSASPKISTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, RSASignerRSASPKISTH::kSTHHex, + Result::ERROR_BAD_SIGNATURE, 0, 0, nullptr }, + { RSASignerECSPKISTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, RSASignerECSPKISTH::kSTHHex, + Result::ERROR_BAD_DER, 0, 0, nullptr }, + { ECSignerRSASPKISTH::kSPKIHex, pkix::DigestAlgorithm::sha256, + pkix::der::PublicKeyAlgorithm::ECDSA, ECSignerRSASPKISTH::kSTHHex, + Result::ERROR_BAD_SIGNATURE, 0, 0, nullptr }, +}; + +TEST_P(BTSignedTreeHeadTest, BTSignedTreeHeadSimpleTest) +{ + const BTSignedTreeHeadTestParams& params(GetParam()); + + Buffer subjectPublicKeyInfoBuffer(HexToBytes(params.mSubjectPublicKeyInfoHex)); + Input subjectPublicKeyInfoInput = InputForBuffer(subjectPublicKeyInfoBuffer); + + Buffer signedTreeHeadBuffer(HexToBytes(params.mSignedTreeHeadHex)); + Input signedTreeHeadInput = InputForBuffer(signedTreeHeadBuffer); + + SignedTreeHeadDataV2 sth; + EXPECT_EQ(params.mExpectedSignedTreeHeadResult, + DecodeAndVerifySignedTreeHead(subjectPublicKeyInfoInput, + params.mDigestAlgorithm, params.mPublicKeyAlgorithm, signedTreeHeadInput, + sth)); + + if (params.mExpectedSignedTreeHeadResult == Success) { + EXPECT_EQ(params.mExpectedTimestamp, sth.timestamp); + EXPECT_EQ(params.mExpectedTreeSize, sth.treeSize); + EXPECT_EQ(HexToBytes(params.mExpectedRootHashHex), sth.rootHash); + } +} + +INSTANTIATE_TEST_CASE_P(BTSignedTreeHeadTest, + BTSignedTreeHeadTest, + testing::ValuesIn(BT_SIGNED_TREE_HEAD_TEST_PARAMS)); + +TEST_F(BTSignedTreeHeadTest, BTSignedTreeHeadTamperedSignatureTest) +{ + Buffer subjectPublicKeyInfoBuffer(HexToBytes(ValidSTH::kSPKIHex)); + Input subjectPublicKeyInfoInput = InputForBuffer(subjectPublicKeyInfoBuffer); + + Buffer signedTreeHeadBuffer(HexToBytes(ValidSTH::kSTHHex)); + ASSERT_TRUE(signedTreeHeadBuffer.size() > 15); + signedTreeHeadBuffer[signedTreeHeadBuffer.size() - 15] ^= 0xff; + Input signedTreeHeadInput = InputForBuffer(signedTreeHeadBuffer); + + SignedTreeHeadDataV2 sth; + EXPECT_EQ(Result::ERROR_BAD_SIGNATURE, + DecodeAndVerifySignedTreeHead(subjectPublicKeyInfoInput, + pkix::DigestAlgorithm::sha256, pkix::der::PublicKeyAlgorithm::ECDSA, + signedTreeHeadInput, sth)); +} + +TEST_F(BTSignedTreeHeadTest, BTSignedTreeHeadTruncatedSignatureTest) +{ + Buffer subjectPublicKeyInfoBuffer(HexToBytes(ValidSTH::kSPKIHex)); + Input subjectPublicKeyInfoInput = InputForBuffer(subjectPublicKeyInfoBuffer); + + Buffer signedTreeHeadBuffer(HexToBytes(ValidSTH::kSTHHex)); + ASSERT_TRUE(signedTreeHeadBuffer.size() > 17); + signedTreeHeadBuffer.resize(signedTreeHeadBuffer.size() - 17); + Input signedTreeHeadInput = InputForBuffer(signedTreeHeadBuffer); + + SignedTreeHeadDataV2 sth; + EXPECT_EQ(Result::ERROR_BAD_DER, + DecodeAndVerifySignedTreeHead(subjectPublicKeyInfoInput, + pkix::DigestAlgorithm::sha256, pkix::der::PublicKeyAlgorithm::ECDSA, + signedTreeHeadInput, sth)); +} + +TEST_F(BTSignedTreeHeadTest, BTSignedTreeHeadMissingSignatureTest) +{ + Buffer subjectPublicKeyInfoBuffer(HexToBytes(ValidSTH::kSPKIHex)); + Input subjectPublicKeyInfoInput = InputForBuffer(subjectPublicKeyInfoBuffer); + + Buffer signedTreeHeadBuffer = { + 0x02, 0x00, 0x00, + // 1541189938000 milliseconds since the epoch + 0x00, 0x00, 0x01, 0x66, 0xd6, 0x14, 0x2b, 0x50, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, // 7 total nodes + 0x20, // 32 byte hash + 0xd1, 0xa0, 0xd3, 0x94, 0x7d, 0xb4, 0xae, 0x83, 0x05, 0xf2, 0xac, 0x32, + 0x98, 0x59, 0x57, 0xe0, 0x26, 0x59, 0xb2, 0xea, 0x3c, 0x10, 0xda, 0x52, + 0xa4, 0x8d, 0x25, 0x26, 0xe9, 0xaf, 0x3b, 0xbc, + 0x00, 0x00, // no extensions + // missing signature + }; + Input signedTreeHeadInput = InputForBuffer(signedTreeHeadBuffer); + + SignedTreeHeadDataV2 sth; + EXPECT_EQ(Result::ERROR_BAD_DER, + DecodeAndVerifySignedTreeHead(subjectPublicKeyInfoInput, + pkix::DigestAlgorithm::sha256, pkix::der::PublicKeyAlgorithm::ECDSA, + signedTreeHeadInput, sth)); +} + +} } //namespace mozilla::ct diff --git a/security/ct/tests/gtest/BTVerificationTest.cpp b/security/ct/tests/gtest/BTVerificationTest.cpp index 6236774e6848..9e158c60ae09 100644 --- a/security/ct/tests/gtest/BTVerificationTest.cpp +++ b/security/ct/tests/gtest/BTVerificationTest.cpp @@ -242,10 +242,8 @@ TEST_P(BTVerificationTest, BTVerificationSimpleTest) Buffer encodedProofBuffer(HexToBytes(params.mInclusionProofHex)); Input encodedProof = InputForBuffer(encodedProofBuffer); - Reader encodedProofReader(encodedProof); - InclusionProofDataV2 ipr; - ASSERT_EQ(Success, DecodeInclusionProof(encodedProofReader, ipr)); + ASSERT_EQ(Success, DecodeInclusionProof(encodedProof, ipr)); Buffer leafEntryBuffer(HexToBytes(params.mInputHex)); Input leafEntry = InputForBuffer(leafEntryBuffer); diff --git a/security/ct/tests/gtest/CTLogVerifierTest.cpp b/security/ct/tests/gtest/CTLogVerifierTest.cpp index 96243c99d1fb..b549a4a2e47f 100644 --- a/security/ct/tests/gtest/CTLogVerifierTest.cpp +++ b/security/ct/tests/gtest/CTLogVerifierTest.cpp @@ -109,21 +109,6 @@ TEST_F(CTLogVerifierTest, FailsInvalidLogID) certSct)); } -TEST_F(CTLogVerifierTest, VerifiesValidSTH) -{ - SignedTreeHead sth; - GetSampleSignedTreeHead(sth); - EXPECT_EQ(Success, mLog.VerifySignedTreeHead(sth)); -} - -TEST_F(CTLogVerifierTest, DoesNotVerifyInvalidSTH) -{ - SignedTreeHead sth; - GetSampleSignedTreeHead(sth); - sth.sha256RootHash[0] ^= '\xFF'; - EXPECT_EQ(pkix::Result::ERROR_BAD_SIGNATURE, mLog.VerifySignedTreeHead(sth)); -} - // Test that excess data after the public key is rejected. TEST_F(CTLogVerifierTest, ExcessDataInPublicKey) { diff --git a/security/ct/tests/gtest/CTSerializationTest.cpp b/security/ct/tests/gtest/CTSerializationTest.cpp index a16e2861caca..fc975b4adb4f 100644 --- a/security/ct/tests/gtest/CTSerializationTest.cpp +++ b/security/ct/tests/gtest/CTSerializationTest.cpp @@ -230,30 +230,4 @@ TEST_F(CTSerializationTest, FailsDecodingInvalidSignedCertificateTimestamp) DecodeSignedCertificateTimestamp(invalidLengthSctReader, sct)); } -TEST_F(CTSerializationTest, EncodesValidSignedTreeHead) -{ - SignedTreeHead signedTreeHead; - GetSampleSignedTreeHead(signedTreeHead); - - Buffer encoded; - ASSERT_EQ(Success, - EncodeTreeHeadSignature(signedTreeHead, encoded)); - // Expected size is 50 bytes: - // Byte 0 is version, byte 1 is signature type - // Bytes 2-9 are timestamp - // Bytes 10-17 are tree size - // Bytes 18-49 are sha256 root hash - ASSERT_EQ(50u, encoded.size()); - Buffer expectedBuffer = { - 0x00, // version - 0x01, // signature type - 0x00, 0x00, 0x01, 0x45, 0x3c, 0x5f, 0xb8, 0x35, // timestamp - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x15 // tree size - // sha256 root hash should follow - }; - Buffer hash = GetSampleSTHSHA256RootHash(); - expectedBuffer.insert(expectedBuffer.end(), hash.begin(), - hash.begin() + hash.size()); - EXPECT_EQ(expectedBuffer, encoded); -} } } // namespace mozilla::ct diff --git a/security/ct/tests/gtest/CTTestUtils.cpp b/security/ct/tests/gtest/CTTestUtils.cpp index 2b42bf6a3bb2..b56c3be3dbd0 100644 --- a/security/ct/tests/gtest/CTTestUtils.cpp +++ b/security/ct/tests/gtest/CTTestUtils.cpp @@ -9,7 +9,7 @@ #include #include -#include "BTInclusionProof.h" +#include "BTTypes.h" #include "CTSerialization.h" #include "gtest/gtest.h" #include "mozpkix/Input.h" @@ -20,7 +20,6 @@ #include "mozpkix/pkixcheck.h" #include "mozpkix/pkixutil.h" #include "SignedCertificateTimestamp.h" -#include "SignedTreeHead.h" namespace mozilla { namespace ct { @@ -107,16 +106,6 @@ const char kTestSCTPrecertSignatureData[] = "30450220482f6751af35dba65436be1fd6640f3dbf9a41429495924530288fa3e5e23e0602" "2100e4edc0db3ac572b1e2f5e8ab6a680653987dcf41027dfeffa105519d89edbf08"; -// For the sample STH -const char kSampleSTHSHA256RootHash[] = - "726467216167397babca293dca398e4ce6b621b18b9bc42f30c900d1f92ac1e4"; -const char kSampleSTHTreeHeadSignature[] = - "0403004730450220365a91a2a88f2b9332f41d8959fa7086da7e6d634b7b089bc9da066426" - "6c7a20022100e38464f3c0fd066257b982074f7ac87655e0c8f714768a050b4be9a7b441cb" - "d3"; -const size_t kSampleSTHTreeSize = 21u; -const uint64_t kSampleSTHTimestamp = 1396877277237u; - // test-embedded-cert.pem const char kTestEmbeddedCertData[] = "30820359308202c2a003020102020107300d06092a864886f70d01010505" @@ -633,40 +622,6 @@ GetDefaultIssuerKeyHash() return HexToBytes(kDefaultIssuerKeyHash); } -// A sample, valid STH -void -GetSampleSignedTreeHead(SignedTreeHead& sth) -{ - sth.version = SignedTreeHead::Version::V1; - sth.timestamp = kSampleSTHTimestamp; - sth.treeSize = kSampleSTHTreeSize; - sth.sha256RootHash = GetSampleSTHSHA256RootHash(); - GetSampleSTHTreeHeadDecodedSignature(sth.signature); -} - -Buffer -GetSampleSTHSHA256RootHash() -{ - return HexToBytes(kSampleSTHSHA256RootHash); -} - -Buffer -GetSampleSTHTreeHeadSignature() -{ - return HexToBytes(kSampleSTHTreeHeadSignature); -} - -void -GetSampleSTHTreeHeadDecodedSignature(DigitallySigned& signature) -{ - Buffer ths = HexToBytes(kSampleSTHTreeHeadSignature); - Input thsInput; - ASSERT_EQ(Success, thsInput.Init(ths.data(), ths.size())); - Reader thsReader(thsInput); - ASSERT_EQ(Success, DecodeDigitallySigned(thsReader, signature)); - ASSERT_TRUE(thsReader.AtEnd()); -} - Buffer GetDEREncodedTestEmbeddedCert() { diff --git a/security/ct/tests/gtest/CTTestUtils.h b/security/ct/tests/gtest/CTTestUtils.h index 808084485770..a1403586d73b 100644 --- a/security/ct/tests/gtest/CTTestUtils.h +++ b/security/ct/tests/gtest/CTTestUtils.h @@ -13,7 +13,6 @@ #include "mozpkix/Time.h" #include "seccomon.h" #include "SignedCertificateTimestamp.h" -#include "SignedTreeHead.h" namespace mozilla { namespace ct { @@ -75,9 +74,6 @@ void GetPrecertSCT(SignedCertificateTimestamp& sct); // Issuer key hash. Buffer GetDefaultIssuerKeyHash(); -// A sample, valid STH. -void GetSampleSignedTreeHead(SignedTreeHead& sth); - // The SHA256 root hash for the sample STH. Buffer GetSampleSTHSHA256RootHash(); diff --git a/security/ct/tests/gtest/createSTHTestData.py b/security/ct/tests/gtest/createSTHTestData.py new file mode 100755 index 000000000000..dff3026693ab --- /dev/null +++ b/security/ct/tests/gtest/createSTHTestData.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python +# +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +""" +This utility is used by the build system to create test inputs for the +signed tree head decoding and verification implementation. The format is +generally lines of : pairs except for the to-be-signed +section, which consists of one or more lines of hex bytes. Comments may +appear at the end of lines and begin with '//'. +The following keys are valid: +signingKey: A pykey key identifier to use to sign the to-be-signed data. + Required. +spki: A pykey key identifier to create an encoded SubjectPublicKeyInfo + to be included with the test data. The tests will use this spki to + validate the signature. Required. +prefix: Hex bytes to include at the beginning of the signed tree head + data. This data is not covered by the signature (typically this + is used for the log_id field). Optional. Defaults to the empty + string. +hash: The name of a hash algorithm to use when signing. Optional. + Defaults to 'sha256'. +""" + +from pyasn1.codec.der import encoder +import binascii + +import os +import sys +sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..', + 'manager', 'ssl', 'tests', 'unit')) +import pykey + + +def sign(signingKey, hashAlgorithm, hexToSign): + """Given a pykey, the name of a hash function, and hex bytes to + sign, signs the data (as binary) and returns a hex string consisting + of the signature.""" + # key.sign returns a hex string in the format "''H", + # so we have to strip off the "'"s and trailing 'H' + return signingKey.sign(binascii.unhexlify(hexToSign), + 'hash:%s' % hashAlgorithm)[1:-2] + + +class Error(Exception): + """Base class for exceptions in this module.""" + pass + + +class UnknownParameterTypeError(Error): + """Base class for handling unexpected input in this module.""" + + def __init__(self, value): + super(Error, self).__init__() + self.value = value + self.category = 'key' + + def __str__(self): + return 'Unknown %s type "%s"' % (self.category, repr(self.value)) + + +class InputTooLongError(Error): + """Helper exception type for inputs that are too long.""" + + def __init__(self, length): + super(InputTooLongError, self).__init__() + self.length = length + + def __str__(self): + return 'Input too long: %s > 65535' % self.length + + +def getTwoByteLenAsHex(callLenOnMe): + """Given something that len can be called on, returns a hex string + representing the two-byte length of the something, in network byte + order (the length must be less than or equal to 65535).""" + length = len(callLenOnMe) + if length > 65535: + raise InputTooLongError(length) + return binascii.hexlify(chr(length / 256) + chr(length % 256)) + + +def createSTH(configStream): + """Given a stream that will provide the specification for a signed + tree head (see the comment at the top of this file), creates the + corresponding signed tree head. Returns a string that can be + compiled as C/C++ that declares two const char*s kSTHHex and + kSPKIHex corresponding to the hex encoding of the signed tree head + and the hex encoding of the subject public key info from the + specification, respectively.""" + toSign = '' + prefix = '' + hashAlgorithm = 'sha256' + for line in configStream.readlines(): + if ':' in line: + param = line.split(':')[0] + arg = line.split(':')[1].split('//')[0].strip() + if param == 'signingKey': + signingKey = pykey.keyFromSpecification(arg) + elif param == 'spki': + spki = pykey.keyFromSpecification(arg) + elif param == 'prefix': + prefix = arg + elif param == 'hash': + hashAlgorithm = arg + else: + raise UnknownParameterTypeError(param) + else: + toSign = toSign + line.split('//')[0].strip() + signature = sign(signingKey, hashAlgorithm, toSign) + lengthBytesHex = getTwoByteLenAsHex(binascii.unhexlify(signature)) + sth = prefix + toSign + lengthBytesHex + signature + spkiHex = binascii.hexlify(encoder.encode(spki.asSubjectPublicKeyInfo())) + return ('const char* kSTHHex = "%s";\nconst char* kSPKIHex = "%s";\n' % + (sth, spkiHex)) + + +def main(output, inputPath): + """Given a file-like output and the path to a signed tree head + specification (see the comment at the top of this file), reads the + specification, creates the signed tree head, and outputs test data + that can be included by a gtest corresponding to the + specification.""" + with open(inputPath) as configStream: + output.write(createSTH(configStream)) diff --git a/security/ct/tests/gtest/ec-signer-rsa-spki-sth.inc.tbs b/security/ct/tests/gtest/ec-signer-rsa-spki-sth.inc.tbs new file mode 100644 index 000000000000..a8593e27c495 --- /dev/null +++ b/security/ct/tests/gtest/ec-signer-rsa-spki-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:default // this is the default 2048-bit RSA key +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/missing-extensions-sth.inc.tbs b/security/ct/tests/gtest/missing-extensions-sth.inc.tbs new file mode 100644 index 000000000000..98807b854d31 --- /dev/null +++ b/security/ct/tests/gtest/missing-extensions-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +// missing extensions diff --git a/security/ct/tests/gtest/missing-log-id-sth.inc.tbs b/security/ct/tests/gtest/missing-log-id-sth.inc.tbs new file mode 100644 index 000000000000..6c1bb21997d2 --- /dev/null +++ b/security/ct/tests/gtest/missing-log-id-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +// missing logid +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/missing-root-hash-sth.inc.tbs b/security/ct/tests/gtest/missing-root-hash-sth.inc.tbs new file mode 100644 index 000000000000..5accf70fe85a --- /dev/null +++ b/security/ct/tests/gtest/missing-root-hash-sth.inc.tbs @@ -0,0 +1,7 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +// missing root_hash +0000 // no extensions diff --git a/security/ct/tests/gtest/missing-timestamp-sth.inc.tbs b/security/ct/tests/gtest/missing-timestamp-sth.inc.tbs new file mode 100644 index 000000000000..5e7ebb6cf2dc --- /dev/null +++ b/security/ct/tests/gtest/missing-timestamp-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +// missing timestamp +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/missing-tree-size-sth.inc.tbs b/security/ct/tests/gtest/missing-tree-size-sth.inc.tbs new file mode 100644 index 000000000000..128e6d64b1cd --- /dev/null +++ b/security/ct/tests/gtest/missing-tree-size-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +// missing tree_size +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/moz.build b/security/ct/tests/gtest/moz.build index 891fc5ae37eb..aeca759a7bf8 100644 --- a/security/ct/tests/gtest/moz.build +++ b/security/ct/tests/gtest/moz.build @@ -4,8 +4,39 @@ # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. -SOURCES += [ +@template +def STHTestFile(name): + if not CONFIG['COMPILE_ENVIRONMENT']: + return + + GENERATED_FILES += [name] + props = GENERATED_FILES[name] + props.script = 'createSTHTestData.py' + props.inputs = ['%s.tbs' % name] + +STHTestFile('valid-sth.inc') +STHTestFile('valid-with-extension-sth.inc') +STHTestFile('valid-secp521r1-sha512-sth.inc') +STHTestFile('signature-covers-log-id-sth.inc') +STHTestFile('wrong-spki-sth.inc') +STHTestFile('wrong-signing-key-sth.inc') +STHTestFile('missing-log-id-sth.inc') +STHTestFile('missing-timestamp-sth.inc') +STHTestFile('missing-tree-size-sth.inc') +STHTestFile('missing-root-hash-sth.inc') +STHTestFile('missing-extensions-sth.inc') +STHTestFile('truncated-log-id-sth.inc') +STHTestFile('truncated-timestamp-sth.inc') +STHTestFile('truncated-tree-size-sth.inc') +STHTestFile('truncated-root-hash-sth.inc') +STHTestFile('truncated-extension-sth.inc') +STHTestFile('rsa-signer-rsa-spki-sth.inc') +STHTestFile('rsa-signer-ec-spki-sth.inc') +STHTestFile('ec-signer-rsa-spki-sth.inc') + +UNIFIED_SOURCES += [ 'BTSerializationTest.cpp', + 'BTSignedTreeHeadTest.cpp', 'BTVerificationTest.cpp', 'CTDiversityPolicyTest.cpp', 'CTLogVerifierTest.cpp', diff --git a/security/ct/tests/gtest/rsa-signer-ec-spki-sth.inc.tbs b/security/ct/tests/gtest/rsa-signer-ec-spki-sth.inc.tbs new file mode 100644 index 000000000000..92f1a47490a1 --- /dev/null +++ b/security/ct/tests/gtest/rsa-signer-ec-spki-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:default // this is the default 2048-bit RSA key +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/rsa-signer-rsa-spki-sth.inc.tbs b/security/ct/tests/gtest/rsa-signer-rsa-spki-sth.inc.tbs new file mode 100644 index 000000000000..b412c87e12f4 --- /dev/null +++ b/security/ct/tests/gtest/rsa-signer-rsa-spki-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:default // this is the default 2048-bit RSA key +spki:default +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/signature-covers-log-id-sth.inc.tbs b/security/ct/tests/gtest/signature-covers-log-id-sth.inc.tbs new file mode 100644 index 000000000000..723ee7a9788a --- /dev/null +++ b/security/ct/tests/gtest/signature-covers-log-id-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +020000 // This is the log id. It should not be covered by the signature, but it is in this case. +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/truncated-extension-sth.inc.tbs b/security/ct/tests/gtest/truncated-extension-sth.inc.tbs new file mode 100644 index 000000000000..0fe30a58dae5 --- /dev/null +++ b/security/ct/tests/gtest/truncated-extension-sth.inc.tbs @@ -0,0 +1,11 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0014 // 20 bytes of extensions + ffff // extension type ffff + 0010 // 16 bytes of data + ffffffffff // truncated diff --git a/security/ct/tests/gtest/truncated-log-id-sth.inc.tbs b/security/ct/tests/gtest/truncated-log-id-sth.inc.tbs new file mode 100644 index 000000000000..267976af4442 --- /dev/null +++ b/security/ct/tests/gtest/truncated-log-id-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:0200 // truncated log_id +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/truncated-root-hash-sth.inc.tbs b/security/ct/tests/gtest/truncated-root-hash-sth.inc.tbs new file mode 100644 index 000000000000..295b06988016 --- /dev/null +++ b/security/ct/tests/gtest/truncated-root-hash-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e0 // truncated +0000 // no extensions diff --git a/security/ct/tests/gtest/truncated-timestamp-sth.inc.tbs b/security/ct/tests/gtest/truncated-timestamp-sth.inc.tbs new file mode 100644 index 000000000000..247bd4dddcab --- /dev/null +++ b/security/ct/tests/gtest/truncated-timestamp-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6 // truncated timestamp +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/truncated-tree-size-sth.inc.tbs b/security/ct/tests/gtest/truncated-tree-size-sth.inc.tbs new file mode 100644 index 000000000000..9e0a94282710 --- /dev/null +++ b/security/ct/tests/gtest/truncated-tree-size-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +000000 // truncate tree_size +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/valid-secp521r1-sha512-sth.inc.tbs b/security/ct/tests/gtest/valid-secp521r1-sha512-sth.inc.tbs new file mode 100644 index 000000000000..674adfec56d8 --- /dev/null +++ b/security/ct/tests/gtest/valid-secp521r1-sha512-sth.inc.tbs @@ -0,0 +1,10 @@ +signingKey:secp521r1 +spki:secp521r1 +hash:sha512 +prefix:020000 +000001670e7ca6e1 // 1542136309473 milliseconds since the epoch +000000002b982da5 // 731393445 total nodes +40 // 64 byte hash + 374d794a95cdcfd8b35993185fef9ba368f160d8daf432d08ba9f1ed1e5abe6c + c69291e0fa2fe0006a52570ef18c19def4e617c33ce52ef0a6e5fbe318cb0387 +0000 // no extensions diff --git a/security/ct/tests/gtest/valid-sth.inc.tbs b/security/ct/tests/gtest/valid-sth.inc.tbs new file mode 100644 index 000000000000..b1bb592e9337 --- /dev/null +++ b/security/ct/tests/gtest/valid-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/valid-with-extension-sth.inc.tbs b/security/ct/tests/gtest/valid-with-extension-sth.inc.tbs new file mode 100644 index 000000000000..62612de30158 --- /dev/null +++ b/security/ct/tests/gtest/valid-with-extension-sth.inc.tbs @@ -0,0 +1,11 @@ +signingKey:secp256r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0014 // 20 bytes of extensions + ffff // extension type ffff + 0010 // 16 bytes of data + ffffffffffffffffffffffffffffffff diff --git a/security/ct/tests/gtest/wrong-signing-key-sth.inc.tbs b/security/ct/tests/gtest/wrong-signing-key-sth.inc.tbs new file mode 100644 index 000000000000..b8a93bb39ec2 --- /dev/null +++ b/security/ct/tests/gtest/wrong-signing-key-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp384r1 +spki:secp256r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/security/ct/tests/gtest/wrong-spki-sth.inc.tbs b/security/ct/tests/gtest/wrong-spki-sth.inc.tbs new file mode 100644 index 000000000000..c02282c90481 --- /dev/null +++ b/security/ct/tests/gtest/wrong-spki-sth.inc.tbs @@ -0,0 +1,8 @@ +signingKey:secp256r1 +spki:secp384r1 +prefix:020000 +00000166d6142b50 // 1541189938000 milliseconds since the epoch +0000000000000007 // 7 total nodes +20 // 32 byte hash + d1a0d3947db4ae8305f2ac32985957e02659b2ea3c10da52a48d2526e9af3bbc +0000 // no extensions diff --git a/testing/firefox-ui/tests/puppeteer/manifest.ini b/testing/firefox-ui/tests/puppeteer/manifest.ini index 72cf05a3b67e..0bd5132bda2b 100644 --- a/testing/firefox-ui/tests/puppeteer/manifest.ini +++ b/testing/firefox-ui/tests/puppeteer/manifest.ini @@ -3,6 +3,7 @@ tags = local # API tests [test_appinfo.py] +skip-if = artifact # bug 1298233 - build ids are different for artifact builds [test_l10n.py] [test_places.py] [test_security.py] diff --git a/testing/firefox-ui/tests/puppeteer/test_appinfo.py b/testing/firefox-ui/tests/puppeteer/test_appinfo.py index f0be0f61684f..fffc4bf67e93 100644 --- a/testing/firefox-ui/tests/puppeteer/test_appinfo.py +++ b/testing/firefox-ui/tests/puppeteer/test_appinfo.py @@ -18,9 +18,7 @@ class TestAppInfo(PuppeteerMixin, MarionetteTestCase): self.assertEqual(self.puppeteer.appinfo.name, version_info['application_name']) self.assertEqual(self.puppeteer.appinfo.vendor, version_info['application_vendor']) self.assertEqual(self.puppeteer.appinfo.version, version_info['application_version']) - # Bug 1298328 - Platform buildid mismatch due to incremental builds - # self.assertEqual(self.puppeteer.appinfo.platformBuildID, - # version_info['platform_buildid']) + self.assertEqual(self.puppeteer.appinfo.platformBuildID, version_info['platform_buildid']) self.assertEqual(self.puppeteer.appinfo.platformVersion, version_info['platform_version']) self.assertIsNotNone(self.puppeteer.appinfo.locale) self.assertIsNotNone(self.puppeteer.appinfo.user_agent) diff --git a/testing/mozharness/mozharness/mozilla/testing/errors.py b/testing/mozharness/mozharness/mozilla/testing/errors.py index 998e991eeb00..8ebd625d29c5 100644 --- a/testing/mozharness/mozharness/mozilla/testing/errors.py +++ b/testing/mozharness/mozharness/mozilla/testing/errors.py @@ -127,6 +127,8 @@ HarnessErrorList = [ {'substr': 'PROCESS-CRASH', 'level': ERROR, }, {'regex': re.compile('''ERROR: (Address|Leak)Sanitizer'''), 'level': ERROR, }, {'regex': re.compile('''thread '([^']+)' panicked'''), 'level': ERROR, }, + {'substr': 'pure virtual method called', 'level': ERROR, }, + {'substr': 'Pure virtual function called!', 'level': ERROR, }, ] LogcatErrorList = [ diff --git a/third_party/rust/gl_generator/.cargo-checksum.json b/third_party/rust/gl_generator/.cargo-checksum.json index 88883913bd22..744d74078254 100644 --- a/third_party/rust/gl_generator/.cargo-checksum.json +++ b/third_party/rust/gl_generator/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"a11980c70bdc8957d169c4482a3e57a0dd5cb3de6e9eae7b9c15caac7ad8f835","README.md":"e0ae9e1224f6ce5d6df8e30272a1a23044d2d33b0051bf32ccd74e559f8a9f6c","generators/debug_struct_gen.rs":"35223dab284989801bbb7bd676e25533d7fef8e2d990f686867eec1efe95dc62","generators/global_gen.rs":"cad1d5f209dc7ce06d0cea897ee56870c33b812403735adedf2c2d9d3712783f","generators/mod.rs":"9d9f9c20c70de67ca16f4692aff3cdcb7f9209433ebd49e771dbce94349a2a75","generators/static_gen.rs":"9fb4ee9f056263611658234539977fb415f93435d290053b84b092e05de16924","generators/static_struct_gen.rs":"23b910c2b14936766036876b9915639058e0cf3bca468c317d4edc7f6498b471","generators/struct_gen.rs":"03d1bcb9d8ddd64d9326fefe2898633e6714e0caffc32f54b6c873bc75b8a497","generators/templates/types/egl.rs":"d1785a30f1098e101302ba74ba4c22cf95ac44b17edf221dbb9d890f4bd635a2","generators/templates/types/gl.rs":"f71f3a2200c0fa13f09687ef05e51c28c5b11c1bb841acd402c0097d8f9130bd","generators/templates/types/glx.rs":"f444166d117b96afed2d8d13db6cd3369d6c59704f296e76202269f411bbd4a8","generators/templates/types/wgl.rs":"9d626e0959374c694c19a36d4dd34dae2f37acf3cb94e9bd4d242a16b41a970d","lib.rs":"4d68840c600a1025025438454d68d70e6da3891f2a5bb33406d4255cb257cda1","registry/mod.rs":"4c42448775dc25449c9995a5ec76e95d6c0762d92443f3c12e865768e4e1dc2a","registry/parse.rs":"5619135099e9be42e47c45a29a359d63890ab60da482bd4f437728a53d561e95"},"package":"7a795170cbd85b5a7baa58d6d7525cae6a03e486859860c220f7ebbbdd379d0a"} \ No newline at end of file +{"files":{"Cargo.toml":"1d8172e33254e98db947a0a4e9c9abfe1e17884857c88228e210bed6d3a490a9","README.md":"52d8fee4681c879f2c964fd30e3faf0c907e8bf676eab7b44beab5c5bbd5c284","generators/debug_struct_gen.rs":"73164956c9c5fe848a568aac1a7518947a0786ad6118618d78b4f0208c3f442e","generators/global_gen.rs":"486384b1d7fc234dbe55815bd99e5fbd69144f361f8cefdf4aa9841db1d7832a","generators/mod.rs":"100a1da965bf11eaa9fad48a06c7856b60f48363a4a707e34ba97938bedae0b8","generators/static_gen.rs":"925a9401e27358a466baadfb660056a24394cf2fa21f5613e2d7f50ab8935e71","generators/static_struct_gen.rs":"eb08e6e59b0e0947c4ab263a0749efbb28430c5741634c413a2be011fcdad88f","generators/struct_gen.rs":"13444b524e992d88fdd2f4b0990e06bdee292b076047b274b7f607f3de12a85d","generators/templates/types/egl.rs":"d1785a30f1098e101302ba74ba4c22cf95ac44b17edf221dbb9d890f4bd635a2","generators/templates/types/gl.rs":"f71f3a2200c0fa13f09687ef05e51c28c5b11c1bb841acd402c0097d8f9130bd","generators/templates/types/glx.rs":"f444166d117b96afed2d8d13db6cd3369d6c59704f296e76202269f411bbd4a8","generators/templates/types/wgl.rs":"9d626e0959374c694c19a36d4dd34dae2f37acf3cb94e9bd4d242a16b41a970d","lib.rs":"6f47da878479b503b5202bda84ad8935607264ac03c0b68203109fad9cd479db","registry/mod.rs":"7782ce4cec631bc91919ff83bcc50fede34d863630fb7fc00a22a43e982c842c","registry/parse.rs":"231985bac6c8cf4ef4e6867cf386980d041d3734f2ae73d41ec1b50d9c9bd096"},"package":"a0ffaf173cf76c73a73e080366bf556b4776ece104b06961766ff11449f38604"} \ No newline at end of file diff --git a/third_party/rust/gl_generator/Cargo.toml b/third_party/rust/gl_generator/Cargo.toml index 4591fd3cb3ab..698c1b435277 100644 --- a/third_party/rust/gl_generator/Cargo.toml +++ b/third_party/rust/gl_generator/Cargo.toml @@ -12,10 +12,10 @@ [package] name = "gl_generator" -version = "0.9.0" +version = "0.10.0" authors = ["Brendan Zabarauskas ", "Corey Richardson", "Arseny Kapoulkine"] description = "Code generators for creating bindings to the Khronos OpenGL APIs." -homepage = "https://github.com/brendanzab/gl-rs/gl_generator/" +homepage = "https://github.com/brendanzab/gl-rs/" documentation = "https://docs.rs/gl_generator" readme = "README.md" keywords = ["gl", "egl", "opengl", "khronos"] @@ -27,13 +27,13 @@ repository = "https://github.com/brendanzab/gl-rs/" name = "gl_generator" path = "lib.rs" [dependencies.khronos_api] -version = "2.1.0" +version = "3.0.0" [dependencies.log] -version = "0.4.1" +version = "0.4" [dependencies.xml-rs] -version = "0.7.0" +version = "0.8" [features] unstable_generator_utils = [] diff --git a/third_party/rust/gl_generator/README.md b/third_party/rust/gl_generator/README.md index ddafa2ca484d..36d3e707b6c9 100644 --- a/third_party/rust/gl_generator/README.md +++ b/third_party/rust/gl_generator/README.md @@ -59,8 +59,8 @@ mod gl { fn main() { let window = ...; - // Assuming `window` is GLFW: initialize, and made current - gl::load_with(|s| window.get_proc_address(s)); + // Assuming `window` is GLFW: initialize, and make current + gl::load_with(|s| window.get_proc_address(s) as *const _); } ``` diff --git a/third_party/rust/gl_generator/generators/debug_struct_gen.rs b/third_party/rust/gl_generator/generators/debug_struct_gen.rs index 072004814e53..c8d329032ada 100644 --- a/third_party/rust/gl_generator/generators/debug_struct_gen.rs +++ b/third_party/rust/gl_generator/generators/debug_struct_gen.rs @@ -20,7 +20,8 @@ pub struct DebugStructGenerator; impl super::Generator for DebugStructGenerator { fn write(&self, registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write + where + W: io::Write, { try!(write_header(dest)); try!(write_type_aliases(registry, dest)); @@ -36,29 +37,35 @@ impl super::Generator for DebugStructGenerator { /// Creates a `__gl_imports` module which contains all the external symbols that we need for the /// bindings. fn write_header(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - r#" + writeln!( + dest, + r#" mod __gl_imports {{ pub use std::mem; pub use std::marker::Send; pub use std::os::raw; }} - "#) + "# + ) } /// Creates a `types` module which contains all the type aliases. /// /// See also `generators::gen_types`. fn write_type_aliases(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - try!(writeln!(dest, - r#" + try!(writeln!( + dest, + r#" pub mod types {{ #![allow(non_camel_case_types, non_snake_case, dead_code, missing_copy_implementations)] - "#)); + "# + )); try!(super::gen_types(registry.api, dest)); @@ -67,7 +74,8 @@ fn write_type_aliases(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates all the `` elements at the root of the bindings. fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { for enm in ®istry.enums { try!(super::gen_enum_item(enm, "types::", dest)); @@ -78,10 +86,12 @@ fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates a `FnPtr` structure which contains the store for a single binding. fn write_fnptr_struct_def(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - " + writeln!( + dest, + " #[allow(dead_code, missing_copy_implementations)] #[derive(Clone)] pub struct FnPtr {{ @@ -113,35 +123,42 @@ fn write_fnptr_struct_def(dest: &mut W) -> io::Result<()> self.is_loaded }} }} - ") + " + ) } /// Creates a `panicking` module which contains one function per GL command. /// /// These functions are the mocks that are called if the real function could not be loaded. fn write_panicking_fns(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - "#[inline(never)] + writeln!( + dest, + "#[inline(never)] fn missing_fn_panic() -> ! {{ panic!(\"{api} function was not loaded\") }}", - api = registry.api) + api = registry.api + ) } /// Creates a structure which stores all the `FnPtr` of the bindings. /// /// The name of the struct corresponds to the namespace. fn write_struct(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - try!(writeln!(dest, - " + try!(writeln!( + dest, + " #[allow(non_camel_case_types, non_snake_case, dead_code)] #[derive(Clone)] pub struct {api} {{", - api = super::gen_struct_name(registry.api))); + api = super::gen_struct_name(registry.api) + )); for cmd in ®istry.cmds { if let Some(v) = registry.aliases.get(&cmd.proto.ident) { @@ -156,7 +173,8 @@ fn write_struct(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates the `impl` of the structure created by `write_struct`. fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { try!(writeln!(dest, "impl {api} {{ @@ -189,45 +207,49 @@ fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> api = super::gen_struct_name(registry.api))); for cmd in ®istry.cmds { - try!(writeln!(dest, + try!(writeln!( + dest, "{name}: FnPtr::new(metaloadfn(\"{symbol}\", &[{fallbacks}])),", name = cmd.proto.ident, symbol = super::gen_symbol_name(registry.api, &cmd.proto.ident), fallbacks = match registry.aliases.get(&cmd.proto.ident) { - Some(fbs) => { - fbs.iter() - .map(|name| format!("\"{}\"", super::gen_symbol_name(registry.api, &name))) - .collect::>().join(", ") - }, + Some(fbs) => fbs + .iter() + .map(|name| format!("\"{}\"", super::gen_symbol_name(registry.api, &name))) + .collect::>() + .join(", "), None => format!(""), }, )) } try!(writeln!(dest, "_priv: ()")); - try!(writeln!(dest, - "}} - }}")); + try!(writeln!( + dest, + "}} + }}" + )); for cmd in ®istry.cmds { let idents = super::gen_parameters(cmd, true, false); let typed_params = super::gen_parameters(cmd, false, true); - let println = format!("println!(\"[OpenGL] {}({})\" {});", - cmd.proto.ident, - (0..idents.len()) - .map(|_| "{:?}".to_string()) - .collect::>() - .join(", "), - idents - .iter() - .zip(typed_params.iter()) - .map(|(name, ty)| if ty.contains("GLDEBUGPROC") { - format!(", \"\"") - } else { - format!(", {}", name) - }) - .collect::>() - .concat()); + let println = format!( + "println!(\"[OpenGL] {}({})\" {});", + cmd.proto.ident, + (0..idents.len()) + .map(|_| "{:?}".to_string()) + .collect::>() + .join(", "), + idents + .iter() + .zip(typed_params.iter()) + .map(|(name, ty)| if ty.contains("GLDEBUGPROC") { + format!(", \"\"") + } else { + format!(", {}", name) + }).collect::>() + .concat() + ); try!(writeln!(dest, "#[allow(non_snake_case, unused_variables, dead_code)] @@ -257,9 +279,11 @@ fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> })) } - writeln!(dest, - "}} + writeln!( + dest, + "}} unsafe impl __gl_imports::Send for {api} {{}}", - api = super::gen_struct_name(registry.api)) + api = super::gen_struct_name(registry.api) + ) } diff --git a/third_party/rust/gl_generator/generators/global_gen.rs b/third_party/rust/gl_generator/generators/global_gen.rs index cb1cf2c28cb8..ac737fa60b6c 100644 --- a/third_party/rust/gl_generator/generators/global_gen.rs +++ b/third_party/rust/gl_generator/generators/global_gen.rs @@ -20,7 +20,8 @@ pub struct GlobalGenerator; impl super::Generator for GlobalGenerator { fn write(&self, registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write + where + W: io::Write, { try!(write_header(dest)); try!(write_metaloadfn(dest)); @@ -39,23 +40,28 @@ impl super::Generator for GlobalGenerator { /// Creates a `__gl_imports` module which contains all the external symbols that we need for the /// bindings. fn write_header(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - r#" + writeln!( + dest, + r#" mod __gl_imports {{ pub use std::mem; pub use std::os::raw; }} - "#) + "# + ) } /// Creates the metaloadfn function for fallbacks fn write_metaloadfn(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - r#" + writeln!( + dest, + r#" #[inline(never)] fn metaloadfn(loadfn: &mut FnMut(&'static str) -> *const __gl_imports::raw::c_void, symbol: &'static str, @@ -69,32 +75,39 @@ fn write_metaloadfn(dest: &mut W) -> io::Result<()> }} ptr }} - "#) + "# + ) } /// Creates a `types` module which contains all the type aliases. /// /// See also `generators::gen_types`. fn write_type_aliases(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - try!(writeln!(dest, - r#" + try!(writeln!( + dest, + r#" pub mod types {{ #![allow(non_camel_case_types, non_snake_case, dead_code, missing_copy_implementations)] - "#)); + "# + )); try!(super::gen_types(registry.api, dest)); - writeln!(dest, - " + writeln!( + dest, + " }} - ") + " + ) } /// Creates all the `` elements at the root of the bindings. fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { for enm in ®istry.enums { try!(super::gen_enum_item(enm, "types::", dest)); @@ -108,7 +121,8 @@ fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> /// The function calls the corresponding function pointer stored in the `storage` module created /// by `write_ptrs`. fn write_fns(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { for cmd in ®istry.cmds { if let Some(v) = registry.aliases.get(&cmd.proto.ident) { @@ -134,7 +148,8 @@ fn write_fns(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates a `FnPtr` structure which contains the store for a single binding. fn write_fnptr_struct_def(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { writeln!(dest, " @@ -161,23 +176,27 @@ fn write_fnptr_struct_def(dest: &mut W) -> io::Result<()> /// Creates a `storage` module which contains a static `FnPtr` per GL command in the registry. fn write_ptrs(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - - try!(writeln!(dest, - "mod storage {{ + try!(writeln!( + dest, + "mod storage {{ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] use super::__gl_imports::raw; - use super::FnPtr;")); + use super::FnPtr;" + )); for c in ®istry.cmds { - try!(writeln!(dest, - "pub static mut {name}: FnPtr = FnPtr {{ + try!(writeln!( + dest, + "pub static mut {name}: FnPtr = FnPtr {{ f: super::missing_fn_panic as *const raw::c_void, is_loaded: false }};", - name = c.proto.ident)); + name = c.proto.ident + )); } writeln!(dest, "}}") @@ -188,16 +207,18 @@ fn write_ptrs(registry: &Registry, dest: &mut W) -> io::Result<()> /// Each module contains `is_loaded` and `load_with` which interact with the `storage` module /// created by `write_ptrs`. fn write_fn_mods(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { for c in ®istry.cmds { let fallbacks = match registry.aliases.get(&c.proto.ident) { Some(v) => { - let names = v.iter() + let names = v + .iter() .map(|name| format!("\"{}\"", super::gen_symbol_name(registry.api, &name[..]))) .collect::>(); format!("&[{}]", names.join(", ")) - } + }, None => "&[]".to_string(), }; let fnname = &c.proto.ident[..]; @@ -234,22 +255,26 @@ fn write_fn_mods(registry: &Registry, dest: &mut W) -> io::Result<()> /// /// This function is the mock that is called if the real function could not be called. fn write_panicking_fns(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - "#[inline(never)] + writeln!( + dest, + "#[inline(never)] fn missing_fn_panic() -> ! {{ panic!(\"{api} function was not loaded\") }} ", - api = registry.api) + api = registry.api + ) } /// Creates the `load_with` function. /// /// The function calls `load_with` in each module created by `write_fn_mods`. fn write_load_fn(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { try!(writeln!(dest, " @@ -263,13 +288,17 @@ fn write_load_fn(registry: &Registry, dest: &mut W) -> io::Result<()> ")); for c in ®istry.cmds { - try!(writeln!(dest, - "{cmd_name}::load_with(&mut loadfn);", - cmd_name = &c.proto.ident[..])); + try!(writeln!( + dest, + "{cmd_name}::load_with(&mut loadfn);", + cmd_name = &c.proto.ident[..] + )); } - writeln!(dest, - " + writeln!( + dest, + " }} - ") + " + ) } diff --git a/third_party/rust/gl_generator/generators/mod.rs b/third_party/rust/gl_generator/generators/mod.rs index 83d346e6fcea..659d2ecaf4bd 100644 --- a/third_party/rust/gl_generator/generators/mod.rs +++ b/third_party/rust/gl_generator/generators/mod.rs @@ -12,20 +12,24 @@ // See the License for the specific language governing permissions and // limitations under the License. -use Api; -use registry::{Enum, Registry, Cmd}; +use registry::{Cmd, Enum, Registry}; use std::io; +use Api; pub mod debug_struct_gen; pub mod global_gen; pub mod static_gen; -pub mod struct_gen; pub mod static_struct_gen; +pub mod struct_gen; /// Trait for a bindings generator. +/// +/// See https://github.com/brendanzab/gl-rs/tree/master/gl_generator#generator-types pub trait Generator { /// Builds the GL bindings. - fn write(&self, registry: &Registry, dest: &mut W) -> io::Result<()> where W: io::Write; + fn write(&self, registry: &Registry, dest: &mut W) -> io::Result<()> + where + W: io::Write; } pub fn gen_struct_name(api: Api) -> &'static str { @@ -43,7 +47,8 @@ pub fn gen_struct_name(api: Api) -> &'static str { /// This function generates a `const name: type = value;` item. pub fn gen_enum_item(enm: &Enum, types_prefix: &str, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { writeln!(dest, "#[allow(dead_code, non_upper_case_globals)] pub const {ident}: {types_prefix}{ty} = {value}{cast_suffix};", @@ -63,7 +68,8 @@ pub fn gen_enum_item(enm: &Enum, types_prefix: &str, dest: &mut W) -> io::Res /// Aliases are either `pub type = ...` or `#[repr(C)] pub struct ... { ... }` and contain all the /// things that we can't obtain from the XML files. pub fn gen_types(api: Api, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { if let Api::Egl = api { try!(writeln!(dest, "{}", include_str!("templates/types/egl.rs"))); @@ -75,7 +81,7 @@ pub fn gen_types(api: Api, dest: &mut W) -> io::Result<()> match api { Api::Glx => try!(writeln!(dest, "{}", include_str!("templates/types/glx.rs"))), Api::Wgl => try!(writeln!(dest, "{}", include_str!("templates/types/wgl.rs"))), - _ => {} + _ => {}, } Ok(()) diff --git a/third_party/rust/gl_generator/generators/static_gen.rs b/third_party/rust/gl_generator/generators/static_gen.rs index cbab248b835b..8d15de0103a3 100644 --- a/third_party/rust/gl_generator/generators/static_gen.rs +++ b/third_party/rust/gl_generator/generators/static_gen.rs @@ -20,7 +20,8 @@ pub struct StaticGenerator; impl super::Generator for StaticGenerator { fn write(&self, registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write + where + W: io::Write, { try!(write_header(dest)); try!(write_type_aliases(registry, dest)); @@ -33,40 +34,49 @@ impl super::Generator for StaticGenerator { /// Creates a `__gl_imports` module which contains all the external symbols that we need for the /// bindings. fn write_header(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - r#" + writeln!( + dest, + r#" mod __gl_imports {{ pub use std::mem; pub use std::os::raw; }} - "#) + "# + ) } /// Creates a `types` module which contains all the type aliases. /// /// See also `generators::gen_types`. fn write_type_aliases(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - try!(writeln!(dest, - r#" + try!(writeln!( + dest, + r#" pub mod types {{ #![allow(non_camel_case_types, non_snake_case, dead_code, missing_copy_implementations)] - "#)); + "# + )); try!(super::gen_types(registry.api, dest)); - writeln!(dest, - " + writeln!( + dest, + " }} - ") + " + ) } /// Creates all the `` elements at the root of the bindings. fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { for enm in ®istry.enums { try!(super::gen_enum_item(enm, "types::", dest)); @@ -79,15 +89,19 @@ fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> /// /// These are foreign functions, they don't have any content. fn write_fns(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - try!(writeln!(dest, - " + try!(writeln!( + dest, + " #[allow(non_snake_case, unused_variables, dead_code)] - extern \"system\" {{")); + extern \"system\" {{" + )); for cmd in ®istry.cmds { - try!(writeln!(dest, + try!(writeln!( + dest, "#[link_name=\"{symbol}\"] pub fn {name}({params}) -> {return_suffix};", symbol = super::gen_symbol_name(registry.api, &cmd.proto.ident), diff --git a/third_party/rust/gl_generator/generators/static_struct_gen.rs b/third_party/rust/gl_generator/generators/static_struct_gen.rs index 9ec604e713fd..c03a3e09dde3 100644 --- a/third_party/rust/gl_generator/generators/static_struct_gen.rs +++ b/third_party/rust/gl_generator/generators/static_struct_gen.rs @@ -20,7 +20,8 @@ pub struct StaticStructGenerator; impl super::Generator for StaticStructGenerator { fn write(&self, registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write + where + W: io::Write, { try!(write_header(dest)); try!(write_type_aliases(registry, dest)); @@ -35,28 +36,34 @@ impl super::Generator for StaticStructGenerator { /// Creates a `__gl_imports` module which contains all the external symbols that we need for the /// bindings. fn write_header(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - r#" + writeln!( + dest, + r#" mod __gl_imports {{ pub use std::mem; pub use std::os::raw; }} - "#) + "# + ) } /// Creates a `types` module which contains all the type aliases. /// /// See also `generators::gen_types`. fn write_type_aliases(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - try!(writeln!(dest, - r#" + try!(writeln!( + dest, + r#" pub mod types {{ #![allow(non_camel_case_types, non_snake_case, dead_code, missing_copy_implementations)] - "#)); + "# + )); try!(super::gen_types(registry.api, dest)); @@ -65,7 +72,8 @@ fn write_type_aliases(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates all the `` elements at the root of the bindings. fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { for enm in ®istry.enums { try!(super::gen_enum_item(enm, "types::", dest)); @@ -78,9 +86,12 @@ fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> /// /// The name of the struct corresponds to the namespace. fn write_struct(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, " + writeln!( + dest, + " #[allow(non_camel_case_types, non_snake_case, dead_code)] #[derive(Copy, Clone)] pub struct {api};", @@ -90,20 +101,22 @@ fn write_struct(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates the `impl` of the structure created by `write_struct`. fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { try!(writeln!(dest, "impl {api} {{ /// Stub function. #[allow(dead_code)] - pub fn load_with(mut _loadfn: F) -> {api} where F: FnMut(&str) -> *const __gl_imports::raw::c_void {{ + pub fn load_with(mut _loadfn: F) -> {api} where F: FnMut(&'static str) -> *const __gl_imports::raw::c_void {{ {api} }}", api = super::gen_struct_name(registry.api), )); for cmd in ®istry.cmds { - try!(writeln!(dest, + try!(writeln!( + dest, "#[allow(non_snake_case)] // #[allow(unused_variables)] #[allow(dead_code)] @@ -125,18 +138,21 @@ fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> /// /// These are foreign functions, they don't have any content. fn write_fns(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - - try!(writeln!(dest, - " + try!(writeln!( + dest, + " #[allow(non_snake_case)] #[allow(unused_variables)] #[allow(dead_code)] - extern \"system\" {{")); + extern \"system\" {{" + )); for cmd in ®istry.cmds { - try!(writeln!(dest, + try!(writeln!( + dest, "#[link_name=\"{symbol}\"] fn {name}({params}) -> {return_suffix};", symbol = super::gen_symbol_name(registry.api, &cmd.proto.ident), name = cmd.proto.ident, diff --git a/third_party/rust/gl_generator/generators/struct_gen.rs b/third_party/rust/gl_generator/generators/struct_gen.rs index c74dd0956c70..a8c03d06436c 100644 --- a/third_party/rust/gl_generator/generators/struct_gen.rs +++ b/third_party/rust/gl_generator/generators/struct_gen.rs @@ -20,7 +20,8 @@ pub struct StructGenerator; impl super::Generator for StructGenerator { fn write(&self, registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write + where + W: io::Write, { try!(write_header(dest)); try!(write_type_aliases(registry, dest)); @@ -36,29 +37,35 @@ impl super::Generator for StructGenerator { /// Creates a `__gl_imports` module which contains all the external symbols that we need for the /// bindings. fn write_header(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - r#" + writeln!( + dest, + r#" mod __gl_imports {{ pub use std::mem; pub use std::marker::Send; pub use std::os::raw; }} - "#) + "# + ) } /// Creates a `types` module which contains all the type aliases. /// /// See also `generators::gen_types`. fn write_type_aliases(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - try!(writeln!(dest, - r#" + try!(writeln!( + dest, + r#" pub mod types {{ #![allow(non_camel_case_types, non_snake_case, dead_code, missing_copy_implementations)] - "#)); + "# + )); try!(super::gen_types(registry.api, dest)); @@ -67,7 +74,8 @@ fn write_type_aliases(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates all the `` elements at the root of the bindings. fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { for enm in ®istry.enums { try!(super::gen_enum_item(enm, "types::", dest)); @@ -78,10 +86,12 @@ fn write_enums(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates a `FnPtr` structure which contains the store for a single binding. fn write_fnptr_struct_def(dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - " + writeln!( + dest, + " #[allow(dead_code, missing_copy_implementations)] #[derive(Clone)] pub struct FnPtr {{ @@ -113,35 +123,42 @@ fn write_fnptr_struct_def(dest: &mut W) -> io::Result<()> self.is_loaded }} }} - ") + " + ) } /// Creates a `panicking` module which contains one function per GL command. /// /// These functions are the mocks that are called if the real function could not be loaded. fn write_panicking_fns(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - writeln!(dest, - "#[inline(never)] + writeln!( + dest, + "#[inline(never)] fn missing_fn_panic() -> ! {{ panic!(\"{api} function was not loaded\") }}", - api = registry.api) + api = registry.api + ) } /// Creates a structure which stores all the `FnPtr` of the bindings. /// /// The name of the struct corresponds to the namespace. fn write_struct(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { - try!(writeln!(dest, - " + try!(writeln!( + dest, + " #[allow(non_camel_case_types, non_snake_case, dead_code)] #[derive(Clone)] pub struct {api} {{", - api = super::gen_struct_name(registry.api))); + api = super::gen_struct_name(registry.api) + )); for cmd in ®istry.cmds { if let Some(v) = registry.aliases.get(&cmd.proto.ident) { @@ -156,7 +173,8 @@ fn write_struct(registry: &Registry, dest: &mut W) -> io::Result<()> /// Creates the `impl` of the structure created by `write_struct`. fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> - where W: io::Write +where + W: io::Write, { try!(writeln!(dest, "impl {api} {{ @@ -189,16 +207,17 @@ fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> api = super::gen_struct_name(registry.api))); for cmd in ®istry.cmds { - try!(writeln!(dest, + try!(writeln!( + dest, "{name}: FnPtr::new(metaloadfn(\"{symbol}\", &[{fallbacks}])),", name = cmd.proto.ident, symbol = super::gen_symbol_name(registry.api, &cmd.proto.ident), fallbacks = match registry.aliases.get(&cmd.proto.ident) { - Some(fbs) => { - fbs.iter() - .map(|name| format!("\"{}\"", super::gen_symbol_name(registry.api, &name))) - .collect::>().join(", ") - }, + Some(fbs) => fbs + .iter() + .map(|name| format!("\"{}\"", super::gen_symbol_name(registry.api, &name))) + .collect::>() + .join(", "), None => format!(""), }, )) @@ -206,9 +225,11 @@ fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> try!(writeln!(dest, "_priv: ()")); - try!(writeln!(dest, - "}} - }}")); + try!(writeln!( + dest, + "}} + }}" + )); for cmd in ®istry.cmds { try!(writeln!(dest, @@ -225,9 +246,11 @@ fn write_impl(registry: &Registry, dest: &mut W) -> io::Result<()> )) } - writeln!(dest, - "}} + writeln!( + dest, + "}} unsafe impl __gl_imports::Send for {api} {{}}", - api = super::gen_struct_name(registry.api)) + api = super::gen_struct_name(registry.api) + ) } diff --git a/third_party/rust/gl_generator/lib.rs b/third_party/rust/gl_generator/lib.rs index e49582291738..ebeb07be2556 100644 --- a/third_party/rust/gl_generator/lib.rs +++ b/third_party/rust/gl_generator/lib.rs @@ -71,11 +71,11 @@ mod generators; mod registry; -pub use generators::Generator; pub use generators::debug_struct_gen::DebugStructGenerator; pub use generators::global_gen::GlobalGenerator; pub use generators::static_gen::StaticGenerator; pub use generators::static_struct_gen::StaticStructGenerator; pub use generators::struct_gen::StructGenerator; +pub use generators::Generator; pub use registry::*; diff --git a/third_party/rust/gl_generator/registry/mod.rs b/third_party/rust/gl_generator/registry/mod.rs index 73642aeda3aa..c7cf6ee472a9 100644 --- a/third_party/rust/gl_generator/registry/mod.rs +++ b/third_party/rust/gl_generator/registry/mod.rs @@ -115,20 +115,18 @@ pub struct Registry { } impl Registry { - pub fn new<'a, Exts>(api: Api, - version: (u8, u8), - profile: Profile, - fallbacks: Fallbacks, - extensions: Exts) - -> Registry - where Exts: AsRef<[&'a str]> + pub fn new<'a, Exts>( + api: Api, + version: (u8, u8), + profile: Profile, + fallbacks: Fallbacks, + extensions: Exts, + ) -> Registry + where + Exts: AsRef<[&'a str]>, { let (major, minor) = version; - let extensions = extensions - .as_ref() - .iter() - .map(<&str>::to_string) - .collect(); + let extensions = extensions.as_ref().iter().map(<&str>::to_string).collect(); let filter = parse::Filter { api: api, @@ -149,8 +147,9 @@ impl Registry { } pub fn write_bindings(&self, generator: G, output: &mut W) -> io::Result<()> - where G: Generator, - W: io::Write + where + G: Generator, + W: io::Write, { generator.write(&self, output) } diff --git a/third_party/rust/gl_generator/registry/parse.rs b/third_party/rust/gl_generator/registry/parse.rs index 0e8a0ca3a01f..ea7d8977c7b2 100644 --- a/third_party/rust/gl_generator/registry/parse.rs +++ b/third_party/rust/gl_generator/registry/parse.rs @@ -19,11 +19,11 @@ use std::collections::btree_map::Entry; use std::collections::{BTreeMap, BTreeSet}; use std::io; use xml::attribute::OwnedAttribute; -use xml::EventReader as XmlEventReader; use xml::reader::XmlEvent; +use xml::EventReader as XmlEventReader; -use {Fallbacks, Api, Profile}; use registry::{Binding, Cmd, Enum, GlxOpcode, Registry}; +use {Api, Fallbacks, Profile}; pub fn from_xml(src: R, filter: Filter) -> Registry { XmlEventReader::new(src) @@ -41,8 +41,9 @@ struct Attribute { impl Attribute { fn new(key: Key, value: Value) -> Attribute - where Key: ToString, - Value: ToString + where + Key: ToString, + Value: ToString, { Attribute { key: key.to_string(), @@ -69,10 +70,12 @@ impl ParseEvent { match event { XmlEvent::StartDocument { .. } => None, XmlEvent::EndDocument => None, - XmlEvent::StartElement { name, attributes, .. } => { + XmlEvent::StartElement { + name, attributes, .. + } => { let attributes = attributes.into_iter().map(Attribute::from).collect(); Some(ParseEvent::Start(name.local_name, attributes)) - } + }, XmlEvent::EndElement { name } => Some(ParseEvent::End(name.local_name)), XmlEvent::Characters(chars) => Some(ParseEvent::Text(chars)), XmlEvent::ProcessingInstruction { .. } => None, @@ -83,16 +86,17 @@ impl ParseEvent { } } -fn api_from_str(src: &str) -> Result { +fn api_from_str(src: &str) -> Result, ()> { match src { - "gl" => Ok(Api::Gl), - "glx" => Ok(Api::Glx), - "wgl" => Ok(Api::Wgl), - "egl" => Ok(Api::Egl), - "glcore" => Ok(Api::GlCore), - "gles1" => Ok(Api::Gles1), - "gles2" => Ok(Api::Gles2), - "glsc2" => Ok(Api::Glsc2), + "gl" => Ok(Some(Api::Gl)), + "glx" => Ok(Some(Api::Glx)), + "wgl" => Ok(Some(Api::Wgl)), + "egl" => Ok(Some(Api::Egl)), + "glcore" => Ok(Some(Api::GlCore)), + "gles1" => Ok(Some(Api::Gles1)), + "gles2" => Ok(Some(Api::Gles2)), + "glsc2" => Ok(Some(Api::Glsc2)), + "disabled" => Ok(None), _ => Err(()), } } @@ -193,7 +197,7 @@ fn make_egl_enum(ident: String, ty: Option, value: String, alias: Option } } else { match value.chars().next() { - Some('-') | Some('0' ... '9') => (), + Some('-') | Some('0'...'9') => (), _ => panic!("Unexpected value format: {}", value), } @@ -217,7 +221,6 @@ fn make_egl_enum(ident: String, ty: Option, value: String, alias: Option } } - fn trim_cmd_prefix(ident: &str, api: Api) -> &str { match api { Api::Gl | Api::GlCore | Api::Gles1 | Api::Gles2 | Api::Glsc2 => trim_str(ident, "gl"), @@ -232,10 +235,10 @@ fn merge_map(a: &mut BTreeMap>, b: BTreeMap { ent.get_mut().extend(v); - } + }, Entry::Vacant(ent) => { ent.insert(v); - } + }, } } } @@ -304,31 +307,29 @@ trait Parse: Sized + Iterator { // add enum namespace ParseEvent::Start(ref name, _) if name == "enums" => { enums.extend(self.consume_enums(filter.api)); - } + }, // add command namespace ParseEvent::Start(ref name, _) if name == "commands" => { let (new_cmds, new_aliases) = self.consume_cmds(filter.api); cmds.extend(new_cmds); merge_map(&mut aliases, new_aliases); - } + }, ParseEvent::Start(ref name, ref attributes) if name == "feature" => { debug!("Parsing feature: {:?}", attributes); features.push(Feature::convert(&mut self, &attributes)); - } + }, - ParseEvent::Start(ref name, _) if name == "extensions" => { - loop { - match self.next().unwrap() { - ParseEvent::Start(ref name, ref attributes) if name == "extension" => { - extensions.push(Extension::convert(&mut self, &attributes)); - } - ParseEvent::End(ref name) if name == "extensions" => break, - event => panic!("Unexpected message {:?}", event), - } + ParseEvent::Start(ref name, _) if name == "extensions" => loop { + match self.next().unwrap() { + ParseEvent::Start(ref name, ref attributes) if name == "extension" => { + extensions.push(Extension::convert(&mut self, &attributes)); + }, + ParseEvent::End(ref name) if name == "extensions" => break, + event => panic!("Unexpected message {:?}", event), } - } + }, // finished building the registry ParseEvent::End(ref name) if name == "registry" => break, @@ -376,9 +377,10 @@ trait Parse: Sized + Iterator { for extension in &extensions { if filter.extensions.contains(&extension.name) { if !extension.supported.contains(&filter.api) { - panic!("Requested {}, which doesn't support the {} API", - extension.name, - filter.api); + panic!( + "Requested {}, which doesn't support the {} API", + extension.name, filter.api + ); } for require in &extension.requires { desired_enums.extend(require.enums.iter().map(|x| x.clone())); @@ -388,17 +390,17 @@ trait Parse: Sized + Iterator { } let is_desired_enum = |e: &Enum| { - desired_enums.contains(&("GL_".to_string() + &e.ident)) || - desired_enums.contains(&("WGL_".to_string() + &e.ident)) || - desired_enums.contains(&("GLX_".to_string() + &e.ident)) || - desired_enums.contains(&("EGL_".to_string() + &e.ident)) + desired_enums.contains(&("GL_".to_string() + &e.ident)) + || desired_enums.contains(&("WGL_".to_string() + &e.ident)) + || desired_enums.contains(&("GLX_".to_string() + &e.ident)) + || desired_enums.contains(&("EGL_".to_string() + &e.ident)) }; let is_desired_cmd = |c: &Cmd| { - desired_cmds.contains(&("gl".to_string() + &c.proto.ident)) || - desired_cmds.contains(&("wgl".to_string() + &c.proto.ident)) || - desired_cmds.contains(&("glX".to_string() + &c.proto.ident)) || - desired_cmds.contains(&("egl".to_string() + &c.proto.ident)) + desired_cmds.contains(&("gl".to_string() + &c.proto.ident)) + || desired_cmds.contains(&("wgl".to_string() + &c.proto.ident)) + || desired_cmds.contains(&("glX".to_string() + &c.proto.ident)) + || desired_cmds.contains(&("egl".to_string() + &c.proto.ident)) }; Registry { @@ -428,7 +430,7 @@ trait Parse: Sized + Iterator { } else { panic!("Expected <{}>, found: <{}>", expected_name, name) } - } + }, event => panic!("Expected <{}>, found: {:?}", expected_name, event), } } @@ -444,16 +446,17 @@ trait Parse: Sized + Iterator { loop { match self.next().unwrap() { ParseEvent::End(ref name) if expected_name == name => break, - _ => {} + _ => {}, } } } - fn consume_two<'a, T: FromXml, U: FromXml>(&mut self, - one: &'a str, - two: &'a str, - end: &'a str) - -> (Vec, Vec) { + fn consume_two<'a, T: FromXml, U: FromXml>( + &mut self, + one: &'a str, + two: &'a str, + end: &'a str, + ) -> (Vec, Vec) { debug!("consume_two: looking for {} and {} until {}", one, two, end); let mut ones = Vec::new(); @@ -480,7 +483,7 @@ trait Parse: Sized + Iterator { } else { panic!("Unexpected element: <{:?} {:?}>", n, &attributes); } - } + }, ParseEvent::End(ref name) => { debug!("Found end element ", name); @@ -497,7 +500,7 @@ trait Parse: Sized + Iterator { } else { panic!("Unexpected end element {:?}", name); } - } + }, event => panic!("Unexpected message {:?}", event), } } @@ -508,13 +511,13 @@ trait Parse: Sized + Iterator { loop { match self.next().unwrap() { // ignores - ParseEvent::Text(_) => {} + ParseEvent::Text(_) => {}, ParseEvent::Start(ref name, _) if name == "unused" => self.skip_to_end("unused"), // add enum definition ParseEvent::Start(ref name, ref attributes) if name == "enum" => { enums.push(self.consume_enum(api, attributes)); - } + }, // finished building the namespace ParseEvent::End(ref name) if name == "enums" => break, @@ -534,7 +537,7 @@ trait Parse: Sized + Iterator { match api { Api::Egl => make_egl_enum(ident, ty, value, alias), - _ => make_enum(ident, ty, value, alias) + _ => make_enum(ident, ty, value, alias), } } @@ -550,14 +553,14 @@ trait Parse: Sized + Iterator { match aliases.entry(v.clone()) { Entry::Occupied(mut ent) => { ent.get_mut().push(new.proto.ident.clone()); - } + }, Entry::Vacant(ent) => { ent.insert(vec![new.proto.ident.clone()]); - } + }, } } cmds.push(new); - } + }, // finished building the namespace ParseEvent::End(ref name) if name == "commands" => break, // error handling @@ -581,23 +584,23 @@ trait Parse: Sized + Iterator { match self.next().unwrap() { ParseEvent::Start(ref name, _) if name == "param" => { params.push(self.consume_binding("param")); - } + }, ParseEvent::Start(ref name, ref attributes) if name == "alias" => { alias = get_attribute(&attributes, "name"); alias = alias.map(|t| trim_cmd_prefix(&t, api).to_string()); self.consume_end_element("alias"); - } + }, ParseEvent::Start(ref name, ref attributes) if name == "vecequiv" => { vecequiv = get_attribute(&attributes, "vecequiv"); self.consume_end_element("vecequiv"); - } + }, ParseEvent::Start(ref name, ref attributes) if name == "glx" => { glx = Some(GlxOpcode { - opcode: get_attribute(&attributes, "opcode").unwrap(), - name: get_attribute(&attributes, "name"), - }); + opcode: get_attribute(&attributes, "opcode").unwrap(), + name: get_attribute(&attributes, "name"), + }); self.consume_end_element("glx"); - } + }, ParseEvent::End(ref name) if name == "command" => break, event => panic!("Expected , found: {:?}", event), } @@ -688,7 +691,7 @@ impl FromXml for Feature { fn convert(parser: &mut P, a: &[Attribute]) -> Feature { debug!("Doing a FromXml on Feature"); let api = get_attribute(a, "api").unwrap(); - let api = api_from_str(&api).unwrap(); + let api = api_from_str(&api).unwrap().unwrap(); let name = get_attribute(a, "name").unwrap(); let number = get_attribute(a, "number").unwrap(); @@ -713,15 +716,16 @@ impl FromXml for Extension { let supported = get_attribute(a, "supported") .unwrap() .split('|') - .map(api_from_str) - .map(Result::unwrap) + .filter_map(|api| { + api_from_str(api).unwrap_or_else(|()| panic!("unsupported API `{}`", api)) + }) .collect::>(); let mut require = Vec::new(); loop { match parser.next().unwrap() { ParseEvent::Start(ref name, ref attributes) if name == "require" => { require.push(FromXml::convert(parser, &attributes)); - } + }, ParseEvent::End(ref name) if name == "extension" => break, event => panic!("Unexpected message {:?}", event), } @@ -813,6 +817,7 @@ pub fn to_rust_ty>(ty: T) -> Cow<'static, str> { "const GLfloat *" => "*const types::GLfloat", "const GLhalfNV *" => "*const types::GLhalfNV", "const GLint *" => "*const types::GLint", + "const GLint*" => "*const types::GLint", "const GLint64 *" => "*const types::GLint64", "const GLint64EXT *" => "*const types::GLint64EXT", "const GLintptr *" => "*const types::GLintptr", @@ -988,7 +993,9 @@ pub fn to_rust_ty>(ty: T) -> Cow<'static, str> { "EGLDisplay" => "types::EGLDisplay", "EGLSurface" => "types::EGLSurface", "EGLClientBuffer" => "types::EGLClientBuffer", - "__eglMustCastToProperFunctionPointerType" => "types::__eglMustCastToProperFunctionPointerType", + "__eglMustCastToProperFunctionPointerType" => { + "types::__eglMustCastToProperFunctionPointerType" + }, "EGLImageKHR" => "types::EGLImageKHR", "EGLImage" => "types::EGLImage", "EGLOutputLayerEXT" => "types::EGLOutputLayerEXT", @@ -1019,15 +1026,16 @@ pub fn to_rust_ty>(ty: T) -> Cow<'static, str> { "EGLTimeKHR *" => "*mut types::EGLTimeKHR", "EGLOutputPortEXT *" => "*mut types::EGLOutputPortEXT", "EGLuint64KHR *" => "*mut types::EGLuint64KHR", + "const struct AHardwareBuffer *" => "*const __gl_imports::raw::c_void", // humm "GLeglClientBufferEXT" => "types::GLeglClientBufferEXT", - "GLVULKANPROCNV" => "type::GLVULKANPROCNV", - "EGLDEBUGPROCKHR" => "type::EGLDEBUGPROCKHR", - "EGLObjectKHR" => "type::EGLObjectKHR", - "EGLLabelKHR" => "type::EGLLabelKHR", - "EGLnsecsANDROID" => "type::EGLnsecsANDROID", - "EGLnsecsANDROID *" => "*mut type::EGLnsecsANDROID", - "EGLBoolean *" => "*mut type::EGLBoolean", + "GLVULKANPROCNV" => "types::GLVULKANPROCNV", + "EGLDEBUGPROCKHR" => "types::EGLDEBUGPROCKHR", + "EGLObjectKHR" => "types::EGLObjectKHR", + "EGLLabelKHR" => "types::EGLLabelKHR", + "EGLnsecsANDROID" => "types::EGLnsecsANDROID", + "EGLnsecsANDROID *" => "*mut types::EGLnsecsANDROID", + "EGLBoolean *" => "*mut types::EGLBoolean", // failure _ => panic!("Type conversion not implemented for `{}`", ty.as_ref()), @@ -1076,10 +1084,12 @@ mod tests { #[test] fn test_cast_0() { - let e = parse::make_enum("FOO".to_string(), - None, - "((EGLint)-1)".to_string(), - Some("BAR".to_string())); + let e = parse::make_enum( + "FOO".to_string(), + None, + "((EGLint)-1)".to_string(), + Some("BAR".to_string()), + ); assert_eq!(e.ident, "FOO"); assert_eq!((&*e.ty, &*e.value), ("EGLint", "-1")); assert_eq!(e.alias, Some("BAR".to_string())); @@ -1087,10 +1097,12 @@ mod tests { #[test] fn test_cast_1() { - let e = parse::make_enum("FOO".to_string(), - None, - "((EGLint)(-1))".to_string(), - Some("BAR".to_string())); + let e = parse::make_enum( + "FOO".to_string(), + None, + "((EGLint)(-1))".to_string(), + Some("BAR".to_string()), + ); assert_eq!(e.ident, "FOO"); assert_eq!((&*e.ty, &*e.value), ("EGLint", "(-1)")); assert_eq!(e.alias, Some("BAR".to_string())); @@ -1098,10 +1110,12 @@ mod tests { #[test] fn test_no_type() { - let e = parse::make_enum("FOO".to_string(), - None, - "value".to_string(), - Some("BAR".to_string())); + let e = parse::make_enum( + "FOO".to_string(), + None, + "value".to_string(), + Some("BAR".to_string()), + ); assert_eq!(e.ident, "FOO"); assert_eq!(e.value, "value"); assert_eq!(e.alias, Some("BAR".to_string())); @@ -1111,29 +1125,35 @@ mod tests { #[test] fn test_u() { - let e = parse::make_enum("FOO".to_string(), - Some("u".to_string()), - String::new(), - None); + let e = parse::make_enum( + "FOO".to_string(), + Some("u".to_string()), + String::new(), + None, + ); assert_eq!(e.ty, "GLuint"); } #[test] fn test_ull() { - let e = parse::make_enum("FOO".to_string(), - Some("ull".to_string()), - String::new(), - None); + let e = parse::make_enum( + "FOO".to_string(), + Some("ull".to_string()), + String::new(), + None, + ); assert_eq!(e.ty, "GLuint64"); } #[test] #[should_panic] fn test_unknown_type() { - parse::make_enum("FOO".to_string(), - Some("blargh".to_string()), - String::new(), - None); + parse::make_enum( + "FOO".to_string(), + Some("blargh".to_string()), + String::new(), + None, + ); } #[test] @@ -1160,10 +1180,12 @@ mod tests { #[test] fn test_cast_egl() { - let e = parse::make_egl_enum("FOO".to_string(), - None, - "EGL_CAST(EGLint,-1)".to_string(), - Some("BAR".to_string())); + let e = parse::make_egl_enum( + "FOO".to_string(), + None, + "EGL_CAST(EGLint,-1)".to_string(), + Some("BAR".to_string()), + ); assert_eq!(e.ident, "FOO"); assert_eq!((&*e.ty, &*e.value), ("EGLint", "-1")); assert_eq!(e.alias, Some("BAR".to_string())); @@ -1183,47 +1205,42 @@ mod tests { #[test] fn test_ull() { - let e = parse::make_egl_enum("FOO".to_string(), - Some("ull".to_string()), - "1234".to_string(), - None); + let e = parse::make_egl_enum( + "FOO".to_string(), + Some("ull".to_string()), + "1234".to_string(), + None, + ); assert_eq!(e.ty, "EGLuint64KHR"); } #[test] fn test_negative_value() { - let e = parse::make_egl_enum("FOO".to_string(), - None, - "-1".to_string(), - None); + let e = parse::make_egl_enum("FOO".to_string(), None, "-1".to_string(), None); assert_eq!(e.ty, "EGLint"); } #[test] #[should_panic] fn test_unknown_type() { - parse::make_egl_enum("FOO".to_string(), - Some("blargh".to_string()), - String::new(), - None); + parse::make_egl_enum( + "FOO".to_string(), + Some("blargh".to_string()), + String::new(), + None, + ); } #[test] #[should_panic] fn test_unknown_value() { - parse::make_egl_enum("FOO".to_string(), - None, - "a".to_string(), - None); + parse::make_egl_enum("FOO".to_string(), None, "a".to_string(), None); } #[test] #[should_panic] fn test_empty_value() { - parse::make_egl_enum("FOO".to_string(), - None, - String::new(), - None); + parse::make_egl_enum("FOO".to_string(), None, String::new(), None); } } @@ -1241,19 +1258,27 @@ mod tests { fn test_start_event() { let given = XmlEvent::StartElement { name: OwnedName::local("element"), - attributes: vec![OwnedAttribute::new(OwnedName::local("attr1"), "val1"), - OwnedAttribute::new(OwnedName::local("attr2"), "val2")], + attributes: vec![ + OwnedAttribute::new(OwnedName::local("attr1"), "val1"), + OwnedAttribute::new(OwnedName::local("attr2"), "val2"), + ], namespace: Namespace::empty(), }; - let expected = ParseEvent::Start("element".to_string(), - vec![Attribute::new("attr1", "val1"), - Attribute::new("attr2", "val2")]); + let expected = ParseEvent::Start( + "element".to_string(), + vec![ + Attribute::new("attr1", "val1"), + Attribute::new("attr2", "val2"), + ], + ); assert_eq!(ParseEvent::from_xml(given), Some(expected)); } #[test] fn test_end_element() { - let given = XmlEvent::EndElement { name: OwnedName::local("element") }; + let given = XmlEvent::EndElement { + name: OwnedName::local("element"), + }; let expected = ParseEvent::End("element".to_string()); assert_eq!(ParseEvent::from_xml(given), Some(expected)); } diff --git a/third_party/rust/gleam/.cargo-checksum.json b/third_party/rust/gleam/.cargo-checksum.json index 025c86c8a6ad..af285e9b1862 100644 --- a/third_party/rust/gleam/.cargo-checksum.json +++ b/third_party/rust/gleam/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"COPYING":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"0b59acef8c840e73d2c3ade921cac7fab2c0d26db5535fa320d965fd434e7184","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"2de24b7458d6b88f20324303a48acf64a4f2bbfb83d2ec4d6ff2b4f4a1fd2275","build.rs":"5dfbe1a39fdb8b91c91cef0581de3c62aa9617afe8427a5837cc7bc90e681adb","src/gl.rs":"84e1cdf6ad785de343b1b14398a5a75c94a12e43e5f1bc8e12d9cc5036468bf5","src/gl_fns.rs":"2c16ca840c519cd6bf73ced3a8334cbadd40e1d79c9eba47a4c67dbac729c222","src/gles_fns.rs":"b3cf28f9530948a13d55e79dd4310e3bb2deb3445c0d0076e19d81994d1230d8","src/lib.rs":"16610c19b45a3f26d56b379a3591aa2e4fc9477e7bd88f86b31c6ea32e834861"},"package":"2260952cc0393ca6f183e1a91a035c65c85ddb02505f3d53e5a775eb05946f44"} \ No newline at end of file +{"files":{"COPYING":"ec82b96487e9e778ee610c7ab245162464782cfa1f555c2299333f8dbe5c036a","Cargo.toml":"4bb3cfbab2fff43adff71eb4fa74ffa377c311775d89481fb5fb0c5959cd7724","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"62065228e42caebca7e7d7db1204cbb867033de5982ca4009928915e4095f3a3","README.md":"1acb12040be43a3582d5897f11870b3ffdcd7ce0f4f32de158175bb6b33ec0b7","build.rs":"5a9444663f14ecfc4a692409f946ed635c708b480a987b420a2dd15da600228d","src/gl.rs":"7f922e7a2816f12effe22f63e83cb691a0f2a5a92b6434f9af105b7beaa1997f","src/gl_fns.rs":"43302c33d181f897c07f79c677d0183bbb6c15dbffe1b92763c0531aec0b305e","src/gles_fns.rs":"fc67b18cf11c661f8b7031142c762dd1c011550bb9d606a6f78a443c30ba8240","src/lib.rs":"16610c19b45a3f26d56b379a3591aa2e4fc9477e7bd88f86b31c6ea32e834861"},"package":"4b47f5b15742aee359c7895ab98cf2cceecc89bb4feb6f4e42f802d7899877da"} \ No newline at end of file diff --git a/third_party/rust/gleam/COPYING b/third_party/rust/gleam/COPYING old mode 100755 new mode 100644 diff --git a/third_party/rust/gleam/Cargo.toml b/third_party/rust/gleam/Cargo.toml index 73d4ef6ecbea..7c2ce29e55b3 100644 --- a/third_party/rust/gleam/Cargo.toml +++ b/third_party/rust/gleam/Cargo.toml @@ -12,12 +12,12 @@ [package] name = "gleam" -version = "0.6.3" +version = "0.6.8" authors = ["The Servo Project Developers"] build = "build.rs" description = "Generated OpenGL bindings and wrapper for Servo." -documentation = "http://doc.servo.org/gleam/" +documentation = "https://doc.servo.org/gleam/" license = "Apache-2.0/MIT" repository = "https://github.com/servo/gleam" [build-dependencies.gl_generator] -version = "0.9" +version = "0.10" diff --git a/third_party/rust/gleam/LICENSE-APACHE b/third_party/rust/gleam/LICENSE-APACHE old mode 100755 new mode 100644 diff --git a/third_party/rust/gleam/LICENSE-MIT b/third_party/rust/gleam/LICENSE-MIT old mode 100755 new mode 100644 diff --git a/third_party/rust/gleam/README.md b/third_party/rust/gleam/README.md old mode 100755 new mode 100644 index da405dc4cf7a..1eaa2128fdab --- a/third_party/rust/gleam/README.md +++ b/third_party/rust/gleam/README.md @@ -1,6 +1,6 @@ servo-gl ======== -[Documentation](http://doc.servo.org/gleam/) +[Documentation](https://doc.servo.org/gleam/) OpenGL bindings for Servo diff --git a/third_party/rust/gleam/build.rs b/third_party/rust/gleam/build.rs old mode 100755 new mode 100644 index 65f8fa2a920b..47a7a5bdf85c --- a/third_party/rust/gleam/build.rs +++ b/third_party/rust/gleam/build.rs @@ -17,6 +17,7 @@ fn main() { "GL_APPLE_fence", "GL_APPLE_texture_range", "GL_ARB_blend_func_extended", + "GL_ARB_copy_image", "GL_ARB_get_program_binary", "GL_ARB_invalidate_subdata", "GL_ARB_texture_rectangle", @@ -25,12 +26,13 @@ fn main() { "GL_EXT_texture_filter_anisotropic", "GL_KHR_debug", ]; - let gl_reg = Registry::new(Api::Gl, (3, 3), Profile::Core, Fallbacks::All, gl_extensions); + let gl_reg = Registry::new(Api::Gl, (3, 3), Profile::Compatibility, Fallbacks::All, gl_extensions); gl_reg.write_bindings(gl_generator::StructGenerator, &mut file_gl) .unwrap(); // GLES 3.0 bindings let gles_extensions = [ + "GL_EXT_copy_image", "GL_EXT_debug_marker", "GL_EXT_disjoint_timer_query", "GL_EXT_shader_texture_lod", @@ -40,6 +42,7 @@ fn main() { "GL_KHR_debug", "GL_OES_EGL_image_external", "GL_OES_EGL_image", + "GL_OES_texture_half_float", ]; let gles_reg = Registry::new(Api::Gles2, (3, 0), Profile::Core, Fallbacks::All, gles_extensions); gles_reg.write_bindings(gl_generator::StructGenerator, &mut file_gles) diff --git a/third_party/rust/gleam/src/gl.rs b/third_party/rust/gleam/src/gl.rs old mode 100755 new mode 100644 index dcc24ed4719a..aa1050a5d5e7 --- a/third_party/rust/gleam/src/gl.rs +++ b/third_party/rust/gleam/src/gl.rs @@ -302,6 +302,22 @@ declare_gl_apis! { format: GLenum, ty: GLenum, output: &mut [u8]); + unsafe fn copy_image_sub_data(&self, + src_name: GLuint, + src_target: GLenum, + src_level: GLint, + src_x: GLint, + src_y: GLint, + src_z: GLint, + dst_name: GLuint, + dst_target: GLenum, + dst_level: GLint, + dst_x: GLint, + dst_y: GLint, + dst_z: GLint, + src_width: GLsizei, + src_height: GLsizei, + src_depth: GLsizei); fn invalidate_framebuffer(&self, target: GLenum, diff --git a/third_party/rust/gleam/src/gl_fns.rs b/third_party/rust/gleam/src/gl_fns.rs old mode 100755 new mode 100644 index c7c8814854db..3ce17a689c4a --- a/third_party/rust/gleam/src/gl_fns.rs +++ b/third_party/rust/gleam/src/gl_fns.rs @@ -667,6 +667,41 @@ impl Gl for GlFns { } } + unsafe fn copy_image_sub_data(&self, + src_name: GLuint, + src_target: GLenum, + src_level: GLint, + src_x: GLint, + src_y: GLint, + src_z: GLint, + dst_name: GLuint, + dst_target: GLenum, + dst_level: GLint, + dst_x: GLint, + dst_y: GLint, + dst_z: GLint, + src_width: GLsizei, + src_height: GLsizei, + src_depth: GLsizei) { + self.ffi_gl_.CopyImageSubData( + src_name, + src_target, + src_level, + src_x, + src_y, + src_z, + dst_name, + dst_target, + dst_level, + dst_x, + dst_y, + dst_z, + src_width, + src_height, + src_depth, + ); + } + fn invalidate_framebuffer(&self, target: GLenum, attachments: &[GLenum]) { diff --git a/third_party/rust/gleam/src/gles_fns.rs b/third_party/rust/gleam/src/gles_fns.rs old mode 100755 new mode 100644 index ec842eff5c5f..2aced15fca55 --- a/third_party/rust/gleam/src/gles_fns.rs +++ b/third_party/rust/gleam/src/gles_fns.rs @@ -681,6 +681,41 @@ impl Gl for GlesFns { panic!("not supported"); } + unsafe fn copy_image_sub_data(&self, + src_name: GLuint, + src_target: GLenum, + src_level: GLint, + src_x: GLint, + src_y: GLint, + src_z: GLint, + dst_name: GLuint, + dst_target: GLenum, + dst_level: GLint, + dst_x: GLint, + dst_y: GLint, + dst_z: GLint, + src_width: GLsizei, + src_height: GLsizei, + src_depth: GLsizei) { + self.ffi_gl_.CopyImageSubDataEXT( + src_name, + src_target, + src_level, + src_x, + src_y, + src_z, + dst_name, + dst_target, + dst_level, + dst_x, + dst_y, + dst_z, + src_width, + src_height, + src_depth, + ); + } + fn invalidate_framebuffer(&self, target: GLenum, attachments: &[GLenum]) { @@ -1516,14 +1551,30 @@ impl Gl for GlesFns { shader_type: GLuint, precision_type: GLuint) -> (GLint, GLint, GLint) { - let mut range = [0 as GLint, 0]; - let mut precision = 0 as GLint; + let (mut range, mut precision) = match precision_type { + // These values are for a 32-bit twos-complement integer format. + ffi::LOW_INT | + ffi::MEDIUM_INT | + ffi::HIGH_INT => ([31, 30], 0), + + // These values are for an IEEE single-precision floating-point format. + ffi::LOW_FLOAT | + ffi::MEDIUM_FLOAT | + ffi::HIGH_FLOAT => ([127, 127], 23), + + _ => unreachable!("invalid precision"), + }; + // This function is sometimes defined even though it's really just + // a stub, so we need to set range and precision as if it weren't + // defined before calling it. Suppress any error that might occur. unsafe { self.ffi_gl_.GetShaderPrecisionFormat(shader_type, precision_type, range.as_mut_ptr(), &mut precision); + let _ = self.ffi_gl_.GetError(); } + (range[0], range[1], precision) } diff --git a/third_party/rust/gleam/src/lib.rs b/third_party/rust/gleam/src/lib.rs old mode 100755 new mode 100644 diff --git a/third_party/rust/khronos_api/.cargo-checksum.json b/third_party/rust/khronos_api/.cargo-checksum.json index baea7949c998..7a705ae2dd86 100644 --- a/third_party/rust/khronos_api/.cargo-checksum.json +++ b/third_party/rust/khronos_api/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"e0120828d1aa70c40f47a6c7dc0cc08e089470d8faf8644e68836c31f44248b3","README.md":"45772358ebfb8a7554056ce7faab27c3dc73d881ba4be66891d39e4830657877","api/xml/gl.xml":"5c3d768a361dc998b3497e93c1e0d837615c942ab82ff17dfeed8c1917b74bbb","api/xml/glx.xml":"1862e651300ae36fa6621b23910f55f63f29cd3550c114312be27c204e9828c5","api/xml/wgl.xml":"27fdf88d0f9fae2b025820f28ee3cb67dfc0388e68532a135ca7043db0427a35","api_egl/api/egl.xml":"7b20c062af2fda6dd340f4d03983c49204d75067ed161f10f671c805ace692f7","api_webgl/extensions/ANGLE_instanced_arrays/extension.xml":"213f7e7636e8df0c390a18ad1339618335d7744970837998a191c275f7d1a95c","api_webgl/extensions/EXT_blend_minmax/extension.xml":"d1798c0faf13dfa7930032994f5a47c07b6f2f44b45d033059bfcffb7c1d579c","api_webgl/extensions/EXT_color_buffer_float/extension.xml":"48dacbcce0e0e96c206fc6dd2050266680ba24c2f6b254c3a6871c8715639d36","api_webgl/extensions/EXT_color_buffer_half_float/extension.xml":"1900351880046b495af97e6d38e9f3213538b133f74625a4dd73165d43e7710c","api_webgl/extensions/EXT_disjoint_timer_query/extension.xml":"b4df1205df86474e27459dc1cea3c75cba533d0245c38bb3ea5fe608612c512b","api_webgl/extensions/EXT_disjoint_timer_query_webgl2/extension.xml":"09cf6ddc69af0a032a5712df3808be30ff5fecaea0080ec73f464b87e4b3a313","api_webgl/extensions/EXT_float_blend/extension.xml":"5a298482adee7bb1fcc8f613a8aa9b61bb71bf5523fac56da45bb68136e451b8","api_webgl/extensions/EXT_frag_depth/extension.xml":"d19cf823811272352972ac4cb1d37405dcf63a91c48c1dd046e475487fecf9ea","api_webgl/extensions/EXT_sRGB/extension.xml":"7688ba25fa05558fbae72b21661e5bece2c36e899fe78da83bc8a172db9622fd","api_webgl/extensions/EXT_shader_texture_lod/extension.xml":"f1e5741d5d12d6e9a6bbc95049da2ec62ee55a4d1b6ec7b03e87e9f91282c6cb","api_webgl/extensions/EXT_texture_filter_anisotropic/extension.xml":"131ed0429a9951c05ae5c30859179f47c99b9bd6f47ca2825bdecf791f0188b6","api_webgl/extensions/OES_element_index_uint/extension.xml":"734f7a90af440ea559fa0fe777144aaef8acc7de94a8c3ce153a75ff85cb1f6b","api_webgl/extensions/OES_fbo_render_mipmap/extension.xml":"43bede667b814b80e15b5af463620c53f6fa9e1a610c2e9756ad2fa55b9f7589","api_webgl/extensions/OES_standard_derivatives/extension.xml":"2fa53259457d9f6042194bfb13c0db4b3c63d2d99d9e44f057d8fe4d5b28fe69","api_webgl/extensions/OES_texture_float/extension.xml":"42a782fcc2cafd3df9ea33c9259343c66b3fbd2ebfc216dc20ee6be53481f042","api_webgl/extensions/OES_texture_float_linear/extension.xml":"98041c4427f5abf741eb2c34e23f9b8c84090d4d5b4e2e0f1b04f9b53c73259a","api_webgl/extensions/OES_texture_half_float/extension.xml":"14cb4ce4e6f259fcb6ce0d988c4e81880299f28343cdcba4f7abbf8956207529","api_webgl/extensions/OES_texture_half_float_linear/extension.xml":"d2f29c9a9bf31e757fc8c6da277cdb813350a1504be773c3bd105bfa92e45502","api_webgl/extensions/OES_vertex_array_object/extension.xml":"8262ec860c2af3b23daacc27a17bcf29054bcc03baf59f90779c4e53fc469f41","api_webgl/extensions/WEBGL_color_buffer_float/extension.xml":"d68800fe416384a951fe45fdbcb324494d848cbecdecbdcacf7bbafe8a2aae93","api_webgl/extensions/WEBGL_compressed_texture_astc/extension.xml":"9ba9c29e7e09aa8ec950ec70c79eae42c6f844d354b49fc88d9f048318a9c400","api_webgl/extensions/WEBGL_compressed_texture_atc/extension.xml":"a8de4e909b3d7c29ff6ca58ff6bc91b14c298a12beded04c025bb0ecb1d74db2","api_webgl/extensions/WEBGL_compressed_texture_etc/extension.xml":"d926f0a7f533ea6ce43215a7e90f35064e1a51df539e04c49a2e918f69943aad","api_webgl/extensions/WEBGL_compressed_texture_etc1/extension.xml":"02a008b04a5b40e274023defe3a2fb94f06a2150c059ae703c282faa6b6b4b0e","api_webgl/extensions/WEBGL_compressed_texture_pvrtc/extension.xml":"1570f8ebb56480908e46706683182a097928e8e0a2e992e3eab8f1a2c16124c9","api_webgl/extensions/WEBGL_compressed_texture_s3tc/extension.xml":"87585ba713ad1a8dd5c04fd24a7068a0cf88799ea697e940752c68698de0c707","api_webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/extension.xml":"e22e01bd35b437adabfc7592f5eb6d750fdaabac61b0f79561fe58e860843993","api_webgl/extensions/WEBGL_debug_renderer_info/extension.xml":"af71073e0031b0296b7e5b609cdd272458cbae434a7fa31649054be0969a72e0","api_webgl/extensions/WEBGL_debug_shaders/extension.xml":"fc8c59747ee8cc289aa269c6ac5b6a45f7dc036d509209ace8db7062481a1abe","api_webgl/extensions/WEBGL_depth_texture/extension.xml":"5d91c9b8252b9f3a19f3f6a2f861a660d200446cfcaf09fa2a337e6f6b2dd5bd","api_webgl/extensions/WEBGL_draw_buffers/extension.xml":"9b465aa066d86ba044ad1604f6a3ce9f9e9a3afe3b4d36750a60870a67697fa1","api_webgl/extensions/WEBGL_get_buffer_sub_data_async/extension.xml":"abea14f4cb2012a04db6edc1219ad3da97bfc0975c4756f9d61ab3378a283cae","api_webgl/extensions/WEBGL_lose_context/extension.xml":"71defc6045fefdf7b14cd2d1fe4a432d504b2567e7acb1e77b8737aea7ba1bb0","api_webgl/extensions/WEBGL_multiview/extension.xml":"ac8368b843bb76afb9a82460ef619aa278be180f285964070ccedcd66213f0e0","api_webgl/extensions/WEBGL_security_sensitive_resources/extension.xml":"99634c2e0117d7abb9b44bbd64d8c4e8c8ebbcfe6342222dfc624b05e8532249","api_webgl/extensions/WEBGL_shared_resources/extension.xml":"90b6f51521fbb2ba23563cdfd2029cf28de1233aba4b2844b7d832b323c0fa10","api_webgl/extensions/proposals/EXT_clip_cull_distance/extension.xml":"a4f9b465b1e1efa0367a8fbbada7a6156ffb3e4ee1c677a0d220a7ea1402a260","api_webgl/extensions/proposals/WEBGL_debug/extension.xml":"c8cdbb65c17dfe4851e7a56094c492b835f76f06a9cdb1b3fd273584357864b1","api_webgl/extensions/proposals/WEBGL_dynamic_texture/extension.xml":"7f5bc906ba61037befd4acd9fc39209d2e4bd8eea20ba01f34ebe4700bfd1806","api_webgl/extensions/proposals/WEBGL_subarray_uploads/extension.xml":"87cde732f220d4b54faaef1e6d5efc6174849c1b54983908084659f525c7f40f","api_webgl/extensions/proposals/WEBGL_texture_multisample/extension.xml":"338f0fc6f62bf875a0f7b19e4c284ed48e5a76e791e55414843659cf402636da","api_webgl/extensions/proposals/WEBGL_texture_source_iframe/extension.xml":"378beada6abe201a0ebdb68a3935e8bf27f620ae2653d696a38df9e499808eda","api_webgl/extensions/proposals/WEBGL_video_texture/extension.xml":"b9e0ffa1cf37c827b9be82d71adcd40ce44d05e434a87d174b289c7a5b9d30b0","api_webgl/extensions/rejected/EXT_texture_storage/extension.xml":"9fb3883d1b6d73e09b03129a30845031e0b27c9003b9fb0e2f2b2b2d5a9dbb1e","api_webgl/extensions/rejected/OES_depth24/extension.xml":"159c541fc025c3d454887cdedd1ff5c19ed17e9356c63d95510d70c586502af7","api_webgl/extensions/rejected/WEBGL_debug_shader_precision/extension.xml":"f618d6f82e21cf78146e86c396a3d7b3dd51cf778ab2dc7a504834d835abc5c8","api_webgl/extensions/rejected/WEBGL_draw_elements_no_range_check/extension.xml":"a3a616760a9cca44ecca27e8a8afd49679974f1bf0dfd4624231bcffaf4aec54","api_webgl/extensions/rejected/WEBGL_subscribe_uniform/extension.xml":"7ec77103308177cdfa0efbc995f62151622c30bab46a4ee191e04520c51965ae","api_webgl/extensions/rejected/WEBGL_texture_from_depth_video/extension.xml":"eabf2a9003050f8ef5ceb4d5cc0fafc98977aef407fb4060d08d704884a3d462","api_webgl/extensions/template/extension.xml":"8da65e0a5d053bf36373c6fcfdf7d8fa2738c48345671cf61b62e30ba9cce117","api_webgl/specs/latest/1.0/webgl.idl":"9ffefd8ed7b99053f0db70966749e8f3d6398e1393367f2772dda6325daf3db8","api_webgl/specs/latest/2.0/webgl2.idl":"121a6d79dae3ce4483b60cf26ee2dbca2e402ad19658c0ba951a5726d49aed22","build.rs":"28156f946b5f8b2ac39237d8ff9070bae75eb0f8f6ac66e5df9c6a0998784d2b","src/lib.rs":"7f1378f4337b537d46a8d67f7224b2c2cc50a633d0326692711e3514374799f4"},"package":"037ab472c33f67b5fbd3e9163a2645319e5356fcd355efa6d4eb7fff4bbcb554"} \ No newline at end of file +{"files":{"Cargo.toml":"0ed811576ec355ab9dad30d38a8531f5a66490fd91479202530d12520f10d14d","README.md":"45772358ebfb8a7554056ce7faab27c3dc73d881ba4be66891d39e4830657877","api/xml/gl.xml":"7dae830ddacefd2af92aef2b438ff89f90fb5496f596dec8282b212eb4fc51e3","api/xml/glx.xml":"338cee03c97e78aa167dd667407ab973f4bc656c58cf9002aa54fa78b2f9ff32","api/xml/wgl.xml":"41e0a2182217b099b1628757956cb103cea9660e830f4d2f9fa07bf3a3679feb","api_egl/api/egl.xml":"523fc17745545daca85c5b107b4a4c1a23dd3de39f70e499c77249e3dd6569ec","api_webgl/extensions/ANGLE_instanced_arrays/extension.xml":"213f7e7636e8df0c390a18ad1339618335d7744970837998a191c275f7d1a95c","api_webgl/extensions/EXT_blend_minmax/extension.xml":"d1798c0faf13dfa7930032994f5a47c07b6f2f44b45d033059bfcffb7c1d579c","api_webgl/extensions/EXT_color_buffer_float/extension.xml":"48dacbcce0e0e96c206fc6dd2050266680ba24c2f6b254c3a6871c8715639d36","api_webgl/extensions/EXT_color_buffer_half_float/extension.xml":"1900351880046b495af97e6d38e9f3213538b133f74625a4dd73165d43e7710c","api_webgl/extensions/EXT_disjoint_timer_query/extension.xml":"5f3502d9359932bb19cb866ad01a35f774851e7290ef7cbafcaa0d67175a29d5","api_webgl/extensions/EXT_disjoint_timer_query_webgl2/extension.xml":"81f643d90164e86c2a98b4053d7f8db233dc3c3339422f3f575df7da9ba8a518","api_webgl/extensions/EXT_float_blend/extension.xml":"5a298482adee7bb1fcc8f613a8aa9b61bb71bf5523fac56da45bb68136e451b8","api_webgl/extensions/EXT_frag_depth/extension.xml":"d19cf823811272352972ac4cb1d37405dcf63a91c48c1dd046e475487fecf9ea","api_webgl/extensions/EXT_sRGB/extension.xml":"7688ba25fa05558fbae72b21661e5bece2c36e899fe78da83bc8a172db9622fd","api_webgl/extensions/EXT_shader_texture_lod/extension.xml":"f1e5741d5d12d6e9a6bbc95049da2ec62ee55a4d1b6ec7b03e87e9f91282c6cb","api_webgl/extensions/EXT_texture_compression_bptc/extension.xml":"823b0280845da20a584b3ad6e85052bb158c4e69add38c3f80899facdf9fda90","api_webgl/extensions/EXT_texture_compression_rgtc/extension.xml":"6b95c30aa46b81a4bcde2a07df0c89cded028387ee1cc3a7e5d0aabf5f0d219e","api_webgl/extensions/EXT_texture_filter_anisotropic/extension.xml":"131ed0429a9951c05ae5c30859179f47c99b9bd6f47ca2825bdecf791f0188b6","api_webgl/extensions/KHR_parallel_shader_compile/extension.xml":"6e13b581cae0c8a6f41a484d98e55bb805b599081f54cfe737253238fe797395","api_webgl/extensions/OES_element_index_uint/extension.xml":"734f7a90af440ea559fa0fe777144aaef8acc7de94a8c3ce153a75ff85cb1f6b","api_webgl/extensions/OES_fbo_render_mipmap/extension.xml":"43bede667b814b80e15b5af463620c53f6fa9e1a610c2e9756ad2fa55b9f7589","api_webgl/extensions/OES_standard_derivatives/extension.xml":"2fa53259457d9f6042194bfb13c0db4b3c63d2d99d9e44f057d8fe4d5b28fe69","api_webgl/extensions/OES_texture_float/extension.xml":"42a782fcc2cafd3df9ea33c9259343c66b3fbd2ebfc216dc20ee6be53481f042","api_webgl/extensions/OES_texture_float_linear/extension.xml":"98041c4427f5abf741eb2c34e23f9b8c84090d4d5b4e2e0f1b04f9b53c73259a","api_webgl/extensions/OES_texture_half_float/extension.xml":"14cb4ce4e6f259fcb6ce0d988c4e81880299f28343cdcba4f7abbf8956207529","api_webgl/extensions/OES_texture_half_float_linear/extension.xml":"d2f29c9a9bf31e757fc8c6da277cdb813350a1504be773c3bd105bfa92e45502","api_webgl/extensions/OES_vertex_array_object/extension.xml":"8262ec860c2af3b23daacc27a17bcf29054bcc03baf59f90779c4e53fc469f41","api_webgl/extensions/WEBGL_color_buffer_float/extension.xml":"d68800fe416384a951fe45fdbcb324494d848cbecdecbdcacf7bbafe8a2aae93","api_webgl/extensions/WEBGL_compressed_texture_astc/extension.xml":"9ba9c29e7e09aa8ec950ec70c79eae42c6f844d354b49fc88d9f048318a9c400","api_webgl/extensions/WEBGL_compressed_texture_etc/extension.xml":"d926f0a7f533ea6ce43215a7e90f35064e1a51df539e04c49a2e918f69943aad","api_webgl/extensions/WEBGL_compressed_texture_etc1/extension.xml":"02a008b04a5b40e274023defe3a2fb94f06a2150c059ae703c282faa6b6b4b0e","api_webgl/extensions/WEBGL_compressed_texture_pvrtc/extension.xml":"1570f8ebb56480908e46706683182a097928e8e0a2e992e3eab8f1a2c16124c9","api_webgl/extensions/WEBGL_compressed_texture_s3tc/extension.xml":"87585ba713ad1a8dd5c04fd24a7068a0cf88799ea697e940752c68698de0c707","api_webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/extension.xml":"e22e01bd35b437adabfc7592f5eb6d750fdaabac61b0f79561fe58e860843993","api_webgl/extensions/WEBGL_debug_renderer_info/extension.xml":"af71073e0031b0296b7e5b609cdd272458cbae434a7fa31649054be0969a72e0","api_webgl/extensions/WEBGL_debug_shaders/extension.xml":"fc8c59747ee8cc289aa269c6ac5b6a45f7dc036d509209ace8db7062481a1abe","api_webgl/extensions/WEBGL_depth_texture/extension.xml":"5d91c9b8252b9f3a19f3f6a2f861a660d200446cfcaf09fa2a337e6f6b2dd5bd","api_webgl/extensions/WEBGL_draw_buffers/extension.xml":"9b465aa066d86ba044ad1604f6a3ce9f9e9a3afe3b4d36750a60870a67697fa1","api_webgl/extensions/WEBGL_lose_context/extension.xml":"71defc6045fefdf7b14cd2d1fe4a432d504b2567e7acb1e77b8737aea7ba1bb0","api_webgl/extensions/WEBGL_multiview/extension.xml":"474fa0ccaa7150e32060fa9ff5357b43d08cfe34930118525a2e4bee698fda0a","api_webgl/extensions/WEBGL_security_sensitive_resources/extension.xml":"99634c2e0117d7abb9b44bbd64d8c4e8c8ebbcfe6342222dfc624b05e8532249","api_webgl/extensions/proposals/EXT_clip_cull_distance/extension.xml":"a4f9b465b1e1efa0367a8fbbada7a6156ffb3e4ee1c677a0d220a7ea1402a260","api_webgl/extensions/proposals/EXT_multi_draw_arrays/extension.xml":"47f3ab7d17e28152b7873db5da9afbee058a61caacebba6b7fd9df4a569683a3","api_webgl/extensions/proposals/WEBGL_blend_equation_advanced_coherent/extension.xml":"4c8d195e8cc21207e372ef596cfb58ada985289c6b1212fad912d8f0ad0563a8","api_webgl/extensions/proposals/WEBGL_debug/extension.xml":"c8cdbb65c17dfe4851e7a56094c492b835f76f06a9cdb1b3fd273584357864b1","api_webgl/extensions/proposals/WEBGL_dynamic_texture/extension.xml":"7f5bc906ba61037befd4acd9fc39209d2e4bd8eea20ba01f34ebe4700bfd1806","api_webgl/extensions/proposals/WEBGL_subarray_uploads/extension.xml":"87cde732f220d4b54faaef1e6d5efc6174849c1b54983908084659f525c7f40f","api_webgl/extensions/proposals/WEBGL_texture_multisample/extension.xml":"338f0fc6f62bf875a0f7b19e4c284ed48e5a76e791e55414843659cf402636da","api_webgl/extensions/proposals/WEBGL_texture_source_iframe/extension.xml":"378beada6abe201a0ebdb68a3935e8bf27f620ae2653d696a38df9e499808eda","api_webgl/extensions/proposals/WEBGL_video_texture/extension.xml":"b9e0ffa1cf37c827b9be82d71adcd40ce44d05e434a87d174b289c7a5b9d30b0","api_webgl/extensions/rejected/EXT_texture_storage/extension.xml":"9fb3883d1b6d73e09b03129a30845031e0b27c9003b9fb0e2f2b2b2d5a9dbb1e","api_webgl/extensions/rejected/OES_depth24/extension.xml":"159c541fc025c3d454887cdedd1ff5c19ed17e9356c63d95510d70c586502af7","api_webgl/extensions/rejected/WEBGL_compressed_texture_atc/extension.xml":"43eab8d74ffb5799f2410a884d79bd4574531070a53947c334d71910c5a9bdee","api_webgl/extensions/rejected/WEBGL_debug_shader_precision/extension.xml":"f618d6f82e21cf78146e86c396a3d7b3dd51cf778ab2dc7a504834d835abc5c8","api_webgl/extensions/rejected/WEBGL_draw_elements_no_range_check/extension.xml":"a3a616760a9cca44ecca27e8a8afd49679974f1bf0dfd4624231bcffaf4aec54","api_webgl/extensions/rejected/WEBGL_get_buffer_sub_data_async/extension.xml":"188b33f4972e400550bbd1be58f29d9a0bc24a8da09203edc2f3e6f1a595679b","api_webgl/extensions/rejected/WEBGL_shared_resources/extension.xml":"cab1d86d6c853c11acf42044c4caea97103c70440c87688979c9f1cc18d622a6","api_webgl/extensions/rejected/WEBGL_subscribe_uniform/extension.xml":"7ec77103308177cdfa0efbc995f62151622c30bab46a4ee191e04520c51965ae","api_webgl/extensions/rejected/WEBGL_texture_from_depth_video/extension.xml":"eabf2a9003050f8ef5ceb4d5cc0fafc98977aef407fb4060d08d704884a3d462","api_webgl/extensions/template/extension.xml":"8da65e0a5d053bf36373c6fcfdf7d8fa2738c48345671cf61b62e30ba9cce117","api_webgl/specs/latest/1.0/webgl.idl":"9bd8707845fb68ff349f95b320582160423ee4cdf47294cbd980933b3b25dae9","api_webgl/specs/latest/2.0/webgl2.idl":"4e9ba68c298e76e85f312f86d474975da4ce656e35c2ad4a8c706437d50253a1","build.rs":"88b55daa5f6f0c90e1ab906c08b74834671316bdadc88d7cc25adfa19fc57e62","src/lib.rs":"7f1378f4337b537d46a8d67f7224b2c2cc50a633d0326692711e3514374799f4"},"package":"62237e6d326bd5871cd21469323bf096de81f1618cd82cbaf5d87825335aeb49"} \ No newline at end of file diff --git a/third_party/rust/khronos_api/Cargo.toml b/third_party/rust/khronos_api/Cargo.toml index 1587f98dd8eb..508cfe255b84 100644 --- a/third_party/rust/khronos_api/Cargo.toml +++ b/third_party/rust/khronos_api/Cargo.toml @@ -12,11 +12,11 @@ [package] name = "khronos_api" -version = "2.2.0" +version = "3.0.0" authors = ["Brendan Zabarauskas ", "Corey Richardson", "Arseny Kapoulkine", "Pierre Krieger "] include = ["/README.md", "/src/**/*", "/Cargo.toml", "/build.rs", "/api/xml/**/*.xml", "/api_egl/api/**/*.xml", "/api_webgl/specs/latest/**/*.idl", "/api_webgl/extensions/**/extension.xml"] description = "The Khronos XML API Registry, exposed as byte string constants." -homepage = "https://github.com/brendanzab/gl-rs/khronos_api/" +homepage = "https://github.com/brendanzab/gl-rs/" documentation = "https://docs.rs/khronos_api" readme = "README.md" keywords = ["gl", "egl", "opengl", "khronos"] diff --git a/third_party/rust/khronos_api/api/xml/gl.xml b/third_party/rust/khronos_api/api/xml/gl.xml index 639f15a62653..324b11716c2b 100644 --- a/third_party/rust/khronos_api/api/xml/gl.xml +++ b/third_party/rust/khronos_api/api/xml/gl.xml @@ -1,7 +1,7 @@ -Copyright (c) 2013-2017 The Khronos Group Inc. +Copyright (c) 2013-2018 The Khronos Group Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -95,8 +95,8 @@ typedef unsigned int GLhandleARB; typedef unsigned short GLhalfARB; typedef unsigned short GLhalf; typedef GLint GLfixed; - typedef ptrdiff_t GLintptr; - typedef ptrdiff_t GLsizeiptr; + typedef khronos_intptr_t GLintptr; + typedef khronos_ssize_t GLsizeiptr; typedef int64_t GLint64; typedef uint64_t GLuint64; typedef ptrdiff_t GLintptrARB; @@ -199,15 +199,16 @@ typedef unsigned int GLhandleARB; - - - - - - + + + + + + + @@ -215,6 +216,41 @@ typedef unsigned int GLhandleARB; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -230,6 +266,7 @@ typedef unsigned int GLhandleARB; + @@ -250,6 +287,25 @@ typedef unsigned int GLhandleARB; + + + + + + + + + + + + + + + + + + + @@ -334,8 +390,11 @@ typedef unsigned int GLhandleARB; + + + @@ -721,6 +780,7 @@ typedef unsigned int GLhandleARB; + @@ -732,6 +792,7 @@ typedef unsigned int GLhandleARB; + @@ -741,10 +802,17 @@ typedef unsigned int GLhandleARB; + + + + + + + @@ -770,6 +838,8 @@ typedef unsigned int GLhandleARB; + + @@ -778,6 +848,7 @@ typedef unsigned int GLhandleARB; + @@ -785,6 +856,7 @@ typedef unsigned int GLhandleARB; + @@ -798,16 +870,19 @@ typedef unsigned int GLhandleARB; + + + @@ -830,6 +905,7 @@ typedef unsigned int GLhandleARB; + @@ -838,6 +914,8 @@ typedef unsigned int GLhandleARB; + + @@ -852,6 +930,7 @@ typedef unsigned int GLhandleARB; + @@ -879,6 +958,7 @@ typedef unsigned int GLhandleARB; + @@ -904,9 +984,11 @@ typedef unsigned int GLhandleARB; + + @@ -918,20 +1000,98 @@ typedef unsigned int GLhandleARB; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -943,14 +1103,20 @@ typedef unsigned int GLhandleARB; - + + + + + + + @@ -968,6 +1134,7 @@ typedef unsigned int GLhandleARB; + @@ -979,6 +1146,8 @@ typedef unsigned int GLhandleARB; + + @@ -1017,23 +1186,35 @@ typedef unsigned int GLhandleARB; + + + + + + + + + + + + @@ -1042,6 +1223,11 @@ typedef unsigned int GLhandleARB; + + + + + @@ -1052,6 +1238,13 @@ typedef unsigned int GLhandleARB; + + + + + + + @@ -1071,9 +1264,18 @@ typedef unsigned int GLhandleARB; + + + + + + + + + @@ -1085,13 +1287,23 @@ typedef unsigned int GLhandleARB; + + + + + + + + + + @@ -1099,13 +1311,20 @@ typedef unsigned int GLhandleARB; + + + + + + + @@ -1380,8 +1599,11 @@ typedef unsigned int GLhandleARB; + + + @@ -1389,12 +1611,16 @@ typedef unsigned int GLhandleARB; + + + + @@ -1457,6 +1683,7 @@ typedef unsigned int GLhandleARB; + @@ -1523,18 +1750,30 @@ typedef unsigned int GLhandleARB; + + + + + + + + + + + + @@ -1546,10 +1785,10 @@ typedef unsigned int GLhandleARB; - + - + @@ -1567,34 +1806,34 @@ typedef unsigned int GLhandleARB; - + - + - - + + - - + + - - - - + + + + @@ -1605,8 +1844,8 @@ typedef unsigned int GLhandleARB; - - + + @@ -1638,7 +1877,7 @@ typedef unsigned int GLhandleARB; - + @@ -2061,7 +2300,9 @@ typedef unsigned int GLhandleARB; + + @@ -2076,6 +2317,11 @@ typedef unsigned int GLhandleARB; + + + + + @@ -2239,6 +2485,10 @@ typedef unsigned int GLhandleARB; + + + + @@ -2304,11 +2554,16 @@ typedef unsigned int GLhandleARB; + + + + + @@ -2390,6 +2645,7 @@ typedef unsigned int GLhandleARB; + @@ -2496,6 +2752,10 @@ typedef unsigned int GLhandleARB; + + + + @@ -2581,9 +2841,9 @@ typedef unsigned int GLhandleARB; - + - + @@ -2658,11 +2918,13 @@ typedef unsigned int GLhandleARB; + + - + @@ -2687,6 +2949,7 @@ typedef unsigned int GLhandleARB; + @@ -3183,7 +3446,7 @@ typedef unsigned int GLhandleARB; - + @@ -3217,6 +3480,8 @@ typedef unsigned int GLhandleARB; + + @@ -3338,6 +3603,10 @@ typedef unsigned int GLhandleARB; + + + + @@ -3389,6 +3658,8 @@ typedef unsigned int GLhandleARB; + + @@ -3425,7 +3696,7 @@ typedef unsigned int GLhandleARB; - + @@ -3453,6 +3724,8 @@ typedef unsigned int GLhandleARB; + + @@ -3588,6 +3861,7 @@ typedef unsigned int GLhandleARB; + @@ -5495,7 +5769,8 @@ typedef unsigned int GLhandleARB; - + + @@ -5691,7 +5966,8 @@ typedef unsigned int GLhandleARB; - + + @@ -6678,7 +6954,7 @@ typedef unsigned int GLhandleARB; - + @@ -7741,6 +8017,10 @@ typedef unsigned int GLhandleARB; + + + + @@ -7767,7 +8047,11 @@ typedef unsigned int GLhandleARB; - + + + + + @@ -8557,7 +8841,22 @@ typedef unsigned int GLhandleARB; - + + + + + + + + + + + + + + + + @@ -8806,7 +9105,8 @@ typedef unsigned int GLhandleARB; - + + @@ -8816,7 +9116,7 @@ typedef unsigned int GLhandleARB; - + @@ -9365,7 +9665,13 @@ typedef unsigned int GLhandleARB; - + + + + + + + @@ -9569,7 +9875,7 @@ typedef unsigned int GLhandleARB; - + @@ -9709,7 +10015,9 @@ typedef unsigned int GLhandleARB; + + @@ -9730,7 +10038,7 @@ typedef unsigned int GLhandleARB; - + @@ -9739,7 +10047,36 @@ typedef unsigned int GLhandleARB; - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -9867,11 +10204,23 @@ typedef unsigned int GLhandleARB; - + + + + + + + + + + + + + - + @@ -9882,16 +10231,46 @@ typedef unsigned int GLhandleARB; - + - + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -9920,7 +10299,28 @@ typedef unsigned int GLhandleARB; - + + + + + + + + + + + + + + + + + + + + + + @@ -10266,6 +10666,7 @@ typedef unsigned int GLhandleARB; void glBeginTransformFeedback GLenum primitiveMode + void glBeginTransformFeedbackEXT @@ -10313,6 +10714,7 @@ typedef unsigned int GLhandleARB; GLenum target GLuint index GLuint buffer + void glBindBufferBaseEXT @@ -10350,6 +10752,7 @@ typedef unsigned int GLhandleARB; GLuint buffer GLintptr offset GLsizeiptr size + void glBindBufferRangeEXT @@ -10529,6 +10932,10 @@ typedef unsigned int GLhandleARB; GLsizei count const GLuint *samplers + + void glBindShadingRateImageNV + GLuint texture + GLuint glBindTexGenParameterEXT GLenum unit @@ -10982,7 +11389,7 @@ typedef unsigned int GLhandleARB; GLint dstY0 GLint dstX1 GLint dstY1 - GLbitfield mask + GLbitfield mask GLenum filter @@ -11010,7 +11417,7 @@ typedef unsigned int GLhandleARB; GLint dstY0 GLint dstX1 GLint dstY1 - GLbitfield mask + GLbitfield mask GLenum filter @@ -11026,7 +11433,7 @@ typedef unsigned int GLhandleARB; GLint dstY0 GLint dstX1 GLint dstY1 - GLbitfield mask + GLbitfield mask GLenum filter @@ -11036,6 +11443,12 @@ typedef unsigned int GLhandleARB; GLuint64EXT address GLsizeiptr length + + void glBufferAttachMemoryNV + GLenum target + GLuint memory + GLuint64 offset + void glBufferData GLenum target @@ -11069,14 +11482,14 @@ typedef unsigned int GLhandleARB; GLenum target GLsizeiptr size const void *data - GLbitfield flags + GLbitfield flags void glBufferStorageEXT GLenum target GLsizeiptr size const void *data - GLbitfield flags + GLbitfield flags @@ -11085,7 +11498,7 @@ typedef unsigned int GLhandleARB; GLintptr offset GLsizeiptr size GLeglClientBufferEXT clientBuffer - GLbitfield flags + GLbitfield flags void glBufferStorageMemEXT @@ -11207,24 +11620,28 @@ typedef unsigned int GLhandleARB; GLint drawbuffer GLfloat depth GLint stencil + void glClearBufferfv GLenum buffer GLint drawbuffer const GLfloat *value + void glClearBufferiv GLenum buffer GLint drawbuffer const GLint *value + void glClearBufferuiv GLenum buffer GLint drawbuffer const GLuint *value + void glClearColor @@ -11439,13 +11856,13 @@ typedef unsigned int GLhandleARB; GLenum glClientWaitSync GLsync sync - GLbitfield flags + GLbitfield flags GLuint64 timeout GLenum glClientWaitSyncAPPLE GLsync sync - GLbitfield flags + GLbitfield flags GLuint64 timeout @@ -11458,7 +11875,7 @@ typedef unsigned int GLhandleARB; void glClipControlEXT GLenum origin GLenum depth - + void glClipPlane @@ -11873,6 +12290,7 @@ typedef unsigned int GLhandleARB; GLboolean b GLboolean a + void glColorMaski @@ -12626,6 +13044,7 @@ typedef unsigned int GLhandleARB; GLintptr readOffset GLintptr writeOffset GLsizeiptr size + void glCopyBufferSubDataNV @@ -13587,7 +14006,7 @@ typedef unsigned int GLhandleARB; void glDeleteSemaphoresEXT GLsizei n - const GLuint *semaphores + const GLuint *semaphores void glDeleteShader @@ -13677,8 +14096,8 @@ typedef unsigned int GLhandleARB; void glDepthRange - GLdouble near - GLdouble far + GLdouble n + GLdouble f @@ -13791,6 +14210,7 @@ typedef unsigned int GLhandleARB; GLenum target GLuint index + void glDisableVariantClientStateEXT @@ -14192,6 +14612,15 @@ typedef unsigned int GLhandleARB; GLsizei count GLsizei width + + void glDrawMeshTasksNV + GLuint first + GLuint count + + + void glDrawMeshTasksIndirectNV + GLintptr indirect + void glDrawPixels GLsizei width @@ -14275,10 +14704,11 @@ typedef unsigned int GLhandleARB; GLfloat z GLfloat width GLfloat height + void glDrawTexfvOES - const GLfloat *coords + const GLfloat *coords void glDrawTexiOES @@ -14287,10 +14717,11 @@ typedef unsigned int GLhandleARB; GLint z GLint width GLint height + void glDrawTexivOES - const GLint *coords + const GLint *coords void glDrawTexsOES @@ -14299,10 +14730,11 @@ typedef unsigned int GLhandleARB; GLshort z GLshort width GLshort height + void glDrawTexsvOES - const GLshort *coords + const GLshort *coords void glDrawTextureNV @@ -14325,10 +14757,11 @@ typedef unsigned int GLhandleARB; GLfixed z GLfixed width GLfixed height + void glDrawTexxvOES - const GLfixed *coords + const GLfixed *coords void glDrawTransformFeedback @@ -14378,11 +14811,23 @@ typedef unsigned int GLhandleARB; GLenum target GLeglImageOES image + + void glEGLImageTargetTexStorageEXT + GLenum target + GLeglImageOES image + const GLint* attrib_list + void glEGLImageTargetTexture2DOES GLenum target GLeglImageOES image + + void glEGLImageTargetTextureStorageEXT + GLuint texture + GLeglImageOES image + const GLint* attrib_list + void glEdgeFlag GLboolean flag @@ -14452,6 +14897,7 @@ typedef unsigned int GLhandleARB; GLenum target GLuint index + void glEnableVariantClientStateEXT @@ -14564,10 +15010,11 @@ typedef unsigned int GLhandleARB; void glEndTilingQCOM - GLbitfield preserveMask + GLbitfield preserveMask void glEndTransformFeedback + void glEndTransformFeedbackEXT @@ -15109,6 +15556,9 @@ typedef unsigned int GLhandleARB; GLsizei n const GLenum *bufs + + void glFramebufferFetchBarrierEXT + void glFramebufferFetchBarrierQCOM @@ -15600,7 +16050,7 @@ typedef unsigned int GLhandleARB; void glGenSemaphoresEXT GLsizei n - GLuint *semaphores + GLuint *semaphores GLuint glGenSymbolsEXT @@ -15765,6 +16215,7 @@ typedef unsigned int GLhandleARB; GLsizei bufSize GLsizei *length GLchar *uniformBlockName + void glGetActiveUniformBlockiv @@ -15772,6 +16223,7 @@ typedef unsigned int GLhandleARB; GLuint uniformBlockIndex GLenum pname GLint *params + void glGetActiveUniformName @@ -15780,6 +16232,7 @@ typedef unsigned int GLhandleARB; GLsizei bufSize GLsizei *length GLchar *uniformName + void glGetActiveUniformsiv @@ -15788,6 +16241,7 @@ typedef unsigned int GLhandleARB; const GLuint *uniformIndices GLenum pname GLint *params + void glGetActiveVaryingNV @@ -15842,6 +16296,7 @@ typedef unsigned int GLhandleARB; GLuint index GLboolean *data + void glGetBooleani_v @@ -16436,6 +16891,7 @@ typedef unsigned int GLhandleARB; GLenum glGetGraphicsResetStatusEXT + GLenum glGetGraphicsResetStatusKHR @@ -16560,6 +17016,7 @@ typedef unsigned int GLhandleARB; GLuint index GLint *data + void glGetIntegeri_v @@ -16790,6 +17247,14 @@ typedef unsigned int GLhandleARB; GLenum pname GLfixed *params + + void glGetMemoryObjectDetachedResourcesuivNV + GLuint memory + GLenum pname + GLint first + GLsizei count + GLuint *params + void glGetMemoryObjectParameterivEXT GLuint memoryObject @@ -17336,7 +17801,7 @@ typedef unsigned int GLhandleARB; GLuint queryHandle GLuint flags GLsizei dataSize - GLvoid *data + void *data GLuint *bytesWritten @@ -17747,7 +18212,7 @@ typedef unsigned int GLhandleARB; void glGetQueryObjectivEXT GLuint id GLenum pname - GLint *params + GLint *params @@ -17782,7 +18247,7 @@ typedef unsigned int GLhandleARB; void glGetQueryObjectuivEXT GLuint id GLenum pname - GLuint *params + GLuint *params void glGetQueryiv @@ -17802,7 +18267,7 @@ typedef unsigned int GLhandleARB; void glGetQueryivEXT GLenum target GLenum pname - GLint *params + GLint *params void glGetRenderbufferParameteriv @@ -17941,6 +18406,19 @@ typedef unsigned int GLhandleARB; GLint *params + + void glGetShadingRateImagePaletteNV + GLuint viewport + GLuint entry + GLenum *rate + + + void glGetShadingRateSampleLocationivNV + GLenum rate + GLuint samples + GLuint index + GLint *location + void glGetSharpenTexFuncSGIS GLenum target @@ -17960,6 +18438,7 @@ typedef unsigned int GLhandleARB; const GLubyte *glGetStringi GLenum name GLuint index + GLuint glGetSubroutineIndex @@ -18340,6 +18819,7 @@ typedef unsigned int GLhandleARB; GLsizei *size GLenum *type GLchar *name + void glGetTransformFeedbackVaryingEXT @@ -18389,6 +18869,7 @@ typedef unsigned int GLhandleARB; GLuint glGetUniformBlockIndex GLuint program const GLchar *uniformBlockName + GLint glGetUniformBufferSizeEXT @@ -18401,6 +18882,7 @@ typedef unsigned int GLhandleARB; GLsizei uniformCount const GLchar *const*uniformNames GLuint *uniformIndices + GLint glGetUniformLocation @@ -19000,7 +19482,7 @@ typedef unsigned int GLhandleARB; GLenum format GLenum type GLsizei bufSize - void *pixels + void *pixels void glGetnTexImageARB @@ -19016,7 +19498,7 @@ typedef unsigned int GLhandleARB; GLuint program GLint location GLsizei bufSize - GLdouble *params + GLdouble *params void glGetnUniformdvARB @@ -19030,7 +19512,7 @@ typedef unsigned int GLhandleARB; GLuint program GLint location GLsizei bufSize - GLfloat *params + GLfloat *params void glGetnUniformfvARB @@ -19052,7 +19534,7 @@ typedef unsigned int GLhandleARB; GLuint program GLint location GLsizei bufSize - GLfloat *params + GLfloat *params @@ -19060,14 +19542,14 @@ typedef unsigned int GLhandleARB; GLuint program GLint location GLsizei bufSize - GLint64 *params + GLint64 *params void glGetnUniformiv GLuint program GLint location GLsizei bufSize - GLint *params + GLint *params void glGetnUniformivARB @@ -19089,7 +19571,7 @@ typedef unsigned int GLhandleARB; GLuint program GLint location GLsizei bufSize - GLint *params + GLint *params @@ -19097,14 +19579,14 @@ typedef unsigned int GLhandleARB; GLuint program GLint location GLsizei bufSize - GLuint64 *params + GLuint64 *params void glGetnUniformuiv GLuint program GLint location GLsizei bufSize - GLuint *params + GLuint *params void glGetnUniformuivARB @@ -19118,7 +19600,7 @@ typedef unsigned int GLhandleARB; GLuint program GLint location GLsizei bufSize - GLuint *params + GLuint *params @@ -19477,6 +19959,7 @@ typedef unsigned int GLhandleARB; GLenum target GLuint index + GLboolean glIsEnabledi @@ -20149,7 +20632,7 @@ typedef unsigned int GLhandleARB; GLenum target GLintptr offset GLsizeiptr length - GLbitfield access + GLbitfield access @@ -20227,7 +20710,7 @@ typedef unsigned int GLhandleARB; GLuint buffer GLintptr offset GLsizeiptr length - GLbitfield access + GLbitfield access void *glMapNamedBufferRangeEXT @@ -20554,15 +21037,15 @@ typedef unsigned int GLhandleARB; void glMemoryBarrier - GLbitfield barriers + GLbitfield barriers void glMemoryBarrierByRegion - GLbitfield barriers + GLbitfield barriers void glMemoryBarrierEXT - GLbitfield barriers + GLbitfield barriers @@ -20819,6 +21302,19 @@ typedef unsigned int GLhandleARB; GLsizei stride + + void glMultiDrawMeshTasksIndirectNV + GLintptr indirect + GLsizei drawcount + GLsizei stride + + + void glMultiDrawMeshTasksIndirectCountNV + GLintptr indirect + GLintptr drawcount + GLsizei maxdrawcount + GLsizei stride + void glMultiDrawRangeElementArrayAPPLE GLenum mode @@ -21744,7 +22240,7 @@ typedef unsigned int GLhandleARB; GLint dstY0 GLint dstX1 GLint dstY1 - GLbitfield mask + GLbitfield mask GLenum filter @@ -21753,7 +22249,7 @@ typedef unsigned int GLhandleARB; GLuint buffer GLintptr offset GLsizeiptr size - const GLvoid *data + const void *data void glMulticastCopyBufferSubDataNV @@ -21826,6 +22322,12 @@ typedef unsigned int GLhandleARB; GLuint signalGpu GLbitfield waitGpuMask + + void glNamedBufferAttachMemoryNV + GLuint buffer + GLuint memory + GLuint64 offset + void glNamedBufferData GLuint buffer @@ -21859,7 +22361,7 @@ typedef unsigned int GLhandleARB; GLuint buffer GLsizeiptr size const void *data - GLbitfield flags + GLbitfield flags void glNamedBufferStorageExternalEXT @@ -21867,14 +22369,14 @@ typedef unsigned int GLhandleARB; GLintptr offset GLsizeiptr size GLeglClientBufferEXT clientBuffer - GLbitfield flags + GLbitfield flags void glNamedBufferStorageEXT GLuint buffer GLsizeiptr size const void *data - GLbitfield flags + GLbitfield flags @@ -22159,6 +22661,15 @@ typedef unsigned int GLhandleARB; GLsizei width GLsizei height + + void glNamedRenderbufferStorageMultisampleAdvancedAMD + GLuint renderbuffer + GLsizei samples + GLsizei storageSamples + GLenum internalformat + GLsizei width + GLsizei height + void glNamedRenderbufferStorageMultisampleCoverageEXT GLuint renderbuffer @@ -22574,7 +23085,7 @@ typedef unsigned int GLhandleARB; GLuint firstPathName GLenum fontTarget const void *fontName - GLbitfield fontStyle + GLbitfield fontStyle GLuint firstGlyphIndex GLsizei numGlyphs GLuint pathParameterTemplate @@ -22584,7 +23095,7 @@ typedef unsigned int GLhandleARB; GLenum glPathGlyphIndexRangeNV GLenum fontTarget const void *fontName - GLbitfield fontStyle + GLbitfield fontStyle GLuint pathParameterTemplate GLfloat emScale GLuint baseAndCount[2] @@ -23131,9 +23642,11 @@ typedef unsigned int GLhandleARB; void glPrimitiveRestartIndexNV GLuint index + void glPrimitiveRestartNV + void glPrioritizeTextures @@ -24626,12 +25139,12 @@ typedef unsigned int GLhandleARB; void glQueryCounter GLuint id - GLenum target + GLenum target void glQueryCounterEXT GLuint id - GLenum target + GLenum target @@ -24647,7 +25160,7 @@ typedef unsigned int GLhandleARB; GLuint param - GLint glQueryResourceNV + GLint glQueryResourceNV GLenum queryType GLint tagId GLuint bufSize @@ -24877,7 +25390,7 @@ typedef unsigned int GLhandleARB; GLenum format GLenum type GLsizei bufSize - void *data + void *data void glReadnPixelsARB @@ -25047,6 +25560,15 @@ typedef unsigned int GLhandleARB; GLsizei width GLsizei height + + void glRenderbufferStorageMultisampleAdvancedAMD + GLenum target + GLsizei samples + GLsizei storageSamples + GLenum internalformat + GLsizei width + GLsizei height + void glRenderbufferStorageMultisampleCoverageNV GLenum target @@ -25277,6 +25799,11 @@ typedef unsigned int GLhandleARB; + + void glResetMemoryObjectParameterNV + GLuint memory + GLenum pname + void glResetMinmax GLenum target @@ -25512,6 +26039,19 @@ typedef unsigned int GLhandleARB; const GLint *v + + void glScissorExclusiveArrayvNV + GLuint first + GLsizei count + const GLint *v + + + void glScissorExclusiveNV + GLint x + GLint y + GLsizei width + GLsizei height + void glScissorIndexed GLuint index @@ -25947,6 +26487,27 @@ typedef unsigned int GLhandleARB; GLuint storageBlockIndex GLuint storageBlockBinding + + void glShadingRateImageBarrierNV + GLboolean synchronize + + + void glShadingRateImagePaletteNV + GLuint viewport + GLuint first + GLsizei count + const GLenum *rates + + + void glShadingRateSampleOrderNV + GLenum order + + + void glShadingRateSampleOrderCustomNV + GLenum rate + GLuint samples + const GLint *locations + void glSharpenTexFuncSGIS GLenum target @@ -26014,7 +26575,7 @@ typedef unsigned int GLhandleARB; GLuint y GLuint width GLuint height - GLbitfield preserveMask + GLbitfield preserveMask void glStateCaptureNV @@ -26276,6 +26837,12 @@ typedef unsigned int GLhandleARB; GLenum object GLuint name + + void glTexAttachMemoryNV + GLenum target + GLuint memory + GLuint64 offset + void glTexBuffer GLenum target @@ -26288,6 +26855,7 @@ typedef unsigned int GLhandleARB; GLenum internalformat GLuint buffer + void glTexBufferEXT @@ -27377,7 +27945,7 @@ typedef unsigned int GLhandleARB; GLsizei height GLsizei depth GLsizei layers - GLbitfield flags + GLbitfield flags void glTexSubImage1D @@ -27494,6 +28062,12 @@ typedef unsigned int GLhandleARB; const void *pixels + + void glTextureAttachMemoryNV + GLuint texture + GLuint memory + GLuint64 offset + void glTextureBarrier @@ -27539,6 +28113,17 @@ typedef unsigned int GLhandleARB; GLboolean alpha + + void glTextureFoveationParametersQCOM + GLuint texture + GLuint layer + GLuint focalPoint + GLfloat focalX + GLfloat focalY + GLfloat gainX + GLfloat gainY + GLfloat foveaArea + void glTextureImage1DEXT GLuint texture @@ -27892,7 +28477,7 @@ typedef unsigned int GLhandleARB; GLsizei height GLsizei depth GLsizei layers - GLbitfield flags + GLbitfield flags void glTextureSubImage1D @@ -28046,6 +28631,7 @@ typedef unsigned int GLhandleARB; GLsizei count const GLchar *const*varyings GLenum bufferMode + void glTransformFeedbackVaryingsEXT @@ -28674,6 +29260,7 @@ typedef unsigned int GLhandleARB; GLuint program GLuint uniformBlockIndex GLuint uniformBlockBinding + void glUniformBufferEXT @@ -28991,13 +29578,13 @@ typedef unsigned int GLhandleARB; void glUseProgramStages GLuint pipeline - GLbitfield stages + GLbitfield stages GLuint program void glUseProgramStagesEXT GLuint pipeline - GLbitfield stages + GLbitfield stages GLuint program @@ -29044,6 +29631,14 @@ typedef unsigned int GLhandleARB; GLsizei numTextureNames const GLuint *textureNames + + GLvdpauSurfaceNV glVDPAURegisterVideoSurfaceWithPictureStructureNV + const void *vdpSurface + GLenum target + GLsizei numTextureNames + const GLuint *textureNames + GLboolean isFrameStructure + void glVDPAUSurfaceAccessNV GLvdpauSurfaceNV surface @@ -33753,6 +34348,7 @@ typedef unsigned int GLhandleARB; + @@ -33774,8 +34370,7 @@ typedef unsigned int GLhandleARB; - - + @@ -34823,6 +35418,7 @@ typedef unsigned int GLhandleARB; + @@ -35816,7 +36412,6 @@ typedef unsigned int GLhandleARB; - @@ -147,6 +149,7 @@ + - - + + @@ -923,6 +935,12 @@ EGLint config_size EGLint *num_config + + EGLBoolean eglClientSignalSyncEXT + EGLDisplay dpy + EGLSync sync + const EGLAttrib *attrib_list + EGLint eglClientWaitSync EGLDisplay dpy @@ -1208,6 +1226,10 @@ EGLint eglGetError + + EGLClientBuffer eglGetNativeClientBufferANDROID + const struct AHardwareBuffer *buffer + EGLBoolean eglGetOutputLayersEXT EGLDisplay dpy @@ -1617,7 +1639,7 @@ EGLBoolean eglStreamConsumerGLTextureExternalAttribsNV EGLDisplay dpy EGLStreamKHR stream - EGLAttrib *attrib_list + const EGLAttrib *attrib_list EGLBoolean eglStreamConsumerOutputEXT @@ -1636,6 +1658,11 @@ EGLStreamKHR stream const EGLAttrib *attrib_list + + EGLBoolean eglStreamFlushNV + EGLDisplay dpy + EGLStreamKHR stream + EGLBoolean eglSurfaceAttrib EGLDisplay dpy @@ -1690,6 +1717,12 @@ EGLDisplay dpy EGLSurface surface + + EGLBoolean eglUnsignalSyncEXT + EGLDisplay dpy + EGLSync sync + const EGLAttrib *attrib_list + EGLBoolean eglWaitClient @@ -2036,6 +2069,11 @@ + + + + + @@ -2131,6 +2169,13 @@ + + + + + + + @@ -2153,6 +2198,7 @@ + @@ -2248,6 +2294,12 @@ + + + + + + @@ -2350,6 +2402,11 @@ + + + + + @@ -2764,6 +2821,7 @@ + @@ -2811,6 +2869,11 @@ + + + + + @@ -2905,6 +2968,11 @@ + + + + + @@ -3039,12 +3107,12 @@ - - - - - - + + + + + + diff --git a/third_party/rust/khronos_api/api_webgl/extensions/EXT_disjoint_timer_query/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/EXT_disjoint_timer_query/extension.xml index bff3a4dc511e..6b630aa8e126 100644 --- a/third_party/rust/khronos_api/api_webgl/extensions/EXT_disjoint_timer_query/extension.xml +++ b/third_party/rust/khronos_api/api_webgl/extensions/EXT_disjoint_timer_query/extension.xml @@ -65,11 +65,11 @@ interface EXT_disjoint_timer_query { WebGLTimerQueryEXT? createQueryEXT(); void deleteQueryEXT(WebGLTimerQueryEXT? query); [WebGLHandlesContextLoss] boolean isQueryEXT(WebGLTimerQueryEXT? query); - void beginQueryEXT(enum target, WebGLTimerQueryEXT query); - void endQueryEXT(enum target); - void queryCounterEXT(WebGLTimerQueryEXT query, enum target); - any getQueryEXT(enum target, enum pname); - any getQueryObjectEXT(WebGLTimerQueryEXT query, enum pname); + void beginQueryEXT(GLenum target, WebGLTimerQueryEXT query); + void endQueryEXT(GLenum target); + void queryCounterEXT(WebGLTimerQueryEXT query, GLenum target); + any getQueryEXT(GLenum target, GLenum pname); + any getQueryObjectEXT(WebGLTimerQueryEXT query, GLenum pname); }; diff --git a/third_party/rust/khronos_api/api_webgl/extensions/EXT_disjoint_timer_query_webgl2/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/EXT_disjoint_timer_query_webgl2/extension.xml index 192f1e40ad90..188bcd4b62db 100644 --- a/third_party/rust/khronos_api/api_webgl/extensions/EXT_disjoint_timer_query_webgl2/extension.xml +++ b/third_party/rust/khronos_api/api_webgl/extensions/EXT_disjoint_timer_query_webgl2/extension.xml @@ -49,7 +49,7 @@ interface EXT_disjoint_timer_query_webgl2 { const GLenum TIMESTAMP_EXT = 0x8E28; const GLenum GPU_DISJOINT_EXT = 0x8FBB; - void queryCounterEXT(WebGLQuery query, enum target); + void queryCounterEXT(WebGLQuery query, GLenum target); }; diff --git a/third_party/rust/khronos_api/api_webgl/extensions/EXT_texture_compression_bptc/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/EXT_texture_compression_bptc/extension.xml new file mode 100644 index 000000000000..c08e98b76006 --- /dev/null +++ b/third_party/rust/khronos_api/api_webgl/extensions/EXT_texture_compression_bptc/extension.xml @@ -0,0 +1,110 @@ + + + + EXT_texture_compression_bptc + + WebGL working group (public_webgl 'at' khronos.org) + + + Olli Etuaho, NVIDIA + Members of the WebGL working group + + 38 + + + + +

+ This extension exposes the compressed texture format defined in the + + EXT_texture_compression_bptc OpenGL ES extension to WebGL. Consult that extension + specification for behavioral definitions, including error behaviors. +

+

+ Sampling from textures in the COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT format performs a color space + conversion as specified for SRGB textures in the + EXT_sRGB OpenGL ES + extension. +

+ + + Compression format COMPRESSED_RGBA_BPTC_UNORM_EXT, + COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT, + COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT, + and COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT may be passed to + the compressedTexImage2D and compressedTexSubImage2D entry points. + + + Calling getParameter with the argument COMPRESSED_TEXTURE_FORMATS + will include the formats from this specification. + + +

+ If the internalformat is one of the BPTC internal formats from this specification, + the byteLength of the ArrayBufferView, pixels, passed to + compressedTexImage2D or compressedTexSubImage2D must be + equal to the following number of bytes: +

+
+ ceil(width / 4) * ceil(height / 4) * 16 +
+

If it is not, an INVALID_VALUE error is generated.

+
+
+
+ +[NoInterfaceObject] +interface EXT_texture_compression_bptc { + const GLenum COMPRESSED_RGBA_BPTC_UNORM_EXT = 0x8E8C; + const GLenum COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = 0x8E8D; + const GLenum COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT = 0x8E8E; + const GLenum COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT = 0x8E8F; +}; + + + + + + Accepted by the internalformat parameter: + COMPRESSED_RGBA_BPTC_UNORM_EXT, + COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT, + COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT, + COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT +
+
+ + + + Accepted by the internalformat parameter: + COMPRESSED_RGBA_BPTC_UNORM_EXT, + COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT, + COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT, + COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT +
+
+
+ + + + The error INVALID_VALUE is generated by compressedTexImage2D and + compressedTexSubImage2D if the internalformat parameter is one of the BPTC + internal formats from this extension and the byteLength of the ArrayBufferView is not: +
+ ceil(width / 4) * ceil(height / 4) * 16 +
+
+
+ + + + Initial revision. + + + Moved to draft status. + + + Retarget against EXT_texture_compression_bptc instead of ARB_texture_compression_bptc + Rename to EXT_texture_compression_bptc from WEBGL_compressed_texture_bptc + + +
diff --git a/third_party/rust/khronos_api/api_webgl/extensions/EXT_texture_compression_rgtc/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/EXT_texture_compression_rgtc/extension.xml new file mode 100644 index 000000000000..02617fc6fa62 --- /dev/null +++ b/third_party/rust/khronos_api/api_webgl/extensions/EXT_texture_compression_rgtc/extension.xml @@ -0,0 +1,126 @@ + + + + EXT_texture_compression_rgtc + + WebGL working group (public_webgl 'at' khronos.org) + + + Olli Etuaho, NVIDIA + Members of the WebGL working group + + 39 + + + + +

+ This extension exposes the compressed texture format defined in the + + EXT_texture_compression_rgtc OpenGL extension to WebGL. Consult that extension + specification for behavioral definitions, including error behaviors. +

+

+ Updates of partial tiles detailed in the "Implementation Note" section of the + EXT_texture_compression_rgtc specification must be supported in an implementation of this + WebGL extension. +

+ + + Compression formats COMPRESSED_RED_RGTC1_EXT, + COMPRESSED_SIGNED_RED_RGTC1_EXT, + COMPRESSED_RED_GREEN_RGTC2_EXT, + and COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT may be passed to + the compressedTexImage2D and compressedTexSubImage2D entry points. + + + Calling getParameter with the argument COMPRESSED_TEXTURE_FORMATS + will include the formats from this specification. + + +

The following format-specific restrictions must be enforced:

+
+
COMPRESSED_RED_RGTC1_EXT
+
COMPRESSED_SIGNED_RED_RGTC1_EXT
+

The byteLength of the ArrayBufferView, pixels, passed to + compressedTexImage2D or compressedTexSubImage2D must be equal to the following number of bytes:

+
+ ceil(width / 4) * ceil(height / 4) * 8 +
+

If it is not, an INVALID_VALUE error is generated.

+
+
COMPRESSED_RED_GREEN_RGTC2_EXT
+
COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT
+

The byteLength of the ArrayBufferView, pixels, passed to + compressedTexImage2D or compressedTexSubImage2D must be equal to the following number of bytes:

+
+ ceil(width / 4) * ceil(height / 4) * 16 +
+

If it is not, an INVALID_VALUE error is generated.

+
+
+
+
+
+ +[NoInterfaceObject] +interface EXT_texture_compression_rgtc { + const GLenum COMPRESSED_RED_RGTC1_EXT = 0x8DBB; + const GLenum COMPRESSED_SIGNED_RED_RGTC1_EXT = 0x8DBC; + const GLenum COMPRESSED_RED_GREEN_RGTC2_EXT = 0x8DBD; + const GLenum COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT = 0x8DBE; +}; + + + + + + Accepted by the internalformat parameter: + COMPRESSED_RED_RGTC1_EXT, + COMPRESSED_SIGNED_RED_RGTC1_EXT, + COMPRESSED_RED_GREEN_RGTC2_EXT, + COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT +
+
+ + + + Accepted by the internalformat parameter: + COMPRESSED_RED_RGTC1_EXT, + COMPRESSED_SIGNED_RED_RGTC1_EXT, + COMPRESSED_RED_GREEN_RGTC2_EXT, + COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT +
+
+
+ + + + The error INVALID_VALUE is generated by compressedTexImage2D and + compressedTexSubImage2D if the internalformat parameter is + COMPRESSED_RED_RGTC1_EXT or COMPRESSED_SIGNED_RED_RGTC1_EXT + and the byteLength of the ArrayBufferView is not: +
+ ceil(width / 4) * ceil(height / 4) * 8 +
+
+ + The error INVALID_VALUE is generated by compressedTexImage2D and + compressedTexSubImage2D if the internalformat parameter is + COMPRESSED_RED_GREEN_RGTC2_EXT or COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT + and the byteLength of the ArrayBufferView is not: +
+ ceil(width / 4) * ceil(height / 4) * 16 +
+
+
+ + + + Initial revision. + + + Rename to EXT_texture_compression_rgtc from WEBGL_compressed_texture_rgtc + + +
diff --git a/third_party/rust/khronos_api/api_webgl/extensions/KHR_parallel_shader_compile/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/KHR_parallel_shader_compile/extension.xml new file mode 100644 index 000000000000..ca057858a7d5 --- /dev/null +++ b/third_party/rust/khronos_api/api_webgl/extensions/KHR_parallel_shader_compile/extension.xml @@ -0,0 +1,103 @@ + + + + + KHR_parallel_shader_compile + + WebGL + working group (public_webgl 'at' khronos.org) + + + Jie Chen, (jie.a.chen 'at' intel.com) + Geoff Lang, (geofflang 'at' google.com) + Members of the WebGL working group + + + 37 + + + + + + + + + + + + Shader compilation and program linking may be performed in a separate CPU thread. This extension provides a mechanism for the application to provide a hint to limit the number of threads it wants to be used to compile shaders, as well as a query to determine if the compilation process is complete. + + + + + + [NoInterfaceObject] + interface KHR_parallel_shader_compile { + const GLenum MAX_SHADER_COMPILER_THREADS_KHR = 0x91B0; + const GLenum COMPLETION_STATUS_KHR = 0x91B1; + + void maxShaderCompilerThreadsKHR(GLuint count); + }; + + + +
+    var canvas = document.createElement("canvas");
+    var gl = canvas.getContext("webgl");
+    var ext = gl.getExtension('KHR_parallel_shader_compile');
+    if (ext) {
+      // Just for demo of API usage. Generally it's not needed unless you really
+      // want to override the implementation-specific maximum.
+      var threads = gl.getParameter(ext.MAX_SHADER_COMPILER_THREADS_KHR);
+      ext.maxShaderCompilerThreadsKHR(Math.max(2, threads));
+    }
+
+    var vSource = "attribute vec2 position; void main() { gl_Position = vec4(position, 0, 1); }";
+    var fSource = "precision mediump float; void main() { gl_FragColor = vec4(1,0,0,1); }";
+
+    var vShader = gl.createShader(gl.VERTEX_SHADER);
+    gl.shaderSource(vShader, vSource);
+    gl.compileShader(vShader);
+
+    var fShader = gl.createShader(gl.FRAGMENT_SHADER);
+    gl.shaderSource(fShader, fSource);
+    gl.compileShader(fShader);
+
+    var program = gl.createProgram();
+    gl.attachShader(program, vShader);
+    gl.attachShader(program, fShader);
+    gl.linkProgram(program);
+
+    function checkToUseProgram() {
+      if (gl.getProgramParameter(program, gl.LINK_STATUS) == true) {
+        gl.useProgram(program);
+      } else {
+        // error check.
+      }
+    }
+
+    if (ext) {
+      function checkCompletion() {
+        if (gl.getProgramParameter(program, ext.COMPLETION_STATUS_KHR) == true) {
+          checkToUseProgram();
+        } else {
+          requestAnimationFrame(checkCompletion);
+        }
+      }
+      requestAnimationFrame(checkCompletion);
+    } else {
+      checkToUseProgram();
+    }
+    
+
+ + + + Initial revision. + + + Moved to draft status. + + +
diff --git a/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_multiview/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_multiview/extension.xml index ffa52a23f7de..fb22e01b600d 100644 --- a/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_multiview/extension.xml +++ b/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_multiview/extension.xml @@ -164,7 +164,7 @@ interface WEBGL_multiview {
  • if numViews is less than one
  • if numViews is more than MAX_VIEWS_OVR
  • -
  • with the parameters set so that baseViewIndex + numViews is larger than the value of MAX_ARRAY_TEXTURE_LAYERS minus one
  • +
  • with the parameters set so that baseViewIndex + numViews is larger than the value of MAX_ARRAY_TEXTURE_LAYERS
  • if baseViewIndex is negative
@@ -277,5 +277,9 @@ interface WEBGL_multiview { Moved to draft status. + + + Fixed off-by-one issue in validating baseViewIndex + numViews. + diff --git a/third_party/rust/khronos_api/api_webgl/extensions/proposals/EXT_multi_draw_arrays/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/proposals/EXT_multi_draw_arrays/extension.xml new file mode 100644 index 000000000000..b520e8d7815c --- /dev/null +++ b/third_party/rust/khronos_api/api_webgl/extensions/proposals/EXT_multi_draw_arrays/extension.xml @@ -0,0 +1,102 @@ + + + EXT_multi_draw_arrays + + WebGL + working group (public_webgl 'at' khronos.org) + + + Contributors to the EXT_multi_draw_arrays specification + Members of the WebGL working group + + + NN + + + + + + + + + +
+

This extension exposes the EXT_multi_draw_arrays functionality to WebGL.

+ +

CAD vendors rendering large models comprised of many individual parts face scalability issues issuing large numbers of draw calls from WebGL. This extension reduces draw call overhead by allowing better batching.

+
+ + + The multiDrawArraysEXT and multiDrawElementsEXT entry points are added. These provide a counterpoint to instanced rendering and are more flexible for certain scenarios. + + The offset arguments to multiDrawArraysEXT and multiDrawElementsEXT choose the starting offset into their respective typed arrays or sequences. This primarily avoids allocation of temporary typed array views. + +
+ + +[NoInterfaceObject] +interface EXT_multi_draw_arrays { + void multiDrawArraysEXT(GLenum mode, + (Int32Array or sequence<GLint>) firstsList, GLuint firstsOffset, + (Int32Array or sequence<GLsizei>) countsList, GLuint countsOffset, + GLsizei drawcount); + void multiDrawElementsEXT(GLenum mode, + (Int32Array or sequence<GLint>) countsList, GLuint countsOffset, + GLenum type, + (Int32Array or sequence<GLsizei>) offsetsList, GLuint offsetsOffset, + GLsizei drawcount); +}; + + + + The multi-draw APIs are subject to all of the same rules regarding out-of-range array accesses as the core WebGL APIs. + + + + + + + + + + + + + + + + + + +
+var ext = gl.getExtension("EXT_multi_draw_arrays");
+{
+  // multiDrawArrays variant.
+  let firsts = new Int32Array(...);
+  let counts = new Int32Array(...);
+  ext.multiDrawArraysEXT(gl.TRIANGLES, firsts, 0, counts, 0, firsts.length);
+}
+
+{
+  // multiDrawElements variant.
+  // Assumes that the indices which have been previously uploaded to the
+  // ELEMENT_ARRAY_BUFFER are to be treated as UNSIGNED_SHORT.
+  let counts = new Int32Array(...);
+  let offsets = new Int32Array(...);
+  ext.multiDrawElementsEXT(gl.TRIANGLES, counts, 0, gl.UNSIGNED_SHORT, offsets, 0,
+                           counts.length);
+}
+    
+
+ + + + + + + + Initial version. + + +
diff --git a/third_party/rust/khronos_api/api_webgl/extensions/proposals/WEBGL_blend_equation_advanced_coherent/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/proposals/WEBGL_blend_equation_advanced_coherent/extension.xml new file mode 100644 index 000000000000..b08bb8f55316 --- /dev/null +++ b/third_party/rust/khronos_api/api_webgl/extensions/proposals/WEBGL_blend_equation_advanced_coherent/extension.xml @@ -0,0 +1,125 @@ + + + WEBGL_blend_equation_advanced_coherent + + WebGL + working group (public_webgl 'at' khronos.org) + + + Ashley Gullen (ashley at scirra dot com) + Members of the WebGL working group + + + NN + + + + + + + + + +
+

This extension exposes the KHR_blend_equation_advanced_coherent functionality to WebGL.

+ +

CanvasRenderingContext2D provides a series of common blend functions with globalComposeOperation, such as "multiply" and "screen". KHR_blend_equation_advanced_coherent provides, with the exception of "xor", exactly the same list of blend functions for WebGL, as detailed below:

+ +
    +
  • "multiply": MULTIPLY_KHR
  • +
  • "screen": SCREEN_KHR
  • +
  • "overlay": OVERLAY_KHR
  • +
  • "darken": DARKEN_KHR
  • +
  • "lighten": LIGHTEN_KHR
  • +
  • "color-dodge": COLORDODGE_KHR
  • +
  • "color-burn": COLORBURN_KHR
  • +
  • "hard-light": HARDLIGHT_KHR
  • +
  • "soft-light": SOFTLIGHT_KHR
  • +
  • "difference": DIFFERENCE_KHR
  • +
  • "exclusion": EXCLUSION_KHR
  • +
  • "hue": HSL_HUE_KHR
  • +
  • "saturation": HSL_SATURATION_KHR
  • +
  • "color": HSL_COLOR_KHR
  • +
  • "luminosity": HSL_LUMINOSITY_KHR
  • +
+ +

These effects are useful for high-quality artistic blends. They can be implemented using shaders and rendering via an intermediate texture. However this has a high performance overhead both in draw calls and GPU bandwidth. Advanced blend modes allow a much simpler, high-performance way of implementing these blends. Using shaders rendering to an intermediate texture can be used as a fallback if this extension is not supported.

+ +

Note only the coherent variant of this extension is exposed in order to eliminate the possibility of undefined behavior in KHR_blend_equation_advanced. This also simplifies the extension and removes the need to insert blend barriers during rendering.

+
+ + + The blendEquation entry point is extended to accept the enums in the IDL below + +
+ + +[NoInterfaceObject] +interface WEBGL_blend_equation_advanced_coherent { + const GLenum MULTIPLY = 0x9294; + const GLenum SCREEN = 0x9295; + const GLenum OVERLAY = 0x9296; + const GLenum DARKEN = 0x9297; + const GLenum LIGHTEN = 0x9298; + const GLenum COLORDODGE = 0x9299; + const GLenum COLORBURN = 0x929A; + const GLenum HARDLIGHT = 0x929B; + const GLenum SOFTLIGHT = 0x929C; + const GLenum DIFFERENCE = 0x929E; + const GLenum EXCLUSION = 0x92A0; + const GLenum HSL_HUE = 0x92AD; + const GLenum HSL_SATURATION = 0x92AE; + const GLenum HSL_COLOR = 0x92AF; + const GLenum HSL_LUMINOSITY = 0x92B0; +}; + + + + + + + + + + + + + + + + + + + + +
+var ext = gl.getExtension("WEBGL_blend_equation_advanced_coherent");
+gl.blendEquation(ext.MULTIPLY);
+gl.getParameter(gl.BLEND_EQUATION) == ext.MULTIPLY;
+    
+
+ + + + + + + + + Forked from WEBGL_blend_equation_advanced to specify only the coherent variant + + + + Converted to extension XML format + + + + Revised description + + + + Original draft as a TXT file + + +
diff --git a/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_compressed_texture_atc/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_compressed_texture_atc/extension.xml similarity index 95% rename from third_party/rust/khronos_api/api_webgl/extensions/WEBGL_compressed_texture_atc/extension.xml rename to third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_compressed_texture_atc/extension.xml index a673e3d4f5d2..a08906974c0b 100644 --- a/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_compressed_texture_atc/extension.xml +++ b/third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_compressed_texture_atc/extension.xml @@ -1,6 +1,6 @@ - + WEBGL_compressed_texture_atc WebGL working group (public_webgl 'at' khronos.org) @@ -105,5 +105,8 @@ interface WEBGL_compressed_texture_atc { Added NoInterfaceObject extended attribute. + + Moved to rejected status at Khronos Montreal face-to-face meeting. + - + diff --git a/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_get_buffer_sub_data_async/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_get_buffer_sub_data_async/extension.xml similarity index 95% rename from third_party/rust/khronos_api/api_webgl/extensions/WEBGL_get_buffer_sub_data_async/extension.xml rename to third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_get_buffer_sub_data_async/extension.xml index c85f02376ca4..b224f6dbc3d4 100644 --- a/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_get_buffer_sub_data_async/extension.xml +++ b/third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_get_buffer_sub_data_async/extension.xml @@ -1,6 +1,6 @@ - + WEBGL_get_buffer_sub_data_async WebGL working group (public_webgl 'at' khronos.org) @@ -132,5 +132,10 @@ interface WEBGL_get_buffer_sub_data_async { Initial revision. + + Set status to rejected following the working group's decision to + allow optimizations of the existing getBufferSubData API instead of + exposing a new one. + - + diff --git a/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_shared_resources/extension.xml b/third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_shared_resources/extension.xml similarity index 95% rename from third_party/rust/khronos_api/api_webgl/extensions/WEBGL_shared_resources/extension.xml rename to third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_shared_resources/extension.xml index 2531999ae8f6..c512f89b672f 100644 --- a/third_party/rust/khronos_api/api_webgl/extensions/WEBGL_shared_resources/extension.xml +++ b/third_party/rust/khronos_api/api_webgl/extensions/rejected/WEBGL_shared_resources/extension.xml @@ -1,6 +1,6 @@ - + WEBGL_shared_resources WebGL working group (public_webgl 'at' khronos.org) @@ -330,7 +330,7 @@ interface WEBGL_shared_resources { long acquireSharedResource( WebGLSharedObject resource, GLenum mode, - AcquireResourcesCallback callback); + AcquireSharedResourcesCallback callback); void releaseSharedResource( WebGLSharedObject resource); void cancelAcquireSharedResource(long id); @@ -340,25 +340,25 @@ callback AcquireSharedResourcesCallback = void (); [NoInterfaceObject] interface WebGLShareGroup { -} +}; interface WebGLSharedObject : WebGLObject { -} +}; interface WebGLBuffer : WebGLSharedObject { -} +}; interface WebGLProgram : WebGLSharedObject { -} +}; interface WebGLRenderbuffer : WebGLSharedObject { -} +}; interface WebGLShader : WebGLSharedObject { -} +}; interface WebGLTexture : WebGLSharedObject { -} +}; @@ -370,5 +370,12 @@ interface WebGLTexture : WebGLSharedObject { Added NoInterfaceObject extended attribute to extension interface and WebGLShareGroup. + + Rejected after discussion on public_webgl and no strong objections. At this point in + the WebGL API's development it is not profitable to invest the time to implement this + extension. Alternatives: CanvasRenderingContext2D.drawImage taking a WebGL-rendered canvas as + argument, or using OffscreenCanvas.transferToImageBitmap with a WebGL-rendered canvas, + combined with ImageBitmapRenderingContext.transferFromImageBitmap. + - + diff --git a/third_party/rust/khronos_api/api_webgl/specs/latest/1.0/webgl.idl b/third_party/rust/khronos_api/api_webgl/specs/latest/1.0/webgl.idl index 2070f29082fd..826dfff0c58e 100644 --- a/third_party/rust/khronos_api/api_webgl/specs/latest/1.0/webgl.idl +++ b/third_party/rust/khronos_api/api_webgl/specs/latest/1.0/webgl.idl @@ -2,9 +2,27 @@ // // WebGL IDL definitions scraped from the Khronos specification: // https://www.khronos.org/registry/webgl/specs/latest/ + +// Copyright (c) 2018 The Khronos Group Inc. // -// This IDL depends on the typed array specification defined at: -// https://www.khronos.org/registry/typedarray/specs/latest/typedarrays.idl +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and/or associated documentation files (the +// "Materials"), to deal in the Materials without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Materials, and to +// permit persons to whom the Materials are furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Materials. +// +// THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. typedef unsigned long GLenum; typedef boolean GLboolean; @@ -38,36 +56,46 @@ dictionary WebGLContextAttributes { GLboolean failIfMajorPerformanceCaveat = false; }; +[Exposed=(Window,Worker)] interface WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLBuffer : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLFramebuffer : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLProgram : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLRenderbuffer : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLShader : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLTexture : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLUniformLocation { }; +[Exposed=(Window,Worker)] interface WebGLActiveInfo { readonly attribute GLint size; readonly attribute GLenum type; readonly attribute DOMString name; }; +[Exposed=(Window,Worker)] interface WebGLShaderPrecisionFormat { readonly attribute GLint rangeMin; readonly attribute GLint rangeMax; @@ -504,7 +532,7 @@ interface mixin WebGLRenderingContextBase const GLenum UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243; const GLenum BROWSER_DEFAULT_WEBGL = 0x9244; - readonly attribute HTMLCanvasElement canvas; + [Exposed=Window] readonly attribute HTMLCanvasElement canvas; readonly attribute GLsizei drawingBufferWidth; readonly attribute GLsizei drawingBufferHeight; @@ -712,13 +740,16 @@ interface mixin WebGLRenderingContextBase void viewport(GLint x, GLint y, GLsizei width, GLsizei height); }; +[Exposed=(Window,Worker)] interface WebGLRenderingContext { }; WebGLRenderingContext includes WebGLRenderingContextBase; -[Constructor(DOMString type, optional WebGLContextEventInit eventInit)] +[Exposed=(Window,Worker), + Constructor(DOMString type, + optional WebGLContextEventInit eventInit)] interface WebGLContextEvent : Event { readonly attribute DOMString statusMessage; }; diff --git a/third_party/rust/khronos_api/api_webgl/specs/latest/2.0/webgl2.idl b/third_party/rust/khronos_api/api_webgl/specs/latest/2.0/webgl2.idl index f3ee86b7c53c..8c565276dec0 100644 --- a/third_party/rust/khronos_api/api_webgl/specs/latest/2.0/webgl2.idl +++ b/third_party/rust/khronos_api/api_webgl/specs/latest/2.0/webgl2.idl @@ -2,26 +2,49 @@ // // WebGL IDL definitions scraped from the Khronos specification: // https://www.khronos.org/registry/webgl/specs/latest/ + +// Copyright (c) 2018 The Khronos Group Inc. // -// This IDL depends on the typed array specification defined at: -// https://www.khronos.org/registry/typedarray/specs/latest/typedarrays.idl +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and/or associated documentation files (the +// "Materials"), to deal in the Materials without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Materials, and to +// permit persons to whom the Materials are furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Materials. +// +// THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. typedef long long GLint64; typedef unsigned long long GLuint64; +[Exposed=(Window,Worker)] interface WebGLQuery : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLSampler : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLSync : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLTransformFeedback : WebGLObject { }; +[Exposed=(Window,Worker)] interface WebGLVertexArrayObject : WebGLObject { }; @@ -571,6 +594,7 @@ interface mixin WebGL2RenderingContextBase void bindVertexArray(WebGLVertexArrayObject? array); }; +[Exposed=(Window,Worker)] interface WebGL2RenderingContext { }; diff --git a/third_party/rust/khronos_api/build.rs b/third_party/rust/khronos_api/build.rs index 757bd739ac91..54fbe012094e 100644 --- a/third_party/rust/khronos_api/build.rs +++ b/third_party/rust/khronos_api/build.rs @@ -17,8 +17,8 @@ // containing the XML specifications for all of them. use std::env; use std::fs::File; -use std::path::*; use std::io::Write; +use std::path::*; fn main() { // Create and open a file in the output directory to contain our generated rust code diff --git a/third_party/rust/xml-rs/.cargo-checksum.json b/third_party/rust/xml-rs/.cargo-checksum.json index f6573da29acb..f418028757c9 100644 --- a/third_party/rust/xml-rs/.cargo-checksum.json +++ b/third_party/rust/xml-rs/.cargo-checksum.json @@ -1 +1 @@ -{"files":{"Cargo.toml":"70a965685fb8ead101d8c75e531d3ff684d68bbdf6b35d3b38bf4bcdac6a5759","Changelog.md":"8fe1afcfc8f2e164e2aa6a10c33be3b4ef7ca003607d57839693468607452843","LICENSE":"0dc18d924dc0a5f41172a393012843a5eaaef338e795b3645da9cc3b6068220b","Readme.md":"79162e348a1dafd1c2723267cd91fe66201b754a0daef7ea14b88491419653f8","design.md":"59eb3e89c9fe3e2c9e7dfd464ddceb56d8bb0fac7459d5b12d3f304487fdfcde","src/analyze.rs":"6fc06790088cc19e2e9c8be9d4d3337fe31f741cf7d5850f4b2dc3522c3b2609","src/attribute.rs":"76ddf747765a461058d6781639161f8b4c10eee630cb0163c8ab205b39f5a673","src/common.rs":"861dca93ca0c6cc7e30cd9f08f486b29dc89d89d361e246ef0947f7060e05ddb","src/escape.rs":"7df467344114064c3bd731c9e70e45c300f7b2704d6edf6e76daf6b32775b780","src/lib.rs":"268e41e85c80214da49af8e4a8a9d171b64b95897be179d18e34b0836434e4c6","src/macros.rs":"8c7f9c18083fceb4af9e27a84d9130888829250c869771cb192eec19941988e0","src/name.rs":"f19eb4cc8c5fb41d84fff9f1b1c3fbb95007ab6c088807272920c022baa8f229","src/namespace.rs":"c3da1668a50bfdf98affdbb8f2126273ebbf73bacde474a5ec5be80f6915957b","src/reader/config.rs":"d63ad011a9bded4031e2cc8a7e417b836bbec7b1d1bf106d771d0b506a2b4525","src/reader/error.rs":"bf6a889e9464f0b981ad5b761af46b53fed203b917265eaa0c439d5937a313f4","src/reader/events.rs":"4a07a3173f2613f6ea5b7880467152238a20de59dda42c95008d50ef80c9c3ed","src/reader/lexer.rs":"79fff053c0df98044144832d030dacf0debf8309ad825e57ceab3142d9db155f","src/reader/mod.rs":"4b7055cb60f736b71dabc91fb99bb1e1bf8429e8bf740f83d5e6e1d64cbe2012","src/reader/parser/inside_cdata.rs":"7217ab332a7e29f8a2282d1bfd4d493465e0d6921e0f9f077634fdcedac331c9","src/reader/parser/inside_closing_tag_name.rs":"595d7888180da8a5ed2003da215be3b8b6521ee0624080b18af4eb3f4a2a6901","src/reader/parser/inside_comment.rs":"1f6b077007422562be7793df0a1d7ace3b2d2afd134e621045cd6650088a438d","src/reader/parser/inside_declaration.rs":"ea00f620e0d2d4fe9024796c80a2b325db2a651fb12467a18ea00f280d83ac48","src/reader/parser/inside_doctype.rs":"c87d1e36aea80ca8443a1a59d5cf2ee32d899c04ccbe38492ce3d02536f8fffd","src/reader/parser/inside_opening_tag.rs":"55c49634886ba41f23ac5f7a8e14f5cb02befb4bf9ea6943b4cc2c31a5569d28","src/reader/parser/inside_processing_instruction.rs":"e9cc8c1f8dd8bb065465659533cf7730d53206a88b06f7385544ccaf54e80368","src/reader/parser/inside_reference.rs":"b87e07f8585fa3329d2527c57a5c8ff3deec889b012ebbef61e9440da54d3b45","src/reader/parser/mod.rs":"fcada7c13000b461ac79ad403b8eb2862e455b963074900227d75f92a250887c","src/reader/parser/outside_tag.rs":"77071f46398a04201e2a0e7ab0ff905165728d6e33e7eb6cc6ba56f772da2947","src/util.rs":"576d7db4550c2c38eb77af6545aebc42dcbe5a81eef190d472202d3ddcd7c97c","src/writer/config.rs":"3aaf615b13862e6daae943d27de05118524bb0d8d9444b1e4f245815696a6fea","src/writer/emitter.rs":"9f6e126ad81f68b58a7535a0d8012dff83ae132d9188bcff832a2b9ce297dea6","src/writer/events.rs":"82db3d1c83144fe1abfa5a841de0593cfe85a1cf7b6563f611ef5dd52bb327d0","src/writer/mod.rs":"81ecabbe31eefd8047e3d55bc8ac2703401807cd2683f31b9155f85dfa6ebaa3","tests/documents/sample_1.xml":"79c9ba2d71d70906230905cef127ba8c09ae8701c60357d32cf581dbfc660237","tests/documents/sample_1_full.txt":"efc646390dd6693c4122bb4a7d0c77e31bba7fda0e5767aa1de501bddc64174f","tests/documents/sample_1_short.txt":"83ef8cca29ac8e4b20dc9aea182155ad39d090fb08b76b6abe581801211b10e4","tests/documents/sample_2.xml":"c8350272a8c205e4004fc7e10be1660a0e10d2c9dbf044395d52ad2ca08fa03a","tests/documents/sample_2_full.txt":"21a7b53ddfb8eeaf73d0f6d7a1f96b1af3188129d69f6a5fd4d21e6376f2fb7f","tests/documents/sample_2_short.txt":"b94bc0600a84acf0999775d19c5a7169d24f88c74cc605a1f30b981181bacfeb","tests/documents/sample_3.xml":"a29359438fe9ca025f09d62d4b96f51a89d4be9e634767a5bb447d555c75aef8","tests/documents/sample_3_full.txt":"3522aa83d2b0e942e963d234af0b3426ad3c08141d60ccacc18077c67e2b2194","tests/documents/sample_3_short.txt":"57a8cc41ec6fcebf854126b3c9bb933a1de8be6c5b62372e857906314bb8f13f","tests/documents/sample_4.xml":"7c0ae3ee71a9c94afe1a35480a8c3bf58ffe90b754bccf42f83784971584e9b8","tests/documents/sample_4_full.txt":"f4f2419b336b04af9746ee12ac908a9b82cebca8fc280ad5422d0ab5483ee817","tests/documents/sample_4_short.txt":"39e1b7947fc33276347031e12a0a3f0e5a70eee9e743aba7d5c45b08a454cfae","tests/documents/sample_5.xml":"356d33417665fee602eb9399a8fb58e9bfaa634bcadfcd97214302bdc32f33c4","tests/documents/sample_5_short.txt":"9b8e3a9e7a71c55ee30ee85d256b06079e2ea8029207efbfb62ca98add4ce585","tests/event_reader.rs":"c4e7c7fe13461502c895c8c2fd3b65ef74432ee41482b8400ea72b0f0be135b9","tests/event_writer.rs":"a0c92666af8f031e0376dfce20f9864c67cd83ec4256a52b8e7c60ed707b8d45","tests/streaming.rs":"1fc96cd6e1cfedddda534c5f07608df169bf3d054c32f4743f256dfc6731f93a"},"package":"3c1cb601d29fe2c2ac60a2b2e5e293994d87a1f6fa9687a31a15270f909be9c2"} \ No newline at end of file +{"files":{"Cargo.toml":"444e5c26b1986ae6c0c549e877b3987cd5c2b439ee6d5521f7b6dc69b74ca92e","Changelog.md":"244e2dbd57656dc505f16ba1077528c30f310f6221f0995c70b37ef76c663599","LICENSE":"0dc18d924dc0a5f41172a393012843a5eaaef338e795b3645da9cc3b6068220b","Readme.md":"269b3cd4286727d936c28c29d3850564104653fc40b6a22bd095679142ce6b01","design.md":"59eb3e89c9fe3e2c9e7dfd464ddceb56d8bb0fac7459d5b12d3f304487fdfcde","src/analyze.rs":"6fc06790088cc19e2e9c8be9d4d3337fe31f741cf7d5850f4b2dc3522c3b2609","src/attribute.rs":"94cb1270e8247af01114b465bda181840b053942dfb7fb6b70d83d48f37f02e2","src/common.rs":"861dca93ca0c6cc7e30cd9f08f486b29dc89d89d361e246ef0947f7060e05ddb","src/escape.rs":"7df467344114064c3bd731c9e70e45c300f7b2704d6edf6e76daf6b32775b780","src/lib.rs":"0c63e2b37cc7e48546b21dfb967c628f38648d52b11323d02b71d8ddd8b41ae1","src/macros.rs":"8c7f9c18083fceb4af9e27a84d9130888829250c869771cb192eec19941988e0","src/name.rs":"fc0d5c0c1e11e14e06f4549a6ddc58cbf4f91f0272802f18591004daf781940a","src/namespace.rs":"d5e1b4b19025d6237f06e1dec3570f7d4f8301631610a93bb56a958d27999480","src/reader/config.rs":"d63ad011a9bded4031e2cc8a7e417b836bbec7b1d1bf106d771d0b506a2b4525","src/reader/error.rs":"bf6a889e9464f0b981ad5b761af46b53fed203b917265eaa0c439d5937a313f4","src/reader/events.rs":"4a07a3173f2613f6ea5b7880467152238a20de59dda42c95008d50ef80c9c3ed","src/reader/lexer.rs":"79fff053c0df98044144832d030dacf0debf8309ad825e57ceab3142d9db155f","src/reader/mod.rs":"4b7055cb60f736b71dabc91fb99bb1e1bf8429e8bf740f83d5e6e1d64cbe2012","src/reader/parser/inside_cdata.rs":"7217ab332a7e29f8a2282d1bfd4d493465e0d6921e0f9f077634fdcedac331c9","src/reader/parser/inside_closing_tag_name.rs":"595d7888180da8a5ed2003da215be3b8b6521ee0624080b18af4eb3f4a2a6901","src/reader/parser/inside_comment.rs":"1f6b077007422562be7793df0a1d7ace3b2d2afd134e621045cd6650088a438d","src/reader/parser/inside_declaration.rs":"ea00f620e0d2d4fe9024796c80a2b325db2a651fb12467a18ea00f280d83ac48","src/reader/parser/inside_doctype.rs":"c87d1e36aea80ca8443a1a59d5cf2ee32d899c04ccbe38492ce3d02536f8fffd","src/reader/parser/inside_opening_tag.rs":"55c49634886ba41f23ac5f7a8e14f5cb02befb4bf9ea6943b4cc2c31a5569d28","src/reader/parser/inside_processing_instruction.rs":"e9cc8c1f8dd8bb065465659533cf7730d53206a88b06f7385544ccaf54e80368","src/reader/parser/inside_reference.rs":"b87e07f8585fa3329d2527c57a5c8ff3deec889b012ebbef61e9440da54d3b45","src/reader/parser/mod.rs":"fcada7c13000b461ac79ad403b8eb2862e455b963074900227d75f92a250887c","src/reader/parser/outside_tag.rs":"77071f46398a04201e2a0e7ab0ff905165728d6e33e7eb6cc6ba56f772da2947","src/util.rs":"576d7db4550c2c38eb77af6545aebc42dcbe5a81eef190d472202d3ddcd7c97c","src/writer/config.rs":"3aaf615b13862e6daae943d27de05118524bb0d8d9444b1e4f245815696a6fea","src/writer/emitter.rs":"50b7d37ef749aab1bb921a4765887c325c295daf7be22e01c5b5e75fa7199459","src/writer/events.rs":"82db3d1c83144fe1abfa5a841de0593cfe85a1cf7b6563f611ef5dd52bb327d0","src/writer/mod.rs":"78c65cf1cf2d286bab3917c4e2c364f6289cdb665ece092422d905d00d1275f9","tests/documents/sample_1.xml":"79c9ba2d71d70906230905cef127ba8c09ae8701c60357d32cf581dbfc660237","tests/documents/sample_1_full.txt":"efc646390dd6693c4122bb4a7d0c77e31bba7fda0e5767aa1de501bddc64174f","tests/documents/sample_1_short.txt":"83ef8cca29ac8e4b20dc9aea182155ad39d090fb08b76b6abe581801211b10e4","tests/documents/sample_2.xml":"c8350272a8c205e4004fc7e10be1660a0e10d2c9dbf044395d52ad2ca08fa03a","tests/documents/sample_2_full.txt":"21a7b53ddfb8eeaf73d0f6d7a1f96b1af3188129d69f6a5fd4d21e6376f2fb7f","tests/documents/sample_2_short.txt":"b94bc0600a84acf0999775d19c5a7169d24f88c74cc605a1f30b981181bacfeb","tests/documents/sample_3.xml":"a29359438fe9ca025f09d62d4b96f51a89d4be9e634767a5bb447d555c75aef8","tests/documents/sample_3_full.txt":"3522aa83d2b0e942e963d234af0b3426ad3c08141d60ccacc18077c67e2b2194","tests/documents/sample_3_short.txt":"57a8cc41ec6fcebf854126b3c9bb933a1de8be6c5b62372e857906314bb8f13f","tests/documents/sample_4.xml":"7c0ae3ee71a9c94afe1a35480a8c3bf58ffe90b754bccf42f83784971584e9b8","tests/documents/sample_4_full.txt":"f4f2419b336b04af9746ee12ac908a9b82cebca8fc280ad5422d0ab5483ee817","tests/documents/sample_4_short.txt":"39e1b7947fc33276347031e12a0a3f0e5a70eee9e743aba7d5c45b08a454cfae","tests/documents/sample_5.xml":"356d33417665fee602eb9399a8fb58e9bfaa634bcadfcd97214302bdc32f33c4","tests/documents/sample_5_short.txt":"9b8e3a9e7a71c55ee30ee85d256b06079e2ea8029207efbfb62ca98add4ce585","tests/event_reader.rs":"c4e7c7fe13461502c895c8c2fd3b65ef74432ee41482b8400ea72b0f0be135b9","tests/event_writer.rs":"a0c92666af8f031e0376dfce20f9864c67cd83ec4256a52b8e7c60ed707b8d45","tests/streaming.rs":"1fc96cd6e1cfedddda534c5f07608df169bf3d054c32f4743f256dfc6731f93a"},"package":"541b12c998c5b56aa2b4e6f18f03664eef9a4fd0a246a55594efae6cc2d964b5"} \ No newline at end of file diff --git a/third_party/rust/xml-rs/Cargo.toml b/third_party/rust/xml-rs/Cargo.toml index 16c97f510a2d..d41464939b1b 100644 --- a/third_party/rust/xml-rs/Cargo.toml +++ b/third_party/rust/xml-rs/Cargo.toml @@ -12,7 +12,7 @@ [package] name = "xml-rs" -version = "0.7.0" +version = "0.8.0" authors = ["Vladimir Matveev "] description = "An XML library in pure Rust" documentation = "http://netvl.github.io/xml-rs/" @@ -28,5 +28,3 @@ path = "src/lib.rs" [[bin]] name = "xml-analyze" path = "src/analyze.rs" -[dependencies.bitflags] -version = "1.0" diff --git a/third_party/rust/xml-rs/Changelog.md b/third_party/rust/xml-rs/Changelog.md index 09a60e020311..7bc817c4693f 100644 --- a/third_party/rust/xml-rs/Changelog.md +++ b/third_party/rust/xml-rs/Changelog.md @@ -1,3 +1,13 @@ +## Version 0.8.0 + +* Same as 0.7.1, with 0.7.1 being yanked because of the incorrect semver bump. + +## Version 0.7.1 + +* Removed dependency on bitflags. +* Added the `XmlWriter::inner_mut()` method. +* Fixed some rustdoc warnings. + ## Version 0.7.0 * Same as 0.6.2, with 0.6.2 being yanked because of the incompatible bump of minimum required version of rustc. diff --git a/third_party/rust/xml-rs/Readme.md b/third_party/rust/xml-rs/Readme.md index 347cb231b757..a1dec478592c 100644 --- a/third_party/rust/xml-rs/Readme.md +++ b/third_party/rust/xml-rs/Readme.md @@ -60,7 +60,7 @@ xml-rs uses [Cargo](http://crates.io), so just add a dependency section in your ```toml [dependencies] -xml-rs = "0.7" +xml-rs = "0.8" ``` The package exposes a single crate called `xml`: diff --git a/third_party/rust/xml-rs/src/attribute.rs b/third_party/rust/xml-rs/src/attribute.rs index 9af83b418262..8728f496d704 100644 --- a/third_party/rust/xml-rs/src/attribute.rs +++ b/third_party/rust/xml-rs/src/attribute.rs @@ -30,17 +30,14 @@ impl<'a> Attribute<'a> { pub fn to_owned(&self) -> OwnedAttribute { OwnedAttribute { name: self.name.into(), - value: self.value.into() + value: self.value.into(), } } /// Creates a borrowed attribute using the provided borrowed name and a borrowed string value. #[inline] pub fn new(name: Name<'a>, value: &'a str) -> Attribute<'a> { - Attribute { - name: name, - value: value - } + Attribute { name, value, } } } @@ -61,7 +58,7 @@ impl OwnedAttribute { pub fn borrow(&self) -> Attribute { Attribute { name: self.name.borrow(), - value: &*self.value + value: &*self.value, } } @@ -69,8 +66,8 @@ impl OwnedAttribute { #[inline] pub fn new>(name: OwnedName, value: S) -> OwnedAttribute { OwnedAttribute { - name: name, - value: value.into() + name, + value: value.into(), } } } diff --git a/third_party/rust/xml-rs/src/lib.rs b/third_party/rust/xml-rs/src/lib.rs index cf23730fb1d1..15919e805884 100644 --- a/third_party/rust/xml-rs/src/lib.rs +++ b/third_party/rust/xml-rs/src/lib.rs @@ -5,9 +5,6 @@ //! This crate currently provides an almost XML 1.0/1.1-compliant pull parser. -#[macro_use] -extern crate bitflags; - pub use reader::EventReader; pub use reader::ParserConfig; pub use writer::EventWriter; diff --git a/third_party/rust/xml-rs/src/name.rs b/third_party/rust/xml-rs/src/name.rs index 3cb87bd6ac2b..a20eae2f10c2 100644 --- a/third_party/rust/xml-rs/src/name.rs +++ b/third_party/rust/xml-rs/src/name.rs @@ -76,11 +76,11 @@ impl<'a> From<(&'a str, &'a str)> for Name<'a> { impl<'a> fmt::Display for Name<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(namespace) = self.namespace { - try! { write!(f, "{{{}}}", namespace) } + write!(f, "{{{}}}", namespace)?; } if let Some(prefix) = self.prefix { - try! { write!(f, "{}:", prefix) } + write!(f, "{}:", prefix)?; } write!(f, "{}", self.local_name) @@ -101,7 +101,7 @@ impl<'a> Name<'a> { #[inline] pub fn local(local_name: &str) -> Name { Name { - local_name: local_name, + local_name, prefix: None, namespace: None } @@ -111,7 +111,7 @@ impl<'a> Name<'a> { #[inline] pub fn prefixed(local_name: &'a str, prefix: &'a str) -> Name<'a> { Name { - local_name: local_name, + local_name, namespace: None, prefix: Some(prefix) } @@ -122,9 +122,9 @@ impl<'a> Name<'a> { #[inline] pub fn qualified(local_name: &'a str, namespace: &'a str, prefix: Option<&'a str>) -> Name<'a> { Name { - local_name: local_name, + local_name, namespace: Some(namespace), - prefix: prefix, + prefix, } } @@ -267,9 +267,9 @@ impl FromStr for OwnedName { (_, _, _) => None }; r.map(|(local_name, prefix)| OwnedName { - local_name: local_name, + local_name, namespace: None, - prefix: prefix + prefix }).ok_or(()) } } diff --git a/third_party/rust/xml-rs/src/namespace.rs b/third_party/rust/xml-rs/src/namespace.rs index 6d9e5b422e67..1ab4a5c02530 100644 --- a/third_party/rust/xml-rs/src/namespace.rs +++ b/third_party/rust/xml-rs/src/namespace.rs @@ -41,9 +41,11 @@ pub const NS_XML_URI: &'static str = "http://www.w3.org/XML/1998/namespace" /// This constant should be used to define or query default namespace which should be used /// for element or attribute names without prefix. For example, if a namespace mapping /// at a particular point in the document contains correspondence like +/// /// ```none /// NS_NO_PREFIX --> urn:some:namespace /// ``` +/// /// then all names declared without an explicit prefix `urn:some:namespace` is assumed as /// a namespace URI. /// @@ -363,7 +365,7 @@ pub struct NamespaceStackMappings<'a> { } impl<'a> NamespaceStackMappings<'a> { - fn to_next_namespace(&mut self) -> bool { + fn go_to_next_namespace(&mut self) -> bool { self.current_namespace = self.namespaces.next().map(|ns| ns.into_iter()); self.current_namespace.is_some() } @@ -374,7 +376,7 @@ impl<'a> Iterator for NamespaceStackMappings<'a> { fn next(&mut self) -> Option> { // If there is no current namespace and no next namespace, we're finished - if self.current_namespace.is_none() && !self.to_next_namespace() { + if self.current_namespace.is_none() && !self.go_to_next_namespace() { return None; } let next_item = self.current_namespace.as_mut().unwrap().next(); @@ -391,7 +393,7 @@ impl<'a> Iterator for NamespaceStackMappings<'a> { Some((k, v)) }, // Current namespace is exhausted - None => if self.to_next_namespace() { + None => if self.go_to_next_namespace() { // If there is next namespace, continue from it self.next() } else { diff --git a/third_party/rust/xml-rs/src/writer/emitter.rs b/third_party/rust/xml-rs/src/writer/emitter.rs index 39c47592ce64..1b878b2531a1 100644 --- a/third_party/rust/xml-rs/src/writer/emitter.rs +++ b/third_party/rust/xml-rs/src/writer/emitter.rs @@ -45,7 +45,7 @@ impl fmt::Display for EmitterError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; - try!(write!(f, "emitter error: ")); + write!(f, "emitter error: ")?; match *self { EmitterError::Io(ref e) => write!(f, "I/O error: {}", e), @@ -94,12 +94,12 @@ pub struct Emitter { impl Emitter { pub fn new(config: EmitterConfig) -> Emitter { Emitter { - config: config, + config, nst: NamespaceStack::empty(), indent_level: 0, - indent_stack: vec!(IndentFlags::empty()), + indent_stack: vec![IndentFlags::WroteNothing], element_names: Vec::new(), @@ -109,36 +109,12 @@ impl Emitter { } } -macro_rules! try_chain( - (ok_unit $e:expr) => ({try!($e); Ok(())}); - (ignore $e:expr) => (try!($e)); - ($e:expr) => (Ok(try!($e))); - ($e:expr, $($rest:tt)*) => ({ - try!($e); - try_chain!($($rest)*) - }) -); - -macro_rules! wrapped_with( - ($_self:ident; $before_name:ident ($arg:expr) and $after_name:ident, $body:expr) => ({ - try!($_self.$before_name($arg)); - let result = $body; - $_self.$after_name(); - result - }) -); - -macro_rules! if_present( - ($opt:ident, $body:expr) => ($opt.map(|$opt| $body).unwrap_or(Ok(()))) -); - -bitflags!( - struct IndentFlags: u8 { - const WROTE_NOTHING = 0; - const WROTE_MARKUP = 1; - const WROTE_TEXT = 2; - } -); +#[derive(Copy, Clone, Eq, PartialEq, Debug)] +enum IndentFlags { + WroteNothing, + WroteMarkup, + WroteText, +} impl Emitter { /// Returns the current state of namespaces. @@ -149,33 +125,33 @@ impl Emitter { #[inline] fn wrote_text(&self) -> bool { - self.indent_stack.last().unwrap().contains(IndentFlags::WROTE_TEXT) + *self.indent_stack.last().unwrap() == IndentFlags::WroteText } #[inline] fn wrote_markup(&self) -> bool { - self.indent_stack.last().unwrap().contains(IndentFlags::WROTE_MARKUP) + *self.indent_stack.last().unwrap() == IndentFlags::WroteMarkup } #[inline] fn set_wrote_text(&mut self) { - *self.indent_stack.last_mut().unwrap() = IndentFlags::WROTE_TEXT; + *self.indent_stack.last_mut().unwrap() = IndentFlags::WroteText; } #[inline] fn set_wrote_markup(&mut self) { - *self.indent_stack.last_mut().unwrap() = IndentFlags::WROTE_MARKUP; + *self.indent_stack.last_mut().unwrap() = IndentFlags::WroteMarkup; } #[inline] fn reset_state(&mut self) { - *self.indent_stack.last_mut().unwrap() = IndentFlags::WROTE_NOTHING; + *self.indent_stack.last_mut().unwrap() = IndentFlags::WroteNothing; } fn write_newline(&mut self, target: &mut W, level: usize) -> Result<()> { - try!(target.write(self.config.line_separator.as_bytes())); + target.write(self.config.line_separator.as_bytes())?; for _ in 0..level { - try!(target.write(self.config.indent_string.as_bytes())); + target.write(self.config.indent_string.as_bytes())?; } Ok(()) } @@ -184,7 +160,7 @@ impl Emitter { if self.config.perform_indent && !self.wrote_text() && (self.indent_level > 0 || self.wrote_markup()) { let indent_level = self.indent_level; - try!(self.write_newline(target, indent_level)); + self.write_newline(target, indent_level)?; if self.indent_level > 0 && self.config.indent_string.len() > 0 { self.after_markup(); } @@ -197,8 +173,8 @@ impl Emitter { } fn before_start_element(&mut self, target: &mut W) -> Result<()> { - try!(self.before_markup(target)); - self.indent_stack.push(IndentFlags::WROTE_NOTHING); + self.before_markup(target)?; + self.indent_stack.push(IndentFlags::WroteNothing); Ok(()) } @@ -238,17 +214,24 @@ impl Emitter { } self.start_document_emitted = true; - wrapped_with!(self; before_markup(target) and after_markup, - try_chain! { - write!(target, "") - } - ) + write!(target, "?>")?; + + Ok(()) + }; + write() + }; + self.after_markup(); + + result } fn check_document_started(&mut self, target: &mut W) -> Result<()> { @@ -272,16 +255,29 @@ impl Emitter { target: &mut W, name: &str, data: Option<&str>) -> Result<()> { - try!(self.check_document_started(target)); - try!(self.fix_non_empty_element(target)); + self.check_document_started(target)?; + self.fix_non_empty_element(target)?; - wrapped_with!(self; before_markup(target) and after_markup, - try_chain! { - write!(target, "") - } - ) + self.before_markup(target)?; + + let result = { + let mut write = || { + write!(target, "")?; + + Ok(()) + }; + write() + }; + + self.after_markup(); + + result } fn emit_start_element_initial(&mut self, target: &mut W, @@ -289,14 +285,12 @@ impl Emitter { attributes: &[Attribute]) -> Result<()> where W: Write { - try_chain! { - self.check_document_started(target), - self.fix_non_empty_element(target), - self.before_start_element(target), - write!(target, "<{}", name.repr_display()), - self.emit_current_namespace_attributes(target), - ignore self.emit_attributes(target, attributes) - } + self.check_document_started(target)?; + self.fix_non_empty_element(target)?; + self.before_start_element(target)?; + write!(target, "<{}", name.repr_display())?; + self.emit_current_namespace_attributes(target)?; + self.emit_attributes(target, attributes)?; self.after_start_element(); Ok(()) } @@ -309,21 +303,22 @@ impl Emitter { if self.config.keep_element_names_stack { self.element_names.push(name.to_owned()); } - try_chain! { - self.emit_start_element_initial(target, name, attributes), - { - self.just_wrote_start_element = true; - if self.config.normalize_empty_elements { Ok(()) } - else { write!(target, ">") } - } + + self.emit_start_element_initial(target, name, attributes)?; + self.just_wrote_start_element = true; + + if !self.config.normalize_empty_elements { + write!(target, ">")?; } + + Ok(()) } pub fn emit_current_namespace_attributes(&mut self, target: &mut W) -> Result<()> where W: Write { for (prefix, uri) in self.nst.peek() { - try!(match prefix { + match prefix { // internal namespaces are not emitted NS_XMLNS_PREFIX | NS_XML_PREFIX => Ok(()), //// there is already a namespace binding with this prefix in scope @@ -334,7 +329,7 @@ impl Emitter { } else { Ok(()) }, // everything else prefix => write!(target, " xmlns:{}=\"{}\"", prefix, uri) - }); + }?; } Ok(()) } @@ -342,12 +337,11 @@ impl Emitter { pub fn emit_attributes(&mut self, target: &mut W, attributes: &[Attribute]) -> Result<()> { for attr in attributes.iter() { - try!(write!( + write!( target, " {}=\"{}\"", attr.name.repr_display(), - if self.config.perform_escaping { escape_str_attribute(attr.value) } - else { Cow::Borrowed(attr.value) } - )) + if self.config.perform_escaping { escape_str_attribute(attr.value) } else { Cow::Borrowed(attr.value) } + )? } Ok(()) } @@ -355,7 +349,7 @@ impl Emitter { pub fn emit_end_element(&mut self, target: &mut W, name: Option) -> Result<()> { let owned_name = if self.config.keep_element_names_stack { - Some(try!(self.element_names.pop().ok_or(EmitterError::LastElementNameNotAvailable))) + Some(self.element_names.pop().ok_or(EmitterError::LastElementNameNotAvailable)?) } else { None }; @@ -378,9 +372,12 @@ impl Emitter { result.map(|_| ()) } else { self.just_wrote_start_element = false; - wrapped_with!(self; before_end_element(target) and after_end_element, - write!(target, "", name.repr_display()).map_err(From::from) - ) + + self.before_end_element(target)?; + let result = write!(target, "", name.repr_display()).map_err(From::from); + self.after_end_element(); + + result } } else { Err(EmitterError::EndElementNameIsNotSpecified) @@ -388,54 +385,63 @@ impl Emitter { } pub fn emit_cdata(&mut self, target: &mut W, content: &str) -> Result<()> { - try!(self.fix_non_empty_element(target)); + self.fix_non_empty_element(target)?; if self.config.cdata_to_characters { self.emit_characters(target, content) } else { // TODO: escape ']]>' characters in CDATA as two adjacent CDATA blocks - try_chain! { - target.write(b"") - }; + target.write(b"")?; + self.after_text(); + Ok(()) } } pub fn emit_characters(&mut self, target: &mut W, content: &str) -> Result<()> { - try!(self.fix_non_empty_element(target)); - try!(target.write( - (if self.config.perform_escaping { escape_str_pcdata(content) } - else { Cow::Borrowed(content) }).as_bytes() - )); + self.fix_non_empty_element(target)?; + target.write( + (if self.config.perform_escaping { + escape_str_pcdata(content) + } else { + Cow::Borrowed(content) + }).as_bytes() + )?; self.after_text(); Ok(()) } pub fn emit_comment(&mut self, target: &mut W, content: &str) -> Result<()> { - try!(self.fix_non_empty_element(target)); + self.fix_non_empty_element(target)?; // TODO: add escaping dashes at the end of the comment let autopad_comments = self.config.autopad_comments; let write = |target: &mut W| -> Result<()> { - try_chain! { - target.write(b"") + target.write(b"")?; + + Ok(()) }; - wrapped_with!(self; before_markup(target) and after_markup, - write(target) - ) + self.before_markup(target)?; + let result = write(target); + self.after_markup(); + + result } } diff --git a/third_party/rust/xml-rs/src/writer/mod.rs b/third_party/rust/xml-rs/src/writer/mod.rs index 53afc67f0832..ea1b24266f3c 100644 --- a/third_party/rust/xml-rs/src/writer/mod.rs +++ b/third_party/rust/xml-rs/src/writer/mod.rs @@ -36,7 +36,7 @@ impl EventWriter { #[inline] pub fn new_with_config(sink: W, config: EmitterConfig) -> EventWriter { EventWriter { - sink: sink, + sink, emitter: Emitter::new(config) } } @@ -72,6 +72,16 @@ impl EventWriter { } } + /// Returns a mutable reference to the underlying `Writer`. + /// + /// Note that having a reference to the underlying sink makes it very easy to emit invalid XML + /// documents. Use this method with care. Valid use cases for this method include accessing + /// methods like `Write::flush`, which do not emit new data but rather change the state + /// of the stream itself. + pub fn inner_mut(&mut self) -> &mut W { + &mut self.sink + } + /// Unwraps this `EventWriter`, returning the underlying writer. /// /// Note that this is a destructive operation: unwrapping a writer and then wrapping diff --git a/toolkit/components/extensions/parent/ext-tabs-base.js b/toolkit/components/extensions/parent/ext-tabs-base.js index 3cc229650fa9..683cd2a261bf 100644 --- a/toolkit/components/extensions/parent/ext-tabs-base.js +++ b/toolkit/components/extensions/parent/ext-tabs-base.js @@ -495,6 +495,15 @@ class TabBase { throw new Error("Not implemented"); } + /** + * @property {integer} successorTabId + * @readonly + * @abstract + */ + get successorTabId() { + throw new Error("Not implemented"); + } + /** * Returns true if this tab matches the the given query info object. Omitted * or null have no effect on the match. @@ -609,6 +618,7 @@ class TabBase { isArticle: this.isArticle, isInReaderMode: this.isInReaderMode, sharingState: this.sharingState, + successorTabId: this.successorTabId, }; // If the tab has not been fully layed-out yet, fallback to the geometry diff --git a/toolkit/components/normandy/actions/ShowHeartbeatAction.jsm b/toolkit/components/normandy/actions/ShowHeartbeatAction.jsm new file mode 100644 index 000000000000..80c22fa7c3e5 --- /dev/null +++ b/toolkit/components/normandy/actions/ShowHeartbeatAction.jsm @@ -0,0 +1,209 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +ChromeUtils.import("resource://gre/modules/Services.jsm"); +ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm"); +ChromeUtils.import("resource://normandy/actions/BaseAction.jsm"); +ChromeUtils.defineModuleGetter(this, "ActionSchemas", "resource://normandy/actions/schemas/index.js"); +ChromeUtils.defineModuleGetter(this, "BrowserWindowTracker", "resource:///modules/BrowserWindowTracker.jsm"); +ChromeUtils.defineModuleGetter(this, "ClientEnvironment", "resource://normandy/lib/ClientEnvironment.jsm"); +ChromeUtils.defineModuleGetter(this, "Heartbeat", "resource://normandy/lib/Heartbeat.jsm"); +ChromeUtils.defineModuleGetter(this, "ShellService", "resource:///modules/ShellService.jsm"); +ChromeUtils.defineModuleGetter(this, "Storage", "resource://normandy/lib/Storage.jsm"); +ChromeUtils.defineModuleGetter(this, "UpdateUtils", "resource://gre/modules/UpdateUtils.jsm"); + +XPCOMUtils.defineLazyServiceGetter(this, "uuidGenerator", "@mozilla.org/uuid-generator;1", "nsIUUIDGenerator"); + +var EXPORTED_SYMBOLS = ["ShowHeartbeatAction"]; + +XPCOMUtils.defineLazyGetter(this, "gAllRecipeStorage", function() { + return new Storage("normandy-heartbeat"); +}); + +const DAY_IN_MS = 24 * 60 * 60 * 1000; +const HEARTBEAT_THROTTLE = 1 * DAY_IN_MS; + +class ShowHeartbeatAction extends BaseAction { + get schema() { + return ActionSchemas["show-heartbeat"]; + } + + async _run(recipe) { + const { + message, + engagementButtonLabel, + thanksMessage, + learnMoreMessage, + learnMoreUrl, + } = recipe.arguments; + + const recipeStorage = new Storage(recipe.id); + + if (!await this.shouldShow(recipeStorage, recipe)) { + return; + } + + this.log.debug(`Heartbeat for recipe ${recipe.id} showing prompt "${message}"`); + const targetWindow = BrowserWindowTracker.getTopWindow(); + + if (!targetWindow) { + throw new Error("No window to show heartbeat in"); + } + + const heartbeat = new Heartbeat(targetWindow, { + surveyId: this.generateSurveyId(recipe), + message, + engagementButtonLabel, + thanksMessage, + learnMoreMessage, + learnMoreUrl, + postAnswerUrl: await this.generatePostAnswerURL(recipe), + flowId: this.uuid(), + surveyVersion: recipe.revision_id, + }); + + heartbeat.eventEmitter.once("Voted", this.updateLastInteraction.bind(this, recipeStorage)); + heartbeat.eventEmitter.once("Engaged", this.updateLastInteraction.bind(this, recipeStorage)); + + let now = Date.now(); + await Promise.all([ + gAllRecipeStorage.setItem("lastShown", now), + recipeStorage.setItem("lastShown", now), + ]); + } + + async shouldShow(recipeStorage, recipe) { + const { repeatOption, repeatEvery } = recipe.arguments; + // Don't show any heartbeats to a user more than once per throttle period + let lastShown = await gAllRecipeStorage.getItem("lastShown"); + if (lastShown) { + const duration = new Date() - lastShown; + if (duration < HEARTBEAT_THROTTLE) { + // show the number of hours since the last heartbeat, with at most 1 decimal point. + const hoursAgo = Math.floor(duration / 1000 / 60 / 6) / 10; + this.log.debug(`A heartbeat was shown too recently (${hoursAgo} hours), skipping recipe ${recipe.id}.`); + return false; + } + } + + switch (repeatOption) { + case "once": { + // Don't show if we've ever shown before + if (await recipeStorage.getItem("lastShown")) { + this.log.debug(`Heartbeat for "once" recipe ${recipe.id} has been shown before, skipping.`); + return false; + } + } + + case "nag": { + // Show a heartbeat again only if the user has not interacted with it before + if (await recipeStorage.getItem("lastInteraction")) { + this.log.debug(`Heartbeat for "nag" recipe ${recipe.id} has already been interacted with, skipping.`); + return false; + } + } + + case "xdays": { + // Show this heartbeat again if it has been at least `repeatEvery` days since the last time it was shown. + let lastShown = await gAllRecipeStorage.getItem("lastShown"); + if (lastShown) { + lastShown = new Date(lastShown); + const duration = new Date() - lastShown; + if (duration < repeatEvery * DAY_IN_MS) { + // show the number of hours since the last time this hearbeat was shown, with at most 1 decimal point. + const hoursAgo = Math.floor(duration / 1000 / 60 / 6) / 10; + this.log.debug( + `Heartbeat for "xdays" recipe ${recipe.id} ran in the last ${repeatEvery} days, skipping. (${hoursAgo} hours ago)` + ); + return false; + } + } + } + } + + return true; + } + + /** + * Returns a surveyId value. If recipe calls to include the Normandy client + * ID, then the client ID is attached to the surveyId in the format + * `${surveyId}::${userId}`. + * + * @return {String} Survey ID, possibly with user UUID + */ + generateSurveyId(recipe) { + const { includeTelemetryUUID, surveyId } = recipe.arguments; + if (includeTelemetryUUID) { + return `${surveyId}::${ClientEnvironment.userId}`; + } + return surveyId; + } + + /* + * Generate a UUID without surrounding brackets, as expected by Heartbeat + * telemetry. + */ + uuid() { + let rv = uuidGenerator.generateUUID().toString(); + return rv.slice(1, rv.length - 1); + } + + /** + * Generate the appropriate post-answer URL for a recipe. + * @param recipe + * @return {String} URL with post-answer query params + */ + async generatePostAnswerURL(recipe) { + const { postAnswerUrl, message, includeTelemetryUUID } = recipe.arguments; + + // Don`t bother with empty URLs. + if (!postAnswerUrl) { + return postAnswerUrl; + } + + const userId = ClientEnvironment.userId; + const searchEngine = await new Promise(resolve => { + Services.search.init(rv => { + if (Components.isSuccessCode(rv)) { + resolve(Services.search.defaultEngine.identifier); + } + }); + }); + + const args = { + fxVersion: Services.appinfo.version, + isDefaultBrowser: ShellService.isDefaultBrowser() ? 1 : 0, + searchEngine, + source: "heartbeat", + // `surveyversion` used to be the version of the heartbeat action when it + // was hosted on a server. Keeping it around for compatibility. + surveyversion: Services.appinfo.version, + syncSetup: Services.prefs.prefHasUserValue("services.sync.username") ? 1 : 0, + updateChannel: UpdateUtils.getUpdateChannel(false), + utm_campaign: encodeURIComponent(message.replace(/\s+/g, "")), + utm_medium: recipe.action, + utm_source: "firefox", + }; + if (includeTelemetryUUID) { + args.userId = userId; + } + + let url = new URL(postAnswerUrl); + // create a URL object to append arguments to + for (const [key, val] of Object.entries(args)) { + if (!url.searchParams.has(key)) { + url.searchParams.set(key, val); + } + } + + // return the address with encoded queries + return url.toString(); + } + + updateLastInteraction(recipeStorage) { + recipeStorage.setItem("lastInteraction", Date.now()); + } +} diff --git a/toolkit/components/normandy/actions/schemas/index.js b/toolkit/components/normandy/actions/schemas/index.js index 70b381d56b7a..cb7ac3caf266 100644 --- a/toolkit/components/normandy/actions/schemas/index.js +++ b/toolkit/components/normandy/actions/schemas/index.js @@ -95,6 +95,72 @@ const ActionSchemas = { }, }, }, + + "show-heartbeat": { + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Show a Heartbeat survey.", + "description": "This action shows a single survey.", + + "type": "object", + "required": [ + "surveyId", + "message", + "thanksMessage", + "postAnswerUrl", + "learnMoreMessage", + "learnMoreUrl", + ], + "properties": { + "repeatOption": { + "type": "string", + "enum": ["once", "xdays", "nag"], + "description": "Determines how often a prompt is shown executes.", + "default": "once", + }, + "repeatEvery": { + "description": "For repeatOption=xdays, how often (in days) the prompt is displayed.", + "default": null, + "type": ["number", "null"], + }, + "includeTelemetryUUID": { + "type": "boolean", + "description": "Include unique user ID in post-answer-url and Telemetry", + "default": false, + }, + "surveyId": { + "type": "string", + "description": "Slug uniquely identifying this survey in telemetry", + }, + "message": { + "description": "Message to show to the user", + "type": "string", + }, + "engagementButtonLabel": { + "description": "Text for the engagement button. If specified, this button will be shown instead of rating stars.", + "default": null, + "type": ["string", "null"], + }, + "thanksMessage": { + "description": "Thanks message to show to the user after they've rated Firefox", + "type": "string", + }, + "postAnswerUrl": { + "description": "URL to redirect the user to after rating Firefox or clicking the engagement button", + "default": null, + "type": ["string", "null"], + }, + "learnMoreMessage": { + "description": "Message to show to the user to learn more", + "default": null, + "type": ["string", "null"], + }, + "learnMoreUrl": { + "description": "URL to show to the user when they click Learn More", + "default": null, + "type": ["string", "null"], + }, + }, + }, }; // Legacy name used on Normandy server diff --git a/toolkit/components/normandy/actions/schemas/package.json b/toolkit/components/normandy/actions/schemas/package.json index 4b669f84aeb3..b07a62f4e794 100644 --- a/toolkit/components/normandy/actions/schemas/package.json +++ b/toolkit/components/normandy/actions/schemas/package.json @@ -1,6 +1,6 @@ { "name": "@mozilla/normandy-action-argument-schemas", - "version": "0.5.0", + "version": "0.6.0", "description": "Schemas for Normandy action arguments", "main": "index.js", "author": "Michael Cooper ", diff --git a/toolkit/components/normandy/lib/ActionsManager.jsm b/toolkit/components/normandy/lib/ActionsManager.jsm index f27490ca8ac1..c941ae8d4bdd 100644 --- a/toolkit/components/normandy/lib/ActionsManager.jsm +++ b/toolkit/components/normandy/lib/ActionsManager.jsm @@ -3,12 +3,13 @@ ChromeUtils.import("resource://normandy/lib/LogManager.jsm"); XPCOMUtils.defineLazyModuleGetters(this, { ActionSandboxManager: "resource://normandy/lib/ActionSandboxManager.jsm", - NormandyApi: "resource://normandy/lib/NormandyApi.jsm", - Uptake: "resource://normandy/lib/Uptake.jsm", AddonStudyAction: "resource://normandy/actions/AddonStudyAction.jsm", ConsoleLogAction: "resource://normandy/actions/ConsoleLogAction.jsm", - PreferenceRolloutAction: "resource://normandy/actions/PreferenceRolloutAction.jsm", + NormandyApi: "resource://normandy/lib/NormandyApi.jsm", PreferenceRollbackAction: "resource://normandy/actions/PreferenceRollbackAction.jsm", + PreferenceRolloutAction: "resource://normandy/actions/PreferenceRolloutAction.jsm", + ShowHeartbeatAction: "resource://normandy/actions/ShowHeartbeatAction.jsm", + Uptake: "resource://normandy/lib/Uptake.jsm", }); var EXPORTED_SYMBOLS = ["ActionsManager"]; @@ -34,9 +35,10 @@ class ActionsManager { this.localActions = { "addon-study": addonStudyAction, "console-log": new ConsoleLogAction(), - "preference-rollout": new PreferenceRolloutAction(), + "opt-out-study": addonStudyAction, // Legacy name used for addon-study on Normandy server "preference-rollback": new PreferenceRollbackAction(), - "opt-out-study": addonStudyAction, // Legacy name used on Normandy server + "preference-rollout": new PreferenceRolloutAction(), + "show-heartbeat": new ShowHeartbeatAction(), }; } diff --git a/toolkit/components/normandy/lib/EventEmitter.jsm b/toolkit/components/normandy/lib/EventEmitter.jsm index 88cb06c588ab..f8a7000605ba 100644 --- a/toolkit/components/normandy/lib/EventEmitter.jsm +++ b/toolkit/components/normandy/lib/EventEmitter.jsm @@ -9,18 +9,10 @@ var EXPORTED_SYMBOLS = ["EventEmitter"]; const log = LogManager.getLogger("event-emitter"); -var EventEmitter = function(sandboxManager) { +var EventEmitter = function() { const listeners = {}; return { - createSandboxedEmitter() { - return sandboxManager.cloneInto({ - on: this.on.bind(this), - off: this.off.bind(this), - once: this.once.bind(this), - }, {cloneFunctions: true}); - }, - emit(eventName, event) { // Fire events async Promise.resolve() @@ -32,7 +24,12 @@ var EventEmitter = function(sandboxManager) { // Clone callbacks array to avoid problems with mutation while iterating const callbacks = Array.from(listeners[eventName]); for (const cb of callbacks) { - cb(sandboxManager.cloneInto(event)); + // Clone event so it can't by modified by the handler + let eventToPass = event; + if (typeof event === "object") { + eventToPass = Object.assign({}, event); + } + cb(eventToPass); } }); }, diff --git a/toolkit/components/normandy/lib/Heartbeat.jsm b/toolkit/components/normandy/lib/Heartbeat.jsm index c0b418a85785..03a704fe6e35 100644 --- a/toolkit/components/normandy/lib/Heartbeat.jsm +++ b/toolkit/components/normandy/lib/Heartbeat.jsm @@ -48,9 +48,6 @@ CleanupManager.addCleanupHandler(() => { * * @param chromeWindow * The chrome window that the heartbeat notification is displayed in. - * @param sandboxManager - * The manager for the sandbox this was called from. Heartbeat will - * increment the hold counter on the manager. * @param {Object} options Options object. * @param {String} options.message * The message, or question, to display on the notification. @@ -60,7 +57,7 @@ CleanupManager.addCleanupHandler(() => { * An identifier for this rating flow. Please note that this is only used to * identify the notification box. * @param {String} [options.engagementButtonLabel=null] - * The text of the engagement button to use instad of stars. If this is null + * The text of the engagement button to use instead of stars. If this is null * or invalid, rating stars are used. * @param {String} [options.learnMoreMessage=null] * The label of the learn more link. No link will be shown if this is null. @@ -77,9 +74,9 @@ CleanupManager.addCleanupHandler(() => { * The url to visit after the user answers the question. */ var Heartbeat = class { - constructor(chromeWindow, sandboxManager, options) { + constructor(chromeWindow, options) { if (typeof options.flowId !== "string") { - throw new Error("flowId must be a string"); + throw new Error(`flowId must be a string, but got ${JSON.stringify(options.flowId)}, a ${typeof options.flowId}`); } if (!options.flowId) { @@ -87,17 +84,13 @@ var Heartbeat = class { } if (typeof options.message !== "string") { - throw new Error("message must be a string"); + throw new Error(`message must be a string, but got ${JSON.stringify(options.message)}, a ${typeof options.message}`); } if (!options.message) { throw new Error("message must not be an empty string"); } - if (!sandboxManager) { - throw new Error("sandboxManager must be provided"); - } - if (options.postAnswerUrl) { options.postAnswerUrl = new URL(options.postAnswerUrl); } else { @@ -113,8 +106,7 @@ var Heartbeat = class { } this.chromeWindow = chromeWindow; - this.eventEmitter = new EventEmitter(sandboxManager); - this.sandboxManager = sandboxManager; + this.eventEmitter = new EventEmitter(); this.options = options; this.surveyResults = {}; this.buttons = null; @@ -237,13 +229,12 @@ var Heartbeat = class { this.close(); }, surveyDuration); - this.sandboxManager.addHold("heartbeat"); CleanupManager.addCleanupHandler(this.close); } maybeNotifyHeartbeat(name, data = {}) { if (this.pingSent) { - log.warn("Heartbeat event recieved after Telemetry ping sent. name:", name, "data:", data); + log.warn("Heartbeat event received after Telemetry ping sent. name:", name, "data:", data); return; } @@ -374,8 +365,6 @@ var Heartbeat = class { // Kill the timers which might call things after we've cleaned up: this.endTimerIfPresent("surveyEndTimer"); this.endTimerIfPresent("engagementCloseTimer"); - - this.sandboxManager.removeHold("heartbeat"); // remove listeners this.chromeWindow.removeEventListener("SSWindowClosing", this.handleWindowClosed); // remove references for garbage collection @@ -386,7 +375,6 @@ var Heartbeat = class { this.rightSpacer = null; this.learnMore = null; this.eventEmitter = null; - this.sandboxManager = null; // Ensure we don't re-enter and release the CleanupManager's reference to us: CleanupManager.removeCleanupHandler(this.close); } diff --git a/toolkit/components/normandy/lib/NormandyDriver.jsm b/toolkit/components/normandy/lib/NormandyDriver.jsm index 2755f439288f..2ebb10f98c4c 100644 --- a/toolkit/components/normandy/lib/NormandyDriver.jsm +++ b/toolkit/components/normandy/lib/NormandyDriver.jsm @@ -11,7 +11,6 @@ ChromeUtils.import("resource://gre/modules/AddonManager.jsm"); ChromeUtils.import("resource://gre/modules/Timer.jsm"); ChromeUtils.import("resource://normandy/lib/LogManager.jsm"); ChromeUtils.import("resource://normandy/lib/Storage.jsm"); -ChromeUtils.import("resource://normandy/lib/Heartbeat.jsm"); ChromeUtils.import("resource://normandy/lib/ClientEnvironment.jsm"); ChromeUtils.import("resource://normandy/lib/PreferenceExperiments.jsm"); @@ -23,7 +22,6 @@ const {generateUUID} = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUID var EXPORTED_SYMBOLS = ["NormandyDriver"]; -const log = LogManager.getLogger("normandy-driver"); const actionLog = LogManager.getLogger("normandy-driver.actions"); var NormandyDriver = function(sandboxManager) { @@ -57,23 +55,6 @@ var NormandyDriver = function(sandboxManager) { actionLog[level](message); }, - showHeartbeat(options) { - log.info(`Showing heartbeat prompt "${options.message}"`); - const aWindow = Services.wm.getMostRecentWindow("navigator:browser"); - - if (!aWindow) { - return sandbox.Promise.reject(new sandbox.Error("No window to show heartbeat in")); - } - - const internalOptions = Object.assign({}, options, {testing: this.testing}); - const heartbeat = new Heartbeat(aWindow, sandboxManager, internalOptions); - return sandbox.Promise.resolve(heartbeat.eventEmitter.createSandboxedEmitter()); - }, - - saveHeartbeatFlow() { - // no-op required by spec - }, - client() { const appinfo = { version: Services.appinfo.version, diff --git a/toolkit/components/normandy/lib/Storage.jsm b/toolkit/components/normandy/lib/Storage.jsm index 1d61f1355c67..3fc1974c0f80 100644 --- a/toolkit/components/normandy/lib/Storage.jsm +++ b/toolkit/components/normandy/lib/Storage.jsm @@ -48,7 +48,7 @@ var Storage = class { /** * Sets an item in the prefixed storage. * @returns {Promise} - * @resolves When the operation is completed succesfully + * @resolves When the operation is completed successfully * @rejects Javascript exception. */ async setItem(name, value) { @@ -63,7 +63,7 @@ var Storage = class { /** * Removes a single item from the prefixed storage. * @returns {Promise} - * @resolves When the operation is completed succesfully + * @resolves When the operation is completed successfully * @rejects Javascript exception. */ async removeItem(name) { @@ -77,7 +77,7 @@ var Storage = class { /** * Clears all storage for the prefix. * @returns {Promise} - * @resolves When the operation is completed succesfully + * @resolves When the operation is completed successfully * @rejects Javascript exception. */ async clear() { diff --git a/toolkit/components/normandy/test/browser/browser.ini b/toolkit/components/normandy/test/browser/browser.ini index 173d31ddd412..4a47111de79f 100644 --- a/toolkit/components/normandy/test/browser/browser.ini +++ b/toolkit/components/normandy/test/browser/browser.ini @@ -11,6 +11,7 @@ skip-if = !healthreport || !telemetry [browser_actions_ConsoleLogAction.js] [browser_actions_PreferenceRolloutAction.js] [browser_actions_PreferenceRollbackAction.js] +[browser_actions_ShowHeartbeatAction.js] [browser_ActionSandboxManager.js] [browser_ActionsManager.js] [browser_AddonStudies.js] diff --git a/toolkit/components/normandy/test/browser/browser_EventEmitter.js b/toolkit/components/normandy/test/browser/browser_EventEmitter.js index 878b4290b29d..7446b52fc7a4 100644 --- a/toolkit/components/normandy/test/browser/browser_EventEmitter.js +++ b/toolkit/components/normandy/test/browser/browser_EventEmitter.js @@ -10,25 +10,24 @@ const evidence = { log: "", }; -function listenerA(x = 1) { +function listenerA(x) { evidence.a += x; evidence.log += "a"; } -function listenerB(x = 1) { +function listenerB(x) { evidence.b += x; evidence.log += "b"; } -function listenerC(x = 1) { +function listenerC(x) { evidence.c += x; evidence.log += "c"; } decorate_task( - withSandboxManager(Assert), - async function(sandboxManager) { - const eventEmitter = new EventEmitter(sandboxManager); + async function() { + const eventEmitter = new EventEmitter(); // Fire an unrelated event, to make sure nothing goes wrong eventEmitter.on("nothing"); @@ -39,7 +38,7 @@ decorate_task( eventEmitter.once("event", listenerC); // one event for all listeners - eventEmitter.emit("event"); + eventEmitter.emit("event", 1); // another event for a and b, since c should have turned off already eventEmitter.emit("event", 10); @@ -98,35 +97,3 @@ decorate_task( is(data.count, 0, "Event data cannot be mutated by handlers."); } ); - -decorate_task( - withSandboxManager(Assert), - async function sandboxedEmitter(sandboxManager) { - const eventEmitter = new EventEmitter(sandboxManager); - - // Event handlers inside the sandbox should be run in response to - // events triggered outside the sandbox. - sandboxManager.addGlobal("emitter", eventEmitter.createSandboxedEmitter()); - sandboxManager.evalInSandbox(` - this.eventCounts = {on: 0, once: 0}; - emitter.on("event", value => { - this.eventCounts.on += value; - }); - emitter.once("eventOnce", value => { - this.eventCounts.once += value; - }); - `); - - eventEmitter.emit("event", 5); - eventEmitter.emit("event", 10); - eventEmitter.emit("eventOnce", 5); - eventEmitter.emit("eventOnce", 10); - await Promise.resolve(); - - const eventCounts = sandboxManager.evalInSandbox("this.eventCounts"); - Assert.deepEqual(eventCounts, { - on: 15, - once: 5, - }, "Events emitted outside a sandbox trigger handlers within a sandbox."); - } -); diff --git a/toolkit/components/normandy/test/browser/browser_Heartbeat.js b/toolkit/components/normandy/test/browser/browser_Heartbeat.js index 01b2f4fbfeaa..eca6438a5e10 100644 --- a/toolkit/components/normandy/test/browser/browser_Heartbeat.js +++ b/toolkit/components/normandy/test/browser/browser_Heartbeat.js @@ -82,7 +82,7 @@ add_task(async function() { const notificationBox = targetWindow.gHighPriorityNotificationBox; const preCount = notificationBox.allNotifications.length; - const hb = new Heartbeat(targetWindow, sandboxManager, { + const hb = new Heartbeat(targetWindow, { testing: true, flowId: "test", message: "test", @@ -128,7 +128,7 @@ add_task(async function() { add_task(async function() { const targetWindow = Services.wm.getMostRecentWindow("navigator:browser"); const notificationBox = targetWindow.gHighPriorityNotificationBox; - const hb = new Heartbeat(targetWindow, sandboxManager, { + const hb = new Heartbeat(targetWindow, { testing: true, flowId: "test", message: "test", @@ -170,7 +170,7 @@ add_task(async function() { add_task(async function() { const targetWindow = await BrowserTestUtils.openNewBrowserWindow(); - const hb = new Heartbeat(targetWindow, sandboxManager, { + const hb = new Heartbeat(targetWindow, { testing: true, flowId: "test", message: "test", diff --git a/toolkit/components/normandy/test/browser/browser_actions_ShowHeartbeatAction.js b/toolkit/components/normandy/test/browser/browser_actions_ShowHeartbeatAction.js new file mode 100644 index 000000000000..6157a8da293b --- /dev/null +++ b/toolkit/components/normandy/test/browser/browser_actions_ShowHeartbeatAction.js @@ -0,0 +1,298 @@ +"use strict"; + +ChromeUtils.import("resource://normandy/actions/ShowHeartbeatAction.jsm", this); +ChromeUtils.import("resource://normandy/lib/ClientEnvironment.jsm", this); +ChromeUtils.import("resource://normandy/lib/Heartbeat.jsm", this); +ChromeUtils.import("resource://normandy/lib/Storage.jsm", this); +ChromeUtils.import("resource://normandy/lib/Uptake.jsm", this); + +const HOUR_IN_MS = 60 * 60 * 1000; + +function heartbeatRecipeFactory(overrides = {}) { + const defaults = { + revision_id: 1, + name: "Test Recipe", + action: "show-heartbeat", + arguments: { + surveyId: "a survey", + message: "test message", + engagementButtonLabel: "", + thanksMessage: "thanks!", + postAnswerUrl: "http://example.com", + learnMoreMessage: "Learn More", + learnMoreUrl: "http://example.com", + repeatOption: "once", + }, + }; + + if (overrides.arguments) { + defaults.arguments = Object.assign(defaults.arguments, overrides.arguments); + delete overrides.arguments; + } + + return recipeFactory(Object.assign(defaults, overrides)); +} + +class MockHeartbeat { + constructor() { + this.eventEmitter = new MockEventEmitter(); + } +} + +class MockEventEmitter { + constructor() { + this.once = sinon.stub(); + } +} + +function withStubbedHeartbeat(testFunction) { + return async function wrappedTestFunction(...args) { + const backstage = ChromeUtils.import("resource://normandy/actions/ShowHeartbeatAction.jsm", {}); + const originalHeartbeat = backstage.Heartbeat; + const heartbeatInstanceStub = new MockHeartbeat(); + const heartbeatClassStub = sinon.stub(); + heartbeatClassStub.returns(heartbeatInstanceStub); + backstage.Heartbeat = heartbeatClassStub; + + try { + await testFunction({heartbeatClassStub, heartbeatInstanceStub}, ...args); + } finally { + backstage.Heartbeat = originalHeartbeat; + } + }; +} + +function withClearStorage(testFunction) { + return async function wrappedTestFunction(...args) { + Storage.clearAllStorage(); + try { + await testFunction(...args); + } finally { + Storage.clearAllStorage(); + } + }; +} + +// Test that a normal heartbeat works as expected +decorate_task( + withStubbedHeartbeat, + withClearStorage, + async function testHappyPath({ heartbeatClassStub, heartbeatInstanceStub }) { + const recipe = heartbeatRecipeFactory(); + const action = new ShowHeartbeatAction(); + await action.runRecipe(recipe); + await action.finalize(); + is(action.state, ShowHeartbeatAction.STATE_FINALIZED, "Action should be finalized"); + is(action.lastError, null, "No errors should have been thrown"); + + const options = heartbeatClassStub.args[0][1]; + Assert.deepEqual( + heartbeatClassStub.args, + [[ + heartbeatClassStub.args[0][0], // target window + { + surveyId: options.surveyId, + message: recipe.arguments.message, + engagementButtonLabel: recipe.arguments.engagementButtonLabel, + thanksMessage: recipe.arguments.thanksMessage, + learnMoreMessage: recipe.arguments.learnMoreMessage, + learnMoreUrl: recipe.arguments.learnMoreUrl, + postAnswerUrl: options.postAnswerUrl, + flowId: options.flowId, + surveyVersion: recipe.revision_id, + }, + ]], + "expected arguments were passed", + ); + + const uuidRegex = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/i; + ok(options.flowId.match(uuidRegex), "flowId should be a uuid"); + + // postAnswerUrl gains several query string parameters. Check that the prefix is right + ok(options.postAnswerUrl.startsWith(recipe.arguments.postAnswerUrl)); + + ok(heartbeatInstanceStub.eventEmitter.once.calledWith("Voted"), "Voted event handler should be registered"); + ok(heartbeatInstanceStub.eventEmitter.once.calledWith("Engaged"), "Engaged event handler should be registered"); + } +); + +/* Test that heartbeat doesn't show if an unrelated heartbeat has shown recently. */ +decorate_task( + withStubbedHeartbeat, + withClearStorage, + async function testRepeatGeneral({ heartbeatClassStub }) { + const allHeartbeatStorage = new Storage("normandy-heartbeat"); + await allHeartbeatStorage.setItem("lastShown", Date.now()); + const recipe = heartbeatRecipeFactory(); + + const action = new ShowHeartbeatAction(); + await action.runRecipe(recipe); + is(action.lastError, null, "No errors should have been thrown"); + + is(heartbeatClassStub.args.length, 0, "Heartbeat should not be called once"); + }, +); + +/* Test that a heartbeat shows if an unrelated heartbeat showed more than 24 hours ago. */ +decorate_task( + withStubbedHeartbeat, + withClearStorage, + async function testRepeatUnrelated({ heartbeatClassStub }) { + const allHeartbeatStorage = new Storage("normandy-heartbeat"); + await allHeartbeatStorage.setItem("lastShown", Date.now() - 25 * HOUR_IN_MS); + const recipe = heartbeatRecipeFactory(); + + const action = new ShowHeartbeatAction(); + await action.runRecipe(recipe); + is(action.lastError, null, "No errors should have been thrown"); + + is(heartbeatClassStub.args.length, 1, "Heartbeat should be called once"); + }, +); + +/* Test that a repeat=once recipe is not shown again, even more than 24 hours ago. */ +decorate_task( + withStubbedHeartbeat, + withClearStorage, + async function testRepeatTypeOnce({ heartbeatClassStub }) { + const recipe = heartbeatRecipeFactory({ arguments: { repeatOption: "once" }}); + const recipeStorage = new Storage(recipe.id); + await recipeStorage.setItem("lastShown", Date.now() - 25 * HOUR_IN_MS); + + const action = new ShowHeartbeatAction(); + await action.runRecipe(recipe); + is(action.lastError, null, "No errors should have been thrown"); + + is(heartbeatClassStub.args.length, 0, "Heartbeat should not be called"); + }, +); + +/* Test that a repeat=xdays recipe is shown again, only after the expected number of days. */ +decorate_task( + withStubbedHeartbeat, + withClearStorage, + async function testRepeatTypeXdays({ heartbeatClassStub }) { + const recipe = heartbeatRecipeFactory({ arguments: { + repeatOption: "xdays", + repeatEvery: 2, + }}); + const recipeStorage = new Storage(recipe.id); + const allHeartbeatStorage = new Storage("normandy-heartbeat"); + + await recipeStorage.setItem("lastShown", Date.now() - 25 * HOUR_IN_MS); + await allHeartbeatStorage.setItem("lastShown", Date.now() - 25 * HOUR_IN_MS); + const action = new ShowHeartbeatAction(); + await action.runRecipe(recipe); + is(action.lastError, null, "No errors should have been thrown"); + is(heartbeatClassStub.args.length, 0, "Heartbeat should not be called"); + + await recipeStorage.setItem("lastShown", Date.now() - 50 * HOUR_IN_MS); + await allHeartbeatStorage.setItem("lastShown", Date.now() - 50 * HOUR_IN_MS); + await action.runRecipe(recipe); + is(action.lastError, null, "No errors should have been thrown"); + is(heartbeatClassStub.args.length, 1, "Heartbeat should have been called once"); + }, +); + +/* Test that a repeat=nag recipe is shown again until lastInteraction is set */ +decorate_task( + withStubbedHeartbeat, + withClearStorage, + async function testRepeatTypeNag({ heartbeatClassStub }) { + const recipe = heartbeatRecipeFactory({ arguments: { repeatOption: "nag" }}); + const recipeStorage = new Storage(recipe.id); + const allHeartbeatStorage = new Storage("normandy-heartbeat"); + + await allHeartbeatStorage.setItem("lastShown", Date.now() - 25 * HOUR_IN_MS); + await recipeStorage.setItem("lastShown", Date.now() - 25 * HOUR_IN_MS); + const action = new ShowHeartbeatAction(); + await action.runRecipe(recipe); + is(action.lastError, null, "No errors should have been thrown"); + is(heartbeatClassStub.args.length, 1, "Heartbeat should be called"); + + await allHeartbeatStorage.setItem("lastShown", Date.now() - 50 * HOUR_IN_MS); + await recipeStorage.setItem("lastShown", Date.now() - 50 * HOUR_IN_MS); + await action.runRecipe(recipe); + is(action.lastError, null, "No errors should have been thrown"); + is(heartbeatClassStub.args.length, 2, "Heartbeat should be called again"); + + await allHeartbeatStorage.setItem("lastShown", Date.now() - 75 * HOUR_IN_MS); + await recipeStorage.setItem("lastShown", Date.now() - 75 * HOUR_IN_MS); + await recipeStorage.setItem("lastInteraction", Date.now() - 50 * HOUR_IN_MS); + await action.runRecipe(recipe); + is(action.lastError, null, "No errors should have been thrown"); + is(heartbeatClassStub.args.length, 2, "Heartbeat should not be called again"); + }, +); + +/* generatePostAnswerURL shouldn't annotate empty strings */ +add_task( + async function postAnswerEmptyString() { + const recipe = heartbeatRecipeFactory({ arguments: { postAnswerUrl: "" }}); + const action = new ShowHeartbeatAction(); + is(await action.generatePostAnswerURL(recipe), "", "an empty string should not be annotated"); + } +); + +/* generatePostAnswerURL should include the right details */ +add_task( + async function postAnswerUrl() { + const recipe = heartbeatRecipeFactory({ arguments: { + postAnswerUrl: "https://example.com/survey?survey_id=42", + includeTelemetryUUID: false, + message: "Hello, World!", + }}); + const action = new ShowHeartbeatAction(); + const url = new URL(await action.generatePostAnswerURL(recipe)); + + is(url.searchParams.get("survey_id"), "42", "Pre-existing search parameters should be preserved"); + is(url.searchParams.get("fxVersion"), Services.appinfo.version, "Firefox version should be included"); + is(url.searchParams.get("surveyversion"), Services.appinfo.version, "Survey version should also be the Firefox version"); + ok(["0", "1"].includes(url.searchParams.get("syncSetup")), `syncSetup should be 0 or 1, got ${url.searchParams.get("syncSetup")}`); + is(url.searchParams.get("updateChannel"), UpdateUtils.getUpdateChannel("false"), "Update channel should be included"); + ok(!url.searchParams.has("userId"), "no user id should be included"); + is(url.searchParams.get("utm_campaign"), "Hello%2CWorld!", "utm_campaign should be an encoded version of the message"); + is(url.searchParams.get("utm_medium"), "show-heartbeat", "utm_medium should be the action name"); + is(url.searchParams.get("utm_source"), "firefox", "utm_source should be firefox"); + } +); + +/* generatePostAnswerURL shouldn't override existing values in the url */ +add_task( + async function postAnswerUrlNoOverwite() { + const recipe = heartbeatRecipeFactory({ arguments: { + postAnswerUrl: "https://example.com/survey?utm_source=shady_tims_firey_fox", + }}); + const action = new ShowHeartbeatAction(); + const url = new URL(await action.generatePostAnswerURL(recipe)); + is(url.searchParams.get("utm_source"), "shady_tims_firey_fox", "utm_source should not be overwritten"); + } +); + +/* generatePostAnswerURL should only include userId if requested */ +add_task( + async function postAnswerUrlUserIdIfRequested() { + const recipeWithId = heartbeatRecipeFactory({ arguments: { includeTelemetryUUID: true }}); + const recipeWithoutId = heartbeatRecipeFactory({ arguments: { includeTelemetryUUID: false }}); + const action = new ShowHeartbeatAction(); + + const urlWithId = new URL(await action.generatePostAnswerURL(recipeWithId)); + is(urlWithId.searchParams.get("userId"), ClientEnvironment.userId, "clientId should be included"); + + const urlWithoutId = new URL(await action.generatePostAnswerURL(recipeWithoutId)); + ok(!urlWithoutId.searchParams.has("userId"), "userId should not be included"); + } +); + +/* generateSurveyId should include userId only if requested */ +decorate_task( + withStubbedHeartbeat, + withClearStorage, + async function testGenerateSurveyId({ heartbeatClassStub }) { + const recipeWithoutId = heartbeatRecipeFactory({ arguments: { surveyId: "test-id", includeTelemetryUUID: false }}); + const recipeWithId = heartbeatRecipeFactory({ arguments: { surveyId: "test-id", includeTelemetryUUID: true }}); + const action = new ShowHeartbeatAction(); + is(action.generateSurveyId(recipeWithoutId), "test-id", "userId should not be included if not requested"); + is(action.generateSurveyId(recipeWithId), `test-id::${ClientEnvironment.userId}`, "userId should be included if requested"); + } +); diff --git a/toolkit/components/places/PlacesSearchAutocompleteProvider.jsm b/toolkit/components/places/PlacesSearchAutocompleteProvider.jsm index 0a3a4f4954f8..6b084802ba90 100644 --- a/toolkit/components/places/PlacesSearchAutocompleteProvider.jsm +++ b/toolkit/components/places/PlacesSearchAutocompleteProvider.jsm @@ -137,7 +137,7 @@ class SuggestionsFetch { this._engine = engine; this._suggestions = []; this._success = false; - this._promise = this._controller.fetch(searchString, inPrivateContext, engine, userContextId).then(results => { + this._promise = this._controller.fetch(searchString, engine, userContextId).then(results => { this._success = true; if (results) { this._suggestions.push( diff --git a/toolkit/components/search/SearchSuggestionController.jsm b/toolkit/components/search/SearchSuggestionController.jsm index 2e55832c5487..7c157c69830b 100644 --- a/toolkit/components/search/SearchSuggestionController.jsm +++ b/toolkit/components/search/SearchSuggestionController.jsm @@ -46,6 +46,8 @@ function SearchSuggestionController(callback = null) { } this.SearchSuggestionController.prototype = { + FIRST_PARTY_DOMAIN: "search.suggestions.8c845959-a33d-4787-953c-5d55a0afd56e.mozilla", + /** * The maximum number of local form history results to return. This limit is * only enforced if remote results are also returned. @@ -99,13 +101,15 @@ this.SearchSuggestionController.prototype = { * results from them will not be provided. * * @param {string} searchTerm - the term to provide suggestions for - * @param {bool} privateMode - whether the request is being made in the context of private browsing * @param {nsISearchEngine} engine - search engine for the suggestions. * @param {int} userContextId - the userContextId of the selected tab. + * @param {bool} privateMode - whether the request should be made private. + * Note that usually we want a private context, even in a non-private + * window, because we don't want to store cookies and offline data. * * @return {Promise} resolving to an object containing results or null. */ - fetch(searchTerm, privateMode, engine, userContextId) { + fetch(searchTerm, engine, userContextId = 0, privateMode = true) { // There is no smart filtering from previous results here (as there is when looking through // history/form data) because the result set returned by the server is different for every typed // value - e.g. "ocean breathes" does not return a subset of the results returned for "ocean". @@ -115,9 +119,6 @@ this.SearchSuggestionController.prototype = { if (!Services.search.isInitialized) { throw new Error("Search not initialized yet (how did you get here?)"); } - if (typeof privateMode === "undefined") { - throw new Error("The privateMode argument is required to avoid unintentional privacy leaks"); - } if (!(engine instanceof Ci.nsISearchEngine)) { throw new Error("Invalid search engine"); } @@ -231,8 +232,12 @@ this.SearchSuggestionController.prototype = { let method = (submission.postData ? "POST" : "GET"); this._request.open(method, submission.uri.spec, true); - this._request.setOriginAttributes({userContextId, - privateBrowsingId: privateMode ? 1 : 0}); + this._request.setOriginAttributes({ + userContextId, + privateBrowsingId: privateMode ? 1 : 0, + // Use a unique first-party domain to isolate the suggestions cookies. + firstPartyDomain: this.FIRST_PARTY_DOMAIN, + }); this._request.mozBackgroundRequest = true; // suppress dialogs and fail silently diff --git a/toolkit/components/search/nsSearchSuggestions.js b/toolkit/components/search/nsSearchSuggestions.js index 285dd6bb1653..cbfbb1a61ac2 100644 --- a/toolkit/components/search/nsSearchSuggestions.js +++ b/toolkit/components/search/nsSearchSuggestions.js @@ -119,19 +119,10 @@ SuggestAutoComplete.prototype = { var formHistorySearchParam = searchParam.split("|")[0]; - // Receive the information about the privacy mode of the window to which - // this search box belongs. The front-end's search.xml bindings passes this - // information in the searchParam parameter. The alternative would have - // been to modify nsIAutoCompleteSearch to add an argument to startSearch - // and patch all of autocomplete to be aware of this, but the searchParam - // argument is already an opaque argument, so this solution is hopefully - // less hackish (although still gross.) - var privacyMode = (searchParam.split("|")[1] == "private"); - // Start search immediately if possible, otherwise once the search // service is initialized if (Services.search.isInitialized) { - this._triggerSearch(searchString, formHistorySearchParam, listener, privacyMode); + this._triggerSearch(searchString, formHistorySearchParam, listener); return; } @@ -140,17 +131,16 @@ SuggestAutoComplete.prototype = { Cu.reportError("Could not initialize search service, bailing out: " + aResult); return; } - this._triggerSearch(searchString, formHistorySearchParam, listener, privacyMode); + this._triggerSearch(searchString, formHistorySearchParam, listener); }); }, /** * Actual implementation of search. */ - _triggerSearch(searchString, searchParam, listener, privacyMode) { + _triggerSearch(searchString, searchParam, listener) { this._listener = listener; this._suggestionController.fetch(searchString, - privacyMode, Services.search.defaultEngine); }, diff --git a/toolkit/components/search/tests/xpcshell/data/searchSuggestions.sjs b/toolkit/components/search/tests/xpcshell/data/searchSuggestions.sjs index bf02317fe673..79e06b9b1f46 100644 --- a/toolkit/components/search/tests/xpcshell/data/searchSuggestions.sjs +++ b/toolkit/components/search/tests/xpcshell/data/searchSuggestions.sjs @@ -21,7 +21,10 @@ function handleRequest(request, response) { response.setStatusLine(request.httpVersion, 200, "OK"); let q = request.method == "GET" ? query.q : undefined; - if (q == "no remote" || q == "no results") { + if (q == "cookie") { + response.setHeader("Set-Cookie", "cookie=1"); + writeSuggestions(q); + } else if (q == "no remote" || q == "no results") { writeSuggestions(q); } else if (q == "Query Mismatch") { writeSuggestions("This is an incorrect query string", ["some result"]); diff --git a/toolkit/components/search/tests/xpcshell/test_searchSuggest.js b/toolkit/components/search/tests/xpcshell/test_searchSuggest.js index 6775594f2898..9631d41a8d73 100644 --- a/toolkit/components/search/tests/xpcshell/test_searchSuggest.js +++ b/toolkit/components/search/tests/xpcshell/test_searchSuggest.js @@ -96,7 +96,7 @@ add_task(async function simple_no_result_callback() { resolve(); }); - controller.fetch("no remote", false, getEngine); + controller.fetch("no remote", getEngine); }); }); @@ -110,7 +110,7 @@ add_task(async function simple_no_result_callback_and_promise() { deferred.resolve(); }); - let result = await controller.fetch("no results", false, getEngine); + let result = await controller.fetch("no results", getEngine); Assert.equal(result.term, "no results"); Assert.equal(result.local.length, 0); Assert.equal(result.remote.length, 0); @@ -120,7 +120,7 @@ add_task(async function simple_no_result_callback_and_promise() { add_task(async function simple_no_result_promise() { let controller = new SearchSuggestionController(); - let result = await controller.fetch("no remote", false, getEngine); + let result = await controller.fetch("no remote", getEngine); Assert.equal(result.term, "no remote"); Assert.equal(result.local.length, 0); Assert.equal(result.remote.length, 0); @@ -128,7 +128,7 @@ add_task(async function simple_no_result_promise() { add_task(async function simple_remote_no_local_result() { let controller = new SearchSuggestionController(); - let result = await controller.fetch("mo", false, getEngine); + let result = await controller.fetch("mo", getEngine); Assert.equal(result.term, "mo"); Assert.equal(result.local.length, 0); Assert.equal(result.remote.length, 3); @@ -139,7 +139,7 @@ add_task(async function simple_remote_no_local_result() { add_task(async function simple_remote_no_local_result_alternative_type() { let controller = new SearchSuggestionController(); - let result = await controller.fetch("mo", false, alternateJSONEngine); + let result = await controller.fetch("mo", alternateJSONEngine); Assert.equal(result.term, "mo"); Assert.equal(result.local.length, 0); Assert.equal(result.remote.length, 3); @@ -150,7 +150,7 @@ add_task(async function simple_remote_no_local_result_alternative_type() { add_task(async function remote_term_case_mismatch() { let controller = new SearchSuggestionController(); - let result = await controller.fetch("Query Case Mismatch", false, getEngine); + let result = await controller.fetch("Query Case Mismatch", getEngine); Assert.equal(result.term, "Query Case Mismatch"); Assert.equal(result.remote.length, 1); Assert.equal(result.remote[0], "Query Case Mismatch"); @@ -160,7 +160,7 @@ add_task(async function simple_local_no_remote_result() { await updateSearchHistory("bump", "no remote entries"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("no remote", false, getEngine); + let result = await controller.fetch("no remote", getEngine); Assert.equal(result.term, "no remote"); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "no remote entries"); @@ -173,7 +173,7 @@ add_task(async function simple_non_ascii() { await updateSearchHistory("bump", "I ❤️ XUL"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("I ❤️", false, getEngine); + let result = await controller.fetch("I ❤️", getEngine); Assert.equal(result.term, "I ❤️"); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "I ❤️ XUL"); @@ -185,7 +185,7 @@ add_task(async function both_local_remote_result_dedupe() { await updateSearchHistory("bump", "Mozilla"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("mo", false, getEngine); + let result = await controller.fetch("mo", getEngine); Assert.equal(result.term, "mo"); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "Mozilla"); @@ -196,7 +196,7 @@ add_task(async function both_local_remote_result_dedupe() { add_task(async function POST_both_local_remote_result_dedupe() { let controller = new SearchSuggestionController(); - let result = await controller.fetch("mo", false, postEngine); + let result = await controller.fetch("mo", postEngine); Assert.equal(result.term, "mo"); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "Mozilla"); @@ -209,7 +209,7 @@ add_task(async function both_local_remote_result_dedupe2() { await updateSearchHistory("bump", "mom"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("mo", false, getEngine); + let result = await controller.fetch("mo", getEngine); Assert.equal(result.term, "mo"); Assert.equal(result.local.length, 2); Assert.equal(result.local[0], "mom"); @@ -223,7 +223,7 @@ add_task(async function both_local_remote_result_dedupe3() { await updateSearchHistory("bump", "modern"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("mo", false, getEngine); + let result = await controller.fetch("mo", getEngine); Assert.equal(result.term, "mo"); Assert.equal(result.local.length, 3); Assert.equal(result.local[0], "modern"); @@ -238,10 +238,10 @@ add_task(async function fetch_twice_in_a_row() { await updateSearchHistory("bump", "delayed local"); let controller = new SearchSuggestionController(); - let resultPromise1 = controller.fetch("delay", false, getEngine); + let resultPromise1 = controller.fetch("delay", getEngine); // A second fetch while the server is still waiting to return results leads to an abort. - let resultPromise2 = controller.fetch("delayed ", false, getEngine); + let resultPromise2 = controller.fetch("delayed ", getEngine); await resultPromise1.then((results) => Assert.equal(null, results)); let result = await resultPromise2; @@ -259,7 +259,7 @@ add_task(async function fetch_twice_subset_reuse_formHistoryResult() { await updateSearchHistory("bump", "delayed local"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("delay", false, getEngine); + let result = await controller.fetch("delay", getEngine); Assert.equal(result.term, "delay"); Assert.equal(result.local.length, 2); Assert.equal(result.local[0], "delay local"); @@ -270,7 +270,7 @@ add_task(async function fetch_twice_subset_reuse_formHistoryResult() { // Remove the entry from the DB but it should remain in the cached formHistoryResult. await updateSearchHistory("remove", "delayed local"); - let result2 = await controller.fetch("delayed ", false, getEngine); + let result2 = await controller.fetch("delayed ", getEngine); Assert.equal(result2.term, "delayed "); Assert.equal(result2.local.length, 1); Assert.equal(result2.local[0], "delayed local"); @@ -287,7 +287,7 @@ add_task(async function both_identical_with_more_than_max_results() { let controller = new SearchSuggestionController(); controller.maxLocalResults = 7; controller.maxRemoteResults = 10; - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 7); for (let i = 0; i < controller.maxLocalResults; i++) { @@ -304,7 +304,7 @@ add_task(async function noremote_maxLocal() { let controller = new SearchSuggestionController(); controller.maxLocalResults = 2; // (should be ignored because no remote results) controller.maxRemoteResults = 0; - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 26); for (let i = 0; i < result.local.length; i++) { @@ -317,7 +317,7 @@ add_task(async function someremote_maxLocal() { let controller = new SearchSuggestionController(); controller.maxLocalResults = 2; controller.maxRemoteResults = 4; - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 2); for (let i = 0; i < result.local.length; i++) { @@ -334,7 +334,7 @@ add_task(async function one_of_each() { let controller = new SearchSuggestionController(); controller.maxLocalResults = 1; controller.maxRemoteResults = 2; - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "letter A"); @@ -347,7 +347,7 @@ add_task(async function local_result_returned_remote_result_disabled() { let controller = new SearchSuggestionController(); controller.maxLocalResults = 1; controller.maxRemoteResults = 1; - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 26); for (let i = 0; i < 26; i++) { @@ -362,7 +362,7 @@ add_task(async function local_result_returned_remote_result_disabled_after_creat controller.maxLocalResults = 1; controller.maxRemoteResults = 1; Services.prefs.setBoolPref("browser.search.suggest.enabled", false); - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 26); for (let i = 0; i < 26; i++) { @@ -378,7 +378,7 @@ add_task(async function one_of_each_disabled_before_creation_enabled_after_creat controller.maxLocalResults = 1; controller.maxRemoteResults = 2; Services.prefs.setBoolPref("browser.search.suggest.enabled", true); - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "letter A"); @@ -394,7 +394,7 @@ add_task(async function one_local_zero_remote() { let controller = new SearchSuggestionController(); controller.maxLocalResults = 1; controller.maxRemoteResults = 0; - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 26); for (let i = 0; i < 26; i++) { @@ -407,7 +407,7 @@ add_task(async function zero_local_one_remote() { let controller = new SearchSuggestionController(); controller.maxLocalResults = 0; controller.maxRemoteResults = 1; - let result = await controller.fetch("letter ", false, getEngine); + let result = await controller.fetch("letter ", getEngine); Assert.equal(result.term, "letter "); Assert.equal(result.local.length, 0); Assert.equal(result.remote.length, 1); @@ -418,7 +418,7 @@ add_task(async function stop_search() { let controller = new SearchSuggestionController((result) => { do_throw("The callback shouldn't be called after stop()"); }); - let resultPromise = controller.fetch("mo", false, getEngine); + let resultPromise = controller.fetch("mo", getEngine); controller.stop(); await resultPromise.then((result) => { Assert.equal(null, result); @@ -428,7 +428,7 @@ add_task(async function stop_search() { add_task(async function empty_searchTerm() { // Empty searches don't go to the server but still get form history. let controller = new SearchSuggestionController(); - let result = await controller.fetch("", false, getEngine); + let result = await controller.fetch("", getEngine); Assert.equal(result.term, ""); Assert.ok(result.local.length > 0); Assert.equal(result.remote.length, 0); @@ -450,7 +450,7 @@ add_task(async function slow_timeout() { check_result(result); d.resolve(); }, 2000); - let result = await controller.fetch("slow ", false, getEngine); + let result = await controller.fetch("slow ", getEngine); check_result(result); await d.promise; }); @@ -458,7 +458,7 @@ add_task(async function slow_timeout() { add_task(async function slow_stop() { let d = PromiseUtils.defer(); let controller = new SearchSuggestionController(); - let resultPromise = controller.fetch("slow ", false, getEngine); + let resultPromise = controller.fetch("slow ", getEngine); setTimeout(function check_timeout() { // The HTTP response takes 10 seconds but we timeout in less than a second so just use 0. controller.stop(); @@ -478,7 +478,7 @@ add_task(async function remote_term_mismatch() { await updateSearchHistory("bump", "Query Mismatch Entry"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("Query Mismatch", false, getEngine); + let result = await controller.fetch("Query Mismatch", getEngine); Assert.equal(result.term, "Query Mismatch"); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "Query Mismatch Entry"); @@ -489,7 +489,7 @@ add_task(async function http_404() { await updateSearchHistory("bump", "HTTP 404 Entry"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("HTTP 404", false, getEngine); + let result = await controller.fetch("HTTP 404", getEngine); Assert.equal(result.term, "HTTP 404"); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "HTTP 404 Entry"); @@ -500,7 +500,7 @@ add_task(async function http_500() { await updateSearchHistory("bump", "HTTP 500 Entry"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("HTTP 500", false, getEngine); + let result = await controller.fetch("HTTP 500", getEngine); Assert.equal(result.term, "HTTP 500"); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "HTTP 500 Entry"); @@ -511,7 +511,7 @@ add_task(async function unresolvable_server() { await updateSearchHistory("bump", "Unresolvable Server Entry"); let controller = new SearchSuggestionController(); - let result = await controller.fetch("Unresolvable Server", false, unresolvableEngine); + let result = await controller.fetch("Unresolvable Server", unresolvableEngine); Assert.equal(result.term, "Unresolvable Server"); Assert.equal(result.local.length, 1); Assert.equal(result.local[0], "Unresolvable Server Entry"); @@ -521,24 +521,17 @@ add_task(async function unresolvable_server() { // Exception handling -add_task(async function missing_pb() { - Assert.throws(() => { - let controller = new SearchSuggestionController(); - controller.fetch("No privacy"); - }, /priva/i); -}); - add_task(async function missing_engine() { Assert.throws(() => { let controller = new SearchSuggestionController(); - controller.fetch("No engine", false); + controller.fetch("No engine"); }, /engine/i); }); add_task(async function invalid_engine() { Assert.throws(() => { let controller = new SearchSuggestionController(); - controller.fetch("invalid engine", false, {}); + controller.fetch("invalid engine", {}); }, /engine/i); }); @@ -547,7 +540,7 @@ add_task(async function no_results_requested() { let controller = new SearchSuggestionController(); controller.maxLocalResults = 0; controller.maxRemoteResults = 0; - controller.fetch("No results requested", false, getEngine); + controller.fetch("No results requested", getEngine); }, /result/i); }); @@ -555,18 +548,18 @@ add_task(async function minus_one_results_requested() { Assert.throws(() => { let controller = new SearchSuggestionController(); controller.maxLocalResults = -1; - controller.fetch("-1 results requested", false, getEngine); + controller.fetch("-1 results requested", getEngine); }, /result/i); }); add_task(async function test_userContextId() { let controller = new SearchSuggestionController(); - controller._fetchRemote = function(searchTerm, engine, privateMode, userContextId) { + controller._fetchRemote = function(searchTerm, engine, userContextId, privateMode) { Assert.equal(userContextId, 1); return PromiseUtils.defer(); }; - controller.fetch("test", false, getEngine, 1); + controller.fetch("test", getEngine, 1); }); // Helpers diff --git a/toolkit/components/search/tests/xpcshell/test_searchSuggest_cookies.js b/toolkit/components/search/tests/xpcshell/test_searchSuggest_cookies.js new file mode 100644 index 000000000000..fa01e6f967d2 --- /dev/null +++ b/toolkit/components/search/tests/xpcshell/test_searchSuggest_cookies.js @@ -0,0 +1,91 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ +/* eslint-disable mozilla/no-arbitrary-setTimeout */ + +/** + * Testing search suggestions from SearchSuggestionController.jsm. + */ + +"use strict"; + +ChromeUtils.import("resource://gre/modules/FormHistory.jsm"); +ChromeUtils.import("resource://gre/modules/SearchSuggestionController.jsm"); +ChromeUtils.import("resource://gre/modules/Timer.jsm"); +ChromeUtils.import("resource://gre/modules/PromiseUtils.jsm"); + +// We must make sure the FormHistoryStartup component is +// initialized in order for it to respond to FormHistory +// requests from nsFormAutoComplete.js. +var formHistoryStartup = Cc["@mozilla.org/satchel/form-history-startup;1"]. + getService(Ci.nsIObserver); +formHistoryStartup.observe(null, "profile-after-change", null); + +var httpServer = new HttpServer(); +var getEngine; + +add_task(async function setup() { + Services.prefs.setBoolPref("browser.search.suggest.enabled", true); + + let server = useHttpServer(); + server.registerContentType("sjs", "sjs"); + + registerCleanupFunction(async function cleanup() { + Services.prefs.clearUserPref("browser.search.suggest.enabled"); + }); + + [getEngine] = await addTestEngines([ + { + name: "GET suggestion engine", + xmlFileName: "engineMaker.sjs?" + JSON.stringify({ + baseURL: gDataUrl, + name: "GET suggestion engine", + method: "GET", + }), + }, + ]); +}); + +add_task(async function test_private() { + await new Promise(resolve => { + let controller = new SearchSuggestionController((result) => { + Assert.equal(result.term, "cookie"); + Assert.equal(result.local.length, 0); + Assert.equal(result.remote.length, 0); + resolve(); + }); + controller.fetch("cookie", getEngine); + }); + info("Enumerating cookies"); + let enumerator = Services.cookies.enumerator; + let cookies = []; + for (let cookie of enumerator) { + info("Cookie:" + cookie.rawHost + " " + JSON.stringify(cookie.originAttributes)); + cookies.push(cookie); + break; + } + Assert.equal(cookies.length, 0, "Should not find any cookie"); +}); + +add_task(async function test_nonprivate() { + let controller; + await new Promise(resolve => { + controller = new SearchSuggestionController((result) => { + Assert.equal(result.term, "cookie"); + Assert.equal(result.local.length, 0); + Assert.equal(result.remote.length, 0); + resolve(); + }); + controller.fetch("cookie", getEngine, 0, false); + }); + info("Enumerating cookies"); + let enumerator = Services.cookies.enumerator; + let cookies = []; + for (let cookie of enumerator) { + info("Cookie:" + cookie.rawHost + " " + JSON.stringify(cookie.originAttributes)); + cookies.push(cookie); + break; + } + Assert.equal(cookies.length, 1, "Should find one cookie"); + Assert.equal(cookies[0].originAttributes.firstPartyDomain, + controller.FIRST_PARTY_DOMAIN, "Check firstPartyDomain"); +}); diff --git a/toolkit/components/search/tests/xpcshell/xpcshell.ini b/toolkit/components/search/tests/xpcshell/xpcshell.ini index c033c1362d0e..82a94b366a7f 100644 --- a/toolkit/components/search/tests/xpcshell/xpcshell.ini +++ b/toolkit/components/search/tests/xpcshell/xpcshell.ini @@ -66,6 +66,7 @@ support-files = data/search_ignorelist.json [test_multipleIcons.js] [test_resultDomain.js] [test_searchSuggest.js] +[test_searchSuggest_cookies.js] [test_async.js] [test_async_addon.js] tags = addons diff --git a/toolkit/components/telemetry/build_scripts/gen_scalar_data.py b/toolkit/components/telemetry/build_scripts/gen_scalar_data.py index 9b0e1f7bdb3f..869b41ed36c6 100644 --- a/toolkit/components/telemetry/build_scripts/gen_scalar_data.py +++ b/toolkit/components/telemetry/build_scripts/gen_scalar_data.py @@ -147,6 +147,7 @@ def generate_JSON_definitions(output, *filenames): # We don't expire dynamic-builtin scalars: they're only meant for # use in local developer builds anyway. They will expire when rebuilding. 'expired': False, + 'stores': scalar.record_into_store, }) json.dump(scalar_definitions, output) diff --git a/toolkit/components/telemetry/core/ScalarInfo.h b/toolkit/components/telemetry/core/ScalarInfo.h index 7d1f8858a48a..c43b7b80f27d 100644 --- a/toolkit/components/telemetry/core/ScalarInfo.h +++ b/toolkit/components/telemetry/core/ScalarInfo.h @@ -41,15 +41,9 @@ struct BaseScalarInfo { virtual const char *name() const = 0; virtual const char *expiration() const = 0; - virtual uint16_t storeOffset() const - { - return UINT16_MAX; - }; + virtual uint32_t storeOffset() const = 0; - virtual uint32_t storeCount() const - { - return 1; - }; + virtual uint32_t storeCount() const = 0; }; /** @@ -83,7 +77,7 @@ struct ScalarInfo : BaseScalarInfo { const char *name() const override; const char *expiration() const override; - uint16_t storeOffset() const override + uint32_t storeOffset() const override { return store_offset; }; diff --git a/toolkit/components/telemetry/core/TelemetryScalar.cpp b/toolkit/components/telemetry/core/TelemetryScalar.cpp index a4c9d652cff9..ccddf9029979 100644 --- a/toolkit/components/telemetry/core/TelemetryScalar.cpp +++ b/toolkit/components/telemetry/core/TelemetryScalar.cpp @@ -117,6 +117,11 @@ const size_t kScalarActionsArrayHighWaterMark = 10000; const char* TEST_SCALAR_PREFIX = "telemetry.test."; +// The max offset supported by gScalarStoresTable for static scalars' stores. +// Also the sentinel value (with store_count == 0) for just the sole "main" +// store. +const uint32_t kMaxStaticStoreOffset = UINT16_MAX; + enum class ScalarResult : uint8_t { // Nothing went wrong. Ok, @@ -147,16 +152,22 @@ struct ScalarKey { bool dynamic; }; +// Dynamic scalar store names. +StaticAutoPtr>> gDynamicStoreNames; + /** * Scalar information for dynamic definitions. */ struct DynamicScalarInfo : BaseScalarInfo { nsCString mDynamicName; bool mDynamicExpiration; + uint32_t store_count; + uint32_t store_offset; DynamicScalarInfo(uint32_t aKind, bool aRecordOnRelease, bool aExpired, const nsACString& aName, - bool aKeyed, bool aBuiltin) + bool aKeyed, bool aBuiltin, + const nsTArray& aStores) : BaseScalarInfo(aKind, aRecordOnRelease ? nsITelemetry::DATASET_RELEASE_CHANNEL_OPTOUT : @@ -167,13 +178,29 @@ struct DynamicScalarInfo : BaseScalarInfo { aBuiltin) , mDynamicName(aName) , mDynamicExpiration(aExpired) - {} + { + store_count = aStores.Length(); + if (store_count == 0) { + store_count = 1; + store_offset = kMaxStaticStoreOffset; + } else { + store_offset = kMaxStaticStoreOffset + 1 + gDynamicStoreNames->Length(); + for (const auto& storeName: aStores) { + gDynamicStoreNames->AppendElement(NS_Atomize(storeName)); + } + MOZ_ASSERT(gDynamicStoreNames->Length() < UINT32_MAX - kMaxStaticStoreOffset - 1, + "Too many dynamic scalar store names. Overflow."); + } + }; // The following functions will read the stored text // instead of looking it up in the statically generated // tables. const char *name() const override; const char *expiration() const override; + + uint32_t storeCount() const override; + uint32_t storeOffset() const override; }; const char * @@ -191,6 +218,18 @@ DynamicScalarInfo::expiration() const return mDynamicExpiration ? "1.0" : "never"; } +uint32_t +DynamicScalarInfo::storeOffset() const +{ + return store_offset; +} + +uint32_t +DynamicScalarInfo::storeCount() const +{ + return store_count; +} + typedef nsBaseHashtableET CharPtrEntryType; typedef AutoHashtable ScalarMapType; @@ -372,7 +411,7 @@ private: ScalarResult HandleUnsupported() const; const uint32_t mStoreCount; - const uint16_t mStoreOffset; + const uint32_t mStoreOffset; nsTArray mStoreHasValue; }; @@ -410,7 +449,7 @@ ScalarBase::SetValueInStores() nsresult ScalarBase::StoreIndex(const nsACString& aStoreName, size_t* aStoreIndex) const { - if (mStoreCount == 1 && mStoreOffset == UINT16_MAX) { + if (mStoreCount == 1 && mStoreOffset == kMaxStaticStoreOffset) { // This Scalar is only in the "main" store. if (aStoreName.EqualsLiteral("main")) { *aStoreIndex = 0; @@ -420,6 +459,20 @@ ScalarBase::StoreIndex(const nsACString& aStoreName, size_t* aStoreIndex) const } // Multiple stores. Linear scan to find one that matches aStoreName. + // Dynamic Scalars start at kMaxStaticStoreOffset + 1 + if (mStoreOffset > kMaxStaticStoreOffset) { + auto dynamicOffset = mStoreOffset - kMaxStaticStoreOffset - 1; + for (uint32_t i = 0; i < mStoreCount; ++i) { + auto scalarStore = (*gDynamicStoreNames)[dynamicOffset + i]; + if (nsAtomCString(scalarStore).Equals(aStoreName)) { + *aStoreIndex = i; + return NS_OK; + } + } + return NS_ERROR_NO_CONTENT; + } + + // Static Scalars are similar. for (uint32_t i = 0; i < mStoreCount; ++i) { uint32_t stringIndex = gScalarStoresTable[mStoreOffset + i]; if (aStoreName.EqualsASCII(&gScalarsStringTable[stringIndex])) { @@ -1924,6 +1977,9 @@ internal_RegisterScalars(const StaticMutexAutoLock& lock, if (!gDynamicScalarInfo) { gDynamicScalarInfo = new nsTArray(); } + if (!gDynamicStoreNames) { + gDynamicStoreNames = new nsTArray>(); + } for (auto scalarInfo : scalarInfos) { // Allow expiring scalars that were already registered. @@ -2444,6 +2500,7 @@ TelemetryScalar::InitializeGlobalState(bool aCanRecordBase, bool aCanRecordExten nsAutoCString("telemetry.dynamic_event_counts"), true /* keyed */, false /* built-in */, + {} /* stores */, }, }); internal_RegisterScalars(locker, initialDynamicScalars); @@ -2463,6 +2520,7 @@ TelemetryScalar::DeInitializeGlobalState() gDynamicBuiltinScalarStorageMap.Clear(); gDynamicBuiltinKeyedScalarStorageMap.Clear(); gDynamicScalarInfo = nullptr; + gDynamicStoreNames = nullptr; gInitDone = false; } @@ -3418,10 +3476,60 @@ TelemetryScalar::RegisterScalars(const nsACString& aCategoryName, expired = static_cast(value.toBoolean()); } + // Get the scalar's optional stores list (default to ["main"]). + nsTArray stores; + if (JS_HasProperty(cx, scalarDef, "stores", &hasProperty) && hasProperty) { + bool isArray = false; + if (!JS_GetProperty(cx, scalarDef, "stores", &value) + || !JS_IsArrayObject(cx, value, &isArray) + || !isArray) { + JS_ReportErrorASCII(cx, "Invalid 'stores' for scalar %s.", + PromiseFlatCString(fullName).get()); + return NS_ERROR_FAILURE; + } + + JS::RootedObject arrayObj(cx, &value.toObject()); + uint32_t storesLength = 0; + if (!JS_GetArrayLength(cx, arrayObj, &storesLength)) { + JS_ReportErrorASCII(cx, "Can't get 'stores' array length for scalar %s.", + PromiseFlatCString(fullName).get()); + return NS_ERROR_FAILURE; + } + + for (uint32_t i = 0; i < storesLength; ++i) { + JS::Rooted elt(cx); + if (!JS_GetElement(cx, arrayObj, i, &elt)) { + JS_ReportErrorASCII(cx, + "Can't get element from scalar %s 'stores' array.", + PromiseFlatCString(fullName).get()); + return NS_ERROR_FAILURE; + } + if (!elt.isString()) { + JS_ReportErrorASCII(cx, + "Element in scalar %s 'stores' array isn't a " + "string.", + PromiseFlatCString(fullName).get()); + return NS_ERROR_FAILURE; + } + + nsAutoJSString jsStr; + if (!jsStr.init(cx, elt)) { + return NS_ERROR_FAILURE; + } + + stores.AppendElement(NS_ConvertUTF16toUTF8(jsStr)); + } + // In the event of the usual case (just "main"), save the storage. + if (stores.Length() == 1 && stores[0].EqualsLiteral("main")) { + stores.TruncateLength(0); + } + } + // We defer the actual registration here in case any other event description is invalid. // In that case we don't need to roll back any partial registration. newScalarInfos.AppendElement(DynamicScalarInfo{ - kind, recordOnRelease, expired, fullName, keyed, aBuiltin + kind, recordOnRelease, expired, fullName, keyed, aBuiltin, + std::move(stores) }); } @@ -3679,7 +3787,8 @@ TelemetryScalar::AddDynamicScalarDefinitions( def.expired, def.name, def.keyed, - false /* builtin */}); + false /* builtin */, + {} /* stores */}); } { diff --git a/toolkit/components/telemetry/tests/python/test_gen_scalar_data_json.py b/toolkit/components/telemetry/tests/python/test_gen_scalar_data_json.py index e52831daeab9..d4aeac7c3f84 100644 --- a/toolkit/components/telemetry/tests/python/test_gen_scalar_data_json.py +++ b/toolkit/components/telemetry/tests/python/test_gen_scalar_data_json.py @@ -51,13 +51,15 @@ newscalar: "kind": "nsITelemetry::SCALAR_TYPE_STRING", "expired": False, "record_on_release": True, - "keyed": False + "keyed": False, + "stores": ["main"], }, "withoptin": { "kind": "nsITelemetry::SCALAR_TYPE_COUNT", "expired": False, "record_on_release": False, - "keyed": False + "keyed": False, + "stores": ["main"], } } } diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryScalars.js b/toolkit/components/telemetry/tests/unit/test_TelemetryScalars.js index 2d9ba55e5c22..6ae2a3b7010c 100644 --- a/toolkit/components/telemetry/tests/unit/test_TelemetryScalars.js +++ b/toolkit/components/telemetry/tests/unit/test_TelemetryScalars.js @@ -603,6 +603,42 @@ add_task(async function test_dynamicScalars_registration() { "evaluation": /Invalid or missing 'kind'/, "description": "No scalar must be registered if the batch contains an invalid one", }, + { + "category": "telemetry.test", + "data": { + "invalid_stores": { + kind: Ci.nsITelemetry.SCALAR_TYPE_COUNT, + keyed: false, + stores: true, + }, + }, + "evaluation": /Invalid 'stores'/, + "description": "Registration must fail if 'stores' is of the wrong type", + }, + { + "category": "telemetry.test", + "data": { + "invalid_stores": { + kind: Ci.nsITelemetry.SCALAR_TYPE_COUNT, + keyed: false, + stores: {}, + }, + }, + "evaluation": /Invalid 'stores'/, + "description": "Registration must fail if 'stores' is of the wrong type", + }, + { + "category": "telemetry.test", + "data": { + "invalid_stores": { + kind: Ci.nsITelemetry.SCALAR_TYPE_COUNT, + keyed: false, + stores: [{}], + }, + }, + "evaluation": /'stores' array isn't a string./, + "description": "Registration must fail if element in 'stores' is of the wrong type", + }, ]; for (let testCase of TEST_CASES) { diff --git a/toolkit/components/telemetry/tests/unit/test_TelemetryScalars_buildFaster.js b/toolkit/components/telemetry/tests/unit/test_TelemetryScalars_buildFaster.js index fc913a90b711..609c3427b5b1 100644 --- a/toolkit/components/telemetry/tests/unit/test_TelemetryScalars_buildFaster.js +++ b/toolkit/components/telemetry/tests/unit/test_TelemetryScalars_buildFaster.js @@ -63,6 +63,20 @@ add_task({ "record_on_release": false, "keyed": false, }, + "builtin_dynamic_multi": { + "kind": "nsITelemetry::SCALAR_TYPE_COUNT", + "expired": false, + "record_on_release": false, + "keyed": false, + "stores": ["main", "sync"], + }, + "builtin_dynamic_sync_only": { + "kind": "nsITelemetry::SCALAR_TYPE_COUNT", + "expired": false, + "record_on_release": false, + "keyed": false, + "stores": ["sync"], + }, }, }; @@ -80,11 +94,16 @@ add_task({ // Store to that scalar. const TEST_SCALAR1 = "telemetry.test.builtin_dynamic"; const TEST_SCALAR2 = "telemetry.test.builtin_dynamic_other"; + const TEST_SCALAR3 = "telemetry.test.builtin_dynamic_multi"; + const TEST_SCALAR4 = "telemetry.test.builtin_dynamic_sync_only"; Telemetry.scalarSet(TEST_SCALAR1, 3785); Telemetry.scalarSet(TEST_SCALAR2, true); + Telemetry.scalarSet(TEST_SCALAR3, 1337); + Telemetry.scalarSet(TEST_SCALAR4, 31337); // Check the values we tried to store. const scalars = Telemetry.getSnapshotForScalars("main", false).parent; + const syncScalars = Telemetry.getSnapshotForScalars("sync", false).parent; // Check that they are serialized to the correct format. Assert.equal(typeof(scalars[TEST_SCALAR1]), "number", @@ -98,6 +117,22 @@ add_task({ Assert.equal(scalars[TEST_SCALAR2], true, TEST_SCALAR2 + " must have the correct value."); + Assert.equal(typeof(scalars[TEST_SCALAR3]), "number", + `${TEST_SCALAR3} must be serialized to the correct format.`); + Assert.equal(scalars[TEST_SCALAR3], 1337, + `${TEST_SCALAR3} must have the correct value.`); + Assert.equal(typeof(syncScalars[TEST_SCALAR3]), "number", + `${TEST_SCALAR3} must be serialized in the sync store to the correct format.`); + Assert.equal(syncScalars[TEST_SCALAR3], 1337, + `${TEST_SCALAR3} must have the correct value in the sync snapshot.`); + + Assert.ok(!(TEST_SCALAR4 in scalars), + `${TEST_SCALAR4} must not be in the main store.`); + Assert.equal(typeof(syncScalars[TEST_SCALAR4]), "number", + `${TEST_SCALAR4} must be in the sync snapshot.`); + Assert.equal(syncScalars[TEST_SCALAR4], 31337, + `${TEST_SCALAR4} must have the correct value.`); + // Clean up. await TelemetryController.testShutdown(); await OS.File.remove(FILE_PATH); diff --git a/toolkit/mozapps/update/updater/bspatch.cpp b/toolkit/mozapps/update/updater/bspatch.cpp index e4b5706ef2de..87256969c921 100644 --- a/toolkit/mozapps/update/updater/bspatch.cpp +++ b/toolkit/mozapps/update/updater/bspatch.cpp @@ -71,16 +71,33 @@ MBS_ReadHeader(FILE* file, MBSPatchHeader *header) struct stat hs; s = fstat(fileno(file), &hs); - if (s) + if (s != 0) return READ_ERROR; if (memcmp(header->tag, "MBDIFF10", 8) != 0) return UNEXPECTED_BSPATCH_ERROR; - if (sizeof(MBSPatchHeader) + - header->cblen + - header->difflen + - header->extralen != uint32_t(hs.st_size)) + if (hs.st_size > INT_MAX) + return UNEXPECTED_BSPATCH_ERROR; + + size_t size = static_cast(hs.st_size); + if (size < sizeof(MBSPatchHeader)) + return UNEXPECTED_BSPATCH_ERROR; + size -= sizeof(MBSPatchHeader); + + if (size < header->cblen) + return UNEXPECTED_BSPATCH_ERROR; + size -= header->cblen; + + if (size < header->difflen) + return UNEXPECTED_BSPATCH_ERROR; + size -= header->difflen; + + if (size < header->extralen) + return UNEXPECTED_BSPATCH_ERROR; + size -= header->extralen; + + if (size != 0) return UNEXPECTED_BSPATCH_ERROR; return OK; @@ -90,6 +107,7 @@ int MBS_ApplyPatch(const MBSPatchHeader *header, FILE* patchFile, unsigned char *fbuffer, FILE* file) { + unsigned char *fbufstart = fbuffer; unsigned char *fbufend = fbuffer + header->slen; unsigned char *buf = (unsigned char*) malloc(header->cblen + @@ -112,10 +130,20 @@ MBS_ApplyPatch(const MBSPatchHeader *header, FILE* patchFile, r -= c; wb += c; + + if (c == 0 && r) { + rv = UNEXPECTED_BSPATCH_ERROR; + goto end; + } } { MBSPatchTriple *ctrlsrc = (MBSPatchTriple*) buf; + if (header->cblen % sizeof(MBSPatchTriple) != 0) { + rv = UNEXPECTED_BSPATCH_ERROR; + goto end; + } + unsigned char *diffsrc = buf + header->cblen; unsigned char *extrasrc = diffsrc + header->difflen; @@ -123,7 +151,7 @@ MBS_ApplyPatch(const MBSPatchHeader *header, FILE* patchFile, unsigned char *diffend = extrasrc; unsigned char *extraend = extrasrc + header->extralen; - do { + while (ctrlsrc < ctrlend) { ctrlsrc->x = ntohl(ctrlsrc->x); ctrlsrc->y = ntohl(ctrlsrc->y); ctrlsrc->z = ntohl(ctrlsrc->z); @@ -140,8 +168,8 @@ MBS_ApplyPatch(const MBSPatchHeader *header, FILE* patchFile, /* Add x bytes from oldfile to x bytes from the diff block */ - if (fbuffer + ctrlsrc->x > fbufend || - diffsrc + ctrlsrc->x > diffend) { + if (ctrlsrc->x > static_cast(fbufend - fbuffer) || + ctrlsrc->x > static_cast(diffend - diffsrc)) { rv = UNEXPECTED_BSPATCH_ERROR; goto end; } @@ -157,7 +185,7 @@ MBS_ApplyPatch(const MBSPatchHeader *header, FILE* patchFile, /* Copy y bytes from the extra block */ - if (extrasrc + ctrlsrc->y > extraend) { + if (ctrlsrc->y > static_cast(extraend - extrasrc)) { rv = UNEXPECTED_BSPATCH_ERROR; goto end; } @@ -169,7 +197,8 @@ MBS_ApplyPatch(const MBSPatchHeader *header, FILE* patchFile, /* "seek" forwards in oldfile by z bytes */ - if (fbuffer + ctrlsrc->z > fbufend) { + if (ctrlsrc->z < fbufstart - fbuffer || + ctrlsrc->z > fbufend - fbuffer) { rv = UNEXPECTED_BSPATCH_ERROR; goto end; } @@ -178,7 +207,7 @@ MBS_ApplyPatch(const MBSPatchHeader *header, FILE* patchFile, /* and on to the next control block */ ++ctrlsrc; - } while (ctrlsrc < ctrlend); + } } end: diff --git a/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js b/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js index 8e215be2838d..c545f0740010 100644 --- a/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/configs/recommended.js @@ -36,6 +36,10 @@ module.exports = { "SharedArrayBuffer": false, "StopIteration": false, "dump": true, + // Override the "browser" env definition of "location" to allow writing as it + // is a writeable property. + // See https://bugzilla.mozilla.org/show_bug.cgi?id=1509270#c1 for more information. + "location": true, "openDialog": false, "saveStack": false, "sizeToContent": false, diff --git a/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/browser-window.js b/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/browser-window.js index ab40e655d4bd..704d2519dac0 100644 --- a/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/browser-window.js +++ b/tools/lint/eslint/eslint-plugin-mozilla/lib/environments/browser-window.js @@ -23,16 +23,14 @@ const rootDir = helpers.rootDir; // When updating EXTRA_SCRIPTS or MAPPINGS, be sure to also update the // 'support-files' config in `tools/lint/eslint.yml`. -// These are scripts not included in global-scripts.inc, but which are loaded -// via overlays. +// These are scripts not loaded from browser.xul or global-scripts.inc +// but via other includes. const EXTRA_SCRIPTS = [ "browser/base/content/nsContextMenu.js", - "toolkit/content/contentAreaUtils.js", - "toolkit/content/customElements.js", "browser/components/places/content/editBookmark.js", "browser/components/downloads/content/downloads.js", "browser/components/downloads/content/indicator.js", - // Via editMenuCommands.inc.xul + "toolkit/content/customElements.js", "toolkit/content/editMenuOverlay.js", ]; @@ -53,12 +51,12 @@ const MAPPINGS = { }; const globalScriptsRegExp = - /