Merge MC -> JM
authorBrian Hackett <bhackett1024@gmail.com>
Tue, 02 Aug 2011 09:08:05 -0700
changeset 76092 afb8ed83d8345ef802a30cd72b2d4dfc08e96c78
parent 76091 8367a678afb6f638915d8e99070cc00ac37a941d (current diff)
parent 73678 b1013d7d7cd8977db811b7f3a0ef374ca3c094fc (diff)
child 76093 37894495d77ddee74fdc66bd3fc2e30f55ab6741
push id3
push userfelipc@gmail.com
push dateFri, 30 Sep 2011 20:09:13 +0000
milestone8.0a1
Merge MC -> JM
browser/base/content/browser.js
content/base/test/file_bug391728.html
content/base/test/file_bug391728_2.html
content/base/test/test_bug391728.html
content/html/document/src/nsHTMLFragmentContentSink.cpp
dom/base/nsDOMClassInfo.cpp
dom/base/nsGlobalWindow.cpp
dom/base/nsJSEnvironment.cpp
js/src/Makefile.in
js/src/assembler/assembler/MacroAssemblerARM.h
js/src/configure.in
js/src/jit-test/tests/basic/testBug653396.js
js/src/jit-test/tests/basic/testCompileScript.js
js/src/jsapi-tests/Makefile.in
js/src/jsapi.cpp
js/src/jsapi.h
js/src/jsclone.cpp
js/src/jsdbgapi.cpp
js/src/jsfun.cpp
js/src/jshashtable.h
js/src/jsinterp.cpp
js/src/jsnum.cpp
js/src/jsprobes.cpp
js/src/jsscript.cpp
js/src/jsscript.h
js/src/jstracer.cpp
js/src/jstypedarray.cpp
js/src/jstypedarray.h
js/src/jstypedarrayinlines.h
js/src/jsval.h
js/src/methodjit/Compiler.cpp
js/src/methodjit/FastArithmetic.cpp
js/src/methodjit/ICLabels.h
js/src/methodjit/MonoIC.cpp
js/src/methodjit/PolyIC.cpp
js/src/methodjit/TypedArrayIC.h
js/src/shell/js.cpp
js/src/tests/ecma_5/RegExp/jstests.list
js/src/tests/js1_8_5/regress/jstests.list
js/src/tracejit/Writer.cpp
js/src/tracejit/Writer.h
js/src/vm/Stack.cpp
js/src/xpconnect/src/nsXPConnect.cpp
js/src/xpconnect/src/xpcjsruntime.cpp
js/src/xpconnect/src/xpcprivate.h
js/src/xpconnect/src/xpcpublic.h
js/src/xpconnect/src/xpcwrappednative.cpp
testing/sisyphus/bin/appinfo.js
testing/sisyphus/bin/build.sh
testing/sisyphus/bin/builder.sh
testing/sisyphus/bin/buildinfo.html
testing/sisyphus/bin/check-spider.sh
testing/sisyphus/bin/checkout.sh
testing/sisyphus/bin/clean.sh
testing/sisyphus/bin/clobber.sh
testing/sisyphus/bin/combo.sh
testing/sisyphus/bin/create-directory.sh
testing/sisyphus/bin/create-profile.sh
testing/sisyphus/bin/dateparse.pl
testing/sisyphus/bin/download.sh
testing/sisyphus/bin/each-to-html.pl
testing/sisyphus/bin/edit-talkback.pl
testing/sisyphus/bin/edit-talkback.sh
testing/sisyphus/bin/firefox.diff
testing/sisyphus/bin/get-build-info.html
testing/sisyphus/bin/get-extension-uuid.pl
testing/sisyphus/bin/include.mk
testing/sisyphus/bin/install-build.sh
testing/sisyphus/bin/install-extensions-1.html
testing/sisyphus/bin/install-extensions.sh
testing/sisyphus/bin/install-plugins.sh
testing/sisyphus/bin/library.sh
testing/sisyphus/bin/master.sed
testing/sisyphus/bin/memory.pl
testing/sisyphus/bin/mips.pl
testing/sisyphus/bin/quit.js
testing/sisyphus/bin/run-mozilla.diff
testing/sisyphus/bin/sayvars.sh
testing/sisyphus/bin/set-build-env.sh
testing/sisyphus/bin/start-spider.html
testing/sisyphus/bin/test-setup.sh
testing/sisyphus/bin/tester.sh
testing/sisyphus/bin/timed_run.py
testing/sisyphus/bin/uninstall-build.sh
testing/sisyphus/bin/userhook-checkspider.js
testing/sisyphus/data/firefox,1.8.0,debug.data
testing/sisyphus/data/firefox,1.8.0,opt.data
testing/sisyphus/data/firefox,1.8.0-test,debug.data
testing/sisyphus/data/firefox,1.8.0-test,opt.data
testing/sisyphus/data/firefox,1.8.0-too-much-gc,debug.data
testing/sisyphus/data/firefox,1.8.1,debug.data
testing/sisyphus/data/firefox,1.8.1,opt.data
testing/sisyphus/data/firefox,1.8.1-test,debug.data
testing/sisyphus/data/firefox,1.8.1-test,opt.data
testing/sisyphus/data/firefox,1.8.1-too-much-gc,debug.data
testing/sisyphus/data/firefox,1.9.0,debug.data
testing/sisyphus/data/firefox,1.9.0,nightly-darwin.data
testing/sisyphus/data/firefox,1.9.0,nightly-linux.data
testing/sisyphus/data/firefox,1.9.0,nightly-nt.data
testing/sisyphus/data/firefox,1.9.0,opt.data
testing/sisyphus/data/firefox,1.9.0-gcov,debug.data
testing/sisyphus/data/firefox,1.9.0-gcov,opt.data
testing/sisyphus/data/firefox,1.9.0-jprof,debug.data
testing/sisyphus/data/firefox,1.9.0-jprof,opt.data
testing/sisyphus/data/firefox,1.9.0-test,debug.data
testing/sisyphus/data/firefox,1.9.0-test,opt.data
testing/sisyphus/data/firefox,1.9.0-too-much-gc,debug.data
testing/sisyphus/data/firefox,1.9.1,debug.data
testing/sisyphus/data/firefox,1.9.1,nightly-darwin.data
testing/sisyphus/data/firefox,1.9.1,nightly-linux.data
testing/sisyphus/data/firefox,1.9.1,nightly-nt.data
testing/sisyphus/data/firefox,1.9.1,opt.data
testing/sisyphus/data/firefox,1.9.1-jprof,debug.data
testing/sisyphus/data/firefox,1.9.1-jprof,opt.data
testing/sisyphus/data/firefox,1.9.1-test,debug.data
testing/sisyphus/data/firefox,1.9.1-test,opt.data
testing/sisyphus/data/firefox,1.9.1-too-much-gc,debug.data
testing/sisyphus/data/firefox,1.9.2,debug.data
testing/sisyphus/data/firefox,1.9.2,nightly-darwin.data
testing/sisyphus/data/firefox,1.9.2,nightly-linux.data
testing/sisyphus/data/firefox,1.9.2,nightly-nt.data
testing/sisyphus/data/firefox,1.9.2,opt.data
testing/sisyphus/data/firefox,1.9.2-test,debug.data
testing/sisyphus/data/firefox,1.9.2-test,opt.data
testing/sisyphus/data/firefox,1.9.3,nightly-darwin.data
testing/sisyphus/data/firefox,1.9.3,nightly-linux.data
testing/sisyphus/data/firefox,1.9.3,nightly-nt.data
testing/sisyphus/data/firefox,1.9.3-tracemonkey,debug.data
testing/sisyphus/data/firefox,1.9.3-tracemonkey,opt.data
testing/sisyphus/data/firefox,1.9.3-tracemonkey-test,debug.data
testing/sisyphus/data/firefox,1.9.3-tracemonkey-test,opt.data
testing/sisyphus/data/js,1.8.0,debug.data
testing/sisyphus/data/js,1.8.0,opt.data
testing/sisyphus/data/js,1.8.0-test,debug.data
testing/sisyphus/data/js,1.8.0-test,opt.data
testing/sisyphus/data/js,1.8.1,debug.data
testing/sisyphus/data/js,1.8.1,opt.data
testing/sisyphus/data/js,1.8.1-test,debug.data
testing/sisyphus/data/js,1.8.1-test,opt.data
testing/sisyphus/data/js,1.8.1-too-much-gc,debug.data
testing/sisyphus/data/js,1.9.0,debug.data
testing/sisyphus/data/js,1.9.0,opt.data
testing/sisyphus/data/js,1.9.0-gcov,debug.data
testing/sisyphus/data/js,1.9.0-gcov,opt.data
testing/sisyphus/data/js,1.9.0-test,debug.data
testing/sisyphus/data/js,1.9.0-test,opt.data
testing/sisyphus/data/js,1.9.0-too-much-gc,debug.data
testing/sisyphus/data/js,1.9.1,debug.data
testing/sisyphus/data/js,1.9.1,opt.data
testing/sisyphus/data/js,1.9.1-test,debug.data
testing/sisyphus/data/js,1.9.1-test,opt.data
testing/sisyphus/data/js,1.9.1-too-much-gc,debug.data
testing/sisyphus/data/js,1.9.2,debug.data
testing/sisyphus/data/js,1.9.2,opt.data
testing/sisyphus/data/js,1.9.2-narcissus,debug.data
testing/sisyphus/data/js,1.9.2-narcissus,opt.data
testing/sisyphus/data/js,1.9.2-test,debug.data
testing/sisyphus/data/js,1.9.2-test,opt.data
testing/sisyphus/data/js,1.9.3,debug.data
testing/sisyphus/data/js,1.9.3,opt.data
testing/sisyphus/data/js,1.9.3-narcissus,debug.data
testing/sisyphus/data/js,1.9.3-narcissus,opt.data
testing/sisyphus/data/js,1.9.3-test,debug.data
testing/sisyphus/data/js,1.9.3-test,opt.data
testing/sisyphus/data/js,1.9.3-tracemonkey,debug.data
testing/sisyphus/data/js,1.9.3-tracemonkey,opt.data
testing/sisyphus/data/js,1.9.3-tracemonkey-test,debug.data
testing/sisyphus/data/js,1.9.3-tracemonkey-test,opt.data
testing/sisyphus/prefs/mail-user.js
testing/sisyphus/prefs/public-user.js
testing/sisyphus/prefs/test-user.js
testing/sisyphus/talkback/linux/Talkback.ini
testing/sisyphus/talkback/mac/Talkback.ini
testing/sisyphus/talkback/win32/Talkback.ini
testing/sisyphus/tests/mozilla.org/download-page/collect-urls-userhook.js
testing/sisyphus/tests/mozilla.org/download-page/test.sh
testing/sisyphus/tests/mozilla.org/download-page/userhook-ftp.js
testing/sisyphus/tests/mozilla.org/download-page/userhook.js
--- a/accessible/src/atk/nsAccessibleWrap.cpp
+++ b/accessible/src/atk/nsAccessibleWrap.cpp
@@ -62,16 +62,18 @@
 #include "nsMaiInterfaceHypertext.h"
 #include "nsMaiInterfaceHyperlinkImpl.h"
 #include "nsMaiInterfaceTable.h"
 #include "nsXPCOMStrings.h"
 #include "nsComponentManagerUtils.h"
 #include "nsMaiInterfaceDocument.h"
 #include "nsMaiInterfaceImage.h"
 
+using namespace mozilla::a11y;
+
 nsAccessibleWrap::EAvailableAtkSignals nsAccessibleWrap::gAvailableAtkSignals =
   eUnknown;
 
 //defined in nsApplicationAccessibleWrap.cpp
 extern "C" GType g_atk_hyperlink_impl_type;
 
 /* MaiAtkObject */
 
@@ -821,31 +823,30 @@ getAttributesCB(AtkObject *aAtkObj)
     nsAccessibleWrap *accWrap = GetAccessibleWrap(aAtkObj);
 
     return accWrap ? GetAttributeSet(accWrap) : nsnull;
 }
 
 AtkObject *
 getParentCB(AtkObject *aAtkObj)
 {
-    if (!aAtkObj->accessible_parent) {
-        nsAccessibleWrap *accWrap = GetAccessibleWrap(aAtkObj);
-        if (!accWrap) {
-            return nsnull;
-        }
+  if (!aAtkObj->accessible_parent) {
+    nsAccessibleWrap* accWrap = GetAccessibleWrap(aAtkObj);
+    if (!accWrap)
+      return nsnull;
 
-        nsAccessible* accParent = accWrap->GetParent();
-        if (!accParent)
-            return nsnull;
+    nsAccessible* accParent = accWrap->Parent();
+    if (!accParent)
+      return nsnull;
 
-        AtkObject *parent = nsAccessibleWrap::GetAtkObject(accParent);
-        if (parent)
-            atk_object_set_parent(aAtkObj, parent);
-    }
-    return aAtkObj->accessible_parent;
+    AtkObject* parent = nsAccessibleWrap::GetAtkObject(accParent);
+    if (parent)
+      atk_object_set_parent(aAtkObj, parent);
+  }
+  return aAtkObj->accessible_parent;
 }
 
 gint
 getChildCountCB(AtkObject *aAtkObj)
 {
     nsAccessibleWrap *accWrap = GetAccessibleWrap(aAtkObj);
     if (!accWrap || nsAccUtils::MustPrune(accWrap)) {
         return 0;
@@ -888,20 +889,19 @@ getIndexInParentCB(AtkObject *aAtkObj)
 {
     // We don't use nsIAccessible::GetIndexInParent() because
     // for ATK we don't want to include text leaf nodes as children
     nsAccessibleWrap *accWrap = GetAccessibleWrap(aAtkObj);
     if (!accWrap) {
         return -1;
     }
 
-    nsAccessible *parent = accWrap->GetParent();
-    if (!parent) {
+    nsAccessible* parent = accWrap->Parent();
+    if (!parent)
         return -1; // No parent
-    }
 
     return parent->GetIndexOfEmbeddedChild(accWrap);
 }
 
 static void
 TranslateStates(PRUint64 aState, AtkStateSet* aStateSet)
 {
 
--- a/accessible/src/atk/nsMaiInterfaceAction.cpp
+++ b/accessible/src/atk/nsMaiInterfaceAction.cpp
@@ -118,17 +118,17 @@ getKeyBindingCB(AtkAction *aAction, gint
   // Return all key bindings including access key and keyboard shortcut.
   nsAutoString keyBindingsStr;
 
   // Get access key.
   KeyBinding keyBinding = acc->AccessKey();
   if (!keyBinding.IsEmpty()) {
     keyBinding.AppendToString(keyBindingsStr, KeyBinding::eAtkFormat);
 
-    nsAccessible* parent = acc->GetParent();
+    nsAccessible* parent = acc->Parent();
     PRUint32 role = parent ? parent->Role() : 0;
     if (role == nsIAccessibleRole::ROLE_PARENT_MENUITEM ||
         role == nsIAccessibleRole::ROLE_MENUITEM ||
         role == nsIAccessibleRole::ROLE_RADIO_MENU_ITEM ||
         role == nsIAccessibleRole::ROLE_CHECK_MENU_ITEM) {
       // It is submenu, expose keyboard shortcuts from menu hierarchy like
       // "s;<Alt>f:s"
       nsAutoString keysInHierarchyStr = keyBindingsStr;
@@ -136,17 +136,17 @@ getKeyBindingCB(AtkAction *aAction, gint
         KeyBinding parentKeyBinding = parent->AccessKey();
         if (!parentKeyBinding.IsEmpty()) {
           nsAutoString str;
           parentKeyBinding.ToString(str, KeyBinding::eAtkFormat);
           str.Append(':');
 
           keysInHierarchyStr.Insert(str, 0);
         }
-      } while ((parent = parent->GetParent()) &&
+      } while ((parent = parent->Parent()) &&
                parent->Role() != nsIAccessibleRole::ROLE_MENUBAR);
 
       keyBindingsStr.Append(';');
       keyBindingsStr.Append(keysInHierarchyStr);
     }
   } else {
     // No access key, add ';' to point this.
     keyBindingsStr.Append(';');
--- a/accessible/src/base/AccEvent.cpp
+++ b/accessible/src/base/AccEvent.cpp
@@ -307,17 +307,17 @@ AccMutationEvent::
 ////////////////////////////////////////////////////////////////////////////////
 // AccHideEvent
 ////////////////////////////////////////////////////////////////////////////////
 
 AccHideEvent::
   AccHideEvent(nsAccessible* aTarget, nsINode* aTargetNode) :
   AccMutationEvent(::nsIAccessibleEvent::EVENT_HIDE, aTarget, aTargetNode)
 {
-  mParent = mAccessible->GetParent();
+  mParent = mAccessible->Parent();
   mNextSibling = mAccessible->NextSibling();
   mPrevSibling = mAccessible->PrevSibling();
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // AccShowEvent
 ////////////////////////////////////////////////////////////////////////////////
--- a/accessible/src/base/AccGroupInfo.cpp
+++ b/accessible/src/base/AccGroupInfo.cpp
@@ -34,21 +34,23 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "AccGroupInfo.h"
 
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 AccGroupInfo::AccGroupInfo(nsAccessible* aItem, PRUint32 aRole) :
   mPosInSet(0), mSetSize(0), mParent(nsnull)
 {
   MOZ_COUNT_CTOR(AccGroupInfo);
-  nsAccessible* parent = aItem->GetParent();
+  nsAccessible* parent = aItem->Parent();
   if (!parent)
     return;
 
   PRInt32 indexInParent = aItem->IndexInParent();
   PRInt32 level = nsAccUtils::GetARIAOrDefaultLevel(aItem);
 
   // Compute position in set.
   mPosInSet = 1;
--- a/accessible/src/base/Makefile.in
+++ b/accessible/src/base/Makefile.in
@@ -82,17 +82,22 @@ CPPSRCS = \
 
 EXPORTS = \
   a11yGeneric.h \
   nsAccDocManager.h \
   nsAccessibilityService.h \
   nsAccessible.h \
   nsAccessNode.h \
   nsARIAMap.h \
-	States.h \
+  $(NULL)
+
+EXPORTS_NAMESPACES = mozilla/a11y
+
+EXPORTS_mozilla/a11y = \
+  States.h \
   $(NULL)
 
 # we don't want the shared lib, but we want to force the creation of a static lib.
 FORCE_STATIC_LIB = 1
 
 include $(topsrcdir)/config/rules.mk
 
 LOCAL_INCLUDES += \
--- a/accessible/src/base/NotificationController.cpp
+++ b/accessible/src/base/NotificationController.cpp
@@ -369,18 +369,18 @@ NotificationController::CoalesceEvents()
 
             // Coalesce text change events for hide events.
             if (tailEvent->mEventRule != AccEvent::eDoNotEmit)
               CoalesceTextChangeEventsFor(tailHideEvent, thisHideEvent);
 
             return;
           }
         } else if (tailEvent->mEventType == nsIAccessibleEvent::EVENT_SHOW) {
-          if (thisEvent->mAccessible->GetParent() ==
-              tailEvent->mAccessible->GetParent()) {
+          if (thisEvent->mAccessible->Parent() ==
+              tailEvent->mAccessible->Parent()) {
             tailEvent->mEventRule = thisEvent->mEventRule;
 
             // Coalesce text change events for show events.
             if (tailEvent->mEventRule != AccEvent::eDoNotEmit) {
               AccShowEvent* tailShowEvent = downcast_accEvent(tailEvent);
               AccShowEvent* thisShowEvent = downcast_accEvent(thisEvent);
               CoalesceTextChangeEventsFor(tailShowEvent, thisShowEvent);
             }
--- a/accessible/src/base/States.h
+++ b/accessible/src/base/States.h
@@ -37,16 +37,18 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _states_h_
 #define _states_h_
 
 #include <prtypes.h>
 
+namespace mozilla {
+namespace a11y {
 namespace states {
 
   /**
    * The object is disabled, opposite to enabled and sensitive.
    */
   const PRUint64 UNAVAILABLE = ((PRUint64) 0x1) << 0;
 
   /**
@@ -298,12 +300,14 @@ namespace states {
    */
   const PRUint64 SENSITIVE = ((PRUint64) 0x1) << 45;
 
   /**
    * The object is expandable, provides a UI to expand/collapse its children
    * @see EXPANDED and COLLAPSED states.
    */
   const PRUint64 EXPANDABLE = ((PRUint64) 0x1) << 46;
-}
+} // namespace states
+} // namespace a11y
+} // namespace mozilla
 
 #endif
 	
--- a/accessible/src/base/TextUpdater.cpp
+++ b/accessible/src/base/TextUpdater.cpp
@@ -64,21 +64,19 @@ TextUpdater::Run(nsDocAccessible* aDocum
     updater.DoUpdate(aNewText, oldText, skipStart);
   }
 }
 
 void
 TextUpdater::DoUpdate(const nsAString& aNewText, const nsAString& aOldText,
                       PRUint32 aSkipStart)
 {
-  nsAccessible* parent = mTextLeaf->GetParent();
-  if (!parent) {
-    NS_ERROR("No parent for text leaf!");
+  nsAccessible* parent = mTextLeaf->Parent();
+  if (!parent)
     return;
-  }
 
   mHyperText = parent->AsHyperText();
   if (!mHyperText) {
     NS_ERROR("Text leaf parent is not hypertext!");
     return;
   }
 
   // Get the text leaf accessible offset and invalidate cached offsets after it.
--- a/accessible/src/base/filters.cpp
+++ b/accessible/src/base/filters.cpp
@@ -36,16 +36,18 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "filters.h"
 
 #include "nsAccessible.h"
 #include "nsAccUtils.h"
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 bool
 filters::GetSelected(nsAccessible* aAccessible)
 {
   return aAccessible->State() & states::SELECTED;
 }
 
 bool
 filters::GetSelectable(nsAccessible* aAccessible)
--- a/accessible/src/base/nsARIAGridAccessible.cpp
+++ b/accessible/src/base/nsARIAGridAccessible.cpp
@@ -40,16 +40,18 @@
 
 #include "AccIterator.h"
 #include "nsAccUtils.h"
 #include "States.h"
 
 #include "nsIMutableArray.h"
 #include "nsComponentManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsARIAGridAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // Constructor
 
@@ -825,17 +827,17 @@ nsARIAGridAccessible::SetARIASelected(ns
   }
 
   // If the given accessible is cell that was unselected and its row is selected
   // then remove aria-selected from row and put aria-selected on
   // siblings cells.
   if (role == nsIAccessibleRole::ROLE_GRID_CELL ||
       role == nsIAccessibleRole::ROLE_ROWHEADER ||
       role == nsIAccessibleRole::ROLE_COLUMNHEADER) {
-    nsAccessible *row = aAccessible->GetParent();
+    nsAccessible* row = aAccessible->Parent();
 
     if (row && row->Role() == nsIAccessibleRole::ROLE_ROW &&
         nsAccUtils::IsARIASelected(row)) {
       rv = SetARIASelected(row, PR_FALSE, PR_FALSE);
       NS_ENSURE_SUCCESS(rv, rv);
 
       AccIterator cellIter(row, filters::GetCell);
       nsAccessible *cell = nsnull;
@@ -944,21 +946,21 @@ NS_IMPL_ISUPPORTS_INHERITED1(nsARIAGridC
 // nsIAccessibleTableCell
 
 NS_IMETHODIMP
 nsARIAGridCellAccessible::GetTable(nsIAccessibleTable **aTable)
 {
   NS_ENSURE_ARG_POINTER(aTable);
   *aTable = nsnull;
 
-  nsAccessible* thisRow = GetParent();
+  nsAccessible* thisRow = Parent();
   if (!thisRow || thisRow->Role() != nsIAccessibleRole::ROLE_ROW)
     return NS_OK;
 
-  nsAccessible* table = thisRow->GetParent();
+  nsAccessible* table = thisRow->Parent();
   if (!table)
     return NS_OK;
 
   PRUint32 tableRole = table->Role();
   if (tableRole != nsIAccessibleRole::ROLE_TABLE &&
       tableRole != nsIAccessibleRole::ROLE_TREE_TABLE)
     return NS_OK;
 
@@ -970,17 +972,17 @@ NS_IMETHODIMP
 nsARIAGridCellAccessible::GetColumnIndex(PRInt32 *aColumnIndex)
 {
   NS_ENSURE_ARG_POINTER(aColumnIndex);
   *aColumnIndex = -1;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  nsAccessible* row = GetParent();
+  nsAccessible* row = Parent();
   if (!row)
     return NS_OK;
 
   *aColumnIndex = 0;
 
   PRInt32 indexInRow = IndexInParent();
   for (PRInt32 idx = 0; idx < indexInRow; idx++) {
     nsAccessible* cell = row->GetChildAt(idx);
@@ -998,21 +1000,21 @@ NS_IMETHODIMP
 nsARIAGridCellAccessible::GetRowIndex(PRInt32 *aRowIndex)
 {
   NS_ENSURE_ARG_POINTER(aRowIndex);
   *aRowIndex = -1;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  nsAccessible* row = GetParent();
+  nsAccessible* row = Parent();
   if (!row)
     return NS_OK;
 
-  nsAccessible* table = row->GetParent();
+  nsAccessible* table = row->Parent();
   if (!table)
     return NS_OK;
 
   *aRowIndex = 0;
 
   PRInt32 indexInTable = row->IndexInParent();
   for (PRInt32 idx = 0; idx < indexInTable; idx++) {
     row = table->GetChildAt(idx);
@@ -1091,17 +1093,17 @@ NS_IMETHODIMP
 nsARIAGridCellAccessible::IsSelected(PRBool *aIsSelected)
 {
   NS_ENSURE_ARG_POINTER(aIsSelected);
   *aIsSelected = PR_FALSE;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  nsAccessible *row = GetParent();
+  nsAccessible* row = Parent();
   if (!row || row->Role() != nsIAccessibleRole::ROLE_ROW)
     return NS_OK;
 
   if (!nsAccUtils::IsARIASelected(row) && !nsAccUtils::IsARIASelected(this))
     return NS_OK;
 
   *aIsSelected = PR_TRUE;
   return NS_OK;
@@ -1115,17 +1117,17 @@ nsARIAGridCellAccessible::ApplyARIAState
 {
   nsHyperTextAccessibleWrap::ApplyARIAState(aState);
 
   // Return if the gridcell has aria-selected="true".
   if (*aState & states::SELECTED)
     return;
 
   // Check aria-selected="true" on the row.
-  nsAccessible* row = GetParent();
+  nsAccessible* row = Parent();
   if (!row || row->Role() != nsIAccessibleRole::ROLE_ROW)
     return;
 
   nsIContent *rowContent = row->GetContent();
   if (nsAccUtils::HasDefinedARIAToken(rowContent,
                                       nsAccessibilityAtoms::aria_selected) &&
       !rowContent->AttrValueIs(kNameSpaceID_None,
                                nsAccessibilityAtoms::aria_selected,
@@ -1139,17 +1141,17 @@ nsARIAGridCellAccessible::GetAttributesI
   if (IsDefunct())
     return NS_ERROR_FAILURE;
   
   nsresult rv = nsHyperTextAccessibleWrap::GetAttributesInternal(aAttributes);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // Expose "table-cell-index" attribute.
 
-  nsAccessible* thisRow = GetParent();
+  nsAccessible* thisRow = Parent();
   if (!thisRow || thisRow->Role() != nsIAccessibleRole::ROLE_ROW)
     return NS_OK;
 
   PRInt32 colIdx = 0, colCount = 0;
   PRInt32 childCount = thisRow->GetChildCount();
   for (PRInt32 childIdx = 0; childIdx < childCount; childIdx++) {
     nsAccessible *child = thisRow->GetChildAt(childIdx);
     if (child == this)
@@ -1157,17 +1159,17 @@ nsARIAGridCellAccessible::GetAttributesI
 
     PRUint32 role = child->Role();
     if (role == nsIAccessibleRole::ROLE_GRID_CELL ||
         role == nsIAccessibleRole::ROLE_ROWHEADER ||
         role == nsIAccessibleRole::ROLE_COLUMNHEADER)
       colCount++;
   }
 
-  nsAccessible* table = thisRow->GetParent();
+  nsAccessible* table = thisRow->Parent();
   if (!table)
     return NS_OK;
 
   PRUint32 tableRole = table->Role();
   if (tableRole != nsIAccessibleRole::ROLE_TABLE &&
       tableRole != nsIAccessibleRole::ROLE_TREE_TABLE)
     return NS_OK;
 
--- a/accessible/src/base/nsARIAMap.cpp
+++ b/accessible/src/base/nsARIAMap.cpp
@@ -40,16 +40,18 @@
 #include "nsARIAMap.h"
 
 #include "nsIAccessibleRole.h"
 #include "States.h"
 
 #include "nsAccessibilityAtoms.h"
 #include "nsIContent.h"
 
+using namespace mozilla::a11y;
+
 /**
  *  This list of WAI-defined roles are currently hardcoded.
  *  Eventually we will most likely be loading an RDF resource that contains this information
  *  Using RDF will also allow for role extensibility. See bug 280138.
  *
  *  Definition of nsRoleMapEntry and nsStateMapEntry contains comments explaining this table.
  *
  *  When no nsIAccessibleRole enum mapping exists for an ARIA role, the
--- a/accessible/src/base/nsAccDocManager.cpp
+++ b/accessible/src/base/nsAccDocManager.cpp
@@ -52,16 +52,18 @@
 #include "nsIDOMDocument.h"
 #include "nsEventListenerManager.h"
 #include "nsIDOMEventTarget.h"
 #include "nsIDOMWindow.h"
 #include "nsIInterfaceRequestorUtils.h"
 #include "nsIWebNavigation.h"
 #include "nsServiceManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccDocManager
 ////////////////////////////////////////////////////////////////////////////////
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccDocManager public
 
 nsDocAccessible*
--- a/accessible/src/base/nsAccUtils.cpp
+++ b/accessible/src/base/nsAccUtils.cpp
@@ -52,16 +52,18 @@
 #include "nsXULTreeGridAccessible.h"
 
 #include "nsIDOMXULContainerElement.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsWhitespaceTokenizer.h"
 #include "nsComponentManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 void
 nsAccUtils::GetAccAttr(nsIPersistentProperties *aAttributes,
                        nsIAtom *aAttrName, nsAString& aAttrValue)
 {
   aAttrValue.Truncate();
 
   aAttributes->GetStringProperty(nsAtomCString(aAttrName), aAttrValue);
 }
@@ -103,17 +105,17 @@ PRInt32
 nsAccUtils::GetDefaultLevel(nsAccessible *aAccessible)
 {
   PRUint32 role = aAccessible->Role();
 
   if (role == nsIAccessibleRole::ROLE_OUTLINEITEM)
     return 1;
 
   if (role == nsIAccessibleRole::ROLE_ROW) {
-    nsAccessible *parent = aAccessible->GetParent();
+    nsAccessible* parent = aAccessible->Parent();
     if (parent && parent->Role() == nsIAccessibleRole::ROLE_TREE_TABLE) {
       // It is a row inside flatten treegrid. Group level is always 1 until it
       // is overriden by aria-level attribute.
       return 1;
     }
   }
 
   return 0;
@@ -333,17 +335,17 @@ nsAccUtils::HasDefinedARIAToken(nsIConte
   return PR_TRUE;
 }
 
 nsAccessible *
 nsAccUtils::GetAncestorWithRole(nsAccessible *aDescendant, PRUint32 aRole)
 {
   nsAccessible *document = aDescendant->GetDocAccessible();
   nsAccessible *parent = aDescendant;
-  while ((parent = parent->GetParent())) {
+  while ((parent = parent->Parent())) {
     PRUint32 testRole = parent->Role();
     if (testRole == aRole)
       return parent;
 
     if (parent == document)
       break;
   }
   return nsnull;
@@ -354,17 +356,17 @@ nsAccUtils::GetSelectableContainer(nsAcc
 {
   if (!aAccessible)
     return nsnull;
 
   if (!(aState & states::SELECTABLE))
     return nsnull;
 
   nsAccessible* parent = aAccessible;
-  while ((parent = parent->GetParent()) && !parent->IsSelect()) {
+  while ((parent = parent->Parent()) && !parent->IsSelect()) {
     if (Role(parent) == nsIAccessibleRole::ROLE_PANE)
       return nsnull;
   }
   return parent;
 }
 
 nsAccessible*
 nsAccUtils::GetMultiSelectableContainer(nsINode* aNode)
@@ -415,17 +417,17 @@ nsAccUtils::GetTextAccessibleFromSelecti
     return nsnull;
   }
 
   do {
     nsHyperTextAccessible* textAcc = accessible->AsHyperText();
     if (textAcc)
       return textAcc;
 
-  } while (accessible = accessible->GetParent());
+  } while (accessible = accessible->Parent());
 
   NS_NOTREACHED("We must reach document accessible implementing nsIAccessibleText!");
   return nsnull;
 }
 
 nsresult
 nsAccUtils::ConvertToScreenCoords(PRInt32 aX, PRInt32 aY,
                                   PRUint32 aCoordinateType,
--- a/accessible/src/base/nsAccessibilityService.cpp
+++ b/accessible/src/base/nsAccessibilityService.cpp
@@ -103,16 +103,18 @@
 #ifndef DISABLE_XFORMS_HOOKS
 #include "nsXFormsFormControlsAccessible.h"
 #include "nsXFormsWidgetsAccessible.h"
 #endif
 
 #include "mozilla/FunctionTimer.h"
 #include "mozilla/dom/Element.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessibilityService
 ////////////////////////////////////////////////////////////////////////////////
 
 nsAccessibilityService *nsAccessibilityService::gAccessibilityService = nsnull;
 PRBool nsAccessibilityService::gIsShutdown = PR_TRUE;
 
 nsAccessibilityService::nsAccessibilityService() : nsAccDocManager()
--- a/accessible/src/base/nsAccessible.cpp
+++ b/accessible/src/base/nsAccessible.cpp
@@ -103,16 +103,17 @@
 #include "nsIDOMCharacterData.h"
 #endif
 
 #include "mozilla/unused.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/Element.h"
 
 using namespace mozilla;
+using namespace mozilla::a11y;
 
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsAccessible. nsISupports
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(nsAccessible)
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(nsAccessible, nsAccessNode)
@@ -416,18 +417,20 @@ nsAccessible::KeyboardShortcut() const
 {
   return KeyBinding();
 }
 
 NS_IMETHODIMP
 nsAccessible::GetParent(nsIAccessible **aParent)
 {
   NS_ENSURE_ARG_POINTER(aParent);
-
-  NS_IF_ADDREF(*aParent = GetParent());
+  if (IsDefunct())
+    return NS_ERROR_FAILURE;
+
+  NS_IF_ADDREF(*aParent = Parent());
   return *aParent ? NS_OK : NS_ERROR_FAILURE;
 }
 
   /* readonly attribute nsIAccessible nextSibling; */
 NS_IMETHODIMP
 nsAccessible::GetNextSibling(nsIAccessible **aNextSibling) 
 {
   NS_ENSURE_ARG_POINTER(aNextSibling);
@@ -716,32 +719,43 @@ nsAccessible::NativeState()
   if (nsCoreUtils::IsXLink(mContent))
     state |= states::LINKED;
 
   return state;
 }
 
   /* readonly attribute boolean focusedChild; */
 NS_IMETHODIMP
-nsAccessible::GetFocusedChild(nsIAccessible **aFocusedChild) 
-{ 
-  nsAccessible *focusedChild = nsnull;
-  if (gLastFocusedNode == mContent) {
-    focusedChild = this;
-  }
-  else if (gLastFocusedNode) {
-    focusedChild = GetAccService()->GetAccessible(gLastFocusedNode);
-    if (focusedChild && focusedChild->GetParent() != this)
-      focusedChild = nsnull;
-  }
-
-  NS_IF_ADDREF(*aFocusedChild = focusedChild);
+nsAccessible::GetFocusedChild(nsIAccessible** aChild)
+{
+  NS_ENSURE_ARG_POINTER(aChild);
+  *aChild = nsnull;
+
+  if (IsDefunct())
+    return NS_ERROR_FAILURE;
+
+  NS_IF_ADDREF(*aChild = FocusedChild());
   return NS_OK;
 }
 
+nsAccessible*
+nsAccessible::FocusedChild()
+{
+  if (!gLastFocusedNode)
+    return nsnull;
+  if (gLastFocusedNode == mContent)
+    return this;
+
+  nsAccessible* focusedChild = GetDocAccessible()->GetAccessible(gLastFocusedNode);
+  if (!focusedChild || focusedChild->Parent() != this)
+    return nsnull;
+
+  return focusedChild;
+}
+
 // nsAccessible::ChildAtPoint()
 nsAccessible*
 nsAccessible::ChildAtPoint(PRInt32 aX, PRInt32 aY,
                            EWhichChildAtPoint aWhichChild)
 {
   // If we can't find the point in a child, we will return the fallback answer:
   // we return |this| if the point is within it, otherwise nsnull.
   PRInt32 x = 0, y = 0, width = 0, height = 0;
@@ -814,17 +828,17 @@ nsAccessible::ChildAtPoint(PRInt32 aX, P
     // return |this| as the answer.
     return accessible;
   }
 
   // Since DOM node of obtained accessible may be out of flow then we should
   // ensure obtained accessible is a child of this accessible.
   nsAccessible* child = accessible;
   while (true) {
-    nsAccessible* parent = child->GetParent();
+    nsAccessible* parent = child->Parent();
     if (!parent) {
       // Reached the top of the hierarchy. These bounds were inside an
       // accessible that is not a descendant of this one.
       return fallbackAnswer;
     }
 
     if (parent == this)
       return aWhichChild == eDeepestChild ? accessible : child;
@@ -2135,19 +2149,18 @@ nsAccessible::GetRelationByType(PRUint32
       // ROLE_WINDOW accessible which will prevent us from going up further
       // (because it is system generated and has no idea about the hierarchy
       // above it).
       nsIFrame *frame = GetFrame();
       if (frame) {
         nsIView *view = frame->GetViewExternal();
         if (view) {
           nsIScrollableFrame *scrollFrame = do_QueryFrame(frame);
-          if (scrollFrame || view->GetWidget() || !frame->GetParent()) {
-            return nsRelUtils::AddTarget(aRelationType, aRelation, GetParent());
-          }
+          if (scrollFrame || view->GetWidget() || !frame->GetParent())
+            return nsRelUtils::AddTarget(aRelationType, aRelation, Parent());
         }
       }
 
       return rv;
     }
 
   case nsIAccessibleRelation::RELATION_CONTROLLED_BY:
     {
@@ -2610,17 +2623,17 @@ nsAccessible::AppendTextTo(nsAString& aT
     return;
 
   nsIFrame *frame = GetFrame();
   if (!frame)
     return;
 
   if (frame->GetType() == nsAccessibilityAtoms::brFrame) {
     aText += kForcedNewLineChar;
-  } else if (nsAccUtils::MustPrune(GetParent())) {
+  } else if (nsAccUtils::MustPrune(Parent())) {
     // Expose the embedded object accessible as imaginary embedded object
     // character if its parent hypertext accessible doesn't expose children to
     // AT.
     aText += kImaginaryEmbeddedObjectChar;
   } else {
     aText += kEmbeddedObjectChar;
   }
 }
@@ -3252,70 +3265,68 @@ nsAccessible::GetPositionAndSizeInternal
   }
 }
 
 PRInt32
 nsAccessible::GetLevelInternal()
 {
   PRInt32 level = nsAccUtils::GetDefaultLevel(this);
 
+  if (!IsBoundToParent())
+    return level;
+
   PRUint32 role = Role();
-  nsAccessible* parent = GetParent();
-
   if (role == nsIAccessibleRole::ROLE_OUTLINEITEM) {
     // Always expose 'level' attribute for 'outlineitem' accessible. The number
     // of nested 'grouping' accessibles containing 'outlineitem' accessible is
     // its level.
     level = 1;
 
-    while (parent) {
+    nsAccessible* parent = this;
+    while ((parent = parent->Parent())) {
       PRUint32 parentRole = parent->Role();
 
       if (parentRole == nsIAccessibleRole::ROLE_OUTLINE)
         break;
       if (parentRole == nsIAccessibleRole::ROLE_GROUPING)
         ++ level;
 
-      parent = parent->GetParent();
     }
 
   } else if (role == nsIAccessibleRole::ROLE_LISTITEM) {
     // Expose 'level' attribute on nested lists. We assume nested list is a last
     // child of listitem of parent list. We don't handle the case when nested
     // lists have more complex structure, for example when there are accessibles
     // between parent listitem and nested list.
 
     // Calculate 'level' attribute based on number of parent listitems.
     level = 0;
-
-    while (parent) {
+    nsAccessible* parent = this;
+    while ((parent = parent->Parent())) {
       PRUint32 parentRole = parent->Role();
 
       if (parentRole == nsIAccessibleRole::ROLE_LISTITEM)
         ++ level;
       else if (parentRole != nsIAccessibleRole::ROLE_LIST)
         break;
 
-      parent = parent->GetParent();
     }
 
     if (level == 0) {
       // If this listitem is on top of nested lists then expose 'level'
       // attribute.
-      nsAccessible* parent(GetParent());
+      parent = Parent();
       PRInt32 siblingCount = parent->GetChildCount();
       for (PRInt32 siblingIdx = 0; siblingIdx < siblingCount; siblingIdx++) {
         nsAccessible* sibling = parent->GetChildAt(siblingIdx);
 
-        nsCOMPtr<nsIAccessible> siblingChild;
-        sibling->GetLastChild(getter_AddRefs(siblingChild));
-        if (nsAccUtils::Role(siblingChild) == nsIAccessibleRole::ROLE_LIST) {
-          level = 1;
-          break;
-        }
+        nsAccessible* siblingChild = sibling->LastChild();
+        if (siblingChild &&
+            siblingChild->Role() == nsIAccessibleRole::ROLE_LIST)
+          return 1;
       }
     } else {
       ++ level; // level is 1-index based
     }
   }
 
   return level;
 }
--- a/accessible/src/base/nsAccessible.h
+++ b/accessible/src/base/nsAccessible.h
@@ -35,17 +35,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef _nsAccessible_H_
 #define _nsAccessible_H_
 
 #include "nsAccessNodeWrap.h"
-#include "States.h"
+#include "mozilla/a11y/States.h"
 
 #include "nsIAccessible.h"
 #include "nsIAccessibleHyperLink.h"
 #include "nsIAccessibleSelectable.h"
 #include "nsIAccessibleValue.h"
 #include "nsIAccessibleRole.h"
 #include "nsIAccessibleStates.h"
 
@@ -213,16 +213,21 @@ public:
    * @param  aY           [in] y coordinate relative screen
    * @param  aWhichChild  [in] flag points if deepest or direct child
    *                        should be returned
    */
   virtual nsAccessible* ChildAtPoint(PRInt32 aX, PRInt32 aY,
                                      EWhichChildAtPoint aWhichChild);
 
   /**
+   * Return the focused child if any.
+   */
+  virtual nsAccessible* FocusedChild();
+
+  /**
    * Return calculated group level based on accessible hierarchy.
    */
   virtual PRInt32 GetLevelInternal();
 
   /**
    * Calculate position in group and group size ('posinset' and 'setsize') based
    * on accessible hierarchy.
    *
@@ -274,17 +279,17 @@ public:
   virtual PRBool RemoveChild(nsAccessible* aChild);
 
   //////////////////////////////////////////////////////////////////////////////
   // Accessible tree traverse methods
 
   /**
    * Return parent accessible.
    */
-  nsAccessible* GetParent() const { return mParent; }
+  nsAccessible* Parent() const { return mParent; }
 
   /**
    * Return child accessible at the given index.
    */
   virtual nsAccessible* GetChildAt(PRUint32 aIndex);
 
   /**
    * Return child accessible count.
@@ -302,22 +307,30 @@ public:
   virtual PRInt32 IndexInParent() const;
 
   /**
    * Return true if accessible has children;
    */
   PRBool HasChildren() { return !!GetChildAt(0); }
 
   /**
-   * Return next/previous sibling of the accessible.
+   * Return first/last/next/previous sibling of the accessible.
    */
   inline nsAccessible* NextSibling() const
     {  return GetSiblingAtOffset(1); }
   inline nsAccessible* PrevSibling() const
     { return GetSiblingAtOffset(-1); }
+  inline nsAccessible* FirstChild()
+    { return GetChildCount() != 0 ? GetChildAt(0) : nsnull; }
+  inline nsAccessible* LastChild()
+  {
+    PRUint32 childCount = GetChildCount();
+    return childCount != 0 ? GetChildAt(childCount - 1) : nsnull;
+  }
+
 
   /**
    * Return embedded accessible children count.
    */
   PRInt32 GetEmbeddedChildCount();
 
   /**
    * Return embedded accessible child at the given index.
@@ -440,17 +453,17 @@ public:
   inline bool IsLinkValid()
   {
     NS_PRECONDITION(IsLink(), "IsLinkValid is called on not hyper link!");
 
     // XXX In order to implement this we would need to follow every link
     // Perhaps we can get information about invalid links from the cache
     // In the mean time authors can use role="link" aria-invalid="true"
     // to force it for links they internally know to be invalid
-    return (0 == (State() & states::INVALID));
+    return (0 == (State() & mozilla::a11y::states::INVALID));
   }
 
   /**
    * Return true if the link currently has the focus.
    */
   inline bool IsLinkSelected()
   {
     NS_PRECONDITION(IsLink(),
--- a/accessible/src/base/nsApplicationAccessible.cpp
+++ b/accessible/src/base/nsApplicationAccessible.cpp
@@ -48,16 +48,18 @@
 
 #include "nsIComponentManager.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMWindow.h"
 #include "nsIWindowMediator.h"
 #include "nsServiceManagerUtils.h"
 #include "mozilla/Services.h"
 
+using namespace mozilla::a11y;
+
 nsApplicationAccessible::nsApplicationAccessible() :
   nsAccessibleWrap(nsnull, nsnull)
 {
   mFlags |= eApplicationAccessible;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsISupports
--- a/accessible/src/base/nsBaseWidgetAccessible.cpp
+++ b/accessible/src/base/nsBaseWidgetAccessible.cpp
@@ -48,16 +48,18 @@
 
 #include "nsIDOMNSHTMLElement.h"
 #include "nsGUIEvent.h"
 #include "nsILink.h"
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsIURI.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsLeafAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsLeafAccessible::
   nsLeafAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
@@ -229,18 +231,18 @@ nsLinkableAccessible::BindToParent(nsAcc
     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;
-  while ((walkUpAcc = walkUpAcc->GetParent()) && !walkUpAcc->IsDoc()) {
-    if (walkUpAcc && walkUpAcc->Role() == nsIAccessibleRole::ROLE_LINK &&
+  while ((walkUpAcc = walkUpAcc->Parent()) && !walkUpAcc->IsDoc()) {
+    if (walkUpAcc->Role() == nsIAccessibleRole::ROLE_LINK &&
         walkUpAcc->State() & states::LINKED) {
       mIsLink = PR_TRUE;
       mActionAcc = walkUpAcc;
       return;
     }
 
     if (nsCoreUtils::HasClickListener(walkUpAcc->GetContent())) {
       mActionAcc = walkUpAcc;
--- a/accessible/src/base/nsDocAccessible.cpp
+++ b/accessible/src/base/nsDocAccessible.cpp
@@ -73,16 +73,17 @@
 #include "nsIWebNavigation.h"
 #include "nsFocusManager.h"
 #include "mozilla/dom/Element.h"
 #ifdef MOZ_XUL
 #include "nsIXULDocument.h"
 #endif
 
 namespace dom = mozilla::dom;
+using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // Static member initialization
 
 PRUint64 nsDocAccessible::gLastFocusedAccessiblesState = 0;
 
 static nsIAtom** kRelationAttrs[] =
 {
@@ -344,28 +345,25 @@ nsDocAccessible::GetAttributes(nsIPersis
 {
   nsAccessible::GetAttributes(aAttributes);
   if (mParent) {
     mParent->GetAttributes(aAttributes); // Add parent attributes (override inner)
   }
   return NS_OK;
 }
 
-NS_IMETHODIMP nsDocAccessible::GetFocusedChild(nsIAccessible **aFocusedChild)
+nsAccessible*
+nsDocAccessible::FocusedChild()
 {
   // XXXndeakin P3 accessibility shouldn't be caching the focus
-  if (!gLastFocusedNode) {
-    *aFocusedChild = nsnull;
-    return NS_OK;
-  }
 
   // Return an accessible for the current global focus, which does not have to
   // be contained within the current document.
-  NS_IF_ADDREF(*aFocusedChild = GetAccService()->GetAccessible(gLastFocusedNode));
-  return NS_OK;
+  return gLastFocusedNode ? GetAccService()->GetAccessible(gLastFocusedNode) :
+    nsnull;
 }
 
 NS_IMETHODIMP nsDocAccessible::TakeFocus()
 {
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   PRUint64 state = NativeState();
@@ -576,17 +574,17 @@ nsDocAccessible::GetAccessible(nsINode* 
     accessible = const_cast<nsDocAccessible*>(this);
   }
 
 #ifdef DEBUG
   // All cached accessible nodes should be in the parent
   // It will assert if not all the children were created
   // when they were first cached, and no invalidation
   // ever corrected parent accessible's child cache.
-  nsAccessible* parent(accessible->GetParent());
+  nsAccessible* parent = accessible->Parent();
   if (parent)
     parent->TestChildCache(accessible);
 #endif
 
   return accessible;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -1482,18 +1480,18 @@ nsDocAccessible::NotifyOfInitialUpdate()
   CacheChildrenInSubtree(this);
 
   // Fire reorder event after the document tree is constructed. Note, since
   // this reorder event is processed by parent document then events targeted to
   // this document may be fired prior to this reorder event. If this is
   // a problem then consider to keep event processing per tab document.
   if (!IsRoot()) {
     nsRefPtr<AccEvent> reorderEvent =
-      new AccEvent(nsIAccessibleEvent::EVENT_REORDER, GetParent(),
-                   eAutoDetect, AccEvent::eCoalesceFromSameSubtree);
+      new AccEvent(nsIAccessibleEvent::EVENT_REORDER, Parent(), eAutoDetect,
+                   AccEvent::eCoalesceFromSameSubtree);
     ParentDocument()->FireDelayedAccessibleEvent(reorderEvent);
   }
 }
 
 void
 nsDocAccessible::AddDependentIDsFor(nsAccessible* aRelProvider,
                                     nsIAtom* aRelAttr)
 {
@@ -1812,17 +1810,17 @@ nsDocAccessible::UpdateTree(nsAccessible
                                    ancestor->GetNode());
         break;
       }
 
       // Don't climb above this document.
       if (ancestor == this)
         break;
 
-      ancestor = ancestor->GetParent();
+      ancestor = ancestor->Parent();
     }
   }
 
   // Fire value change event.
   if (aContainer->Role() == nsIAccessibleRole::ROLE_ENTRY) {
     FireDelayedAccessibleEvent(nsIAccessibleEvent::EVENT_VALUE_CHANGE,
                                aContainer->GetNode());
   }
@@ -1897,17 +1895,17 @@ nsDocAccessible::UpdateTreeInternal(nsAc
       FireDelayedAccessibleEvent(nsIAccessibleEvent::EVENT_FOCUS,
                                  node, AccEvent::eCoalesceFromSameDocument);
     }
   } else {
     // Update the tree for content removal.
     // The accessible parent may differ from container accessible if
     // the parent doesn't have own DOM node like list accessible for HTML
     // selects.
-    nsAccessible* parent = aChild->GetParent();
+    nsAccessible* parent = aChild->Parent();
     NS_ASSERTION(parent, "No accessible parent?!");
     if (parent)
       parent->RemoveChild(aChild);
 
     UncacheChildrenInSubtree(aChild);
   }
 
   return updateFlags;
--- a/accessible/src/base/nsDocAccessible.h
+++ b/accessible/src/base/nsDocAccessible.h
@@ -89,17 +89,16 @@ public:
 
   nsDocAccessible(nsIDocument *aDocument, nsIContent *aRootContent,
                   nsIWeakReference* aShell);
   virtual ~nsDocAccessible();
 
   // nsIAccessible
   NS_IMETHOD GetName(nsAString& aName);
   NS_IMETHOD GetAttributes(nsIPersistentProperties **aAttributes);
-  NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
   NS_IMETHOD TakeFocus(void);
 
   // nsIScrollPositionListener
   virtual void ScrollPositionWillChange(nscoord aX, nscoord aY) {}
   virtual void ScrollPositionDidChange(nscoord aX, nscoord aY);
 
   // nsIDocumentObserver
   NS_DECL_NSIDOCUMENTOBSERVER
@@ -109,16 +108,17 @@ public:
   virtual void Shutdown();
   virtual nsIFrame* GetFrame() const;
   virtual bool IsDefunct() const;
   virtual nsINode* GetNode() const { return mDocument; }
   virtual nsIDocument* GetDocumentNode() const { return mDocument; }
 
   // nsAccessible
   virtual void Description(nsString& aDescription);
+  virtual nsAccessible* FocusedChild();
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual void ApplyARIAState(PRUint64* aState);
 
   virtual void SetRoleMapEntry(nsRoleMapEntry* aRoleMapEntry);
 
 #ifdef DEBUG_ACCDOCMGR
   virtual nsresult HandleAccEvent(AccEvent* aAccEvent);
--- a/accessible/src/base/nsOuterDocAccessible.cpp
+++ b/accessible/src/base/nsOuterDocAccessible.cpp
@@ -37,16 +37,18 @@
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsOuterDocAccessible.h"
 
 #include "States.h"
 #include "nsAccUtils.h"
 #include "nsDocAccessible.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsOuterDocAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsOuterDocAccessible::
   nsOuterDocAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/base/nsRootAccessible.cpp
+++ b/accessible/src/base/nsRootAccessible.cpp
@@ -81,16 +81,17 @@
 
 #ifdef MOZ_XUL
 #include "nsXULTreeAccessible.h"
 #include "nsIXULDocument.h"
 #include "nsIXULWindow.h"
 #endif
 
 using namespace mozilla;
+using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsISupports
 
 // Expanded version of NS_IMPL_ISUPPORTS_INHERITED2 
 // so we can QI directly to concrete nsRootAccessible
 NS_IMPL_QUERY_HEAD(nsRootAccessible)
 NS_IMPL_QUERY_BODY(nsIDOMEventListener)
@@ -694,24 +695,24 @@ nsRootAccessible::ProcessDOMEvent(nsIDOM
         fireFocus = PR_TRUE;
       // QI failed for nsMenuFrame means it's not on menu bar
       if (menuFrame && menuFrame->IsOnMenuBar() &&
                        !menuFrame->IsOnActiveMenuBar()) {
         // It is a top level menuitem. Only fire a focus event when the menu bar
         // is active.
         return;
       } else {
-        nsAccessible *containerAccessible = accessible->GetParent();
-        if (!containerAccessible)
+        nsAccessible* container = accessible->Parent();
+        if (!container)
           return;
         // It is not top level menuitem
         // Only fire focus event if it is not inside collapsed popup
         // and not a listitem of a combo box
-        if (containerAccessible->State() & states::COLLAPSED) {
-          nsAccessible *containerParent = containerAccessible->GetParent();
+        if (container->State() & states::COLLAPSED) {
+          nsAccessible* containerParent = container->Parent();
           if (!containerParent)
             return;
           if (containerParent->Role() != nsIAccessibleRole::ROLE_COMBOBOX) {
             return;
           }
         }
       }
     }
@@ -791,25 +792,25 @@ nsRootAccessible::GetContentDocShell(nsI
     // Hidden documents don't have accessibles (like SeaMonkey's sidebar),
     // they are of no interest for a11y.
     if (!accDoc)
       return nsnull;
 
     // If ancestor chain of accessibles is not completely visible,
     // don't use this one. This happens for example if it's inside
     // a background tab (tabbed browsing)
-    nsAccessible *parent = accDoc->GetParent();
+    nsAccessible* parent = accDoc->Parent();
     while (parent) {
       if (parent->State() & states::INVISIBLE)
         return nsnull;
 
       if (parent == this)
         break; // Don't check past original root accessible we started with
 
-      parent = parent->GetParent();
+      parent = parent->Parent();
     }
 
     NS_ADDREF(aStart);
     return aStart;
   }
   nsCOMPtr<nsIDocShellTreeNode> treeNode(do_QueryInterface(aStart));
   if (treeNode) {
     PRInt32 subDocuments;
@@ -873,17 +874,17 @@ nsRootAccessible::HandlePopupShownEvent(
     // AT's expect to get an EVENT_SHOW for the tooltip. 
     // In event callback the tooltip's accessible will be ready.
     nsEventShell::FireEvent(nsIAccessibleEvent::EVENT_SHOW, aAccessible);
     return;
   }
 
   if (role == nsIAccessibleRole::ROLE_COMBOBOX_LIST) {
     // Fire expanded state change event for comboboxes and autocompeletes.
-    nsAccessible* combobox = aAccessible->GetParent();
+    nsAccessible* combobox = aAccessible->Parent();
     if (!combobox)
       return;
 
     PRUint32 comboboxRole = combobox->Role();
     if (comboboxRole == nsIAccessibleRole::ROLE_COMBOBOX ||
         comboboxRole == nsIAccessibleRole::ROLE_AUTOCOMPLETE) {
       nsRefPtr<AccEvent> event =
         new AccStateChangeEvent(combobox, states::EXPANDED, PR_TRUE);
@@ -909,17 +910,17 @@ nsRootAccessible::HandlePopupHidingEvent
     FireCurrentFocusEvent();
   }
 
   // Fire expanded state change event for comboboxes and autocompletes.
   if (!aAccessible ||
       aAccessible->Role() != nsIAccessibleRole::ROLE_COMBOBOX_LIST)
     return;
 
-  nsAccessible* combobox = aAccessible->GetParent();
+  nsAccessible* combobox = aAccessible->Parent();
   if (!combobox)
     return;
 
   PRUint32 comboboxRole = combobox->Role();
   if (comboboxRole == nsIAccessibleRole::ROLE_COMBOBOX ||
       comboboxRole == nsIAccessibleRole::ROLE_AUTOCOMPLETE) {
     nsRefPtr<AccEvent> event =
       new AccStateChangeEvent(combobox, states::EXPANDED, PR_FALSE);
--- a/accessible/src/html/nsHTMLFormControlAccessible.cpp
+++ b/accessible/src/html/nsHTMLFormControlAccessible.cpp
@@ -55,16 +55,18 @@
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsISelectionController.h"
 #include "jsapi.h"
 #include "nsIJSContextStack.h"
 #include "nsIServiceManager.h"
 #include "nsITextControlFrame.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLCheckboxAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLCheckboxAccessible::
   nsHTMLCheckboxAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsFormControlAccessible(aContent, aShell)
 {
@@ -402,18 +404,19 @@ nsHTMLTextFieldAccessible::GetNameIntern
 
   if (mContent->GetBindingParent())
   {
     // XXX: bug 459640
     // There's a binding parent.
     // This means we're part of another control, so use parent accessible for name.
     // This ensures that a textbox inside of a XUL widget gets
     // an accessible name.
-    nsAccessible* parent = GetParent();
-    parent->GetName(aName);
+    nsAccessible* parent = Parent();
+    if (parent)
+      parent->GetName(aName);
   }
 
   if (!aName.IsEmpty())
     return NS_OK;
 
   // text inputs and textareas might have useful placeholder text
   mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::placeholder, aName);
 
@@ -447,17 +450,17 @@ nsHTMLTextFieldAccessible::NativeState()
   PRUint64 state = nsHyperTextAccessibleWrap::NativeState();
 
   // can be focusable, focused, protected. readonly, unavailable, selected
   if (mContent->AttrValueIs(kNameSpaceID_None, nsAccessibilityAtoms::type,
                             nsAccessibilityAtoms::password, eIgnoreCase)) {
     state |= states::PROTECTED;
   }
   else {
-    nsAccessible* parent = GetParent();
+    nsAccessible* parent = Parent();
     if (parent && parent->Role() == nsIAccessibleRole::ROLE_AUTOCOMPLETE)
       state |= states::HASPOPUP;
   }
 
   if (mContent->HasAttr(kNameSpaceID_None, nsAccessibilityAtoms::readonly)) {
     state |= states::READONLY;
   }
 
@@ -645,17 +648,17 @@ nsHTMLLegendAccessible::GetRelationByTyp
                                           nsIAccessibleRelation **aRelation)
 {
   nsresult rv = nsHyperTextAccessibleWrap::
     GetRelationByType(aRelationType, aRelation);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (aRelationType == nsIAccessibleRelation::RELATION_LABEL_FOR) {
     // Look for groupbox parent
-    nsAccessible* groupbox = GetParent();
+    nsAccessible* groupbox = Parent();
 
     if (groupbox && groupbox->Role() == nsIAccessibleRole::ROLE_GROUPING) {
       // XXX: if group box exposes more than one relation of the given type
       // then we fail.
       nsCOMPtr<nsIAccessible> testLabelAccessible =
         nsRelUtils::GetRelatedAccessible(groupbox,
                                          nsIAccessibleRelation::RELATION_LABELLED_BY);
 
--- a/accessible/src/html/nsHTMLImageAccessible.cpp
+++ b/accessible/src/html/nsHTMLImageAccessible.cpp
@@ -48,16 +48,18 @@
 #include "nsIImageLoadingContent.h"
 #include "nsILink.h"
 #include "nsIPresShell.h"
 #include "nsIServiceManager.h"
 #include "nsIDOMHTMLImageElement.h"
 #include "nsIDOMDocument.h"
 #include "nsPIDOMWindow.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLImageAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLImageAccessible::
   nsHTMLImageAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsLinkableAccessible(aContent, aShell)
 {
--- a/accessible/src/html/nsHTMLLinkAccessible.cpp
+++ b/accessible/src/html/nsHTMLLinkAccessible.cpp
@@ -40,16 +40,18 @@
 #include "nsHTMLLinkAccessible.h"
 
 #include "States.h"
 #include "nsCoreUtils.h"
 
 #include "nsEventStates.h"
 #include "mozilla/dom/Element.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLLinkAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLLinkAccessible::
   nsHTMLLinkAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsHyperTextAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/html/nsHTMLSelectAccessible.cpp
+++ b/accessible/src/html/nsHTMLSelectAccessible.cpp
@@ -52,16 +52,18 @@
 #include "nsIDocument.h"
 #include "nsIDOMHTMLInputElement.h"
 #include "nsIDOMHTMLOptGroupElement.h"
 #include "nsIDOMHTMLSelectElement.h"
 #include "nsIListControlFrame.h"
 #include "nsIServiceManager.h"
 #include "nsIMutableArray.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLSelectListAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLSelectListAccessible::
   nsHTMLSelectListAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
@@ -295,17 +297,17 @@ nsHTMLSelectOptionAccessible::NativeStat
       state |= selectState & states::OPAQUE1;
     }
   }
   else {
     // XXX list frames are weird, don't rely on nsAccessible's general
     // visibility implementation unless they get reimplemented in layout
     state &= ~states::OFFSCREEN;
     // <select> is not collapsed: compare bounds to calculate OFFSCREEN
-    nsAccessible* listAcc = GetParent();
+    nsAccessible* listAcc = Parent();
     if (listAcc) {
       PRInt32 optionX, optionY, optionWidth, optionHeight;
       PRInt32 listX, listY, listWidth, listHeight;
       GetBounds(&optionX, &optionY, &optionWidth, &optionHeight);
       listAcc->GetBounds(&listX, &listY, &listWidth, &listHeight);
       if (optionY < listY || optionY + optionHeight > listY + listHeight) {
         state |= states::OFFSCREEN;
       }
@@ -377,18 +379,19 @@ NS_IMETHODIMP nsHTMLSelectOptionAccessib
 
 NS_IMETHODIMP nsHTMLSelectOptionAccessible::DoAction(PRUint8 index)
 {
   if (index == eAction_Select) {   // default action
     nsCOMPtr<nsIDOMHTMLOptionElement> newHTMLOption(do_QueryInterface(mContent));
     if (!newHTMLOption) 
       return NS_ERROR_FAILURE;
     // Clear old selection
-    nsAccessible* parent = GetParent();
-    NS_ASSERTION(parent, "No parent!");
+    nsAccessible* parent = Parent();
+    if (!parent)
+      return NS_OK;
 
     nsCOMPtr<nsIContent> oldHTMLOptionContent =
       GetFocusedOption(parent->GetContent());
     nsCOMPtr<nsIDOMHTMLOptionElement> oldHTMLOption =
       do_QueryInterface(oldHTMLOptionContent);
     if (oldHTMLOption)
       oldHTMLOption->SetSelected(PR_FALSE);
     // Set new selection
@@ -886,17 +889,17 @@ nsHTMLComboboxListAccessible::NativeStat
 /**
   * Gets the bounds for the areaFrame.
   *     Walks the Frame tree and checks for proper frames.
   */
 void nsHTMLComboboxListAccessible::GetBoundsRect(nsRect& aBounds, nsIFrame** aBoundingFrame)
 {
   *aBoundingFrame = nsnull;
 
-  nsAccessible* comboAcc = GetParent();
+  nsAccessible* comboAcc = Parent();
   if (!comboAcc)
     return;
 
   if (0 == (comboAcc->State() & states::COLLAPSED)) {
     nsHTMLSelectListAccessible::GetBoundsRect(aBounds, aBoundingFrame);
     return;
   }
 
--- a/accessible/src/html/nsHTMLTableAccessible.cpp
+++ b/accessible/src/html/nsHTMLTableAccessible.cpp
@@ -61,16 +61,18 @@
 #include "nsIDocument.h"
 #include "nsIPresShell.h"
 #include "nsITableLayout.h"
 #include "nsITableCellLayout.h"
 #include "nsFrameSelection.h"
 #include "nsLayoutErrors.h"
 #include "nsArrayUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLTableCellAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLTableCellAccessible::
   nsHTMLTableCellAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsHyperTextAccessibleWrap(aContent, aShell)
 {
@@ -261,17 +263,17 @@ nsHTMLTableCellAccessible::IsSelected(PR
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLTableCellAccessible: protected implementation
 
 already_AddRefed<nsIAccessibleTable>
 nsHTMLTableCellAccessible::GetTableAccessible()
 {
   nsAccessible* parent = this;
-  while ((parent = parent->GetParent())) {
+  while ((parent = parent->Parent())) {
     PRUint32 role = parent->Role();
     if (role == nsIAccessibleRole::ROLE_TABLE ||
         role == nsIAccessibleRole::ROLE_TREE_TABLE) {
       nsIAccessibleTable* tableAcc = nsnull;
       CallQueryInterface(parent, &tableAcc);
       return tableAcc;
     }
   }
@@ -1523,18 +1525,19 @@ nsHTMLTableAccessible::IsProbablyForLayo
 NS_IMETHODIMP
 nsHTMLCaptionAccessible::GetRelationByType(PRUint32 aRelationType,
                                            nsIAccessibleRelation **aRelation)
 {
   nsresult rv = nsHyperTextAccessible::GetRelationByType(aRelationType,
                                                          aRelation);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (aRelationType == nsIAccessibleRelation::RELATION_LABEL_FOR)
-    return nsRelUtils::AddTarget(aRelationType, aRelation, GetParent());
+  if (aRelationType == nsIAccessibleRelation::RELATION_LABEL_FOR) {
+      return nsRelUtils::AddTarget(aRelationType, aRelation, Parent());
+  }
 
   return NS_OK;
 }
 
 PRUint32
 nsHTMLCaptionAccessible::NativeRole()
 {
   return nsIAccessibleRole::ROLE_CAPTION;
--- a/accessible/src/html/nsHTMLTextAccessible.cpp
+++ b/accessible/src/html/nsHTMLTextAccessible.cpp
@@ -47,16 +47,18 @@
 
 #include "nsIFrame.h"
 #include "nsPresContext.h"
 #include "nsBlockFrame.h"
 #include "nsISelection.h"
 #include "nsISelectionController.h"
 #include "nsComponentManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLTextAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLTextAccessible::
   nsHTMLTextAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsTextAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/html/nsHyperTextAccessible.cpp
+++ b/accessible/src/html/nsHyperTextAccessible.cpp
@@ -61,16 +61,18 @@
 #include "nsIPlaintextEditor.h"
 #include "nsIScrollableFrame.h"
 #include "nsISelection2.h"
 #include "nsISelectionPrivate.h"
 #include "nsIServiceManager.h"
 #include "nsTextFragment.h"
 #include "gfxSkipChars.h"
 
+using namespace mozilla::a11y;
+
 static NS_DEFINE_IID(kRangeCID, NS_RANGE_CID);
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsHyperTextAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHyperTextAccessible::
   nsHyperTextAccessible(nsIContent *aNode, nsIWeakReference *aShell) :
@@ -616,19 +618,19 @@ nsHyperTextAccessible::DOMPointToHyperte
       // This <br> is the hacky "bogus node" used when there is no text in a control
       *aHyperTextOffset = 0;
       return nsnull;
     }
     descendantAcc = GetFirstAvailableAccessible(findNode);
   }
 
   // From the descendant, go up and get the immediate child of this hypertext
-  nsAccessible *childAccAtOffset = nsnull;
+  nsAccessible* childAccAtOffset = nsnull;
   while (descendantAcc) {
-    nsAccessible *parentAcc = descendantAcc->GetParent();
+    nsAccessible* parentAcc = descendantAcc->Parent();
     if (parentAcc == this) {
       childAccAtOffset = descendantAcc;
       break;
     }
 
     // This offset no longer applies because the passed-in text object is not a child
     // of the hypertext. This happens when there are nested hypertexts, e.g.
     // <div>abc<h1>def</h1>ghi</div>
--- a/accessible/src/mac/mozAccessible.mm
+++ b/accessible/src/mac/mozAccessible.mm
@@ -47,16 +47,18 @@
 #include "nsObjCExceptions.h"
 
 #include "nsIAccessible.h"
 #include "nsIAccessibleText.h"
 #include "nsIAccessibleEditableText.h"
 
 #include "nsRootAccessible.h"
 
+using namespace mozilla::a11y;
+
 // These constants are only defined in OS X SDK 10.4, so we define them in order
 // to be able to use for earlier OS versions.
 const NSString *kInstanceDescriptionAttribute = @"AXDescription";       // NSAccessibilityDescriptionAttribute
 const NSString *kTopLevelUIElementAttribute   = @"AXTopLevelUIElement"; // NSAccessibilityTopLevelUIElementAttribute
 const NSString *kTextLinkSubrole              = @"AXTextLink";          // NSAccessibilitySecureTextFieldSubrole
 const NSString *kURLAttribute                 = @"AXURL";
 
 // converts a screen-global point in the cocoa coordinate system (with origo in the bottom-left corner
@@ -329,19 +331,17 @@ GetNativeFromGeckoAccessible(nsIAccessib
 {
 }
 
 - (id)accessibilityFocusedUIElement
 {
   if (mIsExpired)
     return nil;
   
-  nsCOMPtr<nsIAccessible> focusedGeckoChild;
-  mGeckoAccessible->GetFocusedChild (getter_AddRefs (focusedGeckoChild));
-  
+  nsAccessible* focusedGeckoChild = mGeckoAccessible->FocusedChild();
   if (focusedGeckoChild) {
     mozAccessible *focusedChild = GetNativeFromGeckoAccessible(focusedGeckoChild);
     if (focusedChild)
       return GetClosestInterestingAccessible(focusedChild);
   }
   
   // return ourself if we can't get a native focused child.
   return GetClosestInterestingAccessible(self);
--- a/accessible/src/mac/mozActionElements.mm
+++ b/accessible/src/mac/mozActionElements.mm
@@ -36,16 +36,18 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #import "mozActionElements.h"
 #import "nsIAccessible.h"
 
 #include "nsObjCExceptions.h"
 
+using namespace mozilla::a11y;
+
 extern const NSString *kInstanceDescriptionAttribute; // NSAccessibilityDescriptionAttribute
 extern const NSString *kTopLevelUIElementAttribute;   // NSAccessibilityTopLevelUIElementAttribute
 
 enum CheckboxValue {
   // these constants correspond to the values in the OS
   kUnchecked = 0,
   kChecked = 1,
   kMixed = 2
--- a/accessible/src/mac/mozTextAccessible.mm
+++ b/accessible/src/mac/mozTextAccessible.mm
@@ -1,13 +1,15 @@
 #include "nsAccessibleWrap.h"
 #include "nsObjCExceptions.h"
 
 #import "mozTextAccessible.h"
 
+using namespace mozilla::a11y;
+
 extern const NSString *kInstanceDescriptionAttribute; // NSAccessibilityDescriptionAttribute
 extern const NSString *kTopLevelUIElementAttribute;   // NSAccessibilityTopLevelUIElementAttribute
 
 @interface mozTextAccessible (Private)
 - (NSString*)subrole;
 - (NSString*)selectedText;
 - (NSValue*)selectedTextRange;
 - (long)textLength;
--- a/accessible/src/mac/nsAccessibleWrap.h
+++ b/accessible/src/mac/nsAccessibleWrap.h
@@ -81,17 +81,17 @@ class nsAccessibleWrap : public nsAccess
 
     // ignored means that the accessible might still have children, but is not displayed
     // to the user. it also has no native accessible object represented for it.
     PRBool IsIgnored();
     
     PRInt32 GetUnignoredChildCount(PRBool aDeepCount);
     
     PRBool HasPopup () {
-      return (NativeState() & states::HASPOPUP);
+      return (NativeState() & mozilla::a11y::states::HASPOPUP);
     }
     
     // return this accessible's all children, adhering to "flat" accessibles by not returning their children.
     void GetUnignoredChildren(nsTArray<nsRefPtr<nsAccessibleWrap> > &aChildrenArray);
     virtual already_AddRefed<nsIAccessible> GetUnignoredParent();
     
   protected:
 
--- a/accessible/src/mac/nsAccessibleWrap.mm
+++ b/accessible/src/mac/nsAccessibleWrap.mm
@@ -280,17 +280,17 @@ nsAccessibleWrap::GetUnignoredChildren(n
       // simply add the element, since it's not ignored.
       aChildrenArray.AppendElement(childAcc);
   }
 }
 
 already_AddRefed<nsIAccessible>
 nsAccessibleWrap::GetUnignoredParent()
 {
-  nsAccessibleWrap *parentWrap = static_cast<nsAccessibleWrap*>(GetParent());
+  nsAccessibleWrap* parentWrap = static_cast<nsAccessibleWrap*>(Parent());
   if (!parentWrap)
     return nsnull;
     
   // recursively return the parent, until we find one that is not ignored.
   if (parentWrap->IsIgnored())
     return parentWrap->GetUnignoredParent();
   
   nsIAccessible *outValue = nsnull;
@@ -308,18 +308,18 @@ nsAccessibleWrap::AncestorIsFlat()
   // We don't create a native object if we're child of a "flat" accessible;
   // for example, on OS X buttons shouldn't have any children, because that
   // makes the OS confused. 
   //
   // To maintain a scripting environment where the XPCOM accessible hierarchy
   // look the same on all platforms, we still let the C++ objects be created
   // though.
 
-  nsAccessible* parent(GetParent());
+  nsAccessible* parent = Parent();
   while (parent) {
     if (nsAccUtils::MustPrune(parent))
       return PR_TRUE;
 
-    parent = parent->GetParent();
+    parent = parent->Parent();
   }
   // no parent was flat
   return PR_FALSE;
 }
--- a/accessible/src/msaa/CAccessibleComponent.cpp
+++ b/accessible/src/msaa/CAccessibleComponent.cpp
@@ -45,16 +45,18 @@
 #include "nsAccessible.h"
 #include "States.h"
 
 #include "nsString.h"
 
 #include "nsIDOMCSSPrimitiveValue.h"
 #include "nsIDOMNSRGBAColor.h"
 
+using namespace mozilla::a11y;
+
 enum {
   IA2AlphaShift = 24,
   IA2RedShift = 16,
   IA2GreenShift = 8,
   IA2BlueShift = 0
 };
 
 // IUnknown
--- a/accessible/src/msaa/nsAccessNodeWrap.h
+++ b/accessible/src/msaa/nsAccessNodeWrap.h
@@ -56,19 +56,16 @@
 #include "nsIWinAccessNode.h"
 #include "ISimpleDOMNode.h"
 #include "nsIDOMElement.h"
 #include "nsIContent.h"
 #include "nsAccessNode.h"
 #include "OLEIDL.H"
 #include "OLEACC.H"
 #include <winuser.h>
-#ifndef WINABLEAPI
-#include <winable.h>
-#endif
 #ifdef MOZ_CRASHREPORTER
 #include "nsICrashReporter.h"
 #endif
 
 #include "nsRefPtrHashtable.h"
 
 typedef LRESULT (STDAPICALLTYPE *LPFNNOTIFYWINEVENT)(DWORD event,HWND hwnd,LONG idObjectType,LONG idObject);
 typedef LRESULT (STDAPICALLTYPE *LPFNGETGUITHREADINFO)(DWORD idThread, GUITHREADINFO* pgui);
--- a/accessible/src/msaa/nsAccessibleWrap.cpp
+++ b/accessible/src/msaa/nsAccessibleWrap.cpp
@@ -62,16 +62,18 @@
 #include "nsIServiceManager.h"
 #include "nsTextFormatter.h"
 #include "nsIView.h"
 #include "nsIViewManager.h"
 #include "nsRoleMap.h"
 #include "nsEventMap.h"
 #include "nsArrayUtils.h"
 
+using namespace mozilla::a11y;
+
 /* For documentation of the accessibility architecture,
  * see http://lxr.mozilla.org/seamonkey/source/accessible/accessible-docs.html
  */
 
 //#define DEBUG_LEAKS
 
 #ifdef DEBUG_LEAKS
 static gAccessibles = 0;
@@ -209,17 +211,17 @@ STDMETHODIMP nsAccessibleWrap::get_accPa
       if (hwnd && SUCCEEDED(AccessibleObjectFromWindow(hwnd, OBJID_WINDOW,
                                                        IID_IAccessible,
                                                        (void**)ppdispParent))) {
         return S_OK;
       }
     }
   }
 
-  nsAccessible* xpParentAcc = GetParent();
+  nsAccessible* xpParentAcc = Parent();
   if (!xpParentAcc) {
     if (IsApplication())
       return S_OK;
 
     NS_ERROR("No parent accessible. Should we really assert here?");
     return E_UNEXPECTED;
   }
 
@@ -369,17 +371,17 @@ STDMETHODIMP nsAccessibleWrap::get_accRo
   PRUint32 msaaRole = gWindowsRoleMap[xpRole].msaaRole;
   NS_ASSERTION(gWindowsRoleMap[nsIAccessibleRole::ROLE_LAST_ENTRY].msaaRole == ROLE_WINDOWS_LAST_ENTRY,
                "MSAA role map skewed");
 
   // Special case, if there is a ROLE_ROW inside of a ROLE_TREE_TABLE, then call the MSAA role
   // a ROLE_OUTLINEITEM for consistency and compatibility.
   // We need this because ARIA has a role of "row" for both grid and treegrid
   if (xpRole == nsIAccessibleRole::ROLE_ROW) {
-    nsAccessible* xpParent = GetParent();
+    nsAccessible* xpParent = Parent();
     if (xpParent && xpParent->Role() == nsIAccessibleRole::ROLE_TREE_TABLE)
       msaaRole = ROLE_SYSTEM_OUTLINEITEM;
   }
   
   // -- Try enumerated role
   if (msaaRole != USE_ROLE_STRING) {
     pvarRole->vt = VT_I4;
     pvarRole->lVal = msaaRole;  // Normal enumerated role
@@ -517,18 +519,17 @@ STDMETHODIMP nsAccessibleWrap::get_accFo
   //              for the child object with the keyboard focus.
 __try {
   if (IsDefunct())
     return E_FAIL;
 
   VariantInit(pvarChild);
 
   // Return the current IAccessible child that has focus
-  nsCOMPtr<nsIAccessible> focusedAccessible;
-  GetFocusedChild(getter_AddRefs(focusedAccessible));
+  nsAccessible* focusedAccessible = FocusedChild();
   if (focusedAccessible == this) {
     pvarChild->vt = VT_I4;
     pvarChild->lVal = CHILDID_SELF;
   }
   else if (focusedAccessible) {
     pvarChild->vt = VT_DISPATCH;
     pvarChild->pdispVal = NativeAccessible(focusedAccessible);
   }
@@ -1155,17 +1156,17 @@ nsAccessibleWrap::role(long *aRole)
                "MSAA role map skewed");
 
   PRUint32 xpRole = Role();
   *aRole = gWindowsRoleMap[xpRole].ia2Role;
 
   // Special case, if there is a ROLE_ROW inside of a ROLE_TREE_TABLE, then call
   // the IA2 role a ROLE_OUTLINEITEM.
   if (xpRole == nsIAccessibleRole::ROLE_ROW) {
-    nsAccessible* xpParent = GetParent();
+    nsAccessible* xpParent = Parent();
     if (xpParent && xpParent->Role() == nsIAccessibleRole::ROLE_TREE_TABLE)
       *aRole = ROLE_SYSTEM_OUTLINEITEM;
   }
 
   return S_OK;
 
 } __except(nsAccessNodeWrap::FilterA11yExceptions(::GetExceptionCode(), GetExceptionInformation())) { }
   return E_FAIL;
@@ -1763,22 +1764,22 @@ nsAccessibleWrap::GetXPAccessibleFor(con
     // ARIA document.
     if (ARIARole() == nsIAccessibleRole::ROLE_DOCUMENT) {
       nsDocAccessible* document = GetDocAccessible();
       nsAccessible* child =
         document->GetAccessibleByUniqueIDInSubtree(uniqueID);
 
       // Check whether the accessible for the given ID is a child of ARIA
       // document.
-      nsAccessible* parent = child ? child->GetParent() : nsnull;
+      nsAccessible* parent = child ? child->Parent() : nsnull;
       while (parent && parent != document) {
         if (parent == this)
           return child;
 
-        parent = parent->GetParent();
+        parent = parent->Parent();
       }
     }
 
     return nsnull;
   }
 
   // Gecko child indices are 0-based in contrast to indices used in MSAA.
   return GetChildAt(aVarChild.lVal - 1);
--- a/accessible/src/msaa/nsEventMap.h
+++ b/accessible/src/msaa/nsEventMap.h
@@ -34,19 +34,16 @@
  * 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 ***** */
 
 #include <winuser.h>
-#ifndef WINABLEAPI
-#include <winable.h>
-#endif
 #include "AccessibleEventId.h"
 
 const PRUint32 kEVENT_WIN_UNKNOWN = 0x00000000;
 const PRUint32 kEVENT_LAST_ENTRY  = 0xffffffff;
 
 static const PRUint32 gWinEventMap[] = {
   kEVENT_WIN_UNKNOWN,                                // nsIAccessibleEvent doesn't have 0 constant
   EVENT_OBJECT_SHOW,                                 // nsIAccessibleEvent::EVENT_SHOW
--- a/accessible/src/msaa/nsHTMLWin32ObjectAccessible.cpp
+++ b/accessible/src/msaa/nsHTMLWin32ObjectAccessible.cpp
@@ -35,16 +35,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsHTMLWin32ObjectAccessible.h"
 
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsHTMLWin32ObjectOwnerAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsHTMLWin32ObjectOwnerAccessible::
   nsHTMLWin32ObjectOwnerAccessible(nsIContent *aContent,
                                    nsIWeakReference *aShell, void *aHwnd) :
   nsAccessibleWrap(aContent, aShell), mHwnd(aHwnd)
--- a/accessible/src/xforms/nsXFormsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsAccessible.cpp
@@ -47,16 +47,18 @@
 #include "nsServiceManagerUtils.h"
 #include "nsIDOMElement.h"
 #include "nsIDOMNodeList.h"
 #include "nsIEditor.h"
 #include "nsIMutableArray.h"
 #include "nsIXFormsUtilityService.h"
 #include "nsIPlaintextEditor.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXFormsAccessibleBase
 ////////////////////////////////////////////////////////////////////////////////
 
 nsIXFormsUtilityService *nsXFormsAccessibleBase::sXFormsService = nsnull;
 
 nsXFormsAccessibleBase::nsXFormsAccessibleBase()
 {
--- a/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsFormControlsAccessible.cpp
@@ -36,16 +36,18 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsXFormsFormControlsAccessible.h"
 
 #include "States.h"
 #include "nsTextEquivUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXFormsLabelAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXFormsLabelAccessible::
   nsXFormsLabelAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsXFormsAccessible(aContent, aShell)
 {
--- a/accessible/src/xforms/nsXFormsWidgetsAccessible.cpp
+++ b/accessible/src/xforms/nsXFormsWidgetsAccessible.cpp
@@ -35,16 +35,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsXFormsWidgetsAccessible.h"
 
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXFormsDropmarkerWidgetAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXFormsDropmarkerWidgetAccessible::
   nsXFormsDropmarkerWidgetAccessible(nsIContent *aContent,
                                      nsIWeakReference *aShell) :
   nsLeafAccessible(aContent, aShell)
--- a/accessible/src/xul/nsXULAlertAccessible.cpp
+++ b/accessible/src/xul/nsXULAlertAccessible.cpp
@@ -34,16 +34,18 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #include "nsXULAlertAccessible.h"
 
 #include "States.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULAlertAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULAlertAccessible::
   nsXULAlertAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULColorPickerAccessible.cpp
+++ b/accessible/src/xul/nsXULColorPickerAccessible.cpp
@@ -41,16 +41,17 @@
 #include "States.h"
 #include "nsAccUtils.h"
 #include "nsAccTreeWalker.h"
 #include "nsCoreUtils.h"
 #include "nsDocAccessible.h"
 
 #include "nsIDOMElement.h"
 
+using namespace mozilla::a11y;
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULColorPickerTileAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULColorPickerTileAccessible::
   nsXULColorPickerTileAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
--- a/accessible/src/xul/nsXULComboboxAccessible.cpp
+++ b/accessible/src/xul/nsXULComboboxAccessible.cpp
@@ -42,16 +42,18 @@
 
 #include "States.h"
 #include "nsAccessibilityService.h"
 #include "nsCoreUtils.h"
 
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULComboboxAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULComboboxAccessible::
   nsXULComboboxAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULFormControlAccessible.cpp
+++ b/accessible/src/xul/nsXULFormControlAccessible.cpp
@@ -57,16 +57,18 @@
 #include "nsIDOMXULMenuListElement.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULTextboxElement.h"
 #include "nsIEditor.h"
 #include "nsIFrame.h"
 #include "nsINameSpaceManager.h"
 #include "nsITextControlFrame.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULButtonAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULButtonAccessible::
   nsXULButtonAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
@@ -568,18 +570,19 @@ nsXULToolbarButtonAccessible::
 
 void
 nsXULToolbarButtonAccessible::GetPositionAndSizeInternal(PRInt32 *aPosInSet,
                                                          PRInt32 *aSetSize)
 {
   PRInt32 setSize = 0;
   PRInt32 posInSet = 0;
 
-  nsAccessible* parent(GetParent());
-  NS_ENSURE_TRUE(parent,);
+  nsAccessible* parent = Parent();
+  if (!parent)
+    return;
 
   PRInt32 childCount = parent->GetChildCount();
   for (PRInt32 childIdx = 0; childIdx < childCount; childIdx++) {
     nsAccessible* child = parent->GetChildAt(childIdx);
     if (IsSeparator(child)) { // end of a group of buttons
       if (posInSet)
         break; // we've found our group, so we're done
 
--- a/accessible/src/xul/nsXULListboxAccessible.cpp
+++ b/accessible/src/xul/nsXULListboxAccessible.cpp
@@ -43,16 +43,18 @@
 #include "States.h"
 #include "nsAccessibilityService.h"
 #include "nsAccUtils.h"
 
 #include "nsIDOMXULPopupElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULColumnsAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULColumnsAccessible::
   nsXULColumnsAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
@@ -993,38 +995,38 @@ NS_IMETHODIMP
 nsXULListCellAccessible::GetTable(nsIAccessibleTable **aTable)
 {
   NS_ENSURE_ARG_POINTER(aTable);
   *aTable = nsnull;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  nsAccessible* thisRow = GetParent();
+  nsAccessible* thisRow = Parent();
   if (!thisRow || thisRow->Role() != nsIAccessibleRole::ROLE_ROW)
     return NS_OK;
 
-  nsAccessible* table = thisRow->GetParent();
+  nsAccessible* table = thisRow->Parent();
   if (!table || table->Role() != nsIAccessibleRole::ROLE_TABLE)
     return NS_OK;
 
   CallQueryInterface(table, aTable);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULListCellAccessible::GetColumnIndex(PRInt32 *aColumnIndex)
 {
   NS_ENSURE_ARG_POINTER(aColumnIndex);
   *aColumnIndex = -1;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  nsAccessible* row = GetParent();
+  nsAccessible* row = Parent();
   if (!row)
     return NS_OK;
 
   *aColumnIndex = 0;
 
   PRInt32 indexInRow = IndexInParent();
   for (PRInt32 idx = 0; idx < indexInRow; idx++) {
     nsAccessible* cell = row->GetChildAt(idx);
@@ -1043,21 +1045,21 @@ NS_IMETHODIMP
 nsXULListCellAccessible::GetRowIndex(PRInt32 *aRowIndex)
 {
   NS_ENSURE_ARG_POINTER(aRowIndex);
   *aRowIndex = -1;
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
-  nsAccessible* row = GetParent();
+  nsAccessible* row = Parent();
   if (!row)
     return NS_OK;
 
-  nsAccessible* table = row->GetParent();
+  nsAccessible* table = row->Parent();
   if (!table)
     return NS_OK;
 
   *aRowIndex = 0;
 
   PRInt32 indexInTable = row->IndexInParent();
   for (PRInt32 idx = 0; idx < indexInTable; idx++) {
     row = table->GetChildAt(idx);
--- a/accessible/src/xul/nsXULMenuAccessible.cpp
+++ b/accessible/src/xul/nsXULMenuAccessible.cpp
@@ -56,17 +56,17 @@
 #include "nsGUIEvent.h"
 #include "nsILookAndFeel.h"
 #include "nsWidgetsCID.h"
 
 #include "mozilla/Preferences.h"
 #include "mozilla/dom/Element.h"
 
 using namespace mozilla;
-
+using namespace mozilla::a11y;
 
 static NS_DEFINE_CID(kLookAndFeelCID, NS_LOOKANDFEEL_CID);
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULSelectableAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULSelectableAccessible::
@@ -327,31 +327,32 @@ nsXULMenuitemAccessible::NativeState()
     PRBool isSelected = PR_FALSE;
     nsCOMPtr<nsIDOMXULSelectControlItemElement>
       item(do_QueryInterface(mContent));
     NS_ENSURE_TRUE(item, state);
     item->GetSelected(&isSelected);
 
     // Is collapsed?
     PRBool isCollapsed = PR_FALSE;
-    nsAccessible* parentAcc = GetParent();
-    if (parentAcc->State() & states::INVISIBLE)
+    nsAccessible* parent = Parent();
+    if (parent && parent->State() & states::INVISIBLE)
       isCollapsed = PR_TRUE;
 
     if (isSelected) {
       state |= states::SELECTED;
 
       // Selected and collapsed?
       if (isCollapsed) {
         // Set selected option offscreen/invisible according to combobox state
-        nsAccessible* grandParentAcc = parentAcc->GetParent();
-        NS_ENSURE_TRUE(grandParentAcc, state);
-        NS_ASSERTION(grandParentAcc->Role() == nsIAccessibleRole::ROLE_COMBOBOX,
+        nsAccessible* grandParent = parent->Parent();
+        if (!grandParent)
+          return state;
+        NS_ASSERTION(grandParent->Role() == nsIAccessibleRole::ROLE_COMBOBOX,
                      "grandparent of combobox listitem is not combobox");
-        PRUint64 grandParentState = grandParentAcc->State();
+        PRUint64 grandParentState = grandParent->State();
         state &= ~(states::OFFSCREEN | states::INVISIBLE);
         state |= (grandParentState & states::OFFSCREEN) |
                  (grandParentState & states::INVISIBLE) |
                  (grandParentState & states::OPAQUE1);
       } // isCollapsed
     } // isSelected
   } // ROLE_COMBOBOX_OPTION
 
@@ -399,17 +400,17 @@ nsXULMenuitemAccessible::AccessKey() con
   nsAutoString accesskey;
   mContent->GetAttr(kNameSpaceID_None, nsAccessibilityAtoms::accesskey,
                     accesskey);
   if (accesskey.IsEmpty())
     return KeyBinding();
 
   PRUint32 modifierKey = 0;
 
-  nsAccessible* parentAcc = GetParent();
+  nsAccessible* parentAcc = Parent();
   if (parentAcc) {
     if (parentAcc->NativeRole() == nsIAccessibleRole::ROLE_MENUBAR) {
       // If top level menu item, add Alt+ or whatever modifier text to string
       // No need to cache pref service, this happens rarely
       if (gMenuAccesskeyModifier == -1) {
         // Need to initialize cached global accesskey pref
         gMenuAccesskeyModifier = Preferences::GetInt("ui.key.menuAccessKey", 0);
       }
@@ -634,18 +635,19 @@ nsXULMenupopupAccessible::NativeState()
 {
   PRUint64 state = nsAccessible::NativeState();
 
 #ifdef DEBUG_A11Y
   // We are onscreen if our parent is active
   PRBool isActive = mContent->HasAttr(kNameSpaceID_None,
                                       nsAccessibilityAtoms::menuactive);
   if (!isActive) {
-    nsAccessible* parent(GetParent());
-    NS_ENSURE_TRUE(parent, state);
+    nsAccessible* parent = Parent();
+    if (!parent)
+      return state;
 
     nsIContent *parentContent = parnet->GetContent();
     NS_ENSURE_TRUE(parentContent, state);
 
     isActive = parentContent->HasAttr(kNameSpaceID_None,
                                       nsAccessibilityAtoms::open);
   }
 
@@ -680,17 +682,17 @@ nsXULMenupopupAccessible::NativeRole()
     PRUint32 role = mParent->Role();
     if (role == nsIAccessibleRole::ROLE_COMBOBOX ||
         role == nsIAccessibleRole::ROLE_AUTOCOMPLETE) {
       return nsIAccessibleRole::ROLE_COMBOBOX_LIST;
     }
 
     if (role == nsIAccessibleRole::ROLE_PUSHBUTTON) {
       // Some widgets like the search bar have several popups, owned by buttons.
-      nsAccessible* grandParent = mParent->GetParent();
+      nsAccessible* grandParent = mParent->Parent();
       if (grandParent &&
           grandParent->Role() == nsIAccessibleRole::ROLE_AUTOCOMPLETE)
         return nsIAccessibleRole::ROLE_COMBOBOX_LIST;
     }
   }
 
   return nsIAccessibleRole::ROLE_MENUPOPUP;
 }
--- a/accessible/src/xul/nsXULSliderAccessible.cpp
+++ b/accessible/src/xul/nsXULSliderAccessible.cpp
@@ -40,16 +40,18 @@
 
 #include "nsAccessibilityAtoms.h"
 #include "States.h"
 
 #include "nsIDOMDocument.h"
 #include "nsIDOMDocumentXBL.h"
 #include "nsIFrame.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULSliderAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULSliderAccessible::
   nsXULSliderAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULTabAccessible.cpp
+++ b/accessible/src/xul/nsXULTabAccessible.cpp
@@ -45,16 +45,18 @@
 // NOTE: alphabetically ordered
 #include "nsIDocument.h"
 #include "nsIFrame.h"
 #include "nsIDOMDocument.h"
 #include "nsIDOMXULSelectCntrlEl.h"
 #include "nsIDOMXULSelectCntrlItemEl.h"
 #include "nsIDOMXULRelatedElement.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTabAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTabAccessible::
   nsXULTabAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
--- a/accessible/src/xul/nsXULTextAccessible.cpp
+++ b/accessible/src/xul/nsXULTextAccessible.cpp
@@ -48,16 +48,18 @@
 #include "nsTextEquivUtils.h"
 #include "States.h"
 
 #include "nsIDOMXULDescriptionElement.h"
 #include "nsINameSpaceManager.h"
 #include "nsString.h"
 #include "nsNetUtil.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTextAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTextAccessible::
   nsXULTextAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsHyperTextAccessibleWrap(aContent, aShell)
 {
@@ -93,17 +95,17 @@ nsXULTextAccessible::GetRelationByType(P
   nsresult rv =
     nsHyperTextAccessibleWrap::GetRelationByType(aRelationType, aRelation);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (aRelationType == nsIAccessibleRelation::RELATION_LABEL_FOR) {
     // Caption is the label for groupbox
     nsIContent *parent = mContent->GetParent();
     if (parent && parent->Tag() == nsAccessibilityAtoms::caption) {
-      nsAccessible* parent = GetParent();
+      nsAccessible* parent = Parent();
       if (parent && parent->Role() == nsIAccessibleRole::ROLE_GROUPING)
         return nsRelUtils::AddTarget(aRelationType, aRelation, parent);
     }
   }
 
   return NS_OK;
 }
 
--- a/accessible/src/xul/nsXULTreeAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeAccessible.cpp
@@ -47,16 +47,18 @@
 
 #include "nsIDOMXULElement.h"
 #include "nsIDOMXULMultSelectCntrlEl.h"
 #include "nsIDOMXULTreeElement.h"
 #include "nsITreeSelection.h"
 #include "nsIMutableArray.h"
 #include "nsComponentManagerUtils.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTreeAccessible::
   nsXULTreeAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsAccessibleWrap(aContent, aShell)
 {
@@ -195,38 +197,32 @@ nsXULTreeAccessible::NativeRole()
   return primaryCol ?
     static_cast<PRUint32>(nsIAccessibleRole::ROLE_OUTLINE) :
     static_cast<PRUint32>(nsIAccessibleRole::ROLE_LIST);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeAccessible: nsIAccessible implementation
 
-NS_IMETHODIMP
-nsXULTreeAccessible::GetFocusedChild(nsIAccessible **aFocusedChild) 
+nsAccessible*
+nsXULTreeAccessible::FocusedChild()
 {
-  NS_ENSURE_ARG_POINTER(aFocusedChild);
-  *aFocusedChild = nsnull;
-
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
-
   if (gLastFocusedNode != mContent)
-    return NS_OK;
+    return nsnull;
 
   nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelect =
     do_QueryInterface(mContent);
   if (multiSelect) {
     PRInt32 row = -1;
     multiSelect->GetCurrentIndex(&row);
     if (row >= 0)
-      NS_IF_ADDREF(*aFocusedChild = GetTreeItemAccessible(row));
+      return GetTreeItemAccessible(row);
   }
 
-  return NS_OK;
+  return nsnull;
 }
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeAccessible: nsAccessible implementation (DON'T put methods here)
 
 nsAccessible*
 nsXULTreeAccessible::ChildAtPoint(PRInt32 aX, PRInt32 aY,
                                   EWhichChildAtPoint aWhichChild)
@@ -656,39 +652,33 @@ NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION
                                 nsXULTreeItemAccessibleBase)
 NS_INTERFACE_TABLE_TAIL_INHERITING(nsAccessible)
 NS_IMPL_ADDREF_INHERITED(nsXULTreeItemAccessibleBase, nsAccessible)
 NS_IMPL_RELEASE_INHERITED(nsXULTreeItemAccessibleBase, nsAccessible)
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeItemAccessibleBase: nsIAccessible implementation
 
-NS_IMETHODIMP
-nsXULTreeItemAccessibleBase::GetFocusedChild(nsIAccessible **aFocusedChild) 
+nsAccessible*
+nsXULTreeItemAccessibleBase::FocusedChild()
 {
-  NS_ENSURE_ARG_POINTER(aFocusedChild);
-  *aFocusedChild = nsnull;
-
-  if (IsDefunct())
-    return NS_ERROR_FAILURE;
-
   if (gLastFocusedNode != mContent)
-    return NS_OK;
+    return nsnull;
 
   nsCOMPtr<nsIDOMXULMultiSelectControlElement> multiSelect =
     do_QueryInterface(mContent);
 
   if (multiSelect) {
     PRInt32 row = -1;
     multiSelect->GetCurrentIndex(&row);
     if (row == mRow)
-      NS_ADDREF(*aFocusedChild = this);
+      return this;
   }
 
-  return NS_OK;
+  return nsnull;
 }
 
 NS_IMETHODIMP
 nsXULTreeItemAccessibleBase::GetBounds(PRInt32 *aX, PRInt32 *aY,
                                        PRInt32 *aWidth, PRInt32 *aHeight)
 {
   NS_ENSURE_ARG_POINTER(aX);
   *aX = 0;
@@ -1220,17 +1210,17 @@ nsXULTreeColumnsAccessible::GetSiblingAt
   nsCOMPtr<nsITreeBoxObject> tree = nsCoreUtils::GetTreeBoxObject(mContent);
   if (tree) {
     nsCOMPtr<nsITreeView> treeView;
     tree->GetView(getter_AddRefs(treeView));
     if (treeView) {
       PRInt32 rowCount = 0;
       treeView->GetRowCount(&rowCount);
       if (rowCount > 0 && aOffset <= rowCount) {
-        nsRefPtr<nsXULTreeAccessible> treeAcc = do_QueryObject(GetParent());
+        nsRefPtr<nsXULTreeAccessible> treeAcc = do_QueryObject(Parent());
 
         if (treeAcc)
           return treeAcc->GetTreeItemAccessible(aOffset - 1);
       }
     }
   }
 
   return nsnull;
--- a/accessible/src/xul/nsXULTreeAccessible.h
+++ b/accessible/src/xul/nsXULTreeAccessible.h
@@ -71,27 +71,27 @@ public:
 
   // nsISupports and cycle collection
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsXULTreeAccessible,
                                            nsAccessible)
 
   // nsIAccessible
   NS_IMETHOD GetValue(nsAString& aValue);
-  NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
 
   // nsAccessNode
   virtual bool IsDefunct() const;
   virtual void Shutdown();
 
   // nsAccessible
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual nsAccessible* ChildAtPoint(PRInt32 aX, PRInt32 aY,
                                      EWhichChildAtPoint aWhichChild);
+  virtual nsAccessible* FocusedChild();
 
   virtual nsAccessible* GetChildAt(PRUint32 aIndex);
   virtual PRInt32 GetChildCount();
 
   // SelectAccessible
   virtual bool IsSelect();
   virtual already_AddRefed<nsIArray> SelectedItems();
   virtual PRUint32 SelectedItemCount();
@@ -177,18 +177,16 @@ public:
                               nsITreeView *aTreeView, PRInt32 aRow);
 
   // nsISupports and cycle collection
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsXULTreeItemAccessibleBase,
                                            nsAccessibleWrap)
 
   // nsIAccessible
-  NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
-
   NS_IMETHOD GetBounds(PRInt32 *aX, PRInt32 *aY,
                        PRInt32 *aWidth, PRInt32 *aHeight);
 
   NS_IMETHOD SetSelected(PRBool aSelect); 
   NS_IMETHOD TakeFocus();
 
   NS_IMETHOD GetRelationByType(PRUint32 aRelationType,
                                nsIAccessibleRelation **aRelation);
@@ -204,16 +202,17 @@ public:
   // nsAccessNode
   virtual bool IsDefunct() const;
   virtual void Shutdown();
   virtual bool IsPrimaryForNode() const;
 
   // nsAccessible
   virtual PRUint64 NativeState();
   virtual PRInt32 IndexInParent() const;
+  virtual nsAccessible* FocusedChild();
 
   // nsXULTreeItemAccessibleBase
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_XULTREEITEMBASEACCESSIBLE_IMPL_CID)
 
   /**
    * Return row index associated with the accessible.
    */
   PRInt32 GetRowIndex() const { return mRow; }
--- a/accessible/src/xul/nsXULTreeGridAccessible.cpp
+++ b/accessible/src/xul/nsXULTreeGridAccessible.cpp
@@ -42,16 +42,18 @@
 #include "nsAccessibilityService.h"
 #include "nsAccUtils.h"
 #include "nsDocAccessible.h"
 #include "nsEventShell.h"
 #include "States.h"
 
 #include "nsITreeSelection.h"
 
+using namespace mozilla::a11y;
+
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeGridAccessible
 ////////////////////////////////////////////////////////////////////////////////
 
 nsXULTreeGridAccessible::
   nsXULTreeGridAccessible(nsIContent *aContent, nsIWeakReference *aShell) :
   nsXULTreeAccessible(aContent, aShell)
 {
@@ -843,23 +845,20 @@ NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION
                                 nsXULTreeGridCellAccessible)
 NS_INTERFACE_TABLE_TAIL_INHERITING(nsLeafAccessible)
 NS_IMPL_ADDREF_INHERITED(nsXULTreeGridCellAccessible, nsLeafAccessible)
 NS_IMPL_RELEASE_INHERITED(nsXULTreeGridCellAccessible, nsLeafAccessible)
 
 ////////////////////////////////////////////////////////////////////////////////
 // nsXULTreeGridCellAccessible: nsIAccessible implementation
 
-NS_IMETHODIMP
-nsXULTreeGridCellAccessible::GetFocusedChild(nsIAccessible **aFocusedChild) 
+nsAccessible*
+nsXULTreeGridCellAccessible::FocusedChild()
 {
-  NS_ENSURE_ARG_POINTER(aFocusedChild);
-  *aFocusedChild = nsnull;
-
-  return IsDefunct() ? NS_ERROR_FAILURE : NS_OK;
+  return nsnull;
 }
 
 NS_IMETHODIMP
 nsXULTreeGridCellAccessible::GetName(nsAString& aName)
 {
   aName.Truncate();
 
   if (IsDefunct())
@@ -1011,17 +1010,20 @@ NS_IMETHODIMP
 nsXULTreeGridCellAccessible::GetTable(nsIAccessibleTable **aTable)
 {
   NS_ENSURE_ARG_POINTER(aTable);
   *aTable = nsnull;
 
   if (IsDefunct())
     return NS_OK;
 
-  CallQueryInterface(mParent->GetParent(), aTable);
+  nsAccessible* grandParent = mParent->Parent();
+  if (grandParent)
+    CallQueryInterface(grandParent, aTable);
+
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsXULTreeGridCellAccessible::GetColumnIndex(PRInt32 *aColumnIndex)
 {
   NS_ENSURE_ARG_POINTER(aColumnIndex);
   *aColumnIndex = -1;
@@ -1166,19 +1168,22 @@ nsresult
 nsXULTreeGridCellAccessible::GetAttributesInternal(nsIPersistentProperties *aAttributes)
 {
   NS_ENSURE_ARG_POINTER(aAttributes);
 
   if (IsDefunct())
     return NS_ERROR_FAILURE;
 
   // "table-cell-index" attribute
-  nsCOMPtr<nsIAccessible> accessible;
-  mParent->GetParent(getter_AddRefs(accessible));
-  nsCOMPtr<nsIAccessibleTable> tableAccessible = do_QueryInterface(accessible);
+  nsAccessible* grandParent = mParent->Parent();
+  if (!grandParent)
+    return NS_OK;
+
+  nsCOMPtr<nsIAccessibleTable> tableAccessible =
+    do_QueryInterface(static_cast<nsIAccessible*>(grandParent));
 
   // XXX - temp fix for crash bug 516047
   if (!tableAccessible)
     return NS_ERROR_FAILURE;
     
   PRInt32 colIdx = GetColumnIndex();
 
   PRInt32 cellIdx = -1;
@@ -1303,17 +1308,17 @@ nsXULTreeGridCellAccessible::GetSiblingA
       column = nsCoreUtils::GetNextSensibleColumn(columnAtOffset);
       column.swap(columnAtOffset);
     }
   }
 
   if (!columnAtOffset)
     return nsnull;
 
-  nsRefPtr<nsXULTreeItemAccessibleBase> rowAcc = do_QueryObject(GetParent());
+  nsRefPtr<nsXULTreeItemAccessibleBase> rowAcc = do_QueryObject(Parent());
   return rowAcc->GetCellAccessible(columnAtOffset);
 }
 
 void
 nsXULTreeGridCellAccessible::DispatchClickEvent(nsIContent *aContent,
                                                 PRUint32 aActionIndex)
 {
   if (IsDefunct())
--- a/accessible/src/xul/nsXULTreeGridAccessible.h
+++ b/accessible/src/xul/nsXULTreeGridAccessible.h
@@ -138,17 +138,16 @@ public:
                               PRInt32 aRow, nsITreeColumn* aColumn);
 
   // nsISupports
   NS_DECL_ISUPPORTS_INHERITED
   NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(nsXULTreeGridCellAccessible,
                                            nsLeafAccessible)
 
   // nsIAccessible
-  NS_IMETHOD GetFocusedChild(nsIAccessible **aFocusedChild);
 
   NS_IMETHOD GetName(nsAString& aName);
   NS_IMETHOD GetBounds(PRInt32 *aX, PRInt32 *aY,
                        PRInt32 *aWidth, PRInt32 *aHeight);
 
   NS_IMETHOD GetNumActions(PRUint8 *aCount);
   NS_IMETHOD GetActionName(PRUint8 aIndex, nsAString& aName);
   NS_IMETHOD DoAction(PRUint8 aIndex);
@@ -157,16 +156,17 @@ public:
   NS_DECL_NSIACCESSIBLETABLECELL
 
   // nsAccessNode
   virtual bool IsDefunct() const;
   virtual PRBool Init();
   virtual bool IsPrimaryForNode() const;
 
   // nsAccessible
+  virtual nsAccessible* FocusedChild();
   virtual nsresult GetAttributesInternal(nsIPersistentProperties *aAttributes);
   virtual PRUint32 NativeRole();
   virtual PRUint64 NativeState();
   virtual PRInt32 IndexInParent() const;
 
   // nsXULTreeGridCellAccessible
   NS_DECLARE_STATIC_IID_ACCESSOR(NS_XULTREEGRIDCELLACCESSIBLE_IMPL_CID)
 
--- a/accessible/tests/mochitest/events.js
+++ b/accessible/tests/mochitest/events.js
@@ -757,16 +757,22 @@ function synthClick(aNodeOrID, aCheckerO
   {
     // Scroll the node into view, otherwise synth click may fail.
     if (this.DOMNode instanceof nsIDOMNSHTMLElement)
       this.DOMNode.scrollIntoView(true);
 
     synthesizeMouse(this.DOMNode, 1, 1, {});
   }
 
+  this.finalCheck = function synthClick_finalCheck()
+  {
+    // Scroll top window back.
+    window.top.scrollTo(0, 0);
+  }
+
   this.getID = function synthClick_getID()
   {
     return prettyName(aNodeOrID) + " click"; 
   }
 }
 
 /**
  * Mouse move invoker.
--- a/accessible/tests/mochitest/events/test_tree.xul
+++ b/accessible/tests/mochitest/events/test_tree.xul
@@ -98,23 +98,25 @@
 
     /**
      * Check name changed a11y event.
      */
     function nameChangeChecker(aMsg, aRow, aCol)
     {
       this.type = EVENT_NAME_CHANGE;
 
-      this.target getter = function()
+      function targetGetter()
       {
         var acc = getAccessible(gTree);
 
         var tableAcc = getAccessible(acc, [nsIAccessibleTable]);
         return tableAcc.getCellAt(aRow, aCol);
       }
+      Object.defineProperty(this, "target", { get: targetGetter });
+
       this.getID = function getID()
       {
         return aMsg + "name changed";
       }
     }
 
     ////////////////////////////////////////////////////////////////////////////
     // Invokers
--- a/accessible/tests/mochitest/treeupdate/test_contextmenu.xul
+++ b/accessible/tests/mochitest/treeupdate/test_contextmenu.xul
@@ -230,17 +230,17 @@
       var subsubmenuTree =
       {
         name: "item2.0.0",
         role: ROLE_MENUITEM,
         children: []
       };
 
       if (LINUX || SOLARIS)
-        tree.children[2].children[0].\(subsubmenuTree);
+        tree.children[2].children[0].children.push(subsubmenuTree);
       else
         tree.children[2].children[0].children[0].children[0].children.push(subsubmenuTree);
 
       return tree;
     }
 
 
     function doTests()
--- a/accessible/tests/mochitest/treeupdate/test_doc.html
+++ b/accessible/tests/mochitest/treeupdate/test_doc.html
@@ -371,22 +371,22 @@
       }
 
       this.finalCheck = function changeSrc_finalCheck()
       {
         var tree =
           { INTERNAL_FRAME: [
             { DOCUMENT: [
               { ENTRY: [ ] }
-            ] };
+            ] }
           ] };
         testAccessibleTree(this.containerNode, tree);
       }
 
-      this.getID() = function changeSrc_getID()
+      this.getID = function changeSrc_getID()
       {
         return "change src on iframe";
       }
     }
 
     ////////////////////////////////////////////////////////////////////////////
     // Test
 
--- a/browser/app/blocklist.xml
+++ b/browser/app/blocklist.xml
@@ -1,213 +0,0 @@
-<?xml version="1.0"?>
-<blocklist xmlns="http://www.mozilla.org/2006/addons-blocklist" lastupdate="1311096050000">
-  <emItems>
-      <emItem  blockID="i41" id="{99079a25-328f-4bd4-be04-00955acaa0a7}">
-                        <versionRange  minVersion="0.1" maxVersion="4.3.0.00" severity="1">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i8" id="{B13721C7-F507-4982-B2E5-502A71474FED}">
-                        <versionRange  minVersion=" " severity="1">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i38" 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  blockID="i19" id="{46551EC9-40F0-4e47-8E18-8E5CF550CFB8}">
-                        <versionRange  minVersion="1.1b1" maxVersion="1.1b1">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i16" id="{27182e60-b5f3-411c-b545-b44205977502}">
-                        <versionRange  minVersion="1.0" maxVersion="1.0">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i39" id="{c2d64ff7-0ab8-4263-89c9-ea3b0f8f050c}">
-                        <versionRange  minVersion="0.1" maxVersion="4.3.0.00" severity="1">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i10" id="{8CE11043-9A15-4207-A565-0C94C42D590D}">
-                        </emItem>
-      <emItem  blockID="i1" id="mozilla_cc@internetdownloadmanager.com">
-                        <versionRange  minVersion="2.1" maxVersion="3.3">
-                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-                              <versionRange  minVersion="3.0a1" maxVersion="*" />
-                          </targetApplication>
-                    </versionRange>
-                                <versionRange  minVersion=" " maxVersion="6.9.8">
-                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-                              <versionRange  minVersion="3.7a1pre" maxVersion="*" />
-                          </targetApplication>
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i18" id="msntoolbar@msn.com">
-                        <versionRange  minVersion=" " maxVersion="6.*">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i13" id="{E8E88AB0-7182-11DF-904E-6045E0D72085}">
-                        </emItem>
-      <emItem  blockID="i4" id="{4B3803EA-5230-4DC3-A7FC-33638F3D3542}">
-                        <versionRange  minVersion="1.2" maxVersion="1.2">
-                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-                              <versionRange  minVersion="3.0a1" maxVersion="*" />
-                          </targetApplication>
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i40" id="{28387537-e3f9-4ed7-860c-11e69af4a8a0}">
-                        <versionRange  minVersion="0.1" maxVersion="4.3.0.00" severity="1">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i23" id="firefox@bandoo.com">
-                        <versionRange  minVersion="5.0" maxVersion="5.0" severity="1">
-                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-                              <versionRange  minVersion="3.7a1pre" maxVersion="*" />
-                          </targetApplication>
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i22" id="ShopperReports@ShopperReports.com">
-                        <versionRange  minVersion="3.1.22.0" maxVersion="3.1.22.0">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i2" id="fdm_ffext@freedownloadmanager.org">
-                        <versionRange  minVersion="1.0" maxVersion="1.3.1">
-                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-                              <versionRange  minVersion="3.0a1" maxVersion="*" />
-                          </targetApplication>
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i5" id="support@daemon-tools.cc">
-                        <versionRange  minVersion=" " maxVersion="1.0.0.5">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i6" id="{3f963a5b-e555-4543-90e2-c3908898db71}">
-                        <versionRange  minVersion=" " maxVersion="8.5">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i12" id="masterfiler@gmail.com">
-                        <versionRange  severity="3">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i20" id="{AB2CE124-6272-4b12-94A9-7303C7397BD1}">
-                        <versionRange  minVersion="0.1" maxVersion="5.2.0.7164" severity="1">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i11" id="yslow@yahoo-inc.com">
-                        <versionRange  minVersion="2.0.5" maxVersion="2.0.5">
-                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-                              <versionRange  minVersion="3.5.7" maxVersion="*" />
-                          </targetApplication>
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i17" id="{3252b9ae-c69a-4eaf-9502-dc9c1f6c009e}">
-                        <versionRange  minVersion="2.2" maxVersion="2.2">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i3" id="langpack-vi-VN@firefox.mozilla.org">
-                        <versionRange  minVersion="2.0" maxVersion="2.0">
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i7" id="{2224e955-00e9-4613-a844-ce69fccaae91}">
-                        </emItem>
-      <emItem  blockID="i24" id="{6E19037A-12E3-4295-8915-ED48BC341614}">
-                        <versionRange  minVersion="0.1" maxVersion="1.3.328.4" severity="1">
-                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-                              <versionRange  minVersion="3.7a1pre" maxVersion="*" />
-                          </targetApplication>
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i15" id="personas@christopher.beard">
-                        <versionRange  minVersion="1.6" maxVersion="1.6">
-                      <targetApplication  id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-                              <versionRange  minVersion="3.6" maxVersion="3.6.*" />
-                          </targetApplication>
-                    </versionRange>
-                  </emItem>
-      <emItem  blockID="i21" id="support@update-firefox.com">
-                        </emItem>
-    </emItems>
-
-  <pluginItems>
-      <pluginItem  blockID="p26">
-      <match name="name" exp="^Yahoo Application State Plugin$" />      <match name="description" exp="^Yahoo Application State Plugin$" />      <match name="filename" exp="npYState.dll" />              <versionRange >
-                      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-              <versionRange  minVersion="3.0a1" maxVersion="3.*" />
-            </targetApplication>
-                  </versionRange>
-          </pluginItem>
-      <pluginItem  blockID="p27">
-      <match name="name" exp="QuickTime Plug-in 7[.]1[.]" />            <match name="filename" exp="npqtplugin.?[.]dll" />              <versionRange >
-                      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-              <versionRange  minVersion="3.0a1" maxVersion="3.*" />
-            </targetApplication>
-                  </versionRange>
-          </pluginItem>
-      <pluginItem  blockID="p28">
-                  <match name="filename" exp="NPFFAddOn.dll" />              <versionRange >
-                  </versionRange>
-          </pluginItem>
-      <pluginItem  blockID="p31">
-                  <match name="filename" exp="NPMySrch.dll" />              <versionRange >
-                  </versionRange>
-          </pluginItem>
-      <pluginItem  blockID="p32">
-                  <match name="filename" exp="npViewpoint.dll" />              <versionRange >
-                      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-              <versionRange  minVersion="3.0" maxVersion="*" />
-            </targetApplication>
-                  </versionRange>
-          </pluginItem>
-      <pluginItem  blockID="p33">
-      <match name="name" exp="[0-6]\.0\.[01]\d{2}\.\d+" />            <match name="filename" exp="npdeploytk.dll" />              <versionRange  severity="1">
-                  </versionRange>
-          </pluginItem>
-      <pluginItem  blockID="p34">
-                  <match name="filename" exp="[Nn][Pp][Jj][Pp][Ii]1[56]0_[0-9]+\.[Dd][Ll][Ll]" />              <versionRange >
-                      <targetApplication id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}">
-              <versionRange  minVersion="3.6a1pre" maxVersion="*" />
-            </targetApplication>
-                  </versionRange>
-          </pluginItem>
-    </pluginItems>
-
-  <gfxItems>
-    <gfxBlacklistEntry  blockID="g35">
-      <os>WINNT 6.1</os>
-      <vendor>0x10de</vendor>
-              <devices>
-                      <device>0x0a6c</device>
-                  </devices>
-            <feature>DIRECT2D</feature>
-      <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
-      <driverVersion>8.17.12.5896</driverVersion>
-      <driverVersionComparator>LESS_THAN_OR_EQUAL</driverVersionComparator>
-    </gfxBlacklistEntry>
-    <gfxBlacklistEntry  blockID="g36">
-      <os>WINNT 6.1</os>
-      <vendor>0x10de</vendor>
-              <devices>
-                      <device>0x0a6c</device>
-                  </devices>
-            <feature>DIRECT3D_9_LAYERS</feature>
-      <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
-      <driverVersion>8.17.12.5896</driverVersion>
-      <driverVersionComparator>LESS_THAN_OR_EQUAL</driverVersionComparator>
-    </gfxBlacklistEntry>
-    <gfxBlacklistEntry  blockID="g37">
-      <os>WINNT 5.1</os>
-      <vendor>0x10de</vendor>
-            <feature>DIRECT3D_9_LAYERS</feature>
-      <featureStatus>BLOCKED_DRIVER_VERSION</featureStatus>
-      <driverVersion>7.0.0.0</driverVersion>
-      <driverVersionComparator>GREATER_THAN_OR_EQUAL</driverVersionComparator>
-    </gfxBlacklistEntry>
-    </gfxItems>
-
-
-</blocklist>
\ No newline at end of file
--- a/browser/base/content/NetworkPrioritizer.jsm
+++ b/browser/base/content/NetworkPrioritizer.jsm
@@ -92,50 +92,50 @@ function _handleEvent(aEvent) {
       WindowHelper.removeWindow(aEvent.currentTarget);
       break;
   }
 }
 
 
 // Methods that impact a browser. Put into single object for organization.
 let BrowserHelper = {
-  onOpen: function(aBrowser) {
+  onOpen: function NP_BH_onOpen(aBrowser) {
     // If the tab is in the focused window, leave priority as it is
     if (aBrowser.ownerDocument.defaultView != _lastFocusedWindow)
       this.decreasePriority(aBrowser);
   },
 
-  onSelect: function(aBrowser) {
+  onSelect: function NP_BH_onSelect(aBrowser) {
     let windowEntry = WindowHelper.getEntry(aBrowser.ownerDocument.defaultView);
     if (windowEntry.lastSelectedBrowser)
       this.decreasePriority(windowEntry.lastSelectedBrowser);
     this.increasePriority(aBrowser);
 
     windowEntry.lastSelectedBrowser = aBrowser;
   },
 
   // Auxiliary methods
-  getLoadgroup: function(aBrowser) {
+  getLoadgroup: function NP_BH_getLoadgroup(aBrowser) {
     return aBrowser.webNavigation.QueryInterface(Ci.nsIDocumentLoader)
                    .loadGroup.QueryInterface(Ci.nsISupportsPriority);
   },
 
-  increasePriority: function(aBrowser) {
+  increasePriority: function NP_BH_increasePriority(aBrowser) {
     this.getLoadgroup(aBrowser).adjustPriority(PRIORITY_DELTA);
   },
 
-  decreasePriority: function(aBrowser) {
+  decreasePriority: function NP_BH_decreasePriority(aBrowser) {
     this.getLoadgroup(aBrowser).adjustPriority(PRIORITY_DELTA * -1);
   }
 };
 
 
 // Methods that impact a window. Put into single object for organization.
 let WindowHelper = {
-  addWindow: function(aWindow) {
+  addWindow: function NP_WH_addWindow(aWindow) {
     // Build internal data object
     _windows.push({ window: aWindow, lastSelectedBrowser: null });
 
     // Add event listeners
     TAB_EVENTS.forEach(function(event) {
       aWindow.gBrowser.tabContainer.addEventListener(event, _handleEvent, false);
     });
     WINDOW_EVENTS.forEach(function(event) {
@@ -148,70 +148,70 @@ let WindowHelper = {
       this.handleFocusedWindow(aWindow);
     else
       this.decreasePriority(aWindow);
 
     // Select the selected tab
     BrowserHelper.onSelect(aWindow.gBrowser.selectedBrowser);
   },
 
-  removeWindow: function(aWindow) {
+  removeWindow: function NP_WH_removeWindow(aWindow) {
     if (aWindow == _lastFocusedWindow)
       _lastFocusedWindow = null;
 
     // Delete this window from our tracking
     _windows.splice(this.getEntryIndex(aWindow), 1);
 
     // Remove the event listeners
     TAB_EVENTS.forEach(function(event) {
       aWindow.gBrowser.tabContainer.removeEventListener(event, _handleEvent, false);
     });
     WINDOW_EVENTS.forEach(function(event) {
       aWindow.removeEventListener(event, _handleEvent, false);
     });
   },
 
-  onActivate: function(aWindow, aHasFocus) {
+  onActivate: function NP_WH_onActivate(aWindow, aHasFocus) {
     // If this window was the last focused window, we don't need to do anything
     if (aWindow == _lastFocusedWindow)
       return;
 
     // handleFocusedWindow will deprioritize the current window
     this.handleFocusedWindow(aWindow);
 
     // Lastly we should increase priority for this window
     this.increasePriority(aWindow);
   },
 
-  handleFocusedWindow: function(aWindow) {
+  handleFocusedWindow: function NP_WH_handleFocusedWindow(aWindow) {
     // If we have a last focused window, we need to deprioritize it first
     if (_lastFocusedWindow)
       this.decreasePriority(_lastFocusedWindow);
 
     // aWindow is now focused
     _lastFocusedWindow = aWindow;
   },
 
   // Auxiliary methods
-  increasePriority: function(aWindow) {
+  increasePriority: function NP_WH_increasePriority(aWindow) {
     aWindow.gBrowser.browsers.forEach(function(aBrowser) {
       BrowserHelper.increasePriority(aBrowser);
     });
   },
 
-  decreasePriority: function(aWindow) {
+  decreasePriority: function NP_WH_decreasePriority(aWindow) {
     aWindow.gBrowser.browsers.forEach(function(aBrowser) {
       BrowserHelper.decreasePriority(aBrowser);
     });
   },
 
-  getEntry: function(aWindow) {
+  getEntry: function NP_WH_getEntry(aWindow) {
     return _windows[this.getEntryIndex(aWindow)];
   },
 
-  getEntryIndex: function(aWindow) {
+  getEntryIndex: function NP_WH_getEntryAtIndex(aWindow) {
     // Assumes that every object has a unique window & it's in the array
     for (let i = 0; i < _windows.length; i++)
       if (_windows[i].window == aWindow)
         return i;
   }
 };
 
--- a/browser/base/content/browser-fullZoom.js
+++ b/browser/base/content/browser-fullZoom.js
@@ -257,17 +257,19 @@ var FullZoom = {
 
     if (Services.contentPrefs.hasCachedPref(aURI, this.name)) {
       let zoomValue = Services.contentPrefs.getPref(aURI, this.name);
       this._applyPrefToSetting(zoomValue, browser);
     } else {
       var self = this;
       Services.contentPrefs.getPref(aURI, this.name, function (aResult) {
         // Check that we're still where we expect to be in case this took a while.
-        if (aURI.equals(browser.currentURI)) {
+        // Null check currentURI, since the window may have been destroyed before
+        // we were called.
+        if (browser.currentURI && aURI.equals(browser.currentURI)) {
           self._applyPrefToSetting(aResult, browser);
         }
       });
     }
   },
 
   // update state of zoom type menu item
 
--- a/browser/base/content/browser.css
+++ b/browser/base/content/browser.css
@@ -58,20 +58,16 @@ tabbrowser {
   -moz-transition: opacity 250ms;
 }
 
 .tabbrowser-tabs[positionpinnedtabs] > .tabbrowser-tab[pinned] {
   position: fixed !important;
   display: block; /* position:fixed already does this (bug 579776), but let's be explicit */
 }
 
-.tabbrowser-tabs[drag] > .tabbrowser-tab {
-  pointer-events: none; /* suppress tooltips */
-}
-
 .tabbrowser-tabs[drag] > .tabbrowser-tab[selected] {
   z-index: 2; /* ensure selected tab stays on top despite -moz-transform */
 }
 
 .tabbrowser-tabs[drag] > .tabbrowser-tab[dragged] {
   -moz-transition: 0s; /* suppress opening animation when reattaching tab */
 }
 
--- a/browser/base/content/browser.js
+++ b/browser/base/content/browser.js
@@ -350,16 +350,19 @@ const gSessionHistoryObserver = {
     if (topic != "browser:purge-session-history")
       return;
 
     var backCommand = document.getElementById("Browser:Back");
     backCommand.setAttribute("disabled", "true");
     var fwdCommand = document.getElementById("Browser:Forward");
     fwdCommand.setAttribute("disabled", "true");
 
+    // Hide session restore button on about:home
+    window.messageManager.sendAsyncMessage("Browser:HideSessionRestoreButton");
+
     if (gURLBar) {
       // Clear undo history of the URL bar
       gURLBar.editor.transactionManager.clear()
     }
   }
 };
 
 /**
--- a/browser/base/content/content.js
+++ b/browser/base/content/content.js
@@ -46,8 +46,18 @@ const Cu = Components.utils;
   return docShell.QueryInterface(Ci.nsIWebNavigation);
 });
 
 addMessageListener("WebNavigation:LoadURI", function (message) {
   let flags = message.json.flags || webNavigation.LOAD_FLAGS_NONE;
 
   webNavigation.loadURI(message.json.uri, flags, null, null, null);
 });
+
+addMessageListener("Browser:HideSessionRestoreButton", function (message) {
+  // Hide session restore button on about:home
+  let doc = content.document;
+  let container;
+  if (doc.documentURI.toLowerCase() == "about:home" &&
+      (container = doc.getElementById("sessionRestoreContainer"))){
+    container.hidden = true;
+  }
+});
--- a/browser/base/content/tabbrowser.xml
+++ b/browser/base/content/tabbrowser.xml
@@ -2451,17 +2451,17 @@
                 onget="return this.mCurrentBrowser.userTypedValue;"
                 onset="return this.mCurrentBrowser.userTypedValue = val;"/>
 
       <method name="createTooltip">
         <parameter name="event"/>
         <body><![CDATA[
           event.stopPropagation();
           var tab = document.tooltipNode;
-          if (tab.localName != "tab") {
+          if (tab.localName != "tab" || this.tabContainer.draggedTab) {
             event.preventDefault();
             return;
           }
           event.target.setAttribute("label", tab.mOverCloseButton ?
                                              tab.getAttribute("closetabtext") :
                                              tab.getAttribute("label"));
         ]]></body>
       </method>
@@ -3808,16 +3808,29 @@
 
       <handler event="dragstart"><![CDATA[
         if (this.draggedTab)
           return;
         var tab = this._getDragTargetTab(event);
         if (!tab || !tab._fullyOpen || tab.closing)
           return;
 
+#ifdef XP_MACOSX
+        if (event.altKey) {
+#else
+        if (event.ctrlKey) {
+#endif
+          let dt = event.dataTransfer;
+          let browser = tab.linkedBrowser;
+          dt.setData("text/x-moz-url", browser.currentURI.spec + "\n" + browser.contentTitle);
+          let favicon = document.getAnonymousElementByAttribute(tab, "class", "tab-icon-image");
+          dt.setDragImage(favicon, 16, 16);
+          return;
+        }
+
         this.setAttribute("drag", "move");
         this.draggedTab = tab;
         tab.setAttribute("dragged", "true");
         let data = tab._dragData = {};
         data._dragStartX = event.screenX;
         if (!tab.pinned)
           data._dragStartX += this.mTabstrip.scrollPosition;
         data._dragDistX = 0;
--- a/browser/components/places/content/controller.js
+++ b/browser/components/places/content/controller.js
@@ -133,18 +133,17 @@ PlacesController.prototype = {
   ]),
 
   // nsIClipboardOwner
   LosingOwnership: function PC_LosingOwnership (aXferable) {
     this.cutNodes = [];
   },
 
   terminate: function PC_terminate() {
-    if (this._cutNodes.length > 0)
-      this._clearClipboard();
+    this._releaseClipboardOwnership();
   },
 
   supportsCommand: function PC_supportsCommand(aCommand) {
     //LOG("supportsCommand: " + command);
     // Non-Places specific commands that we also support
     switch (aCommand) {
     case "cmd_undo":
     case "cmd_redo":
@@ -1123,24 +1122,30 @@ PlacesController.prototype = {
     // instances should instead be handled as copies (The sources are not
     // available for this instance).
     if (action == "cut" && actionOwner != this.profileName)
       action = "copy";
 
     return action;
   },
 
+  _releaseClipboardOwnership: function PC__releaseClipboardOwnership() {
+    if (this.cutNodes.length > 0) {
+      // This clears the logical clipboard, doesn't remove data.
+      this.clipboard.emptyClipboard(Ci.nsIClipboard.kGlobalClipboard);
+    }
+  },
+
   _clearClipboard: function PC__clearClipboard() {
-    this.clipboard.emptyClipboard(Ci.nsIClipboard.kGlobalClipboard);
-    // Unfortunately just invoking emptyClipboard is not enough, since it
-    // does not act on the native clipboard.
     let xferable = Cc["@mozilla.org/widget/transferable;1"].
                    createInstance(Ci.nsITransferable);
-    // GTK doesn't like empty transferables, so just add an unknown type.
-    xferable.addDataFlavor("text/x-moz-place-empty");
+    // Empty transferables may cause crashes, so just add an unknown type.
+    const TYPE = "text/x-moz-place-empty";
+    xferable.addDataFlavor(TYPE);
+    xferable.setTransferData(TYPE, PlacesUtils.toISupportsString(""), 0);
     this.clipboard.setData(xferable, null, Ci.nsIClipboard.kGlobalClipboard);
   },
 
   _populateClipboard: function PC__populateClipboard(aNodes, aAction) {
     // This order is _important_! It controls how this and other applications
     // select data to be inserted based on type.
     let contents = [
       { type: PlacesUtils.TYPE_X_MOZ_PLACE, entries: [] },
@@ -1190,21 +1195,25 @@ PlacesController.prototype = {
     });
 
     // Track the exected action in the xferable.  This must be the last flavor
     // since it's the least preferred one.
     // Enqueue a unique instance identifier to distinguish operations across
     // concurrent instances of the application.
     addData(PlacesUtils.TYPE_X_MOZ_PLACE_ACTION, aAction + "," + this.profileName);
 
-    if (hasData)
-      this.clipboard.setData(xferable, this, Ci.nsIClipboard.kGlobalClipboard);
+    if (hasData) {
+      this.clipboard.setData(xferable,
+                             this.cutNodes.length > 0 ? this : null,
+                             Ci.nsIClipboard.kGlobalClipboard);
+    }
   },
 
   _cutNodes: [],
+  get cutNodes() this._cutNodes,
   set cutNodes(aNodes) {
     let self = this;
     function updateCutNodes(aValue) {
       self._cutNodes.forEach(function (aNode) {
         self._view.toggleCutNode(aNode, aValue);
       });
     }
 
--- a/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
+++ b/browser/components/places/tests/browser/browser_410196_paste_into_tags.js
@@ -39,29 +39,30 @@ function onLibraryReady() {
   tests.focusTag();
   waitForClipboard(function(aData) !!aData,
                    tests.copyHistNode,
                    onClipboardReady,
                    PlacesUtils.TYPE_X_MOZ_PLACE);
 }
 
 function onClipboardReady() {
-  tests.pasteToTag();
+  tests.focusTag();
+  PlacesOrganizer._places.controller.paste();
   tests.historyNode();
   tests.checkForBookmarkInUI();
 
   gLibrary.close();
 
   // Remove new Places data we created.
   PlacesUtils.tagging.untagURI(NetUtil.newURI(MOZURISPEC), ["foo"]);
   PlacesUtils.tagging.untagURI(NetUtil.newURI(TEST_URL), ["foo"]);
   let tags = PlacesUtils.tagging.getTagsForURI(NetUtil.newURI(TEST_URL));
   is(tags.length, 0, "tags are gone");
   PlacesUtils.bookmarks.removeFolderChildren(PlacesUtils.unfiledBookmarksFolderId);
-  
+
   waitForClearHistory(finish);
 }
 
 let tests = {
 
   makeHistVisit: function() {
     // need to add a history object
     let testURI1 = NetUtil.newURI(MOZURISPEC);
@@ -75,55 +76,44 @@ let tests = {
     // create an initial tag to work with
     let bmId = add_bookmark(NetUtil.newURI(TEST_URL));
     ok(bmId > 0, "A bookmark was added");
     PlacesUtils.tagging.tagURI(NetUtil.newURI(TEST_URL), ["foo"]);
     let tags = PlacesUtils.tagging.getTagsForURI(NetUtil.newURI(TEST_URL));
     is(tags[0], 'foo', "tag is foo");
   },
 
-  focusTag: function (paste){
+  focusTag: function (){
     // focus the new tag
     PlacesOrganizer.selectLeftPaneQuery("Tags");
     let tags = PlacesOrganizer._places.selectedNode;
     tags.containerOpen = true;
     let fooTag = tags.getChild(0);
-    this.tagNode = fooTag;
+    let tagNode = fooTag;
     PlacesOrganizer._places.selectNode(fooTag);
-    is(this.tagNode.title, 'foo', "tagNode title is foo");
+    is(tagNode.title, 'foo', "tagNode title is foo");
     let ip = PlacesOrganizer._places.insertionPoint;
     ok(ip.isTag, "IP is a tag");
-    if (paste) {
-      ok(true, "About to paste");
-      PlacesOrganizer._places.controller.paste();
-    }
   },
 
-  histNode: null,
-
   copyHistNode: function (){
     // focus the history object
     PlacesOrganizer.selectLeftPaneQuery("History");
     let histContainer = PlacesOrganizer._places.selectedNode;
     PlacesUtils.asContainer(histContainer);
     histContainer.containerOpen = true;
     PlacesOrganizer._places.selectNode(histContainer.getChild(0));
-    this.histNode = PlacesOrganizer._content.view.nodeForTreeIndex(0);
-    PlacesOrganizer._content.selectNode(this.histNode);
-    is(this.histNode.uri, MOZURISPEC,
-       "historyNode exists: " + this.histNode.uri);
+    let histNode = PlacesOrganizer._content.view.nodeForTreeIndex(0);
+    PlacesOrganizer._content.selectNode(histNode);
+    is(histNode.uri, MOZURISPEC,
+       "historyNode exists: " + histNode.uri);
     // copy the history node
     PlacesOrganizer._content.controller.copy();
   },
 
-  pasteToTag: function (){
-    // paste history node into tag
-    this.focusTag(true);
-  },
-
   historyNode: function (){
     // re-focus the history again
     PlacesOrganizer.selectLeftPaneQuery("History");
     let histContainer = PlacesOrganizer._places.selectedNode;
     PlacesUtils.asContainer(histContainer);
     histContainer.containerOpen = true;
     PlacesOrganizer._places.selectNode(histContainer.getChild(0));
     let histNode = PlacesOrganizer._content.view.nodeForTreeIndex(0);
@@ -143,18 +133,16 @@ let tests = {
     // is the bookmark visible in the UI?
     // get the Unsorted Bookmarks node
     PlacesOrganizer.selectLeftPaneQuery("UnfiledBookmarks");
     // now we can see what is in the _content tree
     let unsortedNode = PlacesOrganizer._content.view.nodeForTreeIndex(1);
     ok(unsortedNode, "unsortedNode is not null: " + unsortedNode.uri);
     is(unsortedNode.uri, MOZURISPEC, "node uri's are the same");
   },
-
-  tagNode: null,
 };
 
 /**
  * Clears history invoking callback when done.
  */
 function waitForClearHistory(aCallback) {
   const TOPIC_EXPIRATION_FINISHED = "places-expiration-finished";
   let observer = {
--- a/browser/components/sessionstore/src/nsSessionStore.js
+++ b/browser/components/sessionstore/src/nsSessionStore.js
@@ -180,17 +180,17 @@ SessionStoreService.prototype = {
   classID: Components.ID("{5280606b-2510-4fe0-97ef-9b5a22eafe6b}"),
   QueryInterface: XPCOMUtils.generateQI([Ci.nsISessionStore,
                                          Ci.nsIDOMEventListener,
                                          Ci.nsIObserver,
                                          Ci.nsISupportsWeakReference]),
 
   // xul:tab attributes to (re)store (extensions might want to hook in here);
   // the favicon is always saved for the about:sessionrestore page
-  xulAttributes: ["image"],
+  xulAttributes: {"image": true},
 
   // set default load state
   _loadState: STATE_STOPPED,
 
   // During the initial restore and setBrowserState calls tracks the number of
   // windows yet to be restored
   _restoreCount: 0,
 
@@ -493,16 +493,17 @@ SessionStoreService.prototype = {
       break;
     case "browser:purge-session-history": // catch sanitization 
       this._clearDisk();
       // If the browser is shutting down, simply return after clearing the
       // session data on disk as this notification fires after the
       // quit-application notification so the browser is about to exit.
       if (this._loadState == STATE_QUITTING)
         return;
+      this._lastSessionState = null;
       let openWindows = {};
       this._forEachBrowserWindow(function(aWindow) {
         Array.forEach(aWindow.gBrowser.tabs, function(aTab) {
           delete aTab.linkedBrowser.__SS_data;
           if (aTab.linkedBrowser.__SS_restoreState)
             this._resetTabRestoringState(aTab);
         });
         openWindows[aWindow.__SSi] = true;
@@ -634,25 +635,26 @@ SessionStoreService.prototype = {
       case "enter":
         this._inPrivateBrowsing = true;
         break;
       case "exit":
         aSubject.QueryInterface(Ci.nsISupportsPRBool);
         let quitting = aSubject.data;
         if (quitting) {
           // save the backed up state with session set to stopped,
-          // otherwise resuming next time would look like a crash
+          // otherwise resuming next time would look like a crash.
+          // Whether we restore the session upon resume will be determined by the
+          // usual startup prefs, so we will have the same behavior regardless of
+          // whether the browser was closed while in normal or private browsing mode.
           if ("_stateBackup" in this) {
             var oState = this._stateBackup;
             oState.session = { state: STATE_STOPPED_STR };
 
             this._saveStateObject(oState);
           }
-          // make sure to restore the non-private session upon resuming
-          this._prefBranch.setBoolPref("sessionstore.resume_session_once", true);
         }
         else
           this._inPrivateBrowsing = false;
         delete this._stateBackup;
         break;
       }
 
       this._clearRestoringWindows();
@@ -1421,20 +1423,20 @@ SessionStoreService.prototype = {
       deleteFrom = aTab.linkedBrowser.__SS_data.extData;
     }
 
     if (deleteFrom && deleteFrom[aKey])
       delete deleteFrom[aKey];
   },
 
   persistTabAttribute: function sss_persistTabAttribute(aName) {
-    if (this.xulAttributes.indexOf(aName) != -1)
+    if (aName in this.xulAttributes)
       return; // this attribute is already being tracked
     
-    this.xulAttributes.push(aName);
+    this.xulAttributes[aName] = true;
     this.saveStateDelayed();
   },
 
   /**
    * Restores the session state stored in _lastSessionState. This will attempt
    * to merge data into the current session. If a window was opened at startup
    * with pinned tab(s), then the remaining data from the previous session for
    * that window will be opened into that winddow. Otherwise new windows will
@@ -1731,22 +1733,20 @@ SessionStoreService.prototype = {
     for (var i = 0; i < CAPABILITIES.length; i++)
       if (!browser.docShell["allow" + CAPABILITIES[i]])
         disallow.push(CAPABILITIES[i]);
     if (disallow.length > 0)
       tabData.disallow = disallow.join(",");
     else if (tabData.disallow)
       delete tabData.disallow;
     
-    if (this.xulAttributes.length > 0) {
-      tabData.attributes = {};
-      Array.forEach(aTab.attributes, function(aAttr) {
-        if (this.xulAttributes.indexOf(aAttr.name) > -1)
-          tabData.attributes[aAttr.name] = aAttr.value;
-      }, this);
+    tabData.attributes = {};
+    for (let name in this.xulAttributes) {
+      if (aTab.hasAttribute(name))
+        tabData.attributes[name] = aTab.getAttribute(name);
     }
     
     if (aTab.__SS_extdata)
       tabData.extData = aTab.__SS_extdata;
     else if (tabData.extData)
       delete tabData.extData;
     
     if (history && browser.docShell instanceof Ci.nsIDocShell)
@@ -1908,17 +1908,25 @@ SessionStoreService.prototype = {
    *        the tab is pinned and should be treated differently for privacy
    */
   _serializeSessionStorage:
     function sss_serializeSessionStorage(aTabData, aHistory, aDocShell, aFullData, aIsPinned) {
     let storageData = {};
     let hasContent = false;
 
     for (let i = 0; i < aHistory.count; i++) {
-      let uri = aHistory.getEntryAtIndex(i, false).URI;
+      let uri;
+      try {
+        uri = aHistory.getEntryAtIndex(i, false).URI;
+      }
+      catch (ex) {
+        // Chances are that this is getEntryAtIndex throwing, as seen in bug 669196.
+        // We've already asserted in _collectTabData, so we won't show that again.
+        continue;
+      }
       // sessionStorage is saved per origin (cf. nsDocShell::GetSessionStorageForURI)
       let domain = uri.spec;
       try {
         if (uri.host)
           domain = uri.prePath;
       }
       catch (ex) { /* this throws for host-less URIs (such as about: or jar:) */ }
       if (storageData[domain] ||
@@ -2743,16 +2751,19 @@ SessionStoreService.prototype = {
       else
         tabbrowser.unpinTab(tab);
 
       if (tabData.hidden)
         tabbrowser.hideTab(tab);
       else
         tabbrowser.showTab(tab);
 
+      for (let name in tabData.attributes)
+        this.xulAttributes[name] = true;
+
       tabData._tabStillLoading = true;
 
       // keep the data around to prevent dataloss in case
       // a tab gets closed before it's been properly restored
       browser.__SS_data = tabData;
       browser.__SS_restoreState = TAB_STATE_NEEDS_RESTORE;
 
       // Make sure that set/getTabValue will set/read the correct data by
@@ -2858,19 +2869,18 @@ SessionStoreService.prototype = {
                                                      aIdMap, aDocIdentMap), true);
     }
     
     // make sure to reset the capabilities and attributes, in case this tab gets reused
     var disallow = (tabData.disallow)?tabData.disallow.split(","):[];
     CAPABILITIES.forEach(function(aCapability) {
       browser.docShell["allow" + aCapability] = disallow.indexOf(aCapability) == -1;
     });
-    Array.filter(tab.attributes, function(aAttr) {
-      return (_this.xulAttributes.indexOf(aAttr.name) > -1);
-    }).forEach(tab.removeAttribute, tab);
+    for (let name in this.xulAttributes)
+      tab.removeAttribute(name);
     for (let name in tabData.attributes)
       tab.setAttribute(name, tabData.attributes[name]);
     
     if (tabData.storage && browser.docShell instanceof Ci.nsIDocShell)
       this._deserializeSessionStorage(tabData.storage, browser.docShell);
     
     // notify the tabbrowser that the tab chrome has been restored
     var event = aWindow.document.createEvent("Events");
--- a/build/manifestparser.py
+++ b/build/manifestparser.py
@@ -50,20 +50,20 @@ Mozilla universal manifest parser
 
 import os
 import re
 import shutil
 import sys
 from fnmatch import fnmatch
 from optparse import OptionParser
 
-version = '0.5.2' # package version
+version = '0.5.3' # package version
 try:
     from setuptools import setup
-except ImportError:
+except:
     setup = None
 
 # we need relpath, but it is introduced in python 2.6
 # http://docs.python.org/library/os.path.html
 try:
     relpath = os.path.relpath
 except AttributeError:
     def relpath(path, start):
--- a/build/mobile/remoteautomation.py
+++ b/build/mobile/remoteautomation.py
@@ -74,16 +74,22 @@ class RemoteAutomation(Automation):
 
     # Set up what we need for the remote environment
     def environment(self, env = None, xrePath = None, crashreporter = True):
         # Because we are running remote, we don't want to mimic the local env
         # so no copying of os.environ
         if env is None:
             env = {}
 
+        # Except for the mochitest results table hiding option, which isn't
+        # passed to runtestsremote.py as an actual option, but through the
+        # MOZ_CRASHREPORTER_DISABLE environment variable.
+        if 'MOZ_HIDE_RESULTS_TABLE' in os.environ:
+            env['MOZ_HIDE_RESULTS_TABLE'] = os.environ['MOZ_HIDE_RESULTS_TABLE']
+
         if crashreporter:
             env['MOZ_CRASHREPORTER_NO_REPORT'] = '1'
             env['MOZ_CRASHREPORTER'] = '1'
         else:
             env['MOZ_CRASHREPORTER_DISABLE'] = '1'
 
         return env
 
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..be1632d8ca90969c3835124b7d8308360d744cea
GIT binary patch
literal 569
zc$^FHW@Zs#U|`^2h-!Fax8`u4{6QdZ2O|RmKZ6WIaz;^pZmM2xVqRuiYH>+u2qy#c
zoJ%r(+po&_l~!;wFtU6FsstO*I^iJKVFjMH_jaxeo`+W5E!_~DxM3~7!Yrf6RSU|t
z<nMnqYm@9L8;?o<e^1U}U3<MNgROaQX~u%x+X6G*3+-Z=V6cqMPW^aLz%#)Jr}7th
zt3~Et%S{Q+E9>NXXSsKe0ZVql><OuQMsF;y_dj5_@%riOx$WDuO<_meHhDgYTpP|-
z;3Y9fNn*<8zf7Eb4PvssdpWzGuF>gbe7HpE*e0fxm6fN@^YQXe*ADPke(S7yx}zgg
zZ~nG!v4pqZme21C+`||E4~e4a=XU3A>?~IU@~jvjA(4}xn39@;8WPigiDC;0?{nw1
zJ<n<f255Nd>KO(#Fbeq3*H*W;G*k~|)SEeLxwI6|WEO@1Z$>6LW?Vrp!2kk4Cc~0O
t5DOzBSRoOCW;L>*n7%+ZlnY2<_=y$bCk#Vb*+3eZfN&L%t^}FD004Z7u^0dV
new file mode 100644
--- /dev/null
+++ b/chrome/test/unit/data/test_bug564667/chrome.manifest
@@ -0,0 +1,16 @@
+# Locally defined URLs
+content  test1       test/
+locale   test1 en-US test/
+skin     test1 test  test/
+
+# Test Override
+content testOverride  test/
+override chrome://testOverride/content file:///test1/override
+
+
+# Load external manifest
+manifest loaded.manifest
+
+# Failure Cases
+overlay   chrome://test1/content/overlay.xul   chrome://test1/content/test1.xul
+style     chrome://test1/content/style.xul     chrome://test1/content/test1.css
new file mode 100644
--- /dev/null
+++ b/chrome/test/unit/data/test_bug564667/loaded.manifest
@@ -0,0 +1,2 @@
+content  test2         test/
+locale   test2  en-US  test/
new file mode 100644
--- /dev/null
+++ b/chrome/test/unit/test_bug564667.js
@@ -0,0 +1,155 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ *      the Mozilla Foundation.
+ *
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *      Hernan Rodriguez Colmeiro <colmeiro@gmail.com>.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * 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 *****
+ */
+
+const UNPACKAGED_ADDON = do_get_file("data/test_bug564667");
+const PACKAGED_ADDON = do_get_file("data/test_bug564667.xpi");
+
+var gIOS = Cc["@mozilla.org/network/io-service;1"].
+           getService(Ci.nsIIOService);
+
+var gCR = Cc["@mozilla.org/chrome/chrome-registry;1"].
+          getService(Ci.nsIChromeRegistry).
+          QueryInterface(Ci.nsIXULOverlayProvider);
+
+/*
+ * Checks that a mapping was added
+ */
+function test_mapping(chromeURL, target) {
+  var uri = gIOS.newURI(chromeURL, null, null);
+
+  try {
+    var result = gCR.convertChromeURL(uri);
+    do_check_eq(result.spec, target);
+  }
+  catch (ex) {
+    do_throw(chromeURL + " not Registered");
+  }
+}
+
+/*
+ * Checks that a mapping was removed
+ */
+function test_removed_mapping(chromeURL, target) {
+  var uri = gIOS.newURI(chromeURL, null, null);
+  try {
+    var result = gCR.convertChromeURL(uri);
+    do_throw(chromeURL + " not removed");
+  }
+  catch (ex) {
+    // This should throw
+  }
+}
+
+/*
+ * Checks if any overlay was added after loading
+ * the manifest files
+ *
+ * @param type The type of overlay: overlay|style
+ */
+function test_no_overlays(chromeURL, target, type) {
+  var type = type || "overlay";
+  var uri = gIOS.newURI(chromeURL, null, null);
+  var present = false, elem;
+
+  var overlays = (type == "overlay") ?
+      gCR.getXULOverlays(uri) : gCR.getStyleOverlays(uri);
+
+  // We shouldn't be allowed to register overlays nor styles
+  if (overlays.hasMoreElements()) {
+    if (type == "styles")
+      do_throw("Style Registered: " + chromeURL);
+    else
+      do_throw("Overlay Registered: " + chromeURL);
+  }
+}
+
+function testManifest(manifestPath, baseURI) {
+
+  // ------------------  Add manifest file ------------------------
+  Components.manager.addBootstrappedManifestLocation(manifestPath);
+
+  // Test Adding Content URL
+  test_mapping("chrome://test1/content", baseURI + "test/test1.xul");
+
+  // Test Adding Locale URL
+  test_mapping("chrome://test1/locale", baseURI + "test/test1.dtd");
+
+  // Test Adding Skin URL
+  test_mapping("chrome://test1/skin", baseURI + "test/test1.css");
+
+  // Test Adding Manifest URL
+  test_mapping("chrome://test2/content", baseURI + "test/test2.xul");
+  test_mapping("chrome://test2/locale", baseURI + "test/test2.dtd");
+
+  // Test Adding Override
+  test_mapping("chrome://testOverride/content", 'file:///test1/override')
+
+  // Test Not-Adding Overlays
+  test_no_overlays("chrome://test1/content/overlay.xul",
+                   "chrome://test1/content/test1.xul");
+
+  // Test Not-Adding Styles
+  test_no_overlays("chrome://test1/content/style.xul",
+                   "chrome://test1/content/test1.css", "styles");
+
+
+  // ------------------  Remove manifest file ------------------------
+  Components.manager.removeBootstrappedManifestLocation(manifestPath);
+
+  // Test Removing Content URL
+  test_removed_mapping("chrome://test1/content", baseURI + "test/test1.xul");
+
+  // Test Removing Content URL
+  test_removed_mapping("chrome://test1/locale", baseURI + "test/test1.dtd");
+
+  // Test Removing Skin URL
+  test_removed_mapping("chrome://test1/skin", baseURI + "test/test1.css");
+
+  // Test Removing Manifest URL
+  test_removed_mapping("chrome://test2/content", baseURI + "test/test2.xul");
+  test_removed_mapping("chrome://test2/locale", baseURI + "test/test2.dtd");
+}
+
+function run_test() {
+  // Test an unpackaged addon
+  testManifest(UNPACKAGED_ADDON, gIOS.newFileURI(UNPACKAGED_ADDON).spec);
+
+  // Test a packaged addon
+  testManifest(PACKAGED_ADDON, "jar:" + gIOS.newFileURI(PACKAGED_ADDON).spec + "!/");
+}
--- a/chrome/test/unit/xpcshell.ini
+++ b/chrome/test/unit/xpcshell.ini
@@ -5,12 +5,13 @@ tail =
 [test_abi.js]
 [test_bug292789.js]
 [test_bug380398.js]
 [test_bug397073.js]
 [test_bug399707.js]
 [test_bug401153.js]
 [test_bug415367.js]
 [test_bug519468.js]
+[test_bug564667.js]
 [test_crlf.js]
 [test_data_protocol_registration.js]
 [test_no_remote_registration.js]
 [test_resolve_uris.js]
--- a/config/rules.mk
+++ b/config/rules.mk
@@ -187,17 +187,17 @@ endif # XPCSHELL_TESTS
 ifdef CPP_UNIT_TESTS
 
 # Compile the tests to $(DIST)/bin.  Make lots of niceties available by default
 # through TestHarness.h, by modifying the list of includes and the libs against
 # which stuff links.
 CPPSRCS += $(CPP_UNIT_TESTS)
 SIMPLE_PROGRAMS += $(CPP_UNIT_TESTS:.cpp=$(BIN_SUFFIX))
 INCLUDES += -I$(DIST)/include/testing
-LIBS += $(XPCOM_GLUE_LDOPTS) $(NSPR_LIBS)
+LIBS += $(XPCOM_GLUE_LDOPTS) $(NSPR_LIBS) $(MOZ_JS_LIBS)
 
 # ...and run them the usual way
 check::
 	@$(EXIT_ON_ERROR) \
 	  for f in $(subst .cpp,$(BIN_SUFFIX),$(CPP_UNIT_TESTS)); do \
 	    XPCOM_DEBUG_BREAK=stack-and-abort $(RUN_TEST_PROGRAM) $(DIST)/bin/$$f; \
 	  done
 
--- a/configure.in
+++ b/configure.in
@@ -1869,20 +1869,21 @@ if test -n "$MOZ_SHARK"; then
     MOZ_PROFILING=1
     AC_DEFINE(MOZ_SHARK)
 fi
 
 dnl ========================================================
 dnl callgrind
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(callgrind,
-[  --enable-callgrind      Enable callgrind profiling],
+[  --enable-callgrind      Enable callgrind profiling. Implies --enable-profiling.],
     MOZ_CALLGRIND=1,
     MOZ_CALLGRIND= )
 if test -n "$MOZ_CALLGRIND"; then
+    MOZ_PROFILING=1
     AC_DEFINE(MOZ_CALLGRIND)
 fi
 
 dnl ========================================================
 dnl vtune
 dnl ========================================================
 MOZ_ARG_ENABLE_BOOL(vtune,
 [  --enable-vtune          Enable vtune profiling. Implies --enable-profiling.],
@@ -4282,18 +4283,21 @@ AC_CACHE_CHECK(for trouble comparing to 
                                [Foo<int> f; return (0 != f);],
                                ac_cv_trouble_comparing_to_zero=no,
                                ac_cv_trouble_comparing_to_zero=yes)])
 if test "$ac_cv_trouble_comparing_to_zero" = yes ; then
   AC_DEFINE(HAVE_CPP_TROUBLE_COMPARING_TO_ZERO)
 fi
 
 # try harder, when checking for __thread support, see bug 521750 comment #33 and below
+# We pass MOZ_OPTIMIZE_LDFLAGS to the linker because if dead_strip is
+# enabled, the linker in xcode 4.1 will crash. Without this it would crash when
+# linking XUL.
 _SAVE_LDFLAGS=$LDFLAGS
-LDFLAGS="$LDFLAGS $DSO_PIC_CFLAGS $DSO_LDOPTS"
+LDFLAGS="$LDFLAGS $DSO_PIC_CFLAGS $DSO_LDOPTS $MOZ_OPTIMIZE_LDFLAGS"
 AC_CACHE_CHECK(for __thread keyword for TLS variables,
                ac_cv_thread_keyword,
                [AC_TRY_LINK([__thread bool tlsIsMainThread = false;],
                             [return tlsIsMainThread;],
                             ac_cv_thread_keyword=yes,
                             ac_cv_thread_keyword=no)])
 LDFLAGS=$_SAVE_LDFLAGS
 if test "$ac_cv_thread_keyword" = yes; then
@@ -7544,17 +7548,17 @@ else
       if test -z "$MOZ_DEBUG"; then
         WIN32_CRT_LIBS="msvcrt.lib msvcprt.lib"
       else
         WIN32_CRT_LIBS="msvcrtd.lib msvcprtd.lib"
       fi
       dnl Look for a broken crtdll.obj
       WIN32_CRTDLL_FULLPATH=`lib -nologo -list $WIN32_CRT_LIBS | grep crtdll\\.obj`
       lib -NOLOGO -OUT:crtdll.obj $WIN32_CRT_LIBS -EXTRACT:$WIN32_CRTDLL_FULLPATH
-      if grep -q __imp__\{0,1\}free crtdll.obj; then
+      if grep -q '__imp__\{0,1\}free' crtdll.obj; then
         MOZ_MEMORY_LDFLAGS='-MANIFEST:NO -LIBPATH:$(DIST)/lib -NODEFAULTLIB:msvcrt -NODEFAULTLIB:msvcrtd -NODEFAULTLIB:msvcprt -NODEFAULTLIB:msvcprtd -DEFAULTLIB:mozcrt'
       else
         MOZ_MEMORY_LDFLAGS='$(DIST)/../memory/jemalloc/jemalloc.lib'
       fi
       rm crtdll.obj
     fi
 
     dnl Also pass this to NSPR/NSS
--- a/content/base/public/Makefile.in
+++ b/content/base/public/Makefile.in
@@ -72,16 +72,17 @@ nsIXPathEvaluatorInternal.h \
 mozISanitizingSerializer.h \
 nsCaseTreatment.h \
 nsContentCID.h \
 nsCopySupport.h \
 nsContentCreatorFunctions.h \
 nsDOMFile.h \
 nsLineBreaker.h \
 nsReferencedElement.h \
+nsTreeSanitizer.h \
 nsXMLNameSpaceMap.h \
 nsDOMEventTargetWrapperCache.h \
 $(NULL)
 
 EXPORTS_NAMESPACES = mozilla/dom
 
 EXPORTS_mozilla/dom = \
 		Element.h \
--- a/content/base/public/nsContentCID.h
+++ b/content/base/public/nsContentCID.h
@@ -148,40 +148,24 @@
 // {d4f2b600-b5c1-11d6-b483-cc97c63e567c}
 #define NS_HTMLFRAGMENTSINK_CID \
 { 0xd4f2b600, 0xb5c1, 0x11d6, { 0xb4, 0x83, 0xcc, 0x97, 0xc6, 0x3e, 0x56, 0x7c } }
 
 // {13111d00-ce81-11d6-8082-ecf3665af67c}
 #define NS_HTMLFRAGMENTSINK2_CID \
 { 0x13111d00, 0xce81, 0x11d6, { 0x80, 0x82, 0xec, 0xf3, 0x66, 0x5a, 0xf6, 0x7c } }
 
-// {A47E9526-6E48-4574-9D6C-3164E271F74E}
-#define NS_HTMLPARANOIDFRAGMENTSINK_CID \
-{ 0xa47e9526, 0x6e48, 0x4574, { 0x9d, 0x6c, 0x31, 0x64, 0xe2, 0x71, 0xf7, 0x4e } }
-
-// {35aab9d8-db42-4c82-8aba-fad2b1d8f465}
-#define NS_HTMLPARANOIDFRAGMENTSINK2_CID \
-{ 0x35aab9d8, 0xdb42, 0x4c82, { 0x8a, 0xba, 0xfa, 0xd2, 0xb1, 0xd8, 0xf4, 0x65 } }
-
 // {4B664E54-72A2-4bbf-A5C2-66D4DC3066A0}
 #define NS_XMLFRAGMENTSINK_CID \
 { 0x4b664e54, 0x72a2, 0x4bbf, { 0xa5, 0xc2, 0x66, 0xd4, 0xdc, 0x30, 0x66, 0xa0 } }
 
 // {4DC30689-929D-425e-A709-082C6294E542}
 #define NS_XMLFRAGMENTSINK2_CID \
 { 0x4dc30689, 0x929d, 0x425e, { 0xa7, 0x9, 0x8, 0x2c, 0x62, 0x94, 0xe5, 0x42 } }
 
-// {2D78BBF0-E26C-482B-92B3-78A7B2AFC8F7}
-#define NS_XHTMLPARANOIDFRAGMENTSINK_CID  \
-{ 0x2d78bbf0, 0xe26c, 0x482b, { 0x92, 0xb3, 0x78, 0xa7, 0xb2, 0xaf, 0xc8, 0xf7} }
-
-// {921dac9c-ffd4-4b5c-9901-4015b03862e6}
-#define NS_XHTMLPARANOIDFRAGMENTSINK2_CID  \
-{ 0x921dac9c, 0xffd4, 0x4b5c, { 0x99, 0x01, 0x40, 0x15, 0xb0, 0x38, 0x62, 0xe6} }
-
 // {3986B301-097C-11d3-BF87-00105A1B0627}
 #define NS_XULPOPUPLISTENER_CID \
 { 0x3986b301, 0x97c, 0x11d3, { 0xbf, 0x87, 0x0, 0x10, 0x5a, 0x1b, 0x6, 0x27 } }
 
 // {1F5C1721-7DC3-11d3-BF87-00105A1B0627}
 #define NS_XULCONTROLLERS_CID \
 { 0x1f5c1721, 0x7dc3, 0x11d3, { 0xbf, 0x87, 0x0, 0x10, 0x5a, 0x1b, 0x6, 0x27 } }
 
--- a/content/base/public/nsContentUtils.h
+++ b/content/base/public/nsContentUtils.h
@@ -75,16 +75,19 @@ static fp_except_t oldmask = fpsetmask(~
 #include "nsIDOMEvent.h"
 #include "nsTArray.h"
 #include "nsTextFragment.h"
 #include "nsReadableUtils.h"
 #include "mozilla/AutoRestore.h"
 #include "nsINode.h"
 #include "nsHashtable.h"
 #include "nsIDOMNode.h"
+#include "nsAHtml5FragmentParser.h"
+#include "nsIFragmentContentSink.h"
+#include "nsMathUtils.h"
 
 struct nsNativeKeyEvent; // Don't include nsINativeKeyBindings.h here: it will force strange compilation error!
 
 class nsIDOMScriptObjectFactory;
 class nsIXPConnect;
 class nsIContent;
 class nsIDOMKeyEvent;
 class nsIDocument;
@@ -1032,26 +1035,59 @@ public:
    *
    * Note! In the HTML case with the HTML5 parser enabled, this is only called
    * from Range.createContextualFragment() and the implementation here is
    * quirky accordingly (html context node behaves like a body context node).
    * If you don't want that quirky behavior, don't use this method as-is!
    *
    * @param aContextNode the node which is used to resolve namespaces
    * @param aFragment the string which is parsed to a DocumentFragment
-   * @param aWillOwnFragment is PR_TRUE if ownership of the fragment should be
-   *                         transferred to the caller.
-   * @param aReturn [out] the created DocumentFragment
+   * @param aReturn the resulting fragment
+   * @param aPreventScriptExecution whether to mark scripts as already started
    */
   static nsresult CreateContextualFragment(nsINode* aContextNode,
                                            const nsAString& aFragment,
-                                           PRBool aWillOwnFragment,
+                                           PRBool aPreventScriptExecution,
                                            nsIDOMDocumentFragment** aReturn);
 
   /**
+   * Invoke the fragment parsing algorithm (innerHTML) using the HTML parser.
+   *
+   * @param aSourceBuffer the string being set as innerHTML
+   * @param aTargetNode the target container
+   * @param aContextLocalName local name of context node
+   * @param aContextNamespace namespace of context node
+   * @param aQuirks true to make <table> not close <p>
+   * @param aPreventScriptExecution true to prevent scripts from executing;
+   *        don't set to false when parsing into a target node that has been
+   *        bound to tree.
+   */
+  static void ParseFragmentHTML(const nsAString& aSourceBuffer,
+                                nsIContent* aTargetNode,
+                                nsIAtom* aContextLocalName,
+                                PRInt32 aContextNamespace,
+                                PRBool aQuirks,
+                                PRBool aPreventScriptExecution);
+
+  /**
+   * Invoke the fragment parsing algorithm (innerHTML) using the XML parser.
+   *
+   * @param aSourceBuffer the string being set as innerHTML
+   * @param aTargetNode the target container
+   * @param aTagStack the namespace mapping context
+   * @param aPreventExecution whether to mark scripts as already started
+   * @param aReturn the result fragment
+   */
+  static nsresult ParseFragmentXML(const nsAString& aSourceBuffer,
+                                   nsIDocument* aDocument,
+                                   nsTArray<nsString>& aTagStack,
+                                   PRBool aPreventScriptExecution,
+                                   nsIDOMDocumentFragment** aReturn);
+
+  /**
    * Creates a new XML document, which is marked to be loaded as data.
    *
    * @param aNamespaceURI Namespace for the root element to create and insert in
    *                      the document. Only used if aQualifiedName is not
    *                      empty.
    * @param aQualifiedName Qualified name for the root element to create and
    *                       insert in the document. If empty no root element will
    *                       be created.
@@ -1659,16 +1695,22 @@ public:
   /**
    * Determine whether a content node is focused or not,
    *
    * @param aContent the content node to check
    * @return true if the content node is focused, false otherwise.
    */
   static PRBool IsFocusedContent(const nsIContent *aContent);
 
+  static void GetShiftText(nsAString& text);
+  static void GetControlText(nsAString& text);
+  static void GetMetaText(nsAString& text);
+  static void GetAltText(nsAString& text);
+  static void GetModifierSeparatorText(nsAString& text);
+
   /**
    * Returns if aContent has a tabbable subdocument.
    * A sub document isn't tabbable when it's a zombie document.
    *
    * @param aElement element to test.
    *
    * @return Whether the subdocument is tabbable.
    */
@@ -1683,16 +1725,21 @@ public:
   static void FlushLayoutForTree(nsIDOMWindow* aWindow);
 
   /**
    * Returns true if content with the given principal is allowed to use XUL
    * and XBL and false otherwise.
    */
   static bool AllowXULXBLForPrincipal(nsIPrincipal* aPrincipal);
 
+  /**
+   * Perform cleanup that's appropriate for XPCOM shutdown.
+   */
+  static void XPCOMShutdown();
+
   enum ContentViewerType
   {
       TYPE_UNSUPPORTED,
       TYPE_CONTENT,
       TYPE_PLUGIN,
       TYPE_UNKNOWN
   };
 
@@ -1745,16 +1792,20 @@ private:
                                 nsIPrincipal* aPrincipal);
 
   static nsresult WrapNative(JSContext *cx, JSObject *scope,
                              nsISupports *native, nsWrapperCache *cache,
                              const nsIID* aIID, jsval *vp,
                              nsIXPConnectJSObjectHolder** aHolder,
                              PRBool aAllowWrapping);
 
+  static void InitializeModifierStrings();
+
+  static void DropFragmentParsers();
+
   static nsIDOMScriptObjectFactory *sDOMScriptObjectFactory;
 
   static nsIXPConnect *sXPConnect;
 
   static nsIScriptSecurityManager *sSecurityManager;
 
   static nsIThreadJSContextStack *sThreadJSContextStack;
 
@@ -1807,16 +1858,26 @@ private:
   static nsCOMArray<nsIRunnable>* sBlockedScriptRunners;
   static PRUint32 sRunnersCountAtFirstBlocker;
   static PRUint32 sScriptBlockerCountWhereRunnersPrevented;
 
   static nsIInterfaceRequestor* sSameOriginChecker;
 
   static PRBool sIsHandlingKeyBoardEvent;
   static PRBool sAllowXULXBL_for_file;
+
+  static nsAHtml5FragmentParser* sHTMLFragmentParser;
+  static nsIParser* sXMLFragmentParser;
+  static nsIFragmentContentSink* sXMLFragmentSink;
+
+  static nsString* sShiftText;
+  static nsString* sControlText;
+  static nsString* sMetaText;
+  static nsString* sAltText;
+  static nsString* sModifierSeparator;
 };
 
 #define NS_HOLD_JS_OBJECTS(obj, clazz)                                         \
   nsContentUtils::HoldJSObjects(NS_CYCLE_COLLECTION_UPCAST(obj, clazz),        \
                                 &NS_CYCLE_COLLECTION_NAME(clazz))
 
 #define NS_DROP_JS_OBJECTS(obj, clazz)                                         \
   nsContentUtils::DropJSObjects(NS_CYCLE_COLLECTION_UPCAST(obj, clazz))
@@ -1970,59 +2031,47 @@ public:
 #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
-  return finite(f);
-#endif
-}
-
-/*
  * In the following helper macros we exploit the fact that the result of a
  * series of additions will not be finite if any one of the operands in the
  * series is not finite.
  */
 #define NS_ENSURE_FINITE(f, rv)                                               \
-  if (!NS_FloatIsFinite(f)) {                                                 \
+  if (!NS_finite(f)) {                                                        \
     return (rv);                                                              \
   }
 
 #define NS_ENSURE_FINITE2(f1, f2, rv)                                         \
-  if (!NS_FloatIsFinite((f1)+(f2))) {                                         \
+  if (!NS_finite((f1)+(f2))) {                                                \
     return (rv);                                                              \
   }
 
 #define NS_ENSURE_FINITE3(f1, f2, f3, rv)                                     \
-  if (!NS_FloatIsFinite((f1)+(f2)+(f3))) {                                    \
+  if (!NS_finite((f1)+(f2)+(f3))) {                                           \
     return (rv);                                                              \
   }
 
 #define NS_ENSURE_FINITE4(f1, f2, f3, f4, rv)                                 \
-  if (!NS_FloatIsFinite((f1)+(f2)+(f3)+(f4))) {                               \
+  if (!NS_finite((f1)+(f2)+(f3)+(f4))) {                                      \
     return (rv);                                                              \
   }
 
 #define NS_ENSURE_FINITE5(f1, f2, f3, f4, f5, rv)                             \
-  if (!NS_FloatIsFinite((f1)+(f2)+(f3)+(f4)+(f5))) {                          \
+  if (!NS_finite((f1)+(f2)+(f3)+(f4)+(f5))) {                                 \
     return (rv);                                                              \
   }
 
 #define NS_ENSURE_FINITE6(f1, f2, f3, f4, f5, f6, rv)                         \
-  if (!NS_FloatIsFinite((f1)+(f2)+(f3)+(f4)+(f5)+(f6))) {                     \
+  if (!NS_finite((f1)+(f2)+(f3)+(f4)+(f5)+(f6))) {                            \
     return (rv);                                                              \
   }
 
 // Deletes a linked list iteratively to avoid blowing up the stack (bug 460444).
 #define NS_CONTENT_DELETE_LIST_MEMBER(type_, ptr_, member_)                   \
   {                                                                           \
     type_ *cur = (ptr_)->member_;                                             \
     (ptr_)->member_ = nsnull;                                                 \
--- a/content/base/public/nsIDocument.h
+++ b/content/base/public/nsIDocument.h
@@ -121,18 +121,18 @@ class Loader;
 namespace dom {
 class Link;
 class Element;
 } // namespace dom
 } // namespace mozilla
 
 
 #define NS_IDOCUMENT_IID \
-{ 0x18e4d4bd, 0x006b, 0x4008, \
-  { 0x90, 0x05, 0x27, 0x57, 0x35, 0xf0, 0xd4, 0x85 } }
+{ 0xfac563fb, 0x2b6a, 0x4ac8, \
+ { 0x85, 0xf7, 0xd5, 0x14, 0x4b, 0x3e, 0xce, 0x78 } }
 
 // 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)
@@ -1142,26 +1142,16 @@ public:
     return mMayStartLayout;
   }
 
   void SetMayStartLayout(PRBool aMayStartLayout)
   {
     mMayStartLayout = aMayStartLayout;
   }
 
-  // This method should return an addrefed nsIParser* or nsnull. Implementations
-  // should transfer ownership of the parser to the caller.
-  virtual already_AddRefed<nsIParser> GetFragmentParser() {
-    return nsnull;
-  }
-
-  virtual void SetFragmentParser(nsIParser* aParser) {
-    // Do nothing.
-  }
-
   already_AddRefed<nsIDocumentEncoder> GetCachedEncoder()
   {
     return mCachedEncoder.forget();
   }
 
   void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder)
   {
     mCachedEncoder = aEncoder;
@@ -1381,17 +1371,18 @@ public:
    */
   nsIDocument* GetOriginalDocument() { return mOriginalDocument; }
 
   /**
    * Called by nsParser to preload images. Can be removed and code moved
    * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
    * parser-module is linked with gklayout-module.
    */
-  virtual void MaybePreLoadImage(nsIURI* uri) = 0;
+  virtual void MaybePreLoadImage(nsIURI* uri,
+                                 const nsAString& aCrossOriginAttr) = 0;
 
   /**
    * Called by nsParser to preload style sheets.  Can also be merged into
    * the parser if and when the parser is merged with libgklayout.
    */
   virtual void PreloadStyle(nsIURI* aURI, const nsAString& aCharset) = 0;
 
   /**
--- a/content/base/public/nsINode.h
+++ b/content/base/public/nsINode.h
@@ -1098,29 +1098,51 @@ public:
    * Get the next node in the pre-order tree traversal of the DOM.  If
    * aRoot is non-null, then it must be an ancestor of |this|
    * (possibly equal to |this|) and only nodes that are descendants of
    * aRoot, not including aRoot itself, will be returned.  Returns
    * null if there are no more nodes to traverse.
    */
   nsIContent* GetNextNode(const nsINode* aRoot = nsnull) const
   {
+    return GetNextNodeImpl(aRoot, PR_FALSE);
+  }
+
+  /**
+   * Get the next node in the pre-order tree traversal of the DOM but ignoring
+   * the children of this node.  If aRoot is non-null, then it must be an
+   * ancestor of |this| (possibly equal to |this|) and only nodes that are
+   * descendants of aRoot, not including aRoot itself, will be returned.
+   * Returns null if there are no more nodes to traverse.
+   */
+  nsIContent* GetNextNonChildNode(const nsINode* aRoot = nsnull) const
+  {
+    return GetNextNodeImpl(aRoot, PR_TRUE);
+  }
+
+private:
+
+  nsIContent* GetNextNodeImpl(const nsINode* aRoot,
+                              const PRBool aSkipChildren) const
+  {
     // Can't use nsContentUtils::ContentIsDescendantOf here, since we
     // can't include it here.
 #ifdef DEBUG
     if (aRoot) {
       const nsINode* cur = this;
       for (; cur; cur = cur->GetNodeParent())
         if (cur == aRoot) break;
       NS_ASSERTION(cur, "aRoot not an ancestor of |this|?");
     }
 #endif
-    nsIContent* kid = GetFirstChild();
-    if (kid) {
-      return kid;
+    if (!aSkipChildren) {
+      nsIContent* kid = GetFirstChild();
+      if (kid) {
+        return kid;
+      }
     }
     if (this == aRoot) {
       return nsnull;
     }
     const nsINode* cur = this;
     while (1) {
       nsIContent* next = cur->GetNextSibling();
       if (next) {
@@ -1130,16 +1152,18 @@ public:
       if (parent == aRoot) {
         return nsnull;
       }
       cur = parent;
     }
     NS_NOTREACHED("How did we get here?");
   }
 
+public:
+
   /**
    * Get the previous nsIContent in the pre-order tree traversal of the DOM.  If
    * aRoot is non-null, then it must be an ancestor of |this|
    * (possibly equal to |this|) and only nsIContents that are descendants of
    * aRoot, including aRoot itself, will be returned.  Returns
    * null if there are no more nsIContents to traverse.
    */
   nsIContent* GetPreviousContent(const nsINode* aRoot = nsnull) const
--- a/content/base/public/nsISelectionPrivate.idl
+++ b/content/base/public/nsISelectionPrivate.idl
@@ -44,23 +44,25 @@ interface nsISelectionListener;
 interface nsIContent;
 
 %{C++
 class nsFrameSelection;
 class nsIFrame;
 class nsIPresShell;
 struct nsTextRangeStyle;
 struct nsPoint;
+#include "nsIFrame.h"
 %}
 
 [ptr] native nsFrameSelection(nsFrameSelection);
 [ptr] native nsIFrame(nsIFrame);
 [ptr] native nsIPresShell(nsIPresShell);
 [ref] native constTextRangeStyleRef(const nsTextRangeStyle);
 [ref] native nsPointRef(nsPoint);
+native nsDirection(nsDirection);
 
 [scriptable, uuid(98552206-ad7a-4d2d-8ce3-b6fa2389298b)]
 interface nsISelectionPrivate : nsISupports
  {
     const short ENDOFPRECEDINGLINE=0;
     const short STARTOFNEXTLINE=1;
     
     attribute boolean interlinePosition;
@@ -123,10 +125,16 @@ interface nsISelectionPrivate : nsISuppo
 
     /**
      * Set the painting style for the range. The range must be a range in
      * the selection. The textRangeStyle will be used by text frame
      * when it is painting the selection.
      */
     [noscript] void setTextRangeStyle(in nsIDOMRange range,
                       in constTextRangeStyleRef textRangeStyle);
+
+    /**
+     * Get the direction of the selection.
+     */
+    [noscript, notxpcom] nsDirection getSelectionDirection();
+    [noscript, notxpcom] void setSelectionDirection(in nsDirection aDirection);
 };
 
new file mode 100644
--- /dev/null
+++ b/content/base/public/nsTreeSanitizer.h
@@ -0,0 +1,210 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is HTML/SVG/MathML sanitizer code.
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Foundation.
+ * Portions created by the Initial Developer are Copyright (C) 2011
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Henri Sivonen <hsivonen@iki.fi>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * 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 ***** */
+
+#ifndef nsTreeSanitizer_h_
+#define nsTreeSanitizer_h_
+
+#include "nsIContent.h"
+#include "mozilla/css/StyleRule.h"
+#include "nsIPrincipal.h"
+#include "mozilla/dom/Element.h"
+
+class NS_STACK_CLASS nsTreeSanitizer {
+
+  public:
+
+    /**
+     * The constructor.
+     *
+     * @param aAllowStyles Whether to allow <style> and style=""
+     * @param aAllowComments Whether to allow comment nodes
+     */
+    nsTreeSanitizer(PRBool aAllowStyles, PRBool aAllowComments);
+
+    static void InitializeStatics();
+    static void ReleaseStatics();
+
+    /**
+     * Sanitizes a disconnected DOM fragment freshly obtained from a parser.
+     * The argument must be of type nsINode::eDOCUMENT_FRAGMENT and,
+     * consequently, must not be in the document. Furthermore, the fragment
+     * must have just come from a parser so that it can't have mutation
+     * event listeners set on it.
+     */
+    void Sanitize(nsIContent* aFragment);
+
+  private:
+
+    /**
+     * Whether <style> and style="" are allowed.
+     */
+    PRBool mAllowStyles;
+
+    /**
+     * Whether comment nodes are allowed.
+     */
+    PRBool mAllowComments;
+
+    /**
+     * Queries if an element must be replaced with its children.
+     * @param aNamespace the namespace of the element the question is about
+     * @param aLocal the local name of the element the question is about
+     * @return true if the element must be replaced with its children and
+     *         false if the element is to be kept
+     */
+    PRBool MustFlatten(PRInt32 aNamespace, nsIAtom* aLocal);
+
+    /**
+     * Queries if an element including its children must be removed.
+     * @param aNamespace the namespace of the element the question is about
+     * @param aLocal the local name of the element the question is about
+     * @param aElement the element node itself for inspecting attributes
+     * @return true if the element and its children must be removed and
+     *         false if the element is to be kept
+     */
+    PRBool MustPrune(PRInt32 aNamespace,
+                     nsIAtom* aLocal,
+                     mozilla::dom::Element* aElement);
+
+    /**
+     * Checks if a given local name (for an attribute) is on the given list
+     * of URL attribute names.
+     * @param aURLs the list of URL attribute names
+     * @param aLocalName the name to search on the list
+     * @return true if aLocalName is on the aURLs list and false otherwise
+     */
+    PRBool IsURL(nsIAtom*** aURLs, nsIAtom* aLocalName);
+
+    /**
+     * Removes dangerous attributes from the element. If the style attribute
+     * is allowed, its value is sanitized. The values of URL attributes are
+     * sanitized, except src isn't sanitized when it is allowed to remain
+     * potentially dangerous.
+     *
+     * @param aElement the element whose attributes should be sanitized
+     * @param aAllowed the whitelist of permitted local names to use
+     * @param aURLs the local names of URL-valued attributes
+     * @param aAllowXLink whether XLink attributes are allowed
+     * @param aAllowStyle whether the style attribute is allowed
+     * @param aAllowDangerousSrc whether to leave the value of the src
+     *                           attribute unsanitized
+     */
+    void SanitizeAttributes(mozilla::dom::Element* aElement,
+                            nsTHashtable<nsISupportsHashKey>* aAllowed,
+                            nsIAtom*** aURLs,
+                            PRBool aAllowXLink,
+                            PRBool aAllowStyle,
+                            PRBool aAllowDangerousSrc);
+
+    /**
+     * Remove the named URL attribute from the element if the URL fails a
+     * security check.
+     *
+     * @param aElement the element whose attribute to possibly modify
+     * @param aNamespace the namespace of the URL attribute
+     * @param aLocalName the local name of the URL attribute
+     */
+    void SanitizeURL(mozilla::dom::Element* aElement,
+                     PRInt32 aNamespace,
+                     nsIAtom* aLocalName);
+
+    /**
+     * Checks a style rule for the presence of the 'binding' CSS property and
+     * removes that property from the rule and reserializes in case the
+     * property was found.
+     *
+     * @param aRule The style rule to check
+     * @param aRuleText the serialized mutated rule if the method returns true
+     * @return true if the rule was modified and false otherwise
+     */
+    PRBool SanitizeStyleRule(mozilla::css::StyleRule* aRule,
+                             nsAutoString &aRuleText);
+
+    /**
+     * Parses a style sheet and reserializes it with the 'binding' property
+     * removed if it was present.
+     *
+     * @param aOrigin the original style sheet source
+     * @param aSanitized the reserialization without 'binding'; only valid if
+     *                   this method return true
+     * @param aDocument the document the style sheet belongs to
+     * @param aBaseURI the base URI to use
+     * @return true if the 'binding' property was encountered and false
+     *              otherwise
+     */
+    PRBool SanitizeStyleSheet(const nsAString& aOriginal,
+                              nsAString& aSanitized,
+                              nsIDocument* aDocument,
+                              nsIURI* aBaseURI);
+
+    /**
+     * The whitelist of HTML elements.
+     */
+    static nsTHashtable<nsISupportsHashKey>* sElementsHTML;
+
+    /**
+     * The whitelist of HTML attributes.
+     */
+    static nsTHashtable<nsISupportsHashKey>* sAttributesHTML;
+
+    /**
+     * The whitelist of SVG elements.
+     */
+    static nsTHashtable<nsISupportsHashKey>* sElementsSVG;
+
+    /**
+     * The whitelist of SVG attributes.
+     */
+    static nsTHashtable<nsISupportsHashKey>* sAttributesSVG;
+
+    /**
+     * The whitelist of SVG elements.
+     */
+    static nsTHashtable<nsISupportsHashKey>* sElementsMathML;
+
+    /**
+     * The whitelist of MathML attributes.
+     */
+    static nsTHashtable<nsISupportsHashKey>* sAttributesMathML;
+
+    /**
+     * Reusable null principal for URL checks.
+     */
+    static nsIPrincipal* sNullPrincipal;
+};
+
+#endif // nsTreeSanitizer_h_
--- a/content/base/src/Makefile.in
+++ b/content/base/src/Makefile.in
@@ -134,16 +134,17 @@ CPPSRCS		= \
 		nsStubImageDecoderObserver.cpp \
 		nsStubMutationObserver.cpp \
 		nsStyledElement.cpp \
 		nsStyleLinkElement.cpp \
 		nsSyncLoadService.cpp \
 		nsTextFragment.cpp \
 		nsTextNode.cpp \
 		nsTraversal.cpp \
+		nsTreeSanitizer.cpp \
 		nsTreeWalker.cpp \
 		nsWebSocket.cpp \
 		nsXHTMLContentSerializer.cpp \
 		nsXMLContentSerializer.cpp \
 		nsXMLHttpRequest.cpp \
 		nsXMLNameSpaceMap.cpp \
 		Link.cpp \
 		nsFileDataProtocolHandler.cpp \
--- a/content/base/src/nsContentSink.cpp
+++ b/content/base/src/nsContentSink.cpp
@@ -98,16 +98,17 @@
 #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"
+#include "nsParserConstants.h"
 
 using namespace mozilla;
 
 PRLogModuleInfo* gContentSinkLogModuleInfo;
 
 class nsScriptLoaderObserverProxy : public nsIScriptLoaderObserver
 {
 public:
@@ -330,16 +331,17 @@ nsContentSink::Init(nsIDocument* aDoc,
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsContentSink::StyleSheetLoaded(nsCSSStyleSheet* aSheet,
                                 PRBool aWasAlternate,
                                 nsresult aStatus)
 {
+  NS_ASSERTION(!mFragmentMode, "How come a fragment parser observed sheets?");
   if (!aWasAlternate) {
     NS_ASSERTION(mPendingSheetCount > 0, "How'd that happen?");
     --mPendingSheetCount;
 
     if (mPendingSheetCount == 0 &&
         (mDeferredLayoutStart || mDeferredFlushTags)) {
       if (mDeferredFlushTags) {
         FlushTags();
@@ -636,17 +638,17 @@ nsContentSink::ProcessLinkHeader(nsICont
     last = end - 1;
 
     PRBool needsUnescape = PR_FALSE;
     
     // look for semicolon or comma
     while (*end != kNullCh && *end != kSemicolon && *end != kComma) {
       PRUnichar ch = *end;
 
-      if (ch == kApostrophe || ch == kQuote || ch == kLessThan) {
+      if (ch == kQuote || ch == kLessThan) {
         // quoted string
 
         PRUnichar quote = ch;
         if (quote == kLessThan) {
           quote = kGreaterThan;
         }
         
         needsUnescape = (ch == kQuote);
@@ -718,18 +720,17 @@ nsContentSink::ProcessLinkHeader(nsICont
           nsAutoString  attr(start);
           attr.StripWhitespace();
 
           PRUnichar* value = ++equals;
           while (nsCRT::IsAsciiSpace(*value)) {
             value++;
           }
 
-          if (((*value == kApostrophe) || (*value == kQuote)) &&
-              (*value == *last)) {
+          if ((*value == kQuote) && (*value == *last)) {
             *last = kNullCh;
             value++;
           }
 
           if (needsUnescape) {
             // unescape in-place
             PRUnichar* unescaped = value;
             PRUnichar *src = value;
@@ -869,22 +870,23 @@ nsContentSink::ProcessStyleLink(nsIConte
   nsresult rv = NS_NewURI(getter_AddRefs(url), aHref, nsnull,
                           mDocument->GetDocBaseURI());
   
   if (NS_FAILED(rv)) {
     // The URI is bad, move along, don't propagate the error (for now)
     return NS_OK;
   }
 
+  // If this is a fragment parser, we don't want to observe.
   PRBool isAlternate;
   rv = mCSSLoader->LoadStyleLink(aElement, url, aTitle, aMedia, aAlternate,
-                                 this, &isAlternate);
+                                 mFragmentMode ? nsnull : this, &isAlternate);
   NS_ENSURE_SUCCESS(rv, rv);
   
-  if (!isAlternate) {
+  if (!isAlternate && !mFragmentMode) {
     ++mPendingSheetCount;
     mScriptLoader->AddExecuteBlocker();
   }
 
   return NS_OK;
 }
 
 
@@ -1722,271 +1724,8 @@ nsContentSink::NotifyDocElementCreated(n
     mozilla::services::GetObserverService();
   if (observerService) {
     nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(aDoc);
     observerService->
       NotifyObservers(domDoc, "document-element-inserted",
                       EmptyString().get());
   }
 }
-
-// URIs: action, href, src, longdesc, usemap, cite
-PRBool 
-IsAttrURI(nsIAtom *aName)
-{
-  return (aName == nsGkAtoms::action ||
-          aName == nsGkAtoms::href ||
-          aName == nsGkAtoms::src ||
-          aName == nsGkAtoms::longdesc ||
-          aName == nsGkAtoms::usemap ||
-          aName == nsGkAtoms::cite ||
-          aName == nsGkAtoms::background);
-}
-
-//
-// these two lists are used by the sanitizing fragment serializers
-// Thanks to Mark Pilgrim and Sam Ruby for the initial whitelist
-//
-nsIAtom** const kDefaultAllowedTags [] = {
-  &nsGkAtoms::a,
-  &nsGkAtoms::abbr,
-  &nsGkAtoms::acronym,
-  &nsGkAtoms::address,
-  &nsGkAtoms::area,
-  &nsGkAtoms::article,
-  &nsGkAtoms::aside,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::audio,
-#endif
-  &nsGkAtoms::b,
-  &nsGkAtoms::bdo,
-  &nsGkAtoms::big,
-  &nsGkAtoms::blockquote,
-  &nsGkAtoms::br,
-  &nsGkAtoms::button,
-  &nsGkAtoms::canvas,
-  &nsGkAtoms::caption,
-  &nsGkAtoms::center,
-  &nsGkAtoms::cite,
-  &nsGkAtoms::code,
-  &nsGkAtoms::col,
-  &nsGkAtoms::colgroup,
-  &nsGkAtoms::command,
-  &nsGkAtoms::datalist,
-  &nsGkAtoms::dd,
-  &nsGkAtoms::del,
-  &nsGkAtoms::details,
-  &nsGkAtoms::dfn,
-  &nsGkAtoms::dir,
-  &nsGkAtoms::div,
-  &nsGkAtoms::dl,
-  &nsGkAtoms::dt,
-  &nsGkAtoms::em,
-  &nsGkAtoms::fieldset,
-  &nsGkAtoms::figcaption,
-  &nsGkAtoms::figure,
-  &nsGkAtoms::font,
-  &nsGkAtoms::footer,
-  &nsGkAtoms::form,
-  &nsGkAtoms::h1,
-  &nsGkAtoms::h2,
-  &nsGkAtoms::h3,
-  &nsGkAtoms::h4,
-  &nsGkAtoms::h5,
-  &nsGkAtoms::h6,
-  &nsGkAtoms::header,
-  &nsGkAtoms::hgroup,
-  &nsGkAtoms::hr,
-  &nsGkAtoms::i,
-  &nsGkAtoms::img,
-  &nsGkAtoms::input,
-  &nsGkAtoms::ins,
-  &nsGkAtoms::kbd,
-  &nsGkAtoms::label,
-  &nsGkAtoms::legend,
-  &nsGkAtoms::li,
-  &nsGkAtoms::listing,
-  &nsGkAtoms::map,
-  &nsGkAtoms::mark,
-  &nsGkAtoms::menu,
-  &nsGkAtoms::meter,
-  &nsGkAtoms::nav,
-  &nsGkAtoms::nobr,
-  &nsGkAtoms::noscript,
-  &nsGkAtoms::ol,
-  &nsGkAtoms::optgroup,
-  &nsGkAtoms::option,
-  &nsGkAtoms::output,
-  &nsGkAtoms::p,
-  &nsGkAtoms::pre,
-  &nsGkAtoms::progress,
-  &nsGkAtoms::q,
-  &nsGkAtoms::rp,
-  &nsGkAtoms::rt,
-  &nsGkAtoms::ruby,
-  &nsGkAtoms::s,
-  &nsGkAtoms::samp,
-  &nsGkAtoms::section,
-  &nsGkAtoms::select,
-  &nsGkAtoms::small,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::source,
-#endif
-  &nsGkAtoms::span,
-  &nsGkAtoms::strike,
-  &nsGkAtoms::strong,
-  &nsGkAtoms::sub,
-  &nsGkAtoms::summary,
-  &nsGkAtoms::sup,
-  &nsGkAtoms::table,
-  &nsGkAtoms::tbody,
-  &nsGkAtoms::td,
-  &nsGkAtoms::textarea,
-  &nsGkAtoms::tfoot,
-  &nsGkAtoms::th,
-  &nsGkAtoms::thead,
-  &nsGkAtoms::time,
-  &nsGkAtoms::tr,
-  &nsGkAtoms::track,
-  &nsGkAtoms::tt,
-  &nsGkAtoms::u,
-  &nsGkAtoms::ul,
-  &nsGkAtoms::var,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::video,
-#endif
-  &nsGkAtoms::wbr,
-  nsnull
-};
-
-nsIAtom** const kDefaultAllowedAttributes [] = {
-  &nsGkAtoms::abbr,
-  &nsGkAtoms::accept,
-  &nsGkAtoms::acceptcharset,
-  &nsGkAtoms::accesskey,
-  &nsGkAtoms::action,
-  &nsGkAtoms::align,
-  &nsGkAtoms::alt,
-  &nsGkAtoms::autocomplete,
-  &nsGkAtoms::autofocus,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::autoplay,
-#endif
-  &nsGkAtoms::axis,
-  &nsGkAtoms::background,
-  &nsGkAtoms::bgcolor,
-  &nsGkAtoms::border,
-  &nsGkAtoms::cellpadding,
-  &nsGkAtoms::cellspacing,
-  &nsGkAtoms::_char,
-  &nsGkAtoms::charoff,
-  &nsGkAtoms::charset,
-  &nsGkAtoms::checked,
-  &nsGkAtoms::cite,
-  &nsGkAtoms::_class,
-  &nsGkAtoms::clear,
-  &nsGkAtoms::cols,
-  &nsGkAtoms::colspan,
-  &nsGkAtoms::color,
-  &nsGkAtoms::contenteditable,
-  &nsGkAtoms::contextmenu,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::controls,
-#endif
-  &nsGkAtoms::compact,
-  &nsGkAtoms::coords,
-  &nsGkAtoms::datetime,
-  &nsGkAtoms::dir,
-  &nsGkAtoms::disabled,
-  &nsGkAtoms::draggable,
-  &nsGkAtoms::enctype,
-  &nsGkAtoms::face,
-  &nsGkAtoms::_for,
-  &nsGkAtoms::frame,
-  &nsGkAtoms::headers,
-  &nsGkAtoms::height,
-  &nsGkAtoms::hidden,
-  &nsGkAtoms::high,
-  &nsGkAtoms::href,
-  &nsGkAtoms::hreflang,
-  &nsGkAtoms::hspace,
-  &nsGkAtoms::icon,
-  &nsGkAtoms::id,
-  &nsGkAtoms::ismap,
-  &nsGkAtoms::itemid,
-  &nsGkAtoms::itemprop,
-  &nsGkAtoms::itemref,
-  &nsGkAtoms::itemscope,
-  &nsGkAtoms::itemtype,
-  &nsGkAtoms::kind,
-  &nsGkAtoms::label,
-  &nsGkAtoms::lang,
-  &nsGkAtoms::list,
-  &nsGkAtoms::longdesc,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::loop,
-  &nsGkAtoms::loopend,
-  &nsGkAtoms::loopstart,
-#endif
-  &nsGkAtoms::low,
-  &nsGkAtoms::max,
-  &nsGkAtoms::maxlength,
-  &nsGkAtoms::media,
-  &nsGkAtoms::method,
-  &nsGkAtoms::min,
-  &nsGkAtoms::mozdonotsend,
-  &nsGkAtoms::multiple,
-  &nsGkAtoms::name,
-  &nsGkAtoms::nohref,
-  &nsGkAtoms::noshade,
-  &nsGkAtoms::novalidate,
-  &nsGkAtoms::nowrap,
-  &nsGkAtoms::open,
-  &nsGkAtoms::optimum,
-  &nsGkAtoms::pattern,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::pixelratio,
-#endif
-  &nsGkAtoms::placeholder,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::playbackrate,
-  &nsGkAtoms::playcount,
-#endif
-  &nsGkAtoms::pointSize,
-#ifdef MOZ_MEDIA
-  &nsGkAtoms::poster,
-  &nsGkAtoms::preload,
-#endif
-  &nsGkAtoms::prompt,
-  &nsGkAtoms::pubdate,
-  &nsGkAtoms::radiogroup,
-  &nsGkAtoms::readonly,
-  &nsGkAtoms::rel,
-  &nsGkAtoms::required,
-  &nsGkAtoms::rev,
-  &nsGkAtoms::reversed,
-  &nsGkAtoms::role,
-  &nsGkAtoms::rows,
-  &nsGkAtoms::rowspan,
-  &nsGkAtoms::rules,
-  &nsGkAtoms::scoped,
-  &nsGkAtoms::scope,
-  &nsGkAtoms::selected,
-  &nsGkAtoms::shape,
-  &nsGkAtoms::size,
-  &nsGkAtoms::span,
-  &nsGkAtoms::spellcheck,
-  &nsGkAtoms::src,
-  &nsGkAtoms::srclang,
-  &nsGkAtoms::start,
-  &nsGkAtoms::summary,
-  &nsGkAtoms::tabindex,
-  &nsGkAtoms::target,
-  &nsGkAtoms::title,
-  &nsGkAtoms::type,
-  &nsGkAtoms::usemap,
-  &nsGkAtoms::valign,
-  &nsGkAtoms::value,
-  &nsGkAtoms::vspace,
-  &nsGkAtoms::width,
-  &nsGkAtoms::wrap,
-  nsnull
-};
--- a/content/base/src/nsContentSink.h
+++ b/content/base/src/nsContentSink.h
@@ -344,16 +344,18 @@ protected:
   // If true, we deferred notifications until sheets load
   PRUint8 mDeferredFlushTags : 1;
   // If false, we're not ourselves a document observer; that means we
   // shouldn't be performing any more content model notifications,
   // since we're not longer updating our child counts.
   PRUint8 mIsDocumentObserver : 1;
   // True if this is a fragment parser
   PRUint8 mFragmentMode : 1;
+  // True to call prevent script execution in the fragment mode.
+  PRUint8 mPreventScriptExecution : 1;
   
   //
   // -- Can interrupt parsing members --
   //
 
   // The number of tokens that have been processed since we measured
   // if it's time to return to the main event loop.
   PRUint32 mDeflectedCount;
@@ -402,14 +404,9 @@ protected:
   static PRInt32 sInteractiveTime;
   // How long to stay in perf mode after initial loading
   static PRInt32 sInitialPerfTime;
   // Should we switch between perf-mode and interactive-mode
   static PRInt32 sEnablePerfMode;
   static PRBool sCanInterruptParser;
 };
 
-// sanitizing content sink whitelists
-extern PRBool IsAttrURI(nsIAtom *aName);
-extern nsIAtom** const kDefaultAllowedTags [];
-extern nsIAtom** const kDefaultAllowedAttributes [];
-
 #endif // _nsContentSink_h_
--- a/content/base/src/nsContentUtils.cpp
+++ b/content/base/src/nsContentUtils.cpp
@@ -197,16 +197,17 @@ static NS_DEFINE_CID(kXTFServiceCID, NS_
 #include "nsIChannelPolicy.h"
 #include "nsChannelPolicy.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsContentDLF.h"
 #ifdef MOZ_MEDIA
 #include "nsHTMLMediaElement.h"
 #endif
 #include "nsDOMTouchEvent.h"
+#include "nsIScriptElement.h"
 
 #include "mozilla/Preferences.h"
 
 using namespace mozilla::dom;
 using namespace mozilla::layers;
 using namespace mozilla;
 
 const char kLoadAsData[] = "loadAsData";
@@ -251,18 +252,28 @@ PRUint32 nsContentUtils::sDOMNodeRemoved
 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;
 
+nsString* nsContentUtils::sShiftText = nsnull;
+nsString* nsContentUtils::sControlText = nsnull;
+nsString* nsContentUtils::sMetaText = nsnull;
+nsString* nsContentUtils::sAltText = nsnull;
+nsString* nsContentUtils::sModifierSeparator = nsnull;
+
 PRBool nsContentUtils::sInitialized = PR_FALSE;
 
+nsAHtml5FragmentParser* nsContentUtils::sHTMLFragmentParser = nsnull;
+nsIParser* nsContentUtils::sXMLFragmentParser = nsnull;
+nsIFragmentContentSink* nsContentUtils::sXMLFragmentSink = nsnull;
+
 static PLDHashTable sEventListenerManagersHash;
 
 class EventListenerManagerMapEntry : public PLDHashEntryHdr
 {
 public:
   EventListenerManagerMapEntry(const void *aKey)
     : mKey(aKey)
   {
@@ -377,16 +388,91 @@ nsContentUtils::Init()
   Preferences::AddBoolVarCache(&sAllowXULXBL_for_file,
                                "dom.allow_XUL_XBL_for_file");
 
   sInitialized = PR_TRUE;
 
   return NS_OK;
 }
 
+void
+nsContentUtils::GetShiftText(nsAString& text)
+{
+  if (!sShiftText)
+    InitializeModifierStrings();
+  text.Assign(*sShiftText);
+}
+
+void
+nsContentUtils::GetControlText(nsAString& text)
+{
+  if (!sControlText)
+    InitializeModifierStrings();
+  text.Assign(*sControlText);
+}
+
+void
+nsContentUtils::GetMetaText(nsAString& text)
+{
+  if (!sMetaText)
+    InitializeModifierStrings();
+  text.Assign(*sMetaText);
+}
+
+void
+nsContentUtils::GetAltText(nsAString& text)
+{
+  if (!sAltText)
+    InitializeModifierStrings();
+  text.Assign(*sAltText);
+}
+
+void
+nsContentUtils::GetModifierSeparatorText(nsAString& text)
+{
+  if (!sModifierSeparator)
+    InitializeModifierStrings();
+  text.Assign(*sModifierSeparator);
+}
+
+void
+nsContentUtils::InitializeModifierStrings()
+{
+  //load the display strings for the keyboard accelerators
+  nsCOMPtr<nsIStringBundleService> bundleService =
+    mozilla::services::GetStringBundleService();
+  nsCOMPtr<nsIStringBundle> bundle;
+  nsresult rv = NS_OK;
+  if (bundleService) {
+    rv = bundleService->CreateBundle( "chrome://global-platform/locale/platformKeys.properties",
+                                      getter_AddRefs(bundle));
+  }
+  
+  NS_ASSERTION(NS_SUCCEEDED(rv) && bundle, "chrome://global/locale/platformKeys.properties could not be loaded");
+  nsXPIDLString shiftModifier;
+  nsXPIDLString metaModifier;
+  nsXPIDLString altModifier;
+  nsXPIDLString controlModifier;
+  nsXPIDLString modifierSeparator;
+  if (bundle) {
+    //macs use symbols for each modifier key, so fetch each from the bundle, which also covers i18n
+    bundle->GetStringFromName(NS_LITERAL_STRING("VK_SHIFT").get(), getter_Copies(shiftModifier));
+    bundle->GetStringFromName(NS_LITERAL_STRING("VK_META").get(), getter_Copies(metaModifier));
+    bundle->GetStringFromName(NS_LITERAL_STRING("VK_ALT").get(), getter_Copies(altModifier));
+    bundle->GetStringFromName(NS_LITERAL_STRING("VK_CONTROL").get(), getter_Copies(controlModifier));
+    bundle->GetStringFromName(NS_LITERAL_STRING("MODIFIER_SEPARATOR").get(), getter_Copies(modifierSeparator));
+  }
+  //if any of these don't exist, we get  an empty string
+  sShiftText = new nsString(shiftModifier);
+  sMetaText = new nsString(metaModifier);
+  sAltText = new nsString(altModifier);
+  sControlText = new nsString(controlModifier);
+  sModifierSeparator = new nsString(modifierSeparator);  
+}
+
 bool nsContentUtils::sImgLoaderInitialized;
 
 void
 nsContentUtils::InitImgLoader()
 {
   sImgLoaderInitialized = true;
 
   // Ignore failure and just don't load images
@@ -1082,19 +1168,16 @@ nsContentUtils::OfflineAppAllowed(nsIPri
 }
 
 // static
 void
 nsContentUtils::Shutdown()
 {
   sInitialized = PR_FALSE;
 
-  NS_HTMLParanoidFragmentSinkShutdown();
-  NS_XHTMLParanoidFragmentSinkShutdown();
-
   NS_IF_RELEASE(sContentPolicyService);
   sTriedToGetContentPolicy = PR_FALSE;
   PRUint32 i;
   for (i = 0; i < PropertiesFile_COUNT; ++i)
     NS_IF_RELEASE(sStringBundles[i]);
 
   NS_IF_RELEASE(sStringBundleService);
   NS_IF_RELEASE(sConsoleService);
@@ -1144,16 +1227,27 @@ nsContentUtils::Shutdown()
   }
 
   NS_ASSERTION(!sBlockedScriptRunners ||
                sBlockedScriptRunners->Count() == 0,
                "How'd this happen?");
   delete sBlockedScriptRunners;
   sBlockedScriptRunners = nsnull;
 
+  delete sShiftText;
+  sShiftText = nsnull;
+  delete sControlText;  
+  sControlText = nsnull;
+  delete sMetaText;  
+  sMetaText = nsnull;
+  delete sAltText;  
+  sAltText = nsnull;
+  delete sModifierSeparator;
+  sModifierSeparator = nsnull;
+
   NS_IF_RELEASE(sSameOriginChecker);
   
   nsTextEditorState::ShutDown();
 }
 
 // static
 PRBool
 nsContentUtils::IsCallerTrustedForCapability(const char* aCapability)
@@ -3512,88 +3606,66 @@ nsContentUtils::IsValidNodeName(nsIAtom 
   return aPrefix != nsGkAtoms::xmlns &&
          (aNamespaceID == kNameSpaceID_XML || aPrefix != nsGkAtoms::xml);
 }
 
 /* static */
 nsresult
 nsContentUtils::CreateContextualFragment(nsINode* aContextNode,
                                          const nsAString& aFragment,
-                                         PRBool aWillOwnFragment,
+                                         PRBool aPreventScriptExecution,
                                          nsIDOMDocumentFragment** aReturn)
 {
   *aReturn = nsnull;
   NS_ENSURE_ARG(aContextNode);
 
-  nsresult rv;
-
   // If we don't have a document here, we can't get the right security context
   // for compiling event handlers... so just bail out.
   nsCOMPtr<nsIDocument> document = aContextNode->GetOwnerDoc();
   NS_ENSURE_TRUE(document, NS_ERROR_NOT_AVAILABLE);
 
   PRBool isHTML = document->IsHTML();
 #ifdef DEBUG
   nsCOMPtr<nsIHTMLDocument> htmlDoc = do_QueryInterface(document);
   NS_ASSERTION(!isHTML || htmlDoc, "Should have HTMLDocument here!");
 #endif
 
-  if (isHTML && nsHtml5Module::sEnabled) {
-    // See if the document has a cached fragment parser. nsHTMLDocument is the
-    // only one that should really have one at the moment.
-    nsCOMPtr<nsIParser> parser = document->GetFragmentParser();
-    if (parser) {
-      // Get the parser ready to use.
-      parser->Reset();
-    }
-    else {
-      // Create a new parser for this operation.
-      parser = nsHtml5Module::NewHtml5Parser();
-      if (!parser) {
-        return NS_ERROR_OUT_OF_MEMORY;
-      }
-    }
+  if (isHTML) {
     nsCOMPtr<nsIDOMDocumentFragment> frag;
-    rv = NS_NewDocumentFragment(getter_AddRefs(frag), document->NodeInfoManager());
-    NS_ENSURE_SUCCESS(rv, rv);
+    NS_NewDocumentFragment(getter_AddRefs(frag), document->NodeInfoManager());
     
     nsCOMPtr<nsIContent> contextAsContent = do_QueryInterface(aContextNode);
     if (contextAsContent && !contextAsContent->IsElement()) {
       contextAsContent = contextAsContent->GetParent();
       if (contextAsContent && !contextAsContent->IsElement()) {
         // can this even happen?
         contextAsContent = nsnull;
       }
     }
     
-    nsAHtml5FragmentParser* asFragmentParser =
-        static_cast<nsAHtml5FragmentParser*> (parser.get());
     nsCOMPtr<nsIContent> fragment = do_QueryInterface(frag);
-    if (contextAsContent &&
-        !(nsGkAtoms::html == contextAsContent->Tag() &&
-          contextAsContent->IsHTML())) {
-      asFragmentParser->ParseHtml5Fragment(aFragment,
-                                           fragment,
-                                           contextAsContent->Tag(),
-                                           contextAsContent->GetNameSpaceID(),
-                                           (document->GetCompatibilityMode() ==
-                                               eCompatibility_NavQuirks),
-                                           PR_FALSE);
+    if (contextAsContent && !contextAsContent->IsHTML(nsGkAtoms::html)) {
+      ParseFragmentHTML(aFragment,
+                        fragment,
+                        contextAsContent->Tag(),
+                        contextAsContent->GetNameSpaceID(),
+                        (document->GetCompatibilityMode() ==
+                            eCompatibility_NavQuirks),
+                        aPreventScriptExecution);
     } else {
-      asFragmentParser->ParseHtml5Fragment(aFragment,
-                                           fragment,
-                                           nsGkAtoms::body,
-                                           kNameSpaceID_XHTML,
-                                           (document->GetCompatibilityMode() ==
-                                               eCompatibility_NavQuirks),
-                                           PR_FALSE);
+      ParseFragmentHTML(aFragment,
+                        fragment,
+                        nsGkAtoms::body,
+                        kNameSpaceID_XHTML,
+                        (document->GetCompatibilityMode() ==
+                            eCompatibility_NavQuirks),
+                        aPreventScriptExecution);
     }
-  
-    frag.swap(*aReturn);
-    document->SetFragmentParser(parser);
+
+    frag.forget(aReturn);
     return NS_OK;
   }
 
   nsAutoTArray<nsString, 32> tagStack;
   nsAutoString uriStr, nameStr;
   nsCOMPtr<nsIContent> content = do_QueryInterface(aContextNode);
   // just in case we have a text node
   if (content && !content->IsElement())
@@ -3642,94 +3714,104 @@ nsContentUtils::CreateContextualFragment
         tagName.Append(NS_LITERAL_STRING(" xmlns=\"") + uriStr +
                        NS_LITERAL_STRING("\""));
       }
     }
 
     content = content->GetParent();
   }
 
-  nsCAutoString contentType;
-  nsAutoString buf;
-  document->GetContentType(buf);
-  LossyCopyUTF16toASCII(buf, contentType);
-
-  // See if the document has a cached fragment parser. nsHTMLDocument is the
-  // only one that should really have one at the moment.
-  nsCOMPtr<nsIParser> parser = document->GetFragmentParser();
-  if (parser) {
-    // Get the parser ready to use.
-    parser->Reset();
-  }
-  else {
-    // Create a new parser for this operation.
-    parser = do_CreateInstance(kCParserCID, &rv);
-    NS_ENSURE_SUCCESS(rv, rv);
-  }
-
-  // See if the parser already has a content sink that we can reuse.
-  nsCOMPtr<nsIFragmentContentSink> sink;
-  nsCOMPtr<nsIContentSink> contentsink = parser->GetContentSink();
-  if (contentsink) {
-    // Make sure it's the correct type.
-    if (isHTML) {
-      nsCOMPtr<nsIHTMLContentSink> htmlsink = do_QueryInterface(contentsink);
-      sink = do_QueryInterface(htmlsink);
-    }
-    else {
-      nsCOMPtr<nsIXMLContentSink> xmlsink = do_QueryInterface(contentsink);
-      sink = do_QueryInterface(xmlsink);
-    }
-  }
-
-  if (!sink) {
-    // Either there was no cached content sink or it was the wrong type. Make a
-    // new one.
-    if (isHTML) {
-      rv = NS_NewHTMLFragmentContentSink(getter_AddRefs(sink));
-    } else {
-      rv = NS_NewXMLFragmentContentSink(getter_AddRefs(sink));
-    }
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    contentsink = do_QueryInterface(sink);
-    NS_ASSERTION(contentsink, "Sink doesn't QI to nsIContentSink!");
-
-    parser->SetContentSink(contentsink);
-  }
-
-  sink->SetTargetDocument(document);
-
-  nsDTDMode mode = eDTDMode_autodetect;
-  switch (document->GetCompatibilityMode()) {
-    case eCompatibility_NavQuirks:
-      mode = eDTDMode_quirks;
-      break;
-    case eCompatibility_AlmostStandards:
-      mode = eDTDMode_almost_standards;
-      break;
-    case eCompatibility_FullStandards:
-      mode = eDTDMode_full_standards;
-      break;
-    default:
-      NS_NOTREACHED("unknown mode");
-      break;
-  }
-
-  rv = parser->ParseFragment(aFragment, nsnull, tagStack,
-                             !isHTML, contentType, mode);
-  if (NS_SUCCEEDED(rv)) {
-    rv = sink->GetFragment(aWillOwnFragment, aReturn);
-  }
-
-  document->SetFragmentParser(parser);
+  return ParseFragmentXML(aFragment,
+                          document,
+                          tagStack,
+                          aPreventScriptExecution,
+                          aReturn);
+}
+
+/* static */
+void
+nsContentUtils::DropFragmentParsers()
+{
+  NS_IF_RELEASE(sHTMLFragmentParser);
+  NS_IF_RELEASE(sXMLFragmentParser);
+  NS_IF_RELEASE(sXMLFragmentSink);
+}
+
+/* static */
+void
+nsContentUtils::XPCOMShutdown()
+{
+  nsContentUtils::DropFragmentParsers();
+}
+
+/* static */
+void
+nsContentUtils::ParseFragmentHTML(const nsAString& aSourceBuffer,
+                                  nsIContent* aTargetNode,
+                                  nsIAtom* aContextLocalName,
+                                  PRInt32 aContextNamespace,
+                                  PRBool aQuirks,
+                                  PRBool aPreventScriptExecution)
+{
+  if (!sHTMLFragmentParser) {
+    sHTMLFragmentParser =
+      static_cast<nsAHtml5FragmentParser*>(nsHtml5Module::NewHtml5Parser().get());
+    // Now sHTMLFragmentParser owns the object
+  }
+  sHTMLFragmentParser->ParseHtml5Fragment(aSourceBuffer,
+                                          aTargetNode,
+                                          aContextLocalName,
+                                          aContextNamespace,
+                                          aQuirks,
+                                          aPreventScriptExecution);
+  sHTMLFragmentParser->Reset();
+}
+
+/* static */
+nsresult
+nsContentUtils::ParseFragmentXML(const nsAString& aSourceBuffer,
+                                 nsIDocument* aDocument,
+                                 nsTArray<nsString>& aTagStack,
+                                 PRBool aPreventScriptExecution,
+                                 nsIDOMDocumentFragment** aReturn)
+{
+  if (!sXMLFragmentParser) {
+    nsCOMPtr<nsIParser> parser = do_CreateInstance(kCParserCID);
+    parser.forget(&sXMLFragmentParser);
+    // sXMLFragmentParser now owns the parser
+  }
+  if (!sXMLFragmentSink) {
+    NS_NewXMLFragmentContentSink(&sXMLFragmentSink);
+    // sXMLFragmentSink now owns the sink
+  }
+  nsCOMPtr<nsIContentSink> contentsink = do_QueryInterface(sXMLFragmentSink);
+  NS_ABORT_IF_FALSE(contentsink, "Sink doesn't QI to nsIContentSink!");
+  sXMLFragmentParser->SetContentSink(contentsink);
+
+  sXMLFragmentSink->SetTargetDocument(aDocument);
+  sXMLFragmentSink->SetPreventScriptExecution(aPreventScriptExecution);
+
+  nsresult rv =
+    sXMLFragmentParser->ParseFragment(aSourceBuffer,
+                                      aTagStack);
+  if (NS_FAILED(rv)) {
+    // Drop the fragment parser and sink that might be in an inconsistent state
+    NS_IF_RELEASE(sXMLFragmentParser);
+    NS_IF_RELEASE(sXMLFragmentSink);
+    return rv;
+  }
+
+  rv = sXMLFragmentSink->FinishFragmentParsing(aReturn);
+
+  sXMLFragmentParser->Reset();
 
   return rv;
 }
 
+
 /* static */
 nsresult
 nsContentUtils::CreateDocument(const nsAString& aNamespaceURI, 
                                const nsAString& aQualifiedName, 
                                nsIDOMDocumentType* aDoctype,
                                nsIURI* aDocumentURI, nsIURI* aBaseURI,
                                nsIPrincipal* aPrincipal,
                                nsIScriptGlobalObject* aEventObject,
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -198,16 +198,18 @@
 
 #include "mozilla/dom/Link.h"
 #include "nsIHTMLDocument.h"
 #include "nsXULAppAPI.h"
 #include "nsDOMTouchEvent.h"
 
 #include "mozilla/Preferences.h"
 
+#include "imgILoader.h"
+
 using namespace mozilla;
 using namespace mozilla::dom;
 
 typedef nsTArray<Link*> LinkArray;
 
 
 #ifdef PR_LOGGING
 static PRLogModuleInfo* gDocumentLeakPRLog;
@@ -7663,37 +7665,47 @@ FireOrClearDelayedEvents(nsTArray<nsCOMP
       if (shell) {
         shell->FireOrClearDelayedEvents(aFireEvents);
       }
     }
   }
 }
 
 void
-nsDocument::MaybePreLoadImage(nsIURI* uri)
+nsDocument::MaybePreLoadImage(nsIURI* uri, const nsAString &aCrossOriginAttr)
 {
   // Early exit if the img is already present in the img-cache
   // which indicates that the "real" load has already started and
   // that we shouldn't preload it.
   PRInt16 blockingStatus;
   if (nsContentUtils::IsImageInCache(uri) ||
       !nsContentUtils::CanLoadImage(uri, static_cast<nsIDocument *>(this),
                                     this, NodePrincipal(), &blockingStatus)) {
     return;
   }
 
+  nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
+  if (aCrossOriginAttr.LowerCaseEqualsLiteral("anonymous")) {
+    loadFlags |= imgILoader::LOAD_CORS_ANONYMOUS;
+  } else if (aCrossOriginAttr.LowerCaseEqualsLiteral("use-credentials")) {
+    loadFlags |= imgILoader::LOAD_CORS_USE_CREDENTIALS;
+  }
+  // else should we err on the side of not doing the preload if
+  // aCrossOriginAttr is nonempty?  Let's err on the side of doing the
+  // preload as CORS_NONE.
+
   // Image not in cache - trigger preload
   nsCOMPtr<imgIRequest> request;
   nsresult rv =
     nsContentUtils::LoadImage(uri,
                               this,
                               NodePrincipal(),
                               mDocumentURI, // uri of document used as referrer
                               nsnull,       // no observer
-                              nsIRequest::LOAD_NORMAL,
+                              loadFlags,
                               getter_AddRefs(request));
 
   // Pin image-reference to avoid evicting it from the img-cache before
   // the "real" load occurs. Unpinned in DispatchContentLoadedEvents and
   // unlink
   if (NS_SUCCEEDED(rv)) {
     mPreloadingImages.AppendObject(request);
   }
@@ -8384,12 +8396,12 @@ nsIDocument::SizeOf() const
 
   return size;
 }
 
 PRInt64
 nsDocument::SizeOf() const
 {
   PRInt64 size = MemoryReporter::GetBasicSize<nsDocument, nsIDocument>(this);
-  size += mAttrStyleSheet ? mAttrStyleSheet->SizeOf() : 0;
+  size += mAttrStyleSheet ? mAttrStyleSheet->DOMSizeOf() : 0;
   return size;
 }
 
--- a/content/base/src/nsDocument.h
+++ b/content/base/src/nsDocument.h
@@ -880,17 +880,18 @@ public:
   void SetLoadedAsData(PRBool aLoadedAsData) { mLoadedAsData = aLoadedAsData; }
 
   nsresult CloneDocHelper(nsDocument* clone) const;
 
   void MaybeInitializeFinalizeFrameLoaders();
 
   void MaybeEndOutermostXBLUpdate();
 
-  virtual void MaybePreLoadImage(nsIURI* uri);
+  virtual void MaybePreLoadImage(nsIURI* uri,
+                                 const nsAString &aCrossOriginAttr);
 
   virtual void PreloadStyle(nsIURI* uri, const nsAString& charset);
 
   virtual nsresult LoadChromeSheetSync(nsIURI* uri, PRBool isAgentSheet,
                                        nsCSSStyleSheet** sheet);
 
   virtual nsISupports* GetCurrentContentSink();
 
--- a/content/base/src/nsGenericElement.cpp
+++ b/content/base/src/nsGenericElement.cpp
@@ -4308,30 +4308,25 @@ nsGenericElement::AddScriptEventListener
   nsIDocument *ownerDoc = GetOwnerDoc();
   if (!ownerDoc || ownerDoc->IsLoadedAsData()) {
     // Make this a no-op rather than throwing an error to avoid
     // the error causing problems setting the attribute.
     return NS_OK;
   }
 
   NS_PRECONDITION(aEventName, "Must have event name!");
-  nsCOMPtr<nsISupports> target;
   PRBool defer = PR_TRUE;
-  nsRefPtr<nsEventListenerManager> manager;
-
-  GetEventListenerManagerForAttr(getter_AddRefs(manager),
-                                 getter_AddRefs(target),
-                                 &defer);
+  nsEventListenerManager* manager = GetEventListenerManagerForAttr(&defer);
   if (!manager) {
     return NS_OK;
   }
 
   defer = defer && aDefer; // only defer if everyone agrees...
   PRUint32 lang = GetScriptTypeID();
-  manager->AddScriptEventListener(target, aEventName, aValue, lang, defer,
+  manager->AddScriptEventListener(aEventName, aValue, lang, defer,
                                   !nsContentUtils::IsChromeDoc(ownerDoc));
   return NS_OK;
 }
 
 
 //----------------------------------------------------------------------
 
 const nsAttrName*
@@ -4590,27 +4585,21 @@ nsGenericElement::SetMappedAttribute(nsI
                                      nsIAtom* aName,
                                      nsAttrValue& aValue,
                                      nsresult* aRetval)
 {
   *aRetval = NS_OK;
   return PR_FALSE;
 }
 
-nsresult
-nsGenericElement::GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                                 nsISupports** aTarget,
-                                                 PRBool* aDefer)
-{
-  *aManager = GetListenerManager(PR_TRUE);
+nsEventListenerManager*
+nsGenericElement::GetEventListenerManagerForAttr(PRBool* aDefer)
+{
   *aDefer = PR_TRUE;
-  NS_ENSURE_STATE(*aManager);
-  NS_ADDREF(*aManager);
-  NS_ADDREF(*aTarget = static_cast<nsIContent*>(this));
-  return NS_OK;
+  return GetListenerManager(PR_TRUE);
 }
 
 nsGenericElement::nsAttrInfo
 nsGenericElement::GetAttrInfo(PRInt32 aNamespaceID, nsIAtom* aName) const
 {
   NS_ASSERTION(nsnull != aName, "must have attribute name");
   NS_ASSERTION(aNamespaceID != kNameSpaceID_Unknown,
                "must have a real namespace ID!");
--- a/content/base/src/nsGenericElement.h
+++ b/content/base/src/nsGenericElement.h
@@ -779,20 +779,18 @@ protected:
   {
     return NS_OK;
   }
 
   /**
    * Hook to allow subclasses to produce a different nsEventListenerManager if
    * needed for attachment of attribute-defined handlers
    */
-  virtual nsresult
-    GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                   nsISupports** aTarget,
-                                   PRBool* aDefer);
+  virtual nsEventListenerManager*
+    GetEventListenerManagerForAttr(PRBool* aDefer);
 
   /**
    * Copy attributes and state to another element
    * @param aDest the object to copy to
    */
   nsresult CopyInnerTo(nsGenericElement* aDest) const;
 
   /**
--- a/content/base/src/nsGkAtomList.h
+++ b/content/base/src/nsGkAtomList.h
@@ -149,16 +149,17 @@ GK_ATOM(blockquote, "blockquote")
 GK_ATOM(blur, "blur")
 GK_ATOM(body, "body")
 GK_ATOM(boolean, "boolean")
 GK_ATOM(border, "border")
 GK_ATOM(bordercolor, "bordercolor")
 GK_ATOM(both, "both")
 GK_ATOM(bottom, "bottom")
 GK_ATOM(bottomend, "bottomend")
+GK_ATOM(bottomstart, "bottomstart")
 GK_ATOM(bottomleft, "bottomleft")
 GK_ATOM(bottommargin, "bottommargin")
 GK_ATOM(bottompadding, "bottompadding")
 GK_ATOM(bottomright, "bottomright")
 GK_ATOM(box, "box")
 GK_ATOM(br, "br")
 GK_ATOM(braille, "braille")
 GK_ATOM(broadcast, "broadcast")
--- a/content/base/src/nsHTMLContentSerializer.cpp
+++ b/content/base/src/nsHTMLContentSerializer.cpp
@@ -68,16 +68,17 @@
 #include "nsLWBrkCIID.h"
 #include "nsIScriptElement.h"
 #include "nsAttrName.h"
 #include "nsIDocShell.h"
 #include "nsIEditorDocShell.h"
 #include "nsIEditor.h"
 #include "nsIHTMLEditor.h"
 #include "mozilla/dom/Element.h"
+#include "nsParserConstants.h"
 
 using namespace mozilla::dom;
 
 static const PRInt32 kLongLineLen = 128;
 
 nsresult NS_NewHTMLContentSerializer(nsIContentSerializer** aSerializer)
 {
   nsHTMLContentSerializer* it = new nsHTMLContentSerializer();
--- a/content/base/src/nsParserUtils.cpp
+++ b/content/base/src/nsParserUtils.cpp
@@ -35,22 +35,22 @@
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Namespace class for some static parsing-related methods.
  */
 
 #include "nsParserUtils.h"
-#include "nsIParser.h" // for kQuote et. al.
 #include "jsapi.h"
 #include "nsReadableUtils.h"
 #include "nsCRT.h"
 #include "nsContentUtils.h"
 #include "nsIParserService.h"
+#include "nsParserConstants.h"
 
 #define SKIP_WHITESPACE(iter, end_iter, end_res)                 \
   while ((iter) != (end_iter) && nsCRT::IsAsciiSpace(*(iter))) { \
     ++(iter);                                                    \
   }                                                              \
   if ((iter) == (end_iter)) {                                    \
     return (end_res);                                            \
   }
--- a/content/base/src/nsRange.cpp
+++ b/content/base/src/nsRange.cpp
@@ -2049,17 +2049,17 @@ nsRange::Detach()
 
 // nsIDOMNSRange interface
 NS_IMETHODIMP    
 nsRange::CreateContextualFragment(const nsAString& aFragment,
                                   nsIDOMDocumentFragment** aReturn)
 {
   if (mIsPositioned) {
     return nsContentUtils::CreateContextualFragment(mStartParent, aFragment,
-                                                    PR_TRUE, aReturn);
+                                                    PR_FALSE, aReturn);
   }
   return NS_ERROR_FAILURE;
 }
 
 static void ExtractRectFromOffset(nsIFrame* aFrame,
                                   const nsIFrame* aRelativeTo, 
                                   const PRInt32 aOffset, nsRect* aR, PRBool aKeepLeft)
 {
new file mode 100644
--- /dev/null
+++ b/content/base/src/nsTreeSanitizer.cpp
@@ -0,0 +1,1498 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set sw=2 ts=2 et tw=80: */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is mozilla.org code.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 1998
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *   Robert Sayre <sayrer@gmail.com>
+ *   Henri Sivonen <hsivonen@iki.fi>
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either of the GNU General Public License Version 2 or later (the "GPL"),
+ * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * 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 ***** */
+
+#include "nsTreeSanitizer.h"
+#include "nsCSSParser.h"
+#include "nsCSSProperty.h"
+#include "mozilla/css/Declaration.h"
+#include "mozilla/css/StyleRule.h"
+#include "mozilla/css/Rule.h"
+#include "nsUnicharInputStream.h"
+#include "nsCSSStyleSheet.h"
+#include "nsIDOMCSSRule.h"
+#include "nsAttrName.h"
+#include "nsIScriptSecurityManager.h"
+#include "nsNetUtil.h"
+#include "nsComponentManagerUtils.h"
+#include "nsNullPrincipal.h"
+
+//
+// Thanks to Mark Pilgrim and Sam Ruby for the initial whitelist
+//
+nsIAtom** const kElementsHTML[] = {
+  &nsGkAtoms::a,
+  &nsGkAtoms::abbr,
+  &nsGkAtoms::acronym,
+  &nsGkAtoms::address,
+  &nsGkAtoms::area,
+  &nsGkAtoms::article,
+  &nsGkAtoms::aside,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::audio,
+#endif
+  &nsGkAtoms::b,
+  &nsGkAtoms::bdo,
+  &nsGkAtoms::big,
+  &nsGkAtoms::blockquote,
+  &nsGkAtoms::br,
+  &nsGkAtoms::button,
+  &nsGkAtoms::canvas,
+  &nsGkAtoms::caption,
+  &nsGkAtoms::center,
+  &nsGkAtoms::cite,
+  &nsGkAtoms::code,
+  &nsGkAtoms::col,
+  &nsGkAtoms::colgroup,
+  &nsGkAtoms::command,
+  &nsGkAtoms::datalist,
+  &nsGkAtoms::dd,
+  &nsGkAtoms::del,
+  &nsGkAtoms::details,
+  &nsGkAtoms::dfn,
+  &nsGkAtoms::dir,
+  &nsGkAtoms::div,
+  &nsGkAtoms::dl,
+  &nsGkAtoms::dt,
+  &nsGkAtoms::em,
+  &nsGkAtoms::fieldset,
+  &nsGkAtoms::figcaption,
+  &nsGkAtoms::figure,
+  &nsGkAtoms::font,
+  &nsGkAtoms::footer,
+  &nsGkAtoms::form,
+  &nsGkAtoms::h1,
+  &nsGkAtoms::h2,
+  &nsGkAtoms::h3,
+  &nsGkAtoms::h4,
+  &nsGkAtoms::h5,
+  &nsGkAtoms::h6,
+  &nsGkAtoms::header,
+  &nsGkAtoms::hgroup,
+  &nsGkAtoms::hr,
+  &nsGkAtoms::i,
+  &nsGkAtoms::img,
+  &nsGkAtoms::input,
+  &nsGkAtoms::ins,
+  &nsGkAtoms::kbd,
+  &nsGkAtoms::label,
+  &nsGkAtoms::legend,
+  &nsGkAtoms::li,
+  &nsGkAtoms::link,
+  &nsGkAtoms::listing,
+  &nsGkAtoms::map,
+  &nsGkAtoms::mark,
+  &nsGkAtoms::menu,
+  &nsGkAtoms::meta,
+  &nsGkAtoms::meter,
+  &nsGkAtoms::nav,
+  &nsGkAtoms::nobr,
+  &nsGkAtoms::noscript,
+  &nsGkAtoms::ol,
+  &nsGkAtoms::optgroup,
+  &nsGkAtoms::option,
+  &nsGkAtoms::output,
+  &nsGkAtoms::p,
+  &nsGkAtoms::pre,
+  &nsGkAtoms::progress,
+  &nsGkAtoms::q,
+  &nsGkAtoms::rp,
+  &nsGkAtoms::rt,
+  &nsGkAtoms::ruby,
+  &nsGkAtoms::s,
+  &nsGkAtoms::samp,
+  &nsGkAtoms::section,
+  &nsGkAtoms::select,
+  &nsGkAtoms::small,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::source,
+#endif
+  &nsGkAtoms::span,
+  &nsGkAtoms::strike,
+  &nsGkAtoms::strong,
+  &nsGkAtoms::sub,
+  &nsGkAtoms::summary,
+  &nsGkAtoms::sup,
+  &nsGkAtoms::table,
+  &nsGkAtoms::tbody,
+  &nsGkAtoms::td,
+  &nsGkAtoms::textarea,
+  &nsGkAtoms::tfoot,
+  &nsGkAtoms::th,
+  &nsGkAtoms::thead,
+  &nsGkAtoms::time,
+  &nsGkAtoms::tr,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::track,
+#endif
+  &nsGkAtoms::tt,
+  &nsGkAtoms::u,
+  &nsGkAtoms::ul,
+  &nsGkAtoms::var,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::video,
+#endif
+  &nsGkAtoms::wbr,
+  nsnull
+};
+
+nsIAtom** const kAttributesHTML[] = {
+  &nsGkAtoms::abbr,
+  &nsGkAtoms::accept,
+  &nsGkAtoms::acceptcharset,
+  &nsGkAtoms::accesskey,
+  &nsGkAtoms::action,
+  &nsGkAtoms::align,
+  &nsGkAtoms::alt,
+  &nsGkAtoms::autocomplete,
+  &nsGkAtoms::autofocus,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::autoplay,
+#endif
+  &nsGkAtoms::axis,
+  &nsGkAtoms::background,
+  &nsGkAtoms::bgcolor,
+  &nsGkAtoms::border,
+  &nsGkAtoms::cellpadding,
+  &nsGkAtoms::cellspacing,
+  &nsGkAtoms::_char,
+  &nsGkAtoms::charoff,
+  &nsGkAtoms::charset,
+  &nsGkAtoms::checked,
+  &nsGkAtoms::cite,
+  &nsGkAtoms::_class,
+  &nsGkAtoms::clear,
+  &nsGkAtoms::cols,
+  &nsGkAtoms::colspan,
+  &nsGkAtoms::color,
+  &nsGkAtoms::contenteditable,
+  &nsGkAtoms::contextmenu,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::controls,
+#endif
+  &nsGkAtoms::compact,
+  &nsGkAtoms::coords,
+  &nsGkAtoms::datetime,
+  &nsGkAtoms::dir,
+  &nsGkAtoms::disabled,
+  &nsGkAtoms::draggable,
+  &nsGkAtoms::enctype,
+  &nsGkAtoms::face,
+  &nsGkAtoms::_for,
+  &nsGkAtoms::frame,
+  &nsGkAtoms::headers,
+  &nsGkAtoms::height,
+  &nsGkAtoms::hidden,
+  &nsGkAtoms::high,
+  &nsGkAtoms::href,
+  &nsGkAtoms::hreflang,
+  &nsGkAtoms::hspace,
+  &nsGkAtoms::icon,
+  &nsGkAtoms::id,
+  &nsGkAtoms::ismap,
+  &nsGkAtoms::itemid,
+  &nsGkAtoms::itemprop,
+  &nsGkAtoms::itemref,
+  &nsGkAtoms::itemscope,
+  &nsGkAtoms::itemtype,
+  &nsGkAtoms::kind,
+  &nsGkAtoms::label,
+  &nsGkAtoms::lang,
+  &nsGkAtoms::list,
+  &nsGkAtoms::longdesc,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::loop,
+  &nsGkAtoms::loopend,
+  &nsGkAtoms::loopstart,
+#endif
+  &nsGkAtoms::low,
+  &nsGkAtoms::max,
+  &nsGkAtoms::maxlength,
+  &nsGkAtoms::media,
+  &nsGkAtoms::method,
+  &nsGkAtoms::min,
+  &nsGkAtoms::mozdonotsend,
+  &nsGkAtoms::multiple,
+  &nsGkAtoms::name,
+  &nsGkAtoms::nohref,
+  &nsGkAtoms::noshade,
+  &nsGkAtoms::novalidate,
+  &nsGkAtoms::nowrap,
+  &nsGkAtoms::open,
+  &nsGkAtoms::optimum,
+  &nsGkAtoms::pattern,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::pixelratio,
+#endif
+  &nsGkAtoms::placeholder,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::playbackrate,
+  &nsGkAtoms::playcount,
+#endif
+  &nsGkAtoms::pointSize,
+#ifdef MOZ_MEDIA
+  &nsGkAtoms::poster,
+  &nsGkAtoms::preload,
+#endif
+  &nsGkAtoms::prompt,
+  &nsGkAtoms::pubdate,
+  &nsGkAtoms::radiogroup,
+  &nsGkAtoms::readonly,
+  &nsGkAtoms::rel,
+  &nsGkAtoms::required,
+  &nsGkAtoms::rev,
+  &nsGkAtoms::reversed,
+  &nsGkAtoms::role,
+  &nsGkAtoms::rows,
+  &nsGkAtoms::rowspan,
+  &nsGkAtoms::rules,
+  &nsGkAtoms::scoped,
+  &nsGkAtoms::scope,
+  &nsGkAtoms::selected,
+  &nsGkAtoms::shape,
+  &nsGkAtoms::size,
+  &nsGkAtoms::span,
+  &nsGkAtoms::spellcheck,
+  &nsGkAtoms::src,
+  &nsGkAtoms::srclang,
+  &nsGkAtoms::start,
+  &nsGkAtoms::summary,
+  &nsGkAtoms::tabindex,
+  &nsGkAtoms::target,
+  &nsGkAtoms::title,
+  &nsGkAtoms::type,
+  &nsGkAtoms::usemap,
+  &nsGkAtoms::valign,
+  &nsGkAtoms::value,
+  &nsGkAtoms::vspace,
+  &nsGkAtoms::width,
+  &nsGkAtoms::wrap,
+  nsnull
+};
+
+nsIAtom** const kURLAttributesHTML[] = {
+  &nsGkAtoms::action,
+  &nsGkAtoms::href,
+  &nsGkAtoms::src,
+  &nsGkAtoms::longdesc,
+  &nsGkAtoms::cite,
+  &nsGkAtoms::background,
+  nsnull
+};
+
+nsIAtom** const kElementsSVG[] = {
+#ifdef MOZ_SVG
+  &nsGkAtoms::a, // a
+  &nsGkAtoms::altGlyph, // altGlyph
+  &nsGkAtoms::altGlyphDef, // altGlyphDef
+  &nsGkAtoms::altGlyphItem, // altGlyphItem
+  &nsGkAtoms::animate, // animate
+  &nsGkAtoms::animateColor, // animateColor
+  &nsGkAtoms::animateMotion, // animateMotion
+  &nsGkAtoms::animateTransform, // animateTransform
+  &nsGkAtoms::circle, // circle
+  &nsGkAtoms::clipPath, // clipPath
+  &nsGkAtoms::colorProfile, // color-profile
+  &nsGkAtoms::cursor, // cursor
+  &nsGkAtoms::defs, // defs
+  &nsGkAtoms::desc, // desc
+  &nsGkAtoms::ellipse, // ellipse
+  &nsGkAtoms::elevation, // elevation
+  &nsGkAtoms::erode, // erode
+  &nsGkAtoms::ex, // ex
+  &nsGkAtoms::exact, // exact
+  &nsGkAtoms::exponent, // exponent
+  &nsGkAtoms::feBlend, // feBlend
+  &nsGkAtoms::feColorMatrix, // feColorMatrix
+  &nsGkAtoms::feComponentTransfer, // feComponentTransfer
+  &nsGkAtoms::feComposite, // feComposite
+  &nsGkAtoms::feConvolveMatrix, // feConvolveMatrix
+  &nsGkAtoms::feDiffuseLighting, // feDiffuseLighting
+  &nsGkAtoms::feDisplacementMap, // feDisplacementMap
+  &nsGkAtoms::feDistantLight, // feDistantLight
+  &nsGkAtoms::feFlood, // feFlood
+  &nsGkAtoms::feFuncA, // feFuncA
+  &nsGkAtoms::feFuncB, // feFuncB
+  &nsGkAtoms::feFuncG, // feFuncG
+  &nsGkAtoms::feFuncR, // feFuncR
+  &nsGkAtoms::feGaussianBlur, // feGaussianBlur
+  &nsGkAtoms::feImage, // feImage
+  &nsGkAtoms::feMerge, // feMerge
+  &nsGkAtoms::feMergeNode, // feMergeNode
+  &nsGkAtoms::feMorphology, // feMorphology
+  &nsGkAtoms::feOffset, // feOffset
+  &nsGkAtoms::fePointLight, // fePointLight
+  &nsGkAtoms::feSpecularLighting, // feSpecularLighting
+  &nsGkAtoms::feSpotLight, // feSpotLight
+  &nsGkAtoms::feTile, // feTile
+  &nsGkAtoms::feTurbulence, // feTurbulence
+  &nsGkAtoms::filter, // filter
+  &nsGkAtoms::font, // font
+  &nsGkAtoms::font_face, // font-face
+  &nsGkAtoms::font_face_format, // font-face-format
+  &nsGkAtoms::font_face_name, // font-face-name
+  &nsGkAtoms::font_face_src, // font-face-src
+  &nsGkAtoms::font_face_uri, // font-face-uri
+  &nsGkAtoms::foreignObject, // foreignObject
+  &nsGkAtoms::g, // g
+  &nsGkAtoms::glyph, // glyph
+  &nsGkAtoms::glyphRef, // glyphRef
+  &nsGkAtoms::hkern, // hkern
+  &nsGkAtoms::image, // image
+  &nsGkAtoms::line, // line
+  &nsGkAtoms::linearGradient, // linearGradient
+  &nsGkAtoms::marker, // marker
+  &nsGkAtoms::mask, // mask
+  &nsGkAtoms::metadata, // metadata
+  &nsGkAtoms::missingGlyph, // missingGlyph
+  &nsGkAtoms::mpath, // mpath
+  &nsGkAtoms::path, // path
+  &nsGkAtoms::pattern, // pattern
+  &nsGkAtoms::polygon, // polygon
+  &nsGkAtoms::polyline, // polyline
+  &nsGkAtoms::radialGradient, // radialGradient
+  &nsGkAtoms::rect, // rect
+  &nsGkAtoms::set, // set
+  &nsGkAtoms::stop, // stop
+  &nsGkAtoms::svg, // svg
+  &nsGkAtoms::svgSwitch, // switch
+  &nsGkAtoms::symbol, // symbol
+  &nsGkAtoms::text, // text
+  &nsGkAtoms::textPath, // textPath
+  &nsGkAtoms::title, // title
+  &nsGkAtoms::tref, // tref
+  &nsGkAtoms::tspan, // tspan
+  &nsGkAtoms::use, // use
+  &nsGkAtoms::view, // view
+  &nsGkAtoms::vkern, // vkern
+#endif
+  nsnull
+};
+
+nsIAtom** const kAttributesSVG[] = {
+#ifdef MOZ_SVG
+  // accent-height
+#ifdef MOZ_SMIL
+  &nsGkAtoms::accumulate, // accumulate
+  &nsGkAtoms::additive, // additive
+#endif
+  &nsGkAtoms::alignment_baseline, // alignment-baseline
+  // alphabetic
+  &nsGkAtoms::amplitude, // amplitude
+  // arabic-form
+  // ascent
+#ifdef MOZ_SMIL
+  &nsGkAtoms::attributeName, // attributeName
+  &nsGkAtoms::attributeType, // attributeType
+#endif
+  &nsGkAtoms::azimuth, // azimuth
+  &nsGkAtoms::baseFrequency, // baseFrequency
+  &nsGkAtoms::baseline_shift, // baseline-shift
+  // baseProfile
+  // bbox
+#ifdef MOZ_SMIL
+  &nsGkAtoms::begin, // begin
+#endif
+  &nsGkAtoms::bias, // bias
+#ifdef MOZ_SMIL
+  &nsGkAtoms::by, // by
+  &nsGkAtoms::calcMode, // calcMode
+#endif
+  // cap-height
+  &nsGkAtoms::_class, // class
+  &nsGkAtoms::clip_path, // clip-path
+  &nsGkAtoms::clip_rule, // clip-rule
+  &nsGkAtoms::clipPathUnits, // clipPathUnits
+  &nsGkAtoms::color, // color
+  &nsGkAtoms::colorInterpolation, // color-interpolation
+  &nsGkAtoms::colorInterpolationFilters, // color-interpolation-filters
+  // contentScriptType
+  // contentStyleType
+  &nsGkAtoms::cursor, // cursor
+  &nsGkAtoms::cx, // cx
+  &nsGkAtoms::cy, // cy
+  &nsGkAtoms::d, // d
+  // descent
+  &nsGkAtoms::diffuseConstant, // diffuseConstant
+  &nsGkAtoms::direction, // direction
+  &nsGkAtoms::display, // display
+  &nsGkAtoms::divisor, // divisor
+  &nsGkAtoms::dominant_baseline, // dominant-baseline
+#ifdef MOZ_SMIL
+  &nsGkAtoms::dur, // dur
+#endif
+  &nsGkAtoms::dx, // dx
+  &nsGkAtoms::dy, // dy
+  &nsGkAtoms::edgeMode, // edgeMode
+  &nsGkAtoms::elevation, // elevation
+  // enable-background
+#ifdef MOZ_SMIL
+  &nsGkAtoms::end, // end
+#endif
+  &nsGkAtoms::fill, // fill
+  &nsGkAtoms::fill_opacity, // fill-opacity
+  &nsGkAtoms::fill_rule, // fill-rule
+  &nsGkAtoms::filter, // filter
+  &nsGkAtoms::filterRes, // filterRes
+  &nsGkAtoms::filterUnits, // filterUnits
+  &nsGkAtoms::flood_color, // flood-color
+  &nsGkAtoms::flood_opacity, // flood-opacity
+  // XXX focusable
+  &nsGkAtoms::font, // font
+  &nsGkAtoms::font_family, // font-family
+  &nsGkAtoms::font_size, // font-size
+  &nsGkAtoms::font_size_adjust, // font-size-adjust
+  &nsGkAtoms::font_stretch, // font-stretch
+  &nsGkAtoms::font_style, // font-style
+  &nsGkAtoms::font_variant, // font-variant
+  &nsGkAtoms::fontWeight, // font-weight
+  &nsGkAtoms::format, // format
+  &nsGkAtoms::from, // from
+  &nsGkAtoms::fx, // fx
+  &nsGkAtoms::fy, // fy
+  // g1
+  // g2
+  // glyph-name
+  // glyphRef
+  &nsGkAtoms::glyph_orientation_horizontal, // glyph-orientation-horizontal
+  &nsGkAtoms::glyph_orientation_vertical, // glyph-orientation-vertical
+  &nsGkAtoms::gradientTransform, // gradientTransform
+  &nsGkAtoms::gradientUnits, // gradientUnits
+  &nsGkAtoms::height, // height
+  // horiz-adv-x
+  // horiz-origin-x
+  // horiz-origin-y
+  &nsGkAtoms::id, // id
+  // ideographic
+  &nsGkAtoms::image_rendering, // image-rendering
+  &nsGkAtoms::in, // in
+  &nsGkAtoms::in2, // in2
+  &nsGkAtoms::intercept, // intercept
+  // k
+  &nsGkAtoms::k1, // k1
+  &nsGkAtoms::k2, // k2
+  &nsGkAtoms::k3, // k3
+  &nsGkAtoms::k4, // k4
+  &nsGkAtoms::kerning, // kerning
+  &nsGkAtoms::kernelMatrix, // kernelMatrix
+  &nsGkAtoms::kernelUnitLength, // kernelUnitLength
+#ifdef MOZ_SMIL
+  &nsGkAtoms::keyPoints, // keyPoints
+  &nsGkAtoms::keySplines, // keySplines
+  &nsGkAtoms::keyTimes, // keyTimes
+#endif
+  &nsGkAtoms::lang, // lang
+  // lengthAdjust
+  &nsGkAtoms::letter_spacing, // letter-spacing
+  &nsGkAtoms::lighting_color, // lighting-color
+  &nsGkAtoms::limitingConeAngle, // limitingConeAngle
+  // local
+  &nsGkAtoms::marker, // marker
+  &nsGkAtoms::marker_end, // marker-end
+  &nsGkAtoms::marker_mid, // marker-mid
+  &nsGkAtoms::marker_start, // marker-start
+  &nsGkAtoms::markerHeight, // markerHeight
+  &nsGkAtoms::markerUnits, // markerUnits
+  &nsGkAtoms::markerWidth, // markerWidth
+  &nsGkAtoms::mask, // mask
+  &nsGkAtoms::maskContentUnits, // maskContentUnits
+  &nsGkAtoms::maskUnits, // maskUnits
+  // mathematical
+  &nsGkAtoms::max, // max
+  &nsGkAtoms::media, // media
+  &nsGkAtoms::method, // method
+  &nsGkAtoms::min, // min
+  &nsGkAtoms::mode, // mode
+  &nsGkAtoms::name, // name
+  &nsGkAtoms::numOctaves, // numOctaves
+  &nsGkAtoms::offset, // offset
+  &nsGkAtoms::opacity, // opacity
+  &nsGkAtoms::_operator, // operator
+  &nsGkAtoms::order, // order
+  &nsGkAtoms::orient, // orient
+  &nsGkAtoms::orientation, // orientation
+  // origin
+  // overline-position
+  // overline-thickness
+  &nsGkAtoms::overflow, // overflow
+  // panose-1
+  &nsGkAtoms::path, // path
+  &nsGkAtoms::pathLength, // pathLength
+  &nsGkAtoms::patternContentUnits, // patternContentUnits
+  &nsGkAtoms::patternTransform, // patternTransform
+  &nsGkAtoms::patternUnits, // patternUnits
+  &nsGkAtoms::pointer_events, // pointer-events XXX is this safe?
+  &nsGkAtoms::points, // points
+  &nsGkAtoms::pointsAtX, // pointsAtX
+  &nsGkAtoms::pointsAtY, // pointsAtY
+  &nsGkAtoms::pointsAtZ, // pointsAtZ
+  &nsGkAtoms::preserveAlpha, // preserveAlpha
+  &nsGkAtoms::preserveAspectRatio, // preserveAspectRatio
+  &nsGkAtoms::primitiveUnits, // primitiveUnits
+  &nsGkAtoms::r, // r
+  &nsGkAtoms::radius, // radius
+  &nsGkAtoms::refX, // refX
+  &nsGkAtoms::refY, // refY
+#ifdef MOZ_SMIL
+  &nsGkAtoms::repeatCount, // repeatCount
+  &nsGkAtoms::repeatDur, // repeatDur
+#endif
+  &nsGkAtoms::requiredExtensions, // requiredExtensions
+  &nsGkAtoms::requiredFeatures, // requiredFeatures
+#ifdef MOZ_SMIL
+  &nsGkAtoms::restart, // restart
+#endif
+  &nsGkAtoms::result, // result
+  &nsGkAtoms::rotate, // rotate
+  &nsGkAtoms::rx, // rx
+  &nsGkAtoms::ry, // ry
+  &nsGkAtoms::scale, // scale
+  &nsGkAtoms::seed, // seed
+  &nsGkAtoms::shape_rendering, // shape-rendering
+  &nsGkAtoms::slope, // slope
+  &nsGkAtoms::spacing, // spacing
+  &nsGkAtoms::specularConstant, // specularConstant
+  &nsGkAtoms::specularExponent, // specularExponent
+  &nsGkAtoms::spreadMethod, // spreadMethod
+  &nsGkAtoms::startOffset, // startOffset
+  &nsGkAtoms::stdDeviation, // stdDeviation
+  // stemh
+  // stemv
+  &nsGkAtoms::stitchTiles, // stitchTiles
+  &nsGkAtoms::stop_color, // stop-color
+  &nsGkAtoms::stop_opacity, // stop-opacity
+  // strikethrough-position
+  // strikethrough-thickness
+  &nsGkAtoms::string, // string
+  &nsGkAtoms::stroke, // stroke
+  &nsGkAtoms::stroke_dasharray, // stroke-dasharray
+  &nsGkAtoms::stroke_dashoffset, // stroke-dashoffset
+  &nsGkAtoms::stroke_linecap, // stroke-linecap
+  &nsGkAtoms::stroke_linejoin, // stroke-linejoin
+  &nsGkAtoms::stroke_miterlimit, // stroke-miterlimit
+  &nsGkAtoms::stroke_opacity, // stroke-opacity
+  &nsGkAtoms::stroke_width, // stroke-width
+  &nsGkAtoms::surfaceScale, // surfaceScale
+  &nsGkAtoms::systemLanguage, // systemLanguage
+  &nsGkAtoms::tableValues, // tableValues
+  &nsGkAtoms::target, // target
+  &nsGkAtoms::targetX, // targetX
+  &nsGkAtoms::targetY, // targetY
+  &nsGkAtoms::text_anchor, // text-anchor
+  &nsGkAtoms::text_decoration, // text-decoration
+  // textLength
+  &nsGkAtoms::text_rendering, // text-rendering
+  &nsGkAtoms::title, // title
+#ifdef MOZ_SMIL
+  &nsGkAtoms::to, // to
+#endif
+  &nsGkAtoms::transform, // transform
+  &nsGkAtoms::type, // type
+  // u1
+  // u2
+  // underline-position
+  // underline-thickness
+  // unicode
+  &nsGkAtoms::unicode_bidi, // unicode-bidi
+  // unicode-range
+  // units-per-em
+  // v-alphabetic
+  // v-hanging
+  // v-ideographic
+  // v-mathematical
+  &nsGkAtoms::values, // values
+  // vert-adv-y
+  // vert-origin-x
+  // vert-origin-y
+  &nsGkAtoms::viewBox, // viewBox
+  &nsGkAtoms::visibility, // visibility
+  // viewTarget
+  &nsGkAtoms::width, // width
+  // widths
+  &nsGkAtoms::word_spacing, // word-spacing
+  // writing-mode
+  &nsGkAtoms::x, // x
+  // x-height
+  &nsGkAtoms::x1, // x1
+  &nsGkAtoms::x2, // x2
+  &nsGkAtoms::xChannelSelector, // xChannelSelector
+  &nsGkAtoms::y, // y
+  &nsGkAtoms::y1, // y1
+  &nsGkAtoms::y2, // y2
+  &nsGkAtoms::yChannelSelector, // yChannelSelector
+  &nsGkAtoms::z, // z
+  &nsGkAtoms::zoomAndPan, // zoomAndPan
+#endif
+  nsnull
+};
+
+nsIAtom** const kURLAttributesSVG[] = {
+  nsnull
+};
+
+nsIAtom** const kElementsMathML[] = {
+   &nsGkAtoms::abs_, // abs
+   &nsGkAtoms::_and, // and
+   &nsGkAtoms::annotation_, // annotation
+   &nsGkAtoms::annotation_xml_, // annotation-xml
+   &nsGkAtoms::apply_, // apply
+   &nsGkAtoms::approx_, // approx
+   &nsGkAtoms::arccos_, // arccos
+   &nsGkAtoms::arccosh_, // arccosh
+   &nsGkAtoms::arccot_, // arccot
+   &nsGkAtoms::arccoth_, // arccoth
+   &nsGkAtoms::arccsc_, // arccsc
+   &nsGkAtoms::arccsch_, // arccsch
+   &nsGkAtoms::arcsec_, // arcsec
+   &nsGkAtoms::arcsech_, // arcsech
+   &nsGkAtoms::arcsin_, // arcsin
+   &nsGkAtoms::arcsinh_, // arcsinh
+   &nsGkAtoms::arctan_, // arctan
+   &nsGkAtoms::arctanh_, // arctanh
+   &nsGkAtoms::arg_, // arg
+   &nsGkAtoms::bind_, // bind
+   &nsGkAtoms::bvar_, // bvar
+   &nsGkAtoms::card_, // card
+   &nsGkAtoms::cartesianproduct_, // cartesianproduct
+   &nsGkAtoms::cbytes_, // cbytes
+   &nsGkAtoms::ceiling, // ceiling
+   &nsGkAtoms::cerror_, // cerror
+   &nsGkAtoms::ci_, // ci
+   &nsGkAtoms::cn_, // cn
+   &nsGkAtoms::codomain_, // codomain
+   &nsGkAtoms::complexes_, // complexes
+   &nsGkAtoms::compose_, // compose
+   &nsGkAtoms::condition_, // condition
+   &nsGkAtoms::conjugate_, // conjugate
+   &nsGkAtoms::cos_, // cos
+   &nsGkAtoms::cosh_, // cosh
+   &nsGkAtoms::cot_, // cot
+   &nsGkAtoms::coth_, // coth
+   &nsGkAtoms::cs_, // cs
+   &nsGkAtoms::csc_, // csc
+   &nsGkAtoms::csch_, // csch
+   &nsGkAtoms::csymbol_, // csymbol
+   &nsGkAtoms::curl_, // curl
+   &nsGkAtoms::declare, // declare
+   &nsGkAtoms::degree_, // degree
+   &nsGkAtoms::determinant_, // determinant
+   &nsGkAtoms::diff_, // diff
+   &nsGkAtoms::divergence_, // divergence
+   &nsGkAtoms::divide_, // divide
+   &nsGkAtoms::domain_, // domain
+   &nsGkAtoms::domainofapplication_, // domainofapplication
+   &nsGkAtoms::el_, // el
+   &nsGkAtoms::emptyset_, // emptyset
+   &nsGkAtoms::eq_, // eq
+   &nsGkAtoms::equivalent_, // equivalent
+   &nsGkAtoms::eulergamma_, // eulergamma
+   &nsGkAtoms::exists_, // exists
+   &nsGkAtoms::exp_, // exp
+   &nsGkAtoms::exponentiale_, // exponentiale
+   &nsGkAtoms::factorial_, // factorial
+   &nsGkAtoms::factorof_, // factorof
+   &nsGkAtoms::_false, // false
+   &nsGkAtoms::floor, // floor
+   &nsGkAtoms::fn_, // fn
+   &nsGkAtoms::forall_, // forall
+   &nsGkAtoms::gcd_, // gcd
+   &nsGkAtoms::geq_, // geq
+   &nsGkAtoms::grad, // grad
+   &nsGkAtoms::gt_, // gt
+   &nsGkAtoms::ident_, // ident
+   &nsGkAtoms::image, // image
+   &nsGkAtoms::imaginary_, // imaginary
+   &nsGkAtoms::imaginaryi_, // imaginaryi
+   &nsGkAtoms::implies_, // implies
+   &nsGkAtoms::in, // in
+   &nsGkAtoms::infinity, // infinity
+   &nsGkAtoms::int_, // int
+   &nsGkAtoms::integers_, // integers
+   &nsGkAtoms::intersect_, // intersect
+   &nsGkAtoms::interval_, // interval
+   &nsGkAtoms::inverse_, // inverse
+   &nsGkAtoms::lambda_, // lambda
+   &nsGkAtoms::laplacian_, // laplacian
+   &nsGkAtoms::lcm_, // lcm
+   &nsGkAtoms::leq_, // leq
+   &nsGkAtoms::limit_, // limit
+   &nsGkAtoms::list_, // list
+   &nsGkAtoms::ln_, // ln
+   &nsGkAtoms::log_, // log
+   &nsGkAtoms::logbase_, // logbase
+   &nsGkAtoms::lowlimit_, // lowlimit
+   &nsGkAtoms::lt_, // lt
+   &nsGkAtoms::maction_, // maction
+   &nsGkAtoms::malign_, // malign
+   &nsGkAtoms::maligngroup_, // maligngroup
+   &nsGkAtoms::malignmark_, // malignmark
+   &nsGkAtoms::malignscope_, // malignscope
+   &nsGkAtoms::math, // math
+   &nsGkAtoms::matrix, // matrix
+   &nsGkAtoms::matrixrow_, // matrixrow
+   &nsGkAtoms::max, // max
+   &nsGkAtoms::mean_, // mean
+   &nsGkAtoms::median_, // median
+   &nsGkAtoms::menclose_, // menclose
+   &nsGkAtoms::merror_, // merror
+   &nsGkAtoms::mfenced_, // mfenced
+   &nsGkAtoms::mfrac_, // mfrac
+   &nsGkAtoms::mfraction_, // mfraction
+   &nsGkAtoms::mglyph_, // mglyph
+   &nsGkAtoms::mi_, // mi
+   &nsGkAtoms::min, // min
+   &nsGkAtoms::minus_, // minus
+   &nsGkAtoms::mlabeledtr_, // mlabeledtr
+   &nsGkAtoms::mlongdiv_, // mlongdiv
+   &nsGkAtoms::mmultiscripts_, // mmultiscripts
+   &nsGkAtoms::mn_, // mn
+   &nsGkAtoms::mo_, // mo
+   &nsGkAtoms::mode, // mode
+   &nsGkAtoms::moment_, // moment
+   &nsGkAtoms::momentabout_, // momentabout
+   &nsGkAtoms::mover_, // mover
+   &nsGkAtoms::mpadded_, // mpadded
+   &nsGkAtoms::mphantom_, // mphantom
+   &nsGkAtoms::mprescripts_, // mprescripts
+   &nsGkAtoms::mroot_, // mroot
+   &nsGkAtoms::mrow_, // mrow
+   &nsGkAtoms::ms_, // ms
+   &nsGkAtoms::mscarries_, // mscarries
+   &nsGkAtoms::mscarry_, // mscarry
+   &nsGkAtoms::msgroup_, // msgroup
+   &nsGkAtoms::msline_, // msline
+   &nsGkAtoms::mspace_, // mspace
+   &nsGkAtoms::msqrt_, // msqrt
+   &nsGkAtoms::msrow_, // msrow
+   &nsGkAtoms::mstack_, // mstack
+   &nsGkAtoms::mstyle_, // mstyle
+   &nsGkAtoms::msub_, // msub
+   &nsGkAtoms::msubsup_, // msubsup
+   &nsGkAtoms::msup_, // msup
+   &nsGkAtoms::mtable_, // mtable
+   &nsGkAtoms::mtd_, // mtd
+   &nsGkAtoms::mtext_, // mtext
+   &nsGkAtoms::mtr_, // mtr
+   &nsGkAtoms::munder_, // munder
+   &nsGkAtoms::munderover_, // munderover
+   &nsGkAtoms::naturalnumbers_, // naturalnumbers
+   &nsGkAtoms::neq_, // neq
+   &nsGkAtoms::none, // none
+   &nsGkAtoms::_not, // not
+   &nsGkAtoms::notanumber_, // notanumber
+   &nsGkAtoms::note_, // note
+   &nsGkAtoms::notin_, // notin
+   &nsGkAtoms::notprsubset_, // notprsubset
+   &nsGkAtoms::notsubset_, // notsubset
+   &nsGkAtoms::_or, // or
+   &nsGkAtoms::otherwise, // otherwise
+   &nsGkAtoms::outerproduct_, // outerproduct
+   &nsGkAtoms::partialdiff_, // partialdiff
+   &nsGkAtoms::pi_, // pi
+   &nsGkAtoms::piece_, // piece
+   &nsGkAtoms::piecewise_, // piecewise
+   &nsGkAtoms::plus_, // plus
+   &nsGkAtoms::power_, // power
+   &nsGkAtoms::primes_, // primes
+   &nsGkAtoms::product_, // product
+   &nsGkAtoms::prsubset_, // prsubset
+   &nsGkAtoms::quotient_, // quotient
+   &nsGkAtoms::rationals_, // rationals
+   &nsGkAtoms::real_, // real
+   &nsGkAtoms::reals_, // reals
+   &nsGkAtoms::reln_, // reln
+   &nsGkAtoms::rem, // rem
+   &nsGkAtoms::root_, // root
+   &nsGkAtoms::scalarproduct_, // scalarproduct
+   &nsGkAtoms::sdev_, // sdev
+   &nsGkAtoms::sec_, // sec
+   &nsGkAtoms::sech_, // sech
+   &nsGkAtoms::selector_, // selector
+   &nsGkAtoms::semantics_, // semantics
+   &nsGkAtoms::sep_, // sep
+   &nsGkAtoms::set_, // set
+   &nsGkAtoms::setdiff_, // setdiff
+   &nsGkAtoms::share_, // share
+   &nsGkAtoms::sin_, // sin
+   &nsGkAtoms::sinh_, // sinh
+   &nsGkAtoms::subset_, // subset
+   &nsGkAtoms::sum, // sum
+   &nsGkAtoms::tan_, // tan
+   &nsGkAtoms::tanh_, // tanh
+   &nsGkAtoms::tendsto_, // tendsto
+   &nsGkAtoms::times_, // times
+   &nsGkAtoms::transpose_, // transpose
+   &nsGkAtoms::_true, // true
+   &nsGkAtoms::union_, // union
+   &nsGkAtoms::uplimit_, // uplimit
+   &nsGkAtoms::variance_, // variance
+   &nsGkAtoms::vector_, // vector
+   &nsGkAtoms::vectorproduct_, // vectorproduct
+   &nsGkAtoms::xor_, // xor
+  nsnull
+};
+
+nsIAtom** const kAttributesMathML[] = {
+   &nsGkAtoms::accent_, // accent
+   &nsGkAtoms::accentunder_, // accentunder
+   &nsGkAtoms::actiontype_, // actiontype
+   &nsGkAtoms::align, // align
+   &nsGkAtoms::alignmentscope_, // alignmentscope
+   &nsGkAtoms::alt, // alt
+   &nsGkAtoms::altimg_, // altimg
+   &nsGkAtoms::altimg_height_, // altimg-height
+   &nsGkAtoms::altimg_valign_, // altimg-valign
+   &nsGkAtoms::altimg_width_, // altimg-width
+   &nsGkAtoms::background, // background
+   &nsGkAtoms::base, // base
+   &nsGkAtoms::bevelled_, // bevelled
+   &nsGkAtoms::cd_, // cd
+   &nsGkAtoms::cdgroup_, // cdgroup
+   &nsGkAtoms::charalign_, // charalign
+   &nsGkAtoms::close, // close
+   &nsGkAtoms::closure_, // closure
+   &nsGkAtoms::color, // color
+   &nsGkAtoms::columnalign_, // columnalign
+   &nsGkAtoms::columnalignment_, // columnalignment
+   &nsGkAtoms::columnlines_, // columnlines
+   &nsGkAtoms::columnspacing_, // columnspacing
+   &nsGkAtoms::columnspan_, // columnspan
+   &nsGkAtoms::columnwidth_, // columnwidth
+   &nsGkAtoms::crossout_, // crossout
+   &nsGkAtoms::decimalpoint_, // decimalpoint
+   &nsGkAtoms::definitionURL_, // definitionURL
+   &nsGkAtoms::denomalign_, // denomalign
+   &nsGkAtoms::depth_, // depth
+   &nsGkAtoms::dir, // dir
+   &nsGkAtoms::display, // display
+   &nsGkAtoms::displaystyle_, // displaystyle
+   &nsGkAtoms::edge_, // edge
+   &nsGkAtoms::encoding, // encoding
+   &nsGkAtoms::equalcolumns_, // equalcolumns
+   &nsGkAtoms::equalrows_, // equalrows
+   &nsGkAtoms::fence_, // fence
+   &nsGkAtoms::fontfamily_, // fontfamily
+   &nsGkAtoms::fontsize_, // fontsize
+   &nsGkAtoms::fontstyle_, // fontstyle
+   &nsGkAtoms::fontweight_, // fontweight
+   &nsGkAtoms::form, // form
+   &nsGkAtoms::frame, // frame
+   &nsGkAtoms::framespacing_, // framespacing
+   &nsGkAtoms::groupalign_, // groupalign
+   &nsGkAtoms::height, // height
+   &nsGkAtoms::href, // href
+   &nsGkAtoms::id, // id
+   &nsGkAtoms::indentalign_, // indentalign
+   &nsGkAtoms::indentalignfirst_, // indentalignfirst
+   &nsGkAtoms::indentalignlast_, // indentalignlast
+   &nsGkAtoms::indentshift_, // indentshift
+   &nsGkAtoms::indentshiftfirst_, // indentshiftfirst
+   &nsGkAtoms::indenttarget_, // indenttarget
+   &nsGkAtoms::index, // index
+   &nsGkAtoms::integer, // integer
+   &nsGkAtoms::largeop_, // largeop
+   &nsGkAtoms::length, // length
+   &nsGkAtoms::linebreak_, // linebreak
+   &nsGkAtoms::linebreakmultchar_, // linebreakmultchar
+   &nsGkAtoms::linebreakstyle_, // linebreakstyle
+   &nsGkAtoms::linethickness_, // linethickness
+   &nsGkAtoms::location_, // location
+   &nsGkAtoms::longdivstyle_, // longdivstyle
+   &nsGkAtoms::lquote_, // lquote
+   &nsGkAtoms::lspace_, // lspace
+   &nsGkAtoms::ltr, // ltr
+   &nsGkAtoms::mathbackground_, // mathbackground
+   &nsGkAtoms::mathcolor_, // mathcolor
+   &nsGkAtoms::mathsize_, // mathsize
+   &nsGkAtoms::mathvariant_, // mathvariant
+   &nsGkAtoms::maxsize_, // maxsize
+   &nsGkAtoms::mediummathspace_, // mediummathspace
+   &nsGkAtoms::minlabelspacing_, // minlabelspacing
+   &nsGkAtoms::minsize_, // minsize
+   &nsGkAtoms::monospaced_, // monospaced
+   &nsGkAtoms::movablelimits_, // movablelimits
+   &nsGkAtoms::msgroup_, // msgroup
+   &nsGkAtoms::name, // name
+   &nsGkAtoms::negativemediummathspace_, // negativemediummathspace
+   &nsGkAtoms::negativethickmathspace_, // negativethickmathspace
+   &nsGkAtoms::negativethinmathspace_, // negativethinmathspace
+   &nsGkAtoms::negativeverythickmathspace_, // negativeverythickmathspace
+   &nsGkAtoms::negativeverythinmathspace_, // negativeverythinmathspace
+   &nsGkAtoms::negativeveryverythickmathspace_, // negativeveryverythickmathspace
+   &nsGkAtoms::negativeveryverythinmathspace_, // negativeveryverythinmathspace
+   &nsGkAtoms::newline, // newline
+   &nsGkAtoms::notation_, // notation
+   &nsGkAtoms::numalign_, // numalign
+   &nsGkAtoms::number, // number
+   &nsGkAtoms::open, // open
+   &nsGkAtoms::order, // order
+   &nsGkAtoms::other_, // other
+   &nsGkAtoms::overflow, // overflow
+   &nsGkAtoms::position, // position
+   &nsGkAtoms::role, // role
+   &nsGkAtoms::rowalign_, // rowalign
+   &nsGkAtoms::rowlines_, // rowlines
+   &nsGkAtoms::rowspacing_, // rowspacing
+   &nsGkAtoms::rowspan, // rowspan
+   &nsGkAtoms::rquote_, // rquote
+   &nsGkAtoms::rspace_, // rspace
+   &nsGkAtoms::schemaLocation_, // schemaLocation
+   &nsGkAtoms::scriptlevel_, // scriptlevel
+   &nsGkAtoms::scriptminsize_, // scriptminsize
+   &nsGkAtoms::scriptsize_, // scriptsize
+   &nsGkAtoms::scriptsizemultiplier_, // scriptsizemultiplier
+   &nsGkAtoms::selection_, // selection
+   &nsGkAtoms::separator_, // separator
+   &nsGkAtoms::separators_, // separators
+   &nsGkAtoms::shift_, // shift
+   &nsGkAtoms::side_, // side
+   &nsGkAtoms::src, // src
+   &nsGkAtoms::stackalign_, // stackalign
+   &nsGkAtoms::stretchy_, // stretchy
+   &nsGkAtoms::subscriptshift_, // subscriptshift
+   &nsGkAtoms::superscriptshift_, // superscriptshift
+   &nsGkAtoms::symmetric_, // symmetric
+   &nsGkAtoms::thickmathspace_, // thickmathspace
+   &nsGkAtoms::thinmathspace_, // thinmathspace
+   &nsGkAtoms::type, // type
+   &nsGkAtoms::verythickmathspace_, // verythickmathspace
+   &nsGkAtoms::verythinmathspace_, // verythinmathspace
+   &nsGkAtoms::veryverythickmathspace_, // veryverythickmathspace
+   &nsGkAtoms::veryverythinmathspace_, // veryverythinmathspace
+   &nsGkAtoms::voffset_, // voffset
+   &nsGkAtoms::width, // width
+   &nsGkAtoms::xref_, // xref
+  nsnull
+};
+
+nsIAtom** const kURLAttributesMathML[] = {
+  &nsGkAtoms::href,
+  &nsGkAtoms::src,
+  &nsGkAtoms::definitionURL_,
+  nsnull
+};
+
+nsTHashtable<nsISupportsHashKey>* nsTreeSanitizer::sElementsHTML = nsnull;
+nsTHashtable<nsISupportsHashKey>* nsTreeSanitizer::sAttributesHTML = nsnull;
+nsTHashtable<nsISupportsHashKey>* nsTreeSanitizer::sElementsSVG = nsnull;
+nsTHashtable<nsISupportsHashKey>* nsTreeSanitizer::sAttributesSVG = nsnull;
+nsTHashtable<nsISupportsHashKey>* nsTreeSanitizer::sElementsMathML = nsnull;
+nsTHashtable<nsISupportsHashKey>* nsTreeSanitizer::sAttributesMathML = nsnull;
+nsIPrincipal* nsTreeSanitizer::sNullPrincipal = nsnull;
+
+nsTreeSanitizer::nsTreeSanitizer(PRBool aAllowStyles, PRBool aAllowComments)
+ : mAllowStyles(aAllowStyles)
+ , mAllowComments(aAllowComments)
+{
+  if (!sElementsHTML) {
+    // Initialize lazily to avoid having to initialize at all if the user
+    // doesn't paste HTML or load feeds.
+    InitializeStatics();
+  }
+}
+
+PRBool
+nsTreeSanitizer::MustFlatten(PRInt32 aNamespace, nsIAtom* aLocal)
+{
+  if (aNamespace == kNameSpaceID_XHTML) {
+    return !sElementsHTML->GetEntry(aLocal);
+  }
+  if (aNamespace == kNameSpaceID_SVG) {
+    return !sElementsSVG->GetEntry(aLocal);
+  }
+  if (aNamespace == kNameSpaceID_MathML) {
+    return !sElementsMathML->GetEntry(aLocal);
+  }
+  return PR_TRUE;
+}
+
+PRBool
+nsTreeSanitizer::IsURL(nsIAtom*** aURLs, nsIAtom* aLocalName)
+{
+  nsIAtom** atomPtrPtr;
+  while ((atomPtrPtr = *aURLs)) {
+    if (*atomPtrPtr == aLocalName) {
+      return PR_TRUE;
+    }
+    ++aURLs;
+  }
+  return PR_FALSE;
+}
+
+PRBool
+nsTreeSanitizer::MustPrune(PRInt32 aNamespace,
+                           nsIAtom* aLocal,
+                           mozilla::dom::Element* aElement)
+{
+  // To avoid attacks where a MathML script becomes something that gets
+  // serialized in a way that it parses back as an HTML script, let's just
+  // drop elements with the local name 'script' regardless of namespace.
+  if (nsGkAtoms::script == aLocal) {
+    return PR_TRUE;
+  }
+  if (aNamespace == kNameSpaceID_XHTML) {
+    if (nsGkAtoms::title == aLocal) {
+      // emulate the quirks of the old parser
+      return PR_TRUE;
+    }
+    if ((nsGkAtoms::meta == aLocal || nsGkAtoms::link == aLocal) &&
+        !(aElement->HasAttr(kNameSpaceID_None, nsGkAtoms::itemprop) ||
+          aElement->HasAttr(kNameSpaceID_None, nsGkAtoms::itemscope))) {
+      // emulate old behavior for non-Microdata <meta> and <link> presumably
+      // in <head>. <meta> and <link> are whitelisted in order to avoid
+      // corrupting Microdata when they appear in <body>. Note that
+      // SanitizeAttributes() will remove the rel attribute from <link> and
+      // the name attribute from <meta>.
+      return PR_TRUE;
+    }
+  }
+  if (mAllowStyles) {
+    if (nsGkAtoms::style == aLocal && !(aNamespace == kNameSpaceID_XHTML
+        || aNamespace == kNameSpaceID_SVG)) {
+      return PR_TRUE;
+    }
+    return PR_FALSE;
+  }
+  if (nsGkAtoms::style == aLocal) {
+    return PR_TRUE;
+  }
+  return PR_FALSE;
+}
+
+PRBool
+nsTreeSanitizer::SanitizeStyleRule(mozilla::css::StyleRule *aRule,
+                                   nsAutoString &aRuleText)
+{
+  PRBool didSanitize = PR_FALSE;
+  aRuleText.Truncate();
+  mozilla::css::Declaration* style = aRule->GetDeclaration();
+  if (style) {
+    didSanitize = style->HasProperty(eCSSProperty_binding);
+    style->RemoveProperty(eCSSProperty_binding);
+    style->ToString(aRuleText);
+  }
+  return didSanitize;
+}
+
+PRBool
+nsTreeSanitizer::SanitizeStyleSheet(const nsAString& aOriginal,
+                                    nsAString& aSanitized,
+                                    nsIDocument* aDocument,
+                                    nsIURI* aBaseURI)
+{
+  nsresult rv;
+  aSanitized.Truncate();
+  // aSanitized will hold the permitted CSS text.
+  // -moz-binding is blacklisted.
+  PRBool didSanitize = PR_FALSE;
+  // Create a sheet to hold the parsed CSS
+  nsRefPtr<nsCSSStyleSheet> sheet;
+  rv = NS_NewCSSStyleSheet(getter_AddRefs(sheet));
+  NS_ENSURE_SUCCESS(rv, PR_TRUE);
+  sheet->SetURIs(aDocument->GetDocumentURI(), nsnull, aBaseURI);
+  sheet->SetPrincipal(aDocument->NodePrincipal());
+  // Create the CSS parser, and parse the CSS text.
+  nsCSSParser parser(nsnull, sheet);
+  rv = parser.ParseSheet(aOriginal, aDocument->GetDocumentURI(), aBaseURI,
+                         aDocument->NodePrincipal(), 0, PR_FALSE);
+  NS_ENSURE_SUCCESS(rv, PR_TRUE);
+  // Mark the sheet as complete.
+  NS_ABORT_IF_FALSE(!sheet->IsModified(),
+      "should not get marked modified during parsing");
+  sheet->SetComplete();
+  // Loop through all the rules found in the CSS text
+  PRInt32 ruleCount = sheet->StyleRuleCount();
+  for (PRInt32 i = 0; i < ruleCount; ++i) {
+    nsRefPtr<mozilla::css::Rule> rule;
+    rv = sheet->GetStyleRuleAt(i, *getter_AddRefs(rule));
+    if (NS_FAILED(rv))
+      continue; NS_ASSERTION(rule, "We should have a rule by now");
+    switch (rule->GetType()) {
+      default:
+        didSanitize = PR_TRUE;
+        // Ignore these rule types.
+        break;
+      case mozilla::css::Rule::NAMESPACE_RULE:
+      case mozilla::css::Rule::FONT_FACE_RULE: {
+        // Append @namespace and @font-face rules verbatim.
+        nsAutoString cssText;
+        nsCOMPtr<nsIDOMCSSRule> styleRule = do_QueryInterface(rule);
+        if (styleRule) {
+          rv = styleRule->GetCssText(cssText);
+          if (NS_SUCCEEDED(rv)) {
+            aSanitized.Append(cssText);
+          }
+        }
+        break;
+      }
+      case mozilla::css::Rule::STYLE_RULE: {
+        // For style rules, we will just look for and remove the
+        // -moz-binding properties.
+        nsRefPtr<mozilla::css::StyleRule> styleRule = do_QueryObject(rule);
+        NS_ASSERTION(styleRule, "Must be a style rule");
+        nsAutoString decl;
+        PRBool sanitized = SanitizeStyleRule(styleRule, decl);
+        didSanitize = sanitized || didSanitize;
+        if (!sanitized) {
+          styleRule->GetCssText(decl);
+        }
+        aSanitized.Append(decl);
+      }
+    }
+  }
+  return didSanitize;
+}
+
+void
+nsTreeSanitizer::SanitizeAttributes(mozilla::dom::Element* aElement,
+                                    nsTHashtable<nsISupportsHashKey>* aAllowed,
+                                    nsIAtom*** aURLs,
+                                    PRBool aAllowXLink,
+                                    PRBool aAllowStyle,
+                                    PRBool aAllowDangerousSrc)
+{
+  PRUint32 ac = aElement->GetAttrCount();
+
+  nsresult rv;
+
+  for (PRInt32 i = ac - 1; i >= 0; --i) {
+    rv = NS_OK;
+    const nsAttrName* attrName = aElement->GetAttrNameAt(i);
+    PRInt32 attrNs = attrName->NamespaceID();
+    nsIAtom* attrLocal = attrName->LocalName();
+
+    if (kNameSpaceID_None == attrNs) {
+      if (aAllowStyle && nsGkAtoms::style == attrLocal) {
+        nsCOMPtr<nsIURI> baseURI = aElement->GetBaseURI();
+        nsIDocument* document = aElement->GetOwnerDoc();
+        // Pass the CSS Loader object to the parser, to allow parser error
+        // reports to include the outer window ID.
+        nsCSSParser parser(document->CSSLoader());
+        nsRefPtr<mozilla::css::StyleRule> rule;
+        nsAutoString value;
+        aElement->GetAttr(attrNs, attrLocal, value);
+        rv = parser.ParseStyleAttribute(value,
+                                        document->GetDocumentURI(),
+                                        baseURI,
+                                        document->NodePrincipal(),
+                                        getter_AddRefs(rule));
+        if (NS_SUCCEEDED(rv)) {
+          nsAutoString cleanValue;
+          if (SanitizeStyleRule(rule, cleanValue)) {
+            aElement->SetAttr(kNameSpaceID_None,
+                              nsGkAtoms::style,
+                              cleanValue,
+                              PR_FALSE);
+          }
+        }
+        continue;
+      }
+      if (aAllowDangerousSrc && nsGkAtoms::src == attrLocal) {
+        continue;
+      }
+      if (IsURL(aURLs, attrLocal)) {
+        SanitizeURL(aElement, attrNs, attrLocal);
+        continue;
+      }
+      if (aAllowed->GetEntry(attrLocal) &&
+          !(attrLocal == nsGkAtoms::rel &&
+            aElement->IsHTML(nsGkAtoms::link)) &&
+          !(attrLocal == nsGkAtoms::name &&
+            aElement->IsHTML(nsGkAtoms::meta))) {
+        // name="" and rel="" are whitelisted, but treat them as blacklisted
+        // for <meta name> and <link rel> to avoid document-wide metadata
+        // or styling overrides with non-conforming <meta name itemprop> or
+        // <link rel itemprop>
+        continue;
+      }
+      const PRUnichar* localStr = attrLocal->GetUTF16String();
+      // Allow underscore to cater to the MCE editor library.
+      // Allow data-* on SVG and MathML, too, as a forward-compat measure.
+      if (*localStr == '_' || (attrLocal->GetLength() > 5 && localStr[0] == 'd'
+          && localStr[1] == 'a' && localStr[2] == 't' && localStr[3] == 'a'
+          && localStr[4] == '-')) {
+        continue;
+      }
+      // else not allowed
+    } else if (kNameSpaceID_XML == attrNs) {
+      if (nsGkAtoms::base == attrLocal) {
+        SanitizeURL(aElement, attrNs, attrLocal);
+        continue;
+      }
+      if (nsGkAtoms::lang == attrLocal || nsGkAtoms::space == attrLocal) {
+        continue;
+      }
+      // else not allowed
+    } else if (aAllowXLink && kNameSpaceID_XLink == attrNs) {
+      if (nsGkAtoms::href == attrLocal) {
+        SanitizeURL(aElement, attrNs, attrLocal);
+        continue;
+      }
+      if (nsGkAtoms::type == attrLocal || nsGkAtoms::title == attrLocal
+          || nsGkAtoms::show == attrLocal || nsGkAtoms::actuate == attrLocal) {
+        continue;
+      }
+      // else not allowed
+    }
+    aElement->UnsetAttr(kNameSpaceID_None, attrLocal, PR_FALSE);
+    // in case the attribute removal shuffled the attribute order, start the
+    // loop again.
+    --ac;
+    i = ac; // i will be decremented immediately thanks to the for loop
+  }
+
+  // If we've got HTML audio or video, add the controls attribute, because
+  // otherwise the content is unplayable with scripts removed.
+  if (aElement->IsHTML(nsGkAtoms::video) ||
+      aElement->IsHTML(nsGkAtoms::audio)) {
+    aElement->SetAttr(kNameSpaceID_None,
+                      nsGkAtoms::controls,
+                      EmptyString(),
+                      PR_FALSE);
+  }
+}
+
+void
+nsTreeSanitizer::SanitizeURL(mozilla::dom::Element* aElement,
+                             PRInt32 aNamespace,
+                             nsIAtom* aLocalName)
+{
+  nsAutoString value;
+  aElement->GetAttr(aNamespace, aLocalName, value);
+
+  // Get value and remove mandatory quotes
+  static const char* kWhitespace = "\n\r\t\b";
+  const nsAString& v =
+    nsContentUtils::TrimCharsInSet(kWhitespace, value);
+
+  nsIScriptSecurityManager* secMan = nsContentUtils::GetSecurityManager();
+  PRUint32 flags = nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL;
+
+  nsCOMPtr<nsIURI> baseURI = aElement->GetBaseURI();
+  nsCOMPtr<nsIURI> attrURI;
+  nsresult rv = NS_NewURI(getter_AddRefs(attrURI), v, nsnull, baseURI);
+  if (NS_SUCCEEDED(rv)) {
+    rv = secMan->CheckLoadURIWithPrincipal(sNullPrincipal, attrURI, flags);
+  }
+  if (NS_FAILED(rv)) {
+    aElement->UnsetAttr(aNamespace, aLocalName, PR_FALSE);
+  }
+}
+
+void
+nsTreeSanitizer::Sanitize(nsIContent* aFragment) {
+  // If you want to relax these preconditions, be sure to check the code in
+  // here that notifies / does not notify or that fires mutation events if
+  // in tree.
+  NS_PRECONDITION(aFragment->IsNodeOfType(nsINode::eDOCUMENT_FRAGMENT),
+      "Argument was not DOM fragment.");
+  NS_PRECONDITION(!aFragment->IsInDoc(), "The fragment is in doc?");
+
+  nsIContent* node = aFragment->GetFirstChild();
+  while (node) {
+    if (node->IsElement()) {
+      mozilla::dom::Element* elt = node->AsElement();
+      nsINodeInfo* nodeInfo = node->NodeInfo();
+      nsIAtom* localName = nodeInfo->NameAtom();
+      PRInt32 ns = nodeInfo->NamespaceID();
+
+      if (MustPrune(ns, localName, elt)) {
+        nsIContent* next = node->GetNextNonChildNode(aFragment);
+        node->GetParent()->RemoveChild(node);
+        node = next;
+        continue;
+      }
+      if (nsGkAtoms::style == localName) {
+        // If styles aren't allowed, style elements got pruned above. Even
+        // if styles are allowed, non-HTML, non-SVG style elements got pruned
+        // above.
+        NS_ASSERTION(ns == kNameSpaceID_XHTML || ns == kNameSpaceID_SVG,
+            "Should have only HTML or SVG here!");
+        nsAutoString styleText;
+        nsContentUtils::GetNodeTextContent(node, PR_FALSE, styleText);
+        nsAutoString sanitizedStyle;
+        nsCOMPtr<nsIURI> baseURI = node->GetBaseURI();
+        if (SanitizeStyleSheet(styleText,
+                               sanitizedStyle,
+                               aFragment->GetOwnerDoc(),
+                               baseURI)) {
+          nsContentUtils::SetNodeTextContent(node, sanitizedStyle, PR_TRUE);
+        } else {
+          // If the node had non-text child nodes, this operation zaps those.
+          nsContentUtils::SetNodeTextContent(node, styleText, PR_TRUE);
+        }
+        if (ns == kNameSpaceID_XHTML) {
+          SanitizeAttributes(elt,
+                             sAttributesHTML,
+                             (nsIAtom***)kURLAttributesHTML,
+                             PR_FALSE,
+                             mAllowStyles,
+                             PR_FALSE);
+        } else {
+          SanitizeAttributes(elt,
+                             sAttributesSVG,
+                             (nsIAtom***)kURLAttributesSVG,
+                             PR_TRUE,
+                             mAllowStyles,
+                             PR_FALSE);
+        }
+        node = node->GetNextNonChildNode(aFragment);
+        continue;
+      }
+      if (MustFlatten(ns, localName)) {
+        nsIContent* next = node->GetNextNode(aFragment);
+        nsIContent* parent = node->GetParent();
+        nsCOMPtr<nsIContent> child; // Must keep the child alive during move
+        nsresult rv;
+        while ((child = node->GetFirstChild())) {
+          parent->InsertBefore(child, node, &rv);
+          if (NS_FAILED(rv)) {
+            break;
+          }
+        }
+        parent->RemoveChild(node);
+        node = next;
+        continue;
+      }
+      NS_ASSERTION(ns == kNameSpaceID_XHTML ||
+                   ns == kNameSpaceID_SVG ||
+                   ns == kNameSpaceID_MathML,
+          "Should have only HTML, MathML or SVG here!");
+      if (ns == kNameSpaceID_XHTML) {
+        SanitizeAttributes(elt,
+                           sAttributesHTML,
+                           (nsIAtom***)kURLAttributesHTML,
+                           PR_FALSE, mAllowStyles,
+                           (nsGkAtoms::img == localName));
+      } else if (ns == kNameSpaceID_SVG) {
+        SanitizeAttributes(elt,
+                           sAttributesSVG,
+                           (nsIAtom***)kURLAttributesSVG,
+                           PR_TRUE,
+                           mAllowStyles,
+                           PR_FALSE);
+      } else {
+        SanitizeAttributes(elt,
+                           sAttributesMathML,
+                           (nsIAtom***)kURLAttributesMathML,
+                           PR_TRUE,
+                           PR_FALSE,
+                           PR_FALSE);
+      }
+      node = node->GetNextNode(aFragment);
+      continue;
+    }
+    NS_ASSERTION(!node->GetFirstChild(), "How come non-element node had kids?");
+    nsIContent* next = node->GetNextNonChildNode(aFragment);
+    if (!mAllowComments && node->IsNodeOfType(nsINode::eCOMMENT)) {
+      node->GetParent()->RemoveChild(node);
+    }
+    node = next;
+  }
+}
+
+void
+nsTreeSanitizer::InitializeStatics()
+{
+  NS_PRECONDITION(!sElementsHTML, "Initializing a second time.");
+
+  sElementsHTML = new nsTHashtable<nsISupportsHashKey> ();
+  sElementsHTML->Init(NS_ARRAY_LENGTH(kElementsHTML));
+  for (PRUint32 i = 0; kElementsHTML[i]; i++) {
+    sElementsHTML->PutEntry(*kElementsHTML[i]);
+  }
+
+  sAttributesHTML = new nsTHashtable<nsISupportsHashKey> ();
+  sAttributesHTML->Init(NS_ARRAY_LENGTH(kAttributesHTML));
+  for (PRUint32 i = 0; kAttributesHTML[i]; i++) {
+    sAttributesHTML->PutEntry(*kAttributesHTML[i]);
+  }
+
+  sElementsSVG = new nsTHashtable<nsISupportsHashKey> ();
+  sElementsSVG->Init(NS_ARRAY_LENGTH(kElementsSVG));
+  for (PRUint32 i = 0; kElementsSVG[i]; i++) {
+    sElementsSVG->PutEntry(*kElementsSVG[i]);
+  }
+
+  sAttributesSVG = new nsTHashtable<nsISupportsHashKey> ();
+  sAttributesSVG->Init(NS_ARRAY_LENGTH(kAttributesSVG));
+  for (PRUint32 i = 0; kAttributesSVG[i]; i++) {
+    sAttributesSVG->PutEntry(*kAttributesSVG[i]);
+  }
+
+  sElementsMathML = new nsTHashtable<nsISupportsHashKey> ();
+  sElementsMathML->Init(NS_ARRAY_LENGTH(kElementsMathML));
+  for (PRUint32 i = 0; kElementsMathML[i]; i++) {
+    sElementsMathML->PutEntry(*kElementsMathML[i]);
+  }
+
+  sAttributesMathML = new nsTHashtable<nsISupportsHashKey> ();
+  sAttributesMathML->Init(NS_ARRAY_LENGTH(kAttributesMathML));
+  for (PRUint32 i = 0; kAttributesMathML[i]; i++) {
+    sAttributesMathML->PutEntry(*kAttributesMathML[i]);
+  }
+
+  nsCOMPtr<nsIPrincipal> principal =
+      do_CreateInstance(NS_NULLPRINCIPAL_CONTRACTID);
+  principal.forget(&sNullPrincipal);
+}
+
+void
+nsTreeSanitizer::ReleaseStatics()
+{
+  delete sElementsHTML;
+  sElementsHTML = nsnull;
+
+  delete sAttributesHTML;
+  sAttributesHTML = nsnull;
+
+  delete sElementsSVG;
+  sElementsSVG = nsnull;
+
+  delete sAttributesSVG;
+  sAttributesSVG = nsnull;
+
+  delete sElementsMathML;
+  sElementsMathML = nsnull;
+
+  delete sAttributesMathML;
+  sAttributesMathML = nsnull;
+
+  NS_IF_RELEASE(sNullPrincipal);
+}
--- a/content/base/src/nsXHTMLContentSerializer.cpp
+++ b/content/base/src/nsXHTMLContentSerializer.cpp
@@ -63,16 +63,17 @@
 #include "nsEscape.h"
 #include "nsITextToSubURI.h"
 #include "nsCRT.h"
 #include "nsIParserService.h"
 #include "nsContentUtils.h"
 #include "nsLWBrkCIID.h"
 #include "nsIScriptElement.h"
 #include "nsAttrName.h"
+#include "nsParserConstants.h"
 
 static const char kMozStr[] = "moz";
 
 static const PRInt32 kLongLineLen = 128;
 
 #define kXMLNS "xmlns"
 
 nsresult NS_NewXHTMLContentSerializer(nsIContentSerializer** aSerializer)
--- a/content/base/src/nsXMLContentSerializer.cpp
+++ b/content/base/src/nsXMLContentSerializer.cpp
@@ -60,16 +60,17 @@
 #include "nsString.h"
 #include "prprf.h"
 #include "nsUnicharUtils.h"
 #include "nsCRT.h"
 #include "nsContentUtils.h"
 #include "nsAttrName.h"
 #include "nsILineBreaker.h"
 #include "mozilla/dom/Element.h"
+#include "nsParserConstants.h"
 
 using namespace mozilla::dom;
 
 static const char kMozStr[] = "moz";
 
 #define kXMLNS "xmlns"
 
 // to be readable, we assume that an indented line contains
--- a/content/base/test/Makefile.in
+++ b/content/base/test/Makefile.in
@@ -240,20 +240,17 @@ include $(topsrcdir)/config/rules.mk
 		test_bug28293.html \
 		test_bug28293.xhtml \
 		file_bug28293.sjs \
 		test_bug445225.html \
 		file_bug445225_multipart.txt \
 		file_bug445225_multipart.txt^headers^ \
 		test_title.html \
 		test_bug453521.html \
-		test_bug391728.html \
-		file_bug391728.html \
 		test_bug454325.html \
-		file_bug391728_2.html \
 		test_bug456262.html \
 		test_bug482935.html \
 		     bug482935.sjs \
 		test_bug590870.html \
 		file_bug590870.html \
 		test_bug590812.html \
 		file_bug590812.xml \
 		file_bug590812-ref.xhtml \
--- a/content/base/test/chrome/Makefile.in
+++ b/content/base/test/chrome/Makefile.in
@@ -44,16 +44,19 @@ include $(DEPTH)/config/autoconf.mk
 include $(topsrcdir)/config/rules.mk
 
 _TEST_FILES = \
     bug421622-referer.sjs \
     $(NULL)
 
 _CHROME_FILES = \
     test_bug206691.xul \
+    test_bug391728.html \
+    file_bug391728.html \
+    file_bug391728_2.html \
     test_bug421622.xul \
     test_bug429785.xul \
     test_bug430050.xul \
     test_bug467123.xul \
     test_title.xul \
     title_window.xul \
     test_bug549682.xul \
     file_bug549682.xul \
rename from content/base/test/file_bug391728.html
rename to content/base/test/chrome/file_bug391728.html
rename from content/base/test/file_bug391728_2.html
rename to content/base/test/chrome/file_bug391728_2.html
rename from content/base/test/test_bug391728.html
rename to content/base/test/chrome/test_bug391728.html
--- a/content/base/test/test_bug391728.html
+++ b/content/base/test/chrome/test_bug391728.html
@@ -1,19 +1,19 @@
 <!DOCTYPE HTML>
 <html>
 <!--
 https://bugzilla.mozilla.org/show_bug.cgi?id=391728
 -->
 <head>
   <title>Test for Bug 391728</title>
-  <script type="text/javascript" src="/MochiKit/packed.js"></script>
-  <script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="text/javascript" src="/tests/SimpleTest/PluginUtils.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+  <script type="text/javascript" src="chrome://mochikit/content/MochiKit/packed.js"></script>
+  <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/PluginUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />
 </head>
 <body>
 <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=391728">Mozilla Bug 391728</a>
 <p id="display"></p>
 <div id="content">
   <iframe id="testframe" width="150" height="250" src="about:blank"></iframe>
 </div>
 <pre id="test">
@@ -37,17 +37,16 @@ function blocked_plugin_detected(event) 
   gBlocked.push(event.target.id);
 }
 
 function unknown_plugin_detected(event) {
   gUnknown.push(event.target.id);
 }
 
 function init_test() {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   // Make sure the blocklist is off for the duration of this test
   var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                         .getService(Components.interfaces.nsIPrefBranch);
   prefs.setBoolPref("extensions.blocklist.enabled", false);
 
   if (!PluginUtils.withTestPlugin(start_test))
     SimpleTest.finish();
 }
@@ -115,51 +114,47 @@ function test_list(list) {
     ok(list.indexOf("plugin" + i) >= 0, "Plugin " + i + " did not send the event");
   }
   for (i = 1; i <= FALLBACK_COUNT; i++) {
     ok(list.indexOf("fallback" + i) < 0, "Fallback plugin " + i + " should not have sent the event");
   }
 }
 
 function test_normal(plugin) {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   is(gUnknown.length, 0, "Should not have been any unknown plugins");
   is(gDisabled.length, 0, "Should not have been any disabled plugins");
   is(gBlocked.length, 0, "Should not have been any blocked plugins");
   test_style("solid");
   plugin.disabled = true;
   load_frame(test_disabled, "file_bug391728");
 }
 
 function test_disabled(plugin) {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   is(gUnknown.length, 0, "Should not have been any unknown plugins");
   is(gDisabled.length, PLUGIN_COUNT, "Should have been disabled plugins");
   test_list(gDisabled);
   is(gBlocked.length, 0, "Should not have been any blocked plugins");
   test_style("dotted");
   ok(plugin.disabled, "Plugin lost its disabled status");
   plugin.disabled = false;
   plugin.blocklisted = true;
   load_frame(test_blocked, "file_bug391728");
 }
 
 function test_blocked(plugin) {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   is(gUnknown.length, 0, "Should not have been any unknown plugins");
   is(gDisabled.length, 0, "Should not have been any disabled plugins");
   is(gBlocked.length, PLUGIN_COUNT, "Should have been blocked plugins");
   test_list(gBlocked);
   test_style("dashed");
   ok(plugin.blocklisted, "Plugin lost its blocklist status");
   load_frame(test_unknown, "file_bug391728_2");
 }
 
 function test_unknown(plugin) {
-  netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
   is(gUnknown.length, PLUGIN_COUNT, "Should have been unknown plugins");
   test_list(gUnknown);
   is(gDisabled.length, 0, "Should not have been any disabled plugins");
   is(gBlocked.length, 0, "Should not have been any blocked plugins");
   test_style("none");
   finish_test(plugin);
 }
 
--- a/content/events/src/nsEventListenerManager.cpp
+++ b/content/events/src/nsEventListenerManager.cpp
@@ -583,30 +583,29 @@ nsEventListenerManager::FindJSEventListe
     }
   }
   return nsnull;
 }
 
 nsresult
 nsEventListenerManager::SetJSEventListener(nsIScriptContext *aContext,
                                            void *aScopeObject,
-                                           nsISupports *aObject,
                                            nsIAtom* aName,
                                            PRBool aIsString,
                                            PRBool aPermitUntrustedEvents)
 {
   nsresult rv = NS_OK;
   PRUint32 eventType = nsContentUtils::GetEventId(aName);
   nsListenerStruct* ls = FindJSEventListener(eventType, aName);
 
   if (!ls) {
     // If we didn't find a script listener or no listeners existed
     // create and add a new one.
     nsCOMPtr<nsIDOMEventListener> scriptListener;
-    rv = NS_NewJSEventListener(aContext, aScopeObject, aObject, aName,
+    rv = NS_NewJSEventListener(aContext, aScopeObject, mTarget, aName,
                                getter_AddRefs(scriptListener));
     if (NS_SUCCEEDED(rv)) {
       AddEventListener(scriptListener, eventType, aName, nsnull,
                        NS_EVENT_FLAG_BUBBLE | NS_PRIV_EVENT_FLAG_SCRIPT);
 
       ls = FindJSEventListener(eventType, aName);
     }
   }
@@ -619,18 +618,17 @@ nsEventListenerManager::SetJSEventListen
       ls->mFlags |= NS_PRIV_EVENT_UNTRUSTED_PERMITTED;
     }
   }
 
   return rv;
 }
 
 nsresult
-nsEventListenerManager::AddScriptEventListener(nsISupports *aObject,
-                                               nsIAtom *aName,
+nsEventListenerManager::AddScriptEventListener(nsIAtom *aName,
                                                const nsAString& aBody,
                                                PRUint32 aLanguage,
                                                PRBool aDeferCompilation,
                                                PRBool aPermitUntrustedEvents)
 {
   NS_PRECONDITION(aLanguage != nsIProgrammingLanguage::UNKNOWN,
                   "Must know the language for the script event listener");
   nsIScriptContext *context = nsnull;
@@ -641,42 +639,41 @@ nsEventListenerManager::AddScriptEventLi
   // such scripts based on the source of their code, not just the source
   // of the event.
   if (aPermitUntrustedEvents && 
       aLanguage != nsIProgrammingLanguage::JAVASCRIPT) {
     NS_WARNING("Discarding non-JS event listener from untrusted source");
     return NS_ERROR_FAILURE;
   }
 
-  nsCOMPtr<nsINode> node(do_QueryInterface(aObject));
+  nsCOMPtr<nsINode> node(do_QueryInterface(mTarget));
 
   nsCOMPtr<nsIDocument> doc;
 
-  nsISupports *objiSupp = aObject;
   nsCOMPtr<nsIScriptGlobalObject> global;
 
   if (node) {
     // Try to get context from doc
     // XXX sXBL/XBL2 issue -- do we really want the owner here?  What
     // if that's the XBL document?
     doc = node->GetOwnerDoc();
     if (doc)
       global = doc->GetScriptGlobalObject();
   } else {
-    nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(aObject));
+    nsCOMPtr<nsPIDOMWindow> win(do_QueryInterface(mTarget));
     if (win) {
       NS_ASSERTION(win->IsInnerWindow(),
                    "Event listener added to outer window!");
 
       nsCOMPtr<nsIDOMDocument> domdoc;
       win->GetDocument(getter_AddRefs(domdoc));
       doc = do_QueryInterface(domdoc);
       global = do_QueryInterface(win);
     } else {
-      global = do_QueryInterface(aObject);
+      global = do_QueryInterface(mTarget);
     }
   }
 
   if (!global) {
     // This can happen; for example this document might have been
     // loaded as data.
     return NS_OK;
   }
@@ -697,17 +694,17 @@ nsEventListenerManager::AddScriptEventLi
       if ( !inlineOK ) {
         // gather information to log with violation report
         nsIURI* uri = doc->GetDocumentURI();
         nsCAutoString asciiSpec;
         if (uri)
           uri->GetAsciiSpec(asciiSpec);
         nsAutoString scriptSample, attr, tagName(NS_LITERAL_STRING("UNKNOWN"));
         aName->ToString(attr);
-        nsCOMPtr<nsIDOMNode> domNode(do_QueryInterface(aObject));
+        nsCOMPtr<nsIDOMNode> domNode(do_QueryInterface(mTarget));
         if (domNode)
           domNode->GetNodeName(tagName);
         // build a "script sample" based on what we know about this element
         scriptSample.Assign(attr);
         scriptSample.AppendLiteral(" attribute on ");
         scriptSample.Append(tagName);
         scriptSample.AppendLiteral(" element");
         csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_INLINE_SCRIPT,
@@ -728,25 +725,25 @@ nsEventListenerManager::AddScriptEventLi
 
   context = global->GetScriptContext(aLanguage);
   NS_ENSURE_TRUE(context, NS_ERROR_FAILURE);
 
   void *scope = global->GetScriptGlobal(aLanguage);
 
   if (!aDeferCompilation) {
     nsCOMPtr<nsIScriptEventHandlerOwner> handlerOwner =
-      do_QueryInterface(aObject);
+      do_QueryInterface(mTarget);
 
     nsScriptObjectHolder handler(context);
     PRBool done = PR_FALSE;
 
     if (handlerOwner) {
       rv = handlerOwner->GetCompiledEventHandler(aName, handler);
       if (NS_SUCCEEDED(rv) && handler) {
-        rv = context->BindCompiledEventHandler(aObject, scope, aName, handler);
+        rv = context->BindCompiledEventHandler(mTarget, scope, aName, handler);
         if (NS_FAILED(rv))
           return rv;
         done = PR_TRUE;
       }
     }
 
     if (!done) {
       PRUint32 lineNo = 0;
@@ -757,17 +754,17 @@ nsEventListenerManager::AddScriptEventLi
           uri->GetSpec(url);
           lineNo = 1;
         }
       }
 
       if (handlerOwner) {
         // Always let the handler owner compile the event handler, as
         // it may want to use a special context or scope object.
-        rv = handlerOwner->CompileEventHandler(context, aObject, aName,
+        rv = handlerOwner->CompileEventHandler(context, mTarget, aName,
                                                aBody, url.get(), lineNo, handler);
       }
       else {
         PRInt32 nameSpace = kNameSpaceID_Unknown;
         if (node && node->IsNodeOfType(nsINode::eCONTENT)) {
           nsIContent* content = static_cast<nsIContent*>(node.get());
           nameSpace = content->GetNameSpaceID();
         }
@@ -792,24 +789,24 @@ nsEventListenerManager::AddScriptEventLi
                                           SCRIPTVERSION_DEFAULT, // for now?
                                           handler);
         if (rv == NS_ERROR_ILLEGAL_VALUE) {
           NS_WARNING("Probably a syntax error in the event handler!");
           return NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA;
         }
         NS_ENSURE_SUCCESS(rv, rv);
         // And bind it.
-        rv = context->BindCompiledEventHandler(aObject, scope,
+        rv = context->BindCompiledEventHandler(mTarget, scope,
                                                aName, handler);
       }
       if (NS_FAILED(rv)) return rv;
     }
   }
 
-  return SetJSEventListener(context, scope, objiSupp, aName, aDeferCompilation,
+  return SetJSEventListener(context, scope, aName, aDeferCompilation,
                             aPermitUntrustedEvents);
 }
 
 void
 nsEventListenerManager::RemoveScriptEventListener(nsIAtom* aName)
 {
   PRUint32 eventType = nsContentUtils::GetEventId(aName);
   nsListenerStruct* ls = FindJSEventListener(eventType, aName);
@@ -822,25 +819,24 @@ nsEventListenerManager::RemoveScriptEven
 }
 
 jsid
 nsEventListenerManager::sAddListenerID = JSID_VOID;
 
 nsresult
 nsEventListenerManager::RegisterScriptEventListener(nsIScriptContext *aContext,
                                                     void *aScope,
-                                                    nsISupports *aObject, 
                                                     nsIAtom *aName)
 {
   // Check that we have access to set an event listener. Prevents
   // snooping attacks across domains by setting onkeypress handlers,
   // for instance.
   // You'd think it'd work just to get the JSContext from aContext,
   // but that's actually the JSContext whose private object parents
-  // the object in aObject.
+  // the object in mTarget.
   nsresult rv;
   nsCOMPtr<nsIJSContextStack> stack =
     do_GetService("@mozilla.org/js/xpc/ContextStack;1", &rv);
   if (NS_FAILED(rv))
     return rv;
   JSContext *cx;
   if (NS_FAILED(rv = stack->Peek(&cx)))
     return rv;
@@ -850,17 +846,17 @@ nsEventListenerManager::RegisterScriptEv
       JSAutoRequest ar(cx);
       sAddListenerID =
         INTERNED_STRING_TO_JSID(cx, ::JS_InternString(cx, "addEventListener"));
     }
 
     if (aContext->GetScriptTypeID() == nsIProgrammingLanguage::JAVASCRIPT) {
         nsCOMPtr<nsIXPConnectJSObjectHolder> holder;
         jsval v;
-        rv = nsContentUtils::WrapNative(cx, (JSObject *)aScope, aObject, &v,
+        rv = nsContentUtils::WrapNative(cx, (JSObject *)aScope, mTarget, &v,
                                         getter_AddRefs(holder));
         NS_ENSURE_SUCCESS(rv, rv);
       
         rv = nsContentUtils::GetSecurityManager()->
           CheckPropertyAccess(cx, JSVAL_TO_OBJECT(v),
                               "EventTarget",
                               sAddListenerID,
                               nsIXPCSecurityManager::ACCESS_SET_PROPERTY);
@@ -871,39 +867,38 @@ nsEventListenerManager::RegisterScriptEv
     } else {
         NS_WARNING("Skipping CheckPropertyAccess for non JS language");
     }
         
   }
 
   // Untrusted events are always permitted for non-chrome script
   // handlers.
-  return SetJSEventListener(aContext, aScope, aObject, aName,
-                            PR_FALSE, !nsContentUtils::IsCallerChrome());
+  return SetJSEventListener(aContext, aScope, aName, PR_FALSE,
+                            !nsContentUtils::IsCallerChrome());
 }
 
 nsresult
 nsEventListenerManager::CompileScriptEventListener(nsIScriptContext *aContext, 
                                                    void *aScope,
-                                                   nsISupports *aObject, 
                                                    nsIAtom *aName,
                                                    PRBool *aDidCompile)
 {
   nsresult rv = NS_OK;
   *aDidCompile = PR_FALSE;
   PRUint32 eventType = nsContentUtils::GetEventId(aName);
   nsListenerStruct* ls = FindJSEventListener(eventType, aName);
 
   if (!ls) {
     //nothing to compile
     return NS_OK;
   }
 
   if (ls->mHandlerIsString) {
-    rv = CompileEventHandlerInternal(aContext, aScope, aObject, aName,
+    rv = CompileEventHandlerInternal(aContext, aScope, mTarget, aName,
                                      ls, /*XXX fixme*/nsnull, PR_TRUE);
   }
 
   // Set *aDidCompile to true even if we didn't really compile
   // anything right now, if we get here it means that this event
   // handler has been compiled at some point, that's good enough for
   // us.
 
--- a/content/events/src/nsEventListenerManager.h
+++ b/content/events/src/nsEventListenerManager.h
@@ -102,30 +102,27 @@ public:
   void RemoveEventListenerByIID(nsIDOMEventListener *aListener,
                                 const nsIID& aIID, PRInt32 aFlags);
   nsresult AddEventListenerByType(nsIDOMEventListener *aListener,
                                   const nsAString& type,
                                   PRInt32 aFlags);
   void RemoveEventListenerByType(nsIDOMEventListener *aListener,
                                  const nsAString& type,
                                  PRInt32 aFlags);
-  nsresult AddScriptEventListener(nsISupports *aObject,
-                                  nsIAtom *aName,
+  nsresult AddScriptEventListener(nsIAtom *aName,
                                   const nsAString& aFunc,
                                   PRUint32 aLanguage,
                                   PRBool aDeferCompilation,
                                   PRBool aPermitUntrustedEvents);
   nsresult RegisterScriptEventListener(nsIScriptContext *aContext,
                                        void *aScopeObject,
-                                       nsISupports *aObject,
                                        nsIAtom* aName);
   void RemoveScriptEventListener(nsIAtom *aName);
   nsresult CompileScriptEventListener(nsIScriptContext *aContext,
                                       void *aScopeObject,
-                                      nsISupports *aObject,
                                       nsIAtom* aName, PRBool *aDidCompile);
 
   void HandleEvent(nsPresContext* aPresContext,
                    nsEvent* aEvent, 
                    nsIDOMEvent** aDOMEvent,
                    nsIDOMEventTarget* aCurrentTarget,
                    PRUint32 aFlags,
                    nsEventStatus* aEventStatus,
@@ -211,17 +208,16 @@ protected:
                                        nsISupports *aObject,
                                        nsIAtom *aName,
                                        nsListenerStruct *aListenerStruct,
                                        nsISupports* aCurrentTarget,
                                        PRBool aNeedsCxPush);
   nsListenerStruct* FindJSEventListener(PRUint32 aEventType, nsIAtom* aTypeAtom);
   nsresult SetJSEventListener(nsIScriptContext *aContext,
                               void *aScopeGlobal,
-                              nsISupports *aObject,
                               nsIAtom* aName, PRBool aIsString,
                               PRBool aPermitUntrustedEvents);
   nsresult AddEventListener(nsIDOMEventListener *aListener, 
                             PRUint32 aType,
                             nsIAtom* aTypeAtom,
                             const EventTypeData* aTypeData,
                             PRInt32 aFlags);
   void RemoveEventListener(nsIDOMEventListener *aListener,
--- a/content/events/src/nsEventStateManager.cpp
+++ b/content/events/src/nsEventStateManager.cpp
@@ -1503,16 +1503,45 @@ nsEventStateManager::ExecuteAccessKey(ns
         }
         return PR_TRUE;
       }
     }
   }
   return PR_FALSE;
 }
 
+PRBool
+nsEventStateManager::GetAccessKeyLabelPrefix(nsAString& aPrefix)
+{
+  aPrefix.Truncate();
+  nsAutoString separator, modifierText;
+  nsContentUtils::GetModifierSeparatorText(separator);
+
+  nsCOMPtr<nsISupports> container = mPresContext->GetContainer();
+  PRInt32 modifier = GetAccessModifierMask(container);
+
+  if (modifier & NS_MODIFIER_CONTROL) {
+    nsContentUtils::GetControlText(modifierText);
+    aPrefix.Append(modifierText + separator);
+  }
+  if (modifier & NS_MODIFIER_META) {
+    nsContentUtils::GetMetaText(modifierText);
+    aPrefix.Append(modifierText + separator);
+  }
+  if (modifier & NS_MODIFIER_ALT) {
+    nsContentUtils::GetAltText(modifierText);
+    aPrefix.Append(modifierText + separator);
+  }
+  if (modifier & NS_MODIFIER_SHIFT) {
+    nsContentUtils::GetShiftText(modifierText);
+    aPrefix.Append(modifierText + separator);
+  }
+  return !aPrefix.IsEmpty();
+}
+
 void
 nsEventStateManager::HandleAccessKey(nsPresContext* aPresContext,
                                      nsKeyEvent *aEvent,
                                      nsEventStatus* aStatus,
                                      nsIDocShellTreeItem* aBubbledFrom,
                                      ProcessingAccessKeyState aAccessKeyState,
                                      PRInt32 aModifierMask)
 {
@@ -2637,24 +2666,25 @@ nsEventStateManager::ComputeWheelActionF
   if (aMouseEvent->message == NS_MOUSE_PIXEL_SCROLL) {
     if (action == MOUSE_SCROLL_N_LINES || action == MOUSE_SCROLL_PAGE ||
         (aMouseEvent->scrollFlags & nsMouseScrollEvent::kIsMomentum)) {
       action = MOUSE_SCROLL_PIXELS;
     } else {
       // Do not scroll pixels when zooming
       action = -1;
     }
-  } else if (aMouseEvent->scrollFlags & nsMouseScrollEvent::kHasPixels) {
-    if (aUseSystemSettings ||
-        action == MOUSE_SCROLL_N_LINES || action == MOUSE_SCROLL_PAGE ||
-        (aMouseEvent->scrollFlags & nsMouseScrollEvent::kIsMomentum)) {
-      // Don't scroll lines when a pixel scroll event will follow.
-      // Also, don't do history scrolling or zooming for momentum scrolls.
-      action = -1;
-    }
+  } else if (((aMouseEvent->scrollFlags & nsMouseScrollEvent::kHasPixels) &&
+              (aUseSystemSettings ||
+               action == MOUSE_SCROLL_N_LINES || action == MOUSE_SCROLL_PAGE)) ||
+             ((aMouseEvent->scrollFlags & nsMouseScrollEvent::kIsMomentum) &&
+              (action == MOUSE_SCROLL_HISTORY || action == MOUSE_SCROLL_ZOOM))) {
+    // Don't scroll lines or page when a pixel scroll event will follow.
+    // Also, don't do history scrolling or zooming for momentum scrolls,
+    // no matter what's going on with pixel scrolling.
+    action = -1;
   }
 
   return action;
 }
 
 PRInt32
 nsEventStateManager::GetWheelActionFor(nsMouseScrollEvent* aMouseEvent)
 {
--- a/content/events/src/nsEventStateManager.h
+++ b/content/events/src/nsEventStateManager.h
@@ -155,16 +155,18 @@ public:
   /**
    * Get accesskey registered on the given element or 0 if there is none.
    *
    * @param  aContent  the given element
    * @return           registered accesskey
    */
   PRUint32 GetRegisteredAccessKey(nsIContent* aContent);
 
+  PRBool GetAccessKeyLabelPrefix(nsAString& aPrefix);
+
   nsresult SetCursor(PRInt32 aCursor, imgIContainer* aContainer,
                      PRBool aHaveHotspot, float aHotspotX, float aHotspotY,
                      nsIWidget* aWidget, PRBool aLockCursor); 
 
   static void StartHandlingUserInput()
   {
     ++sUserInputEventDepth;
   }
--- a/content/events/test/test_bug574663.html
+++ b/content/events/test/test_bug574663.html
@@ -30,17 +30,21 @@ function sendTouchpadScrollMotion(scroll
     'axis': "vertical",
     'delta': direction,
     'hasPixels': true,
     'ctrlKey': ctrl,
     'isMomentum': momentum,
   };
   // first a line scroll
   synthesizeMouseScroll(scrollbox, 10, 10, event, win);
+  // Then a line scroll with hasPixels set to false
+  event.hasPixels = false;
+  synthesizeMouseScroll(scrollbox, 10, 10, event, win);
   // then 5 pixel scrolls
+  event.hasPixels = true;
   event.delta *= 3;
   event.type = "MozMousePixelScroll";
   event.hasPixels = false;
   for (let i = 0; i < 5; ++i) {
     synthesizeMouseScroll(scrollbox, 10, 10, event, win);
   }
 }
 
--- a/content/html/content/src/nsGenericHTMLElement.cpp
+++ b/content/html/content/src/nsGenericHTMLElement.cpp
@@ -458,16 +458,31 @@ nsresult
 nsGenericHTMLElement::SetClassName(const nsAString& aClassName)
 {
   SetAttr(kNameSpaceID_None, nsGkAtoms::_class, aClassName, PR_TRUE);
   return NS_OK;
 }
 
 NS_IMPL_STRING_ATTR(nsGenericHTMLElement, AccessKey, accesskey)
 
+NS_IMETHODIMP
+nsGenericHTMLElement::GetAccessKeyLabel(nsAString& aLabel)
+{
+  nsPresContext *presContext = GetPresContext();
+
+  if (presContext &&
+    presContext->EventStateManager()->GetAccessKeyLabelPrefix(aLabel)) {
+      nsAutoString suffix;
+      GetAccessKey(suffix);
+      aLabel.Append(suffix);
+  }
+
+  return NS_OK;
+}
+
 static PRBool
 IsBody(nsIContent *aContent)
 {
   return aContent->NodeInfo()->Equals(nsGkAtoms::body) &&
          aContent->IsHTML();
 }
 
 static PRBool IS_TABLE_CELL(nsIAtom* frameType) {
@@ -701,97 +716,179 @@ nsGenericHTMLElement::GetInnerHTML(nsASt
   NS_ENSURE_SUCCESS(rv, rv);
 
   docEncoder->SetNativeContainerNode(this);
   rv = docEncoder->EncodeToString(aInnerHTML);
   doc->SetCachedEncoder(docEncoder.forget());
   return rv;
 }
 
+void
+nsGenericHTMLElement::FireMutationEventsForDirectParsing(nsIDocument* aDoc,
+                                                         nsIContent* aDest,
+                                                         PRInt32 aOldChildCount)
+{
+  // Fire mutation events. Optimize for the case when there are no listeners
+  PRInt32 newChildCount = aDest->GetChildCount();
+  if (newChildCount && nsContentUtils::
+        HasMutationListeners(aDoc, NS_EVENT_BITS_MUTATION_NODEINSERTED)) {
+    nsAutoTArray<nsCOMPtr<nsIContent>, 50> childNodes;
+    NS_ASSERTION(newChildCount - aOldChildCount >= 0,
+                 "What, some unexpected dom mutation has happened?");
+    childNodes.SetCapacity(newChildCount - aOldChildCount);
+    for (nsINode::ChildIterator iter(aDest); !iter.IsDone(); iter.Next()) {
+      childNodes.AppendElement(iter);
+    }
+    nsGenericElement::FireNodeInserted(aDoc, aDest, childNodes);
+  }
+}
+
 nsresult
 nsGenericHTMLElement::SetInnerHTML(const nsAString& aInnerHTML)
 {
   nsIDocument* doc = GetOwnerDoc();
   NS_ENSURE_STATE(doc);
 
   nsresult rv = NS_OK;
 
   // Batch possible DOMSubtreeModified events.
   mozAutoSubtreeModified subtree(doc, nsnull);
 
   FireNodeRemovedForChildren();
 
-  // This BeginUpdate/EndUpdate pair is important to make us reenable the
-  // scriptloader before the last EndUpdate call.
+  // Needed when innerHTML is used in combination with contenteditable
   mozAutoDocUpdate updateBatch(doc, UPDATE_CONTENT_MODEL, PR_TRUE);
 
   // Remove childnodes.
   // i is unsigned, so i >= is always true
   for (PRUint32 i = GetChildCount(); i-- != 0; ) {
     RemoveChildAt(i, PR_TRUE);
   }
 
   nsCOMPtr<nsIDOMDocumentFragment> df;
 
-  // Strong ref since appendChild can fire events
-  nsRefPtr<nsScriptLoader> loader = doc->ScriptLoader();
-  PRBool scripts_enabled = loader->GetEnabled();
-  loader->SetEnabled(PR_FALSE);
-
-  if (doc->IsHTML() && nsHtml5Module::sEnabled) {
-    nsCOMPtr<nsIParser> parser = doc->GetFragmentParser();
-    if (parser) {
-      parser->Reset();
-    } else {
-      parser = nsHtml5Module::NewHtml5Parser();
-      NS_ENSURE_TRUE(parser, NS_ERROR_OUT_OF_MEMORY);
-    }
-
+  if (doc->IsHTML()) {
     PRInt32 oldChildCount = GetChildCount();
-    nsAHtml5FragmentParser* asFragmentParser =
-        static_cast<nsAHtml5FragmentParser*> (parser.get());
-    asFragmentParser->ParseHtml5Fragment(aInnerHTML,
-                                         this,
-                                         Tag(),
-                                         GetNameSpaceID(),
-                                         doc->GetCompatibilityMode() ==
-                                             eCompatibility_NavQuirks,
-                                         PR_TRUE);
-    doc->SetFragmentParser(parser);
-
+    nsContentUtils::ParseFragmentHTML(aInnerHTML,
+                                      this,
+                                      Tag(),
+                                      GetNameSpaceID(),
+                                      doc->GetCompatibilityMode() ==
+                                          eCompatibility_NavQuirks,
+                                      PR_TRUE);
     // 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)) {
-      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.AppendElement(iter);
-      }
-      nsGenericElement::FireNodeInserted(doc, this, childNodes);
-    }
+    FireMutationEventsForDirectParsing(doc, this, oldChildCount);
   } else {
-    rv = nsContentUtils::CreateContextualFragment(this, aInnerHTML, PR_FALSE,
+    rv = nsContentUtils::CreateContextualFragment(this, aInnerHTML,
+                                                  PR_TRUE,
                                                   getter_AddRefs(df));
     nsCOMPtr<nsINode> fragment = do_QueryInterface(df);
     if (NS_SUCCEEDED(rv)) {
       static_cast<nsINode*>(this)->AppendChild(fragment, &rv);
     }
   }
 
-  if (scripts_enabled) {
-    // If we disabled scripts, re-enable them now that we're
-    // done. Don't fire JS timeouts when enabling the context here.
-
-    loader->SetEnabled(PR_TRUE);
+  return rv;
+}
+
+enum nsAdjacentPosition {
+  eBeforeBegin,
+  eAfterBegin,
+  eBeforeEnd,
+  eAfterEnd
+};
+
+nsresult
+nsGenericHTMLElement::InsertAdjacentHTML(const nsAString& aPosition,
+                                         const nsAString& aText)
+{
+  nsAdjacentPosition position;
+  if (aPosition.LowerCaseEqualsLiteral("beforebegin")) {
+    position = eBeforeBegin;
+  } else if (aPosition.LowerCaseEqualsLiteral("afterbegin")) {
+    position = eAfterBegin;
+  } else if (aPosition.LowerCaseEqualsLiteral("beforeend")) {
+    position = eBeforeEnd;
+  } else if (aPosition.LowerCaseEqualsLiteral("afterend")) {
+    position = eAfterEnd;
+  } else {
+    return NS_ERROR_DOM_SYNTAX_ERR;
+  }
+
+  nsCOMPtr<nsIContent> destination;
+  if (position == eBeforeBegin || position == eAfterEnd) {
+    destination = GetParent();
+    if (!destination) {
+      return NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR;
+    }
+  } else {
+    destination = this;
   }
 
+  nsIDocument* doc = GetOwnerDoc();
+  NS_ENSURE_STATE(doc);
+
+  // Needed when insertAdjacentHTML is used in combination with contenteditable
+  mozAutoDocUpdate updateBatch(doc, UPDATE_CONTENT_MODEL, PR_TRUE);
+
+  // Batch possible DOMSubtreeModified events.
+  mozAutoSubtreeModified subtree(doc, nsnull);
+
+  // Parse directly into destination if possible
+  if (doc->IsHTML() &&
+      (position == eBeforeEnd ||
+       (position == eAfterEnd && !GetNextSibling()) ||
+       (position == eAfterBegin && !GetFirstChild()))) {
+    PRInt32 oldChildCount = destination->GetChildCount();
+    PRInt32 contextNs = destination->GetNameSpaceID();
+    nsIAtom* contextLocal = destination->Tag();
+    if (contextLocal == nsGkAtoms::html && contextNs == kNameSpaceID_XHTML) {
+      // For compat with IE6 through IE9. Willful violation of HTML5 as of
+      // 2011-04-06. CreateContextualFragment does the same already.
+      // Spec bug: http://www.w3.org/Bugs/Public/show_bug.cgi?id=12434
+      contextLocal = nsGkAtoms::body;
+    }
+    nsContentUtils::ParseFragmentHTML(aText,
+                                      destination,
+                                      contextLocal,
+                                      contextNs,
+                                      doc->GetCompatibilityMode() ==
+                                          eCompatibility_NavQuirks,
+                                      PR_TRUE);
+    // HTML5 parser has notified, but not fired mutation events.
+    FireMutationEventsForDirectParsing(doc, destination, oldChildCount);
+    return NS_OK;
+  }
+
+  // couldn't parse directly
+  nsCOMPtr<nsIDOMDocumentFragment> df;
+  nsresult rv = nsContentUtils::CreateContextualFragment(destination,
+                                                         aText,
+                                                         PR_TRUE,
+                                                         getter_AddRefs(df));
+  nsCOMPtr<nsINode> fragment = do_QueryInterface(df);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  switch (position) {
+    case eBeforeBegin:
+      destination->InsertBefore(fragment, this, &rv);
+      break;
+    case eAfterBegin:
+      static_cast<nsINode*>(this)->InsertBefore(fragment, GetFirstChild(), &rv);
+      break;
+    case eBeforeEnd:
+      static_cast<nsINode*>(this)->AppendChild(fragment, &rv);
+      break;
+    case eAfterEnd:
+      destination->InsertBefore(fragment, GetNextSibling(), &rv);
+      break;
+    default:
+      NS_NOTREACHED("Bad position.");
+      break;
+  }
   return rv;
 }
 
 nsresult
 nsGenericHTMLElement::ScrollIntoView(PRBool aTop, PRUint8 optional_argc)
 {
   nsIDocument *document = GetCurrentDoc();
 
@@ -1118,62 +1215,47 @@ nsGenericHTMLElement::AfterSetAttr(PRInt
       SyncEditorsOnSubtree(this);
     }
   }
 
   return nsGenericHTMLElementBase::AfterSetAttr(aNamespaceID, aName,
                                                 aValue, aNotify);
 }
 
-nsresult
-nsGenericHTMLElement::GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                                     nsISupports** aTarget,
-                                                     PRBool* aDefer)
+nsEventListenerManager*
+nsGenericHTMLElement::GetEventListenerManagerForAttr(PRBool* aDefer)
 {
   // Attributes on the body and frameset tags get set on the global object
   if (mNodeInfo->Equals(nsGkAtoms::body) ||
       mNodeInfo->Equals(nsGkAtoms::frameset)) {
     nsPIDOMWindow *win;
 
     // If we have a document, and it has a window, add the event
     // listener on the window (the inner window). If not, proceed as
     // normal.
     // XXXbz sXBL/XBL2 issue: should we instead use GetCurrentDoc() here,
     // override BindToTree for those classes and munge event listeners there?
     nsIDocument *document = GetOwnerDoc();
-    nsresult rv = NS_OK;
 
     // FIXME (https://bugzilla.mozilla.org/show_bug.cgi?id=431767)
     // nsDocument::GetInnerWindow can return an outer window in some cases,
     // we don't want to stick an event listener on an outer window, so
     // bail if it does.
+    *aDefer = PR_FALSE;
     if (document &&
         (win = document->GetInnerWindow()) && win->IsInnerWindow()) {
       nsCOMPtr<nsIDOMEventTarget> piTarget(do_QueryInterface(win));
-      NS_ENSURE_TRUE(piTarget, NS_ERROR_FAILURE);
-
-      *aManager = piTarget->GetListenerManager(PR_TRUE);
-
-      if (*aManager) {
-        NS_ADDREF(*aTarget = win);
-        NS_ADDREF(*aManager);
-      }
-      *aDefer = PR_FALSE;
-    } else {
-      *aManager = nsnull;
-      *aTarget = nsnull;
-      *aDefer = PR_FALSE;
+
+      return piTarget->GetListenerManager(PR_TRUE);
     }
 
-    return rv;
+    return nsnull;
   }
 
-  return nsGenericHTMLElementBase::GetEventListenerManagerForAttr(aManager,
-                                                                  aTarget,
-                                                                  aDefer);
+  return nsGenericHTMLElementBase::GetEventListenerManagerForAttr(aDefer);
 }
 
 nsresult
 nsGenericHTMLElement::SetAttr(PRInt32 aNameSpaceID, nsIAtom* aName,
                               nsIAtom* aPrefix, const nsAString& aValue,
                               PRBool aNotify)
 {
   PRBool contentEditable = aNameSpaceID == kNameSpaceID_None &&
--- a/content/html/content/src/nsGenericHTMLElement.h
+++ b/content/html/content/src/nsGenericHTMLElement.h
@@ -130,16 +130,18 @@ public:
   // methods.
   nsresult GetOffsetTop(PRInt32* aOffsetTop);
   nsresult GetOffsetLeft(PRInt32* aOffsetLeft);
   nsresult GetOffsetWidth(PRInt32* aOffsetWidth);
   nsresult GetOffsetHeight(PRInt32* aOffsetHeight);
   nsresult GetOffsetParent(nsIDOMElement** aOffsetParent);
   virtual nsresult GetInnerHTML(nsAString& aInnerHTML);
   virtual nsresult SetInnerHTML(const nsAString& aInnerHTML);
+  virtual nsresult InsertAdjacentHTML(const nsAString& aPosition,
+                                      const nsAString& aText);
   nsresult ScrollIntoView(PRBool aTop, PRUint8 optional_argc);
   // Declare Focus(), Blur(), GetTabIndex(), SetTabIndex(), GetHidden(),
   // SetHidden(), GetSpellcheck(), SetSpellcheck(), and GetDraggable() such that
   // classes that inherit interfaces with those methods properly override them.
   NS_IMETHOD Focus();
   NS_IMETHOD Blur();
   NS_IMETHOD Click();
   NS_IMETHOD GetTabIndex(PRInt32 *aTabIndex);
@@ -147,16 +149,17 @@ public:
   NS_IMETHOD GetHidden(PRBool* aHidden);
   NS_IMETHOD SetHidden(PRBool aHidden);
   NS_IMETHOD GetSpellcheck(PRBool* aSpellcheck);
   NS_IMETHOD SetSpellcheck(PRBool aSpellcheck);
   NS_IMETHOD GetDraggable(PRBool* aDraggable);
   NS_IMETHOD SetDraggable(PRBool aDraggable);
   NS_IMETHOD GetAccessKey(nsAString &aAccessKey);
   NS_IMETHOD SetAccessKey(const nsAString& aAccessKey);
+  NS_IMETHOD GetAccessKeyLabel(nsAString& aLabel);
   nsresult GetContentEditable(nsAString& aContentEditable);
   nsresult GetIsContentEditable(PRBool* aContentEditable);
   nsresult SetContentEditable(const nsAString &aContentEditable);
   nsresult GetDataset(nsIDOMDOMStringMap** aDataset);
   // Callback for destructor of of dataset to ensure to null out weak pointer.
   nsresult ClearDataset();
 
   // Implementation for nsIContent
@@ -565,33 +568,43 @@ protected:
   void UnregAccessKey()
   {
     if (HasFlag(NODE_HAS_ACCESSKEY)) {
       RegUnRegAccessKey(PR_FALSE);
     }
   }
 
 private:
+  /**
+   * Fire mutation events for changes caused by parsing directly into a
+   * context node.
+   *
+   * @param aDoc the document of the node
+   * @param aDest the destination node that got stuff appended to it
+   * @param aOldChildCount the number of children the node had before parsing
+   */
+  void FireMutationEventsForDirectParsing(nsIDocument* aDoc,
+                                          nsIContent* aDest,
+                                          PRInt32 aOldChildCount);
+
   void RegUnRegAccessKey(PRBool aDoReg);
 
 protected:
   /**
    * Determine whether an attribute is an event (onclick, etc.)
    * @param aName the attribute
    * @return whether the name is an event handler name
    */
   PRBool IsEventName(nsIAtom* aName);
 
   virtual nsresult AfterSetAttr(PRInt32 aNamespaceID, nsIAtom* aName,
                                 const nsAString* aValue, PRBool aNotify);
 
-  virtual nsresult
-    GetEventListenerManagerForAttr(nsEventListenerManager** aManager,
-                                   nsISupports** aTarget,
-                                   PRBool* aDefer);
+  virtual nsEventListenerManager*
+    GetEventListenerManagerForAttr(PRBool* aDefer);
 
   virtual const nsAttrName* InternalGetExistingAttrNameFromQName(const nsAString& aStr) const;
 
   /**
    * Helper method for NS_IMPL_STRING_ATTR macro.
    * Gets the value of an attribute, returns empty string if
    * attribute isn't set. Only works for attributes in null namespace.
    *
@@ -1468,16 +1481,17 @@ protected:
   NS_SCRIPTABLE NS_IMETHOD GetLang(nsAString & aLang) { return _to GetLang(aLang); } \
   NS_SCRIPTABLE NS_IMETHOD SetLang(const nsAString & aLang) { return _to SetLang(aLang); } \
   NS_SCRIPTABLE NS_IMETHOD GetDir(nsAString & aDir) { return _to GetDir(aDir); } \
   NS_SCRIPTABLE NS_IMETHOD SetDir(const nsAString & aDir) { return _to SetDir(aDir); } \
   NS_SCRIPTABLE NS_IMETHOD GetClassName(nsAString & aClassName) { return _to GetClassName(aClassName); } \
   NS_SCRIPTABLE NS_IMETHOD SetClassName(const nsAString & aClassName) { return _to SetClassName(aClassName); } \
   NS_SCRIPTABLE NS_IMETHOD GetAccessKey(nsAString & aAccessKey) { return _to GetAccessKey(aAccessKey); } \
   NS_SCRIPTABLE NS_IMETHOD SetAccessKey(const nsAString & aAccessKey) { return _to SetAccessKey(aAccessKey); } \
+  NS_SCRIPTABLE NS_IMETHOD GetAccessKeyLabel(nsAString & aLabel) { return _to GetAccessKeyLabel(aLabel); } \
   NS_SCRIPTABLE NS_IMETHOD Blur(void) { return _to Blur(); }
 
 /**
  * A macro to declare the NS_NewHTMLXXXElement() functions.
  */
 #define NS_DECLARE_NS_NEW_HTML_ELEMENT(_elementName)                       \
 nsGenericHTMLElement*                                                      \
 NS_NewHTML##_elementName##Element(already_AddRefed<nsINodeInfo> aNodeInfo, \
--- a/content/html/content/src/nsHTMLCanvasElement.cpp
+++ b/content/html/content/src/nsHTMLCanvasElement.cpp
@@ -507,17 +507,16 @@ nsHTMLCanvasElement::GetContext(const ns
         }
       }
 
       contextProps = newProps;
     }
 
     rv = UpdateContext(contextProps);
     if (NS_FAILED(rv)) {
-      mCurrentContext = nsnull;
       if (!forceThebes) {
         // Try again with a Thebes context
         forceThebes = PR_TRUE;
         continue;
       }
       return rv;
     }
 
@@ -553,20 +552,17 @@ nsHTMLCanvasElement::MozGetIPCContext(co
     NS_ENSURE_SUCCESS(rv, rv);
     if (!mCurrentContext) {
       return NS_OK;
     }
 
     mCurrentContext->SetIsIPC(PR_TRUE);
 
     rv = UpdateContext();
-    if (NS_FAILED(rv)) {
-      mCurrentContext = nsnull;
-      return rv;
-    }
+    NS_ENSURE_SUCCESS(rv, rv);
 
     mCurrentContextId.Assign(aContextId);
   } else if (!mCurrentContextId.Equals(aContextId)) {
     //XXX eventually allow for more than one active context on a given canvas
     return NS_ERROR_INVALID_ARG;
   }
 
   NS_ADDREF (*aContext = mCurrentContext);
--- a/content/html/content/src/nsHTMLInputElement.cpp
+++ b/content/html/content/src/nsHTMLInputElement.cpp
@@ -2718,25 +2718,34 @@ nsHTMLInputElement::GetTextLength(PRInt3
 
   *aTextLength = val.Length();
 
   return rv;
 }
 
 NS_IMETHODIMP
 nsHTMLInputElement::SetSelectionRange(PRInt32 aSelectionStart,
-                                      PRInt32 aSelectionEnd)
+                                      PRInt32 aSelectionEnd,
+                                      const nsAString& aDirection)
 {
   nsresult rv = NS_ERROR_FAILURE;
   nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
 
   if (formControlFrame) {
     nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
     if (textControlFrame) {
-      rv = textControlFrame->SetSelectionRange(aSelectionStart, aSelectionEnd);
+      // Default to forward, even if not specified.
+      // Note that we don't currently support directionless selections, so
+      // "none" is treated like "forward".
+      nsITextControlFrame::SelectionDirection dir = nsITextControlFrame::eForward;
+      if (aDirection.EqualsLiteral("backward")) {
+        dir = nsITextControlFrame::eBackward;
+      }
+
+      rv = textControlFrame->SetSelectionRange(aSelectionStart, aSelectionEnd, dir);
       if (NS_SUCCEEDED(rv)) {
         rv = textControlFrame->ScrollSelectionIntoView();
       }
     }
   }
 
   return rv;
 }
@@ -2748,59 +2757,53 @@ nsHTMLInputElement::GetSelectionStart(PR
   
   PRInt32 selEnd;
   return GetSelectionRange(aSelectionStart, &selEnd);
 }
 
 NS_IMETHODIMP
 nsHTMLInputElement::SetSelectionStart(PRInt32 aSelectionStart)
 {
-  nsresult rv = NS_ERROR_FAILURE;
-  nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
-
-  if (formControlFrame) {
-    nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
-    if (textControlFrame) {
-      rv = textControlFrame->SetSelectionStart(aSelectionStart);
-      if (NS_SUCCEEDED(rv)) {
-        rv = textControlFrame->ScrollSelectionIntoView();
-      }
-    }
+  nsAutoString direction;
+  nsresult rv = GetSelectionDirection(direction);
+  NS_ENSURE_SUCCESS(rv, rv);
+  PRInt32 start, end;
+  rv = GetSelectionRange(&start, &end);
+  NS_ENSURE_SUCCESS(rv, rv);
+  start = aSelectionStart;
+  if (end < start) {
+    end = start;
   }
-
-  return rv;
+  return SetSelectionRange(start, end, direction);
 }
 
 NS_IMETHODIMP
 nsHTMLInputElement::GetSelectionEnd(PRInt32* aSelectionEnd)
 {
   NS_ENSURE_ARG_POINTER(aSelectionEnd);
   
   PRInt32 selStart;
   return GetSelectionRange(&selStart, aSelectionEnd);
 }
 
 
 NS_IMETHODIMP
 nsHTMLInputElement::SetSelectionEnd(PRInt32 aSelectionEnd)
 {
-  nsresult rv = NS_ERROR_FAILURE;
-  nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
-
-  if (formControlFrame) {
-    nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
-    if (textControlFrame) {
-      rv = textControlFrame->SetSelectionEnd(aSelectionEnd);
-      if (NS_SUCCEEDED(rv)) {
-        rv = textControlFrame->ScrollSelectionIntoView();
-      }
-    }
+  nsAutoString direction;
+  nsresult rv = GetSelectionDirection(direction);
+  NS_ENSURE_SUCCESS(rv, rv);
+  PRInt32 start, end;
+  rv = GetSelectionRange(&start, &end);
+  NS_ENSURE_SUCCESS(rv, rv);
+  end = aSelectionEnd;
+  if (start > end) {
+    start = end;
   }
-
-  return rv;
+  return SetSelectionRange(start, end, direction);
 }
 
 NS_IMETHODIMP
 nsHTMLInputElement::GetFiles(nsIDOMFileList** aFileList)
 {
   *aFileList = nsnull;
 
   if (mType != NS_FORM_INPUT_FILE) {
@@ -2831,16 +2834,55 @@ nsHTMLInputElement::GetSelectionRange(PR
     if (textControlFrame)
       rv = textControlFrame->GetSelectionRange(aSelectionStart, aSelectionEnd);
   }
 
   return rv;
 }
 
 NS_IMETHODIMP
+nsHTMLInputElement::GetSelectionDirection(nsAString& aDirection)
+{
+  nsresult rv = NS_ERROR_FAILURE;
+  nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
+
+  if (formControlFrame) {
+    nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
+    if (textControlFrame) {
+      nsITextControlFrame::SelectionDirection dir;
+      rv = textControlFrame->GetSelectionRange(nsnull, nsnull, &dir);
+      if (NS_SUCCEEDED(rv)) {
+        if (dir == nsITextControlFrame::eNone) {
+          aDirection.AssignLiteral("none");
+        } else if (dir == nsITextControlFrame::eForward) {
+          aDirection.AssignLiteral("forward");
+        } else if (dir == nsITextControlFrame::eBackward) {
+          aDirection.AssignLiteral("backward");
+        } else {
+          NS_NOTREACHED("Invalid SelectionDirection value");
+        }
+      }
+    }
+  }
+
+  return rv;
+}
+
+NS_IMETHODIMP
+nsHTMLInputElement::SetSelectionDirection(const nsAString& aDirection) {
+  PRInt32 start, end;
+  nsresult rv = GetSelectionRange(&start, &end);
+  if (NS_SUCCEEDED(rv)) {
+    rv = SetSelectionRange(start, end, aDirection);
+  }
+
+  return rv;
+}
+
+NS_IMETHODIMP
 nsHTMLInputElement::GetPhonetic(nsAString& aPhonetic)
 {
   aPhonetic.Truncate(0);
   nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
 
   if (formControlFrame) {
     nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
     if (textControlFrame)
--- a/content/html/content/src/nsHTMLMediaElement.cpp
+++ b/content/html/content/src/nsHTMLMediaElement.cpp
@@ -2029,16 +2029,21 @@ void nsHTMLMediaElement::Error(PRUint16 
 }
 
 void nsHTMLMediaElement::PlaybackEnded()
 {
   NS_ASSERTION(mDecoder->IsEnded(), "Decoder fired ended, but not in ended state");
   // We changed the state of IsPlaybackEnded which can affect AddRemoveSelfReference
   AddRemoveSelfReference();
 
+  if (mDecoder && mDecoder->IsInfinite()) {
+    LOG(PR_LOG_DEBUG, ("%p, got duration by reaching the end of the stream", this));
+    DispatchAsyncEvent(NS_LITERAL_STRING("durationchange"));
+  }
+
   FireTimeUpdate(PR_FALSE);
   DispatchAsyncEvent(NS_LITERAL_STRING("ended"));
 }
 
 void nsHTMLMediaElement::SeekStarted()
 {
   DispatchAsyncEvent(NS_LITERAL_STRING("seeking"));
   FireTimeUpdate(PR_FALSE);
--- a/content/html/content/src/nsHTMLSelectElement.cpp
+++ b/content/html/content/src/nsHTMLSelectElement.cpp
@@ -682,18 +682,19 @@ nsHTMLSelectElement::Add(nsIDOMHTMLEleme
 NS_IMETHODIMP
 nsHTMLSelectElement::Add(nsIDOMHTMLElement* aElement,
                          nsIVariant* aBefore)
 {
   PRUint16 dataType;
   nsresult rv = aBefore->GetDataType(&dataType);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  // aBefore is omitted or null
-  if (dataType == nsIDataType::VTYPE_EMPTY) {
+  // aBefore is omitted, undefined or null
+  if (dataType == nsIDataType::VTYPE_EMPTY ||
+      dataType == nsIDataType::VTYPE_VOID) {
     return Add(aElement);
   }
 
   nsCOMPtr<nsISupports> supports;
   nsCOMPtr<nsIDOMHTMLElement> beforeElement;
 
   // whether aBefore is nsIDOMHTMLElement...
   if (NS_SUCCEEDED(aBefore->GetAsISupports(getter_AddRefs(supports)))) {
--- a/content/html/content/src/nsHTMLTextAreaElement.cpp
+++ b/content/html/content/src/nsHTMLTextAreaElement.cpp
@@ -824,58 +824,52 @@ nsHTMLTextAreaElement::GetSelectionStart
   
   PRInt32 selEnd;
   return GetSelectionRange(aSelectionStart, &selEnd);
 }
 
 NS_IMETHODIMP
 nsHTMLTextAreaElement::SetSelectionStart(PRInt32 aSelectionStart)
 {
-  nsresult rv = NS_ERROR_FAILURE;
-  nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
-
-  if (formControlFrame){
-    nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
-    if (textControlFrame) {
-      rv = textControlFrame->SetSelectionStart(aSelectionStart);
-      if (NS_SUCCEEDED(rv)) {
-        rv = textControlFrame->ScrollSelectionIntoView();
-      }
-    }
+  nsAutoString direction;
+  nsresult rv = GetSelectionDirection(direction);
+  NS_ENSURE_SUCCESS(rv, rv);
+  PRInt32 start, end;
+  rv = GetSelectionRange(&start, &end);
+  NS_ENSURE_SUCCESS(rv, rv);
+  start = aSelectionStart;
+  if (end < start) {
+    end = start;
   }
-
-  return rv;
+  return SetSelectionRange(start, end, direction);
 }
 
 NS_IMETHODIMP
 nsHTMLTextAreaElement::GetSelectionEnd(PRInt32 *aSelectionEnd)
 {
   NS_ENSURE_ARG_POINTER(aSelectionEnd);
   
   PRInt32 selStart;
   return GetSelectionRange(&selStart, aSelectionEnd);
 }
 
 NS_IMETHODIMP
 nsHTMLTextAreaElement::SetSelectionEnd(PRInt32 aSelectionEnd)
 {
-  nsresult rv = NS_ERROR_FAILURE;
-  nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
-
-  if (formControlFrame) {
-    nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
-    if (textControlFrame) {
-      rv = textControlFrame->SetSelectionEnd(aSelectionEnd);
-      if (NS_SUCCEEDED(rv)) {
-        rv = textControlFrame->ScrollSelectionIntoView();
-      }
-    }
+  nsAutoString direction;
+  nsresult rv = GetSelectionDirection(direction);
+  NS_ENSURE_SUCCESS(rv, rv);
+  PRInt32 start, end;
+  rv = GetSelectionRange(&start, &end);
+  NS_ENSURE_SUCCESS(rv, rv);
+  end = aSelectionEnd;
+  if (start > end) {
+    start = end;
   }
-
-  return rv;
+  return SetSelectionRange(start, end, direction);
 }
 
 nsresult
 nsHTMLTextAreaElement::GetSelectionRange(PRInt32* aSelectionStart,
                                       PRInt32* aSelectionEnd)
 {
   nsresult rv = NS_ERROR_FAILURE;
   nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
@@ -884,26 +878,75 @@ nsHTMLTextAreaElement::GetSelectionRange
     nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
     if (textControlFrame)
       rv = textControlFrame->GetSelectionRange(aSelectionStart, aSelectionEnd);
   }
 
   return rv;
 }
 
+nsresult
+nsHTMLTextAreaElement::GetSelectionDirection(nsAString& aDirection)
+{
+  nsresult rv = NS_ERROR_FAILURE;
+  nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
+
+  if (formControlFrame) {
+    nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
+    if (textControlFrame) {
+      nsITextControlFrame::SelectionDirection dir;
+      rv = textControlFrame->GetSelectionRange(nsnull, nsnull, &dir);
+      if (NS_SUCCEEDED(rv)) {
+        if (dir == nsITextControlFrame::eNone) {
+          aDirection.AssignLiteral("none");
+        } else if (dir == nsITextControlFrame::eForward) {
+          aDirection.AssignLiteral("forward");
+        } else if (dir == nsITextControlFrame::eBackward) {
+          aDirection.AssignLiteral("backward");
+        } else {
+          NS_NOTREACHED("Invalid SelectionDirection value");
+        }
+      }
+    }
+  }
+
+  return rv;
+}
+
 NS_IMETHODIMP
-nsHTMLTextAreaElement::SetSelectionRange(PRInt32 aSelectionStart, PRInt32 aSelectionEnd)
+nsHTMLTextAreaElement::SetSelectionDirection(const nsAString& aDirection) {
+  PRInt32 start, end;
+  nsresult rv = GetSelectionRange(&start, &end);
+  if (NS_SUCCEEDED(rv)) {
+    rv = SetSelectionRange(start, end, aDirection);
+  }
+
+  return rv;
+}
+
+NS_IMETHODIMP
+nsHTMLTextAreaElement::SetSelectionRange(PRInt32 aSelectionStart,
+                                         PRInt32 aSelectionEnd,
+                                         const nsAString& aDirection)
 { 
   nsresult rv = NS_ERROR_FAILURE;
   nsIFormControlFrame* formControlFrame = GetFormControlFrame(PR_TRUE);
 
   if (formControlFrame) {
     nsITextControlFrame* textControlFrame = do_QueryFrame(formControlFrame);
     if (textControlFrame) {
-      rv = textControlFrame->SetSelectionRange(aSelectionStart, aSelectionEnd);
+      // Default to forward, even if not specified.
+      // Note that we don't currently support directionless selections, so
+      // "none" is treated like "forward".
+      nsITextControlFrame::SelectionDirection dir = nsITextControlFrame::eForward;
+      if (aDirection.EqualsLiteral("backward")) {
+        dir = nsITextControlFrame::eBackward;
+      }
+
+      rv = textControlFrame->SetSelectionRange(aSelectionStart, aSelectionEnd, dir);
       if (NS_SUCCEEDED(rv)) {
         rv = textControlFrame->ScrollSelectionIntoView();
       }
     }
   }
 
   return rv;
 } 
--- a/content/html/content/test/Makefile.in
+++ b/content/html/content/test/Makefile.in
@@ -272,13 +272,15 @@ include $(topsrcdir)/config/rules.mk
 		test_bug649134.html \
 		test_bug658746.html \
 		test_bug659596.html \
 		test_bug659743.xml \
 		test_bug660663.html \
 		test_bug664299.html \
 		test_bug666200.html \
 		test_bug666666.html \
+		test_bug674558.html \
+		test_bug583533.html \
 		test_restore_from_parser_fragment.html \
 		$(NULL)
 
 libs:: $(_TEST_FILES)
 	$(INSTALL) $(foreach f,$^,"$f") $(DEPTH)/_tests/testing/mochitest/tests/$(relativesrcdir)
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug583533.html
@@ -0,0 +1,76 @@
+<!DOCTYPE HTML>
+<html>
+    <!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=583533
+-->
+    <head>
+        <title>Test for Bug 583514</title>
+        <script type="application/javascript" src="/MochiKit/packed.js"></script>
+        <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+        <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+    </head>
+    <body>
+        <a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=583533">Mozilla Bug 583533</a>
+        <p id="display"></p>
+        <div id="content">
+            <div id="e" accesskey="a">
+  </div>
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+    /** Test for Bug 583533 **/
+
+    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+
+    var sbs = Components.classes["@mozilla.org/intl/stringbundle;1"].
+    getService(Components.interfaces.nsIStringBundleService);
+    var bundle = sbs.createBundle("chrome://global-platform/locale/platformKeys.properties");
+    
+    var shiftText = bundle.GetStringFromName("VK_SHIFT");
+    var altText = bundle.GetStringFromName("VK_ALT");
+    var controlText = bundle.GetStringFromName("VK_CONTROL");
+    var metaText = bundle.GetStringFromName("VK_META");
+    var separatorText = bundle.GetStringFromName("MODIFIER_SEPARATOR");
+
+    var modifier = Components.classes["@mozilla.org/preferences-service;1"]
+                                      .getService(Components.interfaces.nsIPrefBranch)
+                                      .getIntPref("ui.key.contentAccess");
+                                      
+    var domEvent = Components.interfaces.nsIDOMNSEvent;
+    
+    var isShift;
+    var isAlt;
+    var isControl;
+    var isMeta;
+
+    is(modifier < 16 && modifier >= 0, true, "Modifier in range");
+
+    if (modifier & domEvent.META_MASK)
+        isMeta = true;
+    if (modifier & domEvent.SHIFT_MASK)
+        isShift = true;
+    if (modifier & domEvent.CONTROL_MASK)
+        isControl = true;
+    if (modifier & domEvent.ALT_MASK)
+        isAlt = true;
+
+    var label = "";
+
+    if (isControl)
+        label += controlText + separatorText;
+    if (isMeta)
+        label += metaText + separatorText;
+    if (isAlt)
+        label += altText + separatorText;
+    if (isShift)
+        label += shiftText + separatorText;
+
+    label += document.getElementById("e").accessKey;
+
+    is(label, document.getElementById("e").accessKeyLabel, "JS and C++ agree on accessKeyLabel");
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/content/test/test_bug666200.html
+++ b/content/html/content/test/test_bug666200.html
@@ -17,24 +17,28 @@ https://bugzilla.mozilla.org/show_bug.cg
 <pre id="test">
 <script class="testbody" type="text/javascript">
 /** Test for Bug 666200 **/
 var sel = document.createElement("select");
 var opt1 = new Option();
 var opt2 = new Option();
 var opt3 = new Option();
 var opt4 = new Option();
+var opt5 = new Option();
 opt1.value = 1;
 opt2.value = 2;
 opt3.value = 3;
 opt4.value = 4;
+opt5.value = 5;
 sel.add(opt1);
 sel.add(opt2, 0);
 sel.add(opt3, 1000);
 sel.options.add(opt4, opt3);
+sel.add(opt5, undefined);
 is(sel[0], opt2, "1st item should be 2");
 is(sel[1], opt1, "2nd item should be 1");
 is(sel[2], opt4, "3rd item should be 4");
 is(sel[3], opt3, "4th item should be 3");
+is(sel[4], opt5, "5th item should be 5");
 </script>
 </pre>
 </body>
 </html>
new file mode 100644
--- /dev/null
+++ b/content/html/content/test/test_bug674558.html
@@ -0,0 +1,151 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=674558
+-->
+<head>
+  <title>Test for Bug 674558</title>
+  <script type="application/javascript" src="/MochiKit/packed.js"></script>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="text/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=674558">Mozilla Bug 674558</a>
+<p id="display"></p>
+<div id="content">
+</div>
+<pre id="test">
+<script type="application/javascript">
+
+/** Test for Bug 674558 **/
+SimpleTest.waitForExplicitFinish();
+SimpleTest.waitForFocus(function() {
+  function textAreaCtor() {
+    return document.createElement("textarea");
+  }
+  var ctors = [textAreaCtor];
+  ["text", "password", "search"].forEach(function(type) {
+    ctors.push(function inputCtor() {
+      var input = document.createElement("input");
+      input.type = type;
+      return input;
+    });
+  });
+
+  for (var ctor in ctors) {
+    test(ctors[ctor]);
+  }
+
+  SimpleTest.finish();
+});
+
+function test(ctor) {
+  var elem = ctor();
+  ok(true, "Testing " + name(elem));
+
+  ok("selectionDirection" in elem, "elem should have the selectionDirection property");
+
+  var content = document.getElementById("content");
+  content.appendChild(elem);
+
+  elem.value = "foobar";
+
+  is(elem.selectionStart, 0, "Default value");
+  is(elem.selectionEnd, 0, "Default value");
+  is(elem.selectionDirection, "forward", "Default value");
+
+  elem.setSelectionRange(1, 3);
+  is(elem.selectionStart, 1, "Correct value");
+  is(elem.selectionEnd, 3, "Correct value");
+  is(elem.selectionDirection, "forward", "If not set, should default to forward");
+
+  // extend to right
+  elem.focus();
+  synthesizeKey("VK_RIGHT", {shiftKey: true});
+
+  is(elem.selectionStart, 1, "Value unchanged");
+  is(elem.selectionEnd, 4, "Correct value");
+  is(elem.selectionDirection, "forward", "Still forward");
+
+  // change the direction
+  elem.selectionDirection = "backward";
+
+  is(elem.selectionStart, 1, "Value unchanged");
+  is(elem.selectionEnd, 4, "Value unchanged");
+  is(elem.selectionDirection, "backward", "Correct value");
+
+  // extend to right again
+  synthesizeKey("VK_RIGHT", {shiftKey: true});
+
+  is(elem.selectionStart, 2, "Correct value");
+  is(elem.selectionEnd, 4, "Value unchanged");
+  is(elem.selectionDirection, "backward", "Still backward");
+
+  elem.selectionEnd = 5;
+
+  is(elem.selectionStart, 2, "Value unchanged");
+  is(elem.selectionEnd, 5, "Correct value");
+  is(elem.selectionDirection, "backward", "Still backward");
+
+  elem.selectionDirection = "none";
+
+  is(elem.selectionStart, 2, "Value unchanged");
+  is(elem.selectionEnd, 5, "Value unchanged");
+  is(elem.selectionDirection, "forward", "none not supported");
+
+  elem.selectionDirection = "backward";
+
+  is(elem.selectionStart, 2, "Value unchanged");
+  is(elem.selectionEnd, 5, "Value unchanged");
+  is(elem.selectionDirection, "backward", "Correct Value");
+
+  elem.selectionDirection = "invalid";
+
+  is(elem.selectionStart, 2, "Value unchanged");
+  is(elem.selectionEnd, 5, "Value unchanged");
+  is(elem.selectionDirection, "forward", "Treated as none");
+
+  elem.selectionDirection = "backward";
+
+  is(elem.selectionStart, 2, "Value unchanged");
+  is(elem.selectionEnd, 5, "Value unchanged");
+  is(elem.selectionDirection, "backward", "Correct Value");
+
+  elem.setSelectionRange(1, 4);
+
+  is(elem.selectionStart, 1, "Correct value");
+  is(elem.selectionEnd, 4, "Correct value");
+  is(elem.selectionDirection, "forward", "Correct value");
+
+  elem.setSelectionRange(1, 1);
+  synthesizeKey("VK_RIGHT", {shiftKey: true});
+  synthesizeKey("VK_RIGHT", {shiftKey: true});
+  synthesizeKey("VK_RIGHT", {shiftKey: true});
+
+  is(elem.selectionStart, 1, "Correct value");
+  is(elem.selectionEnd, 4, "Correct value");
+  is(elem.selectionDirection, "forward", "Correct value");
+
+  elem.setSelectionRange(5, 5);
+  synthesizeKey("VK_LEFT", {shiftKey: true});
+  synthesizeKey("VK_LEFT", {shiftKey: true});
+  synthesizeKey("VK_LEFT", {shiftKey: true});
+
+  is(elem.selectionStart, 2, "Correct value");
+  is(elem.selectionEnd, 5, "Correct value");
+  is(elem.selectionDirection, "backward", "Correct value");
+}
+
+function name(elem) {
+  var tag = elem.localName;
+  if (tag == "input") {
+    tag += "[type=" + elem.type + "]";
+  }
+  return tag;
+}
+
+</script>
+</pre>
+</body>
+</html>
--- a/content/html/document/src/Makefile.in
+++ b/content/html/document/src/Makefile.in
@@ -44,17 +44,16 @@ include $(DEPTH)/config/autoconf.mk
 
 MODULE		= content
 LIBRARY_NAME	= gkconhtmldoc_s
 LIBXUL_LIBRARY	= 1
 
 
 CPPSRCS		= \
 		nsHTMLContentSink.cpp \
-		nsHTMLFragmentContentSink.cpp \
 		nsHTMLDocument.cpp \
 		ImageDocument.cpp \
 		MediaDocument.cpp \
 		PluginDocument.cpp \
 		$(NULL)
 
 ifdef MOZ_MEDIA
 CPPSRCS += VideoDocument.cpp
--- a/content/html/document/src/nsHTMLContentSink.cpp
+++ b/content/html/document/src/nsHTMLContentSink.cpp
@@ -2627,18 +2627,20 @@ HTMLContentSink::ProcessLINKTag(const ns
     }
 
     mCurrentContext->AddLeaf(element); // <link>s are leaves
 
     if (ssle) {
       ssle->SetEnableUpdates(PR_TRUE);
       PRBool willNotify;
       PRBool isAlternate;
-      result = ssle->UpdateStyleSheet(this, &willNotify, &isAlternate);
-      if (NS_SUCCEEDED(result) && willNotify && !isAlternate) {
+      result = ssle->UpdateStyleSheet(mFragmentMode ? nsnull : this,
+                                      &willNotify,
+                                      &isAlternate);
+      if (NS_SUCCEEDED(result) && willNotify && !isAlternate && !mFragmentMode) {
         ++mPendingSheetCount;
         mScriptLoader->AddExecuteBlocker();
       }
 
       // look for <link rel="next" href="url">
       nsAutoString relVal;
       element->GetAttr(kNameSpaceID_None, nsGkAtoms::rel, relVal);
       if (!relVal.IsEmpty()) {
@@ -2840,18 +2842,20 @@ HTMLContentSink::ProcessSTYLEEndTag(nsGe
   nsresult rv = NS_OK;
 
   if (ssle) {
     // Note: if we are inside a noXXX tag, then we init'ed this style element
     // with mDontLoadStyle = PR_TRUE, so these two calls will have no effect.
     ssle->SetEnableUpdates(PR_TRUE);
     PRBool willNotify;
     PRBool isAlternate;
-    rv = ssle->UpdateStyleSheet(this, &willNotify, &isAlternate);
-    if (NS_SUCCEEDED(rv) && willNotify && !isAlternate) {
+    rv = ssle->UpdateStyleSheet(mFragmentMode ? nsnull : this,
+                                &willNotify,
+                                &isAlternate);
+    if (NS_SUCCEEDED(rv) && willNotify && !isAlternate && !mFragmentMode) {
       ++mPendingSheetCount;
       mScriptLoader->AddExecuteBlocker();
     }
   }
 
   return rv;
 }
 
--- a/content/html/document/src/nsHTMLDocument.cpp
+++ b/content/html/document/src/nsHTMLDocument.cpp
@@ -280,30 +280,28 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mEmbeds)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mLinks)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mAnchors)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mForms, nsIDOMNodeList)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR_AMBIGUOUS(mFormControls,
                                                        nsIDOMNodeList)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mWyciwygChannel)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mMidasCommandManager)
-  NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mFragmentParser)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(nsHTMLDocument, nsDocument)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mImages)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mApplets)
   NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mEmbeds)