Merge autoland to mozilla-central a=merge
authorarthur.iakab <aiakab@mozilla.com>
Thu, 30 Aug 2018 07:35:49 +0300
changeset 433984 95b4b8e25577093b1e2358ce08cdd8c3ee191cc2
parent 433966 e547a1a4ac86d4725d37a57821a1b2979cda9844 (current diff)
parent 433983 8897c80e6240025264a58cf1b3ff7cbdf97c6e76 (diff)
child 434014 af9308e581b85f79ad8b82bdd943df3d3cbc3c07
push id34529
push useraiakab@mozilla.com
push dateThu, 30 Aug 2018 04:36:03 +0000
treeherdermozilla-central@95b4b8e25577 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone63.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge autoland to mozilla-central a=merge
--- a/accessible/tests/browser/events/browser_test_textcaret.js
+++ b/accessible/tests/browser/events/browser_test_textcaret.js
@@ -9,38 +9,37 @@
 function caretMoveChecker(target, caretOffset) {
   return function(event) {
     let cmEvent = event.QueryInterface(nsIAccessibleCaretMoveEvent);
     return cmEvent.accessible == getAccessible(target) && cmEvent.caretOffset == caretOffset;
   };
 }
 
 async function checkURLBarCaretEvents() {
-  let url = "about:mozilla";
+  const kURL = "about:mozilla";
+  let newWin = await BrowserTestUtils.openNewBrowserWindow();
+  newWin.gBrowser.selectedBrowser.loadURI(kURL);
 
-  let onDocLoad = waitForEvent(
+  await waitForEvent(
     EVENT_DOCUMENT_LOAD_COMPLETE,
     event => {
       try {
-        return event.accessible.QueryInterface(nsIAccessibleDocument).URL == url;
+        return event.accessible.QueryInterface(nsIAccessibleDocument).URL == kURL;
       } catch (e) {
         return false;
       }
     }
   );
-  let [ newWin ] = await Promise.all([
-    BrowserTestUtils.openNewBrowserWindow({ url }),
-    onDocLoad
-  ]);
+  info("Loaded " + kURL);
 
   let urlbarInputEl = newWin.document.getElementById("urlbar").inputField;
   let urlbarInput = getAccessible(urlbarInputEl, [ nsIAccessibleText ]);
 
   let onCaretMove = waitForEvents([
-    [ EVENT_TEXT_CARET_MOVED, caretMoveChecker(urlbarInput, url.length) ],
+    [ EVENT_TEXT_CARET_MOVED, caretMoveChecker(urlbarInput, kURL.length) ],
     [ EVENT_FOCUS, urlbarInput ]
   ]);
 
   urlbarInput.caretOffset = -1;
   await onCaretMove;
   ok(true, "Caret move in URL bar #1");
 
   onCaretMove = waitForEvent(
--- a/browser/base/content/browser-captivePortal.js
+++ b/browser/base/content/browser-captivePortal.js
@@ -108,16 +108,22 @@ var CaptivePortalWatcher = {
   },
 
   _captivePortalDetected() {
     if (this._delayedCaptivePortalDetectedInProgress) {
       return;
     }
 
     let win = BrowserWindowTracker.getTopWindow();
+    // Used by tests: ignore the main test window in order to enable testing of
+    // the case where we have no open windows.
+    if (win && win.document.documentElement.getAttribute("ignorecaptiveportal")) {
+      win = null;
+    }
+
     // If no browser window has focus, open and show the tab when we regain focus.
     // This is so that if a different application was focused, when the user
     // (re-)focuses a browser window, we open the tab immediately in that window
     // so they can log in before continuing to browse.
     if (win != Services.ww.activeWindow) {
       this._delayedCaptivePortalDetectedInProgress = true;
       Services.obs.addObserver(this, "xul-window-visible");
     }
@@ -131,16 +137,22 @@ var CaptivePortalWatcher = {
    * the tab if needed after a short delay to allow the recheck to complete.
    */
   _delayedCaptivePortalDetected() {
     if (!this._delayedCaptivePortalDetectedInProgress) {
       return;
     }
 
     let win = BrowserWindowTracker.getTopWindow();
+    // Used by tests: ignore the main test window in order to enable testing of
+    // the case where we have no open windows.
+    if (win && win.document.documentElement.getAttribute("ignorecaptiveportal")) {
+      win = null;
+    }
+
     if (win != Services.ww.activeWindow) {
       // The window that got focused was not a browser window.
       return;
     }
     Services.obs.removeObserver(this, "xul-window-visible");
     this._delayedCaptivePortalDetectedInProgress = false;
 
     if (win != window) {
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -4276,16 +4276,29 @@ function toOpenWindowByType(inType, uri,
   if (topWindow)
     topWindow.focus();
   else if (features)
     window.open(uri, "_blank", features);
   else
     window.open(uri, "_blank", "chrome,extrachrome,menubar,resizable,scrollbars,status,toolbar");
 }
 
+/**
+ * Open a new browser window.
+ *
+ * @param {Object} options
+ *        {
+ *          private: A boolean indicating if the window should be
+ *                   private
+ *          remote:  A boolean indicating if the window should run
+ *                   remote browser tabs or not. If omitted, the window
+ *                   will choose the profile default state.
+ *        }
+ * @return a reference to the new window.
+ */
 function OpenBrowserWindow(options) {
   var telemetryObj = {};
   TelemetryStopwatch.start("FX_NEW_WINDOW_MS", telemetryObj);
 
   var handler = Cc["@mozilla.org/browser/clh;1"]
                   .getService(Ci.nsIBrowserHandler);
   var defaultArgs = handler.defaultArgs;
   var wintype = document.documentElement.getAttribute("windowtype");
--- a/browser/base/content/tabbrowser.js
+++ b/browser/base/content/tabbrowser.js
@@ -5263,16 +5263,20 @@ var TabContextMenu = {
     contextPinTab.hidden = this.contextTab.pinned || multiselectionContext;
     let contextUnpinTab = document.getElementById("context_unpinTab");
     contextUnpinTab.hidden = !this.contextTab.pinned || multiselectionContext;
     let contextPinSelectedTabs = document.getElementById("context_pinSelectedTabs");
     contextPinSelectedTabs.hidden = this.contextTab.pinned || !multiselectionContext;
     let contextUnpinSelectedTabs = document.getElementById("context_unpinSelectedTabs");
     contextUnpinSelectedTabs.hidden = !this.contextTab.pinned || !multiselectionContext;
 
+    // Hide the "Duplicate Tab" if there is a selection present
+    let contextDuplicateTab = document.getElementById("context_duplicateTab");
+    contextDuplicateTab.hidden = multiselectionContext;
+
     // Disable "Close Tabs to the Right" if there are no tabs
     // following it.
     document.getElementById("context_closeTabsToTheEnd").disabled =
       gBrowser.getTabsToTheEndFrom(this.contextTab).length == 0;
 
     // Disable "Close other Tabs" if there are no unpinned tabs.
     let unpinnedTabsToClose = multiselectionContext ?
       gBrowser.visibleTabs.filter(t => !t.multiselected && !t.pinned).length :
--- a/browser/base/content/test/captivePortal/head.js
+++ b/browser/base/content/test/captivePortal/head.js
@@ -15,32 +15,23 @@ const PORTAL_NOTIFICATION_VALUE = "capti
 async function setupPrefsAndRecentWindowBehavior() {
   await SpecialPowers.pushPrefEnv({
     set: [["captivedetect.canonicalURL", CANONICAL_URL],
           ["captivedetect.canonicalContent", CANONICAL_CONTENT]],
   });
   // We need to test behavior when a portal is detected when there is no browser
   // window, but we can't close the default window opened by the test harness.
   // Instead, we deactivate CaptivePortalWatcher in the default window and
-  // exclude it from BrowserWindowTracker.getTopWindow in an attempt to
-  // mask its presence.
+  // exclude it using an attribute to mask its presence.
   window.CaptivePortalWatcher.uninit();
-  let getTopWindowCopy = BrowserWindowTracker.getTopWindow;
-  let defaultWindow = window;
-  BrowserWindowTracker.getTopWindow = () => {
-    let win = getTopWindowCopy();
-    if (win == defaultWindow) {
-      return null;
-    }
-    return win;
-  };
+  window.document.documentElement.setAttribute("ignorecaptiveportal", "true");
 
   registerCleanupFunction(function cleanUp() {
-    BrowserWindowTracker.getTopWindow = getTopWindowCopy;
     window.CaptivePortalWatcher.init();
+    window.document.documentElement.removeAttribute("ignorecaptiveportal");
   });
 }
 
 async function portalDetected() {
   Services.obs.notifyObservers(null, "captive-portal-login");
   await BrowserTestUtils.waitForCondition(() => {
     return cps.state == cps.LOCKED_PORTAL;
   }, "Waiting for Captive Portal Service to update state after portal detected.");
--- a/browser/base/content/test/forms/browser_selectpopup.js
+++ b/browser/base/content/test/forms/browser_selectpopup.js
@@ -585,28 +585,34 @@ add_task(async function test_large_popup
 
   await performLargePopupTests(window);
 
   BrowserTestUtils.removeTab(tab);
 });
 
 // This test checks the same as the previous test but in a new smaller window.
 add_task(async function test_large_popup_in_small_window() {
-  let newwin = await BrowserTestUtils.openNewBrowserWindow({ width: 400, height: 400 });
+  let newWin = await BrowserTestUtils.openNewBrowserWindow();
+
+  let resizePromise = BrowserTestUtils.waitForEvent(newWin, "resize", false, e => {
+    return newWin.innerHeight <= 400 && newWin.innerWidth <= 400;
+  });
+  newWin.resizeTo(400, 400);
+  await resizePromise;
 
   const pageUrl = "data:text/html," + escape(PAGECONTENT_SMALL);
-  let browserLoadedPromise = BrowserTestUtils.browserLoaded(newwin.gBrowser.selectedBrowser);
-  await BrowserTestUtils.loadURI(newwin.gBrowser.selectedBrowser, pageUrl);
+  let browserLoadedPromise = BrowserTestUtils.browserLoaded(newWin.gBrowser.selectedBrowser);
+  await BrowserTestUtils.loadURI(newWin.gBrowser.selectedBrowser, pageUrl);
   await browserLoadedPromise;
 
-  newwin.gBrowser.selectedBrowser.focus();
+  newWin.gBrowser.selectedBrowser.focus();
 
-  await performLargePopupTests(newwin);
+  await performLargePopupTests(newWin);
 
-  await BrowserTestUtils.closeWindow(newwin);
+  await BrowserTestUtils.closeWindow(newWin);
 });
 
 async function performSelectSearchTests(win) {
   let browser = win.gBrowser.selectedBrowser;
   await ContentTask.spawn(browser, null, async function() {
     let doc = content.document;
     let select = doc.getElementById("one");
 
--- a/browser/base/content/test/plugins/browser_private_clicktoplay.js
+++ b/browser/base/content/test/plugins/browser_private_clicktoplay.js
@@ -21,17 +21,18 @@ function finishTest() {
 }
 
 let createPrivateWindow = async function createPrivateWindow(url) {
   gPrivateWindow = await BrowserTestUtils.openNewBrowserWindow({private: true});
   ok(!!gPrivateWindow, "should have created a private window.");
   gPrivateBrowser = gPrivateWindow.getBrowser().selectedBrowser;
 
   BrowserTestUtils.loadURI(gPrivateBrowser, url);
-  await BrowserTestUtils.browserLoaded(gPrivateBrowser);
+  await BrowserTestUtils.browserLoaded(gPrivateBrowser, false, url);
+  info("loaded " + url);
 };
 
 add_task(async function test() {
   registerCleanupFunction(function() {
     clearAllPluginPermissions();
     getTestPlugin().enabledState = Ci.nsIPluginTag.STATE_ENABLED;
     getTestPlugin("Second Test Plug-in").enabledState = Ci.nsIPluginTag.STATE_ENABLED;
   });
--- a/browser/base/content/test/sidebar/browser_sidebar_adopt.js
+++ b/browser/base/content/test/sidebar/browser_sidebar_adopt.js
@@ -14,21 +14,21 @@ function failIfSidebarFocusedFires() {
 }
 
 add_task(async function testAdoptedTwoWindows() {
   // First open a new window, show the sidebar in that window, and close it.
   // Then, open another new window and confirm that the sidebar is closed since it is
   // being adopted from the main window which doesn't have a shown sidebar. See Bug 1407737.
   info("Ensure that sidebar state is adopted only from the opener");
 
-  let win1 = await BrowserTestUtils.openNewBrowserWindow({opener: window});
+  let win1 = await BrowserTestUtils.openNewBrowserWindow();
   await win1.SidebarUI.show("viewBookmarksSidebar");
   await BrowserTestUtils.closeWindow(win1);
 
-  let win2 = await BrowserTestUtils.openNewBrowserWindow({opener: window});
+  let win2 = await BrowserTestUtils.openNewBrowserWindow();
   ok(!win2.document.getElementById("sidebar-button").hasAttribute("checked"), "Sidebar button isn't checked");
   ok(!win2.SidebarUI.isOpen, "Sidebar is closed");
   await BrowserTestUtils.closeWindow(win2);
 });
 
 add_task(async function testEventsReceivedInMainWindow() {
   info("Opening the sidebar and expecting both SidebarShown and SidebarFocused events");
 
@@ -41,17 +41,17 @@ add_task(async function testEventsReceiv
 
   ok(true, "SidebarShown and SidebarFocused events fired on a new window");
 });
 
 add_task(async function testEventReceivedInNewWindow() {
   info("Opening a new window and expecting the SidebarFocused event to not fire");
 
   let promiseNewWindow = BrowserTestUtils.waitForNewWindow();
-  BrowserTestUtils.openNewBrowserWindow({opener: window});
+  BrowserTestUtils.openNewBrowserWindow();
   let win = await promiseNewWindow;
 
   let adoptedShown = BrowserTestUtils.waitForEvent(win, "SidebarShown");
   win.addEventListener("SidebarFocused", failIfSidebarFocusedFires);
 
   registerCleanupFunction(async function() {
     win.removeEventListener("SidebarFocused", failIfSidebarFocusedFires);
     await BrowserTestUtils.closeWindow(win);
--- a/browser/base/content/test/tabs/browser.ini
+++ b/browser/base/content/test/tabs/browser.ini
@@ -22,16 +22,17 @@ support-files =
 [browser_multiselect_tabs_active_tab_selected_by_default.js]
 [browser_multiselect_tabs_bookmark.js]
 [browser_multiselect_tabs_clear_selection_when_tab_switch.js]
 [browser_multiselect_tabs_close_other_tabs.js]
 [browser_multiselect_tabs_close_tabs_to_the_right.js]
 [browser_multiselect_tabs_close_using_shortcuts.js]
 [browser_multiselect_tabs_close.js]
 [browser_multiselect_tabs_copy_through_drag_and_drop.js]
+[browser_multiselect_tabs_duplicate.js]
 [browser_multiselect_tabs_event.js]
 [browser_multiselect_tabs_move_to_another_window_drag.js]
 [browser_multiselect_tabs_move_to_new_window_contextmenu.js]
 [browser_multiselect_tabs_mute_unmute.js]
 [browser_multiselect_tabs_pin_unpin.js]
 [browser_multiselect_tabs_positional_attrs.js]
 [browser_multiselect_tabs_reload.js]
 [browser_multiselect_tabs_reorder.js]
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabs/browser_multiselect_tabs_duplicate.js
@@ -0,0 +1,48 @@
+const PREF_MULTISELECT_TABS = "browser.tabs.multiselect";
+
+add_task(async function setPref() {
+    await SpecialPowers.pushPrefEnv({
+        set: [[PREF_MULTISELECT_TABS, true]]
+    });
+});
+
+add_task(async function test() {
+    let tab1 = await addTab();
+    let tab2 = await addTab();
+    let tab3 = await addTab();
+
+    let menuItemDuplicateTab = document.getElementById("context_duplicateTab");
+
+    is(gBrowser.multiSelectedTabsCount, 0, "Zero multiselected tabs");
+
+    await BrowserTestUtils.switchTab(gBrowser, tab1);
+    await triggerClickOn(tab2, { ctrlKey: true });
+
+    ok(tab1.multiselected, "Tab1 is multiselected");
+    ok(tab2.multiselected, "Tab2 is multiselected");
+    ok(!tab3.multiselected, "Tab3 is not multiselected");
+
+    // Check the context menu with a multiselected tabs
+    updateTabContextMenu(tab2);
+    is(menuItemDuplicateTab.hidden, true, "Duplicate Tab is hidden");
+
+    // Check the context menu with a non-multiselected tab
+    updateTabContextMenu(tab3);
+    is(menuItemDuplicateTab.hidden, false, "Duplicate Tab is visible");
+
+    let newTabOpened = BrowserTestUtils.waitForNewTab(gBrowser, "http://mochi.test:8888/");
+    window.TabContextMenu.contextTab = tab3; // Set proper context for command handler
+    menuItemDuplicateTab.click();
+    let tab4 = await newTabOpened;
+
+    // Selection should be cleared after duplication
+    ok(!tab1.multiselected, "Tab1 is not multiselected");
+    ok(!tab2.multiselected, "Tab2 is not multiselected");
+    ok(!tab4.multiselected, "Tab3 is not multiselected");
+    ok(!tab3.multiselected, "Tab4 is not multiselected");
+
+    BrowserTestUtils.removeTab(tab1);
+    BrowserTestUtils.removeTab(tab2);
+    BrowserTestUtils.removeTab(tab3);
+    BrowserTestUtils.removeTab(tab4);
+});
--- a/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js
+++ b/browser/base/content/test/urlbar/browser_urlbarAddonIframe.js
@@ -1,9 +1,11 @@
-/* eslint-disable mozilla/no-arbitrary-setTimeout */
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
 "use strict";
 
 // The purpose of this test is to test the urlbar popup's add-on iframe.  It has
 // a few parts:
 //
 // (1) This file, a normal browser mochitest.
 // (2) html/js files that are loaded in the urlbar popup's add-on iframe:
 //     urlbarAddonIframe.{html,js}
@@ -128,23 +130,24 @@ add_task(async function() {
   // urlbar.getPanelHeight
   let height = iframe.getBoundingClientRect().height;
   let readHeight = await promiseUrlbarFunctionCall("getPanelHeight");
   Assert.equal(readHeight, height, "getPanelHeight");
 
   // urlbar.setPanelHeight
   let newHeight = height + 100;
   await promiseUrlbarFunctionCall("setPanelHeight", newHeight);
-  await new Promise(resolve => {
-    // The height change is animated, so give it time to complete.  Again, wait
-    // a sec to be safe.
-    setTimeout(resolve, 1000);
+  // The height change is animated, so give it time to complete.
+  await TestUtils.waitForCondition(
+    () => Math.round(iframe.getBoundingClientRect().height) == newHeight,
+    "Wait for panel height change after setPanelHeight"
+  ).catch(ex => {
+    info("Last detected height: " + Math.round(iframe.getBoundingClientRect().height));
+    throw ex;
   });
-  Assert.equal(iframe.getBoundingClientRect().height, newHeight,
-               "setPanelHeight");
 });
 
 function promiseIframeLoad() {
   let msgName = "TestIframeLoadAck";
   return new Promise(resolve => {
     info("Waiting for iframe load ack");
     gMsgMan.addMessageListener(msgName, function onMsg(msg) {
       info("Received iframe load ack");
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -88,16 +88,17 @@ file, You can obtain one at http://mozil
         this.inputField.controllers.insertControllerAt(0, this._copyCutController);
         this.inputField.addEventListener("paste", this);
         this.inputField.addEventListener("mousedown", this);
         this.inputField.addEventListener("mousemove", this);
         this.inputField.addEventListener("mouseout", this);
         this.inputField.addEventListener("overflow", this);
         this.inputField.addEventListener("underflow", this);
         this.inputField.addEventListener("scrollend", this);
+        window.addEventListener("resize", this);
 
         var textBox = document.getAnonymousElementByAttribute(this,
                                                 "anonid", "moz-input-box");
         // Force the Custom Element to upgrade until Bug 1470242 handles this:
         customElements.upgrade(textBox);
         var cxmenu = textBox.menupopup;
         var pasteAndGo;
         cxmenu.addEventListener("popupshowing", function() {
@@ -153,16 +154,17 @@ file, You can obtain one at http://mozil
         this.inputField.controllers.removeController(this._copyCutController);
         this.inputField.removeEventListener("paste", this);
         this.inputField.removeEventListener("mousedown", this);
         this.inputField.removeEventListener("mousemove", this);
         this.inputField.removeEventListener("mouseout", this);
         this.inputField.removeEventListener("overflow", this);
         this.inputField.removeEventListener("underflow", this);
         this.inputField.removeEventListener("scrollend", this);
+        window.removeEventListener("resize", this);
 
         if (this._deferredKeyEventTimeout) {
           clearTimeout(this._deferredKeyEventTimeout);
           this._deferredKeyEventTimeout = null;
         }
 
         // Null out the one-offs' popup and textbox so that it cleans up its
         // internal state for both.  Most importantly, it removes the event
@@ -506,36 +508,51 @@ file, You can obtain one at http://mozil
         <body><![CDATA[
           // This method must not modify the given URL such that calling
           // nsIURIFixup::createFixupURI with the result will produce a different URI.
           return this._mayTrimURLs ? trimURL(aURL) : aURL;
         ]]></body>
       </method>
 
       <field name="_formattingEnabled">true</field>
+
+      <!--
+        If the input value is a URL, the input is not focused, and formatting is
+        enabled, this method highlights the domain, and if mixed content is
+        present, it crosses out the https scheme.  It also ensures that the host
+        is visible (not scrolled out of sight).  Otherwise it removes formatting.
+
+        @param  onlyEnsureFormattedHostVisible
+                Pass true to skip formatting and instead only ensure that the
+                host is visible.
+      -->
       <method name="formatValue">
+        <parameter name="onlyEnsureFormattedHostVisible"/>
         <body><![CDATA[
           // Used to avoid re-entrance in async callbacks.
           let instance = this._formattingInstance = {};
 
           if (!this.editor)
             return;
 
-          // Cleanup previously set styles.
-          this.scheme.value = "";
           let controller, strikeOut, selection;
-          if (this._formattingEnabled) {
-            controller = this.editor.selectionController;
-            strikeOut = controller.getSelection(controller.SELECTION_URLSTRIKEOUT);
-            strikeOut.removeAllRanges();
-            selection = controller.getSelection(controller.SELECTION_URLSECONDARY);
-            selection.removeAllRanges();
-            this.formatScheme(controller.SELECTION_URLSTRIKEOUT, true);
-            this.formatScheme(controller.SELECTION_URLSECONDARY, true);
-            this.inputField.style.setProperty("--urlbar-scheme-size", "0px");
+
+          if (!onlyEnsureFormattedHostVisible) {
+            // Cleanup previously set styles.
+            this.scheme.value = "";
+            if (this._formattingEnabled) {
+              controller = this.editor.selectionController;
+              strikeOut = controller.getSelection(controller.SELECTION_URLSTRIKEOUT);
+              strikeOut.removeAllRanges();
+              selection = controller.getSelection(controller.SELECTION_URLSECONDARY);
+              selection.removeAllRanges();
+              this.formatScheme(controller.SELECTION_URLSTRIKEOUT, true);
+              this.formatScheme(controller.SELECTION_URLSECONDARY, true);
+              this.inputField.style.setProperty("--urlbar-scheme-size", "0px");
+            }
           }
 
           let textNode = this.editor.rootElement.firstChild;
           let value = textNode.textContent;
           if (!value)
             return;
 
           if (this.focused)
@@ -594,17 +611,17 @@ file, You can obtain one at http://mozil
             // char just after the domain, and in such a case we should not
             // scroll to the left.
             if (directionality == window.windowUtils.DIRECTION_RTL &&
                 value[preDomain.length + domain.length] != "\u200E") {
               this.inputField.scrollLeft = this.inputField.scrollLeftMax;
             }
           });
 
-          if (!this._formattingEnabled)
+          if (onlyEnsureFormattedHostVisible || !this._formattingEnabled)
             return;
 
           this.formatScheme(controller.SELECTION_URLSECONDARY);
 
           // Strike out the "https" part if mixed active content is loaded.
           if (this.getAttribute("pageproxystate") == "valid" &&
               value.startsWith("https:") &&
               gBrowser.securityUI.state &
@@ -1429,16 +1446,39 @@ file, You can obtain one at http://mozil
               this.updateTextOverflow();
               break;
             case "TabSelect":
               // The autocomplete controller uses heuristic on some internal caches
               // to handle cases like backspace, autofill or repeated searches.
               // Ensure to clear those internal caches when switching tabs.
               this.controller.resetInternalState();
               break;
+            case "resize":
+              // Make sure the host remains visible in the input field when the
+              // window is resized.  We don't want to hurt resize performance,
+              // though, so do this only after resize events have stopped and a
+              // small timeout has elapsed.
+              if (aEvent.target == window) {
+                if (this._resizeThrottleTimeout) {
+                  clearTimeout(this._resizeThrottleTimeout);
+                }
+                this._resizeThrottleTimeout = setTimeout(() => {
+                  this._resizeThrottleTimeout = null;
+
+                  // Close the popup since it would be wrongly sized, we'll
+                  // recalculate a proper size on reopening. For example, this
+                  // may happen when using special OS resize functions like
+                  // Win+Arrow.
+                  this.closePopup();
+
+                  // Make the host visible via formatValue.
+                  this.formatValue(true);
+                }, 100);
+              }
+              break;
           }
         ]]></body>
       </method>
 
       <method name="updateTextOverflow">
         <body><![CDATA[
           if (this._inOverflow) {
             window.promiseDocumentFlushed(() => {
--- a/browser/components/customizableui/test/browser_sidebar_toggle.js
+++ b/browser/components/customizableui/test/browser_sidebar_toggle.js
@@ -37,15 +37,15 @@ add_task(async function() {
   is(SidebarUI.currentID, "viewBookmarksSidebar", "Default sidebar selected");
   await SidebarUI.show("viewHistorySidebar");
 
   await hideSidebar();
   await showSidebar();
   is(SidebarUI.currentID, "viewHistorySidebar", "Selected sidebar remembered");
 
   await hideSidebar();
-  let otherWin = await BrowserTestUtils.openNewBrowserWindow({opener: window});
+  let otherWin = await BrowserTestUtils.openNewBrowserWindow();
   await showSidebar(otherWin);
   is(otherWin.SidebarUI.currentID, "viewHistorySidebar", "Selected sidebar remembered across windows");
   await hideSidebar(otherWin);
 
   await BrowserTestUtils.closeWindow(otherWin);
 });
--- a/browser/components/extensions/test/browser/browser_ext_sidebarAction_windows.js
+++ b/browser/components/extensions/test/browser/browser_ext_sidebarAction_windows.js
@@ -43,17 +43,17 @@ add_task(async function sidebar_windows(
   ok(elements.length > 0, "have a menuitem");
   let style = elements[0].getAttribute("style");
   ok(style.includes("webextension-menuitem-image"), "this menu has style");
 
   let secondSidebar = extension.awaitMessage("sidebar");
 
   // SidebarUI relies on window.opener being set, which is normal behavior when
   // using menu or key commands to open a new browser window.
-  let win = await BrowserTestUtils.openNewBrowserWindow({opener: window});
+  let win = await BrowserTestUtils.openNewBrowserWindow();
 
   await secondSidebar;
   ok(!win.document.getElementById("sidebar-box").hidden, "sidebar box is visible in second window");
   // Check that the menuitem has our image styling.
   elements = win.document.getElementsByClassName("webextension-menuitem");
   ok(elements.length > 0, "have a menuitem");
   style = elements[0].getAttribute("style");
   ok(style.includes("webextension-menuitem-image"), "this menu has style");
--- a/browser/components/sessionstore/test/browser_394759_perwindowpb.js
+++ b/browser/components/sessionstore/test/browser_394759_perwindowpb.js
@@ -12,18 +12,17 @@ const TESTS = [
     key: "bug 394759 PB",
     value: "uniq" + r() },
 ];
 
 function promiseTestOpenCloseWindow(aIsPrivate, aTest) {
   return (async function() {
     let win = await BrowserTestUtils.openNewBrowserWindow({ "private": aIsPrivate });
     win.gBrowser.selectedBrowser.loadURI(aTest.url);
-    await promiseBrowserLoaded(win.gBrowser.selectedBrowser);
-    await Promise.resolve();
+    await promiseBrowserLoaded(win.gBrowser.selectedBrowser, true, aTest.url);
     // Mark the window with some unique data to be restored later on.
     ss.setWindowValue(win, aTest.key, aTest.value);
     await TabStateFlusher.flushWindow(win);
     // Close.
     await BrowserTestUtils.closeWindow(win);
   })();
 }
 
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -314,17 +314,17 @@ DecreasePrivateDocShellCount()
 nsDocShell::nsDocShell()
   : nsDocLoader()
   , mForcedCharset(nullptr)
   , mParentCharset(nullptr)
   , mTreeOwner(nullptr)
   , mChromeEventHandler(nullptr)
   , mDefaultScrollbarPref(Scrollbar_Auto, Scrollbar_Auto)
   , mCharsetReloadState(eCharsetReloadInit)
-  , mOrientationLock(eScreenOrientation_None)
+  , mOrientationLock(hal::eScreenOrientation_None)
   , mParentCharsetSource(0)
   , mMarginWidth(-1)
   , mMarginHeight(-1)
   , mItemType(typeContent)
   , mPreviousTransIndex(-1)
   , mLoadedTransIndex(-1)
   , mChildOffset(0)
   , mSandboxFlags(0)
@@ -2024,24 +2024,24 @@ nsDocShell::SetFullscreenAllowed(bool aF
     // propagate the value of the parent's "mozFullscreenAllowed" attribute
     // across process boundaries.
     return NS_ERROR_UNEXPECTED;
   }
   mFullscreenAllowed = (aFullscreenAllowed ? PARENT_ALLOWS : PARENT_PROHIBITS);
   return NS_OK;
 }
 
-ScreenOrientationInternal
+hal::ScreenOrientation
 nsDocShell::OrientationLock()
 {
   return mOrientationLock;
 }
 
 void
-nsDocShell::SetOrientationLock(ScreenOrientationInternal aOrientationLock)
+nsDocShell::SetOrientationLock(hal::ScreenOrientation aOrientationLock)
 {
   mOrientationLock = aOrientationLock;
 }
 
 NS_IMETHODIMP
 nsDocShell::GetMayEnableCharacterEncodingMenu(
     bool* aMayEnableCharacterEncodingMenu)
 {
@@ -10156,25 +10156,26 @@ nsDocShell::InternalLoad(nsIURI* aURI,
       return NS_OK;
     }
   }
 
   // Whenever a top-level browsing context is navigated, the user agent MUST
   // lock the orientation of the document to the document's default
   // orientation. We don't explicitly check for a top-level browsing context
   // here because orientation is only set on top-level browsing contexts.
-  if (OrientationLock() != eScreenOrientation_None) {
+  if (OrientationLock() != hal::eScreenOrientation_None) {
 #ifdef DEBUG
     nsCOMPtr<nsIDocShellTreeItem> parent;
     GetSameTypeParent(getter_AddRefs(parent));
     MOZ_ASSERT(!parent);
 #endif
-    SetOrientationLock(eScreenOrientation_None);
+    SetOrientationLock(hal::eScreenOrientation_None);
     if (mIsActive) {
-      ScreenOrientation::UpdateActiveOrientationLock(eScreenOrientation_None);
+      ScreenOrientation::UpdateActiveOrientationLock(
+        hal::eScreenOrientation_None);
     }
   }
 
   // Check for saving the presentation here, before calling Stop().
   // This is necessary so that we can catch any pending requests.
   // Since the new request has not been created yet, we pass null for the
   // new request parameter.
   // Also pass nullptr for the document, since it doesn't affect the return
--- a/docshell/base/nsDocShell.h
+++ b/docshell/base/nsDocShell.h
@@ -3,16 +3,17 @@
 /* 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 nsDocShell_h__
 #define nsDocShell_h__
 
 #include "mozilla/BasePrincipal.h"
+#include "mozilla/HalScreenConfiguration.h"
 #include "mozilla/LinkedList.h"
 #include "mozilla/Maybe.h"
 #include "mozilla/Move.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/UniquePtr.h"
 #include "mozilla/WeakPtr.h"
 
 #include "mozilla/dom/BrowsingContext.h"
@@ -64,17 +65,16 @@
 namespace mozilla {
 class Encoding;
 class HTMLEditor;
 enum class TaskCategory;
 namespace dom {
 class ClientInfo;
 class ClientSource;
 class EventTarget;
-typedef uint32_t ScreenOrientationInternal;
 } // namespace dom
 } // namespace mozilla
 
 class nsICommandManager;
 class nsIContentViewer;
 class nsIController;
 class nsIDocShellTreeOwner;
 class nsIDocument;
@@ -1014,19 +1014,17 @@ private: // data members
 
   nsIDocShellTreeOwner* mTreeOwner; // Weak Reference
   mozilla::dom::EventTarget* mChromeEventHandler; // Weak Reference
 
   nsIntPoint mDefaultScrollbarPref; // persistent across doc loads
 
   eCharsetReloadState mCharsetReloadState;
 
-  // The orientation lock as described by
-  // https://w3c.github.io/screen-orientation/
-  mozilla::dom::ScreenOrientationInternal mOrientationLock;
+  mozilla::hal::ScreenOrientation mOrientationLock;
 
   int32_t mParentCharsetSource;
   int32_t mMarginWidth;
   int32_t mMarginHeight;
 
   // This can either be a content docshell or a chrome docshell. After
   // Create() is called, the type is not expected to change.
   int32_t mItemType;
--- a/dom/base/DocumentOrShadowRoot.cpp
+++ b/dom/base/DocumentOrShadowRoot.cpp
@@ -7,30 +7,61 @@
 #include "DocumentOrShadowRoot.h"
 #include "mozilla/EventStateManager.h"
 #include "mozilla/dom/ShadowRoot.h"
 #include "mozilla/dom/StyleSheetList.h"
 #include "nsDocument.h"
 #include "nsFocusManager.h"
 #include "nsLayoutUtils.h"
 #include "nsSVGUtils.h"
+#include "nsWindowSizes.h"
 
 namespace mozilla {
 namespace dom {
 
 DocumentOrShadowRoot::DocumentOrShadowRoot(mozilla::dom::ShadowRoot& aShadowRoot)
   : mAsNode(aShadowRoot)
   , mKind(Kind::ShadowRoot)
 {}
 
 DocumentOrShadowRoot::DocumentOrShadowRoot(nsIDocument& aDoc)
   : mAsNode(aDoc)
   , mKind(Kind::Document)
 {}
 
+void
+DocumentOrShadowRoot::AddSizeOfOwnedSheetArrayExcludingThis(
+  nsWindowSizes& aSizes,
+  const nsTArray<RefPtr<StyleSheet>>& aSheets) const
+{
+  size_t n = 0;
+  n += aSheets.ShallowSizeOfExcludingThis(aSizes.mState.mMallocSizeOf);
+  for (StyleSheet* sheet : aSheets) {
+    if (!sheet->GetAssociatedDocumentOrShadowRoot()) {
+      // Avoid over-reporting shared sheets.
+      continue;
+    }
+    n += sheet->SizeOfIncludingThis(aSizes.mState.mMallocSizeOf);
+  }
+
+  if (mKind == Kind::ShadowRoot) {
+    aSizes.mLayoutShadowDomStyleSheetsSize += n;
+  } else {
+    aSizes.mLayoutStyleSheetsSize += n;
+  }
+}
+
+void
+DocumentOrShadowRoot::AddSizeOfExcludingThis(nsWindowSizes& aSizes) const
+{
+  AddSizeOfOwnedSheetArrayExcludingThis(aSizes, mStyleSheets);
+  aSizes.mDOMOtherSize +=
+    mIdentifierMap.SizeOfExcludingThis(aSizes.mState.mMallocSizeOf);
+}
+
 DocumentOrShadowRoot::~DocumentOrShadowRoot()
 {
   for (StyleSheet* sheet : mStyleSheets) {
     sheet->ClearAssociatedDocumentOrShadowRoot();
   }
 }
 
 StyleSheetList&
--- a/dom/base/DocumentOrShadowRoot.h
+++ b/dom/base/DocumentOrShadowRoot.h
@@ -10,16 +10,17 @@
 #include "mozilla/dom/NameSpaceConstants.h"
 #include "nsContentListDeclarations.h"
 #include "nsTArray.h"
 #include "nsIdentifierMapEntry.h"
 
 class nsContentList;
 class nsIDocument;
 class nsINode;
+class nsWindowSizes;
 
 namespace mozilla {
 class StyleSheet;
 
 namespace dom {
 
 class Element;
 class StyleSheetList;
@@ -185,16 +186,21 @@ public:
 
   void ReportEmptyGetElementByIdArg();
 
 protected:
   // Returns the reference to the sheet, if found in mStyleSheets.
   already_AddRefed<StyleSheet> RemoveSheet(StyleSheet& aSheet);
   void InsertSheetAt(size_t aIndex, StyleSheet& aSheet);
 
+  void AddSizeOfExcludingThis(nsWindowSizes&) const;
+  void AddSizeOfOwnedSheetArrayExcludingThis(
+      nsWindowSizes&,
+      const nsTArray<RefPtr<StyleSheet>>&) const;
+
   nsIContent* Retarget(nsIContent* aContent) const;
 
   /**
    * If focused element's subtree root is this document or shadow root, return
    * focused element, otherwise, get the shadow host recursively until the
    * shadow host's subtree root is this document or shadow root.
    */
   Element* GetRetargetedFocusedElement();
--- a/dom/base/ScreenOrientation.cpp
+++ b/dom/base/ScreenOrientation.cpp
@@ -29,44 +29,44 @@ NS_IMPL_CYCLE_COLLECTION_INHERITED(Scree
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ScreenOrientation)
 NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
 
 NS_IMPL_ADDREF_INHERITED(ScreenOrientation, DOMEventTargetHelper)
 NS_IMPL_RELEASE_INHERITED(ScreenOrientation, DOMEventTargetHelper)
 
 static OrientationType
-InternalOrientationToType(ScreenOrientationInternal aOrientation)
+InternalOrientationToType(hal::ScreenOrientation aOrientation)
 {
   switch (aOrientation) {
-  case eScreenOrientation_PortraitPrimary:
+  case hal::eScreenOrientation_PortraitPrimary:
     return OrientationType::Portrait_primary;
-  case eScreenOrientation_PortraitSecondary:
+  case hal::eScreenOrientation_PortraitSecondary:
     return OrientationType::Portrait_secondary;
-  case eScreenOrientation_LandscapePrimary:
+  case hal::eScreenOrientation_LandscapePrimary:
     return OrientationType::Landscape_primary;
-  case eScreenOrientation_LandscapeSecondary:
+  case hal::eScreenOrientation_LandscapeSecondary:
     return OrientationType::Landscape_secondary;
   default:
     MOZ_CRASH("Bad aOrientation value");
   }
 }
 
-static ScreenOrientationInternal
+static hal::ScreenOrientation
 OrientationTypeToInternal(OrientationType aOrientation)
 {
   switch (aOrientation) {
   case OrientationType::Portrait_primary:
-    return eScreenOrientation_PortraitPrimary;
+    return hal::eScreenOrientation_PortraitPrimary;
   case OrientationType::Portrait_secondary:
-    return eScreenOrientation_PortraitSecondary;
+    return hal::eScreenOrientation_PortraitSecondary;
   case OrientationType::Landscape_primary:
-    return eScreenOrientation_LandscapePrimary;
+    return hal::eScreenOrientation_LandscapePrimary;
   case OrientationType::Landscape_secondary:
-    return eScreenOrientation_LandscapeSecondary;
+    return hal::eScreenOrientation_LandscapeSecondary;
   default:
     MOZ_CRASH("Bad aOrientation value");
   }
 }
 
 ScreenOrientation::ScreenOrientation(nsPIDOMWindowInner* aWindow, nsScreen* aScreen)
   : DOMEventTargetHelper(aWindow), mScreen(aScreen)
 {
@@ -116,34 +116,34 @@ class ScreenOrientation::LockOrientation
 {
   ~LockOrientationTask();
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIRUNNABLE
 
   LockOrientationTask(ScreenOrientation* aScreenOrientation,
                       Promise* aPromise,
-                      ScreenOrientationInternal aOrientationLock,
+                      hal::ScreenOrientation aOrientationLock,
                       nsIDocument* aDocument,
                       bool aIsFullScreen);
 protected:
   bool OrientationLockContains(OrientationType aOrientationType);
 
   RefPtr<ScreenOrientation> mScreenOrientation;
   RefPtr<Promise> mPromise;
-  ScreenOrientationInternal mOrientationLock;
+  hal::ScreenOrientation mOrientationLock;
   nsCOMPtr<nsIDocument> mDocument;
   bool mIsFullScreen;
 };
 
 NS_IMPL_ISUPPORTS(ScreenOrientation::LockOrientationTask, nsIRunnable)
 
 ScreenOrientation::LockOrientationTask::LockOrientationTask(
   ScreenOrientation* aScreenOrientation, Promise* aPromise,
-  ScreenOrientationInternal aOrientationLock,
+  hal::ScreenOrientation aOrientationLock,
   nsIDocument* aDocument, bool aIsFullScreen)
   : mScreenOrientation(aScreenOrientation), mPromise(aPromise),
     mOrientationLock(aOrientationLock), mDocument(aDocument),
     mIsFullScreen(aIsFullScreen)
 {
   MOZ_ASSERT(aScreenOrientation);
   MOZ_ASSERT(aPromise);
   MOZ_ASSERT(aDocument);
@@ -175,17 +175,17 @@ ScreenOrientation::LockOrientationTask::
 
   if (mDocument->Hidden()) {
     // Active orientation lock is not the document's orientation lock.
     mPromise->MaybeResolveWithUndefined();
     mDocument->SetOrientationPendingPromise(nullptr);
     return NS_OK;
   }
 
-  if (mOrientationLock == eScreenOrientation_None) {
+  if (mOrientationLock == hal::eScreenOrientation_None) {
     mScreenOrientation->UnlockDeviceOrientation();
     mPromise->MaybeResolveWithUndefined();
     mDocument->SetOrientationPendingPromise(nullptr);
     return NS_OK;
   }
 
   ErrorResult rv;
   bool result = mScreenOrientation->LockDeviceOrientation(mOrientationLock,
@@ -196,60 +196,60 @@ ScreenOrientation::LockOrientationTask::
 
   if (NS_WARN_IF(!result)) {
     mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
     mDocument->SetOrientationPendingPromise(nullptr);
     return NS_OK;
   }
 
   if (OrientationLockContains(mDocument->CurrentOrientationType()) ||
-      (mOrientationLock == eScreenOrientation_Default &&
+      (mOrientationLock == hal::eScreenOrientation_Default &&
        mDocument->CurrentOrientationAngle() == 0)) {
     // Orientation lock will not cause an orientation change.
     mPromise->MaybeResolveWithUndefined();
     mDocument->SetOrientationPendingPromise(nullptr);
   }
 
   return NS_OK;
 }
 
 already_AddRefed<Promise>
 ScreenOrientation::Lock(OrientationLockType aOrientation, ErrorResult& aRv)
 {
-  ScreenOrientationInternal orientation = eScreenOrientation_None;
+  hal::ScreenOrientation orientation = hal::eScreenOrientation_None;
 
   switch (aOrientation) {
   case OrientationLockType::Any:
-    orientation = eScreenOrientation_PortraitPrimary |
-                  eScreenOrientation_PortraitSecondary |
-                  eScreenOrientation_LandscapePrimary |
-                  eScreenOrientation_LandscapeSecondary;
+    orientation = hal::eScreenOrientation_PortraitPrimary |
+                  hal::eScreenOrientation_PortraitSecondary |
+                  hal::eScreenOrientation_LandscapePrimary |
+                  hal::eScreenOrientation_LandscapeSecondary;
     break;
   case OrientationLockType::Natural:
-    orientation |= eScreenOrientation_Default;
+    orientation |= hal::eScreenOrientation_Default;
     break;
   case OrientationLockType::Landscape:
-    orientation = eScreenOrientation_LandscapePrimary |
-                  eScreenOrientation_LandscapeSecondary;
+    orientation = hal::eScreenOrientation_LandscapePrimary |
+                  hal::eScreenOrientation_LandscapeSecondary;
     break;
   case OrientationLockType::Portrait:
-    orientation = eScreenOrientation_PortraitPrimary |
-                  eScreenOrientation_PortraitSecondary;
+    orientation = hal::eScreenOrientation_PortraitPrimary |
+                  hal::eScreenOrientation_PortraitSecondary;
     break;
   case OrientationLockType::Portrait_primary:
-    orientation = eScreenOrientation_PortraitPrimary;
+    orientation = hal::eScreenOrientation_PortraitPrimary;
     break;
   case OrientationLockType::Portrait_secondary:
-    orientation = eScreenOrientation_PortraitSecondary;
+    orientation = hal::eScreenOrientation_PortraitSecondary;
     break;
   case OrientationLockType::Landscape_primary:
-    orientation = eScreenOrientation_LandscapePrimary;
+    orientation = hal::eScreenOrientation_LandscapePrimary;
     break;
   case OrientationLockType::Landscape_secondary:
-    orientation = eScreenOrientation_LandscapeSecondary;
+    orientation = hal::eScreenOrientation_LandscapeSecondary;
     break;
   default:
     NS_WARNING("Unexpected orientation type");
     aRv.Throw(NS_ERROR_UNEXPECTED);
     return nullptr;
   }
 
   return LockInternal(orientation, aRv);
@@ -278,17 +278,18 @@ AbortOrientationPromises(nsIDocShell* aD
       if (childShell) {
         AbortOrientationPromises(childShell);
       }
     }
   }
 }
 
 already_AddRefed<Promise>
-ScreenOrientation::LockInternal(ScreenOrientationInternal aOrientation, ErrorResult& aRv)
+ScreenOrientation::LockInternal(hal::ScreenOrientation aOrientation,
+                                ErrorResult& aRv)
 {
   // Steps to apply an orientation lock as defined in spec.
 
   nsIDocument* doc = GetResponsibleDocument();
   if (NS_WARN_IF(!doc)) {
     aRv.Throw(NS_ERROR_UNEXPECTED);
     return nullptr;
   }
@@ -344,17 +345,17 @@ ScreenOrientation::LockInternal(ScreenOr
     return nullptr;
   }
 
   return p.forget();
 #endif
 }
 
 bool
-ScreenOrientation::LockDeviceOrientation(ScreenOrientationInternal aOrientation,
+ScreenOrientation::LockDeviceOrientation(hal::ScreenOrientation aOrientation,
                                          bool aIsFullScreen, ErrorResult& aRv)
 {
   if (!GetOwner()) {
     aRv.Throw(NS_ERROR_UNEXPECTED);
     return false;
   }
 
   nsCOMPtr<EventTarget> target = do_QueryInterface(GetOwner()->GetDoc());
@@ -384,17 +385,17 @@ ScreenOrientation::LockDeviceOrientation
   }
 
   return true;
 }
 
 void
 ScreenOrientation::Unlock(ErrorResult& aRv)
 {
-  RefPtr<Promise> p = LockInternal(eScreenOrientation_None, aRv);
+  RefPtr<Promise> p = LockInternal(hal::eScreenOrientation_None, aRv);
 }
 
 void
 ScreenOrientation::UnlockDeviceOrientation()
 {
   hal::UnlockScreenOrientation();
 
   if (!mFullScreenListener || !GetOwner()) {
@@ -509,21 +510,21 @@ ScreenOrientation::Notify(const hal::Scr
     return;
   }
 
   nsIDocument* doc = GetResponsibleDocument();
   if (!doc) {
     return;
   }
 
-  ScreenOrientationInternal orientation = aConfiguration.orientation();
-  if (orientation != eScreenOrientation_PortraitPrimary &&
-      orientation != eScreenOrientation_PortraitSecondary &&
-      orientation != eScreenOrientation_LandscapePrimary &&
-      orientation != eScreenOrientation_LandscapeSecondary) {
+  hal::ScreenOrientation orientation = aConfiguration.orientation();
+  if (orientation != hal::eScreenOrientation_PortraitPrimary &&
+      orientation != hal::eScreenOrientation_PortraitSecondary &&
+      orientation != hal::eScreenOrientation_LandscapePrimary &&
+      orientation != hal::eScreenOrientation_LandscapeSecondary) {
     // The platform may notify of some other values from
     // an orientation lock, but we only care about real
     // changes to screen orientation which result in one of
     // the values we care about.
     return;
   }
 
   OrientationType previousOrientation = mType;
@@ -559,19 +560,20 @@ ScreenOrientation::Notify(const hal::Scr
                         this,
                         &ScreenOrientation::DispatchChangeEvent);
     rv = NS_DispatchToMainThread(runnable);
     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "NS_DispatchToMainThread failed");
   }
 }
 
 void
-ScreenOrientation::UpdateActiveOrientationLock(ScreenOrientationInternal aOrientation)
+ScreenOrientation::UpdateActiveOrientationLock(
+  hal::ScreenOrientation aOrientation)
 {
-  if (aOrientation == eScreenOrientation_None) {
+  if (aOrientation == hal::eScreenOrientation_None) {
     hal::UnlockScreenOrientation();
   } else {
     DebugOnly<bool> ok = hal::LockScreenOrientation(aOrientation);
     NS_WARNING_ASSERTION(ok, "hal::LockScreenOrientation failed");
   }
 }
 
 void
--- a/dom/base/ScreenOrientation.h
+++ b/dom/base/ScreenOrientation.h
@@ -13,28 +13,16 @@
 #include "mozilla/HalScreenConfiguration.h"
 
 class nsScreen;
 
 namespace mozilla {
 namespace dom {
 
 class Promise;
-// Make sure that any change to ScreenOrientationInternal values are
-// also made in mobile/android/base/GeckoScreenOrientation.java
-typedef uint32_t ScreenOrientationInternal;
-
-static const ScreenOrientationInternal eScreenOrientation_None               = 0;
-static const ScreenOrientationInternal eScreenOrientation_PortraitPrimary    = 1u << 0;
-static const ScreenOrientationInternal eScreenOrientation_PortraitSecondary  = 1u << 1;
-static const ScreenOrientationInternal eScreenOrientation_LandscapePrimary   = 1u << 2;
-static const ScreenOrientationInternal eScreenOrientation_LandscapeSecondary = 1u << 3;
-//eScreenOrientation_Default will use the natural orientation for the deivce,
-//it could be PortraitPrimary or LandscapePrimary depends on display resolution
-static const ScreenOrientationInternal eScreenOrientation_Default            = 1u << 4;
 
 class ScreenOrientation final : public DOMEventTargetHelper,
                                 public mozilla::hal::ScreenConfigurationObserver
 {
   // nsScreen has deprecated API that shares implementation.
   friend class ::nsScreen;
 
 public:
@@ -58,17 +46,17 @@ public:
   // (as defined in specification).
   OrientationType GetType(CallerType aCallerType, ErrorResult& aRv) const;
   uint16_t GetAngle(CallerType aCallerType, ErrorResult& aRv) const;
 
   virtual JSObject* WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
 
   void Notify(const mozilla::hal::ScreenConfiguration& aConfiguration) override;
 
-  static void UpdateActiveOrientationLock(ScreenOrientationInternal aOrientation);
+  static void UpdateActiveOrientationLock(hal::ScreenOrientation aOrientation);
 
 private:
   virtual ~ScreenOrientation();
 
   // Listener to unlock orientation if we leave fullscreen.
   class FullScreenEventListener;
 
   // Listener to update document's orienation lock when document becomes
@@ -81,28 +69,28 @@ private:
   enum LockPermission {
     LOCK_DENIED,
     FULLSCREEN_LOCK_ALLOWED,
     LOCK_ALLOWED
   };
 
   // This method calls into the HAL to lock the device and sets
   // up listeners for full screen change.
-  bool LockDeviceOrientation(ScreenOrientationInternal aOrientation,
+  bool LockDeviceOrientation(hal::ScreenOrientation aOrientation,
                              bool aIsFullscreen, ErrorResult& aRv);
 
   // This method calls in to the HAL to unlock the device and removes
   // full screen change listener.
   void UnlockDeviceOrientation();
 
   // This method performs the same function as |Lock| except it takes
-  // a ScreenOrientationInternal argument instead of an OrientationType.
+  // a hal::ScreenOrientation argument instead of an OrientationType.
   // This method exists in order to share implementation with nsScreen that
-  // uses ScreenOrientationInternal.
-  already_AddRefed<Promise> LockInternal(ScreenOrientationInternal aOrientation,
+  // uses ScreenOrientation.
+  already_AddRefed<Promise> LockInternal(hal::ScreenOrientation aOrientation,
                                          ErrorResult& aRv);
 
   void DispatchChangeEvent();
 
   bool ShouldResistFingerprinting() const;
 
   LockPermission GetLockOrientationPermission(bool aCheckSandbox) const;
 
--- a/dom/base/ShadowRoot.cpp
+++ b/dom/base/ShadowRoot.cpp
@@ -5,20 +5,21 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/ShadowRoot.h"
 #include "mozilla/dom/DocumentFragment.h"
 #include "ChildIterator.h"
 #include "nsContentUtils.h"
 #include "nsIStyleSheetLinkingElement.h"
+#include "nsWindowSizes.h"
+#include "nsXBLPrototypeBinding.h"
 #include "mozilla/dom/DirectionalityUtils.h"
 #include "mozilla/dom/Element.h"
 #include "mozilla/dom/HTMLSlotElement.h"
-#include "nsXBLPrototypeBinding.h"
 #include "mozilla/EventDispatcher.h"
 #include "mozilla/ServoStyleRuleMap.h"
 #include "mozilla/StyleSheet.h"
 #include "mozilla/StyleSheetInlines.h"
 #include "mozilla/dom/StyleSheetList.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
@@ -98,16 +99,31 @@ ShadowRoot::~ShadowRoot()
   MOZ_DIAGNOSTIC_ASSERT(!OwnerDoc()->IsComposedDocShadowRoot(*this));
 
   UnsetFlags(NODE_IS_IN_SHADOW_TREE);
 
   // nsINode destructor expects mSubtreeRoot == this.
   SetSubtreeRootPointer(this);
 }
 
+MOZ_DEFINE_MALLOC_SIZE_OF(ShadowRootAuthorStylesMallocSizeOf)
+MOZ_DEFINE_MALLOC_ENCLOSING_SIZE_OF(ShadowRootAuthorStylesMallocEnclosingSizeOf)
+
+void
+ShadowRoot::AddSizeOfExcludingThis(nsWindowSizes& aSizes, size_t* aNodeSize) const
+{
+  DocumentFragment::AddSizeOfExcludingThis(aSizes, aNodeSize);
+  DocumentOrShadowRoot::AddSizeOfExcludingThis(aSizes);
+  aSizes.mLayoutShadowDomAuthorStyles +=
+    Servo_AuthorStyles_SizeOfIncludingThis(
+      ShadowRootAuthorStylesMallocSizeOf,
+      ShadowRootAuthorStylesMallocEnclosingSizeOf,
+      mServoStyles.get());
+}
+
 JSObject*
 ShadowRoot::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
 {
   return mozilla::dom::ShadowRoot_Binding::Wrap(aCx, this, aGivenProto);
 }
 
 void
 ShadowRoot::CloneInternalDataFrom(ShadowRoot* aOther)
--- a/dom/base/ShadowRoot.h
+++ b/dom/base/ShadowRoot.h
@@ -50,16 +50,18 @@ public:
   NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
 
   ShadowRoot(Element* aElement, ShadowRootMode aMode,
              already_AddRefed<mozilla::dom::NodeInfo>&& aNodeInfo);
 
+  void AddSizeOfExcludingThis(nsWindowSizes&, size_t* aNodeSize) const final;
+
   // Shadow DOM v1
   Element* Host() const
   {
     MOZ_ASSERT(GetHost(), "ShadowRoot always has a host, how did we create "
                           "this ShadowRoot?");
     return GetHost();
   }
 
--- a/dom/base/nsDocument.cpp
+++ b/dom/base/nsDocument.cpp
@@ -11759,18 +11759,16 @@ nsIDocument::MaybeActiveMediaComponents(
   }
 
   GetWindow()->MaybeActiveMediaComponents();
 }
 
 /* virtual */ void
 nsIDocument::DocAddSizeOfExcludingThis(nsWindowSizes& aSizes) const
 {
-  nsINode::AddSizeOfExcludingThis(aSizes, &aSizes.mDOMOtherSize);
-
   if (mPresShell) {
     mPresShell->AddSizeOfIncludingThis(aSizes);
   }
 
   aSizes.mPropertyTablesSize +=
     mPropertyTable.SizeOfExcludingThis(aSizes.mState.mMallocSizeOf);
 
   if (EventListenerManager* elm = GetExistingListenerManager()) {
@@ -11796,52 +11794,37 @@ nsIDocument::DocAddSizeOfExcludingThis(n
 
 void
 nsIDocument::DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const
 {
   aWindowSizes.mDOMOtherSize += aWindowSizes.mState.mMallocSizeOf(this);
   DocAddSizeOfExcludingThis(aWindowSizes);
 }
 
-static size_t
-SizeOfOwnedSheetArrayExcludingThis(const nsTArray<RefPtr<StyleSheet>>& aSheets,
-                                   MallocSizeOf aMallocSizeOf)
-{
-  size_t n = 0;
-  n += aSheets.ShallowSizeOfExcludingThis(aMallocSizeOf);
-  for (StyleSheet* sheet : aSheets) {
-    if (!sheet->GetAssociatedDocumentOrShadowRoot()) {
-      // Avoid over-reporting shared sheets.
-      continue;
-    }
-    n += sheet->SizeOfIncludingThis(aMallocSizeOf);
-  }
-  return n;
-}
 
 void
 nsDocument::AddSizeOfExcludingThis(nsWindowSizes& aSizes,
                                    size_t* aNodeSize) const
 {
   // This AddSizeOfExcludingThis() overrides the one from nsINode.  But
   // nsDocuments can only appear at the top of the DOM tree, and we use the
   // specialized DocAddSizeOfExcludingThis() in that case.  So this should never
   // be called.
   MOZ_CRASH();
 }
 
-static void
-AddSizeOfNodeTree(nsIContent* aNode, nsWindowSizes& aWindowSizes)
+/* static */ void
+nsIDocument::AddSizeOfNodeTree(nsINode& aNode, nsWindowSizes& aWindowSizes)
 {
   size_t nodeSize = 0;
-  aNode->AddSizeOfIncludingThis(aWindowSizes, &nodeSize);
+  aNode.AddSizeOfIncludingThis(aWindowSizes, &nodeSize);
 
   // This is where we transfer the nodeSize obtained from
   // nsINode::AddSizeOfIncludingThis() to a value in nsWindowSizes.
-  switch (aNode->NodeType()) {
+  switch (aNode.NodeType()) {
   case nsINode::ELEMENT_NODE:
     aWindowSizes.mDOMElementNodesSize += nodeSize;
     break;
   case nsINode::TEXT_NODE:
     aWindowSizes.mDOMTextNodesSize += nodeSize;
     break;
   case nsINode::CDATA_SECTION_NODE:
     aWindowSizes.mDOMCDATANodesSize += nodeSize;
@@ -11849,76 +11832,89 @@ AddSizeOfNodeTree(nsIContent* aNode, nsW
   case nsINode::COMMENT_NODE:
     aWindowSizes.mDOMCommentNodesSize += nodeSize;
     break;
   default:
     aWindowSizes.mDOMOtherSize += nodeSize;
     break;
   }
 
-  if (EventListenerManager* elm = aNode->GetExistingListenerManager()) {
+  if (EventListenerManager* elm = aNode.GetExistingListenerManager()) {
     aWindowSizes.mDOMEventListenersCount += elm->ListenerCount();
   }
 
-  AllChildrenIterator iter(aNode, nsIContent::eAllChildren);
-  for (nsIContent* n = iter.GetNextChild(); n; n = iter.GetNextChild()) {
-    AddSizeOfNodeTree(n, aWindowSizes);
+  if (aNode.IsContent()) {
+    nsTArray<nsIContent*> anonKids;
+    nsContentUtils::AppendNativeAnonymousChildren(aNode.AsContent(),
+                                                  anonKids,
+                                                  nsIContent::eAllChildren);
+    for (nsIContent* anonKid : anonKids) {
+      AddSizeOfNodeTree(*anonKid, aWindowSizes);
+    }
+
+    if (auto* element = Element::FromNode(aNode)) {
+      if (ShadowRoot* shadow = element->GetShadowRoot()) {
+        AddSizeOfNodeTree(*shadow, aWindowSizes);
+      }
+
+      for (nsXBLBinding* binding = element->GetXBLBinding();
+           binding;
+           binding = binding->GetBaseBinding()) {
+        if (nsIContent* anonContent = binding->GetAnonymousContent()) {
+          AddSizeOfNodeTree(*anonContent, aWindowSizes);
+        }
+      }
+    }
+  }
+
+  // NOTE(emilio): If you feel smart and want to change this function to use
+  // GetNextNode(), think twice, since you'd need to handle <xbl:content> in a
+  // sane way, and kids of <content> won't point to the parent, so we'd never
+  // find the root node where we should stop at.
+  for (nsIContent* kid = aNode.GetFirstChild(); kid; kid = kid->GetNextSibling()) {
+    AddSizeOfNodeTree(*kid, aWindowSizes);
   }
 }
 
 void
 nsDocument::DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const
 {
-  // We use AllChildrenIterator to iterate over DOM nodes in
-  // AddSizeOfNodeTree(). The obvious place to start is at the document's root
-  // element, using GetRootElement(). However, that will miss comment nodes
-  // that are siblings of the root element. Instead we use
-  // GetFirstChild()/GetNextSibling() to traverse the document's immediate
-  // child nodes, calling AddSizeOfNodeTree() on each to measure them and then
-  // all their descendants. (The comment nodes won't have any descendants).
-  for (nsIContent* node = nsINode::GetFirstChild();
-       node;
-       node = node->GetNextSibling()) {
-    AddSizeOfNodeTree(node, aWindowSizes);
+  nsINode::AddSizeOfExcludingThis(aWindowSizes, &aWindowSizes.mDOMOtherSize);
+
+  for (nsIContent* kid = GetFirstChild(); kid; kid = kid->GetNextSibling()) {
+    AddSizeOfNodeTree(*kid, aWindowSizes);
   }
 
   // IMPORTANT: for our ComputedValues measurements, we want to measure
   // ComputedValues accessible from DOM elements before ComputedValues not
   // accessible from DOM elements (i.e. accessible only from the frame tree).
   //
   // Therefore, the measurement of the nsIDocument superclass must happen after
   // the measurement of DOM nodes (above), because nsIDocument contains the
   // PresShell, which contains the frame tree.
   nsIDocument::DocAddSizeOfExcludingThis(aWindowSizes);
 
-  aWindowSizes.mLayoutStyleSheetsSize +=
-    SizeOfOwnedSheetArrayExcludingThis(mStyleSheets,
-                                       aWindowSizes.mState.mMallocSizeOf);
+  DocumentOrShadowRoot::AddSizeOfExcludingThis(aWindowSizes);
   for (auto& sheetArray : mAdditionalSheets) {
-    aWindowSizes.mLayoutStyleSheetsSize +=
-      SizeOfOwnedSheetArrayExcludingThis(sheetArray,
-                                         aWindowSizes.mState.mMallocSizeOf);
+    AddSizeOfOwnedSheetArrayExcludingThis(aWindowSizes, sheetArray);
   }
   // Lumping in the loader with the style-sheets size is not ideal,
   // but most of the things in there are in fact stylesheets, so it
   // doesn't seem worthwhile to separate it out.
   aWindowSizes.mLayoutStyleSheetsSize +=
     CSSLoader()->SizeOfIncludingThis(aWindowSizes.mState.mMallocSizeOf);
 
   aWindowSizes.mDOMOtherSize += mAttrStyleSheet
                               ? mAttrStyleSheet->DOMSizeOfIncludingThis(
                                   aWindowSizes.mState.mMallocSizeOf)
                               : 0;
 
   aWindowSizes.mDOMOtherSize +=
     mStyledLinks.ShallowSizeOfExcludingThis(aWindowSizes.mState.mMallocSizeOf);
 
-  aWindowSizes.mDOMOtherSize +=
-    mIdentifierMap.SizeOfExcludingThis(aWindowSizes.mState.mMallocSizeOf);
-
   // Measurement of the following members may be added later if DMD finds it
   // is worthwhile:
   // - many!
 }
 
 already_AddRefed<nsIDocument>
 nsIDocument::Constructor(const GlobalObject& aGlobal,
                          ErrorResult& rv)
--- a/dom/base/nsGlobalWindowInner.cpp
+++ b/dom/base/nsGlobalWindowInner.cpp
@@ -4420,24 +4420,26 @@ nsGlobalWindowInner::DisableVRUpdates()
 void
 nsGlobalWindowInner::ResetVRTelemetry(bool aUpdate)
 {
   if (mVREventObserver) {
     mVREventObserver->UpdateSpentTimeIn2DTelemetry(aUpdate);
   }
 }
 
+#ifndef XP_WIN // This guard should match the guard at the callsite.
 static bool ShouldShowFocusRingIfFocusedByMouse(nsIContent* aNode)
 {
   if (!aNode) {
     return true;
   }
   return !nsContentUtils::ContentIsLink(aNode) &&
     !aNode->IsAnyOfHTMLElements(nsGkAtoms::video, nsGkAtoms::audio);
 }
+#endif
 
 void
 nsGlobalWindowInner::SetFocusedElement(Element* aElement,
                                        uint32_t aFocusMethod,
                                        bool aNeedsFocus)
 {
   if (aElement && aElement->GetComposedDoc() != mDoc) {
     NS_WARNING("Trying to set focus to a node from a wrong document");
--- a/dom/base/nsIDocument.h
+++ b/dom/base/nsIDocument.h
@@ -3012,16 +3012,20 @@ public:
                      const char16_t **aParams = nullptr,
                      uint32_t aParamsLength = 0) const;
 
   // Posts an event to call UpdateVisibilityState
   void PostVisibilityUpdateEvent();
 
   bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
 
+  // Adds the size of a given node, which must not be a document node, to the
+  // window sizes passed-in.
+  static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
+
   // Note: nsIDocument is a sub-class of nsINode, which has a
   // SizeOfExcludingThis function.  However, because nsIDocument objects can
   // only appear at the top of the DOM tree, we have a specialized measurement
   // function which returns multiple sizes.
   virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
   // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
   // because nsIDocument inherits from nsINode;  see the comment above the
   // declaration of nsINode::SizeOfIncludingThis.
--- a/dom/base/nsScreen.cpp
+++ b/dom/base/nsScreen.cpp
@@ -183,17 +183,17 @@ nsScreen::GetMozOrientation(nsString& aO
     break;
   default:
     MOZ_CRASH("Unacceptable screen orientation type.");
   }
 }
 
 static void
 UpdateDocShellOrientationLock(nsPIDOMWindowInner* aWindow,
-                              ScreenOrientationInternal aOrientation)
+                              hal::ScreenOrientation aOrientation)
 {
   if (!aWindow) {
     return;
   }
 
   nsCOMPtr<nsIDocShell> docShell = aWindow->GetDocShell();
   if (!docShell) {
     return;
@@ -223,37 +223,37 @@ nsScreen::MozLockOrientation(const nsASt
 
 bool
 nsScreen::MozLockOrientation(const Sequence<nsString>& aOrientations,
                              ErrorResult& aRv)
 {
   if (ShouldResistFingerprinting()) {
     return false;
   }
-  ScreenOrientationInternal orientation = eScreenOrientation_None;
+  hal::ScreenOrientation orientation = hal::eScreenOrientation_None;
 
   for (uint32_t i = 0; i < aOrientations.Length(); ++i) {
     const nsString& item = aOrientations[i];
 
     if (item.EqualsLiteral("portrait")) {
-      orientation |= eScreenOrientation_PortraitPrimary |
-                     eScreenOrientation_PortraitSecondary;
+      orientation |= hal::eScreenOrientation_PortraitPrimary |
+                     hal::eScreenOrientation_PortraitSecondary;
     } else if (item.EqualsLiteral("portrait-primary")) {
-      orientation |= eScreenOrientation_PortraitPrimary;
+      orientation |= hal::eScreenOrientation_PortraitPrimary;
     } else if (item.EqualsLiteral("portrait-secondary")) {
-      orientation |= eScreenOrientation_PortraitSecondary;
+      orientation |= hal::eScreenOrientation_PortraitSecondary;
     } else if (item.EqualsLiteral("landscape")) {
-      orientation |= eScreenOrientation_LandscapePrimary |
-                     eScreenOrientation_LandscapeSecondary;
+      orientation |= hal::eScreenOrientation_LandscapePrimary |
+                     hal::eScreenOrientation_LandscapeSecondary;
     } else if (item.EqualsLiteral("landscape-primary")) {
-      orientation |= eScreenOrientation_LandscapePrimary;
+      orientation |= hal::eScreenOrientation_LandscapePrimary;
     } else if (item.EqualsLiteral("landscape-secondary")) {
-      orientation |= eScreenOrientation_LandscapeSecondary;
+      orientation |= hal::eScreenOrientation_LandscapeSecondary;
     } else if (item.EqualsLiteral("default")) {
-      orientation |= eScreenOrientation_Default;
+      orientation |= hal::eScreenOrientation_Default;
     } else {
       // If we don't recognize the token, we should just return 'false'
       // without throwing.
       return false;
     }
   }
 
   switch (mScreenOrientation->GetLockOrientationPermission(false)) {
@@ -273,17 +273,17 @@ nsScreen::MozLockOrientation(const Seque
 }
 
 void
 nsScreen::MozUnlockOrientation()
 {
   if (ShouldResistFingerprinting()) {
     return;
   }
-  UpdateDocShellOrientationLock(GetOwner(), eScreenOrientation_None);
+  UpdateDocShellOrientationLock(GetOwner(), hal::eScreenOrientation_None);
   mScreenOrientation->UnlockDeviceOrientation();
 }
 
 bool
 nsScreen::IsDeviceSizePageSize()
 {
   if (nsPIDOMWindowInner* owner = GetOwner()) {
     nsIDocShell* docShell = owner->GetDocShell();
--- a/dom/base/nsWindowMemoryReporter.cpp
+++ b/dom/base/nsWindowMemoryReporter.cpp
@@ -348,17 +348,25 @@ CollectWindowReports(nsGlobalWindowInner
               "Memory used by MediaQueryList objects for the window's "
               "document.");
 
   REPORT_SIZE("/dom/other", mDOMOtherSize,
               "Memory used by a window's DOM that isn't measured by the "
               "other 'dom/' numbers.");
 
   REPORT_SIZE("/layout/style-sheets", mLayoutStyleSheetsSize,
-              "Memory used by style sheets within a window.");
+              "Memory used by document style sheets within a window.");
+
+  REPORT_SIZE("/layout/shadow-dom/style-sheets", mLayoutShadowDomStyleSheetsSize,
+              "Memory used by Shadow DOM style sheets within a window.");
+
+  // TODO(emilio): We might want to split this up between invalidation map /
+  // element-and-pseudos / revalidation too just like the style set.
+  REPORT_SIZE("/layout/shadow-dom/author-styles", mLayoutShadowDomAuthorStyles,
+              "Memory used by Shadow DOM computed rule data within a window.");
 
   REPORT_SIZE("/layout/pres-shell", mLayoutPresShellSize,
               "Memory used by layout's PresShell, along with any structures "
               "allocated in its arena and not measured elsewhere, "
               "within a window.");
 
   REPORT_SIZE("/layout/style-sets/stylist/rule-tree",
               mLayoutStyleSetsStylistRuleTree,
@@ -410,20 +418,16 @@ CollectWindowReports(nsGlobalWindowInner
 
   REPORT_SIZE("/layout/computed-values/non-dom", mLayoutComputedValuesNonDom,
               "Memory used by ComputedValues objects not accessible from DOM "
               "elements.");
 
   REPORT_SIZE("/layout/computed-values/visited", mLayoutComputedValuesVisited,
               "Memory used by ComputedValues objects used for visited styles.");
 
-  REPORT_SIZE("/layout/computed-values/stale", mLayoutComputedValuesStale,
-              "Memory used by ComputedValues and style structs it holds that "
-              "is no longer used but still alive.");
-
   REPORT_SIZE("/property-tables", mPropertyTablesSize,
               "Memory used for the property tables within a window.");
 
   REPORT_SIZE("/bindings", mBindingsSize,
               "Memory used by bindings within a window.");
 
   REPORT_COUNT("/dom/event-targets", mDOMEventTargetsCount,
                "Number of non-node event targets in the event targets table "
--- a/dom/base/nsWindowSizes.h
+++ b/dom/base/nsWindowSizes.h
@@ -162,31 +162,32 @@ class nsWindowSizes
   macro(DOM,   mDOMCDATANodesSize) \
   macro(DOM,   mDOMCommentNodesSize) \
   macro(DOM,   mDOMEventTargetsSize) \
   macro(DOM,   mDOMMediaQueryLists) \
   macro(DOM,   mDOMPerformanceUserEntries) \
   macro(DOM,   mDOMPerformanceResourceEntries) \
   macro(DOM,   mDOMOtherSize) \
   macro(Style, mLayoutStyleSheetsSize) \
+  macro(Style, mLayoutShadowDomStyleSheetsSize) \
+  macro(Style, mLayoutShadowDomAuthorStyles) \
   macro(Other, mLayoutPresShellSize) \
   macro(Style, mLayoutStyleSetsStylistRuleTree) \
   macro(Style, mLayoutStyleSetsStylistElementAndPseudosMaps) \
   macro(Style, mLayoutStyleSetsStylistInvalidationMap) \
   macro(Style, mLayoutStyleSetsStylistRevalidationSelectors) \
   macro(Style, mLayoutStyleSetsStylistOther) \
   macro(Style, mLayoutStyleSetsOther) \
   macro(Style, mLayoutElementDataObjects) \
   macro(Other, mLayoutTextRunsSize) \
   macro(Other, mLayoutPresContextSize) \
   macro(Other, mLayoutFramePropertiesSize) \
   macro(Style, mLayoutComputedValuesDom) \
   macro(Style, mLayoutComputedValuesNonDom) \
   macro(Style, mLayoutComputedValuesVisited) \
-  macro(Style, mLayoutComputedValuesStale) \
   macro(Other, mPropertyTablesSize) \
   macro(Other, mBindingsSize) \
 
 public:
   explicit nsWindowSizes(mozilla::SizeOfState& aState)
     :
       FOR_EACH_SIZE(ZERO_SIZE)
       mDOMEventTargetsCount(0),
--- a/dom/clients/manager/ClientOpenWindowUtils.cpp
+++ b/dom/clients/manager/ClientOpenWindowUtils.cpp
@@ -12,16 +12,17 @@
 #include "nsContentUtils.h"
 #include "nsIBrowserDOMWindow.h"
 #include "nsIDocShell.h"
 #include "nsIDOMChromeWindow.h"
 #include "nsIURI.h"
 #include "nsIWebProgress.h"
 #include "nsIWebProgressListener.h"
 #include "nsIWindowWatcher.h"
+#include "nsIXPConnect.h"
 #include "nsNetUtil.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowWatcher.h"
 
 #ifdef MOZ_WIDGET_ANDROID
 #include "FennecJNIWrappers.h"
 #endif
 
--- a/dom/clients/manager/ClientPrefs.cpp
+++ b/dom/clients/manager/ClientPrefs.cpp
@@ -1,16 +1,18 @@
 /* -*- 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 "ClientPrefs.h"
 
+#include "mozilla/Preferences.h"
+
 namespace mozilla {
 namespace dom {
 
 namespace {
 
 bool gDataURLUniqueOpaqueOrigin = false;
 
 } // anonymous namespace
--- a/dom/gamepad/GamepadManager.cpp
+++ b/dom/gamepad/GamepadManager.cpp
@@ -206,18 +206,25 @@ GamepadManager::GetGamepad(uint32_t aInd
   RefPtr<Gamepad> gamepad;
   if (mGamepads.Get(aIndex, getter_AddRefs(gamepad))) {
     return gamepad.forget();
   }
 
   return nullptr;
 }
 
+already_AddRefed<Gamepad>
+GamepadManager::GetGamepad(uint32_t aGamepadId, GamepadServiceType aServiceType) const
+{
+  return GetGamepad(GetGamepadIndexWithServiceType(aGamepadId, aServiceType));
+}
+
+
 uint32_t GamepadManager::GetGamepadIndexWithServiceType(uint32_t aIndex,
-                                                        GamepadServiceType aServiceType)
+                                                        GamepadServiceType aServiceType) const
 {
   uint32_t newIndex = 0;
 
   switch (aServiceType) {
     case GamepadServiceType::Standard:
       MOZ_ASSERT(aIndex <= VR_GAMEPAD_IDX_OFFSET);
       newIndex = aIndex;
       break;
--- a/dom/gamepad/GamepadManager.h
+++ b/dom/gamepad/GamepadManager.h
@@ -55,16 +55,19 @@ class GamepadManager final : public nsIO
   void RemoveGamepad(uint32_t aIndex, GamepadServiceType aServiceType);
 
   // Synchronize the state of |aGamepad| to match the gamepad stored at |aIndex|
   void SyncGamepadState(uint32_t aIndex, Gamepad* aGamepad);
 
   // Returns gamepad object if index exists, null otherwise
   already_AddRefed<Gamepad> GetGamepad(uint32_t aIndex) const;
 
+    // Returns gamepad object if GamepadId exists, null otherwise
+  already_AddRefed<Gamepad> GetGamepad(uint32_t aGamepadId, GamepadServiceType aServiceType) const;
+
   // Receive GamepadChangeEvent messages from parent process to fire DOM events
   void Update(const GamepadChangeEvent& aGamepadEvent);
 
   // Trigger vibrate haptic event to gamepad channels.
   already_AddRefed<Promise> VibrateHaptic(uint32_t aControllerIdx, uint32_t aHapticIndex,
                                           double aIntensity, double aDuration,
                                           nsIGlobalObject* aGlobal, ErrorResult& aRv);
   // Send stop haptic events to gamepad channels.
@@ -127,17 +130,17 @@ class GamepadManager final : public nsIO
   // explicitly interacted with a gamepad while this window
   // was focused, by pressing buttons or similar actions.
   bool WindowHasSeenGamepad(nsGlobalWindowInner* aWindow, uint32_t aIndex) const;
   // Indicate that a window has received data from a gamepad.
   void SetWindowHasSeenGamepad(nsGlobalWindowInner* aWindow, uint32_t aIndex,
                                bool aHasSeen = true);
   // Our gamepad index has VR_GAMEPAD_IDX_OFFSET while GamepadChannelType
   // is from VRManager.
-  uint32_t GetGamepadIndexWithServiceType(uint32_t aIndex, GamepadServiceType aServiceType);
+  uint32_t GetGamepadIndexWithServiceType(uint32_t aIndex, GamepadServiceType aServiceType) const;
 
   // Gamepads connected to the system. Copies of these are handed out
   // to each window.
   nsRefPtrHashtable<nsUint32HashKey, Gamepad> mGamepads;
   // Inner windows that are listening for gamepad events.
   // has been sent to that window.
   nsTArray<RefPtr<nsGlobalWindowInner>> mListeners;
   uint32_t mPromiseID;
--- a/dom/ipc/DOMTypes.ipdlh
+++ b/dom/ipc/DOMTypes.ipdlh
@@ -19,17 +19,17 @@ using struct mozilla::SerializedStructur
 
 using LayoutDeviceIntRect from "Units.h";
 using DesktopIntRect from "Units.h";
 using DesktopToLayoutDeviceScale from "Units.h";
 using CSSToLayoutDeviceScale from "Units.h";
 using CSSRect from "Units.h";
 using CSSSize from "Units.h";
 using mozilla::LayoutDeviceIntPoint from "Units.h";
-using mozilla::dom::ScreenOrientationInternal from "mozilla/dom/ScreenOrientation.h";
+using hal::ScreenOrientation from "mozilla/HalScreenConfiguration.h";
 using struct mozilla::layers::TextureFactoryIdentifier from "mozilla/layers/CompositorTypes.h";
 using mozilla::layers::CompositorOptions from "mozilla/layers/CompositorOptions.h";
 using mozilla::layers::LayersId from "mozilla/layers/LayersTypes.h";
 using mozilla::gfx::SurfaceFormat from "mozilla/gfx/Types.h";
 
 
 namespace mozilla {
 namespace dom {
@@ -95,17 +95,17 @@ struct ScreenDetails {
   CSSToLayoutDeviceScale defaultCSSScaleFactor;
   float dpi;
 };
 
 struct DimensionInfo
 {
   CSSRect rect;
   CSSSize size;
-  ScreenOrientationInternal orientation;
+  ScreenOrientation orientation;
   LayoutDeviceIntPoint clientOffset;
   LayoutDeviceIntPoint chromeOffset;
 };
 
 struct FrameScriptInfo
 {
   nsString url;
   bool runInGlobalScope;
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -403,17 +403,17 @@ TabChild::TabChild(nsIContentChild* aMan
   , mManager(aManager)
   , mChromeFlags(aChromeFlags)
   , mMaxTouchPoints(0)
   , mLayersId{0}
   , mBeforeUnloadListeners(0)
   , mDidFakeShow(false)
   , mNotified(false)
   , mTriedBrowserInit(false)
-  , mOrientation(eScreenOrientation_PortraitPrimary)
+  , mOrientation(hal::eScreenOrientation_PortraitPrimary)
   , mIgnoreKeyPressEvent(false)
   , mHasValidInnerSize(false)
   , mDestroyed(false)
   , mUniqueId(aTabId)
   , mHasSiblings(false)
   , mIsTransparent(false)
   , mIPCOpen(false)
   , mParentIsActive(false)
--- a/dom/ipc/TabChild.h
+++ b/dom/ipc/TabChild.h
@@ -472,17 +472,17 @@ public:
     *aTouchPoints = mMaxTouchPoints;
   }
 
   void SetMaxTouchPoints(uint32_t aMaxTouchPoints)
   {
     mMaxTouchPoints = aMaxTouchPoints;
   }
 
-  ScreenOrientationInternal GetOrientation() const { return mOrientation; }
+  hal::ScreenOrientation GetOrientation() const { return mOrientation; }
 
   void SetBackgroundColor(const nscolor& aColor);
 
   void NotifyPainted();
 
   void RequestEditCommands(nsIWidget::NativeKeyBindingsType aType,
                            const WidgetKeyboardEvent& aEvent,
                            nsTArray<CommandInt>& aCommands);
@@ -823,17 +823,17 @@ private:
   uint32_t mMaxTouchPoints;
   layers::LayersId mLayersId;
   int64_t mBeforeUnloadListeners;
   CSSRect mUnscaledOuterRect;
   Maybe<bool> mLayersConnected;
   bool mDidFakeShow;
   bool mNotified;
   bool mTriedBrowserInit;
-  ScreenOrientationInternal mOrientation;
+  hal::ScreenOrientation mOrientation;
 
   bool mIgnoreKeyPressEvent;
   RefPtr<APZEventState> mAPZEventState;
   SetAllowedTouchBehaviorCallback mSetAllowedTouchBehaviorCallback;
   bool mHasValidInnerSize;
   bool mDestroyed;
   // Position of client area relative to the outer window
   LayoutDeviceIntPoint mClientOffset;
--- a/dom/ipc/TabParent.cpp
+++ b/dom/ipc/TabParent.cpp
@@ -764,17 +764,17 @@ TabParent::UpdateDimensions(const nsIntR
   nsCOMPtr<nsIWidget> widget = GetWidget();
   if (!widget) {
     NS_WARNING("No widget found in TabParent::UpdateDimensions");
     return;
   }
 
   hal::ScreenConfiguration config;
   hal::GetCurrentScreenConfiguration(&config);
-  ScreenOrientationInternal orientation = config.orientation();
+  hal::ScreenOrientation orientation = config.orientation();
   LayoutDeviceIntPoint clientOffset = GetClientOffset();
   LayoutDeviceIntPoint chromeOffset = -GetChildProcessOffset();
 
   if (!mUpdatedDimensions || mOrientation != orientation ||
       mDimensions != size || !mRect.IsEqualEdges(rect) ||
       clientOffset != mClientOffset ||
       chromeOffset != mChromeOffset) {
 
--- a/dom/ipc/TabParent.h
+++ b/dom/ipc/TabParent.h
@@ -632,17 +632,17 @@ protected:
   RecvSetSystemFont(const nsCString& aFontName) override;
   mozilla::ipc::IPCResult
   RecvGetSystemFont(nsCString* aFontName) override;
 
   ContentCacheInParent mContentCache;
 
   nsIntRect mRect;
   ScreenIntSize mDimensions;
-  ScreenOrientationInternal mOrientation;
+  hal::ScreenOrientation mOrientation;
   float mDPI;
   int32_t mRounding;
   CSSToLayoutDeviceScale mDefaultScale;
   bool mUpdatedDimensions;
   nsSizeMode mSizeMode;
   LayoutDeviceIntPoint mClientOffset;
   LayoutDeviceIntPoint mChromeOffset;
 
--- a/dom/tests/browser/browser_bug1236512.js
+++ b/dom/tests/browser/browser_bug1236512.js
@@ -38,22 +38,26 @@ async function waitContentVisibilityChan
 /**
  * This test is to test the visibility state will change to "hidden" when browser
  * window is fully covered by another non-translucent application. Note that we
  * only support this on Mac for now, other platforms don't support reporting
  * occlusion state.
  */
 add_task(async function() {
   info("creating test window");
+  let winTest = await BrowserTestUtils.openNewBrowserWindow();
   // Specify the width, height, left and top, so that the new window can be
   // fully covered by "window".
-  let winTest = await BrowserTestUtils.openNewBrowserWindow({ width: 500,
-                                                              height: 500,
-                                                              left: 200,
-                                                              top: 200 });
+  let resizePromise = BrowserTestUtils.waitForEvent(winTest, "resize", false, e => {
+    return winTest.innerHeight <= 500 && winTest.innerWidth <= 500;
+  });
+  winTest.moveTo(200, 200);
+  winTest.resizeTo(500, 500);
+  await resizePromise;
+
   let browserTest = winTest.gBrowser;
 
   info(`loading test page: ${testPageURL}`);
   browserTest.selectedBrowser.loadURI(testPageURL);
   await BrowserTestUtils.browserLoaded(browserTest.selectedBrowser);
 
   info("test init visibility state");
   await testContentVisibilityState(false /* isHidden */, browserTest);
--- a/gfx/layers/client/ClientLayerManager.cpp
+++ b/gfx/layers/client/ClientLayerManager.cpp
@@ -5,17 +5,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "ClientLayerManager.h"
 #include "GeckoProfiler.h"              // for AUTO_PROFILER_LABEL
 #include "gfxEnv.h"                     // for gfxEnv
 #include "gfxPrefs.h"                   // for gfxPrefs::LayersTile...
 #include "mozilla/Assertions.h"         // for MOZ_ASSERT, etc
 #include "mozilla/Hal.h"
-#include "mozilla/dom/ScreenOrientation.h"  // for ScreenOrientation
 #include "mozilla/dom/TabChild.h"       // for TabChild
 #include "mozilla/dom/TabGroup.h"       // for TabGroup
 #include "mozilla/hal_sandbox/PHal.h"   // for ScreenConfiguration
 #include "mozilla/layers/CompositableClient.h"
 #include "mozilla/layers/CompositorBridgeChild.h" // for CompositorBridgeChild
 #include "mozilla/layers/FrameUniformityData.h"
 #include "mozilla/layers/ISurfaceAllocator.h"
 #include "mozilla/layers/LayersMessages.h"  // for EditReply, etc
@@ -208,17 +207,17 @@ ClientLayerManager::BeginTransactionWith
   NS_ASSERTION(!InTransaction(), "Nested transactions not allowed");
   mPhase = PHASE_CONSTRUCTION;
 
   MOZ_ASSERT(mKeepAlive.IsEmpty(), "uncommitted txn?");
 
   // If the last transaction was incomplete (a failed DoEmptyTransaction),
   // don't signal a new transaction to ShadowLayerForwarder. Carry on adding
   // to the previous transaction.
-  dom::ScreenOrientationInternal orientation;
+  hal::ScreenOrientation orientation;
   if (dom::TabChild* window = mWidget->GetOwningTabChild()) {
     orientation = window->GetOrientation();
   } else {
     hal::ScreenConfiguration currentConfig;
     hal::GetCurrentScreenConfiguration(&currentConfig);
     orientation = currentConfig.orientation();
   }
   LayoutDeviceIntRect targetBounds = mWidget->GetNaturalBounds();
--- a/gfx/layers/composite/AsyncCompositionManager.cpp
+++ b/gfx/layers/composite/AsyncCompositionManager.cpp
@@ -50,20 +50,20 @@
 struct nsCSSValueSharedList;
 
 namespace mozilla {
 namespace layers {
 
 using namespace mozilla::gfx;
 
 static bool
-IsSameDimension(dom::ScreenOrientationInternal o1, dom::ScreenOrientationInternal o2)
+IsSameDimension(hal::ScreenOrientation o1, hal::ScreenOrientation o2)
 {
-  bool isO1portrait = (o1 == dom::eScreenOrientation_PortraitPrimary || o1 == dom::eScreenOrientation_PortraitSecondary);
-  bool isO2portrait = (o2 == dom::eScreenOrientation_PortraitPrimary || o2 == dom::eScreenOrientation_PortraitSecondary);
+  bool isO1portrait = (o1 == hal::eScreenOrientation_PortraitPrimary || o1 == hal::eScreenOrientation_PortraitSecondary);
+  bool isO2portrait = (o2 == hal::eScreenOrientation_PortraitPrimary || o2 == hal::eScreenOrientation_PortraitSecondary);
   return !(isO1portrait ^ isO2portrait);
 }
 
 static bool
 ContentMightReflowOnOrientationChange(const IntRect& rect)
 {
   return rect.Width() != rect.Height();
 }
@@ -127,19 +127,18 @@ AsyncCompositionManager::ResolveRefLayer
       }
 
       Layer* referent = state->mRoot;
       if (!referent) {
         return;
       }
 
       if (!refLayer->GetLocalVisibleRegion().IsEmpty()) {
-        dom::ScreenOrientationInternal chromeOrientation =
-          mTargetConfig.orientation();
-        dom::ScreenOrientationInternal contentOrientation =
+        hal::ScreenOrientation chromeOrientation = mTargetConfig.orientation();
+        hal::ScreenOrientation contentOrientation =
           state->mTargetConfig.orientation();
         if (!IsSameDimension(chromeOrientation, contentOrientation) &&
             ContentMightReflowOnOrientationChange(mTargetConfig.naturalBounds())) {
           mReadyForCompose = false;
         }
       }
 
       refLayer->ConnectReferentLayer(referent);
--- a/gfx/layers/composite/AsyncCompositionManager.h
+++ b/gfx/layers/composite/AsyncCompositionManager.h
@@ -7,19 +7,19 @@
 #ifndef GFX_ASYNCCOMPOSITIONMANAGER_H
 #define GFX_ASYNCCOMPOSITIONMANAGER_H
 
 #include "Units.h"                      // for ScreenPoint, etc
 #include "mozilla/layers/LayerManagerComposite.h"  // for LayerManagerComposite
 #include "mozilla/Attributes.h"         // for final, etc
 #include "mozilla/RefPtr.h"             // for RefCounted
 #include "mozilla/TimeStamp.h"          // for TimeStamp
-#include "mozilla/dom/ScreenOrientation.h"  // for ScreenOrientation
 #include "mozilla/gfx/BasePoint.h"      // for BasePoint
 #include "mozilla/gfx/Matrix.h"         // for Matrix4x4
+#include "mozilla/HalScreenConfiguration.h" // For ScreenOrientation
 #include "mozilla/layers/FrameUniformityData.h" // For FrameUniformityData
 #include "mozilla/layers/LayersMessages.h"  // for TargetConfig
 #include "mozilla/RefPtr.h"                   // for nsRefPtr
 #include "nsISupportsImpl.h"            // for LayerManager::AddRef, etc
 #include "CompositorBridgeParent.h"     // for TransformsToSkip
 
 namespace mozilla {
 namespace layers {
@@ -97,17 +97,17 @@ public:
   // Call after updating our layer tree.
   void Updated(bool isFirstPaint, const TargetConfig& aTargetConfig)
   {
     mIsFirstPaint |= isFirstPaint;
     mLayersUpdated = true;
     mTargetConfig = aTargetConfig;
   }
 
-  bool RequiresReorientation(mozilla::dom::ScreenOrientationInternal aOrientation) const
+  bool RequiresReorientation(hal::ScreenOrientation aOrientation) const
   {
     return mTargetConfig.orientation() != aOrientation;
   }
 
   // True if the underlying layer tree is ready to be composited.
   bool ReadyForCompose() { return mReadyForCompose; }
 
   // Returns true if the next composition will be the first for a
--- a/gfx/layers/ipc/LayersMessages.ipdlh
+++ b/gfx/layers/ipc/LayersMessages.ipdlh
@@ -22,17 +22,17 @@ using mozilla::gfx::IntPoint from "mozil
 using class mozilla::gfx::Matrix4x4 from "mozilla/gfx/Matrix.h";
 using nscoord from "nsCoord.h";
 using struct nsRect from "nsRect.h";
 using struct nsPoint from "nsPoint.h";
 using class mozilla::TimeDuration from "mozilla/TimeStamp.h";
 using class mozilla::TimeStamp from "mozilla/TimeStamp.h";
 using mozilla::ScreenRotation from "mozilla/WidgetUtils.h";
 using nsCSSPropertyID from "nsCSSPropertyID.h";
-using mozilla::dom::ScreenOrientationInternal from "mozilla/dom/ScreenOrientation.h";
+using hal::ScreenOrientation from "mozilla/HalScreenConfiguration.h";
 using struct mozilla::layers::TextureInfo from "mozilla/layers/CompositorTypes.h";
 using mozilla::LayerMargin from "Units.h";
 using mozilla::LayerPoint from "Units.h";
 using mozilla::LayerCoord from "Units.h";
 using mozilla::LayerSize from "Units.h";
 using mozilla::LayerRect from "Units.h";
 using mozilla::LayerIntRegion from "Units.h";
 using mozilla::ParentLayerIntRect from "Units.h";
@@ -55,17 +55,17 @@ using mozilla::layers::LayersId from "mo
 using mozilla::layers::TransactionId from "mozilla/layers/LayersTypes.h";
 
 namespace mozilla {
 namespace layers {
 
 struct TargetConfig {
   IntRect naturalBounds;
   ScreenRotation rotation;
-  ScreenOrientationInternal orientation;
+  ScreenOrientation orientation;
   nsIntRegion clearRegion;
 };
 
 // Create a shadow layer for |layer|
 struct OpCreatePaintedLayer    { LayerHandle layer; };
 struct OpCreateContainerLayer  { LayerHandle layer; };
 struct OpCreateImageLayer      { LayerHandle layer; };
 struct OpCreateColorLayer      { LayerHandle layer; };
--- a/gfx/layers/ipc/ShadowLayerUtilsX11.cpp
+++ b/gfx/layers/ipc/ShadowLayerUtilsX11.cpp
@@ -86,16 +86,19 @@ SurfaceDescriptorX11::SurfaceDescriptorX
   , mSize(aSize)
   , mGLXPixmap(X11None)
 { }
 
 already_AddRefed<gfxXlibSurface>
 SurfaceDescriptorX11::OpenForeign() const
 {
   Display* display = DefaultXDisplay();
+  if (!display) {
+    return nullptr;
+  }
   Screen* screen = DefaultScreenOfDisplay(display);
 
   RefPtr<gfxXlibSurface> surf;
   XRenderPictFormat* pictFormat = GetXRenderPictFormatFromId(display, mFormat);
   if (pictFormat) {
     surf = new gfxXlibSurface(screen, mId, pictFormat, mSize);
   } else {
     Visual* visual;
--- a/gfx/layers/ipc/ShadowLayers.cpp
+++ b/gfx/layers/ipc/ShadowLayers.cpp
@@ -60,23 +60,23 @@ typedef nsTArray<Edit> EditVector;
 typedef nsTHashtable<nsPtrHashKey<ShadowableLayer>> ShadowableLayerSet;
 typedef nsTArray<OpDestroy> OpDestroyVector;
 
 class Transaction
 {
 public:
   Transaction()
     : mTargetRotation(ROTATION_0)
-    , mTargetOrientation(dom::eScreenOrientation_None)
+    , mTargetOrientation(hal::eScreenOrientation_None)
     , mOpen(false)
     , mRotationChanged(false)
   {}
 
   void Begin(const gfx::IntRect& aTargetBounds, ScreenRotation aRotation,
-             dom::ScreenOrientationInternal aOrientation)
+             hal::ScreenOrientation aOrientation)
   {
     mOpen = true;
     mTargetBounds = aTargetBounds;
     if (aRotation != mTargetRotation) {
       // the first time this is called, mRotationChanged will be false if
       // aRotation is 0, but we should be OK because for the first transaction
       // we should only compose if it is non-empty. See the caller(s) of
       // RotationChanged.
@@ -137,17 +137,17 @@ public:
 
   EditVector mCset;
   nsTArray<CompositableOperation> mPaints;
   OpDestroyVector mDestroyedActors;
   ShadowableLayerSet mMutants;
   ShadowableLayerSet mSimpleMutants;
   gfx::IntRect mTargetBounds;
   ScreenRotation mTargetRotation;
-  dom::ScreenOrientationInternal mTargetOrientation;
+  hal::ScreenOrientation mTargetOrientation;
 
 private:
   bool mOpen;
   bool mRotationChanged;
 
   // disabled
   Transaction(const Transaction&);
   Transaction& operator=(const Transaction&);
@@ -280,17 +280,17 @@ ShadowLayerForwarder::~ShadowLayerForwar
       NS_DispatchToMainThread(event);
     }
   }
 }
 
 void
 ShadowLayerForwarder::BeginTransaction(const gfx::IntRect& aTargetBounds,
                                        ScreenRotation aRotation,
-                                       dom::ScreenOrientationInternal aOrientation)
+                                       hal::ScreenOrientation aOrientation)
 {
   MOZ_ASSERT(IPCOpen(), "no manager to forward to");
   MOZ_ASSERT(mTxn->Finished(), "uncommitted txn?");
   UpdateFwdTransactionId();
   mTxn->Begin(aTargetBounds, aRotation, aOrientation);
 }
 
 static const LayerHandle&
--- a/gfx/layers/ipc/ShadowLayers.h
+++ b/gfx/layers/ipc/ShadowLayers.h
@@ -8,18 +8,18 @@
 #define mozilla_layers_ShadowLayers_h 1
 
 #include <stddef.h>                     // for size_t
 #include <stdint.h>                     // for uint64_t
 #include "gfxTypes.h"
 #include "mozilla/Attributes.h"         // for override
 #include "mozilla/gfx/Rect.h"
 #include "mozilla/WidgetUtils.h"        // for ScreenRotation
-#include "mozilla/dom/ScreenOrientation.h"  // for ScreenOrientation
 #include "mozilla/ipc/SharedMemory.h"   // for SharedMemory, etc
+#include "mozilla/HalScreenConfiguration.h" // for ScreenOrientation
 #include "mozilla/layers/CompositableForwarder.h"
 #include "mozilla/layers/FocusTarget.h"
 #include "mozilla/layers/LayersTypes.h"
 #include "mozilla/layers/TextureForwarder.h"
 #include "mozilla/layers/CompositorTypes.h"  // for OpenMode, etc
 #include "mozilla/layers/CompositorBridgeChild.h"
 #include "nsCOMPtr.h"                   // for already_AddRefed
 #include "nsRegion.h"                   // for nsIntRegion
@@ -153,17 +153,17 @@ public:
                                ShadowableLayer* aLayer);
 
   /**
    * Begin recording a transaction to be forwarded atomically to a
    * LayerManagerComposite.
    */
   void BeginTransaction(const gfx::IntRect& aTargetBounds,
                         ScreenRotation aRotation,
-                        mozilla::dom::ScreenOrientationInternal aOrientation);
+                        hal::ScreenOrientation aOrientation);
 
   /**
    * The following methods may only be called after BeginTransaction()
    * but before EndTransaction().  They mirror the LayerManager
    * interface in Layers.h.
    */
 
   /**
--- a/gfx/vr/VRDisplayClient.cpp
+++ b/gfx/vr/VRDisplayClient.cpp
@@ -8,16 +8,17 @@
 
 #include "prlink.h"
 #include "prenv.h"
 #include "gfxPrefs.h"
 #include "nsIGlobalObject.h"
 #include "nsRefPtrHashtable.h"
 #include "nsString.h"
 #include "mozilla/dom/GamepadManager.h"
+#include "mozilla/dom/Gamepad.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Unused.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIScreenManager.h"
 
 #ifdef XP_WIN
 #include "../layers/d3d11/CompositorD3D11.h"
 #endif
@@ -164,17 +165,18 @@ VRDisplayClient::FireGamepadEvents()
         dom::GamepadChangeEvent event(gamepadId, dom::GamepadServiceType::VR, body);
         gamepadManager->Update(event);
       }
       // Do not process any further events for removed controllers
       continue;
     }
 
     // Send events to notify that new controllers are added
-    if (lastState.controllerName[0] == '\0') {
+    RefPtr<dom::Gamepad> existing = gamepadManager->GetGamepad(gamepadId, dom::GamepadServiceType::VR);
+    if (lastState.controllerName[0] == '\0' || !existing) {
       dom::GamepadAdded info(NS_ConvertUTF8toUTF16(state.controllerName),
                              dom::GamepadMappingType::_empty,
                              state.hand,
                              mDisplayInfo.mDisplayID,
                              state.numButtons,
                              state.numAxes,
                              state.numHaptics);
       dom::GamepadChangeEventBody body(info);
--- a/gfx/vr/ipc/VRManagerChild.h
+++ b/gfx/vr/ipc/VRManagerChild.h
@@ -2,16 +2,17 @@
 /* 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 MOZILLA_GFX_VR_VRMANAGERCHILD_H
 #define MOZILLA_GFX_VR_VRMANAGERCHILD_H
 
+#include "mozilla/dom/WindowBinding.h" // For FrameRequestCallback
 #include "mozilla/gfx/PVRManagerChild.h"
 #include "mozilla/ipc/SharedMemory.h"   // for SharedMemory, etc
 #include "ThreadSafeRefcountingWithMainThreadDestruction.h"
 #include "mozilla/layers/ISurfaceAllocator.h"  // for ISurfaceAllocator
 #include "mozilla/layers/LayersTypes.h"  // for LayersBackend
 #include "mozilla/layers/TextureForwarder.h"
 
 namespace mozilla {
--- a/gfx/webrender_bindings/RenderD3D11TextureHostOGL.cpp
+++ b/gfx/webrender_bindings/RenderD3D11TextureHostOGL.cpp
@@ -12,36 +12,16 @@
 #include "GLContextEGL.h"
 #include "mozilla/DebugOnly.h"
 #include "mozilla/gfx/Logging.h"
 #include "ScopedGLHelpers.h"
 
 namespace mozilla {
 namespace wr {
 
-static EGLint
-GetEGLTextureFormat(gfx::SurfaceFormat aFormat)
-{
-  switch (aFormat) {
-    case gfx::SurfaceFormat::B8G8R8A8:
-    case gfx::SurfaceFormat::B8G8R8X8:
-    case gfx::SurfaceFormat::R8G8B8A8:
-    case gfx::SurfaceFormat::R8G8B8X8:
-    case gfx::SurfaceFormat::A8R8G8B8:
-    case gfx::SurfaceFormat::X8R8G8B8:
-      return LOCAL_EGL_TEXTURE_RGBA;
-    case gfx::SurfaceFormat::R8G8B8:
-    case gfx::SurfaceFormat::B8G8R8:
-      return LOCAL_EGL_TEXTURE_RGB;
-    default:
-      gfxCriticalError() << "GetEGLTextureFormat(): unexpected texture format";
-      return LOCAL_EGL_TEXTURE_RGBA;
-  }
-}
-
 RenderDXGITextureHostOGL::RenderDXGITextureHostOGL(WindowsHandle aHandle,
                                                    gfx::SurfaceFormat aFormat,
                                                    gfx::IntSize aSize)
   : mHandle(aHandle)
   , mSurface(0)
   , mStream(0)
   , mTextureHandle{0}
   , mFormat(aFormat)
--- a/hal/Hal.cpp
+++ b/hal/Hal.cpp
@@ -16,17 +16,16 @@
 #include "nsIWebNavigation.h"
 #include "nsThreadUtils.h"
 #include "nsXULAppAPI.h"
 #include "nsPIDOMWindow.h"
 #include "nsJSUtils.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/Observer.h"
 #include "mozilla/dom/ContentChild.h"
-#include "mozilla/dom/ScreenOrientation.h"
 #include "WindowIdentifier.h"
 
 #ifdef XP_WIN
 #include <process.h>
 #define getpid _getpid
 #endif
 
 using namespace mozilla::services;
@@ -534,17 +533,17 @@ GetCurrentScreenConfiguration(ScreenConf
 void
 NotifyScreenConfigurationChange(const ScreenConfiguration& aScreenConfiguration)
 {
   ScreenConfigurationObservers().CacheInformation(aScreenConfiguration);
   ScreenConfigurationObservers().BroadcastCachedInformation();
 }
 
 bool
-LockScreenOrientation(const dom::ScreenOrientationInternal& aOrientation)
+LockScreenOrientation(const ScreenOrientation& aOrientation)
 {
   AssertMainThread();
   RETURN_PROXY_IF_SANDBOXED(LockScreenOrientation(aOrientation), false);
 }
 
 void
 UnlockScreenOrientation()
 {
--- a/hal/Hal.h
+++ b/hal/Hal.h
@@ -5,17 +5,16 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_Hal_h
 #define mozilla_Hal_h
 
 #include "base/basictypes.h"
 #include "base/platform_thread.h"
 #include "nsTArray.h"
-#include "mozilla/dom/ScreenOrientation.h"
 #include "mozilla/hal_sandbox/PHal.h"
 #include "mozilla/HalBatteryInformation.h"
 #include "mozilla/HalNetworkInformation.h"
 #include "mozilla/HalScreenConfiguration.h"
 #include "mozilla/HalWakeLockInformation.h"
 #include "mozilla/HalTypes.h"
 #include "mozilla/Types.h"
 
@@ -220,17 +219,17 @@ void GetCurrentScreenConfiguration(hal::
  * @param aScreenConfiguration The new screen orientation.
  */
 void NotifyScreenConfigurationChange(const hal::ScreenConfiguration& aScreenConfiguration);
 
 /**
  * Lock the screen orientation to the specific orientation.
  * @return Whether the lock has been accepted.
  */
-MOZ_MUST_USE bool LockScreenOrientation(const dom::ScreenOrientationInternal& aOrientation);
+MOZ_MUST_USE bool LockScreenOrientation(const hal::ScreenOrientation& aOrientation);
 
 /**
  * Unlock the screen orientation.
  */
 void UnlockScreenOrientation();
 
 /**
  * Return true if the current platform supports the setting of process
--- a/hal/HalScreenConfiguration.h
+++ b/hal/HalScreenConfiguration.h
@@ -6,15 +6,30 @@
 
 #ifndef mozilla_HalScreenConfiguration_h
 #define mozilla_HalScreenConfiguration_h
 
 #include "mozilla/Observer.h"
 
 namespace mozilla {
 namespace hal {
+
+// Make sure that any change to ScreenOrientation values are also made in
+// mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoScreenOrientation.java
+typedef uint32_t ScreenOrientation;
+
+static const ScreenOrientation eScreenOrientation_None               = 0;
+static const ScreenOrientation eScreenOrientation_PortraitPrimary    = 1u << 0;
+static const ScreenOrientation eScreenOrientation_PortraitSecondary  = 1u << 1;
+static const ScreenOrientation eScreenOrientation_LandscapePrimary   = 1u << 2;
+static const ScreenOrientation eScreenOrientation_LandscapeSecondary = 1u << 3;
+//eScreenOrientation_Default will use the natural orientation for the deivce,
+//it could be PortraitPrimary or LandscapePrimary depends on display resolution
+static const ScreenOrientation eScreenOrientation_Default            = 1u << 4;
+
 class ScreenConfiguration;
 typedef Observer<ScreenConfiguration> ScreenConfigurationObserver;
+
 } // namespace hal
 } // namespace mozilla
 
 #endif  // mozilla_HalScreenConfiguration_h
 
--- a/hal/android/AndroidHal.cpp
+++ b/hal/android/AndroidHal.cpp
@@ -3,18 +3,18 @@
  * 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 "Hal.h"
 #include "HalImpl.h"
 #include "WindowIdentifier.h"
 #include "AndroidBridge.h"
 #include "mozilla/dom/network/Constants.h"
-#include "mozilla/dom/ScreenOrientation.h"
 #include "nsIScreenManager.h"
+#include "nsPIDOMWindow.h"
 #include "nsServiceManagerUtils.h"
 
 using namespace mozilla::dom;
 using namespace mozilla::hal;
 
 namespace java = mozilla::java;
 
 namespace mozilla {
@@ -120,39 +120,39 @@ GetCurrentScreenConfiguration(ScreenConf
     do_GetService("@mozilla.org/gfx/screenmanager;1", &rv);
   if (NS_FAILED(rv)) {
     NS_ERROR("Can't find nsIScreenManager!");
     return;
   }
 
   int32_t colorDepth, pixelDepth;
   int16_t angle;
-  ScreenOrientationInternal orientation;
+  ScreenOrientation orientation;
   nsCOMPtr<nsIScreen> screen;
 
   int32_t rectX, rectY, rectWidth, rectHeight;
 
   screenMgr->GetPrimaryScreen(getter_AddRefs(screen));
   
   screen->GetRect(&rectX, &rectY, &rectWidth, &rectHeight);
   screen->GetColorDepth(&colorDepth);
   screen->GetPixelDepth(&pixelDepth);
-  orientation = static_cast<ScreenOrientationInternal>(bridge->GetScreenOrientation());
+  orientation = static_cast<ScreenOrientation>(bridge->GetScreenOrientation());
   angle = bridge->GetScreenAngle();
 
   *aScreenConfiguration =
     hal::ScreenConfiguration(nsIntRect(rectX, rectY, rectWidth, rectHeight),
                              orientation, angle, colorDepth, pixelDepth);
 }
 
 bool
-LockScreenOrientation(const ScreenOrientationInternal& aOrientation)
+LockScreenOrientation(const ScreenOrientation& aOrientation)
 {
   // Force the default orientation to be portrait-primary.
-  ScreenOrientationInternal orientation =
+  ScreenOrientation orientation =
     aOrientation == eScreenOrientation_Default ? eScreenOrientation_PortraitPrimary
                                                : aOrientation;
 
   switch (orientation) {
     // The Android backend only supports these orientations.
     case eScreenOrientation_PortraitPrimary:
     case eScreenOrientation_PortraitSecondary:
     case eScreenOrientation_PortraitPrimary | eScreenOrientation_PortraitSecondary:
--- a/hal/fallback/FallbackScreenConfiguration.cpp
+++ b/hal/fallback/FallbackScreenConfiguration.cpp
@@ -19,17 +19,17 @@ DisableScreenConfigurationNotifications(
 
 void
 GetCurrentScreenConfiguration(hal::ScreenConfiguration* aScreenConfiguration)
 {
   fallback::GetCurrentScreenConfiguration(aScreenConfiguration);
 }
 
 bool
-LockScreenOrientation(const dom::ScreenOrientationInternal& aOrientation)
+LockScreenOrientation(const ScreenOrientation& aOrientation)
 {
   return false;
 }
 
 void
 UnlockScreenOrientation()
 {
 }
--- a/hal/fallback/FallbackScreenConfiguration.h
+++ b/hal/fallback/FallbackScreenConfiguration.h
@@ -1,17 +1,16 @@
 /* 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 mozilla_fallback_FallbackScreenConfiguration_h
 #define mozilla_fallback_FallbackScreenConfiguration_h
 
 #include "Hal.h"
-#include "mozilla/dom/ScreenOrientation.h"
 #include "nsIScreenManager.h"
 #include "nsServiceManagerUtils.h"
 
 namespace mozilla {
 namespace fallback {
 
 inline void
 GetCurrentScreenConfiguration(hal::ScreenConfiguration* aScreenConfiguration)
@@ -20,26 +19,26 @@ GetCurrentScreenConfiguration(hal::Scree
   nsCOMPtr<nsIScreenManager> screenMgr =
     do_GetService("@mozilla.org/gfx/screenmanager;1", &rv);
   if (NS_FAILED(rv)) {
     NS_ERROR("Can't find nsIScreenManager!");
     return;
   }
 
   int32_t colorDepth, pixelDepth, x, y, w, h;
-  dom::ScreenOrientationInternal orientation;
+  ScreenOrientation orientation;
   nsCOMPtr<nsIScreen> screen;
 
   screenMgr->GetPrimaryScreen(getter_AddRefs(screen));
   screen->GetRect(&x, &y, &w, &h);
   screen->GetColorDepth(&colorDepth);
   screen->GetPixelDepth(&pixelDepth);
   orientation = w >= h
-                ? dom::eScreenOrientation_LandscapePrimary
-                : dom::eScreenOrientation_PortraitPrimary;
+                ? hal::eScreenOrientation_LandscapePrimary
+                : hal::eScreenOrientation_PortraitPrimary;
 
   *aScreenConfiguration = hal::ScreenConfiguration(nsIntRect(x, y, w, h),
 						   orientation, 0,
 						   colorDepth, pixelDepth);
 }
 
 }
 }
--- a/hal/sandbox/PHal.ipdl
+++ b/hal/sandbox/PHal.ipdl
@@ -4,17 +4,17 @@
  * 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 protocol PContent;
 include protocol PBrowser;
 
 include "mozilla/GfxMessageUtils.h";
 
-using mozilla::dom::ScreenOrientationInternal from "mozilla/dom/ScreenOrientation.h";
+using hal::ScreenOrientation from "mozilla/HalScreenConfiguration.h";
 using mozilla::hal::SensorType from "mozilla/HalSensor.h";
 using mozilla::hal::WakeLockControl from "mozilla/HalTypes.h";
 using mozilla::hal::ProcessPriority from "mozilla/HalTypes.h";
 using nsIntRect from "nsRect.h";
 using PRTime from "prtime.h";
 
 namespace mozilla {
 
@@ -41,17 +41,17 @@ struct WakeLockInformation {
   nsString topic;
   uint32_t numLocks;
   uint32_t numHidden;
   uint64_t[] lockingProcesses;
 };
 
 struct ScreenConfiguration {
   nsIntRect rect;
-  ScreenOrientationInternal orientation;
+  ScreenOrientation orientation;
   uint16_t angle;
   uint32_t colorDepth;
   uint32_t pixelDepth;
 };
 
 } // namespace hal
 
 namespace hal_sandbox {
@@ -85,17 +85,17 @@ parent:
                          uint64_t aProcessID);
     async EnableWakeLockNotifications();
     async DisableWakeLockNotifications();
     sync GetWakeLockInfo(nsString aTopic)
       returns (WakeLockInformation aWakeLockInfo);
 
     async EnableScreenConfigurationNotifications();
     async DisableScreenConfigurationNotifications();
-    sync LockScreenOrientation(ScreenOrientationInternal aOrientation)
+    sync LockScreenOrientation(ScreenOrientation aOrientation)
       returns (bool allowed);
     async UnlockScreenOrientation();
 
 child:
     async NotifySensorChange(SensorData aSensorData);
 
 parent:
     async EnableSensorNotifications(SensorType aSensor);
--- a/hal/sandbox/SandboxHal.cpp
+++ b/hal/sandbox/SandboxHal.cpp
@@ -7,17 +7,16 @@
 #include "Hal.h"
 #include "HalLog.h"
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/ContentParent.h"
 #include "mozilla/hal_sandbox/PHalChild.h"
 #include "mozilla/hal_sandbox/PHalParent.h"
 #include "mozilla/dom/TabParent.h"
 #include "mozilla/dom/TabChild.h"
-#include "mozilla/dom/ScreenOrientation.h"
 #include "mozilla/fallback/FallbackScreenConfiguration.h"
 #include "mozilla/EnumeratedRange.h"
 #include "mozilla/Observer.h"
 #include "mozilla/Unused.h"
 #include "nsAutoPtr.h"
 #include "WindowIdentifier.h"
 
 using namespace mozilla;
@@ -117,17 +116,17 @@ DisableScreenConfigurationNotifications(
 
 void
 GetCurrentScreenConfiguration(ScreenConfiguration* aScreenConfiguration)
 {
   fallback::GetCurrentScreenConfiguration(aScreenConfiguration);
 }
 
 bool
-LockScreenOrientation(const dom::ScreenOrientationInternal& aOrientation)
+LockScreenOrientation(const ScreenOrientation& aOrientation)
 {
   bool allowed;
   Hal()->SendLockScreenOrientation(aOrientation, &allowed);
   return allowed;
 }
 
 void
 UnlockScreenOrientation()
@@ -327,17 +326,17 @@ public:
 
   virtual mozilla::ipc::IPCResult
   RecvDisableScreenConfigurationNotifications() override {
     hal::UnregisterScreenConfigurationObserver(this);
     return IPC_OK();
   }
 
   virtual mozilla::ipc::IPCResult
-  RecvLockScreenOrientation(const dom::ScreenOrientationInternal& aOrientation, bool* aAllowed) override
+  RecvLockScreenOrientation(const ScreenOrientation& aOrientation, bool* aAllowed) override
   {
     // FIXME/bug 777980: unprivileged content may only lock
     // orientation while fullscreen.  We should check whether the
     // request comes from an actor in a process that might be
     // fullscreen.  We don't have that information currently.
     *aAllowed = hal::LockScreenOrientation(aOrientation);
     return IPC_OK();
   }
--- a/js/xpconnect/src/XPCJSRuntime.cpp
+++ b/js/xpconnect/src/XPCJSRuntime.cpp
@@ -20,16 +20,17 @@
 #include "nsNetUtil.h"
 
 #include "nsExceptionHandler.h"
 #include "nsIMemoryInfoDumper.h"
 #include "nsIMemoryReporter.h"
 #include "nsIObserverService.h"
 #include "nsIDebug2.h"
 #include "nsIDocShell.h"
+#include "nsIDocument.h"
 #include "nsIRunnable.h"
 #include "nsPIDOMWindow.h"
 #include "nsPrintfCString.h"
 #include "nsWindowSizes.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/Services.h"
 #include "mozilla/dom/ScriptLoader.h"
@@ -2136,49 +2137,43 @@ class OrphanReporter : public JS::Object
   public:
     explicit OrphanReporter(GetISupportsFun aGetISupports)
       : JS::ObjectPrivateVisitor(aGetISupports)
       , mState(OrphanMallocSizeOf)
     {}
 
     virtual size_t sizeOfIncludingThis(nsISupports* aSupports) override
     {
-        size_t n = 0;
         nsCOMPtr<nsINode> node = do_QueryInterface(aSupports);
-        // https://bugzilla.mozilla.org/show_bug.cgi?id=773533#c11 explains
-        // that we have to skip XBL elements because they violate certain
-        // assumptions.  Yuk.
-        if (node && !node->IsInComposedDoc() &&
-            !(node->IsElement() && node->AsElement()->IsInNamespace(kNameSpaceID_XBL)))
-        {
-            // This is an orphan node.  If we haven't already handled the
-            // sub-tree that this node belongs to, measure the sub-tree's size
-            // and then record its root so we don't measure it again.
-            nsCOMPtr<nsINode> orphanTree = node->SubtreeRoot();
-            if (orphanTree && !mState.HaveSeenPtr(orphanTree.get())) {
-                n += SizeOfTreeIncludingThis(orphanTree);
-            }
+        // https://bugzilla.mozilla.org/show_bug.cgi?id=773533#c11 explains that we have to skip
+        // XBL elements because they violate certain assumptions.  Yuk.
+        if (!node || node->IsInComposedDoc() ||
+            (node->IsElement() && node->AsElement()->IsInNamespace(kNameSpaceID_XBL))) {
+            return 0;
         }
-        return n;
-    }
-
-    size_t SizeOfTreeIncludingThis(nsINode* tree)
-    {
-        size_t nodeSize = 0;
+
+        // This is an orphan node.  If we haven't already handled the sub-tree that this node
+        // belongs to, measure the sub-tree's size and then record its root so we don't measure it
+        // again.
+        nsCOMPtr<nsINode> orphanTree = node->SubtreeRoot();
+        if (!orphanTree || mState.HaveSeenPtr(orphanTree.get())) {
+            return 0;
+        }
+
         nsWindowSizes sizes(mState);
-        tree->AddSizeOfIncludingThis(sizes, &nodeSize);
-        for (nsIContent* child = tree->GetFirstChild(); child; child = child->GetNextNode(tree))
-            child->AddSizeOfIncludingThis(sizes, &nodeSize);
-
-        // We combine the node size with nsStyleSizes here. It's not ideal, but
-        // it's hard to get the style structs measurements out to
-        // nsWindowMemoryReporter. Also, we drop mServoData in
-        // UnbindFromTree(), so in theory any non-in-tree element won't have
-        // any style data to measure.
-        return nodeSize + sizes.getTotalSize();
+        nsIDocument::AddSizeOfNodeTree(*orphanTree, sizes);
+
+        // We combine the node size with nsStyleSizes here. It's not ideal, but it's hard to get
+        // the style structs measurements out to nsWindowMemoryReporter. Also, we drop mServoData
+        // in UnbindFromTree(), so in theory any non-in-tree element won't have any style data to
+        // measure.
+        //
+        // FIXME(emilio): We should ideally not do this, since ShadowRoots keep their StyleSheets
+        // alive even when detached from a document, and those could be significant in theory.
+        return sizes.getTotalSize();
     }
 
   private:
     SizeOfState mState;
 };
 
 #ifdef DEBUG
 static bool
--- a/layout/generic/nsCanvasFrame.h
+++ b/layout/generic/nsCanvasFrame.h
@@ -221,16 +221,18 @@ public:
   NS_DISPLAY_DECL_NAME("CanvasBackgroundImage", TYPE_CANVAS_BACKGROUND_IMAGE)
 };
 
 class nsDisplayCanvasThemedBackground : public nsDisplayThemedBackground {
 public:
   nsDisplayCanvasThemedBackground(nsDisplayListBuilder* aBuilder, nsIFrame* aFrame)
     : nsDisplayThemedBackground(aBuilder, aFrame,
                                 aFrame->GetRectRelativeToSelf() + aBuilder->ToReferenceFrame(aFrame))
-  {}
+  {
+    nsDisplayThemedBackground::Init(aBuilder);
+  }
 
   virtual void Paint(nsDisplayListBuilder* aBuilder, gfxContext* aCtx) override;
 
   NS_DISPLAY_DECL_NAME("CanvasThemedBackground", TYPE_CANVAS_THEMED_BACKGROUND)
 };
 
 #endif /* nsCanvasFrame_h___ */
--- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoScreenOrientation.java
+++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoScreenOrientation.java
@@ -23,17 +23,17 @@ import java.util.List;
  * Updates, locks and unlocks the screen orientation.
  *
  * Note: Replaces the OnOrientationChangeListener to avoid redundant rotation
  * event handling.
  */
 public class GeckoScreenOrientation {
     private static final String LOGTAG = "GeckoScreenOrientation";
 
-    // Make sure that any change in dom/base/ScreenOrientation.h happens here too.
+    // Make sure that any change in hal/HalScreenConfiguration.h happens here too.
     public enum ScreenOrientation {
         NONE(0),
         PORTRAIT_PRIMARY(1 << 0),
         PORTRAIT_SECONDARY(1 << 1),
         PORTRAIT(PORTRAIT_PRIMARY.value | PORTRAIT_SECONDARY.value),
         LANDSCAPE_PRIMARY(1 << 2),
         LANDSCAPE_SECONDARY(1 << 3),
         LANDSCAPE(LANDSCAPE_PRIMARY.value | LANDSCAPE_SECONDARY.value),
--- a/taskcluster/scripts/misc/build-clang-7-pre-mingw.sh
+++ b/taskcluster/scripts/misc/build-clang-7-pre-mingw.sh
@@ -10,17 +10,17 @@ UPLOAD_DIR=$HOME/artifacts
 TOOLCHAIN_DIR=$WORKSPACE/moz-toolchain
 INSTALL_DIR=$TOOLCHAIN_DIR/build/stage3/clang
 CROSS_PREFIX_DIR=$INSTALL_DIR/x86_64-w64-mingw32
 SRC_DIR=$TOOLCHAIN_DIR/src
 
 CLANG_VERSION=7.0.0
 make_flags="-j$(nproc)"
 
-mingw_version=49ca7cfe7e09f924e939921b42a3452203c437b7
+mingw_version=30af18252d4e965e98612e215b8cf6b7ae42c01a
 libunwind_version=86ab23972978242b6f9e27cebc239f3e8428b1af
 
 binutils_version=2.27
 binutils_ext=bz2
 binutils_sha=369737ce51587f92466041a97ab7d2358c6d9e1b6490b3940eb09fb0a9a6ac88
 
 # This is default value of _WIN32_WINNT. Gecko configure script explicitly sets this,
 # so this is not used to build Gecko itself. We default to 0x600, which is Windows Vista.
--- a/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm
+++ b/testing/mochitest/BrowserTestUtils/BrowserTestUtils.jsm
@@ -20,16 +20,19 @@ var EXPORTED_SYMBOLS = [
 ];
 
 ChromeUtils.import("resource://gre/modules/AppConstants.jsm");
 ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
 ChromeUtils.import("resource://gre/modules/Services.jsm");
 ChromeUtils.import("resource://testing-common/TestUtils.jsm");
 ChromeUtils.import("resource://testing-common/ContentTask.jsm");
 
+ChromeUtils.defineModuleGetter(this, "BrowserWindowTracker",
+  "resource:///modules/BrowserWindowTracker.jsm");
+
 Services
   .mm
   .loadFrameScript(
     "chrome://mochikit/content/tests/BrowserTestUtils/content-utils.js", true);
 
 ChromeUtils.defineModuleGetter(this, "E10SUtils",
   "resource://gre/modules/E10SUtils.jsm");
 
@@ -695,71 +698,29 @@ var BrowserTestUtils = {
           resolve(subject.QueryInterface(Ci.nsIDOMWindow));
         }
       }
       Services.ww.registerNotification(observer);
     });
   },
 
   /**
-   * @param {Object} options
-   *        {
-   *          private: A boolean indicating if the window should be
-   *                   private
-   *          remote:  A boolean indicating if the window should run
-   *                   remote browser tabs or not. If omitted, the window
-   *                   will choose the profile default state.
-   *          width: Desired width of window
-   *          height: Desired height of window
-   *        }
+   * Open a new browser window from an existing one.
+   * This relies on OpenBrowserWindow in browser.js, and waits for the window
+   * to be completely loaded before resolving.
+   *
    * @return {Promise}
    *         Resolves with the new window once it is loaded.
    */
   async openNewBrowserWindow(options = {}) {
-    let argString = Cc["@mozilla.org/supports-string;1"].
-                    createInstance(Ci.nsISupportsString);
-    argString.data = "";
-    let features = "chrome,dialog=no,all";
-    let opener = null;
-
-    if (options.opener) {
-      opener = options.opener;
-    }
-
-    if (options.private) {
-      features += ",private";
-    }
-
-    if (options.width) {
-      features += ",width=" + options.width;
-    }
-    if (options.height) {
-      features += ",height=" + options.height;
+    let currentWin = BrowserWindowTracker.getTopWindow({private: false});
+    if (!currentWin) {
+      throw new Error("Can't open a new browser window from this helper if no non-private window is open.");
     }
-
-    if (options.left) {
-      features += ",left=" + options.left;
-    }
-
-    if (options.top) {
-      features += ",top=" + options.top;
-    }
-
-    if (options.hasOwnProperty("remote")) {
-      let remoteState = options.remote ? "remote" : "non-remote";
-      features += `,${remoteState}`;
-    }
-
-    if (options.url) {
-      argString.data = options.url;
-    }
-
-    let win = Services.ww.openWindow(
-      opener, AppConstants.BROWSER_CHROME_URL, "_blank",
-      features, argString);
+    let win = currentWin.OpenBrowserWindow(options);
 
     // Wait for browser-delayed-startup-finished notification, it indicates
     // that the window has loaded completely and is ready to be used for
     // testing.
     let startupPromise =
       TestUtils.topicObserved("browser-delayed-startup-finished",
                               subject => subject == win).then(() => win);
 
--- a/testing/raptor/raptor/manifest.py
+++ b/testing/raptor/raptor/manifest.py
@@ -84,16 +84,23 @@ def write_test_settings_json(test_detail
             test_settings['raptor-options']['measure']['hero'] = test_details['hero'].split()
     if test_details.get("page_timeout", None) is not None:
         test_settings['raptor-options']['page_timeout'] = int(test_details['page_timeout'])
     test_settings['raptor-options']['unit'] = test_details.get("unit", "ms")
     if test_details.get("lower_is_better", "true") == "false":
         test_settings['raptor-options']['lower_is_better'] = False
     else:
         test_settings['raptor-options']['lower_is_better'] = True
+
+    # support optional subtest unit/lower_is_better fields, default to main test values if not set
+    val = test_details.get('subtest_unit', test_settings['raptor-options']['unit'])
+    test_settings['raptor-options']['subtest_unit'] = val
+    val = test_details.get('subtest_lower', test_settings['raptor-options']['lower_is_better'])
+    test_settings['raptor-options']['subtest_lower_is_better'] = val
+
     if test_details.get("alert_threshold", None) is not None:
         test_settings['raptor-options']['alert_threshold'] = float(test_details['alert_threshold'])
 
     settings_file = os.path.join(tests_dir, test_details['name'] + '.json')
     try:
         with open(settings_file, 'w') as out_file:
             json.dump(test_settings, out_file, indent=4, ensure_ascii=False)
             out_file.close()
--- a/testing/raptor/raptor/output.py
+++ b/testing/raptor/raptor/output.py
@@ -46,16 +46,17 @@ class Output(object):
             vals = []
             subtests = []
             suite = {
                 'name': test.name,
                 'type': test.type,
                 'extraOptions': test.extra_options,
                 'subtests': subtests,
                 'lowerIsBetter': test.lower_is_better,
+                'unit': test.unit,
                 'alertThreshold': float(test.alert_threshold)
             }
 
             suites.append(suite)
 
             # process results for pageloader type of tests
             if test.type == "pageload":
                 # each test can report multiple measurements per pageload
@@ -70,20 +71,20 @@ class Output(object):
                 # u'Firefox 62.0a1 20180528123052', u'lower_is_better': True, u'page':
                 # u'https://www.amazon.com/s/url=search-alias%3Daps&field-keywords=laptop',
                 # u'unit': u'ms', u'alert_threshold': 2}
 
                 for measurement_name, replicates in test.measurements.iteritems():
                     new_subtest = {}
                     new_subtest['name'] = test.name + "-" + measurement_name
                     new_subtest['replicates'] = replicates
-                    new_subtest['lowerIsBetter'] = test.lower_is_better
+                    new_subtest['lowerIsBetter'] = test.subtest_lower_is_better
                     new_subtest['alertThreshold'] = float(test.alert_threshold)
                     new_subtest['value'] = 0
-                    new_subtest['unit'] = test.unit
+                    new_subtest['unit'] = test.subtest_unit
 
                     filtered_values = filter.ignore_first(new_subtest['replicates'], 1)
                     new_subtest['value'] = filter.median(filtered_values)
 
                     vals.append([new_subtest['value'], new_subtest['name']])
                     subtests.append(new_subtest)
 
             elif test.type == "benchmark":
@@ -141,19 +142,19 @@ class Output(object):
 
         _subtests = {}
         data = test.measurements['speedometer']
         for page_cycle in data:
             for sub, replicates in page_cycle[0].iteritems():
                 # for each pagecycle, build a list of subtests and append all related replicates
                 if sub not in _subtests.keys():
                     # subtest not added yet, first pagecycle, so add new one
-                    _subtests[sub] = {'unit': test.unit,
+                    _subtests[sub] = {'unit': test.subtest_unit,
                                       'alertThreshold': float(test.alert_threshold),
-                                      'lowerIsBetter': test.lower_is_better,
+                                      'lowerIsBetter': test.subtest_lower_is_better,
                                       'name': sub,
                                       'replicates': []}
                 _subtests[sub]['replicates'].extend([round(x, 3) for x in replicates])
 
         vals = []
         subtests = []
         names = _subtests.keys()
         names.sort(reverse=True)
@@ -178,19 +179,19 @@ class Output(object):
         _subtests = {}
         data = test.measurements['wasm-misc']
         for page_cycle in data:
             for item in page_cycle[0]:
                 # for each pagecycle, build a list of subtests and append all related replicates
                 sub = item['name']
                 if sub not in _subtests.keys():
                     # subtest not added yet, first pagecycle, so add new one
-                    _subtests[sub] = {'unit': test.unit,
+                    _subtests[sub] = {'unit': test.subtest_unit,
                                       'alertThreshold': float(test.alert_threshold),
-                                      'lowerIsBetter': test.lower_is_better,
+                                      'lowerIsBetter': test.subtest_lower_is_better,
                                       'name': sub,
                                       'replicates': []}
                 _subtests[sub]['replicates'].append(item['time'])
 
         vals = []
         subtests = []
         names = _subtests.keys()
         names.sort(reverse=True)
@@ -225,19 +226,19 @@ class Output(object):
         for page_cycle in data:
             data = json.loads(page_cycle[0])
             for item in data:
                 # for each pagecycle, build a list of subtests and append all related replicates
                 sub = item['name']
                 replicates = [item['duration']]
                 if sub not in _subtests.keys():
                     # subtest not added yet, first pagecycle, so add new one
-                    _subtests[sub] = {'unit': test.unit,
+                    _subtests[sub] = {'unit': test.subtest_unit,
                                       'alertThreshold': float(test.alert_threshold),
-                                      'lowerIsBetter': test.lower_is_better,
+                                      'lowerIsBetter': test.subtest_lower_is_better,
                                       'name': sub,
                                       'replicates': []}
                 _subtests[sub]['replicates'].extend([round(x, 3) for x in replicates])
 
         vals = []
         subtests = []
         names = _subtests.keys()
         names.sort(reverse=True)
@@ -280,19 +281,19 @@ class Output(object):
 
             # TODO: this assumes a single suite is run
             suite = page_cycle_results.keys()[0]
             for sub in page_cycle_results[suite].keys():
                 replicate = round(page_cycle_results[suite][sub]['frameLength']['average'], 3)
 
                 if sub not in _subtests.keys():
                     # subtest not added yet, first pagecycle, so add new one
-                    _subtests[sub] = {'unit': test.unit,
+                    _subtests[sub] = {'unit': test.subtest_unit,
                                       'alertThreshold': float(test.alert_threshold),
-                                      'lowerIsBetter': test.lower_is_better,
+                                      'lowerIsBetter': test.subtest_lower_is_better,
                                       'name': sub,
                                       'replicates': []}
                 _subtests[sub]['replicates'].extend([replicate])
 
         vals = []
         subtests = []
         names = _subtests.keys()
         names.sort(reverse=True)
@@ -306,27 +307,27 @@ class Output(object):
     def parseSunspiderOutput(self, test):
         _subtests = {}
         data = test.measurements['sunspider']
         for page_cycle in data:
             for sub, replicates in page_cycle[0].iteritems():
                 # for each pagecycle, build a list of subtests and append all related replicates
                 if sub not in _subtests.keys():
                     # subtest not added yet, first pagecycle, so add new one
-                    _subtests[sub] = {'unit': test.unit,
+                    _subtests[sub] = {'unit': test.subtest_unit,
                                       'alertThreshold': float(test.alert_threshold),
-                                      'lowerIsBetter': test.lower_is_better,
+                                      'lowerIsBetter': test.subtest_lower_is_better,
                                       'name': sub,
                                       'replicates': []}
                 _subtests[sub]['replicates'].extend([round(x, 3) for x in replicates])
 
         total_subtest = {
-            'unit': test.unit,
+            'unit': test.subtest_unit,
             'alertThreshold': float(test.alert_threshold),
-            'lowerIsBetter': test.lower_is_better,
+            'lowerIsBetter': test.subtest_lower_is_better,
             'replicates': [],
             'name': 'benchmark_score',
             'value': 0
         }
         subtests = [total_subtest]
         vals = []
 
         names = _subtests.keys()
@@ -360,19 +361,19 @@ class Output(object):
         data = test.measurements['unity-webgl']
         for page_cycle in data:
             data = json.loads(page_cycle[0])
             for item in data:
                 # for each pagecycle, build a list of subtests and append all related replicates
                 sub = item['benchmark']
                 if sub not in _subtests.keys():
                     # subtest not added yet, first pagecycle, so add new one
-                    _subtests[sub] = {'unit': test.unit,
+                    _subtests[sub] = {'unit': test.subtest_unit,
                                       'alertThreshold': float(test.alert_threshold),
-                                      'lowerIsBetter': test.lower_is_better,
+                                      'lowerIsBetter': test.subtest_lower_is_better,
                                       'name': sub,
                                       'replicates': []}
                 _subtests[sub]['replicates'].append(item['result'])
 
         vals = []
         subtests = []
         names = _subtests.keys()
         names.sort(reverse=True)
@@ -399,19 +400,19 @@ class Output(object):
 
         _subtests = {}
         data = test.measurements['assorted-dom']
         for pagecycle in data:
             for _sub, _value in pagecycle[0].iteritems():
                 # build a list of subtests and append all related replicates
                 if _sub not in _subtests.keys():
                     # subtest not added yet, first pagecycle, so add new one
-                    _subtests[_sub] = {'unit': test.unit,
+                    _subtests[_sub] = {'unit': test.subtest_unit,
                                        'alertThreshold': float(test.alert_threshold),
-                                       'lowerIsBetter': test.lower_is_better,
+                                       'lowerIsBetter': test.subtest_lower_is_better,
                                        'name': _sub,
                                        'replicates': []}
                 _subtests[_sub]['replicates'].extend([_value])
 
         vals = []
         subtests = []
         names = _subtests.keys()
         names.sort(reverse=True)
--- a/testing/raptor/raptor/tests/raptor-speedometer.ini
+++ b/testing/raptor/raptor/tests/raptor-speedometer.ini
@@ -4,18 +4,20 @@
 
 # speedometer benchmark for firefox and chrome
 
 [DEFAULT]
 type =  benchmark
 test_url = http://localhost:<port>/Speedometer/index.html?raptor
 page_cycles = 5
 page_timeout = 180000
-unit = score
-lower_is_better = false
+unit = score
+subtest_unit = ms
+lower_is_better = false
+subtest_lower_is_better = true
 alert_threshold = 2.0
 
 [raptor-speedometer-firefox]
 apps = firefox
 
 [raptor-speedometer-chrome]
 apps = chrome
 
--- a/testing/raptor/webext/raptor/runner.js
+++ b/testing/raptor/webext/raptor/runner.js
@@ -73,17 +73,19 @@ function getTestSettings() {
           // just replace the '<port>' keyword in the URL with actual benchmarkPort
           testURL = testURL.replace("<port>", benchmarkPort);
         }
 
         results.page = testURL;
         results.type = testType;
         results.name = testName;
         results.unit = settings.unit;
-        results.lower_is_better = settings.lower_is_better;
+        results.subtest_unit = settings.subtest_unit;
+        results.lower_is_better = settings.lower_is_better == "true";
+        results.subtest_lower_is_better = settings.subtest_lower_is_better == "true";
         results.alert_threshold = settings.alert_threshold;
 
         if (settings.page_timeout !== undefined) {
           pageTimeout = settings.page_timeout;
         }
         console.log("using page timeout (ms): " + pageTimeout);
 
         if (testType == "pageload") {
--- a/toolkit/mozapps/update/common/moz.build
+++ b/toolkit/mozapps/update/common/moz.build
@@ -31,24 +31,26 @@ USE_STATIC_LIBS = True
 DisableStlWrapping()
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'windows':
     SOURCES += [
         'pathhash.cpp',
         'uachelper.cpp',
         'updatehelper.cpp',
     ]
+    OS_LIBS += [
+        'rpcrt4',
+    ]
     if CONFIG['MOZ_MAINTENANCE_SERVICE']:
         SOURCES += [
             'certificatecheck.cpp',
             'registrycertificates.cpp',
         ]
         OS_LIBS += [
             'crypt32',
-            'rpcrt4',
             'wintrust',
         ]
 
 SOURCES += [
     'readstrings.cpp',
     'updatecommon.cpp',
 ]
 
--- a/toolkit/mozapps/update/common/updatecommon.cpp
+++ b/toolkit/mozapps/update/common/updatecommon.cpp
@@ -194,17 +194,17 @@ void UpdateLog::WarnPrintf(const char *f
  *         false if the check passes and the path can be used
  */
 bool
 PathContainsInvalidLinks(wchar_t * const fullPath)
 {
   wchar_t pathCopy[MAXPATHLEN + 1] = L"";
   wcsncpy(pathCopy, fullPath, MAXPATHLEN);
   wchar_t* remainingPath = nullptr;
-  wchar_t* nextToken = wcstok(pathCopy, L"\\", &remainingPath);
+  wchar_t* nextToken = wcstok_s(pathCopy, L"\\", &remainingPath);
   wchar_t* partialPath = nextToken;
 
   while (nextToken) {
     if ((GetFileAttributesW(partialPath) & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
       nsAutoHandle h(CreateFileW(partialPath, 0,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                                  nullptr, OPEN_EXISTING,
                                  FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
@@ -244,17 +244,17 @@ PathContainsInvalidLinks(wchar_t * const
           break;
       }
 
       if (wcsncmp(reparseTarget, L"\\??\\", ARRAYSIZE(L"\\??\\") - 1) != 0) {
         return true;
       }
     }
 
-    nextToken = wcstok(nullptr, L"\\", &remainingPath);
+    nextToken = wcstok_s(nullptr, L"\\", &remainingPath);
     PathAppendW(partialPath, nextToken);
   }
 
   return false;
 }
 #endif
 
 /**
--- a/widget/android/AndroidBridge.cpp
+++ b/widget/android/AndroidBridge.cpp
@@ -25,17 +25,16 @@
 #include "nsIThreadManager.h"
 #include "gfxPlatform.h"
 #include "gfxContext.h"
 #include "mozilla/gfx/2D.h"
 #include "gfxUtils.h"
 #include "nsPresContext.h"
 #include "nsIDocShell.h"
 #include "nsPIDOMWindow.h"
-#include "mozilla/dom/ScreenOrientation.h"
 #include "nsIDOMWindowUtils.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "nsPrintfCString.h"
 #include "nsContentUtils.h"
 #include "nsIScriptError.h"
 #include "nsIHttpChannel.h"
 
 #include "EventDispatcher.h"
@@ -729,19 +728,19 @@ nsAndroidBridge::RemoveObservers()
 uint32_t
 AndroidBridge::GetScreenOrientation()
 {
     ALOG_BRIDGE("AndroidBridge::GetScreenOrientation");
 
     int16_t orientation = GeckoAppShell::GetScreenOrientation();
 
     if (!orientation)
-        return dom::eScreenOrientation_None;
+        return hal::eScreenOrientation_None;
 
-    return static_cast<dom::ScreenOrientationInternal>(orientation);
+    return static_cast<hal::ScreenOrientation>(orientation);
 }
 
 uint16_t
 AndroidBridge::GetScreenAngle()
 {
     return GeckoAppShell::GetScreenAngle();
 }
 
--- a/widget/android/GeckoScreenOrientation.h
+++ b/widget/android/GeckoScreenOrientation.h
@@ -7,17 +7,16 @@
 #define GeckoScreenOrientation_h
 
 #include "GeneratedJNINatives.h"
 #include "nsAppShell.h"
 #include "nsCOMPtr.h"
 #include "nsIScreenManager.h"
 
 #include "mozilla/Hal.h"
-#include "mozilla/dom/ScreenOrientation.h"
 
 namespace mozilla {
 
 class GeckoScreenOrientation final
     : public java::GeckoScreenOrientation::Natives<GeckoScreenOrientation>
 {
     GeckoScreenOrientation() = delete;
 
@@ -40,16 +39,16 @@ public:
         if (NS_FAILED(screen->GetRect(&rect.x, &rect.y,
                                       &rect.width, &rect.height)) ||
                 NS_FAILED(screen->GetColorDepth(&colorDepth)) ||
                 NS_FAILED(screen->GetPixelDepth(&pixelDepth))) {
             return;
         }
 
         hal::NotifyScreenConfigurationChange(hal::ScreenConfiguration(
-                rect, static_cast<dom::ScreenOrientationInternal>(aOrientation),
+                rect, static_cast<hal::ScreenOrientation>(aOrientation),
                 aAngle, colorDepth, pixelDepth));
     }
 };
 
 } // namespace mozilla
 
 #endif // GeckoScreenOrientation_h