merge mozilla-central to mozilla-inbound. r=merge a=merge
authorSebastian Hengst <archaeopteryx@coole-files.de>
Sat, 09 Sep 2017 13:02:45 +0200
changeset 429410 0298cb04eb7a794501556f2dd8b64f27736d300a
parent 429409 296f26c8422126c7e80812173ebc38e548566234 (current diff)
parent 429385 2a9cffb19ab58a7875aee5492c565c549c037511 (diff)
child 429411 6e7763254023277b9b5526166e7f34c6b1f1802c
push id7761
push userjlund@mozilla.com
push dateFri, 15 Sep 2017 00:19:52 +0000
treeherdermozilla-beta@c38455951db4 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge, merge
milestone57.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 mozilla-central to mozilla-inbound. r=merge a=merge
browser/components/sessionstore/test/browser_restore_reversed_z_order.js
--- a/browser/components/extensions/test/browser/browser_ext_tabs_lazy.js
+++ b/browser/components/extensions/test/browser/browser_ext_tabs_lazy.js
@@ -6,17 +6,16 @@ const SESSION = {
       {entries: [{url: "about:blank"}]},
       {entries: [{url: "https://example.com/"}]},
     ],
   }],
 };
 
 add_task(async function() {
   SessionStore.setBrowserState(JSON.stringify(SESSION));
-  await promiseWindowRestored(window);
   const tab = gBrowser.tabs[1];
 
   is(tab.getAttribute("pending"), "true", "The tab is pending restore");
   is(tab.linkedBrowser.isConnected, false, "The tab is lazy");
 
   async function background() {
     const [tab] = await browser.tabs.query({url: "https://example.com/"});
     browser.test.assertRejects(
--- a/browser/components/extensions/test/browser/head.js
+++ b/browser/components/extensions/test/browser/head.js
@@ -15,17 +15,16 @@
  *          openTabContextMenu closeTabContextMenu
  *          openToolsMenu closeToolsMenu
  *          imageBuffer imageBufferFromDataURI
  *          getListStyleImage getPanelForNode
  *          awaitExtensionPanel awaitPopupResize
  *          promiseContentDimensions alterContent
  *          promisePrefChangeObserved openContextMenuInFrame
  *          promiseAnimationFrame getCustomizableUIPanelID
- *          promiseWindowRestored
  */
 
 // There are shutdown issues for which multiple rejections are left uncaught.
 // This bug should be fixed, but for the moment this directory is whitelisted.
 //
 // NOTE: Entire directory whitelisting should be kept to a minimum. Normally you
 //       should use "expectUncaughtRejection" to flag individual failures.
 const {PromiseTestUtils} = Cu.import("resource://testing-common/PromiseTestUtils.jsm", {});
@@ -444,12 +443,8 @@ function closePageAction(extension, win 
 
 function promisePrefChangeObserved(pref) {
   return new Promise((resolve, reject) =>
     Preferences.observe(pref, function prefObserver() {
       Preferences.ignore(pref, prefObserver);
       resolve();
     }));
 }
-
-function promiseWindowRestored(window) {
-  return new Promise(resolve => window.addEventListener("SSWindowRestored", resolve, {once: true}));
-}
--- a/browser/components/sessionstore/SessionStore.jsm
+++ b/browser/components/sessionstore/SessionStore.jsm
@@ -203,25 +203,16 @@ function debug(aMsg) {
 /**
  * A global value to tell that fingerprinting resistance is enabled or not.
  * If it's enabled, the session restore won't restore the window's size and
  * size mode.
  * This value is controlled by preference privacy.resistFingerprinting.
  */
 var gResistFingerprintingEnabled = false;
 
-/**
- * Return a promise that will be resolved once it receives event
- * |SSBrowserWindowShowing| which is dispatched in onBrowserWindowShown.
- */
-function promiseWindowShowing(window) {
-  return new Promise(resolve => window.addEventListener("SSBrowserWindowShowing",
-    () => resolve(window), {once: true}));
-}
-
 this.SessionStore = {
   get promiseInitialized() {
     return SessionStoreInternal.promiseInitialized;
   },
 
   get promiseAllWindowsRestored() {
     return SessionStoreInternal.promiseAllWindowsRestored;
   },
@@ -696,19 +687,18 @@ var SessionStoreInternal = {
 
           // Update the session start time using the restored session state.
           this._updateSessionStartTime(state);
 
           // make sure that at least the first window doesn't have anything hidden
           delete state.windows[0].hidden;
           // Since nothing is hidden in the first window, it cannot be a popup
           delete state.windows[0].isPopup;
-          // We don't want to minimize and then open a window at startup. However,
-          // when we're restoring, we should preserve previous windows sizemode.
-          if (state.windows[0].sizemode == "minimized" && !ss.doRestore())
+          // We don't want to minimize and then open a window at startup.
+          if (state.windows[0].sizemode == "minimized")
             state.windows[0].sizemode = "normal";
           // clear any lastSessionWindowID attributes since those don't matter
           // during normal restore
           state.windows.forEach(function(aWindow) {
             delete aWindow.__lastSessionWindowID;
           });
         }
       } catch (ex) { debug("The session file is invalid: " + ex); }
@@ -1184,21 +1174,19 @@ var SessionStoreInternal = {
       } else {
         // Nothing to restore, notify observers things are complete.
         Services.obs.notifyObservers(null, NOTIFY_WINDOWS_RESTORED);
         Services.obs.notifyObservers(null, "sessionstore-one-or-no-tab-restored");
         this._deferredAllWindowsRestored.resolve();
       }
     // this window was opened by _openWindowWithState
     } else if (!this._isWindowLoaded(aWindow)) {
-      // We used to restore window when it is opened. However, we
-      // want to restore windows after all windows are opened
-      // (bug 1034036). So the restoration process has been moved to
-      // function restoreWindowsFeaturesAndTabs.
-
+      let state = this._statesToRestore[aWindow.__SS_restoreID];
+      let options = {overwriteTabs: true, isFollowUp: state.windows.length == 1};
+      this.restoreWindow(aWindow, state.windows[0], options);
     // The user opened another, non-private window after starting up with
     // a single private one. Let's restore the session we actually wanted to
     // restore at startup.
     } else if (this._deferredInitialState && !isPrivateWindow &&
              aWindow.toolbar.visible) {
 
       // global data must be restored before restoreWindow is called so that
       // it happens before observers are notified
@@ -1280,20 +1268,16 @@ var SessionStoreInternal = {
    * Called right before a new browser window is shown.
    * @param aWindow
    *        Window reference
    */
   onBeforeBrowserWindowShown(aWindow) {
     // Register the window.
     this.onLoad(aWindow);
 
-    // Dispatch a custom event to tell that a new window is about to be shown.
-    let evt = new aWindow.CustomEvent("SSBrowserWindowShowing");
-    aWindow.dispatchEvent(evt);
-
     // Just call initializeWindow() directly if we're initialized already.
     if (this._sessionInitialized) {
       this.initializeWindow(aWindow);
       return;
     }
 
     // The very first window that is opened creates a promise that is then
     // re-used by all subsequent windows. The promise will be used to tell
@@ -1358,17 +1342,17 @@ var SessionStoreInternal = {
     let completionPromise = Promise.resolve();
     // this window was about to be restored - conserve its original data, if any
     let isFullyLoaded = this._isWindowLoaded(aWindow);
     if (!isFullyLoaded) {
       if (!aWindow.__SSi) {
         aWindow.__SSi = this._generateWindowID();
       }
 
-      this._windows[aWindow.__SSi] = this._statesToRestore[aWindow.__SS_restoreID].windows[0];
+      this._windows[aWindow.__SSi] = this._statesToRestore[aWindow.__SS_restoreID];
       delete this._statesToRestore[aWindow.__SS_restoreID];
       delete aWindow.__SS_restoreID;
     }
 
     // ignore windows not tracked by SessionStore
     if (!aWindow.__SSi || !this._windows[aWindow.__SSi]) {
       return completionPromise;
     }
@@ -2524,17 +2508,16 @@ var SessionStoreInternal = {
     }
 
     // reopen the window
     let state = { windows: this._removeClosedWindow(aIndex) };
     delete state.windows[0].closedAt; // Window is now open.
 
     let window = this._openWindowWithState(state);
     this.windowToFocus = window;
-    promiseWindowShowing(window).then(win => this.restoreWindows(win, state, {overwriteTabs: true}));
 
     // Notify of changes to closed objects.
     this._notifyOfClosedObjectsChange();
 
     return window;
   },
 
   forgetClosedWindow: function ssi_forgetClosedWindow(aIndex) {
@@ -2778,19 +2761,16 @@ var SessionStoreInternal = {
 
     // global data must be restored before restoreWindow is called so that
     // it happens before observers are notified
     this._globalState.setFromState(lastSessionState);
 
     // Restore session cookies.
     SessionCookies.restore(lastSessionState.cookies || []);
 
-    let openedWindows = [];
-    let remainingWindows = [];
-
     // Restore into windows or open new ones as needed.
     for (let i = 0; i < lastSessionState.windows.length; i++) {
       let winState = lastSessionState.windows[i];
       let lastSessionWindowID = winState.__lastSessionWindowID;
       // delete lastSessionWindowID so we don't add that to the window again
       delete winState.__lastSessionWindowID;
 
       // See if we can use an open window. First try one that is associated with
@@ -2809,38 +2789,27 @@ var SessionStoreInternal = {
         // Since we're not overwriting existing tabs, we want to merge _closedTabs,
         // putting existing ones first. Then make sure we're respecting the max pref.
         if (winState._closedTabs && winState._closedTabs.length) {
           let curWinState = this._windows[windowToUse.__SSi];
           curWinState._closedTabs = curWinState._closedTabs.concat(winState._closedTabs);
           curWinState._closedTabs.splice(this._max_tabs_undo, curWinState._closedTabs.length);
         }
 
+        // Restore into that window - pretend it's a followup since we'll already
+        // have a focused window.
         // XXXzpao This is going to merge extData together (taking what was in
         //        winState over what is in the window already.
-        // We don't restore window right away, just store its data.
-        // Later, these windows will be restored with newly opened windows.
-        if ("zIndex" in winState) {
-          windowToUse.__SS_zIndex = winState.zIndex;
-        }
-
-        this._updateWindowRestoreState(windowToUse, {windows: [winState]});
-        windowToUse.__SS_restoreOptions = {overwriteTabs: canOverwriteTabs};
-        openedWindows.push(windowToUse);
+        let options = {overwriteTabs: canOverwriteTabs, isFollowUp: true};
+        this.restoreWindow(windowToUse, winState, options);
       } else {
-        remainingWindows.push(winState);
+        this._openWindowWithState({ windows: [winState] });
       }
     }
 
-    // Actually restore windows in reversed z-order.
-    this.openWindows({windows: remainingWindows}).then(wins => {
-      wins = openedWindows.concat(wins);
-      this.restoreWindowsInReversedZOrder(wins, this._statesToRestore, false);
-    });
-
     // Merge closed windows from this session with ones from last session
     if (lastSessionState._closedWindows) {
       this._closedWindows = this._closedWindows.concat(lastSessionState._closedWindows);
       this._capClosedWindows();
       this._closedObjectsChanged = true;
     }
 
     DevToolsShim.restoreDevToolsSession(lastSessionState);
@@ -3082,49 +3051,27 @@ var SessionStoreInternal = {
     }
 
     return [true, canOverwriteTabs];
   },
 
   /* ........ Saving Functionality .............. */
 
   /**
-   * Return z-index of a window.
-   * If a window is minimized, its z-index is -1.
-   *
-   * @param aWindow
-   *        Window reference
-   * @return z-index of that window
-   */
-  _getZIndex(window) {
-    let isMinimized = this._getWindowDimension(window, "sizemode") == "minimized";
-    return isMinimized ? -1 : window.__SS_zIndex;
-  },
-
-  /**
    * Store window dimensions, visibility, sidebar
    * @param aWindow
    *        Window reference
    */
   _updateWindowFeatures: function ssi_updateWindowFeatures(aWindow) {
     var winData = this._windows[aWindow.__SSi];
 
     WINDOW_ATTRIBUTES.forEach(function(aAttr) {
       winData[aAttr] = this._getWindowDimension(aWindow, aAttr);
     }, this);
 
-    // We only update zIndex when a valid zIndex is found in a window.
-    // There will be a case (flushAllWindowsAsync) where this function
-    // is called outside |forEachBrowserWindow|, therefore, no zIndex
-    // is found.
-    let zIndex = this._getZIndex(aWindow);
-    if (zIndex) {
-      winData.zIndex = this._getZIndex(aWindow);
-    }
-
     var hidden = WINDOW_HIDEABLE_FEATURES.filter(function(aItem) {
       return aWindow[aItem] && !aWindow[aItem].visible;
     });
     if (hidden.length != 0)
       winData.hidden = hidden.join(",");
     else if (winData.hidden)
       delete winData.hidden;
 
@@ -3309,49 +3256,37 @@ var SessionStoreInternal = {
 
     DirtyWindows.remove(aWindow);
     return tabMap;
   },
 
   /* ........ Restoring Functionality .............. */
 
   /**
-   * Open windows with data
-   *
-   * @param root
-   *        Windows data
-   * @returns a promise resolved when all windows have been opened
-   */
-  openWindows(root) {
-    let openedWindowPromises = [];
-    for (let winData of root.windows) {
-      if (winData && winData.tabs && winData.tabs[0]) {
-        let window = this._openWindowWithState({ windows: [winData] });
-        openedWindowPromises.push(promiseWindowShowing(window));
-      }
-    }
-    return Promise.all(openedWindowPromises);
-  },
-
-  /**
    * restore features to a single window
    * @param aWindow
    *        Window reference to the window to use for restoration
    * @param winData
    *        JS object
    * @param aOptions
    *        {overwriteTabs: true} to overwrite existing tabs w/ new ones
+   *        {isFollowUp: true} if this is not the restoration of the 1st window
    *        {firstWindow: true} if this is the first non-private window we're
    *                            restoring in this session, that might open an
    *                            external link as well
    */
   restoreWindow: function ssi_restoreWindow(aWindow, winData, aOptions = {}) {
     let overwriteTabs = aOptions && aOptions.overwriteTabs;
+    let isFollowUp = aOptions && aOptions.isFollowUp;
     let firstWindow = aOptions && aOptions.firstWindow;
 
+    if (isFollowUp) {
+      this.windowToFocus = aWindow;
+    }
+
     // initialize window if necessary
     if (aWindow && (!aWindow.__SSi || !this._windows[aWindow.__SSi]))
       this.onLoad(aWindow);
 
     TelemetryStopwatch.start("FX_SESSION_RESTORE_RESTORE_WINDOW_MS");
 
     // We're not returning from this before we end up calling restoreTabs
     // for this window, so make sure we send the SSWindowStateBusy event.
@@ -3478,16 +3413,17 @@ var SessionStoreInternal = {
     // We want to correlate the window with data from the last session, so
     // assign another id if we have one. Otherwise clear so we don't do
     // anything with it.
     delete aWindow.__SS_lastSessionWindowID;
     if (winData.__lastSessionWindowID)
       aWindow.__SS_lastSessionWindowID = winData.__lastSessionWindowID;
 
     if (overwriteTabs) {
+      this.restoreWindowFeatures(aWindow, winData);
       delete this._windows[aWindow.__SSi].extData;
     }
 
     // Restore cookies from legacy sessions, i.e. before bug 912717.
     SessionCookies.restore(winData.cookies || []);
 
     if (winData.extData) {
       if (!this._windows[aWindow.__SSi].extData) {
@@ -3576,78 +3512,36 @@ var SessionStoreInternal = {
       }
       // A flag indicate that we've prepared a connection for this tab and
       // if is called again, we shouldn't prepare another connection.
       tab.__SS_connectionPrepared = true;
     }
   },
 
   /**
-   * This function will restore window features and then retore window data.
-   *
-   * @param windows
-   *        array of windows to be restored into
-   * @param statesToRestore
-   *        states of windows to be restored
-   */
-  restoreWindowsFeaturesAndTabs(windows, statesToRestore) {
-    // First, we restore window features, so that when users
-    // interacting with a window, we don't steal the window focus.
-    windows.forEach((window) => {
-      let state = statesToRestore[window.__SS_restoreID];
-      this.restoreWindowFeatures(window, state.windows[0]);
-    });
-
-    // Then we restore data into windows.
-    for (let i = 0; i < windows.length; ++i) {
-      let state = statesToRestore[windows[i].__SS_restoreID];
-      let option = windows[i].__SS_restoreOptions || {overwriteTabs: true};
-      this.restoreWindow(windows[i], state.windows[0], option);
-      delete windows[i].__SS_restoreOptions;
-      delete windows[i].__SS_zIndex;
-    }
-  },
-
-  /**
-   * This function will restore window in reversed z-index, so that users
-   * will be presented with most recently used window first.
-   *
-   * @param windows
-   *        array of windows to be restored into
-   * @param statesToRestore
-   *        states of windows to be restored
-   * @param areFollowUps
-   *        a flag indicate these windows are follow-up windows
-   */
-  restoreWindowsInReversedZOrder(windows, statesToRestore, areFollowUps) {
-    if (windows.some(window => !!window.__SS_zIndex)) {
-      windows.sort((a, b) => b.__SS_zIndex - a.__SS_zIndex);
-    }
-
-    if (!areFollowUps) {
-      this.windowToFocus = windows[0];
-    }
-
-    this.restoreWindowsFeaturesAndTabs(windows, statesToRestore);
-  },
-
-  /**
    * Restore multiple windows using the provided state.
    * @param aWindow
    *        Window reference to the first window to use for restoration.
    *        Additionally required windows will be opened.
    * @param aState
    *        JS object or JSON string
    * @param aOptions
    *        {overwriteTabs: true} to overwrite existing tabs w/ new ones
+   *        {isFollowUp: true} if this is not the restoration of the 1st window
    *        {firstWindow: true} if this is the first non-private window we're
    *                            restoring in this session, that might open an
    *                            external link as well
    */
   restoreWindows: function ssi_restoreWindows(aWindow, aState, aOptions = {}) {
+    let isFollowUp = aOptions && aOptions.isFollowUp;
+
+    if (isFollowUp) {
+      this.windowToFocus = aWindow;
+    }
+
     // initialize window if necessary
     if (aWindow && (!aWindow.__SSi || !this._windows[aWindow.__SSi]))
       this.onLoad(aWindow);
 
     let root;
     try {
       root = (typeof aState == "string") ? JSON.parse(aState) : aState;
     } catch (ex) { // invalid state object - don't restore anything
@@ -3663,38 +3557,34 @@ var SessionStoreInternal = {
     }
 
     // We're done here if there are no windows.
     if (!root.windows || !root.windows.length) {
       this._sendRestoreCompletedNotifications();
       return;
     }
 
-    // Store z-index to current window so that it can be restored in reversed z-order.
-    let firstWindowData = root.windows.splice(0, 1);
-    if ("zIndex" in firstWindowData[0]) {
-      aWindow.__SS_zIndex = firstWindowData[0].zIndex;
-    }
-
-    // Store the restore state and restore option of the current window,
-    // so that the window can be restored in reversed z-order.
-    this._updateWindowRestoreState(aWindow, {windows: firstWindowData});
-    aWindow.__SS_restoreOptions = aOptions;
-
-    // Begin the restoration: First open all windows in creation order.
-    // After all windows are opened, we restore states to windows in
-    // reversed z-order.
-    this.openWindows(root).then(windows => {
-      // We want to add current window to opened window, so that this window will be
-      // restored in reversed z-order. (We add the window to first position, in case
-      // no z-indices are found, that window will be restored first.)
-      windows.unshift(aWindow);
-
-      this.restoreWindowsInReversedZOrder(windows, this._statesToRestore, false);
-    });
+    if (!root.selectedWindow || root.selectedWindow > root.windows.length) {
+      root.selectedWindow = 0;
+    }
+
+    // open new windows for all further window entries of a multi-window session
+    // (unless they don't contain any tab data)
+    let winData;
+    for (var w = 1; w < root.windows.length; w++) {
+      winData = root.windows[w];
+      if (winData && winData.tabs && winData.tabs[0]) {
+        var window = this._openWindowWithState({ windows: [winData] });
+        if (w == root.selectedWindow - 1) {
+          this.windowToFocus = window;
+        }
+      }
+    }
+
+    this.restoreWindow(aWindow, root.windows[0], aOptions);
 
     DevToolsShim.restoreDevToolsSession(aState);
   },
 
   /**
    * Manage history restoration for a window
    * @param aWindow
    *        Window to restore the tabs into
@@ -4272,52 +4162,28 @@ var SessionStoreInternal = {
   _updateSessionStartTime: function ssi_updateSessionStartTime(state) {
     // Attempt to load the session start time from the session state
     if (state.session && state.session.startTime) {
       this._sessionStartTime = state.session.startTime;
     }
   },
 
   /**
-   * A boolean flag indicates whether we can iterate over all windows
-   * in their z order.
-   */
-  get isWMZOrderBroken() {
-    let broken_wm_z_order = AppConstants.platform != "macosx" && AppConstants.platform != "win";
-    delete this.isWMZOrderBroken;
-    return this.isWMZOrderBroken = broken_wm_z_order;
-  },
-
-  /**
-   * Call a callback for all currently opened browser windows.
-   * This will iterate the windows in z-index from front to back,
-   * and assign z-index to the window.
+   * call a callback for all currently opened browser windows
    * (might miss the most recent one)
    * @param aFunc
    *        Callback each window is passed to
    */
   _forEachBrowserWindow: function ssi_forEachBrowserWindow(aFunc) {
-    let windowsEnum = this.isWMZOrderBroken ?
-                      Services.wm.getEnumerator("navigator:browser") :
-                      Services.wm.getZOrderDOMWindowEnumerator("navigator:browser", false);
-    let mostRecentWindow = this.isWMZOrderBroken ? this._getMostRecentBrowserWindow() : null;
-
-    // We want to start zIndex at 1, so that, in _updateWindowFeatures, if no z-index is found
-    // in a window, we can just check with a simple condition if: `if (zIndex)`.
-    let zIndex = 1;
+    var windowsEnum = Services.wm.getEnumerator("navigator:browser");
+
     while (windowsEnum.hasMoreElements()) {
-      let window = windowsEnum.getNext();
+      var window = windowsEnum.getNext();
       if (window.__SSi && !window.closed) {
-        if (this.isWMZOrderBroken) {
-          window.__SS_zIndex = mostRecentWindow.__SSi === window.__SSi ? 2 : 1;
-        } else {
-          window.__SS_zIndex = zIndex++;
-        }
         aFunc.call(this, window);
-        delete window.__SS_zIndex;
       }
     }
   },
 
   /**
    * Returns most recent window
    * @returns Window reference
    */
@@ -4339,33 +4205,16 @@ var SessionStoreInternal = {
       if (window.closed) {
         promises.push(this.onClose(window));
       }
     }
     return Promise.all(promises);
   },
 
   /**
-   * Store a restore state of a window to this._statesToRestore. The window
-   * will be given an id that can be used to get the restore state from
-   * this._statesToRestore.
-   *
-   * @param window
-   *        a reference to a window that has a state to restore
-   * @param state
-   *        an object containing session data
-   */
-  _updateWindowRestoreState(window, state) {
-    do {
-      var ID = "window" + Math.random();
-    } while (ID in this._statesToRestore);
-    this._statesToRestore[(window.__SS_restoreID = ID)] = state;
-  },
-
-  /**
    * open a new browser window for a given session state
    * called when restoring a multi-window session
    * @param aState
    *        Object containing session data
    */
   _openWindowWithState: function ssi_openWindowWithState(aState) {
     var argString = Cc["@mozilla.org/supports-string;1"].
                     createInstance(Ci.nsISupportsString);
@@ -4383,22 +4232,20 @@ var SessionStoreInternal = {
     if (winState.isPrivate) {
       features += ",private";
     }
 
     var window =
       Services.ww.openWindow(null, this._prefBranch.getCharPref("chromeURL"),
                              "_blank", features, argString);
 
-    // Store z-index, so that windows can be restored in reversed z-order.
-    if ("zIndex" in aState.windows[0]) {
-      window.__SS_zIndex = aState.windows[0].zIndex;
-    }
-
-    this._updateWindowRestoreState(window, aState);
+    do {
+      var ID = "window" + Math.random();
+    } while (ID in this._statesToRestore);
+    this._statesToRestore[(window.__SS_restoreID = ID)] = aState;
 
     return window;
   },
 
   /**
    * Whether or not to resume session, if not recovering from a crash.
    * @returns bool
    */
--- a/browser/components/sessionstore/test/browser.ini
+++ b/browser/components/sessionstore/test/browser.ini
@@ -260,9 +260,9 @@ skip-if = !e10s # GroupedSHistory is e10
 [browser_duplicate_history.js]
 [browser_tabicon_after_bg_tab_crash.js]
 skip-if = !crashreporter || !e10s # Tabs can't crash without e10s
 
 [browser_cookies.js]
 [browser_cookies_legacy.js]
 [browser_cookies_privacy.js]
 [browser_speculative_connect.js]
-[browser_restore_reversed_z_order.js]
+
--- a/browser/components/sessionstore/test/browser_423132.js
+++ b/browser/components/sessionstore/test/browser_423132.js
@@ -32,17 +32,16 @@ add_task(async function() {
   }
   Assert.equal(i, 1, "expected one cookie");
 
   // remove the cookie
   Services.cookies.removeAll();
 
   // restore the window state
   ss.setBrowserState(state);
-  await promiseWindowRestored(window);
 
   // at this point, the cookie should be restored...
   enumerator = Services.cookies.enumerator;
   let cookie2;
   while (enumerator.hasMoreElements()) {
     cookie2 = enumerator.getNext().QueryInterface(Ci.nsICookie);
     if (cookie.name == cookie2.name)
       break;
--- a/browser/components/sessionstore/test/browser_461634.js
+++ b/browser/components/sessionstore/test/browser_461634.js
@@ -33,54 +33,52 @@ function test() {
 
   // Open a window and add the above closed tab list.
   let newWin = openDialog(location, "", "chrome,all,dialog=no");
   promiseWindowLoaded(newWin).then(() => {
     gPrefService.setIntPref("browser.sessionstore.max_tabs_undo",
                             test_state.windows[0]._closedTabs.length);
     ss.setWindowState(newWin, JSON.stringify(test_state), true);
 
-    promiseWindowRestored(newWin).then(() => {
-      let closedTabs = SessionStore.getClosedTabData(newWin, false);
+    let closedTabs = SessionStore.getClosedTabData(newWin, false);
 
-      // Verify that non JSON serialized data is the same as JSON serialized data.
-      is(JSON.stringify(closedTabs), SessionStore.getClosedTabData(newWin),
-        "Non-serialized data is the same as serialized data")
+    // Verify that non JSON serialized data is the same as JSON serialized data.
+    is(JSON.stringify(closedTabs), SessionStore.getClosedTabData(newWin),
+       "Non-serialized data is the same as serialized data")
 
-      is(closedTabs.length, test_state.windows[0]._closedTabs.length,
-        "Closed tab list has the expected length");
-      is(countByTitle(closedTabs, FORGET),
-        test_state.windows[0]._closedTabs.length - remember_count,
-        "The correct amout of tabs are to be forgotten");
-      is(countByTitle(closedTabs, REMEMBER), remember_count,
-        "Everything is set up");
+    is(closedTabs.length, test_state.windows[0]._closedTabs.length,
+       "Closed tab list has the expected length");
+    is(countByTitle(closedTabs, FORGET),
+       test_state.windows[0]._closedTabs.length - remember_count,
+       "The correct amout of tabs are to be forgotten");
+    is(countByTitle(closedTabs, REMEMBER), remember_count,
+       "Everything is set up");
 
-      // All of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE.
-      ok(testForError(() => ss.forgetClosedTab({}, 0)),
-        "Invalid window for forgetClosedTab throws");
-      ok(testForError(() => ss.forgetClosedTab(newWin, -1)),
-        "Invalid tab for forgetClosedTab throws");
-      ok(testForError(() => ss.forgetClosedTab(newWin, test_state.windows[0]._closedTabs.length + 1)),
-        "Invalid tab for forgetClosedTab throws");
+    // All of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE.
+    ok(testForError(() => ss.forgetClosedTab({}, 0)),
+       "Invalid window for forgetClosedTab throws");
+    ok(testForError(() => ss.forgetClosedTab(newWin, -1)),
+       "Invalid tab for forgetClosedTab throws");
+    ok(testForError(() => ss.forgetClosedTab(newWin, test_state.windows[0]._closedTabs.length + 1)),
+       "Invalid tab for forgetClosedTab throws");
 
-      // Remove third tab, then first tab.
-      ss.forgetClosedTab(newWin, 2);
-      ss.forgetClosedTab(newWin, null);
+    // Remove third tab, then first tab.
+    ss.forgetClosedTab(newWin, 2);
+    ss.forgetClosedTab(newWin, null);
 
-      closedTabs = SessionStore.getClosedTabData(newWin, false);
+    closedTabs = SessionStore.getClosedTabData(newWin, false);
 
-      // Verify that non JSON serialized data is the same as JSON serialized data.
-      is(JSON.stringify(closedTabs), SessionStore.getClosedTabData(newWin),
-        "Non-serialized data is the same as serialized data")
+    // Verify that non JSON serialized data is the same as JSON serialized data.
+    is(JSON.stringify(closedTabs), SessionStore.getClosedTabData(newWin),
+       "Non-serialized data is the same as serialized data")
 
-      is(closedTabs.length, remember_count,
-        "The correct amout of tabs was removed");
-      is(countByTitle(closedTabs, FORGET), 0,
-        "All tabs specifically forgotten were indeed removed");
-      is(countByTitle(closedTabs, REMEMBER), remember_count,
-        "... and tabs not specifically forgetten weren't");
+    is(closedTabs.length, remember_count,
+       "The correct amout of tabs was removed");
+    is(countByTitle(closedTabs, FORGET), 0,
+       "All tabs specifically forgotten were indeed removed");
+    is(countByTitle(closedTabs, REMEMBER), remember_count,
+       "... and tabs not specifically forgetten weren't");
 
-      // Clean up.
-      gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo");
-      BrowserTestUtils.closeWindow(newWin).then(finish);
-    });
+    // Clean up.
+    gPrefService.clearUserPref("browser.sessionstore.max_tabs_undo");
+    BrowserTestUtils.closeWindow(newWin).then(finish);
   });
 }
--- a/browser/components/sessionstore/test/browser_464199.js
+++ b/browser/components/sessionstore/test/browser_464199.js
@@ -52,17 +52,16 @@ add_task(async function() {
   }
 
   // open a window and add the above closed tab list
   let newWin = openDialog(location, "", "chrome,all,dialog=no");
   await promiseWindowLoaded(newWin);
   gPrefService.setIntPref("browser.sessionstore.max_tabs_undo",
                           test_state.windows[0]._closedTabs.length);
   ss.setWindowState(newWin, JSON.stringify(test_state), true);
-  await promiseWindowRestored(newWin);
 
   let closedTabs = JSON.parse(ss.getClosedTabData(newWin));
   is(closedTabs.length, test_state.windows[0]._closedTabs.length,
      "Closed tab list has the expected length");
   is(countByTitle(closedTabs, FORGET),
      test_state.windows[0]._closedTabs.length - remember_count,
      "The correct amout of tabs are to be forgotten");
   is(countByTitle(closedTabs, REMEMBER), remember_count,
--- a/browser/components/sessionstore/test/browser_465223.js
+++ b/browser/components/sessionstore/test/browser_465223.js
@@ -17,35 +17,29 @@ function test() {
   let newWin = openDialog(location, "_blank", "chrome,all,dialog=no");
   promiseWindowLoaded(newWin).then(() => {
     ss.setWindowValue(newWin, uniqueKey1, uniqueValue1);
 
     let newState = { windows: [{ tabs: [{ entries: [] }], extData: {} }] };
     newState.windows[0].extData[uniqueKey2] = uniqueValue2;
     ss.setWindowState(newWin, JSON.stringify(newState), false);
 
-    promiseWindowRestored(newWin).then(() => {
-      is(newWin.gBrowser.tabs.length, 2,
-        "original tab wasn't overwritten");
-      is(ss.getWindowValue(newWin, uniqueKey1), uniqueValue1,
-        "window value wasn't overwritten when the tabs weren't");
-      is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue2,
-        "new window value was correctly added");
+    is(newWin.gBrowser.tabs.length, 2,
+       "original tab wasn't overwritten");
+    is(ss.getWindowValue(newWin, uniqueKey1), uniqueValue1,
+       "window value wasn't overwritten when the tabs weren't");
+    is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue2,
+       "new window value was correctly added");
 
-      newState.windows[0].extData[uniqueKey2] = uniqueValue1;
-      ss.setWindowState(newWin, JSON.stringify(newState), true);
+    newState.windows[0].extData[uniqueKey2] = uniqueValue1;
+    ss.setWindowState(newWin, JSON.stringify(newState), true);
 
-      promiseWindowRestored(newWin).then(() => {
-        is(newWin.gBrowser.tabs.length, 1,
-          "original tabs were overwritten");
-        is(ss.getWindowValue(newWin, uniqueKey1), "",
-          "window value was cleared");
-        is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue1,
-          "window value was correctly overwritten");
+    is(newWin.gBrowser.tabs.length, 1,
+       "original tabs were overwritten");
+    is(ss.getWindowValue(newWin, uniqueKey1), "",
+       "window value was cleared");
+    is(ss.getWindowValue(newWin, uniqueKey2), uniqueValue1,
+       "window value was correctly overwritten");
 
-        // clean up
-        BrowserTestUtils.closeWindow(newWin).then(finish);
-
-      });
-    });
+    // clean up
+    BrowserTestUtils.closeWindow(newWin).then(finish);
   });
 }
-
--- a/browser/components/sessionstore/test/browser_477657.js
+++ b/browser/components/sessionstore/test/browser_477657.js
@@ -20,48 +20,41 @@ function test() {
     let uniqueKey = "bug 477657";
     let uniqueValue = "unik" + Date.now();
 
     ss.setWindowValue(newWin, uniqueKey, uniqueValue);
     is(ss.getWindowValue(newWin, uniqueKey), uniqueValue,
        "window value was set before the window was overwritten");
     ss.setWindowState(newWin, JSON.stringify(newState), true);
 
-    promiseWindowRestored(newWin).then(() => {
-      // use newWin.setTimeout(..., 0) to mirror sss_restoreWindowFeatures
+    // use newWin.setTimeout(..., 0) to mirror sss_restoreWindowFeatures
+    newWin.setTimeout(function() {
+      is(ss.getWindowValue(newWin, uniqueKey), "",
+         "window value was implicitly cleared");
+
+      is(newWin.windowState, newWin.STATE_MAXIMIZED,
+         "the window was maximized");
+
+      is(JSON.parse(ss.getClosedTabData(newWin)).length, 1,
+         "the closed tab was added before the window was overwritten");
+      delete newState.windows[0]._closedTabs;
+      delete newState.windows[0].sizemode;
+      ss.setWindowState(newWin, JSON.stringify(newState), true);
+
       newWin.setTimeout(function() {
-        is(ss.getWindowValue(newWin, uniqueKey), "",
-          "window value was implicitly cleared");
+        is(JSON.parse(ss.getClosedTabData(newWin)).length, 0,
+           "closed tabs were implicitly cleared");
 
         is(newWin.windowState, newWin.STATE_MAXIMIZED,
-          "the window was maximized");
-
-        is(JSON.parse(ss.getClosedTabData(newWin)).length, 1,
-          "the closed tab was added before the window was overwritten");
-        delete newState.windows[0]._closedTabs;
-        delete newState.windows[0].sizemode;
+           "the window remains maximized");
+        newState.windows[0].sizemode = "normal";
         ss.setWindowState(newWin, JSON.stringify(newState), true);
 
-        promiseWindowRestored(newWin).then(() => {
-          newWin.setTimeout(function() {
-            is(JSON.parse(ss.getClosedTabData(newWin)).length, 0,
-              "closed tabs were implicitly cleared");
-
-            is(newWin.windowState, newWin.STATE_MAXIMIZED,
-              "the window remains maximized");
-            newState.windows[0].sizemode = "normal";
-            ss.setWindowState(newWin, JSON.stringify(newState), true);
+        newWin.setTimeout(function() {
+          isnot(newWin.windowState, newWin.STATE_MAXIMIZED,
+                "the window was explicitly unmaximized");
 
-            promiseWindowRestored(newWin).then(() => {
-              newWin.setTimeout(function() {
-                isnot(newWin.windowState, newWin.STATE_MAXIMIZED,
-                  "the window was explicitly unmaximized");
-
-                BrowserTestUtils.closeWindow(newWin).then(finish);
-              }, 0);
-            });
-          }, 0);
-        });
+          BrowserTestUtils.closeWindow(newWin).then(finish);
+        }, 0);
       }, 0);
-    });
+    }, 0);
   });
 }
-
--- a/browser/components/sessionstore/test/browser_490040.js
+++ b/browser/components/sessionstore/test/browser_490040.js
@@ -46,17 +46,16 @@ add_task(async function test_bug_490040(
     let startingClosedWindowCount = ss.getClosedWindowCount();
     await pushPrefs(["browser.sessionstore.max_windows_undo",
                      startingClosedWindowCount + 1]);
 
     let curClosedWindowCount = ss.getClosedWindowCount();
     let win = await BrowserTestUtils.openNewBrowserWindow();
 
     ss.setWindowState(win, JSON.stringify(state.windowState), true);
-    await promiseWindowRestored(win);
     if (state.windowState.windows[0].tabs.length) {
       await BrowserTestUtils.browserLoaded(win.gBrowser.selectedBrowser);
     }
 
     await BrowserTestUtils.closeWindow(win);
 
     is(ss.getClosedWindowCount(),
        curClosedWindowCount + (state.shouldBeAdded ? 1 : 0),
--- a/browser/components/sessionstore/test/browser_491577.js
+++ b/browser/components/sessionstore/test/browser_491577.js
@@ -80,43 +80,40 @@ function test() {
 
   // open a window and add the above closed window list
   let newWin = openDialog(location, "_blank", "chrome,all,dialog=no");
   promiseWindowLoaded(newWin).then(() => {
     gPrefService.setIntPref("browser.sessionstore.max_windows_undo",
                             test_state._closedWindows.length);
     ss.setWindowState(newWin, JSON.stringify(test_state), true);
 
-    promiseWindowRestored(newWin).then(() => {
-      let closedWindows = JSON.parse(ss.getClosedWindowData());
-      is(closedWindows.length, test_state._closedWindows.length,
-        "Closed window list has the expected length");
-      is(countByTitle(closedWindows, FORGET),
-        test_state._closedWindows.length - remember_count,
-        "The correct amount of windows are to be forgotten");
-      is(countByTitle(closedWindows, REMEMBER), remember_count,
-        "Everything is set up.");
+    let closedWindows = JSON.parse(ss.getClosedWindowData());
+    is(closedWindows.length, test_state._closedWindows.length,
+       "Closed window list has the expected length");
+    is(countByTitle(closedWindows, FORGET),
+       test_state._closedWindows.length - remember_count,
+       "The correct amount of windows are to be forgotten");
+    is(countByTitle(closedWindows, REMEMBER), remember_count,
+       "Everything is set up.");
 
-      // all of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE
-      ok(testForError(() => ss.forgetClosedWindow(-1)),
-        "Invalid window for forgetClosedWindow throws");
-      ok(testForError(() => ss.forgetClosedWindow(test_state._closedWindows.length + 1)),
-        "Invalid window for forgetClosedWindow throws");
+    // all of the following calls with illegal arguments should throw NS_ERROR_ILLEGAL_VALUE
+    ok(testForError(() => ss.forgetClosedWindow(-1)),
+       "Invalid window for forgetClosedWindow throws");
+    ok(testForError(() => ss.forgetClosedWindow(test_state._closedWindows.length + 1)),
+       "Invalid window for forgetClosedWindow throws");
 
-      // Remove third window, then first window
-      ss.forgetClosedWindow(2);
-      ss.forgetClosedWindow(null);
+    // Remove third window, then first window
+    ss.forgetClosedWindow(2);
+    ss.forgetClosedWindow(null);
 
-      closedWindows = JSON.parse(ss.getClosedWindowData());
-      is(closedWindows.length, remember_count,
-        "The correct amount of windows were removed");
-      is(countByTitle(closedWindows, FORGET), 0,
-        "All windows specifically forgotten were indeed removed");
-      is(countByTitle(closedWindows, REMEMBER), remember_count,
-        "... and windows not specifically forgetten weren't.");
+    closedWindows = JSON.parse(ss.getClosedWindowData());
+    is(closedWindows.length, remember_count,
+       "The correct amount of windows were removed");
+    is(countByTitle(closedWindows, FORGET), 0,
+       "All windows specifically forgotten were indeed removed");
+    is(countByTitle(closedWindows, REMEMBER), remember_count,
+       "... and windows not specifically forgetten weren't.");
 
-      // clean up
-      gPrefService.clearUserPref("browser.sessionstore.max_windows_undo");
-      BrowserTestUtils.closeWindow(newWin).then(finish);
-    });
+    // clean up
+    gPrefService.clearUserPref("browser.sessionstore.max_windows_undo");
+    BrowserTestUtils.closeWindow(newWin).then(finish);
   });
 }
-
--- a/browser/components/sessionstore/test/browser_495495.js
+++ b/browser/components/sessionstore/test/browser_495495.js
@@ -17,28 +17,26 @@ function test() {
       promiseWindowLoaded(newWin).then(() => {
         let state2 = ss.getWindowState(newWin);
 
         function testState(state, expected, callback) {
           let win = openDialog(location, "_blank", "chrome,all,dialog=no");
           promiseWindowLoaded(win).then(() => {
 
             is(win.gURLBar.readOnly, false,
-              "URL bar should not be read-only before setting the state");
+               "URL bar should not be read-only before setting the state");
             is(win.gURLBar.getAttribute("enablehistory"), "true",
-              "URL bar autocomplete should be enabled before setting the state");
+               "URL bar autocomplete should be enabled before setting the state");
             ss.setWindowState(win, state, true);
-            promiseWindowRestored(win).then(() => {
-              is(win.gURLBar.readOnly, expected.readOnly,
-                "URL bar read-only state should be restored correctly");
-              is(win.gURLBar.getAttribute("enablehistory"), expected.enablehistory,
-                "URL bar autocomplete state should be restored correctly");
+            is(win.gURLBar.readOnly, expected.readOnly,
+               "URL bar read-only state should be restored correctly");
+            is(win.gURLBar.getAttribute("enablehistory"), expected.enablehistory,
+               "URL bar autocomplete state should be restored correctly");
 
-              BrowserTestUtils.closeWindow(win).then(callback);
-            });
+            BrowserTestUtils.closeWindow(win).then(callback);
           });
         }
 
         BrowserTestUtils.closeWindow(newWin).then(() => {
           testState(state1, {readOnly: false, enablehistory: "true"}, function() {
             testState(state2, {readOnly: true, enablehistory: "false"}, finish);
           });
         });
--- a/browser/components/sessionstore/test/browser_514751.js
+++ b/browser/components/sessionstore/test/browser_514751.js
@@ -23,16 +23,14 @@ function test() {
     executeSoon(function() {
       var gotError = false;
       try {
         ss.setWindowState(theWin, JSON.stringify(state), true);
       } catch (e) {
         if (/NS_ERROR_MALFORMED_URI/.test(e))
           gotError = true;
       }
-      promiseWindowRestored(theWin).then(() => {
-        ok(!gotError, "Didn't get a malformed URI error.");
-        BrowserTestUtils.closeWindow(theWin).then(finish);
-      });
+      ok(!gotError, "Didn't get a malformed URI error.");
+      BrowserTestUtils.closeWindow(theWin).then(finish);
     });
   }, {once: true});
 }
 
--- a/browser/components/sessionstore/test/browser_607016.js
+++ b/browser/components/sessionstore/test/browser_607016.js
@@ -78,17 +78,16 @@ add_task(async function() {
 
     while (gBrowser.tabs.length > 1) {
       await promiseRemoveTab(gBrowser.tabs[1]);
     }
   }
 
   // Set the test state.
   ss.setBrowserState(JSON.stringify(state));
-  await promiseWindowRestored(window);
 
   // Wait until the selected tab is restored and all others are pending.
   await Promise.all(Array.map(gBrowser.tabs, tab => {
     return (tab == gBrowser.selectedTab) ?
       promiseTabRestored(tab) : promiseTabRestoring(tab)
   }));
 
   // Kick off the actual tests.
--- a/browser/components/sessionstore/test/browser_637020.js
+++ b/browser/components/sessionstore/test/browser_637020.js
@@ -37,17 +37,16 @@ add_task(async function test() {
     }, "domwindowopened");
   });
 
   // Set the new browser state that will
   // restore a window with two slowly loading tabs.
   let backupState = SessionStore.getBrowserState();
   SessionStore.setBrowserState(JSON.stringify(TEST_STATE));
   let win = await promiseWindow;
-  await promiseWindowRestored(win);
 
   // The window has now been opened. Check the state that is returned,
   // this should come from the cache while the window isn't restored, yet.
   info("the window has been opened");
   checkWindows();
 
   // The history has now been restored and the tabs are loading. The data must
   // now come from the window, if it's correctly been marked as dirty before.
--- a/browser/components/sessionstore/test/browser_687710.js
+++ b/browser/components/sessionstore/test/browser_687710.js
@@ -32,18 +32,17 @@ var state = {windows: [{tabs: [{entries:
         docIdentifier: 1,
         url: "http://example.com",
         triggeringPrincipal_base64,
       }
     ]
   }
 ]}]}]}
 
-add_task(async function test() {
+function test() {
   registerCleanupFunction(function() {
     ss.setBrowserState(stateBackup);
   });
 
   /* This test fails by hanging. */
   ss.setBrowserState(JSON.stringify(state));
-  await promiseWindowRestored(window);
   ok(true, "Didn't hang!");
-});
+}
--- a/browser/components/sessionstore/test/browser_694378.js
+++ b/browser/components/sessionstore/test/browser_694378.js
@@ -19,17 +19,14 @@ function test() {
   let gotError = false;
   try {
     ss.setWindowState(window, brokenStateString, true);
   } catch (ex) {
     gotError = true;
     info(ex);
   }
 
-  promiseWindowRestored(window).then(() => {
-    ok(!gotError, "ss.setWindowState did not throw an error");
+  ok(!gotError, "ss.setWindowState did not throw an error");
 
-    // Make sure that we reset the state. Use a full state just in case things get crazy.
-    let blankState = { windows: [{ tabs: [{ entries: [{ url: "about:blank", triggeringPrincipal_base64 }] }]}]};
-    waitForBrowserState(blankState, finish);
-  });
+  // Make sure that we reset the state. Use a full state just in case things get crazy.
+  let blankState = { windows: [{ tabs: [{ entries: [{ url: "about:blank", triggeringPrincipal_base64 }] }]}]};
+  waitForBrowserState(blankState, finish);
 }
-
--- a/browser/components/sessionstore/test/browser_frame_history.js
+++ b/browser/components/sessionstore/test/browser_frame_history.js
@@ -96,32 +96,29 @@ add_task(async function() {
        "frame " + i + " has the right url");
   }
   gBrowser.removeTab(newTab);
 });
 
 // Now, test that we don't record history if the iframe is added dynamically
 add_task(async function() {
   // Start with an empty history
-  let blankState = JSON.stringify({
-    windows: [{
-      tabs: [{ entries: [{ url: "about:blank", triggeringPrincipal_base64 }] }],
-      _closedTabs: []
-    }],
-    _closedWindows: []
-  });
-  ss.setBrowserState(blankState);
-  await promiseWindowRestored(window);
+    let blankState = JSON.stringify({
+      windows: [{
+        tabs: [{ entries: [{ url: "about:blank", triggeringPrincipal_base64 }] }],
+        _closedTabs: []
+      }],
+      _closedWindows: []
+    });
+    ss.setBrowserState(blankState);
 
   let testURL = getRootDirectory(gTestPath) + "browser_frame_history_index_blank.html";
   let tab = BrowserTestUtils.addTab(gBrowser, testURL);
   gBrowser.selectedTab = tab;
-  dump("Wait here\n");
   await waitForLoadsInBrowser(tab.linkedBrowser, 1);
-  dump("Finished Wait here\n");
 
   info("dynamic: Opening a page with an iframe containing three frames, 4 dynamic loads should take place");
   let doc = tab.linkedBrowser.contentDocument;
   let iframe = doc.createElement("iframe");
   iframe.id = "iframe";
   iframe.src = "browser_frame_history_index.html";
   doc.body.appendChild(iframe);
   await waitForLoadsInBrowser(tab.linkedBrowser, 4);
--- a/browser/components/sessionstore/test/browser_merge_closed_tabs.js
+++ b/browser/components/sessionstore/test/browser_merge_closed_tabs.js
@@ -32,23 +32,21 @@ add_task(async function() {
   }
 
   const maxTabsUndo = 4;
   gPrefService.setIntPref("browser.sessionstore.max_tabs_undo", maxTabsUndo);
 
   // Open a new window and restore it to an initial state.
   let win = await promiseNewWindowLoaded({private: false});
   SessionStore.setWindowState(win, JSON.stringify(initialState), true);
-  await promiseWindowRestored(win);
   is(SessionStore.getClosedTabCount(win), 2, "2 closed tabs after restoring initial state");
 
   // Restore the new state but do not overwrite existing tabs (this should
   // cause the closed tabs to be merged).
   SessionStore.setWindowState(win, JSON.stringify(restoreState), false);
-  await promiseWindowRestored(win);
 
   // Verify the windows closed tab data is correct.
   let iClosed = initialState.windows[0]._closedTabs;
   let rClosed = restoreState.windows[0]._closedTabs;
   let cData = JSON.parse(SessionStore.getClosedTabData(win));
 
   is(cData.length, Math.min(iClosed.length + rClosed.length, maxTabsUndo),
      "Number of closed tabs is correct");
--- a/browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js
+++ b/browser/components/sessionstore/test/browser_remoteness_flip_on_restore.js
@@ -130,17 +130,16 @@ async function runScenarios(scenarios) {
       await BrowserTestUtils.switchTab(tabbrowser, tabToSelect);
     }
 
     // Okay, time to test!
     let state = prepareState(scenario.stateToRestore,
                              scenario.selectedTab);
 
     SessionStore.setWindowState(win, state, true);
-    await promiseWindowRestored(win);
 
     for (let i = 0; i < scenario.expectedRemoteness.length; ++i) {
       let expectedRemoteness = scenario.expectedRemoteness[i];
       let tab = tabbrowser.tabs[i];
 
       Assert.equal(tab.linkedBrowser.isRemoteBrowser, expectedRemoteness,
                    "Should have gotten the expected remoteness " +
                    `for the tab at index ${i}`);
--- a/browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js
+++ b/browser/components/sessionstore/test/browser_restore_cookies_noOriginAttributes.js
@@ -130,17 +130,16 @@ add_task(async function run_test() {
   // Clear cookies.
   Services.cookies.removeAll();
 
   // Open a new window.
   let win = await promiseNewWindowLoaded();
 
   // Restore window with session cookies that have no originAttributes.
   ss.setWindowState(win, SESSION_DATA, true);
-  await promiseWindowRestored(win);
 
   let enumerator = Services.cookies.getCookiesFromHost(TEST_HOST, {});
   let cookie;
   let cookieCount = 0;
   while (enumerator.hasMoreElements()) {
     cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
     cookieCount++;
   }
@@ -151,17 +150,16 @@ add_task(async function run_test() {
   is(cookie.value, COOKIE.value, "cookie value successfully restored");
   is(cookie.path, COOKIE.path, "cookie path successfully restored");
 
   // Clear cookies.
   Services.cookies.removeAll();
 
   // Restore window with session cookies that have originAttributes within.
   ss.setWindowState(win, SESSION_DATA_OA, true);
-  await promiseWindowRestored(win);
 
   enumerator = Services.cookies.getCookiesFromHost(TEST_HOST, {});
   cookieCount = 0;
   while (enumerator.hasMoreElements()) {
     cookie = enumerator.getNext().QueryInterface(Ci.nsICookie);
     cookieCount++;
   }
 
deleted file mode 100644
--- a/browser/components/sessionstore/test/browser_restore_reversed_z_order.js
+++ /dev/null
@@ -1,155 +0,0 @@
-const TEST_URLS_MAP = {
-  "about:about": "About About",
-  "about:license": "Licenses",
-  "about:profiles": "About Profiles",
-  "about:mozilla": "The Book of Mozilla, 15:1"
-};
-const TEST_URLS = Object.keys(TEST_URLS_MAP);
-const TEST_LABELS = Object.values(TEST_URLS_MAP);
-
-const Paths = SessionFile.Paths;
-const BROKEN_WM_Z_ORDER = AppConstants.platform != "macosx" && AppConstants.platform != "win";
-
-let source;
-let state;
-
-function promiseProvideWindow(url, features) {
-  return new Promise(resolve => provideWindow(resolve, url, features));
-}
-
-add_task(async function init() {
-  // Make sure that we start with only primary window.
-  await promiseAllButPrimaryWindowClosed();
-
-  let promises = [];
-  for (let i = 0; i < 4; ++i) {
-    let url = Object.keys(TEST_URLS_MAP)[i];
-    let window = await promiseProvideWindow();
-    BrowserTestUtils.loadURI(window.gBrowser, url);
-    if (i == 2) {
-      window.minimize();
-    }
-    // We want to get the lastest state from each window.
-    await BrowserTestUtils.waitForLocationChange(window.gBrowser, url);
-    await BrowserTestUtils.browserStopped(window.gBrowser.selectedBrowser, url);
-    promises.push(TabStateFlusher.flushWindow(window));
-  }
-
-  // Wait until we get the lastest history from all windows.
-  await Promise.all(promises);
-
-  // Force save state and read the written state.
-  source = await promiseRecoveryFileContents();
-  state = JSON.parse(source);
-
-  // Close all windows as we don't need them.
-  await promiseAllButPrimaryWindowClosed();
-});
-
-add_task(async function test_z_indices_are_saved_correctly() {
-  is(state.windows.length, 4, "Correct number of windows saved");
-
-  // Check if we saved state in correct order of creation.
-  for (let i = 0; i < TEST_URLS.length; ++i) {
-    is(state.windows[i].tabs[0].entries[0].url, TEST_URLS[i],
-       `Window #${i} is stored in correct creation order`);
-  }
-
-  // Check if we saved a valid zIndex (no null, no undefined or no 0).
-  for (let win of state.windows) {
-    ok(win.zIndex, "A valid zIndex is stored");
-  }
-
-  if (BROKEN_WM_Z_ORDER) {
-    // Last window should have zIndex of 2.
-    is(state.windows[3].zIndex, 2, "Currently using window has correct z-index");
-
-    // Other windows should have zIndex of 1.
-    is(state.windows[0].zIndex, 1, "Window #1 has correct z-index");
-    is(state.windows[1].zIndex, 1, "Window #2 has correct z-index");
-
-    // Minimized window should have zIndex of -1.
-    is(state.windows[2].zIndex, -1, "Minimized window has correct z-index");
-  } else {
-    is(state.windows[2].zIndex, -1, "Minimzed window has correct z-index");
-    ok(state.windows[0].zIndex != -1, "Window #1 shouldn't has z-index -1");
-    ok(state.windows[1].zIndex > state.windows[0].zIndex, "Window #2 has correct z-index");
-    ok(state.windows[3].zIndex > state.windows[1].zIndex, "Currently using window has correct z-index");
-  }
-});
-
-add_task(async function test_windows_are_restored_in_reversed_z_index() {
-  let windowsOpened = 1;
-  let windows = [window];
-  let windowsRestored = 0;
-  let tabsRestoredLabels = [];
-
-  // A defer promise that will be resolved once
-  // we restored all tabs.
-  let defer = {};
-  defer.promise = new Promise((resolve, reject) => {
-    defer.resolve = resolve;
-    defer.reject = reject;
-  });
-
-  function allTabsRestored() {
-    is(tabsRestoredLabels[0], TEST_LABELS[3], "First restored tab should be previous used tab");
-    // We don't care about restoration order of windows in between the first and last window
-    // when the OS has broken vm z-order.
-    if (!BROKEN_WM_Z_ORDER) {
-      is(tabsRestoredLabels[1], TEST_LABELS[1], "Second restored tab is correct");
-      is(tabsRestoredLabels[2], TEST_LABELS[0], "Third restored tab is correct");
-    }
-    is(tabsRestoredLabels[3], TEST_LABELS[2], "Last restored tab should be in minimized window");
-
-    // Finish the test.
-    defer.resolve();
-  }
-
-  function onSSWindowRestored(aEvent) {
-    if (++windowsRestored == 4) {
-      // Remove the event listener from each window
-      windows.forEach(function(win) {
-        win.removeEventListener("SSWindowRestored", onSSWindowRestored, true);
-      });
-      executeSoon(allTabsRestored);
-    }
-    tabsRestoredLabels.push(aEvent.target.gBrowser.tabs[0].label);
-  }
-
-  // Used to add our listener to further windows so we can catch SSWindowRestored
-  // coming from them when creating a multi-window state.
-  function windowObserver(aSubject, aTopic, aData) {
-    if (aTopic == "domwindowopened") {
-      let newWindow = aSubject.QueryInterface(Ci.nsIDOMWindow);
-      newWindow.addEventListener("load", function() {
-        if (++windowsOpened == 3) {
-          Services.ww.unregisterNotification(windowObserver);
-        }
-
-        // Track this window so we can remove the progress listener later.
-        windows.push(newWindow);
-        // Add the progress listener.
-        newWindow.addEventListener("SSWindowRestored", onSSWindowRestored, true);
-      }, { once: true });
-    }
-  }
-
-  Services.ww.registerNotification(windowObserver);
-  registerCleanupFunction(function() {
-    windows.forEach(function(win) {
-      win.removeEventListener("SSWindowRestored", onSSWindowRestored, true);
-      if (win !== window) {
-        BrowserTestUtils.closeWindow(win);
-      }
-    });
-  });
-
-  window.addEventListener("SSWindowRestored", onSSWindowRestored, true);
-
-  // Restore states.
-  ss.setBrowserState(source);
-
-  await defer.promise;
-});
-
--- a/browser/components/sessionstore/test/browser_windowStateContainer.js
+++ b/browser/components/sessionstore/test/browser_windowStateContainer.js
@@ -37,17 +37,16 @@ add_task(async function() {
   // fewer tabs and with different order with win.
   for (let userContextId = 3; userContextId > 0; userContextId--) {
     let tab = win2.gBrowser.addTab("http://example.com/", {userContextId});
     await promiseBrowserLoaded(tab.linkedBrowser);
     await TabStateFlusher.flush(tab.linkedBrowser);
   }
 
   ss.setWindowState(win2, JSON.stringify(winState), true);
-  await promiseWindowRestored(win2);
 
   for (let i = 0; i < 4; i++) {
     let browser = win2.gBrowser.tabs[i].linkedBrowser;
     await ContentTask.spawn(browser, { expectedId: i + 1 }, async function(args) {
       Assert.equal(docShell.getOriginAttributes().userContextId,
                    args.expectedId,
                    "The docShell has the correct userContextId");
 
@@ -98,17 +97,16 @@ add_task(async function() {
   await TabStateFlusher.flush(tab2.linkedBrowser);
 
   // Move the first normal tab to end, so the first tab of win2 will be a
   // container tab.
   win2.gBrowser.moveTabTo(win2.gBrowser.tabs[0], win2.gBrowser.tabs.length - 1);
   await TabStateFlusher.flush(win2.gBrowser.tabs[0].linkedBrowser);
 
   ss.setWindowState(win2, JSON.stringify(winState), true);
-  await promiseWindowRestored(win2);
 
   for (let i = 0; i < 2; i++) {
     let browser = win2.gBrowser.tabs[i].linkedBrowser;
     await ContentTask.spawn(browser, { expectedId: i }, async function(args) {
       Assert.equal(docShell.getOriginAttributes().userContextId,
                    args.expectedId,
                    "The docShell has the correct userContextId");
 
--- a/browser/components/sessionstore/test/head.js
+++ b/browser/components/sessionstore/test/head.js
@@ -181,20 +181,16 @@ function promiseTabState(tab, state) {
     state = JSON.stringify(state);
   }
 
   let promise = promiseTabRestored(tab);
   ss.setTabState(tab, state);
   return promise;
 }
 
-function promiseWindowRestored(win) {
-  return new Promise(resolve => win.addEventListener("SSWindowRestored", resolve, {once: true}));
-}
-
 /**
  * Wait for a content -> chrome message.
  */
 function promiseContentMessage(browser, name) {
   let mm = browser.messageManager;
 
   return new Promise(resolve => {
     function removeListener() {