merge m-c to devtools
authorRob Campbell <rcampbell@mozilla.com>
Mon, 30 May 2011 11:46:04 -0400
changeset 70888 117044f42385a458857c17d8ba923cce9ad2ef81
parent 70887 6d63840e3a49f2be371acec15ec6e4a44dceab13 (current diff)
parent 70338 15bfb9729ff3b1408a41d5af81becf4f3a22561e (diff)
child 70889 b9ceaebb878f60d378224cc4abdecf2f81f55da6
push id3
push usergsharp@mozilla.com
push dateMon, 13 Jun 2011 17:29:15 +0000
treeherderfx-team@479e2681c25f [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone7.0a1
merge m-c to devtools
accessible/tests/mochitest/test_elm_media.html
accessible/tests/mochitest/test_nsIAccessible_comboboxes.xul
browser/base/content/test/Makefile.in
content/html/content/src/nsHTMLDelElement.cpp
content/html/content/src/nsImageMapUtils.cpp
content/html/content/src/nsImageMapUtils.h
content/html/document/src/nsImageDocument.cpp
content/html/document/src/nsMediaDocument.cpp
content/html/document/src/nsMediaDocument.h
content/html/document/src/nsPluginDocument.cpp
content/html/document/src/nsVideoDocument.cpp
content/xslt/public/txDouble.h
dom/interfaces/core/nsIDOM3Text.idl
dom/interfaces/core/nsIDOMEntity.idl
dom/interfaces/core/nsIDOMEntityReference.idl
dom/interfaces/core/nsIDOMNSDocument.idl
dom/interfaces/html/nsIDOMNSHTMLDocument.idl
dom/interfaces/html/nsIDOMNSHTMLFormElement.idl
dom/interfaces/html/nsIDOMNSHTMLHRElement.idl
dom/interfaces/stylesheets/nsIDOMDocumentStyle.idl
dom/interfaces/stylesheets/nsIDOMNSDocumentStyle.idl
mobile/chrome/content/content.css
mobile/themes/core/gingerbread/images/check-selected-46.png
mobile/themes/core/gingerbread/images/check-unselected-46.png
toolkit/components/autocomplete/tests/unit/test_autofill.js
--- a/.hgtags
+++ b/.hgtags
@@ -58,8 +58,11 @@ 138f593553b66c9f815e8f57870c19d6347f7702
 e56ecd8b3a68c158025207c5fd081d043e28f5ce GECKO_2_0_BASE
 e273946b74c8d631ed86bd74ba9afe0e67b12378 GECKO_2_1_BASE
 b70744835d94e54eec97b8fd186c96da5708a506 PRE_MOBILE_MERGE
 b70744835d94e54eec97b8fd186c96da5708a506 PRE_MOBILE_MERGE_20110406
 a71bd564ebf5bf4f93d13e84114f759c263130b0 MOBILE_MERGE_DONE
 a71bd564ebf5bf4f93d13e84114f759c263130b0 MOBILE_MERGE_DONE_20110406
 a95d426422816513477e5863add1b00ac7041dcb AURORA_BASE_20110412
 138f593553b66c9f815e8f57870c19d6347f7702 UPDATE_PACKAGING_R14
+9eae975b3d6fb7748fe5a3c0113d449b1c7cc0b2 AURORA_BASE_20110524
+138f593553b66c9f815e8f57870c19d6347f7702 UPDATE_PACKAGING_R14
+462c726144bc1fb45b61e774f64ac5d61b4e047c UPDATE_PACKAGING_R14
--- a/accessible/src/base/nsAccessNode.cpp
+++ b/accessible/src/base/nsAccessNode.cpp
@@ -50,19 +50,16 @@
 #include "nsApplicationAccessibleWrap.h"
 #include "nsIAccessibleDocument.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocument.h"
 #include "nsIDOMCSSPrimitiveValue.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMElement.h"
-#include "nsIDOMHTMLDocument.h"
-#include "nsIDOMHTMLElement.h"
-#include "nsIDOMNSDocument.h"
 #include "nsIDOMNSHTMLElement.h"
 #include "nsIDOMWindow.h"
 #include "nsPIDOMWindow.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIFrame.h"
 #include "nsIPrefService.h"
 #include "nsIPrefBranch.h"
 #include "nsPresContext.h"
@@ -130,16 +127,22 @@ void nsAccessNode::LastRelease()
   }
   // ... then die.
   delete this;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessNode public
 
+bool
+nsAccessNode::IsDefunct() const
+{
+  return !mContent;
+}
+
 PRBool
 nsAccessNode::Init()
 {
   return PR_TRUE;
 }
 
 
 void
--- a/accessible/src/base/nsAccessNode.h
+++ b/accessible/src/base/nsAccessNode.h
@@ -116,31 +116,31 @@ public:
    * Return focused node within accessible window.
    *
    * XXX: it shouldn't break us if we return focused node not depending on
    * window so that we can turn this method into util method.
    */
   already_AddRefed<nsINode> GetCurrentFocus();
 
   /**
-   * Returns true when the accessible is defunct.
-   */
-  virtual PRBool IsDefunct() { return !mContent; }
-
-  /**
    * Initialize the access node object, add it to the cache.
    */
   virtual PRBool Init();
 
   /**
    * Shutdown the access node object.
    */
   virtual void Shutdown();
 
   /**
+   * Returns true when the accessible is defunct.
+   */
+  virtual bool IsDefunct() const;
+
+  /**
    * Return frame for the given access node object.
    */
   virtual nsIFrame* GetFrame() const;
 
   /**
    * Return DOM node associated with this accessible.
    */
   already_AddRefed<nsIDOMNode> GetDOMNode() const
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -102,17 +102,16 @@
 
 #ifndef DISABLE_XFORMS_HOOKS
 #include "nsXFormsFormControlsAccessible.h"
 #include "nsXFormsWidgetsAccessible.h"
 #endif
 
 #include "mozilla/FunctionTimer.h"
 #include "mozilla/dom/Element.h"
-#include "nsImageMapUtils.h"
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessibilityService
 ////////////////////////////////////////////////////////////////////////////////
 
 nsAccessibilityService *nsAccessibilityService::gAccessibilityService = nsnull;
 PRBool nsAccessibilityService::gIsShutdown = PR_TRUE;
 
@@ -270,18 +269,20 @@ nsAccessibilityService::CreateHTMLCombob
 already_AddRefed<nsAccessible>
 nsAccessibilityService::CreateHTMLImageAccessible(nsIContent* aContent,
                                                   nsIPresShell* aPresShell)
 {
   nsAutoString mapElmName;
   aContent->GetAttr(kNameSpaceID_None,
                     nsAccessibilityAtoms::usemap,
                     mapElmName);
-  nsCOMPtr<nsIDOMHTMLMapElement> mapElm =
-    nsImageMapUtils::FindImageMap(aContent->GetCurrentDoc(), mapElmName);
+  nsCOMPtr<nsIDOMHTMLMapElement> mapElm;
+  if (nsIDocument* document = aContent->GetCurrentDoc()) {
+    mapElm = do_QueryInterface(document->FindImageMap(mapElmName));
+  }
 
   nsCOMPtr<nsIWeakReference> weakShell(do_GetWeakReference(aPresShell));
   nsAccessible* accessible = mapElm ?
     new nsHTMLImageMapAccessible(aContent, weakShell, mapElm) :
     new nsHTMLImageAccessibleWrap(aContent, weakShell);
   NS_IF_ADDREF(accessible);
   return accessible;
 }
--- a/accessible/src/base/nsApplicationAccessible.cpp
+++ b/accessible/src/base/nsApplicationAccessible.cpp
@@ -327,18 +327,18 @@ nsApplicationAccessible::GetPlatformVers
 
   AppendUTF8toUTF16(cversion, aVersion);
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessNode public methods
 
-PRBool
-nsApplicationAccessible::IsDefunct()
+bool
+nsApplicationAccessible::IsDefunct() const
 {
   return nsAccessibilityService::IsShutdown();
 }
 
 PRBool
 nsApplicationAccessible::Init()
 {
   mAppInfo = do_GetService("@mozilla.org/xre/app-info;1");
--- a/accessible/src/base/nsApplicationAccessible.h
+++ b/accessible/src/base/nsApplicationAccessible.h
@@ -110,17 +110,17 @@ public:
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString &aName);
   NS_IMETHOD GetActionDescription(PRUint8 aIndex, nsAString &aDescription);
   NS_IMETHOD DoAction(PRUint8 aIndex);
 
   // nsIAccessibleApplication
   NS_DECL_NSIACCESSIBLEAPPLICATION
 
   // nsAccessNode
-  virtual PRBool IsDefunct();
+  virtual bool IsDefunct() const;
   virtual PRBool Init();
   virtual void Shutdown();
   virtual bool IsPrimaryForNode() const;
 
   // nsAccessible
   virtual void ApplyARIAState(PRUint64* aState);
   virtual void Description(nsString& aDescription);
   virtual PRUint32 NativeRole();
--- a/accessible/src/base/nsBaseWidgetAccessible.cpp
+++ b/accessible/src/base/nsBaseWidgetAccessible.cpp
@@ -136,17 +136,17 @@ nsLinkableAccessible::GetValue(nsAString
 }
 
 
 NS_IMETHODIMP
 nsLinkableAccessible::GetNumActions(PRUint8 *aNumActions)
 {
   NS_ENSURE_ARG_POINTER(aNumActions);
 
-  *aNumActions = mActionAcc ? 1 : 0;
+  *aNumActions = (mIsOnclick || mIsLink) ? 1 : 0;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsLinkableAccessible::GetActionName(PRUint8 aIndex, nsAString& aName)
 {
   aName.Truncate();
 
@@ -223,17 +223,16 @@ nsLinkableAccessible::BindToParent(nsAcc
   nsAccessibleWrap::BindToParent(aParent, aIndexInParent);
 
   // Cache action content.
   mActionAcc = nsnull;
   mIsLink = PR_FALSE;
   mIsOnclick = PR_FALSE;
 
   if (nsCoreUtils::HasClickListener(mContent)) {
-    mActionAcc = this;
     mIsOnclick = PR_TRUE;
     return;
   }
 
   // XXX: The logic looks broken since the click listener may be registered
   // on non accessible node in parent chain but this node is skipped when tree
   // is traversed.
   nsAccessible* walkUpAcc = this;
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -49,18 +49,16 @@
 #include "nsICommandManager.h"
 #include "nsIDocShell.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocument.h"
 #include "nsIDOMAttr.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentType.h"
-#include "nsIDOMNSDocument.h"
-#include "nsIDOMNSHTMLDocument.h"
 #include "nsIDOMXULDocument.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsPIDOMWindow.h"
 #include "nsIDOMXULPopupElement.h"
 #include "nsIEditingSession.h"
 #include "nsEventStateManager.h"
 #include "nsIFrame.h"
 #include "nsHTMLSelectAccessible.h"
@@ -406,32 +404,34 @@ NS_IMETHODIMP nsDocAccessible::GetURL(ns
     webNav->GetCurrentURI(getter_AddRefs(pURI));
     if (pURI)
       pURI->GetSpec(theURL);
   }
   CopyUTF8toUTF16(theURL, aURL);
   return NS_OK;
 }
 
-NS_IMETHODIMP nsDocAccessible::GetTitle(nsAString& aTitle)
+NS_IMETHODIMP
+nsDocAccessible::GetTitle(nsAString& aTitle)
 {
-  nsCOMPtr<nsIDOMNSDocument> domnsDocument(do_QueryInterface(mDocument));
-  if (domnsDocument) {
-    return domnsDocument->GetTitle(aTitle);
+  nsCOMPtr<nsIDOMDocument> domDocument = do_QueryInterface(mDocument);
+  if (!domDocument) {
+    return NS_ERROR_FAILURE;
   }
-  return NS_ERROR_FAILURE;
+  return domDocument->GetTitle(aTitle);
 }
 
-NS_IMETHODIMP nsDocAccessible::GetMimeType(nsAString& aMimeType)
+NS_IMETHODIMP
+nsDocAccessible::GetMimeType(nsAString& aMimeType)
 {
-  nsCOMPtr<nsIDOMNSDocument> domnsDocument(do_QueryInterface(mDocument));
-  if (domnsDocument) {
-    return domnsDocument->GetContentType(aMimeType);
+  nsCOMPtr<nsIDOMDocument> domDocument = do_QueryInterface(mDocument);
+  if (!domDocument) {
+    return NS_ERROR_FAILURE;
   }
-  return NS_ERROR_FAILURE;
+  return domDocument->GetContentType(aMimeType);
 }
 
 NS_IMETHODIMP nsDocAccessible::GetDocType(nsAString& aDocType)
 {
   nsCOMPtr<nsIDOMDocument> domDoc(do_QueryInterface(mDocument));
   nsCOMPtr<nsIDOMDocumentType> docType;
 
 #ifdef MOZ_XUL
@@ -602,16 +602,22 @@ nsDocAccessible::Init()
   NS_LOG_ACCDOCCREATE_FOR("document initialize", mDocument, this)
 
   // Initialize notification controller.
   nsCOMPtr<nsIPresShell> shell(GetPresShell());
   mNotificationController = new NotificationController(this, shell);
   if (!mNotificationController)
     return PR_FALSE;
 
+  // Mark the document accessible as loaded if its DOM document was loaded at
+  // this point (this can happen because a11y is started late or DOM document
+  // having no container was loaded.
+  if (mDocument->GetReadyStateEnum() == nsIDocument::READYSTATE_COMPLETE)
+    mIsLoaded = PR_TRUE;
+
   AddEventListeners();
   return PR_TRUE;
 }
 
 void
 nsDocAccessible::Shutdown()
 {
   if (!mWeakShell) // already shutdown
@@ -665,18 +671,18 @@ nsDocAccessible::GetFrame() const
 
   nsIFrame* root = nsnull;
   if (shell)
     root = shell->GetRootFrame();
 
   return root;
 }
 
-PRBool
-nsDocAccessible::IsDefunct()
+bool
+nsDocAccessible::IsDefunct() const
 {
   return nsHyperTextAccessibleWrap::IsDefunct() || !mDocument;
 }
 
 // nsDocAccessible protected member
 void nsDocAccessible::GetBoundsRect(nsRect& aBounds, nsIFrame** aRelativeFrame)
 {
   *aRelativeFrame = GetFrame();
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -103,17 +103,17 @@ public:
 
   // nsIDocumentObserver
   NS_DECL_NSIDOCUMENTOBSERVER
 
   // nsAccessNode
   virtual PRBool Init();
   virtual void Shutdown();
   virtual nsIFrame* GetFrame() const;
-  virtual PRBool IsDefunct();
+  virtual bool IsDefunct() const;
   virtual nsINode* GetNode() const { return mDocument; }
   virtual nsIDocument* GetDocumentNode() const { return mDocument; }
 
   // nsAccessible
   virtual void Description(nsString& aDescription);
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual void ApplyARIAState(PRUint64* aState);
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -54,17 +54,16 @@
 #include "nsIDOMElement.h"
 #include "nsIDOMEventListener.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMHTMLAnchorElement.h"
 #include "nsIDOMHTMLImageElement.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLSelectElement.h"
 #include "nsIDOMDataContainerEvent.h"
-#include "nsIDOMNSDocument.h"
 #include "nsIDOMNSEvent.h"
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULPopupElement.h"
 #include "nsIDocument.h"
 #include "nsIEventListenerManager.h"
 #include "nsIFrame.h"
@@ -134,17 +133,17 @@ nsRootAccessible::GetName(nsAString& aNa
 
   if (mRoleMapEntry) {
     nsAccessible::GetName(aName);
     if (!aName.IsEmpty()) {
       return NS_OK;
     }
   }
 
-  nsCOMPtr<nsIDOMNSDocument> document(do_QueryInterface(mDocument));
+  nsCOMPtr<nsIDOMDocument> document = do_QueryInterface(mDocument);
   return document->GetTitle(aName);
 }
 
 PRUint32
 nsRootAccessible::NativeRole()
 {
   // If it's a <dialog> or <wizard>, use nsIAccessibleRole::ROLE_DIALOG instead
   dom::Element *root = mDocument->GetRootElement();
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -151,18 +151,18 @@ nsXULTreeAccessible::GetValue(nsAString&
   }
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeAccessible: nsAccessNode implementation
 
-PRBool
-nsXULTreeAccessible::IsDefunct()
+bool
+nsXULTreeAccessible::IsDefunct() const
 {
   return nsAccessibleWrap::IsDefunct() || !mTree || !mTreeView;
 }
 
 void
 nsXULTreeAccessible::Shutdown()
 {
   // XXX: we don't remove accessible from document cache if shutdown wasn't
@@ -829,18 +829,18 @@ nsXULTreeItemAccessibleBase::DoAction(PR
 
   DoCommand(nsnull, aIndex);
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeItemAccessibleBase: nsAccessNode implementation
 
-PRBool
-nsXULTreeItemAccessibleBase::IsDefunct()
+bool
+nsXULTreeItemAccessibleBase::IsDefunct() const
 {
   if (nsAccessibleWrap::IsDefunct() || !mTree || !mTreeView || mRow < 0)
     return PR_TRUE;
 
   PRInt32 rowCount = 0;
   nsresult rv = mTreeView->GetRowCount(&rowCount);
   return NS_FAILED(rv) || mRow >= rowCount;
 }
@@ -1086,18 +1086,18 @@ nsXULTreeItemAccessible::GetName(nsAStri
     mTreeView->GetCellValue(mRow, mColumn, aName);
 
   return NS_OK;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeItemAccessible: nsAccessNode implementation
 
-PRBool
-nsXULTreeItemAccessible::IsDefunct()
+bool
+nsXULTreeItemAccessible::IsDefunct() const
 {
   return nsXULTreeItemAccessibleBase::IsDefunct() || !mColumn;
 }
 
 PRBool
 nsXULTreeItemAccessible::Init()
 {
   if (!nsXULTreeItemAccessibleBase::Init())
--- a/accessible/src/xul/nsXULTreeAccessible.h
+++ b/accessible/src/xul/nsXULTreeAccessible.h
@@ -75,17 +75,17 @@ public:
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsXULTreeAccessible,
                                            nsAccessible)
 
   // nsIAccessible
   NS_IMETHOD GetValue(nsAString& aValue);
   NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
 
   // nsAccessNode
-  virtual PRBool IsDefunct();
+  virtual bool IsDefunct() const;
   virtual void Shutdown();
 
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual nsAccessible* GetChildAtPoint(PRInt32 aX, PRInt32 aY,
                                         EWhichChildAtPoint aWhichChild);
 
@@ -196,17 +196,17 @@ public:
                            PRInt32 *aSimilarItemsInGroup,
                            PRInt32 *aPositionInGroup);
 
   NS_IMETHOD GetNumActions(PRUint8 *aCount);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 aIndex);
 
   // nsAccessNode
-  virtual PRBool IsDefunct();
+  virtual bool IsDefunct() const;
   virtual void Shutdown();
   virtual bool IsPrimaryForNode() const;
 
   // nsAccessible
   virtual PRUint64 NativeState();
   virtual PRInt32 GetIndexInParent() const;
 
   // nsXULTreeItemAccessibleBase
@@ -261,17 +261,17 @@ class nsXULTreeItemAccessible : public n
 public:
   nsXULTreeItemAccessible(nsIContent *aContent, nsIWeakReference *aShell,
                           nsAccessible *aParent, nsITreeBoxObject *aTree,
                           nsITreeView *aTreeView, PRInt32 aRow);
 
   NS_IMETHOD GetName(nsAString& aName);
 
   // nsAccessNode
-  virtual PRBool IsDefunct();
+  virtual bool IsDefunct() const;
   virtual PRBool Init();
   virtual void Shutdown();
 
   // nsAccessible
   virtual PRUint32 NativeRole();
 
   // nsXULTreeItemAccessibleBase
   virtual void RowInvalidated(PRInt32 aStartColIdx, PRInt32 aEndColIdx);
--- a/accessible/src/xul/nsXULTreeGridAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeGridAccessible.cpp
@@ -1082,18 +1082,18 @@ nsXULTreeGridCellAccessible::IsSelected(
   NS_ENSURE_SUCCESS(rv, rv);
 
   return selection->IsSelected(mRow, aIsSelected);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeGridCellAccessible: nsAccessNode implementation
 
-PRBool
-nsXULTreeGridCellAccessible::IsDefunct()
+bool
+nsXULTreeGridCellAccessible::IsDefunct() const
 {
   return nsLeafAccessible::IsDefunct() || !mParent || !mTree || !mTreeView ||
     !mColumn;
 }
 
 PRBool
 nsXULTreeGridCellAccessible::Init()
 {
--- a/accessible/src/xul/nsXULTreeGridAccessible.h
+++ b/accessible/src/xul/nsXULTreeGridAccessible.h
@@ -150,17 +150,17 @@ public:
   NS_IMETHOD GetNumActions(PRUint8 *aCount);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 aIndex);
 
   // nsIAccessibleTableCell
   NS_DECL_NSIACCESSIBLETABLECELL
 
   // nsAccessNode
-  virtual PRBool IsDefunct();
+  virtual bool IsDefunct() const;
   virtual PRBool Init();
   virtual bool IsPrimaryForNode() const;
 
   // nsAccessible
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual PRInt32 GetIndexInParent() const;
--- a/accessible/tests/mochitest/Makefile.in
+++ b/accessible/tests/mochitest/Makefile.in
@@ -85,26 +85,24 @@ include $(topsrcdir)/config/rules.mk
 		value.js \
 		test_aria_activedescendant.html \
 		test_aria_role_article.html \
 		test_aria_role_equation.html \
 		test_aria_roles.html \
 		test_aria_roles.xul \
 		test_aria_token_attrs.html \
 		test_bug420863.html \
-	$(warning   test_childAtPoint.html temporarily disabled) \
-	$(warning	test_childAtPoint.xul temporarily disabled) \
+		test_childAtPoint.html \
+		test_childAtPoint.xul \
 		test_descr.html \
 		test_elm_landmarks.html \
 		test_elm_listbox.xul \
-	$(warning   test_elm_media.html temporarily disabled) \
 		test_elm_nsApplicationAcc.html \
 		test_elm_plugin.html \
 		test_keys.html \
-	$(warning test_nsIAccessible_comboboxes.xul temporarily disabled) \
  		test_nsIAccessible_selects.html \
 		test_nsIAccessibleDocument.html \
 		test_nsIAccessibleImage.html \
 		test_nsIAccessNode_utils.html \
 		test_nsOuterDocAccessible.html \
 		test_role_nsHyperTextAcc.html \
 		test_takeFocus.html \
 		test_text_caret.html \
--- a/accessible/tests/mochitest/actions/Makefile.in
+++ b/accessible/tests/mochitest/actions/Makefile.in
@@ -47,14 +47,15 @@ include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =\
 		test_anchors.html \
 		test_aria.html \
 		test_general.html \
 		test_general.xul \
 		test_inputs.html \
 		test_link.html \
+		test_media.html \
 		test_tree.xul \
 		test_treegrid.xul \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/a11y/$(relativesrcdir)
--- a/accessible/tests/mochitest/actions/test_general.html
+++ b/accessible/tests/mochitest/actions/test_general.html
@@ -31,19 +31,29 @@
           ID: "li_clickable2",
           actionName: "click",
           events: CLICK_EVENTS
         },
         {
           ID: "li_clickable3",
           actionName: "click",
           events: CLICK_EVENTS
+        },
+        {
+          ID: "onclick_img",
+          actionName: "click",
+          events: CLICK_EVENTS
         }
       ];
+
       testActions(actionsArray);
+
+      getAccessible("onclick_img").takeFocus();
+is(getAccessible("link1").numActions, 1, "links should have one action");
+is(getAccessible("link2").numActions, 1, "link with onclick handler should have 1 action");
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
 
 <body>
@@ -53,20 +63,31 @@
      title="nsHTMLLiAccessible shouldn't be inherited from linkable accessible">
     Mozilla Bug 523789
   </a><br>
   <a target="_blank"
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=423409"
      title="Expose click action if mouseup and mousedown are registered">
     Mozilla Bug 423409
   </a>
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=659620"
+     title="hang when trying to edit a page on wikimo with NVDA running">
+    Mozilla Bug 659620
+  </a>
   <p id="display"></p>
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
   <ul>
     <li id="li_clickable1" onclick="">Clickable list item</li>
     <li id="li_clickable2" onmousedown="">Clickable list item</li>
     <li id="li_clickable3" onmouseup="">Clickable list item</li>
   </ul>
+
+  <!-- linkable accessibles -->
+  <img id="onclick_img" onclick="" src="../moz.png">
+
+  <a id="link1" href="www">linkable textleaf accessible</a>
+  <div id="link2" onclick="">linkable textleaf accessible</div>
 </body>
 </html>
rename from accessible/tests/mochitest/test_elm_media.html
rename to accessible/tests/mochitest/actions/test_media.html
--- a/accessible/tests/mochitest/test_elm_media.html
+++ b/accessible/tests/mochitest/actions/test_media.html
@@ -8,25 +8,25 @@ https://bugzilla.mozilla.org/show_bug.cg
   <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
 
   <script type="application/javascript"
           src="chrome://mochikit/content/MochiKit/packed.js"></script>
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 
   <script type="application/javascript"
-          src="common.js"></script>
+          src="../common.js"></script>
   <script type="application/javascript"
-          src="events.js"></script>
+          src="../events.js"></script>
   <script type="application/javascript"
-          src="actions.js"></script>
+          src="../actions.js"></script>
   <script type="application/javascript"
-          src="role.js"></script>
+          src="../role.js"></script>
   <script type="application/javascript"
-          src="states.js"></script>
+          src="../states.js"></script>
 
   <script type="application/javascript">
 
     // gA11yEventDumpID = "eventDump";
 
     function focusChecker(aAcc)
     {
       this.type = EVENT_FOCUS;
@@ -54,87 +54,49 @@ https://bugzilla.mozilla.org/show_bug.cg
         is(aEvent.accessible.name, aName,
            "Wrong name of " + prettyName(aEvent.accessible) + " on focus");
       }
     }
 
     function doTest()
     {
       //////////////////////////////////////////////////////////////////////////
-      // test the accessible tree
+      // test actions of audio controls
 
-      var accTree = {
-        role: ROLE_GROUPING,
-        children: [
-          { // start/stop button
-            role: ROLE_PUSHBUTTON,
-            name: "Play",
-            states: {
-              states: STATE_FOCUSABLE
-            }
-          },
-          { // buffer bar
-            role: ROLE_PROGRESSBAR
-          },
-          { // progress bar
-            role: ROLE_PROGRESSBAR
-          },
-          { // slider of progress bar
-            role: ROLE_SLIDER,
-            name: "0:00 of 0:01 elapsed",
-            states: {
-              states: STATE_FOCUSABLE
-            }
-          },
-          { // duration label, role="presentation"
-            role: ROLE_NOTHING
-          },
-          { // mute button
-            role: ROLE_PUSHBUTTON,
-            name: "Mute",
-            states: {
-              states: STATE_FOCUSABLE
-            }
-          }
-        ]
-      };
-      testAccessibleTree("audio", accTree);
-
-      //////////////////////////////////////////////////////////////////////////
-      // test actions of audio controls
+      todo(false, "Focus test are disabled until bug 494175 is fixed.");
 
       var audioElm = getAccessible("audio");
       var playBtn = audioElm.firstChild;
       var scrubber = playBtn.nextSibling.nextSibling.nextSibling;
       var muteBtn = audioElm.lastChild;
 
       var actions = [
         {
           ID: muteBtn,
           actionName: "press",
           events: CLICK_EVENTS,
           eventSeq: [
-            new focusChecker(muteBtn),
+     //       new focusChecker(muteBtn),
             new nameChecker(muteBtn, "Unmute"),
           ]
         },
-        {
-          ID: scrubber,
-          actionName: "activate",
-          events: null,
-          eventSeq: [
-            new focusChecker(scrubber)
-          ]
-        },
+     //   {
+     //     ID: scrubber,
+     //     actionName: "activate",
+     //     events: null,
+     //     eventSeq: [
+     //       new focusChecker(scrubber)
+     //     ]
+     //   },
         {
           ID: playBtn,
           actionName: "press",
           events: CLICK_EVENTS,
           eventSeq: [
-            new focusChecker(playBtn),
+     //       new focusChecker(playBtn),
             new nameChecker(playBtn, "Pause"),
           ]
         }
       ];
 
       testActions(actions); // Will call SimpleTest.finish();
     }
 
@@ -147,14 +109,14 @@ https://bugzilla.mozilla.org/show_bug.cg
   <a target="_blank"
      title="Expose HTML5 video and audio elements' embedded controls through accessibility APIs"
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=483573">Mozilla Bug 483573</a>
   <p id="display"></p>
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
-  <audio id="audio" src="bug461281.ogg"
+  <audio id="audio" src="../bug461281.ogg"
          controls="true"></audio>
 
   <div id="eventDump"></div>
 </body>
 </html>
--- a/accessible/tests/mochitest/attributes/test_obj_group.xul
+++ b/accessible/tests/mochitest/attributes/test_obj_group.xul
@@ -25,31 +25,34 @@
       testGroupAttrs("item1", 1, 2);
       testGroupAttrs("item2", 2, 2);
 
       //////////////////////////////////////////////////////////////////////////
       // xul:menu (bug 443881)
       var menu1 = document.getElementById("menu_item1");
       menu1.open = true;
 
-      window.setTimeout(function() {
+      menu1.addEventListener("popupshown", function() {
         var menu2 = document.getElementById("menu_item2");
         menu2.open = true;
 
-        window.setTimeout(function() {
+        menu2.addEventListener("popupshown", function() {
           testGroupAttrs("menu_item1.1", 1, 1);
           testGroupAttrs("menu_item1.2", 1, 3);
           testGroupAttrs("menu_item1.4", 2, 3);
           testGroupAttrs("menu_item2", 3, 3);
           testGroupAttrs("menu_item2.1", 1, 2, 1);
           testGroupAttrs("menu_item2.2", 2, 2, 1);
 
+          menu1.open = false;
+          menu2.open = false;
+
           SimpleTest.finish();
-        }, 200);
-      }, 200);
+        }, false);
+      }, false);
 
       //////////////////////////////////////////////////////////////////////////
       // xul:tab
       testGroupAttrs("tab1", 1, 2);
       testGroupAttrs("tab2", 2, 2);
 
       //////////////////////////////////////////////////////////////////////////
       // xul:radio
--- a/accessible/tests/mochitest/common.js
+++ b/accessible/tests/mochitest/common.js
@@ -88,17 +88,17 @@ function addA11yLoadEvent(aFunc)
       function()
       {
         var accDoc = getAccessible(document);
         var state = {};
         accDoc.getState(state, {});
         if (state.value & STATE_BUSY)
           return waitForDocLoad();
 
-        window.setTimeout(aFunc, 150);
+        window.setTimeout(aFunc, 0);
       },
       0
     );
   }
 
   SimpleTest.waitForFocus(waitForDocLoad);
 }
 
--- a/accessible/tests/mochitest/events/test_docload.html
+++ b/accessible/tests/mochitest/events/test_docload.html
@@ -113,16 +113,35 @@
         if (aAction == kRemove)
           return "remove iframe";
 
         return "change display style of iframe to " +
           ((aAction == kHide) ? "none" : "block");
       }
     }
 
+    function makeIFrameVisible(aID)
+    {
+      this.DOMNode = getNode(aID);
+
+      this.eventSeq = [
+        new invokerChecker(EVENT_REORDER, this.DOMNode.parentNode)
+      ];
+
+      this.invoke = function makeIFrameVisible_invoke()
+      {
+        this.DOMNode.style.visibility = "visible";
+      }
+
+      this.getID = function makeIFrameVisible_getID()
+      {
+        return "The accessible for DOM document loaded before it's shown shouldn't have busy state.";
+      }
+    }
+
     function openDialogWnd(aURL)
     {
       // Get application root accessible.
       var docAcc = getAccessible(document);
       while (docAcc) {
         this.mRootAcc = docAcc;
         try {
           docAcc = docAcc.parent;
@@ -219,33 +238,51 @@
 
     ////////////////////////////////////////////////////////////////////////////
     // Do tests
 
     var gQueue = null;
 
     // Debug stuff.
     // gA11yEventDumpID = "eventdump";
-    // gA11yEventDumpToConsole = true;
+    //gA11yEventDumpToConsole = true;
 
     function doTests()
     {
       gQueue = new eventQueue();
 
       gQueue.push(new changeIframeSrc("iframe", "about:"));
       gQueue.push(new changeIframeSrc("iframe", "about:buildconfig"));
       gQueue.push(new morphIFrame("iframe", kHide));
       gQueue.push(new morphIFrame("iframe", kShow));
       gQueue.push(new morphIFrame("iframe", kRemove));
+      gQueue.push(new makeIFrameVisible("iframe2"));
       gQueue.push(new openDialogWnd("about:"));
       gQueue.push(new openWndShutdownDoc());
 
+      gQueue.onFinish = doLastCallTests;
+
       gQueue.invoke(); // Will call SimpleTest.finish();
     }
 
+    function doLastCallTests()
+    {
+      //////////////////////////////////////////////////////////////////////////
+      // makeIFrameVisible() test, part2
+
+      // The document shouldn't have busy state (the DOM document was loaded
+      // before its accessible was created). Do this test lately to make sure
+      // the content of document accessible was created initially, prior to this
+      // the document accessible keeps busy state. The initial creation happens
+      // asynchronously after document creation, there are no events we could
+      // use to catch it.
+      var iframeDoc = getAccessible("iframe2").firstChild;
+      testStates(iframeDoc, 0, 0, STATE_BUSY);
+    }
+
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTests);
   </script>
 </head>
 
 <body>
 
   <a target="_blank"
@@ -263,18 +300,24 @@
      title="Reorganize accessible document handling">
     Mozilla Bug 566103
   </a><br>
   <a target="_blank"
      href="https://bugzilla.mozilla.org/show_bug.cgi?id=571459"
      title="Shutdown document accessible when presshell goes away">
     Mozilla Bug 571459
   </a>
+  <a target="_blank"
+     href="https://bugzilla.mozilla.org/show_bug.cgi?id=658185"
+     title="The DOM document loaded before it's shown shouldn't have busy state">
+    Mozilla Bug 658185
+  </a>
 
   <p id="display"></p>
   <div id="content" style="display: none"></div>
   <pre id="test">
   </pre>
 
   <div id="testContainer"><iframe id="iframe"></iframe></div>
+  <div id="testContainer2"><iframe id="iframe2" src="about:" style="visibility: hidden;"></iframe></div>
   <div id="eventdump"></div>
 </body>
 </html>
--- a/accessible/tests/mochitest/states/Makefile.in
+++ b/accessible/tests/mochitest/states/Makefile.in
@@ -44,16 +44,17 @@ relativesrcdir  = accessible/states
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES =\
 		test_aria.html \
 		test_aria_imgmap.html \
 		test_aria_tabs.html \
+		test_comboboxes.xul \
 		test_doc.html \
 		test_docarticle.html \
 		test_editablebody.html \
 		test_frames.html \
 		test_inputs.html \
 		test_inputs.xul \
 		test_link.html \
 		test_popup.xul \
rename from accessible/tests/mochitest/test_nsIAccessible_comboboxes.xul
rename to accessible/tests/mochitest/states/test_comboboxes.xul
--- a/accessible/tests/mochitest/test_nsIAccessible_comboboxes.xul
+++ b/accessible/tests/mochitest/states/test_comboboxes.xul
@@ -11,19 +11,19 @@
   <script type="application/javascript" 
           src="chrome://mochikit/content/MochiKit/packed.js"></script>
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/EventUtils.js" />
 
   <script type="application/javascript"
-          src="common.js" />
+          src="../common.js" />
   <script type="application/javascript"
-          src="events.js" />        
+          src="../events.js" />
 
   <script type="application/javascript">
   <![CDATA[
     function openHideCombobox(aComboboxNodeOrID, aIsOpen)
     {
       this.invoke = function invoke()
       {
         synthesizeMouse(this.DOMNode, 5, 5, {});
@@ -59,16 +59,17 @@
       gQueue.push(new openHideCombobox(ID, true));
       gQueue.push(new openHideCombobox(ID, false));
 
       // XXX: searchbar doesn't fire state change events because accessible
       // parent of combobox_list accessible is pushbutton accessible.
       //var searchbar = document.getElementById("searchbar");
       //gQueue.push(new openHideCombobox(searchbar, true));
       //gQueue.push(new openHideCombobox(searchbar, false));
+      todo(false, "Enable states test for XUL searchbar widget!");
 
       gQueue.invoke(); // Will call SimpleTest.finish();
     }
 
     // This is the hack needed for searchbar work outside of browser.
     function getBrowser()
     {
       return {
--- a/accessible/tests/mochitest/test_childAtPoint.html
+++ b/accessible/tests/mochitest/test_childAtPoint.html
@@ -20,29 +20,29 @@
       // Not specific case, child and deepchild testing.
       var list = getAccessible("list");
       var listitem = getAccessible("listitem");
       var image = getAccessible("image");
       testChildAtPoint(list, 1, 1, false, listitem);
       testChildAtPoint(list, 1, 1, true, image.firstChild);
 
       // ::MustPrune case (in this case childAtPoint doesn't look inside a
-      // button), point is inside of button.
-      var btn = getAccessible("btn");
-      testChildAtPoint(btn, 1, 1, false, btn);
-      testChildAtPoint(btn, 1, 1, true, btn);
+      // textbox), point is inside of textbox.
+      var txt = getAccessible("txt");
+      testChildAtPoint(txt, 1, 1, false, txt);
+      testChildAtPoint(txt, 1, 1, true, txt);
 
-      // ::MustPrune case, point is outside of button accessible but is in
+      // ::MustPrune case, point is outside of textbox accessible but is in
       // document.
-      testChildAtPoint(btn, -1, 1, false, null);
-      testChildAtPoint(btn, -1, 1, true, null);
+      testChildAtPoint(txt, -1, 1, false, null);
+      testChildAtPoint(txt, -1, 1, true, null);
 
       // ::MustPrune case, point is outside of root accessible.
-      testChildAtPoint(btn, -10000, 10000, false, null);
-      testChildAtPoint(btn, -10000, 10000, true, null);
+      testChildAtPoint(txt, -10000, 10000, false, null);
+      testChildAtPoint(txt, -10000, 10000, true, null);
 
       // Not specific case, point is inside of label accessible.
       var label = getAccessible("label");
       var labelText = label.firstChild;
       testChildAtPoint(label, 1, 1, false, labelText);
       testChildAtPoint(label, 1, 1, true, labelText);
   
       // Not specific case, point is outside of label accessible.
@@ -77,16 +77,16 @@
   </pre>
 
   <div role="list" id="list">
     <div role="listitem" id="listitem"><span role="image" id="image">img</span>item</div>
   </div>
 
   <span role="label">label1</span><span role="label" id="label">label2</span>
 
-  <span role="button">btn1</span><span role="button" id="btn">btn2</span>
+  <span role="textbox">textbox1</span><span role="textbox" id="txt">textbox2</span>
 
   <div id="outofflow" style="width: 10px; height: 10px; position: absolute; left: 0px; top: 0px; background-color: yellow;">
   </div>
   <div id="area" style="width: 100px; height: 100px; background-color: blue;"></div>
 
 </body>
 </html>
--- a/accessible/tests/mochitest/test_childAtPoint.xul
+++ b/accessible/tests/mochitest/test_childAtPoint.xul
@@ -19,18 +19,17 @@
   <script type="application/javascript"
           src="layout.js" />
 
   <script type="application/javascript">
   <![CDATA[
     function doTest()
     {
       // Initialize the tree
-      var view = new inTreeView();
-      view.mRowCount = 5;
+      var view = new nsTableTreeView(5);
 
       var tree = getNode("tree");
       var treeBox = tree.treeBoxObject;
       treeBox.view = view;
 
       // Tests
       var treecols = getNode("treecols");
       var x = treecols.boxObject.x;
--- a/accessible/tests/mochitest/tree/test_media.html
+++ b/accessible/tests/mochitest/tree/test_media.html
@@ -25,34 +25,43 @@ https://bugzilla.mozilla.org/show_bug.cg
     {
       //////////////////////////////////////////////////////////////////////////
       // test the accessible tree
 
       var accTree = {
         role: ROLE_GROUPING,
         children: [
           { // start/stop button
-            role: ROLE_PUSHBUTTON
+            role: ROLE_PUSHBUTTON,
+            name: "Play",
+            children: []
           },
           { // buffer bar
-            role: ROLE_PROGRESSBAR
+            role: ROLE_PROGRESSBAR,
+            children: []
           },
           { // progress bar
-            role: ROLE_PROGRESSBAR
+            role: ROLE_PROGRESSBAR,
+            children: []
           },
           { // slider of progress bar
-            role: ROLE_SLIDER
+            role: ROLE_SLIDER,
+            //name: "0:00 of 0:02 elapsed",
+            children: []
           },
           { // mute button
-            role: ROLE_PUSHBUTTON
+            role: ROLE_PUSHBUTTON,
+            name: "Mute",
+            children: []
           }
         ]
       };
       testAccessibleTree("audio", accTree);
 
+      todo(false, "Enable name test for slider. Fail on Linux.");
       SimpleTest.finish();
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   </script>
 </head>
 <body>
--- a/accessible/tests/mochitest/tree/test_txtctrl.xul
+++ b/accessible/tests/mochitest/tree/test_txtctrl.xul
@@ -10,16 +10,18 @@
           src="chrome://mochikit/content/MochiKit/packed.js" />
   <script type="application/javascript"
           src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js" />
 
   <script type="application/javascript"
           src="../common.js" />
   <script type="application/javascript"
           src="../role.js" />
+  <script type="application/javascript"
+          src="../events.js" />
 
   <script type="application/javascript">
   <![CDATA[
     ////////////////////////////////////////////////////////////////////////////
     // Test
 
     function doTest()
     {
@@ -103,16 +105,21 @@
           {
             // xul:menupopup
             role: ROLE_COMBOBOX_LIST,
             children: []
           }
         ]
       };
 
+      function test_txc7() {
+        testAccessibleTree("txc7", accTree);
+        SimpleTest.finish();
+      }
+
       // XPFE and Toolkit autocomplete widgets differ.
       var txc7 = document.getElementById("txc7");
       if ("clearResults" in txc7) {
         SimpleTest.ok(true, "Testing (Old) XPFE autocomplete widget.");
 
         // Popup is always created. (See code below.)
 
         accTree.children.push(
@@ -134,21 +141,24 @@
                         children: []
                       }
                     ]
                   }
                 ]
               }
             ]
           }
-          );
+        );
+        test_txc7();
+
       } else {
         SimpleTest.ok(true, "Testing (New) Toolkit autocomplete widget.");
 
-        // Dumb access to trigger popup lazy creation. (See code below.)
+        // Dumb access to trigger popup lazy creation.
+        waitForEvent(EVENT_REORDER, txc7, test_txc7);
         txc7.popup;
 
         accTree.children.push(
           {
             role: ROLE_LIST,
             children: [
               {
                 role: ROLE_LIST,
@@ -156,27 +166,18 @@
                   {
                     role: ROLE_COLUMNHEADER,
                     children: []
                   }
                 ]
               }
             ]
           }
-          );
+        );
       }
-
-      // Delay txc7 test a bit, to let Toolkit popup lazy creation complete.
-      function test_txc7() {
-        testAccessibleTree("txc7", accTree);
-  
-        SimpleTest.finish();
-      }
-      // SimpleTest.executeSoon() doesn't help here: use setTimeout() with a little delay.
-      setTimeout(test_txc7, 25);
     }
 
     SimpleTest.waitForExplicitFinish();
     addA11yLoadEvent(doTest);
   ]]>
   </script>
 
   <hbox flex="1" style="overflow: auto;">
--- a/browser/app/blocklist.xml
+++ b/browser/app/blocklist.xml
@@ -92,16 +92,21 @@
       <versionRange severity="1"/>
     </emItem>
     <emItem id="{B7082FAA-CB62-4872-9106-E42DD88EDE45}">
       <versionRange minVersion="0.1" maxVersion="3.3.0.*">
         <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
            <versionRange minVersion="3.7a1" maxVersion="*"/>
         </targetApplication>
       </versionRange>
+      <versionRange minVersion="3.3.1" maxVersion="*">
+        <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
+           <versionRange minVersion="5.0a1" maxVersion="*"/>
+        </targetApplication>
+      </versionRange>
     </emItem>
     <emItem id="{E8E88AB0-7182-11DF-904E-6045E0D72085}"/>
   </emItems>
 <pluginItems>
   <pluginItem>
     <match name="name" exp="^Yahoo Application State Plugin$"/>
     <match name="description" exp="^Yahoo Application State Plugin$"/>
     <match name="filename" exp="npYState.dll"/>
--- a/browser/app/macbuild/Contents/Info.plist.in
+++ b/browser/app/macbuild/Contents/Info.plist.in
@@ -87,16 +87,65 @@
 			<array>
 				<string>GIFf</string>
 				<string>JPEG</string>
 				<string>PNGf</string>
 			</array>
 			<key>CFBundleTypeRole</key>
 			<string>Viewer</string>
 		</dict>
+		<dict>
+			<key>CFBundleTypeExtensions</key>
+			<array>
+				<string>oga</string>
+				<string>ogg</string>
+			</array>
+			<key>CFBundleTypeIconFile</key>
+			<string>document.icns</string>
+			<key>CFBundleTypeMIMETypes</key>
+			<array>
+				<string>audio/ogg</string>
+			</array>
+			<key>CFBundleTypeName</key>
+			<string>HTML5 Audio (Ogg)</string>
+			<key>CFBundleTypeRole</key>
+			<string>Viewer</string>
+		</dict>
+		<dict>
+			<key>CFBundleTypeExtensions</key>
+			<array>
+				<string>ogv</string>
+			</array>
+			<key>CFBundleTypeIconFile</key>
+			<string>document.icns</string>
+			<key>CFBundleTypeMIMETypes</key>
+			<array>
+				<string>video/ogg</string>
+			</array>
+			<key>CFBundleTypeName</key>
+			<string>HTML5 Video (Ogg)</string>
+			<key>CFBundleTypeRole</key>
+			<string>Viewer</string>
+		</dict>
+		<dict>
+			<key>CFBundleTypeExtensions</key>
+			<array>
+				<string>webm</string>
+			</array>
+			<key>CFBundleTypeIconFile</key>
+			<string>document.icns</string>
+			<key>CFBundleTypeMIMETypes</key>
+			<array>
+				<string>video/webm</string>
+			</array>
+			<key>CFBundleTypeName</key>
+			<string>HTML5 Video (WebM)</string>
+			<key>CFBundleTypeRole</key>
+			<string>Viewer</string>
+		</dict>
 	</array>
 	<key>CFBundleExecutable</key>
 	<string>firefox-bin</string>
 	<key>CFBundleGetInfoString</key>
 	<string>%APP_NAME% %APP_VERSION%</string>
 	<key>CFBundleIconFile</key>
 	<string>firefox</string>
 	<key>CFBundleIdentifier</key>
--- a/browser/app/profile/extensions/testpilot@labs.mozilla.com/content/experiment-page.js
+++ b/browser/app/profile/extensions/testpilot@labs.mozilla.com/content/experiment-page.js
@@ -118,17 +118,17 @@ var stringBundle;
 	response == nsIFilePicker.returnReplace) {
       const nsIWebBrowserPersist = Components.interfaces.nsIWebBrowserPersist;
       let file = filePicker.file;
 
       // create a data url from the canvas and then create URIs of the source
       // and targets
       let io = Components.classes["@mozilla.org/network/io-service;1"].
 	getService(Components.interfaces.nsIIOService);
-      let source = io.newURI(canvas.toDataURL("image/png", ""), "UTF8", null);
+      let source = io.newURI(canvas.toDataURL("image/png"), "UTF8", null);
       let target = io.newFileURI(file);
 
       // prepare to save the canvas data
       let persist = Components.classes[
 	"@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].
 	  createInstance(nsIWebBrowserPersist);
       persist.persistFlags = nsIWebBrowserPersist.
 	PERSIST_FLAGS_REPLACE_EXISTING_FILES;
--- a/browser/app/profile/extensions/testpilot@labs.mozilla.com/install.rdf
+++ b/browser/app/profile/extensions/testpilot@labs.mozilla.com/install.rdf
@@ -1,24 +1,24 @@
 <?xml version="1.0"?>
 
 <RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
      xmlns:em="http://www.mozilla.org/2004/em-rdf#">
   <Description about="urn:mozilla:install-manifest">
     <em:id>testpilot@labs.mozilla.com</em:id>
-    <em:version>1.1.1</em:version>
+    <em:version>1.1.2</em:version>
     <em:type>2</em:type>
 
     <!-- Target Application this extension can install into, 
          with minimum and maximum supported versions. --> 
     <em:targetApplication>
       <Description>
         <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
         <em:minVersion>3.5</em:minVersion>
-        <em:maxVersion>5.0</em:maxVersion>
+        <em:maxVersion>6.0</em:maxVersion>
       </Description>
     </em:targetApplication>
    
     <!-- Front End MetaData -->
     <em:name>Feedback</em:name>
     <em:description>Help make Firefox better by giving feedback.</em:description>
     <em:creator>Mozilla Corporation</em:creator>
     <em:homepageURL>http://testpilot.mozillalabs.com/</em:homepageURL>
--- a/browser/app/profile/extensions/{972ce4c6-7e08-4474-a285-3208198ce6fd}/Makefile.in
+++ b/browser/app/profile/extensions/{972ce4c6-7e08-4474-a285-3208198ce6fd}/Makefile.in
@@ -38,18 +38,16 @@
 DEPTH		= ../../../../..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
-DEFINES += -DFIREFOX_VERSION=$(FIREFOX_VERSION)
-
 FILES := \
 	install.rdf \
 	$(NULL)
 
 libs::
 	$(PYTHON) $(MOZILLA_DIR)/config/Preprocessor.py $(DEFINES) $(ACDEFINES) $(srcdir)/install.rdf.in > install.rdf
 	$(INSTALL) $(FILES) $(DIST)/bin/extensions/{972ce4c6-7e08-4474-a285-3208198ce6fd}
  
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -65,16 +65,17 @@ pref("extensions.webservice.discoverURL"
 // Blocklist preferences
 pref("extensions.blocklist.enabled", true);
 pref("extensions.blocklist.interval", 86400);
 // Controls what level the blocklist switches from warning about items to forcibly
 // blocking them.
 pref("extensions.blocklist.level", 2);
 pref("extensions.blocklist.url", "https://addons.mozilla.org/blocklist/3/%APP_ID%/%APP_VERSION%/%PRODUCT%/%BUILD_ID%/%BUILD_TARGET%/%LOCALE%/%CHANNEL%/%OS_VERSION%/%DISTRIBUTION%/%DISTRIBUTION_VERSION%/%PING_COUNT%/%TOTAL_PING_COUNT%/%DAYS_SINCE_LAST_PING%/");
 pref("extensions.blocklist.detailsURL", "https://www.mozilla.com/%LOCALE%/blocklist/");
+pref("extensions.blocklist.itemURL", "https://addons.mozilla.org/%LOCALE%/%APP%/blocked/%blockID%");
 
 pref("extensions.update.autoUpdateDefault", true);
 
 // Dictionary download preference
 pref("browser.dictionaries.download.url", "https://addons.mozilla.org/%LOCALE%/firefox/dictionaries/");
 
 // The minimum delay in seconds for the timer to fire.
 // default=2 minutes
@@ -259,17 +260,17 @@ pref("browser.urlbar.clickSelectsAll", f
 #else
 pref("browser.urlbar.clickSelectsAll", true);
 #endif
 #ifdef UNIX_BUT_NOT_MAC
 pref("browser.urlbar.doubleClickSelectsAll", true);
 #else
 pref("browser.urlbar.doubleClickSelectsAll", false);
 #endif
-pref("browser.urlbar.autoFill", true);
+pref("browser.urlbar.autoFill", false);
 // 0: Match anywhere (e.g., middle of words)
 // 1: Match on word boundaries and then try matching anywhere
 // 2: Match only on word boundaries (e.g., after / or .)
 // 3: Match at the beginning of the url or title
 pref("browser.urlbar.matchBehavior", 1);
 pref("browser.urlbar.filter.javascript", true);
 
 // the maximum number of results to show in autocomplete when doing richResults
--- a/browser/base/content/browser-tabview.js
+++ b/browser/base/content/browser-tabview.js
@@ -43,16 +43,17 @@ let TabView = {
   _browserKeyHandlerInitialized: false,
   _isFrameLoading: false,
   _initFrameCallbacks: [],
   PREF_BRANCH: "browser.panorama.",
   PREF_FIRST_RUN: "browser.panorama.experienced_first_run",
   PREF_STARTUP_PAGE: "browser.startup.page",
   PREF_RESTORE_ENABLED_ONCE: "browser.panorama.session_restore_enabled_once",
   VISIBILITY_IDENTIFIER: "tabview-visibility",
+  GROUPS_IDENTIFIER: "tabview-groups",
 
   // ----------
   get windowTitle() {
     delete this.windowTitle;
     let brandBundle = document.getElementById("bundle_brand");
     let brandShortName = brandBundle.getString("brandShortName");
     let title = gNavigatorBundle.getFormattedString("tabView2.title", [brandShortName]);
     return this.windowTitle = title;
@@ -90,24 +91,31 @@ let TabView = {
   init: function TabView_init() {
     if (this.firstUseExperienced) {
       if ((gBrowser.tabs.length - gBrowser.visibleTabs.length) > 0)
         this._setBrowserKeyHandlers();
 
       // ___ visibility
       let sessionstore =
         Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
+
       let data = sessionstore.getWindowValue(window, this.VISIBILITY_IDENTIFIER);
-
       if (data && data == "true") {
         this.show();
       } else {
-        let self = this;
+        try {
+          data = sessionstore.getWindowValue(window, this.GROUPS_IDENTIFIER);
+          if (data) {
+            let parsedData = JSON.parse(data);
+            this.updateGroupNumberBroadcaster(parsedData.totalNumber || 0);
+          }
+        } catch (e) { }
 
-        // if a tab is changed from hidden to unhidden and the iframe is not 
+        let self = this;
+        // if a tab is changed from hidden to unhidden and the iframe is not
         // initialized, load the iframe and setup the tab.
         this._tabShowEventListener = function (event) {
           if (!self._window)
             self._initFrame(function() {
               self._window.UI.onTabSelect(gBrowser.selectedTab);
             });
         };
         gBrowser.tabContainer.addEventListener(
@@ -376,16 +384,24 @@ let TabView = {
     currentSet[alltabsPos] += "," + buttonId;
     currentSet = currentSet.join(",");
     toolbar.currentSet = currentSet;
     toolbar.setAttribute("currentset", currentSet);
     document.persist(toolbar.id, "currentset");
   },
 
   // ----------
+  // Function: updateGroupNumberBroadcaster
+  // Updates the group number broadcaster.
+  updateGroupNumberBroadcaster: function TabView_updateGroupNumberBroadcaster(number) {
+    let groupsNumber = document.getElementById("tabviewGroupsNumber");
+    groupsNumber.setAttribute("groups", number);
+  },
+
+  // ----------
   // Function: enableSessionRestore
   // Enables automatic session restore when the browser is started. Does
   // nothing if we already did that once in the past.
   enableSessionRestore: function UI_enableSessionRestore() {
     if (!this._window || !this.firstUseExperienced)
       return;
 
     // do nothing if we already enabled session restore once
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -2959,21 +2959,16 @@ function FillInHTMLTooltip(tipElement)
     return retVal;
 
   const XLinkNS = "http://www.w3.org/1999/xlink";
 
 
   var titleText = null;
   var XLinkTitleText = null;
   var SVGTitleText = null;
-#ifdef MOZ_SVG
-  var lookingForSVGTitle = true;
-#else
-  var lookingForSVGTitle = false;
-#endif // MOZ_SVG
   var direction = tipElement.ownerDocument.dir;
 
   // If the element is invalid per HTML5 Forms specifications and has no title,
   // show the constraint validation error message.
   if ((tipElement instanceof HTMLInputElement ||
        tipElement instanceof HTMLTextAreaElement ||
        tipElement instanceof HTMLSelectElement ||
        tipElement instanceof HTMLButtonElement) &&
@@ -2984,30 +2979,24 @@ function FillInHTMLTooltip(tipElement)
     titleText = tipElement.validationMessage;
   }
 
   while (!titleText && !XLinkTitleText && !SVGTitleText && tipElement) {
     if (tipElement.nodeType == Node.ELEMENT_NODE) {
       titleText = tipElement.getAttribute("title");
       if ((tipElement instanceof HTMLAnchorElement && tipElement.href) ||
           (tipElement instanceof HTMLAreaElement && tipElement.href) ||
-          (tipElement instanceof HTMLLinkElement && tipElement.href)
-#ifdef MOZ_SVG
-          || (tipElement instanceof SVGAElement && tipElement.hasAttributeNS(XLinkNS, "href"))
-#endif // MOZ_SVG
-          ) {
+          (tipElement instanceof HTMLLinkElement && tipElement.href) ||
+          (tipElement instanceof SVGAElement && tipElement.hasAttributeNS(XLinkNS, "href"))) {
         XLinkTitleText = tipElement.getAttributeNS(XLinkNS, "title");
       }
-      if (lookingForSVGTitle &&
-          !(tipElement instanceof SVGElement &&
-            tipElement.parentNode instanceof SVGElement &&
-            !(tipElement.parentNode instanceof SVGForeignObjectElement))) {
-        lookingForSVGTitle = false;
-      }
-      if (lookingForSVGTitle) {
+      if (tipElement instanceof SVGElement &&
+          tipElement.parentNode instanceof SVGElement &&
+          !(tipElement.parentNode instanceof SVGForeignObjectElement)) {
+        // Looking for SVG title
         let length = tipElement.childNodes.length;
         for (let i = 0; i < length; i++) {
           let childNode = tipElement.childNodes[i];
           if (childNode instanceof SVGTitleElement) {
             SVGTitleText = childNode.textContent;
             break;
           }
         }
@@ -3341,27 +3330,27 @@ const BrowserSearch = {
    * or focuses an existing window, if necessary.
    */
   webSearch: function BrowserSearch_webSearch() {
 #ifdef XP_MACOSX
     if (window.location.href != getBrowserURL()) {
       var win = getTopWin();
       if (win) {
         // If there's an open browser window, it should handle this command
-        win.focus()
+        win.focus();
         win.BrowserSearch.webSearch();
       } else {
         // If there are no open browser windows, open a new one
         function observer(subject, topic, data) {
           if (subject == win) {
             BrowserSearch.webSearch();
             Services.obs.removeObserver(observer, "browser-delayed-startup-finished");
           }
         }
-        win = window.openDialog("chrome://browser/content/", "_blank",
+        win = window.openDialog(getBrowserURL(), "_blank",
                                 "chrome,all,dialog=no", "about:blank");
         Services.obs.addObserver(observer, "browser-delayed-startup-finished", false); 
       }
       return;
     }
 #endif
     var searchBar = this.searchBar;
     if (searchBar && window.fullScreen)
--- a/browser/base/content/pageinfo/pageInfo.js
+++ b/browser/base/content/pageinfo/pageInfo.js
@@ -621,26 +621,24 @@ function grabAll(elem)
         addImage(url.getStringValue(), gStrings.mediaBGImg, gStrings.notSet, elem, true);
     });
   }
 
   // one swi^H^H^Hif-else to rule them all
   if (elem instanceof HTMLImageElement)
     addImage(elem.src, gStrings.mediaImg,
              (elem.hasAttribute("alt")) ? elem.alt : gStrings.notSet, elem, false);
-#ifdef MOZ_SVG
   else if (elem instanceof SVGImageElement) {
     try {
       // Note: makeURLAbsolute will throw if either the baseURI is not a valid URI
       //       or the URI formed from the baseURI and the URL is not a valid URI
       var href = makeURLAbsolute(elem.baseURI, elem.href.baseVal);
       addImage(href, gStrings.mediaImg, "", elem, false);
     } catch (e) { }
   }
-#endif
 #ifdef MOZ_MEDIA
   else if (elem instanceof HTMLVideoElement) {
     addImage(elem.currentSrc, gStrings.mediaVideo, "", elem, false);
   }
   else if (elem instanceof HTMLAudioElement) {
     addImage(elem.currentSrc, gStrings.mediaAudio, "", elem, false);
   }
 #endif
@@ -836,19 +834,17 @@ function makePreview(row)
   var url = gImageView.data[row][COL_IMAGE_ADDRESS];
   var isBG = gImageView.data[row][COL_IMAGE_BG];
   var isAudio = false;
 
   setItemValue("imageurltext", url);
 
   var imageText;
   if (!isBG &&
-#ifdef MOZ_SVG
       !(item instanceof SVGImageElement) &&
-#endif
       !(gDocument instanceof ImageDocument)) {
     imageText = item.title || item.alt;
 
     if (!imageText && !(item instanceof HTMLImageElement))
       imageText = getValueText(item);
   }
   setItemValue("imagetext", imageText);
 
@@ -936,19 +932,17 @@ function makePreview(row)
 
   var newImage = new Image;
   newImage.id = "thepreviewimage";
   var physWidth = 0, physHeight = 0;
   var width = 0, height = 0;
 
   if ((item instanceof HTMLLinkElement || item instanceof HTMLInputElement ||
        item instanceof HTMLImageElement ||
-#ifdef MOZ_SVG
        item instanceof SVGImageElement ||
-#endif
       (item instanceof HTMLObjectElement && /^image\//.test(mimeType)) || isBG) && isProtocolAllowed) {
     newImage.setAttribute("src", url);
     physWidth = newImage.width || 0;
     physHeight = newImage.height || 0;
 
     // "width" and "height" attributes must be set to newImage,
     // even if there is no "width" or "height attribute in item;
     // otherwise, the preview image cannot be displayed correctly.
@@ -958,22 +952,20 @@ function makePreview(row)
     }
     else {
       // the Width and Height of an HTML tag should not be used for its background image
       // (for example, "table" can have "width" or "height" attributes)
       newImage.width = newImage.naturalWidth;
       newImage.height = newImage.naturalHeight;
     }
 
-#ifdef MOZ_SVG
     if (item instanceof SVGImageElement) {
       newImage.width = item.width.baseVal.value;
       newImage.height = item.height.baseVal.value;
     }
-#endif
 
     width = newImage.width;
     height = newImage.height;
 
     document.getElementById("theimagecontainer").collapsed = false
     document.getElementById("brokenimagecontainer").collapsed = true;
   }
 #ifdef MOZ_MEDIA
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -90,17 +90,17 @@
         document.getElementById(this.getAttribute("tabcontainer"));
       </field>
       <field name="tabs" readonly="true">
         this.tabContainer.childNodes;
       </field>
       <property name="visibleTabs" readonly="true">
         <getter><![CDATA[
           return Array.filter(this.tabs, function(tab) {
-            return !tab.hidden && this._removingTabs.indexOf(tab) == -1;
+            return !tab.hidden && !tab.closing;
           }, this);
         ]]></getter>
       </property>
       <field name="mURIFixup" readonly="true">
         Components.classes["@mozilla.org/docshell/urifixup;1"]
                   .getService(Components.interfaces.nsIURIFixup);
       </field>
       <field name="mFaviconService" readonly="true">
@@ -203,17 +203,17 @@
             keyClose.setAttribute("disabled", "true");
 
           // We also want to remove the keyboard shortcut from the file menu
           // when the shortcut is disabled, and bring it back when it's
           // renabled.
           //
           // Fixing bug 630826 could make that happen automatically.
           // Fixing bug 630830 could avoid the ugly hack below.
-          
+
           let closeMenuItem = document.getElementById("menu_close");
           let parentPopup = closeMenuItem.parentNode;
           let nextItem = closeMenuItem.nextSibling;
           let clonedItem = closeMenuItem.cloneNode(true);
 
           parentPopup.removeChild(closeMenuItem);
 
           if (aEnabled)
@@ -958,16 +958,20 @@
                   break;
                 }
 
                 // Focus the location bar if it was previously focused for that tab.
                 // In full screen mode, only bother making the location bar visible
                 // if the tab is a blank one.
                 oldBrowser._urlbarFocused = (gURLBar && gURLBar.focused);
                 if (newBrowser._urlbarFocused && gURLBar) {
+
+                  // Explicitly close the popup if the URL bar retains focus
+                  gURLBar.closePopup();
+
                   if (!window.fullScreen) {
                     gURLBar.focus();
                     break;
                   } else if (isTabEmpty(this.mCurrentTab)) {
                     focusAndSelectUrlBar();
                     break;
                   }
                 }
@@ -994,17 +998,17 @@
             }
           ]]>
         </body>
       </method>
 
       <method name="_tabAttrModified">
         <parameter name="aTab"/>
         <body><![CDATA[
-          if (this._removingTabs.indexOf(aTab) > -1)
+          if (aTab.closing)
             return;
 
           // This event should be dispatched when any of these attributes change:
           // label, crop, busy, image, selected
           var event = document.createEvent("Events");
           event.initEvent("TabAttrModified", true, false);
           aTab.dispatchEvent(event);
         ]]></body>
@@ -1450,17 +1454,17 @@
             if (aParams) {
               var animate = aParams.animate;
               var byMouse = aParams.byMouse;
             }
 
             // Handle requests for synchronously removing an already
             // asynchronously closing tab.
             if (!animate &&
-                this._removingTabs.indexOf(aTab) > -1) {
+                aTab.closing) {
               this._endRemoveTab(aTab);
               return;
             }
 
             var isLastTab = (this.tabs.length - this._removingTabs.length == 1);
 
             if (!this._beginRemoveTab(aTab, false, null, true))
               return;
@@ -1504,17 +1508,17 @@
 
       <method name="_beginRemoveTab">
         <parameter name="aTab"/>
         <parameter name="aTabWillBeMoved"/>
         <parameter name="aCloseWindowWithLastTab"/>
         <parameter name="aCloseWindowFastpath"/>
         <body>
           <![CDATA[
-            if (this._removingTabs.indexOf(aTab) > -1 || this._windowIsClosing)
+            if (aTab.closing || this._windowIsClosing)
               return false;
 
             var browser = this.getBrowserForTab(aTab);
 
             if (!aTabWillBeMoved) {
               let ds = browser.docShell;
               if (ds && ds.contentViewer && !ds.contentViewer.permitUnload())
                 return false;
@@ -1534,16 +1538,17 @@
                   aCloseWindowFastpath &&
                   this._removingTabs.length == 0 &&
                   (this._windowIsClosing = window.closeWindow(true)))
                 return null;
 
               newTab = true;
             }
 
+            aTab.closing = true;
             this._removingTabs.push(aTab);
             if (newTab)
               this.addTab("about:blank", {skipAnimation: true});
             else
               this.tabContainer.updateVisibility();
 
             // We're committed to closing the tab now.
             // Dispatch a notification.
@@ -1702,28 +1707,28 @@
         <parameter name="aTab"/>
         <body>
           <![CDATA[
             if (this.mCurrentTab != aTab)
               return;
 
             if (aTab.owner &&
                 !aTab.owner.hidden &&
-                this._removingTabs.indexOf(aTab.owner) == -1 &&
+                !aTab.owner.closing &&
                 Services.prefs.getBoolPref("browser.tabs.selectOwnerOnClose")) {
               this.selectedTab = aTab.owner;
               return;
             }
 
             // Switch to a visible tab unless there aren't any others remaining
             let remainingTabs = this.visibleTabs;
             let numTabs = remainingTabs.length;
             if (numTabs == 0 || numTabs == 1 && remainingTabs[0] == aTab) {
               remainingTabs = Array.filter(this.tabs, function(tab) {
-                return this._removingTabs.indexOf(tab) == -1;
+                return !tab.closing;
               }, this);
             }
 
             // Try to find a remaining tab that comes after the given tab
             var tab = aTab;
             do {
               tab = tab.nextSibling;
             } while (tab && remainingTabs.indexOf(tab) == -1);
@@ -1928,17 +1933,17 @@
         </body>
       </method>
 
       <method name="hideTab">
         <parameter name="aTab"/>
         <body>
         <![CDATA[
           if (!aTab.hidden && !aTab.pinned && !aTab.selected &&
-              this._removingTabs.indexOf(aTab) == -1) {
+              !aTab.closing) {
             aTab.setAttribute("hidden", "true");
             this.tabContainer.adjustTabstrip();
             let event = document.createEvent("Events");
             event.initEvent("TabHide", true, false);
             aTab.dispatchEvent(event);
           }
         ]]>
         </body>
@@ -2943,18 +2948,17 @@
           }
         ]]></body>
       </method>
 
       <method name="_positionPinnedTabs">
         <body><![CDATA[
           var numPinned = this.tabbrowser._numPinnedTabs;
           var doPosition = this.getAttribute("overflow") == "true" &&
-                           numPinned > 0 &&
-                           numPinned < this.tabbrowser.visibleTabs.length;
+                           numPinned > 0;
 
           if (doPosition) {
             this.setAttribute("positionpinnedtabs", "true");
 
             let scrollButtonWidth = this.mTabstrip._scrollButtonDown.scrollWidth;
             let paddingStart = this.mTabstrip.scrollboxPaddingStart;
             let width = 0;
 
@@ -3072,17 +3076,17 @@
 
       <method name="_getDropIndex">
         <parameter name="event"/>
         <body><![CDATA[
           var tabs = this.childNodes;
           var tab = this._getDragTargetTab(event);
           if (window.getComputedStyle(this, null).direction == "ltr") {
             for (let i = tab ? tab._tPos : 0; i < tabs.length; i++)
-              if (event.screenX < tabs[i].boxObject.screenX + tabs[i].boxObject.width / 2) 
+              if (event.screenX < tabs[i].boxObject.screenX + tabs[i].boxObject.width / 2)
                 return i;
           } else {
             for (let i = tab ? tab._tPos : 0; i < tabs.length; i++)
               if (event.screenX > tabs[i].boxObject.screenX + tabs[i].boxObject.width / 2)
                 return i;
           }
           return tabs.length;
         ]]></body>
@@ -3166,17 +3170,17 @@
           this.mTabstrip._updateScrollButtonsDisabledState();
         ]]></body>
       </method>
 
       <method name="_canAdvanceToTab">
         <parameter name="aTab"/>
         <body>
         <![CDATA[
-          return this.tabbrowser._removingTabs.indexOf(aTab) == -1;
+          return !aTab.closing;
         ]]>
         </body>
       </method>
 
       <!-- Deprecated stuff, implemented for backwards compatibility. -->
       <property name="mTabstripClosebutton" readonly="true"
                 onget="return document.getElementById('tabs-closebutton');"/>
       <property name="mAllTabsPopup" readonly="true"
@@ -3189,17 +3193,17 @@
       <handler event="transitionend"><![CDATA[
         if (event.propertyName != "max-width")
           return;
 
         var tab = event.target;
 
         if (tab.getAttribute("fadein") == "true")
           this._handleNewTab(tab);
-        else if (this.tabbrowser._removingTabs.indexOf(tab) > -1)
+        else if (tab.closing)
           this.tabbrowser._endRemoveTab(tab);
       ]]></handler>
 
       <handler event="dblclick"><![CDATA[
 #ifdef MOZ_WIDGET_GTK2
         // Disable this on GTK2 when the menubar is draggable, since (a)
         // the menubar and tabbbar have unified appearance and should
         // thus not have different behavior (though this condition alone
@@ -3332,17 +3336,17 @@
             return;
           }
         }
 
         var newIndex = this._getDropIndex(event);
         var scrollRect = tabStrip.scrollClientRect;
         var rect = this.getBoundingClientRect();
         var minMargin = scrollRect.left - rect.left;
-        var maxMargin = Math.min(minMargin + scrollRect.width, 
+        var maxMargin = Math.min(minMargin + scrollRect.width,
                                  scrollRect.right);
         if (!ltr)
           [minMargin, maxMargin] = [this.clientWidth - maxMargin,
                                     this.clientWidth - minMargin];
         var newMargin;
         if (pixelsToScroll) {
           // if we are scrolling, put the drop indicator at the edge
           // so that it doesn't jump while scrolling
@@ -3630,16 +3634,17 @@
         <getter>
           return this.getAttribute("hidden") == "true";
         </getter>
       </property>
 
       <field name="mOverCloseButton">false</field>
       <field name="mCorrespondingMenuitem">null</field>
       <field name="_fullyOpen">false</field>
+      <field name="closing">false</field>
     </implementation>
 
     <handlers>
       <handler event="mouseover">
         var anonid = event.originalTarget.getAttribute("anonid");
         if (anonid == "close-button")
           this.mOverCloseButton = true;
       </handler>
@@ -3741,28 +3746,28 @@
             let curTab = this.childNodes[i].tab;
             if (!curTab) // "Tab Groups" menuitem and its menuseparator
               continue;
             let curTabBO = curTab.boxObject;
             if (!curTabBO) // "Tabs From Other Computers" menuitem
               continue;
             if (curTabBO.screenX >= tabstripBO.screenX &&
                 curTabBO.screenX + curTabBO.width <= tabstripBO.screenX + tabstripBO.width)
-              this.childNodes[i].setAttribute("tabIsVisible", "true"); 
+              this.childNodes[i].setAttribute("tabIsVisible", "true");
             else
               this.childNodes[i].removeAttribute("tabIsVisible");
           }
         ]]></body>
       </method>
 
       <method name="_createTabMenuItem">
         <parameter name="aTab"/>
         <body><![CDATA[
           var menuItem = document.createElementNS(
-            "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", 
+            "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul",
             "menuitem");
 
           menuItem.setAttribute("class", "menuitem-iconic alltabs-item menuitem-with-favicon");
 
           this._setMenuitemAttributes(menuItem, aTab);
 
           // Keep some attributes of the menuitem in sync with its
           // corresponding tab (e.g. the tab label)
--- a/browser/base/content/tabview/groupitems.js
+++ b/browser/base/content/tabview/groupitems.js
@@ -2102,17 +2102,19 @@ let GroupItems = {
   // Function: _save
   // Saves GroupItems state.
   _save: function GroupItems__save() {
     if (!this._inited) // too soon to save now
       return;
 
     let activeGroupId = this._activeGroupItem ? this._activeGroupItem.id : null;
     Storage.saveGroupItemsData(
-      gWindow, { nextID: this.nextID, activeGroupId: activeGroupId });
+      gWindow,
+      { nextID: this.nextID, activeGroupId: activeGroupId,
+        totalNumber: this.groupItems.length });
   },
 
   // ----------
   // Function: getBoundingBox
   // Given an array of DOM elements, returns a <Rect> with (roughly) the union of their locations.
   getBoundingBox: function GroupItems_getBoundingBox(els) {
     var bounds = [iQ(el).bounds() for each (el in els)];
     var left   = Math.min.apply({},[ b.left   for each (b in bounds) ]);
--- a/browser/base/content/tabview/tabitems.js
+++ b/browser/base/content/tabview/tabitems.js
@@ -1553,11 +1553,11 @@ TabCanvas.prototype = {
     let top = win.scrollY;
 
     return new Rect(left, top, width, height);
   },
 
   // ----------
   // Function: toImageData
   toImageData: function TabCanvas_toImageData() {
-    return this.canvas.toDataURL("image/png", "");
+    return this.canvas.toDataURL("image/png");
   }
 };
--- a/browser/base/content/tabview/ui.js
+++ b/browser/base/content/tabview/ui.js
@@ -951,22 +951,21 @@ let UI = {
       var index = this._reorderTabItemsOnShow.indexOf(groupItem);
       if (index == -1)
         this._reorderTabItemsOnShow.push(groupItem);
     }
   },
   
   // ----------
   updateTabButton: function UI__updateTabButton() {
-    let groupsNumber = gWindow.document.getElementById("tabviewGroupsNumber");
     let exitButton = document.getElementById("exit-button");
     let numberOfGroups = GroupItems.groupItems.length;
 
-    groupsNumber.setAttribute("groups", numberOfGroups);
     exitButton.setAttribute("groups", numberOfGroups);
+    gTabView.updateGroupNumberBroadcaster(numberOfGroups);
   },
 
   // ----------
   // Function: getClosestTab
   // Convenience function to get the next tab closest to the entered position
   getClosestTab: function UI_getClosestTab(tabCenter) {
     let cl = null;
     let clDist;
@@ -990,26 +989,27 @@ let UI = {
 
     [
 #ifdef XP_UNIX
       "quitApplication",
 #endif
 #ifdef XP_MACOSX
       "preferencesCmdMac", "minimizeWindow",
 #endif
-      "newNavigator", "newNavigatorTab", "find"
+      "newNavigator", "newNavigatorTab", "undo", "cut", "copy", "paste", 
+      "selectAll", "find"
      ].forEach(function(key) {
       let element = gWindow.document.getElementById("key_" + key);
       keys[key] = element.getAttribute("key").toLocaleLowerCase().charCodeAt(0);
     });
 
     // for key combinations with shift key, the charCode of upper case letters 
     // are different to the lower case ones so need to handle them differently.
     ["closeWindow", "tabview", "undoCloseTab", "undoCloseWindow",
-     "privatebrowsing"].forEach(function(key) {
+     "privatebrowsing", "redo"].forEach(function(key) {
       let element = gWindow.document.getElementById("key_" + key);
       keys[key] = element.getAttribute("key").toLocaleUpperCase().charCodeAt(0);
     });
 
     delete this._browserKeys;
     this._browserKeys = keys;
   },
 
@@ -1038,29 +1038,35 @@ let UI = {
 #endif
           let preventDefault = true;
           if (evt.shiftKey) {
             switch (evt.charCode) {
               case self._browserKeys.privatebrowsing:
               case self._browserKeys.undoCloseTab:
               case self._browserKeys.undoCloseWindow:
               case self._browserKeys.closeWindow:
+              case self._browserKeys.redo:
                 preventDefault = false;
                 break;
               case self._browserKeys.tabview:
                 self.exit();
                 break;
             }
           } else {
             switch (evt.charCode) {
               case self._browserKeys.find:
                 self.enableSearch();
                 break;
               case self._browserKeys.newNavigator:
               case self._browserKeys.newNavigatorTab:
+              case self._browserKeys.undo:
+              case self._browserKeys.cut:
+              case self._browserKeys.copy:
+              case self._browserKeys.paste:
+              case self._browserKeys.selectAll:
                 preventDefault = false;
                 break;
 #ifdef XP_UNIX
               case self._browserKeys.quitApplication:
                 preventDefault = false;
                 break;
 #endif
 #ifdef XP_MACOSX
--- a/browser/base/content/test/Makefile.in
+++ b/browser/base/content/test/Makefile.in
@@ -166,16 +166,17 @@ endif
                  browser_bug597218.js \
                  browser_bug598923.js \
                  browser_bug599325.js \
                  browser_bug609700.js \
                  browser_bug616836.js \
                  browser_bug623893.js \
                  browser_bug624734.js \
                  browser_bug647886.js \
+                 browser_bug655584.js \
                  browser_findbarClose.js \
                  browser_contextSearchTabPosition.js \
                  browser_ctrlTab.js \
                  browser_customize_popupNotification.js \
                  browser_disablechrome.js \
                  browser_discovery.js \
                  browser_duplicateIDs.js \
                  browser_gestureSupport.js \
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/browser_bug655584.js
@@ -0,0 +1,23 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+// Bug 655584 - awesomebar suggestions don't update after tab is closed
+
+function test() {
+  var tab1 = gBrowser.addTab();
+  var tab2 = gBrowser.addTab();
+
+  // When urlbar in a new tab is focused, and a tab switch occurs,
+  // the urlbar popup should be closed
+  gBrowser.selectedTab = tab2;
+  gURLBar.focus(); // focus the urlbar in the tab we will switch to
+  gBrowser.selectedTab = tab1;
+  gURLBar.openPopup();
+  gBrowser.selectedTab = tab2;
+  ok(!gURLBar.popupOpen, "urlbar focused in tab to switch to, close popup");
+  
+  // cleanup
+  gBrowser.removeCurrentTab();
+  gBrowser.removeCurrentTab();
+}
--- a/browser/base/content/test/browser_urlHighlight.js
+++ b/browser/base/content/test/browser_urlHighlight.js
@@ -49,16 +49,19 @@ function test() {
   testVal("<http://>mozilla.org</file.ext>");
   testVal("<http://>mozilla.org</sub/file.ext>");
   testVal("<http://>mozilla.org</sub/file.ext?foo>");
   testVal("<http://>mozilla.org</sub/file.ext?foo&bar>");
   testVal("<http://>mozilla.org</sub/file.ext?foo&bar#top>");
 
   testVal("<http://sub.>mozilla.org<:666/file.ext>");
 
+  testVal("<http://>[fe80::222:19ff:fe11:8c76]</file.ext>");
+  testVal("<http://user:pass@>[fe80::222:19ff:fe11:8c76]<:666/file.ext>");
+
   testVal("mailto:admin@mozilla.org");
   testVal("gopher://mozilla.org/");
   testVal("about:config");
 
   Services.prefs.setBoolPref(prefname, false);
 
   testVal("http://mozilla.org/");
 }
--- a/browser/base/content/test/tabview/Makefile.in
+++ b/browser/base/content/test/tabview/Makefile.in
@@ -110,16 +110,17 @@ include $(topsrcdir)/config/rules.mk
                  browser_tabview_bug625269.js \
                  browser_tabview_bug625424.js \
                  browser_tabview_bug625666.js \
                  browser_tabview_bug626368.js \
                  browser_tabview_bug626525.js \
                  browser_tabview_bug626791.js \
                  browser_tabview_bug627288.js \
                  browser_tabview_bug627736.js \
+                 browser_tabview_bug628061.js \
                  browser_tabview_bug628165.js \
                  browser_tabview_bug628270.js \
                  browser_tabview_bug629189.js \
                  browser_tabview_bug629195.js \
                  browser_tabview_bug630102.js \
                  browser_tabview_bug630157.js \
                  browser_tabview_bug631662.js \
                  browser_tabview_bug631752.js \
--- a/browser/base/content/test/tabview/browser_tabview_bug624265.js
+++ b/browser/base/content/test/tabview/browser_tabview_bug624265.js
@@ -14,25 +14,16 @@ function test() {
   let assertOneSingleGroupItem = function () {
     is(getContentWindow().GroupItems.groupItems.length, 1, 'There is one single groupItem');
   }
 
   let assertNumberOfVisibleTabs = function (numTabs) {
     is(gBrowser.visibleTabs.length, numTabs, 'There should be ' + numTabs + ' visible tabs');
   }
 
-  let restoreTab = function (callback) {
-    let tab = undoCloseTab(0);
-    
-    tab._tabViewTabItem.addSubscriber(tab, 'reconnected', function () {
-      tab._tabViewTabItem.removeSubscriber(tab, 'reconnected');
-      afterAllTabsLoaded(callback);
-    });
-  }
-
   let next = function () {
     while (gBrowser.tabs.length-1)
       gBrowser.removeTab(gBrowser.tabs[1]);
 
     hideTabView(function () {
       let callback = tests.shift();
 
       if (!callback)
@@ -81,17 +72,17 @@ function test() {
   }
 
   // ----------
   // [623792] duplicating tabs via middle click on forward/back buttons
   let testBackForwardDuplicateTab = function () {
     let tab = gBrowser.loadOneTab('http://mochi.test:8888/#1', {inBackground: true});
     gBrowser.selectedTab = tab;
 
-    let continueTest = function () {
+    afterAllTabsLoaded(function () {
       tab.linkedBrowser.loadURI('http://mochi.test:8888/#2');
 
       afterAllTabsLoaded(function () {
         ok(gBrowser.canGoBack, 'browser can go back in history');
         BrowserBack({button: 1});
 
         afterAllTabsLoaded(function () {
           assertNumberOfVisibleTabs(3);
@@ -101,23 +92,17 @@ function test() {
 
           afterAllTabsLoaded(function () {
             assertNumberOfVisibleTabs(4);
             assertOneSingleGroupItem();
             next();
           });
         });
       });
-    }
-
-    // The executeSoon() call is really needed here because there's probably
-    // some callback waiting to be fired after gBrowser.loadOneTab(). After
-    // that the browser is in a state where loadURI() will create a new entry
-    // in the session history (that is vital for back/forward functionality).
-    afterAllTabsLoaded(function () executeSoon(continueTest));
+    });
   }
 
   // ----------
   // [624102] check state after return from private browsing
   let testPrivateBrowsing = function () {
     gBrowser.loadOneTab('http://mochi.test:8888/#1', {inBackground: true});
     gBrowser.loadOneTab('http://mochi.test:8888/#2', {inBackground: true});
 
@@ -151,50 +136,35 @@ function test() {
   // tests for #624102
   tests.push(testPrivateBrowsing);
 
   loadTabView(next);
 }
 
 // ----------
 function loadTabView(callback) {
-  window.addEventListener('tabviewshown', function () {
-    window.removeEventListener('tabviewshown', arguments.callee, false);
-
-    hideTabView(function () {
-      window.removeEventListener('tabviewhidden', arguments.callee, false);
-      callback();
-    });
-  }, false);
-
-  TabView.show();
-}
-
-// ----------
-function hideTabView(callback) {
-  if (!TabView.isVisible())
-    return callback();
-
-  window.addEventListener('tabviewhidden', function () {
-    window.removeEventListener('tabviewhidden', arguments.callee, false);
-    callback();
-  }, false);
-
-  TabView.hide();
+  showTabView(function () {
+    hideTabView(callback);
+  });
 }
 
 // ----------
 function enterAndLeavePrivateBrowsing(callback) {
+  togglePrivateBrowsing(function () {
+    togglePrivateBrowsing(callback);
+  });
+}
+
+// ----------
+function togglePrivateBrowsing(callback) {
+  let topic = "private-browsing-transition-complete";
+
   function pbObserver(aSubject, aTopic, aData) {
-    if (aTopic != "private-browsing-transition-complete")
+    if (aTopic != topic)
       return;
 
-    if (pb.privateBrowsingEnabled)
-      pb.privateBrowsingEnabled = false;
-    else {
-      Services.obs.removeObserver(pbObserver, "private-browsing-transition-complete");
-      afterAllTabsLoaded(function () executeSoon(callback));
-    }
+    Services.obs.removeObserver(pbObserver, topic, false);
+    afterAllTabsLoaded(callback);
   }
 
-  Services.obs.addObserver(pbObserver, "private-browsing-transition-complete", false);
-  pb.privateBrowsingEnabled = true;
+  Services.obs.addObserver(pbObserver, topic, false);
+  pb.privateBrowsingEnabled = !pb.privateBrowsingEnabled;
 }
new file mode 100644
--- /dev/null
+++ b/browser/base/content/test/tabview/browser_tabview_bug628061.js
@@ -0,0 +1,37 @@
+/* Any copyright is dedicated to the Public Domain.
+   http://creativecommons.org/publicdomain/zero/1.0/ */
+
+const ss = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);
+
+let state = {
+  windows: [{
+    tabs: [{
+      entries: [{ url: "about:blank" }],
+      hidden: true,
+      extData: {"tabview-tab": '{"url":"about:blank","groupID":1,"bounds":{"left":20,"top":20,"width":20,"height":20}}'}
+    },{
+      entries: [{ url: "about:blank" }],
+      hidden: false,
+      extData: {"tabview-tab": '{"url":"about:blank","groupID":2,"bounds":{"left":20,"top":20,"width":20,"height":20}}'},
+    }],
+    selected: 2,
+    extData: {
+      "tabview-groups": '{"nextID":3,"activeGroupId":2, "totalNumber":2}',
+      "tabview-group":
+        '{"1":{"bounds":{"left":15,"top":5,"width":280,"height":232},"id":1},' +
+        '"2":{"bounds":{"left":309,"top":5,"width":267,"height":226},"id":2}}'
+    }
+  }]
+};
+
+function test() {
+  waitForExplicitFinish();
+
+  newWindowWithState(state, function(win) {
+    registerCleanupFunction(function() win.close());
+
+    is(win.document.getElementById("tabviewGroupsNumber").getAttribute("groups"), 
+       "2", "There are two groups");
+    waitForFocus(finish);
+  });
+}
--- a/browser/base/content/test/tabview/head.js
+++ b/browser/base/content/test/tabview/head.js
@@ -100,17 +100,17 @@ function afterAllTabsLoaded(callback, wi
   let stillToLoad = 0;
   let restoreHiddenTabs = Services.prefs.getBoolPref(
                           "browser.sessionstore.restore_hidden_tabs");
 
   function onLoad() {
     this.removeEventListener("load", onLoad, true);
     stillToLoad--;
     if (!stillToLoad)
-      callback();
+      executeSoon(callback);
   }
 
   for (let a = 0; a < win.gBrowser.tabs.length; a++) {
     let tab = win.gBrowser.tabs[a];
     let browser = tab.linkedBrowser;
 
     let isRestorable = !(tab.hidden && !restoreHiddenTabs &&
                          browser.__SS_restoreState &&
@@ -296,8 +296,26 @@ function newWindowWithState(state, callb
   whenWindowLoaded(win, function () {
     ss.setWindowState(win, JSON.stringify(state), true);
   });
 
   whenWindowStateReady(win, function () {
     afterAllTabsLoaded(function () callback(win), win);
   });
 }
+
+// ----------
+function restoreTab(callback, index, win) {
+  win = win || window;
+
+  let tab = win.undoCloseTab(index || 0);
+  let tabItem = tab._tabViewTabItem;
+
+  if (tabItem._reconnected) {
+    afterAllTabsLoaded(callback, win);
+    return;
+  }
+
+  tab._tabViewTabItem.addSubscriber(tab, "reconnected", function onReconnected() {
+    tab._tabViewTabItem.removeSubscriber(tab, "reconnected");
+    afterAllTabsLoaded(callback, win);
+  });
+}
--- a/browser/base/content/urlbarBindings.xml
+++ b/browser/base/content/urlbarBindings.xml
@@ -187,17 +187,17 @@
             return;
 
           let controller = this.editor.selectionController;
           let selection = controller.getSelection(controller.SELECTION_URLSECONDARY);
           selection.removeAllRanges();
 
           let textNode = this.editor.rootElement.firstChild;
           let value = textNode.textContent;
-          let matchedURL = value.match(/^((?:http|https|ftp):\/\/(?:[^\/]+@)?)([^\/:]+)/);
+          let matchedURL = value.match(/^((?:http|https|ftp):\/\/(?:[^\/]+@)?)(.+?)(?::\d+)?(?:\/|$)/);
           if (!matchedURL)
             return;
 
           let [, preDomain, domain] = matchedURL;
           let baseDomain = domain;
           try {
             baseDomain = Services.eTLD.getBaseDomainFromHost(domain);
           } catch (e) {}
--- a/browser/components/BrowserComponents.manifest
+++ b/browser/components/BrowserComponents.manifest
@@ -1,18 +1,16 @@
 # nsBrowserContentHandler.js
 component {5d0ce354-df01-421a-83fb-7ead0990c24e} nsBrowserContentHandler.js application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/browser/clh;1 {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 component {47cd0651-b1be-4a0f-b5c4-10e5a573ef71} nsBrowserContentHandler.js application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/browser/final-clh;1 {47cd0651-b1be-4a0f-b5c4-10e5a573ef71} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=text/html {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=application/vnd.mozilla.xul+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
-#ifdef MOZ_SVG
 contract @mozilla.org/uriloader/content-handler;1?type=image/svg+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
-#endif
 contract @mozilla.org/uriloader/content-handler;1?type=text/rdf {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=text/xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=application/xhtml+xml {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=text/css {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=text/plain {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=image/gif {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=image/jpeg {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
 contract @mozilla.org/uriloader/content-handler;1?type=image/jpg {5d0ce354-df01-421a-83fb-7ead0990c24e} application={ec8030f7-c20a-464f-9b0e-13a3a9e97384}
--- a/browser/components/places/content/places.xul
+++ b/browser/components/places/content/places.xul
@@ -216,16 +216,29 @@
                       label="&cmd.new_folder.label;"
                       accesskey="&cmd.new_folder.accesskey;"/>
             <menuitem id="newseparator"
                       command="placesCmd_new:separator"
                       label="&cmd.new_separator.label;"
                       accesskey="&cmd.new_separator.accesskey;"/>
 
 #ifndef XP_MACOSX
+            <menuseparator id="orgUndoSeparator"/>
+
+            <menuitem id="orgUndo"
+                      command="cmd_undo"
+                      label="&undoCmd.label;"
+                      key="key_undo"
+                      accesskey="&undoCmd.accesskey;"/>
+            <menuitem id="orgRedo"
+                      command="cmd_redo"
+                      label="&redoCmd.label;"
+                      key="key_redo"
+                      accesskey="&redoCmd.accesskey;"/>
+
             <menuseparator id="orgCutSeparator"/>
 
             <menuitem id="orgCut"
                       command="cmd_cut"
                       label="&cutCmd.label;"
                       key="key_cut"
                       accesskey="&cutCmd.accesskey;"
                       selection="separator|link|folder|mixed"/>
@@ -236,47 +249,44 @@
                       accesskey="&copyCmd.accesskey;"
                       selection="separator|link|folder|mixed"/>
             <menuitem id="orgPaste"
                       command="cmd_paste"
                       label="&pasteCmd.label;"
                       key="key_paste"
                       accesskey="&pasteCmd.accesskey;"
                       selection="mutable"/>
-            <menuitem id="orgUndo"
-                      command="cmd_undo"
-                      label="&undoCmd.label;"
-                      key="key_undo"
-                      accesskey="&undoCmd.accesskey;"/>
-            <menuitem id="orgRedo"
-                      command="cmd_redo"
-                      label="&redoCmd.label;"
-                      key="key_redo"
-                      accesskey="&redoCmd.accesskey;"/>
+            <menuitem id="orgDelete"
+                      command="cmd_delete"
+                      label="&deleteCmd.label;"
+                      key="key_delete"
+                      accesskey="&deleteCmd.accesskey;"/>
 
             <menuseparator id="selectAllSeparator"/>
-            
+
             <menuitem id="orgSelectAll"
                       command="cmd_selectAll"
                       label="&selectAllCmd.label;"
                       key="key_selectAll"
                       accesskey="&selectAllCmd.accesskey;"/>
 
 #endif
             <menuseparator id="orgMoveSeparator"/>
+
             <menuitem id="orgMoveBookmarks"
                       command="placesCmd_moveBookmarks"
                       label="&cmd.moveBookmarks.label;"
                       accesskey="&cmd.moveBookmarks.accesskey;"/>
+#ifdef XP_MACOSX
             <menuitem id="orgDelete"
                       command="cmd_delete"
                       label="&deleteCmd.label;"
                       key="key_delete"
                       accesskey="&deleteCmd.accesskey;"/>
-#ifndef XP_MACOSX
+#else
             <menuseparator id="orgCloseSeparator"/>
 
             <menuitem id="orgClose"
                       key="placesKey_close" 
                       label="&file.close.label;"
                       accesskey="&file.close.accesskey;" 
                       oncommand="close();"/>
 #endif
@@ -364,141 +374,137 @@
                oncommand="PlacesSearchBox.search(this.value);"
                collection="bookmarks">
       </textbox>
     </toolbar>
   </toolbox>
 
   <hbox flex="1" id="placesView">
     <tree id="placesList"
-          class="placesTree"
+          class="plain placesTree"
           type="places"
           hidecolumnpicker="true" context="placesContext"
           onselect="PlacesOrganizer.onPlaceSelected(true);"
           onclick="PlacesOrganizer.onTreeClick(event);"
-          onfocus="PlacesOrganizer.onTreeFocus(event);"          
+          onfocus="PlacesOrganizer.onTreeFocus(event);"
           seltype="single"
           persist="width"
           width="200"
           minwidth="100"
           maxwidth="400">
       <treecols>
         <treecol anonid="title" flex="1" primary="true" hideheader="true"/>
       </treecols>
       <treechildren flex="1"/>
     </tree>
     <splitter collapse="none" persist="state"></splitter>
     <vbox id="contentView" flex="4">
-      <deck id="contentDeck" flex="1">
-        <vbox id="defaultView" flex="1">
-          <vbox id="searchModifiers" hidden="true">
-            <toolbar id="organizerScopeBar" class="chromeclass-toolbar" align="center">
-              <label id="scopeBarTitle" value="&search.in.label;"/>
-              <toolbarbutton id="scopeBarAll" type="radio" group="scopeBar"
-                             oncommand="PlacesQueryBuilder.onScopeSelected(this);"
-                             label="&search.scopeBookmarks.label;"
-                             accesskey="&search.scopeBookmarks.accesskey;"/>
-              <!--
-              <toolbarbutton id="scopeBarDownloads" type="radio" group="scopeBar"
-                             oncommand="PlacesQueryBuilder.onScopeSelected(this);"
-                             label="&search.scopeDownloads.label;"
-                             accesskey="&search.scopeDownloads.accesskey;"/>
-              -->
-              <toolbarbutton id="scopeBarHistory" type="radio" group="scopeBar"
-                             oncommand="PlacesQueryBuilder.onScopeSelected(this);"
-                             label="&search.scopeHistory.label;"
-                             accesskey="&search.scopeHistory.accesskey;"/>
-              <toolbarbutton id="scopeBarFolder" type="radio" group="scopeBar"
-                             oncommand="PlacesQueryBuilder.onScopeSelected(this);"
-                             accesskey="&search.scopeFolder.accesskey;"
-                             emptytitle="&search.scopeFolder.label;" flex="1"/>
-              <!-- The folder scope button should flex but not take up more room
-                   than its label needs.  The only simple way to do that is to
-                   set a really big flex on the spacer, e.g., 2^31 - 1. -->
-              <spacer flex="2147483647"/>
-              <button id="saveSearch" class="small" 
-                       label="&saveSearch.label;" accesskey="&saveSearch.accesskey;"
-                       command="OrganizerCommand_search:save"/>
-            </toolbar>
+      <toolbox id="searchModifiers" hidden="true">
+        <toolbar id="organizerScopeBar" class="chromeclass-toolbar" align="center">
+          <label id="scopeBarTitle" value="&search.in.label;"/>
+          <toolbarbutton id="scopeBarAll" class="small-margin"
+                         type="radio" group="scopeBar"
+                         oncommand="PlacesQueryBuilder.onScopeSelected(this);"
+                         label="&search.scopeBookmarks.label;"
+                         accesskey="&search.scopeBookmarks.accesskey;"/>
+          <!--
+          <toolbarbutton id="scopeBarDownloads" class="small-margin"
+                         type="radio" group="scopeBar"
+                         oncommand="PlacesQueryBuilder.onScopeSelected(this);"
+                         label="&search.scopeDownloads.label;"
+                         accesskey="&search.scopeDownloads.accesskey;"/>
+          -->
+          <toolbarbutton id="scopeBarHistory" class="small-margin"
+                         type="radio" group="scopeBar"
+                         oncommand="PlacesQueryBuilder.onScopeSelected(this);"
+                         label="&search.scopeHistory.label;"
+                         accesskey="&search.scopeHistory.accesskey;"/>
+          <toolbarbutton id="scopeBarFolder" class="small-margin"
+                         type="radio" group="scopeBar"
+                         oncommand="PlacesQueryBuilder.onScopeSelected(this);"
+                         accesskey="&search.scopeFolder.accesskey;"
+                         emptytitle="&search.scopeFolder.label;" flex="1"/>
+          <!-- The folder scope button should flex but not take up more room
+                than its label needs.  The only simple way to do that is to
+                set a really big flex on the spacer, e.g., 2^31 - 1. -->
+          <spacer flex="2147483647"/>
+          <button id="saveSearch" class="small-margin"
+                  label="&saveSearch.label;" accesskey="&saveSearch.accesskey;"
+                  command="OrganizerCommand_search:save"/>
+        </toolbar>
+      </toolbox>
+      <tree id="placeContent"
+            class="plain placesTree"
+            context="placesContext"
+            hidecolumnpicker="true"
+            flex="1"
+            type="places"
+            flatList="true"
+            enableColumnDrag="true"
+            onkeypress="if (event.keyCode == KeyEvent.DOM_VK_RETURN) PlacesOrganizer.openSelectedNode(event);"
+            onopenflatcontainer="PlacesOrganizer.openFlatContainer(aContainer);"
+            onselect="PlacesOrganizer.onContentTreeSelect();"
+            onfocus="PlacesOrganizer.onTreeFocus(event);"
+            onclick="PlacesOrganizer.onTreeClick(event);">
+        <treecols id="placeContentColumns" context="placesColumnsContext">
+          <treecol label="&col.name.label;" id="placesContentTitle" anonid="title" flex="5" primary="true" ordinal="1" 
+                    persist="width hidden ordinal sortActive sortDirection"/>
+          <splitter class="tree-splitter"/>
+          <treecol label="&col.tags.label;" id="placesContentTags" anonid="tags" flex="2"
+                    persist="width hidden ordinal sortActive sortDirection"/>
+          <splitter class="tree-splitter"/>
+          <treecol label="&col.url.label;" id="placesContentUrl" anonid="url" flex="5"
+                    persist="width hidden ordinal sortActive sortDirection"/>
+          <splitter class="tree-splitter"/>
+          <treecol label="&col.lastvisit.label;" id="placesContentDate" anonid="date" flex="1" hidden="true"
+                    persist="width hidden ordinal sortActive sortDirection"/>
+          <splitter class="tree-splitter"/>
+          <treecol label="&col.visitcount.label;" id="placesContentVisitCount" anonid="visitCount" flex="1" hidden="true"
+                    persist="width hidden ordinal sortActive sortDirection"/>
+          <splitter class="tree-splitter"/>
+          <treecol label="&col.keyword.label;" id="placesContentKeyword" anonid="keyword" flex="1" hidden="true"
+                    persist="width hidden ordinal sortActive sortDirection"/>
+          <splitter class="tree-splitter"/>
+          <treecol label="&col.description.label;" id="placesContentDescription" anonid="description" flex="1" hidden="true"
+                    persist="width hidden ordinal sortActive sortDirection"/>
+          <splitter class="tree-splitter"/>
+          <treecol label="&col.dateadded.label;" id="placesContentDateAdded" anonid="dateAdded" flex="1" hidden="true"
+                    persist="width hidden ordinal sortActive sortDirection"/>
+          <splitter class="tree-splitter"/>
+          <treecol label="&col.lastmodified.label;" id="placesContentLastModified" anonid="lastModified" flex="1" hidden="true"
+                    persist="width hidden ordinal sortActive sortDirection"/>
+        </treecols>
+        <treechildren flex="1"/>
+      </tree>
+      <deck id="detailsDeck" style="height: 11em;">
+        <vbox id="itemsCountBox" align="center">
+          <spacer flex="3"/>
+          <label id="itemsCountText"/>
+          <spacer flex="1"/>
+          <description id="selectItemDescription">
+              &detailsPane.selectAnItemText.description;
+          </description>
+          <spacer flex="3"/>
+        </vbox>
+        <vbox id="infoBox" minimal="true">
+          <vbox id="editBookmarkPanelContent" flex="1"/>
+          <hbox id="infoBoxExpanderWrapper" align="center">
 
-          </vbox>
-          <vbox flex="1">
-            <tree id="placeContent" class="placesTree" context="placesContext"
-                  hidecolumnpicker="true"
-                  flex="1" type="places"
-                  flatList="true"
-                  enableColumnDrag="true"
-                  onkeypress="if (event.keyCode == KeyEvent.DOM_VK_RETURN) PlacesOrganizer.openSelectedNode(event);"
-                  onopenflatcontainer="PlacesOrganizer.openFlatContainer(aContainer);"
-                  onselect="PlacesOrganizer.onContentTreeSelect();"
-                  onfocus="PlacesOrganizer.onTreeFocus(event);"
-                  onclick="PlacesOrganizer.onTreeClick(event);">
-              <treecols id="placeContentColumns" context="placesColumnsContext">
-                <treecol label="&col.name.label;" id="placesContentTitle" anonid="title" flex="5" primary="true" ordinal="1" 
-                         persist="width hidden ordinal sortActive sortDirection"/>
-                <splitter class="tree-splitter"/>
-                <treecol label="&col.tags.label;" id="placesContentTags" anonid="tags" flex="2"
-                         persist="width hidden ordinal sortActive sortDirection"/>
-                <splitter class="tree-splitter"/>
-                <treecol label="&col.url.label;" id="placesContentUrl" anonid="url" flex="5"
-                         persist="width hidden ordinal sortActive sortDirection"/>
-                <splitter class="tree-splitter"/>
-                <treecol label="&col.lastvisit.label;" id="placesContentDate" anonid="date" flex="1" hidden="true"
-                         persist="width hidden ordinal sortActive sortDirection"/>
-                <splitter class="tree-splitter"/>
-                <treecol label="&col.visitcount.label;" id="placesContentVisitCount" anonid="visitCount" flex="1" hidden="true"
-                         persist="width hidden ordinal sortActive sortDirection"/>
-                <splitter class="tree-splitter"/>
-                <treecol label="&col.keyword.label;" id="placesContentKeyword" anonid="keyword" flex="1" hidden="true"
-                         persist="width hidden ordinal sortActive sortDirection"/>
-                <splitter class="tree-splitter"/>
-                <treecol label="&col.description.label;" id="placesContentDescription" anonid="description" flex="1" hidden="true"
-                         persist="width hidden ordinal sortActive sortDirection"/>
-                <splitter class="tree-splitter"/>
-                <treecol label="&col.dateadded.label;" id="placesContentDateAdded" anonid="dateAdded" flex="1" hidden="true"
-                         persist="width hidden ordinal sortActive sortDirection"/>
-                <splitter class="tree-splitter"/>
-                <treecol label="&col.lastmodified.label;" id="placesContentLastModified" anonid="lastModified" flex="1" hidden="true"
-                         persist="width hidden ordinal sortActive sortDirection"/>
-              </treecols>
-              <treechildren flex="1"/>
-            </tree>
-            <hbox id="infoPaneBox" style="height: 11em;">
-              <deck flex="1" id="detailsDeck">
-                <vbox id="itemsCountBox" align="center">
-                  <spacer flex="3"/>
-                  <label id="itemsCountText"/>
-                  <spacer flex="1"/>
-                  <description id="selectItemDescription">
-                     &detailsPane.selectAnItemText.description;
-                  </description>
-                  <spacer flex="3"/>
-                </vbox>
-                <vbox id="infoBox" minimal="true">
-                  <vbox id="editBookmarkPanelContent"/>
-                  <spacer flex="1"/>
-                  <hbox id="infoBoxExpanderWrapper" align="center">
+            <button type="image" id="infoBoxExpander"
+                    class="expander-down"
+                    oncommand="PlacesOrganizer.toggleAdditionalInfoFields();"
+                    observes="paneElementsBroadcaster"/>
 
-                    <button type="image" id="infoBoxExpander"
-                            class="expander-down"
-                            oncommand="PlacesOrganizer.toggleAdditionalInfoFields();"
-                            observes="paneElementsBroadcaster"/>
+            <label id="infoBoxExpanderLabel"
+                    lesslabel="&detailsPane.less.label;"
+                    lessaccesskey="&detailsPane.less.accesskey;"
+                    morelabel="&detailsPane.more.label;"
+                    moreaccesskey="&detailsPane.more.accesskey;"
+                    value="&detailsPane.more.label;"
+                    accesskey="&detailsPane.more.accesskey;"
+                    control="infoBoxExpander"/>
 
-                    <label id="infoBoxExpanderLabel"
-                           lesslabel="&detailsPane.less.label;"
-                           lessaccesskey="&detailsPane.less.accesskey;"
-                           morelabel="&detailsPane.more.label;"
-                           moreaccesskey="&detailsPane.more.accesskey;"
-                           value="&detailsPane.more.label;"
-                           accesskey="&detailsPane.more.accesskey;"
-                           control="infoBoxExpander"/>
-
-                    <spacer flex="1"/>
-                  </hbox>
-                </vbox>
-              </deck>
-            </hbox>
-          </vbox>
+          </hbox>
         </vbox>
       </deck>
     </vbox>
   </hbox>
 </window>
--- a/browser/components/preferences/aboutPermissions.js
+++ b/browser/components/preferences/aboutPermissions.js
@@ -76,39 +76,39 @@ let TEST_EXACT_PERM_TYPES = ["geo"];
  * Site object represents a single site, uniquely identified by a host.
  */
 function Site(host) {
   this.host = host;
   this.listitem = null;
 
   this.httpURI = NetUtil.newURI("http://" + this.host);
   this.httpsURI = NetUtil.newURI("https://" + this.host);
-
-  this._favicon = "";
 }
 
 Site.prototype = {
   /**
-   * Gets the favicon to use for the site. This will return the default favicon
-   * if there is no favicon stored for the site.
+   * Gets the favicon to use for the site. The callback only gets called if
+   * a favicon is found for either the http URI or the https URI.
    *
-   * @return A favicon image URL.
+   * @param aCallback
+   *        A callback function that takes a favicon image URL as a parameter.
    */
-  get favicon() {
-    if (!this._favicon) {
-      // TODO: Bug 657961: Make this async when bug 655270 is fixed.
+  getFavicon: function Site_getFavicon(aCallback) {
+    function faviconDataCallback(aURI, aDataLen, aData, aMimeType) {
       try {
-        // First try to see if a favicon is stored for the http URI.
-        this._favicon = gFaviconService.getFaviconForPage(this.httpURI).spec;
+        aCallback(aURI.spec);
       } catch (e) {
-        // getFaviconImageForPage returns the default favicon if no stored favicon is found.
-        this._favicon = gFaviconService.getFaviconImageForPage(this.httpsURI).spec;
+        Cu.reportError("AboutPermissions: " + e);
       }
     }
-    return this._favicon;
+
+    // Try to find favicion for both URIs. Callback will only be called if a
+    // favicon URI is found, so this means we'll always prefer the https favicon.
+    gFaviconService.getFaviconURLForPage(this.httpURI, faviconDataCallback);
+    gFaviconService.getFaviconURLForPage(this.httpsURI, faviconDataCallback);
   },
 
   /**
    * Gets the number of history visits for the site.
    *
    * @param aCallback
    *        A function that takes the visit count (a number) as a parameter.
    */
@@ -260,32 +260,32 @@ let PermissionDefaults = {
 
   get password() {
     if (Services.prefs.getBoolPref("signon.rememberSignons")) {
       return this.ALLOW;
     }
     return this.DENY;
   },
   set password(aValue) {
-    let value = (aValue == this.ALLOW);
+    let value = (aValue != this.DENY);
     Services.prefs.setBoolPref("signon.rememberSignons", value);
   },
 
   // For use with network.cookie.* prefs.
   COOKIE_ACCEPT: 0,
   COOKIE_DENY: 2,
   COOKIE_NORMAL: 0,
   COOKIE_SESSION: 2,
 
   get cookie() {
     if (Services.prefs.getIntPref("network.cookie.cookieBehavior") == this.COOKIE_DENY) {
       return this.DENY;
     }
 
-    if (Services.prefs.getIntPref("network.cookie.lifetimePolicy") == this.COOKIE_DENY) {
+    if (Services.prefs.getIntPref("network.cookie.lifetimePolicy") == this.COOKIE_SESSION) {
       return this.SESSION;
     }
     return this.ALLOW;
   },
   set cookie(aValue) {
     let value = (aValue == this.DENY) ? this.COOKIE_DENY : this.COOKIE_ACCEPT;
     Services.prefs.setIntPref("network.cookie.cookieBehavior", value);
 
@@ -298,30 +298,30 @@ let PermissionDefaults = {
     if (!Services.prefs.getBoolPref("geo.enabled")) {
       return this.DENY;
     }
     // We always ask for permission to share location with a specific site, so
     // there is no global ALLOW.
     return this.UNKNOWN;
   },
   set geo(aValue) {
-    let value = (aValue == this.ALLOW);
+    let value = (aValue != this.DENY);
     Services.prefs.setBoolPref("geo.enabled", value);
   },
 
   get indexedDB() {
     if (!Services.prefs.getBoolPref("dom.indexedDB.enabled")) {
       return this.DENY;
     }
     // We always ask for permission to enable indexedDB storage for a specific
     // site, so there is no global ALLOW.
     return this.UNKNOWN;
   },
   set indexedDB(aValue) {
-    let value = (aValue == this.ALLOW);
+    let value = (aValue != this.DENY);
     Services.prefs.setBoolPref("dom.indexedDB.enabled", value);
   },
 
   get popup() {
     if (Services.prefs.getBoolPref("dom.disable_open_during_load")) {
       return this.DENY;
     }
     return this.ALLOW;
@@ -537,17 +537,20 @@ let AboutPermissions = {
    *
    * @param aSite
    *        A Site object.
    */
   addToSitesList: function(aSite) {
     let item = document.createElement("richlistitem");
     item.setAttribute("class", "site");
     item.setAttribute("value", aSite.host);
-    item.setAttribute("favicon", aSite.favicon);
+
+    aSite.getFavicon(function(aURL) {
+      item.setAttribute("favicon", aURL);
+    });
     aSite.listitem = item;
 
     this.sitesList.appendChild(item);    
   },
 
   /**
    * Hides sites in richlistbox based on search text in sites-filter textbox.
    */
--- a/browser/components/sidebar/src/nsSidebar.js
+++ b/browser/components/sidebar/src/nsSidebar.js
@@ -36,40 +36,32 @@
 # use your version of this file under the terms of the MPL, indicate your
 # decision by deleting the provisions above and replace them with the notice
 # and other provisions required by the GPL or the LGPL. If you do not delete
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
 
+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_CID               = Components.ID("{22117140-9c6e-11d3-aaf1-00805f8a4905}");
 const nsISupports               = Components.interfaces.nsISupports;
 const nsISidebar                = Components.interfaces.nsISidebar;
 const nsISidebarExternal        = Components.interfaces.nsISidebarExternal;
 const nsIClassInfo              = Components.interfaces.nsIClassInfo;
 
 // File extension for Sherlock search plugin description files
 const SHERLOCK_FILE_EXT_REGEXP = /\.src$/i;
 
 function nsSidebar()
 {
-    const PROMPTSERVICE_CONTRACTID = "@mozilla.org/embedcomp/prompt-service;1";
-    const nsIPromptService = Components.interfaces.nsIPromptService;
-    this.promptService =
-        Components.classes[PROMPTSERVICE_CONTRACTID].getService(nsIPromptService);
-
-    const SEARCHSERVICE_CONTRACTID = "@mozilla.org/browser/search-service;1";
-    const nsIBrowserSearchService = Components.interfaces.nsIBrowserSearchService;
-    this.searchService =
-      Components.classes[SEARCHSERVICE_CONTRACTID].getService(nsIBrowserSearchService);
 }
 
 nsSidebar.prototype.classID = SIDEBAR_CID;
 
 nsSidebar.prototype.nc = "http://home.netscape.com/NC-rdf#";
 
 function sidebarURLSecurityCheck(url)
 {
@@ -97,30 +89,25 @@ function(aTitle, aContentURL, aCustomize
            aCustomizeURL + ")\n");
 
     return this.addPanelInternal(aTitle, aContentURL, aCustomizeURL, true);
 }
 
 nsSidebar.prototype.addPanelInternal =
 function (aTitle, aContentURL, aCustomizeURL, aPersist)
 {
-    var WINMEDSVC = Components.classes['@mozilla.org/appshell/window-mediator;1']
-                              .getService(Components.interfaces.nsIWindowMediator);
-
     // XXX Bug 620418: We shouldn't do this anymore. Instead, we should find the
     // global object for our caller and use it.
-    var win = WINMEDSVC.getMostRecentWindow( "navigator:browser" );
+    var win = Services.wm.getMostRecentWindow("navigator:browser");
     if (!sidebarURLSecurityCheck(aContentURL))
       return;
 
     var uri = null;
-    var ioService = Components.classes["@mozilla.org/network/io-service;1"]
-                              .getService(Components.interfaces.nsIIOService);
     try {
-      uri = ioService.newURI(aContentURL, null, null);
+      uri = Services.io.newURI(aContentURL, null, null);
     }
     catch(ex) { return; }
 
     win.PlacesUIUtils.showBookmarkDialog({ action: "add"
                                          , type: "bookmark"
                                          , hiddenRows: [ "description"
                                                        , "keyword"
                                                        , "location"
@@ -136,37 +123,35 @@ function (engineURL, iconURL)
 {
   try
   {
     // Make sure the URLs are HTTP, HTTPS, or FTP.
     var isWeb = /^(https?|ftp):\/\//i;
 
     if (!isWeb.test(engineURL))
       throw "Unsupported search engine URL";
-  
+
     if (iconURL && !isWeb.test(iconURL))
       throw "Unsupported search icon URL.";
   }
   catch(ex)
   {
     debug(ex);
     Components.utils.reportError("Invalid argument passed to window.sidebar.addSearchEngine: " + ex);
-    
-    var searchBundle = srGetStrBundle("chrome://global/locale/search/search.properties");
-    var brandBundle = srGetStrBundle("chrome://branding/locale/brand.properties");
+
+    var searchBundle = Services.strings.createBundle("chrome://global/locale/search/search.properties");
+    var brandBundle = Services.strings.createBundle("chrome://branding/locale/brand.properties");
     var brandName = brandBundle.GetStringFromName("brandShortName");
     var title = searchBundle.GetStringFromName("error_invalid_engine_title");
     var msg = searchBundle.formatStringFromName("error_invalid_engine_msg",
                                                 [brandName], 1);
-    var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"].
-             getService(Components.interfaces.nsIWindowWatcher);
-    ww.getNewPrompter(null).alert(title, msg);
+    Services.ww.getNewPrompter(null).alert(title, msg);
     return false;
   }
-  
+
   return true;
 }
 
 // The suggestedTitle and suggestedCategory parameters are ignored, but remain
 // for backward compatibility.
 nsSidebar.prototype.addSearchEngine =
 function (engineURL, iconURL, suggestedTitle, suggestedCategory)
 {
@@ -180,46 +165,44 @@ function (engineURL, iconURL, suggestedT
   // have less consistent suffixes, so we assume that ".src" is a Sherlock
   // (text) file, and anything else is OpenSearch (XML).
   var dataType;
   if (SHERLOCK_FILE_EXT_REGEXP.test(engineURL))
     dataType = Components.interfaces.nsISearchEngine.DATA_TEXT;
   else
     dataType = Components.interfaces.nsISearchEngine.DATA_XML;
 
-  this.searchService.addEngine(engineURL, dataType, iconURL, true);
+  Services.search.addEngine(engineURL, dataType, iconURL, true);
 }
 
 // This function exists largely to implement window.external.AddSearchProvider(),
 // to match other browsers' APIs.  The capitalization, although nonstandard here,
 // is therefore important.
 nsSidebar.prototype.AddSearchProvider =
 function (aDescriptionURL)
 {
   // Get the favicon URL for the current page, or our best guess at the current
   // page since we don't have easy access to the active document.  Most search
   // engines will override this with an icon specified in the OpenSearch
   // description anyway.
-  var WINMEDSVC = Components.classes['@mozilla.org/appshell/window-mediator;1']
-                            .getService(Components.interfaces.nsIWindowMediator);
-  var win = WINMEDSVC.getMostRecentWindow("navigator:browser");
-  var browser = win.document.getElementById("content");
+  var win = Services.wm.getMostRecentWindow("navigator:browser");
+  var browser = win.gBrowser;
   var iconURL = "";
   // Use documentURIObject in the check for shouldLoadFavIcon so that we
   // do the right thing with about:-style error pages.  Bug 453442
   if (browser.shouldLoadFavIcon(browser.selectedBrowser
                                        .contentDocument
                                        .documentURIObject))
-    iconURL = win.gBrowser.getIcon();
-  
+    iconURL = browser.getIcon();
+
   if (!this.validateSearchEngine(aDescriptionURL, iconURL))
     return;
 
   const typeXML = Components.interfaces.nsISearchEngine.DATA_XML;
-  this.searchService.addEngine(aDescriptionURL, typeXML, iconURL, true);
+  Services.search.addEngine(aDescriptionURL, typeXML, iconURL, true);
 }
 
 // This function exists to implement window.external.IsSearchProviderInstalled(),
 // for compatibility with other browsers.  It will return an integer value
 // indicating whether the given engine is installed for the current user.
 // However, it is currently stubbed out due to security/privacy concerns
 // stemming from difficulties in determining what domain issued the request.
 // See bug 340604 and
@@ -260,21 +243,8 @@ function (iid) {
 
 var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsSidebar]);
 
 /* static functions */
 if (DEBUG)
     debug = function (s) { dump("-*- sidebar component: " + s + "\n"); }
 else
     debug = function (s) {}
-
-// String bundle service
-var gStrBundleService = null;
-
-function srGetStrBundle(path)
-{
-  if (!gStrBundleService)
-    gStrBundleService =
-      Components.classes["@mozilla.org/intl/stringbundle;1"]
-                .getService(Components.interfaces.nsIStringBundleService);
-
-  return gStrBundleService.createBundle(path);
-}
--- a/browser/config/version.txt
+++ b/browser/config/version.txt
@@ -1,1 +1,1 @@
-6.0a1
+7.0a1
--- a/browser/installer/package-manifest.in
+++ b/browser/installer/package-manifest.in
@@ -133,17 +133,16 @@
 @BINPATH@/components/commandhandler.xpt
 @BINPATH@/components/commandlines.xpt
 @BINPATH@/components/composer.xpt
 @BINPATH@/components/content_base.xpt
 @BINPATH@/components/content_events.xpt
 @BINPATH@/components/content_canvas.xpt
 @BINPATH@/components/content_htmldoc.xpt
 @BINPATH@/components/content_html.xpt
-@BINPATH@/components/content_xmldoc.xpt
 @BINPATH@/components/content_xslt.xpt
 @BINPATH@/components/content_xtf.xpt
 @BINPATH@/components/cookie.xpt
 @BINPATH@/components/directory.xpt
 @BINPATH@/components/docshell.xpt
 @BINPATH@/components/dom.xpt
 @BINPATH@/components/dom_base.xpt
 @BINPATH@/components/dom_canvas.xpt
--- a/browser/themes/gnomestripe/browser/browser.css
+++ b/browser/themes/gnomestripe/browser/browser.css
@@ -1692,16 +1692,21 @@ richlistitem[type~="action"][actiontype=
 .alltabs-item[selected="true"] {
   font-weight: bold;
 }
 
 .alltabs-item[busy] > .menu-iconic-left > .menu-iconic-icon {
   list-style-image: url("chrome://global/skin/icons/loading_16.png");
 }
 
+.alltabs-item[tabIsVisible] {
+  /* box-shadow instead of background-color to work around native styling */
+  box-shadow: inset 0 0 0 2em hsla(0,0%,50%,.15);
+}
+
 /* Sidebar */
 #sidebar-header > .tabs-closebutton {
   margin-bottom: 0px !important;
   padding: 0px 2px 0px 2px !important;
 }
 
 #sidebar-throbber[loading="true"] {
   list-style-image: url("chrome://global/skin/icons/loading_16.png");
--- a/browser/themes/gnomestripe/browser/places/organizer.css
+++ b/browser/themes/gnomestripe/browser/places/organizer.css
@@ -59,48 +59,21 @@
   height: 12px;
 }
 
 /* Root View */
 #placesView {
   background-color: Window;
 }
 
-/* Place List, Place Content */
-.placesTree {
-  margin: 0px;
-}
-
-#placesList {
-  margin: 0px;
-  border: none;
-  padding: 0;
-}
-
-#placeContent {
-  border: 0px;
-}
-
-#infoPaneBox {
+/* Info box */
+#detailsDeck {
   padding: 5px;
 }
 
-.small, .small[disabled="true"] {
-  min-width: 0px;
-  padding: 0px 4px 0px 4px;
-  margin: 0px;  
-  border: 0px;
-}
-
-.small .button-text,
-.small .button-box {
-  padding: 0px;
-  border: 0px;
-}
-
 #infoBoxExpanderLabel {
   -moz-padding-start: 2px;
 }
 
 #searchModifiers {
   padding-right: 3px;
 }
 
--- a/browser/themes/gnomestripe/browser/preferences/aboutPermissions.css
+++ b/browser/themes/gnomestripe/browser/preferences/aboutPermissions.css
@@ -27,16 +27,21 @@
   padding: 4px;
   border-bottom: 1px solid ThreeDLightShadow;
 }
 
 .site-favicon {
   height: 16px;
   width: 16px;
   -moz-margin-end: 4px;
+  list-style-image: url("moz-icon://stock/gtk-file?size=menu");
+}
+
+#all-sites-item > .site-container > .site-favicon {
+  list-style-image: none;
 }
 
 .site-domain {
   max-width: 200px; /* crop set in XBL will ellipsize the domain if it's too long */
 }
 
 /* permissions box */
 
--- a/browser/themes/pinstripe/browser/browser.css
+++ b/browser/themes/pinstripe/browser/browser.css
@@ -2001,16 +2001,21 @@ toolbarbutton.chevron > .toolbarbutton-m
 .alltabs-item > .menu-iconic-left > .menu-iconic-icon {
   list-style-image: url("chrome://global/skin/tree/item.png");
 }
 
 .alltabs-item[busy] > .menu-iconic-left > .menu-iconic-icon {
   list-style-image: url("chrome://global/skin/icons/loading_16.png") !important;
 }
 
+.alltabs-item[tabIsVisible] {
+  /* box-shadow instead of background-color to work around native styling */
+  box-shadow: inset 0 0 0 2em hsla(0,0%,50%,.15);
+}
+
 /* Tabstrip close button */
 .tabs-closebutton {
   -moz-padding-end: 4px;
   list-style-image: url("chrome://global/skin/icons/close.png");
   -moz-image-region: rect(0, 16px, 16px, 0);
   border: none;
 }
 
--- a/browser/themes/pinstripe/browser/places/organizer.css
+++ b/browser/themes/pinstripe/browser/places/organizer.css
@@ -1,18 +1,12 @@
 %include ../shared.inc
 
 /* Places Organizer Sidebars */
 
-#placesList {
-  -moz-appearance: none;
-  border: none;
-  margin: 0;
-}
-
 #placesList > treechildren::-moz-tree-row {
   background-color: transparent;
   border-color: transparent;
 }
 
 #placesList > treechildren::-moz-tree-row(selected) {  
   background: @sidebarItemBackground@;
   border-top: @sidebarItemBorderTop@;
@@ -174,33 +168,27 @@
 
 /* Root View */
 #placesView {
   border-top: 1px solid ThreeDDarkShadow;
   -moz-user-focus: ignore;
 }
 
 /* Place List, Place Content */
-.placesTree {
-  margin: 0px;
-}
-
 #placesList {
-  -moz-appearance: none;
   background-color: #d2d8e2;
   width: 160px;
-  margin: 0px;
-  border: 0px;
 }
 
 #placesList:-moz-window-inactive {
   background-color: #e8e8e8;
 }
 
-#infoPaneBox {
+/* Info box */
+#detailsDeck {
   border-top: 1px solid #919191;
   background-color: #f0f0f0;
   padding: 10px;
 }
 
 #placeContent {
   -moz-appearance: none;
   border: 0px;
@@ -230,29 +218,16 @@
 #placeContent > treechildren::-moz-tree-column {
   border-right: 1px solid #d7dad7;
 }
 
 #placeContent > treechildren::-moz-tree-cell(separator) {
   border-color: transparent;
 }
 
-.small {
-  min-width: 0px;
-  padding: 0px 4px 0px 4px;
-  margin: 0px;  
-  border: 0px;
-}
-
-.small .button-text,
-.small .button-box {
-  padding: 0px;
-  border: 0px;
-}
-
 /* Scope Bar */
 
 #advancedSearch > hbox, 
 #advancedSearchRows > row {
   background-color: #E8E8E8;
   border-top: 1px solid #F8F8F8;
   border-bottom: 1px solid #BABABA;
 }
--- a/browser/themes/pinstripe/browser/preferences/aboutPermissions.css
+++ b/browser/themes/pinstripe/browser/preferences/aboutPermissions.css
@@ -29,16 +29,21 @@
   padding: 4px;
   border-bottom: 1px solid ThreeDLightShadow;
 }
 
 .site-favicon {
   height: 16px;
   width: 16px;
   -moz-margin-end: 4px;
+  list-style-image: url("chrome://mozapps/skin/places/defaultFavicon.png");
+}
+
+#all-sites-item > .site-container > .site-favicon {
+  list-style-image: none;
 }
 
 .site-domain {
   max-width: 200px; /* crop set in XBL will ellipsize the domain if it's too long */
 }
 
 /* permissions box */
 
--- a/browser/themes/winstripe/browser/browser.css
+++ b/browser/themes/winstripe/browser/browser.css
@@ -1876,16 +1876,21 @@ richlistitem[type~="action"][actiontype=
 .alltabs-item[selected="true"] {
   font-weight: bold;
 }
 
 .alltabs-item[busy] > .menu-iconic-left > .menu-iconic-icon {
   list-style-image: url("chrome://global/skin/icons/loading_16.png");
 }
 
+.alltabs-item[tabIsVisible] {
+  /* box-shadow instead of background-color to work around native styling */
+  box-shadow: inset 0 0 0 2em hsla(0,0%,50%,.15);
+}
+
 /* Tabstrip close button */
 .tabs-closebutton {
   -moz-appearance: none;
   list-style-image: url("chrome://global/skin/icons/close.png");
   -moz-image-region: rect(0, 16px, 16px, 0);
   padding: 4px 2px;
   margin: 0px;
   border: none;
--- a/browser/themes/winstripe/browser/places/organizer-aero.css
+++ b/browser/themes/winstripe/browser/places/organizer-aero.css
@@ -60,17 +60,17 @@
     border-bottom: 1px solid #A9B7C9;
   }
 
   #organizerScopeBar {
     -moz-appearance: none;
     border: none;
   }
 
-  #infoPaneBox {
+  #detailsDeck {
     border-top-color: #A9B7C9;
   }
 
   #searchFilter {
     -moz-appearance: none;
     background-color: rgba(255,255,255,.725);
     color: black;
     padding: 2px;
--- a/browser/themes/winstripe/browser/places/organizer.css
+++ b/browser/themes/winstripe/browser/places/organizer.css
@@ -105,57 +105,27 @@
   -moz-image-region: rect(16px, 48px, 32px, 32px);
 }
 
 /* Root View */
 #placesView {
   border-top: 1px solid ThreeDDarkShadow;
 }
 
-/* Place List, Place Content */
-.placesTree {
-  margin: 0px;
-}
-
-#placesList {
-  -moz-appearance: none;
-  margin: 0px;
-  border: none;
-  padding: 0;
-}
-
-#placeContent {
-  -moz-appearance: none;
-  border: 0px;
-}
-
-#infoPaneBox {
+/* Info box */
+#detailsDeck {
   border-top: 1px solid ThreeDShadow;
   padding: 5px;
 }
 
-.small, .small[disabled="true"] {
-  min-width: 0px;
-  padding: 0px 4px 0px 4px;
-  margin: 0px;  
-  border: 0px;
-}
-
-.small .button-text,
-.small .button-box {
-  padding: 0px;
-  border: 0px;
-}
-
 #infoBoxExpanderLabel {
   -moz-padding-start: 2px;
 }
 
 #organizerScopeBar {
-  -moz-appearance: toolbox;
   padding: 2px 0;
   -moz-padding-end: 3px;
 }
 
 #organizerScopeBar > toolbarbutton {
   -moz-appearance: none;
   border: 1px solid transparent;
   border-radius: 2px;
--- a/browser/themes/winstripe/browser/preferences/aboutPermissions.css
+++ b/browser/themes/winstripe/browser/preferences/aboutPermissions.css
@@ -32,16 +32,21 @@
   padding: 4px;
   border-bottom: 1px solid ThreeDLightShadow;
 }
 
 .site-favicon {
   height: 16px;
   width: 16px;
   -moz-margin-end: 4px;
+  list-style-image: url("chrome://mozapps/skin/places/defaultFavicon.png");
+}
+
+#all-sites-item > .site-container > .site-favicon {
+  list-style-image: none;
 }
 
 .site-domain {
   max-width: 200px; /* crop set in XBL will ellipsize the domain if it's too long */
 }
 
 /* permissions box */
 
--- a/build/Makefile.in
+++ b/build/Makefile.in
@@ -118,21 +118,21 @@ libs:: $(topsrcdir)/tools/rb/fix_stack_u
 ifeq ($(OS_ARCH),Darwin)
 libs:: $(topsrcdir)/tools/rb/fix-macosx-stack.pl
 	$(INSTALL) $< $(DIST)/bin
 libs:: $(topsrcdir)/tools/rb/fix_macosx_stack.py
 	$(INSTALL) $< $(DIST)/bin
 
 # Basic unit tests for some stuff in the unify script
 check::
-# build ppc/i386 binaries, and unify them
-	rm -f unify-test-ppc unify-test-i386 unify-test-universal
-	$(HOST_CC) -arch ppc $(srcdir)/unify-test.c -o unify-test-ppc
+# build x64/i386 binaries, and unify them
+	rm -f unify-test-x64 unify-test-i386 unify-test-universal
+	$(HOST_CC) -arch x86_64 $(srcdir)/unify-test.c -o unify-test-x64
 	$(HOST_CC) -arch i386 $(srcdir)/unify-test.c -o unify-test-i386
-	@if ! $(srcdir)/macosx/universal/unify ./unify-test-ppc ./unify-test-i386 \
+	@if ! $(srcdir)/macosx/universal/unify ./unify-test-x64 ./unify-test-i386 \
           ./unify-test-universal; then \
           echo "TEST-UNEXPECTED-FAIL | build/ | unify failed to produce a universal binary!"; \
           false; \
         fi
 	@if test ! -f ./unify-test-universal; then \
           echo "TEST-UNEXPECTED-FAIL | build/ | unify failed to produce a universal binary!"; \
           false; \
         fi
--- a/build/autoconf/config.sub
+++ b/build/autoconf/config.sub
@@ -1,15 +1,15 @@
 #! /bin/sh
 # Configuration validation subroutine script.
 #   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
 #   2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
 #   Free Software Foundation, Inc.
 
-timestamp='2009-12-04'
+timestamp='2011-01-03'
 
 # This file is (in principle) common to ALL GNU software.
 # The presence of a machine in this file suggests that SOME GNU software
 # can handle that machine.  It does not imply ALL GNU software can.
 #
 # This file is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or
@@ -1427,16 +1427,19 @@ case $os in
 		os=-kaos
 		;;
 	-zvmoe)
 		os=-zvmoe
 		;;
 	-dicos*)
 		os=-dicos
 		;;
+        -android*)
+	        os=android
+                ;;
 	-none)
 		;;
 	*)
 		# Get rid of the `-' at the beginning of $os.
 		os=`echo $os | sed 's/[^-]*-//'`
 		echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
 		exit 1
 		;;
@@ -1681,16 +1684,19 @@ case $basic_machine in
 				vendor=apple
 				;;
 			-*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
 				vendor=atari
 				;;
 			-vos*)
 				vendor=stratus
 				;;
+			*-android*|*-linuxandroid*)
+				vendor=linux-
+				;;
 		esac
 		basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
 		;;
 esac
 
 echo $basic_machine$os
 exit
 
--- a/config/autoconf.mk.in
+++ b/config/autoconf.mk.in
@@ -50,17 +50,16 @@ FIREFOX_VERSION	= @FIREFOX_VERSION@
 MOZ_BUILD_APP = @MOZ_BUILD_APP@
 MOZ_APP_NAME	= @MOZ_APP_NAME@
 MOZ_APP_DISPLAYNAME = @MOZ_APP_DISPLAYNAME@
 MOZ_APP_BASENAME = @MOZ_APP_BASENAME@
 MOZ_APP_VENDOR = @MOZ_APP_VENDOR@
 MOZ_APP_PROFILE = @MOZ_APP_PROFILE@
 MOZ_APP_UA_NAME = @MOZ_APP_UA_NAME@
 MOZ_APP_VERSION = @MOZ_APP_VERSION@
-MOZ_UA_FIREFOX_VERSION = @FIREFOX_VERSION@
 MOZ_UA_BUILDID = @MOZ_UA_BUILDID@
 
 MOZ_PKG_SPECIAL = @MOZ_PKG_SPECIAL@
 
 prefix		= @prefix@
 exec_prefix	= @exec_prefix@
 bindir		= @bindir@
 includedir	= @includedir@/$(MOZ_APP_NAME)-$(MOZ_APP_VERSION)
@@ -253,17 +252,17 @@ MOZ_NATIVE_PNG	= @SYSTEM_PNG@
 MOZ_TREE_CAIRO = @MOZ_TREE_CAIRO@
 MOZ_TREE_PIXMAN = @MOZ_TREE_PIXMAN@
 
 MOZ_UPDATE_XTERM = @MOZ_UPDATE_XTERM@
 MOZ_MATHML = @MOZ_MATHML@
 MOZ_CSS_ANIMATIONS = @MOZ_CSS_ANIMATIONS@
 MOZ_PERMISSIONS = @MOZ_PERMISSIONS@
 MOZ_XTF = @MOZ_XTF@
-MOZ_SVG = @MOZ_SVG@
+MOZ_SVG_DLISTS = @MOZ_SVG_DLISTS@
 MOZ_CAIRO_CFLAGS = @MOZ_CAIRO_CFLAGS@
 MOZ_SMIL = @MOZ_SMIL@
 MOZ_XSLT_STANDALONE = @MOZ_XSLT_STANDALONE@
 
 MOZ_PREF_EXTENSIONS = @MOZ_PREF_EXTENSIONS@
 
 MOZ_CAIRO_LIBS = @MOZ_CAIRO_LIBS@
 
@@ -544,16 +543,17 @@ MOZ_ENABLE_D3D9_LAYER	= @MOZ_ENABLE_D3D9
 MOZ_ENABLE_D3D10_LAYER  = @MOZ_ENABLE_D3D10_LAYER@
 
 MOZ_GTK2_CFLAGS		= @MOZ_GTK2_CFLAGS@
 MOZ_GTK2_LIBS		= @MOZ_GTK2_LIBS@
 
 MOZ_QT_CFLAGS		= @MOZ_QT_CFLAGS@
 MOZ_QT_LIBS		= @MOZ_QT_LIBS@
 MOZ_ENABLE_QTNETWORK    = @MOZ_ENABLE_QTNETWORK@
+MOZ_ENABLE_QMSYSTEM2    = @MOZ_ENABLE_QMSYSTEM2@
 MOZ_ENABLE_QTMOBILITY   = @MOZ_ENABLE_QTMOBILITY@
 MOZ_ENABLE_CONTENTACTION   = @MOZ_ENABLE_CONTENTACTION@
 MOZ_ENABLE_MEEGOTOUCHSHARE = @MOZ_ENABLE_MEEGOTOUCHSHARE@
 
 MOZ_DBUS_CFLAGS         = @MOZ_DBUS_CFLAGS@
 MOZ_DBUS_LIBS           = @MOZ_DBUS_LIBS@
 MOZ_DBUS_GLIB_CFLAGS    = @MOZ_DBUS_GLIB_CFLAGS@
 MOZ_DBUS_GLIB_LIBS      = @MOZ_DBUS_GLIB_LIBS@
--- a/config/milestone.txt
+++ b/config/milestone.txt
@@ -5,9 +5,9 @@
 #    x.x.x.x
 #    x.x.x+
 #
 # Referenced by milestone.pl.
 # Hopefully I'll be able to automate replacement of *all*
 # hardcoded milestones in the tree from these two files.
 #--------------------------------------------------------
 
-6.0a1
+7.0a1
--- a/configure.in
+++ b/configure.in
@@ -259,17 +259,35 @@ MOZ_ARG_WITH_STRING(android-version,
     android_version=$withval,
     android_version=5)
 
 MOZ_ARG_WITH_STRING(android-sdk,
 [  --with-android-sdk=DIR
                           location where the Android SDK can be found (base directory, e.g. .../android/platforms/android-6)],
     android_sdk=$withval)
 
-if test "$target" = "arm-android-eabi" ; then
+MOZ_ARG_WITH_STRING(android-platform,
+[  --with-android-platform=DIR
+                           location of platform dir, default NDK/build/platforms/android-5/arch-arm],
+    android_platform=$withval)
+
+case "$target" in
+arm-linux*-android*|*-linuxandroid*)
+    android_tool_prefix="arm-linux-androideabi"
+    ;;
+arm-android-eabi)
+    android_tool_prefix="arm-eabi"
+    ;;
+*)
+    android_tool_prefix="$target_os"
+    ;;
+esac
+
+case "$target" in
+*-android*|*-linuxandroid*)
     if test -z "$android_ndk" ; then
         AC_MSG_ERROR([You must specify --with-android-ndk=/path/to/ndk when targeting Android.])
     fi
 
     if test -z "$android_sdk" ; then
         AC_MSG_ERROR([You must specify --with-android-sdk=/path/to/sdk when targeting Android.])
     fi
 
@@ -282,34 +300,40 @@ if test "$target" = "arm-android-eabi" ;
         android_toolchain="$android_ndk"/build/prebuilt/`uname -s | tr "[[:upper:]]" "[[:lower:]]"`-x86/arm-eabi-4.4.0
     fi
 
     if test -z "$android_platform" ; then
        android_platform="$android_ndk"/build/platforms/android-"$android_version"/arch-"$target_cpu"
     fi
 
     dnl set up compilers
-    AS="$android_toolchain"/bin/arm-eabi-as
-    CC="$android_toolchain"/bin/arm-eabi-gcc
-    CXX="$android_toolchain"/bin/arm-eabi-g++
-    CPP="$android_toolchain"/bin/arm-eabi-cpp
-    LD="$android_toolchain"/bin/arm-eabi-ld
-    AR="$android_toolchain"/bin/arm-eabi-ar
-    RANLIB="$android_toolchain"/bin/arm-eabi-ranlib
-    STRIP="$android_toolchain"/bin/arm-eabi-strip
-
-    CPPFLAGS="-I$android_platform/usr/include $CPPFLAGS"
+    AS="$android_toolchain"/bin/"$android_tool_prefix"-as
+    CC="$android_toolchain"/bin/"$android_tool_prefix"-gcc
+    CXX="$android_toolchain"/bin/"$android_tool_prefix"-g++
+    CPP="$android_toolchain"/bin/"$android_tool_prefix"-cpp
+    LD="$android_toolchain"/bin/"$android_tool_prefix"-ld
+    AR="$android_toolchain"/bin/"$android_tool_prefix"-ar
+    RANLIB="$android_toolchain"/bin/"$android_tool_prefix"-ranlib
+    STRIP="$android_toolchain"/bin/"$android_tool_prefix"-strip
+
+    if test -e "$android_ndk/sources/cxx-stl/stlport/libs/armeabi-v7a/libstlport_static.a" ; then
+       STLPORT_CPPFLAGS="-I$android_ndk/sources/cxx-stl/stlport/stlport"
+       STLPORT_LDFLAGS="-L$android_ndk/sources/cxx-stl/stlport/libs/armeabi-v7a/  -lstlport_static"
+    fi
+
+    CPPFLAGS="-I$android_platform/usr/include $STLPORT_CPPFLAGS $CPPFLAGS"
     CFLAGS="-mandroid -I$android_platform/usr/include -fno-short-enums -fno-exceptions $CFLAGS"
     CXXFLAGS="-mandroid -I$android_platform/usr/include -fno-short-enums -fno-exceptions $CXXFLAGS"
+    LIBS="$LIBS $STLPORT_LDFLAGS"
 
     dnl Add -llog by default, since we use it all over the place.
     dnl Add --allow-shlib-undefined, because libGLESv2 links to an
     dnl undefined symbol (present on the hardware, just not in the
     dnl NDK.)
-    LDFLAGS="-mandroid -L$android_platform/usr/lib -Wl,-rpath-link=$android_platform/usr/lib --sysroot=$android_platform -llog -Wl,--allow-shlib-undefined $LDFLAGS"
+    LDFLAGS="-mandroid -L$android_platform/usr/lib -L$android_ndk/sources/cxx-stl/gnu-libstdc++/libs/armeabi-v7a -Wl,-rpath-link=$android_platform/usr/lib --sysroot=$android_platform -llog -Wl,--allow-shlib-undefined $LDFLAGS"
 
     dnl prevent cross compile section from using these flags as host flags
     if test -z "$HOST_CPPFLAGS" ; then
         HOST_CPPFLAGS=" "
     fi
     if test -z "$HOST_CFLAGS" ; then
         HOST_CFLAGS=" "
     fi
@@ -331,17 +355,18 @@ if test "$target" = "arm-android-eabi" ;
     fi
 
     AC_DEFINE(ANDROID)
     AC_DEFINE_UNQUOTED(ANDROID_VERSION, $android_version)
     AC_SUBST(ANDROID_VERSION)
     CROSS_COMPILE=1
     MOZ_CHROME_FILE_FORMAT=omni
     ZLIB_DIR=yes
-fi
+    ;;
+esac
 
 AC_SUBST(ANDROID_NDK)
 AC_SUBST(ANDROID_TOOLCHAIN)
 AC_SUBST(ANDROID_PLATFORM)
 AC_SUBST(ANDROID_SDK)
 AC_SUBST(ANDROID_PLATFORM_TOOLS)
 AC_SUBST(ANDROID_PACKAGE_NAME)
 
@@ -1218,17 +1243,17 @@ if test -n "$CROSS_COMPILE"; then
         linux*)       OS_ARCH=Linux OS_TARGET=Linux ;;
         kfreebsd*-gnu) OS_ARCH=GNU_kFreeBSD OS_TARGET=GNU_kFreeBSD ;;
         gnu*)         OS_ARCH=GNU ;;
         solaris*)     OS_ARCH=SunOS OS_RELEASE=5 ;;
         mingw*)       OS_ARCH=WINNT ;;
         darwin*)      OS_ARCH=Darwin OS_TARGET=Darwin ;;
     esac
     case "${target}" in
-        arm-android-eabi) OS_ARCH=Linux OS_TARGET=Android ;;
+        *-android*|*-linuxandroid*) OS_ARCH=Linux OS_TARGET=Android ;;
     esac
 else
     OS_TARGET=`uname -s`
     OS_ARCH=`uname -s | sed -e 's|/|_|g'`
     OS_RELEASE=`uname -r`
 fi
 
 # Before this used `uname -m` when not cross compiling
@@ -2166,16 +2191,33 @@ ia64*-hpux*)
        AC_MSG_WARN([Clearing MOZ_FIX_LINK_PATHS for OSF/1 as fix for bug 333545 (till the reference bug 332075 is fixed.])
        MOZ_FIX_LINK_PATHS=
     fi
     if test -z "$GNU_CXX"; then
       MIPSPRO_CXX=1
     fi
     ;;
 
+*-android*|*-linuxandroid*)
+    AC_DEFINE(NO_PW_GECOS)
+    no_x=yes
+    _PLATFORM_DEFAULT_TOOLKIT=cairo-android
+    TARGET_NSPR_MDCPUCFG='\"md/_linux.cfg\"'
+
+    MOZ_GFX_OPTIMIZE_MOBILE=1
+    # If we're building with --enable-profiling, we need a frame pointer.
+    if test -z "$MOZ_PROFILING"; then
+        MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions -fomit-frame-pointer"
+    else
+        MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions -fno-omit-frame-pointer"
+    fi
+    # The Maemo builders don't know about this flag
+    MOZ_ARM_VFP_FLAGS="-mfpu=vfp"
+    ;;
+
 *-*linux*)
     # Note: both GNU_CC and INTEL_CC are set when using Intel's C compiler.
     # Similarly for GNU_CXX and INTEL_CXX.
     if test "$INTEL_CC" -o "$INTEL_CXX"; then
         # -Os has been broken on Intel's C/C++ compilers for quite a
         # while; Intel recommends against using it.
         MOZ_OPTIMIZE_FLAGS="-O2"
         MOZ_DEBUG_FLAGS="-g"
@@ -2685,33 +2727,16 @@ alpha*-*-osf*)
 *-sysv4.2uw7*) 
 	NSPR_LIBS="-lnspr$NSPR_VERSION -lplc$NSPR_VERSION -lplds$NSPR_VERSION -L/usr/ccs/lib -lcrt"
     ;;
 
 *-os2*)
     HOST_NSPR_MDCPUCFG='\"md/_os2.cfg\"'
     ;;
 
-*-android*)
-    AC_DEFINE(NO_PW_GECOS)
-    no_x=yes
-    _PLATFORM_DEFAULT_TOOLKIT=cairo-android
-    TARGET_NSPR_MDCPUCFG='\"md/_linux.cfg\"'
-
-    MOZ_GFX_OPTIMIZE_MOBILE=1
-    # If we're building with --enable-profiling, we need a frame pointer.
-    if test -z "$MOZ_PROFILING"; then
-        MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions -fomit-frame-pointer"
-    else
-        MOZ_OPTIMIZE_FLAGS="-Os -freorder-blocks -fno-reorder-functions -fno-omit-frame-pointer"
-    fi
-    # The Maemo builders don't know about this flag
-    MOZ_ARM_VFP_FLAGS="-mfpu=vfp"
-    ;;
-
 esac
 
 dnl Only one oddball right now (QNX), but this gives us flexibility
 dnl if any other platforms need to override this in the future.
 AC_DEFINE_UNQUOTED(D_INO,$DIRENT_INO)
 
 dnl ========================================================
 dnl Any platform that doesn't have MKSHLIB_FORCE_ALL defined
@@ -3318,35 +3343,16 @@ fi
 dnl OS/2 has socket in libc.
 case $target in
 *-os2*)
     ;;
 *)
     AC_CHECK_LIB(socket, socket)
 esac
 
-dnl ========================================================
-dnl Check whether we can compile code for Core Text
-dnl (available on Mac OS X 10.5 or later)
-dnl ========================================================
-case "$target" in
-*-darwin*)
-  AC_MSG_CHECKING([for Core Text])
-  AC_TRY_COMPILE([#include <ApplicationServices/ApplicationServices.h>],
-                 [CTLineRef lineRef;],
-                  ac_cv_have_core_text="yes",
-                  ac_cv_have_core_text="no")
-  AC_MSG_RESULT([$ac_cv_have_core_text])
-
-  if test "$ac_cv_have_core_text" = "no"; then
-    AC_MSG_ERROR([Core Text is required (available on Mac OS X 10.5 or later).])
-  fi
-  ;;
-esac
-
 XLDFLAGS="$X_LIBS"
 XLIBS="$X_EXTRA_LIBS"
 
 dnl ========================================================
 dnl Checks for X libraries.
 dnl Ordering is important.
 dnl Xt is dependent upon SM as of X11R6
 dnl ========================================================
@@ -4294,17 +4300,17 @@ AC_CACHE_CHECK(for __thread keyword for 
 LDFLAGS=$_SAVE_LDFLAGS
 if test "$ac_cv_thread_keyword" = yes; then
   # mips builds fail with TLS variables because of a binutils bug.
   # See bug 528687
   case "${target}" in
     mips*-*)
       :
       ;;
-    *-android*)
+    *-android*|*-linuxandroid*)
       :
       ;;
     *)
       AC_DEFINE(HAVE_THREAD_TLS_KEYWORD)
       ;;
   esac
 fi
 
@@ -4830,17 +4836,17 @@ MOZ_PROFILELOCKING=1
 MOZ_PSM=1
 MOZ_RDF=1
 MOZ_REFLOW_PERF=
 MOZ_SAFE_BROWSING=
 MOZ_HELP_VIEWER=
 MOZ_SPELLCHECK=1
 MOZ_SPLASHSCREEN=
 MOZ_STORAGE=1
-MOZ_SVG=1
+MOZ_SVG_DLISTS=
 MOZ_THUMB2=
 MOZ_TIMELINE=
 MOZ_TOOLKIT_SEARCH=1
 MOZ_UI_LOCALE=en-US
 MOZ_UNIVERSALCHARDET=1
 MOZ_URL_CLASSIFIER=
 MOZ_XSLT_STANDALONE=
 MOZ_XTF=1
@@ -4878,17 +4884,17 @@ case "$target_os" in
         fi
         if test -n "$NS_ENABLE_TSF"; then
             AC_DEFINE(NS_ENABLE_TSF)
         fi
         ;;
 esac
 
 case "${target}" in
-    arm-android-eabi)
+    *-android*|*-linuxandroid*)
         NSS_DISABLE_DBM=1
         USE_ARM_KUSER=1
         MOZ_INSTALLER=
         NECKO_WIFI=
         MOZ_THUMB2=1
         MOZ_THEME_FASTSTRIPE=1
         MOZ_TREE_FREETYPE=1
         MOZ_MEMORY=1
@@ -5246,16 +5252,28 @@ then
         HOST_MOC="$QTDIR/bin/moc"
     fi
     if test -z "$HOST_MOC"; then
         AC_MSG_ERROR([No acceptable moc preprocessor found. Qt SDK is not installed or --with-qt is
 incorrect])
     fi
     MOC=$HOST_MOC
 
+    MOZ_ENABLE_QMSYSTEM2=
+    PKG_CHECK_MODULES(_QMSYSTEM2, qmsystem2,
+                      MOZ_ENABLE_QMSYSTEM2=1,
+                      MOZ_ENABLE_QMSYSTEM2=)
+
+    if test "$MOZ_ENABLE_QMSYSTEM2"; then
+      MOZ_ENABLE_QMSYSTEM2=1
+      MOZ_QT_CFLAGS="$MOZ_QT_CFLAGS $_QMSYSTEM2_CFLAGS"
+      MOZ_QT_LIBS="$MOZ_QT_LIBS $_QMSYSTEM2_LIBS"
+      AC_DEFINE(MOZ_ENABLE_QMSYSTEM2)
+    fi
+
     MOZ_ENABLE_QTNETWORK=
     PKG_CHECK_MODULES(_QTNETWORK, QtNetwork >= 4.7,
                       MOZ_ENABLE_QTNETWORK=1,
                       MOZ_ENABLE_QTNETWORK=)
 
     if test "$MOZ_ENABLE_QTNETWORK"; then
       MOZ_ENABLE_QTNETWORK=1
       AC_DEFINE(MOZ_ENABLE_QTNETWORK)
@@ -5285,16 +5303,17 @@ fi
 AC_SUBST(GTK_CONFIG)
 AC_SUBST(TK_CFLAGS)
 AC_SUBST(TK_LIBS)
 
 AC_SUBST(MOZ_ENABLE_GTK2)
 AC_SUBST(MOZ_ENABLE_PHOTON)
 AC_SUBST(MOZ_ENABLE_QT)
 AC_SUBST(MOZ_ENABLE_QTNETWORK)
+AC_SUBST(MOZ_ENABLE_QMSYSTEM2)
 AC_SUBST(MOZ_ENABLE_QTMOBILITY)
 AC_SUBST(MOZ_ENABLE_XREMOTE)
 AC_SUBST(MOZ_GTK2_CFLAGS)
 AC_SUBST(MOZ_GTK2_LIBS)
 AC_SUBST(MOZ_QT_CFLAGS)
 AC_SUBST(MOZ_QT_LIBS)
 
 AC_SUBST(MOC)
@@ -6191,17 +6210,17 @@ i?86-*-mingw*|x86_64-*-mingw*)
 i?86-apple-darwin*|powerpc-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
   ;;
-arm-android-eabi)
+*-android*|*-linuxandroid*)
   MOZ_CRASHREPORTER=1
   ;;
 *solaris*)
   MOZ_CRASHREPORTER=1
   ;;
 esac
 
 MOZ_ARG_DISABLE_BOOL(crashreporter,
@@ -6398,19 +6417,21 @@ MOZ_ARG_DISABLE_BOOL(mathml,
     MOZ_MATHML=1 )
 if test "$MOZ_MATHML"; then
   AC_DEFINE(MOZ_MATHML)
 fi
 
 AC_DEFINE(MOZ_CSS_ANIMATIONS)
 
 dnl ========================================================
-dnl Keeping AC_DEFINE(MOZ_SVG) for the moment in case of something needs it.
-dnl ========================================================
-AC_DEFINE(MOZ_SVG)
+dnl SVG Display Lists
+dnl ========================================================
+if test -n "$MOZ_SVG_DLISTS"; then
+  AC_DEFINE(MOZ_SVG_DLISTS)
+fi
 
 dnl ========================================================
 dnl SMIL
 dnl ========================================================
 MOZ_SMIL=1
 MOZ_ARG_DISABLE_BOOL(smil,
 [  --disable-smil          Disable SMIL animation support],
     MOZ_SMIL=,
@@ -7319,16 +7340,23 @@ else
   dnl platforms we have special knowledge of.
   case "${target}" in
   *-darwin*)
     AC_DEFINE(MOZ_MEMORY_DARWIN)
     ;;
   *-*freebsd*)
     AC_DEFINE(MOZ_MEMORY_BSD)
     ;;
+  *-android*|*-linuxandroid*)
+    AC_DEFINE(MOZ_MEMORY_LINUX)
+    AC_DEFINE(MOZ_MEMORY_ANDROID)
+    _WRAP_MALLOC=1
+    export WRAP_MALLOC_LIB="-L$_objdir/dist/lib -lmozalloc -lmozutils"
+    WRAP_MALLOC_CFLAGS="-Wl,--wrap=dlopen -Wl,--wrap=dlclose -Wl,--wrap=dlerror -Wl,--wrap=dlsym -Wl,--wrap=dladdr"
+    ;;
   *-*linux*)
     AC_DEFINE(MOZ_MEMORY_LINUX)
     ;;
   *-netbsd*)
     AC_DEFINE(MOZ_MEMORY_BSD)
     ;;
   *-solaris*)
     AC_DEFINE(MOZ_MEMORY_SOLARIS)
@@ -7367,23 +7395,16 @@ else
     WIN32_CRT_SRC_DIR=`cd "$WIN32_CRT_SRC_DIR" && pwd -W`
     _objdir_win=`pwd -W`
     WIN32_CUSTOM_CRT_DIR="$_objdir_win/memory/jemalloc/crtsrc/build/$MOZ_CRT_CPU_ARCH"
     MOZ_MEMORY_LDFLAGS="-MANIFEST:NO -LIBPATH:\"$WIN32_CUSTOM_CRT_DIR\" -NODEFAULTLIB:msvcrt -NODEFAULTLIB:msvcrtd -NODEFAULTLIB:msvcprt -NODEFAULTLIB:msvcprtd -DEFAULTLIB:mozcrt19 -DEFAULTLIB:mozcpp19"
     dnl Also pass this to NSPR/NSS
     DLLFLAGS="$DLLFLAGS $MOZ_MEMORY_LDFLAGS"
     export DLLFLAGS
     ;;
-  *-android*)
-    AC_DEFINE(MOZ_MEMORY_LINUX)
-    AC_DEFINE(MOZ_MEMORY_ANDROID)
-    _WRAP_MALLOC=1
-    export WRAP_MALLOC_LIB="-L$_objdir/dist/lib -lmozalloc -lmozutils"
-    WRAP_MALLOC_CFLAGS="-Wl,--wrap=dlopen -Wl,--wrap=dlclose -Wl,--wrap=dlerror -Wl,--wrap=dlsym -Wl,--wrap=dladdr"
-    ;;
   *)
     AC_MSG_ERROR([--enable-jemalloc not supported on ${target}])
     ;;
   esac
 
   if test "$OS_ARCH" != "Darwin"; then
     dnl NB: this must be kept in sync with jemalloc.h
     AC_DEFINE(HAVE_JEMALLOC_VALLOC)
@@ -8375,16 +8396,17 @@ MOZ_CHECK_HEADERS(stdint.h inttypes.h sy
 if test "$MOZ_TREE_CAIRO"; then
     AC_DEFINE(MOZ_TREE_CAIRO)
 
     # For now we assume that we will have a uint64_t available through
     # one of the above headers or mozstdint.h.
     AC_DEFINE(HAVE_UINT64_T)
 
     # Define macros for cairo-features.h
+    TEE_SURFACE_FEATURE="#define CAIRO_HAS_TEE_SURFACE 1"
     if test "$MOZ_X11"; then
         XLIB_SURFACE_FEATURE="#define CAIRO_HAS_XLIB_SURFACE 1"
         XLIB_XRENDER_SURFACE_FEATURE="#define CAIRO_HAS_XLIB_XRENDER_SURFACE 1"
         PS_SURFACE_FEATURE="#define CAIRO_HAS_PS_SURFACE 1"
         FT_FONT_FEATURE="#define CAIRO_HAS_FT_FONT 1"
         MOZ_ENABLE_CAIRO_FT=1
         CAIRO_FT_CFLAGS="$FT2_CFLAGS"
     fi
@@ -8457,16 +8479,17 @@ if test "$MOZ_TREE_CAIRO"; then
     AC_SUBST(FT_FONT_FEATURE)
     AC_SUBST(FC_FONT_FEATURE)
     AC_SUBST(WIN32_FONT_FEATURE)
     AC_SUBST(WIN32_DWRITE_FONT_FEATURE)
     AC_SUBST(WIN32_D2D_SURFACE_FEATURE)
     AC_SUBST(QUARTZ_FONT_FEATURE)
     AC_SUBST(PNG_FUNCTIONS_FEATURE)
     AC_SUBST(QT_SURFACE_FEATURE)
+    AC_SUBST(TEE_SURFACE_FEATURE)
 
     MOZ_CAIRO_LIBS='$(call EXPAND_LIBNAME_PATH,mozcairo,$(DEPTH)/gfx/cairo/cairo/src)'" $CAIRO_FT_LIBS"
 
     if test "$MOZ_TREE_PIXMAN"; then
         AC_DEFINE(MOZ_TREE_PIXMAN)
         MOZ_CAIRO_LIBS="$MOZ_CAIRO_LIBS"' $(call EXPAND_LIBNAME_PATH,mozlibpixman,$(DEPTH)/gfx/cairo/libpixman/src)'
     else
         PKG_CHECK_MODULES(PIXMAN, pixman-1 >= 0.19.2)
@@ -8726,17 +8749,16 @@ AC_SUBST(MOZ_UPDATE_XTERM)
 AC_SUBST(MINIMO)
 AC_SUBST(MOZ_PLATFORM_MAEMO)
 AC_SUBST(MOZ_AUTH_EXTENSION)
 AC_SUBST(MOZ_MATHML)
 AC_SUBST(MOZ_CSS_ANIMATIONS)
 AC_SUBST(MOZ_PERMISSIONS)
 AC_SUBST(MOZ_XTF)
 AC_SUBST(MOZ_PREF_EXTENSIONS)
-AC_SUBST(MOZ_SVG)
 AC_SUBST(MOZ_SMIL)
 AC_SUBST(MOZ_XSLT_STANDALONE)
 AC_SUBST(MOZ_JS_LIBS)
 AC_SUBST(MOZ_PSM)
 AC_SUBST(MOZ_DEBUG)
 AC_SUBST(MOZ_DEBUG_SYMBOLS)
 AC_SUBST(MOZ_DEBUG_ENABLE_DEFS)
 AC_SUBST(MOZ_DEBUG_DISABLE_DEFS)
@@ -8836,17 +8858,17 @@ AC_SUBST(MOZ_APP_DISPLAYNAME)
 AC_SUBST(MOZ_APP_BASENAME)
 AC_SUBST(MOZ_APP_VENDOR)
 AC_SUBST(MOZ_APP_PROFILE)
 AC_DEFINE_UNQUOTED(MOZ_APP_UA_NAME, "$MOZ_APP_UA_NAME")
 AC_SUBST(MOZ_APP_UA_NAME)
 AC_DEFINE_UNQUOTED(MOZ_APP_UA_VERSION, "$MOZ_APP_VERSION")
 AC_SUBST(MOZ_APP_VERSION)
 AC_DEFINE_UNQUOTED(MOZ_UA_FIREFOX_VERSION, "$FIREFOX_VERSION")
-AC_SUBST(MOZ_UA_FIREFOX_VERSION)
+AC_DEFINE_UNQUOTED(FIREFOX_VERSION,$FIREFOX_VERSION)
 AC_SUBST(FIREFOX_VERSION)
 AC_DEFINE_UNQUOTED(MOZ_UA_BUILDID, "$MOZ_UA_BUILDID")
 AC_SUBST(MOZ_UA_BUILDID)
 
 AC_SUBST(MOZ_PKG_SPECIAL)
 
 AC_SUBST(MOZILLA_OFFICIAL)
 
--- a/content/Makefile.in
+++ b/content/Makefile.in
@@ -38,26 +38,22 @@
 DEPTH		= ..
 topsrcdir	= @top_srcdir@
 srcdir		= @srcdir@
 VPATH		= @srcdir@
 
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= content
-PARALLEL_DIRS		= base canvas events html smil xml xul xbl xslt
+PARALLEL_DIRS		= base canvas events html smil svg xml xul xbl xslt
 
 ifdef MOZ_MEDIA
 PARALLEL_DIRS	+= media
 endif
 
-ifdef MOZ_SVG
-PARALLEL_DIRS	+= svg
-endif
-
 ifdef MOZ_XTF
 PARALLEL_DIRS   += xtf
 endif
 
 ifdef MOZ_MATHML
 PARALLEL_DIRS   += mathml
 endif
 
--- a/content/base/crashtests/552651.html
+++ b/content/base/crashtests/552651.html
@@ -4,24 +4,22 @@
   <title>Testcase for bug 552651</title>
   <script class="testbody" type="text/javascript">
 
 function testCancel() {
   var xhr = new XMLHttpRequest();
   xhr.addEventListener("readystatechange", function(e) {
     if (xhr.readyState == 3) // NOTE : only leaks for state == 3
       xhr.abort();
+    else if (xhr.readyState == 4)
+      document.documentElement.className = "";
   }, false);
 
   xhr.open("GET", "552651.xml", true);
   xhr.send();
-
-  setTimeout(function f() {
-      document.documentElement.className = "";
-  }, 1000);
 }
 </script>
 </head>
 <body onload="testCancel()">
 This test should not leak...
 </body>
 </html>
 
--- a/content/base/public/nsContentCID.h
+++ b/content/base/public/nsContentCID.h
@@ -209,25 +209,21 @@
 // {3A0A0FC1-8349-11d3-BE47-00104BDE6048}
 #define NS_XULPROTOTYPECACHE_CID \
 { 0x3a0a0fc1, 0x8349, 0x11d3, { 0xbe, 0x47, 0x0, 0x10, 0x4b, 0xde, 0x60, 0x48 } }
 
 // {a6cf9126-15b3-11d2-932e-00805f8add32}
 #define NS_RANGEUTILS_CID \
 { 0xa6cf9126, 0x15b3, 0x11d2, {0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 } }
 
-#ifdef MOZ_SVG
-
 #define NS_SVGDOCUMENT_CID                        \
 { /* b7f44954-1dd1-11b2-8c2e-c2feab4186bc */      \
   0xb7f44954, 0x11d1, 0x11b2,                     \
   {0x8c, 0x2e, 0xc2, 0xfe, 0xab, 0x41, 0x86, 0xbc}}
 
-#endif // MOZ_SVG
-
 #ifdef MOZ_MEDIA
 
 // {d899a152-9412-46b2-b651-2e71c5c2f05f}
 #define NS_VIDEODOCUMENT_CID   \
 { 0xd899a152, 0x9412, 0x46b2,  \
   { 0xb6, 0x51, 0x2e, 0x71, 0xc5, 0xc2, 0xf0, 0x5f } }
 
 #endif
--- a/content/base/public/nsContentCreatorFunctions.h
+++ b/content/base/public/nsContentCreatorFunctions.h
@@ -120,21 +120,19 @@ NS_NewMathMLElement(nsIContent** aResult
 #ifdef MOZ_XUL
 nsresult
 NS_NewXULElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo);
 
 void
 NS_TrustedNewXULElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo);
 #endif
 
-#ifdef MOZ_SVG
 nsresult
 NS_NewSVGElement(nsIContent** aResult, already_AddRefed<nsINodeInfo> aNodeInfo,
                  mozilla::dom::FromParser aFromParser);
-#endif
 
 nsresult
 NS_NewGenConImageContent(nsIContent** aResult,
                          already_AddRefed<nsINodeInfo> aNodeInfo,
                          imgIRequest* aImageRequest);
 
 nsresult
 NS_NewXMLEventsElement(nsIContent** aResult,
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -46,32 +46,42 @@
 #if defined(XP_WIN) || defined(XP_OS2)
 #include <float.h>
 #endif
 
 #if defined(SOLARIS)
 #include <ieeefp.h>
 #endif
 
+//A trick to handle IEEE floating point exceptions on FreeBSD - E.D.
+#ifdef __FreeBSD__
+#include <ieeefp.h>
+#ifdef __alpha__
+static fp_except_t allmask = FP_X_INV|FP_X_OFL|FP_X_UFL|FP_X_DZ|FP_X_IMP;
+#else
+static fp_except_t allmask = FP_X_INV|FP_X_OFL|FP_X_UFL|FP_X_DZ|FP_X_IMP|FP_X_DNML;
+#endif
+static fp_except_t oldmask = fpsetmask(~allmask);
+#endif
+
 #include "nsAString.h"
 #include "nsIStatefulFrame.h"
 #include "nsINodeInfo.h"
 #include "nsNodeInfoManager.h"
 #include "nsContentList.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIXPCScriptable.h"
 #include "nsIDOM3Node.h"
 #include "nsDataHashtable.h"
 #include "nsIScriptRuntime.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIDOMEvent.h"
 #include "nsTArray.h"
 #include "nsTextFragment.h"
 #include "nsReadableUtils.h"
-#include "nsIPrefBranch2.h"
 #include "mozilla/AutoRestore.h"
 #include "nsINode.h"
 #include "nsHashtable.h"
 
 struct nsNativeKeyEvent; // Don't include nsINativeKeyBindings.h here: it will force strange compilation error!
 
 class nsIDOMScriptObjectFactory;
 class nsIXPConnect;
@@ -88,17 +98,16 @@ class nsIThreadJSContextStack;
 class nsIParserService;
 class nsIIOService;
 class nsIURI;
 class imgIContainer;
 class imgIDecoderObserver;
 class imgIRequest;
 class imgILoader;
 class imgICache;
-class nsIPrefBranch2;
 class nsIImageLoadingContent;
 class nsIDOMHTMLFormElement;
 class nsIDOMDocument;
 class nsIConsoleService;
 class nsIStringBundleService;
 class nsIStringBundle;
 class nsIContentPolicy;
 class nsILineBreaker;
@@ -113,38 +122,31 @@ template<class K, class V> class nsRefPt
 struct JSRuntime;
 class nsIUGenCategory;
 class nsIWidget;
 class nsIDragSession;
 class nsPIDOMWindow;
 class nsPIDOMEventTarget;
 class nsIPresShell;
 class nsIXPConnectJSObjectHolder;
-class nsPrefOldCallback;
-class nsPrefObserverHashKey;
 #ifdef MOZ_XTF
 class nsIXTFService;
 #endif
 #ifdef IBMBIDI
 class nsIBidiKeyboard;
 #endif
 class nsIMIMEHeaderParam;
 class nsIObserver;
 class nsPresContext;
 class nsIChannel;
 class nsAutoScriptBlockerSuppressNodeRemoved;
 struct nsIntMargin;
 class nsPIDOMWindow;
 class nsIDocumentLoaderFactory;
 
-#ifndef have_PrefChangedFunc_typedef
-typedef int (*PR_CALLBACK PrefChangedFunc)(const char *, void *);
-#define have_PrefChangedFunc_typedef
-#endif
-
 namespace mozilla {
 
 namespace layers {
   class LayerManager;
 } // namespace layers
 
 namespace dom {
 class Element;
@@ -209,17 +211,18 @@ public:
   static nsresult GetContextAndScope(nsIDocument *aOldDocument,
                                      nsIDocument *aNewDocument,
                                      JSContext **aCx, JSObject **aNewScope);
 
   /**
    * When a document's scope changes (e.g., from document.open(), call this
    * function to move all content wrappers from the old scope to the new one.
    */
-  static nsresult ReparentContentWrappersInScope(nsIScriptGlobalObject *aOldScope,
+  static nsresult ReparentContentWrappersInScope(JSContext *cx,
+                                                 nsIScriptGlobalObject *aOldScope,
                                                  nsIScriptGlobalObject *aNewScope);
 
   static PRBool   IsCallerChrome();
 
   static PRBool   IsCallerTrustedForRead();
 
   static PRBool   IsCallerTrustedForWrite();
 
@@ -545,37 +548,16 @@ public:
   static nsresult GetNodeInfoFromQName(const nsAString& aNamespaceURI,
                                        const nsAString& aQualifiedName,
                                        nsNodeInfoManager* aNodeInfoManager,
                                        nsINodeInfo** aNodeInfo);
 
   static void SplitExpatName(const PRUnichar *aExpatName, nsIAtom **aPrefix,
                              nsIAtom **aTagName, PRInt32 *aNameSpaceID);
 
-  static nsAdoptingCString GetCharPref(const char *aPref);
-  static PRPackedBool GetBoolPref(const char *aPref,
-                                  PRBool aDefault = PR_FALSE);
-  static PRInt32 GetIntPref(const char *aPref, PRInt32 aDefault = 0);
-  static nsAdoptingString GetLocalizedStringPref(const char *aPref);
-  static nsAdoptingString GetStringPref(const char *aPref);
-  static void RegisterPrefCallback(const char *aPref,
-                                   PrefChangedFunc aCallback,
-                                   void * aClosure);
-  static void UnregisterPrefCallback(const char *aPref,
-                                     PrefChangedFunc aCallback,
-                                     void * aClosure);
-  static void AddBoolPrefVarCache(const char* aPref, PRBool* aVariable,
-                                  PRBool aDefault = PR_FALSE);
-  static void AddIntPrefVarCache(const char* aPref, PRInt32* aVariable,
-                                 PRInt32 aDefault = 0);
-  static nsIPrefBranch2 *GetPrefBranch()
-  {
-    return sPrefBranch;
-  }
-
   // Get a permission-manager setting for the given uri and type.
   // If the pref doesn't exist or if it isn't ALLOW_ACTION, PR_FALSE is
   // returned, otherwise PR_TRUE is returned.
   static PRBool IsSitePermAllow(nsIURI* aURI, const char* aType);
 
   static nsILineBreaker* LineBreaker()
   {
     return sLineBreaker;
@@ -765,19 +747,17 @@ public:
   enum PropertiesFile {
     eCSS_PROPERTIES,
     eXBL_PROPERTIES,
     eXUL_PROPERTIES,
     eLAYOUT_PROPERTIES,
     eFORMS_PROPERTIES,
     ePRINTING_PROPERTIES,
     eDOM_PROPERTIES,
-#ifdef MOZ_SVG
     eSVG_PROPERTIES,
-#endif
     eBRAND_PROPERTIES,
     eCOMMON_DIALOG_PROPERTIES,
     PropertiesFile_COUNT
   };
   static nsresult ReportToConsole(PropertiesFile aFile,
                                   const char *aMessageName,
                                   const PRUnichar **aParams,
                                   PRUint32 aParamsLength,
@@ -861,26 +841,16 @@ public:
   /**
    * Returns true if aDocument belongs to a chrome docshell for
    * display purposes.  Returns false for null documents or documents
    * which do not belong to a docshell.
    */
   static PRBool IsInChromeDocshell(nsIDocument *aDocument);
 
   /**
-   * Release *aSupportsPtr when the shutdown notification is received
-   */
-  static nsresult ReleasePtrOnShutdown(nsISupports** aSupportsPtr) {
-    NS_ASSERTION(aSupportsPtr, "Expect to crash!");
-    NS_ASSERTION(*aSupportsPtr, "Expect to crash!");
-    return sPtrsToPtrsToRelease->AppendElement(aSupportsPtr) != nsnull ? NS_OK :
-      NS_ERROR_OUT_OF_MEMORY;
-  }
-
-  /**
    * Return the content policy service
    */
   static nsIContentPolicy *GetContentPolicy();
 
   /**
    * Quick helper to determine whether there are any mutation listeners
    * of a given type that apply to this content or any of its ancestors.
    * The method has the side effect to call document's MayDispatchMutationEvent
@@ -1486,39 +1456,16 @@ public:
    *
    * The only known case where this lies is mutation events. They run, and can
    * run anything else, when this function returns false, but this is ok.
    */
   static PRBool IsSafeToRunScript() {
     return sScriptBlockerCount == 0;
   }
 
-  /**
-   * Get/Set the current number of removable updates. Currently only
-   * UPDATE_CONTENT_MODEL updates are removable, and only when firing mutation
-   * events. These functions should only be called by mozAutoDocUpdateRemover.
-   * The count is also adjusted by the normal calls to BeginUpdate/EndUpdate.
-   */
-  static void AddRemovableScriptBlocker()
-  {
-    AddScriptBlocker();
-    ++sRemovableScriptBlockerCount;
-  }
-  static void RemoveRemovableScriptBlocker()
-  {
-    NS_ASSERTION(sRemovableScriptBlockerCount != 0,
-                "Number of removable blockers should never go below zero");
-    --sRemovableScriptBlockerCount;
-    RemoveScriptBlocker();
-  }
-  static PRUint32 GetRemovableScriptBlockerLevel()
-  {
-    return sRemovableScriptBlockerCount;
-  }
-
   /* Process viewport META data. This gives us information for the scale
    * and zoom of a page on mobile devices. We stick the information in
    * the document header and use it later on after rendering.
    *
    * See Bug #436083
    */
   static nsresult ProcessViewportInfo(nsIDocument *aDocument,
                                       const nsAString &viewportInfo);
@@ -1818,21 +1765,16 @@ private:
   static nsINameSpaceManager *sNameSpaceManager;
 
   static nsIIOService *sIOService;
 
 #ifdef MOZ_XTF
   static nsIXTFService *sXTFService;
 #endif
 
-  static nsIPrefBranch2 *sPrefBranch;
-  // For old compatibility of RegisterPrefCallback
-  static nsRefPtrHashtable<nsPrefObserverHashKey, nsPrefOldCallback>
-    *sPrefCallbackTable;
-
   static bool sImgLoaderInitialized;
   static void InitImgLoader();
 
   // The following two members are initialized lazily
   static imgILoader* sImgLoader;
   static imgICache* sImgCache;
 
   static nsIConsoleService* sConsoleService;
@@ -1846,30 +1788,26 @@ private:
 
   static nsIContentPolicy* sContentPolicyService;
   static PRBool sTriedToGetContentPolicy;
 
   static nsILineBreaker* sLineBreaker;
   static nsIWordBreaker* sWordBreaker;
   static nsIUGenCategory* sGenCat;
 
-  // Holds pointers to nsISupports* that should be released at shutdown
-  static nsTArray<nsISupports**>* sPtrsToPtrsToRelease;
-
   static nsIScriptRuntime* sScriptRuntimes[NS_STID_ARRAY_UBOUND];
   static PRInt32 sScriptRootCount[NS_STID_ARRAY_UBOUND];
   static PRUint32 sJSGCThingRootCount;
 
 #ifdef IBMBIDI
   static nsIBidiKeyboard* sBidiKeyboard;
 #endif
 
   static PRBool sInitialized;
   static PRUint32 sScriptBlockerCount;
-  static PRUint32 sRemovableScriptBlockerCount;
 #ifdef DEBUG
   static PRUint32 sDOMNodeRemovedSuppressCount;
 #endif
   static nsCOMArray<nsIRunnable>* sBlockedScriptRunners;
   static PRUint32 sRunnersCountAtFirstBlocker;
   static PRUint32 sScriptBlockerCountWhereRunnersPrevented;
 
   static nsIInterfaceRequestor* sSameOriginChecker;
@@ -1927,43 +1865,16 @@ public:
   }
   ~nsAutoScriptBlocker() {
     nsContentUtils::RemoveScriptBlocker();
   }
 private:
   MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
-class NS_STACK_CLASS nsAutoRemovableScriptBlocker {
-public:
-  nsAutoRemovableScriptBlocker(MOZILLA_GUARD_OBJECT_NOTIFIER_ONLY_PARAM) {
-    MOZILLA_GUARD_OBJECT_NOTIFIER_INIT;
-    nsContentUtils::AddRemovableScriptBlocker();
-  }
-  ~nsAutoRemovableScriptBlocker() {
-    nsContentUtils::RemoveRemovableScriptBlocker();
-  }
-private:
-  MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER
-};
-
-class NS_STACK_CLASS mozAutoRemovableBlockerRemover
-{
-public:
-  mozAutoRemovableBlockerRemover(nsIDocument* aDocument
-                                 MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM);
-  ~mozAutoRemovableBlockerRemover();
-
-private:
-  PRUint32 mNestingLevel;
-  nsCOMPtr<nsIDocument> mDocument;
-  nsCOMPtr<nsIDocumentObserver> mObserver;
-  MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER
-};
-
 class NS_STACK_CLASS nsAutoScriptBlockerSuppressNodeRemoved :
                           public nsAutoScriptBlocker {
 public:
   nsAutoScriptBlockerSuppressNodeRemoved() {
 #ifdef DEBUG
     ++nsContentUtils::sDOMNodeRemovedSuppressCount;
 #endif
   }
@@ -1978,16 +1889,98 @@ public:
   if (aIID.Equals(NS_GET_IID(_interface))) {                                  \
     foundInterface = static_cast<_interface *>(_allocator);                   \
     if (!foundInterface) {                                                    \
       *aInstancePtr = nsnull;                                                 \
       return NS_ERROR_OUT_OF_MEMORY;                                          \
     }                                                                         \
   } else
 
+/**
+ * Macros to workaround math-bugs bugs in various platforms
+ */
+
+/**
+ * Stefan Hanske <sh990154@mail.uni-greifswald.de> reports:
+ *  ARM is a little endian architecture but 64 bit double words are stored
+ * differently: the 32 bit words are in little endian byte order, the two words
+ * are stored in big endian`s way.
+ */
+
+#if defined(__arm) || defined(__arm32__) || defined(__arm26__) || defined(__arm__)
+#if !defined(__VFP_FP__)
+#define FPU_IS_ARM_FPA
+#endif
+#endif
+
+typedef union dpun {
+    struct {
+#if defined(IS_LITTLE_ENDIAN) && !defined(FPU_IS_ARM_FPA)
+        PRUint32 lo, hi;
+#else
+        PRUint32 hi, lo;
+#endif
+    } s;
+    PRFloat64 d;
+public:
+    operator double() const {
+        return d;
+    }
+} dpun;
+
+/**
+ * Utility class for doubles
+ */
+#if (__GNUC__ == 2 && __GNUC_MINOR__ > 95) || __GNUC__ > 2
+/**
+ * This version of the macros is safe for the alias optimizations
+ * that gcc does, but uses gcc-specific extensions.
+ */
+#define DOUBLE_HI32(x) (__extension__ ({ dpun u; u.d = (x); u.s.hi; }))
+#define DOUBLE_LO32(x) (__extension__ ({ dpun u; u.d = (x); u.s.lo; }))
+
+#else // __GNUC__
+
+/* We don't know of any non-gcc compilers that perform alias optimization,
+ * so this code should work.
+ */
+
+#if defined(IS_LITTLE_ENDIAN) && !defined(FPU_IS_ARM_FPA)
+#define DOUBLE_HI32(x)        (((PRUint32 *)&(x))[1])
+#define DOUBLE_LO32(x)        (((PRUint32 *)&(x))[0])
+#else
+#define DOUBLE_HI32(x)        (((PRUint32 *)&(x))[0])
+#define DOUBLE_LO32(x)        (((PRUint32 *)&(x))[1])
+#endif
+
+#endif // __GNUC__
+
+#define DOUBLE_HI32_SIGNBIT   0x80000000
+#define DOUBLE_HI32_EXPMASK   0x7ff00000
+#define DOUBLE_HI32_MANTMASK  0x000fffff
+
+#define DOUBLE_IS_NaN(x)                                                \
+((DOUBLE_HI32(x) & DOUBLE_HI32_EXPMASK) == DOUBLE_HI32_EXPMASK && \
+ (DOUBLE_LO32(x) || (DOUBLE_HI32(x) & DOUBLE_HI32_MANTMASK)))
+
+#ifdef IS_BIG_ENDIAN
+#define DOUBLE_NaN {{DOUBLE_HI32_EXPMASK | DOUBLE_HI32_MANTMASK,   \
+                        0xffffffff}}
+#else
+#define DOUBLE_NaN {{0xffffffff,                                         \
+                        DOUBLE_HI32_EXPMASK | DOUBLE_HI32_MANTMASK}}
+#endif
+
+#if defined(XP_WIN)
+#define DOUBLE_COMPARE(LVAL, OP, RVAL)                                  \
+    (!DOUBLE_IS_NaN(LVAL) && !DOUBLE_IS_NaN(RVAL) && (LVAL) OP (RVAL))
+#else
+#define DOUBLE_COMPARE(LVAL, OP, RVAL) ((LVAL) OP (RVAL))
+#endif
+
 /*
  * Check whether a floating point number is finite (not +/-infinity and not a
  * NaN value).
  */
 inline NS_HIDDEN_(PRBool) NS_FloatIsFinite(jsdouble f) {
 #ifdef WIN32
   return _finite(f);
 #else
--- a/content/base/public/nsIDOMFile.idl
+++ b/content/base/public/nsIDOMFile.idl
@@ -77,13 +77,13 @@ interface nsIDOMFile : nsIDOMBlob
   readonly attribute DOMString fileName;
   readonly attribute unsigned long long fileSize;
   DOMString getAsText(in DOMString encoding); // raises(FileException) on retrieval
   DOMString getAsDataURL();             // raises(FileException) on retrieval
   DOMString getAsBinary();              // raises(FileException) on retrieval
 };
 
 [scriptable, uuid(c4a77171-039b-4f84-97f9-820fb51626af)]
-interface nsIDOMBlobBuilder : nsISupports
+interface nsIDOMMozBlobBuilder : nsISupports
 {
   nsIDOMBlob getBlob([optional] in DOMString contentType);
   [implicit_jscontext] void append(in jsval data);
 };
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -119,18 +119,18 @@ class Loader;
 namespace dom {
 class Link;
 class Element;
 } // namespace dom
 } // namespace mozilla
 
 
 #define NS_IDOCUMENT_IID      \
-{ 0x26ef6218, 0xcd5e, 0x4953,  \
- { 0xbb, 0x57, 0xb8, 0x50, 0x29, 0xa1, 0xae, 0x40 } }
+{ 0x2ec7872f, 0x97c3, 0x43de, \
+  { 0x81, 0x0a, 0x8f, 0x18, 0xa0, 0xa0, 0xdf, 0x30 } }
 
 // Flag for AddStyleSheet().
 #define NS_STYLESHEET_FROM_CATALOG                (1 << 0)
 
 // Document states
 
 // RTL locale: specific to the XUL localedir attribute
 #define NS_DOCUMENT_STATE_RTL_LOCALE              NS_DEFINE_EVENT_STATE_MACRO(0)
@@ -356,17 +356,17 @@ public:
    * registered.
    */
   virtual void RemoveIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
                                       void* aData, PRBool aForImage) = 0;
 
   /**
    * Get the Content-Type of this document.
    * (This will always return NS_OK, but has this signature to be compatible
-   *  with nsIDOMNSDocument::GetContentType())
+   *  with nsIDOMDocument::GetContentType())
    */
   NS_IMETHOD GetContentType(nsAString& aContentType) = 0;
 
   /**
    * Set the Content-Type of this document.
    */
   virtual void SetContentType(const nsAString& aContentType) = 0;
 
@@ -474,18 +474,16 @@ public:
 
   nsIPresShell* GetShell() const
   {
     return GetBFCacheEntry() ? nsnull : mPresShell;
   }
 
   void SetBFCacheEntry(nsISHEntry* aSHEntry) {
     mSHEntry = aSHEntry;
-    // Doing this just to keep binary compat for the gecko 2.0 release
-    mShellIsHidden = !!aSHEntry;
   }
 
   nsISHEntry* GetBFCacheEntry() const { return mSHEntry; }
 
   /**
    * Return the parent document of this document. Will return null
    * unless this document is within a compound document and has a
    * parent. Note that this parent chain may cross chrome boundaries.
@@ -1074,17 +1072,17 @@ public:
 
   /**
    * See GetContentListFor on nsBindingManager
    */
   virtual nsresult GetContentListFor(nsIContent* aContent,
                                      nsIDOMNodeList** aResult) = 0;
 
   /**
-   * Helper for nsIDOMNSDocument::elementFromPoint implementation that allows
+   * Helper for nsIDOMDocument::elementFromPoint implementation that allows
    * ignoring the scroll frame and/or avoiding layout flushes.
    *
    * @see nsIDOMWindowUtils::elementFromPoint
    */
   virtual nsresult ElementFromPointHelper(float aX, float aY,
                                           PRBool aIgnoreRootScrollFrame,
                                           PRBool aFlushLayout,
                                           nsIDOMElement** aReturn) = 0;
@@ -1514,16 +1512,18 @@ public:
   virtual nsresult RemoveImage(imgIRequest* aImage) = 0;
 
   // Makes the images on this document locked/unlocked. By default, the locking
   // state is unlocked/false.
   virtual nsresult SetImageLockingState(PRBool aLocked) = 0;
 
   virtual nsresult GetStateObject(nsIVariant** aResult) = 0;
 
+  virtual Element* FindImageMap(const nsAString& aNormalizedMapName) = 0;
+
 protected:
   ~nsIDocument()
   {
     // XXX The cleanup of mNodeInfoManager (calling DropDocumentReference and
     //     releasing it) happens in the nsDocument destructor. We'd prefer to
     //     do it here but nsNodeInfoManager is a concrete class that we don't
     //     want to expose to users of the nsIDocument API outside of Gecko.
   }
@@ -1616,20 +1616,16 @@ protected:
   PRPackedBool mMathMLEnabled;
 
   // True if this document is the initial document for a window.  This should
   // basically be true only for documents that exist in newly-opened windows or
   // documents created to satisfy a GetDocument() on a window when there's no
   // document in it.
   PRPackedBool mIsInitialDocumentInWindow;
 
-  // True if we're currently bfcached. This is only here for binary compat.
-  // Remove once the gecko 2.0 has branched and just use mSHEntry instead.
-  PRPackedBool mShellIsHidden;
-
   PRPackedBool mIsRegularHTML;
   PRPackedBool mIsXUL;
 
   enum {
     eTriUnset = 0,
     eTriFalse,
     eTriTrue
   } mAllowXULXBL;
@@ -1791,20 +1787,18 @@ private:
 
 // XXX These belong somewhere else
 nsresult
 NS_NewHTMLDocument(nsIDocument** aInstancePtrResult);
 
 nsresult
 NS_NewXMLDocument(nsIDocument** aInstancePtrResult);
 
-#ifdef MOZ_SVG
 nsresult
 NS_NewSVGDocument(nsIDocument** aInstancePtrResult);
-#endif
 
 nsresult
 NS_NewImageDocument(nsIDocument** aInstancePtrResult);
 
 #ifdef MOZ_MEDIA
 nsresult
 NS_NewVideoDocument(nsIDocument** aInstancePtrResult);
 #endif
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -509,18 +509,17 @@ public:
    * @param aNotify whether to notify the document (current document for
    *        nsIContent, and |this| for nsIDocument) that the remove has
    *        occurred
    * @param aMutationEvent whether to fire a mutation event
    *
    * Note: If there is no child at aIndex, this method will simply do nothing.
    */
   virtual nsresult RemoveChildAt(PRUint32 aIndex, 
-                                 PRBool aNotify, 
-                                 PRBool aMutationEvent = PR_TRUE) = 0;
+                                 PRBool aNotify) = 0;
 
   /**
    * Get a property associated with this node.
    *
    * @param aPropertyName  name of property to get.
    * @param aStatus        out parameter for storing resulting status.
    *                       Set to NS_PROPTABLE_PROP_NOT_THERE if the property
    *                       is not set.
@@ -1290,18 +1289,17 @@ protected:
    *
    * @param aIndex The index to remove at.
    * @param aNotify Whether to notify.
    * @param aKid The kid at aIndex.  Must not be null.
    * @param aChildArray The child array to work with.
    * @param aMutationEvent whether to fire a mutation event for this removal.
    */
   nsresult doRemoveChildAt(PRUint32 aIndex, PRBool aNotify, nsIContent* aKid,
-                           nsAttrAndChildArray& aChildArray,
-                           PRBool aMutationEvent);
+                           nsAttrAndChildArray& aChildArray);
 
   /**
    * Most of the implementation of the nsINode InsertChildAt method.
    * Should only be called on document, element, and document fragment
    * nodes.  The aChildArray passed in should be the one for |this|.
    *
    * @param aKid The child to insert.
    * @param aIndex The index to insert at.
--- a/content/base/src/mozAutoDocUpdate.h
+++ b/content/base/src/mozAutoDocUpdate.h
@@ -47,32 +47,26 @@ public:
   mozAutoDocUpdate(nsIDocument* aDocument, nsUpdateType aUpdateType,
                    PRBool aNotify) :
     mDocument(aNotify ? aDocument : nsnull),
     mUpdateType(aUpdateType)
   {
     if (mDocument) {
       mDocument->BeginUpdate(mUpdateType);
     }
-    else if (aUpdateType == UPDATE_CONTENT_MODEL) {
-      nsContentUtils::AddRemovableScriptBlocker();
-    }
     else {
       nsContentUtils::AddScriptBlocker();
     }
   }
 
   ~mozAutoDocUpdate()
   {
     if (mDocument) {
       mDocument->EndUpdate(mUpdateType);
     }
-    else if (mUpdateType == UPDATE_CONTENT_MODEL) {
-      nsContentUtils::RemoveRemovableScriptBlocker();
-    }
     else {
       nsContentUtils::RemoveScriptBlocker();
     }
   }
 
 private:
   nsCOMPtr<nsIDocument> mDocument;
   nsUpdateType mUpdateType;
--- a/content/base/src/nsAttrValue.cpp
+++ b/content/base/src/nsAttrValue.cpp
@@ -47,19 +47,17 @@
 #include "mozilla/css/StyleRule.h"
 #include "mozilla/css/Declaration.h"
 #include "nsIHTMLDocument.h"
 #include "nsIDocument.h"
 #include "nsTPtrArray.h"
 #include "nsContentUtils.h"
 #include "nsReadableUtils.h"
 #include "prprf.h"
-#ifdef MOZ_SVG
 #include "nsISVGValue.h"
-#endif
 
 namespace css = mozilla::css;
 
 #define MISC_STR_PTR(_cont) \
   reinterpret_cast<void*>((_cont)->mStringBits & NS_ATTRVALUE_POINTERVALUE_MASK)
 
 nsTPtrArray<const nsAttrValue::EnumTable>* nsAttrValue::sEnumTableArray = nsnull;
 
@@ -81,23 +79,21 @@ nsAttrValue::nsAttrValue(const nsAString
 }
 
 nsAttrValue::nsAttrValue(css::StyleRule* aValue, const nsAString* aSerialized)
     : mBits(0)
 {
   SetTo(aValue, aSerialized);
 }
 
-#ifdef MOZ_SVG
 nsAttrValue::nsAttrValue(nsISVGValue* aValue)
     : mBits(0)
 {
   SetTo(aValue);
 }
-#endif
 
 nsAttrValue::nsAttrValue(const nsIntMargin& aValue)
     : mBits(0)
 {
   SetTo(aValue);
 }
 
 nsAttrValue::~nsAttrValue()
@@ -250,23 +246,21 @@ nsAttrValue::SetTo(const nsAttrValue& aO
     {
       if (!EnsureEmptyAtomArray() ||
           !GetAtomArrayValue()->AppendElements(*otherCont->mAtomArray)) {
         Reset();
         return;
       }
       break;
     }
-#ifdef MOZ_SVG
     case eSVGValue:
     {
       NS_ADDREF(cont->mSVGValue = otherCont->mSVGValue);
       break;
     }
-#endif
     case eDoubleValue:
     {
       cont->mDoubleValue = otherCont->mDoubleValue;
       break;
     }
     case eIntMarginValue:
     {
       if (otherCont->mIntMargin)
@@ -318,27 +312,25 @@ nsAttrValue::SetTo(css::StyleRule* aValu
   if (EnsureEmptyMiscContainer()) {
     MiscContainer* cont = GetMiscContainer();
     NS_ADDREF(cont->mCSSStyleRule = aValue);
     cont->mType = eCSSStyleRule;
     SetMiscAtomOrString(aSerialized);
   }
 }
 
-#ifdef MOZ_SVG
 void
 nsAttrValue::SetTo(nsISVGValue* aValue)
 {
   if (EnsureEmptyMiscContainer()) {
     MiscContainer* cont = GetMiscContainer();
     NS_ADDREF(cont->mSVGValue = aValue);
     cont->mType = eSVGValue;
   }
 }
-#endif
 
 void
 nsAttrValue::SetTo(const nsIntMargin& aValue)
 {
   if (EnsureEmptyMiscContainer()) {
     MiscContainer* cont = GetMiscContainer();
     cont->mIntMargin = new nsIntMargin(aValue);
     cont->mType = eIntMarginValue;
@@ -431,23 +423,21 @@ nsAttrValue::ToString(nsAString& aResult
       css::Declaration *decl = container->mCSSStyleRule->GetDeclaration();
       if (decl) {
         decl->ToString(aResult);
       }
       const_cast<nsAttrValue*>(this)->SetMiscAtomOrString(&aResult);
 
       break;
     }
-#ifdef MOZ_SVG
     case eSVGValue:
     {
       GetMiscContainer()->mSVGValue->GetValueString(aResult);
       break;
     }
-#endif
     case eDoubleValue:
     {
       aResult.Truncate();
       aResult.AppendFloat(GetDoubleValue());
       break;
     }
     default:
     {
@@ -596,22 +586,20 @@ nsAttrValue::HashValue() const
       PRUint32 count = cont->mAtomArray->Length();
       for (nsCOMPtr<nsIAtom> *cur = cont->mAtomArray->Elements(),
                              *end = cur + count;
            cur != end; ++cur) {
         retval ^= NS_PTR_TO_INT32(cur->get());
       }
       return retval;
     }
-#ifdef MOZ_SVG
     case eSVGValue:
     {
       return NS_PTR_TO_INT32(cont->mSVGValue);
     }
-#endif
     case eDoubleValue:
     {
       // XXX this is crappy, but oh well
       return cont->mDoubleValue;
     }
     case eIntMarginValue:
     {
       return NS_PTR_TO_INT32(cont->mIntMargin);
@@ -695,22 +683,20 @@ nsAttrValue::Equals(const nsAttrValue& a
 
       if (!(*thisCont->mAtomArray == *otherCont->mAtomArray)) {
         return PR_FALSE;
       }
 
       needsStringComparison = PR_TRUE;
       break;
     }
-#ifdef MOZ_SVG
     case eSVGValue:
     {
       return thisCont->mSVGValue == otherCont->mSVGValue;
     }
-#endif
     case eDoubleValue:
     {
       return thisCont->mDoubleValue == otherCont->mDoubleValue;
     }
     case eIntMarginValue:
     {
       return thisCont->mIntMargin == otherCont->mIntMargin;
     }
@@ -1304,23 +1290,21 @@ nsAttrValue::EnsureEmptyMiscContainer()
         NS_RELEASE(cont->mCSSStyleRule);
         break;
       }
       case eAtomArray:
       {
         delete cont->mAtomArray;
         break;
       }
-#ifdef MOZ_SVG
       case eSVGValue:
       {
         NS_RELEASE(cont->mSVGValue);
         break;
       }
-#endif
       case eIntMarginValue:
       {
         delete cont->mIntMargin;
         break;
       }
       default:
       {
         break;
--- a/content/base/src/nsAttrValue.h
+++ b/content/base/src/nsAttrValue.h
@@ -100,19 +100,17 @@ public:
 class nsAttrValue {
 public:
   typedef nsTArray< nsCOMPtr<nsIAtom> > AtomArray;
 
   nsAttrValue();
   nsAttrValue(const nsAttrValue& aOther);
   explicit nsAttrValue(const nsAString& aValue);
   nsAttrValue(mozilla::css::StyleRule* aValue, const nsAString* aSerialized);
-#ifdef MOZ_SVG
   explicit nsAttrValue(nsISVGValue* aValue);
-#endif
   explicit nsAttrValue(const nsIntMargin& aValue);
   ~nsAttrValue();
 
   static nsresult Init();
   static void Shutdown();
 
   // This has to be the same as in ValueBaseType
   enum ValueType {
@@ -122,34 +120,30 @@ public:
     eInteger =      0x03, // 0011
     eColor =        0x07, // 0111
     eEnum =         0x0B, // 1011  This should eventually die
     ePercent =      0x0F, // 1111
     // Values below here won't matter, they'll be always stored in the 'misc'
     // struct.
     eCSSStyleRule = 0x10,
     eAtomArray =    0x11 
-#ifdef MOZ_SVG
     ,eSVGValue =    0x12
-#endif
     ,eDoubleValue  = 0x13
     ,eIntMarginValue = 0x14
   };
 
   ValueType Type() const;
 
   void Reset();
 
   void SetTo(const nsAttrValue& aOther);
   void SetTo(const nsAString& aValue);
   void SetTo(PRInt16 aInt);
   void SetTo(mozilla::css::StyleRule* aValue, const nsAString* aSerialized);
-#ifdef MOZ_SVG
   void SetTo(nsISVGValue* aValue);
-#endif
   void SetTo(const nsIntMargin& aValue);
 
   void SwapValueWith(nsAttrValue& aOther);
 
   void ToString(nsAString& aResult) const;
 
   // Methods to get value. These methods do not convert so only use them
   // to retrieve the datatype that this nsAttrValue has.
@@ -157,19 +151,17 @@ public:
   const nsCheapString GetStringValue() const;
   inline nsIAtom* GetAtomValue() const;
   inline PRInt32 GetIntegerValue() const;
   PRBool GetColorValue(nscolor& aColor) const;
   inline PRInt16 GetEnumValue() const;
   inline float GetPercentValue() const;
   inline AtomArray* GetAtomArrayValue() const;
   inline mozilla::css::StyleRule* GetCSSStyleRuleValue() const;
-#ifdef MOZ_SVG
   inline nsISVGValue* GetSVGValue() const;
-#endif
   inline double GetDoubleValue() const;
   PRBool GetIntMarginValue(nsIntMargin& aMargin) const;
 
   /**
    * Returns the string corresponding to the stored enum value.
    *
    * @param aResult   the string representing the enum tag
    * @param aRealTag  wheter we want to have the real tag or the saved one
@@ -338,19 +330,17 @@ private:
     PtrBits mStringBits;
     union {
       PRInt32 mInteger;
       nscolor mColor;
       PRUint32 mEnumValue;
       PRInt32 mPercent;
       mozilla::css::StyleRule* mCSSStyleRule;
       AtomArray* mAtomArray;
-#ifdef MOZ_SVG
       nsISVGValue* mSVGValue;
-#endif
       double mDoubleValue;
       nsIntMargin* mIntMargin;
     };
   };
 
   inline ValueBaseType BaseType() const;
 
   /**
@@ -444,24 +434,22 @@ nsAttrValue::GetAtomArrayValue() const
 
 inline mozilla::css::StyleRule*
 nsAttrValue::GetCSSStyleRuleValue() const
 {
   NS_PRECONDITION(Type() == eCSSStyleRule, "wrong type");
   return GetMiscContainer()->mCSSStyleRule;
 }
 
-#ifdef MOZ_SVG
 inline nsISVGValue*
 nsAttrValue::GetSVGValue() const
 {
   NS_PRECONDITION(Type() == eSVGValue, "wrong type");
   return GetMiscContainer()->mSVGValue;
 }
-#endif
 
 inline double
 nsAttrValue::GetDoubleValue() const
 {
   NS_PRECONDITION(Type() == eDoubleValue, "wrong type");
   return GetMiscContainer()->mDoubleValue;
 }
 
--- a/content/base/src/nsCSPService.cpp
+++ b/content/base/src/nsCSPService.cpp
@@ -39,38 +39,40 @@
 #include "prlog.h"
 #include "nsString.h"
 #include "nsCOMPtr.h"
 #include "nsIURI.h"
 #include "nsIPrincipal.h"
 #include "nsIObserver.h"
 #include "nsIDocument.h"
 #include "nsIContent.h"
-#include "nsContentUtils.h"
 #include "nsCSPService.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsIChannelPolicy.h"
 #include "nsIChannelEventSink.h"
 #include "nsIPropertyBag2.h"
 #include "nsIWritablePropertyBag2.h"
 #include "nsNetError.h"
 #include "nsChannelProperties.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsAsyncRedirectVerifyHelper.h"
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 
 /* Keeps track of whether or not CSP is enabled */
 PRBool CSPService::sCSPEnabled = PR_TRUE;
 
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gCspPRLog;
 #endif
 
 CSPService::CSPService()
 {
-  nsContentUtils::AddBoolPrefVarCache("security.csp.enable", &sCSPEnabled);
+  Preferences::AddBoolVarCache(&sCSPEnabled, "security.csp.enable");
 
 #ifdef PR_LOGGING
   if (!gCspPRLog)
     gCspPRLog = PR_NewLogModule("CSP");
 #endif
 }
 
 CSPService::~CSPService()
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -84,30 +84,32 @@
 #include "nsCRT.h"
 #include "nsEscape.h"
 #include "nsWeakReference.h"
 #include "nsUnicharUtils.h"
 #include "nsNodeInfoManager.h"
 #include "nsIAppShell.h"
 #include "nsIWidget.h"
 #include "nsWidgetsCID.h"
-#include "nsIDOMNSDocument.h"
 #include "nsIRequest.h"
 #include "nsNodeUtils.h"
 #include "nsIDOMNode.h"
 #include "nsThreadUtils.h"
 #include "nsPIDOMWindow.h"
 #include "mozAutoDocUpdate.h"
 #include "nsIWebNavigation.h"
 #include "nsIDocumentLoader.h"
 #include "nsICachingChannel.h"
 #include "nsICacheEntryDescriptor.h"
 #include "nsGenericHTMLElement.h"
 #include "nsHTMLDNSPrefetch.h"
 #include "nsISupportsPrimitives.h"
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 
 PRLogModuleInfo* gContentSinkLogModuleInfo;
 
 class nsScriptLoaderObserverProxy : public nsIScriptLoaderObserver
 {
 public:
   nsScriptLoaderObserverProxy(nsIScriptLoaderObserver* aInner)
     : mInner(do_GetWeakReference(aInner))
@@ -228,51 +230,50 @@ PRInt32 nsContentSink::sPerfParseTime;
 PRInt32 nsContentSink::sInteractiveTime;
 PRInt32 nsContentSink::sInitialPerfTime;
 PRInt32 nsContentSink::sEnablePerfMode;
 PRBool  nsContentSink::sCanInterruptParser;
 
 void
 nsContentSink::InitializeStatics()
 {
-  nsContentUtils::AddBoolPrefVarCache("content.notify.ontimer",
-                                      &sNotifyOnTimer, PR_TRUE);
+  Preferences::AddBoolVarCache(&sNotifyOnTimer,
+                               "content.notify.ontimer", PR_TRUE);
   // -1 means never.
-  nsContentUtils::AddIntPrefVarCache("content.notify.backoffcount",
-                                     &sBackoffCount, -1);
+  Preferences::AddIntVarCache(&sBackoffCount,
+                              "content.notify.backoffcount", -1);
   // The gNotificationInterval has a dramatic effect on how long it
   // takes to initially display content for slow connections.
   // The current value provides good
   // incremental display of content without causing an increase
   // in page load time. If this value is set below 1/10 of second
   // it starts to impact page load performance.
   // see bugzilla bug 72138 for more info.
-  nsContentUtils::AddIntPrefVarCache("content.notify.interval",
-                                     &sNotificationInterval,
-                                     120000);
-  nsContentUtils::AddIntPrefVarCache("content.sink.interactive_deflect_count",
-                                     &sInteractiveDeflectCount, 0);
-  nsContentUtils::AddIntPrefVarCache("content.sink.perf_deflect_count",
-                                     &sPerfDeflectCount, 200);
-  nsContentUtils::AddIntPrefVarCache("content.sink.pending_event_mode",
-                                     &sPendingEventMode, 1);
-  nsContentUtils::AddIntPrefVarCache("content.sink.event_probe_rate",
-                                     &sEventProbeRate, 1);
-  nsContentUtils::AddIntPrefVarCache("content.sink.interactive_parse_time",
-                                     &sInteractiveParseTime, 3000);
-  nsContentUtils::AddIntPrefVarCache("content.sink.perf_parse_time",
-                                     &sPerfParseTime, 360000);
-  nsContentUtils::AddIntPrefVarCache("content.sink.interactive_time",
-                                     &sInteractiveTime, 750000);
-  nsContentUtils::AddIntPrefVarCache("content.sink.initial_perf_time",
-                                     &sInitialPerfTime, 2000000);
-  nsContentUtils::AddIntPrefVarCache("content.sink.enable_perf_mode",
-                                     &sEnablePerfMode, 0);
-  nsContentUtils::AddBoolPrefVarCache("content.interrupt.parsing",
-                                      &sCanInterruptParser, PR_TRUE);
+  Preferences::AddIntVarCache(&sNotificationInterval,
+                              "content.notify.interval", 120000);
+  Preferences::AddIntVarCache(&sInteractiveDeflectCount,
+                              "content.sink.interactive_deflect_count", 0);
+  Preferences::AddIntVarCache(&sPerfDeflectCount,
+                              "content.sink.perf_deflect_count", 200);
+  Preferences::AddIntVarCache(&sPendingEventMode,
+                              "content.sink.pending_event_mode", 1);
+  Preferences::AddIntVarCache(&sEventProbeRate,
+                              "content.sink.event_probe_rate", 1);
+  Preferences::AddIntVarCache(&sInteractiveParseTime,
+                              "content.sink.interactive_parse_time", 3000);
+  Preferences::AddIntVarCache(&sPerfParseTime,
+                              "content.sink.perf_parse_time", 360000);
+  Preferences::AddIntVarCache(&sInteractiveTime,
+                              "content.sink.interactive_time", 750000);
+  Preferences::AddIntVarCache(&sInitialPerfTime,
+                              "content.sink.initial_perf_time", 2000000);
+  Preferences::AddIntVarCache(&sEnablePerfMode,
+                              "content.sink.enable_perf_mode", 0);
+  Preferences::AddBoolVarCache(&sCanInterruptParser,
+                               "content.interrupt.parsing", PR_TRUE);
 }
 
 nsresult
 nsContentSink::Init(nsIDocument* aDoc,
                     nsIURI* aURI,
                     nsISupports* aContainer,
                     nsIChannel* aChannel)
 {
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -44,19 +44,16 @@
 
 #include "jscntxt.h"
 
 #include "nsJSUtils.h"
 #include "nsCOMPtr.h"
 #include "nsAString.h"
 #include "nsPrintfCString.h"
 #include "nsUnicharUtils.h"
-#include "nsIPrefService.h"
-#include "nsIPrefBranch2.h"
-#include "nsIPrefLocalizedString.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptContext.h"
 #include "nsIDOMScriptObjectFactory.h"
 #include "nsDOMCID.h"
 #include "nsContentUtils.h"
 #include "nsIXPConnect.h"
 #include "nsIContent.h"
@@ -206,18 +203,21 @@ static NS_DEFINE_CID(kXTFServiceCID, NS_
 #include "nsChannelPolicy.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsContentDLF.h"
 #ifdef MOZ_MEDIA
 #include "nsHTMLMediaElement.h"
 #endif
 #include "nsDOMTouchEvent.h"
 
+#include "mozilla/Preferences.h"
+
 using namespace mozilla::dom;
 using namespace mozilla::layers;
+using namespace mozilla;
 
 const char kLoadAsData[] = "loadAsData";
 
 static const char kJSStackContractID[] = "@mozilla.org/js/xpc/ContextStack;1";
 static NS_DEFINE_CID(kParserServiceCID, NS_PARSERSERVICE_CID);
 static NS_DEFINE_CID(kCParserCID, NS_PARSER_CID);
 
 nsIDOMScriptObjectFactory *nsContentUtils::sDOMScriptObjectFactory = nsnull;
@@ -225,55 +225,49 @@ nsIXPConnect *nsContentUtils::sXPConnect
 nsIScriptSecurityManager *nsContentUtils::sSecurityManager;
 nsIThreadJSContextStack *nsContentUtils::sThreadJSContextStack;
 nsIParserService *nsContentUtils::sParserService = nsnull;
 nsINameSpaceManager *nsContentUtils::sNameSpaceManager;
 nsIIOService *nsContentUtils::sIOService;
 #ifdef MOZ_XTF
 nsIXTFService *nsContentUtils::sXTFService = nsnull;
 #endif
-nsIPrefBranch2 *nsContentUtils::sPrefBranch = nsnull;
 imgILoader *nsContentUtils::sImgLoader;
 imgICache *nsContentUtils::sImgCache;
 nsIConsoleService *nsContentUtils::sConsoleService;
 nsDataHashtable<nsISupportsHashKey, EventNameMapping>* nsContentUtils::sAtomEventTable = nsnull;
 nsDataHashtable<nsStringHashKey, EventNameMapping>* nsContentUtils::sStringEventTable = nsnull;
 nsCOMArray<nsIAtom>* nsContentUtils::sUserDefinedEvents = nsnull;
 nsIStringBundleService *nsContentUtils::sStringBundleService;
 nsIStringBundle *nsContentUtils::sStringBundles[PropertiesFile_COUNT];
 nsIContentPolicy *nsContentUtils::sContentPolicyService;
 PRBool nsContentUtils::sTriedToGetContentPolicy = PR_FALSE;
 nsILineBreaker *nsContentUtils::sLineBreaker;
 nsIWordBreaker *nsContentUtils::sWordBreaker;
 nsIUGenCategory *nsContentUtils::sGenCat;
-nsTArray<nsISupports**> *nsContentUtils::sPtrsToPtrsToRelease;
 nsIScriptRuntime *nsContentUtils::sScriptRuntimes[NS_STID_ARRAY_UBOUND];
 PRInt32 nsContentUtils::sScriptRootCount[NS_STID_ARRAY_UBOUND];
 PRUint32 nsContentUtils::sJSGCThingRootCount;
 #ifdef IBMBIDI
 nsIBidiKeyboard *nsContentUtils::sBidiKeyboard = nsnull;
 #endif
 PRUint32 nsContentUtils::sScriptBlockerCount = 0;
-PRUint32 nsContentUtils::sRemovableScriptBlockerCount = 0;
 #ifdef DEBUG
 PRUint32 nsContentUtils::sDOMNodeRemovedSuppressCount = 0;
 #endif
 nsCOMArray<nsIRunnable>* nsContentUtils::sBlockedScriptRunners = nsnull;
 PRUint32 nsContentUtils::sRunnersCountAtFirstBlocker = 0;
 PRUint32 nsContentUtils::sScriptBlockerCountWhereRunnersPrevented = 0;
 nsIInterfaceRequestor* nsContentUtils::sSameOriginChecker = nsnull;
 
 PRBool nsContentUtils::sIsHandlingKeyBoardEvent = PR_FALSE;
 PRBool nsContentUtils::sAllowXULXBL_for_file = PR_FALSE;
 
 PRBool nsContentUtils::sInitialized = PR_FALSE;
 
-nsRefPtrHashtable<nsPrefObserverHashKey, nsPrefOldCallback>
-  *nsContentUtils::sPrefCallbackTable = nsnull;
-
 static PLDHashTable sEventListenerManagersHash;
 
 class EventListenerManagerMapEntry : public PLDHashEntryHdr
 {
 public:
   EventListenerManagerMapEntry(const void *aKey)
     : mKey(aKey)
   {
@@ -313,135 +307,26 @@ EventListenerManagerHashClearEntry(PLDHa
 class nsSameOriginChecker : public nsIChannelEventSink,
                             public nsIInterfaceRequestor
 {
   NS_DECL_ISUPPORTS
   NS_DECL_NSICHANNELEVENTSINK
   NS_DECL_NSIINTERFACEREQUESTOR
 };
 
-class nsPrefObserverHashKey : public PLDHashEntryHdr {
-public:
-  typedef nsPrefObserverHashKey* KeyType;
-  typedef const nsPrefObserverHashKey* KeyTypePointer;
-
-  static const nsPrefObserverHashKey* KeyToPointer(nsPrefObserverHashKey *aKey)
-  {
-    return aKey;
-  }
-
-  static PLDHashNumber HashKey(const nsPrefObserverHashKey *aKey)
-  {
-    PRUint32 strHash = nsCRT::HashCode(aKey->mPref.BeginReading(),
-                                       aKey->mPref.Length());
-    return PR_ROTATE_LEFT32(strHash, 4) ^
-           NS_PTR_TO_UINT32(aKey->mCallback);
-  }
-
-  nsPrefObserverHashKey(const char *aPref, PrefChangedFunc aCallback) :
-    mPref(aPref), mCallback(aCallback) { }
-
-  nsPrefObserverHashKey(const nsPrefObserverHashKey *aOther) :
-    mPref(aOther->mPref), mCallback(aOther->mCallback)
-  { }
-
-  PRBool KeyEquals(const nsPrefObserverHashKey *aOther) const
-  {
-    return mCallback == aOther->mCallback &&
-           mPref.Equals(aOther->mPref);
-  }
-
-  nsPrefObserverHashKey *GetKey() const
-  {
-    return const_cast<nsPrefObserverHashKey*>(this);
-  }
-
-  enum { ALLOW_MEMMOVE = PR_TRUE };
-
-public:
-  nsCString mPref;
-  PrefChangedFunc mCallback;
-};
-
-// For nsContentUtils::RegisterPrefCallback/UnregisterPrefCallback
-class nsPrefOldCallback : public nsIObserver,
-                          public nsPrefObserverHashKey
-{
-public:
-  NS_DECL_ISUPPORTS
-  NS_DECL_NSIOBSERVER
-
-public:
-  nsPrefOldCallback(const char *aPref, PrefChangedFunc aCallback)
-    : nsPrefObserverHashKey(aPref, aCallback) { }
-
-  ~nsPrefOldCallback() {
-    nsIPrefBranch2 *prefBranch = nsContentUtils::GetPrefBranch();
-    if(prefBranch)
-      prefBranch->RemoveObserver(mPref.get(), this);
-  }
-
-  void AppendClosure(void *aClosure) {
-    mClosures.AppendElement(aClosure);
-  }
-
-  void RemoveClosure(void *aClosure) {
-    mClosures.RemoveElement(aClosure);
-  }
-
-  PRBool HasNoClosures() {
-    return mClosures.Length() == 0;
-  }
-
-public:
-  nsTArray<void *>  mClosures;
-};
-
-NS_IMPL_ISUPPORTS1(nsPrefOldCallback, nsIObserver)
-
-NS_IMETHODIMP
-nsPrefOldCallback::Observe(nsISupports     *aSubject,
-                           const char      *aTopic,
-                           const PRUnichar *aData)
-{
-  NS_ASSERTION(!strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID),
-               "invalid topic");
-  NS_LossyConvertUTF16toASCII data(aData);
-  for (PRUint32 i = 0; i < mClosures.Length(); i++) {
-    mCallback(data.get(), mClosures.ElementAt(i));
-  }
-
-  return NS_OK;
-}
-
-struct PrefCacheData {
-  void* cacheLocation;
-  union {
-    PRBool defaultValueBool;
-    PRInt32 defaultValueInt;
-  };
-};
-
-nsTArray<nsAutoPtr<PrefCacheData> >* sPrefCacheData = nsnull;
-
 // static
 nsresult
 nsContentUtils::Init()
 {
   if (sInitialized) {
     NS_WARNING("Init() called twice");
 
     return NS_OK;
   }
 
-  sPrefCacheData = new nsTArray<nsAutoPtr<PrefCacheData> >();
-
-  // It's ok to not have a pref service.
-  CallGetService(NS_PREFSERVICE_CONTRACTID, &sPrefBranch);
-
   nsresult rv = NS_GetNameSpaceManager(&sNameSpaceManager);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsXPConnect* xpconnect = nsXPConnect::GetXPConnect();
   NS_ENSURE_TRUE(xpconnect, NS_ERROR_FAILURE);
 
   sXPConnect = xpconnect;
   sThreadJSContextStack = xpconnect;
@@ -462,21 +347,16 @@ nsContentUtils::Init()
   NS_ENSURE_SUCCESS(rv, rv);
   
   rv = CallGetService(NS_WBRK_CONTRACTID, &sWordBreaker);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = CallGetService(NS_UNICHARCATEGORY_CONTRACTID, &sGenCat);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  sPtrsToPtrsToRelease = new nsTArray<nsISupports**>();
-  if (!sPtrsToPtrsToRelease) {
-    return NS_ERROR_OUT_OF_MEMORY;
-  }
-
   if (!InitializeEventTable())
     return NS_ERROR_FAILURE;
 
   if (!sEventListenerManagersHash.ops) {
     static PLDHashTableOps hash_table_ops =
     {
       PL_DHashAllocTable,
       PL_DHashFreeTable,
@@ -494,18 +374,18 @@ nsContentUtils::Init()
 
       return NS_ERROR_OUT_OF_MEMORY;
     }
   }
 
   sBlockedScriptRunners = new nsCOMArray<nsIRunnable>;
   NS_ENSURE_TRUE(sBlockedScriptRunners, NS_ERROR_OUT_OF_MEMORY);
 
-  nsContentUtils::AddBoolPrefVarCache("dom.allow_XUL_XBL_for_file",
-                                      &sAllowXULXBL_for_file);
+  Preferences::AddBoolVarCache(&sAllowXULXBL_for_file,
+                               "dom.allow_XUL_XBL_for_file");
 
   sInitialized = PR_TRUE;
 
   return NS_OK;
 }
 
 bool nsContentUtils::sImgLoaderInitialized;
 
@@ -622,29 +502,27 @@ nsContentUtils::InitializeEventTable() {
     { nsGkAtoms::ondrag,                        NS_DRAGDROP_DRAG, EventNameType_HTMLXUL, NS_DRAG_EVENT },
     { nsGkAtoms::ondragend,                     NS_DRAGDROP_END, EventNameType_HTMLXUL, NS_DRAG_EVENT },
     { nsGkAtoms::ondragstart,                   NS_DRAGDROP_START, EventNameType_HTMLXUL, NS_DRAG_EVENT },
     { nsGkAtoms::ondragleave,                   NS_DRAGDROP_LEAVE_SYNTH, EventNameType_HTMLXUL, NS_DRAG_EVENT },
     { nsGkAtoms::ondrop,                        NS_DRAGDROP_DROP, EventNameType_HTMLXUL, NS_DRAG_EVENT },
 
     { nsGkAtoms::onoverflow,                    NS_SCROLLPORT_OVERFLOW, EventNameType_XUL, NS_EVENT_NULL},
     { nsGkAtoms::onunderflow,                   NS_SCROLLPORT_UNDERFLOW, EventNameType_XUL, NS_EVENT_NULL},
-#ifdef MOZ_SVG
     { nsGkAtoms::onSVGLoad,                     NS_SVG_LOAD, EventNameType_None, NS_SVG_EVENT },
     { nsGkAtoms::onSVGUnload,                   NS_SVG_UNLOAD, EventNameType_None, NS_SVG_EVENT },
     { nsGkAtoms::onSVGAbort,                    NS_SVG_ABORT, EventNameType_None, NS_SVG_EVENT },
     { nsGkAtoms::onSVGError,                    NS_SVG_ERROR, EventNameType_None, NS_SVG_EVENT },
     { nsGkAtoms::onSVGResize,                   NS_SVG_RESIZE, EventNameType_None, NS_SVG_EVENT },
     { nsGkAtoms::onSVGScroll,                   NS_SVG_SCROLL, EventNameType_None, NS_SVG_EVENT },
 
     { nsGkAtoms::onSVGZoom,                     NS_SVG_ZOOM, EventNameType_None, NS_SVGZOOM_EVENT },
 
     // This is a bit hackish, but SVG's event names are weird.
     { nsGkAtoms::onzoom,                        NS_SVG_ZOOM, EventNameType_SVGSVG, NS_EVENT_NULL },
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
     { nsGkAtoms::onbegin,                       NS_SMIL_BEGIN, EventNameType_SMIL, NS_EVENT_NULL },
     { nsGkAtoms::onbeginEvent,                  NS_SMIL_BEGIN, EventNameType_None, NS_SMIL_TIME_EVENT },
     { nsGkAtoms::onend,                         NS_SMIL_END, EventNameType_SMIL, NS_EVENT_NULL },
     { nsGkAtoms::onendEvent,                    NS_SMIL_END, EventNameType_None, NS_SMIL_TIME_EVENT },
     { nsGkAtoms::onrepeat,                      NS_SMIL_REPEAT, EventNameType_SMIL, NS_EVENT_NULL },
     { nsGkAtoms::onrepeatEvent,                 NS_SMIL_REPEAT, EventNameType_None, NS_SMIL_TIME_EVENT },
 #endif // MOZ_SMIL
@@ -1124,35 +1002,36 @@ nsContentUtils::OfflineAppAllowed(nsIURI
 {
   nsCOMPtr<nsIOfflineCacheUpdateService> updateService =
     do_GetService(NS_OFFLINECACHEUPDATESERVICE_CONTRACTID);
   if (!updateService) {
     return PR_FALSE;
   }
 
   PRBool allowed;
-  nsresult rv = updateService->OfflineAppAllowedForURI(aURI,
-                                                       sPrefBranch,
-                                                       &allowed);
+  nsresult rv =
+    updateService->OfflineAppAllowedForURI(aURI,
+                                           Preferences::GetRootBranch(),
+                                           &allowed);
   return NS_SUCCEEDED(rv) && allowed;
 }
 
 /* static */
 PRBool
 nsContentUtils::OfflineAppAllowed(nsIPrincipal *aPrincipal)
 {
   nsCOMPtr<nsIOfflineCacheUpdateService> updateService =
     do_GetService(NS_OFFLINECACHEUPDATESERVICE_CONTRACTID);
   if (!updateService) {
     return PR_FALSE;
   }
 
   PRBool allowed;
   nsresult rv = updateService->OfflineAppAllowed(aPrincipal,
-                                                 sPrefBranch,
+                                                 Preferences::GetRootBranch(),
                                                  &allowed);
   return NS_SUCCEEDED(rv) && allowed;
 }
 
 // static
 void
 nsContentUtils::Shutdown()
 {
@@ -1162,25 +1041,16 @@ nsContentUtils::Shutdown()
   NS_XHTMLParanoidFragmentSinkShutdown();
 
   NS_IF_RELEASE(sContentPolicyService);
   sTriedToGetContentPolicy = PR_FALSE;
   PRUint32 i;
   for (i = 0; i < PropertiesFile_COUNT; ++i)
     NS_IF_RELEASE(sStringBundles[i]);
 
-  // Clean up c-style's observer 
-  if (sPrefCallbackTable) {
-    delete sPrefCallbackTable;
-    sPrefCallbackTable = nsnull;
-  }
-
-  delete sPrefCacheData;
-  sPrefCacheData = nsnull;
-
   NS_IF_RELEASE(sStringBundleService);
   NS_IF_RELEASE(sConsoleService);
   NS_IF_RELEASE(sDOMScriptObjectFactory);
   sXPConnect = nsnull;
   sThreadJSContextStack = nsnull;
   NS_IF_RELEASE(sSecurityManager);
   NS_IF_RELEASE(sNameSpaceManager);
   NS_IF_RELEASE(sParserService);
@@ -1188,37 +1058,27 @@ nsContentUtils::Shutdown()
   NS_IF_RELEASE(sLineBreaker);
   NS_IF_RELEASE(sWordBreaker);
   NS_IF_RELEASE(sGenCat);
 #ifdef MOZ_XTF
   NS_IF_RELEASE(sXTFService);
 #endif
   NS_IF_RELEASE(sImgLoader);
   NS_IF_RELEASE(sImgCache);
-  NS_IF_RELEASE(sPrefBranch);
 #ifdef IBMBIDI
   NS_IF_RELEASE(sBidiKeyboard);
 #endif
 
   delete sAtomEventTable;
   sAtomEventTable = nsnull;
   delete sStringEventTable;
   sStringEventTable = nsnull;
   delete sUserDefinedEvents;
   sUserDefinedEvents = nsnull;
 
-  if (sPtrsToPtrsToRelease) {
-    for (i = 0; i < sPtrsToPtrsToRelease->Length(); ++i) {
-      nsISupports** ptrToPtr = sPtrsToPtrsToRelease->ElementAt(i);
-      NS_RELEASE(*ptrToPtr);
-    }
-    delete sPtrsToPtrsToRelease;
-    sPtrsToPtrsToRelease = nsnull;
-  }
-
   if (sEventListenerManagersHash.ops) {
     NS_ASSERTION(sEventListenerManagersHash.entryCount == 0,
                  "Event listener manager hash not empty at shutdown!");
 
     // See comment above.
 
     // However, we have to handle this table differently.  If it still
     // has entries, we want to leak it too, so that we can keep it alive
@@ -1471,52 +1331,20 @@ nsContentUtils::GetContextAndScope(nsIDo
 
   *aCx = cx;
   *aNewScope = newScope;
 
   return NS_OK;
 }
 
 nsresult
-nsContentUtils::ReparentContentWrappersInScope(nsIScriptGlobalObject *aOldScope,
+nsContentUtils::ReparentContentWrappersInScope(JSContext *cx,
+                                               nsIScriptGlobalObject *aOldScope,
                                                nsIScriptGlobalObject *aNewScope)
 {
-  JSContext *cx = nsnull;
-
-  // Try really hard to find a context to work on.
-  nsIScriptContext *context = aOldScope->GetContext();
-  if (context) {
-    cx = static_cast<JSContext *>(context->GetNativeContext());
-  }
-
-  if (!cx) {
-    context = aNewScope->GetContext();
-    if (context) {
-      cx = static_cast<JSContext *>(context->GetNativeContext());
-    }
-
-    if (!cx) {
-      sThreadJSContextStack->Peek(&cx);
-
-      if (!cx) {
-        sThreadJSContextStack->GetSafeJSContext(&cx);
-
-        if (!cx) {
-          // Wow, this is really bad!
-          NS_WARNING("No context reachable in ReparentContentWrappers()!");
-
-          return NS_ERROR_NOT_AVAILABLE;
-        }
-      }
-    }
-  }
-
-  // Now that we have a context, let's get the global objects from the two
-  // scopes and ask XPConnect to do the rest of the work.
-
   JSObject *oldScopeObj = aOldScope->GetGlobalJSObject();
   JSObject *newScopeObj = aNewScope->GetGlobalJSObject();
 
   if (!newScopeObj || !oldScopeObj) {
     // We can't really do anything without the JSObjects.
 
     return NS_ERROR_NOT_AVAILABLE;
   }
@@ -2590,196 +2418,16 @@ nsContentUtils::IsDraggableImage(nsICont
 
 // static
 PRBool
 nsContentUtils::IsDraggableLink(const nsIContent* aContent) {
   nsCOMPtr<nsIURI> absURI;
   return aContent->IsLink(getter_AddRefs(absURI));
 }
 
-// static
-nsAdoptingCString
-nsContentUtils::GetCharPref(const char *aPref)
-{
-  nsAdoptingCString result;
-
-  if (sPrefBranch) {
-    sPrefBranch->GetCharPref(aPref, getter_Copies(result));
-  }
-
-  return result;
-}
-
-// static
-PRPackedBool
-nsContentUtils::GetBoolPref(const char *aPref, PRBool aDefault)
-{
-  PRBool result;
-
-  if (!sPrefBranch ||
-      NS_FAILED(sPrefBranch->GetBoolPref(aPref, &result))) {
-    result = aDefault;
-  }
-
-  return (PRPackedBool)result;
-}
-
-// static
-PRInt32
-nsContentUtils::GetIntPref(const char *aPref, PRInt32 aDefault)
-{
-  PRInt32 result;
-
-  if (!sPrefBranch ||
-      NS_FAILED(sPrefBranch->GetIntPref(aPref, &result))) {
-    result = aDefault;
-  }
-
-  return result;
-}
-
-// static
-nsAdoptingString
-nsContentUtils::GetLocalizedStringPref(const char *aPref)
-{
-  nsAdoptingString result;
-
-  if (sPrefBranch) {
-    nsCOMPtr<nsIPrefLocalizedString> prefLocalString;
-    sPrefBranch->GetComplexValue(aPref, NS_GET_IID(nsIPrefLocalizedString),
-                                 getter_AddRefs(prefLocalString));
-    if (prefLocalString) {
-      prefLocalString->GetData(getter_Copies(result));
-    }
-  }
-
-  return result;
-}
-
-// static
-nsAdoptingString
-nsContentUtils::GetStringPref(const char *aPref)
-{
-  nsAdoptingString result;
-
-  if (sPrefBranch) {
-    nsCOMPtr<nsISupportsString> theString;
-    sPrefBranch->GetComplexValue(aPref, NS_GET_IID(nsISupportsString),
-                                 getter_AddRefs(theString));
-    if (theString) {
-      theString->ToString(getter_Copies(result));
-    }
-  }
-
-  return result;
-}
-
-// RegisterPrefCallback/UnregisterPrefCallback are for backward compatiblity
-// with c-style observers.
-
-// static
-void
-nsContentUtils::RegisterPrefCallback(const char *aPref,
-                                     PrefChangedFunc aCallback,
-                                     void * aClosure)
-{
-  if (sPrefBranch) {
-    if (!sPrefCallbackTable) {
-      sPrefCallbackTable = 
-        new nsRefPtrHashtable<nsPrefObserverHashKey, nsPrefOldCallback>();
-      sPrefCallbackTable->Init();
-    }
-
-    nsPrefObserverHashKey hashKey(aPref, aCallback);
-    nsRefPtr<nsPrefOldCallback> callback;
-    sPrefCallbackTable->Get(&hashKey, getter_AddRefs(callback));
-    if (callback) {
-      callback->AppendClosure(aClosure);
-      return;
-    }
-
-    callback = new nsPrefOldCallback(aPref, aCallback);
-    callback->AppendClosure(aClosure);
-    if (NS_SUCCEEDED(sPrefBranch->AddObserver(aPref, callback, PR_FALSE))) {
-      sPrefCallbackTable->Put(callback, callback);
-    }
-  }
-}
-
-// static
-void
-nsContentUtils::UnregisterPrefCallback(const char *aPref,
-                                       PrefChangedFunc aCallback,
-                                       void * aClosure)
-{
-  if (sPrefBranch) {
-    if (!sPrefCallbackTable) {
-      return;
-    }
-
-    nsPrefObserverHashKey hashKey(aPref, aCallback);
-    nsRefPtr<nsPrefOldCallback> callback;
-    sPrefCallbackTable->Get(&hashKey, getter_AddRefs(callback));
-
-    if (callback) {
-      callback->RemoveClosure(aClosure);
-      if (callback->HasNoClosures()) {
-        // Delete the callback since its list of closures is empty.
-        sPrefCallbackTable->Remove(callback);
-      }
-    }
-  }
-}
-
-static int
-BoolVarChanged(const char *aPref, void *aClosure)
-{
-  PrefCacheData* cache = static_cast<PrefCacheData*>(aClosure);
-  *((PRBool*)cache->cacheLocation) =
-    nsContentUtils::GetBoolPref(aPref, cache->defaultValueBool);
-  
-  return 0;
-}
-
-void
-nsContentUtils::AddBoolPrefVarCache(const char *aPref,
-                                    PRBool* aCache,
-                                    PRBool aDefault)
-{
-  *aCache = GetBoolPref(aPref, aDefault);
-  PrefCacheData* data = new PrefCacheData;
-  data->cacheLocation = aCache;
-  data->defaultValueBool = aDefault;
-  sPrefCacheData->AppendElement(data);
-  RegisterPrefCallback(aPref, BoolVarChanged, data);
-}
-
-static int
-IntVarChanged(const char *aPref, void *aClosure)
-{
-  PrefCacheData* cache = static_cast<PrefCacheData*>(aClosure);
-  *((PRInt32*)cache->cacheLocation) =
-    nsContentUtils::GetIntPref(aPref, cache->defaultValueInt);
-  
-  return 0;
-}
-
-void
-nsContentUtils::AddIntPrefVarCache(const char *aPref,
-                                   PRInt32* aCache,
-                                   PRInt32 aDefault)
-{
-  *aCache = GetIntPref(aPref, aDefault);
-  PrefCacheData* data = new PrefCacheData;
-  data->cacheLocation = aCache;
-  data->defaultValueInt = aDefault;
-  sPrefCacheData->AppendElement(data);
-  RegisterPrefCallback(aPref, IntVarChanged, data);
-}
-
 PRBool
 nsContentUtils::IsSitePermAllow(nsIURI* aURI, const char* aType)
 {
   nsCOMPtr<nsIPermissionManager> permMgr =
     do_GetService("@mozilla.org/permissionmanager;1");
   NS_ENSURE_TRUE(permMgr, PR_FALSE);
 
   PRUint32 perm;
@@ -3026,19 +2674,17 @@ static const char gPropertiesFiles[nsCon
   // Must line up with the enum values in |PropertiesFile| enum.
   "chrome://global/locale/css.properties",
   "chrome://global/locale/xbl.properties",
   "chrome://global/locale/xul.properties",
   "chrome://global/locale/layout_errors.properties",
   "chrome://global/locale/layout/HtmlForm.properties",
   "chrome://global/locale/printing.properties",
   "chrome://global/locale/dom/dom.properties",
-#ifdef MOZ_SVG
   "chrome://global/locale/svg/svg.properties",
-#endif
   "chrome://branding/locale/brand.properties",
   "chrome://global/locale/commonDialogs.properties"
 };
 
 /* static */ nsresult
 nsContentUtils::EnsureStringBundle(PropertiesFile aFile)
 {
   if (!sStringBundles[aFile]) {
@@ -4496,17 +4142,17 @@ nsContentUtils::GetTopLevelWidget(nsIWid
 }
 
 /* static */
 const nsDependentString
 nsContentUtils::GetLocalizedEllipsis()
 {
   static PRUnichar sBuf[4] = { 0, 0, 0, 0 };
   if (!sBuf[0]) {
-    nsAutoString tmp(GetLocalizedStringPref("intl.ellipsis"));
+    nsAdoptingString tmp = Preferences::GetLocalizedString("intl.ellipsis");
     PRUint32 len = NS_MIN(PRUint32(tmp.Length()),
                           PRUint32(NS_ARRAY_LENGTH(sBuf) - 1));
     CopyUnicodeTo(tmp, 0, sBuf, len);
     if (!sBuf[0])
       sBuf[0] = PRUnichar(0x2026);
   }
   return nsDependentString(sBuf);
 }
@@ -6188,45 +5834,16 @@ nsContentUtils::CheckCCWrapperTraversal(
   callback.mFound = PR_FALSE;
   participant->Trace(aScriptObjectHolder, DebugWrapperTraceCallback, &callback);
   NS_ASSERTION(callback.mFound,
                "Cycle collection participant didn't trace preserved wrapper! "
                "This will probably crash.");
 }
 #endif
 
-mozAutoRemovableBlockerRemover::mozAutoRemovableBlockerRemover(nsIDocument* aDocument MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM_IN_IMPL)
-{
-  MOZILLA_GUARD_OBJECT_NOTIFIER_INIT;
-  mNestingLevel = nsContentUtils::GetRemovableScriptBlockerLevel();
-  mDocument = aDocument;
-  nsISupports* sink = aDocument ? aDocument->GetCurrentContentSink() : nsnull;
-  mObserver = do_QueryInterface(sink);
-  for (PRUint32 i = 0; i < mNestingLevel; ++i) {
-    if (mObserver) {
-      mObserver->EndUpdate(mDocument, UPDATE_CONTENT_MODEL);
-    }
-    nsContentUtils::RemoveRemovableScriptBlocker();
-  }
-
-  NS_ASSERTION(nsContentUtils::IsSafeToRunScript(), "killing mutation events");
-}
-
-mozAutoRemovableBlockerRemover::~mozAutoRemovableBlockerRemover()
-{
-  NS_ASSERTION(nsContentUtils::GetRemovableScriptBlockerLevel() == 0,
-               "Should have had none");
-  for (PRUint32 i = 0; i < mNestingLevel; ++i) {
-    nsContentUtils::AddRemovableScriptBlocker();
-    if (mObserver) {
-      mObserver->BeginUpdate(mDocument, UPDATE_CONTENT_MODEL);
-    }
-  }
-}
-
 // static
 PRBool
 nsContentUtils::IsFocusedContent(const nsIContent* aContent)
 {
   nsFocusManager* fm = nsFocusManager::GetFocusManager();
 
   return fm && fm->GetFocusedContent() == aContent;
 }
@@ -6317,31 +5934,16 @@ nsContentUtils::PlatformToDOMLineBreaks(
                              NS_LITERAL_STRING("\n").get());
 
     // Mac linebreaks: Map any remaining CR to LF:
     aString.ReplaceSubstring(NS_LITERAL_STRING("\r").get(),
                              NS_LITERAL_STRING("\n").get());
   }
 }
 
-static nsIView* GetDisplayRootFor(nsIView* aView)
-{
-  nsIView *displayRoot = aView;
-  for (;;) {
-    nsIView *displayParent = displayRoot->GetParent();
-    if (!displayParent)
-      return displayRoot;
-
-    if (displayRoot->GetFloating() && !displayParent->GetFloating())
-      return displayRoot;
-    displayRoot = displayParent;
-  }
-  return nsnull;
-}
-
 static already_AddRefed<LayerManager>
 LayerManagerForDocumentInternal(nsIDocument *aDoc, bool aRequirePersistent,
                                 bool* aAllowRetaining)
 {
   nsIDocument* doc = aDoc;
   nsIDocument* displayDoc = doc->GetDisplayDocument();
   if (displayDoc) {
     doc = displayDoc;
@@ -6367,17 +5969,17 @@ LayerManagerForDocumentInternal(nsIDocum
     }
   }
 
   if (shell) {
     nsIViewManager* VM = shell->GetViewManager();
     if (VM) {
       nsIView* rootView = VM->GetRootView();
       if (rootView) {
-        nsIView* displayRoot = GetDisplayRootFor(rootView);
+        nsIView* displayRoot = nsIViewManager::GetDisplayRootFor(rootView);
         if (displayRoot) {
           nsIWidget* widget = displayRoot->GetNearestWidget(nsnull);
           if (widget) {
             nsRefPtr<LayerManager> manager =
               widget->
                 GetLayerManager(aRequirePersistent ? nsIWidget::LAYER_MANAGER_PERSISTENT : 
                                                      nsIWidget::LAYER_MANAGER_CURRENT,
                                 aAllowRetaining);
--- a/content/base/src/nsCrossSiteListenerProxy.cpp
+++ b/content/base/src/nsCrossSiteListenerProxy.cpp
@@ -55,16 +55,19 @@
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsCharSeparatedTokenizer.h"
 #include "nsAsyncRedirectVerifyHelper.h"
 #include "prclist.h"
 #include "prtime.h"
 #include "nsClassHashtable.h"
 #include "nsHashKeys.h"
 #include "nsStreamUtils.h"
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 
 #define PREFLIGHT_CACHE_SIZE 100
 
 static PRBool gDisableCORS = PR_FALSE;
 static PRBool gDisableCORSPrivateData = PR_FALSE;
 
 //////////////////////////////////////////////////////////////////////////
 // Preflight cache
@@ -364,18 +367,20 @@ nsPreflightCache::GetCacheKey(nsIURI* aU
 NS_IMPL_ISUPPORTS5(nsCORSListenerProxy, nsIStreamListener,
                    nsIRequestObserver, nsIChannelEventSink,
                    nsIInterfaceRequestor, nsIAsyncVerifyRedirectCallback)
 
 /* static */
 void
 nsCORSListenerProxy::Startup()
 {
-  nsContentUtils::AddBoolPrefVarCache("content.cors.disable", &gDisableCORS);
-  nsContentUtils::AddBoolPrefVarCache("content.cors.no_private_data", &gDisableCORSPrivateData);
+  Preferences::AddBoolVarCache(&gDisableCORS,
+                               "content.cors.disable");
+  Preferences::AddBoolVarCache(&gDisableCORSPrivateData,
+                               "content.cors.no_private_data");
 }
 
 /* static */
 void
 nsCORSListenerProxy::Shutdown()
 {
   delete sPreflightCache;
   sPreflightCache = nsnull;
--- a/content/base/src/nsDOMAttribute.cpp
+++ b/content/base/src/nsDOMAttribute.cpp
@@ -605,19 +605,18 @@ nsDOMAttribute::InsertChildAt(nsIContent
 
 nsresult
 nsDOMAttribute::AppendChildTo(nsIContent* aKid, PRBool aNotify)
 {
   return NS_ERROR_NOT_IMPLEMENTED;
 }
 
 nsresult
-nsDOMAttribute::RemoveChildAt(PRUint32 aIndex, PRBool aNotify, PRBool aMutationEvent)
+nsDOMAttribute::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
 {
-  NS_ASSERTION(aMutationEvent, "Someone tried to inhibit mutations on attribute child removal.");
   if (aIndex != 0 || !mChild) {
     return NS_OK;
   }
 
   {
     nsCOMPtr<nsIContent> child = mChild;
     nsMutationGuard::DidMutate();
     mozAutoDocUpdate updateBatch(GetOwnerDoc(), UPDATE_CONTENT_MODEL, aNotify);
--- a/content/base/src/nsDOMAttribute.h
+++ b/content/base/src/nsDOMAttribute.h
@@ -89,17 +89,17 @@ public:
   virtual PRBool IsNodeOfType(PRUint32 aFlags) const;
   virtual PRUint32 GetChildCount() const;
   virtual nsIContent *GetChildAt(PRUint32 aIndex) const;
   virtual nsIContent * const * GetChildArray(PRUint32* aChildCount) const;
   virtual PRInt32 IndexOf(nsINode* aPossibleChild) const;
   virtual nsresult InsertChildAt(nsIContent* aKid, PRUint32 aIndex,
                                  PRBool aNotify);
   virtual nsresult AppendChildTo(nsIContent* aKid, PRBool aNotify);
-  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify, PRBool aMutationEvent = PR_TRUE);
+  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify);
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
   virtual nsresult PostHandleEvent(nsEventChainPostVisitor& aVisitor);
   virtual nsresult DispatchDOMEvent(nsEvent* aEvent, nsIDOMEvent* aDOMEvent,
                                     nsPresContext* aPresContext,
                                     nsEventStatus* aEventStatus);
   virtual nsIEventListenerManager* GetListenerManager(PRBool aCreateIfNotFound);
   virtual nsresult AddEventListenerByIID(nsIDOMEventListener *aListener,
                                          const nsIID& aIID);
--- a/content/base/src/nsDOMBlobBuilder.cpp
+++ b/content/base/src/nsDOMBlobBuilder.cpp
@@ -216,25 +216,25 @@ nsDOMMultipartBlob::MozSlice(PRInt64 aSt
   }
 
   // we can create our blob now
   nsCOMPtr<nsIDOMBlob> blob = new nsDOMMultipartBlob(blobs, aContentType);
   blob.forget(aBlob);
   return NS_OK;
 }
 
-class nsDOMBlobBuilder : public nsIDOMBlobBuilder
+class nsDOMBlobBuilder : public nsIDOMMozBlobBuilder
 {
 public:
   nsDOMBlobBuilder()
     : mData(nsnull), mDataLen(0), mDataBufferLen(0)
   {}
 
   NS_DECL_ISUPPORTS
-  NS_DECL_NSIDOMBLOBBUILDER
+  NS_DECL_NSIDOMMOZBLOBBUILDER
 protected:
   nsresult AppendVoidPtr(void* aData, PRUint32 aLength);
   nsresult AppendString(JSString* aString, JSContext* aCx);
   nsresult AppendBlob(nsIDOMBlob* aBlob);
   nsresult AppendArrayBuffer(js::ArrayBuffer* aBuffer);
 
   bool ExpandBufferSize(PRUint64 aSize)
   {
@@ -282,17 +282,17 @@ protected:
   PRUint64 mDataBufferLen;
 };
 
 DOMCI_DATA(MozBlobBuilder, nsDOMBlobBuilder)
 
 NS_IMPL_ADDREF(nsDOMBlobBuilder)
 NS_IMPL_RELEASE(nsDOMBlobBuilder)
 NS_INTERFACE_MAP_BEGIN(nsDOMBlobBuilder)
-  NS_INTERFACE_MAP_ENTRY(nsIDOMBlobBuilder)
+  NS_INTERFACE_MAP_ENTRY(nsIDOMMozBlobBuilder)
   NS_INTERFACE_MAP_ENTRY(nsISupports)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(MozBlobBuilder)
 NS_INTERFACE_MAP_END
 
 nsresult
 nsDOMBlobBuilder::AppendVoidPtr(void* aData, PRUint32 aLength)
 {
   NS_ENSURE_ARG_POINTER(aData);
--- a/content/base/src/nsDOMFile.cpp
+++ b/content/base/src/nsDOMFile.cpp
@@ -59,16 +59,17 @@
 #include "nsIUnicodeDecoder.h"
 #include "nsNetCID.h"
 #include "nsNetUtil.h"
 #include "nsIUUIDGenerator.h"
 #include "nsFileDataProtocolHandler.h"
 #include "nsStringStream.h"
 #include "CheckedInt.h"
 #include "nsJSUtils.h"
+#include "mozilla/Preferences.h"
 
 #include "plbase64.h"
 #include "prmem.h"
 
 using namespace mozilla;
 
 // XXXkhuey the input stream that we pass out of a DOMFile
 // can outlive the actual DOMFile object.  Thus, we must
@@ -494,22 +495,22 @@ nsDOMFile::GuessCharset(nsIInputStream *
   }
 
   // First try the universal charset detector
   nsCOMPtr<nsICharsetDetector> detector
     = do_CreateInstance(NS_CHARSET_DETECTOR_CONTRACTID_BASE
                         "universal_charset_detector");
   if (!detector) {
     // No universal charset detector, try the default charset detector
-    const nsAdoptingString& detectorName =
-      nsContentUtils::GetLocalizedStringPref("intl.charset.detector");
+    const nsAdoptingCString& detectorName =
+      Preferences::GetLocalizedCString("intl.charset.detector");
     if (!detectorName.IsEmpty()) {
       nsCAutoString detectorContractID;
       detectorContractID.AssignLiteral(NS_CHARSET_DETECTOR_CONTRACTID_BASE);
-      AppendUTF16toUTF8(detectorName, detectorContractID);
+      detectorContractID += detectorName;
       detector = do_CreateInstance(detectorContractID.get());
     }
   }
 
   nsresult rv;
   if (detector) {
     detector->Init(this);
 
--- a/content/base/src/nsDOMFileReader.cpp
+++ b/content/base/src/nsDOMFileReader.cpp
@@ -72,16 +72,19 @@
 #include "nsIDOMClassInfo.h"
 #include "nsCExternalHandlerService.h"
 #include "nsIStreamConverterService.h"
 #include "nsEventDispatcher.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsLayoutStatics.h"
 #include "nsIScriptObjectPrincipal.h"
 #include "nsFileDataProtocolHandler.h"
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 
 #define LOAD_STR "load"
 #define ERROR_STR "error"
 #define ABORT_STR "abort"
 #define LOADSTART_STR "loadstart"
 #define PROGRESS_STR "progress"
 #define UPLOADPROGRESS_STR "uploadprogress"
 #define LOADEND_STR "loadend"
@@ -679,22 +682,22 @@ nsDOMFileReader::GuessCharset(const char
                               nsACString &aCharset)
 {
   // First try the universal charset detector
   nsCOMPtr<nsICharsetDetector> detector
     = do_CreateInstance(NS_CHARSET_DETECTOR_CONTRACTID_BASE
                         "universal_charset_detector");
   if (!detector) {
     // No universal charset detector, try the default charset detector
-    const nsAdoptingString& detectorName =
-      nsContentUtils::GetLocalizedStringPref("intl.charset.detector");
+    const nsAdoptingCString& detectorName =
+      Preferences::GetLocalizedCString("intl.charset.detector");
     if (!detectorName.IsEmpty()) {
       nsCAutoString detectorContractID;
       detectorContractID.AssignLiteral(NS_CHARSET_DETECTOR_CONTRACTID_BASE);
-      AppendUTF16toUTF8(detectorName, detectorContractID);
+      detectorContractID += detectorName;
       detector = do_CreateInstance(detectorContractID.get());
     }
   }
 
   nsresult rv;
   // The charset detector doesn't work for empty (null) aFileData. Testing
   // aDataLen instead of aFileData so that we catch potential errors.
   if (detector && aDataLen != 0) {
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -198,16 +198,19 @@ static NS_DEFINE_CID(kDOMEventGroupCID, 
 #include "nsHTMLStyleSheet.h"
 #include "nsHTMLCSSStyleSheet.h"
 
 #include "mozilla/dom/Link.h"
 #include "nsIHTMLDocument.h"
 #include "nsXULAppAPI.h"
 #include "nsDOMTouchEvent.h"
 
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 using namespace mozilla::dom;
 
 typedef nsTArray<Link*> LinkArray;
 
 
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gDocumentLeakPRLog;
 static PRLogModuleInfo* gCspPRLog;
@@ -1680,18 +1683,16 @@ nsDocument::~nsDocument()
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsDocument)
 
 NS_INTERFACE_TABLE_HEAD(nsDocument)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_DOCUMENT_INTERFACE_TABLE_BEGIN(nsDocument)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDocument)
-    NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMDocumentStyle)
-    NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMNSDocumentStyle)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMDocumentXBL)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIScriptObjectPrincipal)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOM3EventTarget)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIDOMNSEventTarget)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsPIDOMEventTarget)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsISupportsWeakReference)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIRadioGroupContainer)
     NS_INTERFACE_TABLE_ENTRY(nsDocument, nsIRadioGroupContainer_MOZILLA_2_0_BRANCH)
@@ -1865,16 +1866,18 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mChannel)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mStyleAttrStyleSheet, nsIStyleSheet)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mScriptEventManager)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mXPathEvaluatorTearoff)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLayoutHistoryState)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOnloadBlocker)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFirstBaseNodeWithHref)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mDOMImplementation)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mImageMaps,
+                                                       nsIDOMNodeList)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mOriginalDocument)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mCachedEncoder)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mStateObjectCached)
 
   // Traverse all our nsCOMArrays.
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mStyleSheets)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mCatalogSheets)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMARRAY(mPreloadingImages)
@@ -1917,16 +1920,17 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(ns
     tmp->mChildren.RemoveChildAt(indx);
   }
   tmp->mFirstChild = nsnull;
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCachedRootElement)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDisplayDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mFirstBaseNodeWithHref)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mDOMImplementation)
+  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mImageMaps)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOriginalDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCachedEncoder)
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
   NS_IMPL_CYCLE_COLLECTION_UNLINK_USERDATA
 
   tmp->mParentDocument = nsnull;
 
@@ -3441,31 +3445,30 @@ nsDocument::AppendChildTo(nsIContent* aK
   // subclasses wanted to hook into this stuff, they would have
   // overridden AppendChildTo.
   // XXXbz maybe this should just be a non-virtual method on nsINode?
   // Feels that way to me...
   return nsDocument::InsertChildAt(aKid, GetChildCount(), aNotify);
 }
 
 nsresult
-nsDocument::RemoveChildAt(PRUint32 aIndex, PRBool aNotify, PRBool aMutationEvent)
-{
-  NS_ASSERTION(aMutationEvent, "Someone tried to inhibit mutations on document child removal.");
+nsDocument::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
+{
   nsCOMPtr<nsIContent> oldKid = GetChildAt(aIndex);
   if (!oldKid) {
     return NS_OK;
   }
 
   if (oldKid->IsElement()) {
     // Destroy the link map up front before we mess with the child list.
     DestroyElementMaps();
   }
 
   nsresult rv =
-    doRemoveChildAt(aIndex, aNotify, oldKid, mChildren, aMutationEvent);
+    doRemoveChildAt(aIndex, aNotify, oldKid, mChildren);
   mCachedRootElement = nsnull;
   return rv;
 }
 
 PRInt32
 nsDocument::GetNumberOfStyleSheets() const
 {
   return mStyleSheets.Count();
@@ -3944,36 +3947,26 @@ void
 nsDocument::BeginUpdate(nsUpdateType aUpdateType)
 {
   if (mUpdateNestLevel == 0 && !mInXBLUpdate) {
     mInXBLUpdate = PR_TRUE;
     BindingManager()->BeginOutermostUpdate();
   }
   
   ++mUpdateNestLevel;
-  if (aUpdateType == UPDATE_CONTENT_MODEL) {
-    nsContentUtils::AddRemovableScriptBlocker();
-  }
-  else {
-    nsContentUtils::AddScriptBlocker();
-  }
+  nsContentUtils::AddScriptBlocker();
   NS_DOCUMENT_NOTIFY_OBSERVERS(BeginUpdate, (this, aUpdateType));
 }
 
 void
 nsDocument::EndUpdate(nsUpdateType aUpdateType)
 {
   NS_DOCUMENT_NOTIFY_OBSERVERS(EndUpdate, (this, aUpdateType));
 
-  if (aUpdateType == UPDATE_CONTENT_MODEL) {
-    nsContentUtils::RemoveRemovableScriptBlocker();
-  }
-  else {
-    nsContentUtils::RemoveScriptBlocker();
-  }
+  nsContentUtils::RemoveScriptBlocker();
 
   --mUpdateNestLevel;
 
   // This set of updates may have created XBL bindings.  Let the
   // binding manager know we're done.
   MaybeEndOutermostXBLUpdate();
 
   MaybeInitializeFinalizeFrameLoaders();
@@ -4538,30 +4531,16 @@ nsDocument::CreateAttributeNS(const nsAS
   nsDOMAttribute* attribute =
     new nsDOMAttribute(nsnull, nodeInfo.forget(), value, PR_TRUE);
   NS_ENSURE_TRUE(attribute, NS_ERROR_OUT_OF_MEMORY);
 
   return CallQueryInterface(attribute, aResult);
 }
 
 NS_IMETHODIMP
-nsDocument::CreateEntityReference(const nsAString& aName,
-                                  nsIDOMEntityReference** aReturn)
-{
-  NS_ENSURE_ARG_POINTER(aReturn);
-  *aReturn = nsnull;
-
-  if (IsHTML()) {
-    return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
-  }
-
-  return NS_OK;
-}
-
-NS_IMETHODIMP
 nsDocument::GetElementsByTagName(const nsAString& aTagname,
                                  nsIDOMNodeList** aReturn)
 {
   nsRefPtr<nsContentList> list = GetElementsByTagName(aTagname);
   NS_ENSURE_TRUE(list, NS_ERROR_OUT_OF_MEMORY);
 
   // transfer ref to aReturn
   *aReturn = list.forget().get();
@@ -5157,23 +5136,21 @@ nsDocument::GetTitle(nsAString& aTitle)
   nsAutoString tmp;
 
   switch (rootElement->GetNameSpaceID()) {
 #ifdef MOZ_XUL
     case kNameSpaceID_XUL:
       rootElement->GetAttr(kNameSpaceID_None, nsGkAtoms::title, tmp);
       break;
 #endif
-#ifdef MOZ_SVG
     case kNameSpaceID_SVG:
       if (rootElement->Tag() == nsGkAtoms::svg) {
         GetTitleFromElement(kNameSpaceID_SVG, tmp);
         break;
       } // else fall through
-#endif
     default:
       GetTitleFromElement(kNameSpaceID_XHTML, tmp);
       break;
   }
 
   tmp.CompressWhitespace();
   aTitle = tmp;
   return NS_OK;
@@ -5182,20 +5159,18 @@ nsDocument::GetTitle(nsAString& aTitle)
 NS_IMETHODIMP
 nsDocument::SetTitle(const nsAString& aTitle)
 {
   Element *rootElement = GetRootElement();
   if (!rootElement)
     return NS_OK;
 
   switch (rootElement->GetNameSpaceID()) {
-#ifdef MOZ_SVG
     case kNameSpaceID_SVG:
       return NS_OK; // SVG doesn't support setting a title
-#endif
 #ifdef MOZ_XUL
     case kNameSpaceID_XUL:
       return rootElement->SetAttr(kNameSpaceID_None, nsGkAtoms::title,
                                   aTitle, PR_TRUE);
 #endif
   }
 
   // Batch updates so that mutation events don't change "the title
@@ -6148,22 +6123,16 @@ nsDocument::AdoptNode(nsIDOMNode *aAdopt
 
   NS_ASSERTION(adoptedNode->GetOwnerDoc() == this,
                "Should still be in the document we just got adopted into");
 
   return CallQueryInterface(adoptedNode, aResult);
 }
 
 NS_IMETHODIMP
-nsDocument::NormalizeDocument()
-{
-  return Normalize();
-}
-
-NS_IMETHODIMP
 nsDocument::GetOwnerDocument(nsIDOMDocument** aOwnerDocument)
 {
   return nsINode::GetOwnerDocument(aOwnerDocument);
 }
 
 nsIEventListenerManager*
 nsDocument::GetListenerManager(PRBool aCreateIfNotFound)
 {
@@ -8158,16 +8127,58 @@ nsDocument::GetStateObject(nsIVariant** 
       DeserializeToVariant(cx, getter_AddRefs(mStateObjectCached));
   }
 
   NS_IF_ADDREF(*aState = mStateObjectCached);
   
   return NS_OK;
 }
 
+Element*
+nsDocument::FindImageMap(const nsAString& aUseMapValue)
+{
+  if (aUseMapValue.IsEmpty()) {
+    return nsnull;
+  }
+
+  nsAString::const_iterator start, end;
+  aUseMapValue.BeginReading(start);
+  aUseMapValue.EndReading(end);
+
+  PRInt32 hash = aUseMapValue.FindChar('#');
+  if (hash < 0) {
+    return nsnull;
+  }
+  // aUsemap contains a '#', set start to point right after the '#'
+  start.advance(hash + 1);
+
+  if (start == end) {
+    return nsnull; // aUsemap == "#"
+  }
+
+  const nsAString& mapName = Substring(start, end);
+
+  if (!mImageMaps) {
+    mImageMaps = new nsContentList(this, kNameSpaceID_XHTML, nsGkAtoms::map, nsGkAtoms::map);
+  }
+
+  PRUint32 i, n = mImageMaps->Length(PR_TRUE);
+  for (i = 0; i < n; ++i) {
+    nsIContent* map = mImageMaps->GetNodeAt(i);
+    if (map->AttrValueIs(kNameSpaceID_None, nsGkAtoms::id, mapName,
+                         eCaseMatters) ||
+        map->AttrValueIs(kNameSpaceID_None, nsGkAtoms::name, mapName,
+                         eIgnoreCase)) {
+      return map->AsElement();
+    }
+  }
+
+  return nsnull;
+}
+
 nsresult
 nsDocument::AddImage(imgIRequest* aImage)
 {
   NS_ENSURE_ARG_POINTER(aImage);
 
   // See if the image is already in the hashtable. If it is, get the old count.
   PRUint32 oldCount = 0;
   mImageTracker.Get(aImage, &oldCount);
@@ -8256,17 +8267,17 @@ PLDHashOperator UnlockEnumerator(imgIReq
   return PL_DHASH_NEXT;
 }
 
 
 nsresult
 nsDocument::SetImageLockingState(PRBool aLocked)
 {
   if (XRE_GetProcessType() == GeckoProcessType_Content &&
-      !nsContentUtils::GetBoolPref("content.image.allow_locking", PR_TRUE)) {
+      !Preferences::GetBool("content.image.allow_locking", PR_TRUE)) {
     return NS_OK;
   }
 
   // If there's no change, there's nothing to do.
   if (mLockingImages == aLocked)
     return NS_OK;
 
   // Otherwise, iterate over our images and perform the appropriate action.
--- a/content/base/src/nsDocument.h
+++ b/content/base/src/nsDocument.h
@@ -48,18 +48,16 @@
 #include "nsIDocument.h"
 #include "nsWeakReference.h"
 #include "nsWeakPtr.h"
 #include "nsVoidArray.h"
 #include "nsTArray.h"
 #include "nsHashSets.h"
 #include "nsIDOMXMLDocument.h"
 #include "nsIDOMDocumentXBL.h"
-#include "nsIDOMNSDocument.h"
-#include "nsIDOMNSDocumentStyle.h"
 #include "nsStubDocumentObserver.h"
 #include "nsIDOM3EventTarget.h"
 #include "nsIDOMNSEventTarget.h"
 #include "nsIDOMStyleSheetList.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIContent.h"
 #include "nsIEventListenerManager.h"
@@ -485,18 +483,16 @@ protected:
 // really an nsIDOMXMLDocument. The reason for implementing
 // nsIDOMXMLDocument on this class is to avoid having to duplicate all
 // its inherited methods on document classes that *are*
 // nsIDOMXMLDocument's. nsDocument's QI should *not* claim to support
 // nsIDOMXMLDocument unless someone writes a real implementation of
 // the interface.
 class nsDocument : public nsIDocument,
                    public nsIDOMXMLDocument, // inherits nsIDOMDocument
-                   public nsIDOMNSDocument,
-                   public nsIDOMNSDocumentStyle,
                    public nsIDOMDocumentXBL,
                    public nsSupportsWeakReference,
                    public nsIDOMEventTarget,
                    public nsIDOM3EventTarget,
                    public nsIDOMNSEventTarget,
                    public nsIScriptObjectPrincipal,
                    public nsIRadioGroupContainer_MOZILLA_2_0_BRANCH,
                    public nsIApplicationCacheContainer,
@@ -535,17 +531,17 @@ public:
    * Set the principal responsible for this document.
    */
   virtual void SetPrincipal(nsIPrincipal *aPrincipal);
 
   /**
    * Get the Content-Type of this document.
    */
   // NS_IMETHOD GetContentType(nsAString& aContentType);
-  // Already declared in nsIDOMNSDocument
+  // Already declared in nsIDOMDocument
 
   /**
    * Set the Content-Type of this document.
    */
   virtual void SetContentType(const nsAString& aContentType);
 
   virtual nsresult SetBaseURI(nsIURI* aURI);
 
@@ -725,17 +721,17 @@ public:
   virtual PRBool IsNodeOfType(PRUint32 aFlags) const;
   virtual nsIContent *GetChildAt(PRUint32 aIndex) const;
   virtual nsIContent * const * GetChildArray(PRUint32* aChildCount) const;
   virtual PRInt32 IndexOf(nsINode* aPossibleChild) const;
   virtual PRUint32 GetChildCount() const;
   virtual nsresult InsertChildAt(nsIContent* aKid, PRUint32 aIndex,
                                  PRBool aNotify);
   virtual nsresult AppendChildTo(nsIContent* aKid, PRBool aNotify);
-  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify, PRBool aMutationEvent = PR_TRUE);
+  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify);
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
   virtual nsresult PostHandleEvent(nsEventChainPostVisitor& aVisitor);
   virtual nsresult DispatchDOMEvent(nsEvent* aEvent, nsIDOMEvent* aDOMEvent,
                                     nsPresContext* aPresContext,
                                     nsEventStatus* aEventStatus);
   virtual nsIEventListenerManager* GetListenerManager(PRBool aCreateIfNotFound);
   virtual nsresult AddEventListenerByIID(nsIDOMEventListener *aListener,
                                          const nsIID& aIID);
@@ -786,25 +782,16 @@ public:
   NS_DECL_NSIDOMNODE
 
   // nsIDOMDocument
   NS_DECL_NSIDOMDOCUMENT
 
   // nsIDOMXMLDocument
   NS_DECL_NSIDOMXMLDOCUMENT
 
-  // nsIDOMNSDocument
-  NS_DECL_NSIDOMNSDOCUMENT
-
-  // nsIDOMDocumentStyle
-  NS_DECL_NSIDOMDOCUMENTSTYLE
-
-  // nsIDOMNSDocumentStyle
-  NS_DECL_NSIDOMNSDOCUMENTSTYLE
-
   // nsIDOMDocumentXBL
   NS_DECL_NSIDOMDOCUMENTXBL
 
   // nsIDOMEventTarget
   NS_DECL_NSIDOMEVENTTARGET
 
   // nsIDOM3EventTarget
   NS_DECL_NSIDOM3EVENTTARGET
@@ -956,16 +943,18 @@ public:
   virtual Element *LookupImageElement(const nsAString& aElementId);
 
   virtual NS_HIDDEN_(nsresult) AddImage(imgIRequest* aImage);
   virtual NS_HIDDEN_(nsresult) RemoveImage(imgIRequest* aImage);
   virtual NS_HIDDEN_(nsresult) SetImageLockingState(PRBool aLocked);
 
   virtual nsresult GetStateObject(nsIVariant** aResult);
 
+  virtual Element* FindImageMap(const nsAString& aNormalizedMapName);
+
 protected:
   friend class nsNodeUtils;
 
   /**
    * Check that aId is not empty and log a message to the console
    * service if it is.
    * @returns PR_TRUE if aId looks correct, PR_FALSE otherwise.
    */
@@ -1220,29 +1209,30 @@ private:
 
   nsExternalResourceMap mExternalResourceMap;
 
   // All images in process of being preloaded
   nsCOMArray<imgIRequest> mPreloadingImages;
 
   nsCOMPtr<nsIDOMDOMImplementation> mDOMImplementation;
 
+  nsRefPtr<nsContentList> mImageMaps;
+
   nsCString mScrollToRef;
   PRUint8 mScrolledToRefAlready : 1;
   PRUint8 mChangeScrollPosWhenScrollingToRef : 1;
 
   // Tracking for images in the document.
   nsDataHashtable< nsPtrHashKey<imgIRequest>, PRUint32> mImageTracker;
 
 #ifdef DEBUG
 protected:
   PRBool mWillReparent;
 #endif
 };
 
 #define NS_DOCUMENT_INTERFACE_TABLE_BEGIN(_class)                             \
   NS_NODE_OFFSET_AND_INTERFACE_TABLE_BEGIN(_class)                            \
   NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(_class, nsIDOMDocument, nsDocument)      \
-  NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(_class, nsIDOMNSDocument, nsDocument)    \
   NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(_class, nsIDOMEventTarget, nsDocument)   \
   NS_INTERFACE_TABLE_ENTRY_AMBIGUOUS(_class, nsIDOMNode, nsDocument)
 
 #endif /* nsDocument_h___ */
--- a/content/base/src/nsEventSource.cpp
+++ b/content/base/src/nsEventSource.cpp
@@ -52,16 +52,19 @@
 #include "nsIScriptObjectPrincipal.h"
 #include "jsdbgapi.h"
 #include "nsJSUtils.h"
 #include "nsIAsyncVerifyRedirectCallback.h"
 #include "nsIScriptError.h"
 #include "nsICharsetConverterManager.h"
 #include "nsIChannelPolicy.h"
 #include "nsIContentSecurityPolicy.h"
+#include "mozilla/Preferences.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
 #define COLON_CHAR           (PRUnichar)0x003A
 
@@ -291,18 +294,18 @@ nsEventSource::Init(nsIPrincipal* aPrinc
   rv = srcURI->GetSpec(spec);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mOriginalURL = NS_ConvertUTF8toUTF16(spec);
   mSrc = srcURI;
   mOrigin = origin;
 
   mReconnectionTime =
-    nsContentUtils::GetIntPref("dom.server-events.default-reconnection-time",
-                               DEFAULT_RECONNECTION_TIME_VALUE);
+    Preferences::GetInt("dom.server-events.default-reconnection-time",
+                        DEFAULT_RECONNECTION_TIME_VALUE);
 
   nsCOMPtr<nsICharsetConverterManager> convManager =
     do_GetService(NS_CHARSETCONVERTERMANAGER_CONTRACTID, &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   rv = convManager->GetUnicodeDecoder("UTF-8", getter_AddRefs(mUnicodeDecoder));
   NS_ENSURE_SUCCESS(rv, rv);
   mUnicodeDecoder->SetInputErrorBehavior(nsIUnicodeDecoder::kOnError_Recover);
@@ -770,17 +773,17 @@ nsEventSource::GetInterface(const nsIID 
 
   return QueryInterface(aIID, aResult);
 }
 
 // static
 PRBool
 nsEventSource::PrefEnabled()
 {
-  return nsContentUtils::GetBoolPref("dom.server-events.enabled", PR_FALSE);
+  return Preferences::GetBool("dom.server-events.enabled", PR_FALSE);
 }
 
 nsresult
 nsEventSource::GetBaseURI(nsIURI **aBaseURI)
 {
   NS_ENSURE_ARG_POINTER(aBaseURI);
 
   *aBaseURI = nsnull;
--- a/content/base/src/nsFileDataProtocolHandler.cpp
+++ b/content/base/src/nsFileDataProtocolHandler.cpp
@@ -156,22 +156,33 @@ public:
 
   // Override StartClone to hand back a nsFileDataURI
   virtual nsSimpleURI* StartClone(RefHandlingEnum /* unused */)
   { return new nsFileDataURI(); }
 
   nsCOMPtr<nsIPrincipal> mPrincipal;
 };
 
+static NS_DEFINE_CID(kThisSimpleURIImplementationCID,
+                     NS_THIS_SIMPLEURI_IMPLEMENTATION_CID);
+
 NS_IMPL_ADDREF_INHERITED(nsFileDataURI, nsSimpleURI)
 NS_IMPL_RELEASE_INHERITED(nsFileDataURI, nsSimpleURI)
+
 NS_INTERFACE_MAP_BEGIN(nsFileDataURI)
   NS_INTERFACE_MAP_ENTRY(nsIURIWithPrincipal)
   if (aIID.Equals(kFILEDATAURICID))
-      foundInterface = static_cast<nsIURI*>(this);
+    foundInterface = static_cast<nsIURI*>(this);
+  else if (aIID.Equals(kThisSimpleURIImplementationCID)) {
+    // Need to return explicitly here, because if we just set foundInterface
+    // to null the NS_INTERFACE_MAP_END_INHERITING will end up calling into
+    // nsSimplURI::QueryInterface and finding something for this CID.
+    *aInstancePtr = nsnull;
+    return NS_NOINTERFACE;
+  }
   else
 NS_INTERFACE_MAP_END_INHERITING(nsSimpleURI)
 
 // nsIURIWithPrincipal methods:
 
 NS_IMETHODIMP
 nsFileDataURI::GetPrincipal(nsIPrincipal** aPrincipal)
 {
@@ -252,25 +263,30 @@ nsFileDataURI::EqualsInternal(nsIURI* aO
   
   nsRefPtr<nsFileDataURI> otherFileDataUri;
   aOther->QueryInterface(kFILEDATAURICID, getter_AddRefs(otherFileDataUri));
   if (!otherFileDataUri) {
     *aResult = PR_FALSE;
     return NS_OK;
   }
 
-  nsresult rv = mPrincipal->Equals(otherFileDataUri->mPrincipal, aResult);
-  NS_ENSURE_SUCCESS(rv, rv);
-  
-  if (!*aResult) {
+  // Compare the member data that our base class knows about.
+  if (!nsSimpleURI::EqualsInternal(otherFileDataUri, aRefHandlingMode)) {
+    *aResult = PR_FALSE;
     return NS_OK;
-  }
+   }
 
-  return nsSimpleURI::EqualsInternal(otherFileDataUri, aRefHandlingMode,
-                                     aResult);
+  // Compare the piece of additional member data that we add to base class.
+  if (mPrincipal && otherFileDataUri->mPrincipal) {
+    // Both of us have mPrincipals. Compare them.
+    return mPrincipal->Equals(otherFileDataUri->mPrincipal, aResult);
+  }
+  // else, at least one of us lacks a principal; only equal if *both* lack it.
+  *aResult = (!mPrincipal && !otherFileDataUri->mPrincipal);
+  return NS_OK;
 }
 
 // nsIClassInfo methods:
 NS_IMETHODIMP 
 nsFileDataURI::GetInterfaces(PRUint32 *count, nsIID * **array)
 {
   *count = 0;
   *array = nsnull;
--- a/content/base/src/nsFrameLoader.cpp
+++ b/content/base/src/nsFrameLoader.cpp
@@ -78,17 +78,17 @@
 #include "nsIFrame.h"
 #include "nsSubDocumentFrame.h"
 #include "nsDOMError.h"
 #include "nsGUIEvent.h"
 #include "nsEventDispatcher.h"
 #include "nsISHistory.h"
 #include "nsISHistoryInternal.h"
 #include "nsIDocShellHistory.h"
-#include "nsIDOMNSHTMLDocument.h"
+#include "nsIDOMHTMLDocument.h"
 #include "nsIXULWindow.h"
 #include "nsIEditor.h"
 #include "nsIEditorDocShell.h"
 
 #include "nsLayoutUtils.h"
 #include "nsIView.h"
 #include "nsPLDOMEvent.h"
 
@@ -109,16 +109,18 @@
 #include "mozilla/unused.h"
 
 #include "Layers.h"
 
 #include "ContentParent.h"
 #include "TabParent.h"
 #include "mozilla/layout/RenderFrameParent.h"
 
+#include "mozilla/Preferences.h"
+
 using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::layers;
 typedef FrameMetrics::ViewID ViewID;
 
 #include "jsapi.h"
 
 class nsAsyncDocShellDestroyer : public nsRunnable
@@ -813,17 +815,17 @@ nsFrameLoader::Show(PRInt32 marginWidth,
 
   // Trigger editor re-initialization if midas is turned on in the
   // sub-document. This shouldn't be necessary, but given the way our
   // editor works, it is. See
   // https://bugzilla.mozilla.org/show_bug.cgi?id=284245
   nsCOMPtr<nsIPresShell> presShell;
   mDocShell->GetPresShell(getter_AddRefs(presShell));
   if (presShell) {
-    nsCOMPtr<nsIDOMNSHTMLDocument> doc =
+    nsCOMPtr<nsIDOMHTMLDocument> doc =
       do_QueryInterface(presShell->GetDocument());
 
     if (doc) {
       nsAutoString designMode;
       doc->GetDesignMode(designMode);
 
       if (designMode.EqualsLiteral("on")) {
         // Hold on to the editor object to let the document reattach to the
@@ -831,17 +833,17 @@ nsFrameLoader::Show(PRInt32 marginWidth,
         nsCOMPtr<nsIEditorDocShell> editorDocshell = do_QueryInterface(mDocShell);
         nsCOMPtr<nsIEditor> editor;
         nsresult rv = editorDocshell->GetEditor(getter_AddRefs(editor));
         NS_ENSURE_SUCCESS(rv, PR_FALSE);
 
         doc->SetDesignMode(NS_LITERAL_STRING("off"));
         doc->SetDesignMode(NS_LITERAL_STRING("on"));
       } else {
-        // Re-initialie the presentation for contenteditable documents
+        // Re-initialize the presentation for contenteditable documents
         nsCOMPtr<nsIEditorDocShell> editorDocshell = do_QueryInterface(mDocShell);
         if (editorDocshell) {
           PRBool editable = PR_FALSE,
                  hasEditingSession = PR_FALSE;
           editorDocshell->GetEditable(&editable);
           editorDocshell->GetHasEditingSession(&hasEditingSession);
           nsCOMPtr<nsIEditor> editor;
           editorDocshell->GetEditor(getter_AddRefs(editor));
@@ -1341,18 +1343,18 @@ nsFrameLoader::ShouldUseRemoteProcess()
   // Check for *disabled* multi-process first: environment, prefs, attribute
   // Then check for *enabled* multi-process pref: attribute, prefs
   // Default is not-remote.
 
   if (PR_GetEnv("MOZ_DISABLE_OOP_TABS")) {
     return false;
   }
 
-  PRBool remoteDisabled = nsContentUtils::GetBoolPref("dom.ipc.tabs.disabled",
-                                                      PR_FALSE);
+  PRBool remoteDisabled =
+    Preferences::GetBool("dom.ipc.tabs.disabled", PR_FALSE);
   if (remoteDisabled) {
     return false;
   }
 
   static nsIAtom* const *const remoteValues[] = {
     &nsGkAtoms::_false,
     &nsGkAtoms::_true,
     nsnull
@@ -1361,18 +1363,17 @@ nsFrameLoader::ShouldUseRemoteProcess()
   switch (mOwnerContent->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::Remote,
                                          remoteValues, eCaseMatters)) {
   case 0:
     return false;
   case 1:
     return true;
   }
 
-  PRBool remoteEnabled = nsContentUtils::GetBoolPref("dom.ipc.tabs.enabled",
-                                                     PR_FALSE);
+  PRBool remoteEnabled = Preferences::GetBool("dom.ipc.tabs.enabled", PR_FALSE);
   return (bool) remoteEnabled;
 }
 
 nsresult
 nsFrameLoader::MaybeCreateDocShell()
 {
   if (mDocShell) {
     return NS_OK;
--- a/content/base/src/nsGenericDOMDataNode.cpp
+++ b/content/base/src/nsGenericDOMDataNode.cpp
@@ -718,17 +718,17 @@ nsGenericDOMDataNode::IndexOf(nsINode* a
 nsresult
 nsGenericDOMDataNode::InsertChildAt(nsIContent* aKid, PRUint32 aIndex,
                                     PRBool aNotify)
 {
   return NS_OK;
 }
 
 nsresult
-nsGenericDOMDataNode::RemoveChildAt(PRUint32 aIndex, PRBool aNotify, PRBool aMutationEvent)
+nsGenericDOMDataNode::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
 {
   return NS_OK;
 }
 
 nsIContent *
 nsGenericDOMDataNode::GetBindingParent() const
 {
   nsDataSlots *slots = GetExistingDataSlots();
@@ -841,62 +841,16 @@ nsGenericDOMDataNode::SplitText(PRUint32
   nsCOMPtr<nsIContent> newChild;
   nsresult rv = SplitData(aOffset, getter_AddRefs(newChild));
   if (NS_SUCCEEDED(rv)) {
     rv = CallQueryInterface(newChild, aReturn);
   }
   return rv;
 }
 
-//----------------------------------------------------------------------
-
-// Implementation of the nsGenericDOMDataNode nsIDOM3Text tearoff
-
-NS_IMPL_CYCLE_COLLECTION_CLASS(nsText3Tearoff)
-
-NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsText3Tearoff)
-  NS_INTERFACE_MAP_ENTRY(nsIDOM3Text)
-NS_INTERFACE_MAP_END_AGGREGATED(mNode)
-
-NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsText3Tearoff)
-  NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mNode)
-NS_IMPL_CYCLE_COLLECTION_UNLINK_END
-
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(nsText3Tearoff)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mNode, nsIContent)
-NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
-
-NS_IMPL_CYCLE_COLLECTING_ADDREF(nsText3Tearoff)
-NS_IMPL_CYCLE_COLLECTING_RELEASE(nsText3Tearoff)
-
-NS_IMETHODIMP
-nsText3Tearoff::GetIsElementContentWhitespace(PRBool *aReturn)
-{
-  *aReturn = mNode->IsElementContentWhitespace();
-  return NS_OK;
-}
-
-NS_IMETHODIMP
-nsText3Tearoff::GetWholeText(nsAString& aWholeText)
-{
-  return mNode->GetWholeText(aWholeText);
-}
-
-NS_IMETHODIMP
-nsText3Tearoff::ReplaceWholeText(const nsAString& aContent,
-                                 nsIDOMText **aReturn)
-{
-  nsresult rv;
-  nsIContent* result = mNode->ReplaceWholeText(PromiseFlatString(aContent),
-                                               &rv);
-  return result ? CallQueryInterface(result, aReturn) : rv;
-}
-
-// Implementation of the nsIDOM3Text interface
-
 /* static */ PRInt32
 nsGenericDOMDataNode::FirstLogicallyAdjacentTextNode(nsIContent* aParent,
                                                      PRInt32 aIndex)
 {
   while (aIndex-- > 0) {
     nsIContent* sibling = aParent->GetChildAt(aIndex);
     if (!sibling->IsNodeOfType(nsINode::eTEXT))
       return aIndex + 1;
@@ -913,17 +867,17 @@ nsGenericDOMDataNode::LastLogicallyAdjac
     nsIContent* sibling = aParent->GetChildAt(aIndex);
     if (!sibling->IsNodeOfType(nsINode::eTEXT))
       return aIndex - 1;
   }
   return aCount - 1;
 }
 
 nsresult
-nsGenericTextNode::GetWholeText(nsAString& aWholeText)
+nsGenericDOMDataNode::GetWholeText(nsAString& aWholeText)
 {
   nsIContent* parent = GetParent();
 
   // Handle parent-less nodes
   if (!parent)
     return GetData(aWholeText);
 
   PRInt32 index = parent->IndexOf(this);
@@ -944,45 +898,44 @@ nsGenericTextNode::GetWholeText(nsAStrin
     node = do_QueryInterface(parent->GetChildAt(first));
     node->GetData(tmp);
     aWholeText.Append(tmp);
   } while (first++ < last);
 
   return NS_OK;
 }
 
-nsIContent*
-nsGenericTextNode::ReplaceWholeText(const nsAFlatString& aContent,
-                                    nsresult* aResult)
+nsresult
+nsGenericDOMDataNode::ReplaceWholeText(const nsAString& aContent,
+                                       nsIDOMText **aResult)
 {
-  *aResult = NS_OK;
+  *aResult = nsnull;
 
   // Handle parent-less nodes
   nsCOMPtr<nsIContent> parent = GetParent();
   if (!parent) {
     if (aContent.IsEmpty()) {
-      return nsnull;
+      return NS_OK;
     }
 
     SetNodeValue(aContent);
-    return this;
+    return CallQueryInterface(this, aResult);
   }
 
   // We're relying on mozAutoSubtreeModified to keep the doc alive here.
   nsIDocument* doc = GetOwnerDoc();
 
   // Batch possible DOMSubtreeModified events.
   mozAutoSubtreeModified subtree(doc, nsnull);
 
   PRInt32 index = parent->IndexOf(this);
   if (index < 0) {
     NS_WARNING("Trying to use .replaceWholeText with an anonymous text node "
                "child of a binding parent?");
-    *aResult = NS_ERROR_DOM_NOT_SUPPORTED_ERR;
-    return nsnull;
+    return NS_ERROR_DOM_NOT_SUPPORTED_ERR;
   }
 
   // We don't support entity references or read-only nodes, so remove the
   // logically adjacent text nodes (which therefore must all be siblings of
   // this) and set this one to the provided text, if that text isn't empty.
   PRInt32 first =
     FirstLogicallyAdjacentTextNode(parent, index);
   PRInt32 last =
@@ -1011,21 +964,21 @@ nsGenericTextNode::ReplaceWholeText(cons
     if (last == index && !aContent.IsEmpty())
       continue;
 
     parent->RemoveChildAt(last, PR_TRUE);
   } while (last-- > first);
 
   // Empty string means we removed this node too.
   if (aContent.IsEmpty()) {
-    return nsnull;
+    return NS_OK;
   }
 
-  SetText(aContent.get(), aContent.Length(), PR_TRUE);
-  return this;
+  SetText(aContent.BeginReading(), aContent.Length(), PR_TRUE);
+  return CallQueryInterface(this, aResult);
 }
 
 //----------------------------------------------------------------------
 
 // Implementation of the nsIContent interface text functions
 
 const nsTextFragment *
 nsGenericDOMDataNode::GetText()
--- a/content/base/src/nsGenericDOMDataNode.h
+++ b/content/base/src/nsGenericDOMDataNode.h
@@ -41,17 +41,16 @@
  */
 
 #ifndef nsGenericDOMDataNode_h___
 #define nsGenericDOMDataNode_h___
 
 #include "nsIContent.h"
 #include "nsIDOMCharacterData.h"
 #include "nsIDOMEventTarget.h"
-#include "nsIDOM3Text.h"
 #include "nsTextFragment.h"
 #include "nsDOMError.h"
 #include "nsIEventListenerManager.h"
 #include "nsGenericElement.h"
 #include "nsCycleCollectionParticipant.h"
 #include "nsContentUtils.h"
 
 #ifdef MOZ_SMIL
@@ -150,17 +149,17 @@ public:
 
   // nsINode methods
   virtual PRUint32 GetChildCount() const;
   virtual nsIContent *GetChildAt(PRUint32 aIndex) const;
   virtual nsIContent * const * GetChildArray(PRUint32* aChildCount) const;
   virtual PRInt32 IndexOf(nsINode* aPossibleChild) const;
   virtual nsresult InsertChildAt(nsIContent* aKid, PRUint32 aIndex,
                                  PRBool aNotify);
-  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify, PRBool aMutationEvent = PR_TRUE);
+  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify);
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
   virtual nsresult PostHandleEvent(nsEventChainPostVisitor& aVisitor);
   virtual nsresult DispatchDOMEvent(nsEvent* aEvent, nsIDOMEvent* aDOMEvent,
                                     nsPresContext* aPresContext,
                                     nsEventStatus* aEventStatus);
   virtual nsIEventListenerManager* GetListenerManager(PRBool aCreateIfNotFound);
   virtual nsresult AddEventListenerByIID(nsIDOMEventListener *aListener,
                                          const nsIID& aIID);
@@ -323,17 +322,25 @@ protected:
 
   nsDataSlots *GetExistingDataSlots() const
   {
     return static_cast<nsDataSlots*>(GetExistingSlots());
   }
 
   nsresult SplitText(PRUint32 aOffset, nsIDOMText** aReturn);
 
-  friend class nsText3Tearoff;
+  nsresult GetWholeText(nsAString& aWholeText);
+
+  nsresult ReplaceWholeText(const nsAString& aContent, nsIDOMText **aReturn);
+
+  nsresult GetIsElementContentWhitespace(PRBool *aReturn)
+  {
+    *aReturn = TextIsOnlyWhitespace();
+    return NS_OK;
+  }
 
   static PRInt32 FirstLogicallyAdjacentTextNode(nsIContent* aParent,
                                                 PRInt32 aIndex);
 
   static PRInt32 LastLogicallyAdjacentTextNode(nsIContent* aParent,
                                                PRInt32 aIndex,
                                                PRUint32 aCount);
 
@@ -355,55 +362,16 @@ protected:
   nsTextFragment mText;
 
 private:
   void UpdateBidiStatus(const PRUnichar* aBuffer, PRUint32 aLength);
 
   already_AddRefed<nsIAtom> GetCurrentValueAtom();
 };
 
-class nsGenericTextNode : public nsGenericDOMDataNode
-{
-public:
-  nsGenericTextNode(already_AddRefed<nsINodeInfo> aNodeInfo)
-  : nsGenericDOMDataNode(aNodeInfo)
-  {
-  }
-
-  PRBool IsElementContentWhitespace()
-  {
-    return TextIsOnlyWhitespace();
-  }
-  nsresult GetWholeText(nsAString& aWholeText);
-
-  nsIContent* ReplaceWholeText(const nsAFlatString& aContent,
-                               nsresult *aResult);
-};
-
-/** Tearoff class for the nsIDOM3Text portion of nsGenericDOMDataNode. */
-class nsText3Tearoff : public nsIDOM3Text
-{
-public:
-  NS_DECL_CYCLE_COLLECTING_ISUPPORTS
-
-  NS_DECL_NSIDOM3TEXT
-
-  NS_DECL_CYCLE_COLLECTION_CLASS(nsText3Tearoff)
-
-  nsText3Tearoff(nsGenericTextNode *aNode) : mNode(aNode)
-  {
-  }
-
-protected:
-  virtual ~nsText3Tearoff() {}
-
-private:
-  nsRefPtr<nsGenericTextNode> mNode;
-};
-
 //----------------------------------------------------------------------
 
 /**
  * Mostly implement the nsIDOMNode API by forwarding the methods to
  * nsGenericDOMDataNode
  *
  * Note that classes using this macro will need to implement:
  *       NS_IMETHOD GetNodeType(PRUint16* aNodeType);
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -89,24 +89,20 @@
 #endif /* MOZ_XUL */
 #include "nsFrameManager.h"
 #include "nsFrameSelection.h"
 
 #include "nsBindingManager.h"
 #include "nsXBLBinding.h"
 #include "nsIXBLService.h"
 #include "nsPIDOMWindow.h"
-#include "nsIBoxObject.h"
 #include "nsPIBoxObject.h"
-#include "nsIDOMNSDocument.h"
 #include "nsIDOMNSElement.h"
 #include "nsClientRect.h"
-#ifdef MOZ_SVG
 #include "nsSVGUtils.h"
-#endif
 #include "nsLayoutUtils.h"
 #include "nsGkAtoms.h"
 #include "nsContentUtils.h"
 #include "nsIJSContextStack.h"
 
 #include "nsIServiceManager.h"
 #include "nsIDOMEventListener.h"
 #include "nsIWebNavigation.h"
@@ -144,19 +140,17 @@
 #include "nsCCUncollectableMarker.h"
 
 #include "mozAutoDocUpdate.h"
 
 #include "nsCSSParser.h"
 #include "nsTPtrArray.h"
 #include "prprf.h"
 
-#ifdef MOZ_SVG
 #include "nsSVGFeatures.h"
-#endif /* MOZ_SVG */
 
 using namespace mozilla::dom;
 namespace css = mozilla::css;
 
 NS_DEFINE_IID(kThisPtrOffsetsSID, NS_THISPTROFFSETS_SID);
 
 PRInt32 nsIContent::sTabFocusModel = eTabFocus_any;
 PRBool nsIContent::sTabFocusModelAppliesToXUL = PR_FALSE;
@@ -3658,33 +3652,31 @@ nsINode::doInsertChildAt(nsIContent* aKi
       (new nsPLDOMEvent(aKid, mutation))->RunDOMEventWhenSafe();
     }
   }
 
   return NS_OK;
 }
 
 nsresult
-nsGenericElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify, PRBool aMutationEvent)
+nsGenericElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
 {
   nsCOMPtr<nsIContent> oldKid = mAttrsAndChildren.GetSafeChildAt(aIndex);
   NS_ASSERTION(oldKid == GetChildAt(aIndex), "Unexpected child in RemoveChildAt");
 
   if (oldKid) {
-    return doRemoveChildAt(aIndex, aNotify, oldKid, mAttrsAndChildren,
-                           aMutationEvent);
+    return doRemoveChildAt(aIndex, aNotify, oldKid, mAttrsAndChildren);
   }
 
   return NS_OK;
 }
 
 nsresult
 nsINode::doRemoveChildAt(PRUint32 aIndex, PRBool aNotify,
-                         nsIContent* aKid, nsAttrAndChildArray& aChildArray,
-                         PRBool aMutationEvent)
+                         nsIContent* aKid, nsAttrAndChildArray& aChildArray)
 {
   NS_PRECONDITION(aKid && aKid->GetNodeParent() == this &&
                   aKid == GetChildAt(aIndex) &&
                   IndexOf(aKid) == (PRInt32)aIndex, "Bogus aKid");
 
   nsMutationGuard::DidMutate();
 
   nsIDocument* doc = GetCurrentDoc();
@@ -3986,20 +3978,20 @@ PRBool IsAllowedAsChild(nsIContent* aNew
   }
 
   return PR_FALSE;
 }
 
 void
 nsGenericElement::FireNodeInserted(nsIDocument* aDoc,
                                    nsINode* aParent,
-                                   nsCOMArray<nsIContent>& aNodes)
-{
-  PRInt32 count = aNodes.Count();
-  for (PRInt32 i = 0; i < count; ++i) {
+                                   nsTArray<nsCOMPtr<nsIContent> >& aNodes)
+{
+  PRUint32 count = aNodes.Length();
+  for (PRUint32 i = 0; i < count; ++i) {
     nsIContent* childContent = aNodes[i];
 
     if (nsContentUtils::HasMutationListeners(childContent,
           NS_EVENT_BITS_MUTATION_NODEINSERTED, aParent)) {
       nsMutationEvent mutation(PR_TRUE, NS_MUTATION_NODEINSERTED);
       mutation.mRelatedNode = do_QueryInterface(aParent);
 
       mozAutoSubtreeModified subtree(aDoc, aParent);
@@ -4154,107 +4146,61 @@ nsINode::ReplaceOrInsertBefore(PRBool aR
     PRUint32 count = newContent->GetChildCount();
 
     if (!count) {
       return NS_OK;
     }
 
     // Copy the children into a separate array to avoid having to deal with
     // mutations to the fragment while we're inserting.
-    nsCOMArray<nsIContent> fragChildren;
-    if (!fragChildren.SetCapacity(count)) {
-      return NS_ERROR_OUT_OF_MEMORY;
-    }
-    PRUint32 i;
-    for (i = 0; i < count; i++) {
+    nsAutoTArray<nsCOMPtr<nsIContent>, 50> fragChildren;
+    fragChildren.SetCapacity(count);
+    for (PRUint32 i = 0; i < count; i++) {
       nsIContent* child = newContent->GetChildAt(i);
       NS_ASSERTION(child->GetCurrentDoc() == nsnull,
                    "How did we get a child with a current doc?");
-      fragChildren.AppendObject(child);
-    }
-
-    // Remove the children from the fragment and flag for possible mutations.
-    PRBool mutated = PR_FALSE;
-    for (i = count; i > 0;) {
-      // We don't need to update i if someone mutates the DOM. The only thing
-      // that'd happen is that the resulting child list might be unexpected,
-      // but we should never crash since RemoveChildAt is out-of-bounds safe.
-      nsMutationGuard guard;
-      newContent->RemoveChildAt(--i, PR_TRUE);
-      mutated = mutated || guard.Mutated(1);
+      fragChildren.AppendElement(child);
     }
 
-    // If we've had any unexpected mutations so far we need to recheck that
-    // the child can still be inserted.
-    if (mutated) {
-      for (i = 0; i < count; ++i) {
-        // Get the n:th child from the array.
-        nsIContent* childContent = fragChildren[i];
-        if (!HasSameOwnerDoc(childContent) ||
-            doc != childContent->GetOwnerDoc()) {
-          return NS_ERROR_DOM_WRONG_DOCUMENT_ERR;
-        }
-
-        nsCOMPtr<nsIDOMNode> tmpNode = do_QueryInterface(childContent);
-        PRUint16 tmpType = 0;
-        tmpNode->GetNodeType(&tmpType);
-
-        if (childContent->GetNodeParent() ||
-            !IsAllowedAsChild(childContent, tmpType, this, PR_FALSE,
-                              refContent)) {
-          return NS_ERROR_DOM_HIERARCHY_REQUEST_ERR;
-        }
-      }
-
-      insPos = refContent ? IndexOf(refContent) : GetChildCount();
-      if (insPos < 0) {
-        // Someone seriously messed up the childlist. We have no idea
-        // where to insert the remaining children, so just bail.
-        return NS_ERROR_DOM_NOT_FOUND_ERR;
-      }
+    // Remove the children from the fragment.
+    for (PRUint32 i = count; i > 0;) {
+      newContent->RemoveChildAt(--i, PR_TRUE);
     }
 
     PRBool appending =
       !IsNodeOfType(eDOCUMENT) && PRUint32(insPos) == GetChildCount();
     PRBool firstInsPos = insPos;
     nsIContent* firstInsertedContent = fragChildren[0];
 
     // Iterate through the fragment's children, and insert them in the new
     // parent
-    for (i = 0; i < count; ++i, ++insPos) {
-      nsIContent* childContent = fragChildren[i];
-
+    for (PRUint32 i = 0; i < count; ++i, ++insPos) {
       // XXXbz how come no reparenting here?  That seems odd...
       // Insert the child.
-      res = InsertChildAt(childContent, insPos, PR_FALSE);
+      res = InsertChildAt(fragChildren[i], insPos, !appending);
       if (NS_FAILED(res)) {
         // Make sure to notify on any children that we did succeed to insert
         if (appending && i != 0) {
           nsNodeUtils::ContentAppended(static_cast<nsIContent*>(this),
                                        firstInsertedContent,
                                        firstInsPos);
         }
         return res;
       }
-
-      if (!appending) {
-        nsNodeUtils::ContentInserted(this, childContent, insPos);
-      }
     }
 
-    // Notify
+    // Notify and fire mutation events when appending
     if (appending) {
       nsNodeUtils::ContentAppended(static_cast<nsIContent*>(this),
                                    firstInsertedContent, firstInsPos);
-    }
-
-    // Fire mutation events. Optimize for the case when there are no listeners
-    if (nsContentUtils::
-          HasMutationListeners(doc, NS_EVENT_BITS_MUTATION_NODEINSERTED)) {
-      nsGenericElement::FireNodeInserted(doc, this, fragChildren);
+      // Optimize for the case when there are no listeners
+      if (nsContentUtils::
+            HasMutationListeners(doc, NS_EVENT_BITS_MUTATION_NODEINSERTED)) {
+        nsGenericElement::FireNodeInserted(doc, this, fragChildren);
+      }
     }
   }
   else {
     // Not inserting a fragment but rather a single node.
 
     // FIXME https://bugzilla.mozilla.org/show_bug.cgi?id=544654
     //       We need to reparent here for nodes for which the parent of their
     //       wrapper is not the wrapper for their ownerDocument (XUL elements,
@@ -4624,17 +4570,17 @@ nsGenericElement::SetAttr(PRInt32 aNames
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (aNotify) {
     nsNodeUtils::AttributeWillChange(this, aNamespaceID, aName, modType);
   }
 
   // Hold a script blocker while calling ParseAttribute since that can call
   // out to id-observers
-  nsAutoRemovableScriptBlocker scriptBlocker;
+  nsAutoScriptBlocker scriptBlocker;
 
   nsAttrValue attrValue;
   if (!ParseAttribute(aNamespaceID, aName, aValue, attrValue)) {
     attrValue.SetTo(aValue);
   }
 
   return SetAttrAndNotify(aNamespaceID, aName, aPrefix, oldValue,
                           attrValue, modType, hasListeners, aNotify,
--- a/content/base/src/nsGenericElement.h
+++ b/content/base/src/nsGenericElement.h
@@ -324,17 +324,17 @@ public:
 
   // nsINode interface methods
   virtual PRUint32 GetChildCount() const;
   virtual nsIContent *GetChildAt(PRUint32 aIndex) const;
   virtual nsIContent * const * GetChildArray(PRUint32* aChildCount) const;
   virtual PRInt32 IndexOf(nsINode* aPossibleChild) const;
   virtual nsresult InsertChildAt(nsIContent* aKid, PRUint32 aIndex,
                                  PRBool aNotify);
-  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify, PRBool aMutationEvent = PR_TRUE);
+  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify);
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
   virtual nsresult PostHandleEvent(nsEventChainPostVisitor& aVisitor);
   virtual nsresult DispatchDOMEvent(nsEvent* aEvent, nsIDOMEvent* aDOMEvent,
                                     nsPresContext* aPresContext,
                                     nsEventStatus* aEventStatus);
   virtual nsIEventListenerManager* GetListenerManager(PRBool aCreateIfNotFound);
   virtual nsresult AddEventListenerByIID(nsIDOMEventListener *aListener,
                                          const nsIID& aIID);
@@ -591,17 +591,17 @@ public:
   static PRBool ShouldBlur(nsIContent *aContent);
 
   /**
    * If there are listeners for DOMNodeInserted event, fires the event on all
    * aNodes
    */
   static void FireNodeInserted(nsIDocument* aDoc,
                                nsINode* aParent,
-                               nsCOMArray<nsIContent>& aNodes);
+                               nsTArray<nsCOMPtr<nsIContent> >& aNodes);
 
   /**
    * Helper methods for implementing querySelector/querySelectorAll
    */
   static nsIContent* doQuerySelector(nsINode* aRoot, const nsAString& aSelector,
                                      nsresult *aResult NS_OUTPARAM);
   static nsresult doQuerySelectorAll(nsINode* aRoot,
                                      const nsAString& aSelector,
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -1092,17 +1092,16 @@ GK_ATOM(xml, "xml")
 GK_ATOM(xmlns, "xmlns")
 GK_ATOM(xmp, "xmp")
 GK_ATOM(xulcontentsgenerated, "xulcontentsgenerated")
 GK_ATOM(yes, "yes")
 GK_ATOM(z_index, "z-index")
 GK_ATOM(zeroDigit, "zero-digit")
 
 
-#ifdef MOZ_SVG
 GK_ATOM(percentage, "%")
 GK_ATOM(A, "A")
 GK_ATOM(alignment_baseline, "alignment-baseline")
 GK_ATOM(allowReorder, "allowReorder")
 GK_ATOM(altGlyph, "altGlyph")
 GK_ATOM(altGlyphDef, "altGlyphDef")
 GK_ATOM(altGlyphItem, "altGlyphItem")
 GK_ATOM(amplitude, "amplitude")
@@ -1342,23 +1341,23 @@ GK_ATOM(userSpaceOnUse, "userSpaceOnUse"
 GK_ATOM(view, "view")
 GK_ATOM(viewBox, "viewBox")
 GK_ATOM(vkern, "vkern")
 GK_ATOM(word_spacing, "word-spacing")
 GK_ATOM(x, "x")
 GK_ATOM(x1, "x1")
 GK_ATOM(x2, "x2")
 GK_ATOM(xChannelSelector, "xChannelSelector")
+GK_ATOM(xor_, "xor")
 GK_ATOM(y, "y")
 GK_ATOM(y1, "y1")
 GK_ATOM(y2, "y2")
 GK_ATOM(yChannelSelector, "yChannelSelector")
 GK_ATOM(z, "z")
 GK_ATOM(zoomAndPan, "zoomAndPan")
-#endif
 
 #ifdef MOZ_SMIL
 GK_ATOM(accumulate, "accumulate")
 GK_ATOM(additive, "additive")
 GK_ATOM(attributeName, "attributeName")
 GK_ATOM(attributeType, "attributeType")
 GK_ATOM(auto_reverse, "auto-reverse")
 GK_ATOM(begin, "begin")
@@ -1665,20 +1664,16 @@ GK_ATOM(verythickmathspace_, "verythickm
 GK_ATOM(verythinmathspace_, "verythinmathspace")
 GK_ATOM(veryverythickmathspace_, "veryverythickmathspace")
 GK_ATOM(veryverythinmathspace_, "veryverythinmathspace")
 GK_ATOM(voffset_, "voffset")
 GK_ATOM(xref_, "xref")
 GK_ATOM(math, "math") // the only one without an underscore
 #endif
 
-#if defined(MOZ_SVG) || defined(MOZ_MATHML)
-GK_ATOM(xor_, "xor")
-#endif
-
 #ifndef DISABLE_XFORMS_HOOKS
 GK_ATOM(avg, "avg")
 GK_ATOM(booleanFromString, "boolean-from-string")
 GK_ATOM(countNonEmpty, "count-non-empty")
 GK_ATOM(daysFromDate, "days-from-date")
 GK_ATOM(init, "init")
 GK_ATOM(instance, "instance")
 GK_ATOM(months, "months")
@@ -1769,17 +1764,16 @@ GK_ATOM(tableOuterFrame, "TableOuterFram
 GK_ATOM(tableRowGroupFrame, "TableRowGroupFrame")
 GK_ATOM(tableRowFrame, "TableRowFrame")
 GK_ATOM(textInputFrame,"TextInputFrame")
 GK_ATOM(textFrame, "TextFrame")
 GK_ATOM(viewportFrame, "ViewportFrame")
 #ifdef MOZ_XUL
 GK_ATOM(XULLabelFrame, "XULLabelFrame")
 #endif
-#ifdef MOZ_SVG
 GK_ATOM(svgAFrame, "SVGAFrame")
 GK_ATOM(svgClipPathFrame, "SVGClipPathFrame")
 GK_ATOM(svgDefsFrame, "SVGDefsFrame")
 GK_ATOM(svgFilterFrame, "SVGFilterFrame")
 GK_ATOM(svgForeignObjectFrame, "SVGForeignObjectFrame")
 GK_ATOM(svgGenericContainerFrame, "SVGGenericContainerFrame")
 GK_ATOM(svgGFrame, "SVGGFrame")
 GK_ATOM(svgGlyphFrame, "SVGGlyphFrame")
@@ -1794,17 +1788,16 @@ GK_ATOM(svgPathGeometryFrame, "SVGPathGe
 GK_ATOM(svgPatternFrame, "SVGPatternFrame")
 GK_ATOM(svgRadialGradientFrame, "SVGRadialGradientFrame")
 GK_ATOM(svgStopFrame, "SVGStopFrame")
 GK_ATOM(svgSwitchFrame, "SVGSwitchFrame")
 GK_ATOM(svgTextFrame, "SVGTextFrame")
 GK_ATOM(svgTextPathFrame, "SVGTextPathFrame")
 GK_ATOM(svgTSpanFrame, "SVGTSpanFrame")
 GK_ATOM(svgUseFrame, "SVGUseFrame")
-#endif
 #ifdef MOZ_MEDIA
 GK_ATOM(HTMLVideoFrame, "VideoFrame")
 GK_ATOM(onloadstart, "onloadstart")
 GK_ATOM(onprogress, "onprogress")
 GK_ATOM(onsuspend, "onsuspend")
 GK_ATOM(onemptied, "onemptied")
 GK_ATOM(onstalled, "onstalled")
 GK_ATOM(onplay, "onplay")
--- a/content/base/src/nsImageLoadingContent.cpp
+++ b/content/base/src/nsImageLoadingContent.cpp
@@ -71,19 +71,17 @@
 #include "nsIFrame.h"
 #include "nsIDOMNode.h"
 
 #include "nsContentUtils.h"
 #include "nsIContentPolicy.h"
 #include "nsContentPolicyUtils.h"
 #include "nsEventDispatcher.h"
 #include "nsDOMClassInfo.h"
-#ifdef MOZ_SVG
 #include "nsSVGEffects.h"
-#endif
 
 #include "mozAutoDocUpdate.h"
 
 #ifdef DEBUG_chb
 static void PrintReqURL(imgIRequest* req) {
   if (!req) {
     printf("(null req)\n");
     return;
@@ -353,20 +351,18 @@ nsImageLoadingContent::OnStopDecode(imgI
 
   // Fire the appropriate DOM event.
   if (NS_SUCCEEDED(aStatus)) {
     FireEvent(NS_LITERAL_STRING("load"));
   } else {
     FireEvent(NS_LITERAL_STRING("error"));
   }
 
-#ifdef MOZ_SVG
   nsCOMPtr<nsINode> thisNode = do_QueryInterface(this);
   nsSVGEffects::InvalidateDirectRenderingObservers(thisNode->AsElement());
-#endif
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsImageLoadingContent::OnStopRequest(imgIRequest* aRequest, PRBool aLastPart)
 {
   NS_ENSURE_TRUE(nsContentUtils::IsCallerChrome(), NS_ERROR_NOT_AVAILABLE);
--- a/content/base/src/nsNameSpaceManager.cpp
+++ b/content/base/src/nsNameSpaceManager.cpp
@@ -263,19 +263,17 @@ NameSpaceManagerImpl::HasElementCreator(
 {
   return aNameSpaceID == kNameSpaceID_XHTML ||
 #ifdef MOZ_XUL
          aNameSpaceID == kNameSpaceID_XUL ||
 #endif
 #ifdef MOZ_MATHML
          aNameSpaceID == kNameSpaceID_MathML ||
 #endif
-#ifdef MOZ_SVG
          aNameSpaceID == kNameSpaceID_SVG ||
-#endif
          aNameSpaceID == kNameSpaceID_XMLEvents ||
          PR_FALSE;
 }
 
 nsresult NameSpaceManagerImpl::AddNameSpace(const nsAString& aURI,
                                             const PRInt32 aNameSpaceID)
 {
   if (aNameSpaceID < 0) {
--- a/content/base/src/nsObjectLoadingContent.cpp
+++ b/content/base/src/nsObjectLoadingContent.cpp
@@ -1492,21 +1492,18 @@ nsObjectLoadingContent::LoadObject(nsIUR
   return NS_OK;
 }
 
 PRUint32
 nsObjectLoadingContent::GetCapabilities() const
 {
   return eSupportImages |
          eSupportPlugins |
-         eSupportDocuments
-#ifdef MOZ_SVG
-         | eSupportSVG
-#endif
-         ;
+         eSupportDocuments |
+         eSupportSVG;
 }
 
 void
 nsObjectLoadingContent::Fallback(PRBool aNotify)
 {
   LOG(("OBJLC [%p]: Falling back (Notify=%i)\n", this, aNotify));
 
   AutoNotifier notifier(this, aNotify);
@@ -1701,22 +1698,18 @@ nsObjectLoadingContent::ObjectType
 nsObjectLoadingContent::GetTypeOfContent(const nsCString& aMIMEType)
 {
   PRUint32 caps = GetCapabilities();
 
   if ((caps & eSupportImages) && IsSupportedImage(aMIMEType)) {
     return eType_Image;
   }
 
-#ifdef MOZ_SVG
   PRBool isSVG = aMIMEType.LowerCaseEqualsLiteral("image/svg+xml");
   PRBool supportedSVG = isSVG && (caps & eSupportSVG);
-#else
-  PRBool supportedSVG = PR_FALSE;
-#endif
   if (((caps & eSupportDocuments) || supportedSVG) &&
       IsSupportedDocument(aMIMEType)) {
     return eType_Document;
   }
 
   if ((caps & eSupportPlugins) && IsSupportedPlugin(aMIMEType)) {
     return eType_Plugin;
   }
--- a/content/base/src/nsObjectLoadingContent.h
+++ b/content/base/src/nsObjectLoadingContent.h
@@ -190,19 +190,17 @@ class nsObjectLoadingContent : public ns
                         PRBool aForceLoad = PR_FALSE);
 
     enum Capabilities {
       eSupportImages    = PR_BIT(0), // Images are supported (imgILoader)
       eSupportPlugins   = PR_BIT(1), // Plugins are supported (nsIPluginHost)
       eSupportDocuments = PR_BIT(2), // Documents are supported
                                      // (nsIDocumentLoaderFactory)
                                      // This flag always includes SVG
-#ifdef MOZ_SVG
       eSupportSVG       = PR_BIT(3), // SVG is supported (image/svg+xml)
-#endif
       eSupportClassID   = PR_BIT(4), // The classid attribute is supported
       eOverrideServerType = PR_BIT(5) // The server-sent MIME type is ignored
                                       // (ignored if no type is specified)
     };
 
     /**
      * Returns the list of capabilities this content node supports. This is a
      * bitmask consisting of flags from the Capabilities enum.
--- a/content/base/src/nsPlainTextSerializer.cpp
+++ b/content/base/src/nsPlainTextSerializer.cpp
@@ -53,17 +53,19 @@
 #include "nsINameSpaceManager.h"
 #include "nsTextFragment.h"
 #include "nsContentUtils.h"
 #include "nsReadableUtils.h"
 #include "nsUnicharUtils.h"
 #include "nsCRT.h"
 #include "nsIParserService.h"
 #include "mozilla/dom/Element.h"
+#include "mozilla/Preferences.h"
 
+using namespace mozilla;
 using namespace mozilla::dom;
 
 #define PREF_STRUCTS "converter.html2txt.structs"
 #define PREF_HEADER_STRATEGY "converter.html2txt.header_strategy"
 
 static const  PRInt32 kTabSize=4;
 static const  PRInt32 kOLNumberWidth = 3;
 static const  PRInt32 kIndentSizeHeaders = 2;  /* Indention of h1, if
@@ -201,38 +203,37 @@ nsPlainTextSerializer::Init(PRUint32 aFl
     mLineBreak.AssignLiteral(NS_LINEBREAK);
   }
 
   mLineBreakDue = PR_FALSE;
   mFloatingLines = -1;
 
   if (mFlags & nsIDocumentEncoder::OutputFormatted) {
     // Get some prefs that controls how we do formatted output
-    mStructs = nsContentUtils::GetBoolPref(PREF_STRUCTS, mStructs);
+    mStructs = Preferences::GetBool(PREF_STRUCTS, mStructs);
 
     mHeaderStrategy =
-      nsContentUtils::GetIntPref(PREF_HEADER_STRATEGY, mHeaderStrategy);
+      Preferences::GetInt(PREF_HEADER_STRATEGY, mHeaderStrategy);
 
     // The quotesPreformatted pref is a temporary measure. See bug 69638.
     mQuotesPreformatted =
-      nsContentUtils::GetBoolPref("editor.quotesPreformatted",
-                                  mQuotesPreformatted);
+      Preferences::GetBool("editor.quotesPreformatted", mQuotesPreformatted);
 
     // DontWrapAnyQuotes is set according to whether plaintext mail
     // is wrapping to window width -- see bug 134439.
     // We'll only want this if we're wrapping and formatted.
     if (mFlags & nsIDocumentEncoder::OutputWrap || mWrapColumn > 0) {
       mDontWrapAnyQuotes =
-        nsContentUtils::GetBoolPref("mail.compose.wrap_to_window_width",
-                                    mDontWrapAnyQuotes);
+        Preferences::GetBool("mail.compose.wrap_to_window_width",
+                             mDontWrapAnyQuotes);
     }
   }
 
   // XXX We should let the caller pass this in.
-  if (nsContentUtils::GetBoolPref("browser.frames.enabled")) {
+  if (Preferences::GetBool("browser.frames.enabled")) {
     mFlags &= ~nsIDocumentEncoder::OutputNoFramesContent;
   }
   else {
     mFlags |= nsIDocumentEncoder::OutputNoFramesContent;
   }
 
   return NS_OK;
 }
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -41,17 +41,16 @@
 
 #include "nscore.h"
 #include "nsRange.h"
 
 #include "nsString.h"
 #include "nsReadableUtils.h"
 #include "nsIDOMNode.h"
 #include "nsIDOMDocument.h"
-#include "nsIDOMNSDocument.h"
 #include "nsIDOMDocumentFragment.h"
 #include "nsIContent.h"
 #include "nsIDocument.h"
 #include "nsIDOMText.h"
 #include "nsDOMError.h"
 #include "nsIContentIterator.h"
 #include "nsIDOMNodeList.h"
 #include "nsGkAtoms.h"
--- a/content/base/src/nsStyledElement.cpp
+++ b/content/base/src/nsStyledElement.cpp
@@ -47,20 +47,17 @@
 #include "nsDOMCSSAttrDeclaration.h"
 #include "nsServiceManagerUtils.h"
 #include "nsIDocument.h"
 #include "mozilla/css/StyleRule.h"
 #include "nsCSSParser.h"
 #include "mozilla/css/Loader.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsXULElement.h"
-
-#ifdef MOZ_SVG
 #include "nsIDOMSVGStylable.h"
-#endif
 
 namespace css = mozilla::css;
 
 //----------------------------------------------------------------------
 // nsIContent methods
 
 nsIAtom*
 nsStyledElementNotElementCSSInlineStyle::GetClassAttributeName() const
@@ -131,17 +128,17 @@ nsStyledElementNotElementCSSInlineStyle:
                                              aResult);
 }
 
 nsresult
 nsStyledElementNotElementCSSInlineStyle::UnsetAttr(PRInt32 aNameSpaceID,
                                                    nsIAtom* aAttribute,
                                                    PRBool aNotify)
 {
-  nsAutoRemovableScriptBlocker scriptBlocker;
+  nsAutoScriptBlocker scriptBlocker;
   if (aAttribute == nsGkAtoms::id && aNameSpaceID == kNameSpaceID_None) {
     // Have to do this before clearing flag. See RemoveFromIdTable
     RemoveFromIdTable();
   }
 
   return nsGenericElement::UnsetAttr(aNameSpaceID, aAttribute, aNotify);
 }
 
--- a/content/base/src/nsTextNode.cpp
+++ b/content/base/src/nsTextNode.cpp
@@ -35,17 +35,16 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Implementation of DOM Core's nsIDOMText node.
  */
 
 #include "nsTextNode.h"
-#include "nsIDOM3Text.h"
 #include "nsContentUtils.h"
 #include "nsIDOMEventListener.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsIAttribute.h"
 #include "nsIDocument.h"
 #include "nsThreadUtils.h"
 
@@ -137,34 +136,33 @@ NS_NewTextNode(nsIContent** aInstancePtr
   }
 
   NS_ADDREF(*aInstancePtrResult = instance);
 
   return NS_OK;
 }
 
 nsTextNode::nsTextNode(already_AddRefed<nsINodeInfo> aNodeInfo)
-  : nsGenericTextNode(aNodeInfo)
+  : nsGenericDOMDataNode(aNodeInfo)
 {
 }
 
 nsTextNode::~nsTextNode()
 {
 }
 
 NS_IMPL_ADDREF_INHERITED(nsTextNode, nsGenericDOMDataNode)
 NS_IMPL_RELEASE_INHERITED(nsTextNode, nsGenericDOMDataNode)
 
 DOMCI_NODE_DATA(Text, nsTextNode)
 
 // QueryInterface implementation for nsTextNode
 NS_INTERFACE_TABLE_HEAD(nsTextNode)
   NS_NODE_INTERFACE_TABLE3(nsTextNode, nsIDOMNode, nsIDOMText,
                            nsIDOMCharacterData)
-  NS_INTERFACE_MAP_ENTRY_TEAROFF(nsIDOM3Text, new nsText3Tearoff(this))
   NS_INTERFACE_MAP_ENTRIES_CYCLE_COLLECTION(nsTextNode)
   NS_DOM_INTERFACE_MAP_ENTRY_CLASSINFO(Text)
 NS_INTERFACE_MAP_END_INHERITING(nsGenericDOMDataNode)
 
 NS_IMETHODIMP
 nsTextNode::GetNodeName(nsAString& aNodeName)
 {
   aNodeName.AssignLiteral("#text");
--- a/content/base/src/nsTextNode.h
+++ b/content/base/src/nsTextNode.h
@@ -36,29 +36,28 @@
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Implementation of DOM Core's nsIDOMText node.
  */
 
 #include "nsGenericDOMDataNode.h"
 #include "nsIDOMText.h"
-#include "nsIDOM3Text.h"
 #include "nsContentUtils.h"
 #include "nsIDOMEventListener.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMMutationEvent.h"
 #include "nsIAttribute.h"
 #include "nsIDocument.h"
 #include "nsThreadUtils.h"
 
 /**
  * Class used to implement DOM text nodes
  */
-class nsTextNode : public nsGenericTextNode,
+class nsTextNode : public nsGenericDOMDataNode,
                    public nsIDOMText
 {
 public:
   nsTextNode(already_AddRefed<nsINodeInfo> aNodeInfo);
   virtual ~nsTextNode();
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
--- a/content/base/src/nsWebSocket.cpp
+++ b/content/base/src/nsWebSocket.cpp
@@ -70,16 +70,17 @@
 #include "jsdbgapi.h"
 #include "nsIJSContextStack.h"
 #include "nsJSUtils.h"
 #include "nsIScriptError.h"
 #include "nsNetUtil.h"
 #include "nsIWebSocketProtocol.h"
 #include "nsILoadGroup.h"
 #include "nsIRequest.h"
+#include "mozilla/Preferences.h"
 
 using namespace mozilla;
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsWebSocketEstablishedConnection
 ////////////////////////////////////////////////////////////////////////////////
 
 #define UTF_8_REPLACEMENT_CHAR    static_cast<PRUnichar>(0xFFFD)
@@ -897,17 +898,17 @@ nsWebSocket::CreateAndDispatchCloseEvent
   NS_ENSURE_SUCCESS(rv, rv);
 
   return DispatchDOMEvent(nsnull, event, nsnull, nsnull);
 }
 
 PRBool
 nsWebSocket::PrefEnabled()
 {
-  return nsContentUtils::GetBoolPref("network.websocket.enabled", PR_TRUE);
+  return Preferences::GetBool("network.websocket.enabled", PR_TRUE);
 }
 
 void
 nsWebSocket::SetReadyState(PRUint16 aNewReadyState)
 {
   NS_ABORT_IF_FALSE(NS_IsMainThread(), "Not running on main thread");
   nsresult rv;
 
--- a/content/base/src/nsXMLHttpRequest.cpp
+++ b/content/base/src/nsXMLHttpRequest.cpp
@@ -421,17 +421,18 @@ NS_IMPL_RELEASE_INHERITED(nsXMLHttpReque
 nsXMLHttpRequest::nsXMLHttpRequest()
   : mResponseType(XML_HTTP_RESPONSE_TYPE_DEFAULT),
     mRequestObserver(nsnull), mState(XML_HTTP_REQUEST_UNSENT),
     mUploadTransferred(0), mUploadTotal(0), mUploadComplete(PR_TRUE),
     mUploadProgress(0), mUploadProgressMax(0),
     mErrorLoad(PR_FALSE), mTimerIsActive(PR_FALSE),
     mProgressEventWasDelayed(PR_FALSE),
     mLoadLengthComputable(PR_FALSE), mLoadTotal(0),
-    mFirstStartRequestSeen(PR_FALSE)
+    mFirstStartRequestSeen(PR_FALSE),
+    mResultArrayBuffer(nsnull) 
 {
   mResponseBodyUnicode.SetIsVoid(PR_TRUE);
   nsLayoutStatics::AddRef();
 }
 
 nsXMLHttpRequest::~nsXMLHttpRequest()
 {
   if (mListenerManager) {
@@ -445,16 +446,22 @@ nsXMLHttpRequest::~nsXMLHttpRequest()
   }
 
   NS_ABORT_IF_FALSE(!(mState & XML_HTTP_REQUEST_SYNCLOOPING), "we rather crash than hang");
   mState &= ~XML_HTTP_REQUEST_SYNCLOOPING;
 
   nsLayoutStatics::Release();
 }
 
+void
+nsXMLHttpRequest::RootResultArrayBuffer()
+{
+  nsContentUtils::PreserveWrapper(static_cast<nsPIDOMEventTarget*>(this), this);
+}
+
 /**
  * This Init method is called from the factory constructor.
  */
 nsresult
 nsXMLHttpRequest::Init()
 {
   // Set the original mScriptContext and mPrincipal, if available.
   // Get JSContext from stack.
@@ -567,19 +574,19 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_
 
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mChannelEventSink)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mProgressEventSink)
 
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mUpload,
                                                        nsIXMLHttpRequestUpload)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
-
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsXMLHttpRequest,
                                                 nsXHREventTarget)
+  tmp->mResultArrayBuffer = nsnull;
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mContext)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mChannel)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mReadRequest)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mResponseXML)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mCORSPreflightChannel)
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnUploadProgressListener)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mOnReadystatechangeListener)
@@ -587,16 +594,24 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_IN
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mXMLParserStreamListener)
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mChannelEventSink)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mProgressEventSink)
 
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mUpload)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
+NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(nsXMLHttpRequest,
+                                               nsXHREventTarget)
+  if(tmp->mResultArrayBuffer) {
+    NS_IMPL_CYCLE_COLLECTION_TRACE_JS_CALLBACK(tmp->mResultArrayBuffer,
+                                               "mResultArrayBuffer")
+  }
+NS_IMPL_CYCLE_COLLECTION_TRACE_END
+
 DOMCI_DATA(XMLHttpRequest, nsXMLHttpRequest)
 
 // QueryInterface implementation for nsXMLHttpRequest
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(nsXMLHttpRequest)
   NS_INTERFACE_MAP_ENTRY(nsIXMLHttpRequest)
   NS_INTERFACE_MAP_ENTRY(nsIJSXMLHttpRequest)
   NS_INTERFACE_MAP_ENTRY(nsIDOMLoadListener)
   NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
@@ -834,37 +849,30 @@ NS_IMETHODIMP nsXMLHttpRequest::GetRespo
   if (mState & (XML_HTTP_REQUEST_DONE |
                 XML_HTTP_REQUEST_LOADING)) {
     rv = ConvertBodyToText(aResponseText);
   }
 
   return rv;
 }
 
-nsresult nsXMLHttpRequest::GetResponseArrayBuffer(jsval *aResult)
+nsresult nsXMLHttpRequest::CreateResponseArrayBuffer(JSContext *aCx)
 {
-  JSContext *cx = nsContentUtils::GetCurrentJSContext();
-  if (!cx)
+  if (!aCx)
     return NS_ERROR_FAILURE;
 
-  if (!(mState & (XML_HTTP_REQUEST_DONE |
-                  XML_HTTP_REQUEST_LOADING))) {
-    *aResult = JSVAL_NULL;
-    return NS_OK;
-  }
-
   PRInt32 dataLen = mResponseBody.Length();
-  JSObject *obj = js_CreateArrayBuffer(cx, dataLen);
-  if (!obj)
+  RootResultArrayBuffer();
+  mResultArrayBuffer = js_CreateArrayBuffer(aCx, dataLen);
+  if (!mResultArrayBuffer) {
     return NS_ERROR_FAILURE;
-
-  *aResult = OBJECT_TO_JSVAL(obj);
+  }
 
   if (dataLen > 0) {
-    js::ArrayBuffer *abuf = js::ArrayBuffer::fromJSObject(obj);
+    js::ArrayBuffer *abuf = js::ArrayBuffer::fromJSObject(mResultArrayBuffer);
     NS_ASSERTION(abuf, "What happened?");
     memcpy(abuf->data, mResponseBody.BeginReading(), dataLen);
   }
 
   return NS_OK;
 }
 
 /* attribute AString responseType; */
@@ -949,17 +957,21 @@ NS_IMETHODIMP nsXMLHttpRequest::GetRespo
       if (buf) {
         str.ForgetSharedBuffer();
       }
     }
     break;
 
   case XML_HTTP_RESPONSE_TYPE_ARRAYBUFFER:
     if (mState & XML_HTTP_REQUEST_DONE) {
-      rv = GetResponseArrayBuffer(aResult);
+      if (!mResultArrayBuffer) {  
+         rv = CreateResponseArrayBuffer(aCx);
+         NS_ENSURE_SUCCESS(rv, rv);
+      }
+      *aResult = OBJECT_TO_JSVAL(mResultArrayBuffer);
     } else {
       *aResult = JSVAL_NULL;
     }
     break;
 
   case XML_HTTP_RESPONSE_TYPE_BLOB:
     if (mState & XML_HTTP_REQUEST_DONE && mResponseBlob) {
       JSObject* scope = JS_GetScopeChain(aCx);
@@ -1068,17 +1080,18 @@ nsXMLHttpRequest::Abort()
     mCORSPreflightChannel->Cancel(NS_BINDING_ABORTED);
   }
   mResponseXML = nsnull;
   PRUint32 responseLength = mResponseBody.Length();
   mResponseBody.Truncate();
   mResponseBodyUnicode.SetIsVoid(PR_TRUE);
   mResponseBlob = nsnull;
   mState |= XML_HTTP_REQUEST_ABORTED;
-
+  mResultArrayBuffer = nsnull;
+  
   if (!(mState & (XML_HTTP_REQUEST_UNSENT |
                   XML_HTTP_REQUEST_OPENED |
                   XML_HTTP_REQUEST_DONE))) {
     ChangeState(XML_HTTP_REQUEST_DONE, PR_TRUE);
   }
 
   if (!(mState & XML_HTTP_REQUEST_SYNCLOOPING)) {
     NS_NAMED_LITERAL_STRING(abortStr, ABORT_STR);
--- a/content/base/src/nsXMLHttpRequest.h
+++ b/content/base/src/nsXMLHttpRequest.h
@@ -203,33 +203,33 @@ public:
                           aLoaded, aLengthComputable ? aTotal : LL_MAXUINT);
   }
 
   // This is called by the factory constructor.
   nsresult Init();
 
   void SetRequestObserver(nsIRequestObserver* aObserver);
 
-  NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsXMLHttpRequest,
+  NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_INHERITED(nsXMLHttpRequest,
                                            nsXHREventTarget)
-
   PRBool AllowUploadProgress();
-
+  void RootResultArrayBuffer();
+  
 protected:
   friend class nsMultipartProxyListener;
 
   nsresult DetectCharset(nsACString& aCharset);
   nsresult ConvertBodyToText(nsAString& aOutBuffer);
   static NS_METHOD StreamReaderFunc(nsIInputStream* in,
                 void* closure,
                 const char* fromRawSegment,
                 PRUint32 toOffset,
                 PRUint32 count,
                 PRUint32 *writeCount);
-  nsresult GetResponseArrayBuffer(jsval *aResult);
+  nsresult CreateResponseArrayBuffer(JSContext* aCx);
   void CreateResponseBlob(nsIRequest *request);
   // Change the state of the object with this. The broadcast argument
   // determines if the onreadystatechange listener should be called.
   nsresult ChangeState(PRUint32 aState, PRBool aBroadcast = PR_TRUE);
   nsresult RequestCompleted();
   nsresult GetLoadGroup(nsILoadGroup **aLoadGroup);
   nsIURI *GetBaseURI();
 
@@ -340,16 +340,18 @@ protected:
   PRPackedBool mLoadLengthComputable;
   PRUint64 mLoadTotal; // 0 if not known.
   nsCOMPtr<nsITimer> mProgressNotifier;
 
   PRPackedBool mFirstStartRequestSeen;
   
   nsCOMPtr<nsIAsyncVerifyRedirectCallback> mRedirectCallback;
   nsCOMPtr<nsIChannel> mNewRedirectChannel;
+  
+  JSObject* mResultArrayBuffer;
 };
 
 // helper class to expose a progress DOM Event
 
 class nsXMLHttpProgressEvent : public nsIDOMProgressEvent,
                                public nsIDOMLSProgressEvent,
                                public nsIDOMNSEvent,
                                public nsIPrivateDOMEvent
--- a/content/base/test/test_XHR.html
+++ b/content/base/test/test_XHR.html
@@ -129,16 +129,26 @@ xhr.responseType = 'arraybuffer';
 xhr.send(null)
 is(xhr.status, 200, "wrong status");
 checkResponseTextAccessThrows(xhr);
 checkResponseXMLAccessThrows(xhr);
 ab = xhr.response;
 ok(ab != null, "should have a non-null arraybuffer");
 arraybuffer_equals_to(ab, "\xaa\xee\0\x03\xff\xff\xff\xff\xbb\xbb\xbb\xbb");
 
+// test array buffer GetResult returns the same object
+xhr = new XMLHttpRequest();
+xhr.open("GET", 'file_XHR_binary1.bin', false); 
+xhr.responseType = 'arraybuffer';
+xhr.send(null)
+is(xhr.status, 200, "wrong status");
+checkResponseTextAccessThrows(xhr);
+checkResponseXMLAccessThrows(xhr);
+is(xhr.response, xhr.response, "returns the same ArrayBuffer");
+
 // test response (responseType='blob')
 var onloadCount = 0;
 function checkOnloadCount() {
   if (++onloadCount >= 2) SimpleTest.finish();
 };
 
 // with a simple text file
 xhr = new XMLHttpRequest();
--- a/content/base/test/test_classList.html
+++ b/content/base/test/test_classList.html
@@ -160,55 +160,49 @@ function testClassList(e) {
   is(e.classList + "", "", "wrong classList string conversion value");
 
   e.setAttribute("class", "foo");
   is(e.classList.toString(), "foo", "wrong classList.toString() value");
   is(e.classList + "", "foo", "wrong classList string conversion value");
 
   // item() method
 
-  // TODO out of bounds array indexing should return undefined according to the
-  // WebIDL spec. They are returning an empty string at the moment. (bug 529328)
-  var OOB_VALUE = "";
-  todo_is(OOB_VALUE, undefined, "Wrong out of bounds value");
-
   e.setAttribute("class", "a");
   is(e.classList.item(-1), null, "wrong classList.item() result");
-  is(e.classList[-1], OOB_VALUE, "wrong classList[] result");
+  is(e.classList[-1], undefined, "wrong classList[] result");
   is(e.classList.item(0), "a", "wrong classList.item() result");
-  is(e.classList[0], "a", "wrong classList.item() result");
+  is(e.classList[0], "a", "wrong classList[] result");
   is(e.classList.item(1), null, "wrong classList.item() result");
-  is(e.classList[1], OOB_VALUE, "wrong classList.item() result");
+  is(e.classList[1], undefined, "wrong classList[] result");
 
   e.setAttribute("class", "aa AA aa");
   is(e.classList.item(-1), null, "wrong classList.item() result");
-  is(e.classList[-1], OOB_VALUE, "wrong classList[] result");
+  is(e.classList[-1], undefined, "wrong classList[] result");
   is(e.classList.item(0), "aa", "wrong classList.item() result");
   is(e.classList[0], "aa", "wrong classList[] result");
   is(e.classList.item(1), "AA", "wrong classList.item() result");
   is(e.classList[1], "AA", "wrong classList[] result");
   is(e.classList.item(2), "aa", "wrong classList.item() result");
   is(e.classList[2], "aa", "wrong classList[] result");
   is(e.classList.item(3), null, "wrong classList.item() result");
-  is(e.classList[3], OOB_VALUE, "wrong classList[] result");
+  is(e.classList[3], undefined, "wrong classList[] result");
   is(e.classList.item(0xffffffff), null, "wrong classList.item() result");
-  // XXX returns undefined for index >= 0xffffffff
-  todo_is(e.classList[0xffffffff], OOB_VALUE, "wrong classList[] result");
+  is(e.classList[0xffffffff], undefined, "wrong classList[] result");
   is(e.classList.item(0xfffffffe), null, "wrong classList.item() result");
-  is(e.classList[0xffffffe], OOB_VALUE, "wrong classList[] result");
+  is(e.classList[0xffffffe], undefined, "wrong classList[] result");
 
   e.setAttribute("class", "a b");
   is(e.classList.item(-1), null, "wrong classList.item() result");
-  is(e.classList[-1], OOB_VALUE, "wrong classList[] result");
+  is(e.classList[-1], undefined, "wrong classList[] result");
   is(e.classList.item(0), "a", "wrong classList.item() result");
   is(e.classList[0], "a", "wrong classList[] result");
   is(e.classList.item(1), "b", "wrong classList.item() result");
   is(e.classList[1], "b", "wrong classList[] result");
   is(e.classList.item(2), null, "wrong classList.item() result");
-  is(e.classList[2], OOB_VALUE, "wrong classList[] result");
+  is(e.classList[2], undefined, "wrong classList[] result");
 
   // contains() method
 
   e.removeAttribute("class");
   is(e.classList.contains("a"), false, "wrong classList.contains() result");
   try {
     e.classList.contains("");
     ok(false, "classList.contains() didn't throw");
--- a/content/base/test/test_text_replaceWholeText.html
+++ b/content/base/test/test_text_replaceWholeText.html
@@ -20,17 +20,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 421765 **/
 
 SimpleTest.waitForExplicitFinish();
 
 var xmlDoc;
 
-function entity(n) { return xmlDoc.createEntityReference(n); }
 function text(t) { return document.createTextNode(t); }
 function element() { return document.createElement("div"); }
 function cdata(t)
 {
   xmlDoc = $("xmlDocument").contentDocument;
   // document.createCDATASection isn't implemented; clone for the win
   var node = xmlDoc.documentElement.firstChild.cloneNode(false);
   is(node.nodeType, Node.CDATA_SECTION_NODE,
@@ -228,38 +227,23 @@ function endTests()
   is(second.nextSibling, null, "wrong nextSibling for second");
 
   ok(cdataNode.replaceWholeText("") === null,
      "empty string should cause a return of null");
   is(cdataNode.data, "cdata", "wrong data after replacing with empty string");
   is(outer.lastChild, first, "should be no more text at end");
 }
 
-function entityTests()
-{
-  todo_isnot(entity("bar"), null,
-             "need implementation update if we ever support entity nodes!");
-
-  var root = xmlDoc.documentElement;
-  is(root.lastChild.firstChild.nodeType, Node.TEXT_NODE,
-     "uh-oh, did we start supporting entity references as nodes?");
-  is(root.lastChild.lastChild.nodeType, Node.ELEMENT_NODE,
-     "uh-oh, did we start supporting entity references as nodes?");
-
-  // If any of the above ever fails, add tests here!
-}
-
 function test()
 {
   try
   {
     startTests();
     middleTests();
     endTests();
-    entityTests();
   }
   catch (e)
   {
     ok(false, "exception thrown: " + e);
   }
   finally
   {
     SimpleTest.finish();
--- a/content/base/test/test_text_wholeText.html
+++ b/content/base/test/test_text_wholeText.html
@@ -20,17 +20,16 @@ https://bugzilla.mozilla.org/show_bug.cg
 <script class="testbody" type="text/javascript">
 
 /** Test for Bug 421765 **/
 
 SimpleTest.waitForExplicitFinish();
 
 var xmlDoc;
 
-function entity(n) { return xmlDoc.createEntityReference(n); }
 function text(t) { return document.createTextNode(t); }
 function element() { return document.createElement("div"); }
 function cdata(t)
 {
   xmlDoc = $("xmlDocument").contentDocument;
   // document.createCDATASection isn't implemented; clone for the win
   var node = xmlDoc.documentElement.firstChild.cloneNode(false);
   is(node.nodeType, Node.CDATA_SECTION_NODE,
@@ -202,39 +201,24 @@ function noParentTests()
 
   var cdataSection = cdata("baz");
   is(cdataSection.wholeText, cdataSection.data,
      "orphaned cdatasection should have wholeText == data");
   is(cdataSection.wholeText, "baz",
      "orphaned cdatasection should have wholeText == data");
 }
 
-function entityTests()
-{
-  todo_isnot(entity("bar"), null,
-             "need implementation update if we ever support entity nodes!");
-
-  var root = xmlDoc.documentElement;
-  is(root.lastChild.firstChild.nodeType, Node.TEXT_NODE,
-     "uh-oh, did we start supporting entity references as nodes?");
-  is(root.lastChild.lastChild.nodeType, Node.ELEMENT_NODE,
-     "uh-oh, did we start supporting entity references as nodes?");
-
-  // If any of the above ever fails, add tests here!
-}
-
 function tests()
 {
   try
   {
     firstTests();
     middleTests();
     lastTests();
     noParentTests();
-    entityTests();
   }
   catch (e)
   {
     ok(false, "error thrown: " + e);
   }
   finally
   {
     SimpleTest.finish();
--- a/content/canvas/src/WebGLContext.cpp
+++ b/content/canvas/src/WebGLContext.cpp
@@ -59,19 +59,17 @@
 
 #include "CanvasUtils.h"
 #include "nsDisplayList.h"
 
 #include "GLContextProvider.h"
 
 #include "gfxCrashReporterUtils.h"
 
-#ifdef MOZ_SVG
 #include "nsSVGEffects.h"
-#endif
 
 #include "prenv.h"
 
 using namespace mozilla;
 using namespace mozilla::gl;
 using namespace mozilla::layers;
 
 nsresult NS_NewCanvasRenderingContextWebGL(nsIDOMWebGLRenderingContext** aResult);
@@ -272,19 +270,17 @@ void
 WebGLContext::Invalidate()
 {
     if (mInvalidated)
         return;
 
     if (!mCanvasElement)
         return;
 
-#ifdef MOZ_SVG
     nsSVGEffects::InvalidateDirectRenderingObservers(HTMLCanvasElement());
-#endif
 
     mInvalidated = PR_TRUE;
     HTMLCanvasElement()->InvalidateCanvasContent(nsnull);
 }
 
 /* readonly attribute nsIDOMHTMLCanvasElement canvas; */
 NS_IMETHODIMP
 WebGLContext::GetCanvas(nsIDOMHTMLCanvasElement **canvas)
--- a/content/canvas/src/nsCanvasRenderingContext2D.cpp
+++ b/content/canvas/src/nsCanvasRenderingContext2D.cpp
@@ -531,21 +531,19 @@ protected:
     /**
      * Returns true iff a shadow should be drawn along with a
      * drawing operation.
      */
     PRBool NeedToDrawShadow()
     {
         ContextState& state = CurrentState();
 
-        // The spec says we should not draw shadows when the alpha value is 0,
-        // regardless of the operator being used.
         return state.StyleIsColor(STYLE_SHADOW) &&
                NS_GET_A(state.colorStyles[STYLE_SHADOW]) > 0 &&
-               (state.shadowOffset != gfxPoint(0, 0) || state.shadowBlur != 0);
+               mThebes->CurrentOperator() == gfxContext::OPERATOR_OVER;
     }
 
     /**
      * Checks the current state to determine if an intermediate surface would
      * be necessary to complete a drawing operation. Does not check the
      * condition pertaining to global alpha and patterns since that does not
      * pertain to all drawing operations.
      */
@@ -1032,19 +1030,17 @@ nsCanvasRenderingContext2D::Redraw()
         return NS_OK;
     mIsEntireFrameInvalid = PR_TRUE;
 
     if (!mCanvasElement) {
         NS_ASSERTION(mDocShell, "Redraw with no canvas element or docshell!");
         return NS_OK;
     }
 
-#ifdef MOZ_SVG
     nsSVGEffects::InvalidateDirectRenderingObservers(HTMLCanvasElement());
-#endif
 
     HTMLCanvasElement()->InvalidateCanvasContent(nsnull);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::Redraw(const gfxRect& r)
@@ -1059,19 +1055,17 @@ nsCanvasRenderingContext2D::Redraw(const
         return Redraw();
     }
 
     if (!mCanvasElement) {
         NS_ASSERTION(mDocShell, "Redraw with no canvas element or docshell!");
         return NS_OK;
     }
 
-#ifdef MOZ_SVG
     nsSVGEffects::InvalidateDirectRenderingObservers(HTMLCanvasElement());
-#endif
 
     HTMLCanvasElement()->InvalidateCanvasContent(&r);
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::RedrawUser(const gfxRect& r)
@@ -1425,17 +1419,17 @@ nsCanvasRenderingContext2D::Transform(fl
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::SetTransform(float m11, float m12, float m21, float m22, float dx, float dy)
 {
     if (!FloatValidate(m11,m12,m21,m22,dx,dy))
-        return NS_ERROR_DOM_SYNTAX_ERR;
+        return NS_OK;
 
     gfxMatrix matrix(m11, m12, m21, m22, dx, dy);
     mThebes->SetMatrix(matrix);
 
     return NS_OK;
 }
 
 //
@@ -2092,31 +2086,31 @@ nsCanvasRenderingContext2D::QuadraticCur
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::BezierCurveTo(float cp1x, float cp1y,
                                           float cp2x, float cp2y,
                                           float x, float y)
 {
     if (!FloatValidate(cp1x,cp1y,cp2x,cp2y,x,y))
-        return NS_ERROR_DOM_SYNTAX_ERR;
+        return NS_OK;
 
     mHasPath = PR_TRUE;
     mThebes->CurveTo(gfxPoint(cp1x, cp1y),
                      gfxPoint(cp2x, cp2y),
                      gfxPoint(x, y));
 
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsCanvasRenderingContext2D::ArcTo(float x1, float y1, float x2, float y2, float radius)
 {
     if (!FloatValidate(x1,y1,x2,y2,radius))
-        return NS_ERROR_DOM_SYNTAX_ERR;
+        return NS_OK;
 
     if (radius < 0)
         return NS_ERROR_DOM_INDEX_SIZE_ERR;
 
     mHasPath = PR_TRUE;
 
     gfxPoint p0 = mThebes->CurrentPoint();
 
--- a/content/canvas/test/Makefile.in
+++ b/content/canvas/test/Makefile.in
@@ -75,16 +75,17 @@ include $(topsrcdir)/config/rules.mk
 	test_2d.composite.image.destination-atop.html \
 	test_2d.composite.image.destination-in.html \
 	test_2d.composite.image.source-in.html \
 	test_2d.composite.image.source-out.html \
 	test_2d.composite.uncovered.image.destination-in.html \
 	test_2d.composite.uncovered.image.source-in.html \
 	test_2d.composite.uncovered.image.source-out.html \
 	test_toDataURL_lowercase_ascii.html \
+	test_toDataURL_parameters.html \
 	test_mozGetAsFile.html \
 	test_canvas_strokeStyle_getter.html \
 	test_bug613794.html \
 	test_drawImage_edge_cases.html \
 	$(NULL)
 
 ifneq (1_Linux,$(MOZ_SUITE)_$(OS_ARCH))
 # This test fails in Suite on Linux for some reason, disable it there
--- a/content/canvas/test/test_canvas.html
+++ b/content/canvas/test/test_canvas.html
@@ -11875,17 +11875,17 @@ ctx.lineTo(0, 50);
 ctx.fillStyle = '#0f0';
 ctx.fill();
 isPixel(ctx, 50,25, 0,255,0,255, 0);
 isPixel(ctx, 90,45, 0,255,0,255, 0);
 
 } catch (e) {
     _thrown_outer = true;
 }
-todo(!_thrown_outer, 'should not throw exception');
+ok(!_thrown_outer, 'should not throw exception');
 
 
 }
 </script>
 
 <!-- [[[ test_2d.path.arcTo.scale.html ]]] -->
 
 <p>Canvas test: 2d.path.arcTo.scale</p>
@@ -12388,17 +12388,17 @@ ctx.lineTo(0, 50);
 ctx.fillStyle = '#0f0';
 ctx.fill();
 isPixel(ctx, 50,25, 0,255,0,255, 0);
 isPixel(ctx, 90,45, 0,255,0,255, 0);
 
 } catch (e) {
     _thrown_outer = true;
 }
-todo(!_thrown_outer, 'should not throw exception');
+ok(!_thrown_outer, 'should not throw exception');
 
 
 }
 </script>
 
 <!-- [[[ test_2d.path.bezierCurveTo.scaled.html ]]] -->
 
 <p>Canvas test: 2d.path.bezierCurveTo.scaled</p>
@@ -18990,17 +18990,17 @@ ctx.setTransform(0, 0, 0, 0, Infinity, I
 ctx.fillStyle = '#0f0';
 ctx.fillRect(-100, -10, 100, 50);
 
 isPixel(ctx, 50,25, 0,255,0,255, 0);
 
 } catch (e) {
     _thrown_outer = true;
 }
-todo(!_thrown_outer, 'should not throw exception');
+ok(!_thrown_outer, 'should not throw exception');
 
 
 }
 </script>
 
 <!-- [[[ test_2d.transformation.setTransform.skewed.html ]]] -->
 
 <p>Canvas test: 2d.transformation.setTransform.skewed</p>
@@ -19532,31 +19532,33 @@ function test_bug397524() {
 <canvas id="c614" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
 <script>
 function test_bug405982() {
 
 var canvas = document.getElementById('c614');
 var ctx = canvas.getContext('2d');
 netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
 
+var _threw = false;
 try {
   var data = canvas.toDataURL('image/png', 'quality=100');
-  ok(false, "Should have thrown an exception for invalid args to png encoder");
 }
 catch (e) {
-  is(e.result, Components.results.NS_ERROR_INVALID_ARG, "Exception was wrong for png encoder");
-}
-
+  _threw = true;
+}
+ok(!_threw, "Should not throw an exception for invalid args to png encoder");
+
+_threw = false;
 try {
   var data = canvas.toDataURL('image/jpeg', 'foobar=true');
-  ok(false, "Should have thrown an exception for invalid args to jpeg encoder");
 }
 catch (e) {
-  is(e.result, Components.results.NS_ERROR_INVALID_ARG, "Exception was wrong for jpeg encoder");
-}
+  _threw = true;
+}
+ok(!_threw, "Should not throw an exception for invalid args to jpeg encoder");
 
 }
 </script>
 <!-- [[[ test_context.arguments.extra.html ]]] -->
 
 <p>Canvas test: context.arguments.extra</p>
 <canvas id="c615" width="100" height="50"><p class="fallback">FAIL (fallback content)</p></canvas>
 <script>
@@ -20756,17 +20758,17 @@ var _thrown_outer = false;
 try {
 
 var data = canvas.toDataURL('image/png', 'another argument that should not raise an exception');
 ok(/^data:image\/png[;,]/.test(data), "data =~ /^data:image\\/png[;,]/");
 
 } catch (e) {
     _thrown_outer = true;
 }
-todo(!_thrown_outer, 'should not throw exception');
+ok(!_thrown_outer, 'should not throw exception');
 
 
 }
 </script>
 
 <!-- [[[ test_toDataURL.arguments.2.html ]]] -->
 
 <p>Canvas test: toDataURL.arguments.2 - bug 401795</p>
@@ -20783,17 +20785,17 @@ var _thrown_outer = false;
 try {
 
 var data = canvas.toDataURL('image/png', 'another argument that should not raise an exception', 'and another');
 ok(/^data:image\/png[;,]/.test(data), "data =~ /^data:image\\/png[;,]/");
 
 } catch (e) {
     _thrown_outer = true;
 }
-todo(!_thrown_outer, 'should not throw exception');
+ok(!_thrown_outer, 'should not throw exception');
 
 
 }
 </script>
 
 <!-- [[[ test_toDataURL.arguments.3.html ]]] -->
 
 <p>Canvas test: toDataURL.arguments.3 - bug 401795</p>
@@ -20811,17 +20813,17 @@ try {
 
 // More arguments that should not raise exceptions
 var data = canvas.toDataURL('image/png', null, null, null);
 ok(/^data:image\/png[;,]/.test(data), "data =~ /^data:image\\/png[;,]/");
 
 } catch (e) {
     _thrown_outer = true;
 }
-todo(!_thrown_outer, 'should not throw exception');
+ok(!_thrown_outer, 'should not throw exception');
 
 
 }
 </script>
 
 <!-- [[[ test_toDataURL.complexcolours.html ]]] -->
 
 <p>Canvas test: toDataURL.complexcolours</p>
@@ -21405,16 +21407,21 @@ function runTests() {
  
  //test_2d_path_rect_zero_6();	// This test is bogus according to the spec; see bug 407107
 
  // These tests are bogus according to the spec: shadows should not be 
  // drawn if shadowBlur, shadowOffsetX, and shadowOffsetY are all zero, whic
  // they are in these tests
  //test_2d_shadow_composite_3();
  //test_2d_shadow_composite_4();
+ // Shadows should not be drawn if the operator is not source-over (the spec doesn't
+ // say this yet, but it should be changed). These tests assume shadows will
+ // be drawn with operators other than source-over:
+ //test_2d_shadow_composite_1();
+ //test_2d_shadow_composite_2();
  try {
   test_2d_canvas_readonly();
  } catch (e) {
   ok(false, "unexpected exception thrown in: test_2d_canvas_readonly");
  }
  try {
   test_2d_canvas_reference();
  } catch (e) {
@@ -23791,26 +23798,16 @@ function runTests() {
   ok(false, "unexpected exception thrown in: test_2d_shadow_clip_2");
  }
  try {
   test_2d_shadow_clip_3();
  } catch (e) {
   ok(false, "unexpected exception thrown in: test_2d_shadow_clip_3");
  }
  try {
-  test_2d_shadow_composite_1();
- } catch (e) {
-  ok(false, "unexpected exception thrown in: test_2d_shadow_composite_1");
- }
- try {
-  test_2d_shadow_composite_2();
- } catch (e) {
-  ok(false, "unexpected exception thrown in: test_2d_shadow_composite_2");
- }
- try {
   test_2d_shadow_gradient_alpha();
  } catch (e) {
   ok(false, "unexpected exception thrown in: test_2d_shadow_gradient_alpha");
  }
  try {
   test_2d_shadow_gradient_basic();
  } catch (e) {
   ok(false, "unexpected exception thrown in: test_2d_shadow_gradient_basic");
new file mode 100644
--- /dev/null
+++ b/content/canvas/test/test_toDataURL_parameters.html
@@ -0,0 +1,55 @@
+<!DOCTYPE HTML>
+<title>Canvas test: toDataURL parameters (Bug 564388)</title>
+<script src="/MochiKit/MochiKit.js"></script>
+<script src="/tests/SimpleTest/SimpleTest.js"></script>
+<link rel="stylesheet" href="/tests/SimpleTest/test.css">
+<body>
+<p>
+This test covers the JPEG quality parameter. If (when) the HTML5 spec changes the
+allowed parameters for ToDataURL, new tests should go here.
+</p>
+<canvas id="c" width="100" height="100"><p class="fallback">FAIL (fallback content)</p></canvas>
+<script>
+var canvas = document.getElementById('c');
+var ctx = canvas.getContext("2d");
+
+ctx.strokeStyle = '#FF0000';
+ctx.fillStyle = '#00FF00';
+ctx.fillRect(0, 0, 100, 100);
+ctx.beginPath();
+ctx.moveTo(10, 10);
+ctx.lineTo(90, 90);
+ctx.stroke();
+
+var pngData = canvas.toDataURL('image/png');
+var pngQuality = canvas.toDataURL('image/png', 0.1);
+is(pngQuality, pngData, "Quality is not supported for PNG images");
+
+var data = canvas.toDataURL('image/jpeg');
+if (data.match(/^data:image\/jpeg[;,]/)) {
+    // Test the JPEG quality parameter
+    
+    var fullQuality = canvas.toDataURL('image/jpeg', 1.0);
+    var lowQuality = canvas.toDataURL('image/jpeg', 0.1);
+    isnot(lowQuality, fullQuality, "A low quality (0.1) should differ from high quality (1.0)");
+    
+    var medQuality = canvas.toDataURL('image/jpeg', 0.5);
+    isnot(medQuality, fullQuality, "A medium quality (0.5) should differ from high (1.0)");
+    isnot(medQuality, lowQuality, "A medium quality (0.5) should differ from low (0.5)");
+    
+    var tooHigh = canvas.toDataURL('image/jpeg', 2.0);
+    is(tooHigh, data, "Quality above 1.0 is treated as unspecified");
+    
+    var tooLow = canvas.toDataURL('image/jpeg', -1.0);
+    is(tooLow, data, "Quality below 0.0 is treated as unspecified");
+    
+    var lowQualityExtra = canvas.toDataURL('image/jpeg', 0.1, 'foo', 'bar', null);
+    is(lowQualityExtra, lowQuality, "Quality applies even if extra arguments are present");
+    
+    var lowQualityUppercase = canvas.toDataURL('IMAGE/JPEG', 0.1);
+    is(lowQualityUppercase, lowQuality, "Quality applies to image/jpeg regardless of case");
+    
+    var lowQualityString = canvas.toDataURL('image/jpeg', '0.1');
+    isnot(lowQualityString, lowQuality, "Quality must be a number (should not be a string)");
+}
+</script>
--- a/content/canvas/test/webgl/failing_tests_mac.txt
+++ b/content/canvas/test/webgl/failing_tests_mac.txt
@@ -1,9 +1,8 @@
-conformance/canvas-test.html
 conformance/gl-getshadersource.html
 conformance/gl-object-get-calls.html
 conformance/texture-npot.html
 conformance/glsl-conformance.html
 conformance/invalid-passed-params.html
 conformance/object-deletion-behaviour.html
 conformance/read-pixels-test.html
 conformance/tex-input-validation.html
--- a/content/canvas/test/webgl/test_webgl_conformance_test_suite.html
+++ b/content/canvas/test/webgl/test_webgl_conformance_test_suite.html
@@ -360,20 +360,16 @@ function start() {
     failingTestsFilename = 'failing_tests_mac.txt';
 
   var testsExpectedToFail = loadTextFileSynchronous(failingTestsFilename)
                             .replace(/\r/g, '') // convert to unix line breaks
                             .split('\n');
 
   var testsToIgnore = [];
 
-  // canvas-test.html is currently failing on Windows XP test slaves
-  if (kIsWindows && !kIsWindowsVistaOrHigher)
-      testsToIgnore.push('conformance/canvas-test.html');
-
   var testsSuccessful = [];
 
   runTestSuite();
 }
 
 </script>
 </head>
 <body onload="start()">
--- a/content/events/public/nsIPrivateDOMEvent.h
+++ b/content/events/public/nsIPrivateDOMEvent.h
@@ -92,22 +92,20 @@ NS_NewDOMPopupBlockedEvent(nsIDOMEvent**
 nsresult
 NS_NewDOMDeviceOrientationEvent(nsIDOMEvent** aResult, nsPresContext* aPresContext, nsEvent* aEvent);
 nsresult
 NS_NewDOMTextEvent(nsIDOMEvent** aResult, nsPresContext* aPresContext, class nsTextEvent* aEvent);
 nsresult
 NS_NewDOMBeforeUnloadEvent(nsIDOMEvent** aResult, nsPresContext* aPresContext, nsEvent* aEvent);
 nsresult
 NS_NewDOMPageTransitionEvent(nsIDOMEvent** aResult, nsPresContext* aPresContext, nsEvent* aEvent);
-#ifdef MOZ_SVG
 nsresult
 NS_NewDOMSVGEvent(nsIDOMEvent** aResult, nsPresContext* aPresContext, class nsEvent* aEvent);
 nsresult
 NS_NewDOMSVGZoomEvent(nsIDOMEvent** aResult, nsPresContext* aPresContext, class nsGUIEvent* aEvent);
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
 nsresult
 NS_NewDOMTimeEvent(nsIDOMEvent** aResult, nsPresContext* aPresContext, class nsEvent* aEvent);
 #endif // MOZ_SMIL
 nsresult
 NS_NewDOMXULCommandEvent(nsIDOMEvent** aResult, nsPresContext* aPresContext, class nsInputEvent* aEvent);
 nsresult
 NS_NewDOMCommandEvent(nsIDOMEvent** aInstancePtrResult, nsPresContext* aPresContext, nsCommandEvent* aEvent);
--- a/content/events/src/nsDOMEvent.cpp
+++ b/content/events/src/nsDOMEvent.cpp
@@ -52,16 +52,19 @@
 #include "prmem.h"
 #include "nsGkAtoms.h"
 #include "nsMutationEvent.h"
 #include "nsContentUtils.h"
 #include "nsIURI.h"
 #include "nsIScriptSecurityManager.h"
 #include "nsIScriptError.h"
 #include "nsDOMPopStateEvent.h"
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 
 static const char* const sEventNames[] = {
   "mousedown", "mouseup", "click", "dblclick", "mouseover",
   "mouseout", "MozMouseHittest", "mousemove", "contextmenu", "keydown", "keyup", "keypress",
   "focus", "blur", "load", "popstate", "beforescriptexecute",
   "afterscriptexecute", "beforeunload", "unload",
   "hashchange", "readystatechange", "abort", "error",
   "submit", "reset", "change", "select", "input", "invalid", "text",
@@ -71,20 +74,18 @@ static const char* const sEventNames[] =
   "drag", "dragend", "dragstart", "dragleave", "drop", "resize",
   "scroll", "overflow", "underflow", "overflowchanged",
   "DOMSubtreeModified", "DOMNodeInserted", "DOMNodeRemoved", 
   "DOMNodeRemovedFromDocument", "DOMNodeInsertedIntoDocument",
   "DOMAttrModified", "DOMCharacterDataModified",
   "DOMActivate", "DOMFocusIn", "DOMFocusOut",
   "pageshow", "pagehide", "DOMMouseScroll", "MozMousePixelScroll",
   "offline", "online", "copy", "cut", "paste", "open", "message",
-#ifdef MOZ_SVG
   "SVGLoad", "SVGUnload", "SVGAbort", "SVGError", "SVGResize", "SVGScroll",
   "SVGZoom",
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
   "beginEvent", "endEvent", "repeatEvent",
 #endif // MOZ_SMIL
 #ifdef MOZ_MEDIA
   "loadstart", "progress", "suspend", "emptied", "stalled", "play", "pause",
   "loadedmetadata", "loadeddata", "waiting", "playing", "canplay",
   "canplaythrough", "seeking", "seeked", "timeupdate", "ended", "ratechange",
   "durationchange", "volumechange", "MozAudioAvailable",
@@ -769,32 +770,30 @@ NS_METHOD nsDOMEvent::DuplicatePrivateDa
       break;
     }
     case NS_UI_EVENT:
     {
       newEvent = new nsUIEvent(PR_FALSE, msg,
                                static_cast<nsUIEvent*>(mEvent)->detail);
       break;
     }
-#ifdef MOZ_SVG
     case NS_SVG_EVENT:
     {
       newEvent = new nsEvent(PR_FALSE, msg);
       NS_ENSURE_TRUE(newEvent, NS_ERROR_OUT_OF_MEMORY);
       newEvent->eventStructType = NS_SVG_EVENT;
       break;
     }
     case NS_SVGZOOM_EVENT:
     {
       newEvent = new nsGUIEvent(PR_FALSE, msg, nsnull);
       NS_ENSURE_TRUE(newEvent, NS_ERROR_OUT_OF_MEMORY);
       newEvent->eventStructType = NS_SVGZOOM_EVENT;
       break;
     }
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
     case NS_SMIL_TIME_EVENT:
     {
       newEvent = new nsUIEvent(PR_FALSE, msg, 0);
       NS_ENSURE_TRUE(newEvent, NS_ERROR_OUT_OF_MEMORY);
       newEvent->eventStructType = NS_SMIL_TIME_EVENT;
       break;
     }
@@ -1083,18 +1082,17 @@ nsDOMEvent::GetEventPopupControlState(ns
 // static
 void
 nsDOMEvent::PopupAllowedEventsChanged()
 {
   if (sPopupAllowedEvents) {
     nsMemory::Free(sPopupAllowedEvents);
   }
 
-  nsAdoptingCString str =
-    nsContentUtils::GetCharPref("dom.popup_allowed_events");
+  nsAdoptingCString str = Preferences::GetCString("dom.popup_allowed_events");
 
   // We'll want to do this even if str is empty to avoid looking up
   // this pref all the time if it's not set.
   sPopupAllowedEvents = ToNewCString(str);
 }
 
 // static
 void
@@ -1260,32 +1258,30 @@ const char* nsDOMEvent::GetEventName(PRU
   case NS_CUT:
     return sEventNames[eDOMEvents_cut];
   case NS_PASTE:
     return sEventNames[eDOMEvents_paste];
   case NS_OPEN:
     return sEventNames[eDOMEvents_open];
   case NS_MESSAGE:
     return sEventNames[eDOMEvents_message];
-#ifdef MOZ_SVG
   case NS_SVG_LOAD:
     return sEventNames[eDOMEvents_SVGLoad];
   case NS_SVG_UNLOAD:
     return sEventNames[eDOMEvents_SVGUnload];
   case NS_SVG_ABORT:
     return sEventNames[eDOMEvents_SVGAbort];
   case NS_SVG_ERROR:
     return sEventNames[eDOMEvents_SVGError];
   case NS_SVG_RESIZE:
     return sEventNames[eDOMEvents_SVGResize];
   case NS_SVG_SCROLL:
     return sEventNames[eDOMEvents_SVGScroll];
   case NS_SVG_ZOOM:
     return sEventNames[eDOMEvents_SVGZoom];
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
   case NS_SMIL_BEGIN:
     return sEventNames[eDOMEvents_beginEvent];
   case NS_SMIL_END:
     return sEventNames[eDOMEvents_endEvent];
   case NS_SMIL_REPEAT:
     return sEventNames[eDOMEvents_repeatEvent];
 #endif // MOZ_SMIL
--- a/content/events/src/nsDOMEvent.h
+++ b/content/events/src/nsDOMEvent.h
@@ -133,25 +133,23 @@ public:
     eDOMEvents_MozMousePixelScroll,
     eDOMEvents_offline,
     eDOMEvents_online,
     eDOMEvents_copy,
     eDOMEvents_cut,
     eDOMEvents_paste,
     eDOMEvents_open,
     eDOMEvents_message,
-#ifdef MOZ_SVG
     eDOMEvents_SVGLoad,
     eDOMEvents_SVGUnload,
     eDOMEvents_SVGAbort,
     eDOMEvents_SVGError,
     eDOMEvents_SVGResize,
     eDOMEvents_SVGScroll,
     eDOMEvents_SVGZoom,
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
     eDOMEvents_beginEvent,
     eDOMEvents_endEvent,
     eDOMEvents_repeatEvent,
 #endif // MOZ_SMIL
 #ifdef MOZ_MEDIA
     eDOMEvents_loadstart,
     eDOMEvents_progress,
--- a/content/events/src/nsDOMTouchEvent.cpp
+++ b/content/events/src/nsDOMTouchEvent.cpp
@@ -36,16 +36,19 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsDOMTouchEvent.h"
 #include "nsGUIEvent.h"
 #include "nsDOMClassInfoID.h"
 #include "nsIClassInfo.h"
 #include "nsIXPCScriptable.h"
 #include "nsContentUtils.h"
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 
 DOMCI_DATA(Touch, nsDOMTouch)
 
 NS_IMPL_CYCLE_COLLECTION_1(nsDOMTouch, mTarget)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsDOMTouch)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMTouch)
   NS_INTERFACE_MAP_ENTRY(nsIDOMTouch)
@@ -318,17 +321,17 @@ nsDOMTouchEvent::GetShiftKey(PRBool* aSh
 
 PRBool
 nsDOMTouchEvent::PrefEnabled()
 {
   static PRBool sDidCheckPref = PR_FALSE;
   static PRBool sPrefValue = PR_FALSE;
   if (!sDidCheckPref) {
     sDidCheckPref = PR_TRUE;
-    sPrefValue = nsContentUtils::GetBoolPref("dom.w3c_touch_events.enabled", PR_FALSE);
+    sPrefValue = Preferences::GetBool("dom.w3c_touch_events.enabled", PR_FALSE);
     if (sPrefValue) {
       nsContentUtils::InitializeTouchEventTable();
     }
   }
   return sPrefValue;
 }
 
 nsresult
--- a/content/events/src/nsEventDispatcher.cpp
+++ b/content/events/src/nsEventDispatcher.cpp
@@ -750,24 +750,22 @@ nsEventDispatcher::CreateEvent(nsPresCon
       return NS_NewDOMMouseScrollEvent(aDOMEvent, aPresContext,
                                  static_cast<nsInputEvent*>(aEvent));
     case NS_DRAG_EVENT:
       return NS_NewDOMDragEvent(aDOMEvent, aPresContext,
                                  static_cast<nsDragEvent*>(aEvent));
     case NS_TEXT_EVENT:
       return NS_NewDOMTextEvent(aDOMEvent, aPresContext,
                                 static_cast<nsTextEvent*>(aEvent));
-#ifdef MOZ_SVG
     case NS_SVG_EVENT:
       return NS_NewDOMSVGEvent(aDOMEvent, aPresContext,
                                aEvent);
     case NS_SVGZOOM_EVENT:
       return NS_NewDOMSVGZoomEvent(aDOMEvent, aPresContext,
                                    static_cast<nsGUIEvent*>(aEvent));
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
     case NS_SMIL_TIME_EVENT:
       return NS_NewDOMTimeEvent(aDOMEvent, aPresContext, aEvent);
 #endif // MOZ_SMIL
 
     case NS_COMMAND_EVENT:
       return NS_NewDOMCommandEvent(aDOMEvent, aPresContext,
                                    static_cast<nsCommandEvent*>(aEvent));
@@ -817,24 +815,22 @@ nsEventDispatcher::CreateEvent(nsPresCon
     return NS_NewDOMDeviceOrientationEvent(aDOMEvent, aPresContext, nsnull);
   if (aEventType.LowerCaseEqualsLiteral("uievent") ||
       aEventType.LowerCaseEqualsLiteral("uievents"))
     return NS_NewDOMUIEvent(aDOMEvent, aPresContext, nsnull);
   if (aEventType.LowerCaseEqualsLiteral("event") ||
       aEventType.LowerCaseEqualsLiteral("events") ||
       aEventType.LowerCaseEqualsLiteral("htmlevents"))
     return NS_NewDOMEvent(aDOMEvent, aPresContext, nsnull);
-#ifdef MOZ_SVG
   if (aEventType.LowerCaseEqualsLiteral("svgevent") ||
       aEventType.LowerCaseEqualsLiteral("svgevents"))
     return NS_NewDOMSVGEvent(aDOMEvent, aPresContext, nsnull);
   if (aEventType.LowerCaseEqualsLiteral("svgzoomevent") ||
       aEventType.LowerCaseEqualsLiteral("svgzoomevents"))
     return NS_NewDOMSVGZoomEvent(aDOMEvent, aPresContext, nsnull);
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
   if (aEventType.LowerCaseEqualsLiteral("timeevent") ||
       aEventType.LowerCaseEqualsLiteral("timeevents"))
     return NS_NewDOMTimeEvent(aDOMEvent, aPresContext, nsnull);
 #endif // MOZ_SMIL
   if (aEventType.LowerCaseEqualsLiteral("xulcommandevent") ||
       aEventType.LowerCaseEqualsLiteral("xulcommandevents"))
     return NS_NewDOMXULCommandEvent(aDOMEvent, aPresContext, nsnull);
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -48,19 +48,17 @@
 #include "nsIDOMKeyListener.h"
 #include "nsIDOMFocusListener.h"
 #include "nsIDOMFormListener.h"
 #include "nsIDOMLoadListener.h"
 #include "nsIDOMTextListener.h"
 #include "nsIDOMCompositionListener.h"
 #include "nsIDOMUIListener.h"
 #include "nsITextControlFrame.h"
-#ifdef MOZ_SVG
 #include "nsGkAtoms.h"
-#endif // MOZ_SVG
 #include "nsPIDOMWindow.h"
 #include "nsIPrivateDOMEvent.h"
 #include "nsIJSEventListener.h"
 #include "prmem.h"
 #include "nsIScriptGlobalObject.h"
 #include "nsIScriptRuntime.h"
 #include "nsLayoutUtils.h"
 #include "nsINameSpaceManager.h"
@@ -77,17 +75,16 @@
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsMutationEvent.h"
 #include "nsIXPConnect.h"
 #include "nsDOMCID.h"
 #include "nsIScriptObjectOwner.h" // for nsIScriptEventHandlerOwner
 #include "nsFocusManager.h"
 #include "nsIDOMElement.h"
-#include "nsIDOMNSDocument.h"
 #include "nsContentUtils.h"
 #include "nsJSUtils.h"
 #include "nsIDOMEventGroup.h"
 #include "nsContentCID.h"
 #include "nsEventDispatcher.h"
 #include "nsDOMJSUtils.h"
 #include "nsDOMScriptObjectHolder.h"
 #include "nsDataHashtable.h"
@@ -1001,32 +998,30 @@ nsEventListenerManager::CompileEventHand
     // XXX I don't like that we have to reference content
     // from here. The alternative is to store the event handler
     // string on the JS object itself.
     nsCOMPtr<nsIContent> content = do_QueryInterface(aObject);
     NS_ASSERTION(content, "only content should have event handler attributes");
     if (content) {
       nsAutoString handlerBody;
       nsIAtom* attrName = aName;
-#ifdef MOZ_SVG
       if (aName == nsGkAtoms::onSVGLoad)
         attrName = nsGkAtoms::onload;
       else if (aName == nsGkAtoms::onSVGUnload)
         attrName = nsGkAtoms::onunload;
       else if (aName == nsGkAtoms::onSVGAbort)
         attrName = nsGkAtoms::onabort;
       else if (aName == nsGkAtoms::onSVGError)
         attrName = nsGkAtoms::onerror;
       else if (aName == nsGkAtoms::onSVGResize)
         attrName = nsGkAtoms::onresize;
       else if (aName == nsGkAtoms::onSVGScroll)
         attrName = nsGkAtoms::onscroll;
       else if (aName == nsGkAtoms::onSVGZoom)
         attrName = nsGkAtoms::onzoom;
-#endif // MOZ_SVG
 #ifdef MOZ_SMIL
       else if (aName == nsGkAtoms::onbeginEvent)
         attrName = nsGkAtoms::onbegin;
       else if (aName == nsGkAtoms::onrepeatEvent)
         attrName = nsGkAtoms::onrepeat;
       else if (aName == nsGkAtoms::onendEvent)
         attrName = nsGkAtoms::onend;
 #endif // MOZ_SMIL
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -73,35 +73,32 @@
 #include "nsIDOMHTMLAreaElement.h"
 #include "nsIDOMHTMLButtonElement.h"
 #include "nsIDOMHTMLObjectElement.h"
 #include "nsIDOMHTMLImageElement.h"
 #include "nsIDOMHTMLMapElement.h"
 #include "nsIDOMHTMLBodyElement.h"
 #include "nsIDOMXULControlElement.h"
 #include "nsIDOMXULTextboxElement.h"
-#include "nsImageMapUtils.h"
-#include "nsIHTMLDocument.h"
 #include "nsINameSpaceManager.h"
 #include "nsIBaseWindow.h"
 #include "nsIView.h"
 #include "nsIViewManager.h"
 #include "nsISelection.h"
 #include "nsFrameSelection.h"
 #include "nsIPrivateDOMEvent.h"
 #include "nsIDOMWindowInternal.h"
 #include "nsPIDOMWindow.h"
 #include "nsPIWindowRoot.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIEnumerator.h"
 #include "nsIDocShellTreeItem.h"
 #include "nsIDocShellTreeNode.h"
 #include "nsIWebNavigation.h"
 #include "nsIContentViewer.h"
-#include "nsIPrefBranch2.h"
 #ifdef MOZ_XUL
 #include "nsXULPopupManager.h"
 #endif
 #include "nsFrameManager.h"
 
 #include "nsIServiceManager.h"
 #include "nsIScriptSecurityManager.h"
 
@@ -148,21 +145,25 @@
 #include "nsContentAreaDragDrop.h"
 #ifdef MOZ_XUL
 #include "nsTreeBodyFrame.h"
 #endif
 #include "nsIController.h"
 #include "nsICommandParams.h"
 #include "mozilla/Services.h"
 #include "mozAutoDocUpdate.h"
+#include "nsHTMLLabelElement.h"
+
+#include "mozilla/Preferences.h"
 
 #ifdef XP_MACOSX
 #import <ApplicationServices/ApplicationServices.h>
 #endif
 
+using namespace mozilla;
 using namespace mozilla::dom;
 
 //#define DEBUG_DOCSHELL_FOCUS
 
 #define NS_USER_INTERACTION_INTERVAL 5000 // ms
 
 static NS_DEFINE_CID(kFrameTraversalCID, NS_FRAMETRAVERSAL_CID);
 
@@ -320,31 +321,31 @@ GetDocumentFromWindow(nsIDOMWindow *aWin
   }
 
   return doc;
 }
 
 static PRInt32
 GetAccessModifierMaskFromPref(PRInt32 aItemType)
 {
-  PRInt32 accessKey = nsContentUtils::GetIntPref("ui.key.generalAccessKey", -1);
+  PRInt32 accessKey = Preferences::GetInt("ui.key.generalAccessKey", -1);
   switch (accessKey) {
     case -1:                             break; // use the individual prefs
     case nsIDOMKeyEvent::DOM_VK_SHIFT:   return NS_MODIFIER_SHIFT;
     case nsIDOMKeyEvent::DOM_VK_CONTROL: return NS_MODIFIER_CONTROL;
     case nsIDOMKeyEvent::DOM_VK_ALT:     return NS_MODIFIER_ALT;
     case nsIDOMKeyEvent::DOM_VK_META:    return NS_MODIFIER_META;
     default:                             return 0;
   }
 
   switch (aItemType) {
   case nsIDocShellTreeItem::typeChrome:
-    return nsContentUtils::GetIntPref("ui.key.chromeAccess", 0);
+    return Preferences::GetInt("ui.key.chromeAccess", 0);
   case nsIDocShellTreeItem::typeContent:
-    return nsContentUtils::GetIntPref("ui.key.contentAccess", 0);
+    return Preferences::GetInt("ui.key.contentAccess", 0);
   default:
     return 0;
   }
 }
 
 static void
 GetBasePrefKeyForMouseWheel(nsMouseScrollEvent* aEvent, nsACString& aPref)
 {
@@ -579,17 +580,17 @@ nsMouseWheelTransaction::Shutdown()
   NS_IF_RELEASE(sTimer);
 }
 
 void
 nsMouseWheelTransaction::OnFailToScrollTarget()
 {
   NS_PRECONDITION(sTargetFrame, "We don't have mouse scrolling transaction");
 
-  if (nsContentUtils::GetBoolPref("test.mousescroll", PR_FALSE)) {
+  if (Preferences::GetBool("test.mousescroll", PR_FALSE)) {
     // This event is used for automated tests, see bug 442774.
     nsContentUtils::DispatchTrustedEvent(
                       sTargetFrame->GetContent()->GetOwnerDoc(),
                       sTargetFrame->GetContent(),
                       NS_LITERAL_STRING("MozMouseScrollFailed"),
                       PR_TRUE, PR_TRUE);
   }
   // The target frame might be destroyed in the event handler, at that time,
@@ -607,17 +608,17 @@ nsMouseWheelTransaction::OnTimeout(nsITi
     return;
   }
   // Store the sTargetFrame, the variable becomes null in EndTransaction.
   nsIFrame* frame = sTargetFrame;
   // We need to finish current transaction before DOM event firing. Because
   // the next DOM event might create strange situation for us.
   EndTransaction();
 
-  if (nsContentUtils::GetBoolPref("test.mousescroll", PR_FALSE)) {
+  if (Preferences::GetBool("test.mousescroll", PR_FALSE)) {
     // This event is used for automated tests, see bug 442774.
     nsContentUtils::DispatchTrustedEvent(
                       frame->GetContent()->GetOwnerDoc(),
                       frame->GetContent(),
                       NS_LITERAL_STRING("MozMouseScrollTransactionTimeout"),
                       PR_TRUE, PR_TRUE);
   }
 }
@@ -646,25 +647,23 @@ nsMouseWheelTransaction::GetScreenPoint(
   NS_ASSERTION(aEvent, "aEvent is null");
   NS_ASSERTION(aEvent->widget, "aEvent-widget is null");
   return aEvent->refPoint + aEvent->widget->WidgetToScreenOffset();
 }
 
 PRUint32
 nsMouseWheelTransaction::GetTimeoutTime()
 {
-  return (PRUint32)
-    nsContentUtils::GetIntPref("mousewheel.transaction.timeout", 1500);
+  return Preferences::GetUint("mousewheel.transaction.timeout", 1500);
 }
 
 PRUint32
 nsMouseWheelTransaction::GetIgnoreMoveDelayTime()
 {
-  return (PRUint32)
-    nsContentUtils::GetIntPref("mousewheel.transaction.ignoremovedelay", 100);
+  return Preferences::GetUint("mousewheel.transaction.ignoremovedelay", 100);
 }
 
 PRBool
 nsMouseWheelTransaction::IsAccelerationEnabled()
 {
   return GetAccelerationStart() >= 0 && GetAccelerationFactor() > 0;
 }
 
@@ -703,23 +702,23 @@ nsMouseWheelTransaction::ComputeAccelera
 
   return PRInt32(NS_round(aDelta * sScrollSeriesCounter *
                           (double)aFactor / 10));
 }
 
 PRInt32
 nsMouseWheelTransaction::GetAccelerationStart()
 {
-  return nsContentUtils::GetIntPref("mousewheel.acceleration.start", -1);
+  return Preferences::GetInt("mousewheel.acceleration.start", -1);
 }
 
 PRInt32
 nsMouseWheelTransaction::GetAccelerationFactor()
 {
-  return nsContentUtils::GetIntPref("mousewheel.acceleration.factor", -1);
+  return Preferences::GetInt("mousewheel.acceleration.factor", -1);
 }
 
 PRInt32
 nsMouseWheelTransaction::OverrideSystemScrollSpeed(PRInt32 aScrollLines,
                                                    PRBool aIsHorizontal)
 {
   NS_PRECONDITION(sTargetFrame, "We don't have mouse scrolling transaction");
 
@@ -823,64 +822,64 @@ nsEventStateManager::UpdateUserActivityT
   if (gUserInteractionTimer) {
     gUserInteractionTimer->InitWithCallback(gUserInteractionTimerCallback,
                                             NS_USER_INTERACTION_INTERVAL,
                                             nsITimer::TYPE_ONE_SHOT);
   }
   return NS_OK;
 }
 
+static const char* kObservedPrefs[] = {
+  "accessibility.accesskeycausesactivation",
+  "nglayout.events.dispatchLeftClickOnly",
+  "ui.key.generalAccessKey",
+  "ui.key.chromeAccess",
+  "ui.key.contentAccess",
+  "ui.click_hold_context_menus",
+#if 0
+  "mousewheel.withaltkey.action",
+  "mousewheel.withaltkey.numlines",
+  "mousewheel.withaltkey.sysnumlines",
+  "mousewheel.withcontrolkey.action",
+  "mousewheel.withcontrolkey.numlines",
+  "mousewheel.withcontrolkey.sysnumlines",
+  "mousewheel.withnokey.action",
+  "mousewheel.withnokey.numlines",
+  "mousewheel.withnokey.sysnumlines",
+  "mousewheel.withshiftkey.action",
+  "mousewheel.withshiftkey.numlines",
+  "mousewheel.withshiftkey.sysnumlines",
+#endif
+  "dom.popup_allowed_events",
+  nsnull
+};
+
 nsresult
 nsEventStateManager::Init()
 {
   nsCOMPtr<nsIObserverService> observerService =
     mozilla::services::GetObserverService();
   if (!observerService)
     return NS_ERROR_FAILURE;
 
   observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, PR_TRUE);
 
-  nsIPrefBranch2* prefBranch = nsContentUtils::GetPrefBranch();
-
-  if (prefBranch) {
-    if (sESMInstanceCount == 1) {
-      sLeftClickOnly =
-        nsContentUtils::GetBoolPref("nglayout.events.dispatchLeftClickOnly",
-                                    sLeftClickOnly);
-      sChromeAccessModifier =
-        GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeChrome);
-      sContentAccessModifier =
-        GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeContent);
-    }
-    prefBranch->AddObserver("accessibility.accesskeycausesactivation", this, PR_TRUE);
-    prefBranch->AddObserver("nglayout.events.dispatchLeftClickOnly", this, PR_TRUE);
-    prefBranch->AddObserver("ui.key.generalAccessKey", this, PR_TRUE);
-    prefBranch->AddObserver("ui.key.chromeAccess", this, PR_TRUE);
-    prefBranch->AddObserver("ui.key.contentAccess", this, PR_TRUE);
-    prefBranch->AddObserver("ui.click_hold_context_menus", this, PR_TRUE);
-#if 0
-    prefBranch->AddObserver("mousewheel.withaltkey.action", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withaltkey.numlines", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withaltkey.sysnumlines", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withcontrolkey.action", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withcontrolkey.numlines", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withcontrolkey.sysnumlines", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withnokey.action", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withnokey.numlines", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withnokey.sysnumlines", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withshiftkey.action", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withshiftkey.numlines", this, PR_TRUE);
-    prefBranch->AddObserver("mousewheel.withshiftkey.sysnumlines", this, PR_TRUE);
-#endif
-
-    prefBranch->AddObserver("dom.popup_allowed_events", this, PR_TRUE);
+  if (sESMInstanceCount == 1) {
+    sLeftClickOnly =
+      Preferences::GetBool("nglayout.events.dispatchLeftClickOnly",
+                           sLeftClickOnly);
+    sChromeAccessModifier =
+      GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeChrome);
+    sContentAccessModifier =
+      GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeContent);
   }
+  Preferences::AddWeakObservers(this, kObservedPrefs);
 
   mClickHoldContextMenu =
-    nsContentUtils::GetBoolPref("ui.click_hold_context_menus", PR_FALSE);
+    Preferences::GetBool("ui.click_hold_context_menus", PR_FALSE);
 
   return NS_OK;
 }
 
 nsEventStateManager::~nsEventStateManager()
 {
   if (sActiveESM == this) {
     sActiveESM = nsnull;
@@ -918,43 +917,17 @@ nsEventStateManager::~nsEventStateManage
     }
   }
 
 }
 
 nsresult
 nsEventStateManager::Shutdown()
 {
-  nsIPrefBranch2* prefBranch = nsContentUtils::GetPrefBranch();
-
-  if (prefBranch) {
-    prefBranch->RemoveObserver("accessibility.accesskeycausesactivation", this);
-    prefBranch->RemoveObserver("nglayout.events.dispatchLeftClickOnly", this);
-    prefBranch->RemoveObserver("ui.key.generalAccessKey", this);
-    prefBranch->RemoveObserver("ui.key.chromeAccess", this);
-    prefBranch->RemoveObserver("ui.key.contentAccess", this);
-    prefBranch->RemoveObserver("ui.click_hold_context_menus", this);
-#if 0
-    prefBranch->RemoveObserver("mousewheel.withshiftkey.action", this);
-    prefBranch->RemoveObserver("mousewheel.withshiftkey.numlines", this);
-    prefBranch->RemoveObserver("mousewheel.withshiftkey.sysnumlines", this);
-    prefBranch->RemoveObserver("mousewheel.withcontrolkey.action", this);
-    prefBranch->RemoveObserver("mousewheel.withcontrolkey.numlines", this);
-    prefBranch->RemoveObserver("mousewheel.withcontrolkey.sysnumlines", this);
-    prefBranch->RemoveObserver("mousewheel.withaltkey.action", this);
-    prefBranch->RemoveObserver("mousewheel.withaltkey.numlines", this);
-    prefBranch->RemoveObserver("mousewheel.withaltkey.sysnumlines", this);
-    prefBranch->RemoveObserver("mousewheel.withnokey.action", this);
-    prefBranch->RemoveObserver("mousewheel.withnokey.numlines", this);
-    prefBranch->RemoveObserver("mousewheel.withnokey.sysnumlines", this);
-#endif
-
-    prefBranch->RemoveObserver("dom.popup_allowed_events", this);
-  }
-
+  Preferences::RemoveObservers(this, kObservedPrefs);
   m_haveShutdown = PR_TRUE;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsEventStateManager::Observe(nsISupports *aSubject,
                              const char *aTopic,
                              const PRUnichar *someData)
@@ -963,36 +936,36 @@ nsEventStateManager::Observe(nsISupports
     Shutdown();
   else if (!nsCRT::strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
     if (!someData)
       return NS_OK;
 
     nsDependentString data(someData);
     if (data.EqualsLiteral("accessibility.accesskeycausesactivation")) {
       sKeyCausesActivation =
-        nsContentUtils::GetBoolPref("accessibility.accesskeycausesactivation",
-                                    sKeyCausesActivation);
+        Preferences::GetBool("accessibility.accesskeycausesactivation",
+                             sKeyCausesActivation);
     } else if (data.EqualsLiteral("nglayout.events.dispatchLeftClickOnly")) {
       sLeftClickOnly =
-        nsContentUtils::GetBoolPref("nglayout.events.dispatchLeftClickOnly",
-                                    sLeftClickOnly);
+        Preferences::GetBool("nglayout.events.dispatchLeftClickOnly",
+                             sLeftClickOnly);
     } else if (data.EqualsLiteral("ui.key.generalAccessKey")) {
       sChromeAccessModifier =
         GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeChrome);
       sContentAccessModifier =
         GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeContent);
     } else if (data.EqualsLiteral("ui.key.chromeAccess")) {
       sChromeAccessModifier =
         GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeChrome);
     } else if (data.EqualsLiteral("ui.key.contentAccess")) {
       sContentAccessModifier =
         GetAccessModifierMaskFromPref(nsIDocShellTreeItem::typeContent);
     } else if (data.EqualsLiteral("ui.click_hold_context_menus")) {
       mClickHoldContextMenu =
-        nsContentUtils::GetBoolPref("ui.click_hold_context_menus", PR_FALSE);
+        Preferences::GetBool("ui.click_hold_context_menus", PR_FALSE);
 #if 0
     } else if (data.EqualsLiteral("mousewheel.withaltkey.action")) {
     } else if (data.EqualsLiteral("mousewheel.withaltkey.numlines")) {
     } else if (data.EqualsLiteral("mousewheel.withaltkey.sysnumlines")) {
     } else if (data.EqualsLiteral("mousewheel.withcontrolkey.action")) {
     } else if (data.EqualsLiteral("mousewheel.withcontrolkey.numlines")) {
     } else if (data.EqualsLiteral("mousewheel.withcontrolkey.sysnumlines")) {
     } else if (data.EqualsLiteral("mousewheel.withshiftkey.action")) {
@@ -1715,17 +1688,17 @@ nsEventStateManager::CreateClickHoldTime
     // check for a <menubutton> like bookmarks
     if (mGestureDownContent->Tag() == nsGkAtoms::menubutton)
       return;
   }
 
   mClickHoldTimer = do_CreateInstance("@mozilla.org/timer;1");
   if (mClickHoldTimer) {
     PRInt32 clickHoldDelay =
-      nsContentUtils::GetIntPref("ui.click_hold_context_menus.delay", 500);
+      Preferences::GetInt("ui.click_hold_context_menus.delay", 500);
     mClickHoldTimer->InitWithFuncCallback(sClickHoldCallback, this,
                                           clickHoldDelay,
                                           nsITimer::TYPE_ONE_SHOT);
   }
 } // CreateClickHoldTimer
 
 
 //
@@ -2396,18 +2369,18 @@ nsEventStateManager::GetMarkupDocumentVi
 nsresult
 nsEventStateManager::ChangeTextSize(PRInt32 change)
 {
   nsCOMPtr<nsIMarkupDocumentViewer> mv;
   nsresult rv = GetMarkupDocumentViewer(getter_AddRefs(mv));
   NS_ENSURE_SUCCESS(rv, rv);
 
   float textzoom;
-  float zoomMin = ((float)nsContentUtils::GetIntPref("zoom.minPercent", 50)) / 100;
-  float zoomMax = ((float)nsContentUtils::GetIntPref("zoom.maxPercent", 300)) / 100;
+  float zoomMin = ((float)Preferences::GetInt("zoom.minPercent", 50)) / 100;
+  float zoomMax = ((float)Preferences::GetInt("zoom.maxPercent", 300)) / 100;
   mv->GetTextZoom(&textzoom);
   textzoom += ((float)change) / 10;
   if (textzoom < zoomMin)
     textzoom = zoomMin;
   else if (textzoom > zoomMax)
     textzoom = zoomMax;
   mv->SetTextZoom(textzoom);
 
@@ -2417,18 +2390,18 @@ nsEventStateManager::ChangeTextSize(PRIn
 nsresult
 nsEventStateManager::ChangeFullZoom(PRInt32 change)
 {
   nsCOMPtr<nsIMarkupDocumentViewer> mv;
   nsresult rv = GetMarkupDocumentViewer(getter_AddRefs(mv));
   NS_ENSURE_SUCCESS(rv, rv);
 
   float fullzoom;
-  float zoomMin = ((float)nsContentUtils::GetIntPref("zoom.minPercent", 50)) / 100;
-  float zoomMax = ((float)nsContentUtils::GetIntPref("zoom.maxPercent", 300)) / 100;
+  float zoomMin = ((float)Preferences::GetInt("zoom.minPercent", 50)) / 100;
+  float zoomMax = ((float)Preferences::GetInt("zoom.maxPercent", 300)) / 100;
   mv->GetFullZoom(&fullzoom);
   fullzoom += ((float)change) / 10;
   if (fullzoom < zoomMin)
     fullzoom = zoomMin;
   else if (fullzoom > zoomMax)
     fullzoom = zoomMax;
   mv->SetFullZoom(fullzoom);
 
@@ -2459,20 +2432,21 @@ nsEventStateManager::DoScrollZoom(nsIFra
   nsIContent *content = aTargetFrame->GetContent();
   if (content &&
       !content->IsNodeOfType(nsINode::eHTML_FORM_CONTROL) &&
       !content->IsXUL())
     {
       // positive adjustment to decrease zoom, negative to increase
       PRInt32 change = (adjustment > 0) ? -1 : 1;
 
-      if (nsContentUtils::GetBoolPref("browser.zoom.full"))
+      if (Preferences::GetBool("browser.zoom.full")) {
         ChangeFullZoom(change);
-      else
+      } else {
         ChangeTextSize(change);
+      }
     }
 }
 
 static nsIFrame*
 GetParentFrameToScroll(nsIFrame* aFrame)
 {
   if (!aFrame)
     return nsnull;
@@ -2603,37 +2577,37 @@ nsEventStateManager::ComputeWheelActionF
 }
 
 PRInt32
 nsEventStateManager::GetWheelActionFor(nsMouseScrollEvent* aMouseEvent)
 {
   nsCAutoString prefName;
   GetBasePrefKeyForMouseWheel(aMouseEvent, prefName);
   prefName.Append(".action");
-  return nsContentUtils::GetIntPref(prefName.get());
+  return Preferences::GetInt(prefName.get());
 }
 
 PRInt32
 nsEventStateManager::GetScrollLinesFor(nsMouseScrollEvent* aMouseEvent)
 {
   NS_ASSERTION(!UseSystemScrollSettingFor(aMouseEvent),
     "GetScrollLinesFor() called when should use system settings");
   nsCAutoString prefName;
   GetBasePrefKeyForMouseWheel(aMouseEvent, prefName);
   prefName.Append(".numlines");
-  return nsContentUtils::GetIntPref(prefName.get());
+  return Preferences::GetInt(prefName.get());
 }
 
 PRBool
 nsEventStateManager::UseSystemScrollSettingFor(nsMouseScrollEvent* aMouseEvent)
 {
   nsCAutoString prefName;
   GetBasePrefKeyForMouseWheel(aMouseEvent, prefName);
   prefName.Append(".sysnumlines");
-  return nsContentUtils::GetBoolPref(prefName.get());
+  return Preferences::GetBool(prefName.get());
 }
 
 nsresult
 nsEventStateManager::DoScrollText(nsIFrame* aTargetFrame,
                                   nsMouseScrollEvent* aMouseEvent,
                                   nsIScrollableFrame::ScrollUnit aScrollQuantity,
                                   PRBool aAllowScrollSpeedOverride,
                                   nsQueryContentEvent* aQueryEvent)
@@ -3462,17 +3436,17 @@ nsEventStateManager::UpdateCursor(nsPres
         return;  // don't update the cursor if we failed to get it from the frame see bug 118877
       cursor = framecursor.mCursor;
       container = framecursor.mContainer;
       haveHotspot = framecursor.mHaveHotspot;
       hotspotX = framecursor.mHotspotX;
       hotspotY = framecursor.mHotspotY;
   }
 
-  if (nsContentUtils::GetBoolPref("ui.use_activity_cursor", PR_FALSE)) {
+  if (Preferences::GetBool("ui.use_activity_cursor", PR_FALSE)) {
     // Check whether or not to show the busy cursor
     nsCOMPtr<nsISupports> pcContainer = aPresContext->GetContainer();
     nsCOMPtr<nsIDocShell> docShell(do_QueryInterface(pcContainer));
     if (!docShell) return;
     PRUint32 busyFlags = nsIDocShell::BUSY_FLAGS_NONE;
     docShell->GetBusyFlags(&busyFlags);
 
     // Show busy cursor everywhere before page loads
@@ -4222,45 +4196,36 @@ nsEventStateManager::GetEventTargetConte
   // event target in the PresShell.
   if (!content && mCurrentTarget) {
     mCurrentTarget->GetContentForEvent(mPresContext, aEvent, &content);
   }
 
   return content;
 }
 
-static already_AddRefed<nsIContent>
-GetLabelTarget(nsIContent* aLabel)
+static Element*
+GetLabelTarget(nsIContent* aPossibleLabel)
 {
-  nsCOMPtr<nsIDOMHTMLLabelElement> label = do_QueryInterface(aLabel);
+  nsHTMLLabelElement* label = nsHTMLLabelElement::FromContent(aPossibleLabel);
   if (!label)
     return nsnull;
 
-  nsCOMPtr<nsIDOMHTMLElement> target;
-  label->GetControl(getter_AddRefs(target));
-  nsIContent* targetContent = nsnull;
-  if (target) {
-    CallQueryInterface(target, &targetContent);
-  }
-  return targetContent;
+  return label->GetLabeledElement();
 }
 
 static bool
-IsAncestorOf(nsIContent* aPossibleAncestor, nsIContent* aPossibleDescendant,
-             PRBool aFollowLabels)
+IsAncestorOf(nsIContent* aPossibleAncestor, nsIContent* aPossibleDescendant)
 {
   for (; aPossibleDescendant; aPossibleDescendant = aPossibleDescendant->GetParent()) {
     if (aPossibleAncestor == aPossibleDescendant)
       return true;
 
-    if (aFollowLabels) {
-      nsCOMPtr<nsIContent> labelTarget = GetLabelTarget(aPossibleDescendant);
-      if (labelTarget == aPossibleAncestor)
-        return true;
-    }
+    Element* labelTarget = GetLabelTarget(aPossibleDescendant);
+    if (labelTarget == aPossibleAncestor)
+      return true;
   }
   return false;
 }
 
 static bool
 ShouldShowFocusRing(nsIContent* aContent)
 {
   nsIDocument* doc = aContent->GetOwnerDoc();
@@ -4268,24 +4233,24 @@ ShouldShowFocusRing(nsIContent* aContent
     nsPIDOMWindow* window = doc->GetWindow();
     return window && window->ShouldShowFocusRing();
   }
 
   return false;
 }
 
 nsEventStates
-nsEventStateManager::GetContentState(nsIContent *aContent, PRBool aFollowLabels)
+nsEventStateManager::GetContentState(nsIContent *aContent)
 {
   nsEventStates state = aContent->IntrinsicState();
 
-  if (IsAncestorOf(aContent, mActiveContent, aFollowLabels)) {
+  if (IsAncestorOf(aContent, mActiveContent)) {
     state |= NS_EVENT_STATE_ACTIVE;
   }
-  if (IsAncestorOf(aContent, mHoverContent, aFollowLabels)) {
+  if (IsAncestorOf(aContent, mHoverContent)) {
     state |= NS_EVENT_STATE_HOVER;
   }
 
   nsFocusManager* fm = nsFocusManager::GetFocusManager();
   nsIContent* focusedContent = fm ? fm->GetFocusedContent() : nsnull;
   if (aContent == focusedContent) {
     state |= NS_EVENT_STATE_FOCUS;
 
@@ -4347,17 +4312,17 @@ static nsIContent* FindCommonAncestor(ns
 }
 
 static void
 NotifyAncestors(nsIDocument* aDocument, nsIContent* aStartNode,
                 nsIContent* aStopBefore, nsEventStates aState)
 {
   while (aStartNode && aStartNode != aStopBefore) {
     aDocument->ContentStateChanged(aStartNode, aState);
-    nsCOMPtr<nsIContent> labelTarget = GetLabelTarget(aStartNode);
+    Element* labelTarget = GetLabelTarget(aStartNode);
     if (labelTarget) {
       aDocument->ContentStateChanged(labelTarget, aState);
     }
     aStartNode = aStartNode->GetParent();
   }
 }
 
 PRBool
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -117,25 +117,19 @@ public:
   void ClearFrameRefs(nsIFrame* aFrame);
 
   nsIFrame* GetEventTarget();
   already_AddRefed<nsIContent> GetEventTargetContent(nsEvent* aEvent);
 
   /**
    * Returns the content state of aContent.
    * @param aContent      The control whose state is requested.
-   * @param aFollowLabels Whether to reflect a label's content state on its
-   *                      associated control. If aFollowLabels is true and
-   *                      aContent is a control which has a label that has the 
-   *                      hover or active content state set, GetContentState
-   *                      will pretend that those states are also set on aContent.
    * @return              The content state.
    */
-  virtual nsEventStates GetContentState(nsIContent *aContent,
-                                        PRBool aFollowLabels = PR_FALSE);
+  virtual nsEventStates GetContentState(nsIContent *aContent);
 
   /**
    * Notify that the given NS_EVENT_STATE_* bit has changed for this content.
    * @param aContent Content which has changed states
    * @param aState   Corresponding state flags such as NS_EVENT_STATE_FOCUS
    * @return  Whether the content was able to change all states. Returns PR_FALSE
    *                  if a resulting DOM event causes the content node passed in
    *                  to not change states. Note, the frame for the content may
--- a/content/events/test/Makefile.in
+++ b/content/events/test/Makefile.in
@@ -99,16 +99,18 @@ include $(topsrcdir)/config/rules.mk
 		test_bug605242.html \
 		test_bug613634.html \
 		test_bug607464.html \
 		test_bug624127.html \
 		test_bug650493.html \
 		test_bug641477.html \
 		test_bug648573.html \
 		test_bug615597.html \
+		test_bug656379-1.html \
+		test_bug656379-2.html \
 		test_bug656954.html \
 		$(NULL)
 
 #bug 585630
 ifneq (mobile,$(MOZ_BUILD_APP))
 _TEST_FILES += \
 		test_dragstart.html \
 		$(NULL)
copy from content/events/test/test_bug426082.html
copy to content/events/test/test_bug656379-1.html
--- a/content/events/test/test_bug426082.html
+++ b/content/events/test/test_bug656379-1.html
@@ -1,24 +1,44 @@
 <!DOCTYPE HTML>
 <html>
 <!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=426082
+https://bugzilla.mozilla.org/show_bug.cgi?id=656379
 -->
 <head>
-  <title>Test for Bug 426082</title>
+  <title>Test for Bug 656379</title>
   <script type="application/javascript" src="/MochiKit/packed.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/WindowSnapshot.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
   <style>
     canvas {
       display: none;
     }
+    input[type=button] {
+      -moz-appearance: none;
+      padding: 0;
+      border: none;
+      color: black;
+      background: white;
+    }
+    input[type=button]::-moz-focus-inner { border: none; }
+
+    /* Make sure that normal, focused, hover+active, focused+hover+active
+       buttons all have different styles so that the test keeps moving along. */
+    input[type=button]:hover:active {
+      background: red;
+    }
+    input[type=button]:focus {
+      background: green;
+    }
+    input[type=button]:focus:hover:active {
+      background: purple;
+    }
   </style>
 </head>
 <body onload="runTests()">
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=426082">Mozilla Bug 426082</a>
 <p id="display"></p>
 <div id="content" style="display: none">
   
 </div>
new file mode 100644
--- /dev/null
+++ b/content/events/test/test_bug656379-2.html
@@ -0,0 +1,63 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=656379
+-->
+<head>
+  <title>Test for Bug 656379</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <style>
+    button:hover { color: green; }
+  </style>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=656379">Mozilla Bug 656379</a>
+<p id="display">
+  <label for="button1" id="label1">Label 1</label>
+  <button id="button1">Button 1</button>
+  <label><span id="label2">Label 2</span><button id="button2">Button 2</button></label>
+</p>
+<div id="content" style="display: none">
+  
+</div>
+<pre id="test">
+<script type="application/javascript;version=1.8">
+
+/** Test for Bug 656379 **/
+SimpleTest.waitForExplicitFinish();
+function tests() {
+  synthesizeMouseAtCenter($("label1"), { type: "mousemove" });
+  yield;
+  is($("button1").mozMatchesSelector(":hover"), true,
+     "Button 1 should be hovered");
+  is($("button2").mozMatchesSelector(":hover"), false,
+     "Button 2 should not be hovered");
+  synthesizeMouseAtCenter($("label2"), { type: "mousemove" });
+  yield;
+  is($("button1").mozMatchesSelector(":hover"), false,
+     "Button 1 should not be hovered");
+  is($("button2").mozMatchesSelector(":hover"), true,
+     "Button 2 should be hovered");
+  SimpleTest.finish();
+}
+
+function executeTests() {
+  var testYielder = tests();
+  function execNext() {
+    try {
+      testYielder.next();
+      SimpleTest.executeSoon(execNext);
+    } catch(e) {}
+  }
+  execNext();
+}
+
+SimpleTest.waitForFocus(executeTests);
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/content/public/nsHTMLCanvasElement.h
+++ b/content/html/content/public/nsHTMLCanvasElement.h
@@ -176,17 +176,17 @@ protected:
 
   nsresult UpdateContext(nsIPropertyBag *aNewContextOptions = nsnull);
   nsresult ExtractData(const nsAString& aType,
                        const nsAString& aOptions,
                        char*& aData,
                        PRUint32& aSize,
                        bool& aFellBackToPNG);
   nsresult ToDataURLImpl(const nsAString& aMimeType,
-                         const nsAString& aEncoderOptions,
+                         nsIVariant* aEncoderOptions,
                          nsAString& aDataURL);
   nsresult MozGetAsFileImpl(const nsAString& aName,
                             const nsAString& aType,
                             nsIDOMFile** aResult);
   nsresult GetContextHelper(const nsAString& aContextId,
                             nsICanvasRenderingContextInternal **aContext);
 
   nsString mCurrentContextId;
--- a/content/html/content/src/Makefile.in
+++ b/content/html/content/src/Makefile.in
@@ -43,37 +43,34 @@ VPATH		= @srcdir@
 include $(DEPTH)/config/autoconf.mk
 
 MODULE		= content
 LIBRARY_NAME	= gkconhtmlcon_s
 LIBXUL_LIBRARY	= 1
 
 
 EXPORTS		= \
-		nsImageMapUtils.h \
 		nsClientRect.h \
 		nsHTMLDNSPrefetch.h \
 		$(NULL)
 
 CPPSRCS		= \
 		nsClientRect.cpp \
 		nsHTMLDNSPrefetch.cpp \
 		nsGenericHTMLElement.cpp \
 		nsFormSubmission.cpp \
-		nsImageMapUtils.cpp \
 		nsTextEditorState.cpp \
 		nsHTMLElement.cpp \
 		nsHTMLAnchorElement.cpp \
 		nsHTMLAreaElement.cpp \
 		nsHTMLBRElement.cpp \
 		nsHTMLBodyElement.cpp \
 		nsHTMLButtonElement.cpp \
 		nsHTMLCanvasElement.cpp \
 		nsHTMLDataListElement.cpp \
-		nsHTMLDelElement.cpp \
 		nsHTMLDivElement.cpp \
 		nsHTMLFieldSetElement.cpp \
 		nsHTMLFontElement.cpp \
 		nsHTMLFormElement.cpp \
 		nsHTMLFrameElement.cpp \
 		nsHTMLFrameSetElement.cpp \
 		nsHTMLHRElement.cpp \
 		nsHTMLHeadingElement.cpp \
@@ -81,16 +78,17 @@ CPPSRCS		= \
 		nsHTMLImageElement.cpp \
 		nsHTMLInputElement.cpp \
 		nsHTMLLIElement.cpp \
 		nsHTMLLabelElement.cpp \
 		nsHTMLLegendElement.cpp \
 		nsHTMLLinkElement.cpp \
 		nsHTMLMapElement.cpp \
 		nsHTMLMetaElement.cpp \
+		nsHTMLModElement.cpp \
 		nsHTMLObjectElement.cpp \
 		nsHTMLOListElement.cpp \
 		nsHTMLSharedObjectElement.cpp \
 		nsHTMLOptionElement.cpp \
 		nsHTMLOptGroupElement.cpp \
 		nsHTMLOutputElement.cpp \
 		nsHTMLParagraphElement.cpp \
 		nsHTMLPreElement.cpp \
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -43,17 +43,16 @@
 #include "nsIContentViewer.h"
 #include "mozilla/css/StyleRule.h"
 #include "nsIDocument.h"
 #include "nsIDocumentEncoder.h"
 #include "nsIDOMHTMLBodyElement.h"
 #include "nsIDOMHTMLDocument.h"
 #include "nsIDOMAttr.h"
 #include "nsIDOMDocumentFragment.h"
-#include "nsIDOMNSHTMLDocument.h"
 #include "nsIDOMNSHTMLElement.h"
 #include "nsIDOMElementCSSInlineStyle.h"
 #include "nsIDOMWindow.h"
 #include "nsIDOMDocument.h"
 #include "nsIEventListenerManager.h"
 #include "nsMappedAttributes.h"
 #include "nsHTMLStyleSheet.h"
 #include "nsIHTMLDocument.h"
@@ -111,16 +110,19 @@
 #include "nsLayoutUtils.h"
 #include "nsContentCreatorFunctions.h"
 #include "mozAutoDocUpdate.h"
 #include "nsHtml5Module.h"
 #include "nsITextControlElement.h"
 #include "mozilla/dom/Element.h"
 #include "nsHTMLFieldSetElement.h"
 
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 using namespace mozilla::dom;
 
 #include "nsThreadUtils.h"
 
 class nsINodeInfo;
 class nsIDOMNodeList;
 class nsRuleWalker;
 
@@ -774,22 +776,22 @@ nsGenericHTMLElement::SetInnerHTML(const
                                          PR_TRUE);
     doc->SetFragmentParser(parser);
 
     // HTML5 parser has notified, but not fired mutation events.
     // Fire mutation events. Optimize for the case when there are no listeners
     PRInt32 newChildCount = GetChildCount();
     if (newChildCount && nsContentUtils::
           HasMutationListeners(doc, NS_EVENT_BITS_MUTATION_NODEINSERTED)) {
-      nsCOMArray<nsIContent> childNodes;
+      nsAutoTArray<nsCOMPtr<nsIContent>, 50> childNodes;
       NS_ASSERTION(newChildCount - oldChildCount >= 0,
                    "What, some unexpected dom mutation has happened?");
       childNodes.SetCapacity(newChildCount - oldChildCount);
       for (nsINode::ChildIterator iter(this); !iter.IsDone(); iter.Next()) {
-        childNodes.AppendObject(iter);
+        childNodes.AppendElement(iter);
       }
       nsGenericElement::FireNodeInserted(doc, this, childNodes);
     }
   } else {
     rv = nsContentUtils::CreateContextualFragment(this, aInnerHTML, PR_FALSE,
                                                   getter_AddRefs(df));
     nsCOMPtr<nsINode> fragment = do_QueryInterface(df);
     if (NS_SUCCEEDED(rv)) {
@@ -891,18 +893,17 @@ nsGenericHTMLElement::GetSpellcheck(PRBo
   if (controlType != NS_FORM_INPUT_TEXT) {
     return NS_OK;                       // Not spellchecked by default
   }
 
   // Does the user want input text spellchecked by default?
   // NOTE: Do not reflect a pref value of 0 back to the DOM getter.
   // The web page should not know if the user has disabled spellchecking.
   // We'll catch this in the editor itself.
-  PRInt32 spellcheckLevel =
-    nsContentUtils::GetIntPref("layout.spellcheckDefault", 1);
+  PRInt32 spellcheckLevel = Preferences::GetInt("layout.spellcheckDefault", 1);
   if (spellcheckLevel == 2) {           // "Spellcheck multi- and single-line"
     *aSpellcheck = PR_TRUE;             // Spellchecked by default
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -2540,17 +2541,17 @@ nsGenericHTMLFormElement::BindToTree(nsI
                                                  aCompileEventHandlers);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // An autofocus event has to be launched if the autofocus attribute is
   // specified and the element accept the autofocus attribute. In addition,
   // the document should not be already loaded and the "browser.autofocus"
   // preference should be 'true'.
   if (IsAutofocusable() && HasAttr(kNameSpaceID_None, nsGkAtoms::autofocus) &&
-      nsContentUtils::GetBoolPref("browser.autofocus", PR_TRUE)) {
+      Preferences::GetBool("browser.autofocus", PR_TRUE)) {
     nsCOMPtr<nsIRunnable> event = new nsAutoFocusEvent(this);
     rv = NS_DispatchToCurrentThread(event);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // If @form is set, the element *has* to be in a document, otherwise it
   // wouldn't be possible to find an element with the corresponding id.
   // If @form isn't set, the element *has* to have a parent, otherwise it
--- a/content/html/content/src/nsHTMLCanvasElement.cpp
+++ b/content/html/content/src/nsHTMLCanvasElement.cpp
@@ -42,16 +42,17 @@
 #include "prmem.h"
 #include "nsDOMFile.h"
 #include "CheckedInt.h"
 
 #include "nsIScriptSecurityManager.h"
 #include "nsIXPConnect.h"
 #include "jsapi.h"
 #include "nsJSUtils.h"
+#include "nsMathUtils.h"
 
 #include "nsFrameManager.h"
 #include "nsDisplayList.h"
 #include "ImageLayers.h"
 #include "BasicLayers.h"
 #include "imgIEncoder.h"
 
 #include "nsIWritablePropertyBag2.h"
@@ -191,42 +192,27 @@ nsHTMLCanvasElement::ParseAttribute(PRIn
   return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
                                               aResult);
 }
 
 
 // nsHTMLCanvasElement::toDataURL
 
 NS_IMETHODIMP
-nsHTMLCanvasElement::ToDataURL(const nsAString& aType, const nsAString& aParams,
+nsHTMLCanvasElement::ToDataURL(const nsAString& aType, nsIVariant* aParams,
                                PRUint8 optional_argc, nsAString& aDataURL)
 {
   // do a trust check if this is a write-only canvas
-  // or if we're trying to use the 2-arg form
-  if ((mWriteOnly || optional_argc >= 2) &&
-      !nsContentUtils::IsCallerTrustedForRead()) {
+  if (mWriteOnly && !nsContentUtils::IsCallerTrustedForRead()) {
     return NS_ERROR_DOM_SECURITY_ERR;
   }
 
   return ToDataURLImpl(aType, aParams, aDataURL);
 }
 
-
-// nsHTMLCanvasElement::toDataURLAs
-//
-// Native-callers only
-
-NS_IMETHODIMP
-nsHTMLCanvasElement::ToDataURLAs(const nsAString& aMimeType,
-                                 const nsAString& aEncoderOptions,
-                                 nsAString& aDataURL)
-{
-  return ToDataURLImpl(aMimeType, aEncoderOptions, aDataURL);
-}
-
 nsresult
 nsHTMLCanvasElement::ExtractData(const nsAString& aType,
                                  const nsAString& aOptions,
                                  char*& aResult,
                                  PRUint32& aSize,
                                  bool& aFellBackToPNG)
 {
   // note that if we don't have a current context, the spec says we're
@@ -318,35 +304,54 @@ nsHTMLCanvasElement::ExtractData(const n
     }
   }
 
   return NS_OK;
 }
 
 nsresult
 nsHTMLCanvasElement::ToDataURLImpl(const nsAString& aMimeType,
-                                   const nsAString& aEncoderOptions,
+                                   nsIVariant* aEncoderOptions,
                                    nsAString& aDataURL)
 {
   bool fallbackToPNG = false;
 
   nsIntSize size = GetWidthHeight();
   if (size.height == 0 || size.width == 0) {
     aDataURL = NS_LITERAL_STRING("data:,");
     return NS_OK;
   }
 
   nsAutoString type;
   nsContentUtils::ASCIIToLower(aMimeType, type);
 
+  nsAutoString params;
+
+  // Quality parameter is only valid for the image/jpeg MIME type
+  if (type.EqualsLiteral("image/jpeg")) {
+    PRUint16 vartype;
+
+    if (aEncoderOptions &&
+        NS_SUCCEEDED(aEncoderOptions->GetDataType(&vartype)) &&
+        vartype <= nsIDataType::VTYPE_DOUBLE) {
+
+      double quality;
+      // Quality must be between 0.0 and 1.0, inclusive
+      if (NS_SUCCEEDED(aEncoderOptions->GetAsDouble(&quality)) &&
+          quality >= 0.0 && quality <= 1.0) {
+        params.AppendLiteral("quality=");
+        params.AppendInt(NS_lround(quality * 100.0));
+      }
+    }
+  }
+
   PRUint32 imgSize = 0;
   char* imgData;
 
-  nsresult rv = ExtractData(type, aEncoderOptions, imgData,
-                            imgSize, fallbackToPNG);
+  nsresult rv = ExtractData(type, params, imgData, imgSize, fallbackToPNG);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // base 64, result will be NULL terminated
   char* encodedImg = PL_Base64Encode(imgData, imgSize, nsnull);
   PR_Free(imgData);
   if (!encodedImg) // not sure why this would fail
     return NS_ERROR_OUT_OF_MEMORY;
 
--- a/content/html/content/src/nsHTMLDNSPrefetch.cpp
+++ b/content/html/content/src/nsHTMLDNSPrefetch.cpp
@@ -49,24 +49,26 @@
 
 #include "nsIDNSListener.h"
 #include "nsIWebProgressListener.h"
 #include "nsIWebProgress.h"
 #include "nsCURILoader.h"
 #include "nsIDNSRecord.h"
 #include "nsIDNSService.h"
 #include "nsICancelable.h"
-#include "nsContentUtils.h"
 #include "nsGkAtoms.h"
 #include "nsIDocument.h"
 #include "nsThreadUtils.h"
 #include "nsITimer.h"
 #include "nsIObserverService.h"
 #include "mozilla/dom/Link.h"
 
+#include "mozilla/Preferences.h"
+
+using namespace mozilla;
 using namespace mozilla::dom;
 using namespace mozilla::net;
 
 static NS_DEFINE_CID(kDNSServiceCID, NS_DNSSERVICE_CID);
 PRBool sDisablePrefetchHTTPSPref;
 static PRBool sInitialized = PR_FALSE;
 static nsIDNSService *sDNSService = nsnull;
 static nsHTMLDNSPrefetch::nsDeferrals *sPrefetches = nsnull;
@@ -89,22 +91,22 @@ nsHTMLDNSPrefetch::Initialize()
   if (!sDNSListener) {
     NS_IF_RELEASE(sPrefetches);
     return NS_ERROR_OUT_OF_MEMORY;
   }
   NS_ADDREF(sDNSListener);
 
   sPrefetches->Activate();
 
-  nsContentUtils::AddBoolPrefVarCache("network.dns.disablePrefetchFromHTTPS", 
-                                      &sDisablePrefetchHTTPSPref);
+  Preferences::AddBoolVarCache(&sDisablePrefetchHTTPSPref,
+                               "network.dns.disablePrefetchFromHTTPS");
   
   // Default is false, so we need an explicit call to prime the cache.
   sDisablePrefetchHTTPSPref = 
-    nsContentUtils::GetBoolPref("network.dns.disablePrefetchFromHTTPS", PR_TRUE);
+    Preferences::GetBool("network.dns.disablePrefetchFromHTTPS", PR_TRUE);
   
   NS_IF_RELEASE(sDNSService);
   nsresult rv;
   rv = CallGetService(kDNSServiceCID, &sDNSService);
   if (NS_FAILED(rv)) return rv;
   
   if (IsNeckoChild())
     NeckoChild::InitNeckoChild();
--- a/content/html/content/src/nsHTMLFieldSetElement.cpp
+++ b/content/html/content/src/nsHTMLFieldSetElement.cpp
@@ -212,18 +212,17 @@ nsHTMLFieldSetElement::InsertChildAt(nsI
   if (firstLegendHasChanged) {
     NotifyElementsForFirstLegendChange(aNotify);
   }
 
   return rv;
 }
 
 nsresult
-nsHTMLFieldSetElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify,
-                                     PRBool aMutationEvent /* = PR_TRUE */)
+nsHTMLFieldSetElement::RemoveChildAt(PRUint32 aIndex, PRBool aNotify)
 {
   bool firstLegendHasChanged = false;
 
   if (mFirstLegend && (GetChildAt(aIndex) == mFirstLegend)) {
     // If we are removing the first legend we have to found another one.
     nsIContent* child = mFirstLegend->GetNextSibling();
     mFirstLegend = nsnull;
     firstLegendHasChanged = true;
@@ -231,17 +230,17 @@ nsHTMLFieldSetElement::RemoveChildAt(PRU
     for (; child; child = child->GetNextSibling()) {
       if (child->IsHTML(nsGkAtoms::legend)) {
         mFirstLegend = child;
         break;
       }
     }
   }
 
-  nsresult rv = nsGenericHTMLFormElement::RemoveChildAt(aIndex, aNotify, aMutationEvent);
+  nsresult rv = nsGenericHTMLFormElement::RemoveChildAt(aIndex, aNotify);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (firstLegendHasChanged) {
     NotifyElementsForFirstLegendChange(aNotify);
   }
 
   return rv;
 }
--- a/content/html/content/src/nsHTMLFieldSetElement.h
+++ b/content/html/content/src/nsHTMLFieldSetElement.h
@@ -71,18 +71,17 @@ public:
 
   // nsIContent
   virtual nsresult PreHandleEvent(nsEventChainPreVisitor& aVisitor);
   virtual nsresult AfterSetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                                 const nsAString* aValue, PRBool aNotify);
 
   virtual nsresult InsertChildAt(nsIContent* aChild, PRUint32 aIndex,
                                      PRBool aNotify);
-  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify,
-                                 PRBool aMutationEvent = PR_TRUE);
+  virtual nsresult RemoveChildAt(PRUint32 aIndex, PRBool aNotify);
 
   // nsIFormControl
   NS_IMETHOD_(PRUint32) GetType() const { return NS_FORM_FIELDSET; }
   NS_IMETHOD Reset();
   NS_IMETHOD SubmitNamesValues(nsFormSubmission* aFormSubmission);
   virtual nsresult Clone(nsINodeInfo *aNodeInfo, nsINode **aResult) const;
   virtual nsXPCClassInfo* GetClassInfo();
 
--- a/content/html/content/src/nsHTMLFormElement.cpp
+++ b/content/html/content/src/nsHTMLFormElement.cpp
@@ -323,19 +323,18 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 NS_IMPL_ADDREF_INHERITED(nsHTMLFormElement, nsGenericElement) 
 NS_IMPL_RELEASE_INHERITED(nsHTMLFormElement, nsGenericElement) 
 
 
 DOMCI_NODE_DATA(HTMLFormElement, nsHTMLFormElement)
 
 // QueryInterface implementation for nsHTMLFormElement
 NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(nsHTMLFormElement)
-  NS_HTML_CONTENT_INTERFACE_TABLE6(nsHTMLFormElement,
+  NS_HTML_CONTENT_INTERFACE_TABLE5(nsHTMLFormElement,
                                    nsIDOMHTMLFormElement,
-                                   nsIDOMNSHTMLFormElement,
                                    nsIForm,
                                    nsIWebProgressListener,
                                    nsIRadioGroupContainer,
                                    nsIRadioGroupContainer_MOZILLA_2_0_BRANCH)
   NS_HTML_CONTENT_INTERFACE_TABLE_TO_MAP_SEGUE(nsHTMLFormElement,
                                                nsGenericHTMLElement)
 NS_HTML_CONTENT_INTERFACE_TABLE_TAIL_CLASSINFO(HTMLFormElement)
 
--- a/content/html/content/src/nsHTMLFormElement.h
+++ b/content/html/content/src/nsHTMLFormElement.h
@@ -39,17 +39,16 @@
 #define nsHTMLFormElement_h__
 
 #include "nsCOMPtr.h"
 #include "nsIForm.h"
 #include "nsIFormControl.h"
 #include "nsFormSubmission.h"
 #include "nsGenericHTMLElement.h"
 #include "nsIDOMHTMLFormElement.h"
-#include "nsIDOMNSHTMLFormElement.h"
 #include "nsIWebProgressListener.h"
 #include "nsIRadioGroupContainer.h"
 #include "nsIURI.h"
 #include "nsIWeakReferenceUtils.h"
 #include "nsPIDOMWindow.h"
 #include "nsUnicharUtils.h"
 #include "nsThreadUtils.h"
 #include "nsInterfaceHashtable.h"
@@ -88,17 +87,16 @@ public:
   enum { ALLOW_MEMMOVE = PR_TRUE };
 
 private:
   const nsString mStr;
 };
 
 class nsHTMLFormElement : public nsGenericHTMLElement,
                           public nsIDOMHTMLFormElement,
-                          public nsIDOMNSHTMLFormElement,
                           public nsIWebProgressListener,
                           public nsIForm,
                           public nsIRadioGroupContainer_MOZILLA_2_0_BRANCH
 {