Merge mozilla-central into services-central
authorGregory Szorc <gps@mozilla.com>
Wed, 15 Aug 2012 16:24:21 -0700
changeset 111037 a8db42aa1b2820c73aade9acc4de9909562a2a03
parent 111036 4a0f07b83709a3dded10fe7e0eecc070551411e7 (current diff)
parent 104355 996a68d8420ee36b459933a3e27853d4810e6b39 (diff)
child 111038 4431277116bbe89f1a548d1d08688d4d8d520a76
push id93
push usernmatsakis@mozilla.com
push dateWed, 31 Oct 2012 21:26:57 +0000
milestone17.0a1
Merge mozilla-central into services-central
content/base/public/nsContentErrors.h
content/xslt/src/base/txError.h
dom/base/nsDOMError.h
dom/plugins/base/nsPluginError.h
image/public/ImageErrors.h
layout/base/nsImageLoader.cpp
layout/base/nsImageLoader.h
layout/base/nsLayoutErrors.h
netwerk/base/public/nsNetError.h
storage/public/mozStorage.h
toolkit/components/url-classifier/tests/unit/test_cleankeycache.js
--- a/accessible/src/base/a11yGeneric.h
+++ b/accessible/src/base/a11yGeneric.h
@@ -15,19 +15,16 @@
 // change it so that it works. Yuck.
 #define NS_INTERFACE_MAP_STATIC_AMBIGUOUS(_class)                              \
   if (aIID.Equals(NS_GET_IID(_class))) {                                       \
     NS_ADDREF(this);                                                           \
     *aInstancePtr = this;                                                      \
     return NS_OK;                                                              \
   } else
 
-#define NS_OK_DEFUNCT_OBJECT                                                   \
-  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x22)
-
 #define NS_ENSURE_A11Y_SUCCESS(res, ret)                                       \
   PR_BEGIN_MACRO                                                               \
     nsresult __rv = res; /* Don't evaluate |res| more than once */             \
     if (NS_FAILED(__rv)) {                                                     \
       NS_ENSURE_SUCCESS_BODY(res, ret)                                         \
       return ret;                                                              \
     }                                                                          \
     if (__rv == NS_OK_DEFUNCT_OBJECT)                                          \
--- a/accessible/src/base/nsAccessiblePivot.h
+++ b/accessible/src/base/nsAccessiblePivot.h
@@ -12,20 +12,16 @@
 #include "nsAutoPtr.h"
 #include "nsTObserverArray.h"
 #include "nsCycleCollectionParticipant.h"
 #include "mozilla/Attributes.h"
 
 class Accessible;
 class nsIAccessibleTraversalRule;
 
-// raised when current pivot's position is needed but it is not in the tree.
-#define NS_ERROR_NOT_IN_TREE \
-NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GENERAL, 0x26)
-
 /**
  * Class represents an accessible pivot.
  */
 class nsAccessiblePivot MOZ_FINAL : public nsIAccessiblePivot
 {
 public:
   nsAccessiblePivot(Accessible* aRoot);
 
--- a/accessible/src/base/nsTextEquivUtils.cpp
+++ b/accessible/src/base/nsTextEquivUtils.cpp
@@ -14,19 +14,16 @@
 #include "nsStyleStructInlines.h"
 
 #include "nsIDOMXULLabeledControlEl.h"
 
 #include "nsArrayUtils.h"
 
 using namespace mozilla::a11y;
 
-#define NS_OK_NO_NAME_CLAUSE_HANDLED \
-NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x24)
-
 ////////////////////////////////////////////////////////////////////////////////
 // nsTextEquivUtils. Public.
 
 nsresult
 nsTextEquivUtils::GetNameFromSubtree(Accessible* aAccessible,
                                      nsAString& aName)
 {
   aName.Truncate();
--- a/accessible/src/generic/Accessible.h
+++ b/accessible/src/generic/Accessible.h
@@ -73,28 +73,16 @@ struct nsRect;
 class nsIContent;
 class nsIFrame;
 class nsIAtom;
 class nsIView;
 
 typedef nsRefPtrHashtable<nsPtrHashKey<const void>, Accessible>
   AccessibleHashtable;
 
-// see Accessible::GetAttrValue
-#define NS_OK_NO_ARIA_VALUE \
-NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x21)
-
-// see Accessible::GetNameInternal
-#define NS_OK_EMPTY_NAME \
-NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x23)
-
-// see Accessible::GetNameInternal
-#define NS_OK_NAME_FROM_TOOLTIP \
-NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_GENERAL, 0x25)
-
 
 #define NS_ACCESSIBLE_IMPL_IID                          \
 {  /* 133c8bf4-4913-4355-bd50-426bd1d6e1ad */           \
   0x133c8bf4,                                           \
   0x4913,                                               \
   0x4355,                                               \
   { 0xbd, 0x50, 0x42, 0x6b, 0xd1, 0xd6, 0xe1, 0xad }    \
 }
--- a/accessible/src/html/HTMLTableAccessible.cpp
+++ b/accessible/src/html/HTMLTableAccessible.cpp
@@ -28,17 +28,17 @@
 #include "nsIDOMHTMLTableElement.h"
 #include "nsIDOMHTMLTableRowElement.h"
 #include "nsIDOMHTMLTableSectionElem.h"
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsITableLayout.h"
 #include "nsITableCellLayout.h"
 #include "nsFrameSelection.h"
-#include "nsLayoutErrors.h"
+#include "nsError.h"
 #include "nsArrayUtils.h"
 #include "nsComponentManagerUtils.h"
 
 using namespace mozilla;
 using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // HTMLTableCellAccessible
--- a/b2g/app/b2g.js
+++ b/b2g/app/b2g.js
@@ -137,16 +137,20 @@ pref("browser.search.suggest.enabled", t
 pref("browser.search.noCurrentEngine", true);
 
 // enable xul error pages
 pref("browser.xul.error_pages.enabled", true);
 
 // disable color management
 pref("gfx.color_management.mode", 0);
 
+//prefer Azure/Cairo canvas
+pref("gfx.canvas.azure.enabled", true);
+pref("gfx.canvas.azure.backends", "cairo");
+
 // don't allow JS to move and resize existing windows
 pref("dom.disable_window_move_resize", true);
 
 // prevent click image resizing for nsImageDocument
 pref("browser.enable_click_image_resizing", false);
 
 // controls which bits of private data to clear. by default we clear them all.
 pref("privacy.item.cache", true);
@@ -310,27 +314,27 @@ pref("browser.geolocation.warning.infoUR
 
 // Name of the about: page contributed by safebrowsing to handle display of error
 // pages on phishing/malware hits.  (bug 399233)
 pref("urlclassifier.alternate_error_page", "blocked");
 
 // The number of random entries to send with a gethash request.
 pref("urlclassifier.gethashnoise", 4);
 
+// Randomize all UrlClassifier data with a per-client key.
+pref("urlclassifier.randomizeclient", true);
+
 // The list of tables that use the gethash request to confirm partial results.
 pref("urlclassifier.gethashtables", "goog-phish-shavar,goog-malware-shavar");
 
 // If an urlclassifier table has not been updated in this number of seconds,
 // a gethash request will be forced to check that the result is still in
 // the database.
 pref("urlclassifier.confirm-age", 2700);
 
-// Maximum size of the sqlite3 cache during an update, in bytes
-pref("urlclassifier.updatecachemax", 4194304);
-
 // URL for checking the reason for a malware warning.
 pref("browser.safebrowsing.malware.reportURL", "http://safebrowsing.clients.google.com/safebrowsing/diagnostic?client=%NAME%&hl=%LOCALE%&site=");
 #endif
 
 // True if this is the first time we are showing about:firstrun
 pref("browser.firstrun.show.uidiscovery", true);
 pref("browser.firstrun.show.localepicker", true);
 
--- a/b2g/chrome/content/netError.xhtml
+++ b/b2g/chrome/content/netError.xhtml
@@ -71,22 +71,18 @@
         if (desc == -1)
           return "";
 
         return decodeURIComponent(url.slice(desc + 2));
       }
 
       function retryThis(buttonEl)
       {
-        // If this is the "Offline mode" page, go online!
-        if (getErrorCode() == "netOffline") {
-          window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
-                .getInterface(Components.interfaces.nsIDOMWindowUtils)
-                .goOnline();
-        }
+        // Note: The application may wish to handle switching off "offline mode"
+        // before this event handler runs, by using a capturing event handler.
 
         // Session history has the URL of the page that failed
         // to load, not the one of the error page. So, just call
         // reload(), which will also repost POST data correctly.
         try {
           location.reload();
         } catch (e) {
           // We probably tried to reload a URI that caused an exception to
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -1,9 +1,9 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+# -*- Mode: JavaScript; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 # 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/.
 
 // XXX Toolkit-specific preferences should be moved into toolkit.js
 
 #filter substitution
 
@@ -723,29 +723,26 @@ pref("browser.safebrowsing.malware.repor
 
 // Name of the about: page contributed by safebrowsing to handle display of error
 // pages on phishing/malware hits.  (bug 399233)
 pref("urlclassifier.alternate_error_page", "blocked");
 
 // The number of random entries to send with a gethash request.
 pref("urlclassifier.gethashnoise", 4);
 
+// Randomize all UrlClassifier data with a per-client key.
+pref("urlclassifier.randomizeclient", true);
+
 // The list of tables that use the gethash request to confirm partial results.
 pref("urlclassifier.gethashtables", "goog-phish-shavar,goog-malware-shavar");
 
 // If an urlclassifier table has not been updated in this number of seconds,
 // a gethash request will be forced to check that the result is still in
 // the database.
 pref("urlclassifier.confirm-age", 2700);
-
-// Maximum size of the sqlite3 cache during an update, in bytes
-pref("urlclassifier.updatecachemax", 41943040);
-
-// Maximum size of the sqlite3 cache for lookups, in bytes
-pref("urlclassifier.lookupcachemax", 1048576);
 #endif
 
 pref("browser.geolocation.warning.infoURL", "http://www.mozilla.com/%LOCALE%/firefox/geolocation/");
 
 pref("browser.EULA.version", 3);
 pref("browser.rights.version", 3);
 pref("browser.rights.3.shown", false);
 
@@ -1120,16 +1117,18 @@ pref("browser.menu.showCharacterEncoding
 
 // Allow using tab-modal prompts when possible.
 pref("prompts.tab_modal.enabled", true);
 // Whether the Panorama should animate going in/out of tabs
 pref("browser.panorama.animate_zoom", true);
 
 // Defines the url to be used for new tabs.
 pref("browser.newtab.url", "about:newtab");
+// Activates preloading of the new tab url.
+pref("browser.newtab.preload", false);
 
 // Toggles the content of 'about:newtab'. Shows the grid when enabled.
 pref("browser.newtabpage.enabled", true);
 
 // Enable the DOM fullscreen API.
 pref("full-screen-api.enabled", true);
 
 // True if the fullscreen API requires approval upon a domain entering fullscreen.
--- a/browser/base/content/aboutRobots.xhtml
+++ b/browser/base/content/aboutRobots.xhtml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="UTF-8"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE html [
   <!ENTITY % htmlDTD
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "DTD/xhtml1-strict.dtd">
   %htmlDTD;
   <!ENTITY % netErrorDTD
     SYSTEM "chrome://global/locale/netError.dtd">
--- a/browser/base/content/abouthome/aboutHome.xhtml
+++ b/browser/base/content/abouthome/aboutHome.xhtml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="UTF-8"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE html [
   <!ENTITY % htmlDTD
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "DTD/xhtml1-strict.dtd">
   %htmlDTD;
   <!ENTITY % globalDTD SYSTEM "chrome://global/locale/global.dtd">
   %globalDTD;
--- a/browser/base/content/browser-fullScreen.js
+++ b/browser/base/content/browser-fullScreen.js
@@ -592,20 +592,17 @@ var FullScreen = {
     if (fullscreenctls.parentNode == navbar && ctlsOnTabbar) {
       fullscreenctls.removeAttribute("flex");
       document.getElementById("TabsToolbar").appendChild(fullscreenctls);
     }
     else if (fullscreenctls.parentNode.id == "TabsToolbar" && !ctlsOnTabbar) {
       fullscreenctls.setAttribute("flex", "1");
       navbar.appendChild(fullscreenctls);
     }
-
-    var controls = document.getElementsByAttribute("fullscreencontrol", "true");
-    for (var i = 0; i < controls.length; ++i)
-      controls[i].hidden = aShow;
+    fullscreenctls.hidden = aShow;
   }
 };
 XPCOMUtils.defineLazyGetter(FullScreen, "useLionFullScreen", function() {
   // We'll only use OS X Lion full screen if we're
   // * on OS X
   // * on Lion or higher (Darwin 11+)
   // * have fullscreenbutton="true"
 #ifdef XP_MACOSX
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -454,28 +454,37 @@ window[chromehidden~="toolbar"] toolbar:
 .notification-anchor-icon {
   -moz-user-focus: normal;
 }
 
 .notification-anchor-icon:not([showing]) {
   display: none;
 }
 
+#notification-popup .text-link.custom-link {
+  -moz-binding: url("chrome://global/content/bindings/text.xml#text-label");
+  text-decoration: none;
+}
+
 #invalid-form-popup > description {
   max-width: 280px;
 }
 
 #geolocation-notification {
   -moz-binding: url("chrome://browser/content/urlbarBindings.xml#geolocation-notification");
 }
 
 #addon-progress-notification {
   -moz-binding: url("chrome://browser/content/urlbarBindings.xml#addon-progress-notification");
 }
 
+#identity-request-notification {
+  -moz-binding: url("chrome://browser/content/urlbarBindings.xml#identity-request-notification");
+}
+
 /* override hidden="true" for the status bar compatibility shim
    in case it was persisted for the real status bar */
 #status-bar {
   display: -moz-box;
 }
 
 /* Remove the resizer from the statusbar compatibility shim */
 #status-bar[hideresizer] > .statusbar-resizerpanel {
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -146,16 +146,22 @@ XPCOMUtils.defineLazyModuleGetter(this, 
 #ifdef MOZ_SAFE_BROWSING
 XPCOMUtils.defineLazyGetter(this, "SafeBrowsing", function() {
   let tmp = {};
   Cu.import("resource://gre/modules/SafeBrowsing.jsm", tmp);
   return tmp.SafeBrowsing;
 });
 #endif
 
+XPCOMUtils.defineLazyGetter(this, "gBrowserNewTabPreloader", function () {
+  let tmp = {};
+  Cu.import("resource://gre/modules/BrowserNewTabPreloader.jsm", tmp);
+  return new tmp.BrowserNewTabPreloader();
+});
+
 let gInitialPages = [
   "about:blank",
   "about:newtab",
   "about:home",
   "about:privatebrowsing",
   "about:sessionrestore"
 ];
 
@@ -209,17 +215,17 @@ XPCOMUtils.defineLazyGetter(this, "PageM
 });
 
 /**
 * We can avoid adding multiple load event listeners and save some time by adding
 * one listener that calls all real handlers.
 */
 function pageShowEventHandlers(event) {
   // Filter out events that are not about the document load we are interested in
-  if (event.originalTarget == content.document) {
+  if (event.target == content.document) {
     charsetLoadListener(event);
     XULBrowserWindow.asyncUpdateUI();
 
     // The PluginClickToPlay events are not fired when navigating using the
     // BF cache. |event.persisted| is true when the page is loaded from the
     // BF cache, so this code reshows the notification if necessary.
     if (event.persisted)
       gPluginHandler.reshowClickToPlayNotification();
@@ -1396,16 +1402,22 @@ var gBrowserInit = {
     if (document.mozFullScreen)
       onMozEnteredDomFullscreen();
 
 #ifdef MOZ_SERVICES_SYNC
     // initialize the sync UI
     gSyncUI.init();
 #endif
 
+    // Don't preload new tab pages when the toolbar is hidden
+    // (i.e. when the current window is a popup window).
+    if (window.toolbar.visible) {
+      gBrowserNewTabPreloader.init(window);
+    }
+
     gBrowserThumbnails.init();
     TabView.init();
 
     setUrlAndSearchBarWidthForConditionalForwardButton();
     window.addEventListener("resize", function resizeHandler(event) {
       if (event.target == window)
         setUrlAndSearchBarWidthForConditionalForwardButton();
     });
@@ -1552,16 +1564,20 @@ var gBrowserInit = {
     CombinedStopReload.uninit();
 
     gGestureSupport.init(false);
 
     FullScreen.cleanup();
 
     Services.obs.removeObserver(gPluginHandler.pluginCrashed, "plugin-crashed");
 
+    if (!__lookupGetter__("gBrowserNewTabPreloader")) {
+      gBrowserNewTabPreloader.uninit();
+    }
+
     try {
       gBrowser.removeProgressListener(window.XULBrowserWindow);
       gBrowser.removeTabsProgressListener(window.TabsProgressListener);
     } catch (ex) {
     }
 
     PlacesStarButton.uninit();
 
@@ -2510,16 +2526,19 @@ let BrowserOnClick = {
     // If the event came from an ssl error page, it is probably either the "Add
     // Exception…" or "Get me out of here!" button
     if (/^about:certerror/.test(ownerDoc.documentURI)) {
       this.onAboutCertError(originalTarget, ownerDoc);
     }
     else if (/^about:blocked/.test(ownerDoc.documentURI)) {
       this.onAboutBlocked(originalTarget, ownerDoc);
     }
+    else if (/^about:neterror/.test(ownerDoc.documentURI)) {
+      this.onAboutNetError(originalTarget, ownerDoc);
+    }
     else if (/^about:home$/i.test(ownerDoc.documentURI)) {
       this.onAboutHome(originalTarget, ownerDoc);
     }
   },
 
   onAboutCertError: function BrowserOnClick_onAboutCertError(aTargetElm, aOwnerDoc) {
     let elmId = aTargetElm.getAttribute("id");
     let secHistogram = Cc["@mozilla.org/base/telemetry;1"].
@@ -2676,16 +2695,23 @@ let BrowserOnClick = {
       notificationBox.PRIORITY_CRITICAL_HIGH,
       buttons
     );
     // Persist the notification until the user removes so it
     // doesn't get removed on redirects.
     notification.persistence = -1;
   },
 
+  onAboutNetError: function BrowserOnClick_onAboutNetError(aTargetElm, aOwnerDoc) {
+    let elmId = aTargetElm.getAttribute("id");
+    if (elmId != "errorTryAgain" || !/e=netOffline/.test(aOwnerDoc.documentURI))
+      return;
+    Services.io.offline = false;
+  },
+
   onAboutHome: function BrowserOnClick_onAboutHome(aTargetElm, aOwnerDoc) {
     let elmId = aTargetElm.getAttribute("id");
 
     switch (elmId) {
       case "restorePreviousSession":
         let ss = Cc["@mozilla.org/browser/sessionstore;1"].
                  getService(Ci.nsISessionStore);
         if (ss.canRestoreLastSession) {
@@ -4471,21 +4497,21 @@ var TabsProgressListener = {
     // require error page UI to do privileged things, without letting error
     // pages have any privilege themselves.
     // We can't look for this during onLocationChange since at that point the
     // document URI is not yet the about:-uri of the error page.
 
     if (aStateFlags & Ci.nsIWebProgressListener.STATE_STOP &&
         Components.isSuccessCode(aStatus) &&
         /^about:/.test(aWebProgress.DOMWindow.document.documentURI)) {
-      aBrowser.addEventListener("click", BrowserOnClick, false);
+      aBrowser.addEventListener("click", BrowserOnClick, true);
       aBrowser.addEventListener("pagehide", function onPageHide(event) {
         if (event.target.defaultView.frameElement)
           return;
-        aBrowser.removeEventListener("click", BrowserOnClick, false);
+        aBrowser.removeEventListener("click", BrowserOnClick, true);
         aBrowser.removeEventListener("pagehide", onPageHide, true);
       }, true);
 
       // We also want to make changes to page UI for unprivileged about pages.
       BrowserOnAboutPageLoad(aWebProgress.DOMWindow.document);
     }
   },
 
--- a/browser/base/content/browser.xul
+++ b/browser/base/content/browser.xul
@@ -559,16 +559,17 @@
                  oninput="gBrowser.userTypedValue = this.value;"
                  ontextentered="this.handleCommand(param);"
                  ontextreverted="return this.handleRevert();"
                  pageproxystate="invalid"
                  onfocus="document.getElementById('identity-box').style.MozUserFocus= 'normal'"
                  onblur="setTimeout(function() document.getElementById('identity-box').style.MozUserFocus = '', 0);">
           <box id="notification-popup-box" hidden="true" align="center">
             <image id="default-notification-icon" class="notification-anchor-icon" role="button"/>
+            <image id="identity-notification-icon" class="notification-anchor-icon" role="button"/>
             <image id="geo-notification-icon" class="notification-anchor-icon" role="button"/>
             <image id="addons-notification-icon" class="notification-anchor-icon" role="button"/>
             <image id="indexedDB-notification-icon" class="notification-anchor-icon" role="button"/>
             <image id="password-notification-icon" class="notification-anchor-icon" role="button"/>
             <image id="webapps-notification-icon" class="notification-anchor-icon" role="button"/>
             <image id="plugins-notification-icon" class="notification-anchor-icon" role="button"/>
           </box>
           <!-- Use onclick instead of normal popup= syntax since the popup
@@ -783,17 +784,17 @@
             <menuitem id="BMB_unsortedBookmarks"
                       label="&bookmarksMenuButton.unsorted.label;"
                       oncommand="PlacesCommandHook.showPlacesOrganizer('UnfiledBookmarks');"
                       class="menuitem-iconic"/>
           </menupopup>
         </toolbarbutton>
       </toolbaritem>
 
-      <hbox id="window-controls" hidden="true" fullscreencontrol="true" pack="end">
+      <hbox id="window-controls" hidden="true" pack="end">
         <toolbarbutton id="minimize-button"
                        tooltiptext="&fullScreenMinimize.tooltip;"
                        oncommand="window.minimize();"/>
 
         <toolbarbutton id="restore-button"
                        tooltiptext="&fullScreenRestore.tooltip;"
                        oncommand="BrowserFullScreen();"/>
 
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -1,12 +1,12 @@
-# -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-# 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/.
+/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/. */
 
 let Cc = Components.classes;
 let Ci = Components.interfaces;
 let Cu = Components.utils;
 
 // Bug 671101 - directly using webNavigation in this context
 // causes docshells to leak
 __defineGetter__("webNavigation", function () {
--- a/browser/base/content/newtab/newTab.xul
+++ b/browser/base/content/newtab/newTab.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="UTF-8"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this file,
-# You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/content/newtab/newTab.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/newtab/newTab.css" type="text/css"?>
 
 <!DOCTYPE window [
   <!ENTITY % newTabDTD SYSTEM "chrome://browser/locale/newTab.dtd">
   %newTabDTD;
--- a/browser/base/content/openLocation.js
+++ b/browser/base/content/openLocation.js
@@ -1,13 +1,13 @@
-# -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-#
-# 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/.
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+
+/* 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/. */
 
 var browser;
 var dialog = {};
 var pref = null;
 let openLocationModule = {};
 try {
   pref = Components.classes["@mozilla.org/preferences-service;1"]
                    .getService(Components.interfaces.nsIPrefBranch);
--- a/browser/base/content/openLocation.xul
+++ b/browser/base/content/openLocation.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0"?> 
-#
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 
 <!DOCTYPE dialog SYSTEM "chrome://browser/locale/openLocation.dtd">
  
 <dialog id="openLocation"
         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
         title="&caption.label;"
--- a/browser/base/content/pageinfo/feeds.js
+++ b/browser/base/content/pageinfo/feeds.js
@@ -1,12 +1,12 @@
-# -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-# 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/.
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/. */
 
 function initFeedTab()
 {
   const feedTypes = {
     "application/rss+xml": gBundle.getString("feedRss"),
     "application/atom+xml": gBundle.getString("feedAtom"),
     "text/xml": gBundle.getString("feedXML"),
     "application/xml": gBundle.getString("feedXML"),
--- a/browser/base/content/pageinfo/feeds.xml
+++ b/browser/base/content/pageinfo/feeds.xml
@@ -1,12 +1,12 @@
 <?xml version="1.0"?>
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE bindings [
   <!ENTITY % pageInfoDTD SYSTEM "chrome://browser/locale/pageInfo.dtd">
   %pageInfoDTD;
 ]>
 
 <bindings id="feedBindings"
           xmlns="http://www.mozilla.org/xbl"
--- a/browser/base/content/pageinfo/permissions.js
+++ b/browser/base/content/pageinfo/permissions.js
@@ -1,11 +1,11 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+/* This 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/. */
 
 const UNKNOWN = nsIPermissionManager.UNKNOWN_ACTION;   // 0
 const ALLOW = nsIPermissionManager.ALLOW_ACTION;       // 1
 const BLOCK = nsIPermissionManager.DENY_ACTION;        // 2
 const SESSION = nsICookiePermission.ACCESS_SESSION;    // 8
 
 const nsIIndexedDatabaseManager =
   Components.interfaces.nsIIndexedDatabaseManager;
--- a/browser/base/content/pageinfo/security.js
+++ b/browser/base/content/pageinfo/security.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/. */
 
 var security = {
   // Display the server certificate (static)
   viewCert : function () {
     var cert = security._cert;
     viewCertHelper(window, cert);
   },
 
--- a/browser/base/content/safeMode.js
+++ b/browser/base/content/safeMode.js
@@ -1,12 +1,12 @@
-# -*- Mode: js2; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-# 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/.
+/* -*- Mode: js2; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/. */
 
 let Cc = Components.classes;
 let Ci = Components.interfaces;
 let Cu = Components.utils;
 
 const appStartup = Services.startup;
 
 let defaultToReset = false;
--- a/browser/base/content/safeMode.xul
+++ b/browser/base/content/safeMode.xul
@@ -1,14 +1,13 @@
 <?xml version="1.0"?>
 
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE prefwindow [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd" >
 %brandDTD;
 <!ENTITY % safeModeDTD SYSTEM "chrome://browser/locale/safeMode.dtd" >
 %safeModeDTD;
 <!ENTITY % resetProfileDTD SYSTEM "chrome://global/locale/resetProfile.dtd" >
 %resetProfileDTD;
--- a/browser/base/content/sync/aboutSyncTabs-bindings.xml
+++ b/browser/base/content/sync/aboutSyncTabs-bindings.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <bindings id="tabBindings"
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           xmlns:xbl="http://www.mozilla.org/xbl">
 
   <binding id="tab-listing" extends="chrome://global/content/bindings/richlistbox.xml#richlistitem">
     <content>
--- a/browser/base/content/sync/aboutSyncTabs.xul
+++ b/browser/base/content/sync/aboutSyncTabs.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="UTF-8"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://browser/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/aboutSyncTabs.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/content/sync/aboutSyncTabs.css" type="text/css"?>
 
 <!DOCTYPE window [
   <!ENTITY % aboutSyncTabsDTD SYSTEM "chrome://browser/locale/aboutSyncTabs.dtd">
   %aboutSyncTabsDTD;
--- a/browser/base/content/sync/addDevice.xul
+++ b/browser/base/content/sync/addDevice.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/syncSetup.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/syncCommon.css" type="text/css"?>
 
 <!DOCTYPE window [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
 <!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
--- a/browser/base/content/sync/genericChange.xul
+++ b/browser/base/content/sync/genericChange.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/syncSetup.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/syncCommon.css" type="text/css"?>
 
 <!DOCTYPE window [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
 <!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
--- a/browser/base/content/sync/key.xhtml
+++ b/browser/base/content/sync/key.xhtml
@@ -1,13 +1,13 @@
 <?xml version="1.0" encoding="UTF-8"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE html [
   <!ENTITY % htmlDTD PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
   %htmlDTD;
   <!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
   %syncBrandDTD;
   <!ENTITY % syncKeyDTD SYSTEM "chrome://browser/locale/syncKey.dtd">
   %syncKeyDTD;
@@ -17,17 +17,17 @@
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
   <title>&syncKey.page.title;</title>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
   <meta name="robots" content="noindex"/>
   <style type="text/css">
     #synckey { font-size: 150% }
     footer { font-size: 70% }
-# Bug 575675: Need to have an a:visited rule in a chrome document.
+    /* Bug 575675: Need to have an a:visited rule in a chrome document. */
     a:visited { color: purple; }
   </style>
 </head>
 
 <body dir="&locale.dir;">
 <h1>&syncKey.page.title;</h1>
 
 <p id="synckey" dir="ltr">SYNCKEY</p>
--- a/browser/base/content/sync/notification.xml
+++ b/browser/base/content/sync/notification.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE bindings [
 <!ENTITY % notificationDTD SYSTEM "chrome://global/locale/notification.dtd">
 %notificationDTD;
 ]>
 
 <bindings id="notificationBindings"
           xmlns="http://www.mozilla.org/xbl"
--- a/browser/base/content/sync/progress.xhtml
+++ b/browser/base/content/sync/progress.xhtml
@@ -1,12 +1,12 @@
 <?xml version="1.0" encoding="UTF-8"?>
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE html [
   <!ENTITY % htmlDTD
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "DTD/xhtml1-strict.dtd">
   %htmlDTD;
   <!ENTITY % syncProgressDTD
     SYSTEM "chrome://browser/locale/syncProgress.dtd">
--- a/browser/base/content/sync/quota.xul
+++ b/browser/base/content/sync/quota.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/syncQuota.css"?>
 
 <!DOCTYPE dialog [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
 <!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
 <!ENTITY % syncQuotaDTD SYSTEM "chrome://browser/locale/syncQuota.dtd">
--- a/browser/base/content/sync/setup.xul
+++ b/browser/base/content/sync/setup.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/syncSetup.css" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/syncCommon.css" type="text/css"?>
 
 <!DOCTYPE window [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
 <!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
@@ -474,16 +474,16 @@
             &confirm.server2.label;
           </description>
           <separator class="thin"/>
           <vbox id="clientList">
           </vbox>
         </vbox>
       </deck>
   </wizardpage>
-# In terms of the wizard flow shown to the user, the 'syncOptionsConfirm'
-# page above is not the last wizard page. To prevent the wizard binding from
-# assuming that it is, we're inserting this dummy page here. This also means
-# that the wizard needs to always be closed manually via wizardFinish().
+  <!-- In terms of the wizard flow shown to the user, the 'syncOptionsConfirm'
+       page above is not the last wizard page. To prevent the wizard binding from
+       assuming that it is, we're inserting this dummy page here. This also means
+      that the wizard needs to always be closed manually via wizardFinish(). -->
   <wizardpage>
   </wizardpage>
 </wizard>
 
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -1378,16 +1378,22 @@
                 Cu.reportError(ex);
               }
             }
 
             // We start our browsers out as inactive, and then maintain
             // activeness in the tab switcher.
             b.docShellIsActive = false;
 
+            // If we just created a new tab that loads the default
+            // newtab url, swap in a preloaded page if possible.
+            if (aURI == BROWSER_NEW_TAB_URL) {
+              gBrowserNewTabPreloader.newTab(t);
+            }
+
             // Check if we're opening a tab related to the current tab and
             // move it to after the current tab.
             // aReferrerURI is null or undefined if the tab is opened from
             // an external application or bookmark, i.e. somewhere other
             // than the current tab.
             if ((aRelatedToCurrent == null ? aReferrerURI : aRelatedToCurrent) &&
                 Services.prefs.getBoolPref("browser.tabs.insertRelatedAfterCurrent")) {
               let newTabPos = (this._lastRelatedTab ||
@@ -1611,16 +1617,21 @@
             // We're committed to closing the tab now.
             // Dispatch a notification.
             // We dispatch it before any teardown so that event listeners can
             // inspect the tab that's about to close.
             var evt = document.createEvent("UIEvent");
             evt.initUIEvent("TabClose", true, false, window, aTabWillBeMoved ? 1 : 0);
             aTab.dispatchEvent(evt);
 
+            // Prevent this tab from showing further dialogs, since we're closing it
+            var windowUtils = browser.contentWindow.QueryInterface(Ci.nsIInterfaceRequestor).
+                              getInterface(Ci.nsIDOMWindowUtils);
+            windowUtils.preventFurtherDialogs();
+
             // Remove the tab's filter and progress listener.
             const filter = this.mTabFilters[aTab._tPos];
 #ifdef MOZ_E10S_COMPAT
             // Bug 666801 - WebProgress support for e10s
 #else 
             browser.webProgress.removeProgressListener(filter);
 #endif
             filter.removeProgressListener(this.mTabListeners[aTab._tPos]);
@@ -1808,92 +1819,126 @@
               } while (tab && remainingTabs.indexOf(tab) == -1);
             }
 
             this.selectedTab = tab;
           ]]>
         </body>
       </method>
 
+      <method name="swapNewTabWithBrowser">
+        <parameter name="aNewTab"/>
+        <parameter name="aBrowser"/>
+        <body>
+          <![CDATA[
+            // The browser must be standalone.
+            if (aBrowser.getTabBrowser())
+              throw Cr.NS_ERROR_INVALID_ARG;
+
+            // The tab is definitely not loading.
+            aNewTab.removeAttribute("busy");
+            if (aNewTab == this.selectedTab) {
+              this.mIsBusy = false;
+            }
+
+            this._swapBrowserDocShells(aNewTab, aBrowser);
+
+            // Update the new tab's title.
+            this.setTabTitle(aNewTab);
+
+            if (aNewTab == this.selectedTab) {
+              this.updateCurrentBrowser(true);
+            }
+          ]]>
+        </body>
+      </method>
+
       <method name="swapBrowsersAndCloseOther">
         <parameter name="aOurTab"/>
         <parameter name="aOtherTab"/>
         <body>
           <![CDATA[
             // That's gBrowser for the other window, not the tab's browser!
             var remoteBrowser = aOtherTab.ownerDocument.defaultView.gBrowser;
 
             // First, start teardown of the other browser.  Make sure to not
             // fire the beforeunload event in the process.  Close the other
             // window if this was its last tab.
             if (!remoteBrowser._beginRemoveTab(aOtherTab, true, true))
               return;
 
-            // Unhook our progress listener
-            var ourIndex = aOurTab._tPos;
-            const filter = this.mTabFilters[ourIndex];
-            var tabListener = this.mTabListeners[ourIndex];
-            var ourBrowser = this.getBrowserForTab(aOurTab);
-            ourBrowser.webProgress.removeProgressListener(filter);
-            filter.removeProgressListener(tabListener);
-            var tabListenerBlank = tabListener.mBlank;
-
-            var otherBrowser = aOtherTab.linkedBrowser;
-
-            // Restore current registered open URI.
-            if (ourBrowser.registeredOpenURI) {
-              this._placesAutocomplete.unregisterOpenPage(ourBrowser.registeredOpenURI);
-              delete ourBrowser.registeredOpenURI;
-            }
-            if (otherBrowser.registeredOpenURI) {
-              ourBrowser.registeredOpenURI = otherBrowser.registeredOpenURI;
-              delete otherBrowser.registeredOpenURI;
-            }
-
             // Workarounds for bug 458697
             // Icon might have been set on DOMLinkAdded, don't override that.
+            let ourBrowser = this.getBrowserForTab(aOurTab);
+            let otherBrowser = aOtherTab.linkedBrowser;
             if (!ourBrowser.mIconURL && otherBrowser.mIconURL)
               this.setIcon(aOurTab, otherBrowser.mIconURL);
             var isBusy = aOtherTab.hasAttribute("busy");
             if (isBusy) {
               aOurTab.setAttribute("busy", "true");
               this._tabAttrModified(aOurTab);
               if (aOurTab == this.selectedTab)
                 this.mIsBusy = true;
             }
 
-            // Swap the docshells
-            ourBrowser.swapDocShells(otherBrowser);
+            this._swapBrowserDocShells(aOurTab, otherBrowser);
 
             // Finish tearing down the tab that's going away.
             remoteBrowser._endRemoveTab(aOtherTab);
 
-            // Restore the progress listener
-            tabListener = this.mTabProgressListener(aOurTab, ourBrowser,
-                                                    tabListenerBlank);
-            this.mTabListeners[ourIndex] = tabListener;
-            filter.addProgressListener(tabListener,
-              Components.interfaces.nsIWebProgress.NOTIFY_ALL);
-
-            ourBrowser.webProgress.addProgressListener(filter,
-              Components.interfaces.nsIWebProgress.NOTIFY_ALL);
-
             if (isBusy)
               this.setTabTitleLoading(aOurTab);
             else
               this.setTabTitle(aOurTab);
 
             // If the tab was already selected (this happpens in the scenario
             // of replaceTabWithWindow), notify onLocationChange, etc.
             if (aOurTab == this.selectedTab)
               this.updateCurrentBrowser(true);
           ]]>
         </body>
       </method>
 
+      <method name="_swapBrowserDocShells">
+        <parameter name="aOurTab"/>
+        <parameter name="aOtherBrowser"/>
+        <body>
+          <![CDATA[
+            // Unhook our progress listener
+            let index = aOurTab._tPos;
+            const filter = this.mTabFilters[index];
+            let tabListener = this.mTabListeners[index];
+            let ourBrowser = this.getBrowserForTab(aOurTab);
+            ourBrowser.webProgress.removeProgressListener(filter);
+            filter.removeProgressListener(tabListener);
+
+            // Restore current registered open URI.
+            if (ourBrowser.registeredOpenURI) {
+              this._placesAutocomplete.unregisterOpenPage(ourBrowser.registeredOpenURI);
+              delete ourBrowser.registeredOpenURI;
+            }
+            if (aOtherBrowser.registeredOpenURI) {
+              ourBrowser.registeredOpenURI = aOtherBrowser.registeredOpenURI;
+              delete aOtherBrowser.registeredOpenURI;
+            }
+
+            // Swap the docshells
+            ourBrowser.swapDocShells(aOtherBrowser);
+
+            // Restore the progress listener
+            this.mTabListeners[index] = tabListener =
+              this.mTabProgressListener(aOurTab, ourBrowser, false);
+
+            const notifyAll = Ci.nsIWebProgress.NOTIFY_ALL;
+            filter.addProgressListener(tabListener, notifyAll);
+            ourBrowser.webProgress.addProgressListener(filter, notifyAll);
+          ]]>
+        </body>
+      </method>
+
       <method name="reloadAllTabs">
         <body>
           <![CDATA[
             let tabs = this.visibleTabs;
             let l = tabs.length;
             for (var i = 0; i < l; i++) {
               try {
                 this.getBrowserForTab(tabs[i]).reload();
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -194,16 +194,17 @@ endif
                  browser_scope.js \
                  browser_selectTabAtIndex.js \
                  browser_tab_dragdrop.js \
                  browser_tab_dragdrop2.js \
                  browser_tab_dragdrop2_frame1.xul \
                  browser_tabfocus.js \
                  browser_tabs_isActive.js \
                  browser_tabs_owner.js \
+                 browser_unloaddialogs.js \
                  browser_urlbarAutoFillTrimURLs.js \
                  browser_urlbarCopying.js \
                  browser_urlbarEnter.js \
                  browser_urlbarRevert.js \
                  browser_urlbarStop.js \
                  browser_urlbarTrimURLs.js \
                  browser_urlHighlight.js \
                  browser_visibleFindSelection.js \
--- a/browser/base/content/test/browser_bug724239.js
+++ b/browser/base/content/test/browser_bug724239.js
@@ -16,13 +16,18 @@ function test() {
     whenBrowserLoaded(browser, function () {
       ok(!gBrowser.canGoBack, "about:newtab wasn't added to the session history");
       finish();
     });
   });
 }
 
 function whenBrowserLoaded(aBrowser, aCallback) {
+  if (aBrowser.contentDocument.readyState == "complete") {
+    executeSoon(aCallback);
+    return;
+  }
+
   aBrowser.addEventListener("load", function onLoad() {
     aBrowser.removeEventListener("load", onLoad, true);
     executeSoon(aCallback);
   }, true);
 }
--- a/browser/base/content/test/browser_bug763468.js
+++ b/browser/base/content/test/browser_bug763468.js
@@ -62,15 +62,20 @@ function togglePrivateBrowsing(aCallback
   }, topic, false);
 
   pb.privateBrowsingEnabled = !pb.privateBrowsingEnabled;
 }
 
 function openNewTab(aCallback) {
   // Open a new tab
   BrowserOpenTab();
-  
+
   let browser = gBrowser.selectedBrowser;
+  if (browser.contentDocument.readyState == "complete") {
+    executeSoon(aCallback);
+    return;
+  }
+
   browser.addEventListener("load", function onLoad() {
     browser.removeEventListener("load", onLoad, true);
     executeSoon(aCallback);
   }, true);
 }
--- a/browser/base/content/test/browser_bug767836.js
+++ b/browser/base/content/test/browser_bug767836.js
@@ -79,15 +79,20 @@ function togglePrivateBrowsing(aCallback
   }, topic, false);
 
   pb.privateBrowsingEnabled = !pb.privateBrowsingEnabled;
 }
 
 function openNewTab(aCallback) {
   // Open a new tab
   BrowserOpenTab();
-  
+
   let browser = gBrowser.selectedBrowser;
+  if (browser.contentDocument.readyState == "complete") {
+    executeSoon(aCallback);
+    return;
+  }
+
   browser.addEventListener("load", function onLoad() {
     browser.removeEventListener("load", onLoad, true);
     executeSoon(aCallback);
   }, true);
 }
--- a/browser/base/content/test/browser_popupNotification.js
+++ b/browser/base/content/test/browser_popupNotification.js
@@ -73,17 +73,17 @@ function runNextTest() {
       }
 
       let onHidden = onHiddenArray.shift();
       info("[Test #" + gTestIndex + "] popup hidden (" + onHiddenArray.length + " hides remaining)");
       executeSoon(function () {
         onHidden.call(nextTest, this);
         if (!onHiddenArray.length)
           goNext();
-      });
+      }.bind(this));
     }, onHiddenArray.length);
     info("[Test #" + gTestIndex + "] added listeners; panel state: " + PopupNotifications.isPanelOpen);
   }
 
   info("[Test #" + gTestIndex + "] running test");
   nextTest.run();
 }
 
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_unloaddialogs.js
@@ -0,0 +1,134 @@
+function notify(event)
+{
+  if (event.target.location == "about:blank")
+    return;
+
+  var eventname = event.type;
+  if (eventname == "pagehide")
+    details.pagehides++;
+  else if (eventname == "beforeunload")
+    details.beforeunloads++;
+  else if (eventname == "unload")
+    details.unloads++;
+}
+
+var details;
+
+var gUseFrame = false;
+
+const windowMediator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
+
+const TEST_BASE_URL = "data:text/html,<script>" +
+                      "function note(event) { try { alert(event.type); } catch(ex) { return; } throw 'alert appeared'; }" +
+                      "</script>" +
+                      "<body onpagehide='note(event)' onbeforeunload='alert(event.type);' onunload='note(event)'>";
+
+const TEST_URL = TEST_BASE_URL + "Test</body>";
+const TEST_FRAME_URL = TEST_BASE_URL + "Frames</body>";
+
+function test()
+{
+  waitForExplicitFinish();
+  windowMediator.addListener(promptListener);
+  runTest();
+}
+
+function runTest()
+{
+  details = {
+    testNumber : 0,
+    beforeunloads : 0,
+    pagehides : 0,
+    unloads : 0,
+    prompts : 0
+  };
+
+  var tab = gBrowser.addTab(TEST_URL);
+  gBrowser.selectedTab = tab;
+  tab.linkedBrowser.addEventListener("pageshow", shown, true);
+
+  tab.linkedBrowser.addEventListener("pagehide", notify, true);
+  tab.linkedBrowser.addEventListener("beforeunload", notify, true);
+  tab.linkedBrowser.addEventListener("unload", notify, true);
+}
+
+function shown(event)
+{
+  if (details.testNumber == 0) {
+    var browser;
+    var iframe;
+    if (gUseFrame) {
+      iframe = event.target.createElement("iframe");
+      iframe.src = TEST_FRAME_URL;
+      event.target.documentElement.appendChild(iframe);
+      browser = iframe.contentWindow;
+    }
+    else {
+      browser = gBrowser.selectedTab.linkedBrowser;
+      details.testNumber = 1; // Move onto to the next step immediately
+    }
+  }
+
+  if (details.testNumber == 1) {
+    // Test going to another page
+    executeSoon(function () {
+      const urlToLoad = "data:text/html,<body>Another Page</body>";
+      if (gUseFrame) {
+        event.target.location = urlToLoad;
+      }
+      else {
+        gBrowser.selectedBrowser.loadURI(urlToLoad);
+      }
+    });
+  }
+  else if (details.testNumber == 2) {
+    is(details.pagehides, 1, "pagehides after next page")
+    is(details.beforeunloads, 1, "beforeunloads after next page")
+    is(details.unloads, 1, "unloads after next page")
+    is(details.prompts, 1, "prompts after next page")
+
+    executeSoon(function () gUseFrame ? gBrowser.goBack() : event.target.defaultView.back());
+  }
+  else if (details.testNumber == 3) {
+    is(details.pagehides, 2, "pagehides after back")
+    is(details.beforeunloads, 2, "beforeunloads after back")
+    // No cache, so frame is unloaded
+    is(details.unloads, gUseFrame ? 2 : 1, "unloads after back")
+    is(details.prompts, 1, "prompts after back")
+
+    // Test closing the tab
+    gBrowser.selectedBrowser.removeEventListener("pageshow", shown, true);
+    gBrowser.removeTab(gBrowser.selectedTab);
+
+    // When the frame is present, there is are two beforeunload and prompts,
+    // one for the frame and the other for the parent.
+    is(details.pagehides, 3, "pagehides after close")
+    is(details.beforeunloads, gUseFrame ? 4 : 3, "beforeunloads after close")
+    is(details.unloads, gUseFrame ? 3 : 2, "unloads after close")
+    is(details.prompts, gUseFrame ? 3 : 2, "prompts after close")
+
+    // Now run the test again using a child frame.
+    if (gUseFrame) {
+      windowMediator.removeListener(promptListener);
+      finish();
+    }
+    else {
+      gUseFrame = true;
+      runTest();
+    }
+
+    return;
+  }
+
+  details.testNumber++;
+}
+
+var promptListener = {
+  onWindowTitleChange: function () {},
+  onOpenWindow: function (win) {
+    details.prompts++;
+    let domWin = win.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow);
+    executeSoon(function () { domWin.close() });
+  },
+  onCloseWindow: function () {},
+};
--- a/browser/base/content/test/newtab/head.js
+++ b/browser/base/content/test/newtab/head.js
@@ -198,28 +198,37 @@ function restore() {
 
 /**
  * Creates a new tab containing 'about:newtab'.
  */
 function addNewTabPageTab() {
   let tab = gBrowser.selectedTab = gBrowser.addTab("about:newtab");
   let browser = tab.linkedBrowser;
 
-  // Wait for the new tab page to be loaded.
-  browser.addEventListener("load", function onLoad() {
-    browser.removeEventListener("load", onLoad, true);
-
+  function whenNewTabLoaded() {
     if (NewTabUtils.allPages.enabled) {
       // Continue when the link cache has been populated.
       NewTabUtils.links.populateCache(function () {
         executeSoon(TestRunner.next);
       });
     } else {
       TestRunner.next();
     }
+  }
+
+  // The new tab page might have been preloaded in the background.
+  if (browser.contentDocument.readyState == "complete") {
+    whenNewTabLoaded();
+    return;
+  }
+
+  // Wait for the new tab page to be loaded.
+  browser.addEventListener("load", function onLoad() {
+    browser.removeEventListener("load", onLoad, true);
+    whenNewTabLoaded();
   }, true);
 }
 
 /**
  * Compares the current grid arrangement with the given pattern.
  * @param the pattern (see below)
  * @param the array of sites to compare with (optional)
  *
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -1170,16 +1170,271 @@
       <method name="onDownloadEnded">
         <body><![CDATA[
           this.updateProgress();
         ]]></body>
       </method>
     </implementation>
   </binding>
 
+  <binding id="identity-request-notification" extends="chrome://global/content/bindings/notification.xml#popup-notification">
+    <content align="start">
+
+      <xul:image class="popup-notification-icon"
+                 xbl:inherits="popupid,src=icon"/>
+
+      <xul:vbox flex="1">
+        <xul:vbox anonid="identity-deck">
+          <xul:vbox flex="1" pack="center"> <!-- 1: add an email -->
+            <html:input type="email" anonid="email" required="required" size="30"/>
+            <xul:description anonid="newidentitydesc"/>
+            <xul:spacer flex="1"/>
+            <xul:label class="text-link custom-link small-margin" anonid="chooseemail" hidden="true"/>
+          </xul:vbox>
+          <xul:vbox flex="1" hidden="true"> <!-- 2: choose an email -->
+            <xul:description anonid="chooseidentitydesc"/>
+            <xul:radiogroup anonid="identities">
+            </xul:radiogroup>
+            <xul:label class="text-link custom-link" anonid="newemail"/>
+          </xul:vbox>
+        </xul:vbox>
+        <xul:hbox class="popup-notification-button-container"
+                  pack="end" align="center">
+          <xul:label anonid="tos" class="text-link" hidden="true"/>
+          <xul:label anonid="privacypolicy" class="text-link" hidden="true"/>
+          <xul:spacer flex="1"/>
+          <xul:image anonid="throbber" src="chrome://browser/skin/tabbrowser/loading.png"
+                     style="visibility:hidden" width="16" height="16"/>
+          <xul:button anonid="button"
+                      type="menu-button"
+                      class="popup-notification-menubutton"
+                      xbl:inherits="oncommand=buttoncommand,label=buttonlabel,accesskey=buttonaccesskey">
+            <xul:menupopup anonid="menupopup"
+                           xbl:inherits="oncommand=menucommand">
+              <children/>
+              <xul:menuitem class="menuitem-iconic popup-notification-closeitem"
+                            label="&closeNotificationItem.label;"
+                            xbl:inherits="oncommand=closeitemcommand"/>
+            </xul:menupopup>
+          </xul:button>
+        </xul:hbox>
+      </xul:vbox>
+      <xul:vbox pack="start">
+        <xul:toolbarbutton anonid="closebutton"
+                           class="messageCloseButton popup-notification-closebutton tabbable"
+                           xbl:inherits="oncommand=closebuttoncommand"
+                           tooltiptext="&closeNotification.tooltip;"/>
+      </xul:vbox>
+    </content>
+    <implementation>
+      <constructor><![CDATA[
+        // this.notification.options.identity is used to pass identity-specific info to the binding
+        let origin = this.identity.origin
+
+        // Populate text
+        this.emailField.placeholder = gNavigatorBundle.
+                                      getString("identity.newIdentity.email.placeholder");
+        this.newIdentityDesc.textContent = gNavigatorBundle.getFormattedString(
+                                             "identity.newIdentity.description", [origin]);
+        this.chooseIdentityDesc.textContent = gNavigatorBundle.getFormattedString(
+                                                "identity.chooseIdentity.description", [origin]);
+
+        // Show optional terms of service and privacy policy links
+        this._populateLink(this.identity.termsOfService, "tos", "identity.termsOfService");
+        this._populateLink(this.identity.privacyPolicy, "privacypolicy", "identity.privacyPolicy");
+
+        // Populate the list of identities to choose from. The origin is used to provide
+        // better suggestions.
+        let identities = this.SignInToWebsiteUX.getIdentitiesForSite(origin);
+
+        this._populateIdentityList(identities);
+
+        if (typeof this.step == "undefined") {
+          // First opening of this notification
+          // Show the add email pane (0) if there are no existing identities otherwise show the list
+          this.step = "result" in identities && identities.result.length ? 1 : 0;
+        } else {
+          // Already opened so restore previous state
+          if (this.identity.typedEmail) {
+            this.emailField.value = this.identity.typedEmail;
+          }
+          if (this.identity.selected) {
+            // If the user already chose an identity then update the UI to reflect that
+            this.onIdentitySelected();
+          }
+          // Update the view for the step
+          this.step = this.step;
+        }
+
+        // Fire notification with the chosen identity when main button is clicked
+        this.button.addEventListener("command", this._onButtonCommand.bind(this), true);
+
+        // Do the same if enter is pressed in the email field
+        this.emailField.addEventListener("keypress", function emailFieldKeypress(aEvent) {
+          if (aEvent.keyCode != aEvent.DOM_VK_RETURN)
+            return;
+          this._onButtonCommand(aEvent);
+        }.bind(this));
+
+        this.addEmailLink.value = gNavigatorBundle.getString("identity.newIdentity.label");
+        this.addEmailLink.accessKey = gNavigatorBundle.getString("identity.newIdentity.accessKey");
+        this.addEmailLink.addEventListener("click", function addEmailClick(evt) {
+          this.step = 0;
+        }.bind(this));
+
+        this.chooseEmailLink.value = gNavigatorBundle.getString("identity.chooseIdentity.label");
+        this.chooseEmailLink.hidden = !("result" in identities && identities.result.length);
+        this.chooseEmailLink.addEventListener("click", function chooseEmailClick(evt) {
+          this.step = 1;
+        }.bind(this));
+
+        this.emailField.addEventListener("blur", function onEmailBlur() {
+          this.identity.typedEmail = this.emailField.value;
+        }.bind(this));
+      ]]></constructor>
+
+      <field name="SignInToWebsiteUX" readonly="true">
+        let sitw = {};
+        Components.utils.import("resource:///modules/SignInToWebsite.jsm", sitw);
+        sitw.SignInToWebsiteUX;
+      </field>
+
+      <field name="newIdentityDesc" readonly="true">
+        document.getAnonymousElementByAttribute(this, "anonid", "newidentitydesc");
+      </field>
+
+      <field name="chooseIdentityDesc" readonly="true">
+        document.getAnonymousElementByAttribute(this, "anonid", "chooseidentitydesc");
+      </field>
+
+      <field name="identityList" readonly="true">
+        document.getAnonymousElementByAttribute(this, "anonid", "identities");
+      </field>
+
+      <field name="emailField" readonly="true">
+        document.getAnonymousElementByAttribute(this, "anonid", "email");
+      </field>
+
+      <field name="addEmailLink" readonly="true">
+        document.getAnonymousElementByAttribute(this, "anonid", "newemail");
+      </field>
+
+      <field name="chooseEmailLink" readonly="true">
+        document.getAnonymousElementByAttribute(this, "anonid", "chooseemail");
+      </field>
+
+      <field name="throbber" readonly="true">
+        document.getAnonymousElementByAttribute(this, "anonid", "throbber");
+      </field>
+
+      <field name="identity" readonly="true">
+        this.notification.options.identity;
+      </field>
+
+      <!-- persist the state on the identity object so we can re-create the
+           notification state upon re-opening -->
+      <property name="step">
+        <getter>
+          return this.identity.step;
+        </getter>
+        <setter><![CDATA[
+          let deck = document.getAnonymousElementByAttribute(this, "anonid", "identity-deck");
+          for (let i = 0; i < deck.children.length; i++) {
+            deck.children[i].hidden = (val != i);
+          }
+          this.identity.step = val;
+          switch (val) {
+            case 0:
+              this.emailField.focus();
+              break;
+          }]]>
+        </setter>
+      </property>
+
+      <method name="onIdentitySelected">
+        <body><![CDATA[
+          this.throbber.style.visibility = "visible";
+          this.button.disabled = true;
+          this.emailField.value = this.identity.selected
+          this.emailField.disabled = true;
+          this.identityList.disabled = true;
+        ]]></body>
+      </method>
+
+      <method name="_populateLink">
+        <parameter name="aURL"/>
+        <parameter name="aLinkId"/>
+        <parameter name="aStringId"/>
+        <body><![CDATA[
+          if (aURL) {
+            // Show optional link to aURL
+            let link = document.getAnonymousElementByAttribute(this, "anonid", aLinkId);
+            link.value = gNavigatorBundle.getString(aStringId);
+            link.href = aURL;
+            link.hidden = false;
+          }
+        ]]></body>
+      </method>
+
+      <method name="_populateIdentityList">
+        <parameter name="aIdentities"/>
+        <body><![CDATA[
+          let foundLastUsed = false;
+          let lastUsed = this.identity.selected || aIdentities.lastUsed;
+          for (let id in aIdentities.result) {
+            let label = aIdentities.result[id];
+            let opt = this.identityList.appendItem(label);
+            if (label == lastUsed) {
+              this.identityList.selectedItem = opt;
+              foundLastUsed = true;
+            }
+          }
+          if (!foundLastUsed) {
+            this.identityList.selectedIndex = -1;
+          }
+        ]]></body>
+      </method>
+
+      <method name="_onButtonCommand">
+        <parameter name="aEvent"/>
+        <body><![CDATA[
+          if (aEvent.target != aEvent.currentTarget)
+            return;
+          let chosenId;
+          switch (this.step) {
+            case 0:
+              aEvent.stopPropagation();
+              if (!this.emailField.validity.valid) {
+                this.emailField.focus();
+                return;
+              }
+              chosenId = this.emailField.value;
+              break;
+            case 1:
+              aEvent.stopPropagation();
+              let selectedItem = this.identityList.selectedItem
+              chosenId = selectedItem ? selectedItem.label : null;
+              if (!chosenId)
+                return;
+              break;
+            default:
+              throw new Error("Unknown case");
+              return;
+          }
+          // Actually select the identity
+          this.SignInToWebsiteUX.selectIdentity(this.identity.rpId, chosenId);
+          this.identity.selected = chosenId;
+          this.onIdentitySelected();
+        ]]></body>
+      </method>
+
+    </implementation>
+  </binding>
+
+
   <binding id="splitmenu">
     <content>
       <xul:hbox anonid="menuitem" flex="1"
                 class="splitmenu-menuitem"
                 xbl:inherits="iconic,label,disabled,onclick=oncommand,_moz-menuactive=active"/>
       <xul:menu anonid="menu" class="splitmenu-menu"
                 xbl:inherits="disabled,_moz-menuactive=active"
                 oncommand="event.stopPropagation();">
--- a/browser/base/content/web-panels.js
+++ b/browser/base/content/web-panels.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 const NS_ERROR_MODULE_NETWORK = 2152398848;
 const NS_NET_STATUS_READ_FROM = NS_ERROR_MODULE_NETWORK + 8;
 const NS_NET_STATUS_WROTE_TO  = NS_ERROR_MODULE_NETWORK + 9;
 
 function getPanelBrowser()
 {
     return document.getElementById("web-panels-browser");
--- a/browser/base/content/win6BrowserOverlay.xul
+++ b/browser/base/content/win6BrowserOverlay.xul
@@ -1,12 +1,12 @@
 <?xml version="1.0"?>
-# -*- Mode: HTML -*-
-#
-# 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/.
+
+<!-- -*- Mode: HTML -*- -->
+<!-- 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/. -->
 
 <overlay id="win6-browser-overlay"
          xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
   <toolbar id="toolbar-menubar"
            autohide="true"/>
 </overlay>
--- a/browser/base/jar.mn
+++ b/browser/base/jar.mn
@@ -12,20 +12,20 @@ browser.jar:
 %  overlay chrome://browser/content/browser.xul chrome://browser/content/win6BrowserOverlay.xul os=WINNT osversion>=6
 #endif
 %  overlay chrome://global/content/viewSource.xul chrome://browser/content/viewSourceOverlay.xul
 %  overlay chrome://global/content/viewPartialSource.xul chrome://browser/content/viewSourceOverlay.xul
 %  style chrome://global/content/customizeToolbar.xul chrome://browser/content/browser.css
 %  style chrome://global/content/customizeToolbar.xul chrome://browser/skin/
 *       content/browser/aboutDialog.xul               (content/aboutDialog.xul)
 *       content/browser/aboutDialog.js                (content/aboutDialog.js)
-*       content/browser/aboutDialog.css               (content/aboutDialog.css)
-*       content/browser/aboutRobots.xhtml             (content/aboutRobots.xhtml)
-*       content/browser/abouthome/aboutHome.xhtml     (content/abouthome/aboutHome.xhtml)
-*       content/browser/abouthome/aboutHome.js        (content/abouthome/aboutHome.js)
+        content/browser/aboutDialog.css               (content/aboutDialog.css)
+        content/browser/aboutRobots.xhtml             (content/aboutRobots.xhtml)
+        content/browser/abouthome/aboutHome.xhtml     (content/abouthome/aboutHome.xhtml)
+        content/browser/abouthome/aboutHome.js        (content/abouthome/aboutHome.js)
 *       content/browser/abouthome/aboutHome.css       (content/abouthome/aboutHome.css)
         content/browser/abouthome/snippet1.png        (content/abouthome/snippet1.png)
         content/browser/abouthome/snippet2.png        (content/abouthome/snippet2.png)
         content/browser/abouthome/downloads.png       (content/abouthome/downloads.png)
         content/browser/abouthome/bookmarks.png       (content/abouthome/bookmarks.png)
         content/browser/abouthome/history.png         (content/abouthome/history.png)
         content/browser/abouthome/apps.png            (content/abouthome/apps.png)
         content/browser/abouthome/addons.png          (content/abouthome/addons.png)
@@ -36,72 +36,72 @@ browser.jar:
         content/browser/abouthome/mozilla.png         (content/abouthome/mozilla.png)
         content/browser/abouthome/noise.png           (content/abouthome/noise.png)
         content/browser/aboutRobots-icon.png          (content/aboutRobots-icon.png)
         content/browser/aboutRobots-widget-left.png   (content/aboutRobots-widget-left.png)
 *       content/browser/browser.css                   (content/browser.css)
 *       content/browser/browser.js                    (content/browser.js)
 *       content/browser/browser.xul                   (content/browser.xul)
 *       content/browser/browser-tabPreviews.xml       (content/browser-tabPreviews.xml)
-*       content/browser/content.js                    (content/content.js)
-*       content/browser/newtab/newTab.xul             (content/newtab/newTab.xul)
+        content/browser/content.js                    (content/content.js)
+        content/browser/newtab/newTab.xul             (content/newtab/newTab.xul)
 *       content/browser/newtab/newTab.js              (content/newtab/newTab.js)
         content/browser/newtab/newTab.css             (content/newtab/newTab.css)
 *       content/browser/pageinfo/pageInfo.xul         (content/pageinfo/pageInfo.xul)
 *       content/browser/pageinfo/pageInfo.js          (content/pageinfo/pageInfo.js)
-*       content/browser/pageinfo/pageInfo.css         (content/pageinfo/pageInfo.css)
-*       content/browser/pageinfo/pageInfo.xml         (content/pageinfo/pageInfo.xml)
-*       content/browser/pageinfo/feeds.js             (content/pageinfo/feeds.js)
-*       content/browser/pageinfo/feeds.xml            (content/pageinfo/feeds.xml)
-*       content/browser/pageinfo/permissions.js       (content/pageinfo/permissions.js)
-*       content/browser/pageinfo/security.js          (content/pageinfo/security.js)
+        content/browser/pageinfo/pageInfo.css         (content/pageinfo/pageInfo.css)
+        content/browser/pageinfo/pageInfo.xml         (content/pageinfo/pageInfo.xml)
+        content/browser/pageinfo/feeds.js             (content/pageinfo/feeds.js)
+        content/browser/pageinfo/feeds.xml            (content/pageinfo/feeds.xml)
+        content/browser/pageinfo/permissions.js       (content/pageinfo/permissions.js)
+        content/browser/pageinfo/security.js          (content/pageinfo/security.js)
 #ifdef MOZ_SERVICES_SYNC
-*       content/browser/sync/aboutSyncTabs.xul        (content/sync/aboutSyncTabs.xul)
+        content/browser/sync/aboutSyncTabs.xul        (content/sync/aboutSyncTabs.xul)
         content/browser/sync/aboutSyncTabs.js         (content/sync/aboutSyncTabs.js)
         content/browser/sync/aboutSyncTabs.css        (content/sync/aboutSyncTabs.css)
-*       content/browser/sync/aboutSyncTabs-bindings.xml  (content/sync/aboutSyncTabs-bindings.xml)
-*       content/browser/sync/setup.xul                (content/sync/setup.xul)
+        content/browser/sync/aboutSyncTabs-bindings.xml  (content/sync/aboutSyncTabs-bindings.xml)
+        content/browser/sync/setup.xul                (content/sync/setup.xul)
         content/browser/sync/addDevice.js             (content/sync/addDevice.js)
-*       content/browser/sync/addDevice.xul            (content/sync/addDevice.xul)
+        content/browser/sync/addDevice.xul            (content/sync/addDevice.xul)
         content/browser/sync/setup.js                 (content/sync/setup.js)
-*       content/browser/sync/genericChange.xul        (content/sync/genericChange.xul)
+        content/browser/sync/genericChange.xul        (content/sync/genericChange.xul)
         content/browser/sync/genericChange.js         (content/sync/genericChange.js)
-*       content/browser/sync/key.xhtml                (content/sync/key.xhtml)
-*       content/browser/sync/notification.xml         (content/sync/notification.xml)
-*       content/browser/sync/quota.xul                (content/sync/quota.xul)
+        content/browser/sync/key.xhtml                (content/sync/key.xhtml)
+        content/browser/sync/notification.xml         (content/sync/notification.xml)
+        content/browser/sync/quota.xul                (content/sync/quota.xul)
         content/browser/sync/quota.js                 (content/sync/quota.js)
         content/browser/sync/utils.js                 (content/sync/utils.js)
         content/browser/sync/progress.js              (content/sync/progress.js)
-*       content/browser/sync/progress.xhtml           (content/sync/progress.xhtml)
+        content/browser/sync/progress.xhtml           (content/sync/progress.xhtml)
 #endif
-*       content/browser/openLocation.js               (content/openLocation.js)
-*       content/browser/openLocation.xul              (content/openLocation.xul)
-*       content/browser/safeMode.css                  (content/safeMode.css)
-*       content/browser/safeMode.js                   (content/safeMode.js)
-*       content/browser/safeMode.xul                  (content/safeMode.xul)
+        content/browser/openLocation.js               (content/openLocation.js)
+        content/browser/openLocation.xul              (content/openLocation.xul)
+        content/browser/safeMode.css                  (content/safeMode.css)
+        content/browser/safeMode.js                   (content/safeMode.js)
+        content/browser/safeMode.xul                  (content/safeMode.xul)
 *       content/browser/sanitize.js                   (content/sanitize.js)
 *       content/browser/sanitize.xul                  (content/sanitize.xul)
 *       content/browser/sanitizeDialog.js             (content/sanitizeDialog.js)
         content/browser/sanitizeDialog.css            (content/sanitizeDialog.css)
-*       content/browser/tabbrowser.css                (content/tabbrowser.css)
+        content/browser/tabbrowser.css                (content/tabbrowser.css)
 *       content/browser/tabbrowser.xml                (content/tabbrowser.xml)
 *       content/browser/urlbarBindings.xml            (content/urlbarBindings.xml)
 *       content/browser/utilityOverlay.js             (content/utilityOverlay.js)
-*       content/browser/web-panels.js                 (content/web-panels.js)
+        content/browser/web-panels.js                 (content/web-panels.js)
 *       content/browser/web-panels.xul                (content/web-panels.xul)
 *       content/browser/baseMenuOverlay.xul           (content/baseMenuOverlay.xul)
 *       content/browser/nsContextMenu.js              (content/nsContextMenu.js)
 # XXX: We should exclude this one as well (bug 71895)
 *       content/browser/hiddenWindow.xul              (content/hiddenWindow.xul)
 #ifdef XP_MACOSX
 *       content/browser/macBrowserOverlay.xul         (content/macBrowserOverlay.xul)
 *       content/browser/downloadManagerOverlay.xul    (content/downloadManagerOverlay.xul)
 *       content/browser/jsConsoleOverlay.xul          (content/jsConsoleOverlay.xul)
 *       content/browser/softwareUpdateOverlay.xul  (content/softwareUpdateOverlay.xul)
 #endif
 *       content/browser/viewSourceOverlay.xul         (content/viewSourceOverlay.xul)
 #ifdef XP_WIN
-*       content/browser/win6BrowserOverlay.xul        (content/win6BrowserOverlay.xul)
+        content/browser/win6BrowserOverlay.xul        (content/win6BrowserOverlay.xul)
 #endif
         content/browser/social-icon.png               (content/social-icon.png)
 # the following files are browser-specific overrides
 *       content/browser/license.html                  (/toolkit/content/license.html)
 % override chrome://global/content/license.html chrome://browser/content/license.html
--- a/browser/components/downloads/content/download.xml
+++ b/browser/components/downloads/content/download.xml
@@ -1,14 +1,15 @@
 <?xml version="1.0"?>
-# -*- Mode: HTML; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-# vim: set ts=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/.
+<!-- -*- Mode: HTML; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- -->
+<!-- vim: set ts=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/. -->
 
 <!DOCTYPE bindings SYSTEM "chrome://browser/locale/downloads/downloads.dtd">
 
 <bindings id="downloadBindings"
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           xmlns:xbl="http://www.mozilla.org/xbl">
 
--- a/browser/components/downloads/content/indicatorOverlay.xul
+++ b/browser/components/downloads/content/indicatorOverlay.xul
@@ -1,14 +1,15 @@
 <?xml version="1.0"?>
-# -*- Mode: HTML; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-# vim: set ts=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/.
+<!-- -*- Mode: HTML; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- -->
+<!-- vim: set ts=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/. -->
 
 <?xml-stylesheet href="chrome://browser/content/downloads/downloads.css"?>
 <?xml-stylesheet href="chrome://browser/skin/downloads/downloads.css"?>
 
 <!DOCTYPE overlay SYSTEM "chrome://browser/locale/downloads/downloads.dtd">
 
 <overlay xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
          xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
--- a/browser/components/downloads/jar.mn
+++ b/browser/components/downloads/jar.mn
@@ -1,11 +1,11 @@
 # 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/.
 
 browser.jar:
-*       content/browser/downloads/download.xml           (content/download.xml)
+        content/browser/downloads/download.xml           (content/download.xml)
         content/browser/downloads/downloads.css          (content/downloads.css)
         content/browser/downloads/downloads.js           (content/downloads.js)
 *       content/browser/downloads/downloadsOverlay.xul   (content/downloadsOverlay.xul)
         content/browser/downloads/indicator.js           (content/indicator.js)
-*       content/browser/downloads/indicatorOverlay.xul   (content/indicatorOverlay.xul)
+        content/browser/downloads/indicatorOverlay.xul   (content/indicatorOverlay.xul)
--- a/browser/components/feeds/jar.mn
+++ b/browser/components/feeds/jar.mn
@@ -1,9 +1,9 @@
 # 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/.
 
 browser.jar:
-*   content/browser/feeds/subscribe.xhtml               (content/subscribe.xhtml) 
-*   content/browser/feeds/subscribe.js                  (content/subscribe.js)
-*   content/browser/feeds/subscribe.xml                 (content/subscribe.xml)
+    content/browser/feeds/subscribe.xhtml               (content/subscribe.xhtml) 
+    content/browser/feeds/subscribe.js                  (content/subscribe.js)
+    content/browser/feeds/subscribe.xml                 (content/subscribe.xml)
     content/browser/feeds/subscribe.css                 (content/subscribe.css)
--- a/browser/components/feeds/src/FeedConverter.js
+++ b/browser/components/feeds/src/FeedConverter.js
@@ -1,12 +1,12 @@
-# -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-# 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/.
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 
+/* 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/. */
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 Components.utils.import("resource://gre/modules/debug.js");
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cr = Components.results;
 
--- a/browser/components/feeds/src/Makefile.in
+++ b/browser/components/feeds/src/Makefile.in
@@ -17,22 +17,22 @@ USE_STATIC_LIBS = 1
 
 DEFINES += \
 	-DMOZ_APP_NAME=$(MOZ_APP_NAME) \
 	-DMOZ_MACBUNDLE_NAME=$(MOZ_MACBUNDLE_NAME) \
 	$(NULL)
 
 EXTRA_COMPONENTS = \
   BrowserFeeds.manifest \
+	FeedConverter.js \
+	WebContentConverter.js \
   $(NULL)
 
 EXTRA_PP_COMPONENTS = \
-	FeedConverter.js \
 	FeedWriter.js \
-	WebContentConverter.js \
 	$(NULL)
 
 
 CPPSRCS = nsFeedSniffer.cpp
 
 LOCAL_INCLUDES = -I$(srcdir)/../../build
 
 include $(topsrcdir)/config/rules.mk
--- a/browser/components/feeds/src/WebContentConverter.js
+++ b/browser/components/feeds/src/WebContentConverter.js
@@ -1,12 +1,12 @@
-# -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-# 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/.
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/. */
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cr = Components.results;
 
 function LOG(str) {
--- a/browser/components/migration/jar.mn
+++ b/browser/components/migration/jar.mn
@@ -1,7 +1,7 @@
 # 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/.
 
 browser.jar:
 *  content/browser/migration/migration.xul                    (content/migration.xul)
-*  content/browser/migration/migration.js                     (content/migration.js)
+   content/browser/migration/migration.js                     (content/migration.js)
--- a/browser/components/migration/src/Makefile.in
+++ b/browser/components/migration/src/Makefile.in
@@ -10,28 +10,34 @@ VPATH		= @srcdir@
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= migration
 LIBRARY_NAME	= migration_s
 
 FORCE_STATIC_LIB = 1
 USE_STATIC_LIBS = 1
 
-EXTRA_PP_COMPONENTS = \
+EXTRA_COMPONENTS = \
   ProfileMigrator.js \
+  FirefoxProfileMigrator.js \
+  $(NULL)
+
+EXTRA_PP_COMPONENTS = \
   ChromeProfileMigrator.js \
-  FirefoxProfileMigrator.js \
   $(NULL)
 
 ifeq ($(OS_ARCH),WINNT)
 CPPSRCS += nsIEHistoryEnumerator.cpp
 
-EXTRA_PP_COMPONENTS += IEProfileMigrator.js \
-                       SafariProfileMigrator.js \
+EXTRA_COMPONENTS += IEProfileMigrator.js \
+                    $(NULL)
+
+EXTRA_PP_COMPONENTS += SafariProfileMigrator.js \
                        $(NULL)
+
 DEFINES += -DHAS_IE_MIGRATOR -DHAS_SAFARI_MIGRATOR
 endif
 
 ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT))
 EXTRA_PP_COMPONENTS += SafariProfileMigrator.js \
                        $(NULL)
 DEFINES += -DHAS_SAFARI_MIGRATOR
 endif
--- a/browser/components/nsBrowserGlue.js
+++ b/browser/components/nsBrowserGlue.js
@@ -7,30 +7,31 @@ const Ci = Components.interfaces;
 const Cc = Components.classes;
 const Cr = Components.results;
 const Cu = Components.utils;
 
 const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
 
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
 Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource:///modules/SignInToWebsite.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "AddonManager",
                                   "resource://gre/modules/AddonManager.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "NetUtil",
                                   "resource://gre/modules/NetUtil.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "PlacesUtils",
                                   "resource://gre/modules/PlacesUtils.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "BookmarkHTMLUtils",
                                   "resource://gre/modules/BookmarkHTMLUtils.jsm");
 
-XPCOMUtils.defineLazyModuleGetter(this, "webappsUI", 
+XPCOMUtils.defineLazyModuleGetter(this, "webappsUI",
                                   "resource:///modules/webappsUI.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "PageThumbs",
                                   "resource:///modules/PageThumbs.jsm");
 
 XPCOMUtils.defineLazyModuleGetter(this, "PdfJs",
                                   "resource://pdf.js/PdfJs.jsm");
 
@@ -303,16 +304,17 @@ BrowserGlue.prototype = {
       this._idleService.removeIdleObserver(this, BOOKMARKS_BACKUP_IDLE_TIME);
     if (this._isPlacesInitObserver)
       os.removeObserver(this, "places-init-complete");
     if (this._isPlacesLockedObserver)
       os.removeObserver(this, "places-database-locked");
     if (this._isPlacesShutdownObserver)
       os.removeObserver(this, "places-shutdown");
     webappsUI.uninit();
+    SignInToWebsiteUX.uninit();
   },
 
   _onAppDefaults: function BG__onAppDefaults() {
     // apply distribution customizations (prefs)
     // other customizations are applied in _onProfileStartup()
     this._distributionCustomizer.applyPrefDefaults();
   },
 
@@ -332,16 +334,18 @@ BrowserGlue.prototype = {
     // handle any UI migration
     this._migrateUI();
 
     // Initialize webapps UI
     webappsUI.init();
 
     PageThumbs.init();
 
+    SignInToWebsiteUX.init();
+
     PdfJs.init();
 
     Services.obs.notifyObservers(null, "browser-ui-startup-complete", "");
   },
 
   // the first browser window has finished initializing
   _onFirstWindowLoaded: function BG__onFirstWindowLoaded() {
 #ifdef XP_WIN
--- a/browser/components/places/content/bookmarksPanel.js
+++ b/browser/components/places/content/bookmarksPanel.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/. */
 
 function init() {
   document.getElementById("bookmarks-view").place =
     "place:queryType=1&folder=" + window.top.PlacesUIUtils.allBookmarksFolderId;
 }
 
 function searchBookmarks(aSearchString) {
   var tree = document.getElementById('bookmarks-view');
--- a/browser/components/places/content/bookmarksPanel.xul
+++ b/browser/components/places/content/bookmarksPanel.xul
@@ -1,12 +1,12 @@
 <?xml version="1.0"?> <!-- -*- Mode: SGML; indent-tabs-mode: nil; -*- --> 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/content/places/places.css"?>
 <?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
 <?xul-overlay href="chrome://global/content/editMenuOverlay.xul"?>
 <?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
 
 <!DOCTYPE page SYSTEM "chrome://browser/locale/places/places.dtd">
--- a/browser/components/places/content/editBookmarkOverlay.xul
+++ b/browser/components/places/content/editBookmarkOverlay.xul
@@ -1,11 +1,11 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE overlay [
 <!ENTITY % editBookmarkOverlayDTD SYSTEM "chrome://browser/locale/places/editBookmarkOverlay.dtd">
 %editBookmarkOverlayDTD;
 ]>
 
 <?xml-stylesheet href="chrome://browser/skin/places/editBookmarkOverlay.css"?>
 <?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
--- a/browser/components/places/content/history-panel.js
+++ b/browser/components/places/content/history-panel.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 var gHistoryTree;
 var gSearchBox;
 var gHistoryGrouping = "";
 var gSearching = false;
 
 function HistorySidebarInit()
 {
--- a/browser/components/places/content/moveBookmarks.xul
+++ b/browser/components/places/content/moveBookmarks.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/"?>
 <?xml-stylesheet href="chrome://browser/skin/places/places.css"?>
 <?xml-stylesheet href="chrome://browser/content/places/places.css"?>
 
 <?xul-overlay href="chrome://browser/content/places/placesOverlay.xul"?>
 
 <!DOCTYPE window [
--- a/browser/components/places/content/placesOverlay.xul
+++ b/browser/components/places/content/placesOverlay.xul
@@ -1,11 +1,11 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE overlay [
 <!ENTITY % placesDTD SYSTEM "chrome://browser/locale/places/places.dtd">
 %placesDTD;
 <!ENTITY % editMenuOverlayDTD SYSTEM "chrome://global/locale/editMenuOverlay.dtd">
 %editMenuOverlayDTD;
 ]>
 
--- a/browser/components/places/content/tree.xml
+++ b/browser/components/places/content/tree.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <bindings id="placesTreeBindings"
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xbl="http://www.mozilla.org/xbl"
           xmlns:html="http://www.w3.org/1999/xhtml"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
 
   <binding id="places-tree" extends="chrome://global/content/bindings/tree.xml#tree">
--- a/browser/components/places/jar.mn
+++ b/browser/components/places/jar.mn
@@ -1,32 +1,32 @@
 # 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/.
 
 browser.jar:
 # Provide another URI for the bookmarkProperties dialog so we can persist the
 # attributes separately
-*   content/browser/places/bookmarkProperties2.xul       (content/bookmarkProperties.xul)
+    content/browser/places/bookmarkProperties2.xul       (content/bookmarkProperties.xul)
 *   content/browser/places/places.xul                    (content/places.xul) 
 *   content/browser/places/places.js                     (content/places.js)
     content/browser/places/places.css                    (content/places.css)
     content/browser/places/organizer.css                 (content/organizer.css)
-*   content/browser/places/bookmarkProperties.xul        (content/bookmarkProperties.xul)
-*   content/browser/places/bookmarkProperties.js         (content/bookmarkProperties.js)
-*   content/browser/places/placesOverlay.xul             (content/placesOverlay.xul)
+    content/browser/places/bookmarkProperties.xul        (content/bookmarkProperties.xul)
+    content/browser/places/bookmarkProperties.js         (content/bookmarkProperties.js)
+    content/browser/places/placesOverlay.xul             (content/placesOverlay.xul)
 *   content/browser/places/menu.xml                      (content/menu.xml)
-*   content/browser/places/tree.xml                      (content/tree.xml)
-*   content/browser/places/controller.js                 (content/controller.js)
-*   content/browser/places/treeView.js                   (content/treeView.js)
+    content/browser/places/tree.xml                      (content/tree.xml)
+    content/browser/places/controller.js                 (content/controller.js)
+    content/browser/places/treeView.js                   (content/treeView.js)
 *   content/browser/places/browserPlacesViews.js         (content/browserPlacesViews.js)
 # keep the Places version of the history sidebar at history/history-panel.xul 
 # to prevent having to worry about between versions of the browser
 *   content/browser/history/history-panel.xul            (content/history-panel.xul) 
-*   content/browser/places/history-panel.js              (content/history-panel.js)
+    content/browser/places/history-panel.js              (content/history-panel.js)
 # ditto for the bookmarks sidebar
-*   content/browser/bookmarks/bookmarksPanel.xul         (content/bookmarksPanel.xul)
-*   content/browser/bookmarks/bookmarksPanel.js          (content/bookmarksPanel.js)
+    content/browser/bookmarks/bookmarksPanel.xul         (content/bookmarksPanel.xul)
+    content/browser/bookmarks/bookmarksPanel.js          (content/bookmarksPanel.js)
 *   content/browser/bookmarks/sidebarUtils.js            (content/sidebarUtils.js)
-*   content/browser/places/moveBookmarks.xul             (content/moveBookmarks.xul)
-*   content/browser/places/moveBookmarks.js              (content/moveBookmarks.js)
-*   content/browser/places/editBookmarkOverlay.xul       (content/editBookmarkOverlay.xul)
-*   content/browser/places/editBookmarkOverlay.js        (content/editBookmarkOverlay.js)
+    content/browser/places/moveBookmarks.xul             (content/moveBookmarks.xul)
+    content/browser/places/moveBookmarks.js              (content/moveBookmarks.js)
+    content/browser/places/editBookmarkOverlay.xul       (content/editBookmarkOverlay.xul)
+    content/browser/places/editBookmarkOverlay.js        (content/editBookmarkOverlay.js)
--- a/browser/components/preferences/advanced-scripts.xul
+++ b/browser/components/preferences/advanced-scripts.xul
@@ -1,14 +1,14 @@
 <?xml version="1.0"?>
 
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+<!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- -->
+<!-- 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/. -->
 
 <!DOCTYPE prefwindow SYSTEM "chrome://browser/locale/preferences/advanced-scripts.dtd">
 
 <?xml-stylesheet href="chrome://global/skin/"?>
 
 <prefwindow id="AdvancedJSDialog" type="child"
             xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
             title="&advancedJSDialog.title;"
--- a/browser/components/preferences/applicationManager.xul
+++ b/browser/components/preferences/applicationManager.xul
@@ -1,12 +1,12 @@
 <?xml version="1.0"?>
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/"?>
 
 <!DOCTYPE dialog SYSTEM "chrome://browser/locale/preferences/applicationManager.dtd">
 
 <dialog id="appManager"
         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
         buttons="accept,cancel"
--- a/browser/components/preferences/applications.xul
+++ b/browser/components/preferences/applications.xul
@@ -1,16 +1,14 @@
 <?xml version="1.0"?>
 
-<!--
-# -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-# 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/.
--->
+<!-- -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- -->
+<!-- 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/. -->
 
 <!DOCTYPE overlay [
   <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
   <!ENTITY % applicationsDTD SYSTEM "chrome://browser/locale/preferences/applications.dtd">
   %brandDTD;
   %applicationsDTD;
 ]>
 
--- a/browser/components/preferences/connection.js
+++ b/browser/components/preferences/connection.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 var gConnectionsDialog = {
   beforeAccept: function ()
   {
     var proxyTypePref = document.getElementById("network.proxy.type");
     if (proxyTypePref.value == 2) {
       this.doAutoconfigURLFixup();
       return true;
--- a/browser/components/preferences/content.js
+++ b/browser/components/preferences/content.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 var gContentPane = {
 
   /**
    * Initializes the fonts dropdowns displayed in this pane.
    */
   init: function ()
   {
--- a/browser/components/preferences/content.xul
+++ b/browser/components/preferences/content.xul
@@ -1,14 +1,14 @@
 <?xml version="1.0"?>
 
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+<!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- -->
+<!-- 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/. -->
 
 <!DOCTYPE overlay [
   <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
   <!ENTITY % contentDTD SYSTEM "chrome://browser/locale/preferences/content.dtd">
   %brandDTD;
   %contentDTD;
 ]>
 
--- a/browser/components/preferences/cookies.js
+++ b/browser/components/preferences/cookies.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 const nsICookie = Components.interfaces.nsICookie;
 
 var gCookiesWindow = {
   _cm               : Components.classes["@mozilla.org/cookiemanager;1"]
                                 .getService(Components.interfaces.nsICookieManager),
   _ds               : Components.classes["@mozilla.org/intl/scriptabledateformat;1"]
                                 .getService(Components.interfaces.nsIScriptableDateFormat),
@@ -567,64 +567,64 @@ var gCookiesWindow = {
       blockFutureCookies = psvc.getBoolPref("network.cookie.blockFutureCookies");
     for (var i = 0; i < deleteItems.length; ++i) {
       var item = deleteItems[i];
       this._cm.remove(item.host, item.name, item.path, blockFutureCookies);
     }
   },
 
   deleteCookie: function () {
-#   // Selection Notes
-#   // - Selection always moves to *NEXT* adjacent item unless item
-#   //   is last child at a given level in which case it moves to *PREVIOUS*
-#   //   item
-#   //
-#   // Selection Cases (Somewhat Complicated)
-#   //
-#   // 1) Single cookie selected, host has single child
-#   //    v cnn.com
-#   //    //// cnn.com ///////////// goksdjf@ ////
-#   //    > atwola.com
-#   //
-#   //    Before SelectedIndex: 1   Before RowCount: 3
-#   //    After  SelectedIndex: 0   After  RowCount: 1
-#   //
-#   // 2) Host selected, host open
-#   //    v goats.com ////////////////////////////
-#   //         goats.com             sldkkfjl
-#   //         goat.scom             flksj133
-#   //    > atwola.com
-#   //
-#   //    Before SelectedIndex: 0   Before RowCount: 4
-#   //    After  SelectedIndex: 0   After  RowCount: 1
-#   //
-#   // 3) Host selected, host closed
-#   //    > goats.com ////////////////////////////
-#   //    > atwola.com
-#   //
-#   //    Before SelectedIndex: 0   Before RowCount: 2
-#   //    After  SelectedIndex: 0   After  RowCount: 1
-#   //
-#   // 4) Single cookie selected, host has many children
-#   //    v goats.com
-#   //         goats.com             sldkkfjl
-#   //    //// goats.com /////////// flksjl33 ////
-#   //    > atwola.com
-#   //
-#   //    Before SelectedIndex: 2   Before RowCount: 4
-#   //    After  SelectedIndex: 1   After  RowCount: 3
-#   //
-#   // 5) Single cookie selected, host has many children
-#   //    v goats.com
-#   //    //// goats.com /////////// flksjl33 ////
-#   //         goats.com             sldkkfjl
-#   //    > atwola.com
-#   //
-#   //    Before SelectedIndex: 1   Before RowCount: 4
-#   //    After  SelectedIndex: 1   After  RowCount: 3
+    // Selection Notes
+    // - Selection always moves to *NEXT* adjacent item unless item
+    //   is last child at a given level in which case it moves to *PREVIOUS*
+    //   item
+    //
+    // Selection Cases (Somewhat Complicated)
+    //
+    // 1) Single cookie selected, host has single child
+    //    v cnn.com
+    //    //// cnn.com ///////////// goksdjf@ ////
+    //    > atwola.com
+    //
+    //    Before SelectedIndex: 1   Before RowCount: 3
+    //    After  SelectedIndex: 0   After  RowCount: 1
+    //
+    // 2) Host selected, host open
+    //    v goats.com ////////////////////////////
+    //         goats.com             sldkkfjl
+    //         goat.scom             flksj133
+    //    > atwola.com
+    //
+    //    Before SelectedIndex: 0   Before RowCount: 4
+    //    After  SelectedIndex: 0   After  RowCount: 1
+    //
+    // 3) Host selected, host closed
+    //    > goats.com ////////////////////////////
+    //    > atwola.com
+    //
+    //    Before SelectedIndex: 0   Before RowCount: 2
+    //    After  SelectedIndex: 0   After  RowCount: 1
+    //
+    // 4) Single cookie selected, host has many children
+    //    v goats.com
+    //         goats.com             sldkkfjl
+    //    //// goats.com /////////// flksjl33 ////
+    //    > atwola.com
+    //
+    //    Before SelectedIndex: 2   Before RowCount: 4
+    //    After  SelectedIndex: 1   After  RowCount: 3
+    //
+    // 5) Single cookie selected, host has many children
+    //    v goats.com
+    //    //// goats.com /////////// flksjl33 ////
+    //         goats.com             sldkkfjl
+    //    > atwola.com
+    //
+    //    Before SelectedIndex: 1   Before RowCount: 4
+    //    After  SelectedIndex: 1   After  RowCount: 3
     var seln = this._view.selection;
     var tbo = this._tree.treeBoxObject;
 
     if (seln.count < 1) return;
 
     var nextSelected = 0;
     var rowCountImpact = 0;
     var deleteItems = [];
--- a/browser/components/preferences/fonts.js
+++ b/browser/components/preferences/fonts.js
@@ -1,14 +1,14 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
-# browser.display.languageList LOCK ALL when LOCKED
+// browser.display.languageList LOCK ALL when LOCKED
 
 const kDefaultFontType          = "font.default.%LANG%";
 const kFontNameFmtSerif         = "font.name.serif.%LANG%";
 const kFontNameFmtSansSerif     = "font.name.sans-serif.%LANG%";
 const kFontNameFmtMonospace     = "font.name.monospace.%LANG%";
 const kFontNameListFmtSerif     = "font.name-list.serif.%LANG%";
 const kFontNameListFmtSansSerif = "font.name-list.sans-serif.%LANG%";
 const kFontNameListFmtMonospace = "font.name-list.monospace.%LANG%";
--- a/browser/components/preferences/in-content/jar.mn
+++ b/browser/components/preferences/in-content/jar.mn
@@ -9,16 +9,16 @@ browser.jar:
 *  content/browser/preferences/in-content/main.xul
    content/browser/preferences/in-content/main.js
 *  content/browser/preferences/in-content/tabs.xul
 *  content/browser/preferences/in-content/tabs.js
    content/browser/preferences/in-content/privacy.xul
    content/browser/preferences/in-content/privacy.js
 *  content/browser/preferences/in-content/advanced.xul
 *  content/browser/preferences/in-content/advanced.js
-*  content/browser/preferences/in-content/applications.xul
+   content/browser/preferences/in-content/applications.xul
 *  content/browser/preferences/in-content/applications.js
    content/browser/preferences/in-content/content.xul
    content/browser/preferences/in-content/content.js
    content/browser/preferences/in-content/sync.xul
    content/browser/preferences/in-content/sync.js
    content/browser/preferences/in-content/security.xul
    content/browser/preferences/in-content/security.js
--- a/browser/components/preferences/jar.mn
+++ b/browser/components/preferences/jar.mn
@@ -1,47 +1,47 @@
 # 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/.
 
 browser.jar:
-*   content/browser/preferences/aboutPermissions.xul
-*   content/browser/preferences/aboutPermissions.js
-*   content/browser/preferences/aboutPermissions.css
-*   content/browser/preferences/aboutPermissions.xml
+    content/browser/preferences/aboutPermissions.xul
+    content/browser/preferences/aboutPermissions.js
+    content/browser/preferences/aboutPermissions.css
+    content/browser/preferences/aboutPermissions.xml
 *   content/browser/preferences/advanced.xul
 *   content/browser/preferences/advanced.js
-*   content/browser/preferences/advanced-scripts.xul
-*   content/browser/preferences/applications.xul
+    content/browser/preferences/advanced-scripts.xul
+    content/browser/preferences/applications.xul
 *   content/browser/preferences/applications.js
-*   content/browser/preferences/applicationManager.xul
+    content/browser/preferences/applicationManager.xul
 *   content/browser/preferences/applicationManager.js
 *   content/browser/preferences/colors.xul
 *   content/browser/preferences/cookies.xul
-*   content/browser/preferences/cookies.js
-*   content/browser/preferences/content.xul
-*   content/browser/preferences/content.js
+    content/browser/preferences/cookies.js
+    content/browser/preferences/content.xul
+    content/browser/preferences/content.js
 *   content/browser/preferences/connection.xul
-*   content/browser/preferences/connection.js
+    content/browser/preferences/connection.js
 *   content/browser/preferences/fonts.xul
-*   content/browser/preferences/fonts.js
-*   content/browser/preferences/handlers.xml
-*   content/browser/preferences/handlers.css
+    content/browser/preferences/fonts.js
+    content/browser/preferences/handlers.xml
+    content/browser/preferences/handlers.css
 *   content/browser/preferences/languages.xul
-*   content/browser/preferences/languages.js
+    content/browser/preferences/languages.js
 *   content/browser/preferences/main.xul
-*   content/browser/preferences/main.js
+    content/browser/preferences/main.js
 *   content/browser/preferences/permissions.xul
-*   content/browser/preferences/permissions.js
+    content/browser/preferences/permissions.js
 *   content/browser/preferences/preferences.xul
-*   content/browser/preferences/privacy.xul
-*   content/browser/preferences/privacy.js
-*   content/browser/preferences/sanitize.xul
-*   content/browser/preferences/security.xul
-*   content/browser/preferences/security.js
-*   content/browser/preferences/selectBookmark.xul
-*   content/browser/preferences/selectBookmark.js
+    content/browser/preferences/privacy.xul
+    content/browser/preferences/privacy.js
+    content/browser/preferences/sanitize.xul
+    content/browser/preferences/security.xul
+    content/browser/preferences/security.js
+    content/browser/preferences/selectBookmark.xul
+    content/browser/preferences/selectBookmark.js
 #ifdef MOZ_SERVICES_SYNC
-*   content/browser/preferences/sync.xul
-*   content/browser/preferences/sync.js
+    content/browser/preferences/sync.xul
+    content/browser/preferences/sync.js
 #endif
 *   content/browser/preferences/tabs.xul
 *   content/browser/preferences/tabs.js
--- a/browser/components/preferences/languages.js
+++ b/browser/components/preferences/languages.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 var gLanguagesDialog = {
 
   _availableLanguagesList : [],
   _acceptLanguages        : { },
   
   _selectedItemID         : null,
   
--- a/browser/components/preferences/main.js
+++ b/browser/components/preferences/main.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* 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/. */
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 XPCOMUtils.defineLazyModuleGetter(this, "DownloadsCommon",
                                   "resource:///modules/DownloadsCommon.jsm");
 
 var gMainPane = {
   _pane: null,
 
--- a/browser/components/preferences/permissions.js
+++ b/browser/components/preferences/permissions.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 const nsIPermissionManager = Components.interfaces.nsIPermissionManager;
 const nsICookiePermission = Components.interfaces.nsICookiePermission;
 
 function Permission(host, rawHost, type, capability, perm) 
 {
   this.host = host;
   this.rawHost = rawHost;
--- a/browser/components/preferences/privacy.js
+++ b/browser/components/preferences/privacy.js
@@ -1,14 +1,12 @@
-/*
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
-*/
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 var gPrivacyPane = {
 
   /**
    * Whether the use has selected the auto-start private browsing mode in the UI.
    */
--- a/browser/components/preferences/privacy.xul
+++ b/browser/components/preferences/privacy.xul
@@ -1,14 +1,14 @@
 <?xml version="1.0"?>
 
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+<!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- -->
+<!-- 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/. -->
 
 <!DOCTYPE overlay [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
 <!ENTITY % privacyDTD SYSTEM "chrome://browser/locale/preferences/privacy.dtd">
 %brandDTD;
 %privacyDTD;
 ]>
 
--- a/browser/components/preferences/sanitize.xul
+++ b/browser/components/preferences/sanitize.xul
@@ -1,14 +1,14 @@
 <?xml version="1.0"?>
 
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+<!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- -->
+<!-- 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/"?>
 <?xml-stylesheet href="chrome://browser/skin/preferences/preferences.css" type="text/css"?> 
 
 <!DOCTYPE dialog [
   <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
   <!ENTITY % sanitizeDTD SYSTEM "chrome://browser/locale/sanitize.dtd">
   %brandDTD;
--- a/browser/components/preferences/security.js
+++ b/browser/components/preferences/security.js
@@ -1,12 +1,12 @@
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 var gSecurityPane = {
   _pane: null,
 
   /**
    * Initializes master password UI.
    */
   init: function ()
--- a/browser/components/preferences/security.xul
+++ b/browser/components/preferences/security.xul
@@ -1,14 +1,14 @@
 <?xml version="1.0"?>
 
-# -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+<!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- -->
+<!-- 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/. -->
 
 <!DOCTYPE overlay [
   <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
   <!ENTITY % securityDTD SYSTEM "chrome://browser/locale/preferences/security.dtd">
   %brandDTD;
   %securityDTD;
 ]>
 
--- a/browser/components/preferences/sync.xul
+++ b/browser/components/preferences/sync.xul
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <!DOCTYPE overlay [
 <!ENTITY % brandDTD SYSTEM "chrome://branding/locale/brand.dtd">
 <!ENTITY % syncBrandDTD SYSTEM "chrome://browser/locale/syncBrand.dtd">
 <!ENTITY % syncDTD SYSTEM "chrome://browser/locale/preferences/sync.dtd">
 %brandDTD;
 %syncBrandDTD;
 %syncDTD;
--- a/browser/components/safebrowsing/content/report-phishing-overlay.xul
+++ b/browser/components/safebrowsing/content/report-phishing-overlay.xul
@@ -1,12 +1,13 @@
 <?xml version="1.0"?>
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
+
 <!DOCTYPE overlay [
 <!ENTITY % reportphishDTD SYSTEM "chrome://browser/locale/safebrowsing/report-phishing.dtd">
 %reportphishDTD;
 <!ENTITY % safebrowsingDTD SYSTEM "chrome://browser/locale/safebrowsing/phishing-afterload-warning-message.dtd">
 %safebrowsingDTD;
 ]>
 
 <overlay id="reportPhishingMenuOverlay"
--- a/browser/components/safebrowsing/jar.mn
+++ b/browser/components/safebrowsing/jar.mn
@@ -1,8 +1,8 @@
 # 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/.
 
 browser.jar:
-* content/browser/safebrowsing/report-phishing-overlay.xul     (content/report-phishing-overlay.xul)
+  content/browser/safebrowsing/report-phishing-overlay.xul     (content/report-phishing-overlay.xul)
   content/browser/safebrowsing/blockedSite.xhtml               (content/blockedSite.xhtml)
 % overlay chrome://browser/content/browser.xul         chrome://browser/content/safebrowsing/report-phishing-overlay.xul
--- a/browser/components/search/content/engineManager.js
+++ b/browser/components/search/content/engineManager.js
@@ -1,11 +1,11 @@
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+/* This 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/. */
 
 Components.utils.import("resource://gre/modules/Services.jsm");
 
 const Ci = Components.interfaces;
 const Cc = Components.classes;
 
 const ENGINE_FLAVOR = "text/x-moz-search-engine";
 
--- a/browser/components/search/content/engineManager.xul
+++ b/browser/components/search/content/engineManager.xul
@@ -1,12 +1,12 @@
 <?xml version="1.0"?>
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <?xml-stylesheet href="chrome://global/skin/"?>
 <?xml-stylesheet href="chrome://browser/skin/engineManager.css"?>
 
 <!DOCTYPE dialog SYSTEM "chrome://browser/locale/engineManager.dtd">
 
 <dialog id="engineManager"
         xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
--- a/browser/components/search/jar.mn
+++ b/browser/components/search/jar.mn
@@ -1,9 +1,9 @@
 # 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/.
 
 browser.jar:
 *       content/browser/search/search.xml                           (content/search.xml)
         content/browser/search/searchbarBindings.css                (content/searchbarBindings.css)
-*       content/browser/search/engineManager.xul                    (content/engineManager.xul)
-*       content/browser/search/engineManager.js                     (content/engineManager.js)
+        content/browser/search/engineManager.xul                    (content/engineManager.xul)
+        content/browser/search/engineManager.js                     (content/engineManager.js)
--- a/browser/components/sessionstore/src/Makefile.in
+++ b/browser/components/sessionstore/src/Makefile.in
@@ -7,22 +7,19 @@ topsrcdir = @top_srcdir@
 srcdir    = @srcdir@
 VPATH     = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/config.mk
 
 EXTRA_COMPONENTS = \
   nsSessionStore.manifest \
-  $(NULL)
-
-EXTRA_PP_COMPONENTS = \
 	nsSessionStore.js \
 	nsSessionStartup.js \
-	$(NULL)
+  $(NULL)
 
 JS_MODULES_PATH := $(FINAL_TARGET)/modules/sessionstore
 
 EXTRA_JS_MODULES := \
   DocumentUtils.jsm \
   SessionStorage.jsm \
   XPathGenerator.jsm \
   $(NULL)
--- a/browser/components/sessionstore/src/nsSessionStartup.js
+++ b/browser/components/sessionstore/src/nsSessionStartup.js
@@ -1,40 +1,38 @@
-/*
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
-*/
+/* This 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/. */
 
 /**
-# * Session Storage and Restoration
-# *
-# * Overview
-# * This service reads user's session file at startup, and makes a determination
-# * as to whether the session should be restored. It will restore the session
-# * under the circumstances described below.  If the auto-start Private Browsing
-# * mode is active, however, the session is never restored.
-# *
-# * Crash Detection
-# * The session file stores a session.state property, that
-# * indicates whether the browser is currently running. When the browser shuts
-# * down, the field is changed to "stopped". At startup, this field is read, and
-# * if its value is "running", then it's assumed that the browser had previously
-# * crashed, or at the very least that something bad happened, and that we should
-# * restore the session.
-# *
-# * Forced Restarts
-# * In the event that a restart is required due to application update or extension
-# * installation, set the browser.sessionstore.resume_session_once pref to true,
-# * and the session will be restored the next time the browser starts.
-# *
-# * Always Resume
-# * This service will always resume the session if the integer pref
-# * browser.startup.page is set to 3.
-*/
+ * Session Storage and Restoration
+ *
+ * Overview
+ * This service reads user's session file at startup, and makes a determination
+ * as to whether the session should be restored. It will restore the session
+ * under the circumstances described below.  If the auto-start Private Browsing
+ * mode is active, however, the session is never restored.
+ *
+ * Crash Detection
+ * The session file stores a session.state property, that
+ * indicates whether the browser is currently running. When the browser shuts
+ * down, the field is changed to "stopped". At startup, this field is read, and
+ * if its value is "running", then it's assumed that the browser had previously
+ * crashed, or at the very least that something bad happened, and that we should
+ * restore the session.
+ *
+ * Forced Restarts
+ * In the event that a restart is required due to application update or extension
+ * installation, set the browser.sessionstore.resume_session_once pref to true,
+ * and the session will be restored the next time the browser starts.
+ *
+ * Always Resume
+ * This service will always resume the session if the integer pref
+ * browser.startup.page is set to 3.
+ */
 
 /* :::::::: Constants and Helpers ::::::::::::::: */
 
 const Cc = Components.classes;
 const Ci = Components.interfaces;
 const Cr = Components.results;
 const Cu = Components.utils;
 Cu.import("resource://gre/modules/XPCOMUtils.jsm");
--- a/browser/components/sidebar/Makefile.in
+++ b/browser/components/sidebar/Makefile.in
@@ -5,13 +5,15 @@
 
 DEPTH		= @DEPTH@
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
-EXTRA_COMPONENTS = nsSidebar.manifest
-EXTRA_PP_COMPONENTS = nsSidebar.js
+EXTRA_COMPONENTS = \
+  nsSidebar.manifest \
+  nsSidebar.js \
+  $(NULL)
 
 include $(topsrcdir)/config/rules.mk
 
--- a/browser/components/sidebar/nsSidebar.js
+++ b/browser/components/sidebar/nsSidebar.js
@@ -1,12 +1,12 @@
-# -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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/. */
 
 Components.utils.import("resource://gre/modules/Services.jsm");
 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
 
 const DEBUG = false; /* set to false to suppress debug messages */
 
 const SIDEBAR_CONTRACTID        = "@mozilla.org/sidebar;1";
 const SIDEBAR_CID               = Components.ID("{22117140-9c6e-11d3-aaf1-00805f8a4905}");
--- a/browser/components/tabview/test/browser_tabview_bug587503.js
+++ b/browser/components/tabview/test/browser_tabview_bug587503.js
@@ -1,186 +1,107 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 function test() {
   waitForExplicitFinish();
-  requestLongerTimeout(2);
+
+  function moveTabOutOfGroup(aTab, aGroup, aCW, aCallback) {
+    let tabPos = aTab.getBounds().center();
+    let groupPos = aGroup.getBounds();
+    let groupPosX = (groupPos.left + groupPos.right) / 2;
+    let groupPosY = groupPos.bottom + 200;
+    let offsetX = Math.round(groupPosX - tabPos.x);
+    let offsetY = Math.round(groupPosY - tabPos.y);
+
+    simulateDragDrop(aTab, offsetX, offsetY, aCW);
+  }
+
+  function moveTabInGroup(aTab, aIndexTo, aGroup, aCW) {
+    let tabTo = aGroup.getChild(aIndexTo);
+    let tabPos = aTab.getBounds().center();
+    let tabToPos = tabTo.getBounds().center();
+    let offsetX = Math.round(tabToPos.x - tabPos.x);
+    let offsetY = Math.round(tabToPos.y - tabPos.y);
+
+    simulateDragDrop(aTab, offsetX, offsetY, aCW);
+  }
+
+  function getTabNumbers(aGroup) {
+    return aGroup.getChildren().map(function (child) {
+      let url = child.tab.linkedBrowser.currentURI.spec;
+      return url.replace("about:blank#", "");
+    }).join(",");
+  }
+
+  function moveTabs(aGroup, aCW) {
+    // Test 1: Move the last tab to the third position.
+    let tab = aGroup.getChild(6);
+    moveTabInGroup(tab, 2, aGroup, aCW);
+    is(getTabNumbers(aGroup), "0,1,6,2,3,4,5", "Validate tab positions in test 1.");
 
-  newWindowWithTabView(onTabViewWindowLoaded);
+    // Test 2: Move the second tab to the end of the list.
+    tab = aGroup.getChild(1);
+    moveTabInGroup(tab, 6, aGroup, aCW);
+    is(getTabNumbers(aGroup), "0,6,2,3,4,5,1", "Validate tab positions in test 2.");
+
+    // Test 3: Move the fifth tab outside the group.
+    tab = aGroup.getChild(4);
+    moveTabOutOfGroup(tab, aGroup, aCW);
+    is(getTabNumbers(aGroup), "0,6,2,3,5,1", "Validate tab positions in test 3.");
+    is(aCW.GroupItems.groupItems.length, 3, "Validate group count in test 3.");
+
+    // Test 4: Move the fifth tab back into the group, on the second row.
+    waitForTransition(tab, function() {
+      moveTabInGroup(tab, 4, aGroup, aCW);
+      is(getTabNumbers(aGroup), "0,6,2,3,4,5,1", "Validate tab positions in test 4.");
+      is(aCW.GroupItems.groupItems.length, 2, "Validate group count in test 4.");
+      closeGroupItem(aGroup, function() { hideTabView(finish) });
+    });
+  }
+
+  function createGroup(win) {
+    registerCleanupFunction(function() win.close());
+    let cw = win.TabView.getContentWindow();
+    let group = createGroupItemWithTabs(win, 400, 430, 100, [
+      "about:blank#0", "about:blank#1", "about:blank#2", "about:blank#3",
+      "about:blank#4", "about:blank#5", "about:blank#6"
+    ]);
+    let groupSize = group.getChildren().length;
+
+    is(cw.GroupItems.groupItems.length, 2, "Validate group count in tab view.");
+    ok(!group.shouldStack(groupSize), "Check that group should not stack.");
+    is(group._columns, 3, "Check the there should be three columns.");
+
+    moveTabs(group, cw);
+  }
+
+  newWindowWithTabView(createGroup);
 }
 
-function onTabViewWindowLoaded(win) {
-  ok(win.TabView.isVisible(), "Tab View is visible");
-
-  let contentWindow = win.document.getElementById("tab-view").contentWindow;
-  let [originalTab] = win.gBrowser.visibleTabs;
-
-  let currentGroup = contentWindow.GroupItems.getActiveGroupItem();
-
-  // Create a group and make it active
-  let box = new contentWindow.Rect(100, 100, 400, 430);
-  let group = new contentWindow.GroupItem([], { bounds: box });
-  ok(group.isEmpty(), "This group is empty");
-  contentWindow.UI.setActive(group);
-  
-  // Create a bunch of tabs in the group
-  let tabs = [];
-  tabs.push(win.gBrowser.loadOneTab("about:blank#0", {inBackground: true}));
-  tabs.push(win.gBrowser.loadOneTab("about:blank#1", {inBackground: true}));
-  tabs.push(win.gBrowser.loadOneTab("about:blank#2", {inBackground: true}));
-  tabs.push(win.gBrowser.loadOneTab("about:blank#3", {inBackground: true}));
-  tabs.push(win.gBrowser.loadOneTab("about:blank#4", {inBackground: true}));
-  tabs.push(win.gBrowser.loadOneTab("about:blank#5", {inBackground: true}));
-  tabs.push(win.gBrowser.loadOneTab("about:blank#6", {inBackground: true}));
-
-  ok(!group.shouldStack(group._children.length), "Group should not stack.");
-  is(group._columns, 3, "There should be three columns.");
-  
-  // STAGE 1: move the last tab to the third position
-  let currentTarget = tabs[6]._tabViewTabItem;
-  let currentPos = currentTarget.getBounds().center();
-  let targetPos = tabs[2]._tabViewTabItem.getBounds().center();
-  let vector = new contentWindow.Point(targetPos.x - currentPos.x,
-                                       targetPos.y - currentPos.y);
-  checkDropIndexAndDropSpace(currentTarget, group, vector.x, vector.y, contentWindow,
-                             function(index, dropSpaceActiveValues) {
-    // Now: 0, 1, 6, 2, 3, 4, 5
-    is(index, 2, "Tab 6 is now in the third position");
-    is(dropSpaceActiveValues[0], true, "dropSpace was always showing");
+function simulateDragDrop(aTab, aOffsetX, aOffsetY, aCW) {
+  let target = aTab.container;
+  let rect = target.getBoundingClientRect();
+  let startX = (rect.right - rect.left) / 2;
+  let startY = (rect.bottom - rect.top) / 2;
+  let steps = 2;
+  let incrementX = aOffsetX / steps;
+  let incrementY = aOffsetY / steps;
 
-    // STAGE 2: move the second tab to the end of the list
-    let currentTarget = tabs[1]._tabViewTabItem;
-    let currentPos = currentTarget.getBounds().center();
-    // pick a point in that empty bottom part of the group
-    let groupBounds = group.getBounds();
-    let bottomPos = new contentWindow.Point(
-                      (groupBounds.left + groupBounds.right) / 2,
-                      groupBounds.bottom - 15);
-    let vector = new contentWindow.Point(bottomPos.x - currentPos.x,
-                                         bottomPos.y - currentPos.y);
-    checkDropIndexAndDropSpace(currentTarget, group, vector.x, vector.y, contentWindow,
-                               function(index, dropSpaceActiveValues) {
-      // Now: 0, 6, 2, 3, 4, 5, 1
-      is(index, 6, "Tab 1 is now at the end of the group");
-      is(dropSpaceActiveValues[0], true, "dropSpace was always showing");
-    
-      // STAGE 3: move the fifth tab outside the group
-      // Note: there should be room below the active group...
-      let currentTarget = tabs[4]._tabViewTabItem;
-      let currentPos = currentTarget.getBounds().center();
-      // Pick a point below the group.
-      let belowPos = new contentWindow.Point(
-                        (groupBounds.left + groupBounds.right) / 2,
-                        groupBounds.bottom + 300);
-      let vector = new contentWindow.Point(belowPos.x - currentPos.x,
-                                           belowPos.y - currentPos.y);
-      checkDropIndexAndDropSpace(currentTarget, group, vector.x, vector.y, contentWindow,
-                                 function(index, dropSpaceActiveValues) {
-        // Now: 0, 6, 2, 3, 5, 1
-        is(index, -1, "Tab 5 is no longer in the group");
-        contentWindow.Utils.log('dropSpaceActiveValues',dropSpaceActiveValues);
-        is(dropSpaceActiveValues[0], true, "The group began by showing a dropSpace");
-        is(dropSpaceActiveValues[dropSpaceActiveValues.length - 1], false, "In the end, the group was not showing a dropSpace");
-        
-        // We wrap this in a setTimeout with 1000ms delay in order to wait for the
-        // tab to resize, as it does after we drop it in stage 3 outside of the group.
-        setTimeout(function() {
-          // STAGE 4: move the fifth tab back into the group, on the second row.
-          let currentTarget = tabs[4]._tabViewTabItem;
-          let currentPos = currentTarget.getBounds().center();
-          let targetPos = tabs[5]._tabViewTabItem.getBounds().center();
-          // contentWindow.Utils.log(targetPos, currentPos);
-          vector = new contentWindow.Point(targetPos.x - currentPos.x,
-                                               targetPos.y - currentPos.y);
-          // Call with time = 4000
-          checkDropIndexAndDropSpace(currentTarget, group, vector.x, vector.y, contentWindow,
-                                     function(index, dropSpaceActiveValues) {
+  EventUtils.synthesizeMouse(
+    target, startX, startY, { type: "mousedown" }, aCW);
+  for (let i = 1; i <= steps; i++) {
+    EventUtils.synthesizeMouse(
+      target, incrementX + startX, incrementY + startY,
+      { type: "mousemove" }, aCW);
+  };
+  EventUtils.synthesizeMouseAtCenter(target, { type: "mouseup" }, aCW);
+}
 
-            is(group._columns, 3, "There should be three columns.");
-
-            // Now: 0, 6, 2, 3, 4, 5, 1
-            is(index, 4, "Tab 5 is back and again the fifth tab.");
-            contentWindow.Utils.log('dropSpaceActiveValues',dropSpaceActiveValues);
-            is(dropSpaceActiveValues[0], false, "The group began by not showing a dropSpace");
-            is(dropSpaceActiveValues[dropSpaceActiveValues.length - 1], true, "In the end, the group was showing a dropSpace");
-            
-            // Close the window and we're done!
-            win.close();
-            finish();
-          }, 10000, false);
-        }, 2000);
-        
-      });
-    
-    });
-
+function waitForTransition(aTab, aCallback) {
+  let groupContainer = aTab.parent.container;
+  groupContainer.addEventListener("transitionend", function onTransitionEnd(aEvent) {
+    if (aEvent.target == groupContainer) {
+      groupContainer.removeEventListener("transitionend", onTransitionEnd);
+      executeSoon(aCallback);
+    }
   });
 }
-
-function simulateSlowDragDrop(srcElement, offsetX, offsetY, contentWindow, time) {
-  // enter drag mode
-  let dataTransfer;
-
-  let bounds = srcElement.getBoundingClientRect();
-
-  EventUtils.synthesizeMouse(
-    srcElement, 2, 2, { type: "mousedown" }, contentWindow);
-  let event = contentWindow.document.createEvent("DragEvents");
-  event.initDragEvent(
-    "dragenter", true, true, contentWindow, 0, 0, 0, 0, 0,
-    false, false, false, false, 1, null, dataTransfer);
-  srcElement.dispatchEvent(event);
-  
-  let steps = 20;
-  
-  // drag over
-  let moveIncremental = function moveIncremental(i, steps) {
-    // calculate how much to move
-    let offsetXDiff = Math.round(i * offsetX / steps) - Math.round((i - 1) * offsetX / steps);
-    let offsetYDiff = Math.round(i * offsetY / steps) - Math.round((i - 1) * offsetY / steps);
-    // contentWindow.Utils.log('step', offsetXDiff, offsetYDiff);
-    // simulate mousemove
-    EventUtils.synthesizeMouse(
-      srcElement, offsetXDiff + 2, offsetYDiff + 2,
-      { type: "mousemove" }, contentWindow);
-    // simulate dragover
-    let event = contentWindow.document.createEvent("DragEvents");
-    event.initDragEvent(
-      "dragover", true, true, contentWindow, 0, 0, 0, 0, 0,
-      false, false, false, false, 0, null, dataTransfer);
-    srcElement.dispatchEvent(event);
-    let bounds = srcElement.getBoundingClientRect();
-    // contentWindow.Utils.log(i, 'center', bounds.left + bounds.width / 2, bounds.top + bounds.height / 2);
-  };
-  for (let i = 1; i <= steps; i++)
-    setTimeout(moveIncremental, i / (steps + 1) * time, i, steps);
-
-  // drop
-  let finalDrop = function finalDrop() {
-    EventUtils.synthesizeMouseAtCenter(srcElement, { type: "mouseup" }, contentWindow);
-    event = contentWindow.document.createEvent("DragEvents");
-    event.initDragEvent(
-      "drop", true, true, contentWindow, 0, 0, 0, 0, 0,
-      false, false, false, false, 0, null, dataTransfer);
-    srcElement.dispatchEvent(event);
-    contentWindow.iQ(srcElement).css({border: 'green 1px solid'});
-  }
-  setTimeout(finalDrop, time);
-}
-
-function checkDropIndexAndDropSpace(item, group, offsetX, offsetY, contentWindow, callback, time) {
-  contentWindow.UI.setActive(item);
-  let dropSpaceActiveValues = [];
-  let recordDropSpaceValue = function() {
-    dropSpaceActiveValues.push(group._dropSpaceActive);
-  };
-
-  let onDrop = function() {
-    item.container.removeEventListener('dragover', recordDropSpaceValue, false);
-    item.container.removeEventListener('drop', onDrop, false);
-    let index = group._children.indexOf(item);
-    callback(index, dropSpaceActiveValues);
-  };
-  item.container.addEventListener('dragover', recordDropSpaceValue, false);
-  item.container.addEventListener('drop', onDrop, false);
-  simulateSlowDragDrop(item.container, offsetX, offsetY, contentWindow, time || 1000);
-}
--- a/browser/components/tabview/test/browser_tabview_bug626455.js
+++ b/browser/components/tabview/test/browser_tabview_bug626455.js
@@ -57,19 +57,16 @@ function testStayOnPage() {
 
   closeGroupItem(activeGroup);
 }
 
 function testLeavePage() {
   let dialogsAccepted = 0;
 
   whenDialogOpened(function onDialogOpened(dialog) {
-    if (++dialogsAccepted < 3)
-      whenDialogOpened(onDialogOpened);
-
     // Leave page
     dialog.acceptDialog();
   });
 
   whenGroupClosed(activeGroup, finishTest);
   closeGroupItem(activeGroup);
 }
 
--- a/browser/components/thumbnails/Makefile.in
+++ b/browser/components/thumbnails/Makefile.in
@@ -9,17 +9,17 @@ VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 EXTRA_COMPONENTS = \
 	BrowserPageThumbs.manifest \
 	PageThumbsProtocol.js \
 	$(NULL)
 
-EXTRA_PP_JS_MODULES = \
+EXTRA_JS_MODULES = \
 	PageThumbs.jsm \
 	$(NULL)
 
 TEST_DIRS += test
 
 include $(topsrcdir)/config/rules.mk
 
 XPIDL_FLAGS += -I$(topsrcdir)/browser/components/
--- a/browser/devtools/debugger/test/Makefile.in
+++ b/browser/devtools/debugger/test/Makefile.in
@@ -30,17 +30,17 @@ MOCHITEST_BROWSER_TESTS = \
 	browser_dbg_propertyview-04.js \
 	browser_dbg_propertyview-05.js \
 	browser_dbg_propertyview-06.js \
 	browser_dbg_propertyview-07.js \
 	browser_dbg_propertyview-08.js \
 	browser_dbg_propertyview-09.js \
 	browser_dbg_propertyview-10.js \
 	browser_dbg_propertyview-edit.js \
-	browser_dbg_reload-same-script.js \
+	$(warning browser_dbg_reload-same-script.js temporarily disabled due to oranges, see bug 780198 & bug 782179) \
 	browser_dbg_panesize.js \
 	browser_dbg_panesize-inner.js \
 	browser_dbg_stack-01.js \
 	browser_dbg_stack-02.js \
 	browser_dbg_stack-03.js \
 	browser_dbg_stack-04.js \
 	browser_dbg_stack-05.js \
 	browser_dbg_location-changes.js \
--- a/browser/devtools/webconsole/WebConsoleUtils.jsm
+++ b/browser/devtools/webconsole/WebConsoleUtils.jsm
@@ -948,68 +948,77 @@ function JSPropertyProvider(aScope, aInp
     return null;
   }
 
   // Skip Iterators and Generators.
   if (WCU.isIteratorOrGenerator(obj)) {
     return null;
   }
 
-  let matches = Object.keys(getMatchedProps(obj, matchProp));
+  let matches = Object.keys(getMatchedProps(obj, {matchProp:matchProp}));
 
   return {
     matchProp: matchProp,
     matches: matches.sort(),
   };
 }
 
 /**
- * Get all accessible properties on this object.
+ * Get all accessible properties on this JS value.
  * Filter those properties by name.
  * Take only a certain number of those.
  *
- * @param object obj
- *        Object whose properties we want to collect.
+ * @param mixed aObj
+ *        JS value whose properties we want to collect.
  *
- * @param string matchProp
- *        Filter for properties that match this one.
- *        Defaults to the empty string (which always matches).
+ * @param object aOptions
+ *        Options that the algorithm takes.
+ *        - matchProp (string): Filter for properties that match this one.
+ *          Defaults to the empty string (which always matches).
  *
  * @return object
  *         Object whose keys are all accessible properties on the object.
  */
-function getMatchedProps(aObj, aMatchProp = "")
+function getMatchedProps(aObj, aOptions = {matchProp: ""})
 {
+  // Argument defaults.
+  aOptions.matchProp = aOptions.matchProp || "";
+
+  if (aObj == null) { return {}; }
+  try {
+    Object.getPrototypeOf(aObj);
+  } catch(e) {
+    aObj = aObj.constructor.prototype;
+  }
   let c = MAX_COMPLETIONS;
   let names = {};   // Using an Object to avoid duplicates.
-  let ownNames = Object.getOwnPropertyNames(aObj);
-  for (let i = 0; i < ownNames.length; i++) {
-    if (ownNames[i].indexOf(aMatchProp) == 0) {
-      if (names[ownNames[i]] != true) {
-        c--;
-        if (c < 0) {
-          return names;
-        }
+
+  // We need to go up the prototype chain.
+  let ownNames = null;
+  while (aObj !== null) {
+    ownNames = Object.getOwnPropertyNames(aObj);
+    for (let i = 0; i < ownNames.length; i++) {
+      // Filtering happens here.
+      // If we already have it in, no need to append it.
+      if (ownNames[i].indexOf(aOptions.matchProp) != 0 ||
+          names[ownNames[i]] == true) {
+        continue;
+      }
+      c--;
+      if (c < 0) {
+        return names;
+      }
+      // If it is an array index, we can't take it.
+      // This uses a trick: converting a string to a number yields NaN if
+      // the operation failed, and NaN is not equal to itself.
+      if (+ownNames[i] != +ownNames[i]) {
         names[ownNames[i]] = true;
       }
     }
+    aObj = Object.getPrototypeOf(aObj);
   }
 
-  // We need to recursively go up the prototype chain.
-  aObj = Object.getPrototypeOf(aObj);
-  if (aObj !== null) {
-    let parentScope = getMatchedProps(aObj, aMatchProp);
-    for (let name in parentScope) {
-      if (names[name] != true) {
-        c--;
-        if (c < 0) {
-          return names;
-        }
-        names[name] = true;
-      }
-    }
-  }
   return names;
 }
 
 
 return JSPropertyProvider;
 })(WebConsoleUtils);
--- a/browser/devtools/webconsole/test/browser_webconsole_bug_585991_autocomplete_keys.js
+++ b/browser/devtools/webconsole/test/browser_webconsole_bug_585991_autocomplete_keys.js
@@ -190,20 +190,47 @@ function testReturnKey()
 
       ok(!popup.isOpen, "popup is not open after VK_RETURN");
 
       is(inputNode.value, "window.foobarBug585991.__defineSetter__",
          "completion was successful after VK_RETURN");
 
       ok(!completeNode.value, "completeNode is empty");
 
-      executeSoon(finishTest);
+      dontShowArrayNumbers();
     }, false);
 
     EventUtils.synthesizeKey("VK_RETURN", {});
   }, false);
 
   executeSoon(function() {
     jsterm.setInputValue("window.foobarBug58599");
     EventUtils.synthesizeKey("1", {});
     EventUtils.synthesizeKey(".", {});
   });
 }
+
+function dontShowArrayNumbers()
+{
+  content.wrappedJSObject.foobarBug585991 = ["Sherlock Holmes"];
+
+  let jsterm = HUD.jsterm;
+  let popup = jsterm.autocompletePopup;
+  let completeNode = jsterm.completeNode;
+
+  popup._panel.addEventListener("popupshown", function onShown() {
+    popup._panel.removeEventListener("popupshown", onShown, false);
+
+    let sameItems = popup.getItems().map(function(e) {return e.label;});
+    ok(!sameItems.some(function(prop, index) { prop === "0"; }),
+       "Completing on an array doesn't show numbers.");
+
+    popup._panel.addEventListener("popuphidden", consoleOpened, false);
+
+    EventUtils.synthesizeKey("VK_TAB", {});
+
+    executeSoon(finishTest);
+  }, false);
+
+  jsterm.setInputValue("window.foobarBug585991");
+  EventUtils.synthesizeKey(".", {});
+}
+
--- a/browser/devtools/webconsole/test/browser_webconsole_completion.js
+++ b/browser/devtools/webconsole/test/browser_webconsole_completion.js
@@ -93,13 +93,20 @@ function testCompletion(hud) {
 
   // Test multi-line completion works
   input.value =                 "console.log('one');\nconsol";
   jsterm.complete(jsterm.COMPLETE_HINT_ONLY, testNext);
   yield;
 
   is(jsterm.completeNode.value, "                   \n      e", "multi-line completion");
 
+  // Test non-object autocompletion.
+  input.value = "Object.name.sl";
+  jsterm.complete(jsterm.COMPLETE_HINT_ONLY, testNext);
+  yield;
+
+  is(jsterm.completeNode.value, "              ice", "non-object completion");
+
   testDriver = jsterm = input = null;
   executeSoon(finishTest);
   yield;
 }
 
--- a/browser/devtools/webconsole/webconsole.xul
+++ b/browser/devtools/webconsole/webconsole.xul
@@ -1,17 +1,17 @@
 <?xml version="1.0" encoding="utf-8"?>
 <!-- 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/. -->
 <!DOCTYPE window [
 <!ENTITY % webConsoleDTD SYSTEM "chrome://browser/locale/devtools/webConsole.dtd">
 %webConsoleDTD;
 ]>
-<?xml-stylesheet href="chrome://browser/skin/" type="text/css"?>
+<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
 <?xml-stylesheet href="chrome://browser/skin/devtools/webconsole.css"
                  type="text/css"?>
 <?xul-overlay href="chrome://global/content/editMenuOverlay.xul"?>
 <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
         title="&window.title;"
         windowtype="devtools:webconsole"
         persist="screenX screenY width height sizemode">
   <script type="text/javascript" src="chrome://global/content/globalOverlay.js"/>
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -396,16 +396,17 @@
 @BINPATH@/components/toolkitplaces.manifest
 @BINPATH@/components/nsLivemarkService.js
 @BINPATH@/components/nsTaggingService.js
 @BINPATH@/components/nsPlacesAutoComplete.manifest
 @BINPATH@/components/nsPlacesAutoComplete.js
 @BINPATH@/components/nsPlacesExpiration.js
 @BINPATH@/components/PlacesProtocolHandler.js
 @BINPATH@/components/PlacesCategoriesStarter.js
+@BINPATH@/components/ColorAnalyzer.js
 @BINPATH@/components/PageThumbsProtocol.js
 @BINPATH@/components/nsDefaultCLH.manifest
 @BINPATH@/components/nsDefaultCLH.js
 @BINPATH@/components/nsContentPrefService.manifest
 @BINPATH@/components/nsContentPrefService.js
 @BINPATH@/components/nsContentDispatchChooser.manifest
 @BINPATH@/components/nsContentDispatchChooser.js
 @BINPATH@/components/nsHandlerService.manifest
--- a/browser/locales/en-US/chrome/browser/browser.properties
+++ b/browser/locales/en-US/chrome/browser/browser.properties
@@ -378,8 +378,26 @@ social.enable.label=%S integration
 social.enable.accesskey=n
 
 # LOCALIZATION NOTE (social.remove.label): %S = brandShortName
 social.remove.label=Remove from %S
 social.remove.accesskey=R
 
 # LOCALIZATION NOTE (social.enabled.message): %1$S is the name of the social provider, %2$S is brandShortName (e.g. Firefox)
 social.activated.message=%1$S integration with %2$S has been activated.
+
+# Identity notifications popups
+identity.termsOfService = Terms of Service
+identity.privacyPolicy = Privacy Policy
+identity.chooseIdentity.description = Sign in to %S
+identity.chooseIdentity.label = Use an existing email
+identity.newIdentity.label = Use a different email
+identity.newIdentity.accessKey = e
+identity.newIdentity.email.placeholder = Email
+# LOCALIZATION NOTE (identity.newIdentity.description, identity.chooseIdentity.description): %S is the website origin (ie. https://www.mozilla.org) shown in popup notifications.
+identity.newIdentity.description = Enter your email address to sign in to %S
+identity.next.label = Next
+identity.next.accessKey = n
+# LOCALIZATION NOTE: shown in the popup notification when a user successfully logs into a website
+# LOCALIZATION NOTE (identity.loggedIn.description): %S is the website origin (ie. https://www.mozilla.org)
+identity.loggedIn.description = Signed in as: %S
+identity.loggedIn.signOut.label = Sign Out
+identity.loggedIn.signOut.accessKey = O
--- a/browser/locales/en-US/chrome/browser/pageInfo.dtd
+++ b/browser/locales/en-US/chrome/browser/pageInfo.dtd
@@ -1,13 +1,11 @@
-<!--
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
--->
+<!-- This 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/. -->
 
 <!ENTITY  pageInfoWindow.width  "600">
 <!ENTITY  pageInfoWindow.height "500">
 
 <!ENTITY  copy.key              "C">
 <!ENTITY  copy.label            "Copy">
 <!ENTITY  copy.accesskey        "C">
 <!ENTITY  selectall.key         "A">
--- a/browser/locales/en-US/chrome/overrides/settingsChange.dtd
+++ b/browser/locales/en-US/chrome/overrides/settingsChange.dtd
@@ -1,8 +1,7 @@
-<!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
-# 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/.
--->
+<!-- -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- -->
+<!-- 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/. -->
 
 <!ENTITY  settingsChangePreferences.label  "Settings can be changed using the Applications tab in &brandShortName;'s Preferences.">
 <!ENTITY  settingsChangeOptions.label      "Settings can be changed using the Applications tab in &brandShortName;'s Options.">
--- a/browser/locales/jar.mn
+++ b/browser/locales/jar.mn
@@ -11,17 +11,17 @@
     locale/browser/aboutPrivateBrowsing.dtd        (%chrome/browser/aboutPrivateBrowsing.dtd)
     locale/browser/aboutRobots.dtd                 (%chrome/browser/aboutRobots.dtd)
     locale/browser/aboutHome.dtd                   (%chrome/browser/aboutHome.dtd)
     locale/browser/aboutSessionRestore.dtd         (%chrome/browser/aboutSessionRestore.dtd)
 #ifdef MOZ_SERVICES_SYNC
     locale/browser/syncProgress.dtd                (%chrome/browser/syncProgress.dtd)
     locale/browser/aboutSyncTabs.dtd               (%chrome/browser/aboutSyncTabs.dtd)
 #endif
-*   locale/browser/browser.dtd                     (%chrome/browser/browser.dtd)
+    locale/browser/browser.dtd                     (%chrome/browser/browser.dtd)
     locale/browser/baseMenuOverlay.dtd             (%chrome/browser/baseMenuOverlay.dtd)
     locale/browser/browser.properties              (%chrome/browser/browser.properties)
     locale/browser/devtools/debugger.dtd              (%chrome/browser/devtools/debugger.dtd)
     locale/browser/devtools/debugger.properties       (%chrome/browser/devtools/debugger.properties)
     locale/browser/devtools/gcli.properties           (%chrome/browser/devtools/gcli.properties)
     locale/browser/devtools/gclicommands.properties   (%chrome/browser/devtools/gclicommands.properties)
     locale/browser/devtools/webconsole.properties     (%chrome/browser/devtools/webconsole.properties)
     locale/browser/devtools/inspector.properties      (%chrome/browser/devtools/inspector.properties)
@@ -36,20 +36,20 @@
     locale/browser/devtools/sourceeditor.properties   (%chrome/browser/devtools/sourceeditor.properties)
     locale/browser/devtools/sourceeditor.dtd          (%chrome/browser/devtools/sourceeditor.dtd)
     locale/browser/devtools/layoutview.dtd            (%chrome/browser/devtools/layoutview.dtd)
     locale/browser/devtools/responsiveUI.properties   (%chrome/browser/devtools/responsiveUI.properties)
     locale/browser/newTab.dtd                      (%chrome/browser/newTab.dtd)
     locale/browser/newTab.properties               (%chrome/browser/newTab.properties)
     locale/browser/openLocation.dtd                (%chrome/browser/openLocation.dtd)
     locale/browser/openLocation.properties         (%chrome/browser/openLocation.properties)
-*   locale/browser/pageInfo.dtd                    (%chrome/browser/pageInfo.dtd)
+    locale/browser/pageInfo.dtd                    (%chrome/browser/pageInfo.dtd)
     locale/browser/pageInfo.properties             (%chrome/browser/pageInfo.properties)
     locale/browser/quitDialog.properties           (%chrome/browser/quitDialog.properties)
-*   locale/browser/safeMode.dtd                    (%chrome/browser/safeMode.dtd)
+    locale/browser/safeMode.dtd                    (%chrome/browser/safeMode.dtd)
     locale/browser/sanitize.dtd                    (%chrome/browser/sanitize.dtd)
     locale/browser/search.properties               (%chrome/browser/search.properties)
     locale/browser/searchbar.dtd                   (%chrome/browser/searchbar.dtd)
     locale/browser/engineManager.dtd               (%chrome/browser/engineManager.dtd)
     locale/browser/engineManager.properties        (%chrome/browser/engineManager.properties)
     locale/browser/setDesktopBackground.dtd        (%chrome/browser/setDesktopBackground.dtd)
     locale/browser/shellservice.properties         (%chrome/browser/shellservice.properties)
     locale/browser/tabbrowser.dtd                  (%chrome/browser/tabbrowser.dtd)
@@ -70,17 +70,17 @@
 #endif
     locale/browser/feeds/subscribe.dtd              (%chrome/browser/feeds/subscribe.dtd)
     locale/browser/feeds/subscribe.properties       (%chrome/browser/feeds/subscribe.properties)
     locale/browser/migration/migration.dtd         (%chrome/browser/migration/migration.dtd)
     locale/browser/migration/migration.properties  (%chrome/browser/migration/migration.properties)
     locale/browser/preferences/aboutPermissions.dtd          (%chrome/browser/preferences/aboutPermissions.dtd)
     locale/browser/preferences/aboutPermissions.properties   (%chrome/browser/preferences/aboutPermissions.properties)
     locale/browser/preferences/advanced.dtd           (%chrome/browser/preferences/advanced.dtd)
-*   locale/browser/preferences/advanced-scripts.dtd   (%chrome/browser/preferences/advanced-scripts.dtd)
+    locale/browser/preferences/advanced-scripts.dtd   (%chrome/browser/preferences/advanced-scripts.dtd)
     locale/browser/preferences/applicationManager.dtd        (%chrome/browser/preferences/applicationManager.dtd)
     locale/browser/preferences/applicationManager.properties (%chrome/browser/preferences/applicationManager.properties)
     locale/browser/preferences/colors.dtd             (%chrome/browser/preferences/colors.dtd)
     locale/browser/preferences/cookies.dtd            (%chrome/browser/preferences/cookies.dtd)
     locale/browser/preferences/content.dtd            (%chrome/browser/preferences/content.dtd)
     locale/browser/preferences/connection.dtd         (%chrome/browser/preferences/connection.dtd)
     locale/browser/preferences/applications.dtd       (%chrome/browser/preferences/applications.dtd)
     locale/browser/preferences/fonts.dtd              (%chrome/browser/preferences/fonts.dtd)
@@ -102,19 +102,19 @@
     locale/browser/syncGenericChange.properties         (%chrome/browser/syncGenericChange.properties)
     locale/browser/syncKey.dtd                  (%chrome/browser/syncKey.dtd)
     locale/browser/syncQuota.dtd                (%chrome/browser/syncQuota.dtd)
     locale/browser/syncQuota.properties         (%chrome/browser/syncQuota.properties)
 #endif
 % locale browser-region @AB_CD@ %locale/browser-region/
     locale/browser-region/region.properties        (%chrome/browser-region/region.properties)
 # the following files are browser-specific overrides
-*   locale/browser/netError.dtd                (%chrome/overrides/netError.dtd)
-*   locale/browser/appstrings.properties       (%chrome/overrides/appstrings.properties)
-*   locale/browser/downloads/settingsChange.dtd  (%chrome/overrides/settingsChange.dtd)
+    locale/browser/netError.dtd                (%chrome/overrides/netError.dtd)
+    locale/browser/appstrings.properties       (%chrome/overrides/appstrings.properties)
+    locale/browser/downloads/settingsChange.dtd  (%chrome/overrides/settingsChange.dtd)
 % override chrome://global/locale/netError.dtd chrome://browser/locale/netError.dtd
 % override chrome://global/locale/appstrings.properties chrome://browser/locale/appstrings.properties
 % override chrome://mozapps/locale/downloads/settingsChange.dtd chrome://browser/locale/downloads/settingsChange.dtd
 % locale testpilot @AB_CD@ %locale/feedback/
     locale/feedback/main.dtd                       (%feedback/main.dtd)
     locale/feedback/main.properties                (%feedback/main.properties)
 % locale pdf.js @AB_CD@ %locale/pdfviewer/
     locale/pdfviewer/viewer.properties             (%pdfviewer/viewer.properties)
new file mode 100644
--- /dev/null
+++ b/browser/modules/BrowserNewTabPreloader.jsm
@@ -0,0 +1,160 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+let EXPORTED_SYMBOLS = ["BrowserNewTabPreloader"];
+
+const Cu = Components.utils;
+
+Cu.import("resource://gre/modules/Services.jsm");
+
+const PREF_NEWTAB_URL = "browser.newtab.url";
+const PREF_NEWTAB_PRELOAD = "browser.newtab.preload";
+
+function BrowserNewTabPreloader() {
+}
+
+BrowserNewTabPreloader.prototype = {
+  _url: null,
+  _window: null,
+  _browser: null,
+  _enabled: null,
+
+  init: function Preloader_init(aWindow) {
+    if (this._window) {
+      return;
+    }
+
+    this._window = aWindow;
+    this._enabled = Preferences.enabled;
+    this._url = Preferences.url;
+    Preferences.addObserver(this);
+
+    if (this._enabled) {
+      this._createBrowser();
+    }
+  },
+
+  uninit: function Preloader_uninit() {
+    if (!this._window) {
+      return;
+    }
+
+    if (this._browser) {
+      this._browser.parentNode.removeChild(this._browser);
+      this._browser = null;
+    }
+
+    this._window = null;
+    Preferences.removeObserver(this);
+  },
+
+  newTab: function Preloader_newTab(aTab) {
+    if (!this._window || !this._enabled) {
+      return;
+    }
+
+    let tabbrowser = this._window.gBrowser;
+    if (tabbrowser && this._isPreloaded()) {
+      tabbrowser.swapNewTabWithBrowser(aTab, this._browser);
+    }
+  },
+
+  observe: function Preloader_observe(aEnabled, aURL) {
+    if (this._url != aURL) {
+      this._url = aURL;
+
+      if (this._enabled && aEnabled) {
+        // We're still enabled but the newtab URL has changed.
+        this._browser.setAttribute("src", aURL);
+        return;
+      }
+    }
+
+    if (this._enabled && !aEnabled) {
+      // We got disabled. Remove the browser.
+      this._browser.parentNode.removeChild(this._browser);
+      this._browser = null;
+      this._enabled = false;
+    } else if (!this._enabled && aEnabled) {
+      // We got enabled. Create a browser and start preloading.
+      this._createBrowser();
+      this._enabled = true;
+    }
+  },
+
+  _createBrowser: function Preloader_createBrowser() {
+    let document = this._window.document;
+    this._browser = document.createElement("browser");
+    this._browser.setAttribute("type", "content");
+    this._browser.setAttribute("src", this._url);
+    this._browser.collapsed = true;
+
+    let panel = document.getElementById("browser-panel");
+    panel.appendChild(this._browser);
+  },
+
+  _isPreloaded: function Preloader_isPreloaded()  {
+    return this._browser &&
+           this._browser.contentDocument &&
+           this._browser.contentDocument.readyState == "complete" &&
+           this._browser.currentURI.spec == this._url;
+  }
+};
+
+let Preferences = {
+  _observers: [],
+
+  get _branch() {
+    delete this._branch;
+    return this._branch = Services.prefs.getBranch("browser.newtab.");
+  },
+
+  get enabled() {
+    if (!this._branch.getBoolPref("preload")) {
+      return false;
+    }
+
+    if (this._branch.prefHasUserValue("url")) {
+      return false;
+    }
+
+    let url = this.url;
+    return url && url != "about:blank";
+  },
+
+  get url() {
+    return this._branch.getCharPref("url");
+  },
+
+  addObserver: function Preferences_addObserver(aObserver) {
+    let index = this._observers.indexOf(aObserver);
+    if (index == -1) {
+      if (this._observers.length == 0) {
+        this._branch.addObserver("", this, false);
+      }
+      this._observers.push(aObserver);
+    }
+  },
+
+  removeObserver: function Preferences_removeObserver(aObserver) {
+    let index = this._observers.indexOf(aObserver);
+    if (index > -1) {
+      if (this._observers.length == 1) {
+        this._branch.removeObserver("", this);
+      }
+      this._observers.splice(index, 1);
+    }
+  },
+
+  observe: function Preferences_observe(aSubject, aTopic, aData) {
+    let url = this.url;
+    let enabled = this.enabled;
+
+    for (let obs of this._observers) {
+      obs.observe(enabled, url);
+    }
+  }
+};
--- a/browser/modules/Makefile.in
+++ b/browser/modules/Makefile.in
@@ -9,25 +9,27 @@ VPATH   = @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 include $(topsrcdir)/config/config.mk
 
 TEST_DIRS += test
 
 EXTRA_JS_MODULES = \
+	BrowserNewTabPreloader.jsm \
 	openLocationLastURL.jsm \
 	NetworkPrioritizer.jsm \
 	NewTabUtils.jsm \
 	offlineAppCache.jsm \
+	SignInToWebsite.jsm \
 	TelemetryTimestamps.jsm \
 	Social.jsm \
 	webappsUI.jsm \
 	$(NULL)
 
-ifeq ($(MOZ_WIDGET_TOOLKIT),windows) 
+ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
 EXTRA_JS_MODULES += \
 	WindowsPreviewPerTab.jsm \
 	WindowsJumpLists.jsm \
 	$(NULL)
 endif
 
 include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/browser/modules/SignInToWebsite.jsm
@@ -0,0 +1,235 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const EXPORTED_SYMBOLS = ["SignInToWebsiteUX"];
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cu = Components.utils;
+
+Cu.import("resource://gre/modules/Services.jsm");
+Cu.import("resource://gre/modules/XPCOMUtils.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "IdentityService",
+                                  "resource://gre/modules/identity/Identity.jsm");
+
+XPCOMUtils.defineLazyModuleGetter(this, "Logger",
+                                  "resource://gre/modules/identity/LogUtils.jsm");
+
+function log(...aMessageArgs) {
+  Logger.log.apply(Logger, ["SignInToWebsiteUX"].concat(aMessageArgs));
+}
+
+let SignInToWebsiteUX = {
+
+  init: function SignInToWebsiteUX_init() {
+    Services.obs.addObserver(this, "identity-request", false);
+    Services.obs.addObserver(this, "identity-auth", false);
+    Services.obs.addObserver(this, "identity-auth-complete", false);
+    Services.obs.addObserver(this, "identity-login-state-changed", false);
+  },
+
+  uninit: function SignInToWebsiteUX_uninit() {
+    Services.obs.removeObserver(this, "identity-request");
+    Services.obs.removeObserver(this, "identity-auth");
+    Services.obs.removeObserver(this, "identity-auth-complete");
+    Services.obs.removeObserver(this, "identity-login-state-changed");
+  },
+
+  observe: function SignInToWebsiteUX_observe(aSubject, aTopic, aData) {
+    log("observe: received", aTopic, "with", aData, "for", aSubject);
+    let options = null;
+    if (aSubject) {
+      options = aSubject.wrappedJSObject;
+    }
+    switch(aTopic) {
+      case "identity-request":
+        this.requestLogin(options);
+        break;
+      case "identity-auth":
+        this._openAuthenticationUI(aData, options);
+        break;
+      case "identity-auth-complete":
+        this._closeAuthenticationUI(aData);
+        break;
+      case "identity-login-state-changed":
+        let emailAddress = aData;
+        if (emailAddress) {
+          this._removeRequestUI(options);
+          this._showLoggedInUI(emailAddress, options);
+        } else {
+          this._removeLoggedInUI(options);
+        }
+        break;
+      default:
+        Logger.reportError("SignInToWebsiteUX", "Unknown observer notification:", aTopic);
+        break;
+    }
+  },
+
+  /**
+   * The website is requesting login so the user must choose an identity to use.
+   */
+  requestLogin: function SignInToWebsiteUX_requestLogin(aOptions) {
+    let windowID = aOptions.rpId;
+    log("requestLogin", aOptions);
+    let [chromeWin, browserEl] = this._getUIForWindowID(windowID);
+
+    // message is not shown in the UI but is required
+    let message = aOptions.origin;
+    let mainAction = {
+      label: chromeWin.gNavigatorBundle.getString("identity.next.label"),
+      accessKey: chromeWin.gNavigatorBundle.getString("identity.next.accessKey"),
+      callback: function() {}, // required
+    };
+    let options = {
+      identity: {
+        origin: aOptions.origin,
+      },
+    };
+    let secondaryActions = [];
+
+    // add some extra properties to the notification to store some identity-related state
+    for (let opt in aOptions) {
+      options.identity[opt] = aOptions[opt];
+    }
+    log("requestLogin: rpId: ", options.identity.rpId);
+
+    chromeWin.PopupNotifications.show(browserEl, "identity-request", message,
+                                      "identity-notification-icon", mainAction,
+                                      [], options);
+  },
+
+  /**
+   * Get the list of possible identities to login to the given origin.
+   */
+  getIdentitiesForSite: function SignInToWebsiteUX_getIdentitiesForSite(aOrigin) {
+    return IdentityService.RP.getIdentitiesForSite(aOrigin);
+  },
+
+  /**
+   * User chose a new or existing identity from the doorhanger after a request() call
+   */
+  selectIdentity: function SignInToWebsiteUX_selectIdentity(aRpId, aIdentity) {
+    log("selectIdentity: rpId: ", aRpId, " identity: ", aIdentity);
+    IdentityService.selectIdentity(aRpId, aIdentity);
+  },
+
+  // Private
+
+  /**
+   * Return the chrome window and <browser> for the given outer window ID.
+   */
+  _getUIForWindowID: function(aWindowID) {
+    let someWindow = Services.wm.getMostRecentWindow("navigator:browser");
+    if (!someWindow) {
+      Logger.reportError("SignInToWebsiteUX", "no window");
+      return [null, null];
+    }
+
+    let windowUtils = someWindow.QueryInterface(Ci.nsIInterfaceRequestor)
+                                .getInterface(Ci.nsIDOMWindowUtils);
+    let content = windowUtils.getOuterWindowWithId(aWindowID);
+
+    if (content) {
+      let browser = content.QueryInterface(Ci.nsIInterfaceRequestor)
+                           .getInterface(Ci.nsIWebNavigation)
+                           .QueryInterface(Ci.nsIDocShell).chromeEventHandler;
+      let chromeWin = browser.ownerDocument.defaultView;
+      return [chromeWin, browser];
+    }
+    Logger.reportError("SignInToWebsiteUX", "no content");
+
+    return [null, null];
+  },
+
+  /**
+   * Open UI with a content frame displaying aAuthURI so that the user can authenticate with their
+   * IDP.  Then tell Identity.jsm the identifier for the window so that it knows that the DOM API
+   * calls are for this authentication flow.
+   */
+  _openAuthenticationUI: function _openAuthenticationUI(aAuthURI, aContext) {
+    // Open a tab/window with aAuthURI with an identifier (aID) attached so that the DOM APIs know this is an auth. window.
+    let chromeWin = Services.wm.getMostRecentWindow('navigator:browser');
+    let features = "chrome=false,width=640,height=480,centerscreen,location=yes,resizable=yes,scrollbars=yes,status=yes";
+    log("aAuthURI: ", aAuthURI);
+    let authWin = Services.ww.openWindow(chromeWin, "about:blank", "", features, null);
+    let windowID = authWin.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils).outerWindowID;
+    log("authWin outer id: ", windowID);
+
+    let provId = aContext.provId;
+    // Tell the ID service about the id before loading the url
+    IdentityService.IDP.setAuthenticationFlow(windowID, provId);
+
+    authWin.location = aAuthURI;
+  },
+
+  _closeAuthenticationUI: function _closeAuthenticationUI(aAuthId) {
+    log("_closeAuthenticationUI:", aAuthId);
+    let [chromeWin, browserEl] = this._getUIForWindowID(aAuthId);
+    if (chromeWin)
+      chromeWin.close();
+    else
+      Logger.reportError("SignInToWebsite", "Could not close window with ID", aAuthId);
+  },
+
+  /**
+   * Show a doorhanger indicating the currently logged-in user.
+   */
+  _showLoggedInUI: function _showLoggedInUI(aIdentity, aContext) {
+    let windowID = aContext.rpId;
+    log("_showLoggedInUI for ", windowID);
+    let [chromeWin, browserEl] = this._getUIForWindowID(windowID);
+
+    let message = chromeWin.gNavigatorBundle.getFormattedString("identity.loggedIn.description",
+                                                          [aIdentity]);
+    let mainAction = {
+      label: chromeWin.gNavigatorBundle.getString("identity.loggedIn.signOut.label"),
+      accessKey: chromeWin.gNavigatorBundle.getString("identity.loggedIn.signOut.accessKey"),
+      callback: function() {
+        log("sign out callback fired");
+        IdentityService.RP.logout(windowID);
+      },
+    };
+    let secondaryActions = [];
+    let options = {
+      dismissed: true,
+    };
+    let loggedInNot = chromeWin.PopupNotifications.show(browserEl, "identity-logged-in", message,
+                                                  "identity-notification-icon", mainAction,
+                                                  secondaryActions, options);
+    loggedInNot.rpId = windowID;
+  },
+
+  /**
+   * Remove the doorhanger indicating the currently logged-in user.
+   */
+  _removeLoggedInUI: function _removeLoggedInUI(aContext) {
+    let windowID = aContext.rpId;
+    log("_removeLoggedInUI for ", windowID);
+    if (!windowID)
+      throw "_removeLoggedInUI: Invalid RP ID";
+    let [chromeWin, browserEl] = this._getUIForWindowID(windowID);
+
+    let loggedInNot = chromeWin.PopupNotifications.getNotification("identity-logged-in", browserEl);
+    if (loggedInNot)
+      chromeWin.PopupNotifications.remove(loggedInNot);
+  },
+
+  /**
+   * Remove the doorhanger indicating the currently logged-in user.
+   */
+  _removeRequestUI: function _removeRequestUI(aContext) {
+    let windowID = aContext.rpId;
+    log("_removeRequestUI for ", windowID);
+    let [chromeWin, browserEl] = this._getUIForWindowID(windowID);
+
+    let requestNot = chromeWin.PopupNotifications.getNotification("identity-request", browserEl);
+    if (requestNot)
+      chromeWin.PopupNotifications.remove(requestNot);
+  },
+
+};
--- a/browser/modules/test/Makefile.in
+++ b/browser/modules/test/Makefile.in
@@ -9,18 +9,19 @@ VPATH		= @srcdir@
 relativesrcdir  = @relativesrcdir@
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _BROWSER_FILES = \
                  browser_NetworkPrioritizer.js \
                  browser_TelemetryTimestamps.js \
+                 browser_SignInToWebsite.js \
                  $(NULL)
 
-ifeq ($(MOZ_WIDGET_TOOLKIT),windows) 
+ifeq ($(MOZ_WIDGET_TOOLKIT),windows)
 _BROWSER_FILES += \
                  browser_taskbar_preview.js \
                  $(NULL)
 endif
 
 libs::	$(_BROWSER_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/browser/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/browser/modules/test/browser_SignInToWebsite.js
@@ -0,0 +1,549 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/**
+ * TO TEST:
+ * - test state saved on doorhanger dismissal
+ * - links to switch steps
+ * - TOS and PP link clicks
+ * - identityList is populated correctly
+ */
+
+Services.prefs.setBoolPref("toolkit.identity.debug", true);
+
+XPCOMUtils.defineLazyModuleGetter(this, "IdentityService",
+                                  "resource://gre/modules/identity/Identity.jsm");
+
+const TEST_ORIGIN = "https://example.com";
+const TEST_EMAIL = "user@example.com";
+
+let gTestIndex = 0;
+let outerWinId = gBrowser.contentWindow.QueryInterface(Ci.nsIInterfaceRequestor)
+                         .getInterface(Ci.nsIDOMWindowUtils).outerWindowID;
+
+function NotificationBase(aNotId) {
+  this.id = aNotId;
+}
+NotificationBase.prototype = {
+  message: TEST_ORIGIN,
+  mainAction: {
+    label: "",
+    callback: function() {
+      this.mainActionClicked = true;
+    }.bind(this),
+  },
+  secondaryActions: [],
+  options: {
+    "identity": {
+      origin: TEST_ORIGIN,
+      rpId: outerWinId,
+    },
+  },
+};
+
+let tests = [
+  {
+    name: "test_request_required_typed",
+
+    run: function() {
+      setupRPFlow();
+      this.notifyOptions = {
+        rpId: outerWinId,
+        origin: TEST_ORIGIN,
+      };
+      this.notifyObj = new NotificationBase("identity-request");
+      Services.obs.notifyObservers({wrappedJSObject: this.notifyOptions},
+                                   "identity-request", null);
+    },
+
+    onShown: function(popup) {
+      checkPopup(popup, this.notifyObj);
+      let notification = popup.childNodes[0];
+
+      // Check identity popup state
+      let state = notification.identity;
+      ok(!state.typedEmail, "Nothing should be typed yet");
+      ok(!state.selected, "Identity should not be selected yet");
+      ok(!state.termsOfService, "No TOS specified");
+      ok(!state.privacyPolicy, "No PP specified");
+      is(state.step, 0, "Step should be persisted with default value");
+      is(state.rpId, outerWinId, "Check rpId");
+      is(state.origin, TEST_ORIGIN, "Check origin");
+
+      is(notification.step, 0, "Should be on the new email step");
+      is(notification.chooseEmailLink.hidden, true, "Identity list is empty so link to list view should be hidden");
+      is(notification.addEmailLink.parentElement.hidden, true, "We are already on the email input step so choose email pane should be hidden");
+      is(notification.emailField.value, "", "Email field should default to empty on a new notification");
+      let notifDoc = notification.ownerDocument;
+      ok(notifDoc.getAnonymousElementByAttribute(notification, "anonid", "tos").hidden,
+         "TOS link should be hidden");
+      ok(notifDoc.getAnonymousElementByAttribute(notification, "anonid", "privacypolicy").hidden,
+         "PP link should be hidden");
+
+      // Try to continue with a missing email address
+      triggerMainCommand(popup);
+      is(notification.throbber.style.visibility, "hidden", "is throbber visible");
+      ok(!notification.button.disabled, "Button should not be disabled");
+      is(window.gIdentitySelected, null, "Check no identity selected");
+
+      // Fill in an invalid email address and try again
+      notification.emailField.value = "foo";
+      triggerMainCommand(popup);
+      is(notification.throbber.style.visibility, "hidden", "is throbber visible");
+      ok(!notification.button.disabled, "Button should not be disabled");
+      is(window.gIdentitySelected, null, "Check no identity selected");
+
+      // Fill in an email address and try again
+      notification.emailField.value = TEST_EMAIL;
+      triggerMainCommand(popup);
+      is(window.gIdentitySelected.rpId, outerWinId, "Check identity selected rpId");
+      is(window.gIdentitySelected.identity, TEST_EMAIL, "Check identity selected email");
+      is(notification.identity.selected, TEST_EMAIL, "Check persisted email");
+      is(notification.throbber.style.visibility, "visible", "is throbber visible");
+      ok(notification.button.disabled, "Button should be disabled");
+      ok(notification.emailField.disabled, "Email field should be disabled");
+      ok(notification.identityList.disabled, "Identity list should be disabled");
+
+      PopupNotifications.getNotification("identity-request").remove();
+    },
+
+    onHidden: function(popup) { },
+  },
+  {
+    name: "test_request_optional",
+
+    run: function() {
+      this.notifyOptions = {
+        rpId: outerWinId,
+        origin: TEST_ORIGIN,
+        privacyPolicy: TEST_ORIGIN + "/pp.txt",
+        termsOfService: TEST_ORIGIN + "/tos.tzt",
+      };
+      this.notifyObj = new NotificationBase("identity-request");
+      Services.obs.notifyObservers({ wrappedJSObject: this.notifyOptions },
+                                   "identity-request", null);
+    },
+
+    onShown: function(popup) {
+      checkPopup(popup, this.notifyObj);
+      let notification = popup.childNodes[0];
+
+      // Check identity popup state
+      let state = notification.identity;
+      ok(!state.typedEmail, "Nothing should be typed yet");
+      ok(!state.selected, "Identity should not be selected yet");
+      is(state.termsOfService, this.notifyOptions.termsOfService, "Check TOS URL");
+      is(state.privacyPolicy, this.notifyOptions.privacyPolicy, "Check PP URL");
+      is(state.step, 0, "Step should be persisted with default value");
+      is(state.rpId, outerWinId, "Check rpId");
+      is(state.origin, TEST_ORIGIN, "Check origin");
+
+      is(notification.step, 0, "Should be on the new email step");
+      is(notification.chooseEmailLink.hidden, true, "Identity list is empty so link to list view should be hidden");
+      is(notification.addEmailLink.parentElement.hidden, true, "We are already on the email input step so choose email pane should be hidden");
+      is(notification.emailField.value, "", "Email field should default to empty on a new notification");
+      let notifDoc = notification.ownerDocument;
+      let tosLink = notifDoc.getAnonymousElementByAttribute(notification, "anonid", "tos");
+      ok(!tosLink.hidden, "TOS link should be visible");
+      is(tosLink.href, this.notifyOptions.termsOfService, "Check TOS link URL");
+      let ppLink = notifDoc.getAnonymousElementByAttribute(notification, "anonid", "privacypolicy");
+      ok(!ppLink.hidden, "PP link should be visible");
+      is(ppLink.href, this.notifyOptions.privacyPolicy, "Check PP link URL");
+
+      // Try to continue with a missing email address
+      triggerMainCommand(popup);
+      is(notification.throbber.style.visibility, "hidden", "is throbber visible");
+      ok(!notification.button.disabled, "Button should not be disabled");
+      is(window.gIdentitySelected, null, "Check no identity selected");
+
+      // Fill in an invalid email address and try again
+      notification.emailField.value = "foo";
+      triggerMainCommand(popup);
+      is(notification.throbber.style.visibility, "hidden", "is throbber visible");
+      ok(!notification.button.disabled, "Button should not be disabled");
+      is(window.gIdentitySelected, null, "Check no identity selected");
+
+      // Fill in an email address and try again
+      notification.emailField.value = TEST_EMAIL;
+      triggerMainCommand(popup);
+      is(window.gIdentitySelected.rpId, outerWinId, "Check identity selected rpId");
+      is(window.gIdentitySelected.identity, TEST_EMAIL, "Check identity selected email");
+      is(notification.identity.selected, TEST_EMAIL, "Check persisted email");
+      is(notification.throbber.style.visibility, "visible", "is throbber visible");
+      ok(notification.button.disabled, "Button should be disabled");
+      ok(notification.emailField.disabled, "Email field should be disabled");
+      ok(notification.identityList.disabled, "Identity list should be disabled");
+
+      PopupNotifications.getNotification("identity-request").remove();
+    },
+
+    onHidden: function(popup) {},
+  },
+  {
+    name: "test_login_state_changed",
+    run: function () {
+      this.notifyOptions = {
+        rpId: outerWinId,
+      };
+      this.notifyObj = new NotificationBase("identity-logged-in");
+      this.notifyObj.message = "Signed in as: user@example.com";
+      this.notifyObj.mainAction.label = "Sign Out";
+      this.notifyObj.mainAction.accessKey = "O";
+      Services.obs.notifyObservers({ wrappedJSObject: this.notifyOptions },
+                                   "identity-login-state-changed", TEST_EMAIL);
+      executeSoon(function() {
+        PopupNotifications.getNotification("identity-logged-in").anchorElement.click();
+      });
+    },
+
+    onShown: function(popup) {
+      checkPopup(popup, this.notifyObj);
+
+      // Fire the notification that the user is no longer logged-in to close the UI.
+      Services.obs.notifyObservers({ wrappedJSObject: this.notifyOptions },
+                                   "identity-login-state-changed", null);
+    },
+
+    onHidden: function(popup) {},
+  },
+  {
+    name: "test_login_state_changed_logout",
+    run: function () {
+      this.notifyOptions = {
+        rpId: outerWinId,
+      };
+      this.notifyObj = new NotificationBase("identity-logged-in");
+      this.notifyObj.message = "Signed in as: user@example.com";
+      this.notifyObj.mainAction.label = "Sign Out";
+      this.notifyObj.mainAction.accessKey = "O";
+      Services.obs.notifyObservers({ wrappedJSObject: this.notifyOptions },
+                                   "identity-login-state-changed", TEST_EMAIL);
+      executeSoon(function() {
+        PopupNotifications.getNotification("identity-logged-in").anchorElement.click();
+      });
+    },
+
+    onShown: function(popup) {
+      checkPopup(popup, this.notifyObj);
+
+      // This time trigger the Sign Out button and make sure the UI goes away.
+      triggerMainCommand(popup);
+    },
+
+    onHidden: function(popup) {},
+  },
+];
+
+function test_auth() {
+  let notifyOptions = {
+    provId: outerWinId,
+    origin: TEST_ORIGIN,
+  };
+
+  Services.obs.addObserver(function() {
+    // prepare to send auth-complete and close the window
+    let winCloseObs = new WindowObserver(function(closedWin) {
+      info("closed window");
+      finish();
+    }, "domwindowclosed");
+    Services.ww.registerNotification(winCloseObs);
+    Services.obs.notifyObservers(null, "identity-auth-complete", IdentityService.IDP.authenticationFlowSet.authId);
+
+  }, "test-identity-auth-window", false);
+
+  let winObs = new WindowObserver(function(authWin) {
+    ok(authWin, "Authentication window opened");
+    ok(authWin.contentWindow.location);
+  });
+
+  Services.ww.registerNotification(winObs);
+
+  Services.obs.notifyObservers({ wrappedJSObject: notifyOptions },
+                               "identity-auth", TEST_ORIGIN + "/auth");
+}
+
+function test() {
+  waitForExplicitFinish();
+
+  registerCleanupFunction(cleanUp);
+
+  let sitw = {};
+  Components.utils.import("resource:///modules/SignInToWebsite.jsm", sitw);
+
+  ok(sitw.SignInToWebsiteUX, "SignInToWebsiteUX object exists");
+
+  // Replace implementation of ID Service functions for testing
+  window.selectIdentity = sitw.SignInToWebsiteUX.selectIdentity;
+  sitw.SignInToWebsiteUX.selectIdentity = function(aRpId, aIdentity) {
+    info("Identity selected: " + aIdentity);
+    window.gIdentitySelected = {rpId: aRpId, identity: aIdentity};
+  };
+
+  window.setAuthenticationFlow = IdentityService.IDP.setAuthenticationFlow;
+  IdentityService.IDP.setAuthenticationFlow = function(aAuthId, aProvId) {
+    info("setAuthenticationFlow: " + aAuthId + " : " + aProvId);
+    this.authenticationFlowSet = { authId: aAuthId, provId: aProvId };
+    Services.obs.notifyObservers(null, "test-identity-auth-window", aAuthId);
+  };
+
+  runNextTest();
+}
+
+// Cleanup between tests
+function resetState() {
+  delete window.gIdentitySelected;
+  delete IdentityService.IDP.authenticationFlowSet;
+  IdentityService.reset();
+}
+
+// Cleanup after all tests
+function cleanUp() {
+  info("cleanup");
+  resetState();
+
+  for (let topic in gActiveObservers)
+    Services.obs.removeObserver(gActiveObservers[topic], topic);
+  for (let eventName in gActiveListeners)
+    PopupNotifications.panel.removeEventListener(eventName, gActiveListeners[eventName], false);
+  delete IdentityService.RP._rpFlows[outerWinId];
+
+  // Put the JSM functions back to how they were
+  IdentityService.IDP.setAuthenticationFlow = window.setAuthenticationFlow;
+  delete window.setAuthenticationFlow;
+
+  let sitw = {};
+  Components.utils.import("resource:///modules/SignInToWebsite.jsm", sitw);
+  sitw.SignInToWebsiteUX.selectIdentity = window.selectIdentity;
+  delete window.selectIdentity;
+
+  Services.prefs.clearUserPref("toolkit.identity.debug");
+}
+
+let gActiveListeners = {};
+let gActiveObservers = {};
+let gShownState = {};
+
+function runNextTest() {
+  let nextTest = tests[gTestIndex];
+
+  function goNext() {
+    resetState();
+    if (++gTestIndex == tests.length)
+      executeSoon(test_auth);
+    else
+      executeSoon(runNextTest);
+  }
+
+  function addObserver(topic) {
+    function observer() {
+      Services.obs.removeObserver(observer, "PopupNotifications-" + topic);
+      delete gActiveObservers["PopupNotifications-" + topic];
+
+      info("[Test #" + gTestIndex + "] observer for " + topic + " called");
+      nextTest[topic]();
+      goNext();
+    }
+    Services.obs.addObserver(observer, "PopupNotifications-" + topic, false);
+    gActiveObservers["PopupNotifications-" + topic] = observer;
+  }
+
+  if (nextTest.backgroundShow) {
+    addObserver("backgroundShow");
+  } else if (nextTest.updateNotShowing) {
+    addObserver("updateNotShowing");
+  } else {
+    doOnPopupEvent("popupshowing", function () {
+      info("[Test #" + gTestIndex + "] popup showing");
+    });
+    doOnPopupEvent("popupshown", function () {
+      gShownState[gTestIndex] = true;
+      info("[Test #" + gTestIndex + "] popup shown");
+      nextTest.onShown(this);
+    });
+
+    // We allow multiple onHidden functions to be defined in an array.  They're
+    // called in the order they appear.
+    let onHiddenArray = nextTest.onHidden instanceof Array ?
+                        nextTest.onHidden :
+                        [nextTest.onHidden];
+    doOnPopupEvent("popuphidden", function () {
+      if (!gShownState[gTestIndex]) {
+        // TODO: needed?
+        info("Popup from test " + gTestIndex + " was hidden before its popupshown fired");
+      }
+
+      let onHidden = onHiddenArray.shift();
+      info("[Test #" + gTestIndex + "] popup hidden (" + onHiddenArray.length + " hides remaining)");
+      executeSoon(function () {
+        onHidden.call(nextTest, this);
+        if (!onHiddenArray.length)
+          goNext();
+      }.bind(this));
+    }, onHiddenArray.length);
+    info("[Test #" + gTestIndex + "] added listeners; panel state: " + PopupNotifications.isPanelOpen);
+  }
+
+  info("[Test #" + gTestIndex + "] running test");
+  nextTest.run();
+}
+
+function doOnPopupEvent(eventName, callback, numExpected) {
+  gActiveListeners[eventName] = function (event) {
+    if (event.target != PopupNotifications.panel)
+      return;
+    if (typeof(numExpected) === "number")
+      numExpected--;
+    if (!numExpected) {
+      PopupNotifications.panel.removeEventListener(eventName, gActiveListeners[eventName], false);
+      delete gActiveListeners[eventName];
+    }
+
+    callback.call(PopupNotifications.panel);
+  };
+  PopupNotifications.panel.addEventListener(eventName, gActiveListeners[eventName], false);
+}
+
+function checkPopup(popup, notificationObj) {
+  info("[Test #" + gTestIndex + "] checking popup");
+
+  let notifications = popup.childNodes;
+  is(notifications.length, 1, "only one notification displayed");
+  let notification = notifications[0];
+  let icon = document.getAnonymousElementByAttribute(notification, "class", "popup-notification-icon");
+  is(notification.getAttribute("label"), notificationObj.message, "message matches");
+  is(notification.id, notificationObj.id + "-notification", "id matches");
+  if (notificationObj.id != "identity-request" && notificationObj.mainAction) {
+    is(notification.getAttribute("buttonlabel"), notificationObj.mainAction.label, "main action label matches");
+    is(notification.getAttribute("buttonaccesskey"), notificationObj.mainAction.accessKey, "main action accesskey matches");
+  }
+  let actualSecondaryActions = notification.childNodes;
+  let secondaryActions = notificationObj.secondaryActions || [];
+  let actualSecondaryActionsCount = actualSecondaryActions.length;
+  if (secondaryActions.length) {
+    let lastChild = actualSecondaryActions.item(actualSecondaryActions.length - 1);
+    is(lastChild.tagName, "menuseparator", "menuseparator exists");
+    actualSecondaryActionsCount--;
+  }
+  is(actualSecondaryActionsCount, secondaryActions.length, actualSecondaryActions.length + " secondary actions");
+  secondaryActions.forEach(function (a, i) {
+    is(actualSecondaryActions[i].getAttribute("label"), a.label, "label for secondary action " + i + " matches");
+    is(actualSecondaryActions[i].getAttribute("accesskey"), a.accessKey, "accessKey for secondary action " + i + " matches");
+  });
+}
+
+function triggerMainCommand(popup) {
+  info("[Test #" + gTestIndex + "] triggering main command");
+  let notifications = popup.childNodes;
+  ok(notifications.length > 0, "at least one notification displayed");
+  let notification = notifications[0];
+
+  // 20, 10 so that the inner button is hit
+  EventUtils.synthesizeMouse(notification.button, 20, 10, {});
+}
+
+function triggerSecondaryCommand(popup, index) {
+  info("[Test #" + gTestIndex + "] triggering secondary command");
+  let notifications = popup.childNodes;
+  ok(notifications.length > 0, "at least one notification displayed");
+  let notification = notifications[0];
+
+  notification.button.focus();
+
+  popup.addEventListener("popupshown", function () {
+    popup.removeEventListener("popupshown", arguments.callee, false);
+
+    // Press down until the desired command is selected
+    for (let i = 0; i <= index; i++)
+      EventUtils.synthesizeKey("VK_DOWN", {});
+
+    // Activate
+    EventUtils.synthesizeKey("VK_ENTER", {});
+  }, false);
+
+  // One down event to open the popup
+  EventUtils.synthesizeKey("VK_DOWN", { altKey: (navigator.platform.indexOf("Mac") == -1) });
+}
+
+function dismissNotification(popup) {
+  info("[Test #" + gTestIndex + "] dismissing notification");
+  executeSoon(function () {
+    EventUtils.synthesizeKey("VK_ESCAPE", {});
+  });
+}
+
+function partial(fn) {
+  let args = Array.prototype.slice.call(arguments, 1);
+  return function() {
+    return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
+  };
+}
+
+// create a mock "doc" object, which the Identity Service
+// uses as a pointer back into the doc object
+function mock_doc(aIdentity, aOrigin, aDoFunc) {
+  let mockedDoc = {};
+  mockedDoc.id = outerWinId;
+  mockedDoc.loggedInEmail = aIdentity;
+  mockedDoc.origin = aOrigin;
+  mockedDoc['do'] = aDoFunc;
+  mockedDoc.doReady = partial(aDoFunc, 'ready');
+  mockedDoc.doLogin = partial(aDoFunc, 'login');
+  mockedDoc.doLogout = partial(aDoFunc, 'logout');
+  mockedDoc.doError = partial(aDoFunc, 'error');
+  mockedDoc.doCancel = partial(aDoFunc, 'cancel');
+  mockedDoc.doCoffee = partial(aDoFunc, 'coffee');
+
+  return mockedDoc;
+}
+
+// takes a list of functions and returns a function that
+// when called the first time, calls the first func,
+// then the next time the second, etc.
+function call_sequentially() {
+  let numCalls = 0;
+  let funcs = arguments;
+
+  return function() {
+    if (!funcs[numCalls]) {
+      let argString = Array.prototype.slice.call(arguments).join(",");
+      ok(false, "Too many calls: " + argString);
+      return;
+    }
+    funcs[numCalls].apply(funcs[numCalls], arguments);
+    numCalls += 1;
+  };
+}
+
+function setupRPFlow(aIdentity) {
+  IdentityService.RP.watch(mock_doc(aIdentity, TEST_ORIGIN, call_sequentially(
+    function(action, params) {
+      is(action, "ready", "1st callback");
+      is(params, null);
+    },
+    function(action, params) {
+      is(action, "logout", "2nd callback");
+      is(params, null);
+    },
+    function(action, params) {
+      is(action, "ready", "3rd callback");
+      is(params, null);
+    }
+  )));
+}
+
+function WindowObserver(aCallback, aObserveTopic = "domwindowopened") {
+  this.observe = function(aSubject, aTopic, aData) {
+    if (aTopic != aObserveTopic) {
+      return;
+    }
+    info(aObserveTopic);
+    Services.ww.unregisterNotification(this);
+
+    SimpleTest.executeSoon(function() {
+      let domWin = aSubject.QueryInterface(Ci.nsIDOMWindow);
+      aCallback(domWin);
+    });
+  };
+}
--- a/browser/modules/webappsUI.jsm
+++ b/browser/modules/webappsUI.jsm
@@ -108,17 +108,17 @@ let webappsUI = {
 
     let mainAction = {
       label: bundle.getString("webapps.install"),
       accessKey: bundle.getString("webapps.install.accesskey"),
       callback: function() {
         let app = WebappsInstaller.install(aData);
         if (app) {
           let localDir = null;
-          if (app.appcacheDefined && app.appProfile) {
+          if (app.appProfile) {
             localDir = app.appProfile.localDir;
           }
 
           DOMApplicationRegistry.confirmInstall(aData, false, localDir);
           installationSuccessNotification(app, aWindow);
         } else {
           DOMApplicationRegistry.denyInstall(aData);
         }
--- a/browser/themes/gnomestripe/browser.css
+++ b/browser/themes/gnomestripe/browser.css
@@ -1235,16 +1235,20 @@ toolbar[iconsize="small"] #feed-button {
 .notification-anchor-icon:-moz-focusring {
   outline: 1px dotted -moz-DialogText;
 }
 
 #default-notification-icon {
   list-style-image: url(chrome://global/skin/icons/information-16.png);
 }
 
+#identity-notification-icon {
+  list-style-image: url(chrome://mozapps/skin/profile/profileicon.png);
+}
+
 #geo-notification-icon {
   list-style-image: url(chrome://browser/skin/Geolocation-16.png);
 }
 
 #addons-notification-icon {
   list-style-image: url(chrome://mozapps/skin/extensions/extensionGeneric-16.png);
 }
 
@@ -2559,21 +2563,16 @@ stack[anonid=browserStack][responsivemod
 .web-console-frame[animated] {
   transition: height 100ms;
 }
 
 .web-console-splitter {
   box-shadow: 0 -1px 0 0 ThreeDShadow inset, 0 0 0 10px -moz-Dialog inset;
 }
 
-.web-console-panel {
-  -moz-appearance: none;
-  background-color: white;
-}
-
 
 /* Developer Toolbar */
 
 .developer-toolbar-button {
   -moz-appearance: none;
   min-width: 78px;
   min-height: 22px;
   text-shadow: 0 -1px 0 hsla(210,8%,5%,.45);
--- a/browser/themes/gnomestripe/jar.mn
+++ b/browser/themes/gnomestripe/jar.mn
@@ -65,17 +65,17 @@ browser.jar:
   skin/classic/browser/places/calendar.png            (places/calendar.png)
 * skin/classic/browser/places/editBookmarkOverlay.css (places/editBookmarkOverlay.css)
   skin/classic/browser/places/livemark-item.png       (places/livemark-item.png)
   skin/classic/browser/places/pageStarred.png         (places/pageStarred.png)
   skin/classic/browser/places/starred48.png           (places/starred48.png)
   skin/classic/browser/places/unstarred48.png         (places/unstarred48.png)
   skin/classic/browser/places/places.css              (places/places.css)
   skin/classic/browser/places/organizer.css           (places/organizer.css)
-* skin/classic/browser/places/organizer.xml           (places/organizer.xml)
+  skin/classic/browser/places/organizer.xml           (places/organizer.xml)
   skin/classic/browser/places/query.png               (places/query.png)
   skin/classic/browser/places/starPage.png            (places/starPage.png)
   skin/classic/browser/places/tag.png                 (places/tag.png)
   skin/classic/browser/places/toolbarDropMarker.png   (places/toolbarDropMarker.png)
   skin/classic/browser/places/unsortedBookmarks.png   (places/unsortedBookmarks.png)
   skin/classic/browser/places/downloads.png           (places/downloads.png)
   skin/classic/browser/preferences/alwaysAsk.png      (preferences/alwaysAsk.png)
   skin/classic/browser/preferences/mail.png           (preferences/mail.png)
--- a/browser/themes/gnomestripe/places/organizer.xml
+++ b/browser/themes/gnomestripe/places/organizer.xml
@@ -1,13 +1,13 @@
 <?xml version="1.0"?>
 
-# This Source Code Form is subject to the terms of the Mozilla Public
-# License, v. 2.0. If a copy of the MPL was not distributed with this
-# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+<!-- This 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/. -->
 
 <bindings id="organizerBindings"
           xmlns="http://www.mozilla.org/xbl"
           xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
           xmlns:xbl="http://www.mozilla.org/xbl">
 
   <binding id="toolbarbutton-dropdown"
            extends="chrome://global/content/bindings/menu.xml#menu-base">
--- a/browser/themes/pinstripe/browser.css
+++ b/browser/themes/pinstripe/browser.css
@@ -2364,22 +2364,29 @@ toolbarbutton.chevron > .toolbarbutton-m
   box-shadow: 0 0 2px 1px -moz-mac-focusring inset,
               0 0 3px 2px -moz-mac-focusring;
 }
 
 #default-notification-icon {
   list-style-image: url(chrome://global/skin/icons/information-16.png);
 }
 
+#identity-notification-icon {
+  list-style-image: url(chrome://mozapps/skin/profile/profileicon.png);
+}
+
 #geo-notification-icon {
   list-style-image: url(chrome://browser/skin/Geolocation-16.png);
 }
 
+#notification-popup .text-link {
+  color: #fff;
+}
+
 .geolocation-text-link {
-  color: #fff;
   -moz-margin-start: 0; /* override default label margin to match description margin */
 }
 
 .telemetry-text-link {
   color: #fff;
 }
 
 #addons-notification-icon {
@@ -3326,21 +3333,16 @@ stack[anonid=browserStack][responsivemod
 }
 
 .web-console-splitter {
   border-bottom: solid #a5a5a5 1px;
   background: url("chrome://global/skin/splitter/dimple.png") no-repeat center,
     -moz-linear-gradient(top, #fcfcfc, #dfdfdf);
 }
 
-.web-console-panel {
-  -moz-appearance: none;
-  background-color: white;
-}
-
 /* Developer Toolbar */
 
 .developer-toolbar-button {
   -moz-appearance: none;
   min-width: 78px;
   min-height: 22px;
   text-shadow: 0 -1px 0 hsla(210,8%,5%,.45);
   border-radius: @toolbarbuttonCornerRadius@;
--- a/browser/themes/pinstripe/jar.mn
+++ b/browser/themes/pinstripe/jar.mn
@@ -105,17 +105,17 @@ browser.jar:
   skin/classic/browser/preferences/alwaysAsk.png            (preferences/alwaysAsk.png)
   skin/classic/browser/preferences/application.png          (preferences/application.png)
   skin/classic/browser/preferences/Options.png              (preferences/Options.png)
 #ifdef MOZ_SERVICES_SYNC
   skin/classic/browser/preferences/Options-sync.png         (preferences/Options-sync.png)
 #endif
   skin/classic/browser/preferences/saveFile.png             (preferences/saveFile.png)
 * skin/classic/browser/preferences/preferences.css          (preferences/preferences.css)
-* skin/classic/browser/preferences/in-content/preferences.css (preferences/in-content/preferences.css)
+  skin/classic/browser/preferences/in-content/preferences.css (preferences/in-content/preferences.css)
   skin/classic/browser/preferences/applications.css         (preferences/applications.css)
   skin/classic/browser/preferences/aboutPermissions.css     (preferences/aboutPermissions.css)
   skin/classic/browser/social/social.png                    (social/social.png)
   skin/classic/browser/social/panelarrow-down.png           (social/panelarrow-down.png)
   skin/classic/browser/social/panelarrow-horiz.png          (social/panelarrow-horiz.png)
   skin/classic/browser/social/panelarrow-up.png             (social/panelarrow-up.png)
   skin/classic/browser/tabbrowser/alltabs-box-bkgnd-icon.png             (tabbrowser/alltabs-box-bkgnd-icon.png)
   skin/classic/browser/tabbrowser/newtab.png                             (tabbrowser/newtab.png)
--- a/browser/themes/winstripe/browser.css
+++ b/browser/themes/winstripe/browser.css
@@ -2370,16 +2370,20 @@ toolbarbutton.bookmark-item[dragover="tr
   outline: 1px dotted -moz-DialogText;
   outline-offset: -3px;
 }
 
 #default-notification-icon {
   list-style-image: url(chrome://global/skin/icons/information-16.png);
 }
 
+#identity-notification-icon {
+  list-style-image: url(chrome://mozapps/skin/profile/profileicon.png);
+}
+
 #geo-notification-icon {
   list-style-image: url(chrome://browser/skin/Geolocation-16.png);
 }
 
 #addons-notification-icon {
   list-style-image: url(chrome://mozapps/skin/extensions/extensionGeneric-16.png);
 }
 
@@ -3240,21 +3244,16 @@ stack[anonid=browserStack][responsivemod
 .web-console-frame[animated] {
   transition: height 100ms;
 }
 
 .web-console-splitter {
   border-top: none;
 }
 
-.web-console-panel {
-  -moz-appearance: none;
-  background-color: white;
-}
-
 /* Developer Toolbar */
 
 .developer-toolbar-button {
   -moz-appearance: none;
   min-width: 78px;
   min-height: 22px;
   text-shadow: 0 -1px 0 hsla(210,8%,5%,.45);
   border-radius: 3px;
--- a/browser/themes/winstripe/jar.mn
+++ b/browser/themes/winstripe/jar.mn
@@ -42,17 +42,17 @@ browser.jar:
         skin/classic/browser/Privacy-16.png
         skin/classic/browser/Privacy-48.png
         skin/classic/browser/reload-stop-go.png
         skin/classic/browser/Secure24.png                            (Secure24.png)
         skin/classic/browser/Toolbar.png                             (Toolbar.png)
         skin/classic/browser/Toolbar-inverted.png
         skin/classic/browser/toolbarbutton-dropdown-arrow.png
         skin/classic/browser/toolbarbutton-dropdown-arrow-inverted.png
-*       skin/classic/browser/searchbar.css                           (searchbar.css)
+        skin/classic/browser/searchbar.css                           (searchbar.css)
         skin/classic/browser/searchbar-dropdown-arrow.png
         skin/classic/browser/setDesktopBackground.css
         skin/classic/browser/share-button.png
         skin/classic/browser/share-button-active.png
         skin/classic/browser/share-button-shared.png
         skin/classic/browser/menu-back.png                           (menu-back.png)
         skin/classic/browser/menu-forward.png                        (menu-forward.png)
         skin/classic/browser/monitor.png
@@ -244,17 +244,17 @@ browser.jar:
         skin/classic/aero/browser/Privacy-16.png                     (Privacy-16-aero.png)
         skin/classic/aero/browser/Privacy-48.png                     (Privacy-48-aero.png)
         skin/classic/aero/browser/reload-stop-go.png
         skin/classic/aero/browser/Secure24.png                       (Secure24-aero.png)
         skin/classic/aero/browser/Toolbar.png
         skin/classic/aero/browser/Toolbar-inverted.png
         skin/classic/aero/browser/toolbarbutton-dropdown-arrow.png
         skin/classic/aero/browser/toolbarbutton-dropdown-arrow-inverted.png
-*       skin/classic/aero/browser/searchbar.css                      (searchbar.css)
+        skin/classic/aero/browser/searchbar.css                      (searchbar.css)
         skin/classic/aero/browser/searchbar-dropdown-arrow.png       (searchbar-dropdown-arrow-aero.png)
         skin/classic/aero/browser/setDesktopBackground.css
         skin/classic/aero/browser/share-button.png
         skin/classic/aero/browser/share-button-active.png
         skin/classic/aero/browser/share-button-shared.png
         skin/classic/aero/browser/menu-back.png                      (menu-back-aero.png)
         skin/classic/aero/browser/menu-forward.png                   (menu-forward-aero.png)
         skin/classic/aero/browser/monitor.png
--- a/build/mobile/devicemanager.py
+++ b/build/mobile/devicemanager.py
@@ -1,13 +1,12 @@
 # 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/.
 
-import time
 import hashlib
 import socket
 import os
 import re
 import StringIO
 
 class FileError(Exception):
   " Signifies an error which occurs while doing a file operation."
--- a/build/mobile/devicemanagerADB.py
+++ b/build/mobile/devicemanagerADB.py
@@ -1,18 +1,18 @@
 # 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/.
 
 import subprocess
 from devicemanager import DeviceManager, DMError, _pop_last_line
 import re
 import os
-import sys
 import tempfile
+import time
 
 class DeviceManagerADB(DeviceManager):
 
   def __init__(self, host=None, port=20701, retrylimit=5, packageName='fennec',
                adbPath='adb', deviceSerial=None, deviceRoot=None):
     self.host = host
     self.port = port
     self.retrylimit = retrylimit
@@ -60,17 +60,17 @@ class DeviceManagerADB(DeviceManager):
     except DMError:
       pass
 
     # Can we run things as root? (currently not required)
     useRunAsTmp = self.useRunAs
     self.useRunAs = False
     try:
       self.verifyRoot()
-    except DMError, e:
+    except DMError:
       try:
         self.checkCmd(["root"])
         # The root command does not fail even if ADB cannot get
         # root rights (e.g. due to production builds), so we have
         # to check again ourselves that we have root now.
         self.verifyRoot()
       except DMError:
         if useRunAsTmp:
@@ -389,17 +389,19 @@ class DeviceManagerADB(DeviceManager):
     didKillProcess = False
     for (pid, name, user) in procs:
       if name == appname:
          args = ["shell", "kill"]
          if forceKill:
            args.append("-9")
          args.append(pid)
          p = self.runCmdAs(args)
-         didKillProcess = True
+         p.communicate()
+         if p.returncode == 0:
+             didKillProcess = True
 
     return didKillProcess
 
   # external function
   # returns:
   #  success: filecontents
   #  failure: None
   def catFile(self, remoteFile):
@@ -494,21 +496,21 @@ class DeviceManagerADB(DeviceManager):
     return self.getRemoteHash(remoteFile) == self.getLocalHash(localFile)
 
   # return the md5 sum of a remote file
   # internal function
   # returns:
   #  success: MD5 hash for given filename
   #  failure: None
   def getRemoteHash(self, filename):
-    data = p = self.runCmd(["shell", "ls", "-l", filename]).stdout.read()
+    data = self.runCmd(["shell", "ls", "-l", filename]).stdout.read()
     return data.split()[3]
 
   def getLocalHash(self, filename):
-    data = p = subprocess.Popen(["ls", "-l", filename], stdout=subprocess.PIPE).stdout.read()
+    data = subprocess.Popen(["ls", "-l", filename], stdout=subprocess.PIPE).stdout.read()
     return data.split()[4]
 
   # Internal method to setup the device root and cache its value
   def setupDeviceRoot(self):
     # if self.deviceRoot is already set, create it if necessary, and use it
     if self.deviceRoot:
       if not self.dirExists(self.deviceRoot):
         if not self.mkDir(self.deviceRoot):
@@ -688,17 +690,17 @@ class DeviceManagerADB(DeviceManager):
     if (directive == "process" or directive == "all"):
       ret["process"] = self.runCmd(["shell", "ps"]).stdout.read()
     if (directive == "systime" or directive == "all"):
       ret["systime"] = self.runCmd(["shell", "date"]).stdout.read()
     print ret
     return ret
 
   def runCmd(self, args):
-    # If we are not root but have run-as, and we're trying to execute 
+    # If we are not root but have run-as, and we're trying to execute
     # a shell command then using run-as is the best we can do
     finalArgs = [self.adbPath]
     if self.deviceSerial:
       finalArgs.extend(['-s', self.deviceSerial])
     if (not self.haveRoot and self.useRunAs and args[0] == "shell" and args[1] != "run-as"):
       args.insert(1, "run-as")
       args.insert(2, self.packageName)
     finalArgs.extend(args)
@@ -706,17 +708,17 @@ class DeviceManagerADB(DeviceManager):
 
   def runCmdAs(self, args):
     if self.useRunAs:
       args.insert(1, "run-as")
       args.insert(2, self.packageName)
     return self.runCmd(args)
 
   def checkCmd(self, args):
-    # If we are not root but have run-as, and we're trying to execute 
+    # If we are not root but have run-as, and we're trying to execute
     # a shell command then using run-as is the best we can do
     finalArgs = [self.adbPath]
     if self.deviceSerial:
       finalArgs.extend(['-s', self.deviceSerial])
     if (not self.haveRoot and self.useRunAs and args[0] == "shell" and args[1] != "run-as"):
       args.insert(1, "run-as")
       args.insert(2, self.packageName)
     finalArgs.extend(args)
--- a/build/mobile/devicemanagerSUT.py
+++ b/build/mobile/devicemanagerSUT.py
@@ -1,26 +1,23 @@
 # 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/.
 
 import select
 import socket
 import SocketServer
-import time, datetime
+import time
 import os
 import re
-import hashlib
 import posixpath
 import subprocess
 from threading import Thread
-import traceback
-import sys
 import StringIO
-from devicemanager import DeviceManager, DMError, FileError, NetworkTools, _pop_last_line
+from devicemanager import DeviceManager, FileError, NetworkTools, _pop_last_line
 import errno
 
 class AgentError(Exception):
   "SUTAgent-specific exception."
 
   def __init__(self, msg= '', fatal = False):
     self.msg = msg
     self.fatal = fatal
@@ -121,17 +118,16 @@ class DeviceManagerSUT(DeviceManager):
     '''
     a wrapper for _doCmds that loops up to self.retrylimit iterations.
     this allows us to move the retry logic outside of the _doCmds() to make it
     easier for debugging in the future.
     note that since cmdlist is a list of commands, they will all be retried if
     one fails.  this is necessary in particular for pushFile(), where we don't want
     to accidentally send extra data if a failure occurs during data transmission.
     '''
-    done = False
     while self.retries < self.retrylimit:
       try:
         self._doCmds(cmdlist, outputfile, timeout)
         return
       except AgentError, err:
         # re-raise error if it's fatal (i.e. the device got the command but
         # couldn't execute it). retry otherwise
         if err.fatal:
@@ -182,17 +178,17 @@ class DeviceManagerSUT(DeviceManager):
         sent = self._sock.send(cmdline)
         if sent != len(cmdline):
           raise AgentError("ERROR: our cmd was %s bytes and we "
                            "only sent %s" % (len(cmdline), sent))
         if cmd.get('data'):
           sent = self._sock.send(cmd['data'])
           if sent != len(cmd['data']):
               raise AgentError("ERROR: we had %s bytes of data to send, but "
-                               "only sent %s" % (len(cmd['data'], sent)))
+                               "only sent %s" % (len(cmd['data']), sent))
 
         if (self.debug >= 4): print "sent cmd: " + str(cmd['cmd'])
       except socket.error, msg:
         self._sock.close()
         self._sock = None
         if self.debug >= 1:
           print "Error sending data to socket. cmd="+str(cmd['cmd'])+"; err="+str(msg)
         return False
@@ -498,17 +494,17 @@ class DeviceManagerSUT(DeviceManager):
     if (self.debug >= 2): print "FIRE PROC: '" + appname + "'"
 
     if (self.processExist(appname) != None):
       print "WARNING: process %s appears to be running already\n" % appname
       if (failIfRunning):
         return None
 
     try:
-      data = self.runCmds([{ 'cmd': 'exec ' + appname }])
+      self.runCmds([{ 'cmd': 'exec ' + appname }])
     except AgentError:
       return None
 
     # The 'exec' command may wait for the process to start and end, so checking
     # for the process here may result in process = None.
     process = self.processExist(appname)
     if (self.debug >= 4): print "got pid: %s for process: %s" % (process, appname)
 
@@ -542,17 +538,17 @@ class DeviceManagerSUT(DeviceManager):
   # external function
   # returns:
   #  success: True
   #  failure: False
   def killProcess(self, appname, forceKill=False):
     if forceKill:
       print "WARNING: killProcess(): forceKill parameter unsupported on SUT"
     try:
-      data = self.runCmds([{ 'cmd': 'kill ' + appname }])
+      self.runCmds([{ 'cmd': 'kill ' + appname }])
     except AgentError:
       return False
 
     return True
 
   # external function
   # returns:
   #  success: tmpdir, string
@@ -635,17 +631,18 @@ class DeviceManagerSUT(DeviceManager):
     prompt = self.base_prompt + self.prompt_sep
     buffer = ''
 
     # expected return value:
     # <filename>,<filesize>\n<filedata>
     # or, if error,
     # <filename>,-1\n<error message>
     try:
-      data = self.runCmds([{ 'cmd': 'pull ' + remoteFile }])
+      # just send the command first, we read the response inline below
+      self.runCmds([{ 'cmd': 'pull ' + remoteFile }])
     except AgentError:
       return None
 
     # read metadata; buffer the rest
     metadata, sep, buffer = read_until_char('\n', buffer, 'could not find metadata')
     if not metadata:
       return None
     if self.debug >= 3:
@@ -875,17 +872,16 @@ class DeviceManagerSUT(DeviceManager):
   # external function
   # returns:
   #  success: status from test agent
   #  failure: None
   def reboot(self, ipAddr=None, port=30000):
     cmd = 'rebt'
 
     if (self.debug > 3): print "INFO: sending rebt command"
-    callbacksvrstatus = None
 
     if (ipAddr is not None):
     #create update.info file:
       try:
         destname = '/data/data/com.mozilla.SUTAgentAndroid/files/update.info'
         data = "%s,%s\rrebooting\r" % (ipAddr, port)
         self.runCmds([{ 'cmd': 'push %s %s' % (destname, len(data)),
                         'data': data }])
--- a/build/mobile/emulator.py
+++ b/build/mobile/emulator.py
@@ -263,20 +263,19 @@ class Emulator(object):
             using any availble local port, and return the local port.
         """
 
         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         s.bind(("", 0))
         local_port = s.getsockname()[1]
         s.close()
 
-        output = self._run_adb(['-s', 'emulator-%d' % self.port,
-                                'forward',
-                                'tcp:%d' % local_port,
-                                'tcp:%d' % remote_port])
+        self._run_adb(['-s', 'emulator-%d' % self.port, 'forward',
+                       'tcp:%d' % local_port,
+                       'tcp:%d' % remote_port])
 
         self.local_port = local_port
 
         return local_port
 
     def wait_for_port(self, timeout=300):
         assert(self.local_port)
         starttime = datetime.datetime.now()
--- a/build/mobile/remoteautomation.py
+++ b/build/mobile/remoteautomation.py
@@ -1,48 +1,47 @@
 # 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/.
 
 import time
-import sys
 import os
-import socket
 import automationutils
 import tempfile
 import shutil
+import subprocess
 
 from automation import Automation
-from devicemanager import DeviceManager, NetworkTools
+from devicemanager import NetworkTools
 
 class RemoteAutomation(Automation):
     _devicemanager = None
-    
+
     def __init__(self, deviceManager, appName = '', remoteLog = None):
         self._devicemanager = deviceManager
         self._appName = appName
         self._remoteProfile = None
         self._remoteLog = remoteLog
 
         # Default our product to fennec
         self._product = "fennec"
         Automation.__init__(self)
 
     def setDeviceManager(self, deviceManager):
         self._devicemanager = deviceManager
-        
+
     def setAppName(self, appName):
         self._appName = appName
 
     def setRemoteProfile(self, remoteProfile):
         self._remoteProfile = remoteProfile
 
     def setProduct(self, product):
         self._product = product
-        
+
     def setRemoteLog(self, logfile):
         self._remoteLog = logfile
 
     # Set up what we need for the remote environment
     def environment(self, env = None, xrePath = None, crashreporter = True):
         # Because we are running remote, we don't want to mimic the local env
         # so no copying of os.environ
         if env is None:
@@ -83,21 +82,21 @@ class RemoteAutomation(Automation):
         except:
           print "WARNING: unable to remove directory: %s" % (dumpDir)
 
     def buildCommandLine(self, app, debuggerInfo, profileDir, testURL, extraArgs):
         # If remote profile is specified, use that instead
         if (self._remoteProfile):
             profileDir = self._remoteProfile
 
-        # Hack for robocop, if app & testURL == None and extraArgs contains the rest of the stuff, lets 
+        # Hack for robocop, if app & testURL == None and extraArgs contains the rest of the stuff, lets
         # assume extraArgs is all we need
         if app == "am" and extraArgs[0] == "instrument":
             return app, extraArgs
- 
+
         cmd, args = Automation.buildCommandLine(self, app, debuggerInfo, profileDir, testURL, extraArgs)
         # Remove -foreground if it exists, if it doesn't this just returns
         try:
             args.remove('-foreground')
         except:
             pass
 #TODO: figure out which platform require NO_EM_RESTART
 #        return app, ['--environ:NO_EM_RESTART=1'] + args
@@ -108,17 +107,17 @@ class RemoteAutomation(Automation):
         return nettools.getLanIp()
 
     def Process(self, cmd, stdout = None, stderr = None, env = None, cwd = None):
         if stdout == None or stdout == -1 or stdout == subprocess.PIPE:
           stdout = self._remoteLog
 
         return self.RProcess(self._devicemanager, cmd, stdout, stderr, env, cwd)
 
-    # be careful here as this inner class doesn't have access to outer class members    
+    # be careful here as this inner class doesn't have access to outer class members
     class RProcess(object):
         # device manager process
         dm = None
         def __init__(self, dm, cmd, stdout = None, stderr = None, env = None, cwd = None):
             self.dm = dm
             self.stdoutlen = 0
             self.proc = dm.launchProcess(cmd, stdout, cwd, env, True)
             if (self.proc is None):
@@ -157,26 +156,26 @@ class RemoteAutomation(Automation):
             time.sleep(1)
 
         @property
         def pid(self):
             hexpid = self.dm.processExist(self.procName)
             if (hexpid == None):
                 hexpid = "0x0"
             return int(hexpid, 0)
-    
+
         @property
         def stdout(self):
             t = self.dm.getFile(self.proc)
             if t == None: return ''
             tlen = len(t)
             retVal = t[self.stdoutlen:]
             self.stdoutlen = tlen
             return retVal.strip('\n').strip()
- 
+
         def wait(self, timeout = None):
             timer = 0
             interval = 5
 
             if timeout == None:
                 timeout = self.timeout
 
             while (self.dm.processExist(self.procName)):
@@ -185,11 +184,11 @@ class RemoteAutomation(Automation):
                 time.sleep(interval)
                 timer += interval
                 if (timer > timeout):
                     break
 
             if (timer >= timeout):
                 return 1
             return 0
- 
+
         def kill(self):
             self.dm.killProcess(self.procName)
--- a/build/mobile/robocop/FennecNativeActions.java.in
+++ b/build/mobile/robocop/FennecNativeActions.java.in
@@ -1,24 +1,19 @@
 #filter substitution
 /* 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/. */
 
 package @ANDROID_PACKAGE_NAME@;
 
-import java.lang.Class;
-import java.lang.ClassLoader;
-import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.lang.reflect.InvocationHandler;
-import java.lang.Long;
-import java.lang.NoSuchMethodException;
 import java.util.concurrent.SynchronousQueue;
 import java.util.ArrayList;
 
 import android.app.Activity;
 import android.content.Context;
 import android.app.Instrumentation;
 import android.database.Cursor;
 import android.os.SystemClock;
@@ -35,58 +30,49 @@ import static @ANDROID_PACKAGE_NAME@.Fen
 public class FennecNativeActions implements Actions {
     private Solo mSolo;
     private Instrumentation mInstr;
     private Activity mGeckoApp;
     private Assert mAsserter;
 
     // Objects for reflexive access of fennec classes.
     private ClassLoader mClassLoader;
-    private Class mGel;
-    private Class mGe;
-    private Class mGas;
-    private Class mDrawListener;
-    private Method mRegisterGEL;
-    private Method mUnregisterGEL;
-    private Method mSendGE;
-    private Method mGetLayerClient;
+    private Class mApiClass;
+    private Class mEventListenerClass;
+    private Class mDrawListenerClass;
+    private Method mRegisterEventListener;
+    private Method mUnregisterEventListener;
+    private Method mBroadcastEvent;
     private Method mSetDrawListener;
+    private Method mQuerySql;
+    private Object mRobocopApi;
+
     private static final String LOGTAG = "FennecNativeActions";
 
     public FennecNativeActions(Activity activity, Solo robocop, Instrumentation instrumentation, Assert asserter) {
         mSolo = robocop;
         mInstr = instrumentation;
         mGeckoApp = activity;
         mAsserter = asserter;
         // Set up reflexive access of java classes and methods.
         try {
             mClassLoader = activity.getClassLoader();
-            mGel = mClassLoader.loadClass("org.mozilla.gecko.util.GeckoEventListener");
-            mGe = mClassLoader.loadClass("org.mozilla.gecko.GeckoEvent");
-            mGas = mClassLoader.loadClass("org.mozilla.gecko.GeckoAppShell");
-            Class [] parameters = new Class[2];
-            parameters[0] = String.class;
-            parameters[1] = mGel;
-            mRegisterGEL = mGas.getMethod("registerEventListener", parameters);
-            mUnregisterGEL = mGas.getMethod("unregisterEventListener", parameters);
-            parameters = new Class[1];
-            parameters[0] = mGe;
-            mSendGE = mGas.getMethod("sendEventToGecko", parameters);
+
+            mApiClass = mClassLoader.loadClass("org.mozilla.gecko.RobocopAPI");
+            mEventListenerClass = mClassLoader.loadClass("org.mozilla.gecko.util.GeckoEventListener");
+            mDrawListenerClass = mClassLoader.loadClass("org.mozilla.gecko.gfx.GeckoLayerClient$DrawListener");
 
-            mGetLayerClient = activity.getClass().getMethod("getLayerClient");
-            Class gslc = mClassLoader.loadClass("org.mozilla.gecko.gfx.GeckoLayerClient");
-            mDrawListener = mClassLoader.loadClass("org.mozilla.gecko.gfx.GeckoLayerClient$DrawListener");
-            mSetDrawListener = gslc.getDeclaredMethod("setDrawListener", mDrawListener);
-        } catch (ClassNotFoundException e) {
-            FennecNativeDriver.log(LogLevel.ERROR, e);
-        } catch (SecurityException e) {
-            FennecNativeDriver.log(LogLevel.ERROR, e);
-        } catch (NoSuchMethodException e) {
-            FennecNativeDriver.log(LogLevel.ERROR, e);
-        } catch (IllegalArgumentException e) {
+            mRegisterEventListener = mApiClass.getMethod("registerEventListener", String.class, mEventListenerClass);
+            mUnregisterEventListener = mApiClass.getMethod("unregisterEventListener", String.class, mEventListenerClass);
+            mBroadcastEvent = mApiClass.getMethod("broadcastEvent", String.class, String.class);
+            mSetDrawListener = mApiClass.getMethod("setDrawListener", mDrawListenerClass);
+            mQuerySql = mApiClass.getMethod("querySql", String.class, String.class);
+
+            mRobocopApi = mApiClass.getConstructor(Activity.class).newInstance(activity);
+        } catch (Exception e) {
             FennecNativeDriver.log(LogLevel.ERROR, e);
         }
     }
 
     class wakeInvocationHandler implements InvocationHandler {
         private final GeckoEventExpecter mEventExpecter;
 
         public wakeInvocationHandler(GeckoEventExpecter expecter) {
@@ -139,17 +125,17 @@ public class FennecNativeActions impleme
                 endTime = SystemClock.uptimeMillis();
                 if (!mEventReceived && (endTime - startTime >= MAX_WAIT_MS)) {
                     mAsserter.ok(false, "GeckoEventExpecter", 
                         "blockForEvent timeout: "+mGeckoEvent);
                     return;
                 }
             }
             try {
-                mUnregisterGEL.invoke(null, mRegistrationParams);
+                mUnregisterEventListener.invoke(mRobocopApi, mRegistrationParams);
             } catch (IllegalAccessException e) {
                 FennecNativeDriver.log(LogLevel.ERROR, e);
             } catch (InvocationTargetException e) {
                 FennecNativeDriver.log(LogLevel.ERROR, e);
             }
             FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
                 "unblocked on expecter for " + mGeckoEvent);
         }
@@ -187,17 +173,17 @@ public class FennecNativeActions impleme
                 if (endTime - startTime >= millis) {
                     // success
                     break;
                 }
                 // we got a notify() before we could wait long enough, so we need to start over
                 startTime = endTime;
             }
             try {
-                mUnregisterGEL.invoke(null, mRegistrationParams);
+                mUnregisterEventListener.invoke(mRobocopApi, mRegistrationParams);
             } catch (IllegalAccessException e) {
                 FennecNativeDriver.log(LogLevel.ERROR, e);
             } catch (InvocationTargetException e) {
                 FennecNativeDriver.log(LogLevel.ERROR, e);
             }
             FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
                 "unblocked on expecter for " + mGeckoEvent);
         }
@@ -215,43 +201,36 @@ public class FennecNativeActions impleme
             }
         }
     }
     
     public RepeatedEventExpecter expectGeckoEvent(String geckoEvent) {
         FennecNativeDriver.log(FennecNativeDriver.LogLevel.DEBUG,
             "waiting for "+geckoEvent);
         try {
-            Class [] interfaces = new Class[1];
-            interfaces[0] = mGel;
             Object[] finalParams = new Object[2];
             finalParams[0] = geckoEvent;
-         
             GeckoEventExpecter expecter = new GeckoEventExpecter(geckoEvent, finalParams);
             wakeInvocationHandler wIH = new wakeInvocationHandler(expecter);
-            Object proxy = Proxy.newProxyInstance(mClassLoader, interfaces, wIH);
+            Object proxy = Proxy.newProxyInstance(mClassLoader, new Class[] { mEventListenerClass }, wIH);
             finalParams[1] = proxy;
-            mRegisterGEL.invoke(null, finalParams);
-            
+
+            mRegisterEventListener.invoke(mRobocopApi, finalParams);
             return expecter;
         } catch (IllegalAccessException e) {
             FennecNativeDriver.log(LogLevel.ERROR, e);
         } catch (InvocationTargetException e) {
             FennecNativeDriver.log(LogLevel.ERROR, e);
         }
         return null;
     }
 
     public void sendGeckoEvent(String geckoEvent, String data) {
         try {
-            Method cbe = mGe.getMethod("createBroadcastEvent", String.class, String.class);
-            Object event = cbe.invoke(null, geckoEvent, data);
-            mSendGE.invoke(null, event);
-        } catch (NoSuchMethodException e) {
-            FennecNativeDriver.log(LogLevel.ERROR, e);
+            mBroadcastEvent.invoke(mRobocopApi, geckoEvent, data);
         } catch (IllegalAccessException e) {
             FennecNativeDriver.log(LogLevel.ERROR, e);
         } catch (InvocationTargetException e) {
             FennecNativeDriver.log(LogLevel.ERROR, e);
         }
     }
 
     class DrawListenerProxy implements InvocationHandler {
@@ -279,18 +258,18 @@ public class FennecNativeActions impleme
     }
 
     class PaintExpecter implements RepeatedEventExpecter {
         private Object mLayerClient;
         private boolean mPaintDone;
         private static final int MAX_WAIT_MS = 90000;
 
         PaintExpecter() throws IllegalAccessException, InvocationTargetException {
-            mLayerClient = mGetLayerClient.invoke(mGeckoApp);
-            mSetDrawListener.invoke(mLayerClient, Proxy.newProxyInstance(mClassLoader, new Class[] { mDrawListener }, new DrawListenerProxy(this)));
+            Object proxy = Proxy.newProxyInstance(mClassLoader, new Class[] { mDrawListenerClass }, new DrawListenerProxy(this));
+            mSetDrawListener.invoke(mRobocopApi, proxy);
         }
 
         void notifyOfEvent() {
             synchronized (this) {
                 mPaintDone = true;
                 this.notifyAll();
             }
         }
@@ -307,17 +286,17 @@ public class FennecNativeActions impleme
                 }
                 endTime = SystemClock.uptimeMillis();
                 if (!mPaintDone && (endTime - startTime >= MAX_WAIT_MS)) {
                     mAsserter.ok(false, "PaintExpecter", "blockForEvent timeout");
                     return;
                 }
             }
             try {
-                mSetDrawListener.invoke(mLayerClient, (Object)null);
+                mSetDrawListener.invoke(mRobocopApi, (Object)null);
             } catch (Exception e) {
                 FennecNativeDriver.log(LogLevel.ERROR, e);
             }
         }
 
         public synchronized boolean eventReceived() {
             return mPaintDone;
         }
@@ -355,17 +334,17 @@ public class FennecNativeActions impleme
                 if (endTime - startTime >= millis) {
                     // success
                     break;
                 }
                 // we got a notify() before we could wait long enough, so we need to start over
                 startTime = endTime;
             }
             try {
-                mSetDrawListener.invoke(mLayerClient, (Object)null);
+                mSetDrawListener.invoke(mRobocopApi, (Object)null);
             } catch (Exception e) {
                 FennecNativeDriver.log(LogLevel.ERROR, e);
             }
         }
     }
 
     public RepeatedEventExpecter expectPaint() {
         try {
@@ -410,38 +389,17 @@ public class FennecNativeActions impleme
     }
 
     public void drag(int startingX, int endingX, int startingY, int endingY) {
         mSolo.drag(startingX, endingX, startingY, endingY, 10);
     }
 
     public Cursor querySql(String dbPath, String sql) {
         try {
-            ClassLoader classLoader = mGeckoApp.getClassLoader();
-            Class sqlClass = classLoader.loadClass("org.mozilla.gecko.sqlite.SQLiteBridge");
-            Class stringClass = String.class;
-            Class stringArrayClass = String[].class;
-            Class appshell = classLoader.loadClass("org.mozilla.gecko.GeckoAppShell");
-            Class contextClass = Context.class;
-    
-            Constructor bridgeConstructor = sqlClass.getConstructor(stringClass);
-            Method query = sqlClass.getMethod("rawQuery", stringClass, stringArrayClass);
-            Method loadSQLiteLibs = appshell.getMethod("loadSQLiteLibs", contextClass, stringClass);
-    
-            Object bridge = bridgeConstructor.newInstance(dbPath);
-    
-            String resourcePath = mGeckoApp.getApplication().getPackageResourcePath();
-            loadSQLiteLibs.invoke(null, mGeckoApp, resourcePath);
-            return (Cursor)query.invoke(bridge, sql, null);
-        } catch(ClassNotFoundException ex) {
-            Log.e(LOGTAG, "Error getting class", ex);
-        } catch(NoSuchMethodException ex) {
-            Log.e(LOGTAG, "Error getting method", ex);
+            return (Cursor)mQuerySql.invoke(mRobocopApi, dbPath, sql);
         } catch(InvocationTargetException ex) {
             Log.e(LOGTAG, "Error invoking method", ex);
-        } catch(InstantiationException ex) {
-            Log.e(LOGTAG, "Error calling constructor", ex);
         } catch(IllegalAccessException ex) {
             Log.e(LOGTAG, "Error using field", ex);
         }
         return null;
     }
 }
--- a/build/mobile/robocop/FennecNativeDriver.java.in
+++ b/build/mobile/robocop/FennecNativeDriver.java.in
@@ -13,23 +13,22 @@ import java.io.FileReader;
 import java.io.FileWriter;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.PrintWriter;
 import java.nio.IntBuffer;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
-import java.lang.Class;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.lang.reflect.InvocationHandler;
-import java.lang.Long;
 
 import android.app.Activity;
 import android.opengl.GLSurfaceView;
 import android.view.View;
 import android.util.Log;
 
 import org.json.*;
 
@@ -43,27 +42,26 @@ public class FennecNativeDriver implemen
     private Activity mActivity;
     private Solo mSolo;
 
     private static String mLogFile = null;
     private static LogLevel mLogLevel = LogLevel.INFO;
 
     // Objects for reflexive access of fennec classes.
     private ClassLoader mClassLoader;
-    private Class mGel;
-    private Class mGe;
-    private Class mGas;
-    private Method mRegisterGEL;
-    private Method mUnregisterGEL;
-    private Method mSendGE;
-    private Method _startFrameRecording;
-    private Method _stopFrameRecording;
-    private Method _startCheckerboardRecording;
-    private Method _stopCheckerboardRecording;
-    private Method _getPixels;
+    private Class mApiClass;
+    private Class mEventListenerClass;
+    private Class mPanningPerfClass;
+    private Method mRegisterEventListener;
+    private Method mGetPixels;
+    private Method mStartFrameRecording;
+    private Method mStopFrameRecording;
+    private Method mStartCheckerboardRecording;
+    private Method mStopCheckerboardRecording;
+    private Object mRobocopApi;
 
     public enum LogLevel {
         DEBUG(1),
         INFO(2),
         WARN(3),
         ERROR(4);
 
         private int mValue;
@@ -83,43 +81,30 @@ public class FennecNativeDriver implemen
         mSolo = robocop;
 
         // Set up table of fennec_ids.
         mLocators = convertTextToTable(getFile("/mnt/sdcard/fennec_ids.txt"));
 
         // Set up reflexive access of java classes and methods.
         try {
             mClassLoader = activity.getClassLoader();
-            mGel = mClassLoader.loadClass("org.mozilla.gecko.util.GeckoEventListener");
-            mGe = mClassLoader.loadClass("org.mozilla.gecko.GeckoEvent");
-            mGas = mClassLoader.loadClass("org.mozilla.gecko.GeckoAppShell");
-            Class [] parameters = new Class[2];
-            parameters[0] = String.class;
-            parameters[1] = mGel;
-            mRegisterGEL = mGas.getMethod("registerEventListener", parameters);
-            mUnregisterGEL = mGas.getMethod("unregisterEventListener", parameters);
-            parameters = new Class[1];
-            parameters[0] = mGe;
-            mSendGE = mGas.getMethod("sendEventToGecko", parameters);
+
+            mApiClass = mClassLoader.loadClass("org.mozilla.gecko.RobocopAPI");
+            mEventListenerClass = mClassLoader.loadClass("org.mozilla.gecko.util.GeckoEventListener");
+            mPanningPerfClass = mClassLoader.loadClass("org.mozilla.gecko.gfx.PanningPerfAPI");
 
-            Class gfx = mClassLoader.loadClass("org.mozilla.gecko.gfx.PanningPerfAPI");
-            _startFrameRecording = gfx.getDeclaredMethod("startFrameTimeRecording");
-            _stopFrameRecording = gfx.getDeclaredMethod("stopFrameTimeRecording");
-            _startCheckerboardRecording = gfx.getDeclaredMethod("startCheckerboardRecording");
-            _stopCheckerboardRecording = gfx.getDeclaredMethod("stopCheckerboardRecording");
+            mRegisterEventListener = mApiClass.getMethod("registerEventListener", String.class, mEventListenerClass);
+            mGetPixels = mApiClass.getMethod("getViewPixels", View.class);
+            mStartFrameRecording = mPanningPerfClass.getDeclaredMethod("startFrameTimeRecording");
+            mStopFrameRecording = mPanningPerfClass.getDeclaredMethod("stopFrameTimeRecording");
+            mStartCheckerboardRecording = mPanningPerfClass.getDeclaredMethod("startCheckerboardRecording");
+            mStopCheckerboardRecording = mPanningPerfClass.getDeclaredMethod("stopCheckerboardRecording");
 
-            Class layerView = mClassLoader.loadClass("org.mozilla.gecko.gfx.LayerView");
-            _getPixels = layerView.getDeclaredMethod("getPixels");
-        } catch (ClassNotFoundException e) {
-            log(LogLevel.ERROR, e);
-        } catch (SecurityException e) {
-            log(LogLevel.ERROR, e);
-        } catch (NoSuchMethodException e) {
-            log(LogLevel.ERROR, e);
-        } catch (IllegalArgumentException e) {
+            mRobocopApi = mApiClass.getConstructor(Activity.class).newInstance(activity);
+        } catch (Exception e) {
             log(LogLevel.ERROR, e);
         }
     }
 
     //Information on the location of the Gecko Frame.
     private boolean mGeckoInfo = false;
     private int mGeckoTop = 100;
     private int mGeckoLeft = 0;
@@ -183,32 +168,27 @@ public class FennecNativeDriver implemen
         }
         FennecNativeDriver.log(FennecNativeDriver.LogLevel.ERROR,
             "findElement: Element '"+name+"' does not exist in the list");
         return null;
     }
 
     public void startFrameRecording() {
         try {
-            Object [] params = null;
-            _startFrameRecording.invoke(null, params);
+            mStartFrameRecording.invoke(null);
         } catch (IllegalAccessException e) {
             log(LogLevel.ERROR, e);
         } catch (InvocationTargetException e) {
             log(LogLevel.ERROR, e);
         }
     }
 
     public int stopFrameRecording() {
-        Class [] parameters = new Class[1];
-        parameters[0] = null;
-
         try {
-            Object [] params = null;
-            List<Long> frames = (List<Long>)_stopFrameRecording.invoke(null, params);
+            List<Long> frames = (List<Long>)mStopFrameRecording.invoke(null);
             int badness = 0;
             for (int i = 1; i < frames.size(); i++) {
                 long frameTime = frames.get(i) - frames.get(i - 1);
                 int delay = (int)(frameTime - FRAME_TIME_THRESHOLD);
                 // for each frame we miss, add the square of the delay. This
                 // makes large delays much worse than small delays.
                 if (delay > 0) {
                     badness += delay * delay;
@@ -224,32 +204,27 @@ public class FennecNativeDriver implemen
         }
 
         // higher values are worse, and the test failing is the worst!
         return Integer.MAX_VALUE;
     }
 
     public void startCheckerboardRecording() {
         try {
-            Object [] params = null;
-            _startCheckerboardRecording.invoke(null, params);
+            mStartCheckerboardRecording.invoke(null);
         } catch (IllegalAccessException e) {
             log(LogLevel.ERROR, e);
         } catch (InvocationTargetException e) {
             log(LogLevel.ERROR, e);
         }
     }
 
     public float stopCheckerboardRecording() {
-        Class [] parameters = new Class[1];
-        parameters[0] = null;
-
         try {
-            Object [] params = null;
-            List<Float> checkerboard = (List<Float>)_stopCheckerboardRecording.invoke(null, params);
+            List<Float> checkerboard = (List<Float>)mStopCheckerboardRecording.invoke(null);
             float total = 0;
             for (float val : checkerboard) {
                 total += val;
             }
             return total * 100.0f;
         } catch (IllegalAccessException e) {
             log(LogLevel.ERROR, e);
         } catch (InvocationTargetException e) {
@@ -275,17 +250,17 @@ public class FennecNativeDriver implemen
 
     public PaintedSurface getPaintedSurface() {
         View view = getSurfaceView();
         if (view == null) {
             return null;
         }
         IntBuffer pixelBuffer;
         try {
-            pixelBuffer = (IntBuffer)_getPixels.invoke(view);
+            pixelBuffer = (IntBuffer)mGetPixels.invoke(mRobocopApi, view);
         } catch (Exception e) {
             log(LogLevel.ERROR, e);
             return null;
         }
 
         // now we need to (1) flip the image, because GL likes to do things up-side-down,
         // and (2) rearrange the bits from AGBR-8888 to ARGB-8888.
         int w = view.getWidth();
@@ -362,21 +337,21 @@ public class FennecNativeDriver implemen
     public int getHeight() {
         return mHeight;
     }
 
     public void setupScrollHandling() {
         //Setup scrollHandler to catch "robocop:scroll" events. 
         try {
             Class [] interfaces = new Class[1];
-            interfaces[0] = mGel;
+            interfaces[0] = mEventListenerClass;
             Object[] finalParams = new Object[2];
             finalParams[0] = "robocop:scroll";
             finalParams[1] = Proxy.newProxyInstance(mClassLoader, interfaces, new scrollHandler());
-            mRegisterGEL.invoke(null, finalParams);
+            mRegisterEventListener.invoke(mRobocopApi, finalParams);
         } catch (IllegalAccessException e) {
             log(LogLevel.ERROR, e);
         } catch (InvocationTargetException e) {
             log(LogLevel.ERROR, e);
         }
 
     }
 
@@ -417,16 +392,30 @@ public class FennecNativeDriver implemen
         String[] lines = data.split("\n");
         for (int i = 0; i < lines.length; i++) {
             String[] parts = lines[i].split("=");
             retVal.put(parts[0].trim(), parts[1].trim());
         }
         return retVal;
     }
 
+    public static void logAllStackTraces(LogLevel level) {
+        StringBuffer sb = new StringBuffer();
+        sb.append("Dumping ALL the threads!\n");
+        Map<Thread, StackTraceElement[]> allStacks = Thread.getAllStackTraces();
+        for (Thread t : allStacks.keySet()) {
+            sb.append(t.toString()).append('\n');
+            for (StackTraceElement ste : allStacks.get(t)) {
+                sb.append(ste.toString()).append('\n');
+            }
+            sb.append('\n');
+        }
+        log(level, sb.toString());
+    }
+
     /** 
      *  Set the filename used for logging. If the file already exists, delete it
      *  as a safe-guard against accidentally appending to an old log file.
      */
     public static void setLogFile(String filename) {
         mLogFile = filename;
         File file = new File(mLogFile);
         if (file.exists()) {
--- a/build/mobile/robocop/FennecNativeElement.java.in
+++ b/build/mobile/robocop/FennecNativeElement.java.in
@@ -64,16 +64,17 @@ public class FennecNativeElement impleme
                     }
                 }
             });
         try {
             // Wait for the UiThread code to finish running
             if (syncQueue.poll(MAX_WAIT_MS, TimeUnit.MILLISECONDS) == null) {
                 FennecNativeDriver.log(FennecNativeDriver.LogLevel.ERROR, 
                     "click: time-out waiting for UI thread");
+                FennecNativeDriver.logAllStackTraces(FennecNativeDriver.LogLevel.ERROR);
             }
         } catch (InterruptedException e) {
             FennecNativeDriver.log(FennecNativeDriver.LogLevel.ERROR, e);
         }
         return mClickSuccess;
     }
 
     private Object mText;
@@ -116,16 +117,17 @@ public class FennecNativeElement impleme
                 } // end of run() method definition
             } // end of anonymous Runnable object instantiation
         );
         try {     
             // Wait for the UiThread code to finish running
             if (syncQueue.poll(MAX_WAIT_MS, TimeUnit.MILLISECONDS) == null) {
                 FennecNativeDriver.log(FennecNativeDriver.LogLevel.ERROR, 
                     "getText: time-out waiting for UI thread");
+                FennecNativeDriver.logAllStackTraces(FennecNativeDriver.LogLevel.ERROR);
             }
         } catch (InterruptedException e) {
             FennecNativeDriver.log(FennecNativeDriver.LogLevel.ERROR, e);
         }
         if (mText == null) {
             FennecNativeDriver.log(FennecNativeDriver.LogLevel.WARN,
                 "getText: Text is null for view "+mId);
             return null;
@@ -152,16 +154,17 @@ public class FennecNativeElement impleme
                     }
                 }
             });
         try {
             // Wait for the UiThread code to finish running
             if (syncQueue.poll(MAX_WAIT_MS, TimeUnit.MILLISECONDS) == null) {
                 FennecNativeDriver.log(FennecNativeDriver.LogLevel.ERROR, 
                     "isDisplayed: time-out waiting for UI thread");
+                FennecNativeDriver.logAllStackTraces(FennecNativeDriver.LogLevel.ERROR);
             }
         } catch (InterruptedException e) {
             FennecNativeDriver.log(FennecNativeDriver.LogLevel.ERROR, e);
         }
         return mDisplayed;
     }
 
 }
--- a/caps/idl/nsIPrincipal.idl
+++ b/caps/idl/nsIPrincipal.idl
@@ -235,16 +235,28 @@ interface nsIPrincipal : nsISerializable
 
     /**
      * Shows the status of the app.
      * Can be: APP_STATUS_NOT_INSTALLED, APP_STATUS_INSTALLED,
      *         APP_STATUS_PRIVILEGED or APP_STATUS_CERTIFIED.
      */
     readonly attribute unsigned short appStatus;
 
+    %{C++
+    PRUint16 GetAppStatus()
+    {
+      PRUint16 appStatus;
+      nsresult rv = GetAppStatus(&appStatus);
+      if (NS_FAILED(rv)) {
+        return APP_STATUS_NOT_INSTALLED;
+      }
+      return appStatus;
+    }
+    %}
+
     /**
      * Returns the app id the principal is in, or returns
      * nsIScriptSecurityManager::NO_APP_ID if this principal isn't part of an
      * app.
      */
     readonly attribute unsigned long appId;
 
     /**
--- a/caps/src/nsNullPrincipal.cpp
+++ b/caps/src/nsNullPrincipal.cpp
@@ -14,17 +14,17 @@
 #include "nsNullPrincipal.h"
 #include "nsNullPrincipalURI.h"
 #include "nsMemory.h"
 #include "nsIUUIDGenerator.h"
 #include "nsID.h"
 #include "nsNetUtil.h"
 #include "nsIClassInfoImpl.h"
 #include "nsNetCID.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsScriptSecurityManager.h"
 
 using namespace mozilla;
 
 NS_IMPL_CLASSINFO(nsNullPrincipal, NULL, nsIClassInfo::MAIN_THREAD_ONLY,
                   NS_NULLPRINCIPAL_CID)
 NS_IMPL_QUERY_INTERFACE2_CI(nsNullPrincipal,
--- a/caps/src/nsPrincipal.cpp
+++ b/caps/src/nsPrincipal.cpp
@@ -15,17 +15,17 @@
 #include "nsIProtocolHandler.h"
 #include "nsNetUtil.h"
 #include "nsJSPrincipals.h"
 #include "nsVoidArray.h"
 #include "nsHashtable.h"
 #include "nsIObjectInputStream.h"
 #include "nsIObjectOutputStream.h"
 #include "nsIClassInfoImpl.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsContentUtils.h"
 #include "jswrapper.h"
 
 #include "nsPrincipal.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/HashFunctions.h"
--- a/caps/src/nsScriptSecurityManager.cpp
+++ b/caps/src/nsScriptSecurityManager.cpp
@@ -17,17 +17,17 @@
 #include "nsJSPrincipals.h"
 #include "nsSystemPrincipal.h"
 #include "nsPrincipal.h"
 #include "nsNullPrincipal.h"
 #include "nsXPIDLString.h"
 #include "nsCRT.h"
 #include "nsCRTGlue.h"
 #include "nsIJSContextStack.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsDOMCID.h"
 #include "jsdbgapi.h"
 #include "nsIXPConnect.h"
 #include "nsIXPCSecurityManager.h"
 #include "nsTextFormatter.h"
 #include "nsIStringBundle.h"
 #include "nsNetUtil.h"
 #include "nsIProperties.h"
--- a/chrome/src/nsChromeRegistry.cpp
+++ b/chrome/src/nsChromeRegistry.cpp
@@ -9,17 +9,17 @@
 #include "nsChromeRegistryContent.h"
 
 #include <string.h>
 
 #include "prio.h"
 #include "prprf.h"
 
 #include "nsCOMPtr.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsEscape.h"
 #include "nsLayoutCID.h"
 #include "nsNetUtil.h"
 #include "nsString.h"
 #include "nsUnicharUtils.h"
 
 #include "nsCSSStyleSheet.h"
 #include "nsIConsoleService.h"
--- a/configure.in
+++ b/configure.in
@@ -886,36 +886,29 @@ dnl when we can run target binaries.
 AC_SUBST(UNIVERSAL_BINARY)
 AC_SUBST(MOZ_CAN_RUN_PROGRAMS)
 
 dnl ========================================================
 dnl Check for MacOS deployment target version
 dnl ========================================================
 
 MOZ_ARG_ENABLE_STRING(macos-target,
-                      [  --enable-macos-target=VER (default=10.5)
+                      [  --enable-macos-target=VER (default=10.6)
                           Set the minimum MacOS version needed at runtime],
                       [_MACOSX_DEPLOYMENT_TARGET=$enableval])
 
 case "$target" in
 *-darwin*)
     if test -n "$_MACOSX_DEPLOYMENT_TARGET" ; then
         dnl Use the specified value
         export MACOSX_DEPLOYMENT_TARGET=$_MACOSX_DEPLOYMENT_TARGET
     else
         dnl No value specified on the command line or in the environment,
         dnl use architecture minimum.
-        case "${target_cpu}" in
-          i*86)
-            export MACOSX_DEPLOYMENT_TARGET=10.5
-            ;;
-          x86_64)
-            export MACOSX_DEPLOYMENT_TARGET=10.6
-            ;;
-        esac
+        export MACOSX_DEPLOYMENT_TARGET=10.6
     fi
     ;;
 esac
 
 AC_SUBST(MACOSX_DEPLOYMENT_TARGET)
 
 dnl ========================================================
 dnl = Mac OS X SDK support
@@ -5774,17 +5767,17 @@ fi
 dnl ========================================================
 dnl = Breakpad crash reporting (on by default on supported platforms)
 dnl ========================================================
 
 case $target in
 i?86-*-mingw*|x86_64-*-mingw*)
   MOZ_CRASHREPORTER=1
   ;;
-i?86-apple-darwin*|powerpc-apple-darwin*|x86_64-apple-darwin*)
+i?86-apple-darwin*|x86_64-apple-darwin*)
   MOZ_CRASHREPORTER=1
   ;;
 i?86-*-linux*|x86_64-*-linux*|arm-*-linux*)
   if test "$MOZ_ENABLE_GTK2"; then
     MOZ_CRASHREPORTER=1
   fi
   ;;
 *-android*|*-linuxandroid*)
--- a/content/base/public/Makefile.in
+++ b/content/base/public/Makefile.in
@@ -13,17 +13,16 @@ MODULE		= content
 XPIDL_MODULE	= content_base
 GRE_MODULE	= 1
 
 EXPORTS		= \
 mozFlushType.h \
 nsIContent.h \
 nsIAttribute.h \
 nsIContentIterator.h \
-nsContentErrors.h \
 nsContentPolicyUtils.h \
 nsContentUtils.h \
 nsIDocument.h \
 nsDeprecatedOperationList.h \
 nsIDocumentObserver.h \
 nsIMutationObserver.h \
 nsINameSpaceManager.h \
 nsINode.h \
deleted file mode 100644
--- a/content/base/public/nsContentErrors.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-// vim: ft=cpp sw=2 ts=2 tw=78 et
-/* 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 nsContentErrors_h___
-#define nsContentErrors_h___
-
-/** Error codes for nsHTMLStyleSheet */
-// XXX this is not really used
-#define NS_HTML_STYLE_PROPERTY_NOT_THERE \
-  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 2)
-
-/** Error codes for image loading */
-#define NS_ERROR_IMAGE_SRC_CHANGED \
-  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_CONTENT, 4)
-
-#define NS_ERROR_IMAGE_BLOCKED \
-  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_CONTENT, 5)
-
-/** Error codes for content policy blocking */
-#define NS_ERROR_CONTENT_BLOCKED \
-  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_CONTENT, 6)
-
-#define NS_ERROR_CONTENT_BLOCKED_SHOW_ALT \
-  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_CONTENT, 7)
-
-/** Success variations of content policy blocking */
-#define NS_CONTENT_BLOCKED \
-  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 8)
-
-#define NS_CONTENT_BLOCKED_SHOW_ALT \
-  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 9)
-
-#define NS_PROPTABLE_PROP_NOT_THERE \
-  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_CONTENT, 10)
-
-#define NS_PROPTABLE_PROP_OVERWRITTEN \
-  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 11)
-
-/* Error codes for FindBroadcaster in nsXULDocument.cpp */
-
-#define NS_FINDBROADCASTER_NOT_FOUND \
-  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 12)
-
-#define NS_FINDBROADCASTER_FOUND \
-  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 13)
-
-#define NS_FINDBROADCASTER_AWAIT_OVERLAYS \
-  NS_ERROR_GENERATE_SUCCESS(NS_ERROR_MODULE_CONTENT, 14)
-
-/* Error codes for CSP */
-#define NS_ERROR_CSP_FRAME_ANCESTOR_VIOLATION \
-  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_SECURITY, 99)
-
-/* Error codes for XBL */
-#define NS_ERROR_XBL_BLOCKED \
-  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_CONTENT, 15)
-
-#endif // nsContentErrors_h___
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -64,27 +64,28 @@ class nsPresContext;
 class nsScriptLoader;
 class nsSMILAnimationController;
 class nsStyleSet;
 class nsWindowSizes;
 
 namespace mozilla {
 namespace css {
 class Loader;
+class ImageLoader;
 } // namespace css
 
 namespace dom {
 class Link;
 class Element;
 } // namespace dom
 } // namespace mozilla
 
 #define NS_IDOCUMENT_IID \
-{ 0xbd70ee06, 0x2a7d, 0x4258, \
-  { 0x86, 0x4b, 0xbd, 0x28, 0xad, 0x9f, 0xd1, 0x41 } }
+{ 0xdb888523, 0x541f, 0x49e3, \
+  { 0xa9, 0x71, 0xb5, 0xea, 0xd1, 0xf0, 0xc3, 0xcf } }
 
 // Flag for AddStyleSheet().
 #define NS_STYLESHEET_FROM_CATALOG                (1 << 0)
 
 // Enum for requesting a particular type of document when creating a doc
 enum DocumentFlavor {
   DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
   DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
@@ -581,16 +582,23 @@ public:
   /**
    * Get this document's CSSLoader.  This is guaranteed to not return null.
    */
   mozilla::css::Loader* CSSLoader() const {
     return mCSSLoader;
   }
 
   /**
+   * Get this document's StyleImageLoader.  This is guaranteed to not return null.
+   */
+  mozilla::css::ImageLoader* StyleImageLoader() const {
+    return mStyleImageLoader;
+  }
+
+  /**
    * Get the channel that was passed to StartDocumentLoad or Reset for this
    * document.  Note that this may be null in some cases (eg if
    * StartDocumentLoad or Reset were never called)
    */
   virtual nsIChannel* GetChannel() const = 0;
 
   /**
    * Get this document's attribute stylesheet.  May return null if
@@ -1734,16 +1742,17 @@ protected:
   nsIDocument* mParentDocument;
 
   // A reference to the element last returned from GetRootElement().
   mozilla::dom::Element* mCachedRootElement;
 
   // We hold a strong reference to mNodeInfoManager through mNodeInfo
   nsNodeInfoManager* mNodeInfoManager; // [STRONG]
   nsRefPtr<mozilla::css::Loader> mCSSLoader;
+  mozilla::css::ImageLoader* mStyleImageLoader; // [STRONG]
   nsHTMLStyleSheet* mAttrStyleSheet;
 
   // The set of all object, embed, applet, video and audio elements for
   // which this is the owner document. (They might not be in the document.)
   // These are non-owning pointers, the elements are responsible for removing
   // themselves when they go away.
   nsAutoPtr<nsTHashtable<nsPtrHashKey<nsIContent> > > mFreezableElements;
 
--- a/content/base/public/nsIImageLoadingContent.idl
+++ b/content/base/public/nsIImageLoadingContent.idl
@@ -29,17 +29,17 @@ interface nsIFrame;
  * observers to check which request they are getting notifications for.
  *
  * Observers added in mid-load will not get any notifications they
  * missed.  We should NOT freeze this interface without considering
  * this issue.  (It could be that the image status on imgIRequest is
  * sufficient, when combined with the imageBlockingStatus information.)
  */
 
-[scriptable, uuid(f7debb84-2854-4731-a57b-1bd752ad71f8)]
+[scriptable, uuid(4bf1a7c5-6edb-4191-a257-e31a90f6aa85)]
 interface nsIImageLoadingContent : imgIDecoderObserver
 {
   /**
    * Request types.  Image loading content nodes attempt to do atomic
    * image changes when the image url is changed.  This means that
    * when the url changes the new image load will start, but the old
    * image will remain the "current" request until the new image is
    * fully loaded.  At that point, the old "current" request will be
@@ -151,14 +151,9 @@ interface nsIImageLoadingContent : imgID
   void forceReload();
 
   /**
    * Enables/disables image state forcing. When |aForce| is PR_TRUE, we force
    * nsImageLoadingContent::ImageState() to return |aState|. Call again with |aForce|
    * as PR_FALSE to revert ImageState() to its original behaviour.
    */
   void forceImageState(in boolean aForce, in unsigned long long aState);
-
-  /**
-    * We need to be notified when our document changes.
-    */
-  [noscript, notxpcom] void NotifyOwnerDocumentChanged(in nsIDocument aOldDoc);
 };
--- a/content/base/public/nsIMutationObserver.h
+++ b/content/base/public/nsIMutationObserver.h
@@ -15,18 +15,18 @@ class nsINode;
 
 namespace mozilla {
 namespace dom {
 class Element;
 } // namespace dom
 } // namespace mozilla
 
 #define NS_IMUTATION_OBSERVER_IID \
-{ 0x85eea794, 0xed8e, 0x4e1b, \
-  { 0xa1, 0x28, 0xd0, 0x93, 0x00, 0xae, 0x51, 0xaa } }
+{ 0x16fe5e3e, 0xeadc, 0x4312, \
+  { 0x9d, 0x44, 0xb6, 0xbe, 0xdd, 0x6b, 0x54, 0x74 } }
 
 /**
  * Information details about a characterdata change.  Basically, we
  * view all changes as replacements of a length of text at some offset
  * with some other text (of possibly some other length).
  */
 struct CharacterDataChangeInfo
 {
@@ -188,16 +188,30 @@ public:
    */
   virtual void AttributeChanged(nsIDocument* aDocument,
                                 mozilla::dom::Element* aElement,
                                 PRInt32      aNameSpaceID,
                                 nsIAtom*     aAttribute,
                                 PRInt32      aModType) = 0;
 
   /**
+   * Notification that an attribute of an element has been
+   * set to the value it already had.
+   *
+   * @param aDocument    The owner-document of aContent.
+   * @param aElement     The element whose attribute changed
+   * @param aNameSpaceID The namespace id of the changed attribute
+   * @param aAttribute   The name of the changed attribute
+   */
+  virtual void AttributeSetToCurrentValue(nsIDocument* aDocument,
+                                          mozilla::dom::Element* aElement,
+                                          PRInt32 aNameSpaceID,
+                                          nsIAtom* aAttribute) {}
+
+  /**
    * Notification that one or more content nodes have been appended to the
    * child list of another node in the tree.
    *
    * @param aDocument  The owner-document of aContent. Can be null.
    * @param aContainer The container that had new children appended. Is never
    *                   null.
    * @param aFirstNewContent the node at aIndexInContainer in aContainer.
    * @param aNewIndexInContainer the index in the container of the first
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -1667,13 +1667,28 @@ extern const nsIID kThisPtrOffsetsSID;
     NS_INTERFACE_TABLE_ENTRY(_class, _i4)                                     \
     NS_INTERFACE_TABLE_ENTRY(_class, _i5)                                     \
     NS_INTERFACE_TABLE_ENTRY(_class, _i6)                                     \
     NS_INTERFACE_TABLE_ENTRY(_class, _i7)                                     \
     NS_INTERFACE_TABLE_ENTRY(_class, _i8)                                     \
   NS_OFFSET_AND_INTERFACE_TABLE_END                                           \
   NS_OFFSET_AND_INTERFACE_TABLE_TO_MAP_SEGUE
 
+#define NS_NODE_INTERFACE_TABLE9(_class, _i1, _i2, _i3, _i4, _i5, _i6, _i7,   \
+                                 _i8, _i9)                                    \
+  NS_NODE_OFFSET_AND_INTERFACE_TABLE_BEGIN(_class)                            \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i1)                                     \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i2)                                     \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i3)                                     \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i4)                                     \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i5)                                     \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i6)                                     \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i7)                                     \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i8)                                     \
+    NS_INTERFACE_TABLE_ENTRY(_class, _i9)                                     \
+  NS_OFFSET_AND_INTERFACE_TABLE_END                                           \
+  NS_OFFSET_AND_INTERFACE_TABLE_TO_MAP_SEGUE
+
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsINode, NS_INODE_IID)
 
 
 #endif /* nsINode_h___ */
--- a/content/base/src/FileIOObject.cpp
+++ b/content/base/src/FileIOObject.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* 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 "FileIOObject.h"
 #include "nsDOMFile.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIDOMEvent.h"
 #include "nsIDOMProgressEvent.h"
 #include "nsComponentManagerUtils.h"
 #include "nsEventDispatcher.h"
 
 #define ERROR_STR "error"
 #define ABORT_STR "abort"
 #define PROGRESS_STR "progress"
--- a/content/base/src/FragmentOrElement.cpp
+++ b/content/base/src/FragmentOrElement.cpp
@@ -40,17 +40,17 @@
 #include "nsDOMCID.h"
 #include "nsIServiceManager.h"
 #include "nsIDOMCSSStyleDeclaration.h"
 #include "nsDOMCSSAttrDeclaration.h"
 #include "nsINameSpaceManager.h"
 #include "nsContentList.h"
 #include "nsDOMTokenList.h"
 #include "nsXBLPrototypeBinding.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsDOMString.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsMutationEvent.h"
 #include "nsNodeUtils.h"
 #include "nsDocument.h"
 #include "nsAttrValueOrString.h"
 #ifdef MOZ_XUL
--- a/content/base/src/nsBlobProtocolHandler.cpp
+++ b/content/base/src/nsBlobProtocolHandler.cpp
@@ -1,15 +1,15 @@
 /* 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 "nsBlobProtocolHandler.h"
 #include "nsBlobURI.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsClassHashtable.h"
 #include "nsNetUtil.h"
 #include "nsIPrincipal.h"
 #include "nsIDOMFile.h"
 
 // -----------------------------------------------------------------------
 // Hash table
 struct FileDataInfo
--- a/content/base/src/nsCSPService.cpp
+++ b/content/base/src/nsCSPService.cpp
@@ -11,17 +11,17 @@
 #include "nsIObserver.h"
 #include "nsIContent.h"
 #include "nsCSPService.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsIChannelPolicy.h"
 #include "nsIChannelEventSink.h"
 #include "nsIPropertyBag2.h"
 #include "nsIWritablePropertyBag2.h"
-#include "nsNetError.h"
+#include "nsError.h"
 #include "nsChannelProperties.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsAsyncRedirectVerifyHelper.h"
 #include "mozilla/Preferences.h"
 #include "nsIScriptError.h"
 #include "nsContentUtils.h"
 
 using namespace mozilla;
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -80,17 +80,17 @@ static NS_DEFINE_CID(kXTFServiceCID, NS_
 #include "nsIURL.h"
 #include "nsICharsetConverterManager.h"
 #include "nsEventListenerManager.h"
 #include "nsAttrName.h"
 #include "nsIDOMUserDataHandler.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsMutationEvent.h"
 #include "nsIMEStateManager.h"
-#include "nsContentErrors.h"
+#include "nsError.h"
 #include "nsUnicharUtilCIID.h"
 #include "nsINativeKeyBindings.h"
 #include "nsXULPopupManager.h"
 #include "nsIPermissionManager.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsNullPrincipal.h"
 #include "nsIRunnable.h"
 #include "nsDOMJSUtils.h"
--- a/content/base/src/nsCrossSiteListenerProxy.cpp
+++ b/content/base/src/nsCrossSiteListenerProxy.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* 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 "nsCrossSiteListenerProxy.h"
 #include "nsIChannel.h"
 #include "nsIHttpChannel.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsContentUtils.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsNetUtil.h"
 #include "nsMimeTypes.h"
 #include "nsIStreamConverterService.h"
 #include "nsStringStream.h"
 #include "nsGkAtoms.h"
 #include "nsWhitespaceTokenizer.h"
--- a/content/base/src/nsDOMAttribute.cpp
+++ b/content/base/src/nsDOMAttribute.cpp
@@ -7,17 +7,17 @@
  * Implementation of DOM Core's nsIDOMAttr node.
  */
 
 #include "nsDOMAttribute.h"
 #include "nsGenericElement.h"
 #include "mozilla/dom/Element.h"
 #include "nsContentCreatorFunctions.h"
 #include "nsINameSpaceManager.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsUnicharUtils.h"
 #include "nsDOMString.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMUserDataHandler.h"
 #include "nsEventDispatcher.h"
 #include "nsGkAtoms.h"
 #include "nsCOMArray.h"
--- a/content/base/src/nsDOMAttributeMap.cpp
+++ b/content/base/src/nsDOMAttributeMap.cpp
@@ -8,17 +8,17 @@
  */
 
 #include "nsDOMAttributeMap.h"
 #include "nsDOMAttribute.h"
 #include "nsIDOMDocument.h"
 #include "nsGenericElement.h"
 #include "nsIDocument.h"
 #include "nsINameSpaceManager.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsContentUtils.h"
 #include "nsNodeInfoManager.h"
 #include "nsAttrName.h"
 #include "nsUnicharUtils.h"
 
 //----------------------------------------------------------------------
 
 nsDOMAttributeMap::nsDOMAttributeMap(Element* aContent)
--- a/content/base/src/nsDOMFile.cpp
+++ b/content/base/src/nsDOMFile.cpp
@@ -4,17 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMFile.h"
 
 #include "nsCExternalHandlerService.h"
 #include "nsContentCID.h"
 #include "nsContentUtils.h"
 #include "nsDOMClassInfoID.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsICharsetDetector.h"
 #include "nsICharsetConverterManager.h"
 #include "nsIClassInfo.h"
 #include "nsIConverterInputStream.h"
 #include "nsIDocument.h"
 #include "nsIFileStreams.h"
 #include "nsIInputStream.h"
 #include "nsIIPCSerializable.h"
--- a/content/base/src/nsDOMFileReader.cpp
+++ b/content/base/src/nsDOMFileReader.cpp
@@ -4,17 +4,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsDOMFileReader.h"
 
 #include "nsContentCID.h"
 #include "nsContentUtils.h"
 #include "nsDOMClassInfoID.h"
 #include "nsDOMFile.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsCharsetAlias.h"
 #include "nsICharsetConverterManager.h"
 #include "nsIConverterInputStream.h"
 #include "nsIFile.h"
 #include "nsIFileStreams.h"
 #include "nsIInputStream.h"
 #include "nsIMIMEService.h"
 #include "nsIUnicodeDecoder.h"
--- a/content/base/src/nsDOMLists.cpp
+++ b/content/base/src/nsDOMLists.cpp
@@ -3,17 +3,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/. */
 
 /*
  * Implementation of nsIDOMDOMStringList, used by various DOM stuff.
  */
 
 #include "nsDOMLists.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsDOMClassInfoID.h"
 #include "nsINode.h"
 
 nsDOMStringList::nsDOMStringList()
 {
 }
 
 nsDOMStringList::~nsDOMStringList()
--- a/content/base/src/nsDOMMutationObserver.cpp
+++ b/content/base/src/nsDOMMutationObserver.cpp
@@ -1,17 +1,17 @@
 /* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 8; -*- */
 /* vim: set sw=4 ts=8 et 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 "nsDOMMutationObserver.h"        
 #include "nsDOMClassInfoID.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIClassInfo.h"
 #include "nsIXPCScriptable.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsContentUtils.h"
 #include "nsThreadUtils.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsTextFragment.h"
 #include "jsapi.h"
--- a/content/base/src/nsDOMMutationObserver.h
+++ b/content/base/src/nsDOMMutationObserver.h
@@ -16,16 +16,17 @@
 #include "nsCOMArray.h"
 #include "nsTArray.h"
 #include "nsAutoPtr.h"
 #include "nsIVariant.h"
 #include "nsContentList.h"
 #include "mozilla/dom/Element.h"
 #include "nsClassHashtable.h"
 #include "nsNodeUtils.h"
+#include "nsIDOMMutationEvent.h"
 
 class nsDOMMutationObserver;
 
 class nsDOMMutationRecord : public nsIDOMMutationRecord
 {
 public:
   nsDOMMutationRecord(const nsAString& aType) : mType(aType)
   {
@@ -268,16 +269,26 @@ public:
   NS_DECL_ISUPPORTS
 
   NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTEWILLCHANGE
   NS_DECL_NSIMUTATIONOBSERVER_CHARACTERDATAWILLCHANGE
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
   NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
   NS_DECL_NSIMUTATIONOBSERVER_NODEWILLBEDESTROYED
+
+  virtual void AttributeSetToCurrentValue(nsIDocument* aDocument,
+                                          mozilla::dom::Element* aElement,
+                                          PRInt32 aNameSpaceID,
+                                          nsIAtom* aAttribute)
+  {
+    // We can reuse AttributeWillChange implementation.
+    AttributeWillChange(aDocument, aElement, aNameSpaceID, aAttribute,
+                        nsIDOMMutationEvent::MODIFICATION);
+  }
 };
 
 NS_DEFINE_STATIC_IID_ACCESSOR(nsMutationReceiver, NS_MUTATION_OBSERVER_IID)
 
 class nsDOMMutationObserver : public nsIDOMMutationObserver,
                               public nsIJSNativeInitializer
 {
 public:
--- a/content/base/src/nsDOMParser.cpp
+++ b/content/base/src/nsDOMParser.cpp
@@ -17,17 +17,17 @@
 #include "nsDOMClassInfoID.h"
 #include "nsReadableUtils.h"
 #include "nsCRT.h"
 #include "nsStreamUtils.h"
 #include "nsThreadUtils.h"
 #include "nsNetCID.h"
 #include "nsContentUtils.h"
 #include "nsDOMJSUtils.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "mozilla/AutoRestore.h"
 
 using namespace mozilla;
 
 nsDOMParser::nsDOMParser()
   : mAttemptedInit(false)
--- a/content/base/src/nsDOMSerializer.cpp
+++ b/content/base/src/nsDOMSerializer.cpp
@@ -8,17 +8,17 @@
 #include "nsDOMClassInfoID.h"
 #include "nsIOutputStream.h"
 #include "nsIDocument.h"
 #include "nsIDOMDocument.h"
 #include "nsIDocumentEncoder.h"
 #include "nsString.h"
 #include "nsContentCID.h"
 #include "nsContentUtils.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 
 nsDOMSerializer::nsDOMSerializer()
 {
 }
 
 nsDOMSerializer::~nsDOMSerializer()
 {
 }
--- a/content/base/src/nsDOMTokenList.cpp
+++ b/content/base/src/nsDOMTokenList.cpp
@@ -5,17 +5,17 @@
 /*
  * Implementation of nsIDOMDOMTokenList specified by HTML5.
  */
 
 #include "nsDOMTokenList.h"
 
 #include "nsAttrValue.h"
 #include "nsContentUtils.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsGenericElement.h"
 #include "dombindings.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 nsDOMTokenList::nsDOMTokenList(nsGenericElement* aElement, nsIAtom* aAttrAtom)
   : mElement(aElement),
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -21,16 +21,17 @@
 #include "nsIInterfaceRequestor.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsDocument.h"
 #include "nsUnicharUtils.h"
 #include "nsContentList.h"
 #include "nsIObserver.h"
 #include "nsIBaseWindow.h"
 #include "mozilla/css/Loader.h"
+#include "mozilla/css/ImageLoader.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIScriptRuntime.h"
 #include "nsCOMArray.h"
 
 #include "nsGUIEvent.h"
 #include "nsAsyncDOMEvent.h"
 #include "nsIDOMNodeFilter.h"
@@ -56,17 +57,17 @@
 #include "nsIDOMComment.h"
 #include "nsDOMDocumentType.h"
 #include "nsNodeIterator.h"
 #include "nsTreeWalker.h"
 
 #include "nsIServiceManager.h"
 
 #include "nsContentCID.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIPresShell.h"
 #include "nsPresContext.h"
 #include "nsIJSON.h"
 #include "nsThreadUtils.h"
 #include "nsNodeInfoManager.h"
 #include "nsIFileChannel.h"
 #include "nsIMultiPartChannel.h"
 #include "nsIRefreshURI.h"
@@ -124,17 +125,16 @@
 #include "nsCycleCollector.h"
 #include "nsCCUncollectableMarker.h"
 #include "nsIContentPolicy.h"
 #include "nsContentPolicyUtils.h"
 #include "nsICategoryManager.h"
 #include "nsIDocumentLoaderFactory.h"
 #include "nsIContentViewer.h"
 #include "nsIXMLContentSink.h"
-#include "nsContentErrors.h"
 #include "nsIXULDocument.h"
 #include "nsIPrompt.h"
 #include "nsIPropertyBag2.h"
 #include "nsIDOMPageTransitionEvent.h"
 #include "nsFrameLoader.h"
 #include "nsEscape.h"
 #include "nsObjectLoadingContent.h"
 #include "nsHtml5TreeOpExecutor.h"
@@ -1641,16 +1641,21 @@ nsDocument::~nsDocument()
     mScriptLoader->DropDocumentReference();
   }
 
   if (mCSSLoader) {
     // Could be null here if Init() failed
     mCSSLoader->DropDocumentReference();
   }
 
+  if (mStyleImageLoader) {
+    mStyleImageLoader->DropDocumentReference();
+    NS_RELEASE(mStyleImageLoader);
+  }
+
   delete mHeaderData;
 
   if (mBoxObjectTable) {
     mBoxObjectTable->EnumerateRead(ClearAllBoxObjects, nullptr);
     delete mBoxObjectTable;
   }
 
   mPendingTitleChangeEvent.Revoke();
@@ -1971,17 +1976,17 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(ns
 
   tmp->mInUnlinkOrDeletion = false;
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 
 nsresult
 nsDocument::Init()
 {
-  if (mCSSLoader || mNodeInfoManager || mScriptLoader) {
+  if (mCSSLoader || mStyleImageLoader || mNodeInfoManager || mScriptLoader) {
     return NS_ERROR_ALREADY_INITIALIZED;
   }
 
   mIdentifierMap.Init();
   mStyledLinks.Init();
   mRadioGroups.Init();
 
   // Force initialization.
@@ -1995,18 +2000,21 @@ nsDocument::Init()
                  NS_ERROR_OUT_OF_MEMORY);
 
 
   mOnloadBlocker = new nsOnloadBlocker();
   mCSSLoader = new mozilla::css::Loader(this);
   // Assume we're not quirky, until we know otherwise
   mCSSLoader->SetCompatibilityMode(eCompatibility_FullStandards);
 
+  mStyleImageLoader = new mozilla::css::ImageLoader(this);
+  NS_ADDREF(mStyleImageLoader);
+
   mNodeInfoManager = new nsNodeInfoManager();
-  nsresult  rv = mNodeInfoManager->Init(this);
+  nsresult rv = mNodeInfoManager->Init(this);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // mNodeInfo keeps NodeInfoManager alive!
   mNodeInfo = mNodeInfoManager->GetDocumentNodeInfo();
   NS_ENSURE_TRUE(mNodeInfo, NS_ERROR_OUT_OF_MEMORY);
   NS_ABORT_IF_FALSE(mNodeInfo->NodeType() == nsIDOMNode::DOCUMENT_NODE,
                     "Bad NodeType in aNodeInfo");
 
@@ -9111,17 +9119,17 @@ nsDocument::RequestFullScreen(Element* a
 
   // If this document hasn't already been approved in this session,
   // check to see if the user has granted the fullscreen access
   // to the document's principal's host, if it has one. Note that documents
   // in web apps which are the same origin as the web app are considered
   // trusted and so are automatically approved.
   if (!mIsApprovedForFullscreen) {
     mIsApprovedForFullscreen =
-      GetWindow()->IsInAppOrigin() ||
+      NodePrincipal()->GetAppStatus() >= nsIPrincipal::APP_STATUS_INSTALLED ||
       nsContentUtils::IsSitePermAllow(NodePrincipal(), "fullscreen");
   }
 
   // If this document, or a document with the same principal has not
   // already been approved for fullscreen this fullscreen-session, dispatch
   // an event so that chrome knows to pop up a warning/approval UI.
   nsCOMPtr<nsIDocument> previousFullscreenDoc(do_QueryReferent(sFullScreenDoc));
   // Note previousFullscreenDoc=nullptr upon first entry, so we always
--- a/content/base/src/nsDocumentFragment.cpp
+++ b/content/base/src/nsDocumentFragment.cpp
@@ -8,17 +8,17 @@
  */
 
 #include "nsIDOMDocumentFragment.h"
 #include "mozilla/dom/FragmentOrElement.h"
 #include "nsGenericElement.h" // for DOMCI_NODE_DATA
 #include "nsINameSpaceManager.h"
 #include "nsINodeInfo.h"
 #include "nsNodeInfoManager.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsGkAtoms.h"
 #include "nsDOMString.h"
 #include "nsContentUtils.h"
 
 using namespace mozilla;
 using namespace mozilla::dom;
 
 class nsDocumentFragment : public FragmentOrElement,
--- a/content/base/src/nsEventSource.cpp
+++ b/content/base/src/nsEventSource.cpp
@@ -28,17 +28,17 @@
 #include "nsContentUtils.h"
 #include "mozilla/Preferences.h"
 #include "xpcpublic.h"
 #include "nsCrossSiteListenerProxy.h"
 #include "nsWrapperCacheInlines.h"
 #include "nsDOMEventTargetHelper.h"
 #include "mozilla/Attributes.h"
 #include "nsDOMClassInfoID.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 
 using namespace mozilla;
 
 #define REPLACEMENT_CHAR     (PRUnichar)0xFFFD
 #define BOM_CHAR             (PRUnichar)0xFEFF
 #define SPACE_CHAR           (PRUnichar)0x0020
 #define CR_CHAR              (PRUnichar)0x000D
 #define LF_CHAR              (PRUnichar)0x000A
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -41,17 +41,17 @@
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIScrollable.h"
 #include "nsFrameLoader.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIFrame.h"
 #include "nsIScrollableFrame.h"
 #include "nsSubDocumentFrame.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsGUIEvent.h"
 #include "nsEventDispatcher.h"
 #include "nsISHistory.h"
 #include "nsISHistoryInternal.h"
 #include "nsIDocShellHistory.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIXULWindow.h"
 #include "nsIEditor.h"
@@ -2369,17 +2369,11 @@ nsFrameLoader::GetOwnerElement(nsIDOMEle
 
 void
 nsFrameLoader::SetRemoteBrowser(nsITabParent* aTabParent)
 {
   MOZ_ASSERT(!mRemoteBrowser);
   MOZ_ASSERT(!mCurrentRemoteFrame);
   mRemoteBrowser = static_cast<TabParent*>(aTabParent);
 
-  EnsureMessageManager();
-  nsCOMPtr<nsIObserverService> os = services::GetObserverService();
-  if (OwnerIsBrowserFrame() && os) {
-    mRemoteBrowserInitialized = true;
-    os->NotifyObservers(NS_ISUPPORTS_CAST(nsIFrameLoader*, this),
-                        "remote-browser-frame-shown", NULL);
-  }
+  ShowRemoteFrame(nsIntSize(0, 0));
 }
 
--- a/content/base/src/nsFrameMessageManager.cpp
+++ b/content/base/src/nsFrameMessageManager.cpp
@@ -5,17 +5,17 @@
 
 #include "base/basictypes.h"
 
 #include "nsFrameMessageManager.h"
 
 #include "ContentChild.h"
 #include "ContentParent.h"
 #include "nsContentUtils.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIXPConnect.h"
 #include "jsapi.h"
 #include "nsJSUtils.h"
 #include "nsJSPrincipals.h"
 #include "nsNetUtil.h"
 #include "nsScriptLoader.h"
 #include "nsIJSContextStack.h"
 #include "nsIXULRuntime.h"
--- a/content/base/src/nsGenConImageContent.cpp
+++ b/content/base/src/nsGenConImageContent.cpp
@@ -30,27 +30,35 @@ public:
 
   nsresult Init(imgIRequest* aImageRequest)
   {
     // No need to notify, since we have no frame.
     return UseAsPrimaryRequest(aImageRequest, false);
   }
 
   // nsIContent overrides
+  virtual nsresult BindToTree(nsIDocument* aDocument, nsIContent* aParent,
+                              nsIContent* aBindingParent,
+                              bool aCompileEventHandlers);
+  virtual void UnbindFromTree(bool aDeep, bool aNullParent);
   virtual nsEventStates IntrinsicState() const;
   
 private:
   virtual ~nsGenConImageContent();
 
 public:
   NS_DECL_ISUPPORTS_INHERITED
 };
 
-NS_IMPL_ISUPPORTS_INHERITED3(nsGenConImageContent, nsXMLElement,
-                             nsIImageLoadingContent, imgIContainerObserver, imgIDecoderObserver)
+NS_IMPL_ISUPPORTS_INHERITED4(nsGenConImageContent,
+                             nsXMLElement,
+                             nsIImageLoadingContent,
+                             imgIContainerObserver,
+                             imgIDecoderObserver,
+                             imgIOnloadBlocker)
 
 nsresult
 NS_NewGenConImageContent(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo,
                          imgIRequest* aImageRequest)
 {
   NS_PRECONDITION(aImageRequest, "Must have request!");
   nsGenConImageContent *it = new nsGenConImageContent(aNodeInfo);
   if (!it)
@@ -62,16 +70,38 @@ NS_NewGenConImageContent(nsIContent** aR
   return rv;
 }
 
 nsGenConImageContent::~nsGenConImageContent()
 {
   DestroyImageLoadingContent();
 }
 
+nsresult
+nsGenConImageContent::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
+                                 nsIContent* aBindingParent,
+                                 bool aCompileEventHandlers)
+{
+  nsresult rv;
+  rv = nsXMLElement::BindToTree(aDocument, aParent, aBindingParent,
+                                aCompileEventHandlers);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  nsImageLoadingContent::BindToTree(aDocument, aParent, aBindingParent,
+                                    aCompileEventHandlers);
+  return NS_OK;
+}
+
+void
+nsGenConImageContent::UnbindFromTree(bool aDeep, bool aNullParent)
+{
+  nsImageLoadingContent::UnbindFromTree(aDeep, aNullParent);
+  nsXMLElement::UnbindFromTree(aDeep, aNullParent);
+}
+
 nsEventStates
 nsGenConImageContent::IntrinsicState() const
 {
   nsEventStates state = nsXMLElement::IntrinsicState();
 
   nsEventStates imageState = nsImageLoadingContent::ImageState();
   if (imageState.HasAtLeastOneOfStates(NS_EVENT_STATE_BROKEN | NS_EVENT_STATE_USERDISABLED)) {
     // We should never be in an error state; if the image fails to load, we
--- a/content/base/src/nsGenericDOMDataNode.h
+++ b/content/base/src/nsGenericDOMDataNode.h
@@ -9,17 +9,17 @@
  */
 
 #ifndef nsGenericDOMDataNode_h___
 #define nsGenericDOMDataNode_h___
 
 #include "nsIContent.h"
 
 #include "nsTextFragment.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsEventListenerManager.h"
 #include "nsGenericElement.h"
 #include "nsCycleCollectionParticipant.h"
 
 #include "nsISMILAttr.h"
 
 // This bit is set to indicate that if the text node changes to
 // non-whitespace, we may need to create a frame for it. This bit must
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -40,17 +40,17 @@
 #include "nsDOMCID.h"
 #include "nsIServiceManager.h"
 #include "nsIDOMCSSStyleDeclaration.h"
 #include "nsDOMCSSAttrDeclaration.h"
 #include "nsINameSpaceManager.h"
 #include "nsContentList.h"
 #include "nsDOMTokenList.h"
 #include "nsXBLPrototypeBinding.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsDOMString.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsMutationEvent.h"
 #include "nsNodeUtils.h"
 #include "mozilla/dom/DirectionalityUtils.h"
 #include "nsDocument.h"
 #include "nsAttrValueOrString.h"
@@ -1878,23 +1878,17 @@ nsGenericElement::MaybeCheckSameAttrVal(
         // should serialize the attribute value now to keep a snapshot.
         //
         // We have to serialize the value anyway in order to create the
         // mutation event so there's no cost in doing it now.
         aOldValue.SetToSerialized(*info.mValue);
       }
       bool valueMatches = aValue.EqualsAsStrings(*info.mValue);
       if (valueMatches && aPrefix == info.mName->GetPrefix()) {
-        if (OwnerDoc()->MayHaveDOMMutationObservers()) {
-          // For backward compatibility, don't fire mutation events
-          // when setting an attribute to its old value.
-          *aHasListeners = false;
-        } else {
-          return true;
-        }
+        return true;
       }
       modification = true;
     }
   }
   *aModType = modification ?
     static_cast<PRUint8>(nsIDOMMutationEvent::MODIFICATION) :
     static_cast<PRUint8>(nsIDOMMutationEvent::ADDITION);
   return false;
@@ -1915,18 +1909,18 @@ nsGenericElement::SetAttr(PRInt32 aNames
     return NS_ERROR_FAILURE;
   }
 
   PRUint8 modType;
   bool hasListeners;
   nsAttrValueOrString value(aValue);
   nsAttrValue oldValue;
 
-  if (MaybeCheckSameAttrVal(aNamespaceID, aName, aPrefix, value, aNotify,
-                            oldValue, &modType, &hasListeners)) {
+  if (OnlyNotifySameValueSet(aNamespaceID, aName, aPrefix, value, aNotify,
+                             oldValue, &modType, &hasListeners)) {
     return NS_OK;
   }
 
   nsresult rv = BeforeSetAttr(aNamespaceID, aName, &value, aNotify);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (aNotify) {
     nsNodeUtils::AttributeWillChange(this, aNamespaceID, aName, modType);
@@ -1962,18 +1956,18 @@ nsGenericElement::SetParsedAttr(PRInt32 
   }
 
 
   PRUint8 modType;
   bool hasListeners;
   nsAttrValueOrString value(aParsedValue);
   nsAttrValue oldValue;
 
-  if (MaybeCheckSameAttrVal(aNamespaceID, aName, aPrefix, value, aNotify,
-                            oldValue, &modType, &hasListeners)) {
+  if (OnlyNotifySameValueSet(aNamespaceID, aName, aPrefix, value, aNotify,
+                             oldValue, &modType, &hasListeners)) {
     return NS_OK;
   }
 
   nsresult rv = BeforeSetAttr(aNamespaceID, aName, &value, aNotify);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (aNotify) {
     nsNodeUtils::AttributeWillChange(this, aNamespaceID, aName, modType);
@@ -2795,17 +2789,17 @@ nsGenericElement::MozRequestPointerLock(
   OwnerDoc()->RequestPointerLock(this);
   return NS_OK;
 }
 
 static const char*
 GetFullScreenError(nsIDocument* aDoc)
 {
   nsCOMPtr<nsPIDOMWindow> win = aDoc->GetWindow();
-  if (win && win->IsInAppOrigin()) {
+  if (aDoc->NodePrincipal()->GetAppStatus() >= nsIPrincipal::APP_STATUS_INSTALLED) {
     // Request is in a web app and in the same origin as the web app.
     // Don't enforce as strict security checks for web apps, the user
     // is supposed to have trust in them. However documents cross-origin
     // to the web app must still confirm to the normal security checks.
     return nullptr;
   }
 
   if (!nsContentUtils::IsRequestFullScreenAllowed()) {
--- a/content/base/src/nsGenericElement.h
+++ b/content/base/src/nsGenericElement.h
@@ -31,17 +31,17 @@
 #include "nsPresContext.h"
 #include "nsIDOMDOMStringMap.h"
 #include "nsContentList.h"
 #include "nsDOMClassInfoID.h" // DOMCI_DATA
 #include "nsIDOMTouchEvent.h"
 #include "nsIInlineEventHandlers.h"
 #include "mozilla/CORSMode.h"
 #include "mozilla/Attributes.h"
-
+#include "nsContentUtils.h"
 #include "nsISMILAttr.h"
 
 class nsIDOMAttr;
 class nsIDOMEventListener;
 class nsIFrame;
 class nsIDOMNamedNodeMap;
 class nsICSSDeclaration;
 class nsIDOMCSSStyleDeclaration;
@@ -97,16 +97,32 @@ public:
    * @param aHasListeners Set to true if there are mutation event listeners
    *   listening for NS_EVENT_BITS_MUTATION_ATTRMODIFIED
    */
   bool MaybeCheckSameAttrVal(PRInt32 aNamespaceID, nsIAtom* aName,
                              nsIAtom* aPrefix,
                              const nsAttrValueOrString& aValue,
                              bool aNotify, nsAttrValue& aOldValue,
                              PRUint8* aModType, bool* aHasListeners);
+
+  bool OnlyNotifySameValueSet(PRInt32 aNamespaceID, nsIAtom* aName,
+                              nsIAtom* aPrefix,
+                              const nsAttrValueOrString& aValue,
+                              bool aNotify, nsAttrValue& aOldValue,
+                              PRUint8* aModType, bool* aHasListeners)
+  {
+    if (MaybeCheckSameAttrVal(aNamespaceID, aName, aPrefix, aValue, aNotify,
+                              aOldValue, aModType, aHasListeners)) {
+      nsAutoScriptBlocker scriptBlocker;
+      nsNodeUtils::AttributeSetToCurrentValue(this, aNamespaceID, aName);
+      return true;
+    }
+    return false;
+  }
+
   virtual nsresult SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName, nsIAtom* aPrefix,
                            const nsAString& aValue, bool aNotify);
   virtual nsresult SetParsedAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                                  nsIAtom* aPrefix, nsAttrValue& aParsedValue,
                                  bool aNotify);
   virtual bool GetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                          nsAString& aResult) const;
   virtual bool HasAttr(PRInt32 aNameSpaceID, nsIAtom* aName) const;
--- a/content/base/src/nsINode.cpp
+++ b/content/base/src/nsINode.cpp
@@ -25,17 +25,17 @@
 #include "nsContentUtils.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsCycleCollector.h"
 #include "nsDocument.h"
 #include "nsDOMAttribute.h"
 #include "nsDOMAttributeMap.h"
 #include "nsDOMCID.h"
 #include "nsDOMCSSAttrDeclaration.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsDOMMutationObserver.h"
 #include "nsDOMString.h"
 #include "nsDOMTokenList.h"
 #include "nsEventDispatcher.h"
 #include "nsEventListenerManager.h"
 #include "nsEventStateManager.h"
 #include "nsFocusManager.h"
 #include "nsFrameManager.h"
--- a/content/base/src/nsImageLoadingContent.cpp
+++ b/content/base/src/nsImageLoadingContent.cpp
@@ -7,17 +7,17 @@
 /*
  * A base class which implements nsIImageLoadingContent and can be
  * subclassed by various content nodes that want to provide image
  * loading functionality (eg <img>, <object>, etc).
  */
 
 #include "nsImageLoadingContent.h"
 #include "nsAutoPtr.h"
-#include "nsContentErrors.h"
+#include "nsError.h"
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIDOMWindow.h"
 #include "nsServiceManagerUtils.h"
 #include "nsContentPolicyUtils.h"
 #include "nsIURI.h"
 #include "nsILoadGroup.h"
@@ -67,29 +67,28 @@ static void PrintReqURL(imgIRequest* req
   nsCAutoString spec;
   uri->GetSpec(spec);
   printf("spec='%s'\n", spec.get());
 }
 #endif /* DEBUG_chb */
 
 
 nsImageLoadingContent::nsImageLoadingContent()
-  : mObserverList(nullptr),
+  : mCurrentRequestFlags(0),
+    mPendingRequestFlags(0),
+    mObserverList(nullptr),
     mImageBlockingStatus(nsIContentPolicy::ACCEPT),
     mLoadingEnabled(true),
     mIsImageStateForced(false),
     mLoading(false),
     // mBroken starts out true, since an image without a URI is broken....
     mBroken(true),
     mUserDisabled(false),
     mSuppressed(false),
-    mBlockingOnload(false),
     mNewRequestsWillNeedAnimationReset(false),
-    mPendingRequestNeedsResetAnimation(false),
-    mCurrentRequestNeedsResetAnimation(false),
     mStateChangerDepth(0),
     mCurrentRequestRegistered(false),
     mPendingRequestRegistered(false)
 {
   if (!nsContentUtils::GetImgLoader()) {
     mLoadingEnabled = false;
   }
 }
@@ -148,33 +147,16 @@ nsImageLoadingContent::OnStartRequest(im
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsImageLoadingContent::OnStartDecode(imgIRequest* aRequest)
 {
   NS_ENSURE_TRUE(nsContentUtils::IsCallerChrome(), NS_ERROR_NOT_AVAILABLE);
 
-  // Onload blocking. This only applies for the current request.
-  if (aRequest == mCurrentRequest) {
-
-    // Determine whether this is a background request (this can be the case
-    // with multipart/x-mixed-replace images, for example).
-    PRUint32 loadFlags;
-    nsresult rv = aRequest->GetLoadFlags(&loadFlags);
-    bool background =
-      (NS_SUCCEEDED(rv) && (loadFlags & nsIRequest::LOAD_BACKGROUND));
-
-    // Block onload for non-background requests
-    if (!background) {
-      NS_ABORT_IF_FALSE(!mBlockingOnload, "Shouldn't already be blocking");
-      SetBlockingOnload(true);
-    }
-  }
-
   LOOP_OVER_OBSERVERS(OnStartDecode(aRequest));
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsImageLoadingContent::OnStartContainer(imgIRequest* aRequest,
                                         imgIContainer* aContainer)
 {
@@ -210,39 +192,26 @@ nsImageLoadingContent::OnDataAvailable(i
 }
 
 NS_IMETHODIMP
 nsImageLoadingContent::OnStopFrame(imgIRequest* aRequest,
                                    PRUint32 aFrame)
 {
   NS_ENSURE_TRUE(nsContentUtils::IsCallerChrome(), NS_ERROR_NOT_AVAILABLE);
 
-  // If we're blocking a load, one frame is enough
-  if (aRequest == mCurrentRequest)
-    SetBlockingOnload(false);
-
   LOOP_OVER_OBSERVERS(OnStopFrame(aRequest, aFrame));
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsImageLoadingContent::OnStopContainer(imgIRequest* aRequest,
                                        imgIContainer* aContainer)
 {
   NS_ENSURE_TRUE(nsContentUtils::IsCallerChrome(), NS_ERROR_NOT_AVAILABLE);
 
-  // This is really hacky. We need to handle the case where we start decoding,
-  // block onload, but then hit an error before we get to our first frame. In
-  // theory we would just hook in at OnStopDecode, but OnStopDecode is broken
-  // until we fix bug 505385. OnStopContainer is actually going away at that
-  // point. So for now we take advantage of the fact that OnStopContainer is
-  // always fired in the decoders at the same time as OnStopDecode.
-  if (aRequest == mCurrentRequest)
-    SetBlockingOnload(false);
-
   LOOP_OVER_OBSERVERS(OnStopContainer(aRequest, aContainer));
   return NS_OK;
 }
 
 // Warning - This isn't actually fired when decode is complete. Rather, it's
 // fired when load is complete. See bug 505385, and in the mean time use
 // OnStopContainer.
 NS_IMETHODIMP
@@ -287,32 +256,34 @@ nsImageLoadingContent::OnStopDecode(imgI
   // decoding, so we can't wait for them to finish. See bug 512435.
   //
   // (*) IsPaintingSuppressed returns false if we haven't gotten the initial
   // reflow yet, so we have to test !DidInitialReflow || IsPaintingSuppressed.
   // It's possible for painting to be suppressed for reasons other than the
   // initial paint delay (for example, being in the bfcache), but we probably
   // aren't loading images in those situations.
 
-  nsIDocument* doc = GetOurDocument();
+  // XXXkhuey should this be GetOurCurrentDoc?  Decoding if we're not in
+  // the document seems silly.
+  nsIDocument* doc = GetOurOwnerDoc();
   nsIPresShell* shell = doc ? doc->GetShell() : nullptr;
   if (shell && shell->IsVisible() &&
       (!shell->DidInitialReflow() || shell->IsPaintingSuppressed())) {
 
     mCurrentRequest->RequestDecode();
   }
 
   // Fire the appropriate DOM event.
   if (NS_SUCCEEDED(aStatus)) {
     FireEvent(NS_LITERAL_STRING("load"));
   } else {
     FireEvent(NS_LITERAL_STRING("error"));
   }
 
-  nsCOMPtr<nsINode> thisNode = do_QueryInterface(this);
+  nsCOMPtr<nsINode> thisNode = do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   nsSVGEffects::InvalidateDirectRenderingObservers(thisNode->AsElement());
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsImageLoadingContent::OnStopRequest(imgIRequest* aRequest, bool aLastPart)
 {
@@ -546,17 +517,17 @@ nsImageLoadingContent::LoadImageWithChan
                                             nsIStreamListener** aListener)
 {
   NS_ENSURE_TRUE(nsContentUtils::IsCallerChrome(), NS_ERROR_NOT_AVAILABLE);
 
   if (!nsContentUtils::GetImgLoader()) {
     return NS_ERROR_NULL_POINTER;
   }
 
-  nsCOMPtr<nsIDocument> doc = GetOurDocument();
+  nsCOMPtr<nsIDocument> doc = GetOurOwnerDoc();
   if (!doc) {
     // Don't bother
     return NS_OK;
   }
 
   // XXX what should we do with content policies here, if anything?
   // Shouldn't that be done before the start of the load?
   // XXX what about shouldProcess?
@@ -591,43 +562,57 @@ NS_IMETHODIMP nsImageLoadingContent::For
   GetCurrentURI(getter_AddRefs(currentURI));
   if (!currentURI) {
     return NS_ERROR_NOT_AVAILABLE;
   }
 
   return LoadImage(currentURI, true, true, nullptr, nsIRequest::VALIDATE_ALWAYS);
 }
 
+NS_IMETHODIMP
+nsImageLoadingContent::BlockOnload(imgIRequest* aRequest)
+{
+  if (aRequest != mCurrentRequest) {
+    return NS_OK;
+  }
+
+  nsIDocument* doc = GetOurCurrentDoc();
+  if (doc) {
+    doc->BlockOnload();
+  }
+
+  return NS_OK;
+}
+
+NS_IMETHODIMP
+nsImageLoadingContent::UnblockOnload(imgIRequest* aRequest)
+{
+  if (aRequest != mCurrentRequest) {
+    return NS_OK;
+  }
+
+  nsIDocument* doc = GetOurCurrentDoc();
+  if (doc) {
+    doc->UnblockOnload(false);
+  }
+
+  return NS_OK;
+}
+
 /*
  * Non-interface methods
  */
 
-void
-nsImageLoadingContent::NotifyOwnerDocumentChanged(nsIDocument *aOldDoc)
-{
-  // If we had a document before, unregister ourselves with it.
-  if (aOldDoc) {
-    if (mCurrentRequest)
-      aOldDoc->RemoveImage(mCurrentRequest);
-    if (mPendingRequest)
-      aOldDoc->RemoveImage(mPendingRequest);
-  }
-
-  // Re-track the images
-  TrackImage(mCurrentRequest);
-  TrackImage(mPendingRequest);
-}
-
 nsresult
 nsImageLoadingContent::LoadImage(const nsAString& aNewURI,
                                  bool aForce,
                                  bool aNotify)
 {
   // First, get a document (needed for security checks and the like)
-  nsIDocument* doc = GetOurDocument();
+  nsIDocument* doc = GetOurOwnerDoc();
   if (!doc) {
     // No reason to bother, I think...
     return NS_OK;
   }
 
   nsCOMPtr<nsIURI> imageURI;
   nsresult rv = StringToURI(aNewURI, doc, getter_AddRefs(imageURI));
   NS_ENSURE_SUCCESS(rv, rv);
@@ -665,21 +650,21 @@ nsImageLoadingContent::LoadImage(nsIURI*
 {
   if (!mLoadingEnabled) {
     // XXX Why fire an error here? seems like the callers to SetLoadingEnabled
     // don't want/need it.
     FireEvent(NS_LITERAL_STRING("error"));
     return NS_OK;
   }
 
-  NS_ASSERTION(!aDocument || aDocument == GetOurDocument(),
+  NS_ASSERTION(!aDocument || aDocument == GetOurOwnerDoc(),
                "Bogus document passed in");
   // First, get a document (needed for security checks and the like)
   if (!aDocument) {
-    aDocument = GetOurDocument();
+    aDocument = GetOurOwnerDoc();
     if (!aDocument) {
       // No reason to bother, I think...
       return NS_OK;
     }
   }
 
   // URI equality check.
   //
@@ -700,26 +685,29 @@ nsImageLoadingContent::LoadImage(nsIURI*
   // From this point on, our image state could change. Watch it.
   AutoStateChanger changer(this, aNotify);
 
   // Sanity check.
   //
   // We use the principal of aDocument to avoid having to QI |this| an extra
   // time. It should always be the same as the principal of this node.
 #ifdef DEBUG
-  nsCOMPtr<nsIContent> thisContent = do_QueryInterface(this);
+  nsCOMPtr<nsIContent> thisContent = do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   NS_ABORT_IF_FALSE(thisContent &&
                     thisContent->NodePrincipal() == aDocument->NodePrincipal(),
                     "Principal mismatch?");
 #endif
 
   // Are we blocked?
   PRInt16 cpDecision = nsIContentPolicy::REJECT_REQUEST;
-  nsContentUtils::CanLoadImage(aNewURI, this, aDocument,
-                               aDocument->NodePrincipal(), &cpDecision);
+  nsContentUtils::CanLoadImage(aNewURI,
+                               static_cast<nsIImageLoadingContent*>(this),
+                               aDocument,
+                               aDocument->NodePrincipal(),
+                               &cpDecision);
   if (!NS_CP_ACCEPTED(cpDecision)) {
     FireEvent(NS_LITERAL_STRING("error"));
     SetBlockedRequest(aNewURI, cpDecision);
     return NS_OK;
   }
 
   nsLoadFlags loadFlags = aLoadFlags;
   PRInt32 corsmode = GetCORSMode();
@@ -815,17 +803,17 @@ nsImageLoadingContent::UpdateImageState(
     // changer is destroyed. Need this to work around the fact that some libpr0n
     // stuff is actually sync and hence we can get OnStopDecode called while
     // we're still under LoadImage, and OnStopDecode doesn't know anything about
     // aNotify.
     // XXX - This machinery should be removed after bug 521604.
     return;
   }
   
-  nsCOMPtr<nsIContent> thisContent = do_QueryInterface(this);
+  nsCOMPtr<nsIContent> thisContent = do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   if (!thisContent) {
     return;
   }
 
   mLoading = mBroken = mUserDisabled = mSuppressed = false;
   
   // If we were blocked by server-based content policy, we claim to be
   // suppressed.  If we were blocked by type-based content policy, we claim to
@@ -877,28 +865,40 @@ nsImageLoadingContent::UseAsPrimaryReque
     TrackImage(req);
   else
     return rv;
 
   return NS_OK;
 }
 
 nsIDocument*
-nsImageLoadingContent::GetOurDocument()
+nsImageLoadingContent::GetOurOwnerDoc()
 {
-  nsCOMPtr<nsIContent> thisContent = do_QueryInterface(this);
+  nsCOMPtr<nsIContent> thisContent =
+    do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   NS_ENSURE_TRUE(thisContent, nullptr);
 
   return thisContent->OwnerDoc();
 }
 
+nsIDocument*
+nsImageLoadingContent::GetOurCurrentDoc()
+{
+  nsCOMPtr<nsIContent> thisContent =
+    do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
+  NS_ENSURE_TRUE(thisContent, nullptr);
+
+  return thisContent->GetCurrentDoc();
+}
+
 nsIFrame*
 nsImageLoadingContent::GetOurPrimaryFrame()
 {
-  nsCOMPtr<nsIContent> thisContent = do_QueryInterface(this);
+  nsCOMPtr<nsIContent> thisContent =
+    do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   return thisContent->GetPrimaryFrame();
 }
 
 nsPresContext* nsImageLoadingContent::GetFramePresContext()
 {
   nsIFrame* frame = GetOurPrimaryFrame();
   if (!frame) {
     return nullptr;
@@ -911,17 +911,17 @@ nsresult
 nsImageLoadingContent::StringToURI(const nsAString& aSpec,
                                    nsIDocument* aDocument,
                                    nsIURI** aURI)
 {
   NS_PRECONDITION(aDocument, "Must have a document");
   NS_PRECONDITION(aURI, "Null out param");
 
   // (1) Get the base URI
-  nsCOMPtr<nsIContent> thisContent = do_QueryInterface(this);
+  nsCOMPtr<nsIContent> thisContent = do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
   NS_ASSERTION(thisContent, "An image loading content must be an nsIContent");
   nsCOMPtr<nsIURI> baseURL = thisContent->GetBaseURI();
 
   // (2) Get the charset
   const nsAFlatCString &charset = aDocument->GetDocumentCharacterSet();
 
   // (3) Construct the silly thing
   return NS_NewURI(aURI,
@@ -933,17 +933,17 @@ nsImageLoadingContent::StringToURI(const
 
 nsresult
 nsImageLoadingContent::FireEvent(const nsAString& aEventType)
 {
   // We have to fire the event asynchronously so that we won't go into infinite
   // loops in cases when onLoad handlers reset the src and the new src is in
   // cache.
 
-  nsCOMPtr<nsINode> thisNode = do_QueryInterface(this);
+  nsCOMPtr<nsINode> thisNode = do_QueryInterface(static_cast<nsIImageLoadingContent*>(this));
 
   nsRefPtr<nsAsyncDOMEvent> event =
     new nsLoadBlockingAsyncDOMEvent(thisNode, aEventType, false, false);
   event->PostDOMEvent();
   
   return NS_OK;
 }
 
@@ -991,29 +991,33 @@ nsImageLoadingContent::PrepareCurrentReq
 {
   // Blocked images go through SetBlockedRequest, which is a separate path. For
   // everything else, we're unblocked.
   mImageBlockingStatus = nsIContentPolicy::ACCEPT;
 
   // Get rid of anything that was there previously.
   ClearCurrentRequest(NS_ERROR_IMAGE_SRC_CHANGED);
 
-  mCurrentRequestNeedsResetAnimation = mNewRequestsWillNeedAnimationReset;
+  if (mNewRequestsWillNeedAnimationReset) {
+    mCurrentRequestFlags |= REQUEST_NEEDS_ANIMATION_RESET;
+  }
 
   // Return a reference.
   return mCurrentRequest;
 }
 
 nsCOMPtr<imgIRequest>&
 nsImageLoadingContent::PreparePendingRequest()
 {
   // Get rid of anything that was there previously.
   ClearPendingRequest(NS_ERROR_IMAGE_SRC_CHANGED);
 
-  mPendingRequestNeedsResetAnimation = mNewRequestsWillNeedAnimationReset;
+  if (mNewRequestsWillNeedAnimationReset) {
+    mPendingRequestFlags |= REQUEST_NEEDS_ANIMATION_RESET;
+  }
 
   // Return a reference.
   return mPendingRequest;
 }
 
 namespace {
 
 class ImageRequestAutoLock
@@ -1049,18 +1053,18 @@ nsImageLoadingContent::MakePendingReques
   // PrepareCurrentRequest() might unlock mCurrentRequest.  If mCurrentRequest
   // and mPendingRequest are both requests for the same image, unlocking
   // mCurrentRequest before we lock mPendingRequest can cause the lock count
   // to go to 0 and the image to be discarded!
   ImageRequestAutoLock autoLock(mCurrentRequest);
 
   PrepareCurrentRequest() = mPendingRequest;
   mPendingRequest = nullptr;
-  mCurrentRequestNeedsResetAnimation = mPendingRequestNeedsResetAnimation;
-  mPendingRequestNeedsResetAnimation = false;
+  mCurrentRequestFlags = mPendingRequestFlags;
+  mPendingRequestFlags = 0;
   ResetAnimationIfNeeded();
 }
 
 void
 nsImageLoadingContent::ClearCurrentRequest(nsresult aReason)
 {
   if (!mCurrentRequest) {
     // Even if we didn't have a current request, we might have been keeping
@@ -1075,21 +1079,17 @@ nsImageLoadingContent::ClearCurrentReque
   // notifications.
   nsLayoutUtils::DeregisterImageRequest(GetFramePresContext(), mCurrentRequest,
                                         &mCurrentRequestRegistered);
 
   // Clean up the request.
   UntrackImage(mCurrentRequest);
   mCurrentRequest->CancelAndForgetObserver(aReason);
   mCurrentRequest = nullptr;
-  mCurrentRequestNeedsResetAnimation = false;
-
-  // We only block onload during the decoding of "current" images. This one is
-  // going away, so we should unblock unconditionally here.
-  SetBlockingOnload(false);
+  mCurrentRequestFlags = 0;
 }
 
 void
 nsImageLoadingContent::ClearPendingRequest(nsresult aReason)
 {
   if (!mPendingRequest)
     return;
 
@@ -1102,17 +1102,17 @@ nsImageLoadingContent::ClearPendingReque
   // Deregister this image from the refresh driver so it no longer receives
   // notifications.
   nsLayoutUtils::DeregisterImageRequest(GetFramePresContext(), mPendingRequest,
                                         &mPendingRequestRegistered);
 
   UntrackImage(mPendingRequest);
   mPendingRequest->CancelAndForgetObserver(aReason);
   mPendingRequest = nullptr;
-  mPendingRequestNeedsResetAnimation = false;
+  mPendingRequestFlags = 0;
 }
 
 bool*
 nsImageLoadingContent::GetRegisteredFlagForRequest(imgIRequest* aRequest)
 {
   if (aRequest == mCurrentRequest) {
     return &mCurrentRequestRegistered;
   } else if (aRequest == mPendingRequest) {
@@ -1120,22 +1120,23 @@ nsImageLoadingContent::GetRegisteredFlag
   } else {
     return nullptr;
   }
 }
 
 void
 nsImageLoadingContent::ResetAnimationIfNeeded()
 {
-  if (mCurrentRequest && mCurrentRequestNeedsResetAnimation) {
+  if (mCurrentRequest &&
+      (mCurrentRequestFlags & REQUEST_NEEDS_ANIMATION_RESET)) {
     nsCOMPtr<imgIContainer> container;
     mCurrentRequest->GetImage(getter_AddRefs(container));
     if (container)
       container->ResetAnimation();
-    mCurrentRequestNeedsResetAnimation = false;
+    mCurrentRequestFlags &= ~REQUEST_NEEDS_ANIMATION_RESET;
   }
 }
 
 bool
 nsImageLoadingContent::HaveSize(imgIRequest *aImage)
 {
   // Handle the null case
   if (!aImage)
@@ -1143,59 +1144,83 @@ nsImageLoadingContent::HaveSize(imgIRequ
 
   // Query the image
   PRUint32 status;
   nsresult rv = aImage->GetImageStatus(&status);
   return (NS_SUCCEEDED(rv) && (status & imgIRequest::STATUS_SIZE_AVAILABLE));
 }
 
 void
-nsImageLoadingContent::SetBlockingOnload(bool aBlocking)
+nsImageLoadingContent::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
+                                  nsIContent* aBindingParent,
+                                  bool aCompileEventHandlers)
 {
-  // If we're already in the desired state, we have nothing to do
-  if (mBlockingOnload == aBlocking)
+  // We may be entering the document, so if our image should be tracked,
+  // track it.
+  if (!aDocument)
     return;
 
-  // Get the document
-  nsIDocument* doc = GetOurDocument();
+  if (mCurrentRequestFlags & REQUEST_SHOULD_BE_TRACKED)
+    aDocument->AddImage(mCurrentRequest);
+  if (mPendingRequestFlags & REQUEST_SHOULD_BE_TRACKED)
+    aDocument->AddImage(mPendingRequest);
+}
 
-  if (doc) {
-    // Take the appropriate action
-    if (aBlocking)
-      doc->BlockOnload();
-    else
-      doc->UnblockOnload(false);
+void
+nsImageLoadingContent::UnbindFromTree(bool aDeep, bool aNullParent)
+{
+  // We may be leaving the document, so if our image is tracked, untrack it.
+  nsCOMPtr<nsIDocument> doc = GetOurCurrentDoc();
+  if (!doc)
+    return;
 
-    // Update our state
-    mBlockingOnload = aBlocking;
-  }
+  if (mCurrentRequestFlags & REQUEST_SHOULD_BE_TRACKED)
+    doc->RemoveImage(mCurrentRequest);
+  if (mPendingRequestFlags & REQUEST_SHOULD_BE_TRACKED)
+    doc->RemoveImage(mPendingRequest);
 }
 
 nsresult
 nsImageLoadingContent::TrackImage(imgIRequest* aImage)
 {
   if (!aImage)
     return NS_OK;
 
-  nsIDocument* doc = GetOurDocument();
+  MOZ_ASSERT(aImage == mCurrentRequest || aImage == mPendingRequest,
+             "Why haven't we heard of this request?");
+  if (aImage == mCurrentRequest) {
+    mCurrentRequestFlags |= REQUEST_SHOULD_BE_TRACKED;
+  } else {
+    mPendingRequestFlags |= REQUEST_SHOULD_BE_TRACKED;
+  }
+
+  nsIDocument* doc = GetOurCurrentDoc();
   if (doc)
     return doc->AddImage(aImage);
   return NS_OK;
 }
 
 nsresult
 nsImageLoadingContent::UntrackImage(imgIRequest* aImage)
 {
   if (!aImage)
     return NS_OK;
 
+  MOZ_ASSERT(aImage == mCurrentRequest || aImage == mPendingRequest,
+             "Why haven't we heard of this request?");
+  if (aImage == mCurrentRequest) {
+    mCurrentRequestFlags &= ~REQUEST_SHOULD_BE_TRACKED;
+  } else {
+    mPendingRequestFlags &= ~REQUEST_SHOULD_BE_TRACKED;
+  }
+
   // If GetOurDocument() returns null here, we've outlived our document.
   // That's fine, because the document empties out the tracker and unlocks
   // all locked images on destruction.
-  nsIDocument* doc = GetOurDocument();
+  nsIDocument* doc = GetOurCurrentDoc();
   if (doc)
     return doc->RemoveImage(aImage);
   return NS_OK;
 }
 
 
 void
 nsImageLoadingContent::CreateStaticImageClone(nsImageLoadingContent* aDest) const
--- a/content/base/src/nsImageLoadingContent.h
+++ b/content/base/src/nsImageLoadingContent.h
@@ -10,38 +10,41 @@
  * loading functionality (eg <img>, <object>, etc).
  */
 
 #ifndef nsImageLoadingContent_h__
 #define nsImageLoadingContent_h__
 
 #include "imgIContainerObserver.h"
 #include "imgIDecoderObserver.h"
+#include "imgIOnloadBlocker.h"
 #include "mozilla/CORSMode.h"
 #include "nsCOMPtr.h"
 #include "nsContentUtils.h" // NS_CONTENT_DELETE_LIST_MEMBER
 #include "nsEventStates.h"
 #include "nsIImageLoadingContent.h"
 #include "nsIRequest.h"
 
 class nsIURI;
 class nsIDocument;
 class imgILoader;
 class nsIIOService;
 
-class nsImageLoadingContent : public nsIImageLoadingContent
+class nsImageLoadingContent : public nsIImageLoadingContent,
+                              public imgIOnloadBlocker
 {
   /* METHODS */
 public:
   nsImageLoadingContent();
   virtual ~nsImageLoadingContent();
 
   NS_DECL_IMGICONTAINEROBSERVER
   NS_DECL_IMGIDECODEROBSERVER
   NS_DECL_NSIIMAGELOADINGCONTENT
+  NS_DECL_IMGIONLOADBLOCKER
 
 protected:
   /**
    * LoadImage is called by subclasses when the appropriate
    * attributes (eg 'src' for <img> tags) change.  The string passed
    * in is the new uri string; this consolidates the code for getting
    * the charset, constructing URI objects, and any other incidentals
    * into this superclass.   
@@ -82,23 +85,24 @@ protected:
    * @param aLoadFlags Optional parameter specifying load flags to use for
    *        the image load
    */
   nsresult LoadImage(nsIURI* aNewURI, bool aForce, bool aNotify,
                      nsIDocument* aDocument = nullptr,
                      nsLoadFlags aLoadFlags = nsIRequest::LOAD_NORMAL);
 
   /**
-   * helper to get the document for this content (from the nodeinfo
-   * and such).  Not named GetDocument to prevent ambiguous method
-   * names in subclasses
+   * helpers to get the document for this content (from the nodeinfo
+   * and such).  Not named GetOwnerDoc/GetCurrentDoc to prevent ambiguous
+   * method names in subclasses
    *
    * @return the document we belong to
    */
-  nsIDocument* GetOurDocument();
+  nsIDocument* GetOurOwnerDoc();
+  nsIDocument* GetOurCurrentDoc();
 
   /**
    * Helper function to get the frame associated with this content. Not named
    * GetPrimaryFrame to prevent ambiguous method names in subclasses.
    *
    * @return The frame which we belong to, or nullptr if it doesn't exist.
    */
   nsIFrame* GetOurPrimaryFrame();
@@ -147,16 +151,21 @@ protected:
   void SetBlockingOnload(bool aBlocking);
 
   /**
    * Returns the CORS mode that will be used for all future image loads. The
    * default implementation returns CORS_NONE unconditionally.
    */
   virtual mozilla::CORSMode GetCORSMode();
 
+  // Subclasses are *required* to call BindToTree/UnbindFromTree.
+  void BindToTree(nsIDocument* aDocument, nsIContent* aParent,
+                  nsIContent* aBindingParent, bool aCompileEventHandlers);
+  void UnbindFromTree(bool aDeep, bool aNullParent);
+
 private:
   /**
    * Struct used to manage the image observers.
    */
   struct ImageObserver {
     ImageObserver(imgIDecoderObserver* aObserver) :
       mObserver(aObserver),
       mNext(nullptr)
@@ -303,16 +312,26 @@ protected:
    * No-op if aImage is null.
    */
   nsresult TrackImage(imgIRequest* aImage);
   nsresult UntrackImage(imgIRequest* aImage);
 
   /* MEMBERS */
   nsCOMPtr<imgIRequest> mCurrentRequest;
   nsCOMPtr<imgIRequest> mPendingRequest;
+  PRUint32 mCurrentRequestFlags;
+  PRUint32 mPendingRequestFlags;
+
+  enum {
+    // Set if the request needs 
+    REQUEST_NEEDS_ANIMATION_RESET = 0x00000001U,
+    // Set if the request should be tracked.  This is true if the request is
+    // not tracked iff this node is not in the document.
+    REQUEST_SHOULD_BE_TRACKED = 0x00000002U
+  };
 
   // If the image was blocked or if there was an error loading, it's nice to
   // still keep track of what the URI was despite not having an imgIRequest.
   // We only maintain this in those situations (in the common case, this is
   // always null).
   nsCOMPtr<nsIURI>      mCurrentURI;
 
 private:
@@ -344,36 +363,28 @@ private:
    * The state we had the last time we checked whether we needed to notify the
    * document of a state change.  These are maintained by UpdateImageState.
    */
   bool mLoading : 1;
   bool mBroken : 1;
   bool mUserDisabled : 1;
   bool mSuppressed : 1;
 
-  /**
-   * Whether we're currently blocking document load.
-   */
-  bool mBlockingOnload : 1;
-
 protected:
   /**
    * A hack to get animations to reset, see bug 594771. On requests
    * that originate from setting .src, we mark them for needing their animation
    * reset when they are ready. mNewRequestsWillNeedAnimationReset is set to
    * true while preparing such requests (as a hack around needing to change an
    * interface), and the other two booleans store which of the current
    * and pending requests are of the sort that need their animation restarted.
    */
   bool mNewRequestsWillNeedAnimationReset : 1;
 
 private:
-  bool mPendingRequestNeedsResetAnimation : 1;
-  bool mCurrentRequestNeedsResetAnimation : 1;
-
   /* The number of nested AutoStateChangers currently tracking our state. */
   PRUint8 mStateChangerDepth;
 
   // Flags to indicate whether each of the current and pending requests are
   // registered with the refresh driver.
   bool mCurrentRequestRegistered;
   bool mPendingRequestRegistered;
 };
--- a/content/base/src/nsNodeIterator.cpp
+++ b/content/base/src/nsNodeIterator.cpp
@@ -7,17 +7,17 @@
 /*
  * Implementation of DOM Traversal's nsIDOMNodeIterator
  */
 
 #include "nsNodeIterator.h"
 
 #include "nsIDOMNode.h"
 #include "nsIDOMNodeFilter.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsDOMClassInfoID.h"
 #include "nsContentUtils.h"
 #include "nsCOMPtr.h"
 
 /*
--- a/content/base/src/nsNodeUtils.cpp
+++ b/content/base/src/nsNodeUtils.cpp
@@ -23,17 +23,16 @@
 #ifdef MOZ_XUL
 #include "nsXULElement.h"
 #endif
 #include "nsBindingManager.h"
 #include "nsGenericHTMLElement.h"
 #ifdef MOZ_MEDIA
 #include "nsHTMLMediaElement.h"
 #endif // MOZ_MEDIA
-#include "nsImageLoadingContent.h"
 #include "jsgc.h"
 #include "nsWrapperCacheInlines.h"
 #include "nsObjectLoadingContent.h"
 #include "nsDOMMutationObserver.h"
 
 using namespace mozilla::dom;
 
 // This macro expects the ownerDocument of content_ to be in scope as
@@ -104,16 +103,26 @@ nsNodeUtils::AttributeChanged(Element* a
 {
   nsIDocument* doc = aElement->OwnerDoc();
   IMPL_MUTATION_NOTIFICATION(AttributeChanged, aElement,
                              (doc, aElement, aNameSpaceID, aAttribute,
                               aModType));
 }
 
 void
+nsNodeUtils::AttributeSetToCurrentValue(Element* aElement,
+                                        PRInt32 aNameSpaceID,
+                                        nsIAtom* aAttribute)
+{
+  nsIDocument* doc = aElement->OwnerDoc();
+  IMPL_MUTATION_NOTIFICATION(AttributeSetToCurrentValue, aElement,
+                             (doc, aElement, aNameSpaceID, aAttribute));
+}
+
+void
 nsNodeUtils::ContentAppended(nsIContent* aContainer,
                              nsIContent* aFirstNewContent,
                              PRInt32 aNewIndexInContainer)
 {
   nsIDocument* doc = aContainer->OwnerDoc();
 
   IMPL_MUTATION_NOTIFICATION(ContentAppended, aContainer,
                              (doc, aContainer, aFirstNewContent,
@@ -506,26 +515,19 @@ nsNodeUtils::CloneAndAdopt(nsINode *aNod
       }
 #endif
       nsCOMPtr<nsIObjectLoadingContent> objectLoadingContent(do_QueryInterface(aNode));
       if (objectLoadingContent) {
         nsObjectLoadingContent* olc = static_cast<nsObjectLoadingContent*>(objectLoadingContent.get());
         olc->NotifyOwnerDocumentActivityChanged();
       }
     }
-
-    // nsImageLoadingContent needs to know when its document changes
-    if (oldDoc != newDoc) {
-      nsCOMPtr<nsIImageLoadingContent> imageContent(do_QueryInterface(aNode));
-      if (imageContent) {
-        imageContent->NotifyOwnerDocumentChanged(oldDoc);
-      }
-      if (oldDoc->MayHaveDOMMutationObservers()) {
-        newDoc->SetMayHaveDOMMutationObservers();
-      }
+ 
+    if (oldDoc != newDoc && oldDoc->MayHaveDOMMutationObservers()) {
+      newDoc->SetMayHaveDOMMutationObservers();
     }
 
     if (elem) {
       elem->RecompileScriptEventListeners();
     }
 
     if (aCx && wrapper) {
       nsIXPConnect *xpc = nsContentUtils::XPConnect();
--- a/content/base/src/nsNodeUtils.h
+++ b/content/base/src/nsNodeUtils.h
@@ -59,16 +59,26 @@ public:
    * @param aAttribute    Local-name of changed attribute
    * @param aModType      Type of change (add/change/removal)
    * @see nsIMutationObserver::AttributeChanged
    */
   static void AttributeChanged(mozilla::dom::Element* aElement,
                                PRInt32 aNameSpaceID,
                                nsIAtom* aAttribute,
                                PRInt32 aModType);
+  /**
+   * Send AttributeSetToCurrentValue notifications to nsIMutationObservers.
+   * @param aElement      Element whose data changed
+   * @param aNameSpaceID  Namespace of the attribute
+   * @param aAttribute    Local-name of the attribute
+   * @see nsIMutationObserver::AttributeSetToCurrentValue
+   */
+  static void AttributeSetToCurrentValue(mozilla::dom::Element* aElement,
+                                         PRInt32 aNameSpaceID,
+                                         nsIAtom* aAttribute);
 
   /**
    * Send ContentAppended notifications to nsIMutationObservers
    * @param aContainer           Node into which new child/children were added
    * @param aFirstNewContent     First new child
    * @param aNewIndexInContainer Index of first new child
    * @see nsIMutationObserver::ContentAppended
    */
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -33,17 +33,17 @@
 #include "nsIURL.h"
 #include "nsIWebNavigation.h"
 #include "nsIWebNavigationInfo.h"
 #include "nsIScriptChannel.h"
 #include "nsIBlocklistService.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsIAppShell.h"
 
-#include "nsPluginError.h"
+#include "nsError.h"
 
 // Util headers
 #include "prenv.h"
 #include "prlog.h"
 
 #include "nsAutoPtr.h"
 #include "nsCURILoader.h"
 #include "nsContentPolicyUtils.h"
@@ -535,17 +535,17 @@ IsPluginEnabledByExtension(nsIURI* uri, 
 nsresult
 IsPluginEnabledForType(const nsCString& aMIMEType)
 {
   nsRefPtr<nsPluginHost> pluginHost =
     already_AddRefed<nsPluginHost>(nsPluginHost::GetInst());
 
   if (!pluginHost) {
     NS_NOTREACHED("No pluginhost");
-    return false;
+    return NS_ERROR_FAILURE;
   }
 
   nsresult rv = pluginHost->IsPluginEnabledForType(aMIMEType.get());
 
   // Check to see if the plugin is disabled before deciding if it
   // should be in the "click to play" state, since we only want to
   // display "click to play" UI for enabled plugins.
   if (NS_FAILED(rv)) {
@@ -600,29 +600,34 @@ nsObjectLoadingContent::IsSupportedDocum
   if (convServ) {
     rv = convServ->CanConvert(aMimeType.get(), "*/*", &canConvert);
   }
   return NS_SUCCEEDED(rv) && canConvert;
 }
 
 nsresult
 nsObjectLoadingContent::BindToTree(nsIDocument* aDocument,
-                                   nsIContent* /*aParent*/,
-                                   nsIContent* /*aBindingParent*/,
-                                   bool /*aCompileEventHandlers*/)
+                                   nsIContent* aParent,
+                                   nsIContent* aBindingParent,
+                                   bool aCompileEventHandlers)
 {
+  nsImageLoadingContent::BindToTree(aDocument, aParent, aBindingParent,
+                                    aCompileEventHandlers);
+
   if (aDocument) {
     return aDocument->AddPlugin(this);
   }
   return NS_OK;
 }
 
 void
-nsObjectLoadingContent::UnbindFromTree(bool /*aDeep*/, bool /*aNullParent*/)
+nsObjectLoadingContent::UnbindFromTree(bool aDeep, bool aNullParent)
 {
+  nsImageLoadingContent::UnbindFromTree(aDeep, aNullParent);
+
   nsCOMPtr<nsIContent> thisContent =
     do_QueryInterface(static_cast<nsIObjectLoadingContent*>(this));
   MOZ_ASSERT(thisContent);
   nsIDocument* ownerDoc = thisContent->OwnerDoc();
   ownerDoc->RemovePlugin(this);
 
   if (mType == eType_Plugin && mInstanceOwner) {
     // we'll let the plugin continue to run at least until we get back to
@@ -630,17 +635,18 @@ nsObjectLoadingContent::UnbindFromTree(b
     // has still not been added back to the document then we tear down the
     // plugin
     nsCOMPtr<nsIRunnable> event = new InDocCheckEvent(this);
 
     nsCOMPtr<nsIAppShell> appShell = do_GetService(kAppShellCID);
     if (appShell) {
       appShell->RunInStableState(event);
     }
-  } else {
+  } else if (mType != eType_Image) {
+    // nsImageLoadingContent handles the image case.
     // Reset state and clear pending events
     /// XXX(johns): The implementation for GenericFrame notes that ideally we
     ///             would keep the docshell around, but trash the frameloader
     UnloadObject();
   }
 
 }
 
@@ -715,17 +721,17 @@ nsObjectLoadingContent::InstantiatePlugi
   doc->FlushPendingNotifications(Flush_Layout);
 
   nsresult rv = NS_ERROR_FAILURE;
   nsRefPtr<nsPluginHost> pluginHost =
     already_AddRefed<nsPluginHost>(nsPluginHost::GetInst());
 
   if (!pluginHost) {
     NS_NOTREACHED("No pluginhost");
-    return false;
+    return NS_ERROR_FAILURE;
   }
 
   // If you add early return(s), be sure to balance this call to
   // appShell->SuspendNative() with additional call(s) to
   // appShell->ReturnNative().
   nsCOMPtr<nsIAppShell> appShell = do_GetService(kAppShellCID);
   if (appShell) {
     appShell->SuspendNative();
--- a/content/base/src/nsPropertyTable.cpp
+++ b/content/base/src/nsPropertyTable.cpp
@@ -17,17 +17,17 @@
  * nsPropertyTable allows a set of arbitrary key/value pairs to be stored
  * for any number of nodes, in a global hashtable rather than on the nodes
  * themselves.  Nodes can be any type of object; the hashtable keys are
  * nsIAtom pointers, and the values are void pointers.
  */
 
 #include "nsPropertyTable.h"
 #include "pldhash.h"
-#include "nsContentErrors.h"
+#include "nsError.h"
 #include "nsIAtom.h"
 
 struct PropertyListMapEntry : public PLDHashEntryHdr {
   const void  *key;
   void        *value;
 };
 
 //----------------------------------------------------------------------
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -14,17 +14,17 @@
 #include "nsReadableUtils.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentFragment.h"
 #include "nsIDOMDocumentType.h"
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsIDOMText.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIContentIterator.h"
 #include "nsIDOMNodeList.h"
 #include "nsGkAtoms.h"
 #include "nsContentUtils.h"
 #include "nsGenericDOMDataNode.h"
 #include "nsClientRect.h"
 #include "nsLayoutUtils.h"
 #include "nsTextFrame.h"
--- a/content/base/src/nsScriptLoader.cpp
+++ b/content/base/src/nsScriptLoader.cpp
@@ -26,17 +26,17 @@
 #include "nsIHttpChannel.h"
 #include "nsIScriptElement.h"
 #include "nsIDOMHTMLScriptElement.h"
 #include "nsIDocShell.h"
 #include "nsContentUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsAutoPtr.h"
 #include "nsIXPConnect.h"
-#include "nsContentErrors.h"
+#include "nsError.h"
 #include "nsThreadUtils.h"
 #include "nsDocShellCID.h"
 #include "nsIContentSecurityPolicy.h"
 #include "prlog.h"
 #include "nsIChannelPolicy.h"
 #include "nsChannelPolicy.h"
 #include "nsCRT.h"
 #include "nsContentCreatorFunctions.h"
--- a/content/base/src/nsTraversal.cpp
+++ b/content/base/src/nsTraversal.cpp
@@ -3,17 +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/. */
 
 #include "nsTraversal.h"
 
 #include "nsIDOMNode.h"
 #include "nsIDOMNodeFilter.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsINode.h"
 
 #include "nsGkAtoms.h"
 
 nsTraversal::nsTraversal(nsINode *aRoot,
                          PRUint32 aWhatToShow,
                          nsIDOMNodeFilter *aFilter) :
     mRoot(aRoot),
--- a/content/base/src/nsTreeWalker.cpp
+++ b/content/base/src/nsTreeWalker.cpp
@@ -7,17 +7,17 @@
 /*
  * Implementation of DOM Traversal's nsIDOMTreeWalker
  */
 
 #include "nsTreeWalker.h"
 
 #include "nsIDOMNode.h"
 #include "nsIDOMNodeFilter.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsINode.h"
 #include "nsDOMClassInfoID.h"
 #include "nsContentUtils.h"
 
 /*
  * Factories, constructors and destructors
  */
 
--- a/content/base/src/nsWebSocket.cpp
+++ b/content/base/src/nsWebSocket.cpp
@@ -10,17 +10,17 @@
 
 #include "nsIScriptGlobalObject.h"
 #include "nsIDOMWindow.h"
 #include "nsIDocument.h"
 #include "nsXPCOM.h"
 #include "nsIXPConnect.h"
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsDOMClassInfoID.h"
 #include "jsapi.h"
 #include "nsIURL.h"
 #include "nsICharsetConverterManager.h"
 #include "nsIUnicodeEncoder.h"
 #include "nsThreadUtils.h"
 #include "nsIDOMMessageEvent.h"
@@ -37,17 +37,16 @@
 #include "nsJSUtils.h"
 #include "nsIScriptError.h"
 #include "nsNetUtil.h"
 #include "nsILoadGroup.h"
 #include "mozilla/Preferences.h"
 #include "nsDOMLists.h"
 #include "xpcpublic.h"
 #include "nsContentPolicyUtils.h"
-#include "nsContentErrors.h"
 #include "jsfriendapi.h"
 #include "prmem.h"
 #include "nsDOMFile.h"
 #include "nsWrapperCacheInlines.h"
 #include "nsDOMEventTargetHelper.h"
 #include "nsIObserverService.h"
 #include "GeneratedEvents.h"
 
--- a/content/base/src/nsXMLHttpRequest.cpp
+++ b/content/base/src/nsXMLHttpRequest.cpp
@@ -46,20 +46,19 @@
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
 #include "nsDOMJSUtils.h"
 #include "nsCOMArray.h"
 #include "nsIScriptableUConv.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsIContentPolicy.h"
 #include "nsContentPolicyUtils.h"
-#include "nsContentErrors.h"
+#include "nsError.h"
 #include "nsLayoutStatics.h"
 #include "nsCrossSiteListenerProxy.h"
-#include "nsDOMError.h"
 #include "nsIHTMLDocument.h"
 #include "nsIMultiPartChannel.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsIStorageStream.h"
 #include "nsIPromptFactory.h"
 #include "nsIWindowWatcher.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsIConsoleService.h"
@@ -3220,18 +3219,18 @@ nsXMLHttpRequest::SetRequestHeader(const
   if (NS_FAILED(IsCapabilityEnabled("UniversalXPConnect", &privileged)))
     return NS_ERROR_FAILURE;
 
   if (!privileged) {
     // Step 5: Check for dangerous headers.
     const char *kInvalidHeaders[] = {
       "accept-charset", "accept-encoding", "access-control-request-headers",
       "access-control-request-method", "connection", "content-length",
-      "cookie", "cookie2", "content-transfer-encoding", "date", "expect",
-      "host", "keep-alive", "origin", "referer", "te", "trailer",
+      "cookie", "cookie2", "content-transfer-encoding", "date", "dnt",
+      "expect", "host", "keep-alive", "origin", "referer", "te", "trailer",
       "transfer-encoding", "upgrade", "user-agent", "via"
     };
     PRUint32 i;
     for (i = 0; i < ArrayLength(kInvalidHeaders); ++i) {
       if (header.LowerCaseEqualsASCII(kInvalidHeaders[i])) {
         NS_WARNING("refusing to set request header");
         return NS_OK;
       }
--- a/content/base/test/chrome/Makefile.in
+++ b/content/base/test/chrome/Makefile.in
@@ -38,11 +38,12 @@ MOCHITEST_CHROME_FILES = \
     test_bug574596.html \
     test_bug683852.xul \
     test_bug599295.html \
     test_bug650776.html \
     test_bug650784.html \
     test_bug752226-3.xul \
     test_bug752226-4.xul \
     test_bug682305.html \
+    test_bug780199.xul \
     $(NULL)
 
 include $(topsrcdir)/config/rules.mk
new file mode 100644
--- /dev/null
+++ b/content/base/test/chrome/test_bug780199.xul
@@ -0,0 +1,51 @@
+<?xml version="1.0"?>
+<?xml-stylesheet type="text/css" href="chrome://global/skin"?>
+<?xml-stylesheet type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css"?>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=780199
+-->
+<window title="Mozilla Bug 780199"
+        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
+        onload="test()">
+  <script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"/>
+
+  <!-- test results are displayed in the html:body -->
+  <body xmlns="http://www.w3.org/1999/xhtml">
+  <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=780199"
+     target="_blank">Mozilla Bug 780199</a>
+  </body>
+
+  <!-- test code goes here -->
+  <script type="application/javascript">
+  <![CDATA[
+
+  /** Test for Bug 780199 **/
+
+  SimpleTest.waitForExplicitFinish();
+
+  var b;
+
+  function callback(r) {
+    is(r[0].type, "attributes");
+    is(r[0].oldValue, b.getAttribute("src"));
+    setTimeout(continueTest, 500);
+  }
+
+  function continueTest() {
+    // Check that a new page wasn't loaded.
+    is(b.contentDocument.documentElement.textContent, "testvalue");
+    SimpleTest.finish();
+  }
+
+  function test() {
+    b = document.getElementById("b");
+    var m = MutationObserver(callback);
+    m.observe(b, { attributes: true, attributeOldValue: true });
+    b.contentDocument.documentElement.textContent = "testvalue";
+    b.setAttribute("src", b.getAttribute("src"));
+  }
+
+  ]]>
+  </script>
+  <browser id="b" src="data:text/plain,initial"/>
+</window>
--- a/content/base/test/test_ipc_messagemanager_blob.html
+++ b/content/base/test/test_ipc_messagemanager_blob.html
@@ -62,17 +62,20 @@
           0,
           new Blob(["this ", "is ", "a ", "great ", "success!"],
                    {"type" : "text\/plain"}),
         ];
         let receivedMessageIndex = 0;
 
         let mm = SpecialPowers.getBrowserFrameMessageManager(iframe);
         mm.addMessageListener("test:ipcClonedMessage", function(message) {
-          is(message.json, messages[receivedMessageIndex++],
+          // We need to wrap to access message.json, and unwrap to do the
+          // identity check.
+          is(SpecialPowers.unwrap(SpecialPowers.wrap(message).json),
+             messages[receivedMessageIndex++],
              "Got correct round-tripped response");
           if (receivedMessageIndex == messages.length) {
             SimpleTest.finish();
           }
         });
         mm.loadFrameScript("data:,(" + childFrameScript.toString() + ")();",
                            false);
 
--- a/content/base/test/test_xhr_forbidden_headers.html
+++ b/content/base/test/test_xhr_forbidden_headers.html
@@ -25,16 +25,17 @@ var headers = [
   "aCcEsS-cOnTrOl-ReQuEsT-mEtHoD",
   "aCcEsS-cOnTrOl-ReQuEsT-hEaDeRs",
   "coNnEctIon",
   "coNtEnt-LEngth",
   "CoOKIe",
   "cOOkiE2",
   "cOntEnt-tRAnsFer-enCoDiNg",
   "DATE",
+  "dNT",
   "exPeCt",
   "hOSt",
   "keep-alive",
   "oRiGiN",
   "reFERer",
   "te",
   "trAiLer",
   "trANsfEr-eNcoDiNg",
--- a/content/base/test/unit/test_bug553888.js
+++ b/content/base/test/unit/test_bug553888.js
@@ -1,13 +1,13 @@
 /* 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/. */
 
-do_load_httpd_js();
+Components.utils.import("resource://testing-common/httpd.js");
 
 var server = null;
 
 const SERVER_PORT = 4444;
 const HTTP_BASE = "http://localhost:" + SERVER_PORT;
 const redirectPath = "/redirect";
 const headerCheckPath = "/headerCheck";
 const redirectURL = HTTP_BASE + redirectPath;
@@ -31,17 +31,17 @@ function headerCheckHandler(metadata, re
   } catch (x) {
   }
   response.setStatusLine(metadata.httpVersion, 200, "OK");
   response.setHeader("Content-Type", "text/plain");
   response.write("");
 }
 
 function run_test() {
-  var server = new nsHttpServer();
+  var server = new HttpServer();
   server.registerPathHandler(redirectPath, redirectHandler);
   server.registerPathHandler(headerCheckPath, headerCheckHandler);
   server.start(SERVER_PORT);
 
   do_test_pending();
   var request = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
                 .createInstance(Components.interfaces.nsIXMLHttpRequest);
   request.open("GET", redirectURL, true);
--- a/content/base/test/unit/test_bug558431.js
+++ b/content/base/test/unit/test_bug558431.js
@@ -1,29 +1,35 @@
-Components.utils.import('resource://gre/modules/CSPUtils.jsm');
-do_load_httpd_js();
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+Cu.import('resource://gre/modules/CSPUtils.jsm');
+Cu.import("resource://testing-common/httpd.js");
 
 var httpserv = null;
 
 const POLICY_FROM_URI = "allow 'self'; img-src *";
 const POLICY_PORT = 9000;
 const POLICY_URI = "http://localhost:" + POLICY_PORT + "/policy";
 const POLICY_URI_RELATIVE = "/policy";
 const DOCUMENT_URI = "http://localhost:" + POLICY_PORT + "/document";
 const CSP_DOC_BODY = "CSP doc content";
 const SD = CSPRep.SRC_DIRECTIVES;
 
 // this will get populated by run_tests()
 var TESTS = [];
 
 // helper to make URIs
 function mkuri(foo) {
-  return Components.classes["@mozilla.org/network/io-service;1"]
-                           .getService(Components.interfaces.nsIIOService)
-                           .newURI(foo, null, null);
+  return Cc["@mozilla.org/network/io-service;1"]
+           .getService(Ci.nsIIOService)
+           .newURI(foo, null, null);
 }
 
 // helper to use .equals on stuff
 function do_check_equivalent(foo, bar, stack) {
   if (!stack)
     stack = Components.stack.caller;
 
   var text = foo + ".equals(" + bar + ")";
@@ -82,17 +88,17 @@ listener.prototype = {
         do_test_finished();
         (TESTS.shift())();
       }
     }
   }
 };
 
 function run_test() {
-  httpserv = new nsHttpServer();
+  httpserv = new HttpServer();
   httpserv.registerPathHandler("/document", csp_doc_response);
   httpserv.registerPathHandler("/policy", csp_policy_response);
   httpserv.start(POLICY_PORT);
   TESTS = [ test_CSPRep_fromPolicyURI, test_CSPRep_fromRelativePolicyURI ];
 
   // when this triggers the "onStopRequest" callback, it'll
   // go to the next test.
   (TESTS.shift())();
--- a/content/base/test/unit/test_cspreports.js
+++ b/content/base/test/unit/test_cspreports.js
@@ -1,17 +1,22 @@
 /* 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/. */
 
-Components.utils.import('resource://gre/modules/CSPUtils.jsm');
-Components.utils.import('resource://gre/modules/NetUtil.jsm');
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cu = Components.utils;
+const Cr = Components.results;
+
+Cu.import('resource://gre/modules/CSPUtils.jsm');
+Cu.import('resource://gre/modules/NetUtil.jsm');
 
 // load the HTTP server
-do_load_httpd_js();
+Cu.import("resource://testing-common/httpd.js");
 
 const REPORT_SERVER_PORT = 9000;
 const REPORT_SERVER_URI = "http://localhost";
 const REPORT_SERVER_PATH = "/report";
 
 var httpServer = null;
 var testsToFinish = 0;
 
@@ -82,17 +87,17 @@ function makeTest(id, expectedJSON, call
   callback(csp);
 }
 
 function run_test() {
   var selfuri = NetUtil.newURI(REPORT_SERVER_URI +
                                ":" + REPORT_SERVER_PORT +
                                "/foo/self");
 
-  httpServer = new nsHttpServer();
+  httpServer = new HttpServer();
   httpServer.start(REPORT_SERVER_PORT);
 
   // test that inline script violations cause a report.
   makeTest(0, {"blocked-uri": "self"},
       function(csp) {
         if(!csp.allowsInlineScript) {
           // force the logging, since the getter doesn't.
           csp.logViolationDetails(Ci.nsIContentSecurityPolicy.VIOLATION_TYPE_INLINE_SCRIPT,
--- a/content/base/test/unit/test_csputils.js
+++ b/content/base/test/unit/test_csputils.js
@@ -1,30 +1,35 @@
 /* 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/. */
 
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cu = Components.utils;
+const Cr = Components.results;
+
 //load('CSPUtils.jsm');
-Components.utils.import('resource://gre/modules/CSPUtils.jsm');
-Components.utils.import('resource://gre/modules/NetUtil.jsm');
+Cu.import('resource://gre/modules/CSPUtils.jsm');
+Cu.import('resource://gre/modules/NetUtil.jsm');
 
 // load the HTTP server
-do_load_httpd_js();
+Cu.import("resource://testing-common/httpd.js");
 
-var httpServer = new nsHttpServer();
+var httpServer = new HttpServer();
 
 const POLICY_FROM_URI = "allow 'self'; img-src *";
 const POLICY_PORT = 9000;
 const POLICY_URI = "http://localhost:" + POLICY_PORT + "/policy";
 const POLICY_URI_RELATIVE = "/policy";
 
 //converts string to nsIURI
 function URI(uriString) {
-  var ioService = Components.classes["@mozilla.org/network/io-service;1"]
-                .getService(Components.interfaces.nsIIOService);
+  var ioService = Cc["@mozilla.org/network/io-service;1"]
+                    .getService(Ci.nsIIOService);
   return ioService.newURI(uriString, null, null);
 }
 
 
 // helper to assert that an array has the given value somewhere.
 function do_check_in_array(arr, val, stack) {
   if (!stack)
     stack = Components.stack.caller;
--- a/content/canvas/src/CustomQS_Canvas2D.h
+++ b/content/canvas/src/CustomQS_Canvas2D.h
@@ -1,14 +1,14 @@
 /* -*- Mode: C++; tab-width: 40; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* 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 "nsDOMError.h"
+#include "nsError.h"
 #include "nsIDOMCanvasRenderingContext2D.h"
 #include "mozilla/CheckedInt.h"
 #include "nsMathUtils.h"
 #include "CustomQS_Canvas.h"
 
 #include "jsapi.h"
 #include "jsfriendapi.h"
 
--- a/content/canvas/src/Makefile.in
+++ b/content/canvas/src/Makefile.in
@@ -47,16 +47,17 @@ CPPSRCS += \
 	WebGLContextUtils.cpp \
 	WebGLContextReporter.cpp \
 	WebGLContextValidate.cpp \
 	WebGLExtensionStandardDerivatives.cpp \
 	WebGLExtensionTextureFilterAnisotropic.cpp \
 	WebGLExtensionLoseContext.cpp \
 	WebGLTexelConversions.cpp \
 	WebGLExtensionCompressedTextureS3TC.cpp \
+	WebGLExtensionDepthTexture.cpp \
 	$(NULL)
 
 DEFINES += -DUSE_ANGLE
 USE_ANGLE=1
 
 else
 
 CPPSRCS += WebGLContextNotSupported.cpp
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -6,17 +6,17 @@
 #include "WebGLContext.h"
 #include "WebGLExtensions.h"
 
 #include "nsIConsoleService.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIClassInfoImpl.h"
 #include "nsContentUtils.h"
 #include "nsIXPConnect.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIGfxInfo.h"
 
 #include "nsIPropertyBag.h"
 #include "nsIVariant.h"
 
 #include "imgIEncoder.h"
 
 #include "gfxContext.h"
@@ -663,18 +663,18 @@ void WebGLContext::LoseOldestWebGLContex
     }
 
     // note that here by "context" we mean "non-lost context". See the check for
     // IsContextLost() below. Indeed, the point of this function is to maybe lose
     // some currently non-lost context.
 
     uint64_t oldestIndex = UINT64_MAX;
     uint64_t oldestIndexThisPrincipal = UINT64_MAX;
-    const WebGLContext *oldestContext = nsnull;
-    const WebGLContext *oldestContextThisPrincipal = nsnull;
+    const WebGLContext *oldestContext = nullptr;
+    const WebGLContext *oldestContextThisPrincipal = nullptr;
     size_t numContexts = 0;
     size_t numContextsThisPrincipal = 0;
 
     for(size_t i = 0; i < contexts.Length(); ++i) {
 
         // don't want to lose ourselves.
         if (contexts[i] == this)
             continue;
@@ -1002,16 +1002,28 @@ bool WebGLContext::IsExtensionSupported(
                 isSupported = true;
             } else if (gl->IsExtensionSupported(GLContext::EXT_texture_compression_dxt1) &&
                        gl->IsExtensionSupported(GLContext::ANGLE_texture_compression_dxt3) &&
                        gl->IsExtensionSupported(GLContext::ANGLE_texture_compression_dxt5))
             {
                 isSupported = true;
             }
             break;
+        case WEBGL_depth_texture:
+            if (gl->IsGLES2() && 
+                gl->IsExtensionSupported(GLContext::OES_packed_depth_stencil) &&
+                gl->IsExtensionSupported(GLContext::OES_depth_texture)) 
+            {
+                isSupported = true;
+            } else if (!gl->IsGLES2() &&
+                       gl->IsExtensionSupported(GLContext::EXT_packed_depth_stencil)) 
+            {
+                isSupported = true;
+            }
+            break;
         default:
             MOZ_ASSERT(false, "should not get there.");
     }
 
     return isSupported;
 }
 
 NS_IMETHODIMP
@@ -1067,16 +1079,22 @@ WebGLContext::GetExtension(const nsAStri
             ext = WEBGL_lose_context;
     }
     else if (aName.Equals(NS_LITERAL_STRING("MOZ_WEBGL_compressed_texture_s3tc"),
              nsCaseInsensitiveStringComparator()))
     {
         if (IsExtensionSupported(WEBGL_compressed_texture_s3tc))
             ext = WEBGL_compressed_texture_s3tc;
     }
+    else if (aName.Equals(NS_LITERAL_STRING("MOZ_WEBGL_depth_texture"),
+             nsCaseInsensitiveStringComparator()))
+    {
+        if (IsExtensionSupported(WEBGL_depth_texture))
+            ext = WEBGL_depth_texture;
+    }
 
     if (ext == WebGLExtensionID_unknown_extension) {
       return nullptr;
     }
 
     if (!mExtensions[ext]) {
         switch (ext) {
             case OES_standard_derivatives:
@@ -1086,16 +1104,19 @@ WebGLContext::GetExtension(const nsAStri
                 mExtensions[ext] = new WebGLExtensionTextureFilterAnisotropic(this);
                 break;
             case WEBGL_lose_context:
                 mExtensions[ext] = new WebGLExtensionLoseContext(this);
                 break;
             case WEBGL_compressed_texture_s3tc:
                 mExtensions[ext] = new WebGLExtensionCompressedTextureS3TC(this);
                 break;
+            case WEBGL_depth_texture:
+                mExtensions[ext] = new WebGLExtensionDepthTexture(this);
+                break;
             default:
                 // create a generic WebGLExtension object for any extensions that don't
                 // have any additional tokens or methods. We still need these to be separate
                 // objects in case the user might extend the corresponding JS objects with custom
                 // properties.
                 mExtensions[ext] = new WebGLExtension(this);
                 break;
         }
@@ -1662,16 +1683,18 @@ WebGLContext::GetSupportedExtensions(Nul
     if (IsExtensionSupported(EXT_texture_filter_anisotropic)) {
         arr.AppendElement(NS_LITERAL_STRING("EXT_texture_filter_anisotropic"));
         arr.AppendElement(NS_LITERAL_STRING("MOZ_EXT_texture_filter_anisotropic"));
     }
     if (IsExtensionSupported(WEBGL_lose_context))
         arr.AppendElement(NS_LITERAL_STRING("MOZ_WEBGL_lose_context"));
     if (IsExtensionSupported(WEBGL_compressed_texture_s3tc))
         arr.AppendElement(NS_LITERAL_STRING("MOZ_WEBGL_compressed_texture_s3tc"));
+    if (IsExtensionSupported(WEBGL_depth_texture))
+        arr.AppendElement(NS_LITERAL_STRING("MOZ_WEBGL_depth_texture"));
 }
 
 NS_IMETHODIMP
 WebGLContext::IsContextLost(WebGLboolean *retval)
 {
     *retval = mContextStatus != ContextStable;
     return NS_OK;
 }
--- a/content/canvas/src/WebGLContext.h
+++ b/content/canvas/src/WebGLContext.h
@@ -106,21 +106,24 @@ enum WebGLTexelFormat
     BadFormat,
     // dummy pseudo-format meaning "use the other format".
     // For example, if SrcFormat=Auto and DstFormat=RGB8, then the source
     // is implicitly treated as being RGB8 itself.
     Auto,
     // 1-channel formats
     R8,
     A8,
+    D16, // used for WEBGL_depth_texture extension
+    D32, // used for WEBGL_depth_texture extension
     R32F, // used for OES_texture_float extension
     A32F, // used for OES_texture_float extension
     // 2-channel formats
     RA8,
     RA32F,
+    D24S8, // used for WEBGL_depth_texture extension
     // 3-channel formats
     RGB8,
     BGRX8, // used for DOM elements. Source format only.
     RGB565,
     RGB32F, // used for OES_texture_float extension
     // 4-channel formats
     RGBA8,
     BGRA8, // used for DOM elements
@@ -456,16 +459,17 @@ class WebGLContext :
     public WebGLRectangleObject,
     public nsWrapperCache
 {
     friend class WebGLMemoryMultiReporterWrapper;
     friend class WebGLExtensionLoseContext;
     friend class WebGLExtensionCompressedTextureS3TC;
     friend class WebGLContextUserData;
     friend class WebGLMemoryPressureObserver;
+    friend class WebGLExtensionDepthTexture;
 
 public:
     WebGLContext();
     virtual ~WebGLContext();
 
     NS_DECL_CYCLE_COLLECTING_ISUPPORTS
 
     NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(WebGLContext,
@@ -1142,16 +1146,17 @@ protected:
 
     // extensions
     enum WebGLExtensionID {
         OES_texture_float,
         OES_standard_derivatives,
         EXT_texture_filter_anisotropic,
         WEBGL_lose_context,
         WEBGL_compressed_texture_s3tc,
+        WEBGL_depth_texture,
         WebGLExtensionID_number_of_extensions,
         WebGLExtensionID_unknown_extension
     };
     nsAutoTArray<nsRefPtr<WebGLExtension>, WebGLExtensionID_number_of_extensions> mExtensions;
 
     // returns true if the extension has been enabled by calling getExtension.
     bool IsExtensionEnabled(WebGLExtensionID ext) {
         return mExtensions[ext];
@@ -2692,18 +2697,38 @@ public:
     bool IsComplete() const {
         const WebGLRectangleObject *thisRect = RectangleObject();
 
         if (!thisRect ||
             !thisRect->Width() ||
             !thisRect->Height())
             return false;
 
-        if (mTexturePtr)
-            return mAttachmentPoint == LOCAL_GL_COLOR_ATTACHMENT0;
+        if (mTexturePtr) {
+            if (!mTexturePtr->HasImageInfoAt(0, 0))
+                return false;
+
+            WebGLenum format = mTexturePtr->ImageInfoAt(0).Format();
+            switch (mAttachmentPoint)
+            {
+                case LOCAL_GL_COLOR_ATTACHMENT0:
+                    return format == LOCAL_GL_ALPHA ||
+                           format == LOCAL_GL_LUMINANCE ||
+                           format == LOCAL_GL_LUMINANCE_ALPHA ||
+                           format == LOCAL_GL_RGB ||
+                           format == LOCAL_GL_RGBA;
+                case LOCAL_GL_DEPTH_ATTACHMENT:
+                    return format == LOCAL_GL_DEPTH_COMPONENT;
+                case LOCAL_GL_DEPTH_STENCIL_ATTACHMENT:
+                    return format == LOCAL_GL_DEPTH_STENCIL;
+
+                default:
+                    MOZ_NOT_REACHED("Invalid WebGL texture format?");
+            }
+        } 
 
         if (mRenderbufferPtr) {
             WebGLenum format = mRenderbufferPtr->InternalFormat();
             switch (mAttachmentPoint) {
                 case LOCAL_GL_COLOR_ATTACHMENT0:
                     return format == LOCAL_GL_RGB565 ||
                            format == LOCAL_GL_RGB5_A1 ||
                            format == LOCAL_GL_RGBA4;
@@ -2939,16 +2964,19 @@ public:
     NS_DECL_NSIWEBGLFRAMEBUFFER
 
     bool CheckAndInitializeRenderbuffers()
     {
         // enforce WebGL section 6.5 which is WebGL-specific, hence OpenGL itself would not
         // generate the INVALID_FRAMEBUFFER_OPERATION that we need here
         if (HasDepthStencilConflict())
             return false;
+        
+        if (HasIncompleteAttachment())
+            return false;
 
         if (!mColorAttachment.HasUninitializedRenderbuffer() &&
             !mDepthAttachment.HasUninitializedRenderbuffer() &&
             !mStencilAttachment.HasUninitializedRenderbuffer() &&
             !mDepthStencilAttachment.HasUninitializedRenderbuffer())
             return true;
 
         // ensure INVALID_FRAMEBUFFER_OPERATION in zero-size case
--- a/content/canvas/src/WebGLContextGL.cpp
+++ b/content/canvas/src/WebGLContextGL.cpp
@@ -8,17 +8,17 @@
 #include "nsString.h"
 #include "nsDebug.h"
 
 #include "gfxImageSurface.h"
 #include "gfxContext.h"
 #include "gfxPlatform.h"
 
 #include "nsContentUtils.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsLayoutUtils.h"
 
 #include "CanvasUtils.h"
 
 #include "jsfriendapi.h"
 
 #include "WebGLTexelConversions.h"
 #include "WebGLValidateStrings.h"
@@ -1032,16 +1032,20 @@ WebGLContext::CopyTexImage2D(WebGLenum t
                                     internalformat == LOCAL_GL_ALPHA ||
                                     internalformat == LOCAL_GL_LUMINANCE_ALPHA;
     bool fboFormatHasAlpha = mBoundFramebuffer ? mBoundFramebuffer->ColorAttachment().HasAlpha()
                                                  : bool(gl->ActualFormat().alpha > 0);
     if (texFormatRequiresAlpha && !fboFormatHasAlpha)
         return ErrorInvalidOperation("copyTexImage2D: texture format requires an alpha channel "
                                      "but the framebuffer doesn't have one");
 
+    if (internalformat == LOCAL_GL_DEPTH_COMPONENT ||
+        internalformat == LOCAL_GL_DEPTH_STENCIL)
+        return ErrorInvalidOperation("copyTexImage2D: a base internal format of DEPTH_COMPONENT or DEPTH_STENCIL isn't supported");
+
     if (mBoundFramebuffer)
         if (!mBoundFramebuffer->CheckAndInitializeRenderbuffers())
             return ErrorInvalidFramebufferOperation("copyTexImage2D: incomplete framebuffer");
 
     WebGLTexture *tex = activeBoundTextureForTarget(target);
     if (!tex)
         return ErrorInvalidOperation("copyTexImage2D: no texture bound to this target");
 
@@ -1153,16 +1157,20 @@ WebGLContext::CopyTexSubImage2D(WebGLenu
                                   format == LOCAL_GL_LUMINANCE_ALPHA;
     bool fboFormatHasAlpha = mBoundFramebuffer ? mBoundFramebuffer->ColorAttachment().HasAlpha()
                                                  : bool(gl->ActualFormat().alpha > 0);
 
     if (texFormatRequiresAlpha && !fboFormatHasAlpha)
         return ErrorInvalidOperation("copyTexSubImage2D: texture format requires an alpha channel "
                                      "but the framebuffer doesn't have one");
 
+    if (format == LOCAL_GL_DEPTH_COMPONENT ||
+        format == LOCAL_GL_DEPTH_STENCIL)
+        return ErrorInvalidOperation("copyTexSubImage2D: a base internal format of DEPTH_COMPONENT or DEPTH_STENCIL isn't supported");
+
     if (mBoundFramebuffer)
         if (!mBoundFramebuffer->CheckAndInitializeRenderbuffers())
             return ErrorInvalidFramebufferOperation("copyTexSubImage2D: incomplete framebuffer");
 
     return CopyTexSubImage2D_base(target, level, format, xoffset, yoffset, x, y, width, height, true);
 }
 
 
@@ -2125,16 +2133,22 @@ WebGLContext::GenerateMipmap(WebGLenum t
 
     if (!tex->IsFirstImagePowerOfTwo())
         return ErrorInvalidOperation("generateMipmap: Level zero of texture does not have power-of-two width and height.");
 
     GLenum format = tex->ImageInfoAt(0, 0).Format();
     if (IsTextureFormatCompressed(format))
         return ErrorInvalidOperation("generateMipmap: Texture data at level zero is compressed.");
 
+    if (IsExtensionEnabled(WEBGL_depth_texture) && 
+        (format == LOCAL_GL_DEPTH_COMPONENT || format == LOCAL_GL_DEPTH_STENCIL))
+        return ErrorInvalidOperation("generateMipmap: "
+                                     "A texture that has a base internal format of "
+                                     "DEPTH_COMPONENT or DEPTH_STENCIL isn't supported");
+
     if (!tex->AreAllLevel0ImageInfosEqual())
         return ErrorInvalidOperation("generateMipmap: The six faces of this cube map have different dimensions, format, or type.");
 
     tex->SetGeneratedMipmap();
 
     MakeContextCurrent();
 
     if (gl->WorkAroundDriverBugs()) {
@@ -5611,16 +5625,18 @@ WebGLContext::TexImage2D_base(WebGLenum 
     }
 
     switch (format) {
         case LOCAL_GL_RGB:
         case LOCAL_GL_RGBA:
         case LOCAL_GL_ALPHA:
         case LOCAL_GL_LUMINANCE:
         case LOCAL_GL_LUMINANCE_ALPHA:
+        case LOCAL_GL_DEPTH_COMPONENT:
+        case LOCAL_GL_DEPTH_STENCIL:
             break;
         default:
             return ErrorInvalidEnumInfo("texImage2D: internal format", internalformat);
     }
 
     if (format != internalformat)
         return ErrorInvalidOperation("texImage2D: format does not match internalformat");
 
@@ -5632,16 +5648,30 @@ WebGLContext::TexImage2D_base(WebGLenum 
         if (!(is_pot_assuming_nonnegative(width) &&
               is_pot_assuming_nonnegative(height)))
             return ErrorInvalidValue("texImage2D: with level > 0, width and height must be powers of two");
     }
 
     if (border != 0)
         return ErrorInvalidValue("texImage2D: border must be 0");
 
+
+    if (format == LOCAL_GL_DEPTH_COMPONENT || format == LOCAL_GL_DEPTH_STENCIL) {
+        if (IsExtensionEnabled(WEBGL_depth_texture)) {
+            if (target != LOCAL_GL_TEXTURE_2D || data != NULL || level != 0)
+                return ErrorInvalidOperation("texImage2D: "
+                                             "with format of DEPTH_COMPONENT or DEPTH_STENCIL "
+                                             "target must be TEXTURE_2D, "
+                                             "data must be NULL, "
+                                             "level must be zero");
+        }
+        else
+            return ErrorInvalidEnumInfo("texImage2D: internal format", internalformat);
+    }
+
     uint32_t dstTexelSize = 0;
     if (!ValidateTexFormatAndType(format, type, jsArrayType, &dstTexelSize, "texImage2D"))
         return;
 
     WebGLTexelFormat dstFormat = GetWebGLTexelFormat(format, type);
     WebGLTexelFormat actualSrcFormat = srcFormat == WebGLTexelConversions::Auto ? dstFormat : srcFormat;
 
     uint32_t srcTexelSize = WebGLTexelConversions::TexelBytesForFormat(actualSrcFormat);
@@ -5844,16 +5874,21 @@ WebGLContext::TexSubImage2D_base(WebGLen
     }
 
     if (level >= 1) {
         if (!(is_pot_assuming_nonnegative(width) &&
               is_pot_assuming_nonnegative(height)))
             return ErrorInvalidValue("texSubImage2D: with level > 0, width and height must be powers of two");
     }
 
+    if (IsExtensionEnabled(WEBGL_depth_texture) && 
+        (format == LOCAL_GL_DEPTH_COMPONENT || format == LOCAL_GL_DEPTH_STENCIL)) {
+        return ErrorInvalidOperation("texSubImage2D: format");
+    }
+
     uint32_t dstTexelSize = 0;
     if (!ValidateTexFormatAndType(format, type, jsArrayType, &dstTexelSize, "texSubImage2D"))
         return;
 
     WebGLTexelFormat dstFormat = GetWebGLTexelFormat(format, type);
     WebGLTexelFormat actualSrcFormat = srcFormat == WebGLTexelConversions::Auto ? dstFormat : srcFormat;
 
     uint32_t srcTexelSize = WebGLTexelConversions::TexelBytesForFormat(actualSrcFormat);
@@ -6112,16 +6147,40 @@ BaseTypeAndSizeFromUniformType(WebGLenum
     }
 
     return true;
 }
 
 
 WebGLTexelFormat mozilla::GetWebGLTexelFormat(GLenum format, GLenum type)
 {
+    //
+    // WEBGL_depth_texture
+    if (format == LOCAL_GL_DEPTH_COMPONENT) {
+        switch (type) {
+            case LOCAL_GL_UNSIGNED_SHORT:
+                return WebGLTexelConversions::D16;
+            case LOCAL_GL_UNSIGNED_INT:
+                return WebGLTexelConversions::D32;
+            default:
+                MOZ_NOT_REACHED("Invalid WebGL texture format/type?");
+                return WebGLTexelConversions::BadFormat;
+        }
+    } else if (format == LOCAL_GL_DEPTH_STENCIL) {
+        switch (type) {
+            case LOCAL_GL_UNSIGNED_INT_24_8_EXT:
+                return WebGLTexelConversions::D24S8;
+            default:
+                MOZ_NOT_REACHED("Invalid WebGL texture format/type?");
+                NS_ABORT_IF_FALSE(false, "Coding mistake?! Should never reach this point.");
+                return WebGLTexelConversions::BadFormat;
+        }
+    }
+
+
     if (type == LOCAL_GL_UNSIGNED_BYTE) {
         switch (format) {
             case LOCAL_GL_RGBA:
                 return WebGLTexelConversions::RGBA8;
             case LOCAL_GL_RGB:
                 return WebGLTexelConversions::RGB8;
             case LOCAL_GL_ALPHA:
                 return WebGLTexelConversions::A8;
@@ -6169,16 +6228,28 @@ WebGLenum
 InternalFormatForFormatAndType(WebGLenum format, WebGLenum type, bool isGLES2)
 {
     // ES2 requires that format == internalformat; floating-point is
     // indicated purely by the type that's loaded.  For desktop GL, we
     // have to specify a floating point internal format.
     if (isGLES2)
         return format;
 
+    if (format == LOCAL_GL_DEPTH_COMPONENT) {
+        if (type == LOCAL_GL_UNSIGNED_SHORT)
+            return LOCAL_GL_DEPTH_COMPONENT16;
+        else if (type == LOCAL_GL_UNSIGNED_INT)
+            return LOCAL_GL_DEPTH_COMPONENT32;
+    } 
+    
+    if (format == LOCAL_GL_DEPTH_STENCIL) {
+        if (type == LOCAL_GL_UNSIGNED_INT_24_8_EXT)
+            return LOCAL_GL_DEPTH24_STENCIL8;
+    }
+
     switch (type) {
     case LOCAL_GL_UNSIGNED_BYTE:
     case LOCAL_GL_UNSIGNED_SHORT_4_4_4_4:
     case LOCAL_GL_UNSIGNED_SHORT_5_5_5_1:
     case LOCAL_GL_UNSIGNED_SHORT_5_6_5:
         return format;
 
     case LOCAL_GL_FLOAT:
--- a/content/canvas/src/WebGLContextNotSupported.cpp
+++ b/content/canvas/src/WebGLContextNotSupported.cpp
@@ -20,8 +20,9 @@ DOMCI_DATA(WebGLRenderbuffer, void)
 DOMCI_DATA(WebGLUniformLocation, void)
 DOMCI_DATA(WebGLShaderPrecisionFormat, void)
 DOMCI_DATA(WebGLActiveInfo, void)
 DOMCI_DATA(WebGLExtension, void)
 DOMCI_DATA(WebGLExtensionStandardDerivatives, void)
 DOMCI_DATA(WebGLExtensionTextureFilterAnisotropic, void)
 DOMCI_DATA(WebGLExtensionLoseContext, void)
 DOMCI_DATA(WebGLExtensionCompressedTextureS3TC, void)
+DOMCI_DATA(WebGLExtensionDepthTexture, void)
--- a/content/canvas/src/WebGLContextUtils.cpp
+++ b/content/canvas/src/WebGLContextUtils.cpp
@@ -185,16 +185,18 @@ bool
 WebGLContext::IsTextureFormatCompressed(GLenum format)
 {
     switch(format) {
         case LOCAL_GL_RGB:
         case LOCAL_GL_RGBA:
         case LOCAL_GL_ALPHA:
         case LOCAL_GL_LUMINANCE:
         case LOCAL_GL_LUMINANCE_ALPHA:
+        case LOCAL_GL_DEPTH_COMPONENT:
+        case LOCAL_GL_DEPTH_STENCIL:
             return false;
 
         case LOCAL_GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
         case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
         case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
         case LOCAL_GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
             return true;
     }
--- a/content/canvas/src/WebGLContextValidate.cpp
+++ b/content/canvas/src/WebGLContextValidate.cpp
@@ -451,16 +451,26 @@ bool WebGLContext::ValidateLevelWidthHei
 
 uint32_t WebGLContext::GetBitsPerTexel(WebGLenum format, WebGLenum type)
 {
     // If there is no defined format or type, we're not taking up any memory
     if (!format || !type) {
         return 0;
     }
 
+    if (format == LOCAL_GL_DEPTH_COMPONENT) {
+        if (type == LOCAL_GL_UNSIGNED_SHORT)
+            return 2;
+        else if (type == LOCAL_GL_UNSIGNED_INT)
+            return 4;
+    } else if (format == LOCAL_GL_DEPTH_STENCIL) {
+        if (type == LOCAL_GL_UNSIGNED_INT_24_8_EXT)
+            return 4;
+    }
+
     if (type == LOCAL_GL_UNSIGNED_BYTE || type == LOCAL_GL_FLOAT) {
         int multiplier = type == LOCAL_GL_FLOAT ? 32 : 8;
         switch (format) {
             case LOCAL_GL_ALPHA:
             case LOCAL_GL_LUMINANCE:
                 return 1 * multiplier;
             case LOCAL_GL_LUMINANCE_ALPHA:
                 return 2 * multiplier;
@@ -486,16 +496,58 @@ uint32_t WebGLContext::GetBitsPerTexel(W
 
     NS_ABORT();
     return 0;
 }
 
 bool WebGLContext::ValidateTexFormatAndType(WebGLenum format, WebGLenum type, int jsArrayType,
                                               uint32_t *texelSize, const char *info)
 {
+    if (IsExtensionEnabled(WEBGL_depth_texture)) {
+        if (format == LOCAL_GL_DEPTH_COMPONENT) {
+            if (jsArrayType != -1) {
+                if ((type == LOCAL_GL_UNSIGNED_SHORT && jsArrayType != js::ArrayBufferView::TYPE_UINT16) ||
+                    (type == LOCAL_GL_UNSIGNED_INT && jsArrayType != js::ArrayBufferView::TYPE_UINT32)) {
+                    ErrorInvalidOperation("%s: invalid typed array type for given texture data type", info);
+                    return false;
+                }
+            }
+
+            switch(type) {
+                case LOCAL_GL_UNSIGNED_SHORT:
+                    *texelSize = 2;
+                    break;
+                case LOCAL_GL_UNSIGNED_INT:
+                    *texelSize = 4;
+                    break;
+                default:
+                    ErrorInvalidOperation("%s: invalid type 0x%x", info, type);
+                    return false;
+            }
+
+            return true;
+
+        } else if (format == LOCAL_GL_DEPTH_STENCIL) {
+            if (type != LOCAL_GL_UNSIGNED_INT_24_8_EXT) {
+                ErrorInvalidOperation("%s: invalid format 0x%x", info, format);
+                return false;
+            }
+            if (jsArrayType != -1) {
+                if (jsArrayType != js::ArrayBufferView::TYPE_UINT32) {
+                    ErrorInvalidOperation("%s: invalid typed array type for given texture data type", info);
+                    return false;
+                }
+            }
+
+            *texelSize = 4;
+            return true;
+        }
+    }
+
+
     if (type == LOCAL_GL_UNSIGNED_BYTE ||
         (IsExtensionEnabled(OES_texture_float) && type == LOCAL_GL_FLOAT))
     {
         if (jsArrayType != -1) {
             if ((type == LOCAL_GL_UNSIGNED_BYTE && jsArrayType != js::ArrayBufferView::TYPE_UINT8) ||
                 (type == LOCAL_GL_FLOAT && jsArrayType != js::ArrayBufferView::TYPE_FLOAT32))
             {
                 ErrorInvalidOperation("%s: invalid typed array type for given texture data type", info);
new file mode 100644
--- /dev/null
+++ b/content/canvas/src/WebGLExtensionDepthTexture.cpp
@@ -0,0 +1,32 @@
+/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* 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 "WebGLContext.h"
+#include "WebGLExtensions.h"
+
+using namespace mozilla;
+
+WebGLExtensionDepthTexture::WebGLExtensionDepthTexture(WebGLContext* context) :
+    WebGLExtension(context)
+{
+
+}
+
+WebGLExtensionDepthTexture::~WebGLExtensionDepthTexture()
+{
+
+}
+
+NS_IMPL_ADDREF_INHERITED(WebGLExtensionDepthTexture, WebGLExtension)
+NS_IMPL_RELEASE_INHERITED(WebGLExtensionDepthTexture, WebGLExtension)
+
+DOMCI_DATA(WebGLExtensionDepthTexture, WebGLExtensionDepthTexture)
+
+NS_INTERFACE_MAP_BEGIN(WebGLExtensionDepthTexture)
+  NS_INTERFACE_MAP_ENTRY(nsIWebGLExtensionDepthTexture)
+  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, WebGLExtension)
+  NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(WebGLExtensionDepthTexture)
+NS_INTERFACE_MAP_END_INHERITING(WebGLExtension)
+
--- a/content/canvas/src/WebGLExtensions.h
+++ b/content/canvas/src/WebGLExtensions.h
@@ -51,11 +51,23 @@ class WebGLExtensionCompressedTextureS3T
 public:
     WebGLExtensionCompressedTextureS3TC(WebGLContext* context);
     virtual ~WebGLExtensionCompressedTextureS3TC();
 
     NS_DECL_ISUPPORTS_INHERITED
     NS_DECL_NSIWEBGLEXTENSION
 };
 
+class WebGLExtensionDepthTexture :
+    public nsIWebGLExtensionDepthTexture,
+    public WebGLExtension
+{
+public:
+    WebGLExtensionDepthTexture(WebGLContext* context);
+    virtual ~WebGLExtensionDepthTexture();
+
+    NS_DECL_ISUPPORTS_INHERITED
+    NS_DECL_NSIWEBGLEXTENSION
+};
+
 }
 
 #endif // WEBGLEXTENSIONS_H_
--- a/content/canvas/src/WebGLTexelConversions.h
+++ b/content/canvas/src/WebGLTexelConversions.h
@@ -104,24 +104,27 @@ inline size_t TexelBytesForFormat(int fo
     switch (format) {
         case WebGLTexelConversions::R8:
         case WebGLTexelConversions::A8:
             return 1;
         case WebGLTexelConversions::RA8:
         case WebGLTexelConversions::RGBA5551:
         case WebGLTexelConversions::RGBA4444:
         case WebGLTexelConversions::RGB565:
+        case WebGLTexelConversions::D16:
             return 2;
         case WebGLTexelConversions::RGB8:
             return 3;
         case WebGLTexelConversions::RGBA8:
         case WebGLTexelConversions::BGRA8:
         case WebGLTexelConversions::BGRX8:
         case WebGLTexelConversions::R32F:
         case WebGLTexelConversions::A32F:
+        case WebGLTexelConversions::D32:
+        case WebGLTexelConversions::D24S8:
             return 4;
         case WebGLTexelConversions::RA32F:
             return 8;
         case WebGLTexelConversions::RGB32F:
             return 12;
         case WebGLTexelConversions::RGBA32F:
             return 16;
         default:
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -21,17 +21,17 @@
 #include "nsICanvasRenderingContextInternal.h"
 #include "nsHTMLCanvasElement.h"
 #include "nsSVGEffects.h"
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsIVariant.h"
 
 #include "nsIInterfaceRequestorUtils.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIScriptError.h"
 
 #include "nsCSSParser.h"
 #include "mozilla/css/StyleRule.h"
 #include "mozilla/css/Declaration.h"
 #include "nsComputedDOMStyle.h"
 #include "nsStyleSet.h"
 
--- a/content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2DAzure.cpp
@@ -20,17 +20,17 @@
 #include "nsHTMLCanvasElement.h"
 #include "nsSVGEffects.h"
 #include "nsPresContext.h"
 #include "nsIPresShell.h"
 #include "nsIVariant.h"
 
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIFrame.h"
-#include "nsDOMError.h"
+#include "nsError.h"
 #include "nsIScriptError.h"
 
 #include "nsCSSParser.h"
 #include "mozilla/css/StyleRule.h"
 #include "mozilla/css/Declaration.h"
 #include "nsComputedDOMStyle.h"
 #include "nsStyleSet.h"
 
--- a/content/canvas/test/webgl/conformance/extensions/00_test_list.txt
+++ b/content/canvas/test/webgl/conformance/extensions/00_test_list.txt
@@ -1,8 +1,9 @@
 oes-standard-derivatives.html
 ext-texture-filter-anisotropic.html
 oes-texture-float.html
 oes-vertex-array-object.html
 webgl-debug-renderer-info.html
 webgl-debug-shaders.html
 --min-version 1.0.2 webgl-compressed-texture-s3tc.html
+--min-version 1.0.2 webgl-depth-texture.html
 
new file mode 100644
--- /dev/null
+++ b/content/canvas/test/webgl/conformance/extensions/webgl-depth-texture.html
@@ -0,0 +1,343 @@
+<!--
+
+/*
+** Copyright (c) 2012 The Khronos Group Inc.
+**
+** Permission is hereby granted, free of charge, to any person obtaining a
+** copy of this software and/or associated documentation files (the
+** "Materials"), to deal in the Materials without restriction, including
+** without limitation the rights to use, copy, modify, merge, publish,
+** distribute, sublicense, and/or sell copies of the Materials, and to
+** permit persons to whom the Materials are furnished to do so, subject to
+** the following conditions:
+**
+** The above copyright notice and this permission notice shall be included
+** in all copies or substantial portions of the Materials.
+**
+** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
+*/
+
+-->
+<!DOCTYPE html>
+<html>
+<head>
+<meta charset="utf-8">
+<link rel="stylesheet" href="../../resources/js-test-style.css"/>
+<script src="../../resources/js-test-pre.js"></script>
+<script src="../resources/webgl-test.js"></script>
+<script src="../resources/webgl-test-utils.js"></script>
+<title>WebGL WEBGL_depth_texture Conformance Tests</title>
+</head>
+<body>
+<script id="vshader" type="x-shader/x-vertex">
+attribute vec4 a_position;
+void main()
+{
+    gl_Position = a_position;
+}
+</script>
+
+<script id="fshader" type="x-shader/x-fragment">
+precision mediump float;
+uniform sampler2D u_texture;
+uniform vec2 u_resolution;
+void main()
+{
+    vec2 texcoord = gl_FragCoord.xy / u_resolution;
+    gl_FragColor = texture2D(u_texture, texcoord);
+}
+</script>
+<div id="description"></div>
+<div id="console"></div>
+<canvas id="canvas" width="8" height="8" style="width: 8px; height: 8px;"></canvas>
+<script>
+if (window.initNonKhronosFramework) {
+    window.initNonKhronosFramework(false);
+}
+description("This test verifies the functionality of the WEBGL_depth_texture extension, if it is available.");
+
+debug("");
+
+var wtu = WebGLTestUtils;
+var canvas = document.getElementById("canvas");
+var gl = wtu.create3DContext(canvas, {antialias: false});
+var program = wtu.setupTexturedQuad(gl);
+var ext = null;
+var vao = null;
+var tex;
+var name;
+var supportedFormats;
+
+if (!gl) {
+    testFailed("WebGL context does not exist");
+} else {
+    testPassed("WebGL context exists");
+
+    // Run tests with extension disabled
+    runTestDisabled();
+
+    // Query the extension and store globally so shouldBe can access it
+    ext = wtu.getExtensionWithKnownPrefixes(gl, "WEBGL_depth_texture");
+    if (!ext) {
+        testPassed("No WEBGL_depth_texture support -- this is legal");
+        runSupportedTest(false);
+    } else {
+        testPassed("Successfully enabled WEBGL_depth_texture extension");
+
+        runSupportedTest(true);
+        runTestExtension();
+    }
+}
+
+function runSupportedTest(extensionEnabled) {
+    var name = wtu.getSupportedExtensionWithKnownPrefixes(gl, "WEBGL_depth_texture");
+    if (name !== undefined) {
+        if (extensionEnabled) {
+            testPassed("WEBGL_depth_texture listed as supported and getExtension succeeded");
+        } else {
+            testFailed("WEBGL_depth_texture listed as supported but getExtension failed");
+        }
+    } else {
+        if (extensionEnabled) {
+            testFailed("WEBGL_depth_texture not listed as supported but getExtension succeeded");
+        } else {
+            testPassed("WEBGL_depth_texture not listed as supported and getExtension failed -- this is legal");
+        }
+    }
+}
+
+
+function runTestDisabled() {
+    debug("Testing binding enum with extension disabled");
+
+    var tex = gl.createTexture();
+    gl.bindTexture(gl.TEXTURE_2D, tex);
+    shouldGenerateGLError(gl, gl.INVALID_ENUM, 'gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, 1, 1, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null)');
+    shouldGenerateGLError(gl, gl.INVALID_ENUM, 'gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, 1, 1, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null)');
+}
+
+
+function dumpIt(gl, res, msg) {
+  return;  // comment out to debug
+  debug(msg);
+  var actualPixels = new Uint8Array(res * res * 4);
+  gl.readPixels(0, 0, res, res, gl.RGBA, gl.UNSIGNED_BYTE, actualPixels);
+
+  for (var yy = 0; yy < res; ++yy) {
+    var strs = [];
+    for (var xx = 0; xx < res; ++xx) {
+      var actual = (yy * res + xx) * 4;
+      strs.push("(" + actualPixels[actual] + "," + actualPixels[actual+1] + "," + actualPixels[actual + 2] + "," + actualPixels[actual + 3] + ")");
+    }
+    debug(strs.join(" "));
+  }
+}
+function runTestExtension() {
+    debug("Testing WEBGL_depth_texture");
+
+    var res = 8;
+
+    // make canvas for testing.
+    canvas2 = document.createElement("canvas");
+    canvas2.width = res;
+    canvas2.height = res;
+    var ctx = canvas2.getContext("2d");
+    ctx.fillStyle = "blue";
+    ctx.fillRect(0, 0, canvas2.width, canvas2.height);
+
+    var program = wtu.setupProgram(gl, ['vshader', 'fshader'], ['a_position']);
+    gl.useProgram(program);
+    gl.uniform2f(gl.getUniformLocation(program, "u_resolution"), res, res);
+
+    var buffer = gl.createBuffer();
+    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
+    gl.bufferData(
+        gl.ARRAY_BUFFER,
+        new Float32Array(
+            [   1,  1,  1,
+               -1,  1,  0,
+               -1, -1, -1,
+                1,  1,  1,
+               -1, -1, -1,
+                1, -1,  0,
+            ]),
+        gl.STATIC_DRAW);
+    gl.enableVertexAttribArray(0);
+    gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0);
+
+    var types = [
+        {obj: 'gl',  attachment: 'DEPTH_ATTACHMENT',         format: 'DEPTH_COMPONENT', type: 'UNSIGNED_SHORT',          data: 'new Uint16Array(1)' },
+        {obj: 'gl',  attachment: 'DEPTH_ATTACHMENT',         format: 'DEPTH_COMPONENT', type: 'UNSIGNED_INT',            data: 'new Uint32Array(1)' },
+        {obj: 'ext', attachment: 'DEPTH_STENCIL_ATTACHMENT', format: 'DEPTH_STENCIL',   type: 'UNSIGNED_INT_24_8_WEBGL', data: 'new Uint32Array(1)' }
+    ];
+
+    for (var ii = 0; ii < types.length; ++ii) {
+        var typeInfo = types[ii];
+        var type = typeInfo.type;
+        var typeStr = typeInfo.obj + '.' + type;
+
+        debug("");
+        debug("testing: " + type);
+
+        // check that cubemaps are not allowed.
+        var cubeTex = gl.createTexture();
+        gl.bindTexture(gl.TEXTURE_CUBE_MAP, cubeTex);
+        var targets = [
+          'TEXTURE_CUBE_MAP_POSITIVE_X',
+          'TEXTURE_CUBE_MAP_NEGATIVE_X',
+          'TEXTURE_CUBE_MAP_POSITIVE_Y',
+          'TEXTURE_CUBE_MAP_NEGATIVE_Y',
+          'TEXTURE_CUBE_MAP_POSITIVE_Z',
+          'TEXTURE_CUBE_MAP_NEGATIVE_Z'
+        ];
+        for (var tt = 0; tt < targets.length; ++tt) {
+            shouldGenerateGLError(gl, gl.INVALID_OPERATION, 'gl.texImage2D(gl.' + targets[ii] + ', 1, gl.' + typeInfo.format + ', 1, 1, 0, gl.' + typeInfo.format + ', ' + typeStr + ', null)');
+        }
+
+        // check 2d textures.
+        tex = gl.createTexture();
+        gl.bindTexture(gl.TEXTURE_2D, tex);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+
+        // test level > 0
+        shouldGenerateGLError(gl, gl.INVALID_OPERATION, 'gl.texImage2D(gl.TEXTURE_2D, 1, gl.' + typeInfo.format + ', 1, 1, 0, gl.' + typeInfo.format + ', ' + typeStr + ', null)');
+
+        // test with data
+        shouldGenerateGLError(gl, gl.INVALID_OPERATION, 'gl.texImage2D(gl.TEXTURE_2D, 0, gl.' + typeInfo.format + ', 1, 1, 0, gl.' + typeInfo.format + ', ' + typeStr + ', ' + typeInfo.data + ')');
+
+        // test with canvas
+        shouldGenerateGLError(gl, [gl.INVALID_VALUE, gl.INVALID_ENUM, gl.INVALID_OPERATION], 'gl.texImage2D(gl.TEXTURE_2D, 0, gl.' + typeInfo.format + ', gl.' + typeInfo.format + ', ' + typeStr  + ', canvas2)');
+
+        // test copyTexImage2D
+        shouldGenerateGLError(gl, [gl.INVALID_ENUM, gl.INVALID_OPERATION], 'gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.' + typeInfo.format + ', 0, 0, 1, 1, 0)');
+
+        // test real thing
+        shouldGenerateGLError(gl, gl.NO_ERROR, 'gl.texImage2D(gl.TEXTURE_2D, 0, gl.' + typeInfo.format + ', ' + res + ', ' + res + ', 0, gl.' + typeInfo.format + ', ' + typeStr + ', null)');
+
+        // test texSubImage2D
+        shouldGenerateGLError(gl, gl.INVALID_OPERATION, 'gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 1, 1, gl.' + typeInfo.format + ', ' + typeStr  + ', ' + typeInfo.data + ')');
+
+        // test copyTexSubImage2D
+        shouldGenerateGLError(gl, gl.INVALID_OPERATION, 'gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, 1, 1)');
+
+        // test generateMipmap
+        shouldGenerateGLError(gl, gl.INVALID_OPERATION, 'gl.generateMipmap(gl.TEXTURE_2D)');
+
+        var fbo = gl.createFramebuffer();
+        gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
+        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl[typeInfo.attachment], gl.TEXTURE_2D, tex, 0);
+        // TODO: remove this check if the spec is updated to require these combinations to work.
+        if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE)
+        {
+            // try adding a color buffer.
+            var colorTex = gl.createTexture();
+            gl.bindTexture(gl.TEXTURE_2D, colorTex);
+            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, res, res, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorTex, 0);
+            shouldBe('gl.checkFramebufferStatus(gl.FRAMEBUFFER)', 'gl.FRAMEBUFFER_COMPLETE');
+        }
+
+        // use the default texture to render with while we return to the depth texture.
+        gl.bindTexture(gl.TEXTURE_2D, null);
+
+        // render the z-quad
+        gl.enable(gl.DEPTH_TEST);
+        gl.clearColor(1, 0, 0, 1);
+        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+        gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+        dumpIt(gl, res, "--first--");
+
+        // render the depth texture.
+        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+        gl.bindTexture(gl.TEXTURE_2D, tex);
+        gl.clearColor(0, 0, 1, 1);
+        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+        gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+        var actualPixels = new Uint8Array(res * res * 4);
+        gl.readPixels(0, 0, res, res, gl.RGBA, gl.UNSIGNED_BYTE, actualPixels);
+
+        dumpIt(gl, res, "--depth--");
+
+        // Check that each pixel's RGB are the same and that it's value is less
+        // than the previous pixel in either direction. Basically verify we have a
+        // gradient.
+        var success = true;
+        for (var yy = 0; yy < res; ++yy) {
+          for (var xx = 0; xx < res; ++xx) {
+            var actual = (yy * res + xx) * 4;
+            var left = actual - 4;
+            var down = actual - res * 4;
+
+            if (actualPixels[actual + 0] != actualPixels[actual + 1]) {
+                testFailed('R != G');
+                success = false;
+            }
+            if (actualPixels[actual + 0] != actualPixels[actual + 2]) {
+                testFailed('R != B');
+                success = false;
+            }
+            // ALPHA is implementation dependent
+            if (actualPixels[actual + 3] != 0xFF && actualPixels[actual + 3] != actualPixels[actual + 0]) {
+                testFailed('A != 255 && A != R');
+                success = false;
+            }
+
+            if (xx > 0) {
+              if (actualPixels[actual] <= actualPixels[left]) {
+                  testFailed("actual(" + actualPixels[actual] + ") < left(" + actualPixels[left] + ")");
+                  success = false;
+              }
+            }
+            if (yy > 0) {
+                if (actualPixels[actual] <= actualPixels[down]) {
+                    testFailed("actual(" + actualPixels[actual] + ") < down(" + actualPixels[down] + ")");
+                    success = false;
+                }
+            }
+          }
+        }
+
+        // Check that bottom left corner is vastly different thatn top right.
+        if (actualPixels[(res * res - 1) * 4] - actualPixels[0] < 0xC0) {
+            testFailed("corners are not different enough");
+            success = false;
+        }
+
+        if (success) {
+            testPassed("depth texture rendered correctly.");
+        }
+
+        // check limitations
+        gl.bindFramebuffer(gl.FRAMEBUFFER, fbo);
+        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl[typeInfo.attachment], gl.TEXTURE_2D, null, 0);
+        var badAttachment = typeInfo.attachment == 'DEPTH_ATTACHMENT' ? 'DEPTH_STENCIL_ATTACHMENT' : 'DEPTH_ATTACHMENT';
+        shouldGenerateGLError(gl, gl.NO_ERROR, 'gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.' + badAttachment + ', gl.TEXTURE_2D, tex, 0)');
+        shouldNotBe('gl.checkFramebufferStatus(gl.FRAMEBUFFER)', 'gl.FRAMEBUFFER_COMPLETE');
+        shouldGenerateGLError(gl, gl.INVALID_FRAMEBUFFER_OPERATION, 'gl.clear(gl.DEPTH_BUFFER_BIT)');
+        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+        shouldBe('gl.getError()', 'gl.NO_ERROR');
+    }
+}
+
+debug("");
+successfullyParsed = true;
+</script>
+<script src="../../resources/js-test-post.js"></script>
+</body>
+</html>
+
--- a/content/events/src/nsDOMDataTransfer.cpp